Skip to content

fix(agents): release completed sessions held by cached WebSockets - #178536

Merged
steipete merged 1 commit into
mainfrom
steipete/perf-micro-idle-session-eviction-and-transcript-dup-20260919
Oct 20, 2026
Merged

steipete merged 1 commit into
mainfrom
steipete/perf-micro-idle-session-eviction-and-transcript-dup-20260919

Conversation

@steipete

@steipete steipete commented Oct 20, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes completed agent sessions remaining reachable through cached OpenAI Responses WebSocket clients, retaining their transcript and tool state between turns.

User Impact

Cached WebSockets remain reusable without keeping the request-specific HTTP callbacks from the turn that opened them. HTTP fallback keeps its original response hooks. There are no configuration, schema, or retention-policy changes.

Why This Change Was Made

Embedded agent sessions already dispose after an attempt and reload from persisted history on the next turn. The leak crosses a different lifetime boundary: the cached SDK WebSocket retains a cloned OpenAI client. Its inherited fetch callback retains request/session state, while the SDK logger proxy retains the original HTTP client and its callbacks. The WebSocket-only clone now resets those two references. Resetting fetch alone still reproduced the leak.

The replay transcript is deliberately detached from mutable storage views by cloneSessionModelContextEntries(). The agent copies the array but shares the supplied replay message objects. Sharing those mutable objects with the manager would let replay/tool-argument changes rewrite its stored-history view. This fix removes the cache's session reference so both views can collect at their existing lifecycle boundary. No eviction timer or second session cache is added.

The GatewayContextBindingOwner audit found owner-attached symbol storage, not a global strong map. Immutable subagent records reserve a binding slot even when unbound, so the instance count includes retained records rather than just loaded sessions. The original production snapshot was unavailable for exact count attribution; no binding-lifetime change is included.

The existing benchmark now supports touching distinct sessions in bounded cohorts, idling, and reopening them. It verifies unchanged persisted history and exactly one answer per turn; source-Gateway census mode counts live SessionManager, AgentSession, and Agent instances without retaining them or writing heap snapshots.

Evidence

Acceptance rule, recorded before sandbox measurement: 100 distinct sessions, cohorts of 10, 128 KiB synthetic prompts, then idle and reopen. Require exact history preservation; completed sessions must collect to the active set; post-idle heap should return within 10% of warmed baseline. Report first-turn and reopened-turn latency, major/minor GC and promotion separately. Paired timings use simultaneous isolated A/B instances, swapped 16-core CPU halves, and at least two pairs. No greater-than-noise regression is acceptable.

  • Existing cache-retention regression upgraded to a real OpenAI client: both retention cases fail on base; 13/13 pass with the fix (0.676 s test execution, 1.68 s wrapper).
  • WebSocket client integration: 22/22 passed, including SSE fallback hooks, timeout, degraded cooldown, and managed proxy/TLS paths (28.32 s cold compilation + execution; 30.24 s wrapper).
  • Changed-file formatting, changed-file lint, and pnpm tsgo:core (native tsrs) passed.
  • Independent Codex review: scoped-clean through P2. GitHub code review also completed with no findings on the submitted head. No production restart requested.

Runtime production change: +5 lines, needed to preserve the original HTTP client's callbacks while removing both references from the cached WebSocket client. The requested census and idle/reopen workload extend the existing diagnostic harness by +210 lines, with +38 lines of benchmark documentation. The prescribed non-test/non-docs/ diff is 299 insertions / 46 deletions (+253), including that harness and its README. No new production owner, cache, configuration option, or storage shape.

Isolated Gateway Measurement

The source-Gateway census completed 100 distinct sessions with cohorts of ten, 128 KiB prompts, one real read tool per turn, six minutes idle, and 100 reopened turns. Synthetic fixture: 5,000 stored sessions, 6,000 retained runs, 200 approvals, 100 cron records, one project, 1 MiB logical background transcript. The background fixture preserves roster shape while avoiding multi-GB writes.

Reproduction (source entry, Node 26.8.2; add --session-census only for the separate object-count diagnostic):

node --import ./scripts/tsx.mjs scripts/perf/transcript-broadcast-measure.ts \
  --state-dir <synthetic-fixture> --scenario session-idle-retention \
  --sessions 100 --runs 10 --chunks 1 --chunk-interval-ms 0 --prompt-kib 128 \
  --duration-ms 360000 --memory-interval-ms 30000 --diagnostics --trace-gc \
  --entry src/entry.ts --start-at <shared-epoch-ms> \
  --port <isolated-loopback-port> --mock-port <isolated-loopback-port>

Base: 15e634e42723ae988a28f03d48e087a2932d38c2; candidate: 5f4c12b34ce2ff467328442be1000eb78d8df1a0. Both share the committed harness and dependencies. Concurrent pairs hold an exclusive lock, use separate identical fixtures/ports and 16-core allocations (96–111 versus 112–127), then swap those allocations. Outside CPU load is recorded per pair for context.

Candidate census (main isolate):

Checkpoint Heap (MiB) SessionManager / AgentSession / Agent
Warmed baseline 635.11 0 / 0 / 0
After 100 touched sessions 726.98 11 / 11 / 11
After six minutes idle 685.28 0 / 0 / 0
Immediately after 100 reopened turns 736.15 17 / 17 / 17

Post-idle heap is 7.90% above warmed baseline, meeting the 10% target; all completed-session objects collected. All 100 histories stayed unchanged during idle, and all 100 reopen operations appended exactly one new final answer without changing the prior history. Incremental post-work heap was 0.919 MiB per touched session; this includes other caches and allocations and is not an exact retained-session object size.

The paired baseline census exceeded the existing 30-second profiler IPC deadline after idle; that side is incomplete. The successful candidate run is reported only as a standalone diagnostic. Two complete concurrent, core-swapped timing pairs (runs 3 and 4) then completed without census, as recommended by the harness documentation. All four runs passed 100 unchanged-history and 100 append-only reopen checks. GC timing excludes the explicit forced-GC checkpoints.

Complete paired results

Metric Pair 3: baseline → candidate (B−A) Pair 4, swapped: baseline → candidate (B−A)
First turn p50 2,615 → 2,700 ms (+3.27%) 2,826 → 2,804 ms (-0.76%)
First turn p95 6,625 → 4,802 ms (-27.52%) 7,403 → 7,429 ms (+0.34%)
First turn p99 6,689 → 4,889 ms (-26.91%) 7,472 → 7,495 ms (+0.31%)
Reopened turn p50 2,753 → 2,593 ms (-5.80%) 2,999 → 2,924 ms (-2.50%)
Reopened turn p95 13,478 → 13,465 ms (-0.10%) 14,750 → 13,501 ms (-8.46%)
Reopened turn p99 13,548 → 13,551 ms (+0.02%) 14,824 → 13,586 ms (-8.35%)
Post-idle heap over warm baseline +9.05% → +8.91% +9.19% → +8.90%

GC and promotion for the measured windows (each turn phase contains 100 completed turns):

Metric Pair 3: baseline → candidate (B−A) Pair 4, swapped: baseline → candidate (B−A)
First turns: minor GC 1,747.1 → 1,794.8 ms (+2.73%) 2,031.2 → 1,842.9 ms (-9.27%)
First turns: major GC 298.7 → 163.5 ms (-45.28%) 317.7 → 257.9 ms (-18.83%)
First turns: promoted 3,021.8 → 3,100.6 MiB (+2.61%) 3,017.7 → 3,036.6 MiB (+0.63%)
Reopened turns: minor GC 1,959.2 → 2,022.2 ms (+3.22%) 2,093.2 → 2,227.7 ms (+6.43%)
Reopened turns: major GC 386.8 → 266.2 ms (-31.18%) 354.4 → 336.1 ms (-5.17%)
Reopened turns: promoted 3,436.9 → 3,476.4 MiB (+1.15%) 3,422.2 → 3,420.0 MiB (-0.07%)
Idle: minor GC 127.4 → 98.8 ms (-22.50%) 105.0 → 111.2 ms (+5.92%)
Idle: major GC 58.0 → 56.1 ms (-3.30%) 59.3 → 59.3 ms (-0.09%)
Idle: promoted 32.7 → 33.0 MiB (+1.13%) 33.2 → 33.3 MiB (+0.42%)

These are within-pair differences, not comparisons of absolute times across runs. The small reopen minor-GC increases are 63 ms and 135 ms per 100 turns; promotion stays within 2.7%. No measured regression exceeded 20%. Several pair-3 improvements exceeded 20%, but the SSE control does not exercise the changed WebSocket code, so they are not claimed as gains from the fix. Reopened p95 remains 13.5–14.7 seconds: these are full source-Gateway agent/tool round trips, not isolated storage-read timings.

Pair 3 used baseline CPUs 96–111 / candidate 112–127; pair 4 swapped them. Mean per-core busy time across CPUs 96–127 was 11.98% and 8.22%, including benchmark activity; individual 10-second core samples ranged 0–100% and 0–89.25%. Host load is context only. Both candidate idle heaps met the 10% bound (+8.91%, +8.90%), with unchanged history and comparable reopened-turn latency.

Scope: the loopback model uses SSE, so this workload checks general session disposal, heap bounds, transcript integrity, and reopening; it does not exercise the affected native cached-WebSocket branch. The real-OpenAI-SDK GC regression isolates that retention defect. The production four-hour memory slope remains to be verified after the next normal deployment/restart.

PR CI: https://github.com/openclaw/openclaw/actions/runs/39454335783 (exact submitted head).

Detach request-scoped HTTP callbacks and the inherited SDK logger from reusable WebSocket clients. Preserve HTTP fallback hooks and cached connection reuse. Add distinct-session idle and reopen diagnostics with source-runtime object counts.
@clawsweeper

clawsweeper Bot commented Oct 20, 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.

@steipete
steipete marked this pull request as ready for review October 20, 2026 16:05
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 20, 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-20T16:09:27.349143Z 5f4c12b Draft marked ready
ℹ️ 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.

@openclaw-barnacle openclaw-barnacle Bot added scripts Repository scripts size: M labels Oct 20, 2026
@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. P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed 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 20, 2026
@clawsweeper

clawsweeper Bot commented Oct 20, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR removes request-scoped callbacks from cached WebSocket clients and extends the existing session-retention diagnostics.

Example: Session session-1 completes a turn while its Responses WebSocket remains cached.

  • Before: The cached SDK client retains the original HTTP client and its request callbacks.
  • After: The WebSocket clone releases those references while the original HTTP client preserves its fallback hooks.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) The narrow production repair is supported by the SDK contract and a meaningful regression extension; runtime confidence remains limited to reported tests.
Proof confidence 🦐 gold shrimp (3/6) This maintainer-authored PR is outside the ordinary contributor proof gate and introduces no material authority change; supplied evidence is test-based, sandbox acceptance remains pending, and the new benchmark selects SSE rather than the changed cached-WebSocket path.
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 sessions retain transcript and tool memory while their provider WebSockets remain cached.
Reason: The source-confirmed lifetime mismatch has a focused repair, and the maintainer-authored direction preserves connection reuse and existing session semantics.

Merge readiness

✅ Ready for maintainer review

Keep open: this maintainer-authored PR fixes a retention edge still present on main, and inspection found no definite introduced correctness or security defect.

Priority: P2
Reviewed head: 5f4c12b34ce2ff467328442be1000eb78d8df1a0

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: The pending acceptance run must exercise real cached Responses WebSockets through the Gateway and show collection with sockets reusable, preserved history after reopening, and paired retention/latency results; the new SSE scenario cannot prove that path.
Agent review details

How this fits together

The Responses transport receives prepared model requests and a request-specific OpenAI client, then leases a session-owned WebSocket or falls back to HTTP streaming.

flowchart LR
  A[Agent turn] --> B[Request HTTP client]
  B --> C[WebSocket client clone]
  C --> D[Session socket cache]
  D --> E[Responses provider]
  B --> F[HTTP fallback]
Loading

Technical review

Best possible solution:

Clear inherited fetch and logger references at the existing WebSocket-clone boundary while retaining HTTP fallback and session-resource ownership.

Do we have a high-confidence way to reproduce the issue?

The current-main clone and pinned SDK source establish the retaining path; the author reports both revised retention cases failing on base and passing on the fix, but this review executed no target code.

Is this the best way to solve the issue?

The production fix is minimal and addresses the retaining producer without changing session disposal, transcript isolation, eviction, or HTTP fallback.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 78e97d169703.

Provenance checked

Testing

Proof path: unit tests only.

Security

None.

Evidence

What I checked:

Likely related people:

  • Vincent Koc: Raw commit 50ea179 adds scripts/lib/gateway-bench-profile.ts:30 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 50ea1795fc80; files: scripts/lib/gateway-bench-profile.ts)

PR surface

Source +5, Tests +16, Docs +38, Other +210. Total +269 across 6 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 1 6 1 +5
Tests 1 19 3 +16
Docs 1 38 0 +38
Config 0 0 0 0
Generated 0 0 0 0
Other 3 255 45 +210
Total 6 318 49 +269

Review metrics

Metric Value Why it matters
Diagnostic controls 2 new benchmark flags and 1 scenario --sessions, --session-census, and session-idle-retention extend the existing diagnostic driver without adding production configuration.

Labels

Label changes:

  • add P2: Completed sessions can retain transcript and tool graphs through reusable sockets, but the existing idle expiry bounds this retaining path and no runtime outage is established.
  • 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 sessions can retain transcript and tool graphs through reusable sockets, but the existing idle expiry bounds this retaining path and no runtime outage is established.
  • 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.

Rank-up moves

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

  • Supply the cached-WebSocket Gateway acceptance evidence described in the testing gap, with credentials and non-public endpoints redacted.

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 20, 2026, 12:21 PM ET / 16:21 UTC.

@steipete
steipete merged commit 5c1432f into main Oct 20, 2026
203 of 204 checks passed
@steipete
steipete deleted the steipete/perf-micro-idle-session-eviction-and-transcript-dup-20260919 branch October 20, 2026 17:02
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 21, 2026
…enclaw#178536)

Detach request-scoped HTTP callbacks and the inherited SDK logger from reusable WebSocket clients. Preserve HTTP fallback hooks and cached connection reuse. Add distinct-session idle and reopen diagnostics with source-runtime object counts.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

P2 Normal backlog priority with limited blast radius. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. scripts Repository scripts 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