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

tml-2869: explicit RLS control — @@rls enablement, policy rename, per-table grading - #945

Merged
wmadden-electric merged 28 commits into
mainfrom
slice/explicit-rls-control
Jul 10, 2026
Merged

wmadden-electric merged 28 commits into
mainfrom
slice/explicit-rls-control

Conversation

@wmadden-electric

@wmadden-electric wmadden-electric commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor

What developers can rely on

RLS enablement is now something you declare, not a side effect of having a policy. A model marked @@rls is RLS-controlled; the marker — not the policy set — drives ENABLE/DISABLE ROW LEVEL SECURITY. Drop the last policy from an @@rls model and RLS stays on (deny-all, fail-closed); RLS turns off only when you remove the marker. A policy on an unmarked model is a load-time authoring error. Renaming a policy (same body, new name) plans as ALTER POLICY … RENAME TO instead of drop-and-recreate. All of this grades correctly under managed/external/tolerated control policies.

namespace public {
  model Profile {
    id       String @id @default(uuid())
    userId   String @unique
    username String
    @@rls
  }
  role appUser
  policy_select profiles_read_all { target = Profile; roles = [appUser]; using = "true" }
}

This is slice 3 of the postgres-rls project (TML-2869), the first behavior-bearing RLS slice on the one-differ substrate (#921). Enablement becomes the first real table-attribute diff through the generic differ.

The three behaviors

@@rls enablement, fail-closed. The marker lowers to a Postgres-only marker entity in the namespace's entries. Derivation stamps rlsEnabled on the expected table node from marker presence (never from the policy set); introspection stamps it from pg_class.relrowsecurity. The table node's isEqualTo now compares rlsEnabled, so a not-equal table issue plans ENABLE or a new destructive-classed DISABLE. The old imperative "enable when a table gains its first policy" path is deleted — which also fixes a real gap: a table whose policies are already in sync but whose RLS is off now re-enables.

Policy rename. A planner post-pass pairs a missing + extra policy issue on the same table whose content-hash suffixes match and prefixes differ, collapsing drop+create into one ALTER POLICY … RENAME TO. This falls straight out of content-addressed policy names — no predicate-body comparison anywhere. Rename is non-destructive: it plans without the destructive allowance (blocking it would defeat the "rename is free" guarantee).

Managed / external / tolerated grading. Proven per op across the matrix: external tables get no RLS ops and grade drift like any other external declared-shape drift; managed tables own their full RLS shape; tolerated tables admit enablement as a creation-class op.

Two generic framework SPIs (no RLS vocabulary below the target)

Targets couldn't contribute @@ model attributes at all, so @@rls needed a new seam:

  • AuthoringContributions.modelAttributes — a target-contributed declarative model-attribute slot, mirroring pslBlockDescriptors. The framework owns the generic consult; the contribution supplies the descriptor + lowering.
  • AuthoringPslBlockDescriptor.requiresModelAttribute — a declarative { parameter, attribute } constraint enforced by a generic pre-interpretation pass. This is how "a policy_* target must be @@rls-marked" is expressed without the framework or SQL family naming RLS. It's the only altitude that works: a block's lowering factory structurally cannot see another declaration's attributes.

The layering invariant held throughout — the framework-vocabulary ratchet is 836/836 at close, and pnpm lint:deps stays clean. Zero RLS symbols in 1-framework/2-sql.

⚠️ Breaking change for contract authors

A policy_* block whose target model lacks @@rls now fails contract emit with PSL_EXTENSION_TARGET_MODEL_MISSING_ATTRIBUTE. Every policy-bearing contract must add @@rls to its policy targets and re-emit (produces a new rls marker entity and storage hash). Upgrade instructions are recorded in both upgrade skills (transition 0.14-to-0.15), covering the authoring rule, the two new SPI surfaces, and the now-required PostgresTableSchemaNode.rlsEnabled / five-field AssembledAuthoringContributions.

Spec amendment adjudicated mid-slice: external + verify

The spec originally claimed external tables verify-suppress RLS drift. They don't: the framework's control-policy disposition suppresses only extras and value-drift under external — declared-shape incompatibilities fail, exactly like external column drift. The code follows the framework; the spec was corrected to match (51ce66767). Consequence for the extension-supabase project: an external table that genuinely runs RLS (Supabase auth.*) must declare @@rls as part of its declared shape, or verify fails. Plan-side, external tables are still never touched by any of the five RLS ops.

Verification

  • Walking-skeleton e2e (examples/supabase, live PGlite): a fail-closed probe (drop the last policy → verify clean → rows still denied under SET ROLE, no DISABLE planned) and a rename round-trip (prefix change → exactly one ALTER POLICY … RENAME TO → verify clean → policy still filters). Variant contract states are real PSL emitted through the CLI and guarded by fixtures:check.
  • Non-RLS op parity: a base-vs-HEAD real-plan() golden diff over the committed examples is byte-identical (ops + SQL preview) for both Postgres examples.
  • Full gate on the merged tree: build, forced typecheck, the whole Lint job (both ratchets), fixtures:check, test:packages / test:integration / test:e2e, the multi-space guards, and check:upgrade-coverage --mode pr.

Two small user-visible improvements ship incidentally: suppressed-enablement warnings now name enableRowLevelSecurity (was a synthetic alterTable), and enablement-op check SQL binds resolved DDL schemas (fixing an __unbound__ sentinel bug caught in-flight).

Review

16 code commits across 6 dispatches, 11 review rounds, 6 findings — all resolved, 0 open. Reviewed dispatch-by-dispatch (spec + plan + ledger under projects/postgres-rls/slices/explicit-rls-control/).

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features
    • Added explicit PostgreSQL row-level security control via the @@rls model attribute.
    • RLS enablement/disablement is now marker-driven and schema-aware, including fail-closed behavior.
    • Added support for safe RLS policy renames during migrations.
    • Extended authoring to support declarative @@ model attributes with validation and collision detection.
  • Documentation
    • Updated upgrade guidance for the new RLS and authoring requirements.
  • Tests
    • Expanded coverage for RLS lifecycle, renames, introspection, verification, and Supabase scenarios.

@@rls marker-driven ENABLE/DISABLE via the table-attribute diff, policy
rename via ALTER POLICY ... RENAME TO paired by content hash, and the
managed/external grading matrix. Six-dispatch plan following the
land-unconsumed-then-flip pattern from slice 2.5.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…ontributions

Adds AuthoringContributions.modelAttributes, a declarative descriptor slot
for target packs to contribute @@ model attributes, mirroring the existing
pslBlockDescriptors slot. The SQL PSL interpretation model-attribute loop
consults contributed descriptors (by bare attribute name) after the
built-in cases and before the PSL_UNSUPPORTED_MODEL_ATTRIBUTE fallthrough,
lowering parsed arguments into an entity filed under entries[attribute][key].

No RLS vocabulary is introduced in this dispatch; the slot is proven with
a test-only @@stamp fake contribution in contract-psl.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…rk surface (W1-F1)

Renames AuthoringModelAttributeContext.tableName to storageName: a
framework context type must not name a model storage object a "table".
Rewords the new jsdoc to drop "table", the "rls" example, and three
"SQL interpreter" mentions (the ratchet scans comments and camelCase-
splits identifiers). The interpreter maps its table name onto the
neutral storageName field; the fake-contribution tests pin that a
consumer reads storageName for both the entries key and its own
target-side name field.

pnpm lint:framework-vocabulary passes at the unchanged 836 threshold.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…riptors

A block descriptor may declare that the model named by one of its ref
parameters must carry a given bare @@ model attribute. The SQL
interpreter enforces the declaration over the parsed symbol table
(whole-document, order-independent) and emits
PSL_EXTENSION_TARGET_MODEL_MISSING_ATTRIBUTE naming the block and the
model. Missing parameters and unresolvable models stay the concern of
the existing missing-parameter/unresolved-ref diagnostics.

Framework and SQL layers stay vocabulary-neutral; proven with a fake
audit_rule/@@Audited contribution.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
The Postgres pack contributes an argument-less rls model attribute
through the modelAttributes slot; presence marks the model RLS-
controlled. It lowers to a PostgresRlsEnablement marker stored in
entries.rls[tableName], registered as an entity kind so serialization,
round-trip, and contract-infer omission ride the existing machinery
(kind-precision pinned: an rls entry in a described contract never
omits the same-named table).

The policy-requires-marker rule is enforced twice per spec D1: at PSL
load via requiresModelAttribute on policy_select (diagnostic naming the
model and the policy prefix, order-independent), and fail-loud at
contract-to-schema-node derivation beside the absent-table throw.

Every in-repo fixture that authors policies gains the marker
(postgres-target + adapter-postgres suites). @prisma-next/psl-parser is
promoted to a production dependency of the target for the ADR-231
modelAttribute() spec.

Known deferral to W6: examples/supabase authors a policy without @@rls
and now fails contract emit (fixtures:check) — examples are out of
scope for this change.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…fixtures gate honest)

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…W2-F1)

