Skip to content

fix: avoid shutdown waits behind shared-state readers - #197219

Merged
steipete merged 4 commits into
mainfrom
steipete/perf-micro-shutdown-agent-db-close-tail-20260919
Nov 11, 2026
Merged

steipete merged 4 commits into
mainfrom
steipete/perf-micro-shutdown-agent-db-close-tail-20260919

Conversation

@steipete

@steipete steipete commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Fixes: Gateway shutdown can wait five seconds per retiring shared-state connection when another reader holds a WAL snapshot, including connections borrowed by agent workers.

User Impact

Retirement stops waiting for peer readers. Existing snapshots and committed writes remain available in the WAL; clean-close proof still requires successful checkpoint/close and empty journals. No schema, configuration, or durability-policy change.

Why This Change Was Made

Agent database close already disables the normal write busy timeout. Shared-state handle retirement omitted that policy, so the agent close step could spend its time waiting on the worker's shared-state TRUNCATE checkpoint. Apply the same policy at the shared-state native lifecycle owner.

The smallest complete repair adds five production lines, including an existing-helper import and the already-closed retry guard. The 30-line regression checks a real reader, preserved WAL/snapshot and persisted writes; its separate test-line allocation covers exactly this growth. No new runtime abstractions or caches.

Evidence

Acceptance, set before the comparison: on a warm 34.94 GiB synthetic agent DB with 10,000 sessions, one million transcript events and roughly 31 MiB of newly written WAL, remove the shared-reader checkpoint wait and bring median async agent retirement below one second, with no 20% CPU or sampled allocation regression. Two A/A controls, five counterbalanced baseline/candidate pairs, and a separate five-pair allocation pass. Native pragma timings include worker connections; sampled JS allocation is main-isolate only.

Metric Before median (range; p95=max, n=5) After median (range; p95=max, n=5)
Async agent retirement 5507.6 ms (5497.2–5549.1) 140.6 ms (137.5–192.6)
Shared-state TRUNCATE 5368.4 ms (5356.1–5379.3) 4.25 ms (2.83–30.47)
Agent TRUNCATE 115.57 ms (114.43–139.73) 118.05 ms (114.28–143.63)
Process CPU 110.65 ms (106.71–115.13) 96.81 ms (88.55–101.27)
Separate sampled main JS allocation 832,192 B (807,192–969,008) 900,488 B (799,056–922,888)

Baseline A/A: 5531.4/5523.1 ms. Every paired run retained the final agent seal. Allocation median increased 8.2% with overlapping ranges; no allocation improvement is claimed, and it remained below the predeclared 20% regression threshold. Native allocations and worker-isolate JS allocations are not measured. Source hashes distinguish both owner versions in every output row. Reproducer: node --expose-gc --import ./scripts/tsx.mjs scripts/perf/agent-db-close-small-wal-measure.mjs --root .local/close-fixture --worker --scatter --shared-reader --samples 5; its header gives the synthetic seed command.

The new regression fails on the unmodified owner at 5,389 ms and passes with the fix. Shared-state cleanup and clean-close admission suites pass (20 tests). No optimize, ANALYZE, or integrity scan occurs during ordinary close. Planner maintenance is already bounded and outside shutdown.

Limits: macOS/APFS with warm filesystem caches; this is the real native agent retirement owner, not whole-Gateway or Linux/btrfs proof. Production attribution and next-handoff timings remain unverified.

Codex autoreview of the complete local change against b45c0f4a0da1554d9902457694e2fe17a47b3db9: scoped-clean through P2, no actionable findings. Runtime delta +5 lines; test delta +30; reproducible measurement tooling +350. The cleanup suite passes 9 tests in a 2.22 s harness run; the admission suite passes 11 in 3.02 s, excluding compiler-cache preparation. UI import-boundary search found no affected browser consumers. Exact-head CI run 43026790597 passed.

pnpm check:changed completed with failures in dead-export and script lint checks. The PR-caused script findings were fixed; the exact script lint command, script-export scan, and final benchmark smoke pass. All other selected checks (core/test types, core lint, format, database boundaries and remaining guards) passed. The remaining 57 production and 32 full-tree dead-export findings reproduce identically with the canonical checker on exact parent b45c0f4a0da1554d9902457694e2fe17a47b3db9, with zero module-resolution errors and zero script findings. This is a real main check regression, not a green full check.

Inherited dead-export attribution

Existing source-cutover attribution is reused from #196784; the exact-parent reproduction was rerun for this PR. Newer entries were traced through their introducing owner patches. No claim of historical green Knip runs for every introduction.

Affected owner / export group Introducing commit / PR
Knowledge tool-result contracts, lean result functions and rowDate 9b7dcdc7a66dc (#196767), new exported definitions without recognized external production consumers
TelegramWidgetMessage, formatTelegramWidgetRequestText b22f35f7ed765 (#196991), new exported definitions with local/test consumers
BoundKeys, nextBindingSeq, TunnelStagedMessage 5f2f21a7ee193 (#196388), new exported definitions with local consumers
tunnel-child/keyfile createKeyFile 37a3b162a0c58 (#196380)
nestRequiredSummaryHeadings c7152f3bda8e5 (#196207), consumer moved into its owner
models-config/openclaw-tools, session auth/model types, linux-oom-score exports 625945b7ae01d (#192552), consumers redirected to narrower owners
tool-search-directory exports 80ba593b8b14b (#196252), local production uses
replyWithBillingRouteWarnings 56617cd000864 (#191326), local production use
provider-runtime auth/catalog facade exports f63e5cd0f6d38 (#190205), consumers redirected to narrower owners
provider-runtime classification/external-auth facade exports 964fa991c0aff (#132716), consumers redirected to narrower owners
provider-external-auth resolver 071f606eae77 (#139911), direct consumer replaced with injected owner resolver
resolveProviderModernModelRef 33d8f24c9926 (#129184), last external production consumer removed
resolveProviderRuntimePlugin a7436c8b4a93b (provider-hook runtime split), consumers redirected
four provider-auth facade types cf1ae7bb6a729 (#190544), contracts and callers moved to provider-auth-types

The first CI run exposed one PR-caused failure in test/scripts/lint-suppressions.test.ts: the trace helper had added a suppression. The helper now passes its database receiver explicitly instead. The exact failed suite passes locally (14 tests, 267 ms test time; 8.55 s harness), focused lint and the real worker-close smoke pass, and the follow-up Codex review is scoped-clean through P2. No allowlist or check was relaxed.

Landed as 78407f8cbfd97c4fb22514f629aed4b63550d720 from tested head 39785544987633f8eaa3bd96caaee3288d496277. Final-head CI passed; ClawSweeper final review has zero findings and zero open items. No deployment or production performance claim.

@clawsweeper

clawsweeper Bot commented Nov 11, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation scripts Repository scripts size: M labels Nov 11, 2026
@steipete
steipete marked this pull request as ready for review November 11, 2026 13:02
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Nov 11, 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-11T13:04:48.902509Z 8a86e40 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.

@steipete

Copy link
Copy Markdown
Contributor Author

The final candidate is 39785544987633f8eaa3bd96caaee3288d496277. The production fix remains the five-line shared-state retirement policy change. The CI suppression failure is repaired without extending an allowlist; its exact 14-test suite, lint, native worker-close smoke, and Codex follow-up review pass. There is no completed ClawSweeper review yet.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Nov 11, 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. 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. labels Nov 11, 2026
@clawsweeper

clawsweeper Bot commented Nov 11, 2026

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge.

What this changes

This PR disables SQLite busy waits when retiring shared-state handles and adds a pinned-reader regression, measurement tooling, and documentation.

Example: An agent worker retires while another connection holds a shared-state WAL snapshot.

  • Before: Reported median agent retirement takes 5507.6 ms, dominated by the shared-state checkpoint wait.
  • After: Reported median retirement takes 140.6 ms while the reader retains its snapshot and committed writes remain available.

Review scores

Measure Result What it means
Overall readiness 🦐 gold shrimp (3/6) Focused, source-supported repair with a valuable real-storage regression; supplied runtime evidence exercises the native owner rather than the shipped Gateway entry point.
Proof confidence 🦐 gold shrimp (3/6) The maintainer-authored PR is outside the ordinary contributor proof gate; its body reports native agent retirement with real SQLite readers on macOS/APFS, reducing the median from 5507.6 ms to 140.6 ms, with whole-Gateway and Linux limits stated explicitly.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Bug fix · Worth it: Yes · Fix scope: Complete
User problem: Gateway and agent-worker retirement can wait five seconds per shared-state connection behind a peer reader.
Reason: The maintainer-authored direction removes an unnecessary shutdown wait through the existing lifecycle owner while preserving storage guarantees.

Merge readiness

✅ Ready for maintainer review

Keep open: this PR fixes a concrete shared-state retirement delay still present on current main, with no actionable correctness or security findings.

Priority: P2
Reviewed head: 39785544987633f8eaa3bd96caaee3288d496277

Before merge

None.

Findings

None.

Tests

  • Missing end-to-end proof: Whole-Gateway signal-driven shutdown is not shown; the reported macOS native-owner measurements establish a narrower retirement result.
Agent review details

How this fits together

Shared-state lifecycle code receives retiring database handles, stops WAL maintenance, closes native connections, and publishes clean-close proof only when existing safety checks permit it.

flowchart TD
  A[Agent worker retirement] --> B[Shared-state lifecycle owner]
  B --> C[Zero busy timeout]
  C --> D[Final WAL checkpoint]
  E[Peer reader snapshot] --> D
  D --> F[Native connection close]
  F --> G[Conditional clean-close seal]
Loading

Technical review

Best possible solution:

Apply the existing zero-timeout retirement policy at the shared-state native lifecycle owner while retaining checkpoint, WAL preservation, and seal safeguards.

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

The source exposes the timeout-bearing final checkpoint, and the PR reports a real pinned-reader baseline failure at 5389 ms; this review executed no target code.

Is this the best way to solve the issue?

The patch restores the policy already used by agent database retirement at the correct shared owner, without adding a competing lifecycle path or weakening clean-close checks.

AGENTS.md: found and applied where relevant.

Codex review notes: model internal, reasoning medium; reviewed against 93e4800f6df9.

Provenance checked

  • Shared-state final checkpoint and clean-close publication keeps the original intent (f787a89: Reuse validated database facts after a clean shutdown while refusing stale or incomplete clean-close proof.)
  • Native shared-state cleanup ownership keeps the original intent (8b16e53: Let SQLite own ordinary exclusion and consolidate resource cleanup instead of maintaining separate coordination machinery.)

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit f787a89 adds src/state/openclaw-state-db-handle.ts:105 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: f787a896894d; files: src/state/openclaw-state-db-handle.ts)

PR surface

Source +5, Tests +30, Docs +5, Other +352. Total +392 across 6 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 1 5 0 +5
Tests 1 30 0 +30
Docs 1 5 0 +5
Config 0 0 0 0
Generated 0 0 0 0
Other 3 352 0 +352
Total 6 392 0 +392

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 +5 lines; tests +30 lines The small owner-level repair has one meaningful regression covering prompt retirement, snapshot preservation, committed data, and withheld sealing.

Labels

Label changes:

  • add P2: Removes a bounded but repeatable five-second wait per retiring shared-state connection without evidence of an outage or lost data.
  • 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: Removes a bounded but repeatable five-second wait per retiring shared-state connection without evidence of an outage or lost data.
  • 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.

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 11, 2026, 8:16 AM ET / 13:16 UTC.

@steipete
steipete merged commit 78407f8 into main Nov 11, 2026
137 of 139 checks passed
@steipete
steipete deleted the steipete/perf-micro-shutdown-agent-db-close-tail-20260919 branch November 11, 2026 13:44
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Nov 12, 2026
* fix: avoid shutdown waits behind shared-state readers

* chore: expose shutdown measurement trace imports to checks

* chore: satisfy shutdown benchmark lint rules

* chore: preserve trace receivers without a lint suppression
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. 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