Repository navigation
TML-2931: a generic tree-walking schema differ — RLS now plans in migration plan - #868
Conversation
…pec) Shaping for Slice 1.5 of postgres-rls. Accepts the schema-diff-over-structured-IR ADR: a schema diff is computed between two derived schema IRs, walked as a tree (coord()/isEqualTo()/children()); both sides project from contract/database; ownership is a post-diff disposition, not a pre-filter. Registry deferred (follow-on C). Plan Slice 1.5 + a prescriptive slice spec (units A-E, exact signatures, 9 ACs). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…TreeNode is taken) A CLI schema-view class already owns SchemaTreeNode (~33 call sites, out of scope). Keep the existing DiffableNode interface name; add coord()/children() and a new DiffableRoot for the root. Avoids the collision and the SchemaDiffIssue retype churn. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
… provenance-symmetric RLS diff) Generic differ walks two schema-IR roots (DiffableRoot/DiffableNode with coord()/isEqualTo()/children()); diffNodes removed. project-from-contract (projectPostgresSchemaFromContract) makes the postgres contractToSchema yield a populated PostgresSchemaIR, so migration plan emits CREATE POLICY. The RLS diff walks the full actual tree and applies owned-namespace suppression to outcomes, not inputs. Planner fail-loud deleted; planRlsDiff guard throws on a non-PostgresSchemaIR schema (an invariant post-seam). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…s to PostgresSchemaIR Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughThe PR replaces flat schema-node diffing with recursive coordinate-based diffing, updates Postgres schema IR nodes to expose coordinates and children, and rewires Postgres migration planning, exports, and tests to use ChangesSchema diff and Postgres planner wiring
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
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. Comment |
@prisma-next/extension-author-tools
@prisma-next/mongo-runtime
@prisma-next/family-mongo
@prisma-next/sql-runtime
@prisma-next/family-sql
@prisma-next/extension-arktype-json
@prisma-next/middleware-cache
@prisma-next/mongo
@prisma-next/extension-paradedb
@prisma-next/extension-pgvector
@prisma-next/extension-postgis
@prisma-next/postgres
@prisma-next/sql-orm-client
@prisma-next/sqlite
@prisma-next/extension-supabase
@prisma-next/target-mongo
@prisma-next/adapter-mongo
@prisma-next/driver-mongo
@prisma-next/contract
@prisma-next/utils
@prisma-next/config
@prisma-next/errors
@prisma-next/framework-components
@prisma-next/operations
@prisma-next/ts-render
@prisma-next/contract-authoring
@prisma-next/ids
@prisma-next/psl-parser
@prisma-next/psl-printer
@prisma-next/cli
@prisma-next/cli-telemetry
@prisma-next/config-loader
@prisma-next/emitter
@prisma-next/language-server
@prisma-next/migration-tools
prisma-next
@prisma-next/vite-plugin-contract-emit
@prisma-next/mongo-codec
@prisma-next/mongo-contract
@prisma-next/mongo-value
@prisma-next/mongo-contract-psl
@prisma-next/mongo-contract-ts
@prisma-next/mongo-emitter
@prisma-next/mongo-schema-ir
@prisma-next/mongo-query-ast
@prisma-next/mongo-orm
@prisma-next/mongo-query-builder
@prisma-next/mongo-lowering
@prisma-next/mongo-wire
@prisma-next/sql-contract
@prisma-next/sql-errors
@prisma-next/sql-operations
@prisma-next/sql-schema-ir
@prisma-next/sql-contract-psl
@prisma-next/sql-contract-ts
@prisma-next/sql-contract-emitter
@prisma-next/sql-lane-query-builder
@prisma-next/sql-relational-core
@prisma-next/sql-builder
@prisma-next/target-postgres
@prisma-next/target-sqlite
@prisma-next/adapter-postgres
@prisma-next/adapter-sqlite
@prisma-next/driver-postgres
@prisma-next/driver-sqlite
commit: |
size-limit report 📦
|
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
packages/1-framework/1-core/framework-components/src/control/schema-diff.ts (1)
27-29: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick winFail loudly on non-unique coordinate keys.
stableKey()is a lossy serialization for a publicEntityCoordinate, and both maps silently overwrite on duplicate keys. That means two distinct siblings can collapse into one entry, sodiffSchema()can miss missing/extra/mismatch issues and downstream planners will emit an incomplete set of operations.Suggested fix
function stableKey(c: EntityCoordinate): string { - return `${c.plane}|${c.namespaceId}|${c.entityKind}|${c.entityName}`; + return JSON.stringify([c.plane, c.namespaceId, c.entityKind, c.entityName]); } @@ const expectedMap = new Map<string, DiffableNode>(); for (const node of expected) { - expectedMap.set(stableKey(node.coord()), node); + const key = stableKey(node.coord()); + if (expectedMap.has(key)) { + throw new Error(`diffSchema: duplicate expected coordinate ${key}`); + } + expectedMap.set(key, node); } @@ const actualMap = new Map<string, DiffableNode>(); for (const node of actual) { - actualMap.set(stableKey(node.coord()), node); + const key = stableKey(node.coord()); + if (actualMap.has(key)) { + throw new Error(`diffSchema: duplicate actual coordinate ${key}`); + } + actualMap.set(key, node); }Also applies to: 57-64
🤖 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/1-core/framework-components/src/control/schema-diff.ts` around lines 27 - 29, The coordinate keying used by stableKey() is lossy and can silently collapse distinct EntityCoordinate values, causing diffSchema() to miss differences. Update the coordinate-to-entry handling in stableKey() and the maps used by diffSchema() to detect duplicate keys and fail loudly instead of overwriting entries; if a collision is encountered, throw an explicit error that includes the conflicting coordinates so the issue is visible during schema diffing.packages/3-targets/3-targets/postgres/src/core/postgres-rls-policy.ts (1)
63-69: 🗄️ Data Integrity & Integration | 🟠 Major | 🏗️ Heavy liftInclude
tableNamein the policy coordinate.
diffSchema()keys nodes bystableKey(node.coord()). With onlynamespaceId + entityKind + namehere, two tables in the same schema that reuse the same policy name collapse to one map entry, so the planner can miss or mispair a policy operation. Postgres policy identity is table-scoped, so the coordinate needs a table discriminator too.🤖 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/postgres-rls-policy.ts` around lines 63 - 69, The policy coordinate is missing the table discriminator, so stableKey(node.coord()) can collide for same-named policies on different tables. Update PostgresRlsPolicy.coord() to include tableName alongside namespaceId, entityKind, and name so each policy is uniquely keyed per table, and make sure the table-scoped value is sourced from the policy’s existing table identifier in the class.
🤖 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/3-targets/3-targets/postgres/src/exports/control.ts`:
- Around line 70-77: Replace the bare production cast in the contract passed to
projectPostgresSchemaFromContract with the approved casting helper from
`@prisma-next/utils/casts`. Use blindCast with a clear reason string instead of
`as unknown as` in control.ts, keeping the existing control flow and the call to
projectPostgresSchemaFromContract unchanged except for the cast.
---
Outside diff comments:
In `@packages/1-framework/1-core/framework-components/src/control/schema-diff.ts`:
- Around line 27-29: The coordinate keying used by stableKey() is lossy and can
silently collapse distinct EntityCoordinate values, causing diffSchema() to miss
differences. Update the coordinate-to-entry handling in stableKey() and the maps
used by diffSchema() to detect duplicate keys and fail loudly instead of
overwriting entries; if a collision is encountered, throw an explicit error that
includes the conflicting coordinates so the issue is visible during schema
diffing.
In `@packages/3-targets/3-targets/postgres/src/core/postgres-rls-policy.ts`:
- Around line 63-69: The policy coordinate is missing the table discriminator,
so stableKey(node.coord()) can collide for same-named policies on different
tables. Update PostgresRlsPolicy.coord() to include tableName alongside
namespaceId, entityKind, and name so each policy is uniquely keyed per table,
and make sure the table-scoped value is sourced from the policy’s existing table
identifier in the class.
🪄 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: 385f2aeb-705a-41f0-86b5-d5484db155e0
⛔ Files ignored due to path filters (3)
projects/postgres-rls/plan.mdis excluded by!projects/**projects/postgres-rls/slices/entity-kind-migration-seam/spec.mdis excluded by!projects/**projects/postgres-rls/specs/adr-schema-diff-over-structured-ir.mdis excluded by!projects/**
📒 Files selected for processing (26)
packages/1-framework/1-core/framework-components/src/control/schema-diff.tspackages/1-framework/1-core/framework-components/src/exports/control.tspackages/1-framework/1-core/framework-components/test/rls-layer-invariant.test.tspackages/1-framework/1-core/framework-components/test/schema-diff.test.tspackages/3-extensions/pgvector/test/migrations/planner.behavior.test.tspackages/3-extensions/pgvector/test/migrations/planner.contract-to-schema-ir.test.tspackages/3-extensions/pgvector/test/migrations/planner.storage-types.test.tspackages/3-targets/3-targets/postgres/src/core/migrations/planner.tspackages/3-targets/3-targets/postgres/src/core/migrations/project-postgres-schema-from-contract.tspackages/3-targets/3-targets/postgres/src/core/migrations/verify-postgres-rls-policies.tspackages/3-targets/3-targets/postgres/src/core/postgres-rls-policy.tspackages/3-targets/3-targets/postgres/src/core/postgres-role.tspackages/3-targets/3-targets/postgres/src/core/postgres-schema-ir.tspackages/3-targets/3-targets/postgres/src/exports/control.tspackages/3-targets/3-targets/postgres/test/migrations/project-postgres-schema-from-contract.test.tspackages/3-targets/3-targets/postgres/test/migrations/rls-planner.test.tspackages/3-targets/3-targets/postgres/test/rls-diffable-nodes.test.tspackages/3-targets/6-adapters/postgres/test/migrations/planner.authoring-surface.test.tspackages/3-targets/6-adapters/postgres/test/migrations/planner.codec-field-event.test.tspackages/3-targets/6-adapters/postgres/test/migrations/planner.cross-space-fk-ddl.test.tspackages/3-targets/6-adapters/postgres/test/migrations/planner.fk-config.test.tspackages/3-targets/6-adapters/postgres/test/migrations/planner.reconciliation.test.tspackages/3-targets/6-adapters/postgres/test/migrations/planner.referential-actions.test.tspackages/3-targets/6-adapters/postgres/test/migrations/planner.semantic-satisfaction.test.tspackages/3-targets/6-adapters/postgres/test/migrations/rls-migration-plan.integration.test.tstest/integration/test/cross-package/postgres-control-policy-planner.test.ts
migration plan
…dExtraIssues The tree-walking differ keys siblings by coordinate. A duplicate key silently overwrote the first node, dropping a real missing/extra/mismatch issue. Throw on a duplicate coordinate at both map-build sites so a future non-content-addressed node kind fails loudly instead of swallowing data. Add unit tests for both sides. Extract the owned-namespace filter as a generic, target-agnostic dropUnownedExtraIssues(issues, isOwned) helper next to the framework SchemaDiffIssue type, so issue-disposition lives in the framework control area rather than inside a Postgres RLS function. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
Rename the contract->IR derivation and the Postgres schema-diff strategy so the names say what they do, paralleling the family contractToSchemaIR they wrap: - projectPostgresSchemaFromContract -> contractToPostgresSchemaIR (file too) - diffPostgresRlsPolicies -> diffPostgresSchema (it is the Postgres schema-diff strategy; policies are just the only node kind in it today) (file too) - planRlsDiff -> planPostgresSchemaDiff diffPostgresSchema now calls the framework dropUnownedExtraIssues helper; the Postgres-specific UNBOUND->public namespace resolution stays in the caller, which builds the ownership predicate. Un-export collectContractRoles (no cross-module caller). Replace the bare contract narrowing cast in the contractToSchema hook with blindCast. Drop "post-seam" jargon and the transient "in this slice" phrasing from comments, stating the plain invariant instead. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
There was a problem hiding this comment.
🧹 Nitpick comments (1)
packages/3-targets/3-targets/postgres/src/core/migrations/contract-to-postgres-schema-ir.ts (1)
20-36: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueOptional: collapse the two near-identical namespace walks.
collectContractRolesandcollectContractRlsPoliciesdiffer only in the projected entry (ns.rolevsns.policy). A small shared traversal helper would remove the copy/paste, but this is a minor cleanup and fine to defer.🤖 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/migrations/contract-to-postgres-schema-ir.ts` around lines 20 - 36, The namespace traversal in collectContractRoles is duplicated with collectContractRlsPolicies, so factor the shared walk over contract.storage.namespaces into one helper and parameterize the extracted field (ns.role versus ns.policy). Keep contractToPostgresSchemaIR using the same helpers to build roles and rlsPolicies, but remove the copy/paste logic so the two projections share the same traversal.
🤖 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.
Nitpick comments:
In
`@packages/3-targets/3-targets/postgres/src/core/migrations/contract-to-postgres-schema-ir.ts`:
- Around line 20-36: The namespace traversal in collectContractRoles is
duplicated with collectContractRlsPolicies, so factor the shared walk over
contract.storage.namespaces into one helper and parameterize the extracted field
(ns.role versus ns.policy). Keep contractToPostgresSchemaIR using the same
helpers to build roles and rlsPolicies, but remove the copy/paste logic so the
two projections share the same traversal.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yml
Review profile: CHILL
Plan: Pro
Run ID: b261265c-9b28-414d-8e55-7c2f4e0b180a
📒 Files selected for processing (16)
packages/1-framework/1-core/framework-components/src/control/schema-diff.tspackages/1-framework/1-core/framework-components/src/exports/control.tspackages/1-framework/1-core/framework-components/test/schema-diff.test.tspackages/3-extensions/pgvector/test/migrations/planner.contract-to-schema-ir.test.tspackages/3-targets/3-targets/postgres/src/core/migrations/contract-to-postgres-schema-ir.tspackages/3-targets/3-targets/postgres/src/core/migrations/diff-postgres-schema.tspackages/3-targets/3-targets/postgres/src/core/migrations/planner.tspackages/3-targets/3-targets/postgres/src/core/postgres-rls-policy.tspackages/3-targets/3-targets/postgres/src/exports/control.tspackages/3-targets/3-targets/postgres/src/exports/planner.tspackages/3-targets/3-targets/postgres/test/migrations/contract-to-postgres-schema-ir.test.tspackages/3-targets/3-targets/postgres/test/migrations/diff-postgres-schema.test.tspackages/3-targets/3-targets/postgres/test/migrations/rls-planner.test.tspackages/3-targets/3-targets/postgres/test/rls-diffable-nodes.test.tspackages/3-targets/6-adapters/postgres/src/core/control-adapter.tspackages/3-targets/6-adapters/postgres/test/migrations/rls-migration-plan.integration.test.ts
✅ Files skipped from review due to trivial changes (1)
- packages/3-targets/3-targets/postgres/src/exports/planner.ts
🚧 Files skipped from review as they are similar to previous changes (6)
- packages/1-framework/1-core/framework-components/src/exports/control.ts
- packages/3-targets/3-targets/postgres/test/rls-diffable-nodes.test.ts
- packages/3-targets/6-adapters/postgres/test/migrations/rls-migration-plan.integration.test.ts
- packages/1-framework/1-core/framework-components/test/schema-diff.test.ts
- packages/3-targets/3-targets/postgres/test/migrations/rls-planner.test.ts
- packages/3-extensions/pgvector/test/migrations/planner.contract-to-schema-ir.test.ts
…gresSchemaIR - Define PostgresContract in target-postgres (postgres-schema.ts) and export it from @prisma-next/target-postgres/types - Re-export it from the adapter's types.ts instead of redefining it - Narrow contractToPostgresSchemaIR's contract parameter from Contract<SqlStorage> to PostgresContract - Update the blindCast in control.ts to target PostgresContract | null - Update makeContract in the test to return PostgresContract so the type flows through Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
There was a problem hiding this comment.
🧹 Nitpick comments (1)
packages/3-targets/6-adapters/postgres/src/core/types.ts (1)
34-34: 📐 Maintainability & Code Quality | 🔵 TrivialMove the
PostgresContractre‑export to the package'sexports/surface.The project guidelines prohibit cross-file re-exports outside of
exports/folders. The filepackages/3-targets/6-adapters/postgres/src/core/types.tsis an implementation file, yet it re-exportsPostgresContractfrom@prisma-next/target-postgres/types. This export is then re-exported bypackages/3-targets/6-adapters/postgres/src/exports/types.ts.To comply with the guidelines, remove this re-export from
core/types.tsand import/re-exportPostgresContractdirectly withinexports/types.ts.Current structure
src/core/types.ts
export type { PostgresContract } from '`@prisma-next/target-postgres/types`';src/exports/types.ts
// ... imports from ../core/typesFix
- Remove the line from
src/core/types.ts.- Add the following to
src/exports/types.ts:import type { PostgresContract } from '`@prisma-next/target-postgres/types`'; export type { PostgresContract };🤖 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/types.ts` at line 34, Move the PostgresContract re-export out of the implementation layer and into the exports surface: remove the export from core/types.ts, then in exports/types.ts import type PostgresContract directly from `@prisma-next/target-postgres/types` and re-export it there alongside the existing exports. Keep the change confined to the core/types.ts and exports/types.ts symbols so the package only exposes cross-file re-exports from the exports/ entrypoint.Source: Coding guidelines
🤖 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.
Nitpick comments:
In `@packages/3-targets/6-adapters/postgres/src/core/types.ts`:
- Line 34: Move the PostgresContract re-export out of the implementation layer
and into the exports surface: remove the export from core/types.ts, then in
exports/types.ts import type PostgresContract directly from
`@prisma-next/target-postgres/types` and re-export it there alongside the existing
exports. Keep the change confined to the core/types.ts and exports/types.ts
symbols so the package only exposes cross-file re-exports from the exports/
entrypoint.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yml
Review profile: CHILL
Plan: Pro
Run ID: c6ddd180-16e4-417a-9c19-b55055ad290f
📒 Files selected for processing (6)
packages/3-targets/3-targets/postgres/src/core/migrations/contract-to-postgres-schema-ir.tspackages/3-targets/3-targets/postgres/src/core/postgres-schema.tspackages/3-targets/3-targets/postgres/src/exports/control.tspackages/3-targets/3-targets/postgres/src/exports/types.tspackages/3-targets/3-targets/postgres/test/migrations/contract-to-postgres-schema-ir.test.tspackages/3-targets/6-adapters/postgres/src/core/types.ts
✅ Files skipped from review due to trivial changes (2)
- packages/3-targets/3-targets/postgres/src/exports/types.ts
- packages/3-targets/3-targets/postgres/src/core/postgres-schema.ts
🚧 Files skipped from review as they are similar to previous changes (3)
- packages/3-targets/3-targets/postgres/src/core/migrations/contract-to-postgres-schema-ir.ts
- packages/3-targets/3-targets/postgres/test/migrations/contract-to-postgres-schema-ir.test.ts
- packages/3-targets/3-targets/postgres/src/exports/control.ts
…ration-seam Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…ership; document coord() uniqueness N1: dropUnownedExtraIssues -> filterSchemaIssuesByOwnership, with a doc stating it filters only extra outcomes (missing/mismatch pass through regardless of ownership). N2: diffSchema -> diffSchemas (it compares two roots). N3: document the coordinate-uniqueness invariant on DiffableNode.coord() - coord() must be unique among siblings aligned at a level; the differ keys on it and a collision is the same entity (enforced by the duplicate-key throw). A kind unique only within a parent (a column within a table) folds its parent into the coordinate. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…on; trim diff JSDoc N4: move collectContractRlsPolicies/collectContractRoles out of the projection file into collect-contract-postgres-nodes.ts, and fix their docs to say "Collect" (they collect nodes, they do not project). Importers in contract-to-postgres-schema-ir.ts, diff-postgres-schema.ts, and the test now import from the new file. collectContractRlsPolicies stays cross-module; collectContractRoles is only used within the migrations folder. N5: trim the ~25-line JSDoc on diffPostgresSchema to one line on what it does plus one line that ownership is applied to outcomes, not inputs. N6/N7: extract one shared resolveNamespaceId (UNBOUND -> 'public') into postgres-schema.ts and route diff-postgres-schema.ts through it, dropping the local copy and POSTGRES_DEFAULT_NAMESPACE_ID. The annotations helper (resolves to introspected pgSchemaName, not the literal 'public') and resolveNamespaceIdForIssue (resolves to the unbound sentinel, used as a namespace-map key) are different resolutions and are left as-is. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…iqueness note Update diffSchema -> diffSchemas across the ADR and slice spec, and add the coordinate-uniqueness sentence to the ADR near the coord()/walk description (coord() must be unique among siblings aligned at a level; a kind unique only within its parent folds the parent into the coordinate). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…string, stableKey comment (R02/R04/R05) 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 root `diffSchemas` now takes two `DiffableNode`s (one per side) and calls `diffPair(expected, actual)` — which checks `isEqualTo`, then recurses into `diffChildren`. `DiffableRoot` is deleted; every node in the tree (including the database root) implements `DiffableNode`. `PostgresSchemaIR` gains `coord()` (database coordinate keyed on `pgSchemaName`), `isEqualTo` (always true — no database-level attributes yet), and `children()` (returns `rlsPolicies`). It now `implements DiffableNode` instead of the deleted `DiffableRoot`. `diffPostgresSchema` passes real `PostgresSchemaIR` nodes on both sides: expected via `contractToPostgresSchemaIR`, actual from the introspected `schema`. When `projectSchemaToSpace` returns a spread plain object (prototype methods absent), it is reconstructed as a class instance before being diffed. `collectContractRlsPolicies` is no longer imported at this call site — it is consumed internally by `contractToPostgresSchemaIR`. Slice spec and ADR updated to reflect the final single-node differ 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]>
…cal keys DiffableNode.coord(): EntityCoordinate → localKey(): string; a sibling-unique path segment the differ accumulates into a readonly string[] path on each issue. SchemaDiffIssue.coordinate → SchemaDiffIssue.path. filterSchemaIssuesByOwnership gains a getNamespaceId callback so callers supply namespace from the node, not the (now-removed) coordinate field. Fixes a real bug: PostgresRlsPolicy.coord() omitted the table, so two policies with the same prefix + body (same wire name) on different tables collided with a duplicate-key throw. localKey() = namespace/tableName/wireName is table-scoped and distinct. Regression test added to diff-postgres-schema.test.ts. Consumer updates: planner reads namespaceId/tableName/name off issue.expected / issue.actual (PostgresRlsPolicy nodes) instead of issue.coordinate; CLI tests and combine-schema-results.test use issue.path. ADR updated to describe the path-based model and record the EntityCoordinate alternative as rejected. 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 value is the node’s own identity among its siblings; the differ concatenating identities into a path is the differ’s concern, not the node’s. localKey/pathSegment encoded that consumer use; id() names the intrinsic property on the DiffableNode interface (review comment #3). Pure rename: same signature, same behavior, all impls and tests in lockstep. Node key composition unchanged (separate task). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
… caller-side whitelist Policies now nest under a PostgresTableNode (database root → table → policy), so a policy’s id() is just its wire name — unique among its table’s policies — instead of folding namespace/table into the key. Same-wire-name policies on different tables stay distinct via their table nodes. The framework differ becomes total: an unmatched non-leaf node emits its own issue and descends, emitting one per node in the missing/extra subtree. So an initial migration (every table missing) still surfaces the policies beneath the missing tables. Coalescing a parent change over its children is the planner’s job. Ownership and node-type selection leave the differ. diffPostgresSchema(expected, actual) takes two built IRs, runs the total diff, whitelists policy-subject issues (isPostgresRlsPolicy), and drops extra policies in namespaces expected does not own. filterSchemaIssuesByOwnership is removed from framework schema-diff.ts — the differ is pure. namespaceId is resolved to its DDL schema name once, at derivation (collectContractRlsPolicies), via the existing resolveDdlSchemaForNamespaceStorage, so expected and actual table nodes pair by id(). The degraded resolveNamespaceId duplicate is deleted. Also completes the coordinate→path migration missed in 6bd0f25: the family-sql filterSchemaDiffIssues test and the supabase skeleton test referenced the removed .coordinate field (CI Test + Type Check were red on that tip). Addresses review comments #2, #5, #6; #3 (id()) landed separately; #4 (rename the root off "IR") deferred as its own leveling change. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
… spec reconcile From the opus review of 5f16b73 (no correctness bugs found): - planner.ts: comment that issue.{expected,actual}.namespaceId is already a resolved DDL schema name, so the resolveDdlSchemaForNamespaceStorage re-call is a tolerated no-op (correct while PostgresSchema.ddlSchemaName() === id). - schema-diff.test.ts: rename the makeNode stub parameter localKey → nodeId so it does not read like a leftover of the renamed id() method. - spec: owned namespaces include expected.existingSchemas (all declared namespaces), so a declared-but-policy-less namespace stays owned — matches the implementation, which is the better definition. Document the unbound-namespace + non-default-search_path non-idempotency as a pre-existing, narrowed limitation. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
Postgres stamps a bare model into the explicit public namespace (the target defaultNamespaceId), not the unbound one — bound namespaces diff correctly regardless of search_path. The limitation applies only to the deliberate Postgres late-binding (unbound keyword) opt-in under a non-public current_schema(), and is partly inherent to late binding (schema unknown at authoring). Doc-only. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…t back-threaded introspection The fix for late-binding RLS is an authoring requirement: the unbound-namespace RLS opt-in must require the user to name the schema to bind to. That name becomes the expected IR; introspection is the actual; a mismatch is real drift. This keeps both sides independently derived (expected never reaches into the live DB), preserving the ADR separation — unlike threading introspected schema back into the contract derivation. Doc-only. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
Branch was 8 commits behind main; the PR had no mergeable ref so CI would not run. Conflicts were limited to 10 relational-planner test files, all in the import block: the slice rewrote them to build a PostgresSchemaIR (the planner now requires one as options.schema) while main refactored their namespace construction (buildSqlNamespace → postgresCreateNamespace). Bodies auto-merged; resolved each import block to the union of symbols the merged body uses. pnpm install reconciled the new deps main added (e.g. apps/lsp-playground). Full clean build + typecheck --force + the affected suites are green (framework-components 437, family-sql 378, cli 1330, target-postgres 478, adapter-postgres 660 +4 expected). No code-integration regressions — the implementer-reported failures were stale-dist / uninstalled-deps in this worktree, not the merge. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…uping CI Lint (biome --error-on-warnings) flagged three noNonNullAssertion in the table-node grouping. Restructure to a single Map<string, Group> keyed by namespace/table whose values hold schemaName/tableName/policies; keep the got-or-created group reference (no re-lookup) and map over Map.values() (insertion order) — no `!`, no casts, same first-seen grouping behavior. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
CI check:upgrade-coverage requires a per-PR declaration in the user upgrade skill when a PR touches examples/. The only examples/ change is the supabase walking-skeleton test tracking the internal RLS schema-diff refactor (coordinate→path, table nodes); the RLS diff surface is in development and the authored feature behaviour is unchanged. Declared incidental (changes: []). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
Addresses Will's round-5 review of PR #868. Tree at derivation (was: flat rlsPolicies + regroup in children()): - PostgresSchemaIR holds `tableNodes` built once at derivation; children() returns them directly. `rlsPolicies` is now a derived getter. - `groupPoliciesIntoTableNodes` is the single grouping site, called by both the contract derivation (collectContractRlsTableNodes) and live introspection (all PostgresSchemaIR sites in control-adapter, incl. the multi-schema merge). Ownership filtering leaves the differ (review): diffPostgresSchema runs the total diff + whitelist + message render only; `dropUnownedExtraPolicyIssues` is applied by the space-aware callers (planPostgresSchemaDiff, collectSchemaDiffIssues). User-facing rendering: policy diff messages render `policy "name" on "schema"."table"` (was a slash-joined path shown verbatim to users). DiffableNode.id is a property (getter), not a method. Plus: assertPostgresSchemaIR replaces the unreachable planner guard; redundant comment deleted; subtree emit uses flatMap; supabase test reads the issue's node id, not the path tail. Deferred (replied on thread): renaming PostgresSchemaIR off "IR" (61 refs; needs the database-vs-schema leveling decided). Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…ic layer) Round 4-5 synthesized a parallel `tableNodes` list by grouping policies, sitting next to the real `tables`. That was the mistake: the schema IR is already a tree and the table-IR instances are already the nodes — the PR only added the DiffableNode interface to make that tree walkable. - New `PostgresTableIR` (extends SqlSchemaIRNode, replicating SqlTableIR fields because SqlTableIR freezes in its constructor — same pattern as PostgresSchemaIR): carries `rlsPolicies`, `id` = table name, `children()` = its policies, `isEqualTo` trivially true (columns still diffed by the legacy relational path this round). - `PostgresSchemaIR.tables` is `Record<string, PostgresTableIR>`; `children()` returns `Object.values(this.tables)`; `rlsPolicies` is a derived getter. - The projection (contract + introspection) attaches each policy to its table, resolving the DDL schema name once per namespace. - Deleted: `PostgresTableNode`, `groupPoliciesIntoTableNodes`, the `tableNodes` field, and the mislabeled `collect-contract-postgres-nodes.ts` (roles inlined). - ifDefined for the policy normalization spreads. Resolves the "RLS table nodes" / "why both tables and tableNodes" / collect-file review comments: there is one table representation, and it is the node. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
… filter; assert on table-less policy Round-7 review cleanup (PR #868): - Move the Postgres schema-IR node classes into src/core/schema-ir/ (postgres-schema-ir, postgres-table-ir, postgres-rls-policy, postgres-role, postgres-schema-ir-annotations) so it reads as the schema-IR node family; postgres-schema.ts (the namespace facade) stays put. Imports updated. - Rename dropUnownedExtraPolicyIssues → filterIssuesByOwnership; planner local diffIssues → filteredDiffIssues. - contractToPostgresSchemaIR throws on a policy whose target table is absent from the schema IR (a malformed contract) instead of stubbing an empty table. The assert caught a malformed test fixture (a policy with no declared table) — fixed the fixture to declare its table. - ifDefined for the policy normalization spreads (carried from r6 cleanup). 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 differ and the schema-diff path are generic; the consumer side wrongly said "RLS". Rename the planner locals rlsCalls -> schemaDiffCalls and rlsPartition -> schemaDiffPartition; reword the "RLS policy drift" docs/comments to "schema drift". Document the policy whitelist in diffPostgresSchema as transitional (the generic differ walks the whole tree; non-policy issues are dropped only because the legacy relational verifier still owns table/column drift). Note that the display-only policy-reference render should route through the adapter SQL renderer if it grows. Delete a useless doc comment. No behaviour change. Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
At a glance
A SELECT policy authored in PSL:
prisma-next migration planused to refuse to plan it offline:Now it plans the policy with no database in reach:
The decision
A schema diff is computed between two derived schema IRs, walked as a tree. Each side is produced by a derivation — read from a contract, or introspected from a live database — and a generic differ walks the two trees, pairing nodes by coordinate and comparing them, while naming no node type of its own. Because both sides are the same derived shape, one comparison serves every command, and a target-contributed entity kind (here, a Postgres RLS policy) participates in all of them.
Design detail:
adr-schema-diff-over-structured-ir.md.Why
migration planwas brokenThe differ was being fed asymmetrically. On the live-database commands (
db init/db update/db verify) one side was a real introspectedPostgresSchemaIRwhile the diff reached into the contract object for the other. Butmigration planhas no database: it derives both sides from contracts, and that derivation dropped target-specific objects entirely — so policies were absent on both sides, and the planner failed loud rather than emit a migration that silently contained no RLS.This change removes the asymmetry: a Postgres contract now projects to a populated
PostgresSchemaIR, so both sides are homogeneous derived IRs on every command.What changed
schema-diff.ts).diffSchema(expected, actual)walks two roots; each node answerscoord()/isEqualTo()/children(). It recurses into matched pairs, so the diff keeps the IR's structure — the planner orders operations by how nodes relate (a role before the policy that names it, a table before its policies). The flatdiffNodesis gone; the node methodidentity()is renamedcoord(). RLS is one level deep today, so its diff output is unchanged.projectPostgresSchemaFromContract). The PostgrescontractToSchemahook returns a populatedPostgresSchemaIRinstead of a bare relational one.migration planfail-loud and the planner'sisPostgresSchemaIRcommand-branches are deleted — nothing downstream asks which command produced a side.public.*) is left alone by filtering the diff'sextraoutcomes, not by pre-filtering the tree.Scope
Deliberately deferred, each with its consequence:
Verification
build,typecheck, the package suite,lint:deps,fixtures:check, and e2e are green.portal "C_N" does not existflake that hops betweensql-orm-clienttests run-to-run and passes in isolation.migration plantest asserting the emittedCREATE POLICY/ENABLE ROW LEVEL SECURITYops.Slice spec:
slices/entity-kind-migration-seam/spec.md.Alternatives considered
migration plan) has no IR on that side at all. Deriving both sides to one shape makes every command uniform.🤖 Generated with Claude Code
Summary by CodeRabbit
diffSchemas) and wired it into Postgres RLS drift detection viadiffPostgresSchema.PostgresSchemaIR, rejecting non-Postgres inputs.