Skip to content

fix(agents): release completed run state from retained async contexts - #184990

Merged
steipete merged 3 commits into
mainfrom
steipete/fix-run-scoped-async-context-retention-20261026
Oct 26, 2026
Merged

steipete merged 3 commits into
mainfrom
steipete/fix-run-scoped-async-context-retention-20261026

Conversation

@steipete

@steipete steipete commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

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.

Metric Before After
Live run validators / attempts, 2,000 → 4,000 calls 2,000 → 4,000 0 → 0
Live tools, 2,000 → 4,000 calls 80,000 → 160,000 0 → 0
Post-GC heap growth, 2,000 → 4,000 calls 34.22 → 67.92 MiB 4.20 → 7.89 MiB
CPU, 4,000 calls 166.61 ms 161.33 ms
Sampled allocation, 4,000 calls 98.63 MiB 99.02 MiB

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.

Metric Before After
Live attempts/signals/reasons, 2,000 → 4,000 calls 2,000 → 4,000 each 0 → 0
Live tools, 2,000 → 4,000 calls 80,000 → 160,000 0 → 0
Post-GC heap growth, 2,000 → 4,000 calls 35.93 → 71.30 MiB 4.97 → 9.40 MiB
Mean CPU per 4,000 calls 193.43 ms 186.68 ms
Mean sampled allocation per 4,000 calls 101.32 MiB 102.96 MiB

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 materializeErrorStack owner. 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.

Metric per 4,000 generations Default before → after Permission change before → after
Main-thread CPU 196.40 → 221.14 ms 189.61 → 243.15 ms
Sampled allocation 93.07 → 111.78 MiB 92.39 → 111.97 MiB
Post-GC heap growth 68.87 → 10.21 MiB 68.43 → 10.03 MiB

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 0bfa4c7eb43b0501ac5b90a03f046e9f8b4f8cef artifact. 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.

Retained-socket result Before abort-stack fix, 4 turns Final, 4 turns Final, 8 turns
Verified network tool requests 4 4 8
Wrapped tool objects 870 0 0
Tool metadata keys 702 0 0
Surviving closed validation scopes 3 5 5
Cleared liveness carriers 3 5 5
Approval reason storage Lazy stack arrays Strings; no lazy arrays Strings; no lazy arrays
Live model callbacks / AgentSessions / continuation-bearing attempts 0 / 0 / 0 0 / 0 / 0 0 / 0 / 0

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.

Final control metric 4 turns 8 turns
Measured duration 3.400 s 8.085 s
Main-thread CPU 37.39%; 1,271 ms 36.49%; 2,950 ms
GC 0.839 s/min 0.888 s/min
Event-loop p99 50.50 ms; 148 samples 77.92 ms; 337 samples
sessions.list client p99 249.19 ms; 21 samples 252.86 ms; 42 samples
Handler latency No complete scrape interval Mean 109.69 ms; p99 bucket 250–300 ms; 29 samples
Post-GC RSS / heap 2,446.11 / 625.18 MiB 2,521.41 / 631.66 MiB
Host one-minute load 16.09 18.57

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.

Post-GC owner count Base 40 / 80 turns Intermediate candidate 40 / 80 turns
Wrapped tool objects 1,449 / 568 0 / 0
Tool metadata keys 1,169 / 458 0 / 0
AgentSession instances 5 / 2 0 / 0
Live validation callbacks 1 / 0 0 / 0
Live model transport callbacks 4 / 2 0 / 0
Continuation-bearing attempt shapes 0 / 0 0 / 0

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
Metric Base 40 turns Candidate 40 turns Base 80 turns Candidate 80 turns
Measured duration (s) 35.87 75.53 79.13 100.27
Main-thread CPU (%) 38.57 32.53 40.78 40.89
Main-thread CPU total (ms) 13,834 24,569 32,265 40,997
GC (s/min) 0.871 1.263 1.090 0.940
Event-loop p99 (ms; samples) 43.65; 1,603 97.78; 2,858 59.11; 3,449 73.79; 4,132
sessions.list client p99 (ms; samples) 449.96; 210 1,527.48; 210 450.20; 420 904.61; 420
sessions.list handler mean (ms; samples) 59.62; 192 111.84; 191 48.43; 400 63.24; 399
Handler p99 histogram bounds (ms) 400–500 1,000–1,250 400–500 500–600
Post-GC RSS (MiB) 2,736.03 2,638.65 2,693.02 2,705.85
Post-GC heap (MiB) 698.98 734.25 706.03 692.75
Host one-minute load samples 24.41 67.28→66.56 37.57→40.21 64.84→51.76

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

  • Regression on the base retains 20 validator owners; the fixed owner releases all 20, preserves concurrent/nested scopes, and rejects matching late calls. The committed Node authority fixture fails on the base with 10 retained attempts, then releases both attempts and internal inputs on the candidate while closed authority checks still reject.
  • Model diagnostic lifecycle and iterator tests: 51 passed, including callback liveness during streaming and collection after completion/error. Compaction: 19 passed. Terminal subscription cleanup: 2 passed.
  • Tool runtime/search/scheduling/Code Mode tests: 80 passed. Authority tests: 69 passed. Import closure and CI planning guards: 182 passed. Export-name collision guard passed.
  • Diagnostic liveness: 3 passed; the regression retains 20 signals on the base and zero signals/owner markers after the fix. Retained-view deadlines, abort behavior, late no-ops, and older callable carriers remain covered.
  • Tool preparation: Node 15/15 and Bun 15/15 passed. Both added Node regressions fail on the unchanged source with a retained retiring-run receiver, then pass after stack materialization while preserving original reason identity and permission-change semantics.
  • Targeted core typecheck, changed-file lint/format, and diff checks passed. All baseline and candidate builds completed successfully. Runtime proof used isolated local Gateways; broad validation runs in PR CI.
  • Independent subagent review (autoreview route unavailable): clean through P2, including follow-up entry-point registrations, diagnostic liveness, and both abort-stack producers. GitHub Codex review also completed without findings on ebf4d19 before the final four-line producer follow-up; the independent follow-up review is clean. The configured review helper refused its provider-route preflight; no operator configuration was changed.

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.

Inherited failure Baseline evidence
Two chat.directive-tags.test.ts expectations omit persisted model-selection metadata Same failures on ancestor main 9d52e3c5: job 121832218663
Two worker containment expectations omit existing recovery guidance Same failures on that ancestor: job 121832218319
Codex dynamic-tool containment expectation omits the same guidance Reproduced unchanged on exact parent 9890d705c25c823aae6102502063cee54ca0ff42: one expected assertion failure, 51 unrelated cases filtered out

The 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 (27b94d43e124 and c0ffba6e18a3). 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 in scripts/perf/run-tool-validation-retention.ts. Heap snapshots stay local; only aggregate counts are reported.

@clawsweeper

clawsweeper Bot commented Oct 26, 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 scripts Repository scripts agents Agent runtime and tooling labels Oct 26, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 26, 2026 •

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-26T21:20:08.135576Z 0bfa4c7 New commits
ℹ️ 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.

@github-actions

github-actions Bot commented Oct 26, 2026 •

Copy link
Copy Markdown
Contributor

⚠️ Security sensitive changes

This maintainer PR changes sensitive security components.

No secops approval is required. This comment is informational because the PR author has Maintain or Admin access.

  • Current SHA: 0bfa4c7eb43b0501ac5b90a03f046e9f8b4f8cef
  • Maintainer: @steipete
  • Repository role: admin

These security sensitive changes were made:

  • src/agents/harness/tool-authority.runtime.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.

Carefully review these changes before merging.

@clawsweeper clawsweeper Bot added clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 26, 2026
@steipete
steipete force-pushed the steipete/fix-run-scoped-async-context-retention-20261026 branch from c3f9738 to ebf4d19 Compare October 26, 2026 20:37
@clawsweeper

clawsweeper Bot commented Oct 26, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

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

  • Before: The reported owner measurement retains 4,000 validators and 160,000 synthetic tools.
  • After: The reported candidate measurement retains zero validators and zero synthetic tools.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Focused lifecycle repair with useful owner-level retention evidence and no identified code defect; shipped-entry-point results remain incomplete.
Proof confidence 🦐 gold shrimp (3/6) This maintainer-authored PR is outside the ordinary contributor-proof gate; supplied Node measurements exercise the production validation owner with retained AsyncResources, while the body still marks built-Gateway candidate results as pending.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Completed agent runs can continue occupying memory while inherited network resources and terminal callbacks remain alive.
Reason: Measured retention and identifiable retaining edges justify the repair, and maintainer authorship supplies the direction decision.

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
Reviewed head: ebf4d19c6dd34fe47dc0ed49772ef4882ca312f7

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: Completed candidate Gateway captures showing released run owners after real network-tool turns are not yet supplied.
Agent review details

How this fits together

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

Technical review

Best 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

  • Per-call tool validation keeps the original intent (4b9c922: Validate final hook-adjusted arguments at the execution boundary while isolating nested and concurrent calls.)
  • Model rate-limit callback keeps the original intent (68a7e7b: Expose shared rate-limit waiting and recovery status during the active model request.)
  • Attempt and question authority keeps the original intent (813b505: Keep exact question-answer custody and live transcript-append authority while an attempt is active.)
  • Subscription terminal metadata keeps the original intent (f65ffdf: Record replay and liveness outcomes for completed embedded runs; the state-owner extraction later made the subscription state authoritative.)
  • Compaction context replacement keeps the original intent (877f157: Retain context-replacement authority through asynchronous write admission; disposal removes the observer while preserving the separate assertion.)
  • Tool execution deadlines keeps the original intent (7df9f83: Preserve accepted foreground execution deadlines through queued recovery while rejecting updates from closed invocations.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

  • Introduced change and current-main boundary: Reviewed the pinned merge-base-to-head diff; comparison with fetched main shows the affected runtime owners still have the original behavior. (ebf4d19c6dd3)
  • Validator retirement preserves rejection: Settlement replaces the captured validator with a shared rejecting function; matching late callbacks cannot silently skip validation, and concurrent scopes remain separate. (src/agents/agent-tools.execution-validation.ts:27, ebf4d19c6dd3)
  • Authority lifetime remains enforced: The attempt payload moves into a releasable bound invocation; settlement still closes live admission, and requester, operation, route, fingerprint, and source-claim checks remain intact. (src/agents/harness/tool-authority.runtime.ts:478, ebf4d19c6dd3)
  • Diagnostic carrier releases its owner: The retained callable carrier drops its invocation reference on close while the separate terminal deadline view preserves the existing fixed allowance until signal abortion. (src/infra/diagnostic-tool-execution-liveness.ts:15, ebf4d19c6dd3)
  • Maintainer direction and measurement scope: The maintainer-authored body explicitly accepts rejection of callbacks inheriting a completed validation scope, reports synthetic owner measurements, and says candidate Gateway captures remain in progress; the security guard confirms no enforced SecOps approval is required for this head. (ebf4d19c6dd3)
  • Inherited worker and Codex assertion drift: The worker failure also appears on feat: discover and manage personal themes in Appearance #184960 in job 121805771774. Both this PR's worker and Codex failures expect the old containment message; upstream commit c0ffba6 introduced the added recovery guidance. (src/agents/apply-patch.ts:136, c0ffba6e18a3)

Likely related people:

  • Peter Steinberger: Raw commit fbeb3c8 adds src/agents/harness/tool-authority.runtime.ts:206 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: fbeb3c85dfae; files: src/agents/harness/tool-authority.runtime.ts)
  • Ayaan Zaidi: Raw commit 813b505 adds src/agents/harness/tool-authority.runtime.ts:108 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 813b5052fb05; files: src/agents/harness/tool-authority.runtime.ts)

PR surface

Source +44, Tests +349, Docs +71, Other +342. Total +806 across 21 files. Added test files: 2.

View PR surface stats
Area Files Added Removed Net
Source 7 91 47 +44
Tests 7 351 2 +349
Docs 2 72 1 +71
Config 0 0 0 0
Generated 0 0 0 0
Other 5 343 1 +342
Total 21 857 51 +806

Review metrics

Metric Value Why it matters
Runtime versus regression coverage Runtime +91/-47 lines; tests and test support +351/-2 lines. The runtime growth supplies explicit reference release at existing owners; the tests cover distinct retention, settlement, isolation, and late-callback behavior.

Labels

Label changes:

  • add P2: Completed payload retention increases memory use, but the supplied evidence establishes neither a current outage nor unbounded whole-Gateway growth.
  • add merge-risk: 🚨 compatibility: The SDK-exposed validation helper now rejects matching callbacks after execution settles; this narrow lifetime change is explicitly accepted and documented by the maintainer author.
  • 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 payload retention increases memory use, but the supplied evidence establishes neither a current outage nor unbounded whole-Gateway growth.
  • merge-risk: 🚨 compatibility: The SDK-exposed validation helper now rejects matching callbacks after execution settles; this narrow lifetime change is explicitly accepted and documented by the maintainer author.
  • 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 26, 2026, 4:56 PM ET / 20:56 UTC.

@steipete

Copy link
Copy Markdown
Contributor Author

The dedicated-origin retained-socket control found one more completed-run retention path after the initial fixes: gatewayToolCaller.approvalSignals → AbortSignal.reason → lazy error stack → releaseTools → tools. The existing validator, model transport, and diagnostic-carrier cleanup is effective, but this remaining path retains 870 wrapped tools across three socket frames.

I am applying the existing materializeErrorStack policy at the two tool-generation abort producers, preserving the original reason objects and all authorization checks. Please hold this PR until that follow-up and its retained-socket proof are pushed.

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 9890d705c25c823aae6102502063cee54ca0ff42 with 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': it fails on the same newly appended recovery guidance. No CI rerun was requested.

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.
@steipete
steipete force-pushed the steipete/fix-run-scoped-async-context-retention-20261026 branch from ebf4d19 to 0bfa4c7 Compare October 26, 2026 21:17
@steipete

Copy link
Copy Markdown
Contributor Author

The follow-up is pushed at 0bfa4c7eb43b0501ac5b90a03f046e9f8b4f8cef, and the retained-socket proof is complete. The dedicated-origin controls retain five completed-run TCP contexts after both 4 and 8 turns, but retain zero tools or metadata keys. The preceding control retained 870 tools. Approval signals and their original reasons remain intact; materialized stacks release the run graph.

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.

@steipete
steipete merged commit 427d397 into main Oct 26, 2026
138 of 142 checks passed
@steipete

Copy link
Copy Markdown
Contributor Author

Admin-merged at the pinned head 0bfa4c7eb43b. The only failing shards contain five inherited assertions, all from earlier main commits:

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.

@steipete
steipete deleted the steipete/fix-run-scoped-async-context-retention-20261026 branch October 26, 2026 21:47
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 27, 2026
…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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. docs Improvements or additions to documentation scripts Repository scripts security-sensitive-changed size: L

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant