Skip to content

feat(responses): track background response jobs in ResponsesStore - #2915

Merged
inureyes merged 3 commits into
mainfrom
feature/issue-2897-background-response-jobs
Nov 10, 2026
Merged

inureyes merged 3 commits into
mainfrom
feature/issue-2897-background-response-jobs

Conversation

@inureyes

@inureyes inureyes commented Nov 10, 2026 •

Copy link
Copy Markdown
Member

Closes #2897

Part of #2903

Summary

ResponsesStore can now track background: true responses from the moment they are created. Active jobs live in a separate jobs map under their own lock, outside entries, so TTL and LRU eviction never touch them. This PR adds no HTTP behavior; the create-and-poll sub-issue (#2898) consumes the API.

Store API

Implemented with the signatures from the issue:

  • BackgroundAdmitError { Disabled, LimitReached { limit }, OverBudget } and BackgroundCancel { NotFound, Requested, Terminal(ResponseObject) }.
  • admit_background(snapshot, input_items, effective_store) -> Result<InFlightToken, BackgroundAdmitError>: forces the snapshot status to queued. Disabled when the job limit, max_entries or max_bytes is 0, LimitReached at the job limit, OverBudget when active bytes plus the new record exceed max_bytes.
  • mark_background_in_progress(id) -> bool: queued to in_progress only.
  • finish_background(id, terminal) -> ResponseObject: removes the job and inserts the terminal entry in one critical section (lock order jobs, then inner). First writer wins; later calls return the recorded object while it is retained, otherwise their own argument. A terminal object larger than max_bytes is recorded as a failed object with error.code: "server_error", empty output, and a message naming the budget.
  • background_snapshot(id): live snapshot of an active job or the retained terminal object, including a store: false one. Does not refresh LRU.
  • background_status(id): active jobs only.
  • request_background_cancel(id): flips the job's token and keeps it active; returns Terminal for a retained finished response.
  • wait_background_terminal(id, timeout): returns the recorded terminal object (from a shared slot set before waiters are woken, so eviction cannot race it), or None on timeout or for an unknown id.
  • active_background_jobs().

Active bytes are tracked separately, included in approximate_total_bytes, and never drive evict_to_limits. The terminal object of a store: false job is an ephemeral entry: get() (and so previous_response_id) skips it, background_snapshot reads it, and the existing lazy sweep removes it after the ephemeral TTL.

Flags

  • --responses-background-max-jobs / MLXCEL_RESPONSES_BACKGROUND_MAX_JOBS, default 64, 0 disables background mode.
  • --responses-background-ephemeral-ttl-secs / MLXCEL_RESPONSES_BACKGROUND_EPHEMERAL_TTL_SECS, default 600, at least 1 (clap range; 0 fails startup).

Both are wired through mlxcel serve (src/main.rs, src/commands/serve.rs), mlxcel-server (src/bin/mlx_server.rs), cli_input.rs and startup.rs into ResponsesStoreConfig, and documented in docs/responses-api.md and docs/environment-variables.md.

Notes for sibling sub-issues

  • The proposed defaults were kept (64 jobs, 600 s ephemeral TTL, in-memory only).
  • ResponsesStoreConfig gained two fields, so struct literals need ..ResponsesStoreConfig::default(). The two existing literals in the store tests were updated that way; no existing test assertion changed.
  • remove() (the DELETE path) also deletes a store: false terminal entry; feat: Create and poll background Responses #2898 decides what DELETE returns for those ids.
  • Admitting an id that is already active replaces that job (its waiters time out). Response ids are server-generated UUIDs, so this is defensive only.
  • With a very small max_bytes, even the trimmed failed object can exceed the budget and is then evicted at once; waiters still receive it.
  • Internally the ephemeral marker is stored as a duration (Entry.ephemeral_ttl) rather than an Instant, which avoids instant overflow for very large TTL values. It is private and does not affect the API.

Changes during review

  • finish_background now serializes the terminal object once, before taking any lock, and reuses the input-item size computed at admission, so a large result no longer blocks admits and polls behind the jobs mutex. Foreground insert() also sizes its payload before taking the store lock.

Tests

  • New src/server/responses_store_background_tests.rs: limit and slot release, disabled and over-budget admission, queued to in_progress, survival under TTL expiry and LRU pressure, 8-thread concurrent finish, store: false visibility and expiry, oversized terminal to failed, active-byte accounting through a lifecycle, cancel, and wait wake-up and timeout.
  • Flag parse, env, and TTL-0 refusal tests in src/main_tests.rs and src/bin/mlx_server.rs.

Verification

  • cargo test --profile test-fast --features cuda -p mlxcel --lib responses_store -- --test-threads=1: 29 passed (16 existing, 13 new).
  • Flag tests in both binaries (responses_background selector): 3 + 3 passed. cli_input, server::routes::responses and serve selectors pass unchanged.
  • Clippy on lib, tests and both binaries with -D warnings, cargo fmt --check, check_env_var_docs.py and the license header check pass.
  • Real binary: mlxcel-server --help lists both flags with their env vars; --responses-background-ephemeral-ttl-secs 0 and MLXCEL_RESPONSES_BACKGROUND_EPHEMERAL_TTL_SECS=0 both exit 2 with a range error; a non-numeric MLXCEL_RESPONSES_BACKGROUND_MAX_JOBS is refused, proving the env var is read. A server on models/qwen3-0.6b-4bit started with both env vars set served POST /v1/responses (store: true, status completed, output 2 + 3 = 5.) and returned it from GET /v1/responses/{id}.

@inureyes inureyes added type:enhancement New features, capabilities, or significant additions priority:medium Medium priority status:review Under review labels Nov 10, 2026
@inureyes

Copy link
Copy Markdown
Member Author

Implementation Review Summary

Intent

Add the in-memory background job API to ResponsesStore (#2897) with the exact contract signatures, plus the two --responses-background-* flags wired into ResponsesStoreConfig. HTTP integration is deferred to #2898.

Findings Addressed

None. No CRITICAL or HIGH findings; auto-fix was scoped to those severities.

Remaining Items

  • finish_background computes fit_terminal (a full JSON serialization of the terminal object) and then insert_locked (a second serialization) while holding the jobs mutex, so a multi-MB terminal briefly blocks every admit, poll, and status call. Matches how insert() already serializes under the inner lock, so not a regression for foreground; worth revisiting if polling load grows. (MEDIUM)
  • An id collision in admit_background replaces the old job and drops its Notify, so waiters on the old job time out with None and the old task's later finish_background would finish the new job. Ids are random, so this is defensive only. (LOW)
  • If the failed fallback object still exceeds a very small max_bytes, evict_to_limits drops it immediately and later polls see 404 (waiters still get it through the OnceLock). (LOW)
  • remove() deletes ephemeral store: false entries; feat: Create and poll background Responses #2898 should decide whether DELETE on such an id returns 404. (LOW, deferred)

Verification

  • All stated requirements implemented (contract signatures match the issue exactly; lock order jobs then inner holds in every two-lock path; first writer wins; ephemeral entries hidden from get() and expired by the lazy sweep; active bytes counted in approximate_total_bytes and excluded from eviction; notified() is created before the OnceLock check, so the wake cannot be missed)
  • No placeholder/mock code remaining
  • Integrated into project code flow (flags wired through main.rs, mlx_server.rs, serve.rs, cli_input.rs, startup.rs; HTTP use deferred to feat: Create and poll background Responses #2898 as the issue permits)
  • Project conventions followed
  • Existing modules reused where applicable (insert_locked factored out of insert, serialized_json_len_saturating, input_items_size_bytes)
  • No unintended structural changes (existing test assertions unchanged; only config literals gained ..Default)
  • Tests pass: responses_store lib tests 29/29 on CUDA, cargo check of bins and their tests clean, fmt clean, CI clippy green

@inureyes

Copy link
Copy Markdown
Member Author

Security and performance review (head 031aa48)

No CRITICAL or HIGH findings, so no commits were pushed.

Checked: memory bounds, lock ordering and contention, poisoning and panics, integer overflow.

  • Memory: active jobs are capped by --responses-background-max-jobs and by max_bytes on active bytes. Terminal objects go through the normal LRU/TTL path. Worst-case resident data is about 2x max_bytes (active plus stored), which is the documented design.
  • Locks: every path takes jobs before inner, and no path takes them in the reverse order, so there is no deadlock. All locks recover from poisoning. notify_waiters runs after the jobs guard is dropped.
  • Overflow: all byte accounting uses saturating arithmetic. Expiry compares elapsed durations and never adds to an Instant. tokio::time::timeout handles very large durations safely. The ephemeral TTL is clamped to at least 1 second in both CLIs and in startup.
  • Ids are server-generated UUIDv4 (routes/responses.rs:226), so a client cannot trigger the duplicate-id replacement path.

Remaining, not fixed:

  • MEDIUM: finish_background serializes the terminal object twice (in fit_terminal and insert_locked) while it holds the jobs mutex, and runs the O(entries) expiry sweep under it. A multi-megabyte terminal object stalls every admit, poll, and cancel for that time, and those callers block async workers on a std mutex. Fix: compute the size once before taking jobs and pass it to the insert.
  • LOW: background_snapshot, request_background_cancel, and wait_background_terminal keep holding jobs while they sweep inner on a miss. They can release jobs first: a miss means finish_background already inserted the entry in the same critical section.
  • LOW: when a duplicate id is admitted, the old job's waiters are never notified and wait until their timeout, and the old task's finish_background would finish the new job. This cannot happen with UUID ids.
  • LOW: on a very small max_bytes, the failed replacement object can still exceed the budget (already noted).

@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
Add an active-job map to ResponsesStore, outside the TTL and LRU entries, so background responses have a record from creation. The API (admit_background, mark_background_in_progress, finish_background, background_snapshot, background_status, request_background_cancel, wait_background_terminal, active_background_jobs) follows the contract in the issue; finish moves a job to a stored entry in one critical section, store:false terminals are ephemeral and hidden from get(), and an oversized terminal is recorded as a failed object.

Add --responses-background-max-jobs (default 64) and --responses-background-ephemeral-ttl-secs (default 600, at least 1) to mlxcel serve and mlxcel-server, wired into ResponsesStoreConfig and documented.
…s lock

finish_background serialized the terminal object twice while holding the jobs mutex, so a multi-megabyte result briefly blocked every admit, poll and cancel. Measure it once before taking any lock, keep the input-item size computed at admission, and pass the precomputed entry size into the insert. Foreground insert() now also sizes its payload before taking the store lock.
@inureyes
inureyes force-pushed the feature/issue-2897-background-response-jobs branch from 58f0396 to 9e1da9b Compare November 10, 2026 01:18
@inureyes
inureyes marked this pull request as ready for review November 10, 2026 01:18
@inureyes
inureyes merged commit 6ead9df into main Nov 10, 2026
@inureyes
inureyes deleted the feature/issue-2897-background-response-jobs branch November 10, 2026 01:18
inureyes added a commit that referenced this pull request Nov 30, 2026
clap reads MLXCEL_* env defaults at parse time, and the ScopedEnv tests in src/main_tests.rs set those variables process-wide while holding CLI_ENV_LOCK. 48 tests parsed the CLI without the lock, so under the default parallel test runner they could see another test's value. On GB10, settings_cli_mlxcel_serve_defaults_off_and_explicit_flag_enables failed once because serve_responses_background_ephemeral_ttl_zero_is_refused (#2915) had MLXCEL_RESPONSES_BACKGROUND_EPHEMERAL_TTL_SECS=0 set.

Every CLI parsing test now takes a shared cli_env_lock() helper, which also recovers from a poisoned lock so one failing test no longer fails the other lock holders. The 11 existing lock sites use the same helper. A new scan test, every_cli_parsing_test_holds_the_env_lock, fails when a test that parses the CLI (directly or through a helper in the file) does not take the lock.

Validation: removing the lock from one test makes the scan test fail and name it; cargo test --bin mlxcel passed 10 of 10 consecutive default-parallel runs (365 passed); clippy with -D warnings and fmt are clean.
inureyes added a commit that referenced this pull request Nov 30, 2026
clap reads `MLXCEL_*` env defaults at parse time, and the `ScopedEnv` tests in `src/main_tests.rs` set those variables process-wide while holding `CLI_ENV_LOCK`. 48 tests parsed the CLI without the lock, so under the default parallel runner they could observe another test's value. During the auto-impl run for #3567 to #3569, `settings_cli_mlxcel_serve_defaults_off_and_explicit_flag_enables` failed once on GB10 with `0 is not in 1..` because `serve_responses_background_ephemeral_ttl_zero_is_refused` (added in #2915) had `MLXCEL_RESPONSES_BACKGROUND_EPHEMERAL_TTL_SECS=0` set at the same moment.

## Changes

- Every CLI parsing test takes a shared `cli_env_lock()` helper. The helper recovers from a poisoned lock, so one failing test no longer fails every other lock holder. The 11 existing lock sites use it too.
- New scan test `every_cli_parsing_test_holds_the_env_lock` reads `main_tests.rs` and fails when a `#[test]` that parses the CLI, directly or through a helper in the file, does not take the lock.

## Validation

- Revert check: removing the lock from one test makes the scan test fail and name that test.
- `cargo test --profile test-fast --features cuda --bin mlxcel`: 10 of 10 consecutive default-parallel runs passed (365 passed).
- `cargo clippy --features cuda --bin mlxcel --tests -- -D warnings`, `cargo fmt --check` and the four `scripts/ci` contract checks pass.
@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: Track background response jobs in ResponsesStore

1 participant