Skip to content

fix(ai): release completed runs held by cached WebSockets - #174752

Merged
steipete merged 2 commits into
mainfrom
steipete/perf-micro-per-run-memory-20260919
Oct 16, 2026
Merged

steipete merged 2 commits into
mainfrom
steipete/perf-micro-per-run-memory-20260919

Conversation

@steipete

@steipete steipete commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Completed OpenAI runs remain reachable through cached WebSocket native resources and failure-cooldown timers until those resources expire. A connection created inside a run inherits its async context, which can keep the session, runtime lease, and model catalog graph alive after completion.

User Impact

Completed execution contexts can be collected while idle WebSockets remain reusable. Cached continuation, transport fallback, and the existing five-minute idle expiry keep their behavior; no configuration or migration is required.

Why This Change Was Made

Socket creation and cache expiry use the existing transport host's detached async context. The generic Responses cooldown callback moves out of the request factory's closure, removing its reference to the failed request and restore callback. Connection resources retain their intended runtime lifetime without inheriting the completed caller's lifetime.

Production code grows by 24 lines (+65/-41): preserving connection reuse and cooldown semantics requires detaching both native sockets and timers and isolating the cooldown callback's lexical scope. This removes the old request-scoped timer closure rather than adding a parallel path. No new cache, manager, API, compatibility layer, dependency, or schema is introduced.

Measurements

Matched before/after measurements used an isolated Linux Gateway with synthetic state: 5,000 sessions, 6,000 retained runs, 200 approvals, 100 disabled cron jobs, and 12 projects. Each cohort used distinct existing workspace checkouts, real Code Mode file reads, a loopback cached-WebSocket provider, verified concurrent responses, completion, archive, and a ten-second settle. Active sessions began with empty histories. One completed/archived run warmed the process before measurement.

MiB; active growth is (active - created) / runs. Heap is the main isolate after forced GC. RSS includes process workers, excludes child processes, and comes from the pass without heap snapshots; phase GC still affects later RSS samples.

Concurrent runs Active RSS/run before → after Active heap/run before → after Settled heap growth over cohort idle before → after
1 -1.67 → 2.12 4.58 → 4.52 4.78 → 4.66
8 29.76 → 29.84 4.32 → 4.00 30.98 → 28.50
24 12.09 → 8.18 2.55 → 2.21 42.72 → 7.64

Across all 33 runs, final post-GC heap growth over the warmed baseline fell from 77.77 to 38.82 MiB. Final RSS was 2,073.25 → 2,081.73 MiB, essentially neutral in these single passes; differing warmed baselines and GC/allocator timing prevent claiming a comparable RSS reduction. Both passes retained 34 open sockets, made 68 WebSocket requests, and used 34 cached continuations: the heap reduction does not come from closing connections.

A separate 24-run snapshot pass isolates reachability. Active post-GC heap was essentially unchanged (442.84 → 442.73 MiB), but completed heap fell from 429.85 to 398.69 MiB and warmed-to-settled heap growth fell from 61.40 to 30.31 MiB. Snapshot-pass RSS is excluded because taking snapshots inflates it.

Objects after completion/settle Before After Warmed baseline
AgentSession 25 1 1
SessionManager 25 1 1
ModelRegistry (settled) 51 35 4
AsyncContextFrame (settled) 355 64 —

Baseline snapshots show a native TCP → AsyncContextFrame → run owner → runtime lease/catalog path. The fix returns session-owner counts to baseline while retaining the sockets. Remaining registry paths are associated with prepared-plugin snapshots; WeakMap ephemeron paths alone do not establish that they are leaked. Shared retained subtrees must not be added together as independent per-run memory.

A follow-up fixed-build pass ran two consecutive 24-run cohorts using the same workspace pool. In the second cohort, post-GC heap was 417.07 MiB at idle and 419.59 MiB after settle (+2.52 MiB total, 0.105 MiB/run); the final sample was 418.24 MiB. Comparing settled samples directly, the first cohort ended at 419.66 MiB and the second at 419.59 MiB (−0.07 MiB). RSS fell from 2,204.41 to 2,096.35 MiB. Open sockets increased from 25 to 49 without expiry, and all 48 measured runs completed and archived. This supports a plateau after workspace warmup, with small residual drift, rather than accumulation of one retained session graph per completed run. The existing runtime deliberately retains up to eight idle Gateway run owners; not every surviving registry was attributed to that cache.

An SSE control was neutral: at 24 runs, active RSS/run was 10.86 → 10.47 MiB and idle-to-settled RSS growth was 60.02 → 58.65 MiB. These measurements establish completed-run retention reduction, not a general active-run RSS improvement or full return of total memory to baseline. Long active transcripts and worker-isolate heap attribution remain outside this fixture's coverage.

Evidence

Three retention regressions fail on unchanged production code: the generic transport retains its completed caller; its cooldown retains the failed caller, request, and restore callback; and a real loopback ChatGPT WebSocket retains its completed caller. They pass with the fix while verifying continuation reuse or live cooldown behavior.

  • All 49 tests across the two changed test files and the Responses client integration sibling passed with one worker; changed-file lint/format and diff whitespace checks passed.
  • The first CI run exposed a regression-fixture issue: Vitest's async rejection matcher retained the rejected Error until test completion. Using Node assert.rejects preserves the error and GC assertions. The corrected transport file passes all 13 tests under CI's Node/unit-support configuration; unchanged production still fails both retention tests (11 pass, 2 expected failures).
  • The same CI run found a widened role: string in the shared test fixture. Preserving the literal "user" type fixes the restore callback contract without changing runtime behavior.
  • Independent Codex autoreview of the production change found no actionable P0–P2 findings. A separate scoped review of the test corrections also found no actionable P0–P2 findings.
  • Broad validation runs in PR CI. No Testbox/Crabbox lease was allocated; the Linux host was used only for measurements.

The first CI run also failed src/plugins/runtime/runtime-llm.prepared-owner.test.ts in keeps completion ownership coherent: lru (expected 3 to be 2, line 923). The exact file reproduces identically on this PR's production code and baseline b921f805a3e535642d29c232c22ece7c831cb5a1: 1 failed, 24 passed in both runs. The fixture uses openai-completions SSE, outside the changed WebSocket branches; its owner-reuse assertion passes, while background catalog publication adds an existing registry fork. Relevant test and fork-producing ownership source is unchanged through CI main parent 87c1f1c673b136b23c374596bc718e317b8810bd; inspected indirect changes do not alter the assertion or extra fork. This is an inherited failure; no CI rerun was requested to chase green.

On corrected head 02657d8c7375938d9d88340392f080e0c0666645, the WebSocket test job and the previously failing test-type stripe pass. All other test/static-check leaves pass; the inherited LRU job reproduces the same single assertion. Its owner-reuse counters remain firstBuilds=2, buildsBeforeSecond=11, secondBuilds=11, matching the local baseline and head. The earlier PR-context failure was a section heading mismatch (Proof versus required Evidence); the corrected body passes that check.

@clawsweeper

clawsweeper Bot commented Oct 16, 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 16, 2026 22:12
@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation size: M labels Oct 16, 2026
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 16, 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-16T22:15:55.531834Z 7005948 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.

@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: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. 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 16, 2026
@clawsweeper

clawsweeper Bot commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

Detach cached OpenAI WebSockets and expiry timers from completed runs so their execution contexts can be collected.

Example: Complete 24 concurrent runs while keeping their WebSockets cached.

  • Before: The reported snapshot retained 25 AgentSession objects against a warmed baseline of 1.
  • After: The reported snapshot retained 1 AgentSession while keeping connections reusable.

Review scores

Measure Result What it means
Overall readiness 🦞 diamond lobster (5/6) Focused ownership repair with Gateway measurements, baseline-sensitive retention regressions, and no remaining actionable finding.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): Supplied measurements exercise completed and archived runs through an isolated Linux Gateway with a loopback cached-WebSocket provider, showing reduced retained session graphs while connections and continuations remain reusable; the corrected regressions retain their collection and cooldown assertions.
Patch quality 🦞 diamond lobster (5/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: A Gateway can retain completed session and runtime graphs while reusable WebSockets or failure cooldowns remain alive.
Reason: The maintainer-authored repair has measurable memory value and preserves working transport behavior without adding configuration or another lifecycle owner.

Merge readiness

✅ Ready for maintainer review

This PR addresses a concrete retention bug still present on main; the test correction resolves the previous finding, and no actionable patch defects remain.

Priority: P2
Reviewed head: 02657d8c7375938d9d88340392f080e0c0666645

Before merge

None.

Findings

None.

Agent review details

How this fits together

The AI provider transports turn authenticated model requests into WebSocket streams and retain session-owned connections, continuation state, and cooldowns between requests.

flowchart LR
A[Agent run] --> B[Provider transport]
B --> C[Captured transport host]
C --> D[Detached resource creation]
D --> E[Cached WebSocket]
D --> F[Expiry and cooldown timers]
E --> G[Provider response stream]
Loading

Technical review

Best possible solution:

Retain reusable connections under their existing runtime owners while severing completed-request async and lexical retention.

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

Current-main source exposes both async-context and cooldown-closure retention paths, supported by reported baseline-failing regressions and Gateway snapshots; this read-only review executed no target code.

Is this the best way to solve the issue?

The patch repairs resource creation at both transport owners using the existing host capability and preserves the original cache, fallback, and cleanup contracts.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 297448e524f0.

Provenance checked

  • Generic Responses WebSocket construction, expiry, and cooldown keeps the original intent (f09a33c: Reduce repeated-turn latency through session-owned connection reuse and conservative continuation while preserving fallback boundaries.)
  • Runtime-scoped ChatGPT connection state keeps the original intent (8a2d2ff: Keep transport policy, credentials, cached connections, and cleanup isolated between independent runtimes.)
  • Shared ChatGPT lease release keeps the original intent (862c39a: Consolidate socket release and continuation cleanup while retaining ownership fences.)
  • ChatGPT socket connection helper keeps the original intent (bb46b79: The available history carries this helper through runtime internalization; its earlier introduction is not established.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

  • Reviewed introduction and follow-up: The pinned introduction changes socket construction, idle expiry, cooldown closure ownership, regression tests, and transport documentation; the follow-up changes only the rejection matcher and fixture role typing. (packages/ai/src/transports/openai-responses-websocket.test.ts:368, 02657d8c7375)
  • Current main still has the retaining construction: Current main constructs the ChatGPT socket directly in the caller context and retains the original request-scoped generic cooldown callback; the two expiry-owner modules also lack this repair. (packages/ai/src/providers/openai-chatgpt-responses.ts:881, 297448e524f0)
  • Existing detached-context owner: OpenClaw already installs runInDetachedAsyncContext on the transport host; this patch consumes that contract while keeping explicit credentials, runtime identities, continuation matching, and cleanup ownership. (src/llm/ai-transport-host.ts:36, 02657d8c7375)
  • Retention and reuse regression: The ChatGPT regression uses a real loopback WebSocket, checks caller collection while the native socket and expiry timer remain alive, then verifies a second request uses the same connection and resp_1 continuation. (packages/ai/src/providers/openai-chatgpt-responses.cache.test.ts:139, 02657d8c7375)
  • Supplied Gateway measurements: The fully read PR body reports synthetic Linux Gateway before/after measurements, session-owner snapshot attribution, unchanged connection reuse, and two consecutive fixed-build cohorts whose settled heaps were 419.66 and 419.59 MiB; it explicitly limits RSS and active-transcript claims. (02657d8c7375)
  • Exact-head checks and previous finding: The previously failing small-18 lane now succeeds. Small-2 annotates the prepared-owner LRU assertion at line 923, matching the author's reported baseline reproduction on the unchanged SSE fixture. PR-context validation also fails despite the current Evidence section, and the overall CI gate remains pending. (src/plugins/runtime/runtime-llm.prepared-owner.test.ts:923, 02657d8c7375)

PR surface

Source +24, Tests +156, Docs +1. Total +181 across 6 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 3 65 41 +24
Tests 2 158 2 +156
Docs 1 2 1 +1
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 6 225 44 +181

Review metrics

Metric Value Why it matters
Production versus test LOC Production +65/-41; tests +158/-2 The production growth separates cooldown lexical scope and detaches native resource creation; the tests protect collection alongside connection reuse and cooldown behavior.

Labels

Label changes:

  • add proof: sufficient: Contributor real behavior proof is sufficient.
  • add rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • remove rating: 🦪 silver shellfish: Current PR rating is rating: 🦞 diamond lobster, so this older rating label is no longer current.
  • remove status: ⏳ waiting on author: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P2: Completed runs retain avoidable session graphs during cached-resource lifetimes, increasing Gateway memory use without evidence of an immediate outage.
  • rating: 🦞 diamond lobster: Overall readiness is 🦞 diamond lobster; proof is 🦞 diamond lobster and patch quality is 🦞 diamond lobster.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR.
  • proof: sufficient: Contributor real behavior proof is sufficient.

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.

History

Review history (1 earlier review cycle)
  • reviewed 2026-10-16T22:29:25.740Z sha 7005948 :: needs changes before merge. :: [P2] Repair the new cooldown retention regression in CI

Reviewed October 16, 2026, 6:45 PM ET / 22:45 UTC (Revision 2).

@steipete

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

The branch and PR evidence are current. The test-only follow-up fixes the Node rejection-matcher retention artifact and preserves the fixture's literal role type. Independent review is clean, and the PR body now includes completed before/after measurements, heap-snapshot attribution, repeated-cohort results, and the separately reproduced baseline LRU failure.

@clawsweeper

clawsweeper Bot commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@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. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. 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 16, 2026
@steipete
steipete merged commit aec5072 into main Oct 16, 2026
143 of 150 checks passed
@steipete
steipete deleted the steipete/perf-micro-per-run-memory-20260919 branch October 16, 2026 22:48
@steipete

Copy link
Copy Markdown
Contributor Author

Merged reviewed head 02657d8c7375938d9d88340392f080e0c0666645 as aec507283f368f0bb9a63ed5eacb8b31f4a22d69 under the authorized inherited-failure exception.

CI run 38976694995 completed with one failing test job: checks-node-changed-compact-small-2. Its src/plugins/runtime/runtime-llm.prepared-owner.test.ts LRU case reports expected 3 to be 2 at line 923. The same single-file command (OPENCLAW_VITEST_RUNTIME=node node scripts/run-vitest.mjs src/plugins/runtime/runtime-llm.prepared-owner.test.ts --maxWorkers=1) failed identically on the PR production code and unchanged baseline b921f805a3e535642d29c232c22ece7c831cb5a1: 1 failed, 24 passed each. The failing test and fork-producing ownership modules are unchanged through CI main parent 87c1f1c673b136b23c374596bc718e317b8810bd; the indirect changes were inspected. All three runs preserve the same owner-reuse counters (firstBuilds=2, buildsBeforeSecond=11, secondBuilds=11). The CI classifier has no matching main job, so this attribution comes from the baseline reproduction and source comparison, not an automatic matching-signature claim.

All other selected test/static-check leaves, UI checks, security-fast, and the current dependency/security review statuses passed. CI's aggregate remains red because of that inherited assertion; no CI rerun was used to chase green. The earlier evidence-heading failure has passing replacements.

The earlier cooldown-test review finding was repaired without weakening the GC or cooldown assertions; its exact-head CI job now passes. The fixture type correction also passes CI. Independent review of the production change and the follow-up test correction found no actionable P0–P2 findings.

The PR body records the completed memory proof: post-GC heap residue 77.77 → 38.82 MiB, finished session-owner counts 25 → 1, and repeated 24-run cohorts settling at 419.657 → 419.588 MiB with cached sockets still open. RSS and the remaining attribution limits are stated separately.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

docs Improvements or additions to documentation P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦞 diamond lobster Very strong PR readiness with only minor 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