Skip to content

Count tool-call argument JSON in history token budget; remove redundant summarization gate - #2225

Merged
malibio merged 1 commit into
mainfrom
issue-2197-history-budget
Aug 21, 2026
Merged

malibio merged 1 commit into
mainfrom
issue-2197-history-budget

Conversation

@malibio

@malibio malibio commented Aug 21, 2026

Copy link
Copy Markdown
Collaborator

Summary

maybe_summarize_history estimated history tokens from msg.content only. A tool-call assistant turn carries its signal in tool_calls[].arguments_json — content is empty by construction — so up to MAX_RESPONSE_TOKENS (2,048) of JSON per tool call went uncounted (entire markdown documents for create_nodes_from_markdown, etc.).

A second budget check then compared history against a static total_budget - SYSTEM_PROMPT_BUDGET (4,000), looser than the real tool-registered system prompt (~6,600 measured tokens per the nlp-engine N_CTX_MINIMUM test). That let the second check pass — and skip summarization — even in the corridor where the first check had already established the real prompt overflows the window.

Fix

  • Count each tool call's function_name and arguments_json into the history text used for token estimation.
  • Remove the second, redundant budget check. The first check (measured history + measured system prompt vs. the effective window) is the correct, authoritative gate; the second check's looser static budget was the source of the bug, not a useful backstop.
  • Drop the now-unused HISTORY_TOKEN_BUDGET const (inlined the equivalent bound in the one test that used it as a sanity ceiling).

Test plan

  • Added history_summarization_counts_tool_call_arguments: a history built entirely from empty-content tool-call turns whose argument JSON alone exceeds a reduced effective window (4096). Verified this test fails without the fix (confirmed by manually reverting just the history_text loop) and passes with it.
  • cargo test -p nodespace-agent --lib: 540 passed, 0 failed.
  • cargo clippy -p nodespace-agent -p nodespace-core -p nodespace-nlp-engine -p nodespace-types --all-targets -- -D warnings -D clippy::unused-async: clean.
  • bun run test:all: 227/227 frontend test files, all Rust workspace tests passing (pre-push gate).

Closes #2197

🤖 Generated with Claude Code

…nt summarization gate (closes #2197)

maybe_summarize_history estimated history tokens from msg.content only, but
a tool-call assistant turn carries its signal in tool_calls[].arguments_json
(content is empty by construction) — up to MAX_RESPONSE_TOKENS worth of JSON
per call went uncounted. A second budget check then compared against a
static total_budget - SYSTEM_PROMPT_BUDGET (4,000), looser than the real
tool-registered system prompt (~6,600 measured tokens), letting it pass and
skip summarization even after the first check had already established the
prompt overflows the window.

Fixes: count each tool call's function_name and arguments_json into the
history text; drop the second, redundant gate so the first (correct) check
against the measured system prompt is authoritative.

Co-Authored-By: Claude <[email protected]>
@malibio

malibio commented Aug 21, 2026

Copy link
Copy Markdown
Collaborator Author

Pragmatic Code Review — PR #2225

Review Type: Initial Review

Issue: #2197 — History token budget undercounts real prompt and refuses to summarize an over-budget conversation

Requirements Check

This is a bug report (no acceptance-criteria checklist) describing two concrete defects at agent_loop.rs's maybe_summarize_history:

  • ✅ Undercounting fixed: history_text now appends each tool call's function_name + arguments_json, not just msg.content. Tool-call assistant turns have empty content by construction (confirmed at ChatMessage::assistant_with_tool_calls), so this closes the exact gap the issue describes — up to MAX_RESPONSE_TOKENS (2,048) of uncounted JSON per call.
  • ✅ Redundant/looser second gate removed: the history_tokens <= history_budget check (where history_budget = total_budget - SYSTEM_PROMPT_BUDGET, a static 4,000) is deleted. The issue correctly identifies this as strictly looser than the first check once system_tokens (measured, ~6,600 in practice) exceeds the static SYSTEM_PROMPT_BUDGET constant — the first check is now the sole, correct gate.
  • ✅ Root cause addressed, not papered over: no feature flag, no dual-path, straight fix per repo's greenfield/no-back-compat standard.

Code Review Findings

No correctness, security, or quality issues found. Notes below are informational, not blocking.

🟢 Suggestion: pre-existing gap, not introduced here — summarization content path already correct
📁 packages/agent/src/local_agent/agent_loop.rs:2851-2882

Worth confirming (not a finding against this PR): the code that builds summary_input when summarization actually fires already special-cases empty-content tool-call turns and renders arguments_json (truncated to 120 chars) into the summary prompt. This PR only had to fix the trigger decision (token counting), not the summarization content itself — that path was already right. Good scoping; this PR doesn't touch code it didn't need to.

🟢 Suggestion: fallback branch (model_info() failure) has no direct unit coverage
📁 packages/agent/src/local_agent/agent_loop.rs:2806-2811

MockEngine::new always returns Ok(Some(spec)) with a fixed context_window: 8192, so every existing test (including the new one) exercises the Ok(Some(spec)) branch, never the _ => TOTAL_TOKEN_BUDGET fallback. This is a pre-existing gap (not introduced by this PR) and the fallback logic itself is untouched by this diff — not a blocker, just noting it's still an open corner if someone wants to close it later.

🟢 Suggestion: SYSTEM_PROMPT_BUDGET + 1 floor is now slightly vestigial
📁 packages/agent/src/local_agent/agent_loop.rs:2810

.max(SYSTEM_PROMPT_BUDGET + 1) guarded against history_budget (the deleted second check's budget) underflowing to zero via saturating_sub. With that second check gone, this floor only prevents total_budget itself from being pathologically tiny on a sub-4KB effective window — still a reasonable safety floor, just no longer serving its original purpose. Not worth a follow-up on its own.

Test Coverage

  • New test history_summarization_counts_tool_call_arguments (agent_loop.rs:4314-4381) is a strong, non-tautological regression test: it builds a history entirely from empty-content tool-call turns whose arguments_json alone exceeds a reduced 4096-token effective window, and asserts summarization still fires. Per the PR description this was manually verified to fail without the fix and pass with it — that's the right bar for a regression test.
  • Existing tests (history_summarization_trigger, summarization_triggers_on_reduced_effective_window, summarization_never_orphans_a_tool_result) still pass and remain meaningful after the refactor.
  • The HISTORY_TOKEN_BUDGET const removal cleanly avoided dead code (per this repo's no-#[allow(dead_code)] policy) by inlining the equivalent bound directly in the one test (history_summarization_reduces_token_count) that used it as a sanity ceiling — correct call; it wasn't providing enough value elsewhere to justify keeping as a named production constant that only a test consumed.

Verification Performed

  • cargo build -p nodespace-agent: clean, no warnings (confirms HISTORY_TOKEN_BUDGET removal left no dead code).
  • cargo test -p nodespace-agent --lib: 540 passed, 0 failed.
  • cargo clippy -p nodespace-agent -p nodespace-core -p nodespace-nlp-engine -p nodespace-types --all-targets -- -D warnings -D clippy::unused-async: clean.
  • bun run test:all (pre-push gate): 227/227 frontend test files, full Rust workspace suite green.
  • Manually reverted just the history_text tool-call accumulation and confirmed the new test fails without it, then restored and confirmed it passes — the test is confirmed to exercise the actual bug.

Recommendation

APPROVE

Minimal, correctly-scoped fix for a real, well-diagnosed bug. Single commit, root-cause fix with no compatibility shims, a regression test that's been verified to actually catch the regression, and no unrelated changes. Nothing here blocks merge.

@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: APPROVE (posted as a comment — GitHub blocks self-approval). Full findings in the review comment above.

@malibio

malibio commented Aug 21, 2026

Copy link
Copy Markdown
Collaborator Author

Address-Review Summary

The review returned APPROVE with zero 🔴 Critical or 🟡 Important findings. All three 🟢 Suggestions were explicitly marked non-blocking / informational by the reviewer:

  • ⏭️ Skip — "summarization content path already correct": confirms pre-existing code (not touched by this PR) already handles tool_calls correctly in the summary-building path. No action needed; this is a positive observation, not a defect.
  • ⏭️ Skip — "fallback branch (model_info() failure) has no direct unit coverage": pre-existing gap, not introduced by this PR, and the fallback logic itself is untouched by this diff. Out of scope for this bug fix; a follow-up test for that branch (if wanted) belongs in its own PR since it's unrelated to the token-undercounting bug this PR fixes.
  • ⏭️ Skip — "SYSTEM_PROMPT_BUDGET + 1 floor is now slightly vestigial": reviewer explicitly noted this is "not worth a follow-up on its own." The floor is harmless and still serves a (secondary) purpose of preventing a pathologically tiny budget.

No code changes made — nothing in the review required implementation.

Re-Review Decision

Decision: NO RE-REVIEW NEEDED

Rationale: The review found no correctness, security, or quality issues, and returned a clean APPROVE. All findings were explicitly informational/non-blocking with no suggested code changes. No commits were added since the reviewed commit (9c11487). The PR is unchanged from what was already reviewed and approved.

The PR is ready for merge (pending final go-ahead).

@malibio

malibio commented Aug 21, 2026

Copy link
Copy Markdown
Collaborator Author

Pragmatic Code Review — PR #2225

Code Review Summary

This is a tight, well-scoped fix that correctly identifies and closes a real bug. The change is a single file, a single commit, and does exactly one thing: it makes the summarization trigger count the tokens that actually exist in the prompt, and it deletes a second gate whose budget was provably looser than the first one it followed.

I verified the central claim empirically rather than taking the PR description on faith. I temporarily reverted only the tool_calls accumulation loop and re-ran the suite:

thread '...history_summarization_counts_tool_call_arguments' panicked at agent_loop.rs:4363:
tool-call argument JSON must count toward the history budget. Before: 24, After: 24

With the loop restored: 9 passed. The new test is genuinely discriminating, not tautological. Full package: 540 passed; 0 failed. cargo clippy -p nodespace-agent --all-targets -- -D warnings: clean. Working tree restored to a clean state afterward.

Both premises behind the fix check out against the actual code, not just the issue text:

  • Assistant tool-call turns really do have empty content. agent_loop.rs:1836 pushes ChatMessage::assistant_with_tool_calls(String::new(), tool_calls) — content is empty by construction, with a deliberate comment explaining why (persisting narration alongside the call makes Gemma's template collapse turns and run away). So the old content-only scan was counting literally nothing for these turns.
  • The ~6,600 system-prompt figure is real. packages/nlp-engine/src/chat/mod.rs:2526 asserts N_CTX_MINIMUM > 6_600. SYSTEM_PROMPT_BUDGET is 4_000. The second gate's implied headroom was therefore ~2,600 tokens looser than reality — it was not a conservative backstop, it was a hole. Deleting it is correct: a backstop that is strictly more permissive than the gate preceding it can only ever undo that gate's decision, never reinforce it.

The removal is behaviorally safe in the intended direction. The remaining gate is strictly more aggressive, so the only change is "summarizes in cases where it previously (wrongly) did not." Nothing can now skip summarization that didn't before.

I also checked the thing that most often makes a fix like this half-complete — whether the content being summarized is still blind to tool calls even after the trigger is fixed. It is not: summary_input construction (agent_loop.rs:2856-2880) already renders called tools: name(args…) for empty-content tool-call turns, capping each argument blob at 120 chars. So trigger and content are consistent, and this PR did not need to touch it. Good — worth noting explicitly since a fix that got the trigger right but summarized empty strings would have been a silent partial fix.

Net assessment: clear net improvement to code health. No blockers.

Requirements Check

Issue #2197 is a bug report with a described failure scenario rather than an acceptance-criteria checklist, so I validated against the root cause as described.

Issue claim Addressed Notes
msg.content-only counting misses tool_calls[].arguments_json ✅ Yes Accumulation loop now appends function_name + arguments_json per call
Redundant second gate (history_tokens <= history_budget) skips summarization ✅ Yes Deleted; first gate is now authoritative
history_budget derived from SYSTEM_PROMPT_BUDGET=4,000 vs real ~6,600 prompt ✅ Yes Verified against N_CTX_MINIMUM test
Tool-definitions JSON never counted ⚠️ Not addressed See 🟡 below
Per-message chat-template overhead never counted ⚠️ Not addressed See 🟢 below

The dominant term — argument JSON, up to MAX_RESPONSE_TOKENS (2,048) per call and entire markdown documents for create_nodes_from_markdown — is fixed. Two smaller terms the issue also listed remain. I do not consider either a blocker for this PR (the failure scenario in the issue is driven by the arg-JSON term and the bad second gate, both now closed), but the tool-definitions one deserves a follow-up because it is systematic rather than incidental.

Findings

Critical Issues

None.

Suggested Improvements

🟡 [agent_loop.rs:2796-2812] The tool-definitions JSON is still uncounted, and it is a large, always-present term.

system_tokens measures system_content only. But tool definitions do not travel inside system_content — they are passed separately as InferenceRequest.tools and serialized into the prompt downstream by the template layer (nlp-engine/src/chat/mod.rs:1252-1287 builds tools_json_string and hands it to apply_chat_template as tools_json). So the full OpenAI-style tool-spec JSON for every registered tool lands in the real prompt while contributing zero to this gate's arithmetic.

This is a constant undercount on every single turn, not an edge case. The comment on SYSTEM_PROMPT_BUDGET even says "system prompt and tool definitions", which suggests the original intent was for that budget to cover both — an intent the measured-system_content path silently dropped.

I would not block on this: it is a pre-existing gap, it is smaller than the arg-JSON term this PR fixes, and folding it in properly means either threading tools into maybe_summarize_history or having the engine expose a "count this request as templated" primitive — a real design decision, not a one-liner. But please file a follow-up rather than letting it close silently with #2197, since #2197 explicitly named it. Right now the gate is much better calibrated than it was, but still structurally optimistic.

🟡 [agent_loop.rs:4333, and the pre-existing sibling at 4136] The test comment's stated arithmetic does not match the budget the test actually exercises.

The comment reads 4096, // effective window small enough that arg JSON alone overflows it, and the body explains "12 calls * 2000 chars of args = 24000 chars ≈ 6000 tokens, which alone exceeds the 4096-token effective window."

The real numbers: with context_window = 4096, total_budget = 4096.saturating_sub(2048).max(4001) = 4001 — the SYSTEM_PROMPT_BUDGET + 1 floor wins, not 4096 - 2048 = 2048. And the measured history is 6,135 tokens, not ~6,000 (the comment omits the function_name + three separator spaces per call, which add ~29 chars × 12).

The test still passes for the right reason and by a wide margin (6,135 + 2 vs 4,001), so this is a comment-accuracy issue rather than a correctness one. But it matters more than a typo normally would: a future reader tuning these constants will reason from "4096" and reach a wrong conclusion about how much headroom the test has. Suggest something like:

4096, // → total_budget floors at SYSTEM_PROMPT_BUDGET + 1 = 4001;
      // history measures ~6,135 tokens, well over it

Worth noting the same off-by-a-floor framing already exists at line 4136 in summarization_triggers_on_reduced_effective_window ("well over a 4096-token effective window"). Fixing both together is cheap and keeps them from reinforcing each other's inaccuracy.

🟢 [agent_loop.rs:2814-2821] The removal-rationale comment is doing archaeology, and will age poorly.

Seven lines explaining what a now-deleted check used to do and why it was wrong. That history is already captured well in the commit message and the PR body, which is where it belongs — per this repo's own standard that comments explain the why of current code, not the story of its edits. Once #2197 is a year old, this paragraph costs every reader time to determine it describes nothing that exists.

Suggest collapsing to the invariant a future reader actually needs, which is the non-obvious part worth keeping:

// Sole gate: measured history + the *actual* system prompt against the
// window. Deliberately no secondary check against a static budget —
// SYSTEM_PROMPT_BUDGET (4,000) is well under the real tool-registered
// prompt (~6,600), so any such check is looser than this one and can
// only undo it.

That preserves the load-bearing warning ("don't re-add a static-budget check") without narrating the diff.

🟢 [agent_loop.rs:2776-2782] Same over-narration in the accumulation-loop comment.

"...that the naive content-only scan would miss entirely, which is exactly the corridor where..." describes the bug being fixed rather than the code as it stands. The genuinely non-obvious fact — that content is empty by construction for tool-call turns, so this loop is not redundant belt-and-braces — is the part to keep. Two lines would do it.

Nitpicks

Nit: [agent_loop.rs:671 / 4689] Removing HISTORY_TOKEN_BUDGET is the right call.

Flagging this only because it was raised as an open question. Inlining is correct here. The const had exactly one remaining use — a test sanity ceiling — and keeping a named module-level constant alive for a single test reference would imply it still participates in production budgeting, which it does not. That implication is precisely what made the old second gate look legitimate. Deleting it removes a misleading affordance, and matches the repo's "delete, don't preserve" stance. No change requested.

Nit: [agent_loop.rs:2786-2791] The separator spaces are slightly generous, in the safe direction.

Each call appends four space separators. Against a len/4 estimate in tests and a real tokenizer in production, this rounds the estimate up, which biases toward summarizing early. That is the correct direction for a gate whose failure mode is ContextOverflow, so this is fine as-is — noting it only so it is a recorded decision rather than an accident.

Nit: [agent_loop.rs:2769] maybe_summarize_history is called once per ReAct iteration (line 1446) and now performs strictly more string building per call.

The extra work is proportional to argument JSON already resident in memory, and it is dwarfed by the inference call that follows, so there is no practical cost. Not worth optimizing — mentioning it only to confirm it was considered and dismissed.

Edge cases checked

  • Empty tool_calls — the for loop is a no-op; user/tool/plain-assistant messages behave exactly as before. No behavior change on non-tool conversations.
  • Multiple tool_calls per message — all are accumulated; the loop is per-call, not per-message. Correct.
  • Very large arguments_json — this is the fixed case. Bounded in practice by MAX_RESPONSE_TOKENS per call.
  • model_info() fallback path — Ok(None), Err(_), or context_window == 0 all fall to TOTAL_TOKEN_BUDGET (32,000). The fallback lost its paired HISTORY_TOKEN_BUDGET, but since the second gate is gone, nothing reads it. Fallback semantics are unchanged and the arm is still exercised by history_summarization_trigger.
  • SYSTEM_PROMPT_BUDGET + 1 floor — retained, so total_budget can never reach zero and force pathological summarization on a tiny window. Unchanged by this PR.
  • Split-point back-off interaction — the new test's history is 24 messages alternating assistant-tool-call / tool-result. split_point starts at 21 (a tool-call assistant message, not Role::Tool), so the orphan-prevention walk-back does not fire and the split_point == 0 early return is not hit. The test reaches the assertion it intends to test rather than passing through an unrelated path — confirmed by the revert experiment, which failed at the intended assertion.
  • Summarization content vs. trigger — summary_input already renders tool calls (agent_loop.rs:2856-2880). No blind-summary gap. This PR correctly did not need to touch it.

Recommendation

APPROVE

The fix is correct, minimal, and grounded in verified facts about the codebase rather than assumption. The new regression test is real — I confirmed it fails without the fix and passes with it. The gate-removal is safe and strictly conservative in direction. Nothing here blocks merge.

The only item I would genuinely like to see not get lost is the uncounted tool-definitions JSON (🟡 above): #2197 named it, this PR does not close it, and it is a permanent per-turn undercount. A follow-up issue is the right home for it — folding it in here would expand the scope beyond the single clean change this PR is. The comment-accuracy and comment-verbosity items are cheap to fold in now if convenient, but are not merge conditions.

@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: APPROVE (posted as a comment — GitHub blocks self-approval). Full findings in the review comment above.

@malibio

malibio commented Aug 21, 2026

Copy link
Copy Markdown
Collaborator Author

Pragmatic Code Review — PR #2225

Verdict: APPROVE

Count tool-call argument JSON in history token budget; remove redundant summarization gate (closes #2197)
Scope: 1 file, +105/−23, all in packages/agent/src/local_agent/agent_loop.rs.


Does it fix the reported bug?

Yes — both halves of #2197, and nothing beyond them.

Issue #2197 reported two co-operating defects in maybe_summarize_history:

  1. Undercounting. The history estimate scanned only msg.content. An assistant tool-call turn is constructed with empty content and carries its entire payload in tool_calls[].arguments_json — up to MAX_RESPONSE_TOKENS (2,048) of JSON per call, and for create_nodes_from_markdown an entire markdown document. All of it was invisible to the budget.
  2. A redundant, looser second gate. After the correct check (history + real system prompt > total_budget) had already established overflow, a second early return compared counted history against total_budget − SYSTEM_PROMPT_BUDGET. Since SYSTEM_PROMPT_BUDGET (4,000) is well below the real tool-registered system prompt (~6,600), that second gate returned Ok(()) and skipped summarization in exactly the corridor where the first check had already proven the prompt overflows.

The diff addresses each directly: the counting loop now folds function_name + arguments_json into history_text (agent_loop.rs:2789-2793), and the second gate is deleted so the first — which measures against the actual system_content — is authoritative.

Verified the ~6,600 figure is real, not folklore. packages/nlp-engine/src/chat/mod.rs:1571-1577 documents it on N_CTX_MINIMUM: "Its tool-registered system prompt alone is ~6,600 tokens." The commit message and the new code comment both cite it accurately.

Correctness

  • Deleting the second gate is strictly safe. It could only ever cause an early return — removing it can make summarization fire more often, never less. And it cannot fire spuriously: the surviving check compares against system_tokens measured from the real system_content passed by the caller, which is the same string later sent to the engine (agent_loop.rs:1450). The gate is now tighter and more accurate at the same time, which is the right direction.
  • No dead constant left behind. HISTORY_TOKEN_BUDGET was the only consumer of the removed arithmetic and is deleted with it. Grepped the whole workspace: SYSTEM_PROMPT_BUDGET survives legitimately as the floor clamp in .max(SYSTEM_PROMPT_BUDGET + 1) and in one test; TOTAL_TOKEN_BUDGET remains the unknown-window fallback. No orphans, and no #[allow(dead_code)] papering over anything.
  • Termination is fine. maybe_summarize_history runs once per ReAct iteration, not in an inner loop, so a history still over budget after one pass simply gets another pass next iteration rather than spinning.
  • The existing tool-call/tool-result pairing guard is untouched. The split_point walk-back that prevents orphaning a Role::Tool message from its issuing assistant turn — and the split_point == 0 bail-out — are unchanged. Since this PR makes summarization fire more often, that guard now matters more; good that it was left intact.
  • Fallback path unchanged. When model_info() reports no window, the budget is still TOTAL_TOKEN_BUDGET (32,000). Combined with more-accurate counting this is a behavior change only in the correct direction.

Test quality

The new test history_summarization_counts_tool_call_arguments (agent_loop.rs:4314-4381) is a real regression guard, not a decoration. I verified this rather than taking it on faith:

I reverted only the production counting loop, leaving the test untouched, and re-ran it:

test local_agent::agent_loop::tests::history_summarization_counts_tool_call_arguments ... FAILED
panicked at agent_loop.rs:4363:
tool-call argument JSON must count toward the history budget. Before: 24, After: 24

It fails without the fix and passes with it. The file was restored to HEAD afterwards (git status clean).

The test is well-constructed for what it targets: every assistant turn has empty content, so the pre-fix content-only scan sees nothing but empty strings — the failure mode is reproduced exactly rather than approximated. The 4,096-token mock window is small enough that argument JSON alone (12 calls x 2,000 chars ≈ 6,000 tokens) overflows it, and each call is paired with a matching tool_result so the history stays structurally valid through the pairing guard.

The touched pre-existing test (history_summarization_reduces_token_count) is a mechanical rename — it recomputes the same value locally now that the constant is gone. No assertion was weakened.

Verification run

  • cargo test -p nodespace-agent --lib → 540 passed, 0 failed, 1 ignored
  • cargo test -p nodespace-agent --lib history → 4/4 pass, including the new test
  • cargo clippy -p nodespace-agent --lib --all-targets → clean, no warnings
  • Negative control (fix reverted) → new test fails as designed

Standards

Complies with the project guide: no backward-compat shims, no #[deprecated], no #[allow(dead_code)], no lint suppression, no new .md files, and no issue numbers embedded in code comments — the comments describe the constraint directly and reference the nlp-engine measurement rather than "#2197".

Observations (non-blocking, no action requested)

  1. Chat-template overhead is still uncounted. Issue History token budget undercounts real prompt and refuses to summarize an over-budget conversation #2197 listed three uncounted contributors: tool-call arguments, the tool-definitions JSON, and per-message chat-template overhead. This PR fixes the first — by far the largest and most variable, since it scales with payload size. The tool-definitions JSON is now effectively covered, because the gate measures the real system_content. Per-message template overhead (role markers, turn delimiters) remains uncounted, but it is small, roughly constant per message, and absorbed by the MAX_RESPONSE_TOKENS reservation. Narrowing scope to the dominant term is the right call for a bug fix; I would not expand this PR.

  2. SYSTEM_PROMPT_BUDGET is now a slightly odd name. It no longer budgets the system prompt — it only serves as a floor in .max(SYSTEM_PROMPT_BUDGET + 1), guaranteeing total_budget stays positive on a pathologically small window. The name is a mild leftover, but renaming it would add diff noise for no behavioral gain. Fine as-is.

  3. The comment block explaining the deleted gate is long (~9 lines for code that no longer exists). It earns its keep here: it records why a plausible-looking second check was wrong, which is precisely the kind of non-obvious constraint that stops someone re-adding it. Worth keeping.


Recommendation: APPROVE. The change is tightly scoped to the reported defect, both halves are correct, the fix direction is conservative (summarize more readily, never less), the new test is a verified regression guard, and the full suite plus clippy are green.

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

Verdict: APPROVE (posted as a comment because GitHub rejects self-approval on an own-authored PR.)

Full review is in the preceding PR comment. Summary: both halves of #2197 are fixed — tool-call arguments_json now counts toward the history budget, and the redundant looser second gate is removed so the check against the real measured system prompt is authoritative. The ~6,600-token system-prompt figure is corroborated by nlp-engine/src/chat/mod.rs:1571-1577.

Verified rather than assumed: reverting only the production counting loop makes the new test history_summarization_counts_tool_call_arguments fail ("Before: 24, After: 24"), so it is a genuine regression guard. cargo test -p nodespace-agent --lib → 540 passed / 0 failed; cargo clippy clean. No dead constants left behind, and the tool-call/tool-result pairing guard is untouched.

Three non-blocking observations (uncounted per-message template overhead, the now-oddly-named SYSTEM_PROMPT_BUDGET floor clamp, comment length) are detailed in the review — none warrant a change. No re-review needed.

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.

History token budget undercounts real prompt and refuses to summarize an over-budget conversation

1 participant