Skip to content

feat(database): PostgreSQL migrations, capability admission and exact schema-drift checks - #172265

Merged
steipete merged 1 commit into
mainfrom
pgprep/r2-engine-migrations
Oct 14, 2026
Merged

steipete merged 1 commit into
mainfrom
pgprep/r2-engine-migrations

Conversation

@steipete

@steipete steipete commented Oct 14, 2026 •

Copy link
Copy Markdown
Contributor

What Problem This Solves

PostgreSQL stores currently reject every schema-version change while admitting changes to default values, CHECK expressions, partial-index predicates, and trigger bodies.

User Impact

PostgreSQL stores can run owner-supplied forward migrations atomically, and startup refuses incompatible versions, PostgreSQL older than 16, non-UTF8 server/client encoding, or exact schema drift with recovery guidance. Fresh stores still bootstrap at the current version. This supplies the migration mechanism for future versions; no existing store receives a new application-schema version here.

Why This Change Was Made

The database engine owns migration custody and admission. Each migration supplies the generated source and destination definitions, including fragment descriptors. The existing advisory-locked writer transaction covers the whole sequence. Each destination is compared with its generated definition before sealing, and committed admission facts publish only after commit.

Bootstrap, migrations, and successful lazy-fragment installation seal PostgreSQL's own catalog deparse with a fingerprint, generated-DDL hash, and server major. Startup compares one catalog snapshot with that seal. A major-version change uses a temporary namespace to compare both definitions on the new server before updating the seal; the same verification seals older port metadata. Ordinary startup performs no scratch DDL. Installed-table deletion now refuses as drift; never-created lazy fragments still install through their existing owner.

The config help and database documentation now describe supported-family offline ports. State bootstrap/preflight and port/backup/generator implementations are untouched.

Evidence

  • Local disposable PostgreSQL 17.11: all 11 new admission/migration cases and 22 existing workboard, state, physical-facts, opener, and wrapper-closure tests pass. The two-step migration test proves rollback of data, DDL, and metadata, advisory-lock custody, publication after commit, and a combined server-major/schema upgrade. It also refuses a successful SQL migration that produces the wrong default and proves complete rollback.
  • All four baseline probes were wrongly admitted before the change; default, CHECK, partial-index, and trigger-body changes now refuse. Unchanged stores admit with one catalog read; simulated server-major changes recompute successfully, and scratch namespaces are removed on success and refusal.
  • SQLite: all 316 raw operation/SQL pairs match byte-for-byte for workboard and shared-state cold/warm opens with a fixed monotonic clock. SQL is not normalized. The real-clock comparison differs only in a deadline-derived busy-timeout value.
  • Format, type-aware lint, core and focused-test typechecks, generated config baseline, and PostgreSQL generation verification pass; the generator's 18 unit tests pass. The dialect ratchet and wrapper inventory/closure pass. One Codex autoreview identified missing destination validation; that finding is fixed and covered by a failing-before/passing-after regression. The worker ratchet passes: live T1 calls remain 223 and compatibility calls remain 12.
  • Net production growth: 307 lines (limit 500).

Component costs on the loaded local host, medians of three runs using the runtime's synchronous_commit=off setting:

Schema Tables Catalog query + JSON parse + fingerprint Scratch create/apply/deparse/compare/drop
Workboard 18 9.8 ms 1.014 s
Shared state, eager 100 52.0 ms 8.898 s
Shared state, all fragments 134 439.9 ms 9.085 s

These component measurements use the same SQL and fingerprint implementation through a local PostgreSQL client. Host contention was substantial: the all-fragment catalog samples ranged from 98.6 to 918.6 ms. A separate actual-bridge admission test measured 25.4 ms for its catalog query and 422.0 ms for the complete small-fixture major-version reopen. No timing threshold is asserted.

The PostgreSQL conformance CI job passed at head 6d9cd1ba375c4c190f7ec835cd96190525b6c16a: 444 tests passed across the three test projects, with 38 other cases skipped. All 11 R2 admission/migration cases executed and passed, including the four drift probes. Its small-fixture actual-bridge sample measured 9.95 ms for the catalog query and 116.88 ms for complete major-version reopen.

Landing CI on the rebased head

Rebased mechanically onto 1a86e3e08fe82952dfd7a03372094655dda5d883; final head is 1b1a6e7ea70989d76754cd2cbc40b1c9d9fae874. PostgreSQL conformance passed 444 tests, including all 11 new acceptance cases. No production or test edits were added during landing.

The sole failed test shard contains two failures qualified under the operator-authorized causal-path exception:

Case Failure Qualification
Managed-image fresh artifact download SessionMutationFactsUnavailableError Uses unchanged SQLite session/fact and artifact-lookup paths. R2's modified PostgreSQL admission branch is not selected; the SQLite branch is unchanged.
Managed npm-pack mutation authority 120-second timeout Uses unchanged npm preparation, installer, registry fixture, and filesystem-authority paths, with no PostgreSQL configuration.

The automatic scheduled-main table reports unknown because shard names differ; this exception does not claim matching-main failure reproduction. The native admin evidence records the exact tested merge, inspected sources, full logs, and passing PostgreSQL proof. The aggregate gate fails only because of that shard. No cancellations occurred, and no shutdown-test watch-item failure was observed. The only landing push was the conflict-free rebase.

Landed as e3b8a282764d3eebcb331f1eabccf13e459a2232 at 2026-10-14T18:09:15Z using the operator-authorized head-pinned REST squash fallback after native main-requalification exceeded ten minutes. Native review, preparation, and merge verification completed; live writer/admin authority, review state, security/dependency checks, and the exact PR head were revalidated before the REST request. The only fix push was the mechanical rebase.

@clawsweeper

clawsweeper Bot commented Oct 14, 2026

Copy link
Copy Markdown
Contributor

🦞👀
ClawSweeper picked this up.

Pull request received. I will update this pull request when review starts.

@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 14, 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-14T16:36:24.529311Z 1b1a6e7 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 scripts Repository scripts size: L labels Oct 14, 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: 6d9cd1ba37

ℹ️ 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".

SELECT catalog::text, to_jsonb(meta)::text AS metadata FROM captured
CROSS JOIN ${quote(namespace)}.openclaw_schema_meta meta WHERE meta.store = ?`,
[store],
).rows[0];

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 Require exactly one schema-metadata row

When openclaw_schema_meta has lost its primary key and contains duplicate rows for the store, selecting .rows[0] silently trusts an arbitrary identity/version, and a subsequent migration updates every duplicate. The previous admission path explicitly required result.rows.length === 1, while the new fingerprint excludes the metadata table entirely, so this corruption is no longer rejected; retain the cardinality check before parsing the row.

AGENTS.md reference: AGENTS.md:L106-L106

Useful? React with 👍 / 👎.

UNION ALL SELECT r.relname, 'indexDefinition', jsonb_build_object('name', c.relname, 'definition', pg_catalog.pg_get_indexdef(i.indexrelid), 'valid', i.indisvalid) FROM relations r JOIN pg_catalog.pg_index i ON i.indrelid = r.oid JOIN pg_catalog.pg_class c ON c.oid = i.indexrelid`
UNION ALL SELECT r.relname, 'indexDefinition', jsonb_build_object('name', c.relname, 'definition', pg_catalog.pg_get_indexdef(i.indexrelid), 'valid', i.indisvalid) FROM relations r JOIN pg_catalog.pg_index i ON i.indrelid = r.oid JOIN pg_catalog.pg_class c ON c.oid = i.indexrelid
UNION ALL SELECT r.relname, 'columnDefinition', jsonb_build_object('name', a.attname, 'default', pg_catalog.pg_get_expr(d.adbin, d.adrelid), 'generated', a.attgenerated, 'identity', a.attidentity, 'collation', a.attcollation::regcollation::text) FROM relations r JOIN pg_catalog.pg_attribute a ON a.attrelid = r.oid LEFT JOIN pg_catalog.pg_attrdef d ON d.adrelid = r.oid AND d.adnum = a.attnum WHERE a.attnum > 0 AND NOT a.attisdropped
UNION ALL SELECT r.relname, 'triggerDefinition', jsonb_build_object('name', t.tgname, 'definition', pg_catalog.pg_get_triggerdef(t.oid), 'enabled', t.tgenabled, 'function', pg_catalog.pg_get_functiondef(t.tgfoid)) FROM relations r JOIN pg_catalog.pg_trigger t ON t.tgrelid = r.oid WHERE NOT t.tgisinternal

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 Capture standalone functions in the schema fingerprint

For a plugin StoreSchema whose generated PostgreSQL DDL contains a standalone function—for example, a helper referenced by a CHECK constraint—this catalog query records function bodies only through pg_trigger. Replacing the standalone function body therefore leaves the live fingerprint unchanged, while the DDL hash only verifies the build's expected text, so startup and migration source verification admit behavior-changing drift. Enumerate namespace-owned routines independently rather than only trigger functions.

Useful? React with 👍 / 👎.

Validate PostgreSQL version and UTF8 capabilities at admission. Verify owner-supplied migration destinations before recording catalog fingerprints, preserve commit-only admission publication, and retain lazy schema fragments.
@steipete
steipete force-pushed the pgprep/r2-engine-migrations branch from 6d9cd1b to 1b1a6e7 Compare October 14, 2026 16:32

@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: 1b1a6e7ea7

ℹ️ 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".

? `UNION ALL SELECT r.relname, 'constraintDefinition', jsonb_build_object('name', c.conname, 'definition', pg_catalog.pg_get_constraintdef(c.oid)) FROM relations r JOIN pg_catalog.pg_constraint c ON c.conrelid = r.oid
UNION ALL SELECT r.relname, 'indexDefinition', jsonb_build_object('name', c.relname, 'definition', pg_catalog.pg_get_indexdef(i.indexrelid), 'valid', i.indisvalid) FROM relations r JOIN pg_catalog.pg_index i ON i.indrelid = r.oid JOIN pg_catalog.pg_class c ON c.oid = i.indexrelid`
UNION ALL SELECT r.relname, 'indexDefinition', jsonb_build_object('name', c.relname, 'definition', pg_catalog.pg_get_indexdef(i.indexrelid), 'valid', i.indisvalid) FROM relations r JOIN pg_catalog.pg_index i ON i.indrelid = r.oid JOIN pg_catalog.pg_class c ON c.oid = i.indexrelid
UNION ALL SELECT r.relname, 'columnDefinition', jsonb_build_object('name', a.attname, 'default', pg_catalog.pg_get_expr(d.adbin, d.adrelid), 'generated', a.attgenerated, 'identity', a.attidentity, 'collation', a.attcollation::regcollation::text) FROM relations r JOIN pg_catalog.pg_attribute a ON a.attrelid = r.oid LEFT JOIN pg_catalog.pg_attrdef d ON d.adrelid = r.oid AND d.adnum = a.attnum WHERE a.attnum > 0 AND NOT a.attisdropped

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 Include identity sequence options in the fingerprint

When a live schema contains generated identity columns, as the shared-state schema does, changing an identity sequence with ALTER TABLE ... ALTER COLUMN ... SET INCREMENT BY ... alters ID allocation without changing the captured default or a.attidentity value. The fingerprint therefore remains unchanged and startup admits schema drift that can change generated IDs; capture the owned identity sequence's stable configuration, such as increment, bounds, and cycle behavior, while excluding its mutable current value.

Useful? React with 👍 / 👎.

@steipete
steipete merged commit e3b8a28 into main Oct 14, 2026
184 of 187 checks passed
@steipete
steipete deleted the pgprep/r2-engine-migrations branch October 14, 2026 18:09
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Oct 15, 2026
… schema-drift checks (openclaw#172265)

Add atomic PostgreSQL forward migrations, reject unsupported version/encoding capabilities, and admit only exact schema facts.

Final-head PostgreSQL CI passed 444 tests, including all 11 acceptance cases. SQLite conformance preserved 316 byte-identical operations.

Land under the operator-authorized causal-path exception for failures in unchanged SQLite session-fact and managed npm installation paths. Full qualification and evidence: openclaw#172265
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 scripts Repository scripts size: L

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant