Repository navigation
feat(server): add automatic Responses compaction (phase B) - #2522
Merged
Merged
Conversation
…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.
This was referenced Oct 21, 2026
Member
Author
Implementation Review SummaryIntent
Findings Addressed
Remaining Items
Verification
|
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.
Member
Author
|
Security and performance review of phase B at 29dfec0. No CRITICAL or HIGH findings, so no commits. MEDIUM (not fixed)
LOW
Checked, no issue found
Validation: |
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Phase B of #2397, after phase A (#2520): automatic compaction on
/v1/responsesthroughcontext_management, the output cap at the remaining context, and the streamedmlx.compaction.*events.Behavior
context_management: [{"type":"compaction","compact_threshold":N}]on/v1/responsesand/responses. The rendered input (chainedprevious_response_id/conversationhistory plusinput, capsules expanded) is counted on the/v1/responses/input_tokenspath. At the threshold, phase A'scompact_historyruns with the sameResponsesCompactionBackendand defaultkeep_tokens, and generation runs on instructions + summary + retained turns. Summary budget is upstream's automatic one: context/16, clamped to 128..1024.outputstarts with thecompactionitem.usagecounts the final generation only, as upstream does.output[0]. The nextprevious_response_idhop therefore assembles instructions + capsule + tail, replays the summary, and compacts again only at the threshold. Aconversationtranscript appends the new input plus output.mlx.compaction.started(input_tokens) andmlx.compaction.completed(input_tokens_before/input_tokens_after), in upstream's payload shape plussequence_number, come right afterresponse.in_progress. The capsule follows asoutput_item.added/doneatoutput_index0, and generated items start at 1.response.completedlists the same capsule once, including the tool-streamed path from feat(server): stream tool-call arguments incrementally on Chat and Responses #2504.[]/null: no extra count and no cap, and the response is unchanged.Decisions to review
>=, 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.incompleteapply only tocontext_managementrequests. Today everylengthstop reportscompleted, and with--context-shiftgeneration may run past the window. A general cap would change both.incomplete_details.reasonismax_output_tokens, the OpenAI and upstream value, not a literallength. The streamed reply then ends withresponse.incomplete. As in OpenAI's shape,completed_atis null and the cut-off message item isstatus: "incomplete", in the final object and in its streamedoutput_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.ResponseStreamSendersends from the blocking task. A streamed overflow therefore returns 400exceed_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.context_length_exceeded. Every other compaction failure keeps phase A's error.context_managementreturns 400invalid_request_error: not an array, more than one entry (duplicates included), a type other thancompaction, or a threshold that is not an integer from 1 to 100000000.Test plan
cargo test --profile test-fast -p mlxcel --libfilters:responses_auto_compact(15, including the reasoning-budget clamp, the busy-server 503, theconversationpath and a streamed request withoutcontext_managementthat 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 --checkmlx-community/Qwen3-30B-A3B-4bit. Media and video prompts withcontext_managementhave 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/messagesauto-compaction, the Codexcompaction_triggerinput, and multi-pass summarization. Follow-up: #2523.Closes #2397