Skip to content

fix(compaction): share model-aware memory maintenance budgets - #130072

Merged
steipete merged 3 commits into
mainfrom
codex/hanselman-compaction-budget
Aug 26, 2026
Merged

steipete merged 3 commits into
mainfrom
codex/hanselman-compaction-budget

Conversation

@steipete

@steipete steipete commented Aug 26, 2026 •

Copy link
Copy Markdown
Contributor

Related: #124911.

What Problem This Solves

Fixes an issue where users of 8k, 16k, and 24k context-window models could silently miss memory flushing and preflight compaction because those paths subtracted a fixed 20k reserve even though the actual agent runner correctly capped that reserve for the selected model.

Why This Change Was Made

Consolidate the effective compaction-reserve calculation at its architectural owner and reuse it in embedded agent settings, preemptive compaction, memory-flush gating, preflight compaction, and threshold diagnostics. Bound soft maintenance headroom against the remaining usable prompt budget while preserving established reserve behavior for large-context models. No retired compaction configuration is restored.

User Impact

Small-context models preserve important history before overflow, compaction and memory flushing agree on the same thresholds, and existing large-model behavior remains unchanged.

Evidence

  • 228 focused compaction, embedded-agent, auto-reply, and reset-session corpus regression tests passed across four Vitest shards on the final head; the earlier combined reliability sweep passed 432 tests.
  • Behavioral regression tables cover 8k, 16k, 24k, 32k, 128k, and 200k context windows for both memory maintenance gates.
  • Existing embedded-agent, auto-reply, and preemptive-compaction sibling regressions remain green.
  • Production code grows by only 12 lines while replacing duplicate reserve and threshold calculations.
  • Independent structured review reported no accepted/actionable findings.
  • Full-repository oxlint, all three Knip unused-export scans, and the 30,272-file formatting gate pass; the adjacent reset-archive fixture was consolidated to preserve its coverage below the existing file-length limit.

@clawsweeper

clawsweeper Bot commented Aug 26, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: S maintainer Maintainer-authored PR labels Aug 26, 2026
@clawsweeper clawsweeper Bot added 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. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Aug 26, 2026
@clawsweeper

clawsweeper Bot commented Aug 26, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: found issues before merge. Reviewed August 26, 2026, 7:10 AM ET / 11:10 UTC.

ClawSweeper review

What this changes

Centralizes model-aware reserve and maintenance-threshold calculations so memory flushing and preflight compaction work on small-context models.

Regression provenance

Possible regression — suspected (reviewed change). No predecessor PR is attributed.

Merge readiness

⚠️ Ready for maintainer review - 5 items remain

Keep open. The small-context maintenance defect is real, but this patch also changes the exported memory-plugin contract by overriding provider-supplied thresholds; that compatibility policy needs an explicit maintainer choice before merge.

Priority: P2
Reviewed head: 616404b7fb8bc5ea00067d251e39ab949379070b
Owner decision: Required. See Decision needed.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The small-window repair is source-backed and tested, but the unresolved exported plugin-contract change prevents a merge-ready rating.
Proof confidence 🌊 off-meta tidepool Not applicable: This maintainer-authored PR is exempt from the external-contributor proof gate; the body reports focused test runs but no real-run artifact was inspected.
Patch quality 🦐 gold shrimp (3/6) 1 actionable review finding remain.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: This maintainer-authored PR is exempt from the external-contributor proof gate; the body reports focused test runs but no real-run artifact was inspected.
Evidence reviewed 6 items Current-main defect: Current main subtracts a raw memory-plan reserve and soft threshold, then returns no gate state when the result is non-positive; an 8k context with the built-in 20k reserve therefore cannot trigger token-based maintenance.
Changed owner path: The PR applies one capped reserve calculation before deriving the shared flush/preflight threshold, and both Gateway call sites use that helper.
Exported plugin contract: MemoryFlushPlan and its resolver are exported through the memory host SDK; current main directly honors their numeric reserve and soft-threshold values, so unconditional clamping changes plugin-visible behavior.
Findings 1 actionable finding [P1] Preserve plugin-owned maintenance thresholds
Security None None.

Live Verification

Command: pnpm openclaw --help

Result: PASS (completed)

$ node scripts/run-node.mjs --help
[openclaw] Building TypeScript (dist is stale: missing_build_stamp - build stamp missing).
[openclaw] Building bundled plugin assets.
[canvas] build: node scripts/bundle-a2ui.mjs
[log] ‹DIR›/a2ui.bundle.js  chunk │ size: 399.96 kB
[log] ‹DIR›/a2ui-v0.9.bundle.js  chunk │ size: 615.66 kB
[log]
[success] rolldown v1.2.0 Finished in 105.93 ms
[diffs] build: node --import tsx ../../scripts/build-diffs-viewer-runtime.mts curated
[diffs-language-pack] build: node --import tsx ../../scripts/build-diffs-viewer-runtime.mts full
[discord] build: node --import tsx ../../scripts/build-discord-activity-sdk.mts
[tsdown-build] invocation 1/2 finished in 0.7s
node_modules/playwright-core/lib/coreBundle.js (65821:28) [EVAL] Use of direct ˋevalˋ function is strongly discouraged as it poses security risks and may cause
issues with minification.
       ╭─[ node_modules/playwright-core/lib/coreBundle.js:65821:29 ]
       │
 65821 │               const value = eval(ˋ(${expr})ˋ);
       │                             ──┬─
       │                               ╰─── Use of direct ˋevalˋ here.
       │
       │ Help: Consider using indirect eval. For more information, check the documentation: https://rolldown.rs/guide/troubleshooting#avoiding-direct-eval
───────╯

node_modules/playwright-core/lib/coreBundle.js (65828:28) [EVAL] Use of direct ˋevalˋ function is strongly discouraged as it poses security risks and may cause
issues with minification.
       ╭─[ node_modules/playwright-core/lib/coreBundle.js:65828:29 ]
       │
 65828 │               const value = eval(ˋ(${expr})ˋ);
       │                             ──┬─
       │                               ╰─── Use of direct ˋevalˋ here.
       │
       │ Help: Consider using indirect eval. For more information, check the documentation: https://rolldown.rs/guide/troubleshooting#avoiding-direct-eval
───────╯

node_modules/web-tree-sitter/web-tree-sitter.js (2343:30) [EVAL] Use of direct ˋevalˋ function is strongly discouraged as it poses security risks and may cause
issues with minification.
      ╭─[ node_modules/web-tree-sitter/web-tree-sitter.js:2343:31 ]
      │
 2343 │           ASM_CONSTS[start] = eval(func);
      │                               ──┬─
      │                                 ╰─── Use of direct ˋevalˋ here.
      │
      │ Help: Consider using indirect eval. For more information, check the documentation: https://rolldown.rs/guide/troubleshooting#avoiding-direct-eval
──────╯

node_modules/web-tree-sitter/web-tree-sitter.js (2366:32) [EVAL] Use of direct ˋevalˋ function is strongly discouraged as it poses security risks and may cause
issues with minification.
      ╭─[ node_modules/web-tree-sitter/web-tree-sitter.js:2366:33 ]
      │
 2366 │           moduleExports[name] = eval(func);
      │                                 ──┬─
      │                                   ╰─── Use of direct ˋevalˋ here.
      │
      │ Help: Consider using indirect eval. For more information, check the documentation: https://rolldown.rs/guide/troubleshooting#avoiding-direct-eval
──────╯

[tsdown-build] invocation 2/2 finished in 14.2s
[plugin-control-plane-loads] verified 35 built modules with native require and checked doctor closures
runtime-postbuild: 11 phases completed in 4330ms (slowest: built plugin control-plane loads 3590ms)

OpenClaw 2026.8.1 (616404b) — All your chats, one OpenClaw.

Usage: openclaw [options] [command]

Options:
  --container ‹name›   Run the CLI inside a running Podman/Docker container named ‹name› (default: env OPENCLAW_CONTAINER)
  --dev                Dev profile: isolate state under ~/.openclaw-dev, default gateway port 19001, and shift derived ports (browser/canvas)
  -h, --help           Display help for command
  --log-level ‹level›  Global log level override for file + console (silent|fatal|error|warn|info|debug|trace)
  --no-color           Disable ANSI colors
  --profile ‹name›     Use a named profile (iso
… output truncated …

Assertions:

  • PASS expect_output: Usage:

How this fits together

The embedded agent runner and the Gateway’s memory-maintenance path use a model context budget to decide when to compact or flush session memory. Their decisions affect whether important transcript context is saved before the next model request.

flowchart LR
  A[Model context window] --> B[Effective reserve]
  C[Memory plugin plan] --> B
  B --> D[Maintenance threshold]
  E[Session token estimate] --> D
  D --> F[Preflight compaction]
  D --> G[Memory flush]
Loading

Decision needed

Question Recommendation
Should the Gateway cap every exported MemoryFlushPlan, or preserve external plugin thresholds and make model-aware normalization an explicit opt-in? Make normalization opt-in: Add a backwards-compatible plan marker used by bundled Memory Core while preserving unmarked external resolver values.

Why: The current public SDK exports this plan shape and current main honors its values verbatim; choosing host ownership versus plugin ownership changes existing plugin behavior.

Before merge

  • Preserve plugin-owned maintenance thresholds (P1) - MemoryFlushPlan is exported through the memory host SDK, and current main honors its reserve and soft-threshold values verbatim. This clamp makes a custom 32k-context plan with a 50k reserve go from disabled maintenance to a 4k trigger; preserve unmarked plugin values or make the new host-owned contract explicit and covered.
  • Resolve merge risk (P1) - An external memory plugin that intentionally returns an oversized reserve or soft threshold to defer or disable maintenance will silently begin flushing or preflight-compacting after this change.
  • Resolve merge risk (P1) - The bug-fix production delta is +12 lines; it is justified only if the final design centralizes built-in normalization without silently redefining plugin-owned plan semantics.
  • Complete next step (P2) - A maintainer must choose the public MemoryFlushPlan ownership semantics before a safe repair can be specified.

Findings

  • [P1] Preserve plugin-owned maintenance thresholds — src/auto-reply/reply/memory-flush.ts:54-64
Agent review details

Security

None.

PR surface

Source +12, Tests +44. Total +56 across 8 files.

View PR surface stats
Area Files Added Removed Net
Source 5 71 59 +12
Tests 3 66 22 +44
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 8 137 81 +56

Review metrics

Metric Value Why it matters
Production vs test LOC production +71/-59 (net +12); tests +66/-22 The small production increase consolidates duplicated reserve logic, but it also changes the behavior of an exported plugin plan.

Stored data model

Persistent data-model change detected: serialized state: packages/memory-host-sdk/src/host/session-files.test.ts, unknown-data-model-change: src/auto-reply/reply/memory-flush.ts, vector/embedding metadata: src/auto-reply/reply/memory-flush.ts. Confirm migration or upgrade compatibility proof before merge.

Merge-risk options

Maintainer options:

  1. Make budget normalization explicit (recommended)
    Preserve existing external plan semantics by adding an opt-in marker for bundled model-aware defaults and test both marked and unmarked plans.
  2. Accept host-owned plan caps
    If every plan is intentionally host-normalized, document that SDK contract and prove the upgrade behavior for custom resolver values.

Technical review

Best possible solution:

Add an explicit, backwards-compatible opt-in for model-aware budget normalization, enable it for the bundled Memory Core plan, preserve unmarked external plan values, and cover both paths.

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

Yes in source: on current main an 8k context with the built-in 20k reserve produces no token gate, while the PR derives a 2k threshold; execution was not run in this read-only review.

Is this the best way to solve the issue?

No: shared normalization is the right direction for the bundled default, but unconditionally capping exported plugin plans changes their established runtime meaning; use an explicit opt-in boundary.

Full review comments:

  • [P1] Preserve plugin-owned maintenance thresholds — src/auto-reply/reply/memory-flush.ts:54-64
    MemoryFlushPlan is exported through the memory host SDK, and current main honors its reserve and soft-threshold values verbatim. This clamp makes a custom 32k-context plan with a 50k reserve go from disabled maintenance to a 4k trigger; preserve unmarked plugin values or make the new host-owned contract explicit and covered.
    Confidence: 0.93

Overall correctness: patch is incorrect
Overall confidence: 0.93

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🌊 off-meta tidepool and patch quality is 🦐 gold shrimp.
  • add status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Not applicable: This maintainer-authored PR is exempt from the external-contributor proof gate; the body reports focused test runs but no real-run artifact was inspected.
  • remove rating: 🐚 platinum hermit: Current PR rating is rating: 🦐 gold shrimp, so this older rating label is no longer current.
  • remove status: 👀 ready for maintainer look: Current PR status label is status: ⏳ waiting on author.

Label justifications:

  • P2: This is a bounded session-maintenance regression with a compatibility decision, not an emergency availability or security incident.
  • merge-risk: 🚨 compatibility: The patch changes how existing external MemoryFlushPlan reserve and threshold values are interpreted at runtime.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🌊 off-meta tidepool and patch quality is 🦐 gold shrimp.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action. Not applicable: This maintainer-authored PR is exempt from the external-contributor proof gate; the body reports focused test runs but no real-run artifact was inspected.

Evidence

What I checked:

Likely related people:

  • steipete: Authored the current PR and the recent context-budget consolidation; history also shows repeated maintenance of the central memory and compaction paths. (role: recent compaction and memory maintainer; confidence: high; commits: 715c379fd949, adcee720dd1b; files: src/agents/agent-settings.ts, src/auto-reply/reply/memory-flush.ts, extensions/memory-core/src/flush-plan.ts)
  • Jarvis: Authored the earlier correction to memory-flush context-token accounting, the historical owner path behind the current threshold gate. (role: original memory-flush gating contributor; confidence: medium; commits: fcb685978469; files: src/auto-reply/reply/memory-flush.ts)
  • obviyus: Authored the recent active-context server-compaction threshold work that shares the same maintenance-decision surface. (role: adjacent server-compaction contributor; confidence: medium; commits: 863f19b72296; files: src/auto-reply/reply/memory-flush.ts)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Choose whether external MemoryFlushPlan values remain authoritative or are host-normalized.
  • Add a regression that distinguishes bundled opt-in normalization from an unmarked custom plugin plan.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
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.

Workflow

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

History

Review history (1 earlier review cycle)
  • reviewed 2026-08-26T10:32:12.744Z sha 89e2283876aa73ab65a0c01a7bb515e1b69ba1f0 :: needs maintainer review before merge. :: none

@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 Aug 26, 2026
@steipete
steipete force-pushed the codex/hanselman-compaction-budget branch from 616404b to ec93902 Compare August 26, 2026 12:04
@openclaw-barnacle openclaw-barnacle Bot added the extensions: memory-core Extension: memory-core label Aug 26, 2026
@steipete
steipete merged commit 6b6f196 into main Aug 26, 2026
200 checks passed
@steipete
steipete deleted the codex/hanselman-compaction-budget branch August 26, 2026 12:24
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

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

Labels

agents Agent runtime and tooling extensions: memory-core Extension: memory-core 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: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. size: M status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant