Skip to content

improve: bound retained tool-result projection data - #139157

Merged
steipete merged 2 commits into
mainfrom
codex/perf10-tool-retention
Sep 5, 2026
Merged

steipete merged 2 commits into
mainfrom
codex/perf10-tool-retention

Conversation

@steipete

@steipete steipete commented Sep 5, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

The session-owned tool-result projection cache retained complete source text for every frozen result, including results that did not need truncation. Cached replacement messages also retained details and non-text content. A long history could therefore keep large read/web outputs alive after the caller released the original messages.

Why This Change Was Made

Store a framed SHA-256 source digest and only the projected output needed for replay. The shared projection-state owner records text blocks for ordinary truncation and exact projected content for cache-TTL replay. Current canonical messages supply metadata and non-text blocks. This removes the complete-message cache and original-text arrays without changing the existing identity, reset, compaction, TTL marker, or source-rewrite invalidation rules.

User Impact

Less session-cache retention after large tool outputs leave the active caller. Existing projected prompt bytes remain frozen across attempts, current metadata stays current, and compaction/reset reclaim the same entries. There is no new setting, schema, storage format or provider eligibility change.

Production +67/-46 (net +21); tests/support +89/-33 (net +56); assertion baseline +1/-1. The production growth establishes one projection-storage owner shared by ordinary and TTL replay. It replaces complete message/source retention while preserving their different content contracts; this ownership boundary needs the additional code.

Evidence

  • Retained-data regression failed on the original owner: 305,346 serialized cache characters exceeded the 6,000-character bound. The final candidate passes and preserves current canonical details, original input content, images and malformed content behavior.
  • Final owner suite: 94 tests across three files and two shards passed. Coverage includes framed block boundaries and lone surrogates, ambiguous keys, cross-attempt frozen bytes, canonical compaction versus provider-filtered history, reset, restored soft/hard TTL projections, and malformed restored content. The malformed/null cases were reproduced before their final fixes and rerun successfully. Final formatting, assertion ratchet and managed P2 review passed with no findings.
  • Fresh-process retained-heap cohorts on Node 26.8.1 retained only the cache after releasing input/output arrays and forcing GC. Sixteen approximately 1 MiB tool results measured 16,834,616 → 39,336 bytes for unchanged outputs, 16,985,168 → 193,328 bytes for truncated outputs, and 16,985,712 → 193,072 bytes with duplicated details. Each before/after output digest matched. These are bounded cache-retention measurements, not process RSS or total Gateway memory.
  • Hashing has a cost. Repeated fitting-history reconciliation/projection measured approximately 0.063 → 0.067 ms per turn for 16 KiB, 0.21 → 0.44 ms for 256 KiB, and 9.27 → 25.22 ms for 16 MiB. These descriptive shared-host measurements disclose the tradeoff; no response-latency or whole-Gateway improvement is claimed.
  • The exact two production blobs also ran in the compiled 20-change candidate: ten real OpenAI outer turns using the public openai/gpt-5.6-luna model across code-mode and tool-search profiles, 14 stages and 50 phases. That B1 run exited cleanly without forced shutdown; all 69 owned process identities and both listeners were cleared. This proves compiled behavior for the combined candidate, not an isolated performance gain from this PR.
  • Original author commit matches all eleven frozen reviewed files. A normal main merge preserves the exact introduced patch, the independently landed HTTP assertion count of 28, the tool-result count of 17, and upstream settlement test additions. Exact-head hosted CI and native preparation passed; native merge verification remains required.

Related #127992 changes OpenAI cache-TTL route eligibility. This PR changes the generic projection cache representation and leaves that eligibility policy untouched.

Data-model compatibility proof: only the process-local projection cache representation changes. Source hashes are never serialized. The existing openclaw.cache-ttl marker still records the same projection key, soft/hard mode and hard-clear placeholder; its reader is unchanged. Existing saved markers rebuild the compact cache through the same restoration path, and final soft/hard restart, pruning-disabled replay, ambiguous-key, compaction/reset and malformed-content tests pass. The canonical transcript and SQLite schema/versions are unchanged, so no migration or upgrade action is required. This addresses the latest ClawSweeper compatibility request; there are no code findings or separate rank-up moves.

Current-main composition: external #139156 adds synchronous replacement-plan budget measurements in the same module. A conflict-free merge-tree reconstruction preserves its changes and this exact introduced patch (stable patch ID 5819fd67901d77fd1834925312b9129da738a8e7); those measurements never enter session projection state. The isolated measurements above remain attributed to the reviewed candidate, not this additional upstream optimization. Exact-head CI run 33973209966 passed.

@clawsweeper

clawsweeper Bot commented Sep 5, 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: M maintainer Maintainer-authored PR labels Sep 5, 2026
@steipete
steipete marked this pull request as ready for review September 5, 2026 14:54
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. 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 Sep 5, 2026
@clawsweeper

clawsweeper Bot commented Sep 5, 2026

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 5, 2026, 11:03 AM ET / 15:03 UTC.

ClawSweeper review

What this changes

Reduces memory retained between agent turns by replacing cached original tool-output text and complete messages with source hashes and the content needed for replay.

Merge readiness

⛔ Blocked before merge - 1 item remains

Keep open: this optimization remains useful on current main, and the introduced patch has no blocking correctness findings.

Priority: P2
Reviewed head: 238af4c2ed86f23db8489dd64234aea8c7f77a3a

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused owner-level optimization with useful retention evidence, disclosed CPU cost, and no blocking findings.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): Reported Node 26.8.1 cache-only GC cohorts exercise the projection owner after caller arrays are released, show substantially lower retained heap, and preserve output digests; the combined real-provider run supplies supplemental integration evidence.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): Reported Node 26.8.1 cache-only GC cohorts exercise the projection owner after caller arrays are released, show substantially lower retained heap, and preserve output digests; the combined real-provider run supplies supplemental integration evidence.
Evidence reviewed 10 items Verified introduction and merge boundaries: The pinned merge-base-to-head diff contains the projection changes and corresponding fixtures. The test merge has the exact base and PR-head parents; its two production files match the reviewed head. Android changes belong to base drift.
Current main still retains complete sources: Current main stores complete replacement messages and original text arrays in the session cache, confirming that the requested retention improvement is still absent.
Storage owner and replay contracts: The shared recorder retains text-only blocks for ordinary truncation and exact projected content for cache-TTL replay. The replay merger takes metadata and ordinary non-text blocks from the current message; JSON-framed hashes preserve text-block boundaries and lone surrogates during source invalidation.
Findings None None.
Security None None.

How this fits together

The embedded agent runner prepares conversation history before sending it to a model. Its session-owned projection cache preserves previously shortened tool results across turns while canonical history supplies current metadata and images.

flowchart TD
  A[Canonical conversation history] --> B[Tool-result projection]
  C[Source hashes and retained content] --> B
  B --> C
  D[Saved pruning markers] --> B
  B --> E[Model request]
  F[Compaction or session reset] --> C
Loading

Before merge

  • Add data-model compatibility proof - Confirm migration or upgrade compatibility proof before merge.
Agent review details

Security

None.

PR surface

Source +21, Tests +56, Other 0. Total +77 across 11 files.

View PR surface stats
Area Files Added Removed Net
Source 2 67 46 +21
Tests 8 89 33 +56
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 1 1 1 0
Total 11 157 80 +77

Review metrics

Metric Value Why it matters
Production versus test growth Production +21 net; tests/support +56 net; assertion baseline net 0 The production growth establishes one shared recorder for ordinary and TTL content contracts while removing complete-message and original-text retention.
Reported hashing tradeoff 16 MiB history: 9.27 → 25.22 ms per reconciliation/projection turn The author discloses additional processing cost separately from cache-retention savings and makes no whole-Gateway latency claim.

Stored data model

Persistent data-model change detected: serialized state: src/agents/embedded-agent-runner/tool-result-truncation.ts, unknown-data-model-change: src/agents/embedded-agent-runner/tool-result-truncation.ts. Confirm migration or upgrade compatibility proof before merge.

Technical review

Best possible solution:

Keep the compact session-owned cache and existing replay lifecycle; arbitrary entry eviction would discard still-needed frozen projections.

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

Yes for excess retention: current main stores full source strings and replacement messages, and the PR supplies a concrete cache-only heap comparison. This read-only review did not rerun it.

Is this the best way to solve the issue?

Yes. Repairing the shared storage owner removes redundant retention without expiring frozen projections or changing persisted markers; the small production increase supports the distinct ordinary and TTL replay contracts.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • add P2: This is a focused memory-retention improvement for tool-heavy sessions, without evidence of an urgent outage.
  • add proof: sufficient: Contributor real behavior proof is sufficient. Reported Node 26.8.1 cache-only GC cohorts exercise the projection owner after caller arrays are released, show substantially lower retained heap, and preserve output digests; the combined real-provider run supplies supplemental integration evidence.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): Reported Node 26.8.1 cache-only GC cohorts exercise the projection owner after caller arrays are released, show substantially lower retained heap, and preserve output digests; the combined real-provider run supplies supplemental integration evidence.

Label justifications:

  • P2: This is a focused memory-retention improvement for tool-heavy sessions, without evidence of an urgent outage.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): Reported Node 26.8.1 cache-only GC cohorts exercise the projection owner after caller arrays are released, show substantially lower retained heap, and preserve output digests; the combined real-provider run supplies supplemental integration evidence.
  • proof: sufficient: Contributor real behavior proof is sufficient. Reported Node 26.8.1 cache-only GC cohorts exercise the projection owner after caller arrays are released, show substantially lower retained heap, and preserve output digests; the combined real-provider run supplies supplemental integration evidence.

Evidence

What I checked:

  • Verified introduction and merge boundaries: The pinned merge-base-to-head diff contains the projection changes and corresponding fixtures. The test merge has the exact base and PR-head parents; its two production files match the reviewed head. Android changes belong to base drift. (34685189ab9b)
  • Current main still retains complete sources: Current main stores complete replacement messages and original text arrays in the session cache, confirming that the requested retention improvement is still absent. (src/agents/embedded-agent-runner/session-prompt-state.ts:6, 12a3b102f507)
  • Storage owner and replay contracts: The shared recorder retains text-only blocks for ordinary truncation and exact projected content for cache-TTL replay. The replay merger takes metadata and ordinary non-text blocks from the current message; JSON-framed hashes preserve text-block boundaries and lone surrogates during source invalidation. (src/agents/embedded-agent-runner/session-prompt-state.ts:64, 238af4c2ed86)
  • Production callers and lifecycle: Provider dispatch calls the projection owner through submitEmbeddedAttemptPrompt. Prompt preparation reconciles canonical history and clones state for preflight; reset cleanup deletes session state, and overflow recovery reconciles after transcript rewrites. These lifecycle boundaries remain unchanged. (src/agents/embedded-agent-runner/run/attempt-prompt-submit.ts:109, 238af4c2ed86)
  • Focused retention and replay coverage: The new regression bounds serialized retained state while checking current metadata, images, malformed blocks, and unchanged source input. Additional cases distinguish framed text boundaries and lone surrogates. Existing coverage exercises frozen prefixes, provider-filtered history, compaction, reset, and soft/hard TTL restoration. Tests were inspected, not executed during this read-only review. (src/agents/embedded-agent-runner/tool-result-truncation.test.ts:1510, 238af4c2ed86)
  • Documented preservation contract: Session-pruning documentation requires stable projected bytes across turns and restarts, with reclamation through compaction or reset. The patch leaves marker fields and pruning eligibility unchanged. Public docs: docs/concepts/session-pruning.md. (docs/concepts/session-pruning.md:79, 238af4c2ed86)

Likely related people:

  • Peter Steinberger: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)
  • Ayaan Zaidi: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

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.

@steipete
steipete merged commit 3190306 into main Sep 5, 2026
260 checks passed
@steipete
steipete deleted the codex/perf10-tool-retention branch September 5, 2026 15:10
@steipete

steipete commented Sep 5, 2026

Copy link
Copy Markdown
Contributor Author

Merged via squash.

vincentkoc added a commit to aniruddhaadak80/openclaw that referenced this pull request Sep 5, 2026
* origin/main: (46 commits)
  fix(gateway): keep chat metadata responsive across auth refresh (openclaw#139192)
  fix(doctor): keep Workshop relocation lint read-only (openclaw#139193)
  perf(ui): retain unchanged forwarded avatar publications (openclaw#139181)
  fix(config): guide exec policy migration repairs (openclaw#139143)
  test(i18n): refresh representative Watch key (openclaw#139197)
  fix(agents): preserve recovered scheduled-run outcomes (openclaw#139037)
  refactor(acp): simplify pending operation accounting (openclaw#139189)
  fix(plugin-sdk): harden account scope for pairing requests and challenges (openclaw#139142)
  perf(gateway): avoid redundant PR landing ancestry checks (openclaw#139186)
  perf(ui): release captured audio cache leases directly (openclaw#139174)
  fix(skills): validate names in library forms (openclaw#139184)
  fix(sessions): reduce cold catalog listing delays (openclaw#139146)
  perf(cron): scan preserved action output once (openclaw#139163)
  fix(agents): keep fresh tool results readable under context pressure (openclaw#139165)
  fix(compaction): heartbeat sessions ignore the active transcript byte cap (openclaw#136533)
  perf(agents): reuse snapshotted web search result rows (openclaw#139162)
  fix(onboarding): keep Tauri setup recoverable and verify model results (openclaw#139140)
  fix(memory): rank indexed sessions by source activity (openclaw#139112)
  perf(terminal): avoid rebuilding sanitized link fallbacks (openclaw#139159)
  perf(agents): bound retained tool result projection data (openclaw#139157)
  ...
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 6, 2026
necromman pushed a commit to necromman/openclaw that referenced this pull request Sep 20, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling maintainer Maintainer-authored PR P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. 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