Skip to content

fix(agent): recover Terminus controls and exited shells - #3983

Merged
lafrancef merged 4 commits into
mainfrom
flafrance/tb21-harness-reliability-20261003
Oct 7, 2026
Merged

lafrancef merged 4 commits into
mainfrom
flafrance/tb21-harness-reliability-20261003

Conversation

@lafrancef

@lafrancef lafrancef commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

When a foreground process stops reading stdin, queued input can fill the terminal buffer and trap Ctrl-C behind a paste. Terminus then receives unchanged observations indefinitely. Adding a newline to a standalone control key also turns it into literal text, despite the parser suggesting that newline. If the interactive shell exits, including after an interrupt with set -e enabled, Harbor can return normally before the model declares completion.

Normalize standalone control keys, drain cancelled input until quiet before sending native Ctrl-C (with a five-second limit), and preserve raw-terminal input semantics. Report unchanged terminal buffers as the current screen, and fall back to Harbor token counting when model usage is absent. These fixes apply automatically to the existing Terminus agent configuration.

Preserve an exited shell's output and replace its PTY, discarding pending input and the remaining command batch. The model receives a notice describing the reset shell state and must confirm completion again. Task files and configured environment remain available. A missing tmux session fails explicitly. Shell replacement fails explicitly when terminal recording is enabled; the Gym agent already disables that recording.

Linux and live-sandbox reproductions cover blocked Ctrl-C, raw-terminal input, ordinary shell failure, and interrupts with set -e, including 32,768 queued commands. They verify that recovery retains files without executing pending input. A real Harbor-loop regression verifies that the model sees the reset notice before confirming completion. Model smoke rollouts for this revision are pending; this remains a draft until their agent and verifier traces are inspected. The regression reproductions are included here, so a separate issue is unnecessary.

Tested: two separate e2e TB2.1 runs achieved >95% completion rate, previous to this change ~92% to ~94%

@copy-pr-bot

copy-pr-bot Bot commented Oct 3, 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 lafrancef changed the title fix(agent): unblock Terminus interrupts behind queued terminal input fix(agent): recover Terminus controls and exited shells Oct 3, 2026

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

Could you add to the PR description how the change was tested? If there is a full run that demonstrates no regression and addresses the problem this PR tries to solve, I can approve it.

@lafrancef
lafrancef marked this pull request as ready for review October 6, 2026 20:10
@lafrancef

Copy link
Copy Markdown
Contributor Author

/ok to test 0928768

Normalize standalone control keys, preserve raw-terminal input semantics, and avoid replaying unchanged terminal output as new. Fall back to token counting when a model response omits usage.

Signed-off-by: Frederic Lafrance <[email protected]>
Read pending input until an idle interval instead of assuming one read window empties a large paste. Bound recovery to five seconds and retain raw-terminal key handling.

Signed-off-by: Frederic Lafrance <[email protected]>
@lafrancef
lafrancef force-pushed the flafrance/tb21-harness-reliability-20261003 branch from 0928768 to 5e493ea Compare October 6, 2026 20:54
@lafrancef

Copy link
Copy Markdown
Contributor Author

/ok to test 5e493ea

@yaoyu-33 yaoyu-33 added area:agent Agent harnesses and Responses API agent behavior bug Something isn't working labels Oct 6, 2026
@yaoyu-33 yaoyu-33 added complexity:medium Single-domain change with interacting parts or a moderate review surface ready-to-merge PR is approved, current, and waiting for final CI or merge labels Oct 6, 2026
@lafrancef
lafrancef added this pull request to the merge queue Oct 7, 2026
@github-actions

github-actions Bot commented Oct 7, 2026

Copy link
Copy Markdown
Contributor

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

Merged via the queue into main with commit 6368213 Oct 7, 2026
48 checks passed
@lafrancef
lafrancef deleted the flafrance/tb21-harness-reliability-20261003 branch October 7, 2026 08:29
fsiino-nvidia added a commit that referenced this pull request Oct 7, 2026
…3983

Merges origin/main. Resolves conflicts in the Terminus 2 agent by taking main's terminal session code and re-applying the private mount bootstrap around TerminusTmuxSession.start().

Removes our recover_stalled_interrupts mechanism, its counters and tests, since #3983 now drains queued input before Ctrl-C by default. Updates the mount tests for the new session flow.

Signed-off-by: Frankie Siino <[email protected]>
fsiino-nvidia added a commit that referenced this pull request Oct 7, 2026
Removes the generic terminal-use message appended to every task, so the recipe sends the original task instructions unchanged. Upstream #3983 now normalizes standalone control keys in code. Re-pins normalized_rows_sha256 for the unmodified rows.

Signed-off-by: Frankie Siino <[email protected]>
khazic pushed a commit to khazic/Gym-lao that referenced this pull request Oct 20, 2026
…eMo#3629)

## Summary

Inkling-Small was reported at **40.17%** on Terminal-Bench 2.1 using
Gym's Terminus 2 harness, against [64.7%
published](https://huggingface.co/thinkingmachines/Inkling-Small#5-evaluations)
with a private harness. Most of the gap turned out to come from the
surrounding harness and infrastructure (stuck terminals, grading
dependencies, dropped reasoning history), not from the model. This PR
adds a reproducible Inkling-Small Terminal-Bench 2.1 recipe (listed in
the benchmark catalog with its own `manifest.yaml`) and the fixes below.

- **Results:** a full run of this work scored **59.41% (423/712)**, and
a rerun at commit `173ec922a` scored **60.34% (429/711)**, with one
attempt cancelled by the cluster scheduler (see [Rerun at the pre-merge
commit](#rerun-at-the-pre-merge-commit)). The final code (commit
`48cc31a7f`: merged `main`, terminal guidance on) scored **58.37%
(415/711)** in a full run, with one attempt (task 17, attempt 3)
cancelled while still running and no failures. All scores use the
automatic benchmark results without manual adjustments, and individual
gains come from separate comparisons that cannot be added together.
- **Scope changes along the way:** items 1 and 3 were superseded by
upstream changes that landed in `main` (NeMo Gym NVIDIA-NeMo#3549 and NVIDIA-NeMo#3983). The
branch has merged `main` and removed the PR's own versions of those.
Item 2 (terminal guidance) was dropped too, then restored once the
merged-code run showed it is worth about 5 points.

PR references below were checked on September 24, 2026, apart from NeMo
Gym NVIDIA-NeMo#3549 and NVIDIA-NeMo#3983, which come from `main`'s git history on October 7,
2026. They provide related failure reports or implementation history;
they do not establish the accuracy gains reported here or imply that
this PR's exact changes were accepted upstream. Items without a linked
PR rely on the local evidence described here.

## Changes

1. QEMU grading dependencies (superseded by upstream)

- **Problem:** Package downloads failed while preparing the two QEMU
graders.
- **Result:** The original run had 13 incomplete graders out of 16 QEMU
attempts.
- **Original solution:** The dated Debian snapshot sources recorded in
the task images were restored and the package indexes refreshed. The
first full run with that change then graded all 16 QEMU attempts, with
seven passing, and scored 41.43% overall.
- **Current state:** [NeMo Gym NVIDIA-NeMo#3549 — retain Bullseye security packages
during sandbox setup](NVIDIA-NeMo#3549),
merged September 21, 2026, fixes the same failure in sandbox setup by
redirecting the Debian Bullseye security source to a signed snapshot. On
October 7, 2026, live sandboxes for both QEMU task images (both Debian
Bullseye) were checked: with `main`'s setup alone the verifier's
`apt-get update` and `apt-get install` succeed. The branch's own QEMU
patch was therefore removed when merging `main`.
- **See:** `_BULLSEYE_SECURITY_SNAPSHOT_SETUP` in
`resources_servers/terminal_bench_2_1/app.py:36`.
- **Related PR:** [Terminal-Bench NVIDIA-NeMo#82 — repair package installation for
the two QEMU
tasks](harbor-framework/terminal-bench-2#82)
reports expired Debian package indexes and missing downloads preventing
grading. Its proposed repair switches to `archive.debian.org` and
removes the old security source; the branch's original patch restored
the dated snapshot sources recorded in the images, and `main` now uses
its own snapshot redirect. This supports the dependency-failure
diagnosis. The PR was open when checked.

2. Terminal guidance

- **Problem:** Traces showed incorrect special-key formatting and
confusion between echoed input and executed commands.
- **Result:** The model sometimes proceeded as though commands had
executed when they had not.
- **Solution:** A short message of general instructions is appended to
every task, explaining terminal controls and how to recognize that the
shell is ready. Both the 59.41% and 60.34% runs included it.
- **Current state:** kept. It was briefly dropped so the recipe's inputs
would match vanilla TB2.1 (an earlier 24-attempt diagnostic scored 13/24
passes with and without it, and upstream NVIDIA-NeMo#3983 normalizes standalone
control keys in code, which covered the one part that was a harness
bug). The full run on the merged code without it (commit `d25578c1d`)
then scored 54.60%, against 61.16% with it restored (commit `4c6c990e6`)
on otherwise identical code (+6.3 points on the 703 attempts finished in
both). That accounts for the whole drop from the pre-merge rerun. The
24-attempt diagnostic was too small to see an effect that is
concentrated in a dozen long-running tasks. The cost is that the
recipe's task inputs differ from vanilla TB2.1.
- **See:** `prepare()` in
`benchmarks/terminal_bench_2_1/prepare_inkling_small.py`, and
`normalized_rows_sha256` in
`benchmarks/terminal_bench_2_1/inkling_small_tasks.json`, which pins the
rows with the guidance appended.

3. Ctrl+C recovery (superseded by upstream)

- **Problem:** Queued terminal input was reproduced preventing correctly
formatted Ctrl+C from taking effect.
- **Result:** The requested interrupt failed to restore terminal control
in those reproductions.
- **Original solution:** Queued input was drained through a separate
execution channel after the model requested Ctrl+C, subject to
terminal-setting checks. Targeted tests demonstrated recovery from the
reproduced condition. A larger comparison showed 43.12% with recovery
off against a full-denominator bound of 45.51–45.65% with it on, but the
enabled job hit its allocation limit with one attempt missing, so that
gain is bounded, not measured.
- **Current state:** [NeMo Gym NVIDIA-NeMo#3983 — recover Terminus controls and
exited shells](NVIDIA-NeMo#3983), merged
October 7, 2026, fixes the same failure upstream. It drains cancelled
input until quiet before sending a native Ctrl-C (with a five-second
limit), normalizes standalone control keys, and recovers exited shells,
automatically for the Terminus agent. The branch's own implementation
was removed when merging `main` (`216e8ba5a`). The 60.34% rerun used the
branch's implementation, not upstream's.
- **See:** `TerminusTmuxSession` in
`responses_api_agents/terminus_2_sandboxed_agent/terminal.py` and
`NeMoGymTerminus2._execute_commands()` in
`responses_api_agents/terminus_2_sandboxed_agent/app.py`.
- **Related PR:** [Harbor NVIDIA-NeMo#1005 — bypass queued terminal input for
Ctrl+C](harbor-framework/harbor#1005) describes
Ctrl+C getting stuck behind earlier input and proposes sending interrupt
signals directly to processes. It is evidence of the same reported
symptom, not validation of any particular recovery implementation.

4. Noninteractive package installation

- **Problem:** Installations stopped at interactive configuration
prompts.
- **Result:** The package manager remained occupied waiting for input,
blocking further installation progress.
- **Solution:** Set DEBIAN_FRONTEND=noninteractive so supported package
configuration uses defaults.
- **Result:** Diagnostic checks supported using this setting to avoid
those configuration prompts.
- **See:** `sandbox_config.env.DEBIAN_FRONTEND` in
`benchmarks/terminal_bench_2_1/inkling_small.yaml:42`.

5. Hide unrelated shared storage

- **Problem:** Filesystem searches were reproduced stalling while
traversing unrelated shared S3 storage.
- **Result:** The search kept the terminal occupied instead of
completing.
- **Solution:** Give the task terminal a private filesystem view that
hides those mounts.
- **Result:** The mounts were hidden, and the complete environment
workaround improved automatic full-run accuracy from 47.89% → 52.81%
(+4.92 percentage points).
- **See:** `private_terminal_bootstrap()` in
`responses_api_agents/terminus_2_sandboxed_agent/terminal_mounts.py:57`
and `terminal_hidden_mounts` in
`benchmarks/terminal_bench_2_1/inkling_small.yaml`. Only the Inkling
recipe sets it, so other benchmarks and models are unaffected: the
agent-level default (`terminal_hidden_mounts: []`) and the shared
`benchmarks/nemotron_3.5_super/sandbox_utils.yaml` are unchanged. It
needs Linux root, user/mount namespaces and the tmux binary that
`sandbox_utils.yaml` configures, which `sbatch_external_vllm.sh` loads
automatically; running `gym eval run` without the launcher requires
adding `--config benchmarks/nemotron_3.5_super/sandbox_utils.yaml`;
without it the mount hiding has no tmux binary and every rollout fails
with `Private terminal requires tmux`.
- **Verified after merging `main`:** on October 7, 2026, the real agent
setup was run with both mounts hidden against a live sandbox. Inside the
agent's terminal `/mnt/s3-data` and `/mnt/.s3-gate` were empty (tmpfs
mounted over them), while direct sandbox execution, which is what the
grader uses, still saw the S3 data and a file the terminal wrote to
`/tmp`. Only the agent's own tmux session remained afterward.

6. Grader HTTPS certificates

- **Problem:** Grading environments could have the download tools
installed without the required trusted-certificate bundle; that
condition was reproduced.
- **Result:** HTTPS dependency downloads failed before the graders could
run their tests.
- **Solution:** Explicitly install ca-certificates during setup of the
affected graders; the patch applies to everyone's TB2.1 grading.
- **Result:** Live checks confirmed that the reproduced setup failures
were repaired.
- **See:** The two task entries in `TEST_SH_PATCHES` in
`resources_servers/terminal_bench_2_1/app.py:127`.
- **Safeguard:** these are exact-string patches, so a patch that matches
no script now logs a warning naming the task and pattern instead of
being skipped without a trace (`_upload_folder` in the same file), and a
unit test checks that every configured patch matches the pinned task
scripts. It warns instead of failing because the default benchmark
clones the task repository unpinned, so a stale patch must not zero a
task whose upstream script was fixed. This exposed a pre-existing
`mcmc-sampling-stan` patch that targeted `solution/solve.sh` from the
`tests/` table and had never applied; it now sits in the golden-patch
table, so it only affects reference-solution validation.

**Note:** with fixes 1–6 applied, the automatic accuracy was 49.58%.
That shows the result with those changes present, not that each change
contributed to the gain. Their individual contributions have not been
isolated.

7. Preserve earlier reasoning

- **Problem:** Captured requests showed that earlier reasoning was
omitted while commands and outputs remained.
- **Result:** Subsequent requests lacked the model's earlier reasoning
text.
- **Solution:** Enable the agent's interleaved_thinking setting in the
Inkling recipe while keeping the model adapter's existing reasoning
support enabled (already its default).
- **Result:** Request checks confirmed retention, and the matched full
comparison improved automatic accuracy from 49.58% → 58.57% (+8.99
percentage points).
- **See:** `interleaved_thinking` in
`benchmarks/terminal_bench_2_1/inkling_small.yaml` (the shared agent
default in
`responses_api_agents/terminus_2_sandboxed_agent/configs/terminus_2_sandboxed_agent.yaml`
stays `false`) and `uses_interleaved_reasoning` in
`responses_api_models/vllm_model/app.py:170` (already the model
default).
- **Upstream feature:** [Harbor NVIDIA-NeMo#265 — optional interleaved
thinking](harbor-framework/harbor#265), merged
December 23, 2025, introduced the option to include earlier reasoning in
subsequent model requests. This is the existing capability this PR's
configuration enables.
- **Gym integration:** [NeMo Gym NVIDIA-NeMo#3540 — wire reasoning history through
the Terminus 2 adapter](NVIDIA-NeMo#3540),
merged September 18, 2026, added the adapter support and exposed
`interleaved_thinking`, initially set to `false`. That code predates
this branch; the Inkling recipe turns it on.

## Supporting change: POV-Ray reference-solution downloads

- **Problem and solution:** The reference solution's source downloads
failed. The download locations were replaced with archived copies, and
all three archives are verified with SHA-256 checks.
- **Related PR:** [Terminal-Bench NVIDIA-NeMo#77 — archived POV-Ray downloads with
SHA-256
verification](harbor-framework/terminal-bench-2#77)
documents the original host returning HTTP 403 and supplies the archive
URLs and checksums used by this repair. The PR was open when checked.
- **Effect on accuracy:** This only repairs validation of the
benchmark's supplied reference solution. Ordinary model evaluations use
`is_verifying_golden_patch: false`, so this change contributed **no
accuracy gain** to those runs. It is separate from the seven evaluation
changes above.
- **See:**
`GOLDEN_PATCH_SOLVE_SH_PATCHES["terminal-bench/build-pov-ray"]` and
`TerminalBench21ResourcesServer.verify()` in
`resources_servers/terminal_bench_2_1/app.py`.

## Rerun at the pre-merge commit

The rerun used commit `173ec922a` on 6 nodes with 4 GPUs each, with a
vLLM 0.29.0 image built for other evaluations (see [Reproducing the
evaluation](#reproducing-the-evaluation)). 711 of the 712 attempts
finished within about 66 minutes. The cluster's scheduler then cancelled
the job 77 minutes in, while one attempt (task 42, `train-fasttext`,
attempt 5) was still running. The model servers had been nearly idle for
roughly 12 minutes beforehand (about zero requests running), which is
consistent with an idle-job policy, but the cause is unconfirmed. The
launcher did not write its aggregate metrics file, so the numbers below
come from the saved results.

| | Rerun | Earlier full run |
| --- | --- | --- |
| Automatic score | **429/711 = 60.34%** | 423/712 = 59.41% |
| If the missing attempt is counted | 60.25% (fail) to 60.39% (pass)
over 712 | n/a |
| Agent attempts completed | 708/711 | 711/712 |
| Graders completed | 707/711 | 709/712 |
| Results in the failures file | 0 | n/a |

## Validation

- **Resources server:** 44 tests pass
(`resources_servers/terminal_bench_2_1/tests/`), including `main`'s
tests and a guard that every configured patch matches the pinned task
scripts. Removing the unmatched-patch warning, or restoring the
misplaced patch, makes tests fail.
- **Recipe and configuration:** 9 tests pass
(`benchmarks/terminal_bench_2_1/tests/test_inkling_small.py`), covering
the prepared task inputs and the resolved settings in launcher order.
The 84 benchmark-catalog tests (`tests/unit_tests/test_benchmarks.py`)
pass with the new
`benchmarks/terminal_bench_2_1/inkling_small/manifest.yaml`.
- **Agent:** 86 tests pass in the agent's own environment (`gym env test
+entrypoint=responses_api_agents/terminus_2_sandboxed_agent`), including
`main`'s `test_terminal.py` and the mount tests updated for `main`'s
session code.
- **Live sandboxes (October 7, 2026, after merging `main`):** the real
agent setup with hidden mounts left both S3 mounts empty inside the
agent terminal while the grader's view kept the data, and both QEMU task
images updated and installed packages successfully without the branch's
QEMU patch.
- **Local checks:** pre-commit passes on all files.
- **Full evaluation:** the reruns above. At the final commit
`48cc31a7f`, a full run on the container in the reproduction command
scored 58.37% (415/711, one attempt cancelled while running, no
failures). Commit `4c6c990e6` (the same code before the last cleanups)
scored 58.85% (419/712) on that container and 61.16% (433/708) on
another vLLM 0.30.0 image. A baseline run of `origin/main` plus only the
recipe files scored 45.22% (322/712).

## Follow-ups

Known gaps that this PR does not address:
- **`regex-chess` grading loophole:** some attempts pass by swapping
Python's regular-expression implementation instead of satisfying the
requested regex-based solution. The grader awards the pass. It needs a
grader fix and a trace review of the passes in the reruns.

## Reproducing the evaluation

The recipe is `benchmarks/terminal_bench_2_1/inkling_small.yaml`
(catalog entry `terminal_bench_2_1/inkling_small`, described by
`benchmarks/terminal_bench_2_1/inkling_small/manifest.yaml`), launched
through `benchmarks/nemotron_3.5_super/sbatch_external_vllm.sh`, which
loads the config file directly. Requirements: the Gym virtual
environment, a valid OpenSandbox key in `env.yaml`, a vLLM image that
includes Gym built from a recent Gym commit, and sandboxes with Linux
root, user/mount namespace support and the tmux binary configured in
`benchmarks/nemotron_3.5_super/sandbox_utils.yaml`.

The launcher mounts the repository checkout as `/opt/Gym`, so do not
edit it while the job runs. The command below, with the container shown,
was used for full runs of the current code:

```bash
(
    set -euo pipefail
    source .venv/bin/activate
    INKLING_REPO=$(pwd -P)
    INKLING_RUN_NAME="inkling-small-tb21-$(date -u +%Y%m%dT%H%M%S)-$$"

    python -m benchmarks.terminal_bench_2_1.prepare_inkling_small
    mkdir -p "results/$INKLING_RUN_NAME" slurm-logs
    git rev-parse HEAD > "results/$INKLING_RUN_NAME/gym-commit.txt"

    unset SBATCH_RESERVATION SBATCH_QOS MODEL_NAME ROLLOUTS_FPATH
    unset OPENSANDBOX_DOMAIN OPENSANDBOX_API_KEY OPENSANDBOX_PROTOCOL

    MODEL=/path/to/Inkling-Small-NVFP4 \
    VLLM_CONFIG=benchmarks/nemotron_3.5_super/vllm_configs/inkling_small.sh \
    EXPERIMENT_NAME="$INKLING_RUN_NAME" \
    VLLM_MODE=aggregated \
    NUM_NODES=6 \
    SEGMENT=6 \
    SBATCH_ACCOUNT=<your Slurm account> \
    SBATCH_PARTITION=batch_long \
    SBATCH_TIMELIMIT=08:00:00 \
    SBATCH_GRES=gpu:4 \
    CONTAINER=/path/to/evaluation-image.sqsh \
    MOUNTS="/lustre:/lustre,$INKLING_REPO:/opt/Gym" \
    WANDB_MODE=disabled \
    LITELLM_LOCAL_MODEL_COST_MAP=True \
    RAY_TMPDIR=/tmp \
    bash benchmarks/nemotron_3.5_super/sbatch_external_vllm.sh \
        --config benchmarks/terminal_bench_2_1/inkling_small.yaml \
        "++model_call_capture_dir=/opt/Gym/results/$INKLING_RUN_NAME/model-calls" \
        "++route_failures_to_sidecar=true"
)
```

---------

Signed-off-by: Frankie Siino <[email protected]>

This branch was previously deployed

1 inactive deployment
public — 5e493ea2 Deployed Oct 6, 2026 by copy-pr-bot[bot] via release / finalize / notify #4501
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 bug Something isn't working complexity:medium Single-domain change with interacting parts or a moderate review surface ready-to-merge PR is approved, current, and waiting for final CI or merge

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants