Skip to content

perf: reduce database write amplification with bundled layouts - #174036

Merged
steipete merged 5 commits into
mainfrom
dbasync/schemabundle
Oct 16, 2026
Merged

steipete merged 5 commits into
mainfrom
dbasync/schemabundle

Conversation

@steipete

@steipete steipete commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

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 main e53640f0c216461fb981fe492d975f3e1932a723. Coordinator GO conditions are satisfied: R14b #174360 merged as 407c309f27dae6f2dcf4487b0dd88a73f681e6b2, and this branch is rebased onto current main including R7b3 89557502c7ca. 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:

DROP INDEX IF EXISTS idx_agent_transcript_event_parent;
DROP INDEX IF EXISTS idx_agent_session_windows_conversation;
CREATE INDEX idx_agent_session_windows_conversation
  ON session_windows(primary_conversation_id)
  WHERE primary_conversation_id IS NOT NULL;

The two rebuilt canonical tables are:

CREATE TABLE memory_entry_origins (
  entry_key TEXT NOT NULL,
  agent_id TEXT NOT NULL,
  session_id TEXT NOT NULL,
  session_key TEXT,
  origin_class TEXT NOT NULL CHECK (origin_class IN ('owner', 'agent', 'untrusted', 'system')),
  observed_at INTEGER NOT NULL,
  PRIMARY KEY (entry_key, agent_id, session_id)
) STRICT, WITHOUT ROWID;

CREATE TABLE session_state_heads (
  session_key TEXT NOT NULL,
  agent_id TEXT NOT NULL,
  last_sequence INTEGER NOT NULL,
  pruned_max_sequence INTEGER NOT NULL DEFAULT 0,
  updated_at INTEGER NOT NULL,
  PRIMARY KEY (session_key, agent_id)
) STRICT, WITHOUT ROWID;

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:

DROP INDEX "idx_agent_transcript_event_parent";
DROP INDEX "idx_agent_session_windows_conversation";
CREATE INDEX "idx_agent_session_windows_conversation"
  ON "session_windows" (("primary_conversation_id") ASC NULLS FIRST)
  WHERE "primary_conversation_id" IS NOT NULL;

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:

Operation Base WAL B/op Candidate WAL B/op Change
Event + identity append 41179.453 35280.987 −14.32%
Window metadata UPSERT 25101.180 21290.180 −15.18%
New memory origin 12055.152 8792.112 −27.07%
Selected-origin delete 9195.872 4239.512 −53.90%
New session head 9179.392 5092.352 −44.52%
Existing hotspot-head UPSERT 4120.032 4120.032 unchanged
Existing distributed-head UPSERT 4144.752 4120.032 −0.60%

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.

Phase Seconds
Doctor discovery/preflight 17.449
Complete owning migration 577.514
Source agent integrity, included above 491.776
Scoped recovery-image build, included above 43.178
Shared-state snapshot child, included above 6.170
Index DDL, included above 2.216
Origins / heads rebuild, included above 0.068 / 0.011
Final agent FK check, included above 9.206
Separate strict destination admission 38.598

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.

Metric, median [min–max] Base Candidate
Warm causal SQL, 30 pooled turns 72 [72–78] 72 [72–78]
Warm causal requests 25 [25–27] 25 [25–27]
Warm causal MAIN 0 [0–0] 0 [0–0]
Warm raw SQL 72 [72–99] 72 [72–106]
Warm raw requests 25 [25–29] 25 [25–32]
Warm raw MAIN 0 [0–9] 0 [0–9]
Whole-workload SQL 4138 [4103–4140] 4137 [4105–4146]
Whole-workload requests 1079 [1074–1083] 1077 [1075–1080]
Whole-workload MAIN 185 [185–185] 185 [185–185]

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 e53640f0c216461fb981fe492d975f3e1932a723 with 69a68da06612a91f3c971dd15617cbc0f3bf6c74. Both complete all 14 turns, idle, compaction, restart and shutdown; the pinned Node 24.22.0 / SQLite 3.54.0 runtime is unchanged.

Warm metric, median [min–max], 10 turns per arm Base Candidate
Causal all-thread statements 71.5 [70–76] 71.5 [70–76]
Causal requests 23.5 [23–25] 23.5 [23–25]
Causal MAIN statements 0 [0–0] 0 [0–0]
Raw all-thread statements 73 [70–95] 72.5 [70–95]
Raw requests 24 [23–26] 23.5 [23–26]
Raw MAIN statements 0 [0–4] 0 [0–4]

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 0cd4aad7d8571957558b324e868a1357c9ef7ae0 follows the required R7b3/R14b rebase onto e53640f0c216461fb981fe492d975f3e1932a723. Canonical PostgreSQL regeneration/check and 41 focused migration/receipt/memory tests passed before the final test-only repair. Production/schema files exactly match the measured 69a68da0 head, 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 main 57c902e0f9bdfce5c72c752c2b14cc5bfc7f2718, 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 are ports 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, and rollback 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.exe imports from both sealed updater runtimes. The same errors were reproduced by the main packaging rule at 07667dcc8f4d; 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 06bd55fbb226 with 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 QuotaSuspension in src/config/sessions/types.ts, and full-tree observeJsonParse and openNewSessionPlusMenu in 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 main 57c902e0f9bdfce5c72c752c2b14cc5bfc7f2718 as 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 base e53640f0c216461fb981fe492d975f3e1932a723 and 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.

@clawsweeper

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

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 16, 2026 •

Copy link
Copy Markdown
Contributor

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-16T19:36:02.762044Z 0cd4aad New commits
ℹ️ 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" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation extensions: memory-core Extension: memory-core size: XL labels Oct 16, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 automation 🚨 May affect CI, automerge, proof capture, label sync, or maintainer automation. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. 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. labels Oct 16, 2026
@clawsweeper

clawsweeper Bot commented Oct 16, 2026

Copy link
Copy Markdown
Contributor

Codex review: blocked before merge.

What this changes

This 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.

  • Before: The PR reports 9,179.39 WAL bytes per operation.
  • After: The PR reports 5,092.35 WAL bytes per operation, with the same logical key and sequence values.

Review scores

Measure Result What it means
Overall readiness 🦪 silver shellfish (2/6) Useful, owner-directed optimization with relevant primitive evidence, but incomplete schema integration and outstanding upgrade compatibility validation.
Proof confidence 🦪 silver shellfish (2/6) Real behavior proof is not required for maintainer- or bot-authored pull requests.
Patch quality 🦪 silver shellfish (2/6) 5 actionable review findings remain.

Product

Kind: Performance · Worth it: Yes · Fix scope: Complete
User problem: Routine transcript, session, memory-origin, and session-head writes maintain redundant SQLite trees and generate avoidable WAL traffic.
Reason: The maintainer-authored direction has concrete primitive measurements and reuses the migration owners without adding configuration or changing retention.

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
Reviewed head: 79c685bdc30ea898d34c80af8b20ba88bbd2097a

Before merge

  • Update package schema declarations with the version bumps (P1) - The runtime now writes agent schema 28 and state schema 26, but package.json still declares agent 27 and state 25. Candidate update admission reads those package declarations and rejects databases already opened by this build as newer than the target supports. Exact-head update-admission and package-alignment tests show this failure. Update both package declarations alongside the runtime constants.
  • Extend preservation verification for the new layouts (P2) - The shipped database verify-preservation path calls captureOpenClawMigrationWitness, whose capture and parser allowlists both stop at agent schema 27. Every schema-28 candidate therefore throws Unsupported agent migration witness schema: 28, as exact-head CI confirms. Extend the witness contract for this transition, including normalization of the deliberately changed indexes and origins rowid layout; changing only the version allowlists would still leave incompatible schema and row hashes.
  • Include the migration modules in the wrapper inventory (P2) - This import and the state maintenance import add three runtime dependencies absent from scripts/pr-lib/wrapper-components.txt: openclaw-agent-write-layout-migration.ts, openclaw-state-db-schema-v26-layout.ts, and sqlite-table-layout-migration.ts. The trusted wrapper archives only inventoried source, so its materialized worker dependency graph is incomplete. The exact-head runtime-closure check identifies precisely these missing modules. Regenerate the inventory with all three included.
  • Keep the v14 admission projection on its historical layout (P2) - AGENT_V14_CORE_SCHEMA_SQL is independently derived from the current canonical SQL and does not apply withLegacyAgentWriteLayout. Changing memory_entry_origins here makes v14 preflight require WITHOUT ROWID before the v28 conversion can run. A legacy rowid origins table is rejected for table-option and autoindex differences; the frozen-input v14 migration test fails at repairAndAssertAgentSchemaGroup. Apply the historical layout transform to this admission projection rather than requiring the destination layout during source validation.
  • Restore pre-28 layouts in historical fixture builders (P2) - The historical admission transform now correctly expects old origins storage and the old conversation index, but restoreEmptyV21StorageForHistoricalFixture leaves both current layouts untouched before callers relabel the database as v17. Consequently participant and outbox migration tests fail during source admission instead of exercising their migration or injected rollback. Restore these layouts in the historical fixture builder, or seed frozen historical inputs, without weakening production admission.
  • Add data-model compatibility proof - The review found that existing stored data may not work after upgrade. Show that existing data still loads and works with this change.

Findings

  • [P1] Update package schema declarations with the version bumps — src/state/openclaw-agent-db-contract.ts:9-10
  • [P2] Extend preservation verification for the new layouts — src/state/openclaw-agent-db-contract.ts:9-10
  • [P2] Include the migration modules in the wrapper inventory — src/state/openclaw-agent-db-schema.ts:117

Tests

  • Missing end-to-end proof: Provide the pending shipped-CLI fresh-install and latest-stable upgrade/restore evidence with settings and retained data intact; the complete large-store migration measurement is also explicitly pending.
Agent review details

How this fits together

The 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
Loading

Technical review

Best 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:

  • [P1] Update package schema declarations with the version bumps — src/state/openclaw-agent-db-contract.ts:9-10
    The runtime now writes agent schema 28 and state schema 26, but package.json still declares agent 27 and state 25. Candidate update admission reads those package declarations and rejects databases already opened by this build as newer than the target supports. Exact-head update-admission and package-alignment tests show this failure. Update both package declarations alongside the runtime constants.
    Confidence: 1
  • [P2] Extend preservation verification for the new layouts — src/state/openclaw-agent-db-contract.ts:9-10
    The shipped database verify-preservation path calls captureOpenClawMigrationWitness, whose capture and parser allowlists both stop at agent schema 27. Every schema-28 candidate therefore throws Unsupported agent migration witness schema: 28, as exact-head CI confirms. Extend the witness contract for this transition, including normalization of the deliberately changed indexes and origins rowid layout; changing only the version allowlists would still leave incompatible schema and row hashes.
    Confidence: 1
  • [P2] Include the migration modules in the wrapper inventory — src/state/openclaw-agent-db-schema.ts:117
    This import and the state maintenance import add three runtime dependencies absent from scripts/pr-lib/wrapper-components.txt: openclaw-agent-write-layout-migration.ts, openclaw-state-db-schema-v26-layout.ts, and sqlite-table-layout-migration.ts. The trusted wrapper archives only inventoried source, so its materialized worker dependency graph is incomplete. The exact-head runtime-closure check identifies precisely these missing modules. Regenerate the inventory with all three included.
    Confidence: 0.99
  • [P2] Keep the v14 admission projection on its historical layout — src/state/openclaw-agent-schema.sql:700
    AGENT_V14_CORE_SCHEMA_SQL is independently derived from the current canonical SQL and does not apply withLegacyAgentWriteLayout. Changing memory_entry_origins here makes v14 preflight require WITHOUT ROWID before the v28 conversion can run. A legacy rowid origins table is rejected for table-option and autoindex differences; the frozen-input v14 migration test fails at repairAndAssertAgentSchemaGroup. Apply the historical layout transform to this admission projection rather than requiring the destination layout during source validation.
    Confidence: 0.97
  • [P2] Restore pre-28 layouts in historical fixture builders — src/state/openclaw-agent-db-schema-helpers.ts:85-88
    The historical admission transform now correctly expects old origins storage and the old conversation index, but restoreEmptyV21StorageForHistoricalFixture leaves both current layouts untouched before callers relabel the database as v17. Consequently participant and outbox migration tests fail during source admission instead of exercising their migration or injected rollback. Restore these layouts in the historical fixture builder, or seed frozen historical inputs, without weakening production admission.
    Confidence: 0.99

Overall correctness: patch is incorrect
Overall confidence: 0.98

AGENTS.md: found and applied where relevant.

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

Provenance checked

Testing

Proof path: in-process harness.

Security

None.

Evidence

What I checked:

Likely related people:

  • Peter Steinberger: Raw commit 2bb79d1 adds src/state/openclaw-state-schema.sql:128 relative to its recorded parents. This identifies author metadata, not feature responsibility or a PR merger. (role: source-line author; confidence: high; commits: 2bb79d10fd65; files: src/state/openclaw-state-schema.sql)

PR surface

Source +195, Tests +4317, Docs +55. Total +4567 across 39 files. Added test files: 5.

View PR surface stats
Area Files Added Removed Net
Source 20 570 375 +195
Tests 13 4318 1 +4317
Docs 6 58 3 +55
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 39 4946 379 +4567

Review metrics

Metric Value Why it matters
Schema version changes Agent 27 → 28; shared state 25 → 26 Both stores gain forward-only upgrade boundaries, making package declarations and preservation verification part of the required cutover.

Labels

Label changes:

  • add P2: This is a useful storage-performance improvement with pre-merge integration defects, rather than an established urgent production incident.
  • add merge-risk: 🚨 compatibility: The new schema versions exceed the package's declared support, and the preservation verifier cannot inspect the destination agent schema.
  • add merge-risk: 🚨 automation: New runtime imports are absent from the trusted PR wrapper source inventory, breaking its closure check and materialized execution path.
  • add rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🦪 silver shellfish.
  • add status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

Label justifications:

  • P2: This is a useful storage-performance improvement with pre-merge integration defects, rather than an established urgent production incident.
  • merge-risk: 🚨 compatibility: The new schema versions exceed the package's declared support, and the preservation verifier cannot inspect the destination agent schema.
  • merge-risk: 🚨 automation: New runtime imports are absent from the trusted PR wrapper source inventory, breaking its closure check and materialized execution path.
  • rating: 🦪 silver shellfish: Overall readiness is 🦪 silver shellfish; proof is 🦪 silver shellfish and patch quality is 🦪 silver shellfish.
  • status: ⏳ waiting on author: ClawSweeper has contributor-facing work open and is waiting for author action.

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 execution lanes are retired.

Reviewed October 16, 2026, 5:04 AM ET / 09:04 UTC.

@openclaw-barnacle openclaw-barnacle Bot added channel: voice-call Channel integration: voice-call scripts Repository scripts commands Command implementations labels Oct 16, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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".

Comment thread package.json
"schemaVersions": {
"state": 25,
"agent": 27
"state": 26,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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 👍 / 👎.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 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(", ");

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P2 Badge 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.
@steipete
steipete force-pushed the dbasync/schemabundle branch from 06bd55f to 5b8d03b Compare October 16, 2026 18:19
@steipete
steipete merged commit bcf9b16 into main Oct 16, 2026
248 of 256 checks passed
@steipete
steipete deleted the dbasync/schemabundle branch October 16, 2026 20:12
steipete added a commit that referenced this pull request Oct 16, 2026
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.
steipete added a commit that referenced this pull request Oct 16, 2026
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.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 17, 2026
…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.
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 17, 2026
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.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

channel: voice-call Channel integration: voice-call commands Command implementations docs Improvements or additions to documentation extensions: memory-core Extension: memory-core merge-risk: 🚨 automation 🚨 May affect CI, automerge, proof capture, label sync, or maintainer automation. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. P2 Normal backlog priority with limited blast radius. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. scripts Repository scripts size: XL 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