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

tml-2870: author RLS policies for every operation, and verify declared roles exist - #950

Merged
wmadden-electric merged 20 commits into
mainfrom
slice/rls-policy-operations-and-roles
Jul 12, 2026
Merged

wmadden-electric merged 20 commits into
mainfrom
slice/rls-policy-operations-and-roles

Conversation

@wmadden-electric

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

Copy link
Copy Markdown
Contributor

Until now you could write exactly one kind of Row-Level Security policy in PSL: a SELECT policy. This PR lets you write all of them, and makes the roles your policies name something db verify checks for.

namespace public {
  model Profile { id String @id; userId String; username String; @@rls }

  // read: anyone may see the public directory; you may always see your own row
  policy_select profile_public_read { target = Profile; roles = [anon];          using = "true" }
  policy_select profile_owner_read  { target = Profile; roles = [authenticated]; using = "userId::uuid = auth.uid()" }

  // write: you may update your own row, and may not hand it to someone else
  policy_update profile_owner_write {
    target = Profile; roles = [authenticated]
    using     = "userId::uuid = auth.uid()"   // which rows you may target
    withCheck = "userId::uuid = auth.uid()"   // what the row may look like afterward
  }
}

The decision

Two things, both scoped deliberately:

  1. Every RLS operation is authorable, not just SELECT. New PSL keywords policy_insert, policy_update, policy_delete, and policy_all, each taking the predicates Postgres allows for that operation, with withCheck for the write-shape constraint.
  2. A role your contract declares is verified to exist — but never created or dropped. db verify fails if a declared role is missing from the database; it leaves a role you didn't declare completely alone. Role provisioning is out of scope, on purpose (more on why below).

Everything else follows from those two choices.

Policy operations

The four new keywords are the only new authoring surface — the machinery underneath was already operation-aware. Slice 3 shipped operation and withCheck on the policy IR, folded both into the content-addressed policy name, and taught the DDL renderer to emit FOR <op> and WITH CHECK (…). So a policy_update gets rename detection, drift verification, and managed/external grading for free, exactly like a policy_select — this PR is almost entirely the keywords and the tests that pin each operation's lifecycle.

Each keyword accepts only the predicates its operation supports, and enforces that at author time: SELECT/DELETE take using, INSERT takes withCheck, UPDATE/ALL take both. Writing using on a policy_insert is a load-time error, not a silently-ignored field.

Roles in verify, and why the diff is asymmetric

A contract can name roles (in a policy's roles = [...]). This PR makes a declared role a thing the verifier checks: introspect pg_roles, compare against the roles the contract declares, and report the difference.

The subtlety is that the comparison is deliberately one-directional:

  • A role the contract declares but the database lacks → db verify fails, under every control policy, external included. You asked for a role that isn't there.
  • A role the database has but the contract doesn't declare → ignored. Never a failure, never dropped, under any policy.

That asymmetry is the whole point, and it's a real design decision rather than a shortcut. A Postgres role is a cluster-wide object shared across databases and applications — your monitoring role, replication role, other teams' roles. A contract does not own the cluster's role list the way a managed table owns its policy set, so "the contract is missing role X, therefore drop X" would delete access other systems depend on. Roles are referenced, not owned.

We expressed that in the diff engine as a new, generic reference subject granularity — the dual of the existing structural one. A structural subject is one the contract owns (its extras fail verify); a reference subject is one the contract names but doesn't own (its extras are tolerated, but a missing declared one still fails). The Postgres target classifies its role nodes as reference; the SQL family handles the granularity generically and never learns what a role is. Because roles aren't owned, they also produce zero migration operations — adding them to the diff changes no plan.

The framework change that made the keywords possible

One structural thing had to move in the framework first. Its PSL-block extension SPI was hard-wired one-keyword-to-one-storage-kind, but five policy_* keywords need to land in one policy entity kind. So a PSL block now carries a keyword (its parse identity) separately from its discriminator (its storage identity), letting many keywords share one kind while each still round-trips to its own keyword. It's a generic capability — proven in the tests with a fake shape_circle/shape_square → shape contribution, no RLS vocabulary involved — and it's the same shape as the target-contributed-attribute SPI from the previous slice.

Proof: the Supabase walking skeleton

examples/supabase now runs the example above end-to-end against live PGlite. Under a manual SET ROLE authenticated, the test shows the write path actually enforces WITH CHECK: updating your own row's username succeeds, and trying to reassign the row's userId to another owner is rejected by Postgres. The rejection is constructed so USING passes (the row is yours to target) but WITH CHECK fails (the post-image isn't yours) — so it proves WITH CHECK, not just row selection. It also shows anon seeing every profile, authenticated seeing only its own, and a declared-but-absent role failing verify.

Compatibility

Additive and non-breaking. Existing SELECT-only or role-free schemas emit and verify byte-for-byte identically, and a base-vs-HEAD golden diff of real planner output confirms no migration operation changed. No consumer action is required.

Alternatives considered

  • Provisioning roles (CREATE ROLE / DROP ROLE). Rejected. Symmetric role management would mean a managed contract drops every cluster role it doesn't declare — deleting roles other databases and systems own. It's also more code (a whole op family) than the existence-only path, and CREATE ROLE from today's name-only role IR would produce an attribute-less role you then can't verify. Role provisioning, if ever wanted, is create-only and needs role attributes first — a separate effort.
  • Treating roles as structural (like policies). Rejected — that would fail verify (and, under managed, drop) an undeclared live role, which is exactly the cluster-shared-object hazard above. The reference/structural split is what keeps policy extras failing while role extras are tolerated.
  • A single policy { operation = … } block instead of per-operation keywords. Rejected — the declarative block SPI requires a fixed parameter set per block, so a conditional body isn't expressible; per-operation keywords give each a fixed, unconditional shape.
  • A distinct storage kind per policy keyword. Rejected — it would fragment the one policy entity slot every downstream consumer (serializer, differ, verify) reads, for no benefit. Separating keyword from discriminator keeps one storage kind.

Known gaps, tracked separately

  • You can't yet declare a role in PSL or the TS builder — role declarations belong to the Supabase extension pack (which owns anon/authenticated), and this PR references roles by name. It builds the verification mechanism; the declaring surface is a follow-on.
  • The framework's generic extension-block parameter validator isn't wired into the interpreter — so unknown or missing parameters on any extension block pass silently today. This PR enforces the RLS predicate rules directly in its own lowering as a narrow workaround; wiring the general validator is spun off as its own task.

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features
    • Expanded PostgreSQL RLS lowering and DDL to support policy_insert, policy_update, policy_delete, and policy_all, with operation-correct USING/WITH CHECK handling.
    • Added role “control” support for contract-defined roles (defaults to external) and improved role-aware verification.
    • PSL extension blocks now preserve the authored keyword through parse/print, including cases where multiple keywords share the same block type.
  • Documentation
    • Clarified extension wiring and role verification behavior.
  • Tests
    • Updated and added coverage for RLS predicate behavior, contract-to-schema planning, and role existence verification.

@wmadden-electric
wmadden-electric requested a review from a team as a code owner July 11, 2026 11:02
@coderabbitai

coderabbitai Bot commented Jul 11, 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: 1bbe2411-2519-4177-9054-c99b5f255108

📥 Commits

Reviewing files that changed from the base of the PR and between 81edcf7 and 72a1032.

📒 Files selected for processing (14)
  • docs/architecture docs/adrs/ADR 225 - Three-layer extensibility for pack-contributed entity kinds.md
  • packages/1-framework/1-core/framework-components/src/shared/framework-authoring.ts
  • packages/1-framework/1-core/framework-components/test/control-stack.test.ts
  • packages/1-framework/2-authoring/psl-printer/src/serialize-print-document.ts
  • packages/1-framework/2-authoring/psl-printer/test/generic-extension-block-printer.test.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/planner.ts
  • packages/3-targets/3-targets/postgres/src/core/postgres-role.ts
  • packages/3-targets/3-targets/postgres/src/core/postgres-validators.ts
  • packages/3-targets/3-targets/postgres/test/migrations/rls-planner.test.ts
  • packages/3-targets/3-targets/postgres/test/postgres-contract-serializer.test.ts
  • packages/3-targets/3-targets/postgres/test/rls-ir-kinds.test.ts
  • packages/3-targets/6-adapters/postgres/test/migrations/rls-role-verify.integration.test.ts
🚧 Files skipped from review as they are similar to previous changes (4)
  • docs/architecture docs/adrs/ADR 225 - Three-layer extensibility for pack-contributed entity kinds.md
  • packages/3-targets/6-adapters/postgres/test/migrations/rls-role-verify.integration.test.ts
  • packages/1-framework/1-core/framework-components/test/control-stack.test.ts
  • packages/3-targets/3-targets/postgres/test/migrations/rls-planner.test.ts

📝 Walkthrough

Walkthrough

This change preserves authored PSL keywords across parsing, lowering, and printing; adds PostgreSQL RLS policy operations with predicate validation; models roles in schema diffs and verification; and updates Supabase examples, tests, ADRs, and upgrade documentation.

Changes

PSL extension routing

Layer / File(s) Summary
Keyword-preserving extension metadata and dispatch
packages/1-framework/..., packages/1-framework/2-authoring/..., docs/architecture/...
PslExtensionBlock retains the authored keyword, descriptor uniqueness is keyword-based, shared discriminators are supported, and printing dispatches by keyword while validating the discriminator.
Routing and printer validation coverage
packages/1-framework/*/test/..., packages/1-framework/3-tooling/..., packages/2-*/..., packages/3-targets/...
Parser, grouping, printer, enum, native-enum, and declarative block tests now provide and verify keyword metadata.

PostgreSQL RLS and roles

Layer / File(s) Summary
RLS policy operations
packages/3-targets/3-targets/postgres/src/core/authoring.ts, packages/3-targets/3-targets/postgres/test/..., packages/3-targets/6-adapters/postgres/test/...
policy_insert, policy_update, policy_delete, and policy_all lower to dynamic operations with compatible using and withCheck predicates, distinct hashes, and corresponding SQL clauses.
Role schema planning and verification
packages/3-targets/3-targets/postgres/src/core/migrations/..., packages/3-targets/3-targets/postgres/src/core/schema-ir/..., packages/3-targets/3-targets/postgres/test/...
Root schema children include roles, role diffs resolve as external verification subjects, relational planning excludes role operations, and tests cover missing and undeclared roles.

Supabase examples and documentation

Layer / File(s) Summary
Supabase RLS contracts and integration tests
examples/supabase/src/..., examples/supabase/test/...
Profile contracts add anonymous public reads and authenticated owner updates, while integration tests verify public reads, WITH CHECK enforcement, policy drops, and missing-role verification.
Architecture and upgrade documentation
docs/architecture/..., skills/upgrade/...
ADR text and upgrade notes document keyword/discriminator routing, additional RLS operations, predicate behavior, and role verification semantics.

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

Sequence Diagram(s)

sequenceDiagram
  participant PSL
  participant PostgresAuthoring
  participant MigrationPlanner
  participant PostgresAdapter
  participant Database
  PSL->>PostgresAuthoring: parse policy_<op> with predicates
  PostgresAuthoring->>MigrationPlanner: lower operation and policy fields
  MigrationPlanner->>PostgresAdapter: build migration operations
  PostgresAdapter->>Database: execute CREATE or DROP POLICY SQL
  Database->>PostgresAdapter: expose policy and role state for verification
Loading

Possibly related PRs

Suggested reviewers: wmadden, aqrln

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 38.10% 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 accurately summarizes the main changes: expanded RLS policy authoring and verification of declared roles.
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/rls-policy-operations-and-roles

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.

@pkg-pr-new

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

Copy link
Copy Markdown

Open in StackBlitz

@prisma-next/extension-author-tools

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

@prisma-next/mongo-runtime

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

@prisma-next/family-mongo

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

@prisma-next/sql-runtime

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

@prisma-next/family-sql

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

@prisma-next/extension-arktype-json

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

@prisma-next/middleware-cache

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

@prisma-next/mongo

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

@prisma-next/extension-paradedb

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

@prisma-next/extension-pgvector

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

@prisma-next/extension-postgis

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

@prisma-next/postgres

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

@prisma-next/sql-orm-client

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

@prisma-next/sqlite

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

@prisma-next/extension-supabase

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

@prisma-next/target-mongo

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

@prisma-next/adapter-mongo

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

@prisma-next/driver-mongo

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

@prisma-next/contract

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

@prisma-next/utils

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

@prisma-next/config

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

@prisma-next/errors

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

@prisma-next/framework-components

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

@prisma-next/operations

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

@prisma-next/ts-render

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

@prisma-next/contract-authoring

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

@prisma-next/ids

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

@prisma-next/psl-parser

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

@prisma-next/psl-printer

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

@prisma-next/cli

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

@prisma-next/cli-telemetry

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

@prisma-next/config-loader

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

@prisma-next/emitter

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

@prisma-next/language-server

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

@prisma-next/migration-tools

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

prisma-next

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

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

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

@prisma-next/mongo-codec

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

@prisma-next/mongo-contract

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

@prisma-next/mongo-value

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

@prisma-next/mongo-contract-psl

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

@prisma-next/mongo-contract-ts

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

@prisma-next/mongo-emitter

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

@prisma-next/mongo-schema-ir

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

@prisma-next/mongo-query-ast

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

@prisma-next/mongo-orm

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

@prisma-next/mongo-query-builder

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

@prisma-next/mongo-lowering

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

@prisma-next/mongo-wire

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

@prisma-next/sql-contract

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

@prisma-next/sql-errors

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

@prisma-next/sql-operations

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

@prisma-next/sql-schema-ir

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

@prisma-next/sql-contract-psl

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

@prisma-next/sql-contract-ts

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

@prisma-next/sql-contract-emitter

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

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

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

@prisma-next/sql-relational-core

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

@prisma-next/sql-builder

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

@prisma-next/target-postgres

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

@prisma-next/target-sqlite

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

@prisma-next/adapter-postgres

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

@prisma-next/adapter-sqlite

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

@prisma-next/driver-postgres

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

@prisma-next/driver-sqlite

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

commit: 2011d74

@github-actions

github-actions Bot commented Jul 11, 2026 •

Copy link
Copy Markdown

size-limit report 📦

Path Size
postgres / no-emit 154.63 KB (+0.34% 🔺)
postgres / emit 129.6 KB (+0.27% 🔺)
mongo / no-emit 98.64 KB (+0.08% 🔺)
mongo / emit 89.41 KB (0%)
cf-worker / no-emit 181.79 KB (+0.28% 🔺)
cf-worker / emit 154.3 KB (+0.24% 🔺)

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

Caution

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

⚠️ Outside diff range comments (1)
packages/1-framework/1-core/framework-components/test/control-stack.test.ts (1)

421-469: 🎯 Functional Correctness | 🟡 Minor | ⚡ Quick win

Exercise N:1 across separate contributions.

Both tests pass a single createDescriptor(...) containing two entries, so they only exercise collisions within one contribution. Build one descriptor per createDescriptor(...) in the array to verify duplicate-keyword rejection and same-discriminator/different-keyword acceptance across the actual assembly boundary.

🤖 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/test/control-stack.test.ts`
around lines 421 - 469, Update both tests around assembleAuthoringContributions
so each pslBlockDescriptors entry is supplied by a separate
createDescriptor(...) in the contributions array. Preserve the existing
duplicate-keyword rejection assertion for policyA/policyB and the non-throwing
N:1 assertion for shapeCircle/shapeSquare, ensuring both behaviors are validated
across separate contributions.
🤖 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 `@docs/architecture` docs/adrs/ADR 225 - Three-layer extensibility for
pack-contributed entity kinds.md:
- Line 25: The ADR’s dispatch description incorrectly states that the
discriminator routes in both directions. Update the paragraph describing
parsing, lowering, and printing so parsing/lowering use the discriminator while
printing selects the descriptor by the block’s keyword, explicitly preserving
the shared-discriminator behavior and the existing naming convention.

In
`@packages/1-framework/2-authoring/psl-printer/src/serialize-print-document.ts`:
- Around line 22-60: Update the block validation logic in the printer around the
keyword lookup and discriminator checks to require the selected descriptor’s
discriminator to equal extensionBlock.kind directly. Remove the now-redundant
discriminators field, collection parameter, and related set population from
PslBlockDispatchMap, buildPslBlockDispatchMap, and collectBlockDescriptors while
preserving keyword-based descriptor lookup.

In
`@packages/3-targets/3-targets/postgres/src/core/schema-ir/postgres-role-schema-node.ts`:
- Around line 16-37: The ROLE_ID_SIGIL scheme in PostgresRoleSchemaNode can
collide with verbatim namespace ids such as role:public. Reserve the role:
prefix during namespace-id validation, or change role-id encoding to remain
collision-free; preserve existing role naming behavior and add a regression test
covering the quoted namespace name case.

---

Outside diff comments:
In `@packages/1-framework/1-core/framework-components/test/control-stack.test.ts`:
- Around line 421-469: Update both tests around assembleAuthoringContributions
so each pslBlockDescriptors entry is supplied by a separate
createDescriptor(...) in the contributions array. Preserve the existing
duplicate-keyword rejection assertion for policyA/policyB and the non-throwing
N:1 assertion for shapeCircle/shapeSquare, ensuring both behaviors are validated
across separate contributions.
🪄 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: 218836c3-9b7f-4972-ae1b-37a4b8c8aef6

📥 Commits

Reviewing files that changed from the base of the PR and between 813bc5a and e3c26d6.

⛔ Files ignored due to path filters (3)
  • projects/postgres-rls/plan.md is excluded by !projects/**
  • projects/postgres-rls/slices/rls-policy-operations-and-roles/plan.md is excluded by !projects/**
  • projects/postgres-rls/slices/rls-policy-operations-and-roles/spec.md is excluded by !projects/**
📒 Files selected for processing (43)
  • docs/architecture docs/adrs/ADR 126 - PSL top-level block SPI.md
  • docs/architecture docs/adrs/ADR 225 - Three-layer extensibility for pack-contributed entity kinds.md
  • examples/supabase/src/contract.d.ts
  • examples/supabase/src/contract.json
  • examples/supabase/src/contract.prisma
  • 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/rls-role-binding.integration.test.ts
  • examples/supabase/test/skeleton.integration.test.ts
  • packages/1-framework/1-core/framework-components/src/control/control-capabilities.ts
  • packages/1-framework/1-core/framework-components/src/shared/framework-authoring.ts
  • packages/1-framework/1-core/framework-components/src/shared/psl-extension-block.ts
  • packages/1-framework/1-core/framework-components/test/control-stack.test.ts
  • packages/1-framework/1-core/framework-components/test/framework-components.authoring.test.ts
  • packages/1-framework/1-core/framework-components/test/psl-ast.test.ts
  • packages/1-framework/1-core/framework-components/test/psl-extension-block-validator.test.ts
  • packages/1-framework/2-authoring/psl-parser/src/block-reconstruction.ts
  • packages/1-framework/2-authoring/psl-parser/test/symbol-table.test.ts
  • packages/1-framework/2-authoring/psl-printer/src/serialize-print-document.ts
  • packages/1-framework/2-authoring/psl-printer/test/generic-extension-block-printer.test.ts
  • packages/1-framework/3-tooling/cli/test/commands/contract-infer.command.test.ts
  • packages/2-mongo-family/9-family/test/authoring-entity-types.enum.test.ts
  • packages/2-sql/9-family/src/core/diff/schema-verify.ts
  • packages/2-sql/9-family/test/authoring-entity-types.enum.test.ts
  • 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/migrations/planner.ts
  • packages/3-targets/3-targets/postgres/src/core/psl-infer/infer-psl-contract.ts
  • packages/3-targets/3-targets/postgres/src/core/schema-ir/postgres-database-schema-node.ts
  • packages/3-targets/3-targets/postgres/src/core/schema-ir/postgres-role-schema-node.ts
  • packages/3-targets/3-targets/postgres/src/core/schema-ir/schema-node-kinds.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/rls-planner.test.ts
  • packages/3-targets/3-targets/postgres/test/postgres-database-schema-node.test.ts
  • packages/3-targets/3-targets/postgres/test/psl-rls-operations.test.ts
  • packages/3-targets/3-targets/postgres/test/schema-ir-leaf-nodes.test.ts
  • packages/3-targets/3-targets/postgres/test/schema-node-subject-granularity.test.ts
  • packages/3-targets/6-adapters/postgres/test/ddl-rls-lowering.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-role-verify.integration.test.ts
  • skills/upgrade/prisma-next-upgrade/upgrades/0.14-to-0.15/instructions.md

@wmadden-electric wmadden-electric changed the title tml-2870: RLS all policy operations + role verify (rls-policy-operations-and-roles) tml-2870: author RLS policies for every operation, and verify declared roles exist Jul 11, 2026
Roles become diffable off the database root (existence-only, never
provisioned): a declared role absent from pg_roles fails verify even
under external; a live undeclared role is tolerated; role issues order
before the policy that references them (dependency-graph seed). Most
substrate already exists (introspection + projection) — the slice is the
children() flip + asymmetric grading + planner zero-ops + leaves-first.
Three-dispatch land-handling-then-flip plan.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…cy-operations-and-roles

Role verify alone was too small once dependency ordering was cut (off the
RLS critical path). Merge it with all-policy-types: both additive, no new
architecture, shared walking-skeleton capstone (UPDATE-own needs
policy_update + roles). Renumber TS authoring to slice 5. Follow-on B
(dependency-aware planner: kill the integer buckets, stamp deps on the
issue, topo-sort) detached from slice 4 and recorded standalone.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
The PSL extension-block SPI assumed one keyword maps to exactly one
discriminator. That assumption blocks any target from contributing
several keywords that share one entity kind (e.g. several policy
keywords that should all lower to one `policy` entity) — the
uniqueness check rejected the second registration outright, and the
printer had no way to tell the keywords apart when emitting them back.

Separate the block's source keyword (its parse-dispatch identity) from
its discriminator (its storage/entity-kind identity):

- `PslExtensionBlock` gains `keyword`, alongside the existing `kind`
  (discriminator).
- `reconstructExtensionBlock` sets both, instead of only `kind`.
- `serializeExtensionBlock` looks up the descriptor by `keyword` and
  prints the block's own `keyword`, while still confirming the block's
  `kind` matches a registered discriminator.
- `assertUniqueDiscriminators` (used for pslBlock uniqueness) is keyed
  on `keyword`, the parser's real dispatch key, instead of
  discriminator — two descriptors may now share a discriminator (and
  therefore one entity factory and one `entries` slot) as long as their
  keywords are distinct.

No target vocabulary is introduced; a fake `shape_circle`/`shape_square`
N:1 contribution exercises the new composition, parse, and print paths.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
The Postgres target only exposed `policy_select`. Add the other four RLS
operations as PSL block descriptors — `policy_insert`, `policy_update`,
`policy_delete`, and `policy_all` — each beside `policy_select` and all
sharing the `policy` discriminator (one entity kind, one factory), which
the framework N:1 keyword/discriminator SPI now permits.

- `lowerRlsPolicyFromBlock` is parameterized by operation (read from the
  block keyword) and lowers a `withCheck` predicate into
  `PostgresRlsPolicy.withCheck`, which already enters the content hash —
  so two policies differing only in `withCheck` get distinct wire names.
- Each keyword carries the operation-appropriate predicate param set:
  SELECT/DELETE take `using`; INSERT takes `withCheck`; UPDATE/ALL take
  both. The lowering enforces this matrix directly, rejecting a predicate
  the operation does not take (e.g. `using` on INSERT) with a load-time
  `PSL_RLS_PREDICATE_NOT_FOR_OPERATION` diagnostic and producing no
  entity. The generic descriptor validator that would otherwise catch
  this is not wired into the SQL-family interpreter, so the lowering owns
  the guarantee.
- Every keyword still requires its `target` model to declare `@@rls`
  (slice 3s `requiresModelAttribute`).

ADR 126 and 225 are updated for the N:1 keyword/discriminator split:
printing looks the descriptor up by keyword, uniqueness is keyed on
keyword, and a discriminator may be shared across keywords.

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

The `PSL_RLS_PREDICATE_NOT_FOR_OPERATION` message hardcoded the article
`a` before the upper-cased operation, so the reachable INSERT case read
"a INSERT policy" — wrong before a vowel sound. Reword to "the <OP>
operation uses …", which sidesteps a/an agreement entirely.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
The createPolicy render, DDL node, contract-free builder, and planner
already carry `withCheck` end-to-end (slice 3 plumbed the full path,
USING before WITH CHECK). W2 pins that behavior for every operation and
guards the shared render path against regressing SELECT-only policies.

- ddl-rls-lowering.test.ts: exact-SQL pins for FOR INSERT (WITH CHECK,
  no USING), FOR UPDATE (USING then WITH CHECK), FOR DELETE (USING only),
  FOR ALL (both), plus a RESTRICTIVE + multi-role INSERT — covering the
  clause set and Postgres ordering per operation.
- rls-migration-plan.integration.test.ts: an offline plan of a
  `policy_update` contract renders FOR UPDATE with both USING and
  WITH CHECK (USING first), proving the contract → plan → render path
  threads `withCheck` for a non-select operation.
- rls-lifecycle-e2e.integration.test.ts: a live-PGlite `policy_insert`
  scenario — apply → pg_policies shows cmd INSERT with with_check set and
  qual null; editing the predicate plans create <hashB> + drop <hashA>,
  pinning the slice-3 lifecycle for a WITH CHECK-bearing operation.

No production code changed; byte-identity confirmed via fixtures:check
and the golden plan-diff (both committed Postgres examples: ops and SQL
preview identical at merge-base vs HEAD).

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Roles were already introspected from pg_roles and projected from the
contract onto the database root, and PostgresRoleSchemaNode was already a
DiffableNode — but the root withheld them from the diff. Close the three
gaps so a declared-but-missing role fails verify while an undeclared live
role is tolerated, and neither produces a migration op.

AC-3 — roles enter the diff:
- PostgresDatabaseSchemaNode.children() now yields the role nodes after
  the namespace nodes (both root-level diff subjects).
- PostgresRoleSchemaNode.id carries a `role:` sigil so a role can never
  collide with a same-named schema in the differ`s flat sibling id map
  (role `public` vs schema `public`); the bare name stays on `.name`.

AC-4/5 — asymmetric grading via a new `reference` granularity:
- A role is referenced by the contract but not owned by it (the framework
  names a role in an access policy but never owns the cluster`s role
  list), unlike a policy set, which the managed table owns. Add a
  `reference` value to the framework`s DiffSubjectGranularity; the target
  maps role → `reference` (policy stays `structural`). The family verdict
  suppresses a `reference` not-expected unconditionally — before strict
  gating and control-policy disposition — so an undeclared live role never
  fails or warns under any policy including `managed`. A not-found role
  stays generic `declaredMissing` → fails under external and managed.
- The diff`s not-expected ownership filter keys on a namespace path
  segment; a role is a root-level sibling with no namespace, so reference
  issues skip that filter and reach the verdict. Role issue messages are
  rewritten to name the bare role (the differ`s default path message would
  leak the `role:` sigil).

AC-6 — zero planner ops:
- Role diff issues are a third partition beside policy/relational that
  maps to no ops: isRoleDiffIssue excludes them from the relational
  pipeline so they never reach mapNodeIssueToCall`s unsupported-operation
  fail-loud. Proven byte-identical against a role-free baseline plan.

Grounding: a policy`s `roles` are `refKind: role` `scope: cross-space`
refs, which pass validation as a documented pass-through today (declared
roles become role nodes and are existence-checked; cross-space role-ref
resolution is separate future work). No authoring validation added.

Golden plan-diff byte-identical; fixtures:check clean.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…ith WITH CHECK enforcement (AC-7)

The examples/supabase Profile gains the project walking skeleton: an
`anon` public-read SELECT policy and an `authenticated` UPDATE-own policy
that uses both `using` (target only own rows) and `withCheck` (may not
reassign a row to another owner) — exercising policy_update + withCheck
from W1/W2 and the anon/authenticated roles the shim provides.

The hermetic PGlite e2e (skeleton.integration.test.ts) proves, under
manual SET ROLE:
- E: anon sees every profile via the public-read policy.
- F: WITH CHECK enforcement under a role — a compliant self-update
  succeeds, an ownership-change update is rejected. Role-scoped writes
  fire the dev-harness WAL-capture trigger, so the role is granted access
  to `_prisma_dev_wal` first (the accommodation that lets a role WRITE,
  not just read — the enforcement proof W2 had to defer).
- G: a role the contract declares but the database lacks fails db verify,
  naming the role (AC-4 end-to-end in the example; roles are injected via
  the role entity kind since PSL cannot author roles yet).

Existing behavioral tests updated for the three-policy base: the
fail-closed test drops all three policies; the rename test is unchanged
(one policy renamed, two identical); rls-role-binding asAnon now returns
every row. Fixtures regenerated through the real pipeline.

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

The new policy_* keywords (policy_insert/update/delete/all + withCheck) and
role verify are additive — existing schemas emit and verify byte-identically,
and no consumer action is required. Record the incidental examples/supabase
walking-skeleton diff in the 0.14-to-0.15 upgrade instructions so
check:upgrade-coverage per-PR declaration passes.

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

The missing-role test (test G) cloned the emitted contract wire JSON,
reached into storage.namespaces.public.entries.role to inject a
hand-authored role object, and cast-smuggled the mutated clone through
deserializeContract — the no-contract-data-patching-in-tests anti-pattern,
and its stale cloned storageHash only matched the marker by coincidence.

Rebuild the role-declaring contract through the genuine construction path:
`new PostgresRole` → `new PostgresSchema` (spreading the deserialized base
namespace entries + the added role) → `new SqlStorage` (carrying the base
named types forward, with a fresh test storage hash). Verify with
`skipMarker: true`, since the test asserts the schema verdict (the role is
missing), not migration-marker identity. No wire-JSON mutation, no
`as unknown as` cast into deserialize, no stale hash. All of test G's
assertions are unchanged, and the same behavior is independently proven in
W3's rls-role-verify.integration.test.ts.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Main (TML-3008, PR #952) shipped DiffableNode.nodeKind and pairs siblings by
(nodeKind, id) rather than id alone, and deleted SchemaDiffIssue.message.
PostgresRoleSchemaNode.id now returns the bare role name — a role and a
same-named namespace no longer need a role: sigil to avoid colliding in the
differ, since nodeKind already disambiguates them. withCleanRoleMessage (which
stripped that sigil out of issue.message) is deleted along with it; consumers
now read reason/path off the issue instead of a rendered message.

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

Delete the reference DiffSubjectGranularity member and the unconditional
not-expected suppress it drove in computeSqlDiffVerdict. A role node now
classifies as structural, same as a policy node. The asymmetric grading a role
needs — a missing declared role still fails, an undeclared live one is
tolerated under every control policy including managed — comes instead from
resolveControlPolicy forcing every role issue to resolve to the external
control policy regardless of the contracts own default/table policy:
externals existing suppress-every-extra-but-still-fail-missing semantics are
exactly the wanted behavior. diff-database-schema.ts still needs an
ownership-filter bypass for role not-expected issues (a role has no namespace
parent to own-scope against), now keyed on the role nodeKind directly instead
of the deleted granularity value.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Matches the frameworks existing runtimeError convention (used elsewhere in
this package for composition-time misconfigurations, e.g. the RUNTIME.
MIDDLEWARE_* errors) instead of a bare new Error. Code
RUNTIME.DUPLICATE_AUTHORING_DISCRIMINATOR carries label/keyLabel/key/
existingPath/path in details. Message text is unchanged, so the existing
regex-pinned tests still pass; a new test pins the structured shape.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Terse field-level doc comment: keyword is the blocks parse identity,
discriminator is its storage identity, and the five policy_* keywords share
one policy entity kind.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
@wmadden-electric
wmadden-electric force-pushed the slice/rls-policy-operations-and-roles branch from e3c26d6 to 81edcf7 Compare July 12, 2026 09:29
…fault role failure, fix stale AC-5 comment

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.

Actionable comments posted: 3

🤖 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`:
- Line 825: Remove the duplicate const r declaration in the test query section,
retaining the single intended declaration so skeleton.integration.test.ts parses
successfully.

In
`@packages/1-framework/2-authoring/psl-printer/src/serialize-print-document.ts`:
- Around line 134-140: Update the validation in the extension block
serialization flow to require descriptor.discriminator to equal
extensionBlock.kind, rather than only checking whether the kind exists in
blockDispatchMap.discriminators. Preserve the existing error behavior and
message for missing or mismatched descriptors, and keep the subsequent printing
logic unchanged.
- Around line 136-138: Update the error thrown in serializePrintDocument when no
descriptor is found to include both the missing extension block keyword and
extensionBlock.kind, while preserving the existing guidance about registering
pslBlockDescriptors or removing the AST block.
🪄 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: 7ba8bb5f-4cc7-44e5-ac37-7f600a6363c9

📥 Commits

Reviewing files that changed from the base of the PR and between e3c26d6 and 81edcf7.

⛔ Files ignored due to path filters (3)
  • projects/postgres-rls/plan.md is excluded by !projects/**
  • projects/postgres-rls/slices/rls-policy-operations-and-roles/plan.md is excluded by !projects/**
  • projects/postgres-rls/slices/rls-policy-operations-and-roles/spec.md is excluded by !projects/**
📒 Files selected for processing (42)
  • docs/architecture docs/adrs/ADR 126 - PSL top-level block SPI.md
  • docs/architecture docs/adrs/ADR 225 - Three-layer extensibility for pack-contributed entity kinds.md
  • examples/supabase/src/contract.d.ts
  • examples/supabase/src/contract.json
  • examples/supabase/src/contract.prisma
  • 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/rls-role-binding.integration.test.ts
  • examples/supabase/test/skeleton.integration.test.ts
  • packages/1-framework/1-core/framework-components/src/control/control-capabilities.ts
  • packages/1-framework/1-core/framework-components/src/shared/framework-authoring.ts
  • packages/1-framework/1-core/framework-components/src/shared/psl-extension-block.ts
  • packages/1-framework/1-core/framework-components/test/control-stack.test.ts
  • packages/1-framework/1-core/framework-components/test/framework-components.authoring.test.ts
  • packages/1-framework/1-core/framework-components/test/psl-ast.test.ts
  • packages/1-framework/1-core/framework-components/test/psl-extension-block-validator.test.ts
  • packages/1-framework/2-authoring/psl-parser/src/block-reconstruction.ts
  • packages/1-framework/2-authoring/psl-parser/test/symbol-table.test.ts
  • packages/1-framework/2-authoring/psl-printer/src/serialize-print-document.ts
  • packages/1-framework/2-authoring/psl-printer/test/generic-extension-block-printer.test.ts
  • packages/1-framework/3-tooling/cli/test/commands/contract-infer.command.test.ts
  • packages/2-mongo-family/9-family/test/authoring-entity-types.enum.test.ts
  • packages/2-sql/9-family/test/authoring-entity-types.enum.test.ts
  • 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/migrations/planner.ts
  • packages/3-targets/3-targets/postgres/src/core/psl-infer/infer-psl-contract.ts
  • packages/3-targets/3-targets/postgres/src/core/schema-ir/postgres-database-schema-node.ts
  • packages/3-targets/3-targets/postgres/src/core/schema-ir/postgres-role-schema-node.ts
  • packages/3-targets/3-targets/postgres/src/core/schema-ir/schema-node-kinds.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/rls-planner.test.ts
  • packages/3-targets/3-targets/postgres/test/postgres-database-schema-node.test.ts
  • packages/3-targets/3-targets/postgres/test/psl-rls-operations.test.ts
  • packages/3-targets/3-targets/postgres/test/schema-ir-leaf-nodes.test.ts
  • packages/3-targets/3-targets/postgres/test/schema-node-subject-granularity.test.ts
  • packages/3-targets/6-adapters/postgres/test/ddl-rls-lowering.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-role-verify.integration.test.ts
  • skills/upgrade/prisma-next-upgrade/upgrades/0.14-to-0.15/instructions.md
🚧 Files skipped from review as they are similar to previous changes (30)
  • examples/supabase/src/contract.d.ts
  • packages/1-framework/3-tooling/cli/test/commands/contract-infer.command.test.ts
  • examples/supabase/src/contract.prisma
  • packages/3-targets/3-targets/postgres/test/schema-node-subject-granularity.test.ts
  • packages/1-framework/2-authoring/psl-parser/test/symbol-table.test.ts
  • packages/1-framework/1-core/framework-components/src/shared/psl-extension-block.ts
  • examples/supabase/test/fixtures/renamed-policy/contract.d.ts
  • packages/3-targets/6-adapters/postgres/test/ddl-rls-lowering.test.ts
  • packages/1-framework/2-authoring/psl-parser/src/block-reconstruction.ts
  • packages/2-mongo-family/9-family/test/authoring-entity-types.enum.test.ts
  • packages/3-targets/3-targets/postgres/src/core/psl-infer/infer-psl-contract.ts
  • packages/1-framework/1-core/framework-components/test/framework-components.authoring.test.ts
  • examples/supabase/src/contract.json
  • docs/architecture docs/adrs/ADR 225 - Three-layer extensibility for pack-contributed entity kinds.md
  • docs/architecture docs/adrs/ADR 126 - PSL top-level block SPI.md
  • packages/2-sql/9-family/test/authoring-entity-types.enum.test.ts
  • packages/3-targets/6-adapters/postgres/test/migrations/rls-role-verify.integration.test.ts
  • packages/1-framework/1-core/framework-components/test/psl-ast.test.ts
  • packages/3-targets/3-targets/postgres/test/migrations/contract-to-postgres-database-schema-node.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-lifecycle-e2e.integration.test.ts
  • packages/3-targets/3-targets/postgres/src/core/schema-ir/postgres-database-schema-node.ts
  • packages/3-targets/3-targets/postgres/test/migrations/rls-planner.test.ts
  • packages/1-framework/1-core/framework-components/src/shared/framework-authoring.ts
  • packages/3-targets/3-targets/postgres/test/psl-rls-operations.test.ts
  • skills/upgrade/prisma-next-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/migrations/planner.ts
  • packages/1-framework/1-core/framework-components/test/control-stack.test.ts
  • packages/1-framework/2-authoring/psl-printer/test/generic-extension-block-printer.test.ts

…scriminator; fix ADR 225 dispatch wording

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
paulwer pushed a commit to paulwer/prisma-next that referenced this pull request Jul 12, 2026
…igil workaround (prisma#952)

## Linked issue

Refs
[TML-3008](https://linear.app/prisma-company/issue/TML-3008/schema-differ-pairs-siblings-by-nodekind-id-delete-the-role-sigil)

Unblocks [prisma#950](prisma#950)
(TML-2870), which rebases onto this and deletes its `role:`-sigil
workaround.

## At a glance

```ts
// packages/1-framework/1-core/framework-components/src/control/schema-diff.ts
export interface DiffableNode {
  readonly id: string;
  readonly nodeKind: string;
  isEqualTo(other: DiffableNode): boolean;
  children(): readonly DiffableNode[];
}
```

Before this PR the differ keyed a parent's children into one flat map on
bare `id` and threw `diffSchemas: duplicate id among siblings` on any
collision — so a Postgres role named `public` and a schema named
`public`, which are different objects that never pair against each
other, could not coexist as siblings in the diff tree.

## Decision

Two things:

1. **The differ pairs siblings by `(nodeKind, id)`, not by a
globally-unique `id`.** `DiffableNode` gains `readonly nodeKind: string`
— the per-node discriminant every SQL schema-IR node already declares,
so the SQL tree satisfies it with zero changes. An `id` now only needs
to be unique among same-kind siblings, which it already is by
construction (you can't declare two roles named `public`, or two columns
named `id` on one table). A node never folds its kind into its id string
to route around the differ.
2. **`SchemaDiffIssue.message` is deleted.** The differ reports
structured data (`path`, `reason`, the nodes); turning that into a human
sentence is the renderer's job. Every producer that baked prose into
`message` — including Mongo's hand-rolled `diffMongoSchemas` — stops;
every consumer renders from `path`/`reason` itself.

## Reviewer notes

- **Byte-identity is the review question.** Sibling pairing uses a
single `Map` keyed on `` `${nodeKind}\u0000${id}` `` — deliberately
*not* a nested per-kind map — so insertion order, and therefore
emitted-issue order, is bit-for-bit what it was. Every `nodeKind` in the
repo is a code-defined literal, so the NUL delimiter cannot collide. The
only input whose behavior changes is one that previously **threw**
(cross-kind sibling id collision); no previously-succeeding diff changes
output. Zero fixture/snapshot/golden files changed in this PR.
- **Mongo `db verify` failure text becomes path-based.**
`diffMongoSchemas` used to bake sentences like `Collection "users" is
missing from the database` into `message`; issues now render as `users`
/ `orders/validator` with the `reason` label. Accepted deliberately — no
committed snapshot pinned the prose, and a follow-up renderer can
rebuild richer text from the structured issue when wanted.
- **The `message` sweep is most of the diff.** The keying change itself
is ~40 lines; the other ~30 files are consumers and test literals that
carried `message`. One consumer was missed on the first pass and caught
by review: the CLI error-envelope formatter printed blank issue bodies
for SQLite/Mongo verify failures
([errors.ts](packages/1-framework/3-tooling/cli/src/utils/formatters/errors.ts)
now renders `message ?? path.join('/')`, since PSL diagnostics share
that envelope and legitimately carry `message`).
- **Slice process artifacts**
(`projects/postgres-rls/slices/differ-kind-keying/`) are committed for
review context and are cleaned up at project close-out, per this repo's
Drive convention.

## How it fits together

1. **The interface carries the discriminant.** `DiffableNode.nodeKind`
is an opaque string — no target vocabulary enters the framework. SQL
nodes inherit it from `SqlSchemaIRNode`'s existing abstract `nodeKind`;
the five Mongo schema-IR nodes each gain a genuine per-node literal
(`collection`, `index`, `validator`, `collectionOptions`, `schema`)
matching their existing `kind` discriminators 1:1.
2. **The differ keys on the pair.** `insertNode`/`diffChildren` build
the sibling map on the combined key and throw only on a genuine
same-kind/same-id duplicate
([schema-diff.ts](packages/1-framework/1-core/framework-components/src/control/schema-diff.ts)).
3. **Issues drop the baked message.** `pathMessage` and
`SchemaDiffIssue.message` are deleted; consumers that need a string
build it from `path` — the CLI verify formatter, `db verify`, the
sqlite/postgres issue planners' conflict summaries, and the CLI
error-envelope formatter.
4. **The ADR records the model.**
[adr-schema-diff-over-structured-ir.md](projects/postgres-rls/specs/adr-schema-diff-over-structured-ir.md)
now states per-kind sibling-id uniqueness and explicitly rejects folding
a node's kind into its `id()` (the guidance that produced prisma#950's sigil).

## Behavior changes & evidence

- Same-name, different-kind siblings diff instead of throwing; each
pairs only against its own-kind counterpart. Implementation:
[schema-diff.ts](packages/1-framework/1-core/framework-components/src/control/schema-diff.ts).
Evidence:
[schema-diff.test.ts](packages/1-framework/1-core/framework-components/test/schema-diff.test.ts)
(role-`public`/namespace-`public` pair independently; same-kind/same-id
still throws; issues carry no `message`).
- Mongo schema-IR nodes declare `nodeKind`; the Mongo diff algorithm is
otherwise unchanged apart from dropping `message`. Implementation:
[schema-node.ts](packages/2-mongo-family/3-tooling/mongo-schema-ir/src/schema-node.ts),
[schema-diff.ts](packages/2-mongo-family/9-family/src/core/schema-diff.ts).
Evidence:
[cli.control-policy.mongo.e2e.test.ts](test/integration/test/cli.control-policy.mongo.e2e.test.ts).
- CLI issue rendering is path-based where prose was removed, with PSL
diagnostics keeping their messages. Implementation:
[verify.ts](packages/1-framework/3-tooling/cli/src/utils/formatters/verify.ts),
[errors.ts](packages/1-framework/3-tooling/cli/src/utils/formatters/errors.ts).
Evidence:
[output.errors.test.ts](packages/1-framework/3-tooling/cli/test/output.errors.test.ts)
(pins both producer shapes).

## Testing performed

- `pnpm build` (68/68), forced `pnpm typecheck` (143/143), `pnpm lint` +
`pnpm lint:deps` on touched packages
- `pnpm test:packages` (12k+ tests), `pnpm test:integration`, `pnpm
test:e2e` (109/109)
- `pnpm fixtures:check` — clean; `git status` after: no
fixture/snapshot/golden file changed
- Reproduced-and-ruled-pre-existing flakes: config-loader `/var`
symlink, sql-orm-client portal race (both known families, untouched
files)

## Follow-ups

- PR prisma#950 rebases onto this and deletes its `role:` sigil +
`withCleanRoleMessage` (TML-2870).
- Optional richer issue rendering (human sentences rebuilt from
structured issues in the CLI formatter) if path-based output proves too
terse.

## Alternatives considered

- **Fold the kind into the id string (the `role:` sigil).** Rejected —
it re-encodes lost structural information into a name, then leaks into
paths and needs laundering (`withCleanRoleMessage`). That workaround is
what prisma#950 currently ships and deletes after this merges.
- **Key the differ on the contract `EntityCoordinate`.** Rejected (and
the ADR's original rejection stands) — schema-IR-node identity is its
own domain; mapping a schema-IR node to a contract coordinate is a
separate consumer-side operation, not the diff walk's concern.
- **A nested `Map<nodeKind, Map<id, node>>`.** Rejected — regrouping by
kind changes iteration order and would break emitted-issue
byte-identity; the single combined-key map preserves insertion order
exactly.
- **Keep `message` populated with the path string.** Rejected — it
duplicates `path` as a pre-rendered string and invites producers (as
Mongo did) to bake presentation into data the renderer should own.

## Checklist

- [x] All commits DCO-signed (`Signed-off-by`)
- [x] Tests written/updated for the behavior changes
- [x] Title follows `TML-XXXX: <sentence case>` convention
- [x] Docs/ADR updated where behavior is described


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

* **Bug Fixes**
* Improved schema-diff matching to avoid conflating items that share an
ID but differ by node type.
* Schema verification and CLI/database-check output now consistently
identify issues using their structured paths (with reason), including in
warnings and formatted error output.
* Migration/rebuild summaries now use deterministic, path-based
locations for conflicts.

* **Refactor**
* Schema-diff issues no longer rely on a preformatted message; they use
structured fields such as path, reason, expected, and actual.
* Mongo schema IR nodes now expose `nodeKind` instead of `kind` for type
discrimination.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…leDiffIssue special-casing

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 12, 2026
Merged via the queue into main with commit cdb8bd0 Jul 12, 2026
19 of 20 checks passed
@wmadden-electric
wmadden-electric deleted the slice/rls-policy-operations-and-roles branch July 12, 2026 16:00
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