Skip to content

feat(scicode): run the SciCode sub-step loop in agent sessions - #5824

Draft
yaoyu-33 wants to merge 15 commits into
mainfrom
yuya/scicode-agent-sessions
Draft

yaoyu-33 wants to merge 15 commits into
mainfrom
yuya/scicode-agent-sessions

Conversation

@yaoyu-33

@yaoyu-33 yaoyu-33 commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

Stacked on #5703 (agent_context). The diff against main includes #5703 until it merges. This PR's own changes are the commits after the merge of main into #5703's branch. To review only them, compare against yuya/agent-context-sessions.

What changed and why

scicode_agent overrides run(). For each sub-step it builds a prompt from the row's sub_steps, calls the model, and accumulates the extracted code. It then sends solutions, step_usage and token_usage_version to /verify as top-level fields. Because of that, single_agent_turn could not drive it. Its benchmark metrics also lived on the agent, which an Environment Server never asks for them. This PR moves the loop into the agent's session activation and moves the metrics to the resources server.

scicode_agent

  • Agent sessions. The agent serves sessions and is added to AGENT_SESSION_AGENT_TYPES.
    • It reads the problem's prompt material from the row's agent_context, using the channel feat(agents): deliver per-task agent context to agent sessions #5703 adds. The material is problem_id, sub_steps (each step's number, description, background, function header and return line), required_dependencies and optional prefilled_steps_code.
    • Test cases and reference code stay with the resources server.
    • A seed without that context, with an undeclared key, with extra sub-step fields, or with sandbox access or required tools is refused with 422.
  • One activation runs the loop. /v1/responses runs the sub-step loop in a single activation. run() and the session share the same loop, so both send the model the same requests. Context-window handling and per-step usage accounting are unchanged.
  • Response. The final sub-step's response comes back with usage summed over the problem. solutions, step_usage and token_usage_version ride under scicode.
  • Observations. The session's model calls are returned as agent observations at close: one invocation, whose model-call refs the trajectory builder joins to captured calls. Each call is recorded as its sub-step completes, so a later failure keeps the calls already made. This follows the per-sub-step trajectory that /run emits on main since fix(scicode): record trajectory and model calls so rollouts are observed #4468, which fix(scicode): emit policy trajectory for rollout health #4087 also targets.
  • Replays. A retry of the activation through another path is refused (409).
  • Metrics. /aggregate_metrics now forwards to the resources server, so the relay path reports what an Environment Server reports.

resources_servers/scicode

  • /verify. It reads solutions, step_usage and token_usage_version from the response's scicode field when the request has no top-level solutions, and drops that field from the echoed response. Scoring of a well-formed answer is unchanged.
  • Rows keep their solutions. Every row, success or masked, now keeps the solutions it was graded on, so the server's REVERIFY_MODE = stateless holds: a re-verify grades the saved answer again. Before, a success row dropped them and a re-verify graded it 0.
  • Answers that cannot be graded fail verification instead of scoring 0:
    • a request with no solutions (for example a row saved before rows kept them);
    • a scicode field without a solutions dict;
    • solution keys or step_usage step numbers that are not the row's sub-steps (an agent session whose agent_context disagrees with the row).
  • Metric hooks. It owns compute_metrics, compute_repeat_metrics, get_key_metrics and the aggregate_metrics override, all moved verbatim from the agent:
    • sub-step-weighted subtask_accuracy;
    • across-run variability;
    • whole-problem token accounting from step_usage;
    • suppression of partial token statistics.
    • One change: a failed rollout that count_failure_classes_as_zero adds (no response, no token accounting) now reports token_usage_complete: false and no token totals. Before, it failed /aggregate_metrics with a token accounting version mismatch.
  • Fit with fix(eval): aggregate execution metrics in the environment server #5455. The hooks read only verify fields (step_usage, num_steps_*), never ng_perf, so they follow fix(eval): aggregate execution metrics in the environment server #5455's split: the Environment Server reduces execution metrics, and the resources server keeps benchmark scoring.

Data and config

  • benchmarks/scicode/prepare.py writes agent_context into each row through scicode_agent_context(row). The committed example rows carry it, and are otherwise byte-identical.
  • If a problem's context would exceed feat(agents): deliver per-task agent context to agent sessions #5703's 64 KiB limit, prepare leaves it out and names the problem. The 11-step example problem's context is 11 KB; the full test split was not measured here.
  • /run does not forward the row's agent_context to /verify, so its payload keeps its old shape.
  • New resources_servers/scicode/configs/scicode_single_agent_turn.yaml runs the pairing through single_agent_turn_legacy. It sits beside scicode.yaml, which keeps the relay, and uses the same instance names.
  • The benchmark configs stay on the relay until users re-prepare their data with agent_context, as with the other feat(agents): deliver per-task agent context to agent sessions #5703 consumers.

Training trajectory. Like /run, the response holds the final sub-step's output. Each sub-step's model call is captured under the rollout path and listed in the agent's observations.

No public issue tracks this; this description is complete.

Validation

  • pytest resources_servers/scicode/tests benchmarks/scicode/tests: 149 passed.
    • A success row from either path, fed through reverification's _build_verify_payload, is graded again to the same reward, step results and solutions.
    • Refusals: no solutions, and four sub-step mismatches (another problem, more, other, or fewer sub-steps).
    • A counted failure row leaves token usage incomplete, both in the hooks and through the endpoint.
    • Mutation checks: dropping the row's solutions, the sub-step check, or the counted-row handling each fails its new tests.
    • The new tests/test_metrics.py holds the metric tests moved from the agent, rebuilt on rows shaped as /verify returns them.
    • A verify of a session response's scicode field equals a verify of the /run body, and the field leaves the echoed response.
    • prepare writes only the prompt material into agent_context, and leaves out an oversize one.
  • pytest responses_api_agents/scicode_agent/tests: 53 passed. The added test checks that with skip_verification the agent reports no metrics and never calls the resources server.
    • The existing step-loop tests pass unchanged against the shared loop.
    • Session parity. TestAgentSessions seeds a session through the agent's app and runs one activation under the rollout path. It covers three cases: plain, prefilled first step, and context window exceeded mid-problem. The task carries sampling settings (temperature, top_p, max_output_tokens, model). In each case, the policy gets the same requests as /run's, and the response carries exactly /run's solutions, step_usage, token_usage_version and response. The close returns the generated steps' model-call refs.
    • This test first caught a regression in the shared request handling, which is fixed in this PR.
    • Replays, wrong rollout or activation paths, and seed refusals are covered.
    • A failed activation's close still lists the model calls made before the failure.
    • /run's verify payload carries no agent_context.
  • Both paths ran with the primary venv and this tree on PYTHONPATH.
  • pytest tests/unit_tests/config/test_global_config.py tests/unit_tests/environment/test_environment_validation.py tests/unit_tests/test_session_contract_repo.py tests/unit_tests/data/test_task_data.py: 746 passed, 1 failed.
    • The failure is test_agent_without_rs_reference_and_no_schema_is_skipped. It fails the same way on untouched main with this local setup.
  • pytest tests/unit_tests/eval/test_rollout_reverification.py environment_servers/single_agent_turn_legacy/tests/test_app.py: 273 passed. pytest tests/unit_tests -k "scicode or session or agent_context or reverif": 1369 passed, 0 failed. Five modules did not collect because this local venv lacks their dependencies (exporters, speed_bench); none are touched here.
  • gym env validate passes for scicode.yaml, scicode_single_agent_turn.yaml and benchmarks/scicode/config.yaml.
  • pre-commit run --files <changed files> passes.
  • Independent review. A separate review of the first commit compared the parent and this commit's app.py against the same mocked servers. /run sent byte-identical model requests, cookies, verify payload and result, including ng_trajectory. The review's findings are fixed in the second commit or listed under Compatibility.

Rollout evidence

Scripted-model smoke (no real model).

  • Setup. gym env start + gym eval run --no-serve on the 5 committed example problems, once with scicode.yaml (relay) and once with scicode_single_agent_turn.yaml.
    • The policy was a scripted Responses-API stub whose code for each sub-step depends only on the prompt.
    • The grader used a scratch interpreter with numpy, scipy and h5py, and an empty test_data.h5. Every scored step therefore executed and failed with exit:1 (reward 0), on both configs and unmasked.
  • Result. Per problem, both configs gave the same step_usage, step_results, scored_step_ids, step_exits, num_steps_*, response usage and reward. One problem has 11 sub-steps; the others have 1.
  • Model calls. 15 calls with identical request bodies on both configs.
  • Metrics. The relay path's agent forwarded /aggregate_metrics to the resources server, and the session path's Environment Server forwarded it there too. The key metrics were identical: subtask_accuracy 0.0, generation_coverage 1.0, token_usage_complete true, mean/output_tokens_per_problem 36.
  • Call order. Every session episode ran resources seed → agent seed with agent_context → one activation → agent close → /verify → /close_session. Each close returned one invocation whose model-call refs were exactly the generated steps' calls (11 for the 11-step problem). No server process was left after teardown.
  • Grading infrastructure failure. An earlier attempt, before the grader had h5py, showed how the paths differ. /run masks a failed /verify as judge_failed, while the session path reports the Environment Server's standard verification failure.

Pending. A real-model smoke with the real test_data.h5, and model-call capture to check the trajectory join and token capture per sub-step. Commands (policy settings in env.yaml):

gym env start --config resources_servers/scicode/configs/scicode_single_agent_turn.yaml --model-type vllm_model \
    ++scicode.resources_servers.scicode.test_data_fpath=/abs/path/to/test_data.h5
gym eval run --no-serve --agent scicode_agent --input resources_servers/scicode/data/example.jsonl \
    --output results/scicode_session_smoke.jsonl --num-repeats 1 --temperature 0.0

Then repeat with --config resources_servers/scicode/configs/scicode.yaml (the relay) and compare per-problem step_results, step_usage and reward.

Compatibility and overlaps

  • Relay configs and benchmark scores. No change to the relay configs. The model requests and grading are unchanged, so benchmark scores should not move.

  • Where the two paths differ. These come from single_agent_turn, not this PR; the reward is the same whenever verification runs and succeeds.

    • Grader failure. On /run, a failed /verify becomes a masked judge_failed row that can be regraded from its saved solutions. On the session path it is the Environment Server's verification failure.
    • skip_verification. /run ignores it and always verifies. The Environment Server honors it.
  • Rows and re-verify. Rows grow by their solutions. Each solution holds the code of every earlier sub-step, so a row grows with roughly the square of its sub-step count: tens of KB for most problems. record_step_code stays a separate opt-in, which copies the same code into each step record. Re-verifying a SciCode rollout file saved before this change now fails verification for its success rows, because they carry no solutions; before, it silently graded them 0.

  • Verification refusals. A missing or mismatched answer now fails verification instead of scoring 0. On /run it becomes a masked judge_failed row. On the session path it is the Environment Server's verification failure, which is not terminal, so a dataset whose agent_context disagrees with its rows reruns until the retry budget runs out. No current caller sends such an answer.

  • Reverification metrics. Reverification posts /aggregate_metrics straight to the resources server, so it now gets the SciCode metrics (for SciCode and SciCode-Verified) instead of the generic ones.

  • SciCode-Verified data. benchmarks/scicode_verified has its own prepare script, which does not write agent_context yet. That is needed before its session path can run.

  • Direct callers. Anything that called ScicodeAgent.compute_metrics / get_key_metrics directly must call the resources server's instead.

  • Known limits, not changed here:

    • A counted failure row still adds nothing to the subtask_accuracy denominator. Its sub-step count depends on the agent's prefilled-step table (step_utils.PREFILLED_STEPS_CODE), which the resources server cannot see. This was already true when the metrics lived on the agent.
    • A session close returns model-call refs but no per-turn records, because the session observation bundle has no turn type. That is part of the agent-session contract, not this PR.
  • CI on a7bdbb3. The failures are flakes:

    • test_process_supervisor.py::test_only_detached_services_survive_harness_group_termination: a /proc/<pid>/stat read raced a process exit.
    • Hermes test_worker_stop_checkpoints_partial_work_before_hard_cleanup[deadline-True]: passed on rerun.
    • The rerun's server-suite failure was a GitHub 504 while downloading the spaCy model for instruction_following.

    This PR touches none of these files.

  • Overlapping open PRs. fix(scicode): use a pinned scientific grading environment #4892 and fix(scicode): require sub-step programs to reach their tests before passing #4946 also edit resources_servers/scicode (grading environment and runner). Whichever merges second rebases its README and test changes.

🤖 Generated with Claude Code

yaoyu-33 and others added 11 commits November 5, 2026 14:23
An agent session gets its initial model input and its grants, but no task
data. Harnesses that build part of their input from the task row, such as
gdp_pdf_agent's document manifest, labbench2_vlm_agent's media directory
and CritPt's formatting prompt, had no supported way to receive it under
single_agent_turn.

A task row now carries that data in a reserved agent_context key: small
inline values (at most 64 KiB) and artifact references, paths relative to
a root the agent configures. SingleAgentTurnTaskInput lifts it out of
task_data, so the Resources Server never receives it, and single_agent_turn
passes it in AgentSeedSessionRequest.agent_context, omitted when empty.

Each agent declares the keys it reads in agent_context_model. The base
seed refuses with a terminal 422 a context the agent declares no model
for, an undeclared key, a missing required key or a mistyped value, so a
task never runs without data it was given. Agents read the typed context
with parse_agent_context() and resolve artifacts with
resolve_agent_context_artifact(), which refuses paths that leave the root.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>
…idation

A server's TaskData schema validates the task-owned fields of a row and reports unknown keys. agent_context goes to the agent session, never to the Resources Server, so it joins RESERVED_ROW_KEYS instead of showing up as an unknown task field.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>
…tate

An agent whose task context lives in its session state, such as a
document or media to put in the model request, had to override
responses() to reach that state from the episode it creates. Environment
validation then infers custom-gym-agent-loop for it, though the agent loop
is still Simple Agent's.

responses() now creates a session activation's episode through
_create_session_episode(state, body, **kwargs), which by default calls
_create_episode. A subclass overrides it to use the session's context and
leaves responses() and the agent loop alone. The sessionless path is
unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>
…erifier

- Refuse an artifact path with a NUL byte at validation, and turn a path the filesystem cannot look up (name
  too long, no permission) into a 422 seed refusal instead of a 500; other OS errors stay retryable.
- Count the 64 KiB values limit in UTF-8 bytes, not ASCII-escaped JSON.
- Treat an empty agent_context as none in the task input and the seed, so the seed and task digest match a row
  without the key and an agent server that predates the key still accepts the seed.
- Skip a task_data container's agent_context in dataset validation, as the task input lifts it out.
- single_agent_turn_legacy: answer a row that fails the episode request model with the typed /run's 422.
- Re-verification no longer sends a stored agent_context to the Resources Server's /verify.
- Docs and helper docstring: a Simple Agent subclass resolves context in _new_session_state (restores rebuild
  through it) and overrides _create_session_episode, never responses(); configure the real directory as the
  root; files under a directory artifact are the agent's to confine.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
scicode_agent overrides run(): it builds each sub-step's prompt from the
row, calls the model once per sub-step, then sends solutions, step_usage
and token_usage_version to /verify as top-level fields. single_agent_turn
could not drive it, and its benchmark metrics lived on the agent, which an
environment server does not ask.

The agent now serves agent sessions. It reads the problem's prompt
material from the row's agent_context (problem_id, sub_steps prompt
fields, required_dependencies, prefilled_steps_code) and runs the same
step loop inside one /v1/responses activation. The loop is shared with
run(), so both paths send the model the same requests. The response
carries solutions, step_usage and token_usage_version under "scicode";
the session's model calls are returned as agent observations at close.

The scicode resources server reads those fields from the response when
the request has no top-level solutions, and drops them from the echoed
response. It now owns compute_metrics, get_key_metrics and the
aggregate_metrics token-suppression override. The agent's
/aggregate_metrics forwards to it, so the relay and an environment
server report the same metrics.

benchmarks/scicode/prepare.py writes agent_context into each row, and
the example rows carry it. The new scicode_single_agent_turn.yaml runs the
pairing through single_agent_turn_legacy beside scicode.yaml, which keeps
the relay.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>
@copy-pr-bot

copy-pr-bot Bot commented Nov 8, 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.

@yaoyu-33

yaoyu-33 commented Nov 8, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test b90b1ba

@github-actions

github-actions Bot commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

… payload

An agent session now records each generated sub-step's model call as it
completes. Before, a model error at a later sub-step closed the session
with no model calls, so the trajectory lost the calls that had been made
and captured.

/run no longer forwards the row's agent_context to /verify: the payload
keeps its shape from before agent_context existed. prepare.py leaves out
an agent_context over the 64 KiB limit and says which problem; that row
still runs through /run. A retry of the activation through another path
than the first one is refused.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>
@yaoyu-33

yaoyu-33 commented Nov 8, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test 92e3ea4

@svcnvidia-nemo-ci svcnvidia-nemo-ci added feature New capabilities, enhancements, or enablement work area:agent Agent harnesses and Responses API agent behavior labels Nov 8, 2026
yaoyu-33 and others added 2 commits November 8, 2026 16:45
…rity

- /verify fails, instead of grading nothing, when the response's `scicode`
  field carries no solutions dict: only a broken agent sends one, and grading
  it scored an empty answer and dropped the row's sub-steps from
  subtask_accuracy. A response without the field grades as before.
- Tests: the session parity test now carries the task's sampling settings
  (a session that dropped them passed before); top-level solutions win over
  the response field; a seed with a required tool is refused; a replay with
  other settings is refused without rerunning the loop; a problem with no
  generated step closes with no invocation; the committed example rows'
  agent_context parses as the agent's context model.
- prepare counts the problems it writes without agent_context.
- Docs: the benchmark README says the resources server computes the metrics
  and that rows carry agent_context; the server README and the session config
  say the two paths' rewards match whenever verification runs and succeeds,
  and name the two differences; the lift's docstring says rows keep no
  solutions, like /run's.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>
@yaoyu-33

yaoyu-33 commented Nov 9, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test a7bdbb3

… sub-steps

Every rollout row now keeps the `solutions` it was graded on, so the
server's stateless re-verify grades a success row again instead of an
empty answer. /verify refuses a request without solutions, and solution
keys or step_usage step numbers that are not the row's sub-steps (an
agent session whose agent_context disagrees with the row), instead of
scoring the model 0.

A failed rollout that count_failure_classes_as_zero adds (no response,
no token accounting) now leaves token usage incomplete instead of
failing /aggregate_metrics with a version mismatch.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Signed-off-by: yaoyu-33 <[email protected]>
@yaoyu-33

yaoyu-33 commented Nov 9, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test 4bf57ee

This branch was previously deployed

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

Labels

area:agent Agent harnesses and Responses API agent behavior feature New capabilities, enhancements, or enablement work

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants