Repository navigation
feat(server): fold over-window histories in bounded compaction passes - #3751
Merged
inureyes merged 4 commits intoDec 4, 2026
Merged
Conversation
Automatic Responses compaction (context_management) now folds a summarized prefix that does not fit one summary pass in at most eight passes, so a history longer than the context window compacts instead of failing with context_length_exceeded. Each pass summarizes the instructions, the previous handoff and the longest run of whole turns that fits, split only at the existing safe boundaries, and must come out shorter than its input. A turn too long for any pass, a newest turn that alone fills the window, or a prefix that needs more than eight passes still fails with context_length_exceeded. The automatic summary budget follows upstream: 1/8 of the window (256 to 1024 tokens, was 1/16, 128 to 1024), and a summary cut at it is retried once with twice the budget, at most 1/4 of the window, before failing with 502. Every pass reserves room for the retry budget. POST /v1/responses/compact keeps its one-window, one-pass contract, its max_output_tokens budget and no retry. Part of lablup#2523.
Automatic compaction with multi-pass accepted any history length and only failed at the eighth pass, so a crafted history could cost eight summary generations plus a re-tokenization of an unbounded prefix per search step. A history above nine context windows can never fold (each pass reads at most one window and the retained turns fit one more), so it is now refused with context_length_exceeded before any count or generation.
Member
Hardening reviewReviewed against the PR body and issue #2523 (multi-pass acceptance criterion only; Chat Completions / Messages and Findings
Fixes pushed
Validation (on the merged tree)
Residual notes
|
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.
Summary
Part of #2523: the multi-pass part, with the automatic summary budget it needs.
Automatic compaction on
/v1/responses(context_management) now folds a history longer than the context window in bounded summary passes instead of refusing it withcontext_length_exceeded. The automatic summary budget moves to upstream's (1/8 of the window, 256 to 1024 tokens, with one retry at twice that, at most 1/4 of the window), because the later passes also re-summarize the previous handoff and ran past the old 1/16 budget on a real model.POST /v1/responses/compactis unchanged: one window, one pass, the client'smax_output_tokens, no retry. Chat Completions / Messages compaction and the Codexcompaction_triggeritem are left for follow-up PRs; both build on this pass loop.Behavior change: an automatic compaction whose input is under the window but whose summarized prefix does not fit one summary pass (prompt plus budget above the window) used to fail with 400
context_length_exceeded; it is now folded in passes like an over-window history. The automatic summary budget also changes, from 1/16 of the window (128 to 1024 tokens) to 1/8 (256 to 1024) with one retry. No CHANGELOG entry is included, since the changelog is written at release time.#2523 acceptance criteria
/v1/chat/completionsand/v1/messagescompact an overflowing history and honorcontext_management, with route tests: follow-up PR.compaction_triggerreturns one compaction item on both arms, with route tests: follow-up PR.context_length_exceeded: this PR.docs/responses-api.mdanddocs/server-features.mdupdated: this PR updates both for multi-pass; each follow-up updates them for its part.What changed
compact_history(src/server/responses_compaction.rs): when the summarized prefix does not fit one summary pass and the caller allows it (CompactionLimits::multi_pass), the prefix is folded in at mostMAX_SUMMARY_PASSES(8, the bound the issue names) passes. Each pass summarizes the system/developer messages, the previous pass's handoff (as an assistant message), and the longest run of whole turns at the front of what is left that still fits one pass. Runs end only at the existingsafe_boundaries(before a user turn, or after the output that closes the last open call) or at the end, so afunction_callnever leaves itsfunction_call_output, and every pass consumes at least one turn. The end of each run is binary-searched (a longer run never fits where a shorter one does not), so a pass costsO(log n)counts.context_length_exceeded, none of which replaces context: a turn too long for any pass (from the second pass on, the message names the previous handoff plus the next turn, since either may be what does not fit); a pass whose handoff is not shorter than what it read; a prefix that needs more than 8 passes; the instructions plus newest turn alone filling the window (checked before any pass runs); a compacted result that leaves no room for output.CompactionBackendgainssummary_fits(head): the headroom testgenerate_summaryalready makes (rendered summary prompt plus the largest budget the pass may use against the window), without generating.ResponsesCompactionBackendimplements it on the count path (so a media prompt is counted on the worker), sharing onesummary_requestbuilder withsummarize.src/server/routes/responses_auto_compact.rs):auto_summary_tokensis(window / 8).clamp(256, 1024)(was(window / 16).clamp(128, 1024)), and the newauto_retry_tokensismin(window / 4, 2 × budget), never below the budget, as upstream's automatic path sizes them.ResponsesCompactionBackendgainsretry_tokens; when a summary generation stops atlengthand the retry budget is larger,summarizeruns it once more with the retry budget and sums the usage of both.summary_fitsreserves the retry budget, so a retry never overflows the window. A summary cut again on the retry is still 502server_error, with a message that names both budgets instead of telling the client to raisemax_output_tokens(which does not set the automatic budget).POST /v1/responses/compactpassesretry_tokens: Noneand keeps its message and behavior.apply_auto_compactionsetsmulti_pass: true.POST /v1/responses/compactsetsmulti_pass: falseand keeps its one-window, one-pass contract (history_over_one_window_fails_without_generatingstill holds), as upstream's standalone compact endpoint does.docs/responses-api.md(Automatic compaction: budget and retry, the pass loop and its failures, the "same as compact" sentence no longer claims the same failures; the failure table; the "Not implemented" line),docs/server-features.md.Deviations from the issue and why
compaction_triggerare separate follow-ups (see the checklist); the last of them will close the issue./v1/responses/compactstill requires its input to fit one window, matching upstream ("The standalone/responses/compactendpoint still requires its input to fit").compaction.pyno longer has a fixed cap ("the number of passes is bounded by the input"); here every pass must still consume at least one turn and shorten its input, and the cap stays as a hard stop on summary generations per request.retry_tokens = ... if automatic else summary_tokens)./compactupstream), so they are left for a separate PR; here such a summary is 502 and such a turn iscontext_length_exceeded.Review checklist
multi_passon; exactlyMAX_SUMMARY_PASSESpasses succeed and one more turn fails; a turn too long for any pass fails without summarizing; a later turn that fits alone but not beside the previous handoff fails after the first pass with the handoff named; a newest turn that fills the window fails before any pass; a result that still fills the window after every pass fails; a history under the window too long for one pass is folded; a pass that does not shorten its input fails; an empty pass summary is a summary failure; tool groups are never split across passes; withmulti_passoff a history over one window still fails before summarizing. Budget table from window 0 to 2^20 (256/256 up to 1024 at 1/8, retry capped at 1/4 and never below the budget); a cut summary retried once at twice the budget succeeds; cut twice is 502 without a third generation;/compactdoes not retry.O(log n)counts per pass and at most 8 passes; every count is bounded by one window. Every automatic compaction now runs one extrasummary_fitsrender and count of the summarized prefix before summarizing; a retry is at most one extra generation per pass.CompactionLimitsis built in two places (apply_auto_compaction,POST /v1/responses/compact) and both setmulti_passexplicitly;ResponsesCompactionBackendis built in the same two places and both setretry_tokensexplicitly;CompactionBackendhas one production implementor (ResponsesCompactionBackend) and the test fake, both implementsummary_fits.summary_fitsuses the same max-token resolution and window asgenerate_summary's pre-generation check.generate_summaryhas one caller (summarize) and now reports alengthfinish instead of refusing it, so the refusal moved intosummarizewith the same/compactwording.context_length_exceeded.cargo fmt --all -- --checkclean.Verification
NVIDIA GB10 (sm_121), driver 580.178.04, CUDA 13, rustc 1.97.1. Base
9402cf893; commit treeb75db775. fmt,check_used_by.py,check_used_by_test.sh,check_env_var_docs.pyand theresponses_tests ran onb75db775. Clippy, the full gate and the live binary ran on42bc549a, which differs from it only by a CHANGELOG entry since removed (no code, test or build script reads CHANGELOG.md). Every other command below ran on42bc549aunless it says otherwise.9402cf893plus only the route tests of this commit (responses_auto_compact_tests.rswithout the budget-table unit test, which names functions main does not have, andresponses_compact_route_tests.rs):cargo test --locked --profile test-fast --features cuda --lib -- responses_auto_compact_tests responses_compact_route_tests→ 28 passed, 3 failed:a_history_over_the_window_is_folded_in_bounded_passes(400input is 2621 tokens, above the 2048-token context window),a_summary_cut_at_its_budget_is_retried_once_at_twice_the_budget(502the summary reached max_output_tokens (256)),a_summary_still_cut_after_the_retry_is_a_bad_gateway(the message tells the client to raisemax_output_tokens). The new/compacttest (a_summary_cut_at_max_output_tokens_is_refused_without_a_retry) passes on the base, as it should: it pins the unchanged contract.CompactionLimits::multi_pass, which only this commit adds, so they were run against the previous revision of this branch (multi-pass without the budget change, the retry and the second-pass message), with every test of this commit except the budget table: 298 passed, 4 failed.a_later_pass_whose_handoff_and_turn_do_not_fit_names_the_handofffails there (a turn of the history is too long for one summary pass), the two retry route tests fail as above, andresponses_background_cancel_tests::cancel_while_in_progress_returns_the_partial_outputfailed once there (conversation; it passed in an identical earlier run of that revision and in every run on this commit);a_compacted_result_that_still_fills_the_window_failsanda_history_under_the_window_too_long_for_one_pass_is_folded_toocover multi-pass branches and pass on both.cargo test --locked --profile test-fast --features cuda --lib -- responses_→ 303 passed, 0 failed (on42bc549a, and three times onb75db775). One further run onb75db775failed onlyresponses_background_route_tests::previous_response_id_waits_for_the_job_and_delete_refuses_an_active_job(conversation), a background-job timing test this change does not touch;-- responses_backgroundthen passed 53/53 five times in a row, and the full gate (one test thread) passed it.cargo fmt --all -- --check: clean.cargo clippy --locked --workspace --all-targets --features cuda -- -D warnings: clean.python3 scripts/ci/check_used_by.py,bash scripts/ci/check_used_by_test.sh,python3 scripts/ci/check_env_var_docs.py: pass.make verify-test-cuda(cargo test --workspace --profile test-fast --features cuda --no-fail-fast -- --test-threads=1): 207 test binaries, 18,908 passed, 2 failed, 578 ignored; themlxcellib binary 14,309 passed, 0 failed, 310 ignored. The two failures aremlx_test_guard_coverage::mlx_evaluating_lib_tests_take_mlx_test_guard(flags onlysrc/vision/encoders/nemotron_h_nano_omni_tests.rs:276) andstep3p7_parity::text_decode_delegates_sequence_local_native_batching(assert!(!wrapper.supports_padded_prefill())); both fail the same way on unmodified9402cf893(same build directory, those two targets), neither file is touched here, and both were pre-existing on the base; currentmainfixes both (feat(speculative): add DeepSeek-V4.1 bundled DSpark drafter (#3262) #3686, test: restore MLX guard scan and no-GPU catalog test gates #3765).git merge-tree --write-tree origin/main HEAD: merges cleanly onto currentorigin/main(5bf7b8628). On the merged tree, the Python tooling tests (python3 -m unittest discover -s tests -p 'test_*.py'), thescripts/cichecks CI runs andcargo fmt --all -- --checkpass.Live server
Both binaries built with
cargo build --locked --release --features cuda --bin mlxcel(different sha256), the fix binary from this commit's tree.mlxcel serve -m Qwen3-4B-Instruct-2507-NVFP4 --ctx-size 8192 --parallel 1; the checkpoint is the llmcompressor NVFP4 export ofQwen/Qwen3-4B-Instruct-2507, snapshot revision3b387679aa88ca4393ab6efc34d71616b61bc57e. Requests on/v1/responseswithcontext_management: [{"type":"compaction","compact_threshold":4000}],max_output_tokens: 64,temperature: 0. Each case ran twice, non-streamed and streamed (4 requests per case and binary).9402cf893, runs 1 and 2, both armscontext_length_exceeded:input is 10590 tokens, above the 8192-token context window(4/4)[compaction, message], answer "The project code name is BLUE HERON." (4/4); 2 passes each (5282 → 464-532, then 5750-5818 → 511-760 tokens); 10590 → 533-782 tokens; 23-31 sinput is 21636 tokens, above the 8192-token context window(4/4)context_length_exceeded:the instructions and the newest turn alone are 11078 tokens, which leaves no room in the 8192-token context window, before any pass (4/4)context_length_exceeded:the summary request needs 8059 prompt tokens plus 512 output tokens, above the 8192-token context window(4/4)[compaction, message], "The project code name is BLUE HERON." (4/4); 2 passes (5282 → 463-494, 3111-3142 → 549-570); 7952 → 571-592 tokens; 22-23 sNo pass needed the retry at this window: every handoff (463-760 tokens) fit the first 1024-token budget. With the 1/16 budget this PR replaces (512 at 8192), the same A requests ended in 502 at pass 2 in 3 of 4 requests (
the summary reached max_output_tokens (512) before it finished).The retry path was exercised on the same binary and checkpoint at
--ctx-size 4096(budget 512, retry 1024), where one 1.7K-token turn takes most of a pass. main refused all 12 requests with 400 (above the 4096-token context window). With this commit, B was refused before any pass as above (4/4). A and C ran one turn per pass, and most passes reached 512 tokens and were retried (loggedsummary reached its budget; retrying once). 6 of the 8 A/C requests reached 1024 on a retry at pass 4, 5 or 6 and ended in 502server_error(the compaction summary reached its 512-token budget, and its 1024-token retry, before it finished; original context preserved, 89-159 s). The other 2 (C, streamed) completed after 5 passes (7952 → 772 and 838 tokens) but had lost the first turn's fact: their answers were "Project code name: Aurora." and "The project code name is not provided in the given context."Limits
compaction_triggerare not in this PR.