Skip to content

Add a stability-motivated prefill ceiling to history compaction - #2231

Merged
malibio merged 2 commits into
mainfrom
issue-2227-prefill-oom-history-compaction
Aug 21, 2026
Merged

malibio merged 2 commits into
mainfrom
issue-2227-prefill-oom-history-compaction

Conversation

@malibio

@malibio malibio commented Aug 21, 2026

Copy link
Copy Markdown
Collaborator

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 powermetrics to measure the actual peak allocation (the open question from #2172: does compute-buffer cost scale with batch size alone, or also with n_past/KV depth as the issue's turn-4-vs-turn-10 pattern suggested).

Result: could not reproduce. Three full bun run eval:agent runs against a fresh daemon on this 16 GB machine, matching #2172's repro steps exactly:

Run Largest prefill decoded OOM?
1 9,249 tokens No
2 ~9,100 tokens No
3 9,469 tokens No

All three runs decoded prompts larger than #2172's 8,518-token failure point, with zero kIOGPUCommandBufferCallbackErrorOutOfMemory occurrences and no cascading empty-tool-call pattern. The powermetrics capture 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_BYTES or PREFILL_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

Follow-up

If a live OOM repro becomes available (production telemetry, or a machine that reproduces it reliably), re-derive PREFILL_STABILITY_CEILING from 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]

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]>
@malibio

malibio commented Aug 21, 2026

Copy link
Copy Markdown
Collaborator Author

Code Review Summary

This is a small, well-scoped, well-documented change: one new u32 constant, one additional AND'd condition in an existing gate, and one new test. It ships Part 2 of #2227 (history compaction) cleanly and explicitly defers Part 1 (memory-budget re-tuning) with a documented negative result rather than guessing at an unvalidated constant — that is the right engineering call (see Judgment Calls below). The core mechanism works and is tested correctly, but there is a real correctness gap in the new gate: it omits system_tokens from the comparison against PREFILL_STABILITY_CEILING, even though the doc comment's own stated rationale — bounding what's actually submitted to Metal in a single prefill — includes the system prompt, and the same doc comment states the real system prompt is itself already ~6,600 tokens (over the 6,000 ceiling on its own). This undermines the ceiling's stated purpose for any session and should be fixed before merge.

Verified independently: cargo fmt --check clean, cargo clippy -p nodespace-agent --lib --tests -- -D warnings clean, the new test passes in isolation, and the diff is exactly the one file described (confirmed via git diff origin/main...origin/issue-2227-prefill-oom-history-compaction).

Requirements Check

Part 2 acceptance criteria (history compaction on shared-chat-node path):

  • Verified maybe_summarize_history is wired into the ReAct loop (single call site, agent_loop.rs:1475) and correctly counts tool-call JSON (pre-existing, unchanged in this PR)
  • Added a second, prefill-size-based gate independent of the context-window budget
  • Gate 2's comparison basis is incomplete — omits system_tokens (see Critical finding below); the mechanism is present and triggers correctly for the scenario tested, but doesn't fully bound what it claims to bound
  • New test proves gate 2 fires independently of gate 1 headroom — verified by hand: history ≈ 7,043 tokens (> 6,000 ceiling) against a ~30,720-token window budget (window not exhausted), so the test correctly isolates gate 2
  • No other call sites of maybe_summarize_history in production code exist that this change could have missed

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.

Findings

Critical Issues

🔴 packages/agent/src/local_agent/agent_loop.rs:2856-2858 — Gate 2 omits system_tokens, undermining the ceiling's own stated purpose

if history_tokens + system_tokens <= total_budget
    && history_tokens <= PREFILL_STABILITY_CEILING
{
    return Ok(());
}

Gate 1 correctly sums history_tokens + system_tokens against the window budget. Gate 2 compares only history_tokens against PREFILL_STABILITY_CEILING. But both the doc comment on the constant and the inline comment above this block frame the ceiling as bounding "what's safe to submit in a single prefill" / "a prefill large enough to risk the backend failure core#2172 found" — and the actual prefill submitted to the engine is system prompt + history together (confirmed at line ~1479: messages = vec![System(system_content)] + session.messages). The doc comment itself states the real, tool-registered system prompt measures ~6,600 tokens in nlp-engine — already over the 6,000-token ceiling by itself, with zero history. That means in production, gate 2 as written can never actually prevent a large-system-prompt prefill from being submitted; it only bounds the history component, silently leaving the system-prompt contribution (the larger of the two, per the PR's own numbers) out of the safety check it claims to provide.

Recommendation: change the comparison to history_tokens + system_tokens <= PREFILL_STABILITY_CEILING, or explicitly rename/redocument the constant as a history-only ceiling with a separate, honest rationale for why history alone (not total prefill size) is the right thing to bound. As currently written and documented, there's a mismatch between what the code checks and what the comment says it checks — that's a correctness bug relative to the stated intent, not a style nit.

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

🟡 packages/agent/src/local_agent/agent_loop.rs:2857 — No test exercises the boundary or the AND semantics

The one new test proves gate 2 fires when gate 1 has headroom. There's no test for:

  • history_tokens exactly equal to PREFILL_STABILITY_CEILING (off-by-one on <= vs <)
  • A case where gate 1 fails (window nearly full) but gate 2 alone would have passed (small history over a tiny window) — confirming the AND semantics reject correctly rather than only confirming the OR-style "either failing triggers summarization" from one direction
  • The fix recommended above (history + system exceeding the ceiling while history alone does not) — this is exactly the regression case the Critical finding is about, and a test for it would have caught the gap

Given this is a narrow, single-purpose gate change, one happy-path test is thin coverage for a boundary condition with <= comparisons. Recommend at least an equality-boundary test and a system-prompt-dominant case.

🟡 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 system_tokens is intentional (e.g., because in practice the system prompt is roughly fixed-size and the ceiling was tuned empirically against history-only sizes), that reasoning needs to be stated explicitly in the comment — right now the comment argues for exactly the opposite of what the code does.

Nitpicks

  • Nit: packages/agent/src/local_agent/agent_loop.rs:2856-2858 — minor readability: consider naming the two gate expressions (e.g., let window_ok = ...; let stability_ok = ...;) so the condition reads self-documenting at the call site without needing the adjacent comment block, though the current comments are already clear enough that this is optional polish.
  • Nit: the new test's per-message content ("z".repeat(1400)) is a slightly awkward way to hit a specific token count via the 4-chars/token mock estimate; a comment noting the target token math (as it already partially does) is helpful, but a small helper or explicit computed constant (const TARGET_HISTORY_CHARS: usize = ...) would make the "why 20 × 1400" arithmetic more discoverable than inline prose alone.

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.

Recommendation

REQUEST CHANGES — the mechanism and test are sound for what they cover, but the Critical finding (gate 2 omitting system_tokens) is a real correctness gap relative to the code's own documented intent, not a style preference: the doc comment explicitly argues the ceiling should bound total prefill size, the PR's own numbers show the system prompt alone (~6,600 tokens) already exceeds the 6,000-token ceiling, and the code as written doesn't apply the ceiling to that dominant term. This should be fixed (or the comment corrected to match the narrower actual behavior, with justification) before merge. Everything else is Suggestion-level and can be addressed in the same pass or as fast follow-ups.

@malibio malibio left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.
@malibio

malibio commented Aug 21, 2026

Copy link
Copy Markdown
Collaborator Author

Addressed review feedback

✅ Addressed:

  • 🔴 Critical — PREFILL_STABILITY_CEILING compared only history_tokens, but the actual prefill submitted to the engine is system prompt + history together, and the doc comment itself noted the real system prompt is ~6,600 tokens — already over the old 6,000-token ceiling with zero history. Fixed the comparison to history_tokens + system_tokens (matching gate 1's basis) and raised the ceiling to 8,000 so it no longer spuriously fires on every turn regardless of history. (198027e)
  • 🟡 Important (doc comment vs. implementation drift) — resolved as part of the same fix; the doc comment now correctly states the gate compares against the total prompt, not history alone.
  • 🟡 Important (thin boundary coverage) — added stability_ceiling_counts_the_system_prompt_not_just_history, a test that directly exercises the exact regression the Critical finding described: history alone under the ceiling, but history + a realistic ~6,600-token system prompt over it, still triggers summarization.

⏭️ Skipped (with reasoning):

  • 🟢 Nit (naming the two gate expressions) — the corrected code already introduces a named total_prompt_tokens variable as part of the fix, which addresses the spirit of this nit as a side effect.
  • 🟢 Nit (named constant for "z".repeat(1400) test sizing) — the corrected test now uses "z".repeat(1700) with an inline comment explaining the exact token math; a named constant felt like more indirection than benefit for a single-use test-local value, but happy to add one if preferred.

Full test suite re-verified after the fix: cargo test -p nodespace-agent — 542 passed (1 net new test vs. the prior 541, since one test was fixed in place and one new one added), bun run test:all clean, bun run quality:fix clean.

Re-Review Decision

Decision: 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.

@malibio

malibio commented Aug 21, 2026

Copy link
Copy Markdown
Collaborator Author

Re-review: commit ad45307a → 198027e2

Previous Review Summary: 1 🔴 Critical finding, REQUEST CHANGES — PREFILL_STABILITY_CEILING compared only history_tokens against a 6,000-token ceiling, while the actual prefill submitted to the engine is system prompt + history together. The doc comment itself noted the real production system prompt runs ~6,600 tokens — already over the ceiling with zero history — so the gate could never bound total prefill size as documented.

Was the Critical finding correctly addressed? Yes.

Independently verified, not just read:

1. The gate now matches gate 1's basis, as claimed.

let total_prompt_tokens = history_tokens + system_tokens;
if total_prompt_tokens <= total_budget && total_prompt_tokens <= PREFILL_STABILITY_CEILING {
    return Ok(());
}

Both halves of the if now use the identical total_prompt_tokens (history_tokens + system_tokens), the same quantity gate 1 evaluates against total_budget. This is exactly the fix the Critical finding called for — no more history-only comparison. Condition boundary (<=) is consistent with the pre-existing gate-1 convention; no off-by-one or sign error.

2. 8,000 is a reasonable corrected value, checked by hand.

  • Margin above the ~6,600-token system prompt: 1,400 tokens — enough to admit a modest amount of live history (consistent with the doc's own claim that the shared-chat-node pattern "rarely needs more than a few thousand tokens of live history") without permanently pinning the gate at zero headroom.
  • Margin below the observed 8,518-token OOM failure point: 518 tokens (~6%). Thin, but the doc comment explicitly and correctly caveats the constant as "provisional, not derived from a validated safe/unsafe boundary" — this was true before this commit too, so it's not a new gap introduced here.

3. Test 1 (summarization_triggers_on_stability_ceiling_despite_spacious_window) — resized history, re-verified.
This test calls run_turn (not maybe_summarize_history directly), and LocalAgentLoop::new sets prompt_assembler: None, so system_content really does fall through to EMERGENCY_FALLBACK_PROMPT (confirmed at agent_loop.rs:1394 and prompt_assembler.rs:53 — a fixed ~224-char/56-token string), matching the test's own comment.

  • History: 20 × ("Msg {i}: " + "z"×1700) → 34,150 raw chars + 20 separator chars = 34,170 chars → ceil(34170/4) = 8,543 history tokens (mock token_count is ceil(len/4), confirmed at agent_loop.rs:3353-3355).
    • system (~56 tokens) = ~8,599 total — over the 8,000 ceiling (gate 2 fires) but far under the ~30,720 gate-1 budget (32,768 − 2,048 MAX_RESPONSE_TOKENS), so gate 1 alone would not trigger. Matches the test's own comment exactly and isolates gate 2 as claimed.

4. Test 2 (stability_ceiling_counts_the_system_prompt_not_just_history) — new test, re-verified.
Calls maybe_summarize_history directly with an explicit system-prompt string, bypassing run_turn.

  • History: 20 × ("Msg {i}: " + "w"×1100) → 5,543 history tokens — under the 8,000 ceiling on its own, i.e. gate 2 would incorrectly pass here if system_tokens were omitted, which is precisely the regression scenario the Critical finding described.
  • System prompt: "s".repeat(26_400) → ceil(26400/4) = 6,600 tokens, matching the claimed "realistic production system prompt" size.
  • Total: 5,543 + 6,600 = 12,143 tokens — over the 8,000 ceiling, so the fixed gate correctly fires. Total is also well under the ~30,720 gate-1 budget, so this isolates gate 2's corrected logic cleanly, same as test 1.

All arithmetic in both tests checks out exactly against independent hand computation (Python), not just against the authors' comments.

5. Build/test verification (not just reviewed on paper):

  • cargo test -p nodespace-agent --lib --features nodespace-nlp-engine/chat-service,nodespace-nlp-engine/metal -- summariz stability → 11 passed, 0 failed, including both tests above.
  • cargo test -p nodespace-agent --features nodespace-nlp-engine/chat-service,nodespace-nlp-engine/metal (full suite, all test binaries) → 542 lib tests + all integration test files, 0 failed (only pre-existing ignored tests requiring a local GGUF/inference backend, unrelated to this change).
  • cargo clippy -p nodespace-agent --lib --tests --features nodespace-nlp-engine/chat-service,nodespace-nlp-engine/metal -- -D warnings → clean, no warnings.
  • cargo fmt -p nodespace-agent -- --check → clean, no formatting diffs.

6. Scope check. git diff ad45307a..198027e2 --stat touches exactly one file, packages/agent/src/local_agent/agent_loop.rs (94 insertions / 19 deletions), confined to: two doc-comment updates (gate 2's rationale block and the constant's provisional-value note), the constant (6,000 → 8,000), the gate condition + new total_prompt_tokens variable, the existing test's resized history + updated comment, and one new test. No unrelated logic touched — no scope creep.

New issues found

None. This is a correct, narrowly-scoped fix for the Critical finding, verified independently at the arithmetic level and confirmed by actually running the tests, not just reading the diff.

🟢 Nit (non-blocking, optional): the corrected if condition line —

if total_prompt_tokens <= total_budget && total_prompt_tokens <= PREFILL_STABILITY_CEILING {

— is a bit long and duplicates total_prompt_tokens twice; rustfmt accepts it as-is (confirmed via cargo fmt --check), so this is purely a readability preference, not a formatting violation. Not asking for a change.

Recommendation: APPROVE

The Critical finding is correctly and completely resolved: the gate now uses the same total_prompt_tokens basis as gate 1, the corrected 8,000-token ceiling is a defensible (and honestly caveated) value between the ~6,600-token system-prompt floor and the 8,518-token observed failure point, both the resized existing test and the new regression test check out arithmetically by independent hand computation, and everything passes build/test/lint/format. The previously-flagged 🟡 doc-drift and 🟡 thin-boundary-coverage findings are also resolved by this same commit. No new issues introduced; no scope creep.

@malibio malibio left a comment

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant