Skip to content

fix(agents): cap compaction budgets for small contexts - #87927

Closed
vincentkoc wants to merge 1 commit into
mainfrom
codex/local-model-lean-context-pressure
Closed

vincentkoc wants to merge 1 commit into
mainfrom
codex/local-model-lean-context-pressure

Conversation

@vincentkoc

@vincentkoc vincentkoc commented May 29, 2026 •

Copy link
Copy Markdown
Member

Summary

  • cap embedded-agent compaction reserve when the known model context window would otherwise leave no usable prompt budget
  • cap keep-recent tokens to the prompt budget remaining after reserve while preserving explicit summary overhead
  • centralize the compaction summary overhead constant and update config help/types, generated config baseline hash, gateway config docs, and session-management reference docs to document context-window caps

Verification

Behavior addressed: small-context runs no longer retain impossible compaction reserveTokens or keepRecentTokens budgets when contextTokenBudget is known, and compacted tails no longer consume the whole post-reserve prompt budget before the summary is added.

Real environment tested: focused local Vitest/docs/format/lint proof in a Codex worktree; remote Crabbox/Testbox proof was attempted on the refreshed head and blocked by runner availability/auth, noted below.

Exact steps or command run after this patch:

node scripts/run-vitest.mjs run src/agents/agent-settings.test.ts --reporter=dot
node --import tsx scripts/generate-config-doc-baseline.ts --write
node --import tsx scripts/generate-config-doc-baseline.ts --check
node scripts/check-docs-mdx.mjs docs/reference/session-management-compaction.md docs/gateway/config-agents.md
node scripts/format-docs.mjs --check docs/reference/session-management-compaction.md docs/gateway/config-agents.md
node_modules/.bin/oxfmt --check --threads=1 src/agents/agent-settings.ts src/agents/agent-settings.test.ts src/agents/agent-compaction-constants.ts src/agents/compaction-planning.ts src/config/schema.help.ts src/config/types.agent-defaults.ts
node scripts/run-oxlint.mjs src/agents/agent-settings.ts src/agents/agent-settings.test.ts src/agents/agent-compaction-constants.ts src/agents/compaction-planning.ts src/config/schema.help.ts src/config/types.agent-defaults.ts
git diff --check origin/main...HEAD
blacksmith testbox list
node scripts/crabbox-wrapper.mjs run --provider azure --target linux --idle-timeout 90m --ttl 180m --timing-json --shell -- "pnpm check:changed"
crabbox stop --provider azure --target linux --id cbx_b8cfba03c38e

Evidence after fix: refreshed head 6d460a45848 is rebased onto current origin/main 5ee3e5d8c07. Focused local wrapper passed src/agents/agent-settings.test.ts with 36/36 tests. Config baseline generation/check passed with OK docs/.generated/config-baseline.sha256; docs MDX passed for docs/reference/session-management-compaction.md and docs/gateway/config-agents.md; docs formatting reported Docs formatting clean; oxfmt, oxlint, and git diff --check origin/main...HEAD passed.

Remote proof: Blacksmith Testbox is blocked locally by not authenticated - run 'blacksmith auth login' first. Azure Crabbox allocated run run_23b37df84fc5 with provider azure, lease id cbx_b8cfba03c38e, slug swift-prawn, target linux, but timed out after 10m waiting for a coordinator lease before running pnpm check:changed. Cleanup stop returned coordinator 404 not_found, so no late active lease remained to release.

Observed result after fix: a 16K-context profile resolves reserve to 8,384 and keep-recent to 4,000; configured over-budget reserve and keep-recent values are capped to the available context window while leaving summary overhead; when no context window is known, existing uncapped behavior is preserved. The session-management reference now documents those context-window caps and points at applyAgentCompactionSettingsFromConfig(), not the old uncapped helper.

What was not tested: broad remote pnpm check:changed on the refreshed head, because Testbox auth and Azure allocation blocked it; no live Ollama generation for this patch because the changed behavior is the embedded-agent settings normalization layer.

@vincentkoc vincentkoc self-assigned this May 29, 2026
@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: S maintainer Maintainer-authored PR labels May 29, 2026
@clawsweeper

clawsweeper Bot commented May 29, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed June 29, 2026, 5:19 PM ET / 21:19 UTC.

Summary
The PR changes embedded-agent compaction normalization, compaction constants, focused agent-settings tests, generated config baseline hashes, and compaction/config docs.

PR surface: Source +33, Tests +38, Docs +14, Generated 0. Total +85 across 9 files.

Reproducibility: yes. at source level: current main caps only the reserve floor, then leaves high existing reserve and keep-recent budgets uncapped when a context window is known. I did not run a live gateway or local-model reproduction in this read-only review.

Review metrics: 1 noteworthy metric.

  • Config/default semantics changed: 2 compaction budgets capped at runtime. reserveTokens and keepRecentTokens can now resolve below stored/current values when context is known, so upgrade behavior needs explicit maintainer acceptance.

Merge readiness
Overall: 🐚 platinum hermit
Proof: 🌊 off-meta tidepool
Patch quality: 🐚 platinum hermit
Result: ready for maintainer review.

Overall follows the weaker of proof and patch quality, so missing proof can cap an otherwise strong patch.

Rank-up moves:

  • Resolve current-main conflicts and refresh the generated config baseline proof.
  • Reconcile the effective reserve/floor behavior with the related explicit-reserve PR before landing.

Risk before merge

  • [P1] The PR currently conflicts with main; rebase/conflict resolution must preserve current-main removal of stale helper code and refresh generated config baselines.
  • [P1] Changing config-backed compaction budgets can alter existing users' effective reserve and recent-tail behavior on upgrade when the active context window is known.
  • [P1] Related open compaction work proposes different explicit reserveTokens / omitted reserveTokensFloor semantics, so landing this PR alone could settle part of that contract without maintainer alignment.

Maintainer options:

  1. Rebase and reconcile compaction semantics (recommended)
    Resolve conflicts against current main, preserve current helper/docs cleanup, and decide how context-window caps interact with explicit reserve-token settings before merge.
  2. Accept the runtime cap as intentional
    Maintainers can land the cap deliberately after conflict resolution if small-context prompt starvation outweighs preserving over-budget stored settings.
  3. Pause behind broader compaction config direction
    Maintainers can pause this PR if they want one canonical contract for absolute caps, percentage-style settings, and explicit reserve floor behavior.

Next step before merge

  • Manual review is appropriate because the protected maintainer PR is currently conflicting and changes upgrade-visible compaction semantics that overlap active compaction reserve work.

Security
Cleared: The diff is limited to agent settings logic, tests, generated config hashes, and docs; no concrete security or supply-chain concern is visible.

Review details

Best possible solution:

Rebase onto current main, reconcile small-context prompt safety with explicit reserve-token semantics across related compaction paths, then merge only if maintainers accept the compatibility change.

Do we have a high-confidence way to reproduce the issue?

Yes at source level: current main caps only the reserve floor, then leaves high existing reserve and keep-recent budgets uncapped when a context window is known. I did not run a live gateway or local-model reproduction in this read-only review.

Is this the best way to solve the issue?

Conditionally yes: settings normalization is a plausible narrow fix location, but the PR must be rebased and maintainer-approved because it changes effective config-backed values and overlaps related reserve-token semantics work.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning high; reviewed against 15de9d881a84.

Label changes

Label justifications:

  • P2: The PR targets a normal-priority compaction budget bug with limited but real agent/runtime impact.
  • merge-risk: 🚨 compatibility: The diff changes effective config-backed compaction reserve and keep-recent values for existing known-context setups.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: This is a maintainer-authored PR, so the external contributor real-behavior proof gate does not apply; the PR body includes focused local command output and notes blocked remote proof.
Evidence reviewed

PR surface:

Source +33, Tests +38, Docs +14, Generated 0. Total +85 across 9 files.

View PR surface stats
Area Files Added Removed Net
Source 5 45 12 +33
Tests 1 56 18 +38
Docs 2 18 4 +14
Config 0 0 0 0
Generated 1 4 4 0
Other 0 0 0 0
Total 9 123 38 +85

What I checked:

  • Root policy read: Root AGENTS.md was read fully and applied; it requires full scoped review and treats config/default behavior as compatibility-sensitive. (AGENTS.md:1, 15de9d881a84)
  • Scoped guides read: The agents and docs scoped guides were read; the relevant guidance affects focused agent test scope and docs link/content handling. (src/agents/AGENTS.md:1, 15de9d881a84)
  • Live PR state: Live GitHub reports the PR open, not draft, maintainer-labeled, and mergeable=CONFLICTING / mergeStateStatus=DIRTY at head 6d460a45848f4af3e21322aeaabd827f7a98b0d0. (6d460a45848f)
  • Current-main gap remains: Current main caps only the reserve floor using the known context window, then leaves selected target reserve and keep-recent values uncapped. (src/agents/agent-settings.ts:79, 15de9d881a84)
  • PR implementation: The PR head caps targetReserveTokens to maxReserveTokens and caps targetKeepRecentTokens to prompt budget after reserve and summary overhead. (src/agents/agent-settings.ts:112, 6d460a45848f)
  • PR regression tests: The PR adds tests for 16K reserve capping, explicit over-budget reserve/keep-recent capping, 32K keep-recent capping, and no-context uncapped behavior. (src/agents/agent-settings.test.ts:170, 6d460a45848f)

Likely related people:

  • vincentkoc: Live GitHub history shows recent commits on src/agents/agent-settings.ts removing and hiding compaction helper surfaces, and this PR changes the same normalization path. (role: recent area contributor; confidence: high; commits: 4637b65470de, 9e3db6bedd28; files: src/agents/agent-settings.ts, src/agents/agent-settings.test.ts)
  • steipete: Live history shows the major internal agent runtime refactor plus compaction planning/docs work touching the same compaction and config surfaces. (role: major agent runtime contributor; confidence: high; commits: bb46b79d3c14, 6443d067645f, 634174f050b4; files: src/agents/agent-settings.ts, src/agents/compaction-planning.ts, docs/reference/session-management-compaction.md)
  • openperf: The merged related reserve-floor cap PR introduced the context-window prompt-budget invariant that this PR extends from floor capping to current and explicit budget capping. (role: adjacent behavior introducer; confidence: medium; commits: 4bc46ccfedc4; files: src/agents/agent-settings.ts, src/agents/agent-compaction-constants.ts, src/agents/embedded-agent-runner/run/preemptive-compaction.ts)
What the crustacean ranks mean
  • 🦀 challenger crab: rare, exceptional readiness with strong proof, clean implementation, and convincing validation.
  • 🦞 diamond lobster: very strong readiness with only minor maintainer review expected.
  • 🐚 platinum hermit: good normal PR, likely mergeable with ordinary maintainer review.
  • 🦐 gold shrimp: useful signal, but proof or patch confidence is still limited.
  • 🦪 silver shellfish: thin signal; proof, validation, or implementation needs work.
  • 🧂 unranked krab: not merge-ready because proof is missing/unusable or there are serious correctness or safety concerns.
  • 🌊 off-meta tidepool: rating does not apply to this item.

Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

How this review workflow works
  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.
Review history (1 earlier review cycle)
  • reviewed 2026-06-21T05:45:43.926Z sha 6d460a4 :: needs maintainer review before merge. :: none

@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. labels May 29, 2026
@vincentkoc
vincentkoc force-pushed the codex/local-model-lean-context-pressure branch from 985f328 to 5dbcc93 Compare May 30, 2026 00:20
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime labels May 30, 2026
@vincentkoc
vincentkoc marked this pull request as ready for review May 30, 2026 00:32
@vincentkoc
vincentkoc force-pushed the codex/local-model-lean-context-pressure branch from 5dbcc93 to 7be9ce4 Compare May 30, 2026 04:52
@clawsweeper clawsweeper Bot added rating: 🌊 off-meta tidepool PR readiness rating does not apply to this item. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels May 30, 2026
@vincentkoc
vincentkoc force-pushed the codex/local-model-lean-context-pressure branch from 7be9ce4 to 470b477 Compare May 30, 2026 20:08
@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🌊 off-meta tidepool PR readiness rating does not apply to this item. labels May 30, 2026
@vincentkoc
vincentkoc force-pushed the codex/local-model-lean-context-pressure branch from 470b477 to 0459aef Compare May 30, 2026 23:08
@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. and removed rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels May 30, 2026
@vincentkoc
vincentkoc force-pushed the codex/local-model-lean-context-pressure branch 3 times, most recently from a9e2e5e to 42c2af5 Compare May 31, 2026 17:48
@clawsweeper clawsweeper Bot added the proof: sufficient ClawSweeper judged the real behavior proof convincing. label May 31, 2026
@vincentkoc
vincentkoc force-pushed the codex/local-model-lean-context-pressure branch from 42c2af5 to aa62240 Compare May 31, 2026 21:19
@vincentkoc
vincentkoc force-pushed the codex/local-model-lean-context-pressure branch from aa62240 to 6d460a4 Compare May 31, 2026 21:20
@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels May 31, 2026
@yetval

yetval commented Jun 30, 2026

Copy link
Copy Markdown
Contributor

Confirming this fix is needed: the unguarded path reproduces live on origin/main (66e676d).

I drove the real applyAgentCompactionSettingsFromConfig with the shipped defaults (reserveTokens 16384) and a 16000-token context window, then fed the resulting reserve into the runtime compaction predicate. Today the floor cap at agent-settings.ts lowers only reserveTokensFloor, and const targetReserveTokens = Math.max(configuredReserveTokens ?? currentReserveTokens, reserveTokensFloor) re-floors it back up via the uncapped 16384 default, so the cap is a no-op:

ctxBudget=16000
effectiveReserve=16384
minPromptBudget=8000
promptBudget(ctx-reserve)=-384
shouldCompact(usage=1 token, ctx=16000) => true

The negative prompt budget means the runtime predicate (contextTokens > contextWindow - reserveTokens, same shape in the vendored runtime at proxy-r0kl0JEO.js) is true on the very first turn, so any model with a context window at or below ~16384 (local/Ollama, small GLM/Qwen, or a low cap) auto-compacts every turn from turn one. shouldDisableAgentAutoCompaction leaves auto-compaction default-on for ordinary providers, so nothing downstream rescues it.

This PR's maxReserveTokens = Math.max(0, ctxBudget - minPromptBudget) plus targetReserveTokens = Math.min(targetReserveTokens, maxReserveTokens) is exactly what closes it: with the same inputs the reserve clamps to 8000 and the prompt budget becomes +8000, so the first-turn compaction no longer fires. LGTM on the approach.

@steipete

steipete commented Jul 6, 2026

Copy link
Copy Markdown
Contributor

The sound part of this PR has been replayed and landed through #100621 as 62d957634c53.

The landed fix caps the final effective reserve for a known small context window. Exact runtime proof showed a 16,384-token context changing from reserve 16,384 with shouldCompact(1) === true to reserve 8,384 with shouldCompact(1) === false; focused tests passed 31/31, broad Testbox pnpm check:changed passed, fresh autoreview was clean, and exact-head hosted CI was green.

I deliberately did not replay the keepRecentTokens cap. Agent-core treats it as a cut target, not a hard maximum; whole messages/turns and split-turn summaries can exceed it, so that half of the original patch was not correct.

The branch could not be updated directly because maintainer edits are disabled, so I recreated the verified subset with Vincent's co-author credit and changelog thanks. Thank you @vincentkoc. For future contributor branches, enabling Allow edits by maintainers lets us repair the original PR in place.

@steipete steipete closed this Jul 6, 2026
@shakkernerd
shakkernerd deleted the codex/local-model-lean-context-pressure branch October 19, 2026 23:33
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling docs Improvements or additions to documentation gateway Gateway runtime maintainer Maintainer-authored PR merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: S status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants