Skip to content

fix(model): keep streaming /v1/messages calls open while they run - #7157

Open
gwarmstrong wants to merge 2 commits into
NVIDIA-NeMo:mainfrom
gwarmstrong:georgea/messages-stream-keepalive
Open

gwarmstrong wants to merge 2 commits into
NVIDIA-NeMo:mainfrom
gwarmstrong:georgea/messages-stream-keepalive

Conversation

@gwarmstrong

@gwarmstrong gwarmstrong commented Dec 2, 2026 •

Copy link
Copy Markdown
Contributor

What does this PR do?

The default /v1/messages route buffers the whole generation and sends nothing, not even the response headers, until it returns. The Claude Code CLI waits 300 s for headers, then abandons the call and sends it again. A turn whose generation takes longer than that can never finish, and Claude Code retries it until the trial ends. Slow self-hosted models hit this often: Kimi K3.1 Pro on vllm_model decodes about 20 tok/s per request.

A streaming call still running after 15 s now opens its stream and sends an SSE comment every 15 s. When the response is ready, the same Anthropic events follow as before. Anthropic clients skip comments, and the chat route already does the same (_CHAT_KEEPALIVE_SECONDS). Nothing changes for non-streaming calls, or for streaming calls that finish within 15 s; they keep their HTTP error statuses. Closing the stream cancels the backend call.

Once the stream has opened, a failure can no longer return an HTTP status. Instead it ends the stream with an Anthropic error event:

  • A refusal the server propagates becomes invalid_request_error, carrying the engine's message (the HTTP 400 it replaces).
  • Any other failure becomes api_error, with the status in the message. Upstream HTTP errors follow the server's existing propagation policy.

Failure reports. The headers, and the failure header with them, go out before the call ends. So the stream's last event carries the request's failure report (nemo_gym_failure_report), as on the Responses and Chat keepalive streams:

  • A call that succeeds carries it on message_stop. A call that fails carries it on its error event.
  • Capture records the failure that ended the call, with its failure_id, as it does when the call fails before the stream opens.
  • StreamFailureReportReader reads the report from message_stop and error events. Collection merges a captured Messages report into the episode as an observation, without changing the episode's selected failure or reward.

No issue.

Validation

At 2daa69e, in a uv sync --extra dev --extra telemetry --extra mlflow --extra wandb environment (Python 3.13.14):

  • pytest tests/unit_tests/models tests/unit_tests/core tests/unit_tests/rollouts tests/unit_tests/trajectory: 7098 passed, 12 skipped. The new tests:
    • TestStreamingMessagesKeepalive: comments arrive while the call runs; a long call over real HTTP gets comments and then the whole message; each of the three failure kinds after the stream opened gives the expected error event; closing the stream cancels the call.
    • test_a_keepalive_messages_stream_reports_late_failures_on_its_last_event: a failure observed after the first comment reaches the caller once, on the last event, with a failure selected only when the call failed. A call that succeeds sends the same message and usage as the buffered path.
    • test_the_reader_takes_messages_reports_only_from_the_events_that_end_the_stream.
    • test_a_slow_messages_call_keeps_its_typed_failure_in_capture_and_merges_it_as_an_observation: the captured call keeps the typed failure and its failure_id; the episode keeps its own selected failure and reward.
    • test_actual_stream_capture_survives_collection_and_store now also runs Messages.
    • Undoing any one of the source changes for failure reports makes at least one of these tests fail.
  • pytest tests/unit_tests/server_runtime tests/unit_tests/telemetry/test_trace_context_path.py tests/unit_tests/benchmarks/test_agentic_vbench_staging.py: 2484 passed, 2 skipped. These include the other tests that call /v1/messages. The supervisor tests that shell out to uv ran with uv 0.13.12.
  • pytest responses_api_agents/claude_code_agent/tests: 342 passed.
  • pre-commit run --files on the changed files: all hooks pass.

Rollouts

The keepalive ran on an internal Gym branch: EFB's Terminal-Bench-Science recipe for Kimi K3.1 Pro with Claude Code 2.1.241, on vllm_model. Canaries 3 and 4 ran 25 tasks × 3 trials each on OpenSandbox with a 1.5 h agent cap; canary 2 was stopped after 80 minutes.

Canary Gym Calls that returned 200 Calls of 300 s or more that returned Cancelled calls
2 without this change 5,245 none 13, of which 11 at 241–300 s with no byte sent
3 with this change 7,663 of 7,695 162, longest 767.5 s 32: 20 at the trial cap, 12 at 765 s (see below)
4 with this change, and CLAUDE_STREAM_IDLE_TIMEOUT_MS=3000000 on the client 8,344 of 8,373 153, longest 1,029 s; 11 of 765 s or more 29, all at the trial cap

Canary 4 graded 75 of 75 trials with no rollout failure.

The canaries ran bb91eba. The failure reports were checked at 2daa69e with the Claude Code 2.1.241 CLI. It ran in print mode against a Gym model server from this branch, with the keepalive interval set to 2 s, and a backend that took 7 s and observed a recovered 503:

  • Call succeeds: the CLI received 3 comments, then the message with the report on message_stop. It printed the answer and exited 0.
  • First call fails: the CLI received 3 comments, then the error event with the report, which selected the final failure. It retried the call without streaming, as it does after a stream error, then printed the answer and exited 0.

Compatibility and benchmark impact

  • Error reporting: a streaming /v1/messages call that fails more than 15 s in now reports an Anthropic error event inside a 200 stream, not an HTTP error status. Anthropic clients, the Claude Code CLI among them, handle both.
  • Failure report field: when the request observed a failure after the stream opened, message_stop or the error event carries a nemo_gym_failure_report field. Clients ignore it, as the CLI check above shows.
  • No configuration change.
  • Benchmark impact: Claude Code runs on slow backends stop losing every turn longer than 300 s.
  • Client setting for turns past ~765 s: the CLI also has a stream idle watchdog. In 2.1.241, raw stream bytes reset it at most 30 times in a row, and the bundled SDK ignores Anthropic ping events, so the server cannot extend it. A turn longer than about 15 s + 30 × 15 s + 300 s = 765 s therefore also needs CLAUDE_STREAM_IDLE_TIMEOUT_MS raised on the client (canary 3 vs canary 4 above). This PR leaves that setting to each run's client environment.

Checklist

  • I have read the contributing guidelines.
  • The change is focused; unrelated "drive-by" edits are tracked as separate issues/PRs.
  • Tests added or updated and pass locally, or N/A for docs-only / non-code changes (so CI unit/server checks pass when applicable).
  • Documentation added or updated, or N/A with justification. (The messages() docstring describes the keepalive and where the failure report goes.)
  • Pre-commit checks pass locally (pre-commit run --all-files) (so CI lint/format checks pass). (Run on the changed files.)
  • New source files include the required Apache-2.0 SPDX header. (No new files.)
  • All commits have DCO sign-off (git commit -s) (so the DCO check passes).

The default /v1/messages route buffers the whole generation and sends nothing, not even the
headers, until it returns. The Claude Code CLI's HTTP client waits 300 s for response headers,
then abandons the call and re-sends it, so a turn that takes longer can never finish: Claude Code
retries it until it gives up on the trial. In a Terminal-Bench-Science canary with Kimi K3.1 Pro
on vllm_model (about 20 tok/s per request), 5,245 calls returned and none took 300 s or more,
while 11 were cancelled at 241-300 s with no byte sent.

A streaming call still running after 15 s now opens the stream and holds it with SSE comments,
as the chat route does; Anthropic clients skip comments, and the events that follow are
unchanged. A call that fails after the stream opened ends it with an Anthropic error event: a
propagated refusal as invalid_request_error with the engine's message, anything else as
api_error with the status, following the server's upstream-error policy.

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

copy-pr-bot Bot commented Dec 2, 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.

@svcnvidia-nemo-ci svcnvidia-nemo-ci added risk:high Autobot PR risk: high bug Something isn't working area:model Model servers, inference providers, and model adapters needs-review PR is ready for code review and waiting on a reviewer labels Dec 2, 2026
@gwarmstrong

Copy link
Copy Markdown
Contributor Author

/ok to test bb91eba

@nemo-pr-automation
nemo-pr-automation Bot requested a review from a team December 2, 2026 22:07

@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

I found two RISKs in failure diagnostics for long streaming Messages calls. Keepalives, response conversion and cancellation worked in the exercised paths.

I reviewed both changed files and their connected capture, checkpoint and report-consumer paths with three delegated reviewers.

Validation:

  • I relied on this head's successful Nemo_CICD_Test, Unit tests / Test, server-suite shards, combined coverage, lint and Claude Code conformance checks. The container build was skipped. Optional harness conformance failed for openclaw, opencode and miniswe_sandboxed. Two attempts to read detailed job results returned HTTP 503, so I have not attributed those failures.
  • CPU probes ran in gym:a4bf4964cd81600018ada0c0397157c78b4b1021, the default branch's CI image. They exercised slow success and failure, token capture, disconnects before and after stream startup, and checkpoint publication with a fake ledger. Backend cleanup completed, token IDs survived, and capture-finalization errors propagated.
  • Base-versus-head probes reproduced the diagnostic regressions below. A consumer probe also showed that the new Messages error report is discarded while the equivalent Chat report is recovered.

I did not rerun CI-covered suites or run GPU inference or a live Claude Code rollout.

Review generated by codex. This was a full review. Request a full review with /review reset=true.

# an error event would hide an invalid capture.
streamed = await served_stream(anthropic_response)
async for event in streamed.body_iterator:
yield event

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: Forward late failure observations when the call succeeds.

Could you attach _stream_report(failure_log, None) to a terminal Anthropic event here? The keepalive commits the headers before generation finishes, but this success loop forwards every event unchanged. A recovered backend failure observed after that point reaches neither the header nor the body. The Chat success path already forwards these late observations.

I reproduced this through the HTTP route with python success_failure_report.py against base and head, using a shortened interval. Base and the head's quick path return the recovered event in the header. The head's keepalive path returns zero events in both the header and body, despite completing the message successfully. This hides recovered model failures from HTTP callers.

Please preserve the completed message, usage and IDs while forwarding the bounded report. Add a regression where a failure is observed after the first comment and generation then succeeds. The caller should recover that event exactly once, with no selected terminal failure.

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.

Fixed in 2daa69e. On the keepalive path, the message_stop of a call that succeeds now carries the request's failure report (_stream_report(failure_log, None)), as the terminal Responses event and the last Chat chunk do. The message, usage and ids are unchanged.

test_a_keepalive_messages_stream_reports_late_failures_on_its_last_event[False] observes a failure after the first comment, and then the call succeeds. The header carries no report, and only message_stop carries one, holding the event once with no failure_id. The message and usage match what the buffered path sends. The Claude Code 2.1.241 CLI accepts the field (the check is in the description).

anthropic_response = to_anthropic(await pending)
except Exception as exc:
# The stream is already open, so only an error event can report the failure.
yield self._streamed_messages_failure_event(exc, _stream_report(failure_log, exc))

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: Preserve the handled terminal failure in capture.

Could this caught exception also reach structured model-call capture? Returning normally after the error event sends capture through its normal completion path, which supplies no terminal exception to the capture writer.

With python typed_failure_capture.py, a backend that raises an NgFailureEvent without first observing it produces the same event and selected failure_id on base and the head's quick path. After the keepalive, the head stores failure_id: null and events: {}. The generic upstream_error category survives, but the typed cause exists only in raw SSE.

That raw report has no working fallback: collection excludes Messages, and the shared reader rejects type: error. My consumer probe recovers the equivalent Chat report but discards this Messages report.

Please carry the handled exception into structured capture and support the emitted Messages terminal reports in the reader and merge path. A slow typed-failure regression should retain its event identity and per-call failure_id, then merge it as an episode observation without changing the episode's selected failure or reward. Keep the intended quick HTTP errors and late SSE errors.

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.

Fixed in 2daa69e:

  • Capture: the route leaves the handled exception in the request state (nemo_gym_streamed_failure), and the capture middleware passes it to _record as failure. The captured call keeps the typed event and its failure_id, as on the quick path.
  • Reader: StreamFailureReportReader reads reports from Messages message_stop events and from error events that carry an error object. A report on any other Messages event is still omitted.
  • Merge: merge_model_call_capture_into_record also reads captured messages calls, as observations with no failure_id.

Tests:

  • test_a_slow_messages_call_keeps_its_typed_failure_in_capture_and_merges_it_as_an_observation checks the per-call failure_id and events, and that the episode keeps its selected failure and reward.
  • test_actual_stream_capture_survives_collection_and_store now also runs Messages.
  • test_the_reader_takes_messages_reports_only_from_the_events_that_end_the_stream covers the reader.

Quick HTTP errors and the late error event are unchanged.

A streaming /v1/messages call that outlives the keepalive interval commits its headers, and with them
the request's failure header, before the call ends. Failures observed after that point reached no
caller: a call that recovered and succeeded sent its message_stop without a report, a handled
failure reached capture as a normal completion with no failure_id or events, and neither the shared
stream reader nor collection read a Messages report.

A successful call's message_stop now carries the request's failure report, as the terminal event of
a Responses keepalive stream and the last chunk of a Chat one do. A call that fails after the stream
opened leaves the handled exception in the request state, so capture records its typed failure and
per-call failure_id as it does when the call fails before the stream opens. StreamFailureReportReader
reads reports from Messages message_stop and error events, and collection merges a captured Messages
report into the episode as an observation, without changing the episode's selected failure or reward.

Signed-off-by: gwarmstrong <[email protected]>
@gwarmstrong

Copy link
Copy Markdown
Contributor Author

/ok to test 2daa69e

@nemo-pr-automation
nemo-pr-automation Bot requested review from a team December 3, 2026 19:11
@github-actions github-actions Bot added the sla:review-overdue Review response is over the one-business-day SLA label Dec 3, 2026

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:model Model servers, inference providers, and model adapters bug Something isn't working needs-review PR is ready for code review and waiting on a reviewer risk:high Autobot PR risk: high sla:review-overdue Review response is over the one-business-day SLA

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants