Repository navigation
fix(model): keep streaming /v1/messages calls open while they run - #7157
gwarmstrong wants to merge 2 commits into
Conversation
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]>
|
/ok to test bb91eba |
svcnvidia-nemo-ci
left a comment
There was a problem hiding this comment.
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 |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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)) |
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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_recordasfailure. The captured call keeps the typed event and itsfailure_id, as on the quick path. - Reader:
StreamFailureReportReaderreads reports from Messagesmessage_stopevents and fromerrorevents that carry anerrorobject. A report on any other Messages event is still omitted. - Merge:
merge_model_call_capture_into_recordalso reads capturedmessagescalls, as observations with nofailure_id.
Tests:
test_a_slow_messages_call_keeps_its_typed_failure_in_capture_and_merges_it_as_an_observationchecks the per-callfailure_idand events, and that the episode keeps its selected failure and reward.test_actual_stream_capture_survives_collection_and_storenow also runs Messages.test_the_reader_takes_messages_reports_only_from_the_events_that_end_the_streamcovers 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]>
|
/ok to test 2daa69e |
What does this PR do?
The default
/v1/messagesroute 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 onvllm_modeldecodes 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
errorevent:invalid_request_error, carrying the engine's message (the HTTP 400 it replaces).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:message_stop. A call that fails carries it on itserrorevent.failure_id, as it does when the call fails before the stream opens.StreamFailureReportReaderreads the report frommessage_stopanderrorevents. 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 wandbenvironment (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 expectederrorevent; 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 itsfailure_id; the episode keeps its own selected failure and reward.test_actual_stream_capture_survives_collection_and_storenow also runs Messages.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 touvran with uv 0.13.12.pytest responses_api_agents/claude_code_agent/tests: 342 passed.pre-commit run --fileson 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.CLAUDE_STREAM_IDLE_TIMEOUT_MS=3000000on the clientCanary 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:
message_stop. It printed the answer and exited 0.errorevent 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
/v1/messagescall that fails more than 15 s in now reports an Anthropicerrorevent inside a 200 stream, not an HTTP error status. Anthropic clients, the Claude Code CLI among them, handle both.message_stopor theerrorevent carries anemo_gym_failure_reportfield. Clients ignore it, as the CLI check above shows.pingevents, so the server cannot extend it. A turn longer than about 15 s + 30 × 15 s + 300 s = 765 s therefore also needsCLAUDE_STREAM_IDLE_TIMEOUT_MSraised on the client (canary 3 vs canary 4 above). This PR leaves that setting to each run's client environment.Checklist
messages()docstring describes the keepalive and where the failure report goes.)pre-commit run --all-files) (so CI lint/format checks pass). (Run on the changed files.)git commit -s) (so the DCO check passes).