Skip to content

feat(server): add automatic Responses compaction (phase B) - #2522

Merged
adrysn merged 7 commits into
mainfrom
feature/issue-2397-auto-compaction
Oct 21, 2026
Merged

adrysn merged 7 commits into
mainfrom
feature/issue-2397-auto-compaction

Conversation

@adrysn

@adrysn adrysn commented Oct 21, 2026 •

Copy link
Copy Markdown
Member

Phase B of #2397, after phase A (#2520): automatic compaction on /v1/responses through context_management, the output cap at the remaining context, and the streamed mlx.compaction.* events.

Behavior

  • context_management: [{"type":"compaction","compact_threshold":N}] on /v1/responses and /responses. The rendered input (chained previous_response_id/conversation history plus input, capsules expanded) is counted on the /v1/responses/input_tokens path. At the threshold, phase A's compact_history runs with the same ResponsesCompactionBackend and default keep_tokens, and generation runs on instructions + summary + retained turns. Summary budget is upstream's automatic one: context/16, clamped to 128..1024.
  • output starts with the compaction item. usage counts the final generation only, as upstream does.
  • Stored shape: the response stores the instructions as its input and the capsule as output[0]. The next previous_response_id hop therefore assembles instructions + capsule + tail, replays the summary, and compacts again only at the threshold. A conversation transcript appends the new input plus output.
  • Streaming: mlx.compaction.started (input_tokens) and mlx.compaction.completed (input_tokens_before/input_tokens_after), in upstream's payload shape plus sequence_number, come right after response.in_progress. The capsule follows as output_item.added/done at output_index 0, and generated items start at 1. response.completed lists the same capsule once, including the tool-streamed path from feat(server): stream tool-call arguments incrementally on Chat and Responses #2504.
  • Without the field, or with []/null: no extra count and no cap, and the response is unchanged.

Decisions to review

  • Threshold is >=, as in upstream and OpenAI's "reaches", although the issue says "exceeds". Compaction also fires below the threshold when the input leaves no room for output.
  • Output cap and incomplete apply only to context_management requests. Today every length stop reports completed, and with --context-shift generation may run past the window. A general cap would change both. incomplete_details.reason is max_output_tokens, the OpenAI and upstream value, not a literal length. The streamed reply then ends with response.incomplete. As in OpenAI's shape, completed_at is null and the cut-off message item is status: "incomplete", in the final object and in its streamed output_item.done. A limited reasoning budget above the capped limit is lowered to one token below it. A server with no free slot returns 503 before any count.
  • Failures are HTTP errors before any output, on both arms. Compaction runs before the SSE stream opens, because ResponseStreamSender sends from the blocking task. A streamed overflow therefore returns 400 exceed_context_size_error/context_length_exceeded, as a stream admission overflow does today. The cost is that the two events carry counts, not live progress.
  • No safe split (one turn, or one unfinished tool group): the request proceeds uncompacted while the input fits, as upstream does. Otherwise it returns context_length_exceeded. Every other compaction failure keeps phase A's error.
  • A malformed context_management returns 400 invalid_request_error: not an array, more than one entry (duplicates included), a type other than compaction, or a threshold that is not an integer from 1 to 100000000.

Test plan

  • cargo test --profile test-fast -p mlxcel --lib filters: responses_auto_compact (15, including the reasoning-budget clamp, the busy-server 503, the conversation path and a streamed request without context_management that keeps its pre-PR event sequence), responses_compact (28), server::routes:: (508), server::responses (74), server::types (107, before the review fixes), streaming_responses (4)
  • cargo clippy -p mlxcel --lib --tests -- -D warnings, cargo fmt --check
  • Known limit: a streamed request that compacts runs the summary pass on the request task, and a client disconnect does not cancel it.
  • Unverified (no Metal or CUDA here): a real model such as mlx-community/Qwen3-30B-A3B-4bit. Media and video prompts with context_management have no test: each count takes a worker slot, and video substitution runs again after compaction.

Out of scope, per the issue: Chat Completions and /v1/messages auto-compaction, the Codex compaction_trigger input, and multi-pass summarization. Follow-up: #2523.

Closes #2397

…gement

/v1/responses now accepts context_management: [{"type":"compaction","compact_threshold":N}] (#2397, phase B). The rendered input, chained history included, is counted on the /v1/responses/input_tokens path; when it reaches N or leaves no room for output, phase A's compact_history runs with the same backend and limits and generation uses the compacted context. The output starts with the compaction item; the stored response keeps the instructions as input and the capsule as its first output, so the next previous_response_id hop replays the summary without compacting again.

For context_management requests only, generation is capped at the context left after the prompt and a length stop reports status incomplete with reason max_output_tokens (mlx-vlm#2458). Compaction finishes before the stream opens, so failures are HTTP errors on both arms; streamed requests then send mlx.compaction.started and mlx.compaction.completed after response.in_progress and the capsule at output_index 0. A history with no safe split proceeds uncompacted while it fits (upstream behavior). Requests without the field are unchanged.
Route tests drive the real router with a scripted model and a byte tokenizer (#2397): the capsule leads the output and the generation renders the summary, not the discarded turns; a chained previous_response_id turn replays the summary with no second summary pass; streaming sends created, in_progress, mlx.compaction.started, mlx.compaction.completed, then the capsule at output_index 0 with consecutive sequence numbers and matching before/after counts; a tool-streamed reply lists the capsule once and a length stop ends with response.incomplete. Also covered: the output cap and incomplete status, an unchanged request without context_management, the no-split and overflow failure paths on both arms, and context_management validation.

The scripted provider gains a length finish step for these tests. Filters responses_auto_compact (11), responses_compact (28), server::routes:: (504), server::responses (74), server::types (107) and streaming_responses (4) pass.
docs/responses-api.md replaces the "not implemented yet" note with the context_management contract (#2397): the threshold count, chained-history scope, summary budget, stored-response shape, the output cap and incomplete status for these requests, the mlx.compaction.* stream events and their ordering, the pre-stream failure policy, the no-split fallback, and what stays out of scope. The field table, event list and gap list follow. CHANGELOG and docs/server-features.md gain matching entries.
@adrysn adrysn added type:enhancement New features, capabilities, or significant additions priority:low Low priority area:inference Generation, sampling, decoding (incl. speculative, DRY) status:review Under review labels Oct 21, 2026
@adrysn

adrysn commented Oct 21, 2026

Copy link
Copy Markdown
Member Author

Implementation Review Summary

Intent

Phase B of #2397: automatic compaction on /v1/responses through context_management, the output cap ending in incomplete, and the streamed mlx.compaction.* events.

Findings Addressed

  • None needed: no CRITICAL or HIGH findings.

Remaining Items

  • No conversation-path auto-compaction test; the path shares output_to_input_items and canonical_compaction_input with the tested previous_response_id chain (MEDIUM)
  • thinking_budget is validated against the uncapped output limit; after the cap a budget above the remaining context never fires and the reply ends incomplete instead of a 400 (LOW, acceptable)
  • /v1/responses/input_tokens accepts a malformed context_management without validating it (LOW)
  • An incomplete reply keeps item status completed and sets completed_at (LOW)
  • Real-model check with a Metal or CUDA build (unverified)

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_auto_compact 11, responses_compact 28, server::routes:: 504, server::responses 74, server::types 107, streaming_responses 4; clippy and fmt clean)

A context_management reply that stops at its output limit already reports status incomplete (#2397). It now also follows OpenAI's shape: completed_at is null and the cut-off message item is status incomplete, in the non-streamed object, the streamed output_item.done event, and response.incomplete. Responses without context_management are untouched because only final_status sets incomplete. Addresses a review note on #2522.
Two review gaps on #2522. A conversation request above the threshold compacts once, and the next turn on the same conversation replays the summary with the system message once and no second summary pass. A streamed request without context_management keeps the exact pre-PR event sequence (no mlx.compaction events, no capsule), consecutive sequence numbers, output_index 0, a completed status after a length stop, and its own max_tokens. The cap tests now also assert the incomplete item status and the null completed_at. The new tests live in responses_auto_compact_chain_tests.rs to keep each file under 500 lines.

Filters: responses_auto_compact (13), responses_compact (28), server::routes:: (506), server::responses (74), streaming_responses (4); clippy lib+tests and fmt clean.
@adrysn

adrysn commented Oct 21, 2026

Copy link
Copy Markdown
Member Author

Security and performance review of phase B at 29dfec0. No CRITICAL or HIGH findings, so no commits.

MEDIUM (not fixed)

  • Reasoning budget is not capped with the output limit. resolve_request_budget validates the budget against the uncapped effective_max_tokens (src/server/routes/responses.rs:200-216). cap_output_tokens then lowers options.max_tokens (:325-331, :528-534), but options.reasoning_budget keeps the old value (:342, :545). A context_management reply near the window can spend the whole capped budget on reasoning and end incomplete with no visible text. Fix: clamp or re-resolve the budget after the cap.
  • The summary pass now blocks the async handler on the streamed path. generate_summary (src/server/routes/responses_compact.rs:284) drains the worker receiver synchronously, and its cancellation flag is never set (src/server/model_provider.rs:1921-1930). Before this PR, a streamed /v1/responses request never blocked its handler. Now a streamed request that compacts holds a tokio worker for up to 1024 summary tokens, and a client that disconnects still pays for the full pass. Non-streamed generation and /v1/responses/compact already behave this way, and slot admission bounds it.
  • Counts run before slot admission. apply_auto_compaction counts before the can_accept_request() check in non_stream_create_response and stream_create_response. A text count is executor-side tokenization. A media count goes through the worker queue (count_prompt_tokens_with_media, src/server/model_provider_prompt_count.rs:65). When every slot is busy, one request with compact_threshold: 1 can still run 1 + ceil(log2(boundaries)) worker counts before the summary pass returns 503. This makes an existing ungated path (/v1/responses/input_tokens) larger; it does not add a new one. A cheap fix is to call can_accept_request() at the top of apply_auto_compaction.

LOW

  • apply_auto_compaction clones the whole request, including a large input, only to clear it (src/server/routes/responses_auto_compact.rs:175).
  • When compaction fails (for example, a small-context model whose 128-token automatic summary hits length), the request fails and does not fall back to generating uncompacted. This is the documented decision, but a client with a low threshold then gets errors.

Checked, no issue found

  • Cost per request is bounded: 1 count, then ceil(log2(boundaries)) counts in the binary search, one summary generation with its own admission check, and 1 final count. A chain with a tiny threshold compacts again on each hop, but each hop costs the same bounded amount, which is no more than calling /compact and then /responses.
  • context_management validation has no panic path. as_u64 rejects floats and negatives, the range is 1..=1e8, the array length is checked, and a non-object entry fails the type check. /input_tokens ignores the field, so it cannot trigger compaction.
  • Cap arithmetic: saturating_sub plus the remaining == 0 guard. The summary-side prompt + max_tokens is bounded by the 1024 clamp. --context-shift is unaffected because the cap applies only to context_management requests, as documented.
  • The prepend_compaction_item dedupe compares against a server-generated cmp_<uuid>. A client-supplied id stays in input and never reaches output.
  • Events are sent inside the stream task after response.in_progress. No lock is held across an await.
  • Storage: the stored input is only the instructions. Conversation transcripts grow per turn, as they did before, within the byte-budget LRU.

Validation: responses_auto_compact (13), responses_compact (28) and streaming_responses (4) pass. cargo clippy -p mlxcel --lib --tests -D warnings and cargo fmt --check are clean.

Two MEDIUM findings from the #2522 security review (#2397).

The reasoning budget was validated by resolve_request_budget against the uncapped max_tokens. After cap_output_tokens lowered the limit, a context_management reply near the window could spend the whole capped output on reasoning. Both arms now clamp a limited budget to one token below the capped max_tokens: the budget <= max_tokens relation from thinking_budget.rs, plus one token for visible output. Requests without context_management are untouched.

apply_auto_compaction now checks can_accept_request() before any token count. A busy server returns the arms' existing 503 instead of first running counts that, for media prompts, go through the worker queue.

Tests: the budget is clamped when the cap lands below it, and a server with no free slot returns 503 on both arms with no generation. Filters responses_auto_compact (15), responses_compact (28), server::routes:: (508), server::responses (74), streaming_responses (4); clippy lib+tests and fmt clean.
@adrysn adrysn added status:done Completed and removed status:review Under review labels Oct 21, 2026
@adrysn
adrysn merged commit e160079 into main Oct 21, 2026
27 of 28 checks passed
@adrysn
adrysn deleted the feature/issue-2397-auto-compaction branch October 21, 2026 12:30
@inureyes inureyes added this to the 0.8 milestone Nov 30, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area:inference Generation, sampling, decoding (incl. speculative, DRY) priority:low Low 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: Add Responses API conversation compaction

2 participants