Repository navigation
perf(gateway): release per-connection state on close - #164307
Conversation
Remove closed sockets from tool-event recipient sets and reject late tool recipient or observer-visibility registration after disconnect. Preserve accepted agent work, live recipients, and run finalization grace. Keep recipient state in the canonical chat-run map; move its existing owner into a sibling module to meet the source line cap. Existing generation-owned session row sharing remains unchanged.
|
🦞👀 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: needs changes before merge. Reviewed October 3, 2026, 10:04 AM ET / 14:04 UTC (Revision 4). ClawSweeper reviewWhat this changesThe Gateway removes disconnected clients from tool-event audiences and prevents late recipient or observer registration while preserving accepted agent work. Merge readiness⛔ Needs changes before merge - 1 item remains This remains a useful, focused fix absent from current main. No introduced correctness or security defect was found, and the updated evidence supports the narrow recipient-retention benefit without claiming whole-heap improvement. Priority: P2 Review scores
Verification
How this fits togetherThe Gateway connects operator and node clients to agent runs over WebSocket. Its connection and subscription owners select event recipients and release delivery state when a connection closes. flowchart TD
A[WebSocket clients] --> B[Connection lifecycle]
B --> C{Connection still active}
C -->|Yes| D[Tool and observer subscriptions]
C -->|No| E[Remove connection delivery state]
F[Agent run events] --> D
D --> G[Authorized live recipients]
E --> H[Accepted runs continue]
Before merge
Agent review detailsSecurityNone. PR surfaceSource +24, Tests +68. Total +92 across 11 files. View PR surface stats
Review metrics
Technical reviewBest possible solution: Keep connection delivery state owned by the existing run and connection lifecycles, with live-client delivery and accepted work preserved. Do we have a high-confidence way to reproduce the issue? Yes, source establishes the mechanism: current main never removes disconnected tool recipients, and continuing events refresh their expiry. This read-only review did not execute a reproduction. Is this the best way to solve the issue? Yes, the patch repairs the existing lifecycle owners without adding competing state, changing stored contracts, or canceling accepted runs. AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 3488ed2897a0. LabelsLabel changes: No label changes. Label justifications:
EvidenceWhat I checked:
Likely related people:
Rank-up movesOptional improvements that raise the rating; they are not merge blockers.
Rating scale
Overall follows the weaker of proof and patch quality. Workflow
History |
) Launch scoped readers and native replacements in the existing detached lifecycle context after capturing launch facts. Release settled operation promises and keep FIFO tails outside request context while preserving per-read admission and command callback authority. Real native/broker GC regressions and two-turn dist Gateway snapshots prove completed callers collect while workers remain reusable. Related: #164307.
Remove closed sockets from tool-event recipient sets and reject late tool recipient or observer-visibility registration after disconnect. Preserve accepted agent work, live recipients, and run finalization grace. Keep recipient state in the canonical chat-run map; move its existing owner into a sibling module to meet the source line cap. Existing generation-owned session row sharing remains unchanged.
…claw#164370) Launch scoped readers and native replacements in the existing detached lifecycle context after capturing launch facts. Release settled operation promises and keep FIFO tails outside request context while preserving per-read admission and command callback authority. Real native/broker GC regressions and two-turn dist Gateway snapshots prove completed callers collect while workers remain reusable. Related: openclaw#164307.
What Problem This Solves
Long-running tool streams retain disconnected clients in their recipient sets. An already-admitted observer visibility request can also recreate a disconnected client's visibility entry after cleanup.
User Impact
Reconnecting clients release delivery-only state promptly while accepted agent work and live recipients continue normally. No configuration or persistence changes are required.
Why This Change Was Made
The tool-recipient owner removes disconnected recipients through the existing connection teardown and checks canonical connection liveness before admitting recipients. Liveness includes the connection owner's aborted signal while admitted node work still drains. Observer visibility checks the same boundary before changing its connection set.
Cleanup uses the existing chat-run map and preserves active run state and final-event grace. The existing recipient factory moves into one sibling module to meet the 700-line cap; both internal type consumers move with it. Production LOC delta: +24. The missing release operation and admission fences require growth; the extracted factory replaces its former location rather than adding another owner.
Session rows and encodings already share their generation-owned values. Recipient envelopes carry authorization and ancestor-reference differences, so this patch preserves those contracts and makes no fanout-allocation improvement claim.
Evidence
Focused tests: all 22 gateway-server test files covering the changed modules (server-connection-state, server-request-context, authenticated-request-dispatch.connection-liveness, session-observer-rpc, server-chat, server-runtime-subscriptions) passed on the isolated Linux rig at commit 13f046e (
node scripts/run-vitest.mjs …, exit 0, 2026-10-03 13:57Z).** Independent review and the remote staged gate passed. The hour-long rigs completed, but show no whole-heap improvement and do not reproduce the production ordinary-old-space slope.On the isolated Linux rig, Node 26.10.0, three long-lived runs and 20 connections per logical minute:
These are selected-subgraph bytes for UUID strings, Set backing storage/wrappers, and recipient state after full GC—not whole-process dominator sizes. The final candidate retains no closed UUIDs in recipient state after attempted late registrations and preserves all three active run records. Cycles are accelerated. At 1,200 connections this is 158.68 → 0 bytes per retired connection; Set capacity makes that average nonconstant. This contribution cannot explain the broader production heap slope.
The existing opt-in fanout benchmark measured 1,191,586 → 1,192,682 bytes per
sessions.changedevent across 50 viewers and 5,000 rows (1,000 events; about 0.09% difference). Both revisions fail its pre-existing hard-coded hash assertion with exactly the same 12 received hashes. Measurements completed, but the benchmark test is not reported as passing; no expected values were changed.The real-socket rigs each completed 60 minutes, 84 unique settled agent turns, 600 TCP resets and 600 clean closes. Twenty clients reconnected every 60 seconds while three text-agent producers emitted 65-second streams. The workload used fixed session identities, session/message/viewer/PR subscriptions, board updates/reads, and history/catalog reads. Values below compare minute 10 with minute 60 within each process.
connIdholdersThe candidate still had its final 20 clients in the authoritative registry during capture; they closed afterward. Baseline captured those closes first. The small cross-run holder-byte difference and falling per-retired-ID ratios are not candidate savings. All string-valued strong
connIdedges were flat. AgentRunRegistry contexts/owners were empty at all four captures; no initial Timeout survived either pair. Each process retained one initial caller identity and one recent identity at its final snapshot.A separate lifetime-owner follow-up remains: the reusable SQLite read worker launches lazily in a caller's Promise context. Its
BrokerChild.stdoutcallback context retains the first completed turn's settlement closure and context-engine lease. The metadata WeakMap is downstream of this same graph, not an independently proven root. The shared worker launch should be investigated at its lifetime owner; generic subprocess callback binding intentionally preserves command context. The observed first-caller holder stayed bounded here.Baseline used a corrected reconnect driver after an earlier expected disconnect exposed a lost-acknowledgement race: one stable admin-transport fallback, zero acknowledgement replays and zero duplicate settled turns. Candidate used the original isolated driver and needed no fallback. Both reported runs used independent synthetic workspace Git roots, with runtime state outside them. Earlier inherited-root runs were excluded after PR statistics could read live SQLite SHM files; a separate probe confirmed process-owned lock loss, though the exact close-to-fault sequence was not captured.
Both Gateways exited 0, mocks stopped, and relevant loopback ports/runtime descendants were absent. The original SSH clients lingered after remote completion and were explicitly terminated (transport exit 255); those transport statuses are distinct from the recorded successful rig outcomes.
Baseline source:
a5ca247a6e744a57bb68e895e80b82fa1fc8bd2a. Candidate was built from that base plus the reviewed patch, matching committed treec049bad1dff2f63e53534ecf6386e151241a3edc/ commit13f046e212034cbd31cb6422f8dc44aba561a103. Runtime: Node 26.10.0, V8 14.6.202.34-node.34, SQLite 3.53.4.Independent review of the final layout passed with no actionable P0–P2 findings. The dedicated Linux rig passed
node scripts/check-changed.mjs --staged(exit 0, approximately 45 minutes): core types, all 27 selected core-test type graphs, lint on all 11 changed files, three dead-export scans, import-cycle checks, and applicable guards. Its first pass found the now-resolved line-cap violation.Blacksmith Testbox
tbx_01m40kc0wr3xzffrg22yhhxjy1disappeared after roughly 74 minutes queued; replacementtbx_01m40qnh3zcxn3mpvztqrkpf5z(openclaw-check) was stopped after the 120-minute admission window. Neither executed a command. AWS fallbackcbx_fb0fbf90c476and Hetzner fallbackcbx_e6e7e7e6660feach timed out after 31 minutes without returning a host. AWS is verified released; the final Hetzner lookup returned not found, with no late active lease observed. CI run 37124181184 was intentionally skipped by the draft-PR policy.