Repository navigation
feat(responses): stream and resume background responses - #2924
Conversation
A `background: true` create with `stream: true` was refused, and a background job dropped its events, so a client could only poll. The OpenAI contract streams the events with a `sequence_number` and lets a client that lost its connection resume with `GET /v1/responses/{id}?stream=true&starting_after=N`.
A streamed background job now owns a `BackgroundEventLog`: a byte-bounded deque of numbered, serialized events (`--responses-background-event-log-bytes`, default 4 MiB) that drops the oldest when full and never the newest, so the terminal event survives. The log numbers events itself, so the sequence has no gaps across its three writers: admission appends `response.created` (status `queued`) and `response.queued`, the driver appends its events through the background sink starting with `response.in_progress` at the first progress callback, and `ResponsesStore::finish_background` appends the terminal event from the object it recorded. Every stream therefore ends with exactly one of `response.completed` (also for `cancelled`), `response.incomplete` or `response.failed`, matching the stored response, whichever path ended the job.
The create call and each resume are independent cursors over the log. A reader that disconnects ends only itself and cannot reach the cancellation token. A cursor older than the retained window gets a 400 naming the oldest retained sequence number, and a reader overrun while streaming gets one `response.error` event and closes. The log moves onto the stored entry when the job finishes, counts in its `size_bytes`, and is freed on eviction.
Foreground streams are unchanged: `PreparedRun::background_opening` is `None` there and the driver emits the same events with the same numbers.
Validated with the `server::routes::responses`, `responses_store`, `responses_background` and `cli_input` lib selectors, clippy and fmt on CUDA, and on `qwen3-0.6b-4bit` by killing a `curl -N` stream and an OpenAI SDK stream midway and resuming both with `starting_after`.
Closes #2900
Implementation Review SummaryIntent
Findings AddressedNo CRITICAL or HIGH findings, so no code changes were made. The 11 listed deviations are sound: appending the terminal event in Remaining Items
Verification
|
A reader of a background event log held a strong reference for its whole lifetime, so a client that kept a streamed create or a resume open without reading pinned up to the full log (4 MiB by default) after the store evicted the entry, outside every budget. Readers now hold the log weakly between reads (strongly only while waiting on the live tail, where the job holds it anyway), copy at most 256 events or 64 KiB per read, and get a `response.error` saying the stream is no longer retained when the log is gone before the terminal event. A `starting_after` past the newest assigned sequence number now returns 400 `invalid_request_error` instead of an empty stream on a finished job or a silent gap on a live one. A resume of a response whose log was dropped for the store budget says the stream is no longer retained instead of claiming it was not created with `stream: true`. `finish_background` serializes the terminal event before taking the jobs lock and uses it when no event slipped in and the object was stored as given. docs/responses-api.md documents the new 400s, eviction ending stalled readers, and that live logs sit beside the admission budget (max jobs times log bytes). Responses lib tests (231), clippy, fmt, env-var-docs and header checks pass on GB10. Refs #2900
|
Security and performance review of the background stream log (issue #2900). Fixes are in 0a0e49b. Fixed:
Documented, not changed:
Lock order stays jobs, then store, then log, with no reverse path. A disconnect drops only the reader's cursor; nothing in the reader reaches the cancel token. Responses lib tests (231), clippy, fmt, env-var-docs and header checks pass on GB10. |
`POST /v1/responses/{id}/cancel` on a `background: true` job now returns the job's final Response object, byte for byte what a following GET returns. A queued job is recorded `cancelled` at once and its pre-generation work (video extraction, automatic compaction, run preparation) is dropped, so create-and-cancel loops cannot bypass `--responses-background-max-jobs`. An in-progress job is asked to stop and the reply waits up to 5 s for the driver's own object with the partial output, then records a `cancelled` snapshot copy; the driver's late write is a no-op. The first terminal write wins: if completion won, the reply is the existing 400, and a repeat cancel returns the stored object. Finished `store: false` jobs now get 400 or their object instead of 404, and the brief 404 window before the terminal write is closed.
A failure after a requested cancel is recorded `cancelled` (the original error is logged at debug level), using a new per-job `cancel_requested` flag rather than the cancellation token, which a refused admission also sets. All cancel paths share the store's terminal-write helper, which also appends the terminal stream event from #2924, so a streamed job's events end with the same object. Foreground cancel is unchanged.
Closes #2899, part of #2903
Summary
background: truewithstream: truenow answers with an SSE stream instead of a 400. Order:response.created(statusqueued),response.queued,response.in_progressat the first progress callback, the usual item and delta events, then exactly one terminal event:response.completed(also forcancelled),response.incompleteorresponse.failed.GET /v1/responses/{id}?stream=true[&starting_after=N](and/responses/{id}) replays the events afterN, tails the live ones and closes after the terminal event. Withoutstream=truethe handler is unchanged.BackgroundEventLogbounded by--responses-background-event-log-bytes/MLXCEL_RESPONSES_BACKGROUND_EVENT_LOG_BYTES(default 4 MiB). It drops the oldest event when full and never the newest. The log moves onto the stored entry infinish_background, counts in itssize_bytes, and is freed on eviction.ResponsesStore::background_event_log(id) -> Option<Arc<BackgroundEventLog>>reads it.sequence_number; a cursor past the newest assigned event gets a 400 naming the newest; a non-integer cursor gets a 400. A reader overrun while streaming gets oneresponse.errorevent with the same message and closes.Weakhandle to the log between reads and copies at most 256 events or 64 KiB per read, so a stalled client cannot keep an evicted log alive; if the log is evicted before the reader reaches the terminal event, it gets aresponse.error(stream_events_evicted) and the stream ends. A resume on a response whose log was dropped for the store budget gets a 400 saying the stream is no longer retained.finish_backgroundtakes the jobs lock, so a large terminal object does not stall admits and polls.PreparedRun::background_openingisNonethere.Deviations from the issue
response.createdandresponse.queuedare appended at admission, not by the driver, so the id is on the wire before the prelude (media decoding, compaction) finishes. ThePreparedRunfield (background_opening: Option<u64>) tells the driver to skipresponse.created, number from that value and sendresponse.in_progressat the first progress callback.ResponsesStore::finish_backgroundfrom the object it recorded, not by the sink orJobRecorder. Every exit path (driver,JobRecorder::fail,cancel_before_start,Drop, an oversized result replaced byfailed) then ends the stream with the event that matches the stored response.admit_backgroundkeeps its signature; the log is attached with the newResponsesStore::attach_background_event_log(id, log).response.error, withcode: "stream_events_evicted".0refusesstream: trueon a background create with a 400.--responses-store-max-bytesbeside its response is dropped when the job finishes, instead of evicting the response.approximate_total_bytesbut not in the admission budget check.mlx.compaction.*events followresponse.in_progress, as in the foreground.responses_background_stream_route_tests.rsandresponses_background_stream_errors_route_tests.rs, child modules ofresponses_background_route_tests.rs, to keep files under 500 lines.Changes during review
0a0e49ba): readers no longer keep an evicted log in memory (HIGH), terminal-event serialization moved out of the jobs lock, a cursor past the newest event is refused with a 400, and the dropped-for-budget resume message names the real cause. Implementation review found no CRITICAL or HIGH issues.Test plan
cargo test --profile test-fast --features cuda -p mlxcel --lib responses -- --test-threads=1: 225 passed.cli_input: 164 passed. Theresponses_backgroundCLI tests of both binaries: 3 passed each.cargo clippy -p mlxcel --lib --tests --profile test-fast --features cuda -- -D warnings,cargo fmt --all -- --check,scripts/ci/check_env_var_docs.py,scripts/insert_apache_header.py --check.0a0e49ba:mlxcel-server -m models/qwen3-0.6b-4biton GB10 (CUDA), 500 output tokens, undergpu-lock. Output of the two check scripts, condensed, ids shortened:Not run: Metal, and the router pool (#2901).
Part of #2903
Closes #2900