Skip to content

improve: reduce idle delivery and notification database work - #168643

Merged
steipete merged 2 commits into
mainfrom
dbasync/pdaudit
Oct 10, 2026
Merged

steipete merged 2 commits into
mainfrom
dbasync/pdaudit

Conversation

@steipete

@steipete steipete commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Idle outbound recovery and Web Push presence checks kept making worker requests, and each current audit append reread the row it had just inserted.

User Impact

Reduces database and worker traffic during ordinary turns. Delivery custody, send authorization, audit collection, retained fields, retention limits, and durability points are unchanged. No schema or update migration is required.

Why This Change Was Made

Use the existing physical-database receipt owner for the empty outbound queue and bound-subscription boolean. Queue insertions/replacements invalidate the empty fact; subscription writers publish or invalidate presence. The host consumes those facts before dispatching a read. The old connection-local delivery cache is removed. Audit reuses its prepared inserted values and validated sequence, retaining readback for already-expired records that pruning can remove.

Mentions already has the corresponding head cache on this base. Audit start/end and trajectory flushes remain separate: they cross distinct durability boundaries, and trajectory's remaining read enforces its sequence and retained-byte window. The target of 4 requests / 14 statements is an aim; this PR ships the smaller verified saving.

Evidence

Focused owner and sibling proof passed: 7 files / 130 tests, via node scripts/run-vitest.mjs ... --maxWorkers=1 (the repository pnpm test runner), 568.38 s wall time including 126.77 s cold worker preparation; Vitest duration 424.44 s on the loaded macOS host. The changed cases took 1.28 s (expired audit append), 3.79 s (subscription presence lifecycle), 4.28 s (expired-send cleanup), and 5.74 s (worker/native queue writes and rollback). These exercise real writer/reader boundaries; there are no new sleeps, timers, serial configs, or test-only production seams. Existing broader store lifecycles account for the suite cost; no CI-seconds claim is inferred from these host timings.

Codex autoreview: initial full-change review had no actionable P0–P2 findings; the second/final round reviewed the wrapper-inventory correction and had no actionable P0/P1 findings. Formatting and git diff --check passed. The initial local two-case probe was invalidated before tests by concurrent source edits during worker compilation; the subsequent frozen-candidate suite passed. No schema/update/Doctor/service/plugin-loading/SDK change, so the published-driver update cell and SDK API diff do not apply.

SQL measurement

Exact baseline e40606fdea96135758ec5bc0b1a355d08ead0c7e, measured product candidate 0d621268cd304261d8fe38573cce02d3ace2c608; final head b2bc97ff6b33c1e23c09ba81e17e2516dd40d822, same AWS host and shared full workload. Ran M,C,M,C,M,C, then the required extra M,C pair for raw warmed growth. The later one-line wrapper inventory correction changes no measured runtime code. Statistics below include all four pairs; warmed values are per turn.

Phase Baseline SQL Candidate SQL Δ SQL Baseline requests Candidate requests Δ requests MAIN baseline → candidate Duration ratio
01.boot 2079 [2079–2079] 2078 [2078–2079] -1 58 [58–58] 58 [58–58] +0 1899 [1899–1899] → 1899 [1899–1899] 0.965
01.connect 932.5 [932–941] 985 [934–1063] +52.5 48 [46–49] 48 [46–50] +0 72 [68–78] → 78 [72–78] 1.002
02.first-turn 1733 [1661–1781] 1614.5 [1485–1777] -118.5 317 [295–328] 293.5 [289–324] -23.5 78 [57–83] → 75.5 [60–108] 0.959
03.warmed 687.6 [683.2–695] 690.65 [681.3–693.4] +3.05 183.35 [182.3–185.4] 183.8 [181.5–184.5] +0.45 8.05 [7.6–10.2] → 9.65 [7.6–10.2] 0.999
04.second-session 2506 [2502–2510] 2486.5 [2484–2572] -19.5 614.5 [614–615] 610.5 [610–632] -4 87 [81–87] → 81 [81–90] 0.998
05.control-plane 14 [13–15] 13 [13–14] -1 4 [3–4] 3 [3–3] -1 0 [0–0] → 0 [0–0] 1.002
06.cron 865.5 [855–871] 863.5 [860–868] -2 196 [194–197] 194 [194–194] -2 36 [29–36] → 36 [36–36] 0.999
07.compaction 273 [272–274] 273 [272–274] +0 74 [74–74] 74 [74–74] +0 23 [23–23] → 23 [23–23] 0.985
08.shutdown 100 [97–100] 92.5 [88–100] -7.5 15 [14–16] 14 [14–15] -1 56 [56–59] → 56 [56–56] 0.958
done 0 [0–0] 0 [0–0] +0 0 [0–0] 0 [0–0] +0 0 [0–0] → 0 [0–0] 0.929
total 15383.5 [15370–15385] 15320.5 [15265–15427] -63 3159 [3157–3161] 3134.5 [3133–3162] -24.5 2328.5 [2321–2341] → 2338 [2326–2383] 0.987

Warmed-window scope operations (per turn):

Operation Baseline SQL Candidate SQL Δ SQL Baseline requests Candidate requests Δ requests
mentions.snapshot 0 [0–0] 0 [0–0] +0 0 [0–0] 0 [0–0] +0
deliveryQueue.outbound 0.4 [0.4–0.4] 0 [0–0] -0.4 0.4 [0.4–0.4] 0 [0–0] -0.4
audit.writer.process 16 [16–16] 14 [14–14.3] -2 2 [2–2] 2 [2–2.1] +0
trajectory.events.append 8 [8–8] 8 [8–8] +0 2 [2–2] 2 [2–2] +0
webPush.hasBoundWebPushSubscriptions 1 [1–1] 0 [0–0] -1 1 [1–1] 0 [0–0] -1

The targeted operations save 3.4 SQL statements and 1.4 requests per warmed turn (25.4 → 22 SQL; 5.4 → 4 requests). The first three pairs had raw warmed medians 683.9 → 691.8 SQL. The extra pair measured 691.3 → 689.5 warmed SQL and 15,382 → 15,331 whole-workload SQL, with requests 3,160 → 3,135. Across four pairs, raw warmed growth is 0.44%, within the unchanged-owner noise floor; the whole-workload median falls by 63 statements and 24.5 requests.

The additional warmed MAIN statements come from unchanged memory-admission cycles. Whole-workload family medians are identical: database.domain.execute 445 SQL / 32 requests, pluginState.compareDelete 119 / 34, pluginState.compareUpdate 102 / 17, and pluginState.observe 51 / 17. These move from first-turn into warmed windows. The deferred-startup boot+connect+first combined median falls 4748.5 → 4678 SQL (base runs 4793, 4786, 4672, 4711; candidate 4789, 4657, 4626, 4699). All compared duration ratios are below 1.5.

One candidate audit BEGIN IMMEDIATE returned busy before the changed readback path. The existing writer kept its queue head, retried after about 32 ms, inserted the record, and committed. Startup/shutdown lock diagnostics also occurred on the baseline. No warmed failures occurred in the extra pair.

Static checks and CI

Remote Madge, standalone Knip, database worker/T1 ratchet, and dialect ratchet passed. check:changed passed its 28 type graphs and preceding guards, then failed the dead-export scan on 16 unrelated existing exports. Running the exact scanner on the pinned baseline produced the same 16 findings, with no candidate-only or baseline-only entries and zero full-tree scan findings.

Initial required CI exposed a PR-caused extracted-wrapper dependency omission: the new delivery cache module was missing from wrapper-components.txt. The follow-up adds that single inventory entry. The focused runtime-import closure regression passes (1 test, 36.18 s runner wall; 25.48 s test). The second/final Codex review is clean. On corrected head b2bc97ff6b33, the source-closure and provisioning suites pass: 19 passed / 1 skipped across two files, 188.48 s command wall (source closure 3.14 s; provisioning 165.19 s). The baseline provisioning suite also passes, confirming the initial CI failure was repaired rather than waived.

The corrected-head CI database ratchets pass. The mock-export failure in src/model-picker/apply-session-model-selection-placement.test.ts matches main run 38090291712, job 114325165253, exactly. The identical Discord ambiguous-announcement timeout is confirmed in earlier PR #168316, run 38089565338 / job 114323332558, before this PR. Its test, queue cache kernel, and SQLite receipt code are byte-identical to this PR base. That cross-process fixture calls the runtime cached queue reader from a process other than the Gateway writer; it needs independent investigation against a direct committed snapshot. No passing CI result or completed fixture repair is claimed. Landing uses Peter’s authorized inherited-failure admin exception; the independent fixture investigation continues separately.

Production +105/−27 lines; tests +132/−53; docs +8/−0; wrapper inventory +1/−0.

Attribution and accepted limits

Implementation by Peter Steinberger. No contributor PR was incorporated. The Gateway is the single runtime writer; external writers must use the Gateway or hold exclusive offline ownership. These presence facts are scheduling hints, never permission to send. Actual delivery and subscription policies retain their current checks.

Keep queue and Web Push presence in the existing physical-database receipt owner. Preserve separate audit durability points while omitting readback for current newly inserted events. Audit collection, retention, and schema are unchanged.
@clawsweeper

clawsweeper Bot commented Oct 10, 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 size: M labels Oct 10, 2026
@clawsweeper clawsweeper Bot added 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. labels Oct 10, 2026
@clawsweeper

clawsweeper Bot commented Oct 10, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs changes before merge.

What this changes

This PR caches idle delivery and subscription-presence facts and avoids rereading newly inserted, unexpired audit events.

Example: A warmed Gateway turn checks an empty outbound queue and Web Push presence while recording audit events.

  • Before: The targeted operations average 25.4 SQL statements and 5.4 worker requests per turn.
  • After: The supplied measurements report 22 SQL statements and 4 worker requests per turn.

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) Useful, focused optimization with measured production behavior, meaningful storage coverage, and the prior finding resolved; no new code blocker was identified.
Proof confidence 🐚 platinum hermit (4/6) Sufficient (live_output): The supplied alternating AWS Gateway workload measurements exercise outbound recovery, Web Push presence, and audit writing at the measured runtime candidate; the final commit changes only wrapper inventory, so runtime evidence remains applicable.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Idle delivery and notification checks consume avoidable worker and SQLite capacity during ordinary Gateway turns.
Reason: The maintainer-authored direction has measured targeted savings, preserves existing contracts, and explicitly limits its broader performance claims.

Merge readiness

⛔ Needs changes before merge - 1 item remains

This PR delivers a useful, measured reduction in database work, and the previous wrapper-inventory finding is fixed. No new actionable code defect was found; the failed baseline-ratchet check remains unattributed.

Priority: P2
Reviewed head: b2bc97ff6b33c1e23c09ba81e17e2516dd40d822

Before merge

  • Complete next step - Identify the failing ratchet in the exact-head job and establish whether its failure is introduced or inherited before landing.

Findings

None.

Agent review details

How this fits together

Gateway delivery recovery, notification scheduling, and audit persistence use shared-state SQLite workers; committed writer receipts now let host callers reuse presence facts before dispatching another read.

flowchart TD
  A[Gateway callers] --> B[Physical database facts]
  B --> C[Shared state workers]
  C --> D[SQLite state database]
  D --> E[Committed writer receipts]
  E --> B
  A --> F[Current send authorization]
  F --> G[Notification transport]
Loading

Technical review

Best possible solution:

Retain this focused optimization with receipt-owned invalidation, unchanged send authorization, and the corrected wrapper inventory.

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

Baseline source shows repeated presence-worker dispatch and audit readback; the supplied workload measurements quantify those paths, and this read-only review ran no target code.

Is this the best way to solve the issue?

The patch uses the existing physical-database receipt owner, removes the superseded delivery cache, and retains readback where retention can remove an expired append.

AGENTS.md: found and applied where relevant.

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

Provenance checked

Testing

Proof path: shipped entry point.

Security

None.

Evidence

What I checked:

  • Pinned change reviewed: The introduced diff replaces the connection-local delivery cache, invalidates the shared empty fact at queue upserts, updates subscription presence at mutations, and preserves expired-audit readback; comparison with fetched main shows these runtime changes remain distinct work. (src/infra/outbound/delivery-queue-storage.kernel.ts:82, b2bc97ff6b33)
  • Previous finding resolved: The only change since the previously reviewed head adds delivery-queue-cache.ts to the extracted-wrapper inventory; its runtime dependencies are already inventoried. (scripts/pr-lib/wrapper-components.txt:827, b2bc97ff6b33)
  • Supplied runtime measurements: The full PR body reports four alternating baseline/candidate AWS workload pairs: targeted warmed operations save 3.4 statements and 1.4 requests per turn; whole-workload medians fall by 63 statements and 24.5 requests. Raw warmed SQL rises 0.44%, so this establishes targeted savings rather than an overall warmed-turn reduction. (b2bc97ff6b33)
  • CI failure attribution unavailable: The exact-head baseline-ratchet job failed during Run baseline ratchets: https://github.com/openclaw/openclaw/actions/runs/38090509599/job/114326018848. Its annotation reports only exit code 1; downloading logs was blocked at the artifact-storage redirect, so neither PR causation nor an inherited failure is established. (.github/workflows/ci.yml:2685, b2bc97ff6b33)
  • Ownership and authorization preserved: The database contract assigns runtime writes to the Gateway and invalidation to committed receipts. Subscription presence remains a scheduling preflight; approval and event delivery still obtain current recipient authority before transport. (src/gateway/approval-web-push.ts:129, b2bc97ff6b33)
  • Feature history: Merged history identifies Peter Steinberger across SQLite queue ownership, audit persistence, Web Push workers, and idle maintenance, with Josh Avant contributing delivery recovery and captured-context ownership. Follow-history inspection reached an unavailable older object; the verified merged history supports routing without asserting an unknown introduction. (src/infra/outbound/delivery-queue-storage.ts:379, 8d1c7bcbce48)

Likely related people:

  • Peter Steinberger: Raw commit 24df78b adds src/infra/push-web-store.kernel.ts:174 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 24df78b85fe1; files: src/infra/push-web-store.kernel.ts)
  • Josh Avant: Raw commit 4f53213 adds src/infra/outbound/delivery-queue-storage.ts:407 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: medium; commits: 4f53213ad359; files: src/infra/outbound/delivery-queue-storage.ts)

PR surface

Source +78, Tests +79, Docs +8, Other +1. Total +166 across 13 files. Added test files: 0.

View PR surface stats
Area Files Added Removed Net
Source 8 105 27 +78
Tests 3 132 53 +79
Docs 1 8 0 +8
Config 0 0 0 0
Generated 0 0 0 0
Other 1 1 0 +1
Total 13 246 80 +166

Review metrics

Metric Value Why it matters
Production versus tests Production +105/−27 lines; tests +132/−53 lines Production growth adds writer publication and host-side reuse while removing the old cache; tests cover real storage lifecycle and retention behavior.

Labels

Label changes:

  • add proof: sufficient: Contributor real behavior proof is sufficient.
  • add rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • remove rating: 🦪 silver shellfish: Current PR rating is rating: 🐚 platinum hermit, so this older rating label is no longer current.
  • remove merge-risk: 🚨 automation: Current PR review selected no merge-risk labels.

Label justifications:

  • P2: This is a bounded performance improvement with measured database and worker-request savings.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🐚 platinum hermit and patch quality is 🐚 platinum hermit.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.
  • 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 need explicit maintainer commands such as @clawsweeper autofix or @clawsweeper automerge.

History

Review history (2 earlier review cycles)
  • reviewed 2026-10-10T21:08:06.331Z sha 0d62126 :: needs maintainer review before merge. :: none
  • reviewed 2026-10-10T21:15:07.528Z sha 0d62126 :: needs changes before merge. :: [P1] [P1] Register the new cache module in the PR wrapper inventory

Reviewed October 10, 2026, 6:20 PM ET / 22:20 UTC (Revision 3).

@clawsweeper clawsweeper Bot added merge-risk: 🚨 automation 🚨 May affect CI, automerge, proof capture, label sync, or maintainer automation. 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 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. labels Oct 10, 2026
@openclaw-barnacle openclaw-barnacle Bot added the scripts Repository scripts label Oct 10, 2026
@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. merge-risk: 🚨 automation 🚨 May affect CI, automerge, proof capture, label sync, or maintainer automation. labels Oct 10, 2026
@steipete
steipete merged commit 566005d into main Oct 10, 2026
158 of 162 checks passed
@steipete
steipete deleted the dbasync/pdaudit branch October 10, 2026 22:49
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via explicitly authorized admin squash with attributed pre-existing CI failures.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 11, 2026
…w#168643)

* perf(sqlite): reuse idle delivery and notification facts

Keep queue and Web Push presence in the existing physical-database receipt owner. Preserve separate audit durability points while omitting readback for current newly inserted events. Audit collection, retention, and schema are unchanged.

* fix(tooling): include delivery cache in extracted PR wrappers
scribe-dandelion-cult added a commit to karmaterminal/openclaw that referenced this pull request Oct 15, 2026
Upstream first-parent #1297, stopping just before #1298 (tool-call XML
grouping) so that change gets its own step. Four conflicts:

- delivery-queue-sqlite-bound: keep both imports, upstream's
  emptyOutboundDeliveryQueueAdmission (openclaw#168643) and our row codec type.
- attempt-execution: keep our startAttemptContinuation; take upstream's
  resolveCommandAuthProfileSelection (openclaw#168392). Upstream's other edits in
  the file (inlined pinnedHarnessId, internal-continuation promptCacheKey)
  merged cleanly; our resolveClaudeCliFallbackPrelude extraction is
  untouched by upstream.
- session.test: keep our custody test state; take upstream's
  buildCommandContextForTest (openclaw#168482).
- plugin-sdk-surface-report: measured 3683/2137 (upstream 3672/2133, +11/+4).

Also: test-mock-exports baseline pruned 10162 -> 10142 (20 stale rows from
#1433's fixes; shrink only, check --prune), worker-access-inventory regen.
pnpm install after the lockfile change.

tsgo core/core-test/ext/ext-projects 0; sdk --check 0; inventory 0;
config docs 0; mock-export ratchet OK. db-worker ratchet 706 -> 709 vs
upstream is #1432 (unchanged vs step 25).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_01Jhynq2GVpzuVQQieebEubg
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: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. scripts Repository scripts size: M status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant