Skip to content

feat(orchestration): record per-job Slurm allocations of a resumable run - #6014

Merged
lafrancef merged 2 commits into
mainfrom
flafrance/gym-slurm-job-allocations
Nov 12, 2026
Merged

lafrancef merged 2 commits into
mainfrom
flafrance/gym-slurm-job-allocations

Conversation

@lafrancef

@lafrancef lafrancef commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

What and why

A resumable Slurm run now records the scheduler allocation of every job it used, so GPU-hours can be computed per job (including preempted, requeued, failed-start and cancelled ones) from the job directory alone, without querying sacct after the fact. Today the chain only keeps the job IDs (.gym_job_chain) and a running walltime total (.gym_accumulated_walltime).

Reading it

<job dir>/job-allocations.jsonl holds one JSON line per allocation incarnation (job ID + restarts) of every job of the run: chain segments, their follow-ups and sentinels, and each requeue separately.

{"alloc_tres":"billing=128,cpu=128,gres/gpu=16,mem=2T,node=2","elapsed_s":300,"end_epoch_s":1300,"ended":true,"gpus":16,"job_id":"100","node_list":"node[01-02]","nodes":2,"recorded_at":"2026-11-11T18:46:24Z","restarts":0,"source":"sacct","start_epoch_s":1000,"state":"NODE_FAIL"}
  • start_epoch_s / end_epoch_s: Unix seconds (sacct with SLURM_TIME_FORMAT=%s); null when the job never started or has not ended.
  • gpus: the gres/gpu=N count of AllocTRES (whole allocation, all nodes); null when absent.
  • state: first word of the Slurm state (CANCELLED by 42 is CANCELLED).
  • GPU-hours of an incarnation: gpus * elapsed_s / 3600, from its "ended": true line when there is one.

How it is recorded

  • Once it has queued its follow-up, every job runs sacct -D -X -P -n over the chain, the claimed follow-ups and the sentinels, and appends every incarnation that has ended and has no line yet. This is idempotent across requeues and re-runs, and a gap left by an unanswered sacct is filled by a later job.
  • A job that ends with nothing after it to record it appends its own allocation as of its exit, with "ended": false and end_epoch_s: null: a prologue stop, a complete run, an idle sentinel, the segment whose epilogue ends the chain, or a segment whose follow-up was not queued. If a later job sees its terminal record, an "ended": true line is added next to it.
  • Recording is best-effort and bounded: the sacct queries and the waits between them end within 30 s (timeout on each query), and when sacct does not answer nothing is written and the chain continues.
  • The read, deduplication and append hold .gym_job_allocations.lock (held for milliseconds, never during sacct; a lock older than a minute is treated as stale), so jobs that record at once never write the same row twice.

The file is a visible JSONL journal next to chain-end-journal.jsonl, since it is meant for readers; the dot-files stay the chain's own state.

Limits

  • Only resumable runs (the prologue/epilogue) record it; a non-resumable single job does not.
  • The last job's line is a lower bound taken shortly before it ends, unless a later job records its terminal row.
  • A job killed abruptly whose follow-up never starts has no line.

Issue: none filed; requested for downstream GPU-hour accounting.

Validation

  • New tests in tests/unit_tests/orchestration/test_resume_script.py run the rendered prologue/epilogue against the fake sacct: ended incarnations recorded once (requeue, cancelled follow-up; the running job skipped), unavailable or stalled accounting records nothing and the chain continues, idle sentinels and stopping jobs record their own allocation, concurrent writers write each row once, a held lock is respected and a stale one broken, the chain-ending job records its own allocation and a later terminal row is added beside it.
  • Rollout evidence: N/A, no environment or agent behavior changes.

🤖 Generated with Claude Code

Each prologue appends, to job-allocations.jsonl in the job dir, one sacct row
per ended allocation incarnation of the run's jobs (segments, follow-ups,
sentinels, requeues), and the job that ends the chain records its own
allocation in its epilogue. Rows carry start/end, elapsed, nodes, node list,
AllocTRES and the GPU count, so GPU-hours can be computed per job without
querying the scheduler again.

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

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

@lafrancef

Copy link
Copy Markdown
Contributor Author

/ok to test 04b4ba2

@github-actions

github-actions Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

@lafrancef
lafrancef marked this pull request as ready for review November 12, 2026 12:16
@lafrancef

Copy link
Copy Markdown
Contributor Author

/review

@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.

SHIP WITH CARE

I found three RISKs in allocation recording: concurrent writers can duplicate accounting rows, orderly prologue exits can omit the final allocation, and the optional scheduler query can block continuation. There's also one NOTE about a test that doesn't exercise its running-row exclusion.

I inspected all three changed files and the affected script-rendering, recovery, and regression-test paths. This was a static review; I didn't execute tests or query Slurm. The acceptance checks below are proposed, not observed results.

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

"," q "restarts" q ":" ($9 + 0) "," q "source" q ":" q "sacct" q "," q "start_epoch_s" q ":" number($3) \
"," q "state" q ":" text(state) "}}"
}}' <<< "$_rows") || return 0
[[ -z "$_new" ]] || printf '%s\\n' "$_new" >> "$_file" || echo "WARNING: cannot append to {job_allocations_name}."

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 — Serialize the journal read, deduplication, and append.

Two legitimate prologues can overlap. When a segment fails, its successor and the sentinel watching that segment can both start (submission branches). Both record allocations before the sentinel decides whether it has work. If both read the journal before either appends, each emits the same newly ended allocation: the existing-row scan and this append aren't one atomic operation. This breaks the one-terminal-row contract and can double-count GPU-hours for the run.

Could you protect the complete read/deduplicate/append operation with a journal-specific, process-safe lock? Locking only the append isn't sufficient. Keep lock acquisition bounded and recording best-effort; don't reuse the resubmit lock or leave a stale recording lock that prevents later gap filling. The available compute-host locking primitive isn't established by the inspected source, so I can't give a certain replacement patch.

Proposed acceptance: start the next segment and an idle sentinel against one directory and the same terminal row. Coordinate their journal reads so the unfixed code would read the same old contents; assert exactly one terminal row for (job_id, restarts) and unchanged submission/exit decisions. Preserve the sequential regression: separate restart values remain separate, and rerunning adds nothing. Preserve the snapshot-to-terminal regression: one running snapshot and one later terminal row for the same incarnation must both remain valid.

[[ -z "$_new" ]] || printf '%s\\n' "$_new" >> "$_file" || echo "WARNING: cannot append to {job_allocations_name}."
return 0
}}
_gym_record_allocations

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 — Record the last allocation on orderly prologue exits too.

Consider a follow-up that stops at the retry cap. Its sentinel starts, records the ended follow-up here, then exits without work. The sentinel's own running row is discarded because this call supplies no self ID. Nothing follows that sentinel, and it never reaches the epilogue recorder, so its allocation has no row even when accounting answers successfully. Completion and other guard exits also bypass the epilogue. This understates the run's allocation cost on an ordinary stop, rather than only after the documented accounting outage or abrupt kill.

Could you record the current allocation before orderly prologue exits that leave no successor? Cover the stop/completion helpers and idle-sentinel exits, and ensure the supplied current ID is included in the query even when it isn't in the chain. Keep idle sentinels out of .gym_job_chain: their exclusion from the continuation budget is intentional. A shared finalizer needs checking against these different exit paths; a blanket EXIT trap isn't a verified patch.

Proposed acceptance: extend the idle-sentinel cases with a recorded sentinel ID and responsive allocation rows. Assert one snapshot for the sentinel with ended: false and end_epoch_s: null, no work or submissions, and unchanged chain, counters, stop marker, and exit status. Check the complete-run prologue exit similarly. A later prologue seeing the sentinel's terminal row must add exactly one ended: true row beside its snapshot. Preserve takeover behavior: a sentinel that continues work must still record the dead follow-up, spend the existing retry budget, and queue its continuation.

_ids=$(_gym_run_job_ids)
[[ -n "$_ids" ]] || return 0
for _sacct_try in 1 2 3 4 5 6; do
_rows=$(SLURM_TIME_FORMAT=%s sacct -D -X -P -n -j "$_ids" --format={job_allocations_format} 2>/dev/null) && \

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 — Bound the optional query's execution time, not only its attempt count.

If the AllocTRES query stalls, this command substitution blocks before the retry loop can advance or return best-effort. Even immediate failures add six ten-second sleeps. The new call runs before the current allocation and provisional marker are recorded and before its successor is secured. For example, a one-minute continuation whose allocation query immediately fails can spend its whole allocation sleeping without reaching either step. The epilogue can also wait here after cancelling its queued jobs, delaying the chain-end journal and return of the driver's status.

Could you give _gym_record_allocations a total deadline covering query execution and retry sleeps, terminate outstanding queries at that deadline, and warn/return zero when recording runs out of time? Preserve the durable bootstrap record before optional scheduler work, and don't let the recording allowance consume the caller's remaining allocation. The appropriate duration and compute-host timeout mechanism need verification, so no exact replacement command is suggested.

Proposed acceptance: make fake sacct block only for AllocTRES while mandatory state/elapsed queries respond immediately. Assert bounded completion, no fabricated allocation rows, a durable current allocation record, and normal successor/sentinel submission. Test immediate failures under a short recording budget too. Repeat with a chain-ending driver and assert bounded shutdown, the chain-end journal, and the original driver exit code. Preserve the existing responsive-accounting rows, deduplication, and unavailable-accounting assertions that continuation proceeds without changing retry/walltime accounting.

f"100|NODE_FAIL|1000|1300|300|2|node[01-02]|{_GPU_TRES}|0\n"
f"100|PREEMPTED|1400|1600|200|2|node[03-04]|{_GPU_TRES}|1\n"
"150|CANCELLED by 42|None|1650|0|1|None assigned||0\n"
f"200|RUNNING|1700|Unknown|5|2|node[05-06]|{_GPU_TRES}|0\n"

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.

NOTE — Suggested coverage improvement: include the running fixture in the requested IDs.

This test queries only 100,150, but its running row belongs to 200. The parser rejects it through the wanted-ID filter before exercising the running-row exclusion. Removing that exclusion would leave this test passing.

A small fixture correction is to use a named running sentinel:

     (tmp_path / ".gym_followup_queued.100").write_text("150\n")
+    (tmp_path / ".gym_followup_sentinel.100").write_text("175\n")
@@
-        # 100 was requeued once, 150 (its follow-up) was cancelled before it started, and 200 (this job) runs.
+        # 100 was requeued once, 150 was cancelled before it started, and sentinel 175 runs.
@@
-        f"200|RUNNING|1700|Unknown|5|2|node[05-06]|{_GPU_TRES}|0\n"
+        f"175|RUNNING|1700|Unknown|5|2|node[05-06]|{_GPU_TRES}|0\n"
@@
-    assert call == f"%s -D -X -P -n -j 100,150 --format={JOB_ALLOCATIONS_FORMAT}"
+    assert call == f"%s -D -X -P -n -j 100,150,175 --format={JOB_ALLOCATIONS_FORMAT}"

Acceptance: retain the three concrete expected rows, assert no row for 175, and retain exactly three rows after the second invocation. This preserves both ended requeue incarnations, cancellation before startup, and sequential idempotence while actually testing the running-row guard. This suggested patch needs verification.

Record the run's ended allocations after the follow-up is queued, with the
sacct queries bounded to 30 s, and append under a lock so jobs that run at
once never write the same row twice. A job that ends with nothing after it
to record it (a stop, a complete run, an idle sentinel, a segment without a
queued follow-up) records its own allocation as of its exit.

Signed-off-by: Frederic Lafrance <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
@lafrancef

Copy link
Copy Markdown
Contributor Author

/ok to test d21df5f

@lafrancef

Copy link
Copy Markdown
Contributor Author

/review

@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.

SHIP

No eligible findings remain in this follow-up.

I verified the concrete prior findings against the current source:

  • The journal's read, deduplication, and append now share a process-safe lock.
  • Orderly stop, completion, and idle-sentinel exits call the self-recording helper, which includes the current job ID without adding idle sentinels to the chain.
  • Durable bootstrap and successor submission now precede optional recording. The deadline and timeout wrapper address the reviewed stalled-query scenario when coreutils timeout is available.
  • The corrected running-row fixture includes sentinel 175 in the query while still requiring only the three ended rows.

I inspected all three changed files and the directly affected rendering, lifecycle, and regression-test paths. New findings were limited to introduced regressions above the historical moderate-impact ceiling. One delegated report wasn't delivered, so I covered its journal-locking assignment directly. This was a static review; I didn't execute tests or query Slurm.

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

@lafrancef
lafrancef requested a review from AdamRajfer November 12, 2026 14:12

@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.

🤖 Adam’s AI assistant
I reviewed this for Adam.

Approving. It only adds files: no exit code, stop marker, retry or score changes, and recording can't hold up the follow-up. Tests pass locally, the new ones fail with the shell changes reverted, and it merges cleanly with #5992.

Small things:

  1. resume_script.py:1032: write the chain-end journal first and record the allocation after. A best-effort sacct query shouldn't sit in front of the bookkeeping operators read, especially near walltime.
  2. Add job-allocations.jsonl to the run-directory list in run-and-babysit-eval/SKILL.md:205.
  3. Who reads this? Please link the consumer or an issue. Non-resumable runs and runs outside Slurm chains never write it, so a reader has to treat a missing file as unknown, not zero GPU-hours.

@lafrancef
lafrancef added this pull request to the merge queue Nov 12, 2026
@github-actions

Copy link
Copy Markdown
Contributor

🔄 Merge queue validation started! You can track the progress here: https://github.com/NVIDIA-NeMo/Gym/actions/runs/43245735445

Merged via the queue into main with commit ae93d0c Nov 12, 2026
122 of 132 checks passed
@lafrancef
lafrancef deleted the flafrance/gym-slurm-job-allocations branch November 12, 2026 15:26
JeffPengCoder added a commit to JeffPengCoder/Gym that referenced this pull request Nov 12, 2026
Include main through 268faf9 after the reviewed provider-repetition health
fix (NVIDIA-NeMo#5975) and Slurm allocation bookkeeping (NVIDIA-NeMo#6014) landed. The prior
GitHub test-merge reference still used the preceding main revision.

Preserve the WebArena layer and the dependent VisualWebArena ancestry.
The upstream provider/core additions receive targeted compatibility checks
and a rerun of the affected Web integration suites before publication;
verification is recorded separately after this source integration.

Signed-off-by: Jeff Peng <[email protected]>

This branch had an error being deployed

1 failed deployment
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants