Skip to content

fix(capture): don't let cancellation strand a queued model-call write - #4092

Merged
wprazuch merged 1 commit into
mainfrom
wprazuch/capture-cancellation-safe
Oct 6, 2026
Merged

wprazuch merged 1 commit into
mainfrom
wprazuch/capture-cancellation-safe

Conversation

@wprazuch

@wprazuch wprazuch commented Oct 6, 2026 •

Copy link
Copy Markdown
Contributor

Problem

_CaptureMiddleware awaits the capture write unshielded on the success path while catching only Exception:

await asyncio.to_thread(_parse_and_record)
except Exception:

A cancellation arriving after that await but before the thread-pool executor picks up the job drops the model-call row with no log line, no .capture.incomplete marker, and no trace anywhere. The error path a few lines above already catches CancelledError; only the success path does not.

The symptom is trajectory_capture_mismatch / missing_captured_call: the agent's ng_trajectory references a response_id that ng_model_call_capture never recorded.

Evidence

Measured on AutomationBench, 600 tasks per run, oci-hsg, by instrumenting four probe points around the finalization and the writer.

unshielded shielded
CAPTURE_FINALIZE (finalizations entered) 8989 9380
CAPTURE_ATTEMPT (writer entered) 8967 9380
CAPTURE_WROTE (writer returned) 8967 9380
FINALIZE − ATTEMPT 22 0
CAPTURE_FINALIZE_CANCELLED 4501 4230
missing_captured_call findings 22 2
unhealthy rollouts 30/600 (5.0%) 3/600 (0.5%)

Three things this pins down:

  1. The store is not the problem. ATTEMPT equals WROTE in both runs — every writer that started, finished. The flock + fsync path in CaptureStore.record never loses a row.
  2. The loss is pre-execution cancellation. In the unshielded run the FINALIZE − ATTEMPT gap is 22, and that run had exactly 22 missing_captured_call findings. No capture-failure warnings were logged, so these were not exceptions.
  3. Shielding closes it. The gap goes to 0 while 4230 cancellations still occur — cancellation is not prevented, it just no longer discards a queued write.

Cancellation on this path is constant (~4000 per 600-task run), but only ~0.5% of cancellations lose data, because asyncio.to_thread cannot cancel a thread that is already running. Only those landing in the pre-execution window lose the row.

Before this, the rate was stable at 5.2–6.3% across four runs that varied checkpoint, serving stack and Gym pin — including a pin carrying #3969, #3970, #3972 and #3974, which address a different capture failure and do not move this one.

Residual: a different mechanism, now isolated

Three rollouts still carry a finding after the fix, down from 22. They are not the same failure, and the distinction is measurable rather than asserted.

Grepping every on-disk *.capture.jsonl in the run for the flagged response_ids:

unshielded shielded
flagged ids absent from disk entirely 39 of 40 0 of 3
flagged ids present on disk 1 of 40 3 of 3

So before the fix the rows were overwhelmingly never written at all; after it, every flagged row is on disk. What remains is a late write — the row reaches the capture file after the rollout record has been snapshotted, so it is absent from ng_model_call_capture while present on disk.

That is a separate race with a separate fix, out of scope here. This change closes the "never written" class completely.

Testing

pytest tests/unit_tests/test_base_responses_api_model.py — 105 passed.

No unit test is added. asyncio.to_thread does not cancel an already-running thread, so the defect only reproduces in the window before the executor starts the job, which I could not schedule deterministically. A test that cannot be made to fail without the fix would be vacuous. The two 600-task runs above are the verification instead.

The success path awaited the capture write unshielded while catching only
Exception, so a cancellation arriving before the thread-pool executor picked
up the job dropped the row with no log line and no incomplete marker. The
error path already catches CancelledError; this matches it.

Signed-off-by: Wojciech Prazuch <[email protected]>
@copy-pr-bot

copy-pr-bot Bot commented Oct 6, 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.

@wprazuch
wprazuch requested review from Glorf and ananthsub and removed request for Glorf October 6, 2026 10:32
@ritaneves

Copy link
Copy Markdown
Contributor

/claude review

@claude

claude Bot commented Oct 6, 2026

Copy link
Copy Markdown
Contributor

SHIP — no reliability concerns.

Single-line change in _CaptureMiddleware: the happy-path capture finalization now wraps asyncio.to_thread(_parse_and_record) in asyncio.shield, with an explicit except asyncio.CancelledError that logs and re-raises.

Verified:

  • Closes a real silent-loss gap. Without the shield, a cancellation landing on the finalization await (e.g. client disconnect / server shutdown mid-request) could strand the queued write before the executor ran it, dropping the capture row with no log line and no incomplete marker — the exact silent-correctness failure the surrounding error path at L1690–1724 already guards against. The shield lets the write complete detached and the new warning leaves a trail.
  • Consistent with the error path. That branch already treats CancelledError as recoverable (records, then re-raises); the happy path now matches.
  • No double-record / no hang. The outer except re-raises, so happy-path finalization only runs when self._app succeeded. shield surfaces outer cancellation immediately rather than blocking, and its internal done-callback retrieves the detached future's result so a later write failure won't leak an 'exception never retrieved' warning.
  • Exception typing correct. CancelledError is a BaseException, so the explicit handler is required (it's not caught by except Exception) and is correctly ordered first.

LGTM.

@yaoyu-33 yaoyu-33 added area:core Shared APIs, servers, telemetry, health, and registries bug Something isn't working complexity:low Localized change in one scope with a small, straightforward review surface needs-review PR is ready for code review and waiting on a reviewer labels Oct 6, 2026
@ritaneves
ritaneves self-requested a review October 6, 2026 12:51
@wprazuch

wprazuch commented Oct 6, 2026

Copy link
Copy Markdown
Contributor Author

/ok to test ee61e2c

@github-actions

github-actions Bot commented Oct 6, 2026

Copy link
Copy Markdown
Contributor

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

Merged via the queue into main with commit 9a0c0e9 Oct 6, 2026
49 checks passed
@wprazuch
wprazuch deleted the wprazuch/capture-cancellation-safe branch October 6, 2026 13:44
elisam0 pushed a commit to elisam0/Gym that referenced this pull request Oct 15, 2026
…a rollout (NVIDIA-NeMo#4593)

## What does this PR do?

A model-call capture write can land on disk *after* the rollout record
is snapshotted. The row is
then present in the capture file but missing from
`ng_model_call_capture`, so the rollout is flagged
`missing_captured_call` / `trajectory_capture_mismatch` even though
nothing about the eval went wrong.

This is the race NVIDIA-NeMo#4092 left open. That PR shielded the capture write so
cancellation can no longer
discard it, and a shielded write runs detached — which is exactly the
ordering problem fixed here.

The write is now claim-tracked:

- the model server writes a per-call pending marker before queueing the
write and clears it when the
  write returns;
- rollout collection waits for a rollout's outstanding claims to clear
before merging capture into the
record (bounded, default 10s, polled every 50ms, returns immediately
when nothing is outstanding);
- a claim still outstanding at the timeout is recorded as a
`model_call_capture_pending` observation
  gap instead of vanishing.

`model_call_capture_pending` is deliberately **not** added to
`_INCOMPLETE_MODEL_CALL_GAPS`. A claimed
write that never landed is real data loss and should stay unhealthy, not
be reclassified as unobserved.

Context: full AutomationBench runs currently report 1.7-18% of rollouts
missing a captured model call
while the scores themselves are unaffected, which fails a 0.1% health
gate downstream.

## Validation

Run against the final diff (branch merged with `main` first):

```
pytest tests/unit_tests/test_base_responses_api_model.py          # 111 passed
pytest tests/unit_tests/test_rollout_collection.py \
       tests/unit_tests/test_rollout_health.py \
       tests/unit_tests/test_rollout_observability.py \
       tests/unit_tests/test_rollout_correlation.py               # 587 passed
pre-commit run --all-files                                        # passed
```

Six new cases in `tests/unit_tests/test_base_responses_api_model.py`
cover: claims scoped to one
rollout, an unsafe `model_call_id` sanitised into the marker filename,
the barrier waiting for a
detached write, the barrier giving up on a stranded claim, the merge
flagging a claim that never
landed, and stale claims being cleared with the captures. The
detached-write case asserts the row is
absent *before* the barrier and present after, so it fails without this
change.

## Rollouts

N/A. No environment or agent behaviour changes — this only affects
capture bookkeeping on the
collection path. Rewards, responses and rollout outputs are untouched.

## Compatibility and benchmark impact

No score impact. Adds a bounded wait before merging capture for a
rollout; the common path is a single
check with nothing outstanding. Adds one new observation gap code,
`model_call_capture_pending`.

## Checklist

- [x] I have read the [contributing
guidelines](https://github.com/NVIDIA-NeMo/Gym/blob/main/CONTRIBUTING.md).
- [x] The change is focused; unrelated "drive-by" edits are tracked as
separate issues/PRs.
- [x] Tests added or updated and pass locally, or N/A for docs-only /
non-code changes (so CI unit/server checks pass when applicable).
- [x] Documentation added or updated, or N/A with justification.
- [x] Pre-commit checks pass locally (`pre-commit run --all-files`) (so
CI lint/format checks pass).
- [x] New source files include the required Apache-2.0 SPDX header.
- [x] All commits have DCO sign-off (`git commit -s`) (so the DCO check
passes).

---------

Signed-off-by: Wojciech Prazuch <[email protected]>

This branch was previously deployed

1 inactive deployment
public — ee61e2c9 Deployed Oct 6, 2026 by copy-pr-bot[bot] via release / finalize / notify #4413
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:core Shared APIs, servers, telemetry, health, and registries bug Something isn't working complexity:low Localized change in one scope with a small, straightforward review surface needs-review PR is ready for code review and waiting on a reviewer

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants