Skip to content

perf(gateway): serve failed-delivery health counts from a status-first index - #164131

Merged
steipete merged 3 commits into
mainfrom
steipete/sqlite-delivery-failed-index
Oct 3, 2026
Merged

steipete merged 3 commits into
mainfrom
steipete/sqlite-delivery-failed-index

Conversation

@steipete

@steipete steipete commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Routine Gateway health polls can scan completed and pending delivery history to count failures when SQLite has no planner statistics.

User Impact

Dead-letter health counts select the failed range directly, with unchanged results and ordering. Existing databases incur a one-time index rebuild during writable admission; large histories require startup I/O and temporary disk space.

Why This Change Was Made

Reorder the existing idx_delivery_queue_failed to (status, queue_name, failed_at, id). This keeps the query, store API, worker execution, and steady-state index count unchanged while removing dependence on statistics-driven skip-scan selection.

Storage design: The shared-state delivery queue owns canonical delivery_queue_entries rows; the nonunique index is derived. This accepted index-only design keeps the schema version unchanged. The existing canonical-index admission owner detects the same-name mismatch, builds a probe and replacement atomically, and retains its integrity validation. No per-request repair is added. Older same-version writable owners can restore their queue-first definition on downgrade or binary rollback without changing rows; strict read-only validation may refuse until that writable repair occurs. Index construction and temporary space scale with retained queue history, and existing database integrity checks remain in force. Row formats, durability, retention, permissions, and configuration are unchanged. No schema-version bump is required.

The existing plugin-index repair regression moves to a focused sibling suite, sharing its template with the delivery case rather than growing the oversized state-database test file.

Evidence

The regression captures SQL from the real count kernel. Before the index change it failed on SCAN ... USING COVERING INDEX; afterward both no-statistics and ANALYZE cases select SEARCH ... (status=?), without a temporary B-tree. Queue-scoped timestamp/ID reads retain their covering search and ordering. Mixed pending/completed/failed rows, nullable failure timestamps, sorted groups, and minima preserve the result contract. Statements per admitted count operation: 1 SELECT before → 1 SELECT after; no new main-thread SQLite access.

The populated existing-database fixture proves runtime upgrade, unchanged row values, including JSON bytes, unchanged version metadata, a second reopen without further DDL, and rollback through the same repair owner using the older schema contract. It does not claim an older binary was booted.

Component micro-benchmark: 100,000 completed rows, 100 failed rows, ten queues; median of nine rounds of forty reads after warmup. Results serialize identically.

Planner state Prior audit, old → new Fresh component probe, old → new
No statistics 2.4850 → 0.01095 ms 3.07308 → 0.01406 ms
After ANALYZE 0.01648 → 0.01095 ms 0.01643 → 0.01693 ms

These measure the SQLite component, not end-to-end health latency. Analyzed databases already benefit from skip-scan; the fresh analyzed comparison was effectively flat. The gain is predictable failed-range selection without statistics. Regression assertions use query plans and statement counts, never timing thresholds.

The five suites below ran on the product candidate before main integration; the affected migration proof was refreshed afterward as described below.

Command Result Command wall time
pnpm test src/state/sqlite-query-plan.test.ts --maxWorkers=1 3 passed 303.32 s
pnpm test src/state/openclaw-state-db.index-repair.test.ts --maxWorkers=1 2 passed 163.22 s
pnpm test src/infra/delivery-queue-sqlite.test.ts --maxWorkers=1 30 passed 126.75 s
pnpm test src/infra/delivery-queue-terminal.test.ts --maxWorkers=1 22 passed 87.15 s
pnpm test src/state/openclaw-state-db.test.ts --maxWorkers=1 92 passed, 1 Linux-only skipped 209.25 s

Wall times include repository subprocess compilation and source verification on a shared host. The new query-plan case took 0.813 s; the delivery upgrade/rollback case took 0.506 s. The first pre-fix attempt failed before tests because its artifact inventory overlapped gateway setup; after setup completed, the pre-fix regression failed at the intended scan assertion (266.63 s command wall).

The terminal-pruning suite initially failed because an existing EQP assertion required queue-first equality-term order (132.79 s command wall). Its assertion now accepts either ordering of the same two equality terms while retaining the indexed-search and no-table-scan requirements; row-retention assertions remain unchanged.

Formatting, targeted oxlint, docs MDX validation, git diff --check, assertion-safety, max-lines, line-cap, and database-worker ratchets passed. Codex autoreview: scoped-clean through P2, no actionable findings.

LOC against the integrated main base: production and all non-test/non-doc files +1/-1 (net 0); tests +203/-53 (net +150); docs +14/-0. CI job seconds remain unavailable while CI is pending; landing is separate.

Current main was integrated to resolve the environment-budget conflict; its budget file is unchanged in this PR. The count query and index definition are unchanged from the tested candidate. Main also optimized canonical-index inspection, so the populated index-repair suite was rerun against the integrated owner: 2 passed, 117.36 s command wall (delivery case 0.174 s). The final diff was independently reviewed against that pinned main base.

Landing integration

After the first merge admission, main advanced and conflicted only in docs/reference/database-schemas/versioning.md. Merge commit fdaf415c3c4ace5f50e479c9229cc77f89e61bed integrates main 46fc2e34f2f2f980f1b496f959df28d1925b7ddb, preserving both the failed-delivery and meeting-caption index documentation. The six-file PR delta against that integrated main is unchanged.

Refreshed all five focused suites in one invocation:

pnpm test src/state/sqlite-query-plan.test.ts src/state/openclaw-state-db.index-repair.test.ts src/infra/delivery-queue-sqlite.test.ts src/infra/delivery-queue-terminal.test.ts src/state/openclaw-state-db.test.ts --maxWorkers=1

Result: 149 passed, 1 Linux-only skipped; 211.91 s command wall time (210.28 s runner total). Docs MDX validation and git diff --check passed. Fresh Codex autoreview of the integrated six-file candidate was scoped-clean through P2. Previous-head CI run 37106670659 completed successfully; it remains prior-head evidence, with current-head GitHub gates enforced during landing. No CI rerun was requested.

Use the existing canonical-index repair owner for the same-version status-first index. Preserve delivery rows, result ordering, and the worker query while covering populated upgrade and rollback. Health polling no longer depends on planner statistics to select the failed range.
@clawsweeper

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

clawsweeper Bot commented Oct 3, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed October 3, 2026, 4:06 AM ET / 08:06 UTC (Revision 3).

ClawSweeper review

What this changes

The PR reorders the existing delivery-failure SQLite index so Gateway health counts can select failed entries directly, and adds query-plan, upgrade, and rollback coverage.

Merge readiness

✅ Ready for maintainer review

The PR remains useful: fetched main still uses the queue-first index. No actionable introduced defect was found, and the documented storage tradeoff has compatibility coverage.

Likely related people: steipete (high-confidence routing based on recent merged database-admission work).

Priority: P2
Reviewed head: fdaf415c3c4ace5f50e479c9229cc77f89e61bed

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused index optimization with meaningful query-plan and compatibility coverage and no actionable introduced findings.
Proof confidence 🌊 off-meta tidepool Not applicable: Verified repository-admin authorship exempts ordinary contributor runtime proof. Supplemental evidence exercises the production count kernel and runtime database admission; populated upgrade, unchanged rows and metadata, idempotent reopen, and prior-schema repair sufficiently cover this derived-index change without claiming an older binary boot.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: Verified repository-admin authorship exempts ordinary contributor runtime proof. Supplemental evidence exercises the production count kernel and runtime database admission; populated upgrade, unchanged rows and metadata, idempotent reopen, and prior-schema repair sufficiently cover this derived-index change without claiming an older binary boot.
Evidence reviewed 8 items Pinned introduced change: The merge-base-to-head diff changes one production index definition; the remaining changes document its lifecycle and protect query plans, results, and compatibility. The stale test merge was not used to infer merge effects.
Still necessary on fetched main: The fetched main schema still defines the failed-delivery index as queue_name, status, failed_at, id. The PR's status-first change is absent there.
Existing query and admission owners: The count kernel filters status=failed, groups and sorts by queue_name, and omits a null minimum timestamp. Writable same-version admission invokes the existing canonical-index owner, whose savepoint builds a probe and replacement and validates integrity before release.
Findings None None.
Security None None.

How this fits together

Gateway health reporting reads failed-message counts from the shared delivery queue through a database worker. Writable database admission maintains the derived index used to group those counts by queue.

flowchart TD
  A[Delivery queue rows] --> B[Writable database admission]
  B --> C[Canonical index repair]
  C --> D[Status-first failure index]
  E[Gateway health poll] --> F[Database worker count]
  D --> F
  F --> G[Failure counts by queue]
Loading

Before merge

None.

Agent review details

Security

None.

PR surface

Source 0, Tests +150, Docs +14. Total +164 across 6 files.

View PR surface stats
Area Files Added Removed Net
Source 1 1 1 0
Tests 4 203 53 +150
Docs 1 14 0 +14
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 6 218 54 +164

Review metrics

Metric Value Why it matters
Steady-state count work 1 SELECT before → 1 SELECT after; 0 additional indexes The optimization changes index selection without adding polling queries or ongoing index-maintenance count.

Technical review

Best possible solution:

Keep one canonical admission owner for the replacement index while preserving delivery rows, count semantics, worker execution, and the documented rollback contract.

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

Yes, the production status-only count and queue-first main index establish the performance mechanism, and the PR reports an intended pre-fix query-plan failure. This review inspected source and coverage without independently executing it.

Is this the best way to solve the issue?

Yes, reordering the existing derived index is a focused solution that preserves the query and worker boundary while retaining queue-scoped ordering.

AGENTS.md: found and applied where relevant.

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

Labels

Label changes:

No label changes.

Label justifications:

  • P2: This is a bounded health-poll performance improvement with unchanged delivery behavior.
  • merge-risk: 🚨 compatibility: The accepted same-version rebuild requires startup I/O and temporary disk, and older strict read-only validation may refuse until writable repair; populated upgrade and rollback coverage addresses the contract.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🌊 off-meta tidepool and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Not applicable: Verified repository-admin authorship exempts ordinary contributor runtime proof. Supplemental evidence exercises the production count kernel and runtime database admission; populated upgrade, unchanged rows and metadata, idempotent reopen, and prior-schema repair sufficiently cover this derived-index change without claiming an older binary boot.

Evidence

What I checked:

  • Pinned introduced change: The merge-base-to-head diff changes one production index definition; the remaining changes document its lifecycle and protect query plans, results, and compatibility. The stale test merge was not used to infer merge effects. (src/state/openclaw-state-schema.sql:1592, fdaf415c3c4a)
  • Still necessary on fetched main: The fetched main schema still defines the failed-delivery index as queue_name, status, failed_at, id. The PR's status-first change is absent there. (src/state/openclaw-state-schema.sql:1592, 7c53de2d0777)
  • Existing query and admission owners: The count kernel filters status=failed, groups and sorts by queue_name, and omits a null minimum timestamp. Writable same-version admission invokes the existing canonical-index owner, whose savepoint builds a probe and replacement and validates integrity before release. (src/infra/sqlite-index-schema.ts:148, fdaf415c3c4a)
  • Query-plan regression: The test captures SQL executed by the production count kernel and checks failed-range covering search both without statistics and after ANALYZE, one statement per count, result ordering, null timestamps, and queue-scoped listing order. The captured PR body reports the intended pre-fix scan failure. (src/state/sqlite-query-plan.test.ts:63, fdaf415c3c4a)
  • Existing-state compatibility: The populated fixture installs the previous index definition, opens through runtime admission, preserves rows including JSON bytes and version metadata, verifies a second reopen without DDL, and restores the prior index through the same repair owner. This proves the derived-index contract, not execution of an older binary. The captured body reports 149 passing focused tests and one Linux-only skip after integration. (src/state/openclaw-state-db.index-repair.test.ts:96, fdaf415c3c4a)
  • Recorded storage tradeoff: The captured PR body explicitly accepts the index-only design, proportional startup I/O and temporary disk, and strict read-only rollback refusal until writable repair. The documentation matches that scope. A live permission read confirms steipete has repository admin access, so this is a repository-authorized design record rather than an external contributor assertion. Public docs: docs/reference/database-schemas/versioning.md. (docs/reference/database-schemas/versioning.md:89, fdaf415c3c4a)

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-03T07:27:25.640Z sha cbffb31 :: needs changes before merge. :: none
  • reviewed 2026-10-03T07:37:44.259Z sha b58c19d :: needs maintainer review before merge. :: none

@steipete
steipete marked this pull request as ready for review October 3, 2026 07:32
Preserve both failed-delivery and meeting-caption index documentation while integrating main 46fc2e3. The delivery-index product delta is unchanged. All five focused suites pass (149 tests, one Linux-only skip); docs validation and independent review through P2 pass.
@steipete
steipete merged commit 6f85fa9 into main Oct 3, 2026
131 checks passed
@steipete
steipete deleted the steipete/sqlite-delivery-failed-index branch October 3, 2026 08:11
@steipete

steipete commented Oct 3, 2026

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 4, 2026
Use the existing canonical-index repair owner for the same-version status-first index. Preserve delivery rows, result ordering, and the worker query while covering populated upgrade and rollback. Health polling no longer depends on planner statistics to select the failed range.
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 merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. 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