Repository navigation
feat(model): keep a streamed Messages request alive with ping events - #6903
Conversation
The model server answers a streamed /v1/messages request only when the whole generation has returned, so the client receives no byte until then. Claude Code 2.1.312 gives a request up after about 360 seconds without a response byte and sends it again. API_TIMEOUT_MS does not lengthen that wait. A longer generation therefore runs twice, and the answer of the first run is lost. A stream that is open and then silent is given up after 300 seconds. A stream that carries a ping event every 15 seconds is kept for as long as the events come. stream_keepalive_s now applies to /v1/messages as it does to /v1/responses. A call that is still running after one interval opens the stream with a ping event and sends another at every interval. The events of the message follow unchanged. A call that ends within the first interval is served as before, so its failure keeps its HTTP status. A call that fails after the stream has opened ends it with an error event. Its type is invalid_request_error for a refusal that the server propagates and for another 4xx status, rate_limit_error for 429, and api_error otherwise. Claude Code answers an error event that precedes message_start by sending the request once more with "stream": false, and that request gets the HTTP status. No event can hold that request open: Claude Code gives it up after about 300 seconds without a response. A client that leaves cancels the backend call, in the first interval and after the stream has opened, as for /v1/responses. A server whose response ids come from an upstream Responses API refuses the setting at startup, as before, so it holds no Messages stream open either. Model-call capture does not count a ping event as the first token. The checkpoint gate of a policy model server does not take a ping event for the start of the answer. As after the lifecycle events of a /v1/responses stream, a checkpoint holds such a call instead of waiting for it, and the ledger row of the call is published when the message starts. Signed-off-by: alexandery <[email protected]> Co-Authored-By: Claude Fable 5.2 <[email protected]>
|
/ok to test da13f6f |
svcnvidia-nemo-ci
left a comment
There was a problem hiding this comment.
SHIP WITH CARE.
I reviewed all 10 changed files and the connected callers, capture paths and checkpoint lifecycle with three delegated reviewers. I found one moderate RISK: late Messages failures lose structured failure attribution. The client still receives an error event; this is not a false-success finding.
Validation: I relied on successful head checks Lint check, Unit tests / Test, Unit tests / Combined core coverage and Unit tests / Server suite. Local probes ran in 766267172432.dkr.ecr.us-east-1.amazonaws.com/gym:ba3eeeb0a60df9a7cd3bb9d2c1f36cabb0a493b5, the default-branch CI image because no head image was found. Base/head failure probes reproduced the finding. Anthropic SDK framing and content preservation passed, as did checkpoint-to-ledger publication, six disconnect cases and four socket-send failure cleanup cases. I did not rerun the CI suites or run a real minutes-long Claude Code request.
CI is not entirely green: Harness conformance (non-blocking) failed, and Autobot PR risk #6903 reports risk:unknown: label change failed. I have not attributed the conformance failures to this change.
Review generated by codex. This was a full review. Request a full review with /review reset=true.
| response = await pending | ||
| except Exception as exc: | ||
| # The stream is already open, so only an event can report the failure. | ||
| yield _ANTHROPIC_CONVERTER.anthropic_error_to_sse(*self._streamed_messages_failure(exc)) |
There was a problem hiding this comment.
RISK: Preserve structured failure evidence after the first ping.
Could this retain the caught exception's report for capture and the terminal stream? This catch converts the exception to text and returns normally. The HTTP headers have already gone out, and _CaptureMiddleware no longer reaches its exception-recording path, which supplies failure=exc.
I reproduced this through the Messages route with capture and the production exception middleware. Running /workspace/review-probes/messages-lifecycle-1/capture_probe.py with PYTHONPATH set to each admitted tree showed:
- Base, or head before the first interval: the saved report selects
probe-engine-unavailableand contains that event. - Head after a ping:
error_category=upstream_error, butfailure_id=nullandevents=[]. Neither the header nor terminal event carries the report.
This affects long streamed Messages calls with keepalive enabled. If the backend already called observe_failure, its event can survive as an observation, but its selected failure ID is still lost. Recovered retry observations also disappear from the wire after headers are committed.
Please preserve the original selected failure and cause chain in capture, and carry the bounded request report on the terminal event, following the Responses keepalive path. Complete that transport change with Messages terminal-event support in StreamFailureReportReader and the rollout reader, rather than adding an unread extension.
Acceptance: delayed typed failures retain their original IDs, kind and causes with and without an earlier observe_failure; delayed successful calls retain retry observations. Keep HTTP 200 plus Anthropic error behavior after a ping, fast-failure HTTP statuses, and ping-only liveness unchanged.
There was a problem hiding this comment.
I reproduced this: a typed failure that the backend raised after the first ping reached the client with no failure report in the header or on the error event, and a failure that a call observed before it answered was not on the wire either.
Commit 2477ee8 of this pull request puts the request's bounded report on the terminal event of a stream that ping events opened (error or message_stop), in nemo_gym_failure_report as on the Responses route, and StreamFailureReportReader and the rollout reader now read it for Messages. test_a_keepalive_messages_stream_reports_late_failures_on_its_terminal_event checks the selected failure and the observed failure on the wire, and the messages cases of test_actual_stream_capture_survives_collection_and_store check that both reach the rollout row through capture.
The observation about the capture record is correct, and this pull request does not change it: for the same late failures, the record of a /v1/responses stream under stream_keepalive_s and of a streamed chat completion equals the Messages record (status_code 200, upstream_error, observed events only), and test_actual_stream_capture_survives_collection_and_store asserts upstream_error for both. Keeping the original category is therefore a change to capture for all three dialects, which this pull request does not make. HTTP 200 with the Anthropic error body, the HTTP status of a call that fails in the first interval and the ping events are unchanged.
A streamed /v1/messages call that outlasts one interval of stream_keepalive_s opens its stream with a ping event, so its HTTP headers go out before the backend call ends. The failure that ended such a call, and the failures that the call observed, were then not reported to the client: the failure header was already sent, and the stream carried no failure report. A keepalive /v1/responses stream and a streamed chat completion carry the report on their terminal event in that case. The terminal event of a Messages stream that ping events opened now carries the request's failure report in the same field, nemo_gym_failure_report: the error event of a call that failed, and message_stop of a call that answered. The report selects the failure that ended the call and holds the failures that the call observed, such as an attempt that a retry replaced. A request with nothing to report sends its events unchanged. StreamFailureReportReader accepts a report on these two event types. Rollout collection reads the report from a captured Messages stream as it does for the two other dialects, so the events reach the rollout's row. The function that adds the report to an event takes the event types from the reader, so they are stated once. Signed-off-by: alexandery <[email protected]> Co-Authored-By: Claude Fable 5.2 <[email protected]>
|
/ok to test 2477ee8 |
|
/review reset=true |
svcnvidia-nemo-ci
left a comment
There was a problem hiding this comment.
SHIP WITH CARE.
I reviewed all 14 changed files and their connected callers with three delegated reviewers. One moderate RISK from review 6096140631 is partly fixed: terminal Messages events now carry failure reports and collection recovers their events, but the saved model-call report still loses the selected failure and its causes. I found no additional material defect.
Validation: I relied on successful head checks Lint check, Unit tests / Test, Unit tests / Combined core coverage and Unit tests / Server suite. Changed server tests and Session routing end-to-end were skipped, not passed. Harness conformance (non-blocking) failed in the miniswe_sandboxed and openclaw probes; I have not attributed those failures to this diff.
CPU probes ran in 766267172432.dkr.ecr.us-east-1.amazonaws.com/gym:ba3eeeb0a60df9a7cd3bb9d2c1f36cabb0a493b5, the default-branch CI image because no head container build was found. Differential failure probes reproduced the remaining finding. Anthropic SDK content/error handling, six disconnect cases, four socket-send cleanup cases, checkpoint/publication controls, ping-excluding TTFT and 580 fragmented terminal-report reader cases passed. Injected publication failures blocked answer delivery as expected. I did not rerun CI suites or run a minutes-long live Claude Code request.
The prior-review commit is an ancestor of this head and was compared directly. This was a full RESET review.
Review generated by codex. This was a full review. Request a full review with /review reset=true.
| except Exception as exc: | ||
| # The stream is already open, so only an event can report the failure. | ||
| error = _ANTHROPIC_CONVERTER.anthropic_error_to_sse(*self._streamed_messages_failure(exc)) | ||
| yield _with_stream_report(error, _stream_report(failure_log, exc)) |
There was a problem hiding this comment.
RISK: Preserve the caught failure in the saved model-call report too.
Could this also retain exc's full report for capture before bounding it for the terminal event? The wire portion of prior finding 4725721843 is fixed, but this catch still returns normally. Capture then calls _record without the exception, and rebuilds the call's report from observations only.
I reproduced this through the real Messages route with automatic capture and production exception middleware:
python /workspace/review-probes/run_review.py /workspace/review/source /workspace/review-probes/leader-reset-1/per_call_report_probe.py
Before the first interval, the captured call selects final and contains [cause, final]. After a ping, it has failure_id=null, events={}, although the terminal event correctly selects final and carries the cause chain. A prior observe_failure can retain events but still does not restore the call's selection.
The rollout reader recovers small terminal reports as episode observations; it does not repair ng_model_call_capture.calls[*].failure_report. Saved calls normally omit raw payloads. A separate oversized-report probe also showed that above the 4096-byte wire bound, only omitted=true survives, while base retains the full report locally. This affects causal diagnostics and attribution for long streamed Messages calls, not error delivery or scoring.
Please carry the full selected report through request-local capture state into the finalized exchange, separately from the bounded wire extension. Adding it only as observations would still lose selection. Preserve HTTP 200 plus Anthropic error after a ping, fast-failure HTTP statuses, recovered-success observations and the enclosing episode's selection policy.
Acceptance: assert original IDs, failure kind and cause links in the raw capture, typed call and collected call for delayed failures with and without prior observations, including a report over the wire bound. Keep the existing terminal-event assertions.
There was a problem hiding this comment.
This is the saved-record part of the earlier finding, and it stays out of this pull request. On main, a /v1/responses stream under stream_keepalive_s and a streamed chat completion save the same record for a call that fails after their first keepalive event, and test_actual_stream_capture_survives_collection_and_store asserts it for both. Keeping the caught failure in the saved record is therefore a change of the capture for all three routes, and this pull request would then change two routes that it does not otherwise touch. What it adds for the Messages route is what the two other routes have: the request's failure report on the terminal event, which rollout collection reads into the rollout's row. If the maintainers want the saved record changed, that fits a pull request of its own for the three routes.
…tatus A streamed Messages request that fails after `ping` events ends with an `error` event. Its type is meant to be the one that Anthropic's API gives the HTTP status that the client would have seen before the stream opened. The type was `rate_limit_error` for 429, `api_error` from 500 and `invalid_request_error` for every other status, so a late 401, 402, 403, 404 or 413 was reported as an invalid request and a late 529 as `api_error`. The type now comes from a table of the statuses for which Anthropic's API has a type of its own: `authentication_error`, `billing_error`, `permission_error`, `not_found_error`, `request_too_large`, `rate_limit_error` and `overloaded_error`. A server that hides upstream statuses still reports `api_error`, and a refusal still reports `invalid_request_error`. Signed-off-by: alexandery <[email protected]> Co-Authored-By: Claude Fable 5.2 <[email protected]>
The docstring of test_messages_ping_events_are_liveness_not_the_answer said that the call's ledger row is published when the first event of the message reaches the gate. The test builds its participant without a ledger: it asserts that the gate's publication step runs at that event, before the event leaves, and it cannot assert a row. The docstring now says that the gate publishes the call. The two tests before it assert the committed row with a ledger. Signed-off-by: alexandery <[email protected]> Co-Authored-By: Claude Fable 5.2 <[email protected]>
|
/ok to test 9b8ede5 |
|
/review reset=true |
main changed the imports of nemo_gym/models/model_call_capture.py beside the line that this branch changes. The merge keeps both: the names that main added and StreamFailureReportReader. Signed-off-by: alexandery <[email protected]> Co-Authored-By: Claude Fable 5.2 <[email protected]>
|
/ok to test 0fa0b9e |
|
Does this workload need to stay on Claude Code 2.1.312? If the version is flexible, I’d favor upgrading to 2.1.335 and setting I tested both versions against a local Is there a version pin or a proxy idle timeout in the target deployment that would still require server-side pings? |
|
Yes, the version is pinned. The pairing that needs this reproduces a reference system that installs Claude Code 2.1.312 today, and its runs are compared with that system's, so the client stays at 2.1.312 until the reference moves. Your measurement of 2.1.312 agrees with ours for A client timeout also moves the limit and does not remove it. A model server answers a streamed On the HTTP error handling: the setting stays opt-in, so a model server without If you want |
main changed six files that this branch also changes, and Git merged each of them without a conflict. In nemo_gym/models/base_responses_api_model.py main imports chat_stream_error_message on the lines below the import that this branch extends with ANTHROPIC_PING_SSE. The merge keeps both. The lines that this branch adds and removes against main are the same as before the merge. Signed-off-by: alexandery <[email protected]> Co-Authored-By: Claude Fable 5.2 <[email protected]>
|
/ok to test 3f23d5d |
A streamed /v1/messages request with stream_keepalive_s has sent its HTTP status 200 before its backend call ends, so a later failure reaches the client as an error event. Model-call capture saved every such call as upstream_error with no selected failure. A 422 or a 429 of the backend then counted as a server fault, a timeout lost its category, and a typed failure lost its id and its causes, while the same failure before the first ping event was saved with them. note_stream_failure stores the failure in the request state, where the capture middleware already reads what a route notes. For a call with a noted failure the middleware takes the category from the expression that it uses for a failure that a route raises (_classify_failure), passes the failure to the saved failure report, and saves the HTTP status of the backend as upstream_status_code where the adapter noted none. status_code stays 200, the status that the client received. The status of an HTTPException is this server's own and is not saved as the backend's. Only the Messages route notes its failure. The keepalive streams of /v1/responses and /v1/chat/completions are saved as before. The tests send the same failure before and after the first keepalive event through the middlewares that run_webserver installs, for a 422, a 429, the error that the model client raises with its observed attempt as cause, a timeout and a typed failure. They compare the category, the server fault, the status of the backend and the failure events of the saved rows, and they state which failure the late call selects. One test covers a late HTTPException, and one reads a typed failure back from the saved row and checks that the episode keeps its own selected failure. Signed-off-by: alexandery <[email protected]> Co-Authored-By: Claude Fable 5.2 <[email protected]>
|
/ok to test 0d83184 |
|
/review reset=true |
|
Thanks for confirming the reference system pins Claude Code to 2.1.312. That answers my timeout question. I’m comfortable with opt-in server-side pings for streamed Good catch on the saved call. The fix in |
|
Thank you. The same capture behavior for #6904 and #6905 are approved and contain this branch. Could you approve this one too, so that the three can merge in order? |
svcnvidia-nemo-ci
left a comment
There was a problem hiding this comment.
LGTM
Review generated by codex. This was a full review. Request a full review with /review reset=true.
…ed itself as local_status_code A route that reports a failure in the terminal event of a stream has sent HTTP status 200 before, so the saved call has status_code 200. For a failure that carries the status of the backend, capture saves that status as upstream_status_code. For an HTTPException, whose status is the model server's own, it saved no status. Rollout recovery reads the saved statuses to decide whether a call is a server fault (is_server_fault_call). An HTTPException with 504 has the category timeout, which is no server-fault category, so the same failure was a server fault when the route raised it before the stream opened and none after. A by_status_code rule of the failure classification could not match such a call either. Capture saves the status of an HTTPException that a route noted with note_stream_failure as local_status_code. The raw capture record holds the key only where such a status was saved. ModelCallRecord and the response metadata of a trajectory's model call carry the field, and the trajectory builder copies it. captured_model_calls and the collector of gym eval resubmit --recover project it, and is_server_fault_call classifies it as it classifies status_code and upstream_status_code. The tests of the recovery predicate cover a call with a local 504, and the collector's projection of that call. Signed-off-by: alexandery <[email protected]> Co-Authored-By: Claude Fable 5.2 <[email protected]>
…on /v1/messages The test of an HTTPException that the Messages route raises after a ping event runs for a 504 and for a 409. It expects the category of the same failure before the stream opens, and equal answers of is_server_fault_call and is_infrastructure_agent_timeout for the two calls, also under a by_status_code rule for the status. The late call holds the status as local_status_code, in the rollout row and in the trajectory's model call, and no upstream_status_code. The capture page names local_status_code. Signed-off-by: alexandery <[email protected]> Co-Authored-By: Claude Fable 5.2 <[email protected]>
…t holds The test of the ping events of a Messages stream sent its call through the gate alone. There the gate's publish() has no capture context and writes nothing, so the test could not tell whether the deferred ledger row of the call is written. The call now goes through the gate and the model server's capture middleware with a file ledger, as the test of the Responses lifecycle events does. _staged_call takes the events that open the stream, the first event of the answer and the route of the request. The test expects no row while the checkpoint holds the call. It expects one committed row once the gate has published the call, when the client has received only the headers and the ping event. Signed-off-by: alexandery <[email protected]> Co-Authored-By: Claude Fable 5.2 <[email protected]>
|
/ok to test 9b1db2a |
|
/review reset=true |
svcnvidia-nemo-ci
left a comment
There was a problem hiding this comment.
LGTM
Review generated by codex. This was a full review. Request a full review with /review reset=true.
yaoyu-33
left a comment
There was a problem hiding this comment.
Approved. I’m comfortable shipping opt-in pings for the pinned Claude Code version. One accepted limitation remains: if the model returns malformed tool arguments after the first ping, the stream can close without a terminal error event.
|
🔄 Merge queue validation started! You can track the progress here: https://github.com/NVIDIA-NeMo/Gym/actions/runs/47279505458 |
main holds the keepalive of a streamed /v1/messages request (#6903). That change and this branch made the same capture and recovery changes, so the library files take main's lines. After the merge this branch differs from main in nemo_gym only by the two calls of note_stream_failure on /v1/responses and /v1/chat/completions. Three files held conflicts. tests/unit_tests/models/test_stream_failure_capture.py keeps one module for the three routes: this branch's helpers and cases, with the /v1/messages request added, so that every case of main's module runs and the Messages route also gets the cases of a propagated refusal, of a model server that does not propagate an HTTP error and of a status that the adapter noted. The assertion of test_streamed_capture_reports.py expects the selected failure on /v1/messages and /v1/chat/completions and none on /v1/responses. The capture page states the saved record once for the three routes and the key local_status_code once. Signed-off-by: alexandery <[email protected]> Co-Authored-By: Claude Fable 5.2 <[email protected]>
What does this PR do?
A model server answers a streamed
/v1/messagesrequest only when the whole generation has returned, so the client receives no byte until then. Claude Code 2.1.312 gives a request up after about 360 seconds without a response byte and sends it again, andAPI_TIMEOUT_MSdoes not lengthen that wait. A longer generation therefore runs twice, and the answer of the first run is lost. This PR appliesstream_keepalive_s, which already holds a/v1/responsesstream open, to/v1/messages. It serves a Claude Code session behind a model server whose model takes minutes for one answer.What changes on a server that sets
stream_keepalive_s:/v1/messagescall that still runs after one interval opens the stream with apingevent and sends another at every interval. The events of the message follow.errorevent. Its type is Anthropic's own type for the status 401, 402, 403, 404, 413, 429 or 529,invalid_request_errorfor a refusal that the server propagates and for another 4xx status, andapi_errorotherwise.message_stoporerror, also carries the request's failure report innemo_gym_failure_reportwhen the request has one, as on a/v1/responsesstream. Rollout collection reads it from the captured stream into the rollout's row.pingevent with the error category that the same failure has before the stream opens and, when the failure carries one, with the HTTP status of the backend, beside the status 200 that the client received. The saved failure report selects the failure's Gym failure event, when it has one, with its causes. The status of anHTTPException, which is the model server's own, is saved as the new keylocal_status_code, andis_server_fault_callreads it as it readsstatus_codeandupstream_status_code./v1/responses.pingevent is not the start of the answer: model-call capture does not count it as the first token, and a checkpoint of a policy model server holds such a call instead of waiting for it, as it does after the lifecycle events of a/v1/responsesstream.What does not change: without the setting, and for a request that is not streamed, the server sends nothing until the response is complete. A server whose response ids come from an upstream Responses API still refuses the setting at startup.
Validation
pytest tests/unit_tests/models: 2762 passed, wheremainhas 2726.pytest responses_api_models/vllm_model: 1313 passed, as atmain.pytest tests/unit_tests/core: 680 passed.pytest tests/unit_tests/rollouts: 3093 passed.pytest tests/unit_tests/eval/recovery: 1521 passed.pytest tests/unit_tests/trajectory: 662 passed.pytest tests/unit_tests/core/test_streamed_failure_reports.py tests/unit_tests/rollouts/test_streamed_capture_reports.py: 33 passed, wheremainhas 29, and the four new cases fail without the code that adds the failure report.ruff checkandruff format --check(ruff 0.9.9) on the changed Python files: no finding.pre-commit run --all-fileswas not run. Its box below is unticked.tests/unit_tests/modelsoutsidetest_stream_failure_capture.pywere also run withbase_responses_api_model.py,_checkpoint.pyandmodel_call_capture.pyofmain. Twenty-three fail. One does not end, because the route waits for the blocked backend, and was stopped. The other four assert what stays: a call within the first interval sends nopingevent and keeps its HTTP status, a request that is not streamed gets no event, and a cancellation in the first interval reaches the backend.tests/unit_tests/models/test_stream_failure_capture.pyfail withmodel_call_capture.pyandbase_responses_api_model.pyof the commit before the fix. The case oftest_streamed_capture_reports.pywith a failure on/v1/messagesfails there too.test_a_late_http_exception_keeps_its_category_without_a_status_of_the_backendlets the Messages route raise a 504 and a 409 before and after the firstpingevent. It expects equal answers ofis_server_fault_callandis_infrastructure_agent_timeoutfor the two calls, also under aby_status_coderule, and the status inlocal_status_codeof the late call. Both cases fail with the six library files of the commit before the key: the late 504 is no server fault there, and the rule does not match the late 409.test_messages_ping_events_are_liveness_not_the_answersends its call through the capture middleware with a file ledger. It expects no ledger row while the checkpoint holds the call and one committed row before the first event of the message leaves. It fails when the gate does not write the deferred row.mainfor the two other streams pass unchanged with the code of this branch: the four filestest_chat_completions_streaming.py,test_responses_api_model_streaming.py,test_streamed_failure_reports.pyandtest_streamed_capture_reports.pyas they are atmain, 406 passed.Rollouts
One task ran with a real model at
mainand at an earlier head of #6905, which is stacked on this one and held thepingevents of this PR without the failure report. Both rollouts setstream_keepalive_s: 1:vllm_model,claude_code_agentwith Claude Code 2.1.312,single_agent_turn_legacyand a Docker sandbox ofubuntu:24.04. The model is an OpenAI model behind an OpenAI-compatible endpoint. Each rollout made two streamed/v1/messagescalls of 1.7 to 2.7 seconds.mainneither stream holds apingevent.pingevents and the second holds one, beforemessage_start. The six events of the message that follow are the same as atmain.healthy, as atmain.pingevents.No rollout held a call of minutes, a call that failed after its stream had opened, or a last event with a failure report. Claude Code 2.1.312 was run against a stand-in endpoint without a model whose last event holds the field. It returned the answer of a stream whose
message_stopholds the field, and after anerrorevent with the field it sent the request again without streaming. The figure of 360 seconds comes from a separate measurement with Claude Code 2.1.312 against a stand-in endpoint, which is not part of the rollouts above.Compatibility and benchmark impact
No default changes apart from the new key below. A server that already sets
stream_keepalive_snow also holds a streamed/v1/messagescall open. A client of that route then receives a failure after the first interval as anerrorevent of a stream with HTTP status 200. The last event of such a stream can hold the additional fieldnemo_gym_failure_report.The saved call gains one optional key,
local_status_code, and no existing value changes. The raw capture record holds the key only for anHTTPExceptionthat a route reported in a stream.ModelCallRecordand the response metadata of a trajectory's model call hold it as null otherwise. No model server in the repository raises anHTTPExceptionwith 504 or 408 today, so the key closes a gap in the contract of the saved call and not an observed failure: without it, a 504 that a route raises is a server-side fault before the firstpingevent and none after it.Checklist
pre-commit run --all-files) (so CI lint/format checks pass).git commit -s) (so the DCO check passes).🤖 Generated with Claude Code