Rewords six sites to state the property instead of citing plan rows:
the policy-target comment in authoring.ts and the round-trip /
load-time / derivation test names. No behavior change.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Marks Profile RLS-controlled (its policy_select requires the marker
since the policy-requires-marker rule landed) and regenerates the
emitted contract via the fixtures pipeline: the contract gains the
rls marker entity and a new storage hash. No migration snapshots
churn; the example test suite is unchanged and green.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
PostgresTableSchemaNode gains a required rlsEnabled: boolean. Expected
side: contract-to-schema-node derivation stamps it from entries.rls
marker presence, never from the policy set. Actual side: adapter
introspection reads pg_class.relrowsecurity per table and stamps it;
the semantic-satisfaction normalization carries the actual value
through unchanged.

isEqualTo stays name-only and children() is unchanged, so the differ
does not see the attribute yet and planner/verify behavior is nil —
pinned by node tests. The field is required with no default, so every
construction site (derivation, introspection, normalization, tests
across target/adapter/pgvector/integration suites) supplies it
explicitly.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
The table listing (information_schema.tables, BASE TABLE) includes
partitioned parents (relkind p) and Postgres supports RLS on them, so
the rlsEnabled scan must cover relkind IN (r, p) — the r-only filter
plus the false fallback would stamp partitioned parents false and, once
the differ consumes the attribute, manufacture perpetual enable drift.
PGlite supports PARTITION BY, so the integration test pins a
partitioned parent introspecting rlsEnabled true.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Two op families land end-to-end with nothing planning them yet:

disableRowLevelSecurity — DisableRowLevelSecurityCall (destructive:
disabling RLS opens row access, so it requires the destructive
allowance exactly like dropRlsPolicy), op builder with
enabled-precheck/disabled-postcheck via rlsEnabledAst, a
PostgresDisableRowLevelSecurity DDL node with contract-free
constructor, and the adapter render hook emitting
ALTER TABLE ... DISABLE ROW LEVEL SECURITY.

renameRlsPolicy — RenamePostgresRlsPolicyCall (widening: the
established non-destructive class for in-place changes to existing
objects, so a rename plans without the destructive allowance), op
builder with old-name-present precheck and new-name-present postcheck,
a PostgresAlterPolicyRename DDL node, and the adapter render hook
emitting ALTER POLICY <old> ON <schema>.<table> RENAME TO <new>.

The inline wire-name parse in adapter introspection is promoted to
parseRlsPolicyWireName in the target rls module (returns prefix +
hash so the rename pairing pass can consume the hash); introspection
now uses it. No planner file is touched.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
RLS control now derives entirely from the marker + content hash.

PostgresTableSchemaNode.isEqualTo compares rlsEnabled alongside the
name — the first table-attribute comparison. The resulting table
not-equal issue routes through the relational pipeline:
mapTableNodeIssue gains the not-equal case, mapping expected
rlsEnabled to EnableRowLevelSecurityCall / DisableRowLevelSecurityCall,
so it rides the issue-level control-policy partition (external
suppresses with a warning), the per-call class gate (a disable without
the destructive allowance surfaces a loud conflict, never a silent
skip), and a new trailing rlsEnable emission bucket. A fresh
RLS-controlled table enables RLS as part of its creation bundle.
Enablement ops bind the resolved DDL schema (not the emission
sentinel) into their relrowsecurity checks, matching the retired
path for late-bound contracts.

The imperative enable-on-first-new-policy (seenEnableTables) is
deleted; the in-sync-policies-but-RLS-off table it missed now plans
ENABLE, pinned.

The policy half gains the rename post-pass: a not-found and a
not-expected policy on the same table whose wire-name hashes match and
prefixes differ collapse into one widening RenamePostgresRlsPolicyCall;
multi-candidate hash groups pair deterministically by sorted name,
leftovers and unparseable names proceed as create/drop. Pairing runs
only when widening is allowed — under additive-only it degrades
deliberately to a bare create of the new name, pinned.

Verify falls out generically: enablement drift grades as
declaredIncompatible per the table control policy. The AC matrix pins
one deliberate spec deviation: external declared-shape/existence RLS
drift FAILS verify (the framework disposition suppresses only extras
and value drift on external subjects — the same verdict external
column drift gets today); plan-side external suppression holds
everywhere.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…tional drift

The spec claimed external tables verify-suppress RLS drift; the framework
disposition under external suppresses only extras and value drift, and
declared-shape incompatibilities fail (same as external column drift).
The code follows the framework; the spec follows the code. An external
table that genuinely runs RLS declares @@rls as part of its shape.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
The flip suppressed the enablement issue for tolerated tables before
any call was built — created policies were left inert with RLS off,
anti-fail-closed. Restores the pre-flip outcome through the channel
that already defines tolerated admission: a table not-equal issue
whose expected side is RLS-controlled resolves the creation factory
name enableRowLevelSecurity (a member of OBJECT_CREATION_FACTORIES)
and marks its subject creation-class, so the issue partition admits it
exactly like the policy creates it guards. The opposite direction
(DISABLE) stays a modification: tolerated and external marker removal
plan nothing, pinned with warnings, and managed disable gating is
unchanged. Three new grading pins: tolerated enable, tolerated
enable+create-policy together, tolerated disable-suppression.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Two live-PGlite journeys on the supabase walking skeleton:

C (fail-closed): from the deployed state, remove the last policy from
the contract while keeping @@rls, db update plans exactly the policy
drop (no enablement change anywhere), verify is clean against the
policy-less contract, and a SET ROLE probe proves rows are DENIED —
RLS stays on with zero policies.

D (rename): change only the policy prefix (same content hash), db
update plans exactly one ALTER POLICY ... RENAME TO (no drop, no
create), applies, verifies clean, and the renamed policy still
filters rows per owner.

Contract variants are built by mutating a structuredClone of the
committed contract.json and recomputing the storage hash so markers,
ledger, and verify stay self-consistent through the journey.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
User skill (examples substrate): policy_select targets must declare
@@rls; re-emit gains the rls marker entity; marker-driven plan
semantics summarized (fail-closed, destructive-gated disable,
prefix-only rename).

Extension-author skill (3-extensions substrate): the same authoring
rule for extension contract spaces; PostgresTableSchemaNodeInput
rlsEnabled now required (isEqualTo compares it); the new
AuthoringContributions.modelAttributes slot (assembled shape is five
fields) and the requiresModelAttribute block-descriptor field.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Replaces the structuredClone-mutate-rehash harness with two committed
fixture states emitted by the real pipeline from variant PSL sources:
test/fixtures/no-policy (the schema minus its policy_select block,
@@rls kept) and test/fixtures/renamed-policy (the same policy body
under the prefix profile_owner_read_v2 — the emitter derives the same
content hash with the new wire name, which the test asserts). Each
variant has its own config; the example emit script now regenerates
both, so fixtures:check guards them like the main contract. The
probes import the fixture JSONs typed by their emitted d.ts — no raw
contract data is touched and the deserializeContract casts are gone.
Every probe assertion (exact plan op-id lists, per-space verify,
SET ROLE row visibility, pre-change sanity check) is unchanged.

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 July 10, 2026 07:41
@pkg-pr-new

pkg-pr-new Bot commented Jul 10, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@prisma-next/extension-author-tools

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

@prisma-next/mongo-runtime

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

@prisma-next/family-mongo

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

@prisma-next/sql-runtime

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

@prisma-next/family-sql

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

@prisma-next/extension-arktype-json

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

@prisma-next/middleware-cache

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

@prisma-next/mongo

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

@prisma-next/extension-paradedb

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

@prisma-next/extension-pgvector

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

@prisma-next/extension-postgis

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

@prisma-next/postgres

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

@prisma-next/sql-orm-client

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

@prisma-next/sqlite

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

@prisma-next/extension-supabase

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

@prisma-next/target-mongo

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

@prisma-next/adapter-mongo

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

@prisma-next/driver-mongo

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

@prisma-next/contract

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

@prisma-next/utils

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

@prisma-next/config

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

@prisma-next/errors

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

@prisma-next/framework-components

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

@prisma-next/operations

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

@prisma-next/ts-render

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

@prisma-next/contract-authoring

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

@prisma-next/ids

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

@prisma-next/psl-parser

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

@prisma-next/psl-printer

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

@prisma-next/cli

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

@prisma-next/cli-telemetry

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

@prisma-next/config-loader

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

@prisma-next/emitter

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

@prisma-next/language-server

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

@prisma-next/migration-tools

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

prisma-next

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

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

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

@prisma-next/mongo-codec

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

@prisma-next/mongo-contract

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

@prisma-next/mongo-value

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

@prisma-next/mongo-contract-psl

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

@prisma-next/mongo-contract-ts

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

@prisma-next/mongo-emitter

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

@prisma-next/mongo-schema-ir

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

@prisma-next/mongo-query-ast

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

@prisma-next/mongo-orm

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

@prisma-next/mongo-query-builder

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

@prisma-next/mongo-lowering

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

@prisma-next/mongo-wire

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

@prisma-next/sql-contract

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

@prisma-next/sql-errors

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

@prisma-next/sql-operations

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

@prisma-next/sql-schema-ir

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

@prisma-next/sql-contract-psl

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

@prisma-next/sql-contract-ts

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

@prisma-next/sql-contract-emitter

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

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

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

@prisma-next/sql-relational-core

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

@prisma-next/sql-builder

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

@prisma-next/target-postgres

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

@prisma-next/target-sqlite

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

@prisma-next/adapter-postgres

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

@prisma-next/adapter-sqlite

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

@prisma-next/driver-postgres

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

@prisma-next/driver-sqlite

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

commit: 14f1b4d

@github-actions

github-actions Bot commented Jul 10, 2026 •

Copy link
Copy Markdown

size-limit report 📦

Path Size
postgres / no-emit 154.11 KB (+0.43% 🔺)
postgres / emit 129.23 KB (+0.35% 🔺)
mongo / no-emit 98.55 KB (+0.2% 🔺)
mongo / emit 89.39 KB (0%)
cf-worker / no-emit 181.26 KB (+0.46% 🔺)
cf-worker / emit 153.93 KB (+0.33% 🔺)

@coderabbitai

coderabbitai Bot commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

Run ID: 7332ccce-e567-4f32-bcf7-33ec37ad0338

📥 Commits

Reviewing files that changed from the base of the PR and between e78f887 and 14f1b4d.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (11)
  • packages/3-targets/3-targets/postgres/src/core/authoring.ts
  • packages/3-targets/3-targets/postgres/src/core/migrations/diff-database-schema.ts
  • packages/3-targets/3-targets/postgres/src/core/postgres-contract-serializer.ts
  • packages/3-targets/3-targets/postgres/src/core/postgres-schema.ts
  • packages/3-targets/3-targets/postgres/src/exports/types.ts
  • packages/3-targets/3-targets/postgres/test/postgres-namespace-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.enum-adoption.test.ts
  • packages/3-targets/3-targets/postgres/test/psl-infer/infer-psl-contract.test.ts
  • packages/3-targets/6-adapters/postgres/src/core/control-adapter.ts
  • skills/extension-author/prisma-next-extension-upgrade/upgrades/0.14-to-0.15/instructions.md
💤 Files with no reviewable changes (1)
  • packages/3-targets/3-targets/postgres/src/core/postgres-schema.ts
✅ Files skipped from review due to trivial changes (1)
  • packages/3-targets/3-targets/postgres/test/postgres-namespace-schema-node.test.ts
🚧 Files skipped from review as they are similar to previous changes (8)
  • packages/3-targets/3-targets/postgres/test/psl-infer/infer-psl-contract.test.ts
  • packages/3-targets/3-targets/postgres/test/psl-infer/fixtures.ts
  • packages/3-targets/3-targets/postgres/src/exports/types.ts
  • packages/3-targets/3-targets/postgres/src/core/migrations/diff-database-schema.ts
  • skills/extension-author/prisma-next-extension-upgrade/upgrades/0.14-to-0.15/instructions.md
  • packages/3-targets/3-targets/postgres/src/core/authoring.ts
  • packages/3-targets/3-targets/postgres/src/core/postgres-contract-serializer.ts
  • packages/3-targets/6-adapters/postgres/src/core/control-adapter.ts

📝 Walkthrough

Walkthrough

This change introduces explicit PostgreSQL RLS control through the @@rls model attribute. It adds model-attribute authoring, RLS markers and schema state, enable/disable and policy-rename planning, adapter support, Supabase fixtures, integration tests, and upgrade guidance.

Changes

Explicit RLS control

Layer / File(s) Summary
Model-attribute authoring and lowering
packages/1-framework/..., packages/2-sql/..., packages/3-targets/...
Authoring contributions now support model attributes, including @@rls; descriptors can require attributes and the interpreter lowers contributed attributes into namespace entries.
Contract and schema representation
packages/3-targets/3-targets/postgres/src/core/...
Postgres contracts serialize RLS enablement markers, while table schema nodes carry and compare explicit rlsEnabled state.
Migration operations and planning
packages/3-targets/3-targets/postgres/src/core/migrations/...
Planning supports marker-driven enable/disable operations and deterministic policy renames based on wire-name hashes.
Adapter and verification support
packages/3-targets/6-adapters/postgres/...
Postgres introspection reads RLS state, and adapter rendering supports disabling RLS and renaming policies with parameterized verification checks.
Supabase fixtures and end-to-end coverage
examples/supabase/...
Generated no-policy and renamed-policy contracts support fail-closed and policy-rename integration scenarios.
Compatibility and upgrade guidance
skills/..., test/...
Existing fixtures provide explicit RLS state and upgrade instructions document @@rls, rlsEnabled, and modelAttributes changes.

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

Possibly related PRs

Suggested reviewers: aqrln, wmadden, jkomyno

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 38.98% 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
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title is concise and accurately reflects the main change set: explicit RLS control via @@rls, policy renames, and grading.
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.
✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch slice/explicit-rls-control

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.

coderabbitai[bot]
coderabbitai Bot previously requested changes Jul 10, 2026

@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: 4

🤖 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 `@examples/supabase/test/skeleton.integration.test.ts`:
- Around line 579-581: Replace the interpolated ownerSub value in the
pgClient.query call with a bind parameter, passing the JWT claims JSON as a
query parameter while preserving the set_config behavior.

In
`@packages/1-framework/1-core/framework-components/src/shared/framework-authoring.ts`:
- Around line 905-919: Remove the redundant hasKind variable and its use from
collectModelAttributeEntries; retain the malformed-descriptor check based on
typeof record['attribute'] === 'string' and 'spec' in record, while preserving
the existing error behavior and traversal.

In
`@packages/3-targets/3-targets/postgres/test/migrations/rls-disable-rename-ops.test.ts`:
- Around line 11-20: Update recordingCheckLowerer() or the OLD_NAME assertion to
use the real Postgres lowerer, or render SQL from the captured AST, instead of
always returning synthetic LOWERED SQL. Ensure the assertion can observe whether
policy names are parameterized in params rather than interpolated into SQL.

In `@projects/postgres-rls/slices/explicit-rls-control/spec.md`:
- Line 88: Update the AC-4 (rename) wording in spec.md by replacing “verifies
clean afterwards” with “verifies clean afterward.”
🪄 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: Organization UI

Review profile: ASSERTIVE

Plan: Pro

Run ID: 2481e576-96d7-4f86-8d11-92e4753bfc4b

📥 Commits

Reviewing files that changed from the base of the PR and between 09a6ce0 and f714cdd.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (86)
  • examples/supabase/package.json
  • examples/supabase/src/contract.d.ts
  • examples/supabase/src/contract.json
  • examples/supabase/src/contract.prisma
  • examples/supabase/test/fixtures/no-policy.config.ts
  • examples/supabase/test/fixtures/no-policy/contract.d.ts
  • examples/supabase/test/fixtures/no-policy/contract.json
  • examples/supabase/test/fixtures/no-policy/contract.prisma
  • examples/supabase/test/fixtures/renamed-policy.config.ts
  • examples/supabase/test/fixtures/renamed-policy/contract.d.ts
  • examples/supabase/test/fixtures/renamed-policy/contract.json
  • examples/supabase/test/fixtures/renamed-policy/contract.prisma
  • examples/supabase/test/skeleton.integration.test.ts
  • packages/1-framework/1-core/framework-components/src/control/control-stack.ts
  • packages/1-framework/1-core/framework-components/src/exports/authoring.ts
  • packages/1-framework/1-core/framework-components/src/shared/framework-authoring.ts
  • packages/1-framework/1-core/framework-components/test/control-stack.model-attributes.test.ts
  • packages/1-framework/1-core/framework-components/test/control-stack.test.ts
  • packages/1-framework/3-tooling/cli/test/config-types.test.ts
  • packages/2-mongo-family/2-authoring/contract-psl/test/provider.test.ts
  • packages/2-mongo-family/2-authoring/contract-ts/test/config-types.test.ts
  • packages/2-sql/2-authoring/contract-psl/src/interpreter.ts
  • packages/2-sql/2-authoring/contract-psl/test/fixtures.ts
  • packages/2-sql/2-authoring/contract-psl/test/interpreter.block-attribute-requirements.test.ts
  • packages/2-sql/2-authoring/contract-psl/test/interpreter.model-attributes.test.ts
  • packages/2-sql/2-authoring/contract-ts/test/config-types.test.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-targets/3-targets/postgres/package.json
  • packages/3-targets/3-targets/postgres/src/contract-free/ddl.ts
  • packages/3-targets/3-targets/postgres/src/core/authoring.ts
  • packages/3-targets/3-targets/postgres/src/core/ddl/nodes.ts
  • packages/3-targets/3-targets/postgres/src/core/descriptor-meta.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/control-policy.ts
  • packages/3-targets/3-targets/postgres/src/core/migrations/diff-database-schema.ts
  • packages/3-targets/3-targets/postgres/src/core/migrations/issue-planner.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/postgres-contract-serializer.ts
  • packages/3-targets/3-targets/postgres/src/core/postgres-rls-enablement.ts
  • packages/3-targets/3-targets/postgres/src/core/postgres-schema.ts
  • packages/3-targets/3-targets/postgres/src/core/postgres-validators.ts
  • packages/3-targets/3-targets/postgres/src/core/rls/wire-name.ts
  • packages/3-targets/3-targets/postgres/src/core/schema-ir/postgres-table-schema-node.ts
  • packages/3-targets/3-targets/postgres/src/exports/ddl.ts
  • packages/3-targets/3-targets/postgres/src/exports/rls-canonicalize.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/node-issue-planner.test.ts
  • packages/3-targets/3-targets/postgres/test/migrations/planner.sibling-scoping.test.ts
  • packages/3-targets/3-targets/postgres/test/migrations/rls-disable-rename-ops.test.ts
  • packages/3-targets/3-targets/postgres/test/migrations/rls-enablement-planner.test.ts
  • packages/3-targets/3-targets/postgres/test/migrations/rls-planner.test.ts
  • packages/3-targets/3-targets/postgres/test/migrations/rls-rename-planner.test.ts
  • packages/3-targets/3-targets/postgres/test/migrations/rls-verdict-matrix.test.ts
  • packages/3-targets/3-targets/postgres/test/migrations/verdict-table-less-namespace.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-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-described-contracts.test.ts
  • packages/3-targets/3-targets/postgres/test/psl-infer/infer-psl-contract.test.ts
  • packages/3-targets/3-targets/postgres/test/psl-policy-authoring.test.ts
  • packages/3-targets/3-targets/postgres/test/psl-rls-authoring.test.ts
  • packages/3-targets/3-targets/postgres/test/rls-wire-name.test.ts
  • packages/3-targets/3-targets/postgres/test/schema-node-subject-granularity.test.ts
  • packages/3-targets/6-adapters/postgres/src/core/control-adapter.ts
  • packages/3-targets/6-adapters/postgres/test/ddl-rls-lowering.test.ts
  • packages/3-targets/6-adapters/postgres/test/migrations/planner.reconciliation.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
  • packages/3-targets/6-adapters/postgres/test/migrations/rls-verify-extension-issues.integration.test.ts
  • packages/3-targets/6-adapters/postgres/test/migrations/rls-walking-skeleton-psl.integration.test.ts
  • packages/3-targets/6-adapters/postgres/test/migrations/rls-walking-skeleton.integration.test.ts
  • projects/postgres-rls/slices/explicit-rls-control/plan.md
  • projects/postgres-rls/slices/explicit-rls-control/spec.md
  • skills/extension-author/prisma-next-extension-upgrade/upgrades/0.14-to-0.15/instructions.md
  • skills/upgrade/prisma-next-upgrade/upgrades/0.14-to-0.15/instructions.md
  • test/integration/test/cross-package/postgres-control-policy-planner.test.ts
  • test/integration/test/cross-package/postgres-issue-planner.test.ts

…uthoring SPIs

- AC-4 wording afterwards→afterward (CodeRabbit)
- record the modelAttributes/requiresModelAttribute ADR as a project
  close-out obligation (PR #945 architect review A1/A2)

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…collision

Two interpreter robustness fixes from PR review:

- Extract duplicateModelAttributeDiagnostic({name, modelName, sourceId,
  span}) so the PSL_DUPLICATE_ATTRIBUTE code and "declared more than
  once" wording live in one place, used by both the built-in @@control
  path and the contributed-model-attribute path (was hand-constructed
  twice).
- The model-attribute-entities merge into a namespace threw nothing on
  a slot collision: a model-attribute entries key colliding with a
  base slot (table/valueSet) or a block-produced kind would silently
  shallow-replace. Now it fails loud at composition. Disjoint today
  (rls vs policy/role/valueSet/table); pinned with a block+attribute
  collision test that asserts the throw.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Adds formatRlsPolicyWireName(prefix, hash) beside parseRlsPolicyWireName
in wire-name.ts and points authoring.ts at it instead of the inline
`${prefix}_${wireHash}` template, so the `<prefix>_<hash>` format is
expressed in exactly one place. Pins a format-then-parse round-trip.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Both set_config('request.jwt.claims', ...) sites interpolated the
owner uuid into SQL. Switch to SELECT set_config($1, $2, false) with
[key, JSON.stringify({ sub })] bind params. SET ROLE authenticated is a
fixed literal (no interpolation) — swept, these were the only two.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…eck (CR)

Reaching the sub-namespace branch means isAuthoringModelAttributeDescriptor
returned false, so kind === "modelAttribute" is impossible there. Remove
the dead hasKind; keep the attribute + spec malformed check and its throw.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
The op-level tests use a recording lowerer that stubs SQL, so their
`precheck.sql not.toContain(name)` assertions were vacuous. Export
rlsPolicyExistsAst / rlsEnabledAst from contract-free and add real tests
in adapter-postgres verification-checks-lowering that render through the
actual adapter lowerer and prove a dangerous policy name binds as $3
(in params, absent from the SQL text). Replace the vacuous op-level
assertions with a pointer comment; the received-AST assertions still pin
which check is lowered.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…rwise (F01)

mapTableNodeIssue and isEnablementCreationIssue assumed any table
not-equal IS enablement drift — true only while rlsEnabled is the single
attribute in PostgresTableSchemaNode.isEqualTo. Key both on the actual
expected-vs-actual rlsEnabled delta: ENABLE on off->on, DISABLE on
on->off, and a not-equal with no rlsEnabled delta fails loud
("unhandled table-attribute drift") rather than emitting a bogus
enable/disable. isEnablementCreationIssue admits creation-class only on
the off->on delta. Pins the fail-loud path via a directly-constructed
equal-rlsEnabled table not-equal.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…pology (F02)

Two in-code docs, no behavior change:
- The relrowsecurity scan stays a separate query from the table listing.
  Folding it in would swap information_schema.tables (grant-filtered) for
  a raw pg_class scan (not), shifting WHICH tables introspect — a real
  behavior change, live-only, uncatchable by the offline golden diff. The
  comment states the fail-safe invariant: a missed table defaults to
  RLS-off, worst case a spurious idempotent ENABLE, never a DISABLE.
- RenamePostgresRlsPolicyCall operationClass=widening is the accepted
  typology tradeoff (plans under every allowance except additive-only
  init; the vocabulary has no neutral class), not because a rename
  widens anything.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>

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

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
packages/2-sql/2-authoring/contract-psl/src/interpreter.ts (1)

2173-2180: 🗄️ Data Integrity & Integration | 🟠 Major | ⚡ Quick win

Reject duplicate lowered entity keys before merging.

declaredContributedModelAttributes only prevents duplicates on one model. If two models in the same namespace lower the same attribute to the same key, Line 2177 silently overwrites the first entity. The later entry-slot check only detects slot collisions, not collisions within a slot. Detect duplicate keys before the spread and add a two-model regression test.

🤖 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/2-sql/2-authoring/contract-psl/src/interpreter.ts` around lines 2173
- 2180, Reject duplicate lowered entity keys before merging
modelAttributeEntitiesByNamespace: in the aggregation logic around the
result.modelAttributeEntities merge, detect when an attribute’s keyed entry
already contains the same key from another model in the namespace and raise the
appropriate duplicate-key error instead of allowing the spread to overwrite it.
Preserve valid merges of distinct keys, and add a regression test covering two
models in one namespace lowering the same attribute to the same key.
🤖 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.

Outside diff comments:
In `@packages/2-sql/2-authoring/contract-psl/src/interpreter.ts`:
- Around line 2173-2180: Reject duplicate lowered entity keys before merging
modelAttributeEntitiesByNamespace: in the aggregation logic around the
result.modelAttributeEntities merge, detect when an attribute’s keyed entry
already contains the same key from another model in the namespace and raise the
appropriate duplicate-key error instead of allowing the spread to overwrite it.
Preserve valid merges of distinct keys, and add a regression test covering two
models in one namespace lowering the same attribute to the same key.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

Run ID: c2bf1734-4906-4e6b-8997-abfe0ffc1431

📥 Commits

Reviewing files that changed from the base of the PR and between f714cdd and e78f887.

⛔ Files ignored due to path filters (2)
  • projects/postgres-rls/slices/explicit-rls-control/spec.md is excluded by !projects/**
  • projects/postgres-rls/spec.md is excluded by !projects/**
📒 Files selected for processing (16)
  • examples/supabase/test/skeleton.integration.test.ts
  • packages/1-framework/1-core/framework-components/src/shared/framework-authoring.ts
  • packages/2-sql/2-authoring/contract-psl/src/interpreter.ts
  • packages/2-sql/2-authoring/contract-psl/test/interpreter.model-attributes.test.ts
  • packages/3-targets/3-targets/postgres/src/core/authoring.ts
  • packages/3-targets/3-targets/postgres/src/core/migrations/control-policy.ts
  • packages/3-targets/3-targets/postgres/src/core/migrations/issue-planner.ts
  • packages/3-targets/3-targets/postgres/src/core/migrations/op-factory-call.ts
  • packages/3-targets/3-targets/postgres/src/core/rls/wire-name.ts
  • packages/3-targets/3-targets/postgres/src/exports/contract-free.ts
  • packages/3-targets/3-targets/postgres/test/migrations/node-issue-planner.test.ts
  • packages/3-targets/3-targets/postgres/test/migrations/rls-disable-rename-ops.test.ts
  • packages/3-targets/3-targets/postgres/test/migrations/rls-ops.test.ts
  • packages/3-targets/3-targets/postgres/test/rls-wire-name.test.ts
  • packages/3-targets/6-adapters/postgres/src/core/control-adapter.ts
  • packages/3-targets/6-adapters/postgres/test/verification-checks-lowering.test.ts
🚧 Files skipped from review as they are similar to previous changes (8)
  • packages/3-targets/3-targets/postgres/src/core/migrations/control-policy.ts
  • packages/3-targets/3-targets/postgres/src/core/migrations/op-factory-call.ts
  • examples/supabase/test/skeleton.integration.test.ts
  • packages/3-targets/3-targets/postgres/src/core/authoring.ts
  • packages/3-targets/3-targets/postgres/test/migrations/rls-disable-rename-ops.test.ts
  • packages/3-targets/6-adapters/postgres/src/core/control-adapter.ts
  • packages/1-framework/1-core/framework-components/src/shared/framework-authoring.ts
  • packages/3-targets/3-targets/postgres/src/core/migrations/issue-planner.ts

@wmadden-electric
wmadden-electric added this pull request to the merge queue Jul 10, 2026
@github-merge-queue
github-merge-queue Bot removed this pull request from the merge queue due to a conflict with the base branch Jul 10, 2026
…ntrol

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>

# Conflicts:
#	skills/extension-author/prisma-next-extension-upgrade/upgrades/0.14-to-0.15/instructions.md
…ge fix)

The native-enum PRs (#941/#944/#946) added
infer-psl-contract.enum-adoption.test.ts, which constructs a
PostgresTableSchemaNode; this slice made rlsEnabled a required field, so
the merged tree failed the (now stricter, per #941) typecheck. Supply
rlsEnabled: false at the one construction site — the same mechanical
ripple every other construction site in this slice already carries.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
@wmadden-electric
wmadden-electric added this pull request to the merge queue Jul 10, 2026
Merged via the queue into main with commit 1aae135 Jul 10, 2026
29 of 30 checks passed
@wmadden-electric
wmadden-electric deleted the slice/explicit-rls-control branch July 10, 2026 14:25
paulwer pushed a commit to paulwer/prisma-next that referenced this pull request Jul 12, 2026
…iation pass (prisma#947)

## Linked issue

Refs [TML-2991](https://linear.app/prisma-company/issue/TML-2991) (slice
2.6 of
[postgres-rls](https://linear.app/prisma-company/project/postgres-rls-b7329340dbb2)).
Between slice 2.5 (`one-differ-two-ir-planner`,
[prisma#921](prisma#921)) and slice 3
(`explicit-rls-control`,
[prisma#945](prisma#945)).

## At a glance

The schema differ compares two derived schema-IR trees and does
**nothing else** — no pre-diff pass that transforms a tree to make the
verdict come out "satisfied". This PR deletes the one place that
violated that:

```diff
 export function diffSqliteSchema(input: { … }) {
-  const expected = neutralizeFlatExpectedFkSchemas(
-    normalizeActualForSatisfaction(contractToSchemaIR(input.contract, { … })),
-  );
-  const actual = normalizeFlatActualForDiff(expected, introspect(input.db));
-  return diffSchemas(expected, actual);
+  const expected = contractToSchemaIR(input.contract);
+  return diffSchemas(expected, introspect(input.db));
 }
```

`diff-tree-normalization.ts` — the 211-line
`resolveSemanticSatisfaction` reconciliation pass — is gone.

## Decision

A unique constraint (`pg_constraint`) and an index (`pg_index`) are
**different schema elements** — different catalog, different DDL,
independent lifecycle. They stay two structural nodes (`SqlUniqueIR`,
`SqlIndexIR`), exactly as primary keys, foreign keys, and check
constraints are already separate nodes. The debt slice 2.5 left behind
was not the two node kinds — it was the pre-diff pass that *massaged*
the actual tree to fake "semantic satisfaction" (a live unique index
silently counting as a declared unique constraint, and vice-versa).

1. **Delete the reconciliation pass.** `resolveSemanticSatisfaction` /
`normalizeFlatActualForDiff` and the caller-less
`isUniqueConstraintSatisfied` / `isIndexSatisfied` are removed; both
diff paths run `diffSchemas(expected, actual)` on the trees as derived.
2. **Keep the two nodes.** `SqlIndexIR.isEqualTo` becomes purely
symmetric structural equality — `unique === unique && type === type &&
options` — dropping the "stronger-satisfies-weaker" rule. No
`constraint` marker, no merging, no dedupe, no fail-loud rule: none is
needed once the two elements are honestly two nodes.
3. **Resolve the FK referenced-namespace from the namespace node, at
derivation.** The FK schema-segment normalization (the other, unrelated
half of the deleted file) moves into derivation — but *not* via a flag.
"Does this database have namespaces?" is answered by asking the
namespace node (`NamespaceBase.isUnbound`), never by comparing an
`__unbound__` string. An FK targeting the unbound namespace stamps no
referenced-namespace (matching what flat introspection produces, so the
two sides' FK ids meet by construction); a bound one stamps it as
before. No pre-diff normalization pass survives, and the sentinel string
never enters the schema-IR layer. (The broader sweep — routing the ~15
remaining `id === UNBOUND_NAMESPACE_ID` consumers through `isUnbound`
and banning the literal — is tracked as
[TML-2997](https://linear.app/prisma-company/issue/TML-2997); this PR
lands the seam.)

## Behavior change

Deleting satisfaction makes a unique-vs-index mismatch plain structural
drift (verdicts and planner ops flip only for the mismatch cases; the
general strict/lenient extra-tolerance and cross-space ownership are
untouched — `schema-verify.ts` is byte-identical to `main`):

- contract `@@unique` vs a live unique **index** → **fails** (constraint
`missing` + index `extra`).
- contract `@@index` vs a live unique **constraint** → **fails**.
- contract `@@index` vs a live unique **index** (both indexes, differ on
`unique`) → **recreate** (`indexIncompatible`) — a plain and a unique
index are genuinely different objects.
- a stray, undeclared live unique index → an ordinary **extra**
(strict-fails, lenient-passes), like any other extra.
- contract `@@unique` vs the live unique **constraint** it created (the
normal round-trip) → **clean**.

The planner needs no new code: a mismatch is a `missing` node plus an
`extra` node, which its existing independent `SqlUniqueIR` /
`SqlIndexIR` arms map to drop-the-extra + create-the-missing, with the
existing control-policy disposition suppressing the drop under an
additive policy.

## Reviewer notes

- **This supersedes an earlier approach on this branch.** An initial
attempt merged unique and index into a single node with a `constraint`
boolean. That merge — two schema elements in one node keyed by column
tuple — forced *new* tree-massaging back in (an introspection dedupe and
a fail-loud derivation rule) to avoid id collisions, which is the exact
anti-pattern the slice exists to remove. It was discarded; this is the
corrected, deletion-dominated design. If you saw the prior force-pushed
history, ignore it.
- **The fence.** `git diff main --
packages/2-sql/9-family/src/core/diff/schema-verify.ts` is **empty**.
The verdict grading, control-policy disposition, and cross-space
ownership are byte-unchanged; the behavior flips fall out purely of the
node model, not the grading.
- **One fixture edited** — `sqlite/.../runner.across-spaces.test.ts`
declared both `@@unique` and `@@index` on `email` but its hand-written
DDL created only `email TEXT UNIQUE`. It passed before *only* because
satisfaction masked the missing index. Added `CREATE INDEX` so the live
schema honestly carries both declared elements.
- **FK namespace identity is now node behavior.**
`NamespaceBase.isUnbound` is added as the single encapsulated place the
`__unbound__` sentinel is compared; derivation reads it instead of the
string. The Postgres target re-stamps `referencedSchema ??
UNBOUND_NAMESPACE_ID` for its own REFERENCES-clause DDL (keeping
Postgres byte-identical — proven by `fixtures:check` clean); that lone
sentinel-as-value in the target layer is the kind of thing TML-2997
sweeps up.
- **Rebased through slice 3.**
[prisma#945](prisma#945) (RLS control) and
native-enums merged into `main` mid-flight and touched these files. This
branch rebased onto them: our reconciliation deletion and slice-3's
`rlsEnabled`/`nativeEnums` coexist (deleting the actual-tree-rebuild
function is *safer* than merging — the introspected tree flows to the
differ unmodified, RLS/enum data intact). The full RLS suite is green on
the new base.
- **Deletion-dominated.** `SqlUniqueIR` and `SqlIndexIR` are otherwise
unchanged from `main`; both planners are untouched.

## Verification

Run on final HEAD (rebased onto current `main`):

- `pnpm build`, `pnpm typecheck` — clean.
- `pnpm lint:deps`, `pnpm lint`, `pnpm lint:casts`, `pnpm
lint:framework-vocabulary`, `pnpm check:upgrade-coverage --mode pr` —
pass.
- `pnpm fixtures:check` — no drift.
- `pnpm test:packages` — pass (only the known macOS
`/var`→`/private/var` config-loader symlink flake).
- `pnpm test:integration`, `pnpm test:e2e` (109/109) — green (documented
environmental flakes only; each passes in isolation).
- The four multi-space guards — pass, untouched.
- **RLS suites (slice 3, now in the base)** — target-postgres RLS units
104/104, RLS + cross-space integration 19/19 (incl.
`runner.unbound-namespace`, which drives the `isUnbound` path end-to-end
on live PGlite). Our deletions do not disturb RLS.

## Alternatives considered

- **Merge unique and index into one node** (a `SqlIndexIR` with a
`constraint` flag). Rejected — it conflates two distinct catalog
elements into one node keyed by column tuple, which cannot represent a
unique constraint and a same-column index at once, forcing an
introspection dedupe and a fail-loud contract rule to paper over the
collision. That re-introduces the tree-massaging this slice removes.
- **Preserve the satisfaction semantics.** Rejected — "a stronger live
object satisfies a weaker declared one" is a fuzzy "sometimes different
is fine" rule requiring a pre-diff pass or classifier special-cases.
Plain structural equality is simpler and more correct: if the projected
schema and the live schema disagree on a matched object, that is drift.

## Skill update

One extension-author upgrade entry recorded
(`schema-ir-fk-unbound-referenced-schema-absent`, 0.14→0.15):
`contractToSchemaIR` no longer stamps `referencedSchema` for an FK
targeting the unbound namespace (identity is read via
`NamespaceBase.isUnbound`); target tree re-builders default with `??
UNBOUND_NAMESPACE_ID`. No public API/CLI/config surface change and the
emitted contract is unchanged; the behavior change is to `db verify` /
`migration plan` drift **semantics** for unique-vs-index mismatches,
documented above.

## Checklist

- [x] All commits are signed off (`git commit -s`) per the DCO.
- [x] I read CONTRIBUTING.md and the change is scoped to one logical
concern.
- [x] Tests are updated.
- [x] The PR title is in `TML-NNNN: <title>` form.
- [x] The Skill update section is filled in.

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

## Summary by CodeRabbit

* **New Features**
* Added clearer namespace identity handling for foreign keys, improving
schema matching across bound and unbound namespaces.
* Added structural validation for unique constraints and indexes,
including migration planning coverage.

* **Bug Fixes**
* Unique constraints and indexes are now compared symmetrically,
preventing mismatches from being treated as equivalent.
* Schema verification and migration planning now produce more accurate
results without legacy normalization behavior.

* **Documentation**
* Added upgrade guidance for foreign keys targeting unbound namespaces.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
tensordreams pushed a commit to prisma/orm that referenced this pull request Jul 28, 2026
…ject artifacts (#979)

## Linked issue

Refs [TML-2501](https://linear.app/prisma-company/issue/TML-2501) —
close-out of the [Postgres
RLS](https://linear.app/prisma-company/project/postgres-rls-b7329340dbb2)
Linear project (now Completed).

## At a glance

All eight postgres-rls slices are merged (final:
[#959](prisma/prisma-next#959), TS RLS
authoring). Per the [`projects/` lifecycle](projects/README.md), this PR
performs the close-out: promote the long-lived docs into `docs/`, strip
the one repo reference into the project directory, and delete
`projects/postgres-rls/`.

Three commits, in lifecycle order:

1. **Promote** — ADR 234 (content-addressed wire names), ADR 235 (schema
differ over two derived IRs), ADR 236 (target-contributed model
attributes, the ADR the project DoD deferred to close-out), and a new
RLS section in the Adapters & Targets subsystem doc.
2. **Strip** — the supabase README pointer into `projects/postgres-rls/`
re-pointed at ADR 234 + the subsystem section (it also named the
pre-decision `.rls(...)` surface; now names the shipped one).
3. **Delete** — `projects/postgres-rls/` (spec, plan, handoff, slice
specs/plans, dispatches, trace).

## Project DoD verification

| DoD item (spec § Definition of Done) | Status | Evidence |
| --- | --- | --- |
| TS + PSL author the same policies to structurally identical IR with
identical wire names; helpers invisible off-Postgres | Met |
[#959](prisma/prisma-next#959):
`ts-psl-rls-parity.test.ts`, byte-identical parity fixture,
`rls-helper-invisibility.test.ts` |
| TS `ref()` predicate helper | Struck | Operator veto at slice-5 review
(2026-07-13): predicates are opaque strings on both surfaces; recorded
in the spec before deletion |
| Full lifecycle on live PGlite through the generic differ (create /
drop / rename via `ALTER POLICY … RENAME TO` / enable) | Met |
[#771](prisma/prisma-next#771) (lifecycle),
[#921](prisma/prisma-next#921) (one differ),
[#945](prisma/prisma-next#945) (rename, `@@rls`,
grading) |
| Declared role absent from `pg_roles` fails verify even under `control:
'external'` | Met |
[#950](prisma/prisma-next#950);
`examples/supabase/test/skeleton.integration.test.ts` case G |
| Walking skeleton: `examples/supabase` Profile policies filter rows
under `SET ROLE`, verifier diffs clean | Met |
[#950](prisma/prisma-next#950) capstone +
[#959](prisma/prisma-next#959) TS-authored
skeleton (`rls-ts-walking-skeleton.integration.test.ts`) |
| Zero RLS vocabulary in framework / SQL-family layers | Met |
`lint:deps` + `lint:framework-vocabulary` green on every slice;
structural invariant test |
| Content-addressed-naming ADR promoted to `docs/architecture
docs/adrs/`; adapter subsystem doc gains an RLS section | Met | **This
PR** — ADR 234 + § Row-Level Security in `5. Adapters & Targets.md` |
| ADR for the slice-3 authoring SPIs (`modelAttributes`,
`requiresModelAttribute`) | Met | **This PR** — ADR 236 |

## Final retro (mandatory at close)

- **Held:** the content-addressed-naming thesis survived every slice
unchanged — the wire name stayed the only equivalence relation, and
rename detection fell out free. One lowering (predicate matrix + hash
assembly) now serves both authoring surfaces.
- **Surprised:** the project spent slices 1.5–2.6 rebuilding the
diff/verify substrate it needed to stack on — the RLS features
themselves (3, 4, 5) were small once the substrate held. Review
repeatedly caught new mechanisms duplicating existing capability
(opRender vs CodecRegistry, coordinate structs, per-factory validation);
the standing probe is now "grep for the existing primitive before
accepting a new one".
- **Lessons landed:** `docs/onboarding/fixtures-emit-and-check.md`
(fixtures:check does not cover planner ops); the per-factory PSL
validation gaps became
[TML-3023](https://linear.app/prisma-company/issue/TML-3023) instead of
a fourth patch.
- **Deferred scope, all ticketed or assigned:**
[TML-3023](https://linear.app/prisma-company/issue/TML-3023)
(block-descriptor validator + PSL prefix cap),
[TML-2958](https://linear.app/prisma-company/issue/TML-2958)
(PSL-inference tree-walk),
[TML-2936](https://linear.app/prisma-company/issue/TML-2936)
(annotations bag),
[TML-2974](https://linear.app/prisma-company/issue/TML-2974) (native
per-space verify render); dependency-aware planner ordering and
codec-ops-on-the-differ get tickets when prioritized.

## Classification (audit trail)

- **Long-lived, migrated with rewrite:**
`specs/adr-content-addressed-policy-names.md` → ADR 234 (authoring
examples updated from the rejected `.rls([...])` surface to the shipped
`policyUpdate(...)` / `policy_update` forms);
`specs/adr-schema-diff-over-structured-ir.md` → ADR 235 (differ
vocabulary updated to the shipped `not-found | not-expected | not-equal`
reasons, property-form `DiffableNode`, the real node tree with roles on
the database root; superseded "table nodes are groupers only" section
dropped).
- **Long-lived, authored at close:** ADR 236 (per the DoD item deferred
from the PR #945 review).
- **Transient, deleted:** `spec.md`, `plan.md`, `HANDOFF.md`,
`trace.jsonl`, `slices/**` (per-slice specs/plans/dispatches), and the
remaining `specs/*` shaping docs (`design-*`, `brief-*`,
`reconciliation-*`, `extension-migration-participation.md`) —
shaping/coordination artifacts whose surviving content is the shipped
state and the promoted ADRs.

## Reference strip

One external reference existed
(`packages/3-extensions/supabase/README.md`); re-pointed. Post-delete
rescan of tracked files for `projects/postgres-rls` is empty.

## Checklist

- [x] Every commit is DCO signed-off
- [x] Docs-only — no behavior change
- [x] Linear project referenced (TML-2501)
🤖 Generated with [Claude Code](https://claude.com/claude-code)


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

## Summary by CodeRabbit

* **Documentation**
* Added architecture guidance for comparing schema representations and
reporting structured differences.
* Documented target-contributed model attributes and declarative
validation rules.
* Expanded PostgreSQL Row-Level Security documentation, including policy
naming, verification, and SQL migration actions.
* Updated Supabase documentation and RLS examples to reflect current
authoring conventions.

<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[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