Skip to content

perf(gateway): move post-ready notice sweeping off the main thread - #165331

Merged
steipete merged 2 commits into
mainfrom
dbasync/postready
Oct 5, 2026
Merged

steipete merged 2 commits into
mainfrom
dbasync/postready

Conversation

@steipete

@steipete steipete commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Post-ready session-watch recovery reads watcher entries and writes cursor watermarks on the Gateway thread. A synthetic Gateway startup reproduced two main-thread BEGIN IMMEDIATE failures (database is locked) after /readyz succeeded. With retained notices, the sweep also scales synchronous session reads with the number of watchers.

Why This Change Was Made

Move pending-cursor discovery into the existing shared-state reader and the sweep transaction into the existing sessionState writer. Prepare watcher identities through the session reader, then recheck physical sources and current session identities at transaction and commit admission. The transaction rereads cursor bindings and watermarks, so acknowledgments and replacements during preparation are respected. Only committed notices return to the existing system-event queue; the startup lifetime joins accepted work before worker teardown.

The native sweep and its synchronous existence helper are removed. Registration, acknowledgment, and sweep share the same extracted admission helper. No schema, configuration, retention, durability, or existing SDK method-signature change; no update migration or new OPENCLAW_* name.

User Impact

The measured durable startup sweep performs no caller-thread SQL. The existing 30-day/50,000-row pruning policy and notice text remain unchanged. This is a main-thread SQL reduction, not a claim that total SQL or latency decreases.

Production diff: +246 / −84 / net +162; 330 changed lines, excluding tests and documentation.

Evidence

Measurement uses the retained sqlmeasure3 native SQLite observer: successful executions at DatabaseSync.exec and StatementSync.get/all/run/iterate, excluding prepares and failed statements. Fixtures and stores are synthetic and isolated; boot admission and teardown are outside the focused sweep window.

Populated real startup-observer entry: 12 retained watcher notices Before After
session-state-events.ts:354 — watcher existence and metadata 44 0
session-state-events.ts:374 — cursor transaction 17 0
session-state-events.ts:366 — shared-state opening 2 0
session-state-events.ts:367 — pending cursor inventory 1 0
Successful main-thread SQL (measured T1) 64 0
Restored notices 12 12
SQL errors in focused sweep 0 0

Baseline: e76032fbab8d; candidate base: a37950a0b4a0, integrated for the pre-existing architecture-cycle fix in #165284. The notice implementation is unchanged between those bases. The full-Gateway 45-second post-ready idle window improved 34 → 16 successful main-thread statements. The empty sweep fell 18 → 0, and failed main-thread BEGIN attempts fell 2 → 0. The remaining 16 statements are eight cron startup device-identity reads and eight GitHub OAuth maintenance reads. Both Gateways shut down cleanly. These are phase-window counts, not latency measurements.

Validation on Node 24.21.0 (macOS arm64):

  • Focused owner, regression, and real-Gateway close checks: 65 passed across five files, --maxWorkers=1, 522.41s wall including compiled-worker preparation. The replay regression took 22.058s; the real close regression took 27.463s. These exercise actual SQLite owners and Gateway teardown; mocked storage would not prove the boundary.
  • Final boundary/race, shared-registry, standalone process, wrapper inventory, and import-closure checks: 32 passed across eight files, --maxWorkers=1, 611.90s wall. The new acknowledgment/rebinding race took 20.892s; its final nine-test boundary file took 174.34s including transformation and setup.
  • Runtime build (qaRuntime): passed; build phases 408.8s. Existing worker-deploy source-map warnings remain; the focused source harness independently supplies caller attribution.
  • Madge: 0 cycles. Database-worker ratchet and line-cap ratchet: passed. Added OPENCLAW_* names: 0.
  • Codex autoreview through P2, Ultrafast: scoped-clean, no accepted/actionable findings.
  • SDK API comparison: completed successfully in 1263.76s wall; 128 reachable-declaration closure changes, 0 entrypoints added/removed, and 0 direct export-declaration changes (digest 1d1fc936). Inspected deltas are the additive sessionState.sweep / sessionState.pendingNotices contracts, the cursor-address type, and declaration movement from extracting the sweep; existing service methods retain their signatures.
  • node scripts/check-changed.mjs: passed in 2761.23s wall, including core typechecking, all 27 test typecheck graphs, formatting, lint, all three dead-export scans, database/auth guards, and zero runtime import cycles. Validation ran on a heavily loaded host; these wall times are not performance claims.

