Skip to content

fix: bound memory growth across long conversations and workspaces - #192944

Merged
steipete merged 1 commit into
mainfrom
steipete/perf-micro-prompt-cache-trackers-and-tokenjuice-rulecache-20260919
Nov 4, 2026
Merged

steipete merged 1 commit into
mainfrom
steipete/perf-micro-prompt-cache-trackers-and-tokenjuice-rulecache-20260919

Conversation

@steipete

@steipete steipete commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Long conversations and workspace churn retain growing diagnostic history and compiled Tokenjuice rule sets in a long-lived Gateway.

User Impact

History retention now has a byte budget as well as an entry limit. Tokenjuice releases old compiled workspace rules at a bounded capacity, while repeated calls within a stable working set remain hot. No configuration, dependency, database, or provider-request changes.

The owner accepted these measured resource tradeoffs on 2026-11-04: constant history-cache eviction adds about 0.13 ms per observation; the first Tokenjuice capacity crossing adds about 47 ms to one result when its public cleanup API loads, plus about 3.26 MB of fixed module retention. This PR is not a claim of uniformly faster requests.

Why This Change Was Made

The existing 512-tracker LRU retains packed fingerprints, but their arrays grow with conversation length. A conservative 16 MiB budget for history strings and container overhead now evicts the oldest whole baselines. Resident sessions keep full rewrite diagnostics; evicted or individually oversized histories start without a prior baseline. Eviction also leaves no unchanged-prefix proof, so context-pressure checks use their existing conservative fallback. Provider prompt snapshots already contain bounded hashes and wire metadata, not request payloads.

Tokenjuice 0.10.0 keys compiled rules by cwd and rule-loading options and has no eviction. Its owning plugin now accounts for distinct cwd input contexts and calls the public clearRuleCache() after 128 distinct contexts settle. The bounded Set contains only scope identities, not rules or memoized results. It preserves the dependency's project-rule selection and cwd precedence; in-flight work may temporarily exceed the settled bound. Cleanup also runs when reduction fails. The public root export is loaded lazily only at capacity because eagerly importing it regresses plugin startup.

Production growth is 35 lines: byte accounting at the existing tracker owner and bounded capacity accounting at the plugin boundary. There is no replacement cache, new loader, private dependency import, or lifecycle hook that misses direct worktree retirement.

Evidence

Acceptance recorded before measurement: lower post-GC retention, bounded growth across increasing session/workspace counts, preserved rewrite/project-rule behavior, and no greater than 20% median/p95 owner CPU or latency regression versus A/A controls. The memory and behavior criteria pass; the two explicit latency tradeoffs above have owner acceptance.

Five alternating baseline/candidate processes per timing workload, plus A/A controls, Node 26.12.1, synthetic data only. Baseline: 8e6e2ae532677c1758fecf28b88fb775af0cea01. Times below are per observation unless stated otherwise.

Owner/workload Baseline median Candidate median
History: 64 sessions × 1,024 messages, tracker-owned bytes after source release 27,451,024 6,863,784 (-75.0%)
History: 4 resident sessions × 2,048 messages, warm wall 0.1404 ms 0.1467 ms
History: resident warm CPU 0.2491 ms 0.2568 ms
History: 64-session round-robin eviction, wall 0.1719 ms 0.3008 ms
History: round-robin eviction, CPU 0.7046 ms 0.8396 ms
Tokenjuice: 2,047 distinct cwd, retained compiled rules at peak occupancy 456,518,944 bytes 28,439,296 bytes (-93.77%)
Tokenjuice: 1,023 distinct cwd, retained compiled rules at peak occupancy 228,205,208 bytes 28,435,632 bytes
Tokenjuice: 2,048 calls alternating two cwd, whole-flow wall / CPU 179.57 / 273.66 ms 181.56 / 276.54 ms
Tokenjuice: plugin import wall / CPU 158.90 / 130.23 ms 163.66 / 136.41 ms
Tokenjuice: first capacity-crossing result, cold public export 2.965 ms 50.024 ms
Tokenjuice: sampled allocation for 2,047 distinct cwd 5.881 GB 5.887 GB

For five samples, nearest-rank p95 is the maximum. Resident history wall ranges were 0.1353–0.1503 ms before and 0.1451–0.1585 ms after; eviction wall ranges were 0.1446–0.1748 and 0.2772–0.3261 ms. Tokenjuice peak-flow p95 was 11.90→12.35 s, stable-working-set p95 197.61→184.79 ms. The first 128-context cold flow was 379.30→430.62 ms median and 400.97→491.53 ms p95; the single first-clear result ranged 47.43–52.63 ms after. A/A controls and allocation runs are separate from timed samples.

All prompt payload/fingerprint digests matched across paired runs, and packaged Tokenjuice outputs matched in the retention regression; benchmark output lengths also matched. Fixtures exercise thousands of cwd identities and long retained conversations through the real owners. Neither owner enumerates unrelated workspace files or reads the agent database; these are owner measurements, not a whole-Gateway, filesystem-platform, or deployment claim.

Focused proof: 124 tests passed, including the new byte-retention regression (406 ms), packaged rule-retention regression (2.075 s), concurrent failure cleanup, and prompt-prefix stability. Both retention regressions fail on the exact baseline for their intended defects. The 103-line test allocation covers these missing memory/lifecycle contracts.

History allocation sampling (two A/A controls and two candidate samples) was 398.6–400.0 MB before and 403.5–403.7 MB after, about +1.1%. Doubling the long-session fixture to 128 sessions retained 6,864,024 bytes after source release; 2,048 short sessions retained 3,831,064 bytes. Separate CPU profiles were collected for both owners. The final eviction-loop simplification uses the same oldest-first policy and also evicts an individually oversized entry through that one path.

Independent Codex autoreview of the complete staged change against the baseline is scoped-clean through P2, with no accepted/actionable findings. Resource acceptance is recorded below.

pnpm check:changed --staged --base HEAD: all checks passed except the inherited unused-export scan. The unused-export gate reproduces on a clean checkout of the exact baseline: postgresSchemaFingerprint was reintroduced by cf50d4a36629 (#192645), and SKILL_WORKSHOP_PLUGIN_ID was introduced by 3e114e23c33c (#192766). These are main regressions, not noise. The PostgreSQL export has since been repaired on main by cfb85a1d15e8 (#192929); the Skill Workshop export remains. No affected owner was edited here. Local pnpm build:ci-artifacts passed, including SDK declarations/exports and built plugin loading. A smoke run of the built Tokenjuice middleware completed 128 distinct cwd calls through the public cleanup import with expected outputs. Separate production/full-tree unused-file scans passed. The build emitted nonfatal Control UI size-budget warnings; no UI-imported module changed. Previous-head CI run 41889018172 completed: only checks-fast-baseline-ratchets failed, with its downstream CI gate; all other selected lanes passed. The separate remote build-artifact workflow also passed. The owner accepted the measured tradeoffs. The rebase is complete at 1a5b0ec11a2535ed3d832e30d3d9783d5e23856a on exact parent 6efce589ab1a0e93e1d338e7d2d0925ced9e5a71; fresh Codex autoreview is scoped-clean through P2 and all 124 focused tests passed again. New exact-head CI run 41892528415 is green for the rebased head.

Previous-head CI failure attribution: the test-line ratchet counts 6,470,146 lines against a 6,470,145 ceiling. This PR adds exactly 103 LF lines and 103 allocation credits. CI's exact main parent dc13ca6d99ce258296cf74d501965ef4d9bf2ae1 already has 6,470,043 lines against 6,470,042. Commit 8e1cc8c469d9 (#192478) introduced seven unallocated lines in src/cli/daemon-cli/lifecycle.test.ts; #192905 reconciled older debt, and #192777 later removed six lines, leaving this one-line main deficit. The unchanged checker permits a zero-delta baseline despite printing its debt; adding fully credited tests exposes it. The exact CI parent also reproduces exit 1 when compared with genuine ancestor f9a25d7c2cac, spanning #192931's own +56 lines and +56 credit: 6,470,043 / 6,470,042, net delta +56. No synthetic edits were used. This was an inherited main regression, not a passing check. It has since been repaired by 58293c5bbec2 (#192932), whose maintainer-approved scalar raise covered its own 187 test lines plus the one inherited line. On the new exact parent, total and ceiling are both 6,470,570. This PR adds exactly 103 LF lines and 103 credits, and the rebased checker passes at 6,470,673 / 6,470,673. No extra allowance is added for unrelated debt.

Rerunnable committed workloads:

node --expose-gc --import ./scripts/tsx.mjs scripts/perf/prompt-cache-observation-measure.ts --sessions 64 --messages 1024 --rounds 1 --reuse-view --allow-eviction
node --expose-gc --import ./scripts/tsx.mjs scripts/perf/prompt-cache-observation-measure.ts --sessions 4 --messages 2048 --rounds 50 --reuse-view
node --expose-gc --import ./scripts/tsx.mjs scripts/perf/tokenjuice-rule-cache-measure.ts --calls 2047
node --expose-gc --import ./scripts/tsx.mjs scripts/perf/tokenjuice-rule-cache-measure.ts --worktrees 2
node --expose-gc --import ./scripts/tsx.mjs scripts/perf/tokenjuice-rule-cache-measure.ts --calls 128 --first-capacity

Final-head local check attribution: the unused-export scan still fails on main-owned exports, all reproduced on exact parent 6efce589ab1a: SKILL_WORKSHOP_PLUGIN_ID (#192766), WORKSHOP_PUBLISH_TIMEOUT_MS (d80b444161de, #192931), and SETUP_PROOF_ACCOUNT_ID, SETUP_PROOF_LOGIN, SETUP_PROOF_REPOSITORY (0b9f3ab3aec3, #192538). Their files are unchanged by this PR. These are main regressions, not passing checks or noise. The parent scan also reports five Talk type exports absent from the built candidate checkout; whole-output equality is not claimed. The native review retains the investigated local failures; final-head CI is green and no CI bypass is requested.

Resource acceptance

Accepted by the perf lead on 2026-11-04 under Peter's standing unattended decision authority: ~0.13 ms extra per observation during continuous history eviction, a one-time ~47 ms Tokenjuice module load, and ~3.26 MB fixed retention, accepted against −75% prompt-cache tracker history retention and −93.8% Tokenjuice rule retention. Reason: the production heap pair on r276 showed these two owners growing +71.5 MB and +36 MB/h at flat load.

@clawsweeper

clawsweeper Bot commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

ClawSweeper review in progress

ClawSweeper is reviewing this revision. This supersedes any previous blocked status.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation scripts Repository scripts agents Agent runtime and tooling extensions: tokenjuice Changes to the bundled tokenjuice extension size: M labels Nov 4, 2026
@steipete
steipete marked this pull request as ready for review November 4, 2026 18:37
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-04T19:01:38.938955Z 1a5b0ec New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. labels Nov 4, 2026
Limit prompt history baselines by estimated bytes as well as session count. Release Tokenjuice compiled rules after bounded distinct workspace contexts while preserving stable-working-set reuse and project rule precedence.

Add 103 regression-test lines for retained-history growth, packaged rule retention, and concurrent failure cleanup. Focused tests pass and Codex autoreview is clean through P2. check:changed fails only on baseline unused exports introduced in #192645 and #192766. Measured eviction and first-cleanup latency tradeoffs are recorded for owner acceptance in the PR.
@steipete
steipete force-pushed the steipete/perf-micro-prompt-cache-trackers-and-tokenjuice-rulecache-20260919 branch from ba01ea5 to 1a5b0ec Compare November 4, 2026 18:59
@clawsweeper clawsweeper Bot removed the clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. label Nov 4, 2026
@steipete
steipete merged commit 1db1416 into main Nov 4, 2026
126 checks passed
@steipete
steipete deleted the steipete/perf-micro-prompt-cache-trackers-and-tokenjuice-rulecache-20260919 branch November 4, 2026 19:17
@steipete

steipete commented Nov 4, 2026

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 5, 2026
…penclaw#192944)

Limit prompt history baselines by estimated bytes as well as session count. Release Tokenjuice compiled rules after bounded distinct workspace contexts while preserving stable-working-set reuse and project rule precedence.

Add 103 regression-test lines for retained-history growth, packaged rule retention, and concurrent failure cleanup. Focused tests pass and Codex autoreview is clean through P2. check:changed fails only on baseline unused exports introduced in openclaw#192645 and openclaw#192766. Measured eviction and first-cleanup latency tradeoffs are recorded for owner acceptance in the PR.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling clawsweeper:intake:bug Preliminary submission classification; full source review pending. docs Improvements or additions to documentation extensions: tokenjuice Changes to the bundled tokenjuice extension scripts Repository scripts size: M

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant