Skip to content

perf(agents): compact retained prompt-cache diagnostics - #178676

Merged
steipete merged 6 commits into
mainfrom
steipete/perf-micro-session-reopen-latency-20260919
Oct 20, 2026
Merged

steipete merged 6 commits into
mainfrom
steipete/perf-micro-session-reopen-latency-20260919

Conversation

@steipete

@steipete steipete commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

Owner acceptance (verbatim)

I ACCEPT #178676. Reasons: retained fingerprints fell 72% (128 → 36 MiB) in both pairs, idle heap growth roughly halved (30% → 17%), reopen and first-text p50/p95 are neutral, and zero session runtime objects were retained. GC was mixed in both directions (reopen minor GC +12% / −8%, major GC −17% / +3%), not a consistent regression. The initial-turn promotion increase (+1.7% / +9.3%) is accepted against ~90 MiB less retained heap. Mark the PR ready, rebase onto latest main if needed, let CI finish (no reruns; use the inherited/unrelated-failure rules if needed), and merge. Report the merge SHA.

Result

The two concurrent, swapped-core Gateway pairs reduce retained diagnostic fingerprints by 71.61% and 71.58%, meeting the 70% memory threshold. The owner accepts the measured initial-turn promotion increase against the retained-memory reduction. The complete per-pair measurements and limits remain below.

What Problem This Solves

Prompt-cache diagnostics retain per-message Maps, arrays, and digest objects after runtime sessions are released. The initial 100-session probe attributed 118.50 MiB to this owner after six minutes idle. The current concurrent baselines retain about 127.8 MiB.

User Impact

Idle sessions retain about 90 MiB less diagnostic heap across this 100-session workload, while preserving history-change diagnostics. The owner accepts the measured initial-turn promotion increase; no user action is required.

Why This Change Was Made

Store full SHA-256 history digests in flat Latin-1 strings with a shared field-name layout. Materialize diagnostic Maps only on divergence. Reopened equal messages reuse the previous baseline; the temporary layout index is discarded after each observation. Provider-request prefixes also pack their full ordered message digests into one string, preserving the existing first-32-message field diagnostic window and 512-message digest bound. Field hashes and public wire diagnostics remain hexadecimal. No provider payload, configuration, schema, retention limit, or cleanup policy changes.

The measured Gateway flow also exposed a separate import-time lifetime: the module-level uninitialized-state Error in src/claws/tool-policy-runtime.ts captured the importing session through lazy stack frames. Construct that Error only in the existing failure branch. The message, cause, consent decision, and fail-closed behavior are unchanged. Both measured sides include this prerequisite, isolating compact fingerprint storage from the independent retention repair.

Runtime production delta: +41 lines. Full hashes, ordered field diagnostics, and lossless compact encoding/decoding account for the growth; the retained object graphs are replaced rather than supplemented by another cache. Related: #178536, #178602.

Evidence

Both concurrent Gateway pairs passed all transcript checks and session-disposal censuses. The tables below retain the measured memory, latency, promotion, and GC tradeoffs.

Measurement

Baseline: 4a4d1e330fdfe92de7fe464d25a6bdf8fd033849. Candidate: c6b4d2f8e2c1a3412b3eec6a5d1d472e161872a2. Both sides receive identical measurement instrumentation and the Error-lifetime prerequisite. Source-performance builds were generated sequentially, with 227 source hashes per tree verified before and after builds. Existing identical dependency installations were reused on both sides (including typebox 1.3.36 and zod 4.6.6).

The committed synthetic Gateway workload uses 100 sessions in cohorts of ten, 655 seeded entries per session, 128 KiB prompts, and six minutes idle before reopening. The roster has 5,000 sessions and 6,000 retained runs. Each pair runs simultaneously under the exclusive measurement lock: baseline on cores 96–111 and candidate on 112–127, then swapped. Separate state directories and loopback ports; outside load recorded. Each side supplies 100 reopen and first-text samples.

After timed reopening, a second six-minute disposal interval precedes fingerprint attribution. Every run passed all 100 append-only transcript checks and had zero reachable SessionManager, AgentSession, and Agent instances. Separate plain forced-GC samples before and after clearing diagnostic observations measure retained fingerprints; this clear never precedes timed reopening. External-memory and array-buffer attribution deltas were zero. Natural main-isolate promotion excludes worker isolates and forced census collections.

Workload command, with separately generated matching synthetic state:

node --import ./scripts/tsx.mjs scripts/perf/transcript-broadcast-measure.ts \
  --state-dir <synthetic-state> --scenario session-idle-retention \
  --sessions 100 --runs 10 --history-turns 163 --chunks 1 \
  --chunk-interval-ms 0 --prompt-kib 128 --duration-ms 360000 \
  --memory-interval-ms 30000 --diagnostics --trace-gc \
  --fingerprint-retention --entry src/entry.ts \
  --start-at <shared-epoch-ms> --port <loopback-port> --mock-port <provider-port>
Metric Pair 1, baseline → candidate Pair 2, baseline → candidate
Retained fingerprints (MiB) 127.74 → 36.26 127.83 → 36.33
Idle heap growth (%) 30.58 → 16.48 30.18 → 17.04
Reopen p50 (ms) 3673.96 → 3649.62 3329.28 → 3223.06
Reopen p95 (ms) 17920.76 → 17626.88 18351.28 → 18425.55
First text p50 (ms) 3137.05 → 3143.77 2725.94 → 2689.54
First text p95 (ms) 17361.77 → 17072.47 17752.44 → 17846.65
Touch promotion (MiB) 6901.69 → 7016.37 7067.36 → 7721.83
Reopen promotion (MiB) 4124.25 → 4546.53 4103.23 → 3919.31
Reopen minor GC count 711.00 → 786.00 661.00 → 615.00
Reopen minor GC time (ms) 2701.51 → 3023.58 2608.89 → 2405.64
Reopen major GC count 8.00 → 6.00 7.00 → 7.00
Reopen major GC time (ms) 462.80 → 385.29 453.50 → 467.63
Reopen main CPU (ms) 33567.21 → 36009.68 30004.17 → 27386.91
Reopen process CPU (ms) 108645.42 → 110374.51 98873.35 → 98077.77

Pair 1: -71.61% retained fingerprint change (-91.48 MiB).

Pair 2: -71.58% retained fingerprint change (-91.50 MiB).

Initial-turn GC, outside the reopen window:

Metric Pair 1, baseline → candidate Pair 2, baseline → candidate
Minor GC count / time (ms) 1401 / 4937.89 → 1350 / 4785.18 1361 / 4983.80 → 1538 / 5447.46
Major GC count / time (ms) 11 / 679.17 → 10 / 831.63 8 / 494.92 → 10 / 642.22

The promotion increase is not explained by the current aggregate operation counters. A read-only source audit found no added timer, event, or persistence call in compact diagnostics; the generic patch counter includes no-op attempts and the transcript-worker counter combines request kinds. Those counts are diagnostic clues, not grounds to normalize away or waive the promotion gate.

Focused proof and limits

  • The provider-prefix change passed 46 focused tests across model-request-body, prompt-cache-observability, and provider-prompt-state. Earlier history/observation/provider-state/prefix-stability proof passed 85 tests; the benchmark profile helper passed nine tests and the consent-policy files passed four. Changed-file format and lint passed.
  • Fresh independent Codex autoreview is scoped-clean through P2, including the provider-prefix change. The requested same-engine retry after the initial rate limit succeeded. The final rebase was patch-identical for the reviewed change and its supplied caller context.
  • PR CI run 39507503012 passed on the unchanged measured/reviewed head c6b4d2f8e2c1a3412b3eec6a5d1d472e161872a2, including the aggregate CI gate. The PR context check initially rejected nonstandard body headings; restoring the repository template headings fixed that body-only failure. No manual CI rerun, broad local suite, extra local install, or additional typecheck lane was used for this follow-up.
  • The deterministic synthetic provider does not establish real-provider reconnect or prompt-cache-hit behavior. The source-runtime absolute timings are not a packaged-runtime comparison.
  • The owner explicitly accepts the measured promotion tradeoff above. The source/package comparison queue is stopped and its sandbox files have been removed; raw measurement evidence is preserved.

@clawsweeper

clawsweeper Bot commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

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

ClawSweeper review complete

ClawSweeper finished reviewing this revision. The review result is being finalized.

View the workflow run.

@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: S labels Oct 20, 2026
@steipete
steipete marked this pull request as ready for review October 20, 2026 18:53
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 20, 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-10-20T22:24:19.033258Z c6b4d2f Draft marked ready
ℹ️ 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.

@steipete
steipete force-pushed the steipete/perf-micro-session-reopen-latency-20260919 branch from c1a823c to c7093c6 Compare October 20, 2026 18:58
@openclaw-barnacle openclaw-barnacle Bot added the scripts Repository scripts label Oct 20, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Oct 20, 2026
@clawsweeper

clawsweeper Bot commented Oct 20, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR compacts retained prompt-history fingerprints while preserving append-only checks and field-level diagnostics.

Example: A Gateway keeps diagnostic baselines for 100 idle sessions with 655 entries each.

  • Before: The reported baseline attributes 118.50 MiB of retained heap to prompt-cache observations after session objects collect.
  • After: Fingerprints use compact arrays, shared hashes, and reused baselines; the final memory reduction remains unmeasured.

Review scores

Measure Result What it means
Overall readiness 🧂 unranked krab (1/6) The implementation is focused and source-consistent, but the author-required performance acceptance has no final-result evidence.
Proof confidence 🧂 unranked krab (1/6) Real behavior proof is not required for maintainer- or bot-authored pull requests.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Idle sessions with long histories retain substantial diagnostic memory even after their runtime objects collect.
Reason: The maintainer-authored direction addresses an attributed cost while retaining useful diagnostics; the only new option is the internal benchmark's --fingerprint-retention flag.

Merge readiness

✅ Ready for maintainer review

Keep open: this maintainer-authored optimization addresses diagnostic memory still retained on main, and inspection found no actionable code defect.

Priority: P2
Reviewed head: c7093c647a17ee20fa9a853aa6fa1981ff410231

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: The final representation lacks the required paired source-Gateway idle/reopen comparison demonstrating the memory target without promotion or latency regression.
Agent review details

How this fits together

Before model dispatch, the request observer fingerprints conversation history through the existing worker and compares it with bounded session baselines, producing cache-change diagnostics without changing provider messages.

flowchart LR
  A[Conversation messages] --> B[Request observer]
  B --> C[History preparation worker]
  C --> D[Compact fingerprints]
  D --> E[Session diagnostic baseline]
  E --> F[Rewrite and cache diagnostics]
Loading

Technical review

Best possible solution:

Compact the existing diagnostic baseline while preserving exact rewrite detection, bounded field details, and session cleanup.

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

Main visibly retains per-message diagnostic Maps after runtime disposal, and the linked Gateway attribution reports 118.50 MiB; this review executed no target code and independently verified no memory magnitude.

Is this the best way to solve the issue?

The change uses the existing fingerprint, worker, tracker, and cleanup owners, removes the superseded equality helper, and preserves diagnostic ordering and redaction without introducing another persistent cache.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 1c4b27072712.

Provenance checked

  • History fingerprint representation and equality keeps the original intent (9dcbe40: Prepare sealed history off-thread while preserving mutable-input rewrite detection and fingerprint reuse.)
  • Field-level history diagnostics keeps the original intent (7fc9770: Identify safe changed block-field paths without exposing content or dynamic extension names.)
  • Source-Gateway census and idle reopening benchmark keeps the original intent (5c1432f: Count disposed session instances using matching source-module identities and verify transcript integrity across idle reopening.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit b61b080 adds src/agents/embedded-agent-runner/prompt-cache-observability.ts:103 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: b61b0809c637; files: src/agents/embedded-agent-runner/prompt-cache-observability.ts)
  • Vincent Koc: Raw commit c76646a adds src/agents/pi-embedded-runner/prompt-cache-observability.ts:49 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: c76646adb135; files: src/agents/pi-embedded-runner/prompt-cache-observability.ts)

PR surface

Source +25, Tests 0, Docs +7, Other +39. Total +71 across 7 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 2 63 38 +25
Tests 1 6 6 0
Docs 1 7 0 +7
Config 0 0 0 0
Generated 0 0 0 0
Other 3 44 5 +39
Total 7 120 49 +71

Review metrics

Metric Value Why it matters
Production versus test LOC Runtime +63/-38 (net +25); tests +6/-6 (net 0) Runtime growth supports compact encoding, lazy diagnostic decoding, and temporary hash sharing; test edits follow the digest implementation.

Labels

Label changes:

  • add P2: Reducing retained diagnostic memory benefits long-history Gateways, with no demonstrated outage or urgent regression.
  • add rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Label justifications:

  • P2: Reducing retained diagnostic memory benefits long-history Gateways, with no demonstrated outage or urgent regression.
  • rating: 🧂 unranked krab: Overall readiness is 🧂 unranked krab; proof is 🧂 unranked krab and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Rank-up moves

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

  • Provide the final representation's paired Gateway measurements against the acceptance rule already recorded in the PR.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

Reviewed October 20, 2026, 3:13 PM ET / 19:13 UTC.

@steipete
steipete marked this pull request as draft October 20, 2026 19:24
@steipete
steipete force-pushed the steipete/perf-micro-session-reopen-latency-20260919 branch from c7093c6 to d59a62c Compare October 20, 2026 19:38
@steipete
steipete marked this pull request as ready for review October 20, 2026 19:39
@steipete
steipete force-pushed the steipete/perf-micro-session-reopen-latency-20260919 branch from d59a62c to 0591c41 Compare October 20, 2026 19:47
@steipete
steipete force-pushed the steipete/perf-micro-session-reopen-latency-20260919 branch from 0591c41 to 8a5f7bb Compare October 20, 2026 20:26
@steipete
steipete marked this pull request as draft October 20, 2026 21:15
@steipete
steipete force-pushed the steipete/perf-micro-session-reopen-latency-20260919 branch from 8a5f7bb to c6b4d2f Compare October 20, 2026 21:27
@steipete
steipete marked this pull request as ready for review October 20, 2026 21:28
@steipete
steipete marked this pull request as draft October 20, 2026 22:13
@steipete steipete changed the title perf(agents): compact retained prompt-history diagnostics perf(agents): compact retained prompt-cache diagnostics Oct 20, 2026
@steipete
steipete marked this pull request as ready for review October 20, 2026 22:21
@steipete
steipete merged commit e9e4dae into main Oct 20, 2026
389 of 416 checks passed
@steipete
steipete deleted the steipete/perf-micro-session-reopen-latency-20260919 branch October 20, 2026 23:16
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 21, 2026
)

* perf(agents): compact retained prompt-history diagnostics

* perf(agents): share compact diagnostic field hashes

* perf(agents): pack diagnostic fingerprints into flat strings

* test(perf): separate census from retention samples

* fix(claws): avoid retaining the first caller in an error stack

* perf(agents): compact provider-request diagnostic fingerprints
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. scripts Repository scripts size: M 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.

1 participant