The worker-cutover caller census found the real sweep tests already in the host-owned database/Gateway projects; no routing changes were needed. The wrapper source-closure tests confirm that the two new host modules require no wrapper inventory addition.

An intermediate test preparation collided with a concurrent runtime rebuild (ENOENT for dist-runtime/extensions/arcee/package.json); final runtime build and test preparation ran sequentially.

The zero-caller-SQL regression failed on the original implementation. Coverage also includes missing watchers, cursor acknowledgment/rebinding while discovery yields, latest material watermarks, and the real Gateway close prelude joining accepted persistence after scheduler/connection cancellation.

Catalog refresh #165034 is already merged and worker-backed. Related parallel lanes: #165028, #165205, #165193, #165129; potential umbrella overlap #162433. The adjacent notice-formatting work in #126890 changes a different part of the notice flow. Also adjacent to the replysnap/readamp/sqlmeasure4, incognito P7e/P7f2/P7h/P7i/P7j, and other SQL phase lanes. These do not change this focused sweep ownership.

Remaining scope limits: the idle workload does not populate managed outgoing-media retention. Its remaining session lookups are separate background SQL debt. Retained-plugin cleanup is scheduled at 30 seconds with busy retries, so a 45-second window does not guarantee execution; its ledger reader is already worker-backed. The static inventory's old boot-sweep classification is not used to claim the measured runtime reduction.

Landing compatibility repair

ClawSweeper identified that admitted older stores may omit the first-use watcher_store_path column. Pending-cursor discovery now retains the previous tolerant row projection, and the writer compares absent bindings as null. The existing older-reader fixture covers cursor advancement and forced retention pruning before the first feature write, while preserving intentional suppression of notices without a physical store binding. No schema repair or authorization change is introduced.

The released-surface audit compared v2026.9.8 with this candidate: the sweep is internal, with no released src/plugin-sdk/**, api.runtime, or documented SDK-subpath exposure. This PR preserves its merge-base async signature. The extracted admission helper is internal; worker operations are additive. The original SDK comparison report remains valid because the compatibility repair changes implementation only, without declaration changes.

Final compatibility repair 5c05afea19f8: the worker-boundary suite passed 10/10 tests in 128.25s wall on Node 26.10.0, including the older-store regression (13.117s). The pre-fix query leaves its notification watermark at 0 instead of 2. The final fixture also verifies that the expired event is present before recovery and pruned afterward, the optional column stays absent through recovery, and a distinct subsequent feature write installs it without changing the user version. Focused lint, formatting, and git diff --check passed. The other 38 owner tests passed during the earlier two-file run; its only failure was the then-incorrect legacy-notice fixture expectation.

Exact-head CI run 37265752016 completed successfully for 5c05afea19f8, with no failed jobs. Summed reported CI job duration is 9,068 seconds (parallel job time, not elapsed or billed time; per-file CI seconds are not separately exposed). Final exact-head Codex P2 autoreview is scoped-clean, with no actionable findings.

ClawSweeper completed the repaired-head review at 2026-10-05 05:02 UTC: the older-store finding is resolved and no actionable findings remain.

Published-driver update proof passed on isolated Linux: published 2026.9.8 upgraded to candidate commit 5c05afea19f8f91d283370ecf2a6ea9651c2a9c4 using the repository's published-driver-update-docker.sh cell. Both packages carry version 2026.9.8; exact build identity distinguishes the candidate (2026.9.8-5c05afea19f8-2026-10-05T06-06-18.584Z). The updater exited 0 in 454.135s, phase finished; running-build and durable/incognito checks passed; /readyz returned HTTP 200 with ready: true and no failing checks. Fixture shutdown exited 0. Canonical packaging also passed all 151 public SDK subpath checks, CLI bootstrap checks, and UI budgets. Candidate tarball SHA-256: d90c681ad114aae68db82a54efc4df4080eb365d84360cda6b7bb2f5af4aec6a.

Infrastructure attempts were separate from product proof: Testbox remained queued and was stopped; AWS quota fallback was undersized and stopped before the payload; the successful host required the supported Docker setup. A concurrent local Node installation change was recovered with an already-installed supported runtime. All task-owned leases are stopped/released.

Replay retained notices through the existing shared-state and session readers, with cursor rereads and current watcher grants in the state writer. Preserve acknowledged publication and startup close settlement; remove the native sweep path.
@clawsweeper

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

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation gateway Gateway runtime size: L labels Oct 5, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 5, 2026
@clawsweeper

clawsweeper Bot commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed October 5, 2026, 1:02 AM ET / 05:02 UTC (Revision 3).

ClawSweeper review

What this changes

Moves startup recovery of retained session-change notices into existing database workers while preserving cursor updates, notice publication, and shutdown settlement.

Merge readiness

✅ Ready for maintainer review

The previous older-store compatibility finding is resolved. No additional actionable defect was found, and current main still performs the synchronous sweep, so this PR remains useful.

Priority: P2
Reviewed head: 5c05afea19f8f91d283370ecf2a6ea9651c2a9c4

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused worker cutover with strong production measurements and the previous compatibility blocker repaired.
Proof confidence 🦞 diamond lobster (5/6) Sufficient (live_output): The supplied macOS startup-observer measurements exercise the changed sweep through real SQLite owners and show zero caller-thread SQL with 12/12 notices restored. Inspected real-owner regressions supplement recovery, rebinding, older-store pruning, and Gateway shutdown settlement. No stored-data format or schema contract changes.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Verified Sufficient (live_output): The supplied macOS startup-observer measurements exercise the changed sweep through real SQLite owners and show zero caller-thread SQL with 12/12 notices restored. Inspected real-owner regressions supplement recovery, rebinding, older-store pruning, and Gateway shutdown settlement. No stored-data format or schema contract changes.
Evidence reviewed 7 items Previous finding resolved: Pending discovery uses selectAll and normalizes absent watcher_store_path values to null; the writer performs the same normalization before comparing bindings. This addresses the exact optional-column failure retained in the previous review.
Older-store regression: The extended fixture removes the first-use column, reopens the store, sweeps before a feature write, verifies cursor advancement and expired-event pruning, preserves intentional suppression of unbound notices, and checks that recovery leaves schema markers unchanged. The captured body and contributor comment report 10/10 boundary tests passing and a pre-fix watermark failure of 0 instead of 2.
Worker ownership and currentness: The sweep captures physical watcher sources, checks identities at transaction and commit admission, rereads cursor bindings and watermarks inside the writer transaction, and publishes only returned committed notices. Registration and acknowledgment reuse the extracted existing admission helper.
Findings None None.
Security None None.

How this fits together

Session watches retain change watermarks so OpenClaw can restore pending notices after restart. Gateway startup reads those watches, validates their receiving sessions, updates the watermarks, and returns notices to the system-event queue.

flowchart TD
  A[Gateway startup] --> B[Pending watch reader]
  B --> C[Watcher session reader]
  C --> D[Current identity checks]
  D --> E[Cursor writer transaction]
  E --> F[System-event queue]
  E --> G[Retention pruning]
  A --> H[Shutdown settlement]
  H --> E
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source +162, Tests +260, Docs +10. Total +432 across 14 files.

View PR surface stats
Area Files Added Removed Net
Source 10 246 84 +162
Tests 3 320 60 +260
Docs 1 10 0 +10
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 14 576 144 +432

Review metrics

Metric Value Why it matters
Measured recovery Caller-thread SQL 64 → 0; restored notices 12 → 12 The supplied production-boundary measurement supports thread placement without claiming reduced total SQL or latency.
Production versus test growth Production net +162 lines; tests net +260 lines Production growth implements worker preparation and admission, while test growth covers recovery, races, compatibility, and shutdown.

Technical review

Best possible solution:

Keep notice recovery with the existing reader and writer owners, preserving older-store tolerance, current watcher identities, and accepted-work settlement.

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

Yes, the synchronous post-ready database path is identifiable on current main, and the supplied startup measurements establish its observed SQL activity; this review did not execute it.

Is this the best way to solve the issue?

Yes, reusing the existing database workers and admission owner is a focused solution, and the revised projection preserves the supported older-store contract.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • add status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The supplied macOS startup-observer measurements exercise the changed sweep through real SQLite owners and show zero caller-thread SQL with 12/12 notices restored. Inspected real-owner regressions supplement recovery, rebinding, older-store pruning, and Gateway shutdown settlement. No stored-data format or schema contract changes.
  • remove rating: 🦐 gold shrimp: Current PR rating is rating: 🐚 platinum hermit, so this older rating label is no longer current.
  • remove merge-risk: 🚨 compatibility: Current PR review selected no merge-risk labels.
  • remove status: ⏳ waiting on author: Current PR status label is status: 👀 ready for maintainer look.

Label justifications:

  • P2: This is a bounded Gateway startup performance and contention improvement with preserved user-facing behavior.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (live_output): The supplied macOS startup-observer measurements exercise the changed sweep through real SQLite owners and show zero caller-thread SQL with 12/12 notices restored. Inspected real-owner regressions supplement recovery, rebinding, older-store pruning, and Gateway shutdown settlement. No stored-data format or schema contract changes.
  • proof: sufficient: Contributor real behavior proof is sufficient. The supplied macOS startup-observer measurements exercise the changed sweep through real SQLite owners and show zero caller-thread SQL with 12/12 notices restored. Inspected real-owner regressions supplement recovery, rebinding, older-store pruning, and Gateway shutdown settlement. No stored-data format or schema contract changes.

Evidence

What I checked:

  • Previous finding resolved: Pending discovery uses selectAll and normalizes absent watcher_store_path values to null; the writer performs the same normalization before comparing bindings. This addresses the exact optional-column failure retained in the previous review. (src/sessions/session-state-events.read.worker.ts:30, 5c05afea19f8)
  • Older-store regression: The extended fixture removes the first-use column, reopens the store, sweeps before a feature write, verifies cursor advancement and expired-event pruning, preserves intentional suppression of unbound notices, and checks that recovery leaves schema markers unchanged. The captured body and contributor comment report 10/10 boundary tests passing and a pre-fix watermark failure of 0 instead of 2. (src/sessions/session-state-events.worker-boundary.test.ts:70, 5c05afea19f8)
  • Worker ownership and currentness: The sweep captures physical watcher sources, checks identities at transaction and commit admission, rereads cursor bindings and watermarks inside the writer transaction, and publishes only returned committed notices. Registration and acknowledgment reuse the extracted existing admission helper. (src/sessions/session-state-events.sweep.ts:100, 5c05afea19f8)
  • Production behavior proof: The captured PR body reports a real startup-observer sweep on isolated synthetic SQLite stores: successful caller-thread SQL fell from 64 to 0 while restored notices remained 12/12. Empty-sweep SQL fell from 18 to 0 and failed caller-thread BEGIN attempts from 2 to 0. Inspected regression code supplements this with zero-host-SQL, cursor-race, and actual Gateway close-boundary assertions; these checks were not executed during this read-only review. (src/gateway/server-lifecycle.catalog-write.test.ts:106, 5c05afea19f8)
  • Still necessary on main: The fetched main source still opens the shared database, inventories pending cursors, performs synchronous watcher lookups, and updates cursor watermarks on the caller thread. The merged catalog and lifecycle-patch work described in related context serves different operations and does not supersede this sweep. (src/sessions/session-state-events.ts:367, c5baaee54b00)
  • Area history: Available current-main history records Peter Steinberger's recent worker migrations for watch/version operations, watched-session prompts, and creation/compaction/spawn signals. These are routing evidence, not proof of feature introduction. (src/sessions/session-state-events.ts, 43ff5f17069f)

Likely related people:

  • steipete: Suggested for follow-up; no historical authorship or introduction is verified. (role: unverified routing candidate; confidence: low)

Rating scale

Score Internal tier Crab rank Meaning
6/6 S 🦀 challenger crab Exceptional readiness
5/6 A 🦞 diamond lobster Very strong readiness
4/6 B 🐚 platinum hermit Good normal PR; ordinary maintainer review
3/6 C 🦐 gold shrimp Useful, but confidence is limited
2/6 D 🦪 silver shellfish Proof or implementation needs work
1/6 F 🧂 unranked krab Not merge-ready
N/A NA 🌊 off-meta tidepool Rating does not apply

Overall follows the weaker of proof and patch quality.
Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

Workflow

  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.

History

Review history (2 earlier review cycles)
  • reviewed 2026-10-05T04:23:30.401Z sha afd2304 :: blocked before merge. :: [P1] Preserve reads without the first-use watcher store column
  • reviewed 2026-10-05T04:34:48.526Z sha afd2304 :: blocked before merge. :: [P1] Preserve reads without the first-use watcher store column

Keep pending cursor discovery tolerant of the first-use watcher store column and compare absent bindings consistently. Extend the existing older-store regression through recovery and pruning without changing schema or unbound notice suppression.
@steipete

steipete commented Oct 5, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Fixed the older-schema discovery finding in 5c05afe. Discovery uses the prior tolerant row projection, and the transaction normalizes the absent binding to null. The extended older-reader regression proves cursor advancement and forced pruning without installing the first-use column. It preserves intentional suppression of notices with an unbound store, then verifies a distinct feature write installs the column without changing the version. All 10 worker-boundary tests pass; the pre-fix query fails the cursor assertion (0 instead of 2).

@clawsweeper

clawsweeper Bot commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

🦞👀
Exact review queued.

Re-review progress:

@clawsweeper clawsweeper Bot added 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 rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Oct 5, 2026
@steipete
steipete merged commit cebf83f into main Oct 5, 2026
152 of 153 checks passed
@steipete
steipete deleted the dbasync/postready branch October 5, 2026 06:38
@steipete

steipete commented Oct 5, 2026

Copy link
Copy Markdown
Contributor Author

Merged via squash.

@vincentkoc

Copy link
Copy Markdown
Member

@steipete — this Gateway fixture needs a separate follow-up. Hosted job 111649085414 fails TS2739 at src/gateway/server-lifecycle.catalog-write.test.ts:162: the runGatewayStartupObservers call omits resolveGatewayContext and loadSubagentRegistryActivation.

The tested merge is 021be16548e3b24639673b650176fd807d9977e5, with baseline 3dc4128bdfef9278e33b0117bdb80fff87f5c99c and tooling head e813033a700708a0cc44101ac9397f00bc652651. The failing file is byte-identical to that baseline; the merge adds only the three tooling files in #165400.

The existing runtime-store fixture supplies both dependencies with resolveGatewayContext: () => undefined and loadSubagentRegistryActivation: async () => () => {}. Please route the separate fixture correction through its Gateway owner, retaining the real accepted-write/shutdown-settlement assertions and verifying the gateway-server type graph plus the actual catalog-write suite. The tooling repair remains held on this CI failure; no Gateway changes or CI reruns have been made as part of it.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 6, 2026
…penclaw#165331)

* perf(gateway): move post-ready notice sweeping into workers

Replay retained notices through the existing shared-state and session readers, with cursor rereads and current watcher grants in the state writer. Preserve acknowledged publication and startup close settlement; remove the native sweep path.

* fix(sessions): preserve notice recovery for older stores

Keep pending cursor discovery tolerant of the first-use watcher store column and compare absent bindings consistently. Extend the existing older-store regression through recovery and pruning without changing schema or unbound notice 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 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. 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.

2 participants