[PR #4831] [Engine] /v1/responses: a request cancelled at the drain deadline gets 503 or response.failed, not 400 malformed #5201

Open
opened 2026-11-07 16:33:25 +07:00 by bsakaguchi · 0 comments
Owner

📋 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)

  • 47912dc Responses 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/responses a 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 serve and strata runtime start set this deadline to 30 s by default. Bare python -m serve.server sets none.

Case Before After
Non-streaming, cancelled mid-answer 400 invalid_request_error, "the request is malformed (KeyError: 'response')", and a traceback in the log 503 server_error, code server_draining, Retry-After: 1
Non-streaming, cancelled before the first token 200 with status in_progress and empty output The same 503
Streaming, cancelled mid-answer The stream ends on response.output_text.delta The stream ends on response.failed, status failed, code server_error
Streaming, cancelled before the first token The stream ends on response.in_progress The stream ends on response.failed
Non-streaming, the client hung up (no drain) "400 malformed request" and a traceback in the log, though nobody receives the answer No such log line. The monitor (--api-monitor) shows disconnected

docs/DETAILS.md promises: "Streaming events are the official ones, in order, ending in response.completed, response.incomplete or response.failed." The OpenAI spec (ResponseFailedEvent) says: "An event that is emitted when a response fails." I found no primary source on server shutdown itself.

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_print around 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_requests later reused the same cancel event for clients still connected. The non-streaming path then read the last delta as the final answer and raised KeyError.

Now a cancelled request raises before that read:

  • If the server is draining, it raises a small new ServerStopping. Non-streaming answers with the same status, code and Retry-After as a request refused while draining. Streaming uses the existing response.failed path.
  • Otherwise the client has left, and it raises the existing ClientGone.

The stream uses code server_error because ResponseErrorCode in 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.md sentence above becomes true for this case.

Validation

Revision: base c62d5e3a plus commit f4226950. 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.py from 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.

    • Base, max_retries=0: non-streaming gives BadRequestError 400 with the KeyError message. For create(stream=True) and the responses.stream helper, the last event is ResponseTextDeltaEvent. Across the six shutdowns the log has 2 "malformed" lines with tracebacks, one for each non-streaming request.
    • Branch, max_retries=0: non-streaming gives InternalServerError 503 "this instance is draining and cancelled this request; retry against the next instance". For create(stream=True) and the helper, the last event is response.failed, status failed, code server_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.format and a bad request, each streaming and non-streaming, 12 in all. Status, headers and body are identical once ids, timestamps, timings and the Date header 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, branch f4226950. 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 with max_retries=0 unless 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.

    Case Base Branch
    Whole, mid-answer 3 of 3: BadRequestError 400 invalid_request_error, "the request is malformed (KeyError: 'response')", no Retry-After, one "malformed" line and one traceback in the log each 3 of 3: InternalServerError 503 server_error, code server_draining, Retry-After: 1, no "malformed" line, no traceback
    Stream, mid-answer 3 of 3: last event response.output_text.delta, then a clean end of stream with no error 3 of 3: last event response.failed, status failed, code server_error
    responses.stream helper, mid-answer 2 of 2: last event response.output_text.delta 2 of 2: last event response.failed. get_final_response() raises the same RuntimeError on both sides
    Whole, before the first token 3 of 3: 200, status in_progress, empty output 3 of 3: the same 503 as above
    Stream, before the first token 3 of 3: last event response.in_progress 3 of 3: response.created, response.in_progress, response.failed
    Whole, mid-answer, default max_retries=2 1 run: 400, not retried 1 run: APIConnectionError, 4.8 s after the SIGTERM
  • Real engine, a request that ends within the drain: N=60, SIGTERM during the request, exit code 0. Status completed with 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 state disconnected for 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 of c62d5e3a, so this change did not cause it.

Not run:

On real hardware:

  • A client that hangs up during a drain, and a streaming client that hangs up with no drain. The hang-ups I ran were whole requests with no drain.
  • Reasoning on. Every real run used effort none, so no stop landed during thinking.
  • Several requests at once: --parallel above 1, or a request still queued at the deadline.
  • A drain cancel during _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.
  • A restart with a next instance for the client to retry against.
  • strata serve and strata runtime start with their 30 s default, and a stop by Ctrl+C. I started serve/server.py directly and sent SIGTERM with deadlines of 1, 2 and 60 s.
  • Other models, other engines and other cards.

Elsewhere:

  • Windows and macOS.
  • CUDA, HIP, SYCL and Metal builds. This change is Python only.
  • Codex and other clients. I tried only the OpenAI Python SDK.

Limits

  • The client's call still fails, because the server is stopping. What changes is the error. No restart test stands behind "retry against the next instance".
  • With the SDK's default max_retries=2, the non-streaming client retried the 503 and ended with APIConnectionError after about 4 s, because the server had stopped and no other instance was running.
  • The SDK's responses.stream(...) helper now sees response.failed while iterating, but get_final_response() still raises RuntimeError "Didn't receive a response.completed event."
  • The choice between the two cases rests on svc.draining. A client that hangs up during a drain gets a 503 that nobody reads, and the monitor shows error, not disconnected. 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 writes response.failed to the closed socket.
  • From reading the code, not run: a drain cancel during _responses_prepare (an image still being prepared) still closes the connection with no answer. This change does not touch that path.
  • From reading the code, not run: a cancel that lands just after the engine finished still counts as cancelled, as it did before.
  • /v1/chat/completions and /v1/messages are 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.

## 📋 Pull Request Information **Original PR:** https://github.com/Niko1221/Strata/pull/4831 **Author:** [@gdevenyi](https://github.com/gdevenyi) **Created:** 10/31/2026 **Status:** 🔄 Open **Base:** `main` ← **Head:** `api/responses-server-cancel` --- ### 📝 Commits (1) - [`47912dc`](https://github.com/Niko1221/Strata/commit/47912dca871ee718df7d7c24e28b3ec1d46f3ff9) Responses 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) <details> <summary>View changed files</summary> 📝 `serve/server.py` (+16 -0) 📝 `serve/test_responses.py` (+124 -1) </details> ### 📄 Description ## Problem and result When a server stops and its drain deadline (`--shutdown-timeout`) expires, it cancels the requests still running. On `/v1/responses` a 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 serve` and `strata runtime start` set this deadline to 30 s by default. Bare `python -m serve.server` sets none. | Case | Before | After | |---|---|---| | Non-streaming, cancelled mid-answer | 400 `invalid_request_error`, "the request is malformed (KeyError: 'response')", and a traceback in the log | 503 `server_error`, code `server_draining`, `Retry-After: 1` | | Non-streaming, cancelled before the first token | 200 with status `in_progress` and empty output | The same 503 | | Streaming, cancelled mid-answer | The stream ends on `response.output_text.delta` | The stream ends on `response.failed`, status `failed`, code `server_error` | | Streaming, cancelled before the first token | The stream ends on `response.in_progress` | The stream ends on `response.failed` | | Non-streaming, the client hung up (no drain) | "400 malformed request" and a traceback in the log, though nobody receives the answer | No such log line. The monitor (`--api-monitor`) shows `disconnected` | `docs/DETAILS.md` promises: "Streaming events are the official ones, in order, ending in `response.completed`, `response.incomplete` or `response.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_print` around 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_requests` later reused the same cancel event for clients still connected. The non-streaming path then read the last delta as the final answer and raised `KeyError`. Now a cancelled request raises before that read: - If the server is draining, it raises a small new `ServerStopping`. Non-streaming answers with the same status, code and `Retry-After` as a request refused while draining. Streaming uses the existing `response.failed` path. - Otherwise the client has left, and it raises the existing `ClientGone`. The stream uses code `server_error` because `ResponseErrorCode` in 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.md` sentence above becomes true for this case. ## Validation Revision: base c62d5e3a plus commit f4226950. 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.py` from 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. - Base, `max_retries=0`: non-streaming gives `BadRequestError` 400 with the `KeyError` message. For `create(stream=True)` and the `responses.stream` helper, the last event is `ResponseTextDeltaEvent`. Across the six shutdowns the log has 2 "malformed" lines with tracebacks, one for each non-streaming request. - Branch, `max_retries=0`: non-streaming gives `InternalServerError` 503 "this instance is draining and cancelled this request; retry against the next instance". For `create(stream=True)` and the helper, the last event is `response.failed`, status `failed`, code `server_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.format` and a bad request, each streaming and non-streaming, 12 in all. Status, headers and body are identical once ids, timestamps, timings and the `Date` header 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, branch f4226950. `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 with `max_retries=0` unless 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. | Case | Base | Branch | |---|---|---| | Whole, mid-answer | 3 of 3: `BadRequestError` 400 `invalid_request_error`, "the request is malformed (KeyError: 'response')", no `Retry-After`, one "malformed" line and one traceback in the log each | 3 of 3: `InternalServerError` 503 `server_error`, code `server_draining`, `Retry-After: 1`, no "malformed" line, no traceback | | Stream, mid-answer | 3 of 3: last event `response.output_text.delta`, then a clean end of stream with no error | 3 of 3: last event `response.failed`, status `failed`, code `server_error` | | `responses.stream` helper, mid-answer | 2 of 2: last event `response.output_text.delta` | 2 of 2: last event `response.failed`. `get_final_response()` raises the same `RuntimeError` on both sides | | Whole, before the first token | 3 of 3: 200, status `in_progress`, empty output | 3 of 3: the same 503 as above | | Stream, before the first token | 3 of 3: last event `response.in_progress` | 3 of 3: `response.created`, `response.in_progress`, `response.failed` | | Whole, mid-answer, default `max_retries=2` | 1 run: 400, not retried | 1 run: `APIConnectionError`, 4.8 s after the SIGTERM | - Real engine, a request that ends within the drain: N=60, SIGTERM during the request, exit code 0. Status `completed` with 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 state `disconnected` for 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 of c62d5e3a, so this change did not cause it. **Not run:** On real hardware: - A client that hangs up during a drain, and a streaming client that hangs up with no drain. The hang-ups I ran were whole requests with no drain. - Reasoning on. Every real run used effort none, so no stop landed during thinking. - Several requests at once: `--parallel` above 1, or a request still queued at the deadline. - A drain cancel during `_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. - A restart with a next instance for the client to retry against. - `strata serve` and `strata runtime start` with their 30 s default, and a stop by Ctrl+C. I started `serve/server.py` directly and sent SIGTERM with deadlines of 1, 2 and 60 s. - Other models, other engines and other cards. Elsewhere: - Windows and macOS. - CUDA, HIP, SYCL and Metal builds. This change is Python only. - Codex and other clients. I tried only the OpenAI Python SDK. ## Limits - The client's call still fails, because the server is stopping. What changes is the error. No restart test stands behind "retry against the next instance". - With the SDK's default `max_retries=2`, the non-streaming client retried the 503 and ended with `APIConnectionError` after about 4 s, because the server had stopped and no other instance was running. - The SDK's `responses.stream(...)` helper now sees `response.failed` while iterating, but `get_final_response()` still raises `RuntimeError` "Didn't receive a `response.completed` event." - The choice between the two cases rests on `svc.draining`. A client that hangs up during a drain gets a 503 that nobody reads, and the monitor shows `error`, not `disconnected`. 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 writes `response.failed` to the closed socket. - From reading the code, not run: a drain cancel during `_responses_prepare` (an image still being prepared) still closes the connection with no answer. This change does not touch that path. - From reading the code, not run: a cancel that lands just after the engine finished still counts as cancelled, as it did before. - `/v1/chat/completions` and `/v1/messages` are unchanged. 🤖 Generated with [Claude Code](https://claude.com/claude-code) https://claude.ai/code/session_01W53iURzvDQMjnYemag8uvv --- <sub>🔄 This issue represents a GitHub Pull Request. It cannot be merged through Gitea due to API limitations.</sub>
Sign in to join this conversation.
No milestone
No project
No assignees
1 participant
Notifications
Due date
The due date is invalid or out of range. Please use the format "yyyy-mm-dd".

No due date set.

Dependencies

No dependencies set.

Reference
Niko1221/Strata#5201
No description provided.