Skip to content

perf(agents): release completed message snapshots during cleanup - #174246

Merged
steipete merged 1 commit into
mainfrom
steipete/perf-micro-main-heap-text-retention-20260919
Oct 16, 2026
Merged

steipete merged 1 commit into
mainfrom
steipete/perf-micro-main-heap-text-retention-20260919

Conversation

@steipete

@steipete steipete commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes completed agent message histories staying on the Gateway heap while accepted background work is still finishing.

User Impact

Completed turns can release their in-memory message snapshots sooner. Transcript persistence, returned results, cancellation, and accepted cleanup work keep their existing behavior. No configuration or migration is required.

Why This Change Was Made

Background resource and cancellation owners retained both the foreground producer and a fulfilled deferred promise. That promise kept the complete result alive even after its caller had dropped it. Separately, accounting callbacks created inside the run loop shared a closure context with the completed attempt snapshot.

Release the producer after invocation and settlement handles after publication, while keeping the cleanup owner alive. Create accounting callbacks in the existing context-recovery owner so they carry scalar accounting state instead of the run loop's attempt context. Late committed accounting still applies; settled or aborted attempts cannot publish a new request budget.

The simplification removes the old callback closures and direct retained rejection resolvers rather than adding a cache or alternate path. Production code grows by 43 net lines: the existing contract requires result publication and mandatory cleanup/cancellation to have separate lifetimes. No storage retention policy changes.

Evidence

A deduplicated heap analysis found 17,944 unique strings at .text properties totaling 189.2 MiB (strings at least 1 KiB), versus the original edge-attributed estimate of 294.3 MiB. All unique strings at least 1 KiB totaled 486.4 MiB. Only type/property/count/size aggregates were exported.

Owner at snapshot time Owner objects Unique text within group
Completed attempt results, session without an active run 48 48.2 MiB
Attempt results, session with an active run 12 18.9 MiB
SessionManager, session without an active run 16 37.6 MiB
SessionManager, session with an active run 7 28.2 MiB

Groups overlap and must not be summed. Completed subagent terminal replies account for another overlapping 34.4 MiB through shared caches/indexes; that retention policy is outside this change. Weak diagnostic maps mirror the strong holders' lifetimes rather than independently rooting their text. Broadcast frame retention was not the source.

The relevant retainer chains are cleanup closure → Context.result → Deferred.promise → Promise.reactions_or_result → messagesSnapshot → content[].text and onCompactionRequestBudget / onContextAccountingEvent → shared run-loop context → attempt snapshot → content[].text. The change removes these references without changing transcript durability or cache policy.

A Linux Node 26 reproduction holds 48 accepted background jobs open, returns one 1 MiB synthetic history from each foreground call, drops the results, and forces GC. The real production helpers retain their cleanup resources throughout:

Helper Before heap used After heap used Retained synthetic text
Resource ownership 59.69 MiB 11.20 MiB 48 MiB → 0
Cancellation ownership 59.69 MiB 11.20 MiB 48 MiB → 0

All 48 result objects and producer inputs become collectible with the change while background work remains pending. Resources release exactly once after the jobs drain. These are focused owner measurements, not a whole-Gateway memory reduction claim.

The full Gateway comparison used Node 26.8.1 on Linux with 5,000 sessions, 6,000 retained runs, 25,655 transcript messages, 1,500 MiB of logical transcript text, and a 4.32 GiB agent database. It selected the 20 longest eligible histories and exercised real agent / agent.wait calls with 20 concurrent mock-model turns per round, after matching preliminary turns, restart, and warmup.

Post-GC main heap Before After Change
Round 1 924.13 MiB 910.53 MiB -1.47%
Round 2 888.78 MiB 883.73 MiB -0.57%

Treat this ordinary completed-turn result as neutral, with no observed regression; two rounds do not establish a whole-Gateway improvement. Each round had 20 primary requests, peak concurrency 20, 220 delivered session events, and no utility requests. Input bodies were about 5.214–5.215 MB per request; candidate bodies were 36 bytes smaller, consistent with its shorter fixture path. Candidate cohort-plus-drain times were 9.37 and 9.58 seconds, within the original 15-second deadline. Its unmeasured preliminary run exceeded that quiet-window deadline after all 20 replies completed, then shut down cleanly; those turns were not repeated.

Both final Gateway snapshots had zero unique string nodes of at least 1 KiB directly referenced by .text. The candidate also had zero such backing nodes reached through sliced/concatenated string parent / first / second edges, deduplicated across its 380 .text string roots. The baseline snapshot was removed to bound disk use before that backing-node metric was added, so its backing-byte comparison is unavailable. Overall large-string bytes were 219,746,359 before and 219,761,303 after. Ordinary drained turns did not reproduce the delayed-background-work retention; the helper experiment is the direct before/after payload-collection proof.

Focused checks passed: async-work-resources.test.ts (5 tests, including Node/V8 collection for both helpers), async-work-scope.test.ts (14 tests), and run.attempt-normalization.direct.test.ts (9 tests). Changed-file lint, formatting, and diff checks pass. Independent review of the final patch found no actionable P0–P2 findings. Test code grows by 147 lines; no new module, export, or test file was added.

The existing physical-retry budget-fencing integration case also passes through the public run owner (run.shared-integration.test.ts, one selected case). Full PR CI and the required gate passed on 6bd07254821708ecdc11c804879994fc053cb15d. No CI rerun, Testbox/Crabbox lease, or local full suite was used. Production has not been redeployed or resampled.

Separate foreground result and producer references from accepted background work. Keep resource release and cancellation ownership until descendants drain, and create accounting callbacks outside the attempt snapshot closure.
@clawsweeper

clawsweeper Bot commented Oct 16, 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 16, 2026 13:22
@openclaw-barnacle openclaw-barnacle Bot added agents Agent runtime and tooling size: M labels Oct 16, 2026
@chatgpt-codex-connector

Copy link
Copy Markdown
Contributor

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-16T13:24:57.062325Z 6bd0725 Draft marked ready
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. labels Oct 16, 2026
@clawsweeper

clawsweeper Bot commented Oct 16, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR releases completed foreground results, producer inputs, and attempt accounting closures while preserving accepted background cleanup.

Example: The reported Linux Node 26 measurement completes 48 foreground calls returning 1 MiB histories while background jobs remain pending.

  • Before: Each helper retains 48 MiB of synthetic text after callers drop their results.
  • After: Retained synthetic text falls to zero while cleanup resources remain owned until the jobs drain.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) A useful, focused ownership repair with no concrete findings; confidence rests on helper measurements and targeted regressions.
Proof confidence 🦐 gold shrimp (3/6) This maintainer-authored PR is outside the ordinary contributor proof gate; its Linux Node 26 measurements exercise the production helpers with pending background jobs and report collection after settlement, while the full Gateway measurement remains unreported.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Completed agent histories can remain in Gateway memory while accepted background work finishes.
Reason: The maintainer-authored direction addresses a measured retention mechanism with a focused change that preserves foreground results and accepted cleanup.

Merge readiness

✅ Ready for maintainer review

Keep open: this maintainer-authored PR addresses a current-main retention problem with a focused ownership repair, and no actionable introduced defects were found.

Priority: P2
Reviewed head: 6bd07254821708ecdc11c804879994fc053cb15d

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: The supplied helper measurements do not demonstrate completed-message collection through a shipped Gateway turn.
Agent review details

How this fits together

The embedded runner and shared async-work helpers separate caller-visible results from background work, cancellation propagation, resource release, and context accounting.

flowchart TD
  A[Agent attempt or plugin call] --> B[Async work owner]
  B --> C[Foreground result]
  C --> D[Caller]
  B --> E[Accepted background work]
  E --> F[Resource cleanup]
  A --> G[Context recovery accounting]
Loading

Technical review

Best possible solution:

Release foreground references within the existing owners while retaining cleanup custody, cancellation context, and committed accounting.

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

Current-main source retains foreground producers and deferred results during background cleanup, and the author supplies comparable before/after collection measurements; this read-only review inspected but did not execute the regressions.

Is this the best way to solve the issue?

The patch repairs the retaining owners directly, preserves existing lifecycle ordering, and avoids changing transcript bytes, storage, configuration, or public signatures.

AGENTS.md: found and applied where relevant.

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

Provenance checked

  • Resource ownership through cleanup keeps the original intent (065dc15: Retain the selected runtime and cancellation context until cooperating auth and transport cleanup finishes, independently of logical result delivery.)
  • Idle resource release before result publication keeps the original intent (33e2ddb: Keep accepted queued admission alive after a successful tool response while preserving ordinary idle cleanup timing.)
  • Managed cancellation context keeps the original intent (542f96b: Preserve executing-plugin identity and original abort reasons through descendant cleanup without delaying the direct result.)
  • Attempt accounting and request-budget publication keeps the original intent (60adac1: Use prepared foreground budgets for compaction while keeping completed replies independent of background maintenance; existing settlement fencing preserves committed accounting.)

Testing

Proof path: unit tests only.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 542f96b adds src/shared/async-work-scope.ts:119 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 542f96bcc54b; files: src/shared/async-work-scope.ts)
  • Vincent Koc: Raw commit 33e2ddb adds src/shared/async-work-resources.ts:8 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 33e2ddbd5023; files: src/shared/async-work-resources.ts)

PR surface

Source +43, Tests +147. Total +190 across 7 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 4 79 36 +43
Tests 3 147 0 +147
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 7 226 36 +190

Review metrics

Metric Value Why it matters
Production versus test LOC Production +79/-36, net +43; tests +147/-0. Production growth separates foreground reference lifetimes from mandatory cleanup and moves accounting into its existing owner; tests protect collection and lifecycle behavior.

Labels

Label changes:

  • add P2: Completed histories can increase long-lived Gateway heap usage, without evidence here of an urgent outage or crash loop.
  • add rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Label justifications:

  • P2: Completed histories can increase long-lived Gateway heap usage, without evidence here of an urgent outage or crash loop.
  • rating: 🦐 gold shrimp: Overall readiness is 🦐 gold shrimp; proof is 🦐 gold shrimp and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.

Rating scale

6/6 🦀 challenger crab · 5/6 🦞 diamond lobster · 4/6 🐚 platinum hermit · 3/6 🦐 gold shrimp · 2/6 🦪 silver shellfish · 1/6 🧂 unranked krab. Overall follows the weaker of proof and patch quality; ✨ marks media proof (a screenshot, video, or linked artifact) that directly shows the changed behavior.

Workflow

ClawSweeper edits this one comment on every review. Comment @clawsweeper re-review for a fresh review only. Repair and merge execution lanes are retired.

Reviewed October 16, 2026, 9:37 AM ET / 13:37 UTC.

@steipete
steipete merged commit c5aabc2 into main Oct 16, 2026
223 of 225 checks passed
@steipete
steipete deleted the steipete/perf-micro-main-heap-text-retention-20260919 branch October 16, 2026 13:48
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 17, 2026
…nclaw#174246)

Separate foreground result and producer references from accepted background work. Keep resource release and cancellation ownership until descendants drain, and create accounting callbacks outside the attempt snapshot closure.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. 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