Repository navigation
feat(engine): add external probe episode runtime - #15
Conversation
|
All contributors have signed the DCO ✍️ ✅ |
3mei
left a comment
There was a problem hiding this comment.
Following up on my comment in #10. This runtime removes the duplicate probe, but the host still has to rebuild UserSim's user side (Gym#3791 does it in _run_external_probe), so hosted results drift from standalone runs. The proposal is to turn this PR into a step-by-step session that runs UserSim's own episode code. A prototype on this branch matched standalone runs on all 14 probes in both modes below.
The session
- Runs the unmodified
ConversationSimulatorGeneratorfor one input row as a background task. Every model call becomes a request the host answers, so per-episode settings, gates, judges, early stop and finalize are UserSim's own. - Agent-run tool loop: the agent records each model response, which answers the pending assistant request. UserSim executes the calls, and the agent fetches the results by call id. The reply says whether the turn continues, whether tools are on next, and gives UserSim's next assistant input. A record that breaks the probe's loop rules is rejected.
- Agents that cannot record: the host returns raw model responses, and UserSim runs the tools.
- The host supplies the model id and token budget per role, and returns reasoning and usage with each response. Host errors surface as failures of UserSim's model call, so UserSim's retries and failure attribution apply.
close()cancels the running episode.
Changes to this PR
- Replace
ProbeEpisodeRuntimewith the session. That removes the allowlist (L21), the bootstrap import (L134-L135), the second finalize and itsnum_tool_callsoverride (L372), and payload comparison (L483): payloads pass through verbatim, and UserSim's own finalize runs. - Drop the loop-policy attributes (probes.py L260-L262, L579, L1032-L1034, tool_calling L240-L241). The live loop applies its own rules.
- Add a notify-only hook where tool calls execute (
ToolExecutionMixin.after_assistant_turnand thesafety_agenticloop), so the session receives raw payloads. With it, 2,675 engine and end-to-end tests pass, the same as without. Probes that write tool messages themselves need the hook too, includingtemplates/probe/generator_tool_calling.py. - Mark assistant requests that continue the current turn explicitly, rather than leaving the host to infer it from the transcript.
- Add a supported way to build the generator outside Data Designer; hosts subclass it today.
- The session is public API and the hook is part of the probe contract: add a hosted-parity check to
usersim.testing, and updateAUTHORING_A_PROBE.md,architecture/engine.mdanddocs/engine/EXTERNAL_PROBE_RUNTIME.mdin the same change. - Move the
safety_agenticrefactor to its own PR. The session does not need it, and it stands on its own. - Tests, per probe with scripted models: a standalone run and a session run are identical in both modes (timing fields excluded), a rule-breaking agent is rejected, concurrent sessions stay isolated, and
close()cancels cleanly.
Episode inputs are a separate change: a flag on usersim simulate that writes the rows the simulator would receive, without model calls (details in #10).
|
I have read the DCO document and I hereby sign the DCO. |
|
Validation refreshed on
The parity test compares the complete normalized direct and resumable result dictionaries, removing only nondeterministic |
|
Superseded by |
|
Implemented reviewer points 1–3 on the UserSim side in Key changes:
Validation:
No Gym files were changed. Gym integration and live rollout success against this new contract are N/A/not yet claimed. |
|
Downstream Gym integration is complete against commit
A UserSim-materialized task also passes a real Resources → Environment → SimpleAgent path and matches standalone generator semantics. Genuine |
3mei
left a comment
There was a problem hiding this comment.
@ffrujeri Thanks for the turnaround!
Blocking
-
Standalone UserSim breaks. The new import in
evaluator/__init__.pystops Data Designer from registering UserSim's column types, so building the config the wayusersim simulatedoes raisesInvalidColumnTypeError. The base (nowmain) passes all 3,588 tests; this head fails 47. Without that import, 2 remain: the network-guard test (fromexcept BaseExceptionin the lifecycle task) andtest_episode_input.py, which needs a code SHA. These failures reproduce at2d9ec0d, not at the PR base. -
Standalone trajectory ids change for 7 of the 14 probes (every probe that reports its own variant), compared with the base on the same inputs and scripted models; the rest of each row matches. Resume and deduplication key on this id.
-
Hosted runs diverge from standalone once tools are used on more than one turn. With tools on every turn:
tool_callingtraces recordturn_idx3 and 5 standalone, 2 and 3 hosted;- the tool simulator's prompt lacks the assistant's tool-call line;
- hosted rows lack
user_query.
The parity test runs one tool round per episode, so it can't see this.
-
Contract errors are blamed on the model under test. A tool message that differs from the runtime's payload makes UserSim retry the turn: 4 activations, the tool runs 4 times, and the episode fails as
assistant_model. -
Role model ids and token budgets don't reach the runtime (item 3 of #10). Hosted
identity_disclosureruns unidentified, and trajectory ids name UserSim's configured models rather than the host's.
One change addresses 3 and 4, and much of the size. Both come from running tools before UserSim's loop reaches them and replaying the agent's turn afterwards. With the record step from #10, UserSim's loop executes the recorded calls with native indices and context, and errors surface at the host-facing call. That also removes the replay machinery, the patching of probe internals, the probe_type == "safety_agentic" branch, and the static loop policy (AssistantToolLoopPolicy, the new probe attributes, and the matching code in Gym's SimpleAgent), since each reply tells the agent what comes next.
Also
- One host contract. The earlier contract is still here next to the lifecycle: the descriptor's user side,
synchronize_transcript, the delegated hooks, andfinalize(messages)with its ownnum_tool_calls. Gym uses none of the transcript or user-side methods. - Separate PRs, per #10: inputs and episode construction (with the trajectory-id decision), the
safety_agenticrefactor, and the evaluator runtime; this PR keeps the lifecycle. The base should bemain. - Probe contract. The new
run_dispatchparameters break probes built fromtemplates/probe/generator_agentic.pywhen hosted. Templates,usersim.testingandAUTHORING_A_PROBE.mdneed to change with any contract change. - Determinism. My "samplers and seeds" in #10 meant UserSim's seed files. Rows are stored as the dataset, so regeneration doesn't need to be deterministic, and
_deterministic_samplingpatches private Data Designer internals and reseeds global generators to achieve it. - Duplication: model aliases redefined in
episode_input.py, config defaults repeated throughgetattr, a second tool-call parser, andusersim_configin every standalone row. - Docs:
EXTERNAL_PROBE_RUNTIME.mddocuments the earlier contract rather than the lifecycle, and claims native indices;architecture/engine.mdisn't updated. - Tests:
- multi-turn, multi-round parity that compares prompts;
- a pinned trajectory id per probe;
- a mismatched-payload case;
- a hosted template-shaped probe;
test_episode_input.pyrunning without a git checkout.
Most of the remaining work is inside UserSim, and several items are mechanical. If it helps, I can make the UserSim-side changes myself, as commits on this branch or as follow-up PRs on top of it, while you keep #3791 and #3802 moving. Which would you prefer?
Signed-off-by: Felipe Vieira Frujeri <[email protected]>
Signed-off-by: Felipe Vieira Frujeri <[email protected]>
Signed-off-by: Felipe Vieira Frujeri <[email protected]>
Signed-off-by: Felipe Vieira Frujeri <[email protected]>
Signed-off-by: Felipe Vieira Frujeri <[email protected]>
Signed-off-by: Felipe Vieira Frujeri <[email protected]>
Signed-off-by: Felipe Vieira Frujeri <[email protected]>
Signed-off-by: Felipe Vieira Frujeri <[email protected]>
Signed-off-by: Felipe Vieira Frujeri <[email protected]>
Signed-off-by: Felipe Vieira Frujeri <[email protected]>
Signed-off-by: Felipe Vieira Frujeri <[email protected]>
Addresses the review on #15. The host no longer executes tool calls ahead of UserSim and replays the agent's turn afterwards. It records the assistant's response, tool calls included, and UserSim's own loop executes them with its own turn and call indices and its own context. A notify-only observer on BaseProbe reports each executed call, so the payloads reach the host by call id. That removes the replay machinery, the patching of probe internals, the probe_type == "safety_agentic" branch, and the static loop policy, since each reply now tells the host what comes next: whether the turn continues, whether tools are offered, and the exact input UserSim would send. - Trajectory ids keep the dispatcher-seeded probe variant. Recomputing the preamble with a probe's self-reported variant changed the id for 7 of the 14 probes, which resume and deduplication key on. Pinned per probe. - Contract errors are raised from advance() to their author, so they no longer consume a model retry or get attributed to the model under test. - HostRoleModel carries the host's real model id and token budget into the episode, and recorded usage feeds per-model accounting. Without it, identity_disclosure ran unidentified and trajectory ids named UserSim's configured models. - finalize() returns the resolved row updated with the result, matching what the generator writes, so hosted rows carry user_query. - One host contract: the descriptor's user side, synchronize_transcript, the delegated hooks and the second finalize had no production consumer and are gone, along with a duplicate tool-call parser and the duplicated role aliases and config defaults. - The evaluator runtime moves to its own branch; its eager import stopped Data Designer registering UserSim's column types, breaking standalone usersim simulate. - Materialization no longer patches Data Designer internals or reseeds global generators; rows are the stored dataset. usersim_config rides on the materialized row rather than on every trajectory row. - Probe contract: run_dispatch overrides take state/seed_state and probes that execute their own tool calls must notify. Templates, usersim.testing and AUTHORING_A_PROBE.md updated together, with assert_hosted_parity published for probe authors and ConversationSimulatorGenerator.with_models as the supported way to build the generator outside Data Designer. Tests: multi-turn multi-round parity comparing prompts, a pinned trajectory id per probe, a rejected mismatched record, a hosted template-shaped probe, close() cancellation, concurrent-episode isolation, and test_episode_input running without a git checkout. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: Felipe Vieira Frujeri <[email protected]>
4fd4c80 to
a4665b3
Compare
Addresses the review on #3791 and adopts the reworked UserSim contract from NVIDIA-NeMo/UserSim#15. The Assistant Agent no longer runs the probe's tools. It makes one model call per activation and returns the model's tool calls unexecuted; UserSim executes them inside its own conversation loop when the Environment records that response, so the turn and call indices, the tool simulator's context, and the loop's own decisions stay UserSim's. - Re-pins UserSim to a4665b3, where standalone `usersim simulate` builds its Data Designer pipeline again. - Declares the models this environment runs per role, with their token budgets, when seeding. Without them `identity_disclosure` ran with no expected identity and trajectory ids named preparation's defaults rather than the models under test. - Returns reasoning and usage with every recorded response; UserSim stores both. - `AgentToolLoopPolicy` leaves Gym's general-purpose agent contract, along with the tool-access batch path. In their place `AgentSeedSessionRequest` carries one generic `execute_tools` flag for callers that run tools themselves. SimpleAgent loses the synthesis, activation-cap and per-turn-cap logic that only existed to mirror UserSim's loop. - Contract errors from the runtime return HTTP 422 to their author instead of being retried against, or attributed to, the model under test. - Drops the tool and batch routes, the tool-call-id header and the MCP/HTTP tool transports for probe tools: nothing executes them host-side now, so parallel calls can no longer be split across rounds by transport. - Loads UserSim's probe registry and assets at Resources startup rather than during the first episodes, where it stalled the event loop. - Points the simulated user at the support model; it was the policy model, so the model under test was interviewing itself. - Closes the runtime through its own `close()` and finalizes through the public lifecycle state rather than private attributes. Tests: end-to-end parity against a standalone generator run for all 14 registered probes through the real Resources/Environment/SimpleAgent stack, declared role models, a rejected contract error, and `execute_tools: false` returning tool calls after exactly one model call. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: Felipe Vieira Frujeri <[email protected]>
Addresses the review on #3791 and adopts the reworked UserSim contract from NVIDIA-NeMo/UserSim#15. Keeps this PR's split: Resources owns the episode, the Assistant Agent owns the model/tool loop, the Environment coordinates. The Agent still drives model -> tool -> model, but it no longer decides the loop's shape. Per step it calls its model, records that response with Resources *before* issuing the response's tool calls, and follows the reply: whether the turn continues, which tools are offered next, and the exact input UserSim would send. Recording is what makes UserSim execute the calls, inside its own conversation loop, so the turn and call indices and the tool simulator's context are UserSim's. The reply's input replaces the Agent's own accumulated transcript, which matters for probes that trim their context. That removes `AgentToolLoopPolicy` from Gym's general-purpose agent contract along with the tool-access batch path, and with them SimpleAgent's synthesis, activation-cap and per-turn-cap logic, which only existed to mirror rules UserSim already enforces. In their place the agent session carries `record_outputs_path` and a generic `execute_tools` for agents that cannot record. - Re-pins UserSim to a4665b3, where standalone `usersim simulate` builds its Data Designer pipeline again. - Declares the models this environment runs per role, with their token budgets, when seeding. Without them `identity_disclosure` ran with no expected identity and trajectory ids named preparation's defaults. - Returns reasoning and usage with every recorded response; UserSim stores both. - Contract errors return HTTP 422 to their author rather than being retried against, or attributed to, the model under test. - Drops the tool batch route and its transport flag: parallel calls now arrive together in one recorded response, so they can no longer be split across rounds by transport. - Loads UserSim's probe registry and assets at Resources startup rather than during the first episodes, where it stalled the event loop. - Points the simulated user at the support model; it was the policy model, so the model under test was interviewing itself. - Closes the runtime through its own `close()` and finalizes through the public lifecycle state rather than private attributes. Tests: end-to-end parity against a standalone generator run for all 14 registered probes through the real Resources/Environment/SimpleAgent stack, the record reply driving the Agent's loop, declared role models, a rejected contract error, and the tool route returning UserSim's payload verbatim. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: Felipe Vieira Frujeri <[email protected]>
Addresses the review on #3791 and adopts the reworked UserSim contract from NVIDIA-NeMo/UserSim#15. Keeps this PR's split: Resources owns the episode, the Assistant Agent owns the model/tool loop, the Environment coordinates. The Agent still drives model -> tool -> model, but it no longer decides the loop's shape. Per step it calls its model, records that response with Resources *before* issuing the response's tool calls, and follows the reply: whether the turn continues, which tools are offered next, and the exact input UserSim would send. Recording is what makes UserSim execute the calls, inside its own conversation loop, so the turn and call indices and the tool simulator's context are UserSim's. The reply's input replaces the Agent's own accumulated transcript, which matters for probes that trim their context. That removes `AgentToolLoopPolicy` from Gym's general-purpose agent contract along with the tool-access batch path, and with them SimpleAgent's synthesis, activation-cap and per-turn-cap logic, which only existed to mirror rules UserSim already enforces. In their place the agent session carries `record_outputs_path` and a generic `execute_tools` for agents that cannot record. - Re-pins UserSim to a4665b3, where standalone `usersim simulate` builds its Data Designer pipeline again. - Declares the models this environment runs per role, with their token budgets, when seeding. Without them `identity_disclosure` ran with no expected identity and trajectory ids named preparation's defaults. - Returns reasoning and usage with every recorded response; UserSim stores both. - Contract errors return HTTP 422 to their author rather than being retried against, or attributed to, the model under test. - Drops the tool batch route and its transport flag: parallel calls now arrive together in one recorded response, so they can no longer be split across rounds by transport. - Loads UserSim's probe registry and assets at Resources startup rather than during the first episodes, where it stalled the event loop. - Points the simulated user at the support model; it was the policy model, so the model under test was interviewing itself. - Closes the runtime through its own `close()` and finalizes through the public lifecycle state rather than private attributes. Tests: end-to-end parity against a standalone generator run for all 14 registered probes through the real Resources/Environment/SimpleAgent stack, the record reply driving the Agent's loop, declared role models, a rejected contract error, and the tool route returning UserSim's payload verbatim. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: Felipe Vieira Frujeri <[email protected]>
3mei
left a comment
There was a problem hiding this comment.
Thanks, this lands the main points.
Remaining before merge:
- Flaky test.
test_materialization_resolves_theme_tools_and_restorable_configassertstoolset_nameon a random sample, and some toolsets have no name; it failed on one of two runs. - Skips.
test_probe_template_contract.pyskips the 5 templates that don't overriderun_dispatch; parametrizing over the ones that do avoids the skips. - History.
ab77157adds the evaluator runtime anda4665b3deletes it; dropping both keeps the history reviewable. Gym#3791 still imports that module at this revision (resources_servers/usersim/app.pyL351). - Separate concerns. The
safety_agenticrefactor and the inputs/construction work can still land on their own, as suggested on #10. - Leftovers. The bootstrap import (
episode_runtime.pyL319), and replacingprobe._modelson the instance (L572). - Docs and description. The new docs add em dashes, and
docs/engine/README.mdL22-L25 still describes the earlier contract. The PR description still reports the earlier failures and refers to reviewer points.
I will take care of these last-mile items as commits on this branch.
Addresses the review on #3791 and adopts the reworked UserSim contract from NVIDIA-NeMo/UserSim#15. Keeps this PR's split: Resources owns the episode, the Assistant Agent owns the model/tool loop, the Environment coordinates. The Agent still drives model -> tool -> model, but it no longer decides the loop's shape. Per step it calls its model, records that response with Resources *before* issuing the response's tool calls, and follows the reply: whether the turn continues, which tools are offered next, and the exact input UserSim would send. Recording is what makes UserSim execute the calls, inside its own conversation loop, so the turn and call indices and the tool simulator's context are UserSim's. The reply's input replaces the Agent's own accumulated transcript, which matters for probes that trim their context. That removes `AgentToolLoopPolicy` from Gym's general-purpose agent contract along with the tool-access batch path, and with them SimpleAgent's synthesis, activation-cap and per-turn-cap logic, which only existed to mirror rules UserSim already enforces. The agent contract gains one field in their place: `record_outputs_path`. - Re-pins UserSim to a4665b3, where standalone `usersim simulate` builds its Data Designer pipeline again. - Declares the models this environment runs per role, with their token budgets, when seeding. Without them `identity_disclosure` ran with no expected identity and trajectory ids named preparation's defaults. - Returns reasoning and usage with every recorded response; UserSim stores both. - Contract errors return HTTP 422 to their author rather than being retried against, or attributed to, the model under test. - Drops the tool batch route and its transport flag: parallel calls now arrive together in one recorded response, so they can no longer be split across rounds by transport. - Loads UserSim's probe registry and assets at Resources startup rather than during the first episodes, where it stalled the event loop. - Points the simulated user at the support model; it was the policy model, so the model under test was interviewing itself. - Closes the runtime through its own `close()` and finalizes through the public lifecycle state rather than private attributes. Tests: end-to-end parity against a standalone generator run for all 14 registered probes through the real Resources/Environment/SimpleAgent stack, the record reply driving the Agent's loop, declared role models, a rejected contract error, and the tool route returning UserSim's payload verbatim. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: Felipe Vieira Frujeri <[email protected]>
Materialization samples toolsets without a pinned seed, and some shipped toolsets carry no name. The test now checks the toolset's tools and category, which every row has, and only the presence of the toolset_name column. Signed-off-by: Yev Meyer <[email protected]>
Only templates that override run_dispatch are checked for the hosted parameters, and a guard test keeps that set from being empty, so no template is skipped. Signed-off-by: Yev Meyer <[email protected]>
The runtime built its activation models only when the episode started and swapped them into the probe's private _models attribute, so a probe that kept a model from construction held the host's role identity and could not call it. The activation models are now built once and passed to both construction and run_dispatch, as a standalone run does, and the swap is gone. Models are fixed at construction, so the parity harness builds each runtime with the models it uses. Signed-off-by: Yev Meyer <[email protected]>
known_probes() and resolve_probe() import the shipped probe modules listed in BUILTIN_PROBE_MODULES before loading extensions, so a lookup no longer depends on something having imported the simulator generator first. The hosted runtime and the CLI drop their side-effect imports of the generator, smoke lists probes through known_probes() and checks the generator import explicitly, and the registry snapshot fixtures load the built-ins before taking their snapshot. The authoring docs point at the new list. Signed-off-by: Yev Meyer <[email protected]>
…untime text Uses commas, colons, semicolons and parentheses in place of em dashes in the external runtime guide, the engine architecture page and the run_dispatch hook row, and rewords that row and four docstrings to state current behaviour. No behaviour change. Signed-off-by: Yev Meyer <[email protected]>
The engine README says any registered probe is hostable: UserSim runs its own loop, pauses at each user, assistant, judge and summary model call for the host to answer, and executes tool calls itself. The external runtime guide adds that a host running tool_calling passes the api_response_model UserSim calls directly, and that financial_services optionally uses an embedding model for dense retrieval. Signed-off-by: Yev Meyer <[email protected]>
The materialization tests run Data Designer's persona sampler, which reads the Nemotron-Personas datasets from the home directory, so they passed only where those downloads were installed. A session-wide fixture writes four synthetic en_US personas and points Data Designer's managed-assets path at them, so every test that samples personas runs the real sampler graph without the download. Signed-off-by: Yev Meyer <[email protected]>
What changed and why
Adds a supported way for another system to host UserSim episodes. UserSim keeps owning episode inputs, the episode loop, tool execution and the finished row.
usersim.engine.external.materialize_episode_inputs()andusersim simulate --materialize-inputsresolve complete episode rows without model calls, using the same samplers asusersim simulate. Each row holds the persona, probe, theme and tools, per-episode settings, trajectory id, provenance and a config snapshot.core/episode_input.pybuilds every episode, standalone or hosted. Trajectory ids are pinned per probe by tests, and every row carries a newusersim_provenancecolumn.ProbeEpisodeRuntime.from_resolved_row(row, models=...)restores an episode.advance()pauses at each user, assistant, judge and summary model call for the host to answer. UserSim executes tool calls itself and returns their payloads throughtool_result(), andfinalize()returns the same rowusersim simulatewrites.HostRoleModeldeclares the model behind each role, andEpisodeContractErrorreports host mistakes without charging them to the model.run_dispatchoverrides acceptstateandseed_state.on_tool_call_executed, and the probe templates are checked against both requirements.usersim.testing.assert_hosted_paritychecks that a probe runs the same hosted and standalone.ConversationSimulatorGenerator.with_models()runs a row without a Data Designer pipeline.BUILTIN_PROBE_MODULESand load on first lookup, soknown_probes()andresolve_probe()work in any process.docs/engine/EXTERNAL_PROBE_RUNTIME.mdis the host guide. The architecture and authoring pages describe the identity rule and the registry.Related: NVIDIA-NeMo/Gym#985.
How it was verified
make check-all,make test(3680 passed),make smoke,make check-license-headers,make check-doc-links,make check-notebooks-clean,make check-dependency-licenses,make check-wheelandmake check-extensions, on Python 3.12 and 3.13. The suite also passes with an empty home directory.usersim_config. Standalone rows matchmainapart from the newusersim_provenancecolumn.make health-checkwas not run: no provider, prompt or scorer changed.Results impact
Standalone output is unchanged apart from the new
usersim_provenancecolumn, and trajectory ids are unchanged.