Skip to content

feat(rollout): write run_examples rollouts to a run folder shard - #5359

Closed
marcromeyn wants to merge 2 commits into
romeyn/rl-path-recordsfrom
romeyn/rl-path-run-records
Closed

marcromeyn wants to merge 2 commits into
romeyn/rl-path-recordsfrom
romeyn/rl-path-run-records

Conversation

@marcromeyn

Copy link
Copy Markdown
Contributor

Stacked on #5318; the diff below is this PR's commit only.

What and why

A training framework that dispatches through run_examples (NeMo RL) keeps no Gym run folder, so Gym's readers (aggregation, the run health check, EvalRDL's reader) can't read its rollouts, and RL dumps Gym state itself (NVIDIA-NeMo/RL#4890). With this PR Gym writes those rollouts itself, in the layout ng_collect_rollouts uses.

  • RunRecordWriter(record_output_dir, shard, *, record_omitted_rollouts=False) writes one shard: <dir>/rollouts-<shard>.jsonl with its failures sidecar beside it. A result goes to the rollouts file, a failed one to the sidecar with its attempt cap, and an interrupted or never-started try to the sidecar as an omitted-rollout row when record_omitted_rollouts is set.
  • run_examples(..., record_output_dir=..., record_shard=..., record_omitted_rollouts=False) writes each rollout through it after feat(rollout): expose per-rollout enrichment to run_examples callers #5318's enrichment (and implies it). An Environment Server episode is written as the record the collector stores.
  • The caller picks the shard label (for example a training step and worker); Gym owns the file names, so a folder of shards is what gym eval aggregate merges and the other readers already read.
  • The identity and routing fields collection stamps on each record (indices, rollout id, agent, task source, skills, environment server and type, elapsed time, policy model server) and the failure-row builder are now shared by both paths, so the rows match.

Shard rules:

  • Reopening a shard replaces it, so a replayed step does not duplicate rows. A writer whose shard was reopened by another refuses to write; opening and each write hold a per-shard file lock.
  • The rollouts file exists from the start, so a shard where every rollout failed is still found.
  • Labels must be plain names and must not end with _failures or _materialized_inputs, which would collide with sidecars.
  • Nothing is replaced until the options, the config and the rows have been validated.

Not in this PR: NeMo RL switching #4890 to these options; identity fields from the capture-identity design (model_ref, weight_version, agent instance); health checks during the run (they can run on the folder afterwards).

Validation

  • With the telemetry extra: pytest tests/unit_tests/test_rollout_collection.py tests/unit_tests/test_fern_docs_links.py: 652 passed.
  • 8 tests (14 cases) for the writer: where each outcome goes (with and without omitted rows), replacing a shard, refused labels, a failures-only shard, a writer whose shard was reopened, the run_examples path writing the enriched and stamped record, a refused call or a dispatch error keeping the existing shard, and a returned rollout id that differs from the row's.
  • pre-commit on the changed files.

Rollout evidence

gym env start --resources-server example_single_tool_call --model-type openai_model ++observability_enabled=true ++model_call_capture_dir=... with gpt-6-luna, then two run_examples(rows, record_output_dir=run, record_shard="step_1" / "step_2") calls on two example rows each: rollouts-step_1.jsonl and rollouts-step_2.jsonl held two records each, with rollout id, agent ref, captured model calls and ng_trajectory. gym eval aggregate +input_glob='run/rollouts-step_*.jsonl' +output_jsonl_fpath=run/rollouts.jsonl then merged the four records and wrote aggregate metrics and verdicts. Not run: an Environment Server pairing through this path.

Compatibility

Opt-in only. ng_collect_rollouts output is unchanged; it now builds its stamping and failure rows through the shared helpers.

Linear: FEP-1907 (part of FEP-1829 / GYM-1170).

marcromeyn and others added 2 commits October 29, 2026 15:52
run_examples returns the raw /run result, so a training framework that
dispatches through it (NeMo RL) never gets what ng_collect_rollouts records
for each rollout: the model server's captured calls, the normalized
ng_trajectory and ng_perf.

enrich_run_result runs the collector's per-rollout steps in place: wait for
capture quiescence, merge the captured model calls, project ng_trajectory and
assemble ng_perf. ng_collect_rollouts now calls it, so there is one
implementation and no behavior change there. run_examples gains an opt-in
enrich_results (with include_model_call_payloads and delete_model_call_capture);
with it off, results are exactly what /run returned.

A row that never started is not joined to calls; an interrupted try keeps the
calls it made. A row that names no task gets no ng_trajectory rather than a
guessed task id, and deleting the capture without keeping payloads is refused.

Co-authored-by: Pranav Thombre <[email protected]>
Signed-off-by: Marc Romeyn <[email protected]>
A training framework that dispatches through run_examples (NeMo RL) keeps no
Gym run folder, so Gym's readers (aggregation, the run health check, EvalRDL's
reader) cannot read its rollouts, and RL dumps Gym state itself.

RunRecordWriter writes finished rollouts the way ng_collect_rollouts lays out a
run, one shard at a time: <dir>/rollouts-<shard>.jsonl with its failures
sidecar beside it. A result goes to the rollouts file, a failed one to the
sidecar with its attempt cap, and an interrupted or never-started try to the
sidecar as an omitted-rollout row when record_omitted_rollouts is set. The
caller picks the shard label (a training step, a worker); Gym owns the file
names, so a folder of shards matches the glob gym eval aggregate merges.
Reopening a shard replaces it, so a replayed step does not duplicate rows.

run_examples(record_output_dir=..., record_shard=...) writes each enriched
rollout through it; an Environment Server episode is written as the record the
collector stores. The collector and the writer share the failure-row builder.

Signed-off-by: Marc Romeyn <[email protected]>
@copy-pr-bot

copy-pr-bot Bot commented Oct 30, 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.

@marcromeyn

Copy link
Copy Markdown
Contributor Author

/ok to test 7ae80de

@nemo-automation-bot
nemo-automation-bot Bot requested a review from a team October 30, 2026 11:07
@svcnvidia-nemo-ci svcnvidia-nemo-ci added area:evaluation Evaluation, rollout collection, reward profiling, comparison, and exporters feature New capabilities, enhancements, or enablement work needs-review PR is ready for code review and waiting on a reviewer labels Oct 30, 2026

@svcnvidia-nemo-ci svcnvidia-nemo-ci left a comment

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.

HOLD — two recording defects need attention: inode reuse can defeat stale-writer rejection, and missing recording indices can erase an existing shard before failing.

Reviewed both changed files and the affected dispatch, enrichment, episode-conversion, aggregation, and run-health paths. The extracted collector stamping preserves the existing assignments. This was a static review; no tests were executed.

Note: formal approval is not available for this request, so this review is posted as a comment only.

Review generated by codex. This was a full review. Request a full review with /review reset=true.

fd, partial = tempfile.mkstemp(dir=self.rollouts_fpath.parent, prefix=f".{self.rollouts_fpath.name}.")
os.close(fd)
Path(partial).replace(self.rollouts_fpath)
self._generation = self.rollouts_fpath.stat().st_ino

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.

BLOCKER — inode reuse can reactivate a superseded writer

Could we identify shard generations independently of inode numbers? This saves only st_ino, while write() accepts any file with that number. After B replaces A's shard, A retains no open descriptor keeping its old inode allocated. A later reopening C can reuse that inode, allowing A to append stale successes or failures into C's replay without raising. The lock serializes operations but does not prevent this ABA sequence. The blast radius is the replayed shard and metrics derived from its mixed records.

Correction: publish a fresh generation token in the persistent lock file and check it under that same lock before every append. Keep the inode comparison as an additional external-replacement check. A small suggested implementation is to import TextIO, change _locked() to return Iterator[TextIO], open with "a+", and yield lock. Then make these additions at its two callers:

# __init__: use `with self._locked() as lock:`.
# After replacing the rollout file and assigning self._generation:
self._writer_token = secrets.token_hex(16)
lock.seek(0)
lock.truncate()
lock.write(self._writer_token)
lock.flush()

# write: use `with self._locked() as lock:`.
# Before the existing inode check:
lock.seek(0)
if lock.read() != self._writer_token:
    raise RuntimeError(
        f"{self.rollouts_fpath} was replaced by another writer for the same shard"
    )

Never unlink or replace the lock file; all writers must lock the same object. Publish the token only after successful shard replacement. This suggestion is unexecuted and needs verification before adoption.

Preservation and acceptance: add a deterministic regression opening A, B, then C for one label while simulating recycled rollout-path inode numbers. A's success and failure appends must both raise, leaving C's files unchanged; C must remain writable. Retain the existing two-writer rejection assertion, replay replacement leaving only reward 1.0, failures-only empty-main discovery, and omitted-row routing on/off. Different labels must remain independently writable. The invariant is that every successful reopening invalidates every earlier writer, even when filesystem identity numbers recur.

latency_tracker=latency_tracker,
**({"retry_requests": False} if not retry_requests else {}),
)
# Opened last, once the options, the config and the rows are known good, because opening replaces the shard.

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.

RISK — validate recording indices before replacing the shard

_run_examples_with_metadata() validates routing but does not require task/rollout indices. An otherwise supported row such as {"agent_ref": {"name": "my_agent"}, "responses_create_params": {"input": []}} therefore reaches this writer initialization. Opening replaces the existing main file and deletes its failures sidecar; after /run succeeds, the new stamping callback raises KeyError. The caller loses the previous shard and receives no newly recorded rollout. Unindexed dispatch is already exercised by an existing dispatcher test.

Correction: recording needs these indices for reader compatibility, so reject missing indices explicitly before constructing RunRecordWriter. Do not weaken shared stamping to use .get() or add guessed indices to all callers. Suggested guard before completions = self._run_examples_with_metadata(...):

if record_output_dir is not None:
    for index, row in enumerate(examples):
        missing = [
            key for key in (TASK_INDEX_KEY_NAME, ROLLOUT_INDEX_KEY_NAME)
            if key not in row
        ]
        if missing:
            raise ValueError(
                f"Recording row {index} is missing required fields: {', '.join(missing)}"
            )

The invariant is that recording's mandatory stamping inputs are checked before any existing shard is replaced. Suggested code is unexecuted and must be verified.

Preservation and acceptance: using the real dispatcher with a fake HTTP client, seed both an existing main file and failures sidecar, then parameterize rows missing either or both indices. run_examples(..., record_output_dir=..., record_shard=...) should raise ValueError synchronously, leave both files byte-for-byte unchanged, and send no /run request. The same unindexed row without recording must retain its existing dispatch behavior, including enrichment-only calls. Indexed flat and materialized episode rows must still record normally; retain the enriched-record assertions and row-owned capture-ID assertions.

@AdamRajfer AdamRajfer left a comment

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.

The shard writer is in #5443 as _RunRecordWriter, reached through run_examples(record_output_dir=..., record_shard=...), with the same file layout and the same replace-on-reopen rule. On top of main it writes typed failure rows, the shard's materialized inputs and a manifest built with RunManifest.create, so gym eval run +resume_from_cache=true resumes a shard, and, from your review, each shard's rollout ids are prefixed with its run id so capture keys no longer collide across shards. One thing the port turned up: the file lock alone didn't stop a superseded writer from overwriting the newer writer's status file, so the writer now carries a token that every write and status flush checks. #5443 is in the merge queue; once it lands nothing remains here and this can be closed.

@marcromeyn

Copy link
Copy Markdown
Contributor Author

Carried into #5443 (merged), rebased onto the failure stack with authorship kept; closing this one.

@marcromeyn marcromeyn closed this Nov 5, 2026

This branch was previously deployed

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

Labels

area:evaluation Evaluation, rollout collection, reward profiling, comparison, and exporters feature New capabilities, enhancements, or enablement work needs-review PR is ready for code review and waiting on a reviewer sla:review-overdue Review response is over the one-business-day SLA

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants