Repository navigation
fix(agents): release completed run state from retained async contexts - #184990
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 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. |
|
c3f9738 to
ebf4d19
Compare
|
Codex review: needs maintainer review before merge. What this changesThis PR releases completed agent-run references from inherited async contexts and lifecycle callbacks. Example: Complete 4,000 tool calls while retaining their inherited async resources.
Review scores
ProductKind: Bug fix · Worth it: Yes · Fix scope: Complete Merge readiness✅ Ready for maintainer review Keep open: this maintainer-authored PR repairs distinct retention paths still present on main, and the source review found no introduced correctness bug. Priority: P2 Before mergeNone. FindingsNone. Tests
Agent review detailsHow this fits togetherAgent tool execution, model transport, subscription, and session lifecycle owners hold run inputs during execution and publish terminal facts at completion; inherited sockets and callbacks can outlive those runs. flowchart TD
A[Agent attempt] --> B[Tool execution scope]
A --> C[Model transport context]
A --> D[Session subscription]
B --> E[Inherited network resources]
C --> E
B --> F[Completion cleanup]
D --> F
F --> G[Recorded terminal facts]
Technical reviewBest possible solution: Release completed payload references through their existing lifecycle owners while preserving terminal facts, active streaming callbacks, and live-authority checks. Do we have a high-confidence way to reproduce the issue? Current-main source retains validators and invocation closures through inherited async stores; supplied owner measurements and red-on-base retention regressions corroborate that path, although this review executed no target code. Is this the best way to solve the issue? The patch addresses the retaining edges at existing owners without adding a manager, cache, or parallel execution path; the separate deadline carrier preserves terminal-view semantics while releasing the callable context. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 827ccc2aebdc. Provenance checked
TestingProof path: in-process harness. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +44, Tests +349, Docs +71, Other +342. Total +806 across 21 files. Added test files: 2. 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 26, 2026, 4:56 PM ET / 20:56 UTC. |
|
The dedicated-origin retained-socket control found one more completed-run retention path after the initial fixes: I am applying the existing The current CI failures are inherited assertion drift. The Gateway and worker failures also appear on ancestor main job 121832218663 and job 121832218319. The remaining Codex containment assertion was reproduced unchanged on exact parent |
Retire tool validators and model transport callbacks at settlement, release attempt invocation captures, and remove disposed session observers. Preserve live-authority checks and reject callbacks carrying a closed validation scope. Add retention regressions and an isolated network-tool Gateway workload.
Release the callable diagnostic carrier after tool completion while preserving queued terminal deadline views and draining runtime callers. A retained socket otherwise keeps the signal and abort reason stack linked to completed tool sets.
Materialize host-created cancellation stacks at tool-generation retirement so retained authority signals keep their original reason without retaining the completed tool graph through native call-site objects. Preserve permission revocation ordering and reason identity.
ebf4d19 to
0bfa4c7
Compare
|
The follow-up is pushed at Independent review is clean, including the final abort producers and the shared AsyncContext integration. The PR body now includes all owner measurements, the small per-generation CPU/allocation cost, Gateway diagnostics and sample counts, and the exact-head CI evidence. CI remains red only on the five inherited assertions documented in the body, with matching main-job or exact-parent reproduction. The earlier hold for the unfinished retention follow-up is resolved; the inherited CI blocker remains. No CI rerun or merge was performed. |
|
Admin-merged at the pinned head
Review: every change releases run-scoped references at their owner. The validator scope is retired after its call, rate-limit callbacks are cleared on model finish, abort-reason stacks are materialized, terminal metadata is bound to recorded state, and the prepared attempt binding is dropped after use. Live authorization at execution is unchanged, and late calls into a closed validation scope fail closed. |
…openclaw#184990) * fix(agents): release completed run state from retained async contexts Retire tool validators and model transport callbacks at settlement, release attempt invocation captures, and remove disposed session observers. Preserve live-authority checks and reject callbacks carrying a closed validation scope. Add retention regressions and an isolated network-tool Gateway workload. * fix(agents): release settled diagnostic liveness contexts Release the callable diagnostic carrier after tool completion while preserving queued terminal deadline views and draining runtime callers. A retained socket otherwise keeps the signal and abort reason stack linked to completed tool sets. * fix(agents): release tool graphs from retained abort stacks Materialize host-created cancellation stacks at tool-generation retirement so retained authority signals keep their original reason without retaining the completed tool graph through native call-site objects. Preserve permission revocation ordering and reason identity.
What Problem This Solves
Fixes completed agent runs retaining their tool sets, prepared attempts, and subscription inputs through long-lived sockets, async contexts, and lifecycle callbacks.
User Impact
Completed run payloads can be collected while inherited network resources and recorded terminal results remain alive. Tool authorization still checks live authority at execution; matching late calls into a completed validation scope fail closed.
Why This Change Was Made
Retire the tool-search validator closure when its call settles, clear model rate-limit callbacks when the model request finishes, release prepared attempt inputs from retained authority closures, remove the context-replacement observer on session disposal, bind terminal metadata updates directly to recorded state, and retire the diagnostic deadline carrier at tool completion, and materialize tool-generation cancellation stacks so retained signals preserve their reason without retaining native call-site objects. Model transport callbacks remain usable during streaming, and disposal preserves the context-replacement authority guard.
Runtime production code grows by 48 lines across eight files. Explicit completion cleanup and a fail-closed validator replace retained run closures; the diagnostic carrier preserves the callable contract used by draining runtime chunks and the deadline view used by queued terminal events; there is no new cache, schema, config option, or duplicate fast path. The remaining diff is focused regression tests, reproducible retention tooling, and documentation. The requested non-test/non-doc-path diff is +459 lines, including the benchmark, analyzer, their per-script documentation, and entry-point registrations; runtime changes account for +48.
Evidence
Retained async-resource owner
Same-workload Node runs retain one real AsyncResource per call, each with 40 synthetic tools and an 8 KiB continuation. Checkpoints are 2,000 and 4,000 cumulative calls; CPU and allocation totals below cover 4,000 calls per arm. Allocation sampling is a separate pass.
The intended improvement is retention: about 60 MiB less post-GC heap growth at 4,000 calls. CPU (-3.2%) and allocation (+0.4%) are effectively neutral at this measurement size. Retained AsyncResources and measurement WeakRefs still grow deliberately; only the run payload slope is zero.
Diagnostic-liveness owner
The first candidate Gateway capture exposed a second socket-held carrier: its closed diagnostic callback retained an AbortSignal whose abort-error stack reached the tool set. The follow-up clears that callable carrier while preserving the recorded deadline view. Separate serial AB/BA timing and allocation runs used two processes per side, 4,000 calls per process, with the same 40-tool payload and an explicit synthetic Error cause modeling the signal → reason → run edge.
This trades about 429 B/call of allocation (+1.62%) for 61.90 MiB less retained heap growth at 4,000 calls (-86.8%). The small CPU delta (-3.49%) is context. Host load was 29.10 across the paired arms. Held AsyncResources and WeakRefs account for the remaining measurement growth.
Retained abort reasons
The dedicated-socket control exposed one remaining edge through a retained approval signal: its abort reason's lazy native stack held the retiring tool graph. Both retirement paths now use the existing
materializeErrorStackowner. This preserves the exact cancellation reason and permission-change marker, and leaves caller authority checks untouched.Two serial AB/BA timing processes and two separate allocation processes per side each retired 4,000 generations. Both N=2,000 and 2N=4,000 checkpoints retain zero candidate runs/tools while deliberately retaining every signal and its original reason. Baselines retain 2,000/4,000 runs and 80,000/160,000 tools through the real lazy stack alone.
Eager stack formatting has a real cost: +6.18/+13.38 µs and +4.90/+5.13 KB per retired generation. Relative CPU rises are 12.6%/28.2%, and allocation rises are 20.1%/21.2% in this isolated abort fixture. This is a retention repair, not an allocation or CPU optimization; source/tsx stack formatting can also differ from the built runtime. The retained-heap reduction is about 85%, without dropping cancellation diagnostics or changing authorization.
Final built-Gateway retained-socket proof
The decisive control gives the synthetic HTTP tool its own loopback origin and a 600-second keepalive. This forces tool-created socket contexts to remain alive across post-work GC instead of allowing provider socket reuse or expiry to hide the retention. It uses a local-only, reviewed variant of the committed benchmark; the runtime is the built
0bfa4c7eb43b0501ac5b90a03f046e9f8b4f8cefartifact. State remains 10,800 synthetic sessions, 40 bundled plugins plus the network fixture, 65 WebSocket clients, and four concurrent mock Code Mode turns with tool search and list/search/sidebar churn.The before control is built ebf4d19, which already contains the validator, model callback, listener, authority, and liveness-carrier fixes. Its remaining strong path is TCP → async frame → caller approval signal → abort reason → lazy stack → tool graph. On the final build, all five retained tool-created frames contain closed validators, cleared liveness delegates, and original approval signals with materialized stacks, yet no tools. This positive control establishes release independently of socket expiry. All owned Gateways, clients, and listeners were shut down afterward.
These are short retention controls: all tails are context only, allocation is unsampled, and no throughput or latency acceptance claim is made. Total heap still includes legitimate session history and process state; only completed-run tool retention is zero.
Earlier shared-origin diagnostic limits
Matching fixed-work captures used 10,800 synthetic sessions, 40 bundled plugins plus one synthetic network tool plugin, 65 WebSocket clients, four concurrent Code Mode turns, real loopback HTTP requests, and sidebar/list/search churn. Each arm completed 40 or 80 measured turns and the same number of network tool calls.
The baseline snapshots identify strong TCP → async-context → validator/rate-limit-callback → tool paths, excluding WeakMap ephemeron value edges. A first candidate exposed the additional diagnostic callback → AbortSignal → abort-error stack → tool path; the diagnostic-carrier fix closes that carrier too. Those shared-origin captures retain 69 TCP handles and 253/257 async frames but no tool-created validation frame. Their zero tool count alone cannot distinguish callback release from socket expiry; the dedicated-origin controls above resolve that gap.
The current-main baseline was a0d0700; the shared-origin diagnostic candidate was ebf4d19, before the final abort-stack fix. The final branch head is 0bfa4c7, based on ea128a1. The table below is discovery evidence from that intermediate candidate, not final-head timing acceptance. Intervening upstream changes, substantially higher host load, and additional time-driven churn confound whole-Gateway CPU/latency attribution. Whole-Gateway timing neutrality is not established. CPU/work rose 77.6%/27.1% in these short diagnostic captures; those increases are not attributed to this fix without controls. No adverse verdict or latency improvement is claimed. Allocation was measured at the owners, not sampled in these Gateway runs; no ten-minute AB/BA or A/A acceptance campaign was run.
Gateway diagnostic timing and memory, with sample counts
Client and handler p99 have fewer than 1,000 samples and are context only. Handler metrics use first-to-last scrape histogram deltas; the final partial interval is excluded. The reused pool bounds baseline retained contexts by connection lifetimes: the longer baseline capture retained fewer tools, so these Gateway snapshots do not establish linear completed-run growth. The owner measurements above isolate that slope.
Correctness and review
Exact-head CI
CI run 40403187437 completed on
0bfa4c7eb43b0501ac5b90a03f046e9f8b4f8cef. Required CI is not green: two shards fail on five inherited assertions, with matching failure details on this final head. No CI rerun was requested.chat.directive-tags.test.tsexpectations omit persisted model-selection metadata9d52e3c5: job 1218322186639890d705c25c823aae6102502063cee54ca0ff42: one expected assertion failure, 51 unrelated cases filtered outThe Codex baseline command was
node scripts/run-vitest.mjs extensions/codex/src/app-server/dynamic-tools.test.ts --maxWorkers=1 -t 'keeps Codex apply_patch containment diagnostics operator-only'. Its test blob is identical on that parent and the candidate. The metadata and recovery-guidance changes predate this PR (27b94d43e124andc0ffba6e18a3). These failures remain outside this retention change; the PR is left open for maintainer review.Reproduction commands and limitations are in
scripts/perf/transcript-broadcast-run-retention.md; owner measurement usage is inscripts/perf/run-tool-validation-retention.ts. Heap snapshots stay local; only aggregate counts are reported.