Skip to content

perf(memory): release diagnostic state on session retirement - #199761

Merged
steipete merged 1 commit into
mainfrom
steipete/perf-soak-retention-pair-20261115
Nov 15, 2026
Merged

steipete merged 1 commit into
mainfrom
steipete/perf-soak-retention-pair-20261115

Conversation

@steipete

@steipete steipete commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Resetting or deleting sessions left their diagnostic activity and aliases reachable until the Gateway restarted.

User Impact

Gateways reclaim diagnostic state for sessions retired through reset/delete. Ordinary completion still preserves idle progress and retry/recovery evidence. There are no schema or configuration changes.

Why This Change Was Made

A same-process heap-snapshot pair found activityByRef retaining every one of 1,861 retired parent-session IDs and 882 deleted session keys in a synthetic soak. Run-ID and recovery-fence cleanup already existed; session-alias cleanup did not.

The existing reset/delete lifecycle already joins turn producers. It now drains the queued diagnostic prefix, checks its existing lifecycle guard, and asks the diagnostic owner to remove the retired activity's aliases. Map.forEach avoids allocating entry pairs during this cold cleanup. The 20 added production lines are necessary to preserve idle/retry evidence until actual retirement; clearing every completed attempt would break that contract.

The rig gains a repeatable --soak mode with independent mock Responses streams, minute memory/CPU/GC/loop samples, hot reloads, and uninterrupted profiler tracking for meaningful object-ID comparisons.

Evidence

Both accepted runs: 165 minutes, snapshots at minutes 35 and 165, 10,000 seeded sessions, 64 WebSocket clients, 40 fixture plugins plus runtime plugins, three concurrent mock Responses streams with real tool/result, subagent, cron, artifact and session-churn paths, and five hot config reloads. Baseline source: 7d7d86bb79ca24bfaf9343290cb22f80d705ab20 (includes #199609 and #199615); candidate: the same source plus this 20-line production repair. Node 26.12.1. These measurements precede the final rebase; exact-head CI is separate evidence.

Measurement Baseline Candidate
Verified parent turns 2,688 2,718
Old-space ten-minute floor slope, MB/h 11.33 4.93
Post-GC snapshot old space, MB 399.97 → 443.54 403.07 → 442.03
Snapshot old-space slope, MB/h 20.11 17.98
Diagnostic map retained, MB 0.602 → 2.226 0.300 → 0.415
Diagnostic map growth, MB/h +0.750 +0.053
Retained retired ID / key aliases 1,861 / 882 0 / 0
Main-thread CPU, % of one core 22.82 21.37
GC seconds/minute 2.130 1.847
GC observations 20,557 20,978
Minute loop p99 median / maximum, ms 41.71 / 316.93 38.42 / 196.87
Loop histogram samples 338,359 352,191
RSS median / maximum, MB 3584.8 / 4051.8 3584.8 / 3762.6
Heap-used median / maximum, MB 669.8 / 1233.6 676.4 / 802.8
Host load1 median / p95 / maximum 15.37 / 42.03 / 54.66 11.95 / 34.77 / 51.05

Decimal MB. Loop rows summarize minute percentiles, not one aggregate percentile. The candidate check covers 1,884 retired parent IDs and 894 deleted keys. The causal result is removal of stale aliases; whole-Gateway differences are contextual, not attributed wholesale to this small repair. The soak did not trace allocation rate or capture RPC/server-handler latency and per-kind GC pause distributions; no A/A-based performance-regression claim is made.

Owner lifecycle microbenchmark: 2,000 unrelated retained sessions, 5,000 create/retire cycles per arm, four counterbalanced timing pairs and two separate allocation pairs. Baseline omits retirement as before; candidate calls the production cleanup.

Owner metric per 5,000 cycles Baseline Candidate
CPU, ms 3.28 101.50
Sampled allocation, MB 10.63 12.44
Retained heap, MB 6.581 0.117
Additional aliases after retirement 10,000 0

Cleanup adds approximately 19.6 µs and 362 sampled allocation bytes per retirement. This is a small retention fix, not a CPU/allocation optimization.

The existing real sessions.delete regression failed on baseline because retired progress remained readable (1 intended failure, 20 other tests passed). With the fix: 21 deletion tests, 8 diagnostic-owner tests, 16 reset-cleanup tests, and 30 rig/import-closure tests passed. Root script and matching Gateway test typechecks, changed-file lint/format, and export-name collision checks passed. An exact 17-line test allocation covers the extension of the existing fixture.

Two incomplete candidate attempts are excluded: initial store initialization and a minute-30 reload returned explicit metadata-changed/retry read responses. The final UI poller records only those two observed chat.history/chat.metadata UNAVAILABLE responses and continues on the next scheduled poll; turns, mutations and unexpected errors remain fatal. The accepted candidate had zero retryable reads. One local test invocation overlapped build output publication and failed setup on a missing extension dist directory; the serialized post-build invocation passed.

Larger growing owners in the baseline were bounded: SessionListViewCache 1.83 → 6.04 MB (512 entries / 32 MiB estimated cap), prompt-history trackers 1.85 → 3.02 MB (512 trackers / 16 MiB history), and replacement cache backing tables. Constructor retained totals overlap and are not summed. The fixture lacks real channel traffic, deep production transcripts, real plugin workloads, external tool runtimes and sandbox/worktree churn; it does not establish the cause of a larger production retention slope.

Exact-head CI passed on 3015721c1cce1eea01cb43139114cf80c1791302: CI run 43761136576, 69 passing checks across the PR and no pending or failed checks. No CI retries were needed.

Reset/delete joins the session's producers and drains queued diagnostics before
releasing activity aliases. Preserve idle progress and retry/recovery evidence
until that lifecycle boundary.

A 165-minute synthetic Gateway soak retained 1,861 retired session IDs and 882
deleted keys before the fix. The repeat retained none; diagnostic map growth
fell from 0.750 to 0.053 MB/hour. Add repeatable same-process heap-pair tooling
and extend the real deletion regression, which fails on the baseline.

Release-note context: reclaim stale diagnostic activity after session reset or
deletion without changing active-run recovery behavior.
@clawsweeper

clawsweeper Bot commented Nov 15, 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.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor
Codex Review Summary: ✅ Completed

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-11-15T21:01:54.344036Z 3015721 PR opened
ℹ️ 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 gateway Gateway runtime scripts Repository scripts size: M labels Nov 15, 2026
@clawsweeper clawsweeper Bot added clawsweeper:intake:bug 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. proof: sufficient ClawSweeper judged the real behavior proof convincing. 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. and removed clawsweeper:intake:bug Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Nov 15, 2026
@clawsweeper

clawsweeper Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR releases diagnostic aliases during Gateway session reset/delete and extends the existing heap rig with a repeatable soak workload.

Example: Delete session sess-active, indexed by agent:main:discord:group:dev and retired-alias.

  • Before: Diagnostic progress remains reachable through the retired session aliases.
  • After: Retired aliases disappear while diagnostic-sibling retains its progress.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused, useful retirement repair with production-entry-point evidence, a meaningful regression, and no actionable findings.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): The supplied built-Gateway soak exercises session churn through real WebSocket RPCs with synthetic Responses servers and reports zero retired aliases after the repair; the measurements precede the final rebase and establish the narrow retention result, not a general Gateway performance improvement.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Long-running Gateways retain diagnostic state for sessions users have reset or deleted.
Reason: The maintainer-authored direction repairs measured stale references with a small runtime change and explicitly accepts its modest cleanup cost.

Merge readiness

✅ Ready for maintainer review

Keep open: this maintainer-authored PR repairs a demonstrated diagnostic memory leak still present on main, with no actionable correctness or security findings; exact-head CI remains pending.

Priority: P2
Reviewed head: 3015721c1cce1eea01cb43139114cf80c1791302

Before merge

None.

Findings

None.

Agent review details

How this fits together

Gateway reset/delete joins session work, then invokes runtime cleanup; the diagnostic owner consumes progress events and indexes activity by session and run references.

flowchart TD
  A[Gateway reset or delete] --> B[Join session producers]
  B --> C[Runtime cleanup]
  C --> D[Drain queued diagnostics]
  D --> E[Check existing lifecycle guard]
  E --> F[Remove retired activity aliases]
Loading

Technical review

Best possible solution:

Retain the focused repair at the existing session-retirement boundary, preserving ordinary completion and recovery evidence.

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

Current-main source retains activity aliases after session cleanup, and the supplied baseline deletion regression fails because retired progress remains readable; this read-only review ran no target code.

Is this the best way to solve the issue?

The patch fixes the existing diagnostic owner at the established retirement boundary, reuses the queue barrier, and preserves completion semantics with no unnecessary production machinery.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 8656c447df05.

Provenance checked

  • Diagnostic activity lifetime keeps the original intent (7b93d64: Release completed-run references after queued events drain while retaining idle progress and retry evidence.)
  • Gateway retirement ordering keeps the original intent (36e277d: Give session lifecycle operations one controller and retire resources after actual producers settle, before a successor is admitted.)
  • Synthetic heap rig keeps the original intent (05ce3c3: Provide repeatable long-running Gateway workloads and retaining-path diagnostics.)

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

  • Pinned introduction and merge scope: The introduced diff contains the seven supplied paths; the verified synthetic merge changes those same paths without removing base-only work. (3015721c1cce)
  • Retirement ordering: Cleanup awaits the existing diagnostic queue-prefix barrier, retains the existing incarnation guard, and then requests alias removal after producer settlement. (src/gateway/session-reset-runtime-cleanup.ts:129, 3015721c1cce)
  • Single diagnostic owner: The new operation removes references only when their activity object matches the retired session's activity; it adds no parallel state owner. (src/logging/diagnostic-run-activity-state.ts:49, 3015721c1cce)
  • Current-main necessity: Fetched main lacks both the retirement operation and its cleanup invocation, so the central repair remains necessary. (src/gateway/session-reset-runtime-cleanup.ts:127, 8656c447df05)
  • Behavioral regression: The existing deletion test now checks removal of the retired ID/key and an additional alias while preserving unrelated progress; the PR reports the intended failure on baseline and success with the repair. (src/gateway/server.sessions.delete-lifecycle.test.ts:203, 3015721c1cce)
  • Supplied Gateway proof and accepted cost: The PR records paired built-Gateway soaks using real WebSocket RPCs and synthetic Responses servers: baseline retained 1,861 retired IDs and 882 deleted keys; candidate retained none across 1,884 retired IDs and 894 deleted keys. The maintainer explicitly records approximately 19.6 microseconds additional cleanup per retirement and limits the performance claim to retention. (3015721c1cce)

Likely related people:

  • Anand Sharma: Raw commit f5fce6e adds src/logging/diagnostic-run-activity-state.ts:48 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: f5fce6e59e45; files: src/logging/diagnostic-run-activity-state.ts)

PR surface

Source +20, Tests +17, Other +193. Total +230 across 7 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 2 20 0 +20
Tests 1 17 0 +17
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 4 293 100 +193
Total 7 330 100 +230

Preflight source

Source unknown. Source comparison at the observed PR snapshot only. Completion is self-reported; body, policy, tests, execution, and report bytes are not verified.

Review metrics

Metric Value Why it matters
Runtime versus regression growth Runtime +20/-0 lines; regression +17/-0 lines The runtime additions implement ordered alias retirement; the regression extends an existing lifecycle fixture.
Diagnostic script options 2 added flags: --soak and --state-dir Both configure the source-checkout heap rig; neither adds Gateway configuration or changes installed defaults.

Labels

Label changes:

No label changes.

Label justifications:

  • P2: The demonstrated leak accumulates diagnostic memory under session churn, without evidence here of an urgent crash or broken delivery workflow.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • 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.

Reviewed November 15, 2026, 4:15 PM ET / 21:15 UTC.

@steipete
steipete merged commit 1e7f1f7 into main Nov 15, 2026
157 of 159 checks passed
@steipete
steipete deleted the steipete/perf-soak-retention-pair-20261115 branch November 15, 2026 21:30
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 16, 2026
…w#199761)

Reset/delete joins the session's producers and drains queued diagnostics before
releasing activity aliases. Preserve idle progress and retry/recovery evidence
until that lifecycle boundary.

A 165-minute synthetic Gateway soak retained 1,861 retired session IDs and 882
deleted keys before the fix. The repeat retained none; diagnostic map growth
fell from 0.750 to 0.053 MB/hour. Add repeatable same-process heap-pair tooling
and extend the real deletion regression, which fails on the baseline.

Release-note context: reclaim stale diagnostic activity after session reset or
deletion without changing active-run recovery behavior.
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. 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