Skip to content

perf(infra): release caller graphs from retained error stacks - #186147

Merged
steipete merged 2 commits into
mainfrom
steipete/perf-cached-error-stack-retention-sweep-20261027
Oct 27, 2026
Merged

steipete merged 2 commits into
mainfrom
steipete/perf-cached-error-stack-retention-sweep-20261027

Conversation

@steipete

@steipete steipete commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes request buffers and session graphs staying alive after failures are cached or retained by long-lived runtime and plugin owners.

Related: #185584, #185647, #186100.

User Impact

Failed database opens, catalog requests, plugin shutdowns, transports, and worker lifecycles release otherwise unreachable caller data while keeping the original error identity, messages, codes, causes, and retry/authority behavior. No configuration or schema changes.

Eager stack formatting costs additional CPU and allocation when a failure is recorded. In the measured fixtures this adds about 11–16 µs per operation and releases roughly 29 MiB per three retained failures. This is a retained-memory fix, not a throughput improvement.

Why This Change Was Made

V8's lazy Error stacks can retain captured frames after the throwing operation ends. Materialize them at the existing failure owner rather than layering another cache or replacing Error instances with lossy records. The shared helper now traverses nested aggregates as well as causes and is available through the existing error-runtime SDK entrypoint.

The per-script census records fixed stores, existing protections, short-lived/string-only cases, and explicit follow-ups. Production delta: +195 lines across 61 files; identity/classification and retained-error contracts require keeping the original objects, so each existing storage boundary needs a small materialization call. No new runtime state or compatibility path.

Evidence

Acceptance: a retained real owner must release every caller fixture while preserving error identity/classification and failure policy. Three synthetic owners each retain three failures created with 10,000 sessions, 40 plugin descriptors, and an 8 MiB buffer per caller. Baseline b4b328b903ecec99179255bbe6f6c95fac885f45: each retains 3/3; candidate: each retains 0/3. SQLite includes an AggregateError.errors child without a cause link.

Five counterbalanced pairs, 3,000 operations per side; untraced timing and separate sampled-allocation passes:

Owner CPU µs/op base → candidate Sampled bytes/op base → candidate Retained buffers base → candidate
SQLite terminal-open latch 5.79 → 22.05 6,586 → 14,986 24 MiB → 0
Codex catalog backoff 4.20 → 14.75 6,164 → 11,700 24 MiB → 0
Matrix SDK stop gate 4.01 → 15.91 2,932 → 8,665 24 MiB → 0

Post-GC heap delta per three records: SQLite 5,236,888 → 18,512 B; catalog 5,226,616 → -6,336 B; Matrix 5,231,808 → -744 B. Small negative deltas are GC noise. Host load ranged 41.08–45.70.

Commands: node --expose-gc --import ./scripts/tsx.mjs scripts/perf/long-lived-error-stacks-measure.ts --owner <sqlite-latch|catalog-backoff|matrix-stop> --mode <heap|timing|allocation>; heap regression uses --records 3 --assert-collected, costs use --iterations 3000, baseline uses --base-dir <pinned-source>.

No production service was touched. No whole-Gateway load test or throughput/GC/latency claim: this follows the scoped fast path for terminal error storage rather than a hot successful request path. No remote validation lease allocated; PR CI supplies broad proof.

Independent subagent review (autoreview route unavailable): initial patch and lint follow-up clean at P0/P1/P2. The configured Codex autoreview preflight refused the requested route because it did not match operator configuration; no configuration was changed.

Focused SQLite latch (2 tests), catalog backoff (4), error-graph, bounded queue, async-work-scope, binary-stream, MCP transport/client (32), and auth-storage (41) checks passed. A first MCP setup attempt was invalidated by source edits during compilation; rerun on frozen source passed. Catalog wrapper took 197 s including 133 s of worker preparation; its retention test took 4.84 s. SQLite wrapper took 2.74 s. Full focused rerun took about 8 minutes, dominated by compiled-worker preparation and existing auth tests. Export collision guard passed. The required eager-import and PR-wrapper closure guards passed (32 tests), and the final error-graph rerun passed (12 tests). The test-line ceiling is unchanged; net test-line delta is -1 (the inherited tree remains 315 lines over its ceiling).

Changed-file formatting and lint passed. Rebased onto current main without conflicts; the patch is unchanged. Exact-head CI completed with the attributed exceptions below.

CI on the first head exposed a missing Control UI Vite subpath alias after the shared error graph gained a runtime import. Added the specific normalization-core/error-coercion source alias before the broad root alias. The existing Vite configuration file passes all 39 tests; changed-file lint/format and independent review passed. The UI build/E2E and Node shard failures from that head are attributable and addressed in 4a9cea446b4beb9639ae997ff49f500332d21152; the production UI build and UI performance job pass on the new head.

Final exact-head CI and failure attribution

CI run 40548562227 completed on 4a9cea446b4beb9639ae997ff49f500332d21152. CI remains red; this is not a green-check claim. Six test jobs failed, plus the aggregate gate. Build artifacts, core/extension lint, test types, package boundaries, docs, baseline ratchets, QA smoke, Docker seed E2E, UI performance, and PostgreSQL conformance passed. No failed CI jobs were rerun.

Failed test Attribution evidence
extensions/x/src/events.test.ts, unparseable-streak case Same AbortError at cleanup on PR head and unchanged parent 24e16034180f7a08eda5f17d2a2b573cde1868a5: 1 failed / 18 passed on both. Focused wrapper times 4.57 / 3.43 s. CI job.
src/config/sessions/session-accessor.sqlite-archive-session.test.ts, idle retirement with open scope false Same 120 s test timeout plus 180 s hook timeout on unchanged parent, after its first two cases passed. Parent recorded the failure at 300.004 s; its stuck cleanup was then terminated through the task-owned runner (exit 143). This is failure evidence, not a passing replay. CI job.
ui/src/e2e/chat-startup-priority.e2e.test.ts:235, hidden suggestion refresh Identical assertion (expected 0, received 1) in scheduled main run 40541472256, before this PR.
ui/src/e2e/chat-header-subagents.e2e.test.ts:211 Identical missing “1 subagent running” locator timeout in scheduled main run 40541472256.
ui/src/e2e/chat-cold-load-anchor.e2e.test.ts:404 Same wait for sessions.messages.unsubscribe times out in focused headless browser runs on head and unchanged parent: 1 failed / 2 passed on both (36.82 / 30.44 s test durations). CI job.
ui/src/pages/chat/chat-view.test.ts, two decorative-prefix cases All 139 tests passed in five isolated runs per revision. Head wrapper times: 16.58, 13.99, 11.53, 12.55, 7.85 s; parent: 9.05, 7.62, 7.95, 9.79, 8.85 s. Independent tracing confirms the string-only rendering path and its fixtures/helpers are unchanged and do not call stack materialization. Classified unrelated under the matched-replay rule; the original shared-shard cause remains unresolved. CI job.

Baseline checks used the same lane checkout, temporarily detached at the unchanged parent and returned to the PR branch afterward. Only the named failing files ran locally. The working tree is clean. This PR remains open and unmerged for the maintainer handoff; no merge or CI rerun was requested.

Materialize retained error graphs at failure owners while preserving error identity and classification. Extend the shared helper to aggregate siblings and expose it through the error-runtime SDK surface.

Three real-owner retention regressions release 24 MiB of caller buffers and about 5 MiB of session objects per three stored failures. Eager stack formatting adds 11–16 microseconds per recorded failure in synthetic owner measurements. Census and measured tradeoffs live beside the benchmark script.
@clawsweeper

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

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 🔄 Running since 2026-10-27T17:06:03.081167Z ce10333 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 docs Improvements or additions to documentation channel: matrix Channel integration: matrix gateway Gateway runtime extensions: memory-core Extension: memory-core scripts Repository scripts agents Agent runtime and tooling extensions: codex plugin: file-transfer extensions: google extensions: copilot plugin: cua-computer extensions: browser extensions: github GitHub plugin: link previews and reader channel: x size: L labels Oct 27, 2026
@github-actions

github-actions Bot commented Oct 27, 2026 •

Copy link
Copy Markdown
Contributor

⚠️ Security sensitive changes

This maintainer PR changes sensitive security components.

No secops approval is required. This comment is informational because the PR author has Maintain or Admin access.

  • Current SHA: 4a9cea446b4beb9639ae997ff49f500332d21152
  • Maintainer: @steipete
  • Repository role: admin

These security sensitive changes were made:

  • src/agents/auth-profiles/legacy-source-diagnostic.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.
  • src/agents/auth-profiles/oauth-refresh-failure.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.
  • src/agents/sessions/auth-storage.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.
  • src/secrets/egress-proxy/proxy-worker.ts: Controls credential persistence, secret resolution, or redaction. Check storage permissions, credential scope, and exposure in logs or responses.

Carefully review these changes before merging.

@openclaw-barnacle openclaw-barnacle Bot added the app: web-ui App: web-ui label Oct 27, 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. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. 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. labels Oct 27, 2026
@clawsweeper clawsweeper Bot removed clawsweeper:intake:needs-environment Preliminary submission classification; full source review pending. clawsweeper:intake:needs-repro Preliminary submission classification; full source review pending. labels Oct 27, 2026
@clawsweeper

clawsweeper Bot commented Oct 27, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR formats retained error stacks across existing runtime and plugin owners so completed callers can be collected.

Example: Three failed SQLite opens each capture an 8 MiB caller buffer.

  • Before: The supplied baseline measurements retain all three caller fixtures and 24 MiB of buffers.
  • After: The supplied candidate measurements retain zero caller fixtures while preserving the original errors and SQLITE_CORRUPT classification.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Useful owner-level retention evidence and a coherent patch with no actionable finding; supplied proof is harness-based and exact-head CI attribution remains unresolved.
Proof confidence 🦐 gold shrimp (3/6) The ordinary contributor proof gate does not apply to this maintainer-authored PR; supplied measurements exercise real SQLite, catalog, and Matrix retention owners with synthetic callers, without claiming live Gateway coverage.
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 failed operations can leave request buffers and session graphs retained by long-lived errors.
Reason: The measured memory saving supports the maintainer-approved failure-path CPU tradeoff, and the implementation preserves existing owners and behavior.

Merge readiness

✅ Ready for maintainer review

Keep this PR open: it addresses retained caller memory that current main still permits, with no discrete introduced bug found; exact-head CI failures remain unattributed.

Priority: P2
Reviewed head: 4a9cea446b4beb9639ae997ff49f500332d21152

Before merge

None.

Findings

None.

Agent review details

How this fits together

Runtime and plugin failure owners receive errors from completed operations and retain them for later rejection, retry, or cleanup; the shared helper materializes their nested stacks before storage.

flowchart LR
  A[Caller operation] --> B[Failure]
  B --> C[Existing failure owner]
  C --> D[Shared stack materializer]
  D --> E[Retained original error]
  E --> F[Retry or cleanup consumer]
Loading

Technical review

Best possible solution:

Keep the existing failure owners and shared materializer, preserving original errors while releasing their captured caller graphs.

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

Current-main source retains unformatted errors and misses aggregate siblings; the supplied baseline/candidate owner measurements demonstrate the retention mechanism, but were not rerun during this read-only review.

Is this the best way to solve the issue?

The change uses the existing shared helper and retention owners, preserves classification and settlement policy, and introduces no competing cache or lifecycle owner.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 7fa041d80fc2.

Provenance checked

  • Shared stack materialization keeps the original intent (40d735e: Release retired plugin inventories retained through long-lived runtime resources; the later repair in perf(process): release contexts retained by long-lived error stacks #185584 preserved error identity while tolerating opaque diagnostics.)
  • Joined cleanup error envelopes keeps the original intent (c7f5c3a: Preserve separate contracts for sole-error unwrapping and always-aggregate cleanup; the consolidated tests retain both contracts.)
  • Codex catalog failure reuse keeps the original intent (fix(codex): avoid repeated session catalog timeout waits #149378: Avoid repeated source timeouts through bounded backoff while preserving one immediate retry and source-scoped recovery.)
  • Matrix failed shutdown custody keeps the original intent (4ba65fc: Keep exclusive crypto-store custody through shutdown and uncertain retirement; materialization leaves the retained failure and no-retry policy intact.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit c7f5c3a adds src/infra/error-graph-internal.ts:17 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: c7f5c3a4406e; files: src/infra/error-graph-internal.ts)

PR surface

Source +195, Tests -1, Docs +108, Other +110. Total +412 across 68 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 61 264 69 +195
Tests 4 95 96 -1
Docs 2 108 0 +108
Config 0 0 0 0
Generated 0 0 0 0
Other 1 121 11 +110
Total 68 588 176 +412

Review metrics

Metric Value Why it matters
Production versus test LOC Production +195 net; tests -1 net Growth places small calls at existing retention owners without adding runtime state; the measurement script is excluded from production totals.

Labels

Label changes:

  • add P2: A bounded failure-path memory-retention repair with demonstrated synthetic-owner savings and no established urgent outage.
  • add merge-risk: 🚨 compatibility: Adds a documented public SDK export; the maintainer-authored direction accepts this additive expansion, with no existing export removed.
  • 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: A bounded failure-path memory-retention repair with demonstrated synthetic-owner savings and no established urgent outage.
  • merge-risk: 🚨 compatibility: Adds a documented public SDK export; the maintainer-authored direction accepts this additive expansion, with no existing export removed.
  • 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.

  • Classify the exact-head X transport and UI diagnostic failures using matching baseline evidence or a focused causal comparison.

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 27, 2026, 1:31 PM ET / 17:31 UTC.

@steipete

Copy link
Copy Markdown
Contributor Author

Admin-merging over checks-node-changed-extensions-bundle-2-1 and the ci-gate that rolls it up. The only failing test is extensions/x/src/events.test.ts > X event transport > warns once per unparseable streak without event content and clears on a good event, where runXEvents rejects with AbortError on caller abort. It fails identically on main at bf72e96b39a2 without this PR (18 passed, 1 failed locally on both), so the failure is inherited and not caused by the small extensions/x/src/spend.ts stack-materialization change here. A separate lane is bisecting and fixing it at the owner. Every other check is green at 4a9cea446b4b.

@steipete
steipete merged commit eea1d35 into main Oct 27, 2026
213 of 223 checks passed
@steipete
steipete deleted the steipete/perf-cached-error-stack-retention-sweep-20261027 branch October 27, 2026 18:46
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 28, 2026
…aw#186147)

* perf(infra): release caller graphs from retained error stacks

Materialize retained error graphs at failure owners while preserving error identity and classification. Extend the shared helper to aggregate siblings and expose it through the error-runtime SDK surface.

Three real-owner retention regressions release 24 MiB of caller buffers and about 5 MiB of session objects per three stored failures. Eager stack formatting adds 11–16 microseconds per recorded failure in synthetic owner measurements. Census and measured tradeoffs live beside the benchmark script.

* fix(ui): resolve the shared error graph source subpath
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling app: web-ui App: web-ui channel: matrix Channel integration: matrix channel: x docs Improvements or additions to documentation extensions: browser extensions: codex extensions: copilot extensions: github GitHub plugin: link previews and reader extensions: google extensions: memory-core Extension: memory-core gateway Gateway runtime merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. plugin: cua-computer plugin: file-transfer rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. scripts Repository scripts security-sensitive-changed size: L 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