Skip to content

perf(agents): release per-session and per-run state when runs finish - #164386

Merged
steipete merged 4 commits into
mainfrom
steipete/perf-micro-session-manager-retention-20260919
Oct 3, 2026
Merged

steipete merged 4 commits into
mainfrom
steipete/perf-micro-session-manager-retention-20260919

Conversation

@steipete

@steipete steipete commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

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_write suppression. 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 5f52ff0f863c544519ec80bbd7eeea4248bbf4d3 plus 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.

Measurement Baseline Candidate
Forced-GC heap, 10 → 60 minutes 291,805,648 → 329,201,304 B 284,879,704 → 294,876,392 B
Additional completed calls in that window 1,650 1,652
Retained growth / additional call 22,664.03 B 6,051.26 B (−73.30%)
Heap after all terminal receipts 331,726,152 B 294,751,896 B (−36,974,256 B)
SessionManager-exclusive bytes, 10m → 60m → post 337,104 → 2,090,320 → 2,150,992 B 95,376 → 706,536 → 481,584 B
Post-terminal manager bytes / three finished long runs 716,997.33 B/run 160,528 B/run
Post-terminal prompt-state map 90,456 B 184 B, empty
Nested activity arrays, 10m → 60m 122,400 → 746,560 B 0 → 0 B
Replacement activity state, 10m → 60m — 1,896 → 1,896 B

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.timeout timers: 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, profile openclaw-check) through node scripts/crabbox-wrapper.mjs run --id <lease> --timing-json -- …, with source-hash verification.

Lease Command / scope Result
tbx_01m40zdr7w69f4dx116fwmz38q node scripts/run-vitest.mjs <33 owner/sibling files> --maxWorkers=1, with focused fixture corrections Passing coverage for all 582 selected cases; 479.31 s total corrective-run wall time
tbx_01m4139kvganqth8psa6eff4vq Same runner: Workshop, activity-summary, and maintenance owner files 84 passed, 70.05 s
tbx_01m413p4ckp08mbvm8t3dmkbcs Same runner: five cleanup/heartbeat files after integration 31 passed, 40.42 s
tbx_01m413p4ckp08mbvm8t3dmkbcs Same runner: final activity-summary suite 23 passed, 46.34 s; collection case 2.586 s
tbx_01m413p4ckp08mbvm8t3dmkbcs node scripts/check-changed.mjs --base 4c35ddd003d42a6eac84841d2e40c7686f249819 --timed plus final affected checks All structural, formatting, production/test type, and dead-export phases passed. Mechanical lint findings corrected; final affected type graph passed in 7.4 s and canonical full core lint passed (6m7.809s command wall).
tbx_01m4179xepyzyaqnt7m6ecj4cq Five focused append/history/canonical-hook files after the final main rebase 121 passed, 72.21 s; exact committed source tree b9d663d1815fd77024e03bb89df1cb9e204b0cf7 verified

CI 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 commit 612810184697; 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 required openclaw/ci-gate checks 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 as 3a8abe6955cc27ff0bef4ff42b47ac6a927adce4 on 2026-10-03 at 16:26:31 UTC.

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.
@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.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime agents Agent runtime and tooling size: XL labels Oct 3, 2026
@steipete
steipete marked this pull request as ready for review October 3, 2026 15:59
@steipete
steipete enabled auto-merge (squash) October 3, 2026 16:00
@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 Oct 3, 2026
@clawsweeper

clawsweeper Bot commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed October 3, 2026, 12:23 PM ET / 16:23 UTC (Revision 2).

ClawSweeper review

What this changes

The 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
Reviewed head: 612810184697c74e03f4e7b94ab074f3da60d556

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A coherent ownership repair with strong measured runtime evidence, meaningful regression controls, and no identified blocking defect.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The captured matched Linux Gateway replay exercises the changed runner, transcript manager, prompt-state cleanup, and background timer paths, reporting reduced retained growth and completed terminal receipts. Hook delivery is covered by supplemental owner tests rather than the replay. The latest commit changes fixtures only; no stored-data contract changes require migration proof.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The captured matched Linux Gateway replay exercises the changed runner, transcript manager, prompt-state cleanup, and background timer paths, reporting reduced retained growth and completed terminal receipts. Hook delivery is covered by supplemental owner tests rather than the replay. The latest commit changes fixtures only; no stored-data contract changes require migration proof.
Evidence reviewed 11 items Pinned introduction and re-review continuity: Reviewed the merge-base-to-head introduced hunks. Comparing the previous reviewed head with the current head shows only the prompt-state lease fixture correction and removal of an obsolete test argument; production behavior is unchanged. The supplied previous review contains no findings.
Current main still retains prompt state: Current main creates cached prompt state containing tool projections and sent-user identifiers and evicts by cache size; it does not implement the introduced last-attempt disposal lease. Main also retains the separate nestedToolActivities array.
Latest release comparison: GitHub's v2026.9.8 source likewise retains prompt projections in the session cache without last-attempt disposal. The release file was inspected through GitHub after its local blob was unavailable.
Findings None None.
Security None None.

How this fits together

The 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]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +246, Tests +673, Docs +6, Other -1. Total +924 across 69 files.

View PR surface stats
Area Files Added Removed Net
Source 24 428 182 +246
Tests 42 1110 437 +673
Docs 2 8 2 +6
Config 0 0 0 0
Generated 0 0 0 0
Other 1 0 1 -1
Total 69 1546 622 +924

Review metrics

Metric Value Why it matters
Production versus regression coverage Production +246 (+428/−182); tests and support +672 (+1109/−437) The stated production growth preserves transcript ancestry, canonical hook evidence, and overlapping cleanup contracts while removing payload retention owners.

Technical review

Best 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.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: This is a measured agent-runtime retention improvement without evidence of an urgent availability regression.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster 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): The captured matched Linux Gateway replay exercises the changed runner, transcript manager, prompt-state cleanup, and background timer paths, reporting reduced retained growth and completed terminal receipts. Hook delivery is covered by supplemental owner tests rather than the replay. The latest commit changes fixtures only; no stored-data contract changes require migration proof.
  • proof: sufficient: Contributor real behavior proof is sufficient. The captured matched Linux Gateway replay exercises the changed runner, transcript manager, prompt-state cleanup, and background timer paths, reporting reduced retained growth and completed terminal receipts. Hook delivery is covered by supplemental owner tests rather than the replay. The latest commit changes fixtures only; no stored-data contract changes require migration proof.

Evidence

What I checked:

  • Pinned introduction and re-review continuity: Reviewed the merge-base-to-head introduced hunks. Comparing the previous reviewed head with the current head shows only the prompt-state lease fixture correction and removal of an obsolete test argument; production behavior is unchanged. The supplied previous review contains no findings. (src/agents/embedded-agent-runner/run/attempt-session-runtime-prepare.test.ts:25, 612810184697)
  • Current main still retains prompt state: Current main creates cached prompt state containing tool projections and sent-user identifiers and evicts by cache size; it does not implement the introduced last-attempt disposal lease. Main also retains the separate nestedToolActivities array. (src/agents/embedded-agent-runner/session-prompt-state.ts:327, 7ae1ec5a37b6)
  • Latest release comparison: GitHub's v2026.9.8 source likewise retains prompt projections in the session cache without last-attempt disposal. The release file was inspected through GitHub after its local blob was unavailable. (src/agents/embedded-agent-runner/session-prompt-state.ts:46, fc23bc864e45)
  • Canonical hook evidence and transient ownership: Accepted activity records retain entry boundaries and session identity instead of payload arrays. Hydration checks the session binding before and after the read, validates accepted activity, and loads through the existing transcript worker. Hook adapters load only for subscribers and warn instead of delivering incomplete evidence. (src/agents/embedded-agent-runner/run/attempt-nested-tool-activity.ts:30, 612810184697)
  • Replay and compatibility coverage: The introduced regressions cover overlapping lease disposal, cleanup failure, frozen/TTL projection restoration, bounded append ancestry, canonical hook rewrites across compaction, and suppressed display rows. Production changes add a query-only maintenance read; stored formats, schemas, public hook event types, and configuration remain unchanged. (src/agents/embedded-agent-runner/run/overflow-context-recovery.test.ts:30, 612810184697)
  • Real Gateway retention proof: The captured PR body reports matched isolated Linux Gateways on Node 26.10.0 completing 2,000 nested calls and all 53 terminal receipts. Retained growth per additional call fell from 22,664.03 to 6,051.26 bytes; the terminal prompt-state map was empty and the replacement activity state remained bounded. This exercises the changed runner, transcript, worker, and timer owners. Whole-heap growth remained positive, peak RSS was essentially unchanged, and the rig had no custom lifecycle-hook consumer; focused tests supplement that hook coverage. Captured sourceRevision: 407e10f061184c487d4c64f24f87c8a584bebb09ee7b588ce758de052839be6d.

Likely related people:

  • Peter Steinberger: Raw commit e40ed06 adds src/agents/sessions/session-manager-append.ts:19 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: e40ed06f23cb; files: src/agents/sessions/session-manager-append.ts)

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.

History

Review history (1 earlier review cycle)
  • reviewed 2026-10-03T16:06:10.627Z sha fe2bff7 :: needs maintainer review before merge. :: none

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.
@steipete
steipete merged commit 3a8abe6 into main Oct 3, 2026
148 of 150 checks passed
@steipete
steipete deleted the steipete/perf-micro-session-manager-retention-20260919 branch October 3, 2026 16:26
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 4, 2026
…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.
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 gateway Gateway runtime 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: XL 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