Skip to content

feat(responses): create and poll background responses - #2919

Merged
inureyes merged 3 commits into
mainfrom
feature/issue-2898-background-responses-create-poll
Nov 10, 2026
Merged

inureyes merged 3 commits into
mainfrom
feature/issue-2898-background-responses-create-poll

Conversation

@inureyes

@inureyes inureyes commented Nov 10, 2026 •

Copy link
Copy Markdown
Member

Summary

POST /v1/responses with background: true now returns HTTP 200 with a queued response at once and runs the generation as a detached job. GET /v1/responses/{id} polls it through queued and in_progress to completed, incomplete, failed or cancelled. Part of #2903.

  • Create: every check the foreground makes before generation still returns a synchronous 400, plus stream: true, a disabled response store (zero entry limit or zero --responses-store-max-bytes) and --responses-background-max-jobs 0. These run before the queue probe, so a full queue cannot turn them into a 503. The job limit and the byte budget return 429 rate_limit_exceeded; a full queue returns the foreground's 503.
  • Job: the video-frames fallback, automatic compaction and prepare_response_run run inside the job. A failure there, a generation error or a worker that exited ends the job as failed with error.code invalid_prompt, server_overloaded or server_error. A panic in the job task or the driver also records failed, through the recorder's Drop.
  • Polling shows output: [] and zero usage until the job is terminal (the issue's proposed default, kept).
  • ResponseObject.background is serialized only when true, so foreground responses are byte-identical to before.
  • previous_response_id naming an unfinished job returns 400 previous response '<id>' has not finished (status: <status>). DELETE on an unfinished job returns 400 and asks for a cancel first.
  • Cancel still goes through cancel_in_flight: the token admit_background returns is the one registered and the one the driver runs with. A cancel that arrives while the job is queued skips generation.
  • conversation gets the turn when the job finishes with output.

Notes for review

  • New ResponsesStore::set_background_input_items: a compacted job must be stored with its compacted input, since the capsule is in its output. Without it a chained request would replay the pre-compaction history twice.
  • The structured-output constraint is still built at create, so an invalid schema is a 400 rather than a failed job.
  • The queue-slot reservation at create is a probe that is released at once. The job reserves its own slot after the prelude, as the foreground does after compaction; holding one across a compaction pass would starve that pass at a queue depth of 1.
  • Not changed, for fix: Return the full Response from background cancel #2899: cancel on a finished store: false background response returns 404, and DELETE also removes a store: false terminal entry.

Test plan

  • cargo test --profile test-fast --features cuda -p mlxcel --lib server::routes::responses -- --test-threads=1: 79 passed (12 new in responses_background_route_tests.rs, including a driver panic after the terminal was recorded, which keeps the recorded result).
  • cargo test --profile test-fast --features cuda -p mlxcel --lib responses_store -- --test-threads=1 and responses_translator.
  • clippy (-p mlxcel --lib --tests --features cuda -D warnings), cargo fmt --all -- --check, env-var docs and license header checks.
  • Real checkpoint on GB10: mlxcel-server -m models/qwen3-0.6b-4bit --port 18298 --responses-background-max-jobs 1, driven with curl.
$ curl -s $U -d '{"model":"local","input":"Write three sentences about rain.","background":true,"max_output_tokens":400}'
HTTP 200 in 0.001249s  {"status":"queued","background":true,"output":[],"usage.total_tokens":0}
$ curl -s $U/$ID   (every 50 ms)
poll[1] status=in_progress ... poll[20] status=completed, background:true, 2 output items, total_tokens 265
$ foreground create with previous_response_id=$ID          -> completed
$ background create with "store":false                     -> queued, then completed by polling
$ create with previous_response_id=<store:false id>        -> HTTP 400 not found or has expired
$ second background create while one job is active         -> HTTP 429 {"type":"rate_limit_exceeded","code":"rate_limit_exceeded"}
$ create with previous_response_id=<active id>             -> HTTP 400 has not finished (status: in_progress)
$ DELETE $U/<active id>                                    -> HTTP 400 cancel it ... before deleting it
$ create with "background":true,"stream":true              -> HTTP 400 streaming a background response is not supported yet
$ foreground create                                        -> completed, no "background" key

Closes #2898

@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

background: true on POST /v1/responses returns queued at once, runs generation as a detached job, and GET /v1/responses/{id} polls it to a terminal status, with foreground output unchanged.

Findings Addressed

No CRITICAL or HIGH findings; no fix commits were needed.

Remaining Items

  • A cancel that flips the job token without registering an acknowledgement (the store's request_background_cancel, which fix: Return the full Response from background cancel #2899 will use) lands in the driver's error path as failed, not cancelled, when it stops generation before the first token. JobRecorder::fail only consults finish_in_flight. fix: Return the full Response from background cancel #2899 should make the recorder treat a set token as cancelled (MEDIUM, sibling scope)
  • The max_entries == 0 / max_bytes == 0 refusal comes from admit_background, after the queue probe, so a full queue answers 503 where a disabled store should answer 400; moving that check into validate_background_request makes the order deterministic (LOW)
  • The JoinError branch in run_background_job calls fail_server_error without is_active(), so a driver panic after the terminal was recorded logs a misleading "background response failed" warning; the store keeps the first terminal (LOW)
  • A cancel during the prelude is honored only after automatic compaction finishes, since compaction takes no token (LOW)

Deviations listed in the PR body are sound: set_background_input_items keeps byte accounting consistent (tested), the append_conversation_turn split leaves persist_response behavior identical, the create-time queue probe matches the foreground 503 while the job reserves its own slot later (a queue that filled meanwhile ends failed with server_overloaded), and cancel-while-queued skips generation without dispatching.

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 lib selector 206/206, responses_background 11/11 three runs, clippy and fmt clean)

@inureyes

Copy link
Copy Markdown
Member Author

Security and performance review (770b424)

No CRITICAL or HIGH findings, so no code changes were made.

Checked and clean:

  • Resource bounds: job count (--responses-background-max-jobs) and byte budget are enforced in admit_background before the job task is spawned. The 503 for a full queue comes before admission, and the snapshot stays output: []. The in-flight registry and cancel_acknowledged entries are removed on every exit (driver finish_registration, fail, cancel_before_start, drop guard).
  • Task and job leaks: a prelude panic drops the last JobRecorder and records failed. A driver panic surfaces as a JoinError and records failed. A worker exit resolves the admission waiter with ChatWorkerGoneError once the driver drops the run. Every lock the drop guard takes tolerates poisoning, so it cannot panic during unwinding.
  • Lock ordering: jobs is only ever taken before inner, and in_flight / cancel_acknowledged never nest with jobs, so there is no inversion. set_background_input_items takes only jobs.
  • No new panics are reachable from a request. Generation runs on the blocking pool, and the async task does only small store updates.

Targeted tests pass on GB10 (responses_background 11, responses_store 30, responses_translator 24, server::routes::responses 78).

Remaining items, none blocking:

  • MEDIUM: max_jobs (default 64) does not depend on slots plus queue depth. When a burst exceeds queue capacity, jobs reach prepare_response_run and fail with server_overloaded (responses_run.rs:143) instead of waiting. The brief chose this, but clients will see failed jobs where they might expect queueing. Worth a doc line or a follow-up that waits for a slot.
  • LOW: GET, DELETE, cancel and previous_response_id for background ids are not scoped to the API key (responses.rs retrieve/delete/cancel). Foreground stored responses work the same way, so this is not a regression; the only boundary is the unguessable UUIDv4 id. Resumable stream sessions are already owner-scoped (request_stream_owner), so scoping the response store per key could be an epic-wide follow-up.
  • LOW: a failed job stores the raw driver error text (err.to_string(), responses_run.rs:724) in error.message, and anyone holding the id can read it for the store TTL. Foreground streaming sends the same text once, to the requester only. It has no stack traces, but a generic message plus a server log line would be safer.
  • LOW: each job holds the request and the translated chat request (including inline media) in memory, but the admit budget counts only the snapshot and canonical input items once. The total is bounded by max_jobs times the JSON body limit.
  • LOW: every poll runs background_snapshot. It holds the jobs mutex across the inner write lock and an O(entries) expiry sweep, so heavy polling serializes admits and terminal writes behind it. This is feat: Track background response jobs in ResponsesStore #2897 code, newly on a hot GET path.
  • LOW, carried over from feat: Track background response jobs in ResponsesStore #2897: DELETE also removes store: false terminal entries, and admitting a duplicate id replaces the active job.

@inureyes inureyes added status:done Completed and removed status:review Under review labels Nov 10, 2026
inureyes added a commit that referenced this pull request Nov 10, 2026
`POST /v1/responses` with `background: true` was refused in the translator. It now returns a `queued` response at once and runs the generation as a detached job that `GET /v1/responses/{id}` polls through `queued` and `in_progress` to `completed`, `incomplete`, `failed` or `cancelled`.

Everything the handler validates before generation still returns a synchronous 400, plus `stream: true`, a disabled response store and a job limit of 0. The slow steps (video-frames fallback, automatic compaction, `prepare_response_run`) run inside the job, and a failure there ends it as `failed` with `error.code` `invalid_prompt`, `server_overloaded` or `server_error`. The job limit and the byte budget return 429 `rate_limit_exceeded`; a full queue returns the foreground's 503.

`routes/responses_background.rs` owns admission and the job task (`spawn_background_job`), and `routes/responses_background_sink.rs` holds `BackgroundSink` and `JobRecorder`. The token `admit_background` returns is registered in the in-flight registry, so the existing cancel route keeps working, and nothing ties it to the client connection. A panic in the job task or the driver drops the last recorder handle, which records `failed`, so no job stays active. `ResponseObject` gains `background`, serialized only when true, so foreground bytes are unchanged. `ResponsesStore::set_background_input_items` lets a compacted job store its compacted input.

`previous_response_id` naming an unfinished job returns 400, and `DELETE` on one asks the client to cancel first.

Validated with the new route tests on the scripted provider (`server::routes::responses`, 78 passed) and with curl against `mlxcel-server` on qwen3-0.6b-4bit on GB10.

Closes #2898
A background create against a store with a zero entry or byte budget reached the 503 queue probe before admit_background refused it as disabled, so a full queue answered 503 where the request is a 400. validate_background_request now checks all three disabling conditions (job limit, max_entries, max_bytes) up front.

The JoinError branch of run_background_job now calls fail_server_error only while the job is still active, so a driver panic after the terminal was recorded no longer logs a misleading failure.

Tests: the validation test covers zero max_entries and max_bytes, and a new test panics the driver after recording a completed terminal and checks the result is kept. The route and store suites pass.

Refs #2898
@inureyes
inureyes force-pushed the feature/issue-2898-background-responses-create-poll branch from 512fef8 to 59a7edf Compare November 10, 2026 02:28
@inureyes
inureyes marked this pull request as ready for review November 10, 2026 02:28
@inureyes
inureyes merged commit 0b01dfb into main Nov 10, 2026
@inureyes
inureyes deleted the feature/issue-2898-background-responses-create-poll branch November 10, 2026 02:28
@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: Create and poll background Responses

1 participant