Repository navigation
perf(agents): release per-session and per-run state when runs finish - #164386
Conversation
Release excluded nested activity from bounded transcript views, hydrate canonical hook evidence on delivery, and dispose prompt-state leases after final attempt cleanup. Detach warm-worker retirement from completed transcript context while preserving host ownership and worker reuse.
Keep canonical nested-tool hook evidence complete, align retention fixtures with durable ancestry and hook delivery, and detach background scheduling from the completed turn's async context. Release cancelled summary pump handles without changing their scheduling or authority contracts. The matched synthetic hour-long replay of the initial lifetime changes reduced retained heap growth from 22664 to 6123 bytes per nested call and identified the remaining background timer roots repaired here. Focused Testbox validation covers 582 original cases plus 84 scheduler-owner cases; six old-code controls fail at the intended assertions. The updated full candidate replay and final integrated checks remain pending.
Keep the existing transcript and terminal-event fixture in a focused sibling module so the lifecycle suite stays within its size budget without dropping coverage. The collection probe owns the session target used by the flow. The 23-case suite passes on Testbox, while restoring the original scheduling owner fails the retained-context assertion. The affected type graph passes.
|
🦞👀 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, 12:23 PM ET / 16:23 UTC (Revision 2). ClawSweeper reviewWhat this changesThe PR releases completed agent-run payloads and prompt state, loads nested-tool history from SQLite for lifecycle hooks, and detaches background scheduling from completed turns. Merge readiness✅ Ready for maintainer review This PR remains useful: current main retains the state it releases, and the related merged fix addresses a different retention path. No concrete introduced correctness or security defect was found. Priority: P2 Review scores
Verification
How this fits togetherThe agent runner turns user prompts and nested tool results into model context, durable transcripts, and lifecycle events. Its cleanup owners determine which data remains reachable after a run finishes. flowchart TD
A[User prompt] --> B[Agent attempt]
B --> C[Nested tool execution]
C --> D[Durable SQLite transcript]
D --> E[Subscribed lifecycle hooks]
B --> F[Attempt cleanup]
F --> G[Release transient prompt state]
F --> H[Host-owned background scheduling]
Before mergeNone. Agent review detailsSecurityNone. PR surfaceSource +246, Tests +673, Docs +6, Other -1. Total +924 across 69 files. View PR surface stats
Review metrics
Technical reviewBest possible solution: Keep durable activity in SQLite and release transient attempt state while restoring identical prompt projections for subsequent turns. Do we have a high-confidence way to reproduce the issue? Yes: current-main source exposes the retaining arrays and prompt-state cache, and the supplied matched Gateway replay measures those paths. This read-only review did not independently execute the reproduction. Is this the best way to solve the issue? Yes: the patch repairs the existing ownership boundaries and reuses canonical transcript hydration, with focused coverage for replay, suppression, compaction, and cleanup. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 7ae1ec5a37b6. LabelsLabel changes: No label changes. Label justifications:
EvidenceWhat I checked:
Likely related people:
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
HistoryReview history (1 earlier review cycle)
|
Model the prompt-state lease and its cleanup handoff in session preparation, and remove the obsolete prompt-state argument from native provider replay. This fixes the two fixture failures from CI run 37135219626. Both test files, the affected agent and root type graphs, and scoped lint pass on Testbox. Production behavior and the measured retention changes are unchanged.
…penclaw#164386) * perf(agents): release per-session and per-run state when runs finish Release excluded nested activity from bounded transcript views, hydrate canonical hook evidence on delivery, and dispose prompt-state leases after final attempt cleanup. Detach warm-worker retirement from completed transcript context while preserving host ownership and worker reuse. * perf(agents): release background references to completed runs Keep canonical nested-tool hook evidence complete, align retention fixtures with durable ancestry and hook delivery, and detach background scheduling from the completed turn's async context. Release cancelled summary pump handles without changing their scheduling or authority contracts. The matched synthetic hour-long replay of the initial lifetime changes reduced retained heap growth from 22664 to 6123 bytes per nested call and identified the remaining background timer roots repaired here. Focused Testbox validation covers 582 original cases plus 84 scheduler-owner cases; six old-code controls fail at the intended assertions. The updated full candidate replay and final integrated checks remain pending. * test(gateway): isolate activity-summary lifecycle fixtures Keep the existing transcript and terminal-event fixture in a focused sibling module so the lifecycle suite stays within its size budget without dropping coverage. The collection probe owns the session target used by the flow. The 23-case suite passes on Testbox, while restoring the original scheduling owner fails the retained-context assertion. The affected type graph passes. * test(agents): align prompt fixtures with state leases Model the prompt-state lease and its cleanup handoff in session preparation, and remove the obsolete prompt-state argument from native provider replay. This fixes the two fixture failures from CI run 37135219626. Both test files, the affected agent and root type graphs, and scoped lint pass on Testbox. Production behavior and the measured retention changes are unchanged.
What Problem This Solves
Long Code Mode runs retain completed nested-tool payloads in both SessionManager and a separate hook-activity array. Prompt projections, review callbacks, and background timers can then keep completed attempts reachable. A matched hour-long synthetic replay shows 73.3% less retained heap growth per completed nested call after the ownership fixes.
User Impact
Completed activity remains available in durable history and lifecycle hooks while display-only payloads leave the active model-context view. Finished attempts unload their replayable prompt state. Warm workers keep their five-minute reuse window. Stored transcript bytes, configuration, schemas, durable retention, and update behavior are unchanged.
Hooks consume canonical persisted activity, including
before_message_writesuppression. A suppressed display row is omitted from finalization/agent-end history, while the successful tool still counts toward settlement. Invalid or unavailable evidence uses the existing best-effort warning path and skips that hook instead of delivering partial history.Why This Change Was Made
Bounded append now follows bounded hydration: SQLite owns excluded payloads and the live manager retains the ancestry needed for subsequent writes. The accumulating nested-activity array is replaced by attempt scope, accepted entry boundaries, and successful tool names. Subscribed lifecycle hooks hydrate the accepted interval through the existing transcript worker, including across compaction.
Prompt-state leases release projections after the last overlapping attempt settles. Recovery restores persisted frozen/TTL projections before truncation, preserving sent bytes. Four-project history remains separately bounded, and the transcript recorder owns sent-state facts. Review callbacks are isolated from the attempt closure and disconnected before asynchronous cleanup.
Warm-worker retirement, Workshop review timers, SQLite maintenance, and delayed activity-summary pumps now register outside the completed turn's async context while retaining their explicit authority checks. Canceled pump handles are released.
The requested non-test diff is +246 lines (429 added / 183 removed); runtime source alone is also +246 lines (428 added / 182 removed). The growth preserves canonical hook evidence across compaction, full/detached transcript ancestry, and overlapping cleanup/prompt-prefix contracts while removing the old payload owners. Most of the 69 changed files update existing callers and fixtures. There is no additional payload cache, public SDK argument, configuration option, or schema.
Evidence
Matched isolated Linux Gateways, Node 26.10.0, both pinned to
5f52ff0f863c544519ec80bbd7eeea4248bbf4d3plus this lane's runtime changes on the candidate. Both completed 2,000 nested calls across three concurrent long sessions, 50 one-shot sessions, and all 53 terminal receipts, with no retries or workload errors. Each nested result contains a unique synthetic 8 KiB payload. Fixtures, tracing, serial pre-clock seeding, and capture barriers are identical.Candidate managers contain zero persisted nested-result rows, versus 1,973 retained baseline rows at minute 60. No finished one-shot manager remains after the 50 one-shot sessions. String-class retained growth falls from 27,892,288 to 1,090,304 B. Constructor/parent/child totals overlap and must not be summed.
The repaired strong paths ran through warm-worker jobs, Workshop timers, per-database maintenance timers, and the summary listener's canceled pump handle, then captured async context and completed sessions. Two long-run managers remain in the final candidate snapshot under live 20-second Node
AbortSignal.timeouttimers:timerListMap → Timeout → AsyncContextFrame → code-mode execution → sessionResources → SessionManager. They retain 240,792 B each. Capture occurred 14.318 seconds after the last receipt, versus 23.939 seconds at baseline; this does not prove retention beyond their deadline. The per-run row is a snapshot normalization, not a leak slope.Active-run cache-TTL markers still grow from 20,880 to 384,024 B, and terminal metadata from 103,488 to 637,056 B. These remain history/settlement data during active runs. Finalization registries fall to 85,888 B after settlement and are not the dominant sustained holder. Other measured growth includes compiled-code metadata, session-count-related inventory rows, and bounded diagnostic records. Whole-heap growth remains positive; this is not proof that production's heap slope is fixed.
The workload takes 3,680.298 → 3,676.564 seconds through the post capture. Sampled peak process RSS is essentially unchanged, 2,351.46 → 2,351.27 MiB; post-capture RSS is 2,332.45 → 2,296.25 MiB. RSS includes workers/native memory and snapshot overhead. This duration-controlled, traced workload is not a throughput benchmark.
The PR is rebased onto
384d14f609e816e9f30ab3eea1d1b29742c6f255, including the related backing-string fix. The three retention/fixture commits are patch-identical across that final rebase; the subsequent CI correction changes only two test fixtures. The paired measurement excludes those later main changes, so their benefit is not credited here.Validation
All heavy development validation used Blacksmith Testbox (
blacksmith-testbox, profileopenclaw-check) throughnode scripts/crabbox-wrapper.mjs run --id <lease> --timing-json -- …, with source-hash verification.tbx_01m40zdr7w69f4dx116fwmz38qnode scripts/run-vitest.mjs <33 owner/sibling files> --maxWorkers=1, with focused fixture correctionstbx_01m4139kvganqth8psa6eff4vqtbx_01m413p4ckp08mbvm8t3dmkbcstbx_01m413p4ckp08mbvm8t3dmkbcstbx_01m413p4ckp08mbvm8t3dmkbcsnode scripts/check-changed.mjs --base 4c35ddd003d42a6eac84841d2e40c7686f249819 --timedplus final affected checkstbx_01m4179xepyzyaqnt7m6ecj4cqb9d663d1815fd77024e03bb89df1cb9e204b0cf7verifiedCI on the first published head caught two remaining test fixtures: a missing prompt-state lease mock export and an obsolete prompt-submission argument in the root native-provider test. Both are corrected without runtime changes. On
tbx_01m418cgmvwe43k00gwb4c7z53, the 9 preparation cases and 6 native-provider cases passed in 33.53 s, the agent and root-plugin type graphs passed in 36.6 / 46.8 s, and scoped lint passed. The independently reviewed correction is commit612810184697; its committed tree exactly matches the validated source tree.Six old-code controls fail at their intended assertions: retained excluded display payloads, malformed middle activity hidden by the old role filter, idle-worker context, Workshop context, SQLite-maintenance context, and summary-pump context. Source was restored and reverified after every control. The final target-bearing summary probe was also rerun against the original owner and retained one context where the fixed code requires zero.
Coverage includes prompt cleanup success/failure/overlap, frozen/TTL recovery, bounded and side-append ancestry, canonical hook evidence across compaction, suppression/cancellation/replacement, real review-transcript wiring, and worker reuse/expiry/pressure/close. Independent review found both the final runtime/integration and final fixture changes scoped-clean P0–P2.
Earlier fixture, lint, and test-file-size failures were repaired and rechecked. One standalone lint invocation used a stricter untouched-file size policy; the canonical rerun used the existing changed-file owner with all 67 actual paths, without changing baselines or suppressions. Resource-failed initial rig attempts are excluded. The successful final pair shut down normally. The rig has no custom lifecycle-hook consumer, so focused owner tests provide that delivery/failure proof. Final exact-head CI run 37136318956 passed on
612810184697c74e03f4e7b94ab074f3da60d556: 67 successful jobs, 20 skipped, and both requiredopenclaw/ci-gatechecks succeeded. Workflow wall time was 487 s; all 27 Node-test jobs passed, consuming 4,687 job-seconds, including 3,308 seconds in test-shard steps. No rerun was needed on this head. The maintainer watcher merged the PR as3a8abe6955cc27ff0bef4ff42b47ac6a927adce4on 2026-10-03 at 16:26:31 UTC.