Skip to content
This repository was archived by the owner on Nov 25, 2026. It is now read-only.

refactor(postgres): schema-node tree restructure — database→namespace→table→policy diff tree - #894

Merged
wmadden merged 61 commits into
mainfrom
slice/schema-node-tree-restructure
Jul 6, 2026
Merged

wmadden merged 61 commits into
mainfrom
slice/schema-node-tree-restructure

Conversation

@wmadden-electric

@wmadden-electric wmadden-electric commented Jun 30, 2026 •

Copy link
Copy Markdown
Contributor

What this delivers

Retires the conflated PostgresSchemaIR (a diff-tree node, a Postgres schema, and the tree root at once) for a single-purpose database → namespace → table → policy schema-node tree, and — through three rounds of review — restructures schema diffing and db verify/plan around it. Foundation for slice 3 (@@rls, managed/external grading, policy rename).

The architecture (as landed)

Authoritative design: design-diff-and-verify.md. Four actors, cleanly separated:

interface SchemaDiffer { diff(contract, actual): SchemaDiff }     // SPI on the target

class SchemaDiff<TNode extends DiffableNode = DiffableNode> {     // the differ's whole result
  readonly issues: readonly SchemaIssue[]                         // legacy relational differ
  readonly schemaDiffIssues: readonly SchemaDiffIssue<TNode>[]    // generic node differ — carries its node
  filter(keep: (issue) => boolean): SchemaDiff<TNode>
}
  • The differ is dumb — one contract + the actual schema in, node-typed issues out (Postgres: SchemaDiff<SqlSchemaDiffNode>; the planner builds ops from the typed nodes, no casts). Internals private.
  • The contract-space aggregate is passive data — it answers ownership (declaresEntity / declaringSpaces); it diffs, verifies, and classifies nothing.
  • The orchestration owns the verbs — it runs the differ per contract space and drives both consumers.
  • Verify presents two distinct pieces of information: (1) per contract space, is the contract satisfied — the space's declared elements, pass/fail by missing/mismatch; (2) which live schema elements are unclaimed by any contract — a standalone list, reported once. An unclaimed element is never forced into a contract's structure (and is no longer duplicated once per space). Strict fails on unclaimed; lenient reports it.
  • The planner interprets nothing about spaces — the orchestration injects a blind keepDiffIssue predicate (built over the passive aggregate); the planner applies it verbatim before op-building. No schema pruning, no "other spaces' names", no post-scoping — scope-schema-result, entitiesOwnedByOtherSpaces, and the set-subtraction helper are deleted.
  • Node typology: five …SchemaNode classes with defined nodeKinds; static is/assert guards (no instanceof, no node-constructing ensure()); isEqualTo is identity; the vocabulary is contract space throughout the aggregate.

Review response

  • Round 1 (17 comments): the diff became a required target-descriptor operation; relational diffing relocated out of the verify module; nodeKind guards.
  • Round 2 (~45 comments, units V1–V5): SchemaDiffer SPI + SchemaDiff result; node-guard consistency; file dedup (one diff module; diff-SPI types out of the catch-all types.ts); planner cleanups; transient IDs removed.
  • Round 3 (12 comments, units R1–R4): node-typed issues (5e3673318); the two-part verify (9e2e80f0f + 8c3d4a10b + 9309fd00d); the plan collapse deleting the cross-space plumbing (14f5b7a73); the contract-space rename retiring "member" and "schema result" (9d56e8eba).
  • Round 4 (5 comments, unit R5): the expectation-failure reason became a declared field — reason: ExpectationFailureReason ('not-expected' | 'not-found' | 'not-equal') on both issue types and grafted verify nodes, stamped at the producers — so the framework filters structurally, with zero family-invented strings (32ad8f571). Legacy outcome stays alongside until the slice-2.5 issue-type merge. The plan(start, end) planner reshape is scheduled as slice 2.5 (one-differ-two-ir-planner) in the project plan.

Confirmed non-duplicates from review: contract-to-postgres-database-schema-node builds the Postgres tree atop the shared per-namespace table conversion (contractToSchemaIR's flat map is SQLite-only); verify-postgres-namespaces is live (its missing_schema issues drive multi-schema CREATE SCHEMA planning).

Verification

Planner ops byte-identical throughout (fixtures:check clean at every unit); contract infer unchanged; the runner's post-apply verify and single-space family verify preserved; multi-space guards green (cross-namespace-fk, supabase classification.e2e + cross-contract-fk, multi-namespace-runtime). lint:deps clean; lint:casts net −11. The deliberate output change is confined to db verify's unclaimed-element reporting (two-part model above). CI on the merge ref arbitrates the full suites.

Follow-ons (out of scope)

  • Relational port — merge the two issue types into one node-typed generic differ; settles SchemaIssue node-typing and lifts root/counts off the relational walk.
  • Multi-namespace verify-tree shaping — the family verify retains only the first namespace's tree while counts sum all namespaces (pre-existing).
  • TML-2958 — PSL-inference tree-walk.
  • TML-2936 — full annotations.pg retirement.

🤖 Generated with Claude Code

wmadden-electric and others added 18 commits June 29, 2026 14:49
Reshape the forward slice sequence and shape slice 2: replace the
conflated PostgresSchemaIR with a single-purpose schema-node tree
(database → namespace → table → policy; roles on the root), split the
diff nodes from the Contract-IR entities, make introspect return the
tree (a node; consumers ensure + walk), and move database→PSL inference
onto the Postgres target. Behaviour-neutral.

spec.md is the prescriptive build (R1–R9, 7 units, alternatives);
design.md is the durable architecture reference.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
… schema-diff nodes

Slice 2 (schema-node-tree-restructure), unit 1 of 7.

PostgresRlsPolicy / PostgresRole were doing two jobs: authored,
serialized Contract-IR entities AND diff-tree leaves. Split them:

- The entities keep their names, lose DiffableNode (id/children/
  isEqualTo gone), and move out of schema-ir/ to core/ alongside the
  other contract-IR / entity-kind definitions.
- New PostgresPolicySchemaNode / PostgresRoleSchemaNode in schema-ir/
  are the diff-tree leaves (DiffableNode, static is() guards).

Tables already split this way (StorageTable vs PostgresTableIR).

Intermediate unit: the differ/planner still reference the entity as a
node and break here; they are rewired in unit 6. The branch goes green
across the unit sequence; the new-node tests pass (37/37).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Slice 2 (schema-node-tree-restructure), unit 2 of 7.

Mechanical rename of the table diff-node to the …SchemaNode scheme, and
point its policy children at the Unit-1 node type:

- PostgresTableIR → PostgresTableSchemaNode (file, class, Input).
- Free guard isPostgresTableIR → static PostgresTableSchemaNode.is().
- Field rlsPolicies → policies: readonly PostgresPolicySchemaNode[];
  children() returns this.policies (resolves the Unit-1 DiffableNode
  type break on the table node).

Still extends SqlSchemaIRNode, freezeNode, isEqualTo => true.

Intermediate unit: the projection/introspection still pass entity
instances where policy nodes are now expected (Unit 5 fixes construction)
and the differ/planner still use the entity guard (Unit 6). Table-node
tests pass (11/11).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Slice 2 (schema-node-tree-restructure), units 3 and 4 of 7.

- PostgresNamespaceSchemaNode: one node per Postgres schema; children()
  = its tables; satisfies the per-schema SqlSchemaIR shape so the legacy
  per-schema consumers take it unchanged in unit 6.
- PostgresDatabaseSchemaNode: the real tree root; children() = namespaces
  (roles held, not yet diffed); static is()/assert()/ensure(); narrows on
  nodeTarget + a nodeKind discriminant that survives the projectSchemaToSpace
  spread.

Additive — does not yet wire/retire PostgresSchemaIR (units 5-6). New-node
tests pass; reviewer SATISFIED. Also closes the carried cast/lint findings
from rounds 1-2 (bare casts in postgres-rls-policy.ts removed by narrowing;
root is()/assert() use blindCast like ensure(); vitest imports merged).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…nit-6 requirement

Surfaced by the unit-3/4 review: verify-postgres-namespaces reads
existingSchemas off the flat schema via isPostgresSchemaIR, so handing it
a namespace node would silently fall back to the [public] default and
regress R9. Pinned into the spec so unit 6 rewires the consumer to read
existingSchemas from the database root.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Collapse the 164-line plan to a status table + brief notes for the
not-yet-done slices + compact locked decisions. Mark slice 1
(select-policies-dependable, #771) and slice 1.5 (#868) as merged;
slice 2 as in progress. Implementation detail lives in the slice specs,
not the plan.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Slice 2 (schema-node-tree-restructure), unit 5 of 7.

Both derivations now build PostgresDatabaseSchemaNode and introspect()
returns the root:
- Projection (contract-to-postgres-schema-ir.ts → contract-to-postgres-
  database-schema-node.ts): tables grouped by owning namespace; policies
  built as PostgresPolicySchemaNode from the contract entities; roles +
  existingSchemas + pgVersion on the root. Malformed-contract assert
  strengthened to per-namespace.
- Introspection: the flat bare-keyed introspectNamespaces merge (silent
  cross-schema table collision; kept only the first schema name) is gone,
  replaced by one namespace node per schema; cluster roles collected once.

Intermediate unit: the build is red on the consumers and the family
introspect() return-type seam (Promise<SqlSchemaIR>, shared with SQLite) —
both rewired in unit 6 (introspect returns a node per design §5). SQLite
and CF-1 untouched here. Producer tests pass (8 projection + 121
introspection); reviewer SATISFIED.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
introspect()/verifySchema/planner-options/toSchemaView/collectSchemaDiffIssues
now type the schema as the family-base SqlSchemaIRNode. The relational verify
walks one per-schema namespace node at a time (namespaceSchemaNodes), never a
flat merge — single-schema is one pass, byte-identical to the pre-tree verify;
multi-schema contract scoping is CF-2.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…SchemaIR

The differ + planner ensure the PostgresDatabaseSchemaNode root and walk the
tree; guards switch to PostgresPolicySchemaNode.is/.assert. collectSchemaIssues
verifies per namespace node (empty root → one empty pass so contract tables
surface as missing). CF-1: existingSchemasFromSchema reads existingSchemas off
the database root, never the public default. PostgresSchemaIR + its
is/assert/ensure are deleted; consumers use PostgresDatabaseSchemaNode statics.
Node ensure() deep-reconstructs namespace/table/policy nodes from the
projectSchemaToSpace spread so the differ always sees real DiffableNodes.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
SQLite planner/runner resolve the single flat namespace from the introspected
node (sqliteFlatSchema). The aggregate projectSchemaToSpace + the verifier-s
orphan detection learn the namespaced tree shape: they prune / enumerate tables
inside each namespace node rather than a flat tables record, keeping per-space
isolation without flattening namespaces. New project-schema-to-space tests cover
the namespaced-tree branch.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Fixtures build PostgresDatabaseSchemaNode roots (namespace nodes holding table
nodes holding policy nodes) instead of the deleted flat PostgresSchemaIR;
introspection tests narrow the result with PostgresDatabaseSchemaNode.assert and
navigate namespaces[…].tables / .roles; policy diff paths gain the namespace
segment. Covers diff-postgres-schema, rls-planner, verify-postgres-namespaces,
the 6-adapters planner/introspection suites, pgvector planner suites, and the
family.introspect / referential-actions integration tests.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
pruneNamespaceTables narrows with a local isRecord type predicate instead of
four bare `as` casts, mirroring the predicate already used in verifier.ts. Net
casts return below the pre-unit-6 baseline (lint:casts delta=-2).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
The unit-6 relational verify ran verifySqlSchema once per actual namespace node
but passed the WHOLE contract each time, so a multi-schema database reported
every contract table as missing_table from the N-1 namespaces it does not
belong to. Replace verifyContractAgainstNamespaceNodes with a per-namespace
pairing: resolve each contract namespace to its live DDL schema (via the
target-s expected-tree projection) and check that namespace-s tables against the
matching actual node. verifySqlSchema gains an optional restrictToNamespaceIds
so the full contract is still consulted for value-set / control-policy
resolution while only the paired namespace-s tables are checked. Single-schema
and SQLite are one pairing — byte-identical to before; multi-schema is correct.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
… planner + verify

The planner and the family schema verify must run the same diffing operation.
Extract the per-namespace pairing into a single shared verifySqlSchemaTree in
@prisma-next/family-sql/schema-verify (the relational verifySqlSchema paired by
namespace identity to the actual nodes). Verify now calls it and rejects when
the issues are non-empty — it owns no pairing/scoping logic of its own. The
planner collectSchemaIssues calls the same function instead of its old
whole-contract-per-node loop, so the planner picks up the multi-schema fix too
(its flat loop had the same latent false-missing bug). Behaviour-neutral:
single-schema is one pairing, byte-identical; multi-schema is correct.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
The migration planner and the schema verify now run ONE combined database-schema
diff instead of each composing the relational + policy strategies themselves.

`diffPostgresDatabaseSchema(...)` (new `diff-database-schema.ts`, Postgres target)
composes, once each: the per-namespace-paired relational diff
(`verifySqlSchemaTree` → table/column/constraint `SchemaIssue`s + the
verification-tree root/counts) and the RLS policy diff (`diffPostgresSchema` →
ownership-filtered `SchemaDiffIssue`s). It returns a `VerifyDatabaseSchemaResult`
whose `schema` carries both shapes — exactly the existing verify-result schema
shape, so nothing downstream changes. The two issue shapes stay separate (the
relational findings are stringly `SchemaIssue`s, the policy findings carry the
live policy nodes the planner needs to build ops); merging them onto one type is
the follow-on relational port, not here.

The control adapter exposes it as the `diffDatabaseSchema` seam (replacing
`collectSchemaDiffIssues`). The family verify calls `controlAdapter.diffDatabaseSchema`
and rejects on non-empty — composing no diff itself (SQLite, which has no
structural diff, falls back to the relational diff alone). The planner calls the
same `diffPostgresDatabaseSchema` and maps `schema.issues` (+ planner-only
namespace presence) to DDL ops and `schema.schemaDiffIssues` to RLS ops — no
re-diff. Behaviour-neutral: planner ops byte-identical, verify accept/reject and
result shape unchanged.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Database→PSL inference is target logic (it owns the dialect type/default maps and
walks its own schema tree), so it moves off the SQL family onto the Postgres
target descriptor — clearing the layering violation and the last expected-red.

- The Postgres target descriptor gains `inferPslContract(tree)`, beside
  `contractSerializer`. New `core/psl-infer/infer-psl-contract.ts`
  (`inferPostgresPslContract`) walks the `PostgresDatabaseSchemaNode` tree and
  owns the Postgres maps (`postgres-type-map` / `postgres-default-mapping`,
  moved from the family). The enum diagnostic now reads each namespace node-s
  `nativeEnumTypeNames`; tables are gathered across namespaces into the model set
  and emitted as the single `__unspecified__` bucket — byte-identical PSL.
- The shape-neutral leaf transforms (name transforms, relation inference,
  `mapDefault`, raw-default parser, the `PslTypeMap`/printer-config types) stay in
  the family and are exported from the new `@prisma-next/family-sql/psl-infer`
  entrypoint, which the target imports.
- The family instance `inferPslContract` delegates to `target.inferPslContract`
  (read off the descriptor like `contractSerializer`); absent ⇒ a clear error
  (Mongo). The flat `sqlSchemaIrToPslAst` + `buildPslDocumentAst` are deleted.
- The inference tests move to the target (`test/psl-infer/`), retargeted to
  `inferPostgresPslContract` via tree fixtures; their inline PSL snapshots are
  unchanged (byte-identity). The neutral-utility tests stay in the family.

No SQL-family file imports the Postgres maps; `contract infer` output is
byte-identical; the full repo typecheck and `fixtures:check` are green.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
… diff

The migration runner held a third, private copy of the whole-contract-against-
each-namespace-node verify loop that the diffDatabaseSchema unification missed —
the same multi-schema false-missing bug already fixed in the family verify and
the planner. For an auth.user + public.note contract the runner-s post-apply
verify reported public.note missing because it checked the full contract against
the auth namespace node, failing db init. The slice-DoD e2e gate caught it
(multi-namespace-runtime).

The runner now delegates to the family `verifySchema`, the single shared
per-namespace-paired diff (diffDatabaseSchema / verifySqlSchemaTree) the CLI
verify and planner already use — no private per-namespace loop remains. Also
update the control-api integration test: introspect() returns the
PostgresDatabaseSchemaNode tree (namespaces), not the old flat { tables }; the
assertion now checks the real tree shape.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
… flatten

The expected-side projection called `contractToSchemaIR` once on the whole
contract, collapsing every namespace into one bare-keyed `Record<string,
SqlTableIR>` that throws on a cross-namespace table-name collision. So a contract
with `public.thing` + `auth.thing` could not be projected — the residual flatten
the tree restructure was meant to remove.

New family helper `contractNamespaceToSchemaIR(storage, namespaceId, options)`
converts only one namespace-s tables, keyed within that namespace, passing the
full storage so cross-namespace type/value-set/enum resolution is unaffected
(and cross-namespace FKs survive — `convertForeignKey` builds purely from
`fk.target`). The Postgres projection now calls it per namespace instead of
flattening. New test proves same-named cross-schema tables project into distinct
namespace nodes without throwing.

`verifySqlSchemaTree`-s `restrictToNamespaceIds` stays — it scopes the relational
`verifySqlSchema`-s contract-table iteration to one namespace while keeping the
full contract available for cross-namespace value-set resolution; the projection
fix is on the diff-s expected tree, not what `verifySqlSchema` consumes.
Behaviour-neutral: planner ops byte-identical, multi-schema + e2e green.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
@wmadden-electric
wmadden-electric requested a review from a team as a code owner June 30, 2026 16:53
@coderabbitai

coderabbitai Bot commented Jun 30, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

This large PR replaces the flat Postgres schema IR (PostgresSchemaIR/PostgresTableIR) with a tree of schema-diff nodes (PostgresDatabaseSchemaNode → namespace → table → policy/role), introduces SqlSchemaIRNode-based SQL family diff/verify APIs (diffDatabaseSchema, verifySqlSchemaTree), and reworks Postgres planner/runner/adapter/PSL-inference around it. Mongo and SQLite gain family-specific diff/verify scoping callbacks replacing schema pre-projection. Separately, the migration-tools aggregate renames ContractSpaceMember to AggregateContractSpace, rewrites the verifier to run full-schema per-space checks with new "unclaimed elements" tracking, and propagates this through CLI commands and formatters.

Changes

Postgres schema IR tree and family diff/verify

Layer / File(s) Summary
New Postgres schema node classes
packages/3-targets/3-targets/postgres/src/core/schema-ir/*, postgres-rls-policy.ts, postgres-role.ts, tests
Adds database/namespace/table/policy/role schema-diff node classes and schema-node-kinds discriminants; PostgresRlsPolicy/PostgresRole become plain Contract-IR entities.
SQL family API + generic diff types
packages/2-sql/9-family/src/core/*, packages/1-framework/1-core/framework-components/src/control/schema-diff.ts, control-migration-types.ts
Introduces SqlSchemaIRNode-based introspect/verifySchema, diffDatabaseSchema, verifySqlSchemaTree, StorageTable.is/assert, and generic SchemaDiffIssue<TNode>/DiffIssue<TNode>/SchemaDiff<TNode>.
Contract-to-node conversion & combined diff
contract-to-postgres-database-schema-node.ts, diff-database-schema.ts, diff-postgres-schema.ts, resolve-ddl-schema.ts
Adds contractToPostgresDatabaseSchemaNode and diffPostgresDatabaseSchema, combining relational and RLS policy diffs.
Planner/runner rewrite
postgres/src/core/migrations/planner.ts, runner.ts, pgvector/adapter tests
planSql computes one combined diff; runner uses family.introspect + family.verifySchema.
PostgresControlAdapter introspect
6-adapters/postgres/src/core/control-adapter.ts, tests
Introspect returns a PostgresDatabaseSchemaNode; collectSchemaDiffIssues replaced by diffDatabaseSchema.
PSL inference entry point
psl-infer/infer-psl-contract.ts, exports/psl-infer.ts
inferPostgresPslContract consumes the schema tree directly; new psl-infer package export.
Mongo/SQLite scoping callbacks
mongo-target/.../scope-verify-result.ts, control-target.ts, sqlite/.../diff-database-schema.ts
Replaces pre-projection with post-verify result scoping (scopeVerifyResultToSpace, diffSqliteDatabaseSchema).

AggregateContractSpace rename and unclaimed elements

Layer / File(s) Summary
Aggregate rename + verifier rewrite
migration/src/aggregate/*, unclaimed-elements.ts, tests
Renames ContractSpaceMember→AggregateContractSpace; verifier now verifies full schema per space and computes unclaimed via stripExtraFindings/collectExtraElementNames.
CLI consumption
cli/src/commands/*, control-api/operations/*, utils/*, tests
CLI commands, combineVerifyResults, and formatters surface per-space results plus unclaimed elements.

Estimated code review effort: 5 (Critical) | ~150 minutes

Sequence Diagram(s)

sequenceDiagram
  participant verifyMigration
  participant verifySchemaForSpace
  participant stripExtraFindings
  participant collectExtraElementNames
  verifyMigration->>verifySchemaForSpace: verify(schemaIntrospection, space, mode)
  verifySchemaForSpace-->>verifyMigration: VerifyDatabaseSchemaResult
  verifyMigration->>stripExtraFindings: strip per-space extras
  stripExtraFindings-->>verifyMigration: schemaPerSpace entry
  verifyMigration->>collectExtraElementNames: gather extra names across spaces
  collectExtraElementNames-->>verifyMigration: unclaimed names
Loading

Possibly related PRs

  • prisma/prisma-next#494: Both PRs change the contract-space per-space schema projection logic around projectSchemaToSpace.
  • prisma/prisma-next#629: Both PRs modify the migration aggregate's per-space ownership/entity-name derivation path affecting verifier.ts.
  • prisma/prisma-next#868: Main PR's unclaimed-elements logic derives "unclaimed" from schemaDiffIssues with outcome === 'extra', matching this PR's diffSchemas/ownership filtering flow.

Suggested reviewers: wmadden

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 44.57% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly captures the main Postgres refactor and the new database→namespace→table→policy schema-node tree.
✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch slice/schema-node-tree-restructure

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

…sions + D1 follow-on

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
@pkg-pr-new

pkg-pr-new Bot commented Jun 30, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@prisma-next/extension-author-tools

npm i https://pkg.pr.new/@prisma-next/extension-author-tools@894

@prisma-next/mongo-runtime

npm i https://pkg.pr.new/@prisma-next/mongo-runtime@894

@prisma-next/family-mongo

npm i https://pkg.pr.new/@prisma-next/family-mongo@894

@prisma-next/sql-runtime

npm i https://pkg.pr.new/@prisma-next/sql-runtime@894

@prisma-next/family-sql

npm i https://pkg.pr.new/@prisma-next/family-sql@894

@prisma-next/extension-arktype-json

npm i https://pkg.pr.new/@prisma-next/extension-arktype-json@894

@prisma-next/middleware-cache

npm i https://pkg.pr.new/@prisma-next/middleware-cache@894

@prisma-next/mongo

npm i https://pkg.pr.new/@prisma-next/mongo@894

@prisma-next/extension-paradedb

npm i https://pkg.pr.new/@prisma-next/extension-paradedb@894

@prisma-next/extension-pgvector

npm i https://pkg.pr.new/@prisma-next/extension-pgvector@894

@prisma-next/extension-postgis

npm i https://pkg.pr.new/@prisma-next/extension-postgis@894

@prisma-next/postgres

npm i https://pkg.pr.new/@prisma-next/postgres@894

@prisma-next/sql-orm-client

npm i https://pkg.pr.new/@prisma-next/sql-orm-client@894

@prisma-next/sqlite

npm i https://pkg.pr.new/@prisma-next/sqlite@894

@prisma-next/extension-supabase

npm i https://pkg.pr.new/@prisma-next/extension-supabase@894

@prisma-next/target-mongo

npm i https://pkg.pr.new/@prisma-next/target-mongo@894

@prisma-next/adapter-mongo

npm i https://pkg.pr.new/@prisma-next/adapter-mongo@894

@prisma-next/driver-mongo

npm i https://pkg.pr.new/@prisma-next/driver-mongo@894

@prisma-next/contract

npm i https://pkg.pr.new/@prisma-next/contract@894

@prisma-next/utils

npm i https://pkg.pr.new/@prisma-next/utils@894

@prisma-next/config

npm i https://pkg.pr.new/@prisma-next/config@894

@prisma-next/errors

npm i https://pkg.pr.new/@prisma-next/errors@894

@prisma-next/framework-components

npm i https://pkg.pr.new/@prisma-next/framework-components@894

@prisma-next/operations

npm i https://pkg.pr.new/@prisma-next/operations@894

@prisma-next/ts-render

npm i https://pkg.pr.new/@prisma-next/ts-render@894

@prisma-next/contract-authoring

npm i https://pkg.pr.new/@prisma-next/contract-authoring@894

@prisma-next/ids

npm i https://pkg.pr.new/@prisma-next/ids@894

@prisma-next/psl-parser

npm i https://pkg.pr.new/@prisma-next/psl-parser@894

@prisma-next/psl-printer

npm i https://pkg.pr.new/@prisma-next/psl-printer@894

@prisma-next/cli

npm i https://pkg.pr.new/@prisma-next/cli@894

@prisma-next/cli-telemetry

npm i https://pkg.pr.new/@prisma-next/cli-telemetry@894

@prisma-next/config-loader

npm i https://pkg.pr.new/@prisma-next/config-loader@894

@prisma-next/emitter

npm i https://pkg.pr.new/@prisma-next/emitter@894

@prisma-next/language-server

npm i https://pkg.pr.new/@prisma-next/language-server@894

@prisma-next/migration-tools

npm i https://pkg.pr.new/@prisma-next/migration-tools@894

prisma-next

npm i https://pkg.pr.new/prisma-next@894

@prisma-next/vite-plugin-contract-emit

npm i https://pkg.pr.new/@prisma-next/vite-plugin-contract-emit@894

@prisma-next/mongo-codec

npm i https://pkg.pr.new/@prisma-next/mongo-codec@894

@prisma-next/mongo-contract

npm i https://pkg.pr.new/@prisma-next/mongo-contract@894

@prisma-next/mongo-value

npm i https://pkg.pr.new/@prisma-next/mongo-value@894

@prisma-next/mongo-contract-psl

npm i https://pkg.pr.new/@prisma-next/mongo-contract-psl@894

@prisma-next/mongo-contract-ts

npm i https://pkg.pr.new/@prisma-next/mongo-contract-ts@894

@prisma-next/mongo-emitter

npm i https://pkg.pr.new/@prisma-next/mongo-emitter@894

@prisma-next/mongo-schema-ir

npm i https://pkg.pr.new/@prisma-next/mongo-schema-ir@894

@prisma-next/mongo-query-ast

npm i https://pkg.pr.new/@prisma-next/mongo-query-ast@894

@prisma-next/mongo-orm

npm i https://pkg.pr.new/@prisma-next/mongo-orm@894

@prisma-next/mongo-query-builder

npm i https://pkg.pr.new/@prisma-next/mongo-query-builder@894

@prisma-next/mongo-lowering

npm i https://pkg.pr.new/@prisma-next/mongo-lowering@894

@prisma-next/mongo-wire

npm i https://pkg.pr.new/@prisma-next/mongo-wire@894

@prisma-next/sql-contract

npm i https://pkg.pr.new/@prisma-next/sql-contract@894

@prisma-next/sql-errors

npm i https://pkg.pr.new/@prisma-next/sql-errors@894

@prisma-next/sql-operations

npm i https://pkg.pr.new/@prisma-next/sql-operations@894

@prisma-next/sql-schema-ir

npm i https://pkg.pr.new/@prisma-next/sql-schema-ir@894

@prisma-next/sql-contract-psl

npm i https://pkg.pr.new/@prisma-next/sql-contract-psl@894

@prisma-next/sql-contract-ts

npm i https://pkg.pr.new/@prisma-next/sql-contract-ts@894

@prisma-next/sql-contract-emitter

npm i https://pkg.pr.new/@prisma-next/sql-contract-emitter@894

@prisma-next/sql-lane-query-builder

npm i https://pkg.pr.new/@prisma-next/sql-lane-query-builder@894

@prisma-next/sql-relational-core

npm i https://pkg.pr.new/@prisma-next/sql-relational-core@894

@prisma-next/sql-builder

npm i https://pkg.pr.new/@prisma-next/sql-builder@894

@prisma-next/target-postgres

npm i https://pkg.pr.new/@prisma-next/target-postgres@894

@prisma-next/target-sqlite

npm i https://pkg.pr.new/@prisma-next/target-sqlite@894

@prisma-next/adapter-postgres

npm i https://pkg.pr.new/@prisma-next/adapter-postgres@894

@prisma-next/adapter-sqlite

npm i https://pkg.pr.new/@prisma-next/adapter-sqlite@894

@prisma-next/driver-postgres

npm i https://pkg.pr.new/@prisma-next/driver-postgres@894

@prisma-next/driver-sqlite

npm i https://pkg.pr.new/@prisma-next/driver-sqlite@894

commit: 3f892ee

@github-actions

github-actions Bot commented Jun 30, 2026 •

Copy link
Copy Markdown

size-limit report 📦

Path Size
postgres / no-emit 148.97 KB (-7.32% 🔽)
postgres / emit 126.45 KB (-14.49% 🔽)
mongo / no-emit 98.2 KB (0%)
mongo / emit 89.39 KB (0%)
cf-worker / no-emit 175.52 KB (-7.08% 🔽)
cf-worker / emit 150.97 KB (-13.33% 🔽)

@coderabbitai coderabbitai 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.

Actionable comments posted: 9

🧹 Nitpick comments (4)
packages/1-framework/3-tooling/migration/src/aggregate/verifier.ts (1)

237-240: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Prefer blindCast over a bare as for this structural read.

As per coding guidelines: "No bare as in production code. Use blindCast<T, \"Reason\"> or castAs<T>".

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/1-framework/3-tooling/migration/src/aggregate/verifier.ts` around
lines 237 - 240, The structural read in verifier.ts uses a bare `as` cast, which
violates the casting guideline. Update the schema narrowing in the verifier
logic to use `blindCast<T, "Reason">` or `castAs<T>` instead of the direct
assertion, keeping the existing `schemaIntrospection` handling and the `schema`
variable in the same flow.

Source: Coding guidelines

packages/1-framework/3-tooling/migration/src/aggregate/project-schema-to-space.ts (1)

68-72: 📐 Maintainability & Code Quality | 🔵 Trivial | ⚡ Quick win

Prefer blindCast over a bare as for this structural read.

The repo convention (and the sibling namespaceSchemaNodes helper this tree feeds) uses blindCast<T, "reason"> for exactly this kind of duck-typed structural read rather than a bare as.
As per coding guidelines: "No bare as in production code. Use blindCast<T, \"Reason\"> or castAs<T>".

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@packages/1-framework/3-tooling/migration/src/aggregate/project-schema-to-space.ts`
around lines 68 - 72, Replace the bare structural cast in the schema reader with
the repo-standard blindCast pattern. In project-schema-to-space’s schema
normalization logic, update the schemaObj assignment to use blindCast with an
explicit reason instead of a plain as cast, matching the convention used by
namespaceSchemaNodes and other duck-typed reads. Keep the inferred shape the
same while making the cast intent explicit and consistent with the coding
guidelines.

Source: Coding guidelines

packages/3-targets/6-adapters/postgres/src/core/control-adapter.ts (1)

597-602: 🚀 Performance & Scalability | 🔵 Trivial | 💤 Low value

getPostgresVersion runs once per namespace though it's cluster-scoped.

introspectSchema calls getPostgresVersion at Line 1202, so a multi-namespace walk issues a SELECT version() per schema and the loop just overwrites pgVersion keeping only the last (Line 601). Consider hoisting the version query out of the per-namespace loop in introspect and dropping it from introspectSchema.

Also applies to: 1202-1202

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/3-targets/6-adapters/postgres/src/core/control-adapter.ts` around
lines 597 - 602, `introspect` is doing a cluster-scoped PostgreSQL version
lookup once per schema and then overwriting the result in the `pgVersion`
accumulator. Hoist the `getPostgresVersion` call out of `introspectSchema` into
`introspect` so it runs once before the `resolvedSchemas` loop, pass the version
through as needed, and remove the version query from `introspectSchema` so it
only handles per-namespace introspection. Ensure the `introspect` and
`introspectSchema` flow still returns the same `pgVersion` value for all
namespaces.
packages/3-targets/3-targets/postgres/src/core/schema-ir/postgres-namespace-schema-node.ts (1)

54-62: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Minor: annotations.pg.nativeEnumTypeNames reuses the raw input array, not the frozen copy.

Line 54 stores a defensively-copied, frozen nativeEnumTypeNames on the instance, but Lines 58-59 embed the original input.nativeEnumTypeNames reference inside annotations.pg. Depending on freezeNode's depth, this either leaves the annotation array externally mutable (shallow freeze) or mutates the caller's array to frozen as a side effect (deep freeze). Consider reusing this.nativeEnumTypeNames for the annotation to keep both consistent.

Proposed tweak
     this.nativeEnumTypeNames = Object.freeze([...input.nativeEnumTypeNames]);
     this.annotations = {
       pg: {
         schema: input.schemaName,
-        ...(input.nativeEnumTypeNames.length > 0 && {
-          nativeEnumTypeNames: input.nativeEnumTypeNames,
+        ...(this.nativeEnumTypeNames.length > 0 && {
+          nativeEnumTypeNames: this.nativeEnumTypeNames,
         }),
       },
     };
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@packages/3-targets/3-targets/postgres/src/core/schema-ir/postgres-namespace-schema-node.ts`
around lines 54 - 62, `PostgresNamespaceSchemaNode` is putting the raw
`input.nativeEnumTypeNames` array into `annotations.pg` instead of the class’s
frozen copy. Update the constructor logic to reuse `this.nativeEnumTypeNames`
when building `annotations`, so `nativeEnumTypeNames` stays consistent with the
defensively copied instance state and avoids leaking the caller’s array
reference.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/1-framework/3-tooling/migration/src/aggregate/verifier.ts`:
- Around line 241-254: The table-name collection in the schema helper is
returning duplicates when the same table exists under multiple namespaces, which
later causes duplicate orphan entries. Update the logic in the schema table-name
gathering path used by detectOrphanElements to dedupe names as they are
collected, ideally by switching the local accumulator from an array to a Set and
returning unique table names while preserving the existing
namespaces/schema.tables fallback behavior.

In `@packages/2-sql/9-family/src/core/control-adapter.ts`:
- Around line 212-218: The diffDatabaseSchema input currently omits
normalizeDefault and normalizeNativeType, so the shared diff path compares raw
defaults and types and can produce false drift. Update the diffDatabaseSchema
signature in control-adapter and any implementations/callers to accept these two
normalizer fields, then thread them through to the shared diff logic used by
diffDatabaseSchema so the target diff applies the normalizations consistently.

In `@packages/2-sql/9-family/src/core/control-instance.ts`:
- Around line 730-737: After `filterSchemaDiffIssues` removes structural issues
in `control-instance.ts`, recompute the `ok` state for the returned `sqlResult`
instead of returning it unchanged. Update the
`schemaDiffIssues`/`schema.counts.fail` branch so that `ok` reflects the
filtered schema issues, especially when the original failure was caused only by
suppressed structural diffs, and keep the logic localized around the
`schemaDiffIssues` and `relationalFails` handling.
- Around line 947-955: The table flattening in toSchemaView is dropping the
namespace identity, which causes duplicate SchemaTreeNode IDs for tables with
the same name in different schemas. Update the tableEntries construction in
control-instance.ts so each entry carries the namespace/schema name from
namespaceSchemaNodes, then use that namespace when building the table-level
nodes and IDs in the subsequent tableNodes mapping. Ensure the resulting
SchemaTreeNode labels and IDs stay unique for cases like public.users and
auth.users.

In `@packages/2-sql/9-family/src/core/schema-verify/verify-sql-schema.ts`:
- Around line 340-343: The strict extra-table claim check in verify-sql-schema
should be limited to the paired namespace set, not all contract namespaces.
Update the claimed-table scan in verifySqlSchema (including the same logic used
around the missing-table handling and the matching block at the later location)
so it skips namespaces not present in restrictToNamespaceIds when that set is
provided. This will keep tree verification from letting a table claimed in auth
mask an unexpected same-named table in the public actual node.
- Around line 1407-1426: `mergeVerifyResults` is merging `schema.counts`
correctly but leaving `summary` from the first result, which can make
multi-namespace failures report stale counts. Update `mergeVerifyResults` in
`verify-sql-schema.ts` so the merged result recomputes `summary` from the
combined `a.schema` and `b.schema` data after summing counts, rather than
reusing `a.summary`; use the existing `mergeVerifyResults` flow and the
`schema`/`counts` fields to keep the summary consistent with the merged totals.

In `@packages/3-targets/3-targets/postgres/package.json`:
- Line 38: The dependency entry for `@prisma-next/psl-printer` in the postgres
package.json uses workspace:* instead of the repo’s pinned internal version
convention. Update this package’s internal `@prisma-next/`* dependency to use the
same literal workspace version string as the other internal deps in this
manifest, keeping the existing dependency naming intact.

In `@packages/3-targets/3-targets/postgres/src/core/migrations/planner.ts`:
- Around line 393-400: The namespace selection logic in namespaceSchemaNode is
too permissive because it falls back to namespaceNodes[0] even when multiple
namespaces exist and none match schemaName. Update the helper so it only returns
the first namespace for the single-namespace case, and otherwise returns no
match or raises the appropriate ambiguity handling for relational planning. Keep
the lookup tied to namespaceSchemaNodes and the byName selection so ambiguous
schema matches do not silently probe the wrong namespace.

In `@packages/3-targets/3-targets/postgres/test/rls-diffable-nodes.test.ts`:
- Around line 60-77: The role fixture in the Postgres diffable nodes tests is
using the wrong namespace coordinate for PostgresRole. Update the relevant role
assertions and any similar fixtures to use the cluster-scoped namespace sentinel
UNBOUND_NAMESPACE_ID instead of public, so the tests match the PostgresRole
contract while still verifying kind and name through the PostgresRole
constructor-based fixtures.

---

Nitpick comments:
In
`@packages/1-framework/3-tooling/migration/src/aggregate/project-schema-to-space.ts`:
- Around line 68-72: Replace the bare structural cast in the schema reader with
the repo-standard blindCast pattern. In project-schema-to-space’s schema
normalization logic, update the schemaObj assignment to use blindCast with an
explicit reason instead of a plain as cast, matching the convention used by
namespaceSchemaNodes and other duck-typed reads. Keep the inferred shape the
same while making the cast intent explicit and consistent with the coding
guidelines.

In `@packages/1-framework/3-tooling/migration/src/aggregate/verifier.ts`:
- Around line 237-240: The structural read in verifier.ts uses a bare `as` cast,
which violates the casting guideline. Update the schema narrowing in the
verifier logic to use `blindCast<T, "Reason">` or `castAs<T>` instead of the
direct assertion, keeping the existing `schemaIntrospection` handling and the
`schema` variable in the same flow.

In
`@packages/3-targets/3-targets/postgres/src/core/schema-ir/postgres-namespace-schema-node.ts`:
- Around line 54-62: `PostgresNamespaceSchemaNode` is putting the raw
`input.nativeEnumTypeNames` array into `annotations.pg` instead of the class’s
frozen copy. Update the constructor logic to reuse `this.nativeEnumTypeNames`
when building `annotations`, so `nativeEnumTypeNames` stays consistent with the
defensively copied instance state and avoids leaking the caller’s array
reference.

In `@packages/3-targets/6-adapters/postgres/src/core/control-adapter.ts`:
- Around line 597-602: `introspect` is doing a cluster-scoped PostgreSQL version
lookup once per schema and then overwriting the result in the `pgVersion`
accumulator. Hoist the `getPostgresVersion` call out of `introspectSchema` into
`introspect` so it runs once before the `resolvedSchemas` loop, pass the version
through as needed, and remove the version query from `introspectSchema` so it
only handles per-namespace introspection. Ensure the `introspect` and
`introspectSchema` flow still returns the same `pgVersion` value for all
namespaces.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

Run ID: 28eb30df-16d3-4255-8569-8ba7e658c740

📥 Commits

Reviewing files that changed from the base of the PR and between d987376 and 91248f6.

⛔ Files ignored due to path filters (4)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
  • projects/postgres-rls/plan.md is excluded by !projects/**
  • projects/postgres-rls/slices/schema-node-tree-restructure/design.md is excluded by !projects/**
  • projects/postgres-rls/slices/schema-node-tree-restructure/spec.md is excluded by !projects/**
📒 Files selected for processing (97)
  • packages/1-framework/3-tooling/migration/src/aggregate/project-schema-to-space.ts
  • packages/1-framework/3-tooling/migration/src/aggregate/verifier.ts
  • packages/1-framework/3-tooling/migration/test/aggregate/project-schema-to-space.test.ts
  • packages/2-sql/1-core/schema-ir/src/ir/sql-schema-ir.ts
  • packages/2-sql/9-family/package.json
  • packages/2-sql/9-family/src/core/control-adapter.ts
  • packages/2-sql/9-family/src/core/control-instance.ts
  • packages/2-sql/9-family/src/core/migrations/contract-to-schema-ir.ts
  • packages/2-sql/9-family/src/core/migrations/types.ts
  • packages/2-sql/9-family/src/core/psl-contract-infer/printer-config.ts
  • packages/2-sql/9-family/src/core/schema-verify/verify-sql-schema.ts
  • packages/2-sql/9-family/src/exports/control.ts
  • packages/2-sql/9-family/src/exports/psl-infer.ts
  • packages/2-sql/9-family/src/exports/schema-verify.ts
  • packages/2-sql/9-family/test/psl-contract-infer/default-mapping.test.ts
  • packages/2-sql/9-family/tsdown.config.ts
  • packages/3-extensions/pgvector/test/migrations/planner.behavior.test.ts
  • packages/3-extensions/pgvector/test/migrations/planner.contract-to-schema-ir.test.ts
  • packages/3-extensions/pgvector/test/migrations/planner.storage-types.test.ts
  • packages/3-targets/3-targets/postgres/package.json
  • packages/3-targets/3-targets/postgres/src/core/authoring.ts
  • packages/3-targets/3-targets/postgres/src/core/entity-kinds.ts
  • packages/3-targets/3-targets/postgres/src/core/migrations/contract-to-postgres-database-schema-node.ts
  • packages/3-targets/3-targets/postgres/src/core/migrations/contract-to-postgres-schema-ir.ts
  • packages/3-targets/3-targets/postgres/src/core/migrations/diff-database-schema.ts
  • packages/3-targets/3-targets/postgres/src/core/migrations/diff-postgres-schema.ts
  • packages/3-targets/3-targets/postgres/src/core/migrations/op-factory-call.ts
  • packages/3-targets/3-targets/postgres/src/core/migrations/operations/rls.ts
  • packages/3-targets/3-targets/postgres/src/core/migrations/planner.ts
  • packages/3-targets/3-targets/postgres/src/core/migrations/runner.ts
  • packages/3-targets/3-targets/postgres/src/core/migrations/verify-postgres-namespaces.ts
  • packages/3-targets/3-targets/postgres/src/core/postgres-rls-policy.ts
  • packages/3-targets/3-targets/postgres/src/core/postgres-role.ts
  • packages/3-targets/3-targets/postgres/src/core/postgres-schema.ts
  • packages/3-targets/3-targets/postgres/src/core/psl-infer/infer-psl-contract.ts
  • packages/3-targets/3-targets/postgres/src/core/psl-infer/postgres-default-mapping.ts
  • packages/3-targets/3-targets/postgres/src/core/psl-infer/postgres-type-map.ts
  • packages/3-targets/3-targets/postgres/src/core/schema-ir/postgres-database-schema-node.ts
  • packages/3-targets/3-targets/postgres/src/core/schema-ir/postgres-namespace-schema-node.ts
  • packages/3-targets/3-targets/postgres/src/core/schema-ir/postgres-policy-schema-node.ts
  • packages/3-targets/3-targets/postgres/src/core/schema-ir/postgres-role-schema-node.ts
  • packages/3-targets/3-targets/postgres/src/core/schema-ir/postgres-schema-ir-annotations.ts
  • packages/3-targets/3-targets/postgres/src/core/schema-ir/postgres-schema-ir.ts
  • packages/3-targets/3-targets/postgres/src/core/schema-ir/postgres-table-schema-node.ts
  • packages/3-targets/3-targets/postgres/src/exports/control.ts
  • packages/3-targets/3-targets/postgres/src/exports/planner.ts
  • packages/3-targets/3-targets/postgres/src/exports/types.ts
  • packages/3-targets/3-targets/postgres/test/migrations/contract-to-postgres-database-schema-node.test.ts
  • packages/3-targets/3-targets/postgres/test/migrations/contract-to-postgres-schema-ir.test.ts
  • packages/3-targets/3-targets/postgres/test/migrations/diff-postgres-schema.test.ts
  • packages/3-targets/3-targets/postgres/test/migrations/rls-ops.test.ts
  • packages/3-targets/3-targets/postgres/test/migrations/rls-planner.test.ts
  • packages/3-targets/3-targets/postgres/test/migrations/verify-postgres-namespaces.test.ts
  • packages/3-targets/3-targets/postgres/test/postgres-contract-serializer.test.ts
  • packages/3-targets/3-targets/postgres/test/postgres-database-schema-node.test.ts
  • packages/3-targets/3-targets/postgres/test/postgres-namespace-schema-node.test.ts
  • packages/3-targets/3-targets/postgres/test/postgres-table-ir.test.ts
  • packages/3-targets/3-targets/postgres/test/postgres-table-schema-node.test.ts
  • packages/3-targets/3-targets/postgres/test/psl-infer/fixtures.ts
  • packages/3-targets/3-targets/postgres/test/psl-infer/infer-psl-contract.test.ts
  • packages/3-targets/3-targets/postgres/test/psl-infer/postgres-type-map.test.ts
  • packages/3-targets/3-targets/postgres/test/psl-infer/print-psl/print-psl.core.test.ts
  • packages/3-targets/3-targets/postgres/test/psl-infer/print-psl/print-psl.defaults-and-types.test.ts
  • packages/3-targets/3-targets/postgres/test/psl-infer/print-psl/print-psl.enums.test.ts
  • packages/3-targets/3-targets/postgres/test/psl-infer/print-psl/print-psl.naming-and-constraints.test.ts
  • packages/3-targets/3-targets/postgres/test/psl-infer/print-psl/print-psl.relations.test.ts
  • packages/3-targets/3-targets/postgres/test/psl-policy-authoring.test.ts
  • packages/3-targets/3-targets/postgres/test/rls-diffable-nodes.test.ts
  • packages/3-targets/3-targets/postgres/test/rls-ir-kinds.test.ts
  • packages/3-targets/3-targets/postgres/test/schema-ir-leaf-nodes.test.ts
  • packages/3-targets/3-targets/sqlite/src/core/migrations/planner.ts
  • packages/3-targets/3-targets/sqlite/src/core/migrations/runner.ts
  • packages/3-targets/6-adapters/postgres/src/core/control-adapter.ts
  • packages/3-targets/6-adapters/postgres/test/control-adapter.check-constraints.test.ts
  • packages/3-targets/6-adapters/postgres/test/control-adapter.defaults.test.ts
  • packages/3-targets/6-adapters/postgres/test/control-adapter.test.ts
  • packages/3-targets/6-adapters/postgres/test/migrations/array-column-introspection.integration.test.ts
  • packages/3-targets/6-adapters/postgres/test/migrations/fixtures/runner-fixtures.ts
  • packages/3-targets/6-adapters/postgres/test/migrations/index-introspection.integration.test.ts
  • packages/3-targets/6-adapters/postgres/test/migrations/planner.authoring-surface.test.ts
  • packages/3-targets/6-adapters/postgres/test/migrations/planner.codec-field-event.test.ts
  • packages/3-targets/6-adapters/postgres/test/migrations/planner.cross-space-fk-ddl.test.ts
  • packages/3-targets/6-adapters/postgres/test/migrations/planner.fk-config.test.ts
  • packages/3-targets/6-adapters/postgres/test/migrations/planner.integration.test.ts
  • packages/3-targets/6-adapters/postgres/test/migrations/planner.reconciliation.integration.test.ts
  • packages/3-targets/6-adapters/postgres/test/migrations/planner.reconciliation.test.ts
  • packages/3-targets/6-adapters/postgres/test/migrations/planner.referential-actions.test.ts
  • packages/3-targets/6-adapters/postgres/test/migrations/planner.semantic-satisfaction.test.ts
  • packages/3-targets/6-adapters/postgres/test/migrations/rls-collect-extension-issues.test.ts
  • packages/3-targets/6-adapters/postgres/test/migrations/rls-introspection.integration.test.ts
  • packages/3-targets/6-adapters/postgres/test/migrations/rls-lifecycle-e2e.integration.test.ts
  • packages/3-targets/6-adapters/postgres/test/migrations/rls-migration-plan.integration.test.ts
  • test/integration/test/control-api.test.ts
  • test/integration/test/cross-package/postgres-control-policy-planner.test.ts
  • test/integration/test/family.introspect.integration.test.ts
  • test/integration/test/family.introspect.test.ts
  • test/integration/test/referential-actions.integration.test.ts
💤 Files with no reviewable changes (4)
  • packages/3-targets/3-targets/postgres/test/migrations/contract-to-postgres-schema-ir.test.ts
  • packages/3-targets/3-targets/postgres/test/postgres-table-ir.test.ts
  • packages/3-targets/3-targets/postgres/src/core/migrations/contract-to-postgres-schema-ir.ts
  • packages/3-targets/3-targets/postgres/src/core/schema-ir/postgres-schema-ir.ts

wmadden-electric and others added 2 commits July 1, 2026 10:12
…PSL slice; note the fail-loud guard)

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
The inference gather flattens the tree-s tables into one bucket for the
single-namespace `__unspecified__` PSL output. It did a silent last-wins
overwrite if two namespaces held the same table name — unreachable today
(`contract infer` introspects a single namespace) but a new silent-lossy path on
this branch. It now throws an actionable error naming the table, mirroring the
`contractToSchemaIR` duplicate-name throw: same-named cross-schema tables are not
yet supported for `contract infer` (multi-namespace `namespace { … }` output is a
later slice). New test proves the tree with two same-named tables throws instead
of dropping one. Behaviour-neutral: unreachable on all single-namespace paths —
psl-infer suite, contract-infer e2e, and fixtures:check stay green.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>

@wmadden wmadden 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.

Completely unacceptable

wmadden-electric and others added 3 commits July 1, 2026 15:08
…tor operation

The combined database-schema diff was an optional method on the SQL control
adapter. Move it to the SQL target descriptor and make it required: schema
comparison is target logic (dialect type/default maps, schema-tree walk), not
adapter I/O, so it belongs on the descriptor alongside contractSerializer and
inferPslContract.

- Relocate the relational diffing code from core/schema-verify/ to core/diff/
  (verify-sql-schema.ts -> sql-schema-diff.ts, plus the sibling files) with no
  logic changes. The family entrypoint moves from ./schema-verify to ./diff.
- Add diffDatabaseSchema to SqlControlTargetDescriptor as a required operation.
  Postgres provides relational + policy diffing (diffPostgresDatabaseSchema);
  SQLite provides relational-only diffing via a new diffSqliteDatabaseSchema.
- The family verifier (verifySchema) becomes a thin consumer: it introspects the
  actual schema, calls target.diffDatabaseSchema, applies control-policy
  suppression as a post-step, and fails when a surviving issue remains. It no
  longer composes any diffing itself and has no SQLite fallback branch.
- Drop the now-dead diffDatabaseSchema method and orphaned imports from the
  Postgres control adapter; update importers and test fixtures accordingly.

Behavior-neutral: planner op-assertions are unchanged and pass.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…ff flatten helper

The schema view and SQLite reached into namespaceSchemaNodes — a diff-internal
flatten helper — to walk the schema IR. Decouple both so the helper is used only
inside the diff module.

- toSchemaView now walks the schema-IR tree own structure (root -> namespaces ->
  tables) directly instead of calling namespaceSchemaNodes, and drops that
  import from control-instance.ts. A multi-namespace test locks the flatten
  output.
- SQLite post-apply verify (runner) and the planner schema-issue collection now
  go through diffSqliteDatabaseSchema (added in the prior unit) rather than
  namespaceSchemaNodes(x)[0] ?? { tables: {} } + a direct verifySqlSchema call.
  The duplicated empty-schema fallback is gone; the planner narrows the flat
  SQLite node directly when building ops.

Behavior-neutral: schema-view output and SQLite db verify verdicts are
unchanged; the SQLite planner op-assertions are unaffected.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
… flatten helper

relationalNamespaceNode was the last consumer of namespaceSchemaNodes outside
the diff module. The Postgres planner always holds a PostgresDatabaseSchemaNode,
so it does not need the generic flatten helper: ensure the node and read its
.namespaces directly to select the namespace by schemaName. namespaceSchemaNodes
is now used only inside the diff module (and re-exported from exports/diff).

Behavior-neutral: planner ops byte-identical (planner/rls-planner op-assertions
unmodified and passing).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
wmadden-electric and others added 3 commits July 6, 2026 09:41
…ld, never a string convention

Will's review: filtering on kind-string enumeration invents a string
convention for a structural characteristic. Every diff issue fails an
expectation one of three ways — not-expected, not-found, not-equal — carried
as reason: ExpectationFailureReason on both issue types and grafted verify
nodes (comparison-relative, so contract-vs-DB and contract-vs-contract stay
unambiguous). SchemaDiffIssue keeps legacy outcome alongside until the
slice-2.5 issue-type merge; the framework never matches family-invented
kind/code strings.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…d; the framework filters structurally

Every diff finding now carries reason: ExpectationFailureReason
("not-expected" | "not-found" | "not-equal") — the three ways an actual state
can fail an expectation, comparison-relative (expected = desired side, actual =
current side), so the vocabulary never anchors to a base that flips between
contract-vs-database and contract-vs-contract comparisons.

SchemaDiffIssue gains reason alongside its legacy outcome; both are stamped at
the one producer (diffSchemas), so they cannot drift, and outcome retires with
the issue-type merge. The family verifiers stamp reason on every relational
issue at construction (SQL walk, verify helpers, Mongo, the namespace check),
and on the verify-tree nodes they graft for live entities no contract expects.

The aggregate strip and unclaimed-elements collection are now structural
filters: the tree strip keeps root children without reason "not-expected"; the
issue strip narrows by the framework-declared extra_table kind (on the legacy
coordinate-based issue the entity level is not yet a structural field — a pure
coordinate-shape check would wrongly strip extra_primary_key and Mongo
extra_validator, which carry no finer coordinate). The kind-enumeration and
family node-code helpers (isExtraIssue, isEntityNode, isExtraTableNode) are
deleted; no "table"/"collection"/"EXTRA_COLLECTION" strings remain. The synth
keep-predicate keys on reason. The diff-extras path in the unclaimed collection
stays: in a tolerant verify the relational walk emits no extra_table issue, so
an undeclared table carrying an RLS policy is only nameable through the
policy node — removing it would change lenient output.

Code comments describe behaviour in plain terms; design-document section
labels are gone. CodeRabbit round: role fixtures use the cluster-scoped
namespace sentinel.

Behaviour-neutral: fixtures byte-identical, verify verdicts and planner ops
unchanged.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…delete the CLI fold

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
wmadden-electric and others added 5 commits July 6, 2026 12:22
…idental

The per-pr-declaration check requires every PR touching
packages/3-extensions/ to record intent in the in-flight extension-author
upgrade instructions. This slice touches extension test files only (pgvector
planner fixtures rebuilt for the schema-node tree, a supabase test comment);
no extension-author API changed, so the declaration is an incidental note per
the established pattern.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…estructure

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>

# Conflicts:
#	skills/extension-author/prisma-next-extension-upgrade/upgrades/0.14-to-0.15/instructions.md
The combined-summary fallback read firstFailure through a bare `as`. When
`okAll` is false the loop assigned `firstFailure`, so an optional read with the
app summary as the (unreachable) fallback expresses the same invariant without
a cast.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
… basis

The Mongo runner scoping recomputed counts with a tree walk that counted the
synthetic root, while diffMongoSchemas tallies per collection and never counts
the root — an off-by-one in pass/totalNodes after a prune. The walk now covers
the root's subtrees only; the tests pin exact counts (one surviving collection
=> totalNodes 1, not 2), red before the fix.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
toSchemaView flattened every namespace's tables into ids/labels built from
the bare table name, so same-named tables in different namespaces (public.thing
and auth.thing) collided in the rendered tree. A multi-namespace root now
qualifies each table's display name with its namespace key through the
table/columns/column/primary-key/unique/index node ids and the table label;
a single-namespace root and a flat SQLite root render exactly as before.
Synthesized constraint/index fallback names keep the bare table name — the
name the database derives them from.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
@wmadden-electric

Copy link
Copy Markdown
Contributor Author

toSchemaView namespace collision (re-raised across rounds): fixed in 338c1e9 — a multi-namespace root now qualifies table ids/labels with the namespace key (table-public.thing vs table-auth.thing) through the table/columns/column/primary-key/unique/index nodes; single-namespace and flat roots render as before, and synthesized fallback constraint names keep the bare table name. Test with public.thing + auth.thing asserts distinct ids. Covers the same re-raise in the round-3 review body.

wmadden-electric and others added 3 commits July 6, 2026 14:35
…ggregate namespaces

collectAggregateNamespaces replaced the whole namespace object per key, so two
contract spaces legitimately sharing a namespaceId had the earlier space's
tables silently dropped from the object handed to introspect — skewing
extra/unclaimed detection in a multi-extension aggregate. Shared namespaces now
merge per entity kind (element disjointness is already enforced by
checkIntegrity, so kind maps cannot collide on a name). Red-first tests cover
the shared-namespace union, per-kind union, and the disjoint case.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
The schema-only render passed --quiet through to the failure output, so
`db verify --schema-only --quiet` against a failing schema exited 1 with zero
diagnostics. The failure render now overrides quiet, the same policy the
full-mode failure branch already applies. Red-first integration test pins
diagnostics + exit 1 for a missing table under --quiet.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…rral

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
@wmadden
wmadden enabled auto-merge July 6, 2026 14:15
@wmadden
wmadden added this pull request to the merge queue Jul 6, 2026
Merged via the queue into main with commit 720677e Jul 6, 2026
20 checks passed
@wmadden
wmadden deleted the slice/schema-node-tree-restructure branch July 6, 2026 14:42
paulwer pushed a commit to paulwer/prisma-next that referenced this pull request Jul 12, 2026
… describe (prisma#919)

## What

`contract infer` now writes a `contract.prisma` containing only what the
stack's contract spaces don't already account for. When a stack
extension pack's contract space declares a DB element (e.g. the Supabase
pack's tables), the inferrer omits it — a brownfield app on top of an
extension gets a contract of *its own* tables.

Slice G of the extension-supabase project (decision C16). Independent of
RLS, native enums, and the complete-contract work (Slice F): it
subtracts whatever the packs declare today, and deepens automatically as
they declare more. Also carries the plan-expansion docs (Slices F/G,
C16, un-defers) from the closed prisma#899, so the plan travels with the work.

## How

The match reuses the framework's existing coordinate primitive — nothing
new is minted.

- The Postgres inferrer runs `elementCoordinates` (from
`@prisma-next/framework-components/ir` — the same coordinate walk the
contract-space aggregate and cross-space collision check already use)
over each pack's contract storage, building a set of declared
`(namespaceId, entityKind, entityName)` coordinates.
- While gathering the `PostgresDatabaseSchemaNode` tree (prisma#894's
substrate), it omits any node whose coordinate is in that set. A table
lives at `(schemaName, 'table', tableName)`; the match is
**entity-agnostic** (enums/roles/policies covered for free as they enter
the tree) and **coordinate-precise** (a pack's `auth.users` cannot
suppress an app's `public.users`).
- The family instance forwards the packs' already-assembled contracts
(`readonly Contract<SqlStorage>[]`) through a widened `inferPslContract`
hook param — no new type, nothing added to `migrations/types.ts`.
- Omission happens **before** the cross-schema duplicate-name check and
relation inference; surviving tables' foreign keys are dropped only when
the referenced name was omitted **and** has no surviving table (so no
dangling `@relation`, and a legitimate same-named relation elsewhere is
never stripped).
- Empty/absent input → byte-identical output (`fixtures:check` clean).
The framework capability, CLI, introspection scope, and `db verify` are
untouched. SQLite doesn't bind the hook; Mongo has no infer.

## Follow-on

The ownership query has no named home yet. TML-2977 extracts a
framework-level `ContractSpaceAggregate` base (pure aggregation of
contract spaces + coordinate-precise ownership) that today's
migration-state aggregate extends as `MigrationSpaceAggregate`; this
slice's inline `elementCoordinates` call then collapses to a one-line
delegation, and re-infer (reconcile the app space via the schema diff)
rides the same base. Not gating this slice.

## Tests

Omission by coordinate + byte-identity; namespace-correctness
(`auth`-declared name doesn't omit a `public` table); entity-kind
precision (a same-named non-table entity never suppresses a table —
proves the key isn't table-typed); dangling-FK both directions (strip vs
keep-a-surviving-same-name); duplicate-name-before-throw; and a real
end-to-end test (real `postgresTargetDescriptor` + real family
instance).

## Verification

build · typecheck (143/143) · family-sql + target-postgres suites ·
fixtures:check byte-identical · lint:deps · lint:casts delta 0 ·
check:upgrade-coverage — all green locally.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **New Features**
* `contract infer` now omits DB tables already covered by stack
extension-pack contract spaces.
* Cross-space foreign keys are now qualified with the owning pack’s
namespace and contract-space identifiers for clearer relation fields and
printed PSL.
* **Bug Fixes**
* Omission is scoped to the exact coordinate (avoiding suppression
across different namespaces/same-named entities).
* Filters only dangling foreign keys that target omitted tables while
preserving valid relationships.
* **Tests**
* Added unit and integration coverage for described-contract omission,
cross-space FK inference, and malformed-pack error handling.
* **Documentation**
* Updated upgrade guidance to reflect the new omission/qualification
behavior.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Co-authored-by: Claude Fable 5 <[email protected]>
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants