Skip to content

perf(agents): bound per-run retained state and share registry snapshots by revision - #164199

Merged
steipete merged 1 commit into
mainfrom
steipete/perf-micro-agent-run-retention-20260919
Oct 3, 2026
Merged

steipete merged 1 commit into
mainfrom
steipete/perf-micro-agent-run-retention-20260919

Conversation

@steipete

@steipete steipete commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Long agent runs retain settled bridge wait reactions, serialized Code Mode outcomes, sanitizer snapshots, and queued trajectory events. Registry reads repeatedly copy published tool-result payloads.

User Impact

A synthetic hour-long agent run with 2,000 nested tool calls retained 33.37% less additional heap per call. Pending operations, loop detection, redaction, hook behavior, and the existing durable trajectory window are preserved. No configuration or schema migration is required.

This does not eliminate all run growth: SessionManager and the separate nested activity projection used by finalization hooks remain significant retainers. The production heap slope has not been remeasured.

Why This Change Was Made

Bridge frontiers now have one removable observer, and settled bridges release their cancellation closure. Private Code Mode outcomes retain canonical hashes. Sanitized projections belong to one event through its consumers, preserving mutation and policy invalidation without the global cache. Registry readers share frozen row publications; their scoped Map views remain caller-owned.

The trajectory writer transfers an admitted batch into its own lifetime while new events enter a bounded queue. Known failures restore the batch; uncertain outcomes remain fenced. Queued eviction boundaries reach the existing transactional trim operation, preserving the newest durable suffix and cursor advancement even during overlapping writes.

Production LOC: +101 (+284/-183). This is an exception to the net-negative target: cancellable observation, mutable callback redaction safety, and asynchronous write settlement with unchanged durable retention require explicit ownership. The global sanitizer cache, per-bridge Promise, read-time deep clones, and borrowPersisted branch are removed. No competing compatibility path remains. Failed physical continuation disposal still retains its owner until cleanup succeeds, preserving retry and runtime-refresh authority.

Evidence

Linux rig openclaw-node-01, Node 26.8.1, synthetic-only state and loopback mock providers. Each side completed one 60-minute agent run with 2,000 unique nested calls, including one long pending call beside 1,999 paced calls. Provider-observed output and terminal receipts passed. scripts/heap-snapshot-diff.mjs compared each process's minute-10/minute-60 snapshots over 1,666 additional completed calls.

Measurement Before After
Heap growth per additional call 79,382.81 B 52,892.95 B
Heap growth in measured window 132,251,760 B 88,119,648 B
Trajectory sink retention, minute 10→60 8,860,480→52,591,080 B 161,360→186,752 B
Promise count growth 1,702 37
SessionManager retained growth 42,806,944 B 42,806,928 B
Run duration, including held-call completion 3,624.455 s 3,621.863 s
Peak sampled RSS, including snapshot overhead 2,212.30 MiB 2,163.05 MiB

Narrow 2,000-item measurements of the unchanged outcome/sanitizer/registry paths:

Measurement Before After
Private outcome bytes per call 8,268.60 64
Outcome fixture GC growth per call 15,126.03 B 233.78 B
Sanitizer fixture GC growth per call, raw results retained 12,734.66 B 8,476.44 B
Deep clones for 2,000 fresh registry prepare/read operations 4,000 0
Retained full-row identities across those reads 2,000 1
Registry fixture GC growth per read 8,805.67 B 59.28 B

Single-observation elapsed times: outcomes 75.65→71.79 ms, sanitizer 3.642→3.422 s, registry 356.60→336.98 ms. These include forced-GC samples and are not statistical throughput claims. The required hour run used generation patch eff5730d; the subsequent changes only repair a test mock's lifecycle signature and make a GC-test predicate explicitly boolean.

Validation:

  • Blacksmith Testbox tbx_01m403m8f8tw3pncwzfbte2jkj: affected rerun passed 150 tests across nine files. Its 604.34 s wall time included cold E2E runtime preparation.
  • Blacksmith Testbox tbx_01m40b78cvzvnh18ym66h1wwwd: node scripts/run-vitest.mjs src/trajectory/runtime-store-writer.test.ts src/trajectory/runtime-store.sqlite.test.ts src/trajectory/runtime.test.ts --maxWorkers=1 passed 62 tests across three files, 45.79 s runner wall time.
  • All four initial regressions fail on original production code for the intended defects: retained bridge promises 201→3,801; outcome bytes 13,038,000 versus 128,000; queued trajectory bytes 1,384,676 versus 65,536; registry row identities 2,000 versus 1.
  • Review regressions also fail on their preceding candidates: evicted queued prefixes preserved stale durable rows, and overlapping A/B/C writes dropped B. The final implementation passes the bounded queue, commit/refusal, cursor, retry, and unknown-outcome cases.
  • Independent Codex review is scoped-clean at P0–P2 after resolving both trajectory findings. Later mechanical test corrections are covered by the final typecheck/lint gate.
  • Authorized Linux rig fallback (openclaw-node-01, /srv/rig/wt-lane369-gate-20261003): node scripts/check-changed.mjs --staged passed, exit 0, 08:22–08:55 UTC. Core lint: zero warnings/errors, 611.9 s. All three dead-export scans: zero entries. Native schema, database-first storage, sidecar loader, runtime import-cycle (zero cycles), webhook, and pairing guards passed. The helper retains the final 80 log lines; it did not emit an aggregate timing table. Staged patch SHA-256: 033f490f26619f7f431df8eb0cf26c8d4707ecddc9e3bb4f4901bbff0df2bcac.

Focused per-file cost on that Testbox, using node scripts/run-vitest.mjs <file> --maxWorkers=1:

File Tests Wall seconds
code-mode-retention.test.ts 2 8.49
tool-loop-detection.test.ts 54 2.46
subagent-registry-state.test.ts 38 7.49
runtime-store-writer.test.ts 10 14.50
embedded-agent-tool-results.cache.test.ts 12 1.77
embedded-agent-tool-results.reuse.test.ts 1 14.03

The writer cases use real SQLite worker admission, native settlement, and durable reads to prove failure/overlap behavior; a mocked store cannot establish those contracts. Most other file wall time is import/transform cost. Exact-head CI run 37111483510 passed on 280c0a811dd87838b5f8f2a04241bdfb57dde2b1: 695 seconds workflow wall time and 10,163 aggregate job-wall seconds excluding skipped jobs (whole workflow, including setup/builds; not incremental test cost). All executed jobs succeeded; no rerun was needed.

The first hour fixture exhausted its default 10-second cumulative guest budget at 1,767 calls. Both completed comparisons use the existing 60-second fixture budget; the failed attempt is not counted. Testbox sync/admission failures required replacement leases and the authorized staged-gate fallback on the rig. All heavy validation ran remotely.

Remaining follow-up: reuse canonical transcript facts for nestedToolActivities hook projection and retain narrow successful-name facts for settlement. The array still holds full results after persistence; removing it without preserving finalization and agent-end hooks would change behavior. Shared/internalized string roots account for roughly 40.4 MB that is not visible in the application's exclusive dominator totals.

@clawsweeper

clawsweeper Bot commented Oct 3, 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.

@steipete
steipete marked this pull request as ready for review October 3, 2026 08:58
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation agents Agent runtime and tooling size: XL labels Oct 3, 2026
@steipete
steipete enabled auto-merge (squash) October 3, 2026 09:02
@clawsweeper

clawsweeper Bot commented Oct 3, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed October 3, 2026, 5:04 AM ET / 09:04 UTC.

ClawSweeper review

What this changes

The PR reduces memory retained during long agent runs by releasing settled waits, hashing private outcomes, sharing immutable registry rows, and batching trajectory events through a bounded queue.

Merge readiness

✅ Ready for maintainer review

Keep open: current main still contains the retention patterns this PR addresses, and the branch provides useful, focused performance work. No concrete introduced correctness defect was found.

Priority: P2
Reviewed head: 280c0a811dd87838b5f8f2a04241bdfb57dde2b1

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) Useful, coherent performance work with quantified runtime evidence and focused lifecycle/storage regressions, with no blocking correctness finding.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): The captured body reports after-fix runs through the actual agent runtime on Linux with synthetic state and loopback providers, including 2,000 nested calls and a pending sibling, with observed output and reduced heap growth. SQLite settlement regressions supplement that evidence; production heap slope was not remeasured. No schema or persisted-format contract changes require migration.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The captured body reports after-fix runs through the actual agent runtime on Linux with synthetic state and loopback providers, including 2,000 nested calls and a pending sibling, with observed output and reduced heap growth. SQLite settlement regressions supplement that evidence; production heap slope was not remeasured. No schema or persisted-format contract changes require migration.
Evidence reviewed 10 items Pinned introduced changes: Reviewed the merge-base-to-head production hunks and associated regression changes. The checkout is the original PR head; base-branch drift was not attributed to this PR.
Still necessary on current main: Current main retains serialized private Code Mode outcomes. The inspected main-to-head comparison also retains the old pending-event array and per-bridge promises on main, establishing that the central improvements remain absent.
Trajectory settlement and retention: Batch transfer occurs inside writer admission; definite failures restore the batch ahead of later arrivals, while unknown outcomes fence replay. Queue eviction reaches the existing transactional trim without changing the schema or serialized event format.
Findings None None.
Security None None.

How this fits together

The agent runtime consumes model and tool events and maintains pending work, tool-result projections, and subagent registry views. Trajectory capture records diagnostic events into the per-agent SQLite database for later inspection and export.

flowchart TD
  A[Model and tool events] --> B[Agent runtime]
  B --> C[Pending bridge waits]
  B --> D[Prepared tool results]
  B --> E[Immutable registry publications]
  D --> F[Bounded trajectory queue]
  F --> G[Admitted SQLite writer]
  G --> H[Diagnostic export]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +101, Tests +428, Docs +2. Total +531 across 38 files.

View PR surface stats
Area Files Added Removed Net
Source 18 284 183 +101
Tests 19 536 108 +428
Docs 1 5 3 +2
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 38 825 294 +531

Review metrics

Metric Value Why it matters
Production versus regression growth production +101 lines; tests and test support +428 lines The PR explicitly justifies production growth through cancellable observation, mutation-safe redaction, and asynchronous write settlement ownership.

Technical review

Best possible solution:

Keep retention bounded within the existing lifecycle and storage owners while preserving pending work, redaction, immutable publications, and the durable diagnostic window.

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

Yes, source inspection establishes the retained serialized outcomes, per-bridge reactions, and unbounded queued events; the PR also reports paired long-run measurements. This review did not execute a current-main reproduction.

Is this the best way to solve the issue?

Yes, the patch keeps the changes at the existing owners and removes redundant retention while preserving their lifecycle contracts; no actionable alternative or introduced defect was established.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • add P2: This addresses measurable memory growth during long agent runs without evidence of an urgent user-facing outage.
  • add proof: sufficient: Contributor real behavior proof is sufficient. The captured body reports after-fix runs through the actual agent runtime on Linux with synthetic state and loopback providers, including 2,000 nested calls and a pending sibling, with observed output and reduced heap growth. SQLite settlement regressions supplement that evidence; production heap slope was not remeasured. No schema or persisted-format contract changes require migration.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.

Label justifications:

  • P2: This addresses measurable memory growth during long agent runs without evidence of an urgent user-facing outage.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • proof: sufficient: Contributor real behavior proof is sufficient. The captured body reports after-fix runs through the actual agent runtime on Linux with synthetic state and loopback providers, including 2,000 nested calls and a pending sibling, with observed output and reduced heap growth. SQLite settlement regressions supplement that evidence; production heap slope was not remeasured. No schema or persisted-format contract changes require migration.

Evidence

What I checked:

  • Pinned introduced changes: Reviewed the merge-base-to-head production hunks and associated regression changes. The checkout is the original PR head; base-branch drift was not attributed to this PR. (280c0a811dd8)
  • Still necessary on current main: Current main retains serialized private Code Mode outcomes. The inspected main-to-head comparison also retains the old pending-event array and per-bridge promises on main, establishing that the central improvements remain absent. (src/agents/code-mode-tool-outcome.ts:25, dd66b6780734)
  • Trajectory settlement and retention: Batch transfer occurs inside writer admission; definite failures restore the batch ahead of later arrivals, while unknown outcomes fence replay. Queue eviction reaches the existing transactional trim without changing the schema or serialized event format. (src/trajectory/runtime-store-writer.ts:158, 280c0a811dd8)
  • Durable boundary regression coverage: The writer regressions exercise real worker-backed SQLite admission and durable reads for bounded queues, lost results, unknown settlement, existing durable prefixes, cursors, and overlapping committed/refused batches. They were inspected but not executed during this read-only review. (src/trajectory/runtime-store-writer.test.ts:156, 280c0a811dd8)
  • Redaction invalidation: Event-scoped preparation validates both input and output snapshots plus the current redaction policy before reuse. Inspected regressions cover consumer mutation, structural changes, accessors, proxies, and newly registered secrets. (src/agents/embedded-agent-tool-result-preparation.ts:84, 280c0a811dd8)
  • Immutable registry publications: Full worker reads freeze admitted row publications after preserving their version facts. Read-context checks, physical database identity selection, and synchronous consumption remain in place; persistence and restore callers publish immutable replacements. (src/agents/subagents/registry/subagent-registry-read-cache.ts:415, 280c0a811dd8)

Likely related people:

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

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 size: XL

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant