Skip to content

feat(usersim): evaluate environment-owned native tool loop - #3797

Merged
ffrujeri merged 0 commit into
ffrujeri/usersim-probe-examplesfrom
ffrujeri/usersim-environment-tool-loop
Oct 6, 2026
Merged

ffrujeri merged 0 commit into
ffrujeri/usersim-probe-examplesfrom
ffrujeri/usersim-environment-tool-loop

Conversation

@ffrujeri

@ffrujeri ffrujeri commented Sep 29, 2026 •

Copy link
Copy Markdown
Contributor

What changed and why

  • Rebuilds the Environment-owned UserSim comparison from the prepared-probe suite in feat(nemo-user-sim): add generated validation tasks #3802.
  • Installs the now-public UserSim repository over HTTPS at main revision a5f676bf6dc5a73914c8a0860f97c10dd2c214ee, after UserSim PR AzureOpenAIModel implementation #17 merged.
  • Makes the Environment own the sole native ProbeEpisodeRuntime and its tool loop.
  • Configures the Assistant SimpleAgent for one model activation with execute_tools: false; UserSim consumes returned function calls, executes native tools, and requests follow-up activations.
  • Keeps Resources limited to immutable-row validation, native trajectory evaluation/scoring, session cleanup, and aggregate metrics. It exposes no probe tool or /runtime routes.
  • Accepts AzureOpenAIModel implementation #17 JSON-text provenance while retaining legacy mapping compatibility.
  • Adds deterministic standalone-versus-Gym parity coverage for tool_calling, safety_agentic, and financial_services.

This is the explicit non-canonical comparison to the completed-turn design in #3907. A separate issue is unnecessary because the implementation exists to compare runtime ownership directly.

How it was verified

  • Public-main runtime import and evaluator import in isolated environments — passed.
  • Environment tests against the public-main dependency — 4 passed.
  • Resources tests against the public-main dependency — 12 passed.
  • Preparation tests — 4 passed.
  • Deterministic native parity for tool_calling, safety_agentic, and financial_services — 3 passed.
  • uv run pre-commit run --files <changed runtime files> — passed.
  • git diff --check — passed.

Rollout evidence

A live three-probe retry completed financial_services and safety_agentic before the run was stopped. financial_services returned the native result with 43 recorded activations. safety_agentic returned a native result but its scorer was masked after the configured support endpoint rejected the scorer JSON schema. The final tool_calling row was stopped before completion. Full clean live validation remains pending, so this PR stays draft.

Results impact

Tool trajectories use UserSim’s native Environment-owned loop rather than an Agent-owned tool loop. Invocation ledgers include User, Assistant, Judge, Summary, and tool-simulation activations. Existing work is pre-release; no compatibility migration is required.

@copy-pr-bot

copy-pr-bot Bot commented Sep 29, 2026

Copy link
Copy Markdown

This pull request requires additional validation before any workflows can run on NVIDIA's runners.

Pull request vetters can view their responsibilities here.

Contributors can view more details about this message here.

@ffrujeri
ffrujeri requested a review from a team as a code owner September 30, 2026 02:27
@ffrujeri
ffrujeri force-pushed the ffrujeri/usersim-environment-tool-loop branch from f216dd6 to e96c901 Compare September 30, 2026 02:31
@ffrujeri
ffrujeri marked this pull request as draft September 30, 2026 02:34
@3mei

3mei commented Sep 30, 2026

Copy link
Copy Markdown
Contributor

@ffrujeri Thanks for building this as a direct comparison. It runs NeMo UserSim's own loop for the episode, which makes it the reference for the proposal in UserSim#10: keep #3791's split (Resources owns the episode, the Assistant Agent owns the model/tool loop), with UserSim's own loop running inside Resources and UserSim producing the episode input rows. A prototype of that session matched standalone runs on all 14 probes.

Suggestion: keep this open as the reference until #3791 reproduces its results on the same rows, then close it, carrying over the UserSim/Responses converters, execute_tools: false (for agents that cannot record their outputs) and context_compression: false.

For reference runs to reproduce standalone UserSim:

@ffrujeri
ffrujeri force-pushed the ffrujeri/usersim-environment-tool-loop branch from e96c901 to 7ea2bda Compare October 1, 2026 23:04
@ffrujeri
ffrujeri changed the base branch from ffrujeri/usersim-rollout-quickstart to ffrujeri/usersim-probe-examples October 1, 2026 23:04
@ffrujeri
ffrujeri force-pushed the ffrujeri/usersim-environment-tool-loop branch from 6fff1e8 to 6c29241 Compare October 2, 2026 00:07
@ffrujeri
ffrujeri added this pull request to stack #3916 October 2, 2026 00:49
@ffrujeri
ffrujeri marked this pull request as ready for review October 2, 2026 00:50
@ffrujeri
ffrujeri force-pushed the ffrujeri/usersim-environment-tool-loop branch from 12e7a1d to 7d07d41 Compare October 2, 2026 00:53
@yaoyu-33 yaoyu-33 added area:environment Individual environments, benchmarks, verifiers, and environment-specific resources servers complexity:high Cross-component or shared-contract change with a large review surface feature New capabilities, enhancements, or enablement work needs-review PR is ready for code review and waiting on a reviewer labels Oct 2, 2026
@ffrujeri
ffrujeri force-pushed the ffrujeri/usersim-environment-tool-loop branch from ecfabcd to fc1287f Compare October 5, 2026 16:16
@ffrujeri
ffrujeri force-pushed the ffrujeri/usersim-environment-tool-loop branch from 106a27d to 84495c5 Compare October 5, 2026 17:25
@ffrujeri
ffrujeri force-pushed the ffrujeri/usersim-environment-tool-loop branch from 84495c5 to 66ea1c9 Compare October 5, 2026 17:42
@ffrujeri ffrujeri added the r0.7.0 Auto-cherrypick to release branch. Apply before merge; cherrypick happens after merge. label Oct 5, 2026
native_failure = outcome.get("status") == "failed"
failure_attribution = outcome.get("failure_attribution")
evaluator_error = assistant_eval.get("error")
mask_sample = (native_failure and failure_attribution != "assistant_model") or bool(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Mask the sample when the judge returns no score.
UserSim's _call_judge catches every judge exception and every unparseable reply, and returns {} (generator.py L348-371).
In that case assistant_quality is None, reward is 0.0, evaluator_error stays None, and mask_sample stays False.
A support endpoint that times out or rejects the judge schema therefore scores every row as a genuine policy failure.
The resources server README in #3910 says evaluator errors are masked.
This was reproduced by running _evaluate with a judge that raises on general_open_ended: reward 0.0, mask_sample=False, failure_kind=None.
Please compute scenario_completed before the mask, then mask completed episodes that have no quality score:

quality_missing = scenario_completed and assistant_quality is None and not assistant_eval.get("skipped", False)
mask_sample = (native_failure and failure_attribution != "assistant_model") or bool(
    scorer_error or evaluator_error or quality_missing
)

Please set failure_kind to JUDGE_FAILED from nemo_gym.failure_kinds in that branch, and add a test that drives the real _evaluate with a failing judge.

Comment on lines +475 to +477
activation_result = await bridge.invoke_activation(event)
event = await runtime.advance(activation_result)
bridge.record_state(await runtime.evidence())

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Record evidence against the activation that produced it.
runtime.advance(...) runs UserSim's tool loop, which appends tool_simulation invocations through the bridge.
record_state then writes to self.invocations[-1], so evidence lands on the last tool simulation call instead of the assistant activation.
runtime.evidence() also deep-copies the full transcript and traces on every activation.
On the prepared financial_services row, one episode produced 63 invocations, and state_after grew from 33 KB to 1.14 MB per snapshot, about 38 MB per episode.
That payload is sent to /verify and stored in the rollout.
Please record against the captured index, which needs record_state to accept it:

Suggested change
activation_result = await bridge.invoke_activation(event)
event = await runtime.advance(activation_result)
bridge.record_state(await runtime.evidence())
activation_result = await bridge.invoke_activation(event)
activation_index = len(bridge.invocations) - 1
event = await runtime.advance(activation_result)
bridge.record_state(activation_index, await runtime.evidence())

Please also store only the final evidence, or per-step deltas, rather than a full snapshot per invocation.

probe_type = str(seeded.resolved_row["probe_type"])
scorer_name = _scorer_for_row(seeded.resolved_row)
native_scores = assistant_eval.get("scorers", {}).get(scorer_name) if scorer_name else None
scorer_error = native_scores.get("error") if isinstance(native_scores, Mapping) else None

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Classify scorer results with UserSim's own rules.
Some scorers report "not applicable" through error, for example identity disclosure's _SKIPPED and the sovereign AI scorers' "scorer skipped".
This line treats any error as a scorer failure, so those rows are masked and dropped.
safety_chat_pressure and identity_disclosure also document status_proposal as tri-state, and None currently becomes an unmasked 0.
Please use scorer_state from usersim.taxonomy.eval_cell, and document how None is handled.

data.update(scenario.probe_data)
return await generator.agenerate(data)
models: dict[str, Any] = {
alias: HostRoleModel(model_name=_configured_model_name(self, alias))

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Financial services retrieval silently falls back to lexical.
Prepared rows use UserSim's default finance_retrieval_mode="hybrid", which embeds queries through the embedding_model alias.
This models dict has no embedding_model, so UserSim logs "DEGRADING TO LEXICAL" and uses word-overlap retrieval.
The parity test run shows that warning.
Standalone UserSim configures an embedding model, so Gym and standalone results diverge on this probe.
Please add an embedding model reference to the environment server config and pass it through here.

if response_format.get("type") != "json_schema" or not isinstance(json_schema, Mapping):
raise NotImplementedError(f"Unsupported response format: {response_format!r}")
params["text"] = {
strict = json_schema.get("strict", True)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Default strict to absent, not True.
UserSim's judge and scorers send json_schema without strict, and their schemas are not strict-compliant.
Forcing strict: True here is a plausible cause of the support endpoint rejecting the scorer schema in the live run described above.

Suggested change
strict = json_schema.get("strict", True)
strict = json_schema.get("strict")

The "strict": strict entry below then needs to be included only when strict is not None.

type: resources_servers
name: usersim_resources
max_steps: 2
max_steps: 1

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Set execute_tools: false on the user agent too.
UserSim's health disclosure move variant calls the user model with tools=[commit_move].
With the default execute_tools: true, SimpleAgent posts /commit_move to the usersim resources server, which has no tool routes, and UserSim then rejects tool calls on a user activation.

Suggested change
max_steps: 1
max_steps: 1
execute_tools: false

resources_server: ResourcesServerRef
model_server: ModelServerRef
max_steps: int = None
execute_tools: bool = True

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Document this flag and limit it to session activations.
With execute_tools: false on the plain /run path, the agent stops after one model call and sends unanswered function_call items to /verify as a completed response.
A user who sets it on a normal single-agent config gets truncated rollouts with no warning.
Please add a field description, and reject or warn when it is used outside an agent session.

) -> None:
rows = [
json.loads(line)["task_input"]["resolved_row"]
for line in (Path(__file__).parents[2] / "environments/usersim/data/example.jsonl").read_text().splitlines()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Make this test run in CI, and exercise the Gym bridge.
It reads environments/usersim/data/example.jsonl, which is gitignored and must be prepared with network access, so on a fresh checkout it fails with FileNotFoundError.
In the core venv, importorskip at L15 always skips it, so CI never runs it.
The Bridge stub answers activations with the same fake the native side uses.
_ConversationBridge.invoke, the Responses conversion and reasoning propagation are therefore never exercised.
Please move the test under environment_servers/usersim/tests/, build rows from a committed fixture, drive the real bridge with a fake server_client, and rename it.
"Option B" is not defined anywhere in the repository.


assert closed.status_code == 200
evaluate = AsyncMock(return_value=(evaluation, {"helpfulness": 1.0, "accuracy": 0.5, "coherence": 1.0}, 5 / 6))
monkeypatch.setattr(server, "_evaluate", evaluate)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This test mocks out the evaluator it is named after.
_evaluate is replaced with an AsyncMock, so the reward assertion checks the mock's own value.
_ResourcesModelFacade, the UserSim evaluator call and every masking branch are uncovered: coverage of this app.py is 53%.
This PR also deletes the registry drift, close-session and scorer-exception tests while that code remains.
Please add tests that drive the real _evaluate with a scripted facade for judge failure, scorer error, scorer skip and close.

assert "personas_panel" not in source


def test_materialized_provenance_is_parquet_safe(tmp_path: Path) -> None:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This test does not call Gym code.
It round-trips a dict through pyarrow.
Please test the provenance produced by prepare instead, or drop it.

@github-actions github-actions Bot removed the sla:triage-overdue Review assignment is over the one-business-day SLA label Oct 5, 2026
@ffrujeri
ffrujeri force-pushed the ffrujeri/usersim-environment-tool-loop branch 2 times, most recently from bd18a1c to 582bba9 Compare October 6, 2026 00:04
@ffrujeri
ffrujeri merged commit c36f94b into main Oct 6, 2026
@ffrujeri
ffrujeri deleted the ffrujeri/usersim-environment-tool-loop branch October 6, 2026 00:50
@ffrujeri
ffrujeri force-pushed the ffrujeri/usersim-environment-tool-loop branch from 582bba9 to c36f94b Compare October 6, 2026 00:50
@ffrujeri
ffrujeri restored the ffrujeri/usersim-environment-tool-loop branch October 6, 2026 00:50
@nemo-automation-bot
nemo-automation-bot Bot requested review from a team October 6, 2026 00:51
@ffrujeri

ffrujeri commented Oct 6, 2026

Copy link
Copy Markdown
Contributor Author

GitHub marked this PR merged when its rewritten head became an ancestor of its former base during stack reordering; it was not merged into main. The separately reviewable replacement runtime layer is #4080, now correctly based on #3801.

This branch was previously deployed

1 inactive deployment
public — c36f94b7 Deployed Oct 6, 2026 by copy-pr-bot[bot] via release / finalize / notify #4377
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:environment Individual environments, benchmarks, verifiers, and environment-specific resources servers complexity:high Cross-component or shared-contract change with a large review surface feature New capabilities, enhancements, or enablement work needs-review PR is ready for code review and waiting on a reviewer r0.7.0 Auto-cherrypick to release branch. Apply before merge; cherrypick happens after merge.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants