Skip to content

fix: avoid slow task lookups and maintenance as history grows - #153548

Merged
steipete merged 5 commits into
mainfrom
codex/sql-query-performance
Sep 20, 2026
Merged

steipete merged 5 commits into
mainfrom
codex/sql-query-performance

Conversation

@steipete

@steipete steipete commented Sep 20, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

Task ownership checks, session recovery, and maintenance perform unnecessary database work as retained history grows. Scoped delivery cleanup scans unrelated queues, and inference retention loads cached payloads merely to count their bytes.

User Impact

Reduces database work while preserving matching, ordering, ownership checks, retention, and stored payloads. State schema 17 and agent schema 21 stay unchanged. The first writable open installs three nonunique indexes through canonical repair; later writes maintain them. Older same-version readers can ignore them.

Why This Change Was Made

The indexes cover requester ownership, placement environment, and exceptional session-validity predicates. Queue-scoped receipt pruning exposes its existing queue index to the planner. Inference pruning reads identity, time, and byte counts instead of payloads on UTF-8 stores; UTF-16 stores retain the existing UTF-8 accounting behavior.

Main's #153467 normalized run and child-session identifiers and made their existing indexes usable. This PR uses that implementation and adds no expression indexes for those identifiers. The accepted remaining storage decision is #153533. Compression and canonical payload redesign are separate follow-up work.

Evidence

  • Behavior and query-plan tests cover task ownership and ordering, exact/global queue isolation, session counts, worker cleanup, Unicode retention across UTF-8/UTF-16, and exact inference replay. The original regressions failed on scans or payload hydration.
  • Fresh/missing/drifted index tests preserve rows and schema versions, prove read-only admission before installation, verify compatible previous-schema expectations, and verify unchanged reopening.
  • Local validation includes the focused storage suites, a successful build, and 15 CLI upgrade tests covering machine-readable output and Doctor migration followed by Gateway readiness. Formatting, core/root test typechecks, targeted lint, schema guards, and changed-file checks passed before the final rebase. The rebased three-index scope passes its query/compatibility tests, formatting, fingerprint check, targeted lint, and independent P0–P2 review. Exact-head CI passed on a33c16a8efbe3cd9938fa2d73efbb6358ba2735f.
  • CI exposed historical fixtures that relabeled current databases while retaining indexes unavailable at those older versions, including one whose cleanup contaminated later tests. The fixture producers now construct the intended historical shape. Production guards and behavior assertions remain intact.

Synthetic in-memory SQLite 3.53.4 / Node 26.8.2 measurements against current main, 25 warm samples after five warmups:

Operation Before p50 After p50
Missing session owner, 100,000 tasks 22.483 ms 0.0011 ms
Session-count correction, 20,000 sessions / 20 exceptions 3.358 ms 0.0277 ms
Missing placement environment, 5,000 placements 0.138 ms 0.0007 ms

The two shared-state indexes added about 2.50 MB of SQLite page allocation and built in about 43 ms. Inserting 1,000 synthetic tasks in a rolled-back transaction increased from 7.18 ms to 7.81 ms. The normalized scoped task lookup was already indexed on main and stayed approximately unchanged. These are local microbenchmarks under variable host load, not end-to-end or live-Gateway latency forecasts. Query plans establish the removal of unrelated scans independently of timings.

@clawsweeper

clawsweeper Bot commented Sep 20, 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 maintainer Maintainer-authored PR labels Sep 20, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. 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 Sep 20, 2026
@clawsweeper

clawsweeper Bot commented Sep 20, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge. Reviewed September 20, 2026, 5:43 AM ET / 09:43 UTC (Revision 4).

ClawSweeper review

What this changes

Adds three SQLite indexes and reduces cleanup-query work so task ownership checks, session counting, and maintenance handle growing history more efficiently.

Merge readiness

⛔ Blocked before merge - 1 item remains

Keep open: the narrowed patch provides useful improvements still absent from main, and the current compatibility evidence addresses the earlier review concern. No actionable correctness or security findings remain.

Priority: P2
Reviewed head: a33c16a8efbe3cd9938fa2d73efbb6358ba2735f

Review scores

Measure Result What it means
Overall readiness 🐚 platinum hermit (4/6) A focused performance patch with meaningful retention and upgrade coverage, explicit cost measurements, and no actionable findings.
Proof confidence 🌊 off-meta tidepool Not applicable: The maintainer-authored PR is exempt from the external-contributor proof gate and does not materially change authority. Its reported SQLite benchmarks and owner-boundary compatibility tests support the changed queries and index installation; they are not live-Gateway latency proof.
Patch quality 🐚 platinum hermit (4/6) No actionable review findings were identified.

Verification

Check Result Evidence
Real behavior Not applicable Not applicable: The maintainer-authored PR is exempt from the external-contributor proof gate and does not materially change authority. Its reported SQLite benchmarks and owner-boundary compatibility tests support the changed queries and index installation; they are not live-Gateway latency proof.
Evidence reviewed 8 items Verified introduced scope: The raw test-merge parents are the pinned base followed by the exact reviewed head. Comparing that merge against its base confirms the introduced storage changes without attributing unrelated base-branch work to this PR.
Still necessary on main: Fetched main still selects complete terminal inference rows and hydrates terminal_json to calculate byte lengths. Its task schema also lacks the requester-session index added here; the merged identifier-normalization work does not replace these improvements.
Upgrade and reopening coverage: The new tests exercise canonical database owners with fresh, missing, and drifted indexes; compare stored rows and schema metadata; verify unchanged reopening; and check read-only admission before installation. The previous-reader case models the preceding schema by removing only these index declarations. The captured PR body reports these compatibility tests passing; this review did not execute them.
Findings None None.
Security None None.

How this fits together

OpenClaw stores task and worker records in its shared SQLite database and session records in per-agent databases. Recovery and maintenance query these records to identify ownership, count readable sessions, and retain completed-operation results.

flowchart TD
  A[Task and session history] --> B[SQLite databases]
  C[Canonical writable schema owner] --> D[Three nonunique indexes]
  D --> B
  B --> E[Ownership and session queries]
  B --> F[Scoped cleanup and byte accounting]
  E --> G[Recovery and session counts]
  F --> H[Retained results and receipts]
Loading

Before merge

  • Add data-model compatibility proof - Confirm migration or upgrade compatibility proof before merge.
Agent review details

Security

None.

PR surface

Source +32, Tests +385, Docs +11, Generated 0. Total +428 across 24 files.

View PR surface stats
Area Files Added Removed Net
Source 6 55 23 +32
Tests 16 468 83 +385
Docs 1 11 0 +11
Config 0 0 0 0
Generated 1 1 1 0
Other 0 0 0 0
Total 24 535 107 +428

Review metrics

Metric Value Why it matters
Persistent schema additions 3 nonunique indexes; 0 schema-version changes The accepted design adds derived lookup structures through existing repair owners without changing stored row formats.
Production versus test growth Production net +32 lines; tests net +385 lines Production growth supports encoding-aware byte accounting and additive indexes; most growth covers behavior and compatibility.

Stored data model

Persistent data-model change detected: database schema: src/state/openclaw-agent-schema.sql, database schema: src/state/openclaw-state-schema.sql. Confirm migration or upgrade compatibility proof before merge.

Root-cause cluster

Relationship: fixed_by_candidate
Canonical: #153533
Summary: This PR implements the accepted remaining index design; earlier merged task-selector optimizations are related but do not supersede it.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Technical review

Best possible solution:

Keep query optimization within the existing database owners, preserving stored bytes, retention decisions, and compatible reopening.

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

Yes, at source level: current main hydrates retained inference payloads for byte counting and lacks the added lookup indexes. The supplied benchmarks and regression coverage support the mechanism; this read-only review did not execute a reproduction.

Is this the best way to solve the issue?

Yes. The narrowed patch reuses canonical schema repair and preserves query semantics, while dropping expression indexes made unnecessary by merged identifier normalization.

AGENTS.md: found and applied where relevant.

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

Labels

Label justifications:

  • P2: This is a bounded database performance improvement for growing retained history, without evidence of an urgent user-facing outage.
  • 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: The maintainer-authored PR is exempt from the external-contributor proof gate and does not materially change authority. Its reported SQLite benchmarks and owner-boundary compatibility tests support the changed queries and index installation; they are not live-Gateway latency proof.

Evidence

What I checked:

  • Verified introduced scope: The raw test-merge parents are the pinned base followed by the exact reviewed head. Comparing that merge against its base confirms the introduced storage changes without attributing unrelated base-branch work to this PR. (986d3d4de8d8)
  • Still necessary on main: Fetched main still selects complete terminal inference rows and hydrates terminal_json to calculate byte lengths. Its task schema also lacks the requester-session index added here; the merged identifier-normalization work does not replace these improvements. (src/gateway/worker-environments/inference-store.ts:202, 1bbd60d9c2b2)
  • Upgrade and reopening coverage: The new tests exercise canonical database owners with fresh, missing, and drifted indexes; compare stored rows and schema metadata; verify unchanged reopening; and check read-only admission before installation. The previous-reader case models the preceding schema by removing only these index declarations. The captured PR body reports these compatibility tests passing; this review did not execute them. (src/state/sqlite-query-index-repair.test.ts:141, a33c16a8efbe)
  • Released validator compatibility: The v2026.9.5 schema validator rejects unexpected unique indexes but permits extra nonunique indexes. This independently supports the additive-index compatibility argument; it does not claim this PR shipped or that a published updater was exercised. (src/infra/sqlite-schema-contract.ts:139, ec9c1a13db89)
  • Accepted storage scope and costs: The linked design at SQLite task and maintenance index design #153533 records acceptance of the three nonunique indexes, canonical installation and repair, unchanged rows and versions, and rollback behavior. The captured PR body reports synthetic build-time, disk-allocation, and write-overhead measurements and explicitly limits their interpretation. Public docs: docs/reference/database-schemas/versioning.md. (docs/reference/database-schemas/versioning.md:37, a33c16a8efbe)
  • Retention semantics preserved: Inference pruning keeps its ordering, protected identity, age, row, and UTF-8 byte-budget rules. UTF-8 databases use octet_length; UTF-16 databases retain the existing Buffer.byteLength calculation. Tests cover all three encodings, exact replay, and avoiding payload hydration. (src/gateway/worker-environments/inference-store.ts:205, a33c16a8efbe)

Likely related people:

  • unknown: The claimed source-line change could not be verified from bounded local history. (role: source history unknown; 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 (3 earlier review cycles)
  • reviewed 2026-09-20T07:52:53.131Z sha c9bb195 :: blocked before merge. :: none
  • reviewed 2026-09-20T08:07:10.600Z sha fdc0bb2 :: blocked before merge. :: none
  • reviewed 2026-09-20T08:44:51.744Z sha bf82b91 :: blocked before merge. :: none

@steipete
steipete marked this pull request as ready for review September 20, 2026 07:55
Add compatible nonunique lookup indexes through canonical schema repair and preserve state 17 / agent 21. Scope receipt pruning by queue and avoid hydrating inference outcomes for UTF-8 byte accounting while retaining UTF-16 semantics.

Storage design: #153533. Release notes: faster task lookup, session recovery, and maintenance as retained history grows; no payload or retention changes.
@steipete
steipete force-pushed the codex/sql-query-performance branch from bf82b91 to a33c16a Compare September 20, 2026 09:35
@openclaw-barnacle openclaw-barnacle Bot added commands Command implementations agents Agent runtime and tooling labels Sep 20, 2026
@steipete
steipete merged commit f69617a into main Sep 20, 2026
227 checks passed
@steipete
steipete deleted the codex/sql-query-performance branch September 20, 2026 10:00
@steipete

Copy link
Copy Markdown
Contributor Author

Merged via squash.

github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Sep 21, 2026
…aw#153548)

* perf(sqlite): avoid retained-history scans and payload reads

Add compatible nonunique lookup indexes through canonical schema repair and preserve state 17 / agent 21. Scope receipt pruning by queue and avoid hydrating inference outcomes for UTF-8 byte accounting while retaining UTF-16 semantics.

Storage design: openclaw#153533. Release notes: faster task lookup, session recovery, and maintenance as retained history grows; no payload or retention changes.

* refactor(sqlite): project retained turn fields explicitly

* test(sqlite): keep legacy fixtures free of later indexes

* test: keep historical SQLite fixtures version accurate

* perf(sqlite): reuse normalized task identifier indexes
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling commands Command implementations docs Improvements or additions to documentation gateway Gateway runtime maintainer Maintainer-authored PR P2 Normal backlog priority with limited blast radius. 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.

1 participant