Skip to content

perf(gateway): release per-connection state on close - #164307

Merged
steipete merged 1 commit into
mainfrom
steipete/perf-micro-connection-retention-20260919
Oct 3, 2026
Merged

steipete merged 1 commit into
mainfrom
steipete/perf-micro-connection-retention-20260919

Conversation

@steipete

@steipete steipete commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

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:

Retired connections Baseline retained recipient graph Candidate
200 26,896 bytes 0 bytes
1,200 190,416 bytes 0 bytes

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.changed event 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.

Metric Baseline Candidate
Eligible retired connection IDs 180 → 1,200 180 → 1,180
Held closed connection identities 4 → 2 4 → 2
Direct strong connId holders 33 → 16 32 → 16
Holder exclusive dominator union 23,792 → 11,904 B 23,424 → 11,608 B
Holder exclusive dominator nodes 336 → 168 330 → 163
Identified closed WebSocket objects 4 → 2 4 → 2
Post-snapshot heap used 296,073,936 → 301,328,232 B 295,061,464 → 302,737,256 B
Whole-heap delta 6.01 MiB/hour 8.80 MiB/hour

The 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 connId edges 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.stdout callback 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 tree c049bad1dff2f63e53534ecf6386e151241a3edc / commit 13f046e212034cbd31cb6422f8dc44aba561a103. 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_01m40kc0wr3xzffrg22yhhxjy1 disappeared after roughly 74 minutes queued; replacement tbx_01m40qnh3zcxn3mpvztqrkpf5z (openclaw-check) was stopped after the 120-minute admission window. Neither executed a command. AWS fallback cbx_fb0fbf90c476 and Hetzner fallback cbx_e6e7e7e6660f each 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.

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.
@clawsweeper

clawsweeper Bot commented Oct 3, 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 gateway Gateway runtime size: M labels Oct 3, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Oct 3, 2026
@clawsweeper

clawsweeper Bot commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge. Reviewed October 3, 2026, 10:04 AM ET / 14:04 UTC (Revision 4).

ClawSweeper review

What this changes

The 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
Reviewed head: 13f046e212034cbd31cb6422f8dc44aba561a103

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused implementation with meaningful runtime evidence and passing reported regressions; required test-cost reporting remains incomplete.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The captured exact-head Linux evidence exercises real Gateway sockets through repeated resets and clean closes, with settled agent work and targeted recipient-state retirement observed after the fix. The whole-heap results do not establish broader memory savings. No stored-data contract changes.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The captured exact-head Linux evidence exercises real Gateway sockets through repeated resets and clean closes, with settled agent work and targeted recipient-state retirement observed after the fix. The whole-heap results do not establish broader memory savings. No stored-data contract changes.
Evidence reviewed 10 items Pinned patch and merge ownership: Inspected the merge-base-to-head introduced diff. The test merge has the recorded base parent followed by the exact PR head, and its result contains the same focused Gateway changes.
Canonical recipient cleanup: Admission checks connection liveness before creating recipient state. Removal deletes only the disconnected connection, releases empty recipient-only records, and preserves records containing active run state; TTL and final-grace behavior remain unchanged.
Production teardown boundary: Connection retirement aborts its signal, and WebSocket close invokes the existing subscription cleanup. The request context now releases tool recipients through that same boundary; draining node connections cannot register new delivery state.
Findings None None.
Security None None.

How this fits together

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

Before merge

  • Complete next step (P2) - Record the changed tests' before/after durations and available CI seconds in the PR body, using existing measurement output where available.
Agent review details

Security

None.

PR surface

Source +24, Tests +68. Total +92 across 11 files.

View PR surface stats
Area Files Added Removed Net
Source 7 122 98 +24
Tests 4 73 5 +68
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 11 195 103 +92

Review metrics

Metric Value Why it matters
Code growth by purpose production net +24 lines; tests and test support net +68 lines Production growth is justified by the missing cleanup operation and liveness fences; the extracted registry replaces its prior owner.

Technical review

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

Labels

Label changes:

No label changes.

Label justifications:

  • P2: This repairs bounded connection-state retention without evidence of a core outage or urgent user-facing regression.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The captured exact-head Linux evidence exercises real Gateway sockets through repeated resets and clean closes, with settled agent work and targeted recipient-state retirement observed after the fix. The whole-heap results do not establish broader memory savings. No stored-data contract changes.
  • proof: sufficient: Contributor real behavior proof is sufficient. The captured exact-head Linux evidence exercises real Gateway sockets through repeated resets and clean closes, with settled agent work and targeted recipient-state retirement observed after the fix. The whole-heap results do not establish broader memory savings. No stored-data contract changes.

Evidence

What I checked:

  • Pinned patch and merge ownership: Inspected the merge-base-to-head introduced diff. The test merge has the recorded base parent followed by the exact PR head, and its result contains the same focused Gateway changes. (13f046e21203)
  • Canonical recipient cleanup: Admission checks connection liveness before creating recipient state. Removal deletes only the disconnected connection, releases empty recipient-only records, and preserves records containing active run state; TTL and final-grace behavior remain unchanged. (src/gateway/server-chat-tool-recipients.ts:62, 13f046e21203)
  • Production teardown boundary: Connection retirement aborts its signal, and WebSocket close invokes the existing subscription cleanup. The request context now releases tool recipients through that same boundary; draining node connections cannot register new delivery state. (src/gateway/server-request-context.ts:561, 13f046e21203)
  • Current main still needs the fix: Fetched main lacks tool-recipient removal in connection cleanup, ignores the aborted connection signal in its liveness predicate, and permits observer visibility based only on a connection ID. (src/gateway/session-observer-rpc.ts:14, 3488ed2897a0)
  • Release inspection limitation: Inspection of the latest release's source blob failed because the promisor remote returned HTTP 403. No shipped-fix claim is made; current-main source was successfully inspected and still lacks the repair.
  • Updated production behavior evidence: The captured PR body identifies the exact candidate commit and isolated Linux/Node 26.10.0 environment. Each real-socket rig completed 60 minutes, 84 settled turns, 600 TCP resets, and 600 clean closes. The targeted recipient graph fell from 190,416 bytes to zero at 1,200 retired connections, including attempted late registrations, while three active run records survived. The body explicitly reports no whole-heap improvement. (13f046e21203)

Likely related people:

  • Peter Steinberger: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rank-up moves

Optional improvements that raise the rating; they are not merge blockers.

  • Record changed-test before/after durations and available CI seconds in the PR body, reusing existing run output where available.

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (3 earlier review cycles)
  • reviewed 2026-10-03T12:54:16.709Z sha 13f046e :: needs changes before merge. :: none
  • reviewed 2026-10-03T13:11:15.112Z sha 13f046e :: needs changes before merge. :: none
  • reviewed 2026-10-03T13:49:26.294Z sha 13f046e :: needs changes before merge. :: none

@clawsweeper clawsweeper Bot added the proof: sufficient ClawSweeper judged the real behavior proof convincing. label Oct 3, 2026
@steipete
steipete marked this pull request as ready for review October 3, 2026 13:58
@steipete
steipete enabled auto-merge (squash) October 3, 2026 13:59
@steipete
steipete merged commit 7e22e11 into main Oct 3, 2026
227 of 229 checks passed
@steipete
steipete deleted the steipete/perf-micro-connection-retention-20260919 branch October 3, 2026 14:06
steipete added a commit that referenced this pull request Oct 3, 2026
)

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.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 4, 2026
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.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 4, 2026
…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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

gateway Gateway runtime P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. 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