Repository navigation
Add a stability-motivated prefill ceiling to history compaction - #2231
Conversation
core#2172 found a Metal command-buffer OOM during prefill at an 8,518-token prompt, with n_ctx granted at 32,768 — the context-window budget maybe_summarize_history already checks (~30K tokens on that machine) was nowhere near full when the backend failed. That budget protects against ContextOverflow, not against submitting a prefill large enough to risk a backend failure; those are different failure modes with no reason to share a threshold. Add PREFILL_STABILITY_CEILING (6,000 tokens) as a second, independent gate in maybe_summarize_history, alongside the existing window budget. Either gate tripping triggers summarization. This constant is explicitly provisional. Investigation attempted to reproduce #2172's OOM on matching 16 GB hardware with powermetrics GPU telemetry to measure the real failure threshold; three full eval-matrix runs — including prompts up to 9,469 tokens, larger than the original failure — decoded cleanly with no backend error. The original OOM's exact trigger remains unmeasured (likely allocator fragmentation state, concurrent GPU clients, or thermal/driver nondeterminism rather than prompt size alone). Given that, this ceiling sits with margin below the observed failure point rather than at a validated safe/unsafe boundary — a documented, cheap hedge, not a proven fix. Revise once a real repro pins the actual threshold. Co-Authored-By: Claude <[email protected]>
Code Review SummaryThis is a small, well-scoped, well-documented change: one new Verified independently: Requirements CheckPart 2 acceptance criteria (history compaction on shared-chat-node path):
Part 1 (memory-budget re-tuning) is explicitly and appropriately out of scope for this PR — documented as a negative result (3 clean eval-matrix runs exceeding the original 8,518-token failure point, no OOM reproduced) rather than an unfinished criterion. Not treated as missing/incomplete here. FindingsCritical Issues🔴 if history_tokens + system_tokens <= total_budget
&& history_tokens <= PREFILL_STABILITY_CEILING
{
return Ok(());
}Gate 1 correctly sums Recommendation: change the comparison to Engineering principle: a guard's comparison basis must match its documented purpose; a safety check whose own justification doc admits the dominant term is missing from the check isn't actually providing the safety property it claims to. Suggested Improvements🟡 The one new test proves gate 2 fires when gate 1 has headroom. There's no test for:
Given this is a narrow, single-purpose gate change, one happy-path test is thin coverage for a boundary condition with 🟡 Doc comment vs. implementation drift risk — Since the doc comment is this thorough and specific about why the ceiling should bound total prefill size, a future reader who trusts the comment over the code will misjudge what protection exists. If the omission of Nitpicks
Judgment Calls (non-blocking discussion)Provisional constant framing (6,000 tokens): The doc comment is honest about the constant being unvalidated — sized with margin below the observed 8,518-token failure point, chosen despite three clean runs up to 9,469 tokens (larger than the failure point) with no reproduction. That's a reasonable hedge-under-uncertainty stance and is clearly labeled as such, not oversold as a measured threshold. Reasonable people could pick a different number (e.g., closer to 8,000, closer to the failure point but still with headroom) but 6,000 isn't indefensible given the stated logic — "cheap to give up unused window headroom" is a legitimate cost/benefit framing when history rarely needs more than a few thousand tokens anyway. Treating this as a design opinion (🟢), not a blocker. Interaction with #2226/#2228 recovery: #2226 made decode failures recoverable (poison + rebuild) and #2228 extended that further, so the failure mode this ceiling hedges against is no longer a permanent outage — it's now a survivable, loud, single-turn cost. That changes the cost/benefit slightly: this gate is now belt-and-suspenders on top of backend-side recovery rather than the only mitigation. I'd still keep it — proactively avoiding a failure (and its associated turn cost + user-visible error + potential retry latency) is strictly better than only recovering from it gracefully when recovery is nearly free to add, and the two mechanisms operate at different layers (this is prevention, #2226/#2228 is graceful degradation). Not redundant enough to be worth ripping out, and the doc comment already acknowledges this framing ("recovery is now loud but still costs a turn"). Regression risk on normal usage: A 6,000-token ceiling is fairly aggressive relative to the ~30K window budget that was previously the only gate. For a typical single-session conversation, this could trigger summarization meaningfully more often than before — every session that accumulates >6K tokens of live history (not hard to hit with a few tool-heavy turns, given tool-call JSON now counts toward history_tokens per the pre-existing fix) now pays an extra inference call for summarization, plus loses some context fidelity earlier than strictly necessary for correctness. This is a real, measurable cost that trades off against the OOM hedge's value, and it's plausible many sessions will now summarize noticeably earlier than before with no OOM risk actually present (per Part 1's own negative-repro result). Worth watching in practice — if this turns out to fire too eagerly, the fix (per the Critical finding) will make it fire even more often once system_tokens is properly included, which raises the stakes on picking the right number. Not a blocker, but worth flagging as something to monitor post-merge. RecommendationREQUEST CHANGES — the mechanism and test are sound for what they cover, but the Critical finding (gate 2 omitting |
malibio
left a comment
There was a problem hiding this comment.
Automated pragmatic-code-review: REQUEST CHANGES (posted as a comment — GitHub blocks self-review on your own PR). Full findings in the review comment above. Critical: the new PREFILL_STABILITY_CEILING gate compares only history_tokens, omitting system_tokens, even though the doc comment's own rationale is bounding total prefill size submitted to Metal (and states the real system prompt is ~6,600 tokens, already over the 6,000 ceiling alone, with zero history).
Review on PR #2231 found the new gate compared only history_tokens against PREFILL_STABILITY_CEILING, but the actual prefill submitted to the engine is system prompt + history together — and the gate's own doc comment already noted the real tool-registered system prompt runs ~6,600 tokens, over the old 6,000-token ceiling on its own. As written the gate could never actually bound what gets prefilled. Changed the comparison to history_tokens + system_tokens (matching gate 1's basis) and raised the ceiling to 8,000 so a turn with little history and the real production system prompt doesn't spuriously trigger summarization every turn. Resized the existing test's history to still land above the corrected ceiling, and added a second test (stability_ceiling_counts_the_system_prompt_not_just_history) that directly exercises the exact regression the review found: history alone under the ceiling, but history + a realistic ~6,600-token system prompt over it. Addresses reviewer recommendations from PR review.
Addressed review feedback✅ Addressed:
⏭️ Skipped (with reasoning):
Full test suite re-verified after the fix: Re-Review DecisionDecision: RE-REVIEW NEEDED Rationale: The Critical finding required a real logic change (comparison basis) and a constant value change (6,000 → 8,000), not just a cosmetic fix — worth a second pass to confirm the corrected gate and its new/updated tests actually hold up, per the "Important architectural or design changes" criterion for re-review. |
Re-review: commit
|
malibio
left a comment
There was a problem hiding this comment.
Self-authored PR — GitHub blocks approving my own PR. Verdict per the review comment above: APPROVE. The Critical finding from the prior review (gate compared history_tokens only, not history+system) is correctly and completely resolved in commit 198027e — verified independently via hand-computed token arithmetic for both tests and by actually running the full test suite (542 lib tests + integration tests, 0 failures), clippy (-D warnings, clean), and cargo fmt --check (clean). No new issues, no scope creep.
Summary
Addresses #2227 (the two follow-up items #2226 deliberately deferred from #2172). This PR ships Part 2 (history compaction) and documents a negative result on Part 1 (memory-budget re-tuning) rather than guessing at a constant with no data behind it.
Part 1: memory-budget re-tuning — could not reproduce, no change made
Attempted to reproduce #2172's Metal OOM on matching 16 GB hardware, with GPU telemetry via
powermetricsto measure the actual peak allocation (the open question from #2172: does compute-buffer cost scale with batch size alone, or also withn_past/KV depth as the issue's turn-4-vs-turn-10 pattern suggested).Result: could not reproduce. Three full
bun run eval:agentruns against a fresh daemon on this 16 GB machine, matching #2172's repro steps exactly:All three runs decoded prompts larger than #2172's 8,518-token failure point, with zero
kIOGPUCommandBufferCallbackErrorOutOfMemoryoccurrences and no cascading empty-tool-call pattern. Thepowermetricscapture itself didn't produce usable telemetry (privileged-tool access wasn't available in this environment), so there's no direct GPU memory measurement — but three clean runs past the original failure size is itself informative: the OOM does not appear to be a deterministic function of prompt size on this hardware. It more likely depends on transient state (Metal allocator fragmentation, other GPU clients, thermal/driver conditions) that wasn't present during this investigation.No change to
COMPUTE_RESERVE_BYTESorPREFILL_BATCH_TOKENS. Changing either without a reliable repro would be exactly the guesswork #2172 and #2227 both flagged against. This needs either real GPU telemetry from a machine that's actively reproducing the failure, or enough live-fleet occurrences to characterize the trigger statistically.Part 2: history compaction — shipped
Independently of whether Part 1's OOM reproduces, this investigation surfaced a real, fixable gap:
maybe_summarize_history(packages/agent/src/local_agent/agent_loop.rs) was already correctly wired into the ReAct loop and correctly counts tool-call JSON — but its only gate budgets against the model's context window (~30K tokens on #2172's hardware), not against what's safe to submit in a single prefill. At #2172's failure point (8,518 tokens), that budget check had massive headroom to spare; compaction had no reason to trigger.Added
PREFILL_STABILITY_CEILING(6,000 tokens) as a second, independent gate: either the window budget or the stability ceiling tripping now triggers summarization. This is explicitly documented in-code as provisional — sized with margin below the observed 8,518-token failure point, not derived from a validated safe/unsafe boundary (see Part 1). It's a cheap hedge — the shared-chat-node pattern that triggered #2172 rarely needs more than a few thousand tokens of live history to function — not a proven fix.Test plan
summarization_triggers_on_stability_ceiling_despite_spacious_window— proves the new gate fires even when the context-window budget has ample room (mirrors Metal OOM on large prefill poisons the backend permanently: agent silently returns zero tool calls until daemon restart #2172's exact scenario: largen_ctx, moderate history)cargo test -p nodespace-agent— 541 passed (2 new vs. prior baseline of 539), no regressionsbun run test:all— 227 frontend files + full Rust workspace, all greenbun run quality:fix— cleanFollow-up
If a live OOM repro becomes available (production telemetry, or a machine that reproduces it reliably), re-derive
PREFILL_STABILITY_CEILINGfrom real measurement rather than the provisional value here — the in-code doc comment on the constant links back to this PR's findings for that purpose.Co-Authored-By: Claude [email protected]