Repository navigation
perf: reduce database write amplification with bundled layouts - #174036
Conversation
|
🦞👀 Pull request received. I will update this pull request when review starts. ClawSweeper review completeClawSweeper finished reviewing this revision. The review result is being finalized. |
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings. |
|
Codex review: blocked before merge. What this changesThis PR bundles smaller indexes and WITHOUT ROWID tables into agent schema 28 and shared-state schema 26 to reduce database writes. Example: Insert a new session state head.
Review scores
ProductKind: Performance · Worth it: Yes · Fix scope: Complete Merge readiness⛔ Blocked before merge - 6 items remain Keep open: this maintainer-directed optimization has value, but the schema cutover leaves update admission, preservation verification, wrapper packaging, and historical migration coverage incomplete. Priority: P2 Before merge
Findings
Tests
Agent review detailsHow this fits togetherThe database owners admit existing stores, back up migration scope, apply transactional layout changes, and publish schema versions before session and memory writers resume. flowchart TD
A[Gateway and Doctor] --> B[Database admission owners]
B --> C[Recovery backup owner]
C --> D[Transactional migrations]
D --> E[SQLite layouts]
D --> F[PostgreSQL indexes and metadata]
E --> G[Session and memory operations]
F --> G
Technical reviewBest possible solution: Complete the schema cutover across admission, preservation, packaging, and historical migrations, then finish the existing upgrade and migration-cost gates. Do we have a high-confidence way to reproduce the issue? Source inspection and exact-head GitHub failure annotations establish the integration failures; no target code or tests were executed during this review. Is this the best way to solve the issue? The physical optimization fits the existing owners and preserves logical keys, but its schema-version integration must be completed before it is safe to land. Full review comments:
Overall correctness: patch is incorrect AGENTS.md: found and applied where relevant. Codex review notes: model internal, reasoning medium; reviewed against 35b769240bb1. Provenance checked
TestingProof path: in-process harness. SecurityNone. EvidenceWhat I checked:
Likely related people:
PR surfaceSource +195, Tests +4317, Docs +55. Total +4567 across 39 files. Added test files: 5. View PR surface stats
Review metrics
LabelsLabel changes:
Label justifications:
Rating scale6/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. WorkflowClawSweeper edits this one comment on every review. Comment Reviewed October 16, 2026, 5:04 AM ET / 09:04 UTC. |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: 8de32a14d3
ℹ️ 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".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| "schemaVersions": { | ||
| "state": 25, | ||
| "agent": 27 | ||
| "state": 26, |
There was a problem hiding this comment.
Bump the storage guide's current schema version
After this changes the shared-state schema to 26, docs/reference/database-schemas/storage-changes.md:142 still says both engines currently use schema 25. Contributors following that canonical storage-change guide can therefore design or generate the next migration from the wrong predecessor; update the guide alongside this version bump.
AGENTS.md reference: AGENTS.md:L128-L128
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: af66c877ee
ℹ️ 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".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| } | ||
| const name = quoteSqliteIdentifier(table); | ||
| const temporary = quoteSqliteIdentifier(`${table}_without_rowid_migration`); | ||
| const columns = [...readTableColumns(db, table)].map(quoteSqliteIdentifier).join(", "); |
There was a problem hiding this comment.
Exclude generated columns from the rebuild insert
When an existing session_state_heads table has a compatible generated column, the production upgrade has already admitted its schema, so readTableColumns parses the stored CREATE TABLE SQL and includes that generated column here. The resulting INSERT INTO temporary (...generated...) SELECT ... is rejected by SQLite because generated columns cannot be inserted explicitly, preventing the v25→v26 update; the direct helper test misses this because its untracked connection falls back to PRAGMA table_info, which omits generated columns. Filter generated/hidden columns from the copy list while retaining their definitions.
AGENTS.md reference: AGENTS.md:L81-L82
Useful? React with 👍 / 👎.
Consolidate the reviewed schema bundle, preserving its exact tree and integration repairs before rebasing onto current main.
06bd55f to
5b8d03b
Compare
Integrate main a3355d9 and resolve the engine import conflict from #174036. Retain both schema-version imports and the strict authority guard from the private maintenance-authority module. No unrelated repair edits. Focused proof: 107 tests across the relay inventory, wrapper closure, history imports, maintenance, storage migration and Doctor migration suites; 22 PostgreSQL tests across four direct engine/owner/port/migration suites. Targeted typechecks, type-aware lint, formatting and isolated P2 review pass. No CI dispatch or rerun.
Mirror the exact test hunk from PR #174638 so this main-CI repair does not wait for that larger performance migration change. PR #174036 intentionally raised the agent schema from 27 to 28. Use OPENCLAW_AGENT_SCHEMA_VERSION for the completed schema-26 repair instead of a stale literal. Keep the full schema-readiness check, transcript and participant preservation assertions, refusal classification, and byte preservation assertions unchanged. Validation: all 7 cases pass with Node 24.22.0 and --maxWorkers=1 (497.80s including worker preparation). Targeted tsgo, type-aware lint, formatting, diff checks, and independent P2 review pass.
…law#174036) Bundle agent schema v28 and shared-state schema v26 through the existing migration and recovery owners. Retire the redundant transcript parent index, narrow the conversation index, and rebuild memory origins and session heads WITHOUT ROWID on SQLite. PostgreSQL receives the matching index DDL and retains ordinary table layouts. Preserve the admitted data and extension columns, scoped recovery, v27 PostgreSQL rollback, and schema fingerprints. Synthetic qualification reduces append/window/origin/head WAL with unchanged warmed statement and request counts. See the PR for measurements, accepted read/write tradeoffs, migration timing, and final CI dispositions.
Mirror the exact test hunk from PR openclaw#174638 so this main-CI repair does not wait for that larger performance migration change. PR openclaw#174036 intentionally raised the agent schema from 27 to 28. Use OPENCLAW_AGENT_SCHEMA_VERSION for the completed schema-26 repair instead of a stale literal. Keep the full schema-readiness check, transcript and participant preservation assertions, refusal classification, and byte preservation assertions unchanged. Validation: all 7 cases pass with Node 24.22.0 and --maxWorkers=1 (497.80s including worker preparation). Targeted tsgo, type-aware lint, formatting, diff checks, and independent P2 review pass.
What Problem This Solves
Transcript appends, session metadata updates, memory-origin inserts and session-head inserts maintain redundant SQLite B-trees. This bundles agent schema 27 → 28 and shared-state schema 25 → 26 to reduce WAL while preserving rows, public keys, retention and query results. Both conditional table conversions qualify. Warmed SQL/request medians remain unchanged; no warmed-query saving is claimed.
Head/base: candidate
0cd4aad7d8571957558b324e868a1357c9ef7ae0, integrated maine53640f0c216461fb981fe492d975f3e1932a723. Coordinator GO conditions are satisfied: R14b #174360 merged as407c309f27dae6f2dcf4487b0dd88a73f681e6b2, and this branch is rebased onto current main including R7b389557502c7ca. Agent v28/state v26 remain free; no renumbering was needed.The R14b integration supplies the exact v27 agent recovery descriptor and changes its rollback case to exercise the real v27→v28 migration, including the conversation index, retained origins/outbox rows, sequence restoration and foreign-write refusal. R7b3's EngineConnection-based memory-origin behavior is preserved. Refreshed migration tests and PostgreSQL generation/check pass. The fresh confirmation pair passed with identical warm causal counts. CI exposed two fixture mismatches, repaired in test-only commits. The receipt suites pass 35 tests, and the PostgreSQL migration case passes under the real Gateway state owner and maintenance scope. Both CLI timeout cases pass in the bounded baseline/candidate replay; the fork timeout remains an unresolved CI-only observation. Final PostgreSQL conformance and all 25 selected static jobs pass. The CLI fork, all five selected abort-durability cases, and voice-call fixture pass the bounded replay on both baseline and candidate; their CI-only observations remain root-unresolved and are explicitly recorded below. The refreshed update cell was blocked by an inherited packaging prerequisite.
Design and recovery
Existing migration/backup/admission owners perform the cutover. SQLite index DDL:
The two rebuilt canonical tables are:
The shared SQLite helper copies explicit nongenerated columns into a replacement built from the admitted table body, then restores captured indexes/triggers under the existing transaction owner. Compatible local extensions survive where source admission permits them; optional origins retain their exact admitted columns and absent lazy origins stay absent. Same-version layout changes and unrelated data/index loss remain rejected.
PostgreSQL forward DDL matches the index changes:
WITHOUT ROWID is a PostgreSQL catalog no-op. The existing runner advances metadata and reseals the catalog fingerprint, DDL hash and server major. Generation preserves the PostgreSQL 16 minimum descriptor and agent search projection; no runtime index hint references either changed index. State v25's operator-recovery fence is preserved.
Agent backup scope:
transcript_event_identities,session_windows,memory_entry_origins,sqlite_stat1,sqlite_stat4. State scope:session_state_heads,sqlite_stat1,sqlite_stat4. The owner adds schema/contentVersion metadata; the complete Doctor runner also requires full shared-state recovery for registry/lease writes. Downgrade uses a verified backup and matching binary. Freed pages are reusable; immediate file shrinkage is not promised.No runtime security/integrity check is removed and no cache, synchronous runtime path, worker operation or SQL request is added. Touched-area T1 is 0 → 0. There are no removed-check edge cases to justify; the measured layout tradeoffs follow.
WAL and latency qualification
Three alternating synthetic pairs on one Linux host, Node 24.19.0 / SQLite 3.53.3, measured:
Origins qualify with preserved conflict/observed_at, isolation, deletion, rollback, reopen and CHECK semantics. Accepted duplicate-origin mean elapsed rises 6.466 → 7.154 µs and CPU 6.454 → 7.115 µs. One candidate arm's conflict/insert elapsed outliers are 33.514/51.233 µs; ranges are retained. Heads qualify because existing-head WAL does not regress; accepted hotspot mean elapsed rises 5.227 → 5.831 µs and CPU 4.933 → 6.666 µs. Watermarks, isolation and rollback pass; sampled layout readers improve.
All hashes/integrity checks and nine parent/three window reader plans/results pass. Index-trial append p50/p95 improves 21.771/41.238 → 17.543/32.341 µs; window UPSERT 20.458/31.449 → 18.685/26.920 µs. Readers are mixed: suffix p50/p95 +1.533/+7.664 µs, ancestor p50 +1.843 µs, latest-window p95 +0.361 µs; branch-correlation p50 improves 3.56%. This accepts a read/write tradeoff, not universal speedup.
Index trials have no-benchmark CPU-busy samples of 0.000%, 0.125%, 0.250%. Layout trials preceded those samples and have weaker elapsed-time provenance. These are native operations, not Gateway latency. The earlier full-actor −8.15% parent-index WAL result is distinct from this native −14.32% result.
Direct full-size migration
A synthetic 43,335,127,040-byte agent DB + 555,945,984-byte state DB contained 4,763,052 events/identities, 8,564 sessions, 9,342 windows, 16,674 origins and 10,663 heads. No private rows or extrapolation were used.
Measured source:
9673b71fde71d4c9942472f3dc1328603f73384f. Later catalog/admission integration makes this prior-head timing, not final-head remeasurement. Backup/rebuild/DDL bodies are unchanged; final migration/catalog proof covers integration correctness. Coordinator GO accepts reuse of this reported timing. Included rows overlap; discovery + migration is 594.963 seconds. This loaded-Mac/external-SSD observation used recently seeded cache and is not a cold-cache prediction.Versions 28/26, counts/sample hashes, layouts, indexes and recovery images passed without migration warnings. Recovery images are 784,756,736 agent bytes and 555,945,984 state bytes. Small calibration proved scoped restore preserves undeclared tables and an unrelated later cache write. Sampled migration-fixture growth peaked +1.570 GB, excluding internal state staging and verification snapshots; APFS shared extents were not measured.
Two proof-setup failures were corrected: old-schema calibration initially requested current admission, and extra postflight initially used internal snapshot staging (stopped after 11.494 GB, partial copy removed). Only postflight was repeated with external cache placement; its 43.335 GB scratch returned to zero. The successful migration was not rerun. All owned scale fixtures and scratch were deleted.
Completed SQL comparison
Three alternating shared-harness-v3 pairs compare
ed4e2160559a4a6464c92967a812a24e6725dd24→2f77fed9da80daad00f1f89476e71e82d9f6237b. Every arm passed 14 top-level turns, native child, cron, idle, compaction, same-state restart and both shutdowns. Node 24.22.0 / SQLite 3.54.0 and harness/runtime hashes were pinned; native execution/prepare errors were zero. Later heads reuse this source-bound evidence, not relabeled measurements.Each arm's causal warm mean is 72.6 SQL / 25.2 requests / 0 MAIN. Raw run-mean medians rise 75.1 → 75.6 SQL and 25.4 → 25.7 requests; pooled warm medians stay flat. Every warmed wire-operation mean matches. Window INSERT/SELECT/UPDATE remain 2/2, 2.2/2.1, 4/4 SQL/requests; identity INSERT/SELECT remain 3/3 and 2/2. All five shared read families are zero warmed. New origins are not exercised warmed; whole-workload head inserts remain 6/6. Parent-index retirement removes one cold bootstrap statement.
Causal first/restart medians stay 224/64/0 and 149/49/0. Raw first SQL rises 816 → 1013, while combined boot/connect/first is 1431 → 1432 SQL and 261 → 258 requests. Raw restart combined rises 760 → 805 SQL and 227 → 229 requests: index-status installation occurs in one base versus two candidate arms (+21 owner-median SQL), with maintenance (+3) and export/memory reads. The scheduling trigger is not proven. No all-phase or Gateway-latency non-regression claim is made; no extra pair is recommended for flat pooled warm and lower whole-workload medians.
Post-R14b confirmation pair
A fresh M,C pair compares
e53640f0c216461fb981fe492d975f3e1932a723with69a68da06612a91f3c971dd15617cbc0f3bf6c74. Both complete all 14 turns, idle, compaction, restart and shutdown; the pinned Node 24.22.0 / SQLite 3.54.0 runtime is unchanged.Causal warm means are identical: 71.8 statements / 23.6 requests / 0 MAIN. Whole-workload totals are 3969 → 3943 statements, 1035 → 1038 requests and 206 → 205 MAIN. The small raw request increase is retained; no whole-workload request reduction or latency improvement is claimed. Host load was high, so this is count evidence only.
All five shared read families were flat or lower (entry-cache-snapshot 24/14 → 23/13 statements/requests; actor-hydration, exact-entry, row-facts, and watermark unchanged), and all 14 warm causal operation rows were identical. Cold session_windows reads increased 171 → 173 and updates 89 → 90, alongside lower CREATE and transcript-identity counts; these are retained whole-run differences, not a claim of warm savings or latency improvement.
Evidence
Candidate
0cd4aad7d8571957558b324e868a1357c9ef7ae0follows the required R7b3/R14b rebase ontoe53640f0c216461fb981fe492d975f3e1932a723. Canonical PostgreSQL regeneration/check and 41 focused migration/receipt/memory tests passed before the final test-only repair. Production/schema files exactly match the measured69a68da0head, whose CI 38947992699 passed all 25 selected static jobs and security checks. Both real v27→v28→v27 PostgreSQL rollback cases passed, including foreign-write refusal.The final test repair moves the generic-receipt case to the real connection/port fixture, where an outer INSERT remains committed after an inner domain receipt rolls back. The PostgreSQL migration fixture now acquires the real Gateway state owner, enters its maintenance scope, and uses the existing maintenance lease and engine opener before ordinary reopen. These fix fixture assumptions without weakening production authority. Formatting, type-aware lint and diff checks pass. All 35 receipt tests and the focused PostgreSQL migration regression pass. Final CI 38955720571 passes all 25 selected static checks, security reviews and PostgreSQL conformance. The PostgreSQL job executes 319 passing tests, including both real v27→v28→v27 rollback cases and the migration owner regression. Its three Matrix cases also pass; their previous failures below remain historical evidence only. The aggregate gate is red from five other behavioral jobs; final attribution follows below.
Earlier CI also exposed native-session, WhatsApp and Matrix failures. The native skill-pins case matches scheduled main run 38940084041/job 117105700181 (
Runtime config is not prepared). Both WhatsApp media-diagnostic assertions and all three Matrix cases reproduce on main57c902e0f9bdfce5c72c752c2b14cc5bfc7f2718, the parent of the earlier PR CI merge. WhatsApp expects expired-reference text that its current producer intentionally omits; Matrix expects the refusal superseded by main’s fresh-root admission. The exact test names and assertion signatures match PR CI. These were observed inherited failures on the earlier run. Final CI passes the three Matrix cases; the native skill-pins case does not recur, while both WhatsApp assertions still fail. The Matrix case names areports every retained token/account root and restores matched backups into fresh namespaces,resume recovers a partially published multi-root port and blocks ordinary startup meanwhile, androllback recovers a partially published multi-root port and blocks ordinary startup meanwhile.The refreshed published-driver run 38946466179 did not execute the update cell: package integrity rejected missing
dist/windows-security-helper.exeimports from both sealed updater runtimes. The same errors were reproduced by the main packaging rule at07667dcc8f4d; all 11 relevant packaging inputs match the tested and final heads. This is an inherited prerequisite failure, routed to the main-repair owner, not a passing update test. The final lint/test-only corrections do not affect packaging or update behavior. The coordinator’s ordinary-forward-schema-migration waiver applies; the dedicated Windows-helper owner tracks the packaging prerequisite. No passing refreshed update cell is claimed.Historical proof is retained with its original source pins: CI 38919369361 passed the migration/PostgreSQL suite and 24 selected static jobs; update run 38919502985 passed all 20 stages in 596 seconds on
06bd55fbb226with published[email protected]. Neither is presented as execution of the rebased head. Previous CLI JSON and custom-schema reliability failures reproduced on their integrated main; the previous Bun observation remains root-unresolved and the watchOS failure was a runner prerequisite.The executed SDK comparison has zero added/removed entrypoints and zero added/removed/signature-changed exports, with 157 reachable-only affected exports from two schema-version declaration blocks. Current candidate and integrated base have identical SDK source, 30 inspected tooling inputs, lockfile and SDK manifest fields. The schema-contract before/after blobs and patches exactly match the measured pair. This supports reuse for the lane's unchanged semantic API delta; no fresh render or zero-diff claim is made. Executed Knip scans on integrated main and the candidate report the same three findings: production
QuotaSuspensioninsrc/config/sessions/types.ts, and full-treeobserveJsonParseandopenNewSessionPlusMenuin their test-support files; scripts has zero findings. These source/rule-matched inherited findings are routed to the main-repair owner. Two Codex review rounds are complete, with no accepted P0/P1 finding remaining.Change size against integrated main: 66 files, +5697/−602. Production: 23 files, +323/−40 (net +283); tests: 20, +1099/−97; historical schema fixtures: 2, +3678/−0; generated catalogs: 10, +493/−451; tooling: 5, +45/−10; docs: 5, +57/−2; package metadata: 1, +2/−2. The frozen historical schemas are recovery inputs, not new runtime logic.
Coordinator GO covers both qualified table conversions, the disclosed tradeoffs and reuse of the reported full-size timing. R14b is merged and the required current-main integration is complete.
Final CI disposition
Final head
0cd4aad7d8571957558b324e868a1357c9ef7ae0, CI run 38955720571, has all 25 selected static gates and security reviews passing. PostgreSQL conformance executes 319 passing tests, including the agent migration, both real v27→v28→v27 rollback variants, and all three Matrix cases. Knip retains only the three exact-base findings described above. The aggregate CI gate remains red; it is not being relabeled green.Two failed families have direct main evidence. The returned-cleanup plugin resource timeout (120000 ms at line 409, followed by six cleanup failures) matches scheduled main
d401ad3409e4d0f19a7740568cd7a5536fd9d30d, run 38955395215/job 117157270785. Both WhatsApp expired-reference diagnostic assertions reproduce on exact main57c902e0f9bdfce5c72c752c2b14cc5bfc7f2718as recorded above.Three CI-only observations remain root-unresolved, not established inherited or fixed: the Bun CLI fork deadlock guard (
keeps a concurrent durable rebind when a stale fork reports its successor), five Bun abort-durability variants refusing access during offline maintenance, and the Node voice-call fixture observing zero transcript timers instead of one. A bounded selected-case replay on integrated basee53640f0c216461fb981fe492d975f3e1932a723and final candidate passes all seven cases on both sides (1 CLI, 5 abort, 1 voice); the additional plugin cleanup case also passes both replays. No timeout, assertion, or product behavior was weakened. These replays did not reproduce a candidate-only regression and do not erase the CI failures. They are routed to their existing owners for follow-up.Landing uses the explicitly authorized RELAXED LANDING v4 / head-pinned REST squash route after the required bounded attribution, with no proven product regression, no owned static failure, and no accepted P0/P1 review finding. No further review or CI rerun is requested.