Repository navigation
feat(cli): add gym job cancel and logs - #5345
Conversation
|
Auto-sync is disabled for draft pull requests in this repository. Workflows must be run manually. Contributors can view more details about this message here. |
68fb9d0 to
be5d014
Compare
svcnvidia-nemo-ci
left a comment
There was a problem hiding this comment.
SHIP WITH CARE
Four RISK findings affect cancellation reliability, log-read error reporting, resumed-log selection, and machine-readable output.
Reviewed all 13 changed files and their directly affected callers, contracts, and tests. This was source-only inspection: no tests or Slurm commands were executed. Suggested patches and regression checks below require verification before adoption.
Review generated by codex. This was a full review. Request a full review with /review reset=true.
| 'followups=""', | ||
| f'for _f in "$dir"/{FOLLOWUP_CLAIM_PREFIX}*; do [ -f "$_f" ] && followups="$followups,$(tr "\\n" "," < "$_f")"; done', | ||
| f'wanted=",$chain,$followups,{recorded},"', | ||
| "squeue_out=$(squeue --me --all --noheader --format='%i|%T|%Z' 2>&1); squeue_rc=$?", |
There was a problem hiding this comment.
RISK — A successor queued after this snapshot escapes cancellation.
Failure: A running auto-resume job can be between creating its empty claim and submitting its successor. This script reads the claim and snapshots parent 800; the resume prologue then queues successor 900 before scancel 800. Only the saved snapshot is cancelled, so 900 receives no cancellation request. Pending-first ordering protects only successors already in that snapshot. This affects cancellation during resumable-job startup, including cancel --all.
The prologue's CANCELLED check does not fully contain the failure: its empty-accounting branch deliberately resumes when accounting remains unavailable, allowing the missed successor to continue the benchmark.
Correction: Could render_terminate_script() coordinate discovery with successor submission and drain jobs appearing during cancellation? The invariant is that an enqueue in flight between discovery and stopping its parent cannot escape the cancellation set, as required by Terminable.terminate. If coordination requires changing render_resume_prologue(), account explicitly for already-generated scripts that do not honor a new guard. I cannot establish a complete small patch from the current implementation; simply reversing cancellation order is not sufficient.
Preservation / acceptance (proposed, not executed): Add a barrier-controlled successor submission: let termination snapshot 800, then enqueue 900 before cancelling 800; assert 900 also receives cancellation and no runnable successor remains. Exercise the empty-accounting continuation branch. Retain the existing control tests: pending 900 is cancelled before running 800, symlinked directories match, claim IDs match outside the directory, unrelated jobs remain untouched, and finished jobs are not passed to scancel.
| """The commands that print `path`, or only its last `tail` lines, after a line saying whether it exists.""" | ||
| quoted = shlex.quote(str(path)) | ||
| reader = f"cat -- {quoted}" if tail is None else f"tail -n {int(tail)} -- {quoted}" | ||
| return ["set +e", f'if [ -f {quoted} ]; then echo "{_MARK}ok"; {reader}; else echo "{_MARK}missing"; fi', "true"] |
There was a problem hiding this comment.
RISK — Propagate failures from cat and tail.
Failure: When the path is a regular file but the reader fails—for example permission denial or a filesystem read error—the script emits __GYM_CONTROL:ok, ignores the reader's exit status, and finishes with true. Connection._checked consequently discards stderr, and the parser returns an empty or truncated log as a successful read. Both whole-file and --tail requests are affected.
Correction: Could reader failure exit the script nonzero? Replace this return in render_read_log_script() with this candidate patch:
return [
"set +e",
f'if [ -f {quoted} ]; then echo "{_MARK}ok"; {reader} || exit $?; else echo "{_MARK}missing"; fi',
"true",
]The invariant is that failed reads raise rather than return successful log content. stream_logs reads eagerly, so the existing CLI RuntimeError handler will report the error before printing partial content. Verify the suggested code before adopting it.
Preservation / acceptance (proposed, not executed): Put stand-in cat and tail commands on PATH that print partial content, emit Input/output error to stderr, and exit 1. Each read must raise RuntimeError containing that reason; CLI stdout must remain empty. Retain the existing assertions for all four lines, the last two lines, tail=0, the distinct missing-file error, replacement decoding, quoted paths, and literal protocol words inside successful log content.
| job = record.benchmark_job(benchmark) | ||
| chosen = _resolve_log_source(job, source, instance) | ||
| observed = executor.query_states([JobRef(record, job)]).get((record.gym_job_id, benchmark)) | ||
| job_id = (observed.job_id if observed else None) or job.job_id |
There was a problem hiding this comment.
RISK — Use the newest known chain ID when accounting is unavailable.
Failure: For a resumed benchmark recorded as job 100, with .gym_job_chain containing 100\n101\n, no active jobs and no accounting entries, Slurm's observer returns job_id=None but job_ids=["100", "101"]. This fallback silently reads driver-100.log instead of the latest known attempt. The job_ids contract retains the chain oldest first, so the newer ID is available.
Correction: Could logs() prefer the observed current ID, then the newest observed chain ID, then the recorded ID? Replace this assignment with:
job_id = job.job_id
if observed is not None:
job_id = observed.job_id or (observed.job_ids[-1] if observed.job_ids else job_id)Preservation: Keep observed.job_id first: when 100 is running and successor 101 is pending, logs must read 100, not the highest ID. Missing observations or empty observed IDs must still fall back to the record; an enqueue failure with no IDs must retain its error. Source/instance resolution and tail/follow forwarding remain unchanged.
Acceptance (proposed, not executed): Extend the operations tests: return ObservedStatus(state=UNKNOWN, job_ids=["12345", "12400"]) for _logged() and assert logs/driver-12400.log is streamed. With job_id="12345" and the same chain, assert logs/driver-12345.log. Retain the existing logs/vllm-12345.log fallback and never-queued ValueError assertions. Verify the candidate patch before adopting it.
| (current,) = status([gym_job_id]) | ||
| live = [job for job in current.jobs if job.state not in _FINISHED] | ||
| if not live: | ||
| print(f"Nothing to cancel: every benchmark of {gym_job_id} has finished.") |
There was a problem hiding this comment.
RISK — Honor --json when cancellation is a no-op.
Failure: Once every benchmark has finished, gym job cancel gym-job-a --all --confirm gym-job-a --json exits successfully but prints Nothing to cancel: ... instead of JSON. A script consuming the advertised machine-readable output therefore fails precisely when retrying cancellation after completion. This early return bypasses the normal JSON result serialization.
Correction: Could this branch serialize the already-observed statuses when as_json is true? A replacement for the if not live block is:
if not live:
if as_json:
print(json.dumps([job.model_dump(mode="json") for job in current.jobs], indent=2))
else:
print(f"Nothing to cancel: every benchmark of {gym_job_id} has finished.")
return 0The invariant is that successful --json invocations always emit the same JSON array shape, including no-op cancellation. This retains the existing human-readable message and performs no termination or additional scheduler query.
Preservation / acceptance (proposed, not executed): Extend the all-finished CLI case with --json: json.loads(stdout) must yield one status with benchmark gpqa and state SUCCEEDED, exit status must be 0, and no scancel call may occur. Retain the exact existing text assertion without --json, the live single-benchmark JSON assertion, and the confirmation/refusal behavior for live submissions. Verify the suggested patch before adopting it.
| from nemo_gym.orchestration.submit import cancel, cancel_submission, status | ||
|
|
||
| if everything and benchmark: | ||
| raise ValueError("Give a benchmark or --all, not both.") |
There was a problem hiding this comment.
nit: Could we make it a argparse error?
There was a problem hiding this comment.
Done, they're argparse errors now.
| _MAX_CONCURRENT_CONNECTIONS = 8 | ||
|
|
||
| # Nothing is left to stop for a job in one of these states. | ||
| _FINISHED = {JobState.SUCCEEDED, JobState.FAILED, JobState.CANCELLED} |
There was a problem hiding this comment.
Same list is defined in cli/job.py
There was a problem hiding this comment.
Good catch, it lives in jobs.py next to JobState now and both import it.
|
|
||
| # Every line of the script's output that carries an answer starts with this, so a warning from a shell | ||
| # profile or from Slurm cannot be mistaken for one. | ||
| _MARK = "__GYM_CONTROL:" |
There was a problem hiding this comment.
Same nit suggestions as for PR 2:
- I wouldn't include separator in the
_MARKand ideally defined it as separate constant - I'd extract here all special strings you use as contants
There was a problem hiding this comment.
nit: Is there a reason to have control and status kept in separate files? And if we want to separate, why the log reading logic is here?
There was a problem hiding this comment.
Status only reads, control acts on the scheduler, so I'd keep them apart. The logs being in control wasn't a good reason, it was just the other half of this PR. Moved them to slurm_logs.py. Happy to fold control into status if you'd rather have one file.
|
|
||
|
|
||
| class SlurmExecutor(BaseExecutor, Resubmittable, Inspectable): | ||
| class SlurmExecutor(BaseExecutor, Resubmittable, Terminable, LogReadable): |
There was a problem hiding this comment.
Was Inspectable removed on purpose?
There was a problem hiding this comment.
Not removed on purpose, but I see why it looks that way. Terminable and LogReadable both subclass Inspectable, so Slurm is still Inspectable through them (isinstance is still true). I dropped it from the class line as redundant.
They subclass it because both need it: cancel calls status before and after terminate (skip finished jobs, report whether the stop worked), and logs calls query_states to find the newest job id for the log path.
The class line hiding that is a fair point though. Listed Inspectable explicitly now (last, so the MRO works), so the line shows everything Slurm supports.
be5d014 to
a899241
Compare
a899241 to
8e9d1e1
Compare
b3c239a to
728a2fe
Compare
728a2fe to
d827788
Compare
d827788 to
d0d9409
Compare
|
/ok to test d0d9409 |
|
🔄 Merge queue validation started! You can track the progress here: https://github.com/NVIDIA-NeMo/Gym/actions/runs/44494135669 |
|
🔄 Merge queue validation started! You can track the progress here: https://github.com/NVIDIA-NeMo/Gym/actions/runs/44497333249 |
…tions cancel asks the scheduler, leaves a finished job alone, stops the rest and reports what it sees next. cancel_submission needs the submission's id as confirmation before it asks anything, and reports a benchmark it cannot stop on its own while the others proceed. logs resolves the source and instance against the planned log sources, fills in the id of the job that is running now, and fails before any output when nothing matches. Signed-off-by: Tomasz Grzegorzek <[email protected]>
SlurmExecutor is Terminable and LogReadable. terminate runs one script that finds everything of a benchmark that is queued or running, by its directory and by the job ids its chain and follow-up claims name, and cancels the pending jobs before the running ones so no follow-up can start in between. stream_logs reads a log, or its last lines, in one call. Command output is now decoded with replacement, so a log with a stray non-UTF-8 byte is read instead of failing. Signed-off-by: Tomasz Grzegorzek <[email protected]>
gym job cancel stops a benchmark, or with --all every live benchmark after the submission's id is typed (or given with --confirm; there is no --yes), and exits 1 if the scheduler refused one. gym job logs prints a benchmark's driver or service log, optionally its last lines. Signed-off-by: Tomasz Grzegorzek <[email protected]>
Signed-off-by: Tomasz Grzegorzek <[email protected]>
Cancel re-reads the queue until nothing of the benchmark is left, so a follow-up queued while its parent dies is cancelled too. A log reader that fails fails the read instead of returning a short log. Logs read the newest job of the chain when none is current. cancel --all --json prints JSON when there is nothing to cancel. Argument checks of cancel are argparse errors, the finished states live in jobs.py, the control script names its answer kinds, and log reading moves to slurm_logs.py. Signed-off-by: Tomasz Grzegorzek <[email protected]>
Signed-off-by: Tomasz Grzegorzek <[email protected]>
…r that resolves Signed-off-by: Tomasz Grzegorzek <[email protected]>
…script Signed-off-by: Tomasz Grzegorzek <[email protected]>
d0d9409 to
e3683aa
Compare
Summary
Stacked on #5344 (which is stacked on #5295): this branch is based on
prokotg/gym-job-status, so the diff shows only this PR. I retarget it as the PRs below it merge.gym job cancelandgym job logs.cancel ID BENCHstops a benchmark;cancel ID --allstops every live benchmark after the submission's id is typed.logs ID BENCHprints the driver's log, or a service's with--source, or only the last lines with--tail N.operations.py):cancelasks the scheduler, leaves a finished job alone, callsterminate, asks again and returns what it sees. The scheduler can take a moment to report a stopped job, so it may still readRUNNING. Nothing is written to the record.cancel_submissionraises unlessconfirmequals the submission's id, before anything is asked. A benchmark that cannot be stopped is reported on its own, with aCANCELLEDfailure saying why, and the others proceed.logsresolves--sourceand--instanceagainst the planned log sources, fills in the id of the job that is running now (a resumed run reads its newest job, not the first), and fails before any output when nothing matches.TerminableandLogReadable(slurm_control.py).terminateis one script that finds everything of the benchmark that is queued or running, by its directory (same-file match) and by the job ids its chain and follow-up claims name, and cancels the pending jobs before the running ones, so a queued auto-resume follow-up cannot start in between.stream_logsreads a log, or its last N lines, in one call.connection.py), so a log with a stray non-UTF-8 byte is read instead of failing the call.--yesdoes not exist, on purpose:--allneeds the id typed, or--confirm IDfor scripts. Without a terminal and without--confirmit fails and cancels nothing. The exit code is 1 when the scheduler refused any benchmark.PR plan
Five PRs, Slurm only. Goal: status, cancel and logs for a submitted run without going to the scheduler.
statusandinfo, SlurmInspectable,gym job list,status,info.cancel,cancel_submissionandlogs, SlurmTerminableandLogReadable,gym job cancelandlogs.gym eval submittells you what to type next.gym job resubmit;gym eval resubmitstays as a deprecated alias until 2026-11-23, with a test that fails then.Not in these five:
logs --follow(the connection returns a whole command's output at once, so following needs a streaming connection), Kubernetes, progress, services declaring their own log sources.What it prints
Real output of the CLI over a job index, with stand-ins for
squeueandscancel. In that runrulerhad a running job and a pending follow-up, andscancelwas called with the pending one first.Validation
terminateand the log reader run for real in a shell against stand-insqueueandscancel: the pending follow-up is cancelled before the running job, a job of another directory is left alone, a symlinked directory still matches, the ids the chain and the claim files name are cancelled whereversqueuesays they run, a finished job is not handed toscancel,scancelorsqueuefailing is raised with what Slurm said, a directory with spaces and quotes, a non-numeric recorded id never reaching the script, and a log that contains the protocol's own words. The CLI is driven throughmain(), including the interactive confirmation (a terminal is simulated) and a refusal fromscancel.canceltests that cover it.mainon macOS (two use GNUsed -i;test_memory_profiler_uses_spawned_server_metadata). The fourth,test_a_service_that_exits_mid_run_ends_the_job_and_names_the_service, runs real processes and timing, passed 3 out of 3 on its own and did not fail in the earlier full runs, so I read it as a flake under load.origin/main(sandbox, docker compose, harbor,super35launcher, CI-environment, telemetry, theopensandboxSlurm-eval tests, and thesedtests above). The timing test named above passed in this run.ruffand pre-commit pass.Known gaps
terminateusessqueue --me --all --noheader --format='%i|%T|%Z'andscancel; whether a queuedafternotokfollow-up starts after its parent is cancelled was not checked on a cluster, so the script cancels pending follow-ups explicitly and first either way.logshas no--followand reads the whole file when there is no--tail, so use--tailon a large log.terminateis one connection per benchmark, socancel --allopens one per live benchmark.cancelandlogsfail withUnsupportedOperationError.Rollout evidence
N/A: no agent, verifier or model behavior is touched.
cancelstops scheduler jobs, so I did not run it against a real cluster in this PR (see above).