Repository navigation
perf(agents): bound per-run retained state and share registry snapshots by revision - #164199
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
|
Codex review: needs maintainer review before merge. Reviewed October 3, 2026, 5:04 AM ET / 09:04 UTC. ClawSweeper reviewWhat this changesThe 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 Review scores
Verification
How this fits togetherThe 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]
Before mergeNone. Agent review detailsSecurityNone. PR surfaceSource +101, Tests +428, Docs +2. Total +531 across 38 files. View PR surface stats
Review metrics
Technical reviewBest 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. LabelsLabel changes:
Label justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
|
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
borrowPersistedbranch 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.mjscompared each process's minute-10/minute-60 snapshots over 1,666 additional completed calls.Narrow 2,000-item measurements of the unchanged outcome/sanitizer/registry paths:
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:
tbx_01m403m8f8tw3pncwzfbte2jkj: affected rerun passed 150 tests across nine files. Its 604.34 s wall time included cold E2E runtime preparation.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=1passed 62 tests across three files, 45.79 s runner wall time.openclaw-node-01,/srv/rig/wt-lane369-gate-20261003):node scripts/check-changed.mjs --stagedpassed, 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:code-mode-retention.test.tstool-loop-detection.test.tssubagent-registry-state.test.tsruntime-store-writer.test.tsembedded-agent-tool-results.cache.test.tsembedded-agent-tool-results.reuse.test.tsThe 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
nestedToolActivitieshook 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.