Skip to content

feat(responses): stream and resume background responses - #2924

Merged
inureyes merged 3 commits into
mainfrom
feature/issue-2900-background-stream-resume
Nov 10, 2026
Merged

inureyes merged 3 commits into
mainfrom
feature/issue-2900-background-stream-resume

Conversation

@inureyes

@inureyes inureyes commented Nov 10, 2026 •

Copy link
Copy Markdown
Member

Summary

  • background: true with stream: true now answers with an SSE stream instead of a 400. Order: response.created (status queued), response.queued, response.in_progress at the first progress callback, the usual item and delta events, then exactly one terminal event: response.completed (also for cancelled), response.incomplete or response.failed.
  • GET /v1/responses/{id}?stream=true[&starting_after=N] (and /responses/{id}) replays the events after N, tails the live ones and closes after the terminal event. Without stream=true the handler is unchanged.
  • Each streamed job owns a BackgroundEventLog bounded 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 in finish_background, counts in its size_bytes, and is freed on eviction. ResponsesStore::background_event_log(id) -> Option<Arc<BackgroundEventLog>> reads it.
  • Readers are independent cursors. A disconnect ends one reader and cannot reach the cancel token. A cursor below the retained window gets a 400 naming the oldest retained 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 one response.error event with the same message and closes.
  • A reader holds only a Weak handle 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 a response.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.
  • The terminal event is serialized before finish_background takes the jobs lock, so a large terminal object does not stall admits and polls.
  • Foreground streams are unchanged: PreparedRun::background_opening is None there.

Deviations from the issue

  • response.created and response.queued are appended at admission, not by the driver, so the id is on the wire before the prelude (media decoding, compaction) finishes. The PreparedRun field (background_opening: Option<u64>) tells the driver to skip response.created, number from that value and send response.in_progress at the first progress callback.
  • The terminal event is appended by ResponsesStore::finish_background from the object it recorded, not by the sink or JobRecorder. Every exit path (driver, JobRecorder::fail, cancel_before_start, Drop, an oversized result replaced by failed) then ends the stream with the event that matches the stored response.
  • The log assigns sequence numbers itself and restamps an event that disagrees, which keeps the sequence gap-free across its three writers.
  • admit_background keeps its signature; the log is attached with the new ResponsesStore::attach_background_event_log(id, log).
  • The overrun event is the server's existing error event, response.error, with code: "stream_events_evicted".
  • The newest event is always retained, so a log can exceed its budget by one event (the terminal one can be larger than the budget).
  • A budget of 0 refuses stream: true on a background create with a 400.
  • A log that does not fit --responses-store-max-bytes beside its response is dropped when the job finishes, instead of evicting the response.
  • A live job's log is counted in approximate_total_bytes but not in the admission budget check.
  • After an automatic compaction, the mlx.compaction.* events follow response.in_progress, as in the foreground.
  • The route tests live in responses_background_stream_route_tests.rs and responses_background_stream_errors_route_tests.rs, child modules of responses_background_route_tests.rs, to keep files under 500 lines.

Changes during review

  • Security pass (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. The responses_background CLI 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.
  • Real model, rerun at 0a0e49ba: mlxcel-server -m models/qwen3-0.6b-4bit on GB10 (CUDA), 500 output tokens, under gpu-lock. Output of the two check scripts, condensed, ids shortened:
$ curl -sN $BASE/v1/responses -d '{"model":"local","input":"Write a long story ...","background":true,"stream":true,"max_output_tokens":500}'   # kill -9 after 25+ events
killed curl after sequence_number 39 of resp_ea38d7ea...
poll: status in_progress
$ curl -sN "$BASE/v1/responses/resp_ea38d7ea...?stream=true&starting_after=39"
part 1: 40 events, sequence 0..39, last type response.output_text.delta
part 2: 457 events, sequence 40..496, last type response.completed
OK: contiguous 0..496, no gap, no duplicate, terminal event last
starting_after=abc -> 400, unknown id -> 404, foreground id with stream=true -> 400 (has no event stream)
$ uv run --with openai python sdk_check.py   # openai 3.48.0
client.responses.create(background=True, stream=True): created resp_f88272e1... status queued
dropped after 30 events, last sequence_number 29 (response.output_text.delta)
first events: response.created, response.queued, response.in_progress, response.output_item.added
client.responses.retrieve(id, stream=True, starting_after=29): 469 events, sequence 30..498, last type response.completed
final status: completed; a replay with no cursor returns the identical 0..498; non-integer cursor -> 400

Not run: Metal, and the router pool (#2901).

Part of #2903

Closes #2900

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
@inureyes inureyes added status:review Under review type:enhancement New features, capabilities, or significant additions priority:medium Medium priority labels Nov 10, 2026
@inureyes

Copy link
Copy Markdown
Member Author

Implementation Review Summary

Intent

Stream background: true, stream: true responses from a bounded, replayable per-job event log, and resume them with GET /v1/responses/{id}?stream=true&starting_after=N.

Findings Addressed

No CRITICAL or HIGH findings, so no code changes were made. The 11 listed deviations are sound: appending the terminal event in finish_background gives exactly one terminal event per job on every exit path (driver, fail, cancel_before_start, Drop, oversized replacement), and log-side numbering keeps the sequence gap-free across admission, sink and store.

Remaining Items

  • finish_background serializes the terminal object for the log (append_terminal) while holding the jobs mutex, which the function otherwise avoids so admits and polls do not wait on a large object (MEDIUM, src/server/responses_store.rs:660)
  • Live event logs are outside the admission budget, so active streamed jobs can hold up to max_jobs x log budget (256 MiB at defaults) above --responses-store-max-bytes until they finish (MEDIUM, documented deviation)
  • starting_after beyond the newest event: on a finished job the reader gets an empty 200 stream with no terminal event, and on a live job it silently skips events up to the cursor; a 400 may be clearer (MEDIUM, src/server/responses_background_events.rs:234)
  • The overrun response.error reuses the evicted event's sequence_number (LOW, src/server/responses_background_events.rs:344)
  • stream_from_start falls back to a JSON body for a stream: true create if the log is gone before the handler reads it; passing the log Arc from admission would avoid the store lookup (LOW, src/server/routes/responses_background_stream.rs:81)
  • A log dropped because it did not fit the store budget makes a later resume answer "not created with stream: true", which is misleading (LOW, src/server/routes/responses_background_stream.rs:109)

Verification

  • All stated requirements implemented
  • No placeholder/mock code remaining
  • Integrated into project code flow
  • Project conventions followed
  • Existing modules reused where applicable
  • No unintended structural changes
  • Tests pass (responses selector: 225 passed; clippy -D warnings, fmt, env-var docs check clean)

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
@inureyes

Copy link
Copy Markdown
Member Author

Security and performance review of the background stream log (issue #2900). Fixes are in 0a0e49b.

Fixed:

  • HIGH (memory): a reader held its Arc<BackgroundEventLog> for the life of the connection, so a client that opened a streamed create or a resume and stopped reading pinned the whole log (up to --responses-background-event-log-bytes) after the store evicted the entry, with nothing bounding it but the number of open connections. Readers now hold the log weakly between reads, buffer at most 256 events or 64 KiB, and end with response.error (stream_events_evicted) when the log is gone before the terminal event.
  • MEDIUM: finish_background cloned and serialized the terminal event under the jobs mutex; it is now prepared before the lock and reused when the number and object still match.
  • MEDIUM: starting_after past the newest assigned sequence_number returns 400 invalid_request_error instead of an empty 200 stream (finished job) or a silent gap (live job).
  • LOW: resuming a response whose log was dropped for the store budget now says the stream is no longer retained.

Documented, not changed:

  • MEDIUM: live-job logs are counted in approximate_total_bytes but not at admission, so they can add max jobs times log bytes (256 MiB with defaults) beside --responses-store-max-bytes. Now stated in docs/responses-api.md.
  • LOW: readers per response are uncapped. Each costs one connection plus the bounded batch above, and appends never wait on readers, so this is equivalent to holding open any other connection.

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.

@inureyes inureyes added status:done Completed and removed status:review Under review labels Nov 10, 2026
@inureyes
inureyes marked this pull request as ready for review November 10, 2026 04:05
@inureyes
inureyes merged commit 6cd038e into main Nov 10, 2026
31 checks passed
@inureyes
inureyes deleted the feature/issue-2900-background-stream-resume branch November 10, 2026 04:06
inureyes added a commit that referenced this pull request Nov 10, 2026
`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
@inureyes inureyes added this to the 0.9 milestone Nov 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

priority:medium Medium priority status:done Completed type:enhancement New features, capabilities, or significant additions

Projects

None yet

Development

Successfully merging this pull request may close these issues.

feat: Stream and resume background Responses

1 participant