Skip to content

feat(cli): add gym job cancel and logs - #5345

Merged
marta-sd merged 8 commits into
mainfrom
prokotg/gym-job-cancel-logs
Nov 19, 2026
Merged

marta-sd merged 8 commits into
mainfrom
prokotg/gym-job-cancel-logs

Conversation

@prokotg

@prokotg prokotg commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

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 cancel and gym job logs. cancel ID BENCH stops a benchmark; cancel ID --all stops every live benchmark after the submission's id is typed. logs ID BENCH prints the driver's log, or a service's with --source, or only the last lines with --tail N.
  • The operations (operations.py):
    • cancel asks the scheduler, leaves a finished job alone, calls terminate, asks again and returns what it sees. The scheduler can take a moment to report a stopped job, so it may still read RUNNING. Nothing is written to the record.
    • cancel_submission raises unless confirm equals the submission's id, before anything is asked. A benchmark that cannot be stopped is reported on its own, with a CANCELLED failure saying why, and the others proceed.
    • logs resolves --source and --instance against 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.
  • Slurm is Terminable and LogReadable (slurm_control.py). terminate is 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_logs reads a log, or its last N lines, in one call.
  • Command output is decoded with replacement (connection.py), so a log with a stray non-UTF-8 byte is read instead of failing the call.
  • Docs: the Job Management page covers both commands.

--yes does not exist, on purpose: --all needs the id typed, or --confirm ID for scripts. Without a terminal and without --confirm it 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.

  1. feat(orchestration): add job-management interfaces and types #5295: the types, the capability interfaces, the operations declared, and the submit-time log plan.
  2. feat(cli): add gym job list, status and info #5344: the logic of status and info, Slurm Inspectable, gym job list, status, info.
  3. This PR: the logic of cancel, cancel_submission and logs, Slurm Terminable and LogReadable, gym job cancel and logs.
  4. feat(cli): tell the user what to type after gym eval submit #5357: gym eval submit tells you what to type next.
  5. feat(cli): add gym job resubmit #5444: gym job resubmit; gym eval resubmit stays 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

$ gym job logs gym-job-20261029T093012Z-4f1a9c ruler --tail 3
line 5
line 6
line 7

$ gym job cancel gym-job-20261029T093012Z-4f1a9c --all --confirm gym-job-20261029T093012Z-4f1a9c
gpqa: already finished (SUCCEEDED); nothing was cancelled
ruler: cancel requested; still RUNNING (the scheduler can take a moment to report CANCELLED)

Real output of the CLI over a job index, with stand-ins for squeue and scancel. In that run ruler had a running job and a pending follow-up, and scancel was called with the pending one first.

Validation

  • 53 new tests. terminate and the log reader run for real in a shell against stand-in squeue and scancel: 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 wherever squeue says they run, a finished job is not handed to scancel, scancel or squeue failing 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 through main(), including the interactive confirmation (a terminal is simulated) and a refusal from scancel.
  • Three mutations confirmed the tests can fail: dropping the id-list match fails the claim-file test, cancelling the running job before the pending one fails the ordering test, and strict decoding fails the non-UTF-8 test. Removing the "leave a finished job alone" check fails the three cancel tests that cover it.
  • Orchestration and CLI tests: 904 passed, 4 failed. Three fail on clean main on macOS (two use GNU sed -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.
  • Full unit suite: 13445 passed, 49 failed. All 49 also fail on clean origin/main (sandbox, docker compose, harbor, super35 launcher, CI-environment, telemetry, the opensandbox Slurm-eval tests, and the sed tests above). The timing test named above passed in this run.
  • The generated job scripts are still byte-identical (six scripts diffed). ruff and pre-commit pass.

Known gaps

  • Not run on a Slurm cluster. terminate uses squeue --me --all --noheader --format='%i|%T|%Z' and scancel; whether a queued afternotok follow-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.
  • logs has no --follow and reads the whole file when there is no --tail, so use --tail on a large log.
  • terminate is one connection per benchmark, so cancel --all opens one per live benchmark.
  • Kubernetes records: cancel and logs fail with UnsupportedOperationError.

Rollout evidence

N/A: no agent, verifier or model behavior is touched. cancel stops scheduler jobs, so I did not run it against a real cluster in this PR (see above).

@prokotg prokotg added feature New capabilities, enhancements, or enablement work area:orchestration Job submission, deployment, services, and lifecycle management area:cli Command-line interfaces and user-facing command behavior labels Oct 30, 2026
@copy-pr-bot

copy-pr-bot Bot commented Oct 30, 2026

Copy link
Copy Markdown

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.

@prokotg
prokotg force-pushed the prokotg/gym-job-cancel-logs branch from 68fb9d0 to be5d014 Compare October 30, 2026 06:42
@prokotg
prokotg added this pull request to stack #5351 October 30, 2026 06:43
@prokotg
prokotg marked this pull request as ready for review October 30, 2026 09:43
@nemo-automation-bot
nemo-automation-bot Bot requested review from a team October 30, 2026 09:43
@svcnvidia-nemo-ci svcnvidia-nemo-ci added the needs-review PR is ready for code review and waiting on a reviewer label Oct 30, 2026
@github-actions

github-actions Bot commented Oct 30, 2026 •

Copy link
Copy Markdown
Contributor

@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

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=$?",

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 — 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"]

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

Comment thread nemo_gym/orchestration/operations.py Outdated
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

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

Comment thread nemo_gym/cli/job.py Outdated
(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.")

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 — 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 0

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

Comment thread nemo_gym/cli/job.py Outdated
from nemo_gym.orchestration.submit import cancel, cancel_submission, status

if everything and benchmark:
raise ValueError("Give a benchmark or --all, not both.")

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.

nit: Could we make it a argparse error?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done, they're argparse errors now.

Comment thread nemo_gym/orchestration/operations.py Outdated
_MAX_CONCURRENT_CONNECTIONS = 8

# Nothing is left to stop for a job in one of these states.
_FINISHED = {JobState.SUCCEEDED, JobState.FAILED, JobState.CANCELLED}

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.

Same list is defined in cli/job.py

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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:"

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.

Same nit suggestions as for PR 2:

  • I wouldn't include separator in the _MARK and ideally defined it as separate constant
  • I'd extract here all special strings you use as contants

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Same as PR 2, done.

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.

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?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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):

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.

Was Inspectable removed on purpose?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

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.

@prokotg
prokotg force-pushed the prokotg/gym-job-cancel-logs branch from b3c239a to 728a2fe Compare November 18, 2026 10:16
@nemo-automation-bot
nemo-automation-bot Bot requested a review from a team November 18, 2026 10:17
@prokotg
prokotg force-pushed the prokotg/gym-job-cancel-logs branch from 728a2fe to d827788 Compare November 18, 2026 15:38
@svcnvidia-nemo-ci svcnvidia-nemo-ci added the risk:high Autobot PR risk: high label Nov 18, 2026
@prokotg
prokotg force-pushed the prokotg/gym-job-cancel-logs branch from d827788 to d0d9409 Compare November 19, 2026 08:20
@prokotg

prokotg commented Nov 19, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test d0d9409

@prokotg
prokotg added this pull request to the merge queue Nov 19, 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/44494135669

@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue because a pull request earlier in the stack was removed Nov 19, 2026
@prokotg
prokotg added this pull request to the merge queue Nov 19, 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/44497333249

@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to failed status checks Nov 19, 2026
Base automatically changed from prokotg/gym-job-status to main November 19, 2026 09:50
…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]>
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]>
@prokotg
prokotg force-pushed the prokotg/gym-job-cancel-logs branch from d0d9409 to e3683aa Compare November 19, 2026 09:50
@nemo-automation-bot
nemo-automation-bot Bot requested a review from a team November 19, 2026 09:51
@marta-sd
marta-sd merged commit 8a67679 into main Nov 19, 2026
61 of 62 checks passed
@marta-sd
marta-sd deleted the prokotg/gym-job-cancel-logs branch November 19, 2026 09:57
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:cli Command-line interfaces and user-facing command behavior area:orchestration Job submission, deployment, services, and lifecycle management feature New capabilities, enhancements, or enablement work needs-review PR is ready for code review and waiting on a reviewer risk:high Autobot PR risk: high

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants