Repository navigation
perf(agents): release completed message snapshots during cleanup - #174246
Conversation
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.
|
🦞👀 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 SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
Codex review: needs maintainer review before merge. What this changesThis 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.
Review scores
ProductKind: Performance · Worth it: Yes · Fix scope: Complete 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 Before mergeNone. FindingsNone. Tests
Agent review detailsHow this fits togetherThe 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]
Technical reviewBest 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
TestingProof path: unit tests only. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +43, Tests +147. Total +190 across 7 files. Added test files: 0. View PR surface stats
Review metrics
LabelsLabel changes:
Label justifications:
Rating scale6/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. WorkflowClawSweeper edits this one comment on every review. Comment Reviewed October 16, 2026, 9:37 AM ET / 13:37 UTC. |
…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.
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
.textproperties 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.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[].textandonCompactionRequestBudget / 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:
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.waitcalls with 20 concurrent mock-model turns per round, after matching preliminary turns, restart, and warmup.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 stringparent/first/secondedges, deduplicated across its 380.textstring 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), andrun.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 on6bd07254821708ecdc11c804879994fc053cb15d. No CI rerun, Testbox/Crabbox lease, or local full suite was used. Production has not been redeployed or resampled.