mirror of
https://github.com/Niko1221/Strata.git
synced 2026-12-03 19:03:30 +07:00
[PR #4831] [Engine] /v1/responses: a request cancelled at the drain deadline gets 503 or response.failed, not 400 malformed #5201
Labels
No labels
needs-format
pull-request
No milestone
No project
No assignees
1 participant
Notifications
Due date
No due date set.
Dependencies
No dependencies set.
Reference
Niko1221/Strata#5201
Loading…
Add table
Add a link
Reference in a new issue
No description provided.
Delete branch "%!s()"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
📋 Pull Request Information
Original PR: https://github.com/Niko1221/Strata/pull/4831
Author: @gdevenyi
Created: 10/31/2026
Status: 🔄 Open
Base:
main← Head:api/responses-server-cancel📝 Commits (1)
47912dcResponses API: a request cancelled at the drain deadline gets 503 server_draining (non-streaming) or response.failed (streaming) instead of 400 "malformed (KeyError)" or a stream with no final event; a client that hung up is no longer logged as a malformed request📊 Changes
2 files changed (+140 additions, -1 deletions)
View changed files
📝
serve/server.py(+16 -0)📝
serve/test_responses.py(+124 -1)📄 Description
Problem and result
When a server stops and its drain deadline (
--shutdown-timeout) expires, it cancels the requests still running. On/v1/responsesa client that was still connected got a wrong answer. No user has reported this. I found it in an audit and reproduced it with a real server, a real SIGTERM and the OpenAI SDK, on the mock engine and on a real engine (see Validation).strata serveandstrata runtime startset this deadline to 30 s by default. Barepython -m serve.serversets none.invalid_request_error, "the request is malformed (KeyError: 'response')", and a traceback in the logserver_error, codeserver_draining,Retry-After: 1in_progressand empty outputresponse.output_text.deltaresponse.failed, statusfailed, codeserver_errorresponse.in_progressresponse.failed--api-monitor) showsdisconnecteddocs/DETAILS.mdpromises: "Streaming events are the official ones, in order, ending inresponse.completed,response.incompleteorresponse.failed." The OpenAI spec (ResponseFailedEvent) says: "An event that is emitted when a response fails." I found no primary source on server shutdown itself.Related discussion
None needed for scope: a small bug fix with no change to a default. My GitHub search found no thread that covers this. PR 2481 (print to
console_printaround these drain lines) and issue 4479 (same lifecycle area) are nearby, and neither is a fix.Approach
The check that skips the final event dates from when a cancel meant the client had left.
cancel_owned_requestslater reused the same cancel event for clients still connected. The non-streaming path then read the last delta as the final answer and raisedKeyError.Now a cancelled request raises before that read:
ServerStopping. Non-streaming answers with the same status, code andRetry-Afteras a request refused while draining. Streaming uses the existingresponse.failedpath.ClientGone.The stream uses code
server_errorbecauseResponseErrorCodein the spec is a closed list. The 503 does not return the partial text. I chose failure over a partial answer because no status in the spec means "the server stopped", and a cut-off answer should not look finished.A request that is not cancelled does not reach the new branch. No docs change: the
DETAILS.mdsentence above becomes true for this case.Validation
Revision: base
c62d5e3aplus commitf4226950. Linux, Python 3.12. Mock engine, and a real engine where marked.Passed:
python -m unittest serve.test_responses.ServerCancel: 7 tests pass, also on 5 repeat runs. They run the shutdown's own steps (begin_drain,wait_for_drain,cancel_owned_requests) and check the status, code,Retry-After, last event, log and monitor state.The same tests with
serve/server.pyfrom the base: 6 of 7 fail, with the "Before" results in the table. The seventh, a request that ends within the drain, passes both ways.python -m unittest serve.test_server serve.test_responses serve.test_anthropic_base_url serve.test_chat_tool_results serve.test_context_overflow serve.test_images: 444 tests in 131 s, failures=1 (listed below), skipped=1.Real server, base and branch:
python -m serve.server --engine mock --script <long text> --script-delay 0.05 --shutdown-timeout 1. A local script, not committed, sends one request with OpenAI SDK 3.42.0 and sends SIGTERM 1 s later. Six shutdowns on each side, server exit code 8 on all of them.max_retries=0: non-streaming givesBadRequestError400 with theKeyErrormessage. Forcreate(stream=True)and theresponses.streamhelper, the last event isResponseTextDeltaEvent. Across the six shutdowns the log has 2 "malformed" lines with tracebacks, one for each non-streaming request.max_retries=0: non-streaming givesInternalServerError503 "this instance is draining and cancelled this request; retry against the next instance". Forcreate(stream=True)and the helper, the last event isresponse.failed, statusfailed, codeserver_error. Across the six shutdowns the log has no "malformed" line and no traceback.Normal requests, base against branch, with a local script, not committed: plain, effort none,
max_output_tokens, tool call,text.formatand a bad request, each streaming and non-streaming, 12 in all. Status, headers and body are identical once ids, timestamps, timings and theDateheader are normalized.Real engine, base and branch: RTX 5080 16 GB, engine 0.1.55 from release v0.2.9, Qwen3.8 IQ3_S, context 65536, base
c62d5e3a, branchf4226950.serve/server.py --shutdown-timeout N, a new server for each stop, one request at a time on/v1/responses, OpenAI SDK 3.42.0 withmax_retries=0unless noted, reasoning effort none, a real SIGTERM. Every stop in the table exited with code 8. Two runs spoiled by my script (a signal sent before the server had taken the request, and a run that reached a base server my script had left running) were repeated and are not counted. Mid-answer: N=2, SIGTERM 3 s after the first delta (stream) or 6 s after the send (whole); the engine had made about 500 to 890 tokens. Before the first token: N=1, a prompt of about 9000 words, and the engine log says 0 tokens.BadRequestError400invalid_request_error, "the request is malformed (KeyError: 'response')", noRetry-After, one "malformed" line and one traceback in the log eachInternalServerError503server_error, codeserver_draining,Retry-After: 1, no "malformed" line, no tracebackresponse.output_text.delta, then a clean end of stream with no errorresponse.failed, statusfailed, codeserver_errorresponses.streamhelper, mid-answerresponse.output_text.deltaresponse.failed.get_final_response()raises the sameRuntimeErroron both sidesin_progress, empty outputresponse.in_progressresponse.created,response.in_progress,response.failedmax_retries=2APIConnectionError, 4.8 s after the SIGTERMReal engine, a request that ends within the drain: N=60, SIGTERM during the request, exit code 0. Status
completedwith the full answer on both sides, stream and whole (base 1 whole and 2 stream, branch 1 of each).Real engine, the client hangs up on a whole request, no drain, monitor on: 3 hang-ups on one server, each 5 s after the send. Base: 3 "malformed" lines with tracebacks, and the monitor shows state
error, HTTP 400, for all 3. Branch: no such line, no traceback, and the monitor shows statedisconnectedfor all 3. On both sides the next request on that server completed.Failed:
serve.test_server.GpuChoice.test_hip_ordinal(AssertionError: '0,1' != '1,0'). It fails the same way on an extract ofc62d5e3a, so this change did not cause it.Not run:
On real hardware:
--parallelabove 1, or a request still queued at the deadline._responses_prepare(it needs an image, and this config has no image encoder), and a cancel that lands just after the engine finished. I did not patch the server to force either.strata serveandstrata runtime startwith their 30 s default, and a stop by Ctrl+C. I startedserve/server.pydirectly and sent SIGTERM with deadlines of 1, 2 and 60 s.Elsewhere:
Limits
max_retries=2, the non-streaming client retried the 503 and ended withAPIConnectionErrorafter about 4 s, because the server had stopped and no other instance was running.responses.stream(...)helper now seesresponse.failedwhile iterating, butget_final_response()still raisesRuntimeError"Didn't receive aresponse.completedevent."svc.draining. A client that hangs up during a drain gets a 503 that nobody reads, and the monitor showserror, notdisconnected. There is no "malformed" line and no traceback. I tested this non-streaming only. From reading the code, a stream takes the same path and writesresponse.failedto the closed socket._responses_prepare(an image still being prepared) still closes the connection with no answer. This change does not touch that path./v1/chat/completionsand/v1/messagesare unchanged.🤖 Generated with Claude Code
https://claude.ai/code/session_01W53iURzvDQMjnYemag8uvv
🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.