Skip to content

fix(terminus_2): bypass tmux input queue for C-c interrupt signals - #1005

Closed
YanhaoLi-Cc wants to merge 3 commits into
harbor-framework:mainfrom
YanhaoLi-Cc:fix/tmux-interrupt-bypass
Closed

YanhaoLi-Cc wants to merge 3 commits into
harbor-framework:mainfrom
YanhaoLi-Cc:fix/tmux-interrupt-bypass

Conversation

@YanhaoLi-Cc

@YanhaoLi-Cc YanhaoLi-Cc commented Mar 5, 2026 •

Copy link
Copy Markdown

Problem

When the agent sends a large input via tmux send-keys (e.g. a heredoc with cat > file << 'EOF'), the keystrokes are buffered in tmux's internal input queue. If the agent subsequently tries to send C-c (Ctrl+C) to interrupt a hanging process or exit heredoc input mode, the C-c keystroke is queued behind the pending characters in tmux's buffer and never reaches the foreground process.

This causes the terminal to appear completely stuck — the agent repeatedly sends C-c but none of them take effect, wasting all remaining turns.

Root Cause

tmux send-keys processes input sequentially through an internal buffer. When a large payload (e.g. a 10KB+ heredoc) is sent, tmux queues the characters and feeds them to the PTY one by one. A subsequent tmux send-keys C-c does not jump the queue — it simply appends \x03 (the interrupt character) to the end of the buffer, after thousands of pending characters. The foreground process never sees the interrupt until the entire buffer is drained.

Solution

This PR adds an interrupt bypass mechanism to TmuxSession.send_keys():

  1. Detection: A regex pattern (^(C-c)+$) detects when the keystrokes consist solely of C-c interrupt signals.

  2. Direct SIGINT delivery (bypassing tmux's input queue):

    • pkill -INT -P {pane_pid} — sends SIGINT to child processes of the shell (e.g. a hanging python or make process).
    • kill -INT {pane_pid} — sends SIGINT to the shell itself (handles heredoc / readline stuck cases where the shell is the foreground process).
  3. Cleanup: After a 0.5s wait for signal delivery, two regular C-c keystrokes are sent via tmux send-keys to abort any partial command that may have been reconstructed from residual buffer contents.

New Methods

Method Purpose
_is_interrupt_only(keys) Detect if input consists solely of C-c signals (supports both str and list[str] input)
_send_interrupt() Core bypass logic: SIGINT via kill/pkill + cleanup C-c
_get_pane_pid() Retrieve the shell PID from tmux via display-message -p '#{pane_pid}'
_raw_send_keys(key) Low-level tmux send-keys without interrupt detection (avoids recursion)
_exec_best_effort(cmd) Execute shell commands with error suppression

Compatibility

  • The existing send_keys API is unchanged — callers do not need modification.
  • Non-interrupt keystrokes follow the original code path with no behavioral change.
  • The bypass gracefully falls back to regular tmux send-keys C-c if the pane PID cannot be determined.

Open with Devin

When tmux's internal buffer has pending keystrokes (e.g. from a large
heredoc), C-c sent via 'tmux send-keys' gets queued behind those
characters and never reaches the foreground process, causing the
terminal to appear stuck.

This commit adds an interrupt bypass mechanism:
- Detect when keystrokes consist solely of C-c signals
- Send SIGINT directly to the pane's foreground process and shell
  via kill/pkill, bypassing tmux's input queue
- Follow up with regular C-c keystrokes to clean up any residual
  partial commands from the drained buffer

This resolves the 'heredoc stuck' issue where Ctrl+C could not
interrupt a hanging process or exit heredoc input mode.
devin-ai-integration[bot]

This comment was marked as resolved.

Remove .strip() to avoid silently swallowing trailing whitespace.
Expand the regex to ^(C-c)+\n?$ to explicitly allow an optional
trailing newline, since 'C-c\n' still has pure interrupt intent.
Arbitrary whitespace like ' C-c ' will no longer match.
@YanhaoLi-Cc YanhaoLi-Cc closed this by deleting the head repository Apr 30, 2026
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]>
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.

1 participant