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

TML-2883: TS RLS policy authoring with PSL-identical wire names - #959

Merged
wmadden-electric merged 21 commits into
mainfrom
slice/rls-ts-authoring
Jul 15, 2026
Merged

wmadden-electric merged 21 commits into
mainfrom
slice/rls-ts-authoring

Conversation

@wmadden-electric

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

Copy link
Copy Markdown
Contributor

Linked issue

Refs TML-2883 — slice 5 (final) of the postgres-rls project. Builds on #950 (all policy operations + role verify, PSL surface).

At a glance

import { defineContract, field, model, policySelect, policyUpdate, rlsEnabled, role } from '@prisma-next/postgres/contract-builder';

const authenticated = role('authenticated');

const Profile = model('Profile', {
  fields: { id: field.column(int4Column).id(), userId: field.column(textColumn) },
}).sql({ table: 'profile' });

export const contract = defineContract({
  models: { Profile },
  entities: [
    rlsEnabled(Profile),
    policySelect(Profile, { name: 'profile_owner_read', roles: [authenticated], using: '"userId"::uuid = auth.uid()' }),
    policyUpdate(Profile, {
      name: 'profile_owner_write', roles: [authenticated],
      using: '"userId"::uuid = auth.uid()', withCheck: '"userId"::uuid = auth.uid()',
    }),
  ],
});

(Real code — trimmed from test/integration/test/authoring/parity/rls/contract.ts.) Before this PR, RLS policies, roles, and @@rls enablement could only be authored in PSL; the TypeScript surface had no way to express them.

Decision

This PR ships TypeScript authoring for Postgres RLS, producing contracts identical to the PSL surface:

  1. Per-operation policy helpers — policySelect / policyInsert / policyUpdate / policyDelete / policyAll (mirroring the five PSL keywords), plus rlsEnabled(model) (the @@rls equivalent) and role(name). All are top-level functions taking the model handle, exported only from @prisma-next/postgres/contract-builder — SQLite and Mongo authors never see them.
  2. One generic entities list on the postgres defineContract. Helpers return inert branded handles; the wrapper lowers them at build time (table names read from the build-resolved model nodes, wire names via the same content-hash functions the PSL lowering uses) and folds them into the existing generic pack-entity channel. No new machinery and zero RLS vocabulary in the framework or SQL-family layers.
  3. Wire-name parity as a pinned invariant — the same policies authored both ways emit byte-identical contract.json, including the content-addressed policy names.
  4. Predicates are opaque strings. using/withCheck take string only — never parsed, validated, or interpolated, matching PSL. (An earlier revision shipped a ref() interpolation helper; it was vetoed in review and removed — see ## Review restructure below.)
  5. A PSL bug fix the parity work exposed: the PSL policy lowering derived a policy's table name by lowercasing the model name's first letter, ignoring @@map — so an @@map'd model got its @@rls marker keyed to the real table and its policies keyed to a nonexistent one. It now resolves the declared storage name, and a policy whose target doesn't resolve gets a load diagnostic instead of lowering silently wrong.
  6. Supabase role exports — anon / authenticated handles from @prisma-next/supabase/contract, imported like AuthUser.

Reviewer notes

  • The commit history shows the review restructure honestly: the initial rounds built the lowering inside the postgres extension (rls-lowering.ts); the final three commits relocate it per review (see ## Review restructure). Read tip-state, not the intermediate commits, for the current architecture — the hash assembly is single-homed in target-postgres and shared by both surfaces, and the parity fixture pins the wire names.
  • Cross-space handles are rejected as policy/rlsEnabled targets. Deliberate: you can't CREATE POLICY on a table another contract space owns, so a cross-space target is a load error naming the policy. (Table names appearing inside predicate SQL are the author's own literal text, like all predicate content.)
  • policyUpdate/policyAll take at least one predicate, not both. PSL accepts a policy_update with only using (Postgres falls back to USING for WITH CHECK), and the hash omits the absent predicate — requiring both in TS would have made such policies unauthorable and forked their wire names.
  • The runtime predicate-matrix check in the helpers duplicates a five-line table from the PSL side rather than importing it. Deliberate: exporting it would couple the surfaces for five lines, and the local copy carries helper names for messages.
  • TS-declared roles file under the contract's default namespace. PSL has no role-declaration block, so there is no parity precedent; the verify projection iterates every namespace's roles, and the walking-skeleton test proves missing-role verify failure end to end from a TS declaration.
  • Slice artifacts (projects/postgres-rls/slices/rls-ts-authoring/spec.md, plan.md) are committed per the project convention; they close out with the project.

How it fits together

  1. Handles (packages/3-extensions/postgres/src/contract/rls.ts) — the helpers construct frozen branded values capturing the prefix, model reference, role handles, and predicates verbatim. The predicate matrix is enforced twice: statically (per-operation descriptor types; withCheck on policySelect is a compile error) and at construction for plain-JS callers.
  2. Lowering — the generic entities walk in contract-ts (contract-lowering.ts) groups handles by the pack that registered each entityKind, resolves declared model refs to table coordinates through the build's own model maps (the same representation the relation lowering uses for FKs), and invokes the pack's batch lowering hook. Postgres implements the hook in core/authoring.ts beside the PSL block lowering — one shared predicate matrix and hash assembly for both surfaces. Authoring mistakes (duplicate prefix, unknown or cross-space target, policy on a non-rlsEnabled model, duplicate role, over-long prefix) error here, naming the policy prefix and never the hash.
  3. PSL fix (packages/3-targets/3-targets/postgres/src/core/authoring.ts) — the policy lowering resolves the target model's declared storage name through a new generic optional lookup on AuthoringEntityContext, populated by the PSL interpreter; a resolution miss is the new PSL_RLS_POLICY_TARGET_UNRESOLVED diagnostic.
  4. Roles (packages/3-extensions/supabase/src/contract/roles.ts) — referencing a role handle lowers to its bare name (what PSL's pass-through produces); putting a role(...) handle in entities declares it into the contract, which is what makes a missing live role fail db verify.
  5. Proof — a parity fixture pair authored in both surfaces plus a live-PGlite walking skeleton authored purely in TS (row filtering under SET ROLE, edit/rename/drop lifecycle, drift and missing-role verify failures).

Behavior changes & evidence

  • TS contracts author RLS with PSL-identical output. Implementation: rls.ts (constructors), contract-lowering.ts (generic walk), core/authoring.ts (postgres hook). Evidence: ts-psl-rls-parity.test.ts (per-prefix wire-name equality, JSON-equal entities) and the parity/rls fixture pinning byte-identical emitted contract.json through the CLI emit path.
  • The TS-authored walking skeleton behaves identically on live PGlite — policies filter rows under SET ROLE; predicate edit → drop+create under a new wire name; prefix rename → ALTER POLICY … RENAME TO; out-of-band drift and a declared-but-absent role fail verify. Evidence: rls-ts-walking-skeleton.integration.test.ts.
  • PSL: @@map'd models get correctly-keyed policies; unresolved targets get a diagnostic (previously: silently mis-keyed table name). Implementation: authoring.ts, interpreter seam in interpreter.ts. Evidence: psl-rls-authoring.test.ts. Wire names are unaffected (the hash excludes table identity); all fixtures byte-identical.
  • The helpers are invisible off-Postgres. Evidence: rls-helper-invisibility.test.ts (SQLite/Mongo contract-builders export none of the seven names).

Testing performed

On the final HEAD (rebased onto current main):

  • pnpm build (68 tasks) · forced full-repo typecheck (143/143)
  • The full Lint job step set: lint:deps, lint:code, lint:packages, lint:examples, lint:rules, lint:rules:symlinks, lint:skills, lint:rules:footprint, lint:docs, lint:manifests, lint:workflows, test:scripts, lint:casts (delta 0), lint:framework-vocabulary (ratchet unchanged), check:upgrade-coverage --mode pr (+ --prev at the merge base), check:release-notes --mode pr
  • pnpm fixtures:check — clean, no fixture drift
  • pnpm test:packages (12591 tests; the three known macOS-only config-loader tmpdir failures reproduce locally and are green on Linux CI) · pnpm test:integration (1152/1152) · pnpm test:e2e (109)
  • pnpm test:examples including the multi-space guards (73/73 tasks)

Review restructure

Will's review of the first push produced four rulings, applied in the final three commits (parity fixtures and wire names byte-identical throughout):

  • No storage-name resolver on any authoring context (c51cf5f1c) — the framework field is gone; the PSL interpreter resolves descriptor-declared model refs to table coordinates during lowering and hands factories resolved data; an unresolved target is the interpreter's diagnostic.
  • entities is a generic channel (239dda283) — kind-agnostic walk in contract-ts, per-pack batch lowering hook (SQL-family contributions extension), RLS lowering relocated into target-postgres sharing one predicate matrix + hash assembly with the PSL path; the extension's rls-lowering.ts deleted.
  • ref() vetoed (b22364ceb) — predicates are opaque strings on both surfaces; the function-form predicate, its machinery, and its tests are removed; the corresponding project-DoD item is struck in the spec.
  • Type tests use expectTypeOf matchers (b22364ceb) — no @ts-expect-error negatives remain.

Skill update

The new public surface is all additive (policySelect/policyInsert/policyUpdate/policyDelete/policyAll/rlsEnabled/role on @prisma-next/postgres/contract-builder; anon/authenticated on @prisma-next/supabase/contract); the extension-author upgrade instructions record it as no-action-required (instructions.md).

Follow-ups

  • Wire the generic PSL block-descriptor validator into the interpreter. Three separate gaps in this slice traced to it being unwired (unresolved refs reaching factories, required params unenforced, required predicates unenforced), each patched per-factory; PSL also lacks the 54-char prefix cap the TS side enforces. Ticket to be filed at project close-out.

Alternatives considered

  • Named policies/roles slots on the postgres defineContract — rejected in design discussion: per-kind named slots multiply surface; the generic entities list rides the existing pack-entity channel and stays kind-agnostic (native enums can adopt it later).
  • Side-effect registration (policySelect(...) as a bare call that implicitly registers) — rejected: breaks "the contract is the value you return" and fails silently when a call is orphaned.
  • A chained .rls(...) model-builder method — rejected: the shared model builder has no target identity to make a Postgres-only method invisible elsewhere; top-level target-package helpers get that for free (design doc).
  • Post-build .add()/register() on the built contract — rejected: contracts are assembled and frozen; partial-contract values could escape.
  • Requiring both predicates on policyUpdate/policyAll — rejected during review: PSL accepts single-predicate forms and hashes them with the predicate omitted, so required-both would fork wire names between surfaces.
  • Asserting (rather than diagnosing) an unresolved PSL policy target — rejected during review: the assertion was reachable from an ordinary typo and crashed the interpreter instead of failing the load with a named diagnostic.

Checklist

  • Every commit is DCO signed-off
  • Tests added/updated for all behavior changes
  • Title follows the TML-NNNN: <description> convention

Summary by CodeRabbit

  • New Features
    • Added PostgreSQL TypeScript RLS authoring helpers for roles, enablement, and policies across supported operations.
    • Added Supabase runtime role handles (anon, authenticated).
    • Added entity-handle attachments to contract building, including build-time resolution into namespace entries.
  • Bug Fixes
    • Improved diagnostics and validation for unresolved, missing, duplicate, and cross-namespace RLS references and policy/enablement requirements.
    • Ensured RLS policies consistently target mapped database table names.
  • Documentation
    • Added upgrade guidance for the TypeScript RLS authoring additions.

…ed storage name

The PSL policy_* block lowering derived tableName by lowercasing the
target model's first character, ignoring @@Map. The sibling @@rls
model-attribute lowering already resolved correctly via the model's
storage name, so an @@Map'd model with a policy got its enablement
keyed to the real table and its policy keyed to a nonexistent one.

Add a generic resolveModelStorageName seam to AuthoringEntityContext,
populated by the PSL interpreter from an early, diagnostics-free model
mapping pass scoped to each namespace. The postgres policy factory
consumes it and asserts on a resolution miss, since target is already
a validated same-namespace model ref.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
The assertion on the storage-name lookup was reachable by an ordinary
user typo: the generic ref-existence validator is not wired into the
SQL-family interpreter and the @@rls-requirement check skips models
that do not resolve, so a misspelled target reached the policy factory
and threw an uncaught Error out of interpretPslDocumentToSqlContract.

Report the miss as a PSL_RLS_POLICY_TARGET_UNRESOLVED load-time
diagnostic naming the policy prefix and the model, spanning the target
parameter, and return undefined from the factory — the same shape as
the predicate-matrix rejection in the same function.

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

policySelect/policyInsert/policyUpdate/policyDelete/policyAll,
rlsEnabled(model), and role(name) return frozen branded handles that
capture their inputs by reference — no hashing, no table-name
resolution, no registration. Lowering happens later in defineContract.

The predicate matrix is static, mirroring Postgres and the five PSL
keywords: SELECT/DELETE descriptors take using only, INSERT takes
withCheck only, UPDATE/ALL take both. Predicates accept a string or a
stored (not evaluated) function of { ref }. permissive is not
authorable. Exported only from @prisma-next/postgres/contract-builder,
so SQLite/Mongo authoring surfaces never see them.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
PSL's lowering accepts policy_update/policy_all with only one of
using/withCheck (the descriptors' required flags live in the unwired
generic validator), and the content hash omits the absent predicate.
Requiring both in TS made such a policy unauthorable, and duplicating
the predicate to satisfy the type would change the hash and wire name,
forcing a spurious drop+create on a PSL-to-TS port.

RlsUsingWithCheckPolicyDescriptor is now a union requiring at least
one predicate; zero predicates stays a compile error. Handles carry
only what was authored, so lowering reproduces PSL's omission
byte-for-byte.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
The postgres defineContract accepts entities: a flat list of the
policy/role/rlsEnabled handles, lowered into the generic packEntities
channel before delegating to buildBoundContract. Lowering resolves
each target model to its build-resolved (tableName, namespaceId) via
buildContractDefinition over the same definition — never derived from
the model name — and reads cross-space extensionModel coordinates off
the handle. Function-form predicates are evaluated once with ref()
returning the qualified "namespace"."table" identifier. Wire names
come from the same normalizePredicate + computeContentHash +
formatRlsPolicyWireName chain the PSL lowering uses, with identical
hash input, and entities fold in with PSL-matching keys (policy by
prefix, rls by tableName, role by name).

Authoring mistakes throw at defineContract time naming the prefix:
duplicate prefix per namespace, unknown target model, target without
rlsEnabled, duplicate role declaration, prefix over the 54-character
cap. Roles are declared contract-wide and filed under the default
namespace (PSL has no role block to set a precedent).

The lowering rides a wrapping factory so factory-built models resolve
too and buildBoundContract's existing packEntities merge and collision
guards stay authoritative. Additive exports only: contract-ts gains
buildContractDefinition + PackEntitiesInput, target-postgres gains
formatRlsPolicyWireName.

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

A policy or rlsEnabled target must live in this contract space — you
cannot CREATE POLICY on a table another space owns. A cross-space
extensionModel handle passed as a target now throws at defineContract
time naming the prefix (or the model for rlsEnabled); cross-space
handles remain usable inside predicates via ref(), which is their
sanctioned role. The unknown-target message no longer suggests passing
a cross-space handle.

A ref() resolution miss now names the enclosing policy prefix instead
of the anonymous "a ref() call".

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
The descriptor types already reject a predicate the operation does not
take, but a plain-JS caller bypasses them: a smuggled withCheck on
policySelect lowered into FOR SELECT ... WITH CHECK, which Postgres
rejects at apply time, far from the mistake. buildPolicyHandle now
enforces the matrix at runtime — the same backstop the PSL lowering
provides via PSL_RLS_PREDICATE_NOT_FOR_OPERATION — naming the policy
and the predicates the operation takes. A policy with no predicate at
all is rejected the same way, matching the type-level requirement.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
The supabase pack exports anon and authenticated role handles from
@prisma-next/extension-supabase/contract beside AuthUser — Supabase
provisions these roles at runtime, so the contract never declares
them; referencing one in a policy lowers to its bare name, matching
PSL bare-identifier pass-through.

The parity suite pins TS and PSL RLS authoring to identical output:
an inline test asserts whole-contract equality, identical
entries.policy/entries.rls keys, identical content-hash wire names,
and JSON-equal entities for the walking-skeleton policies, all five
operations, a single-predicate update, and an @@map-mapped model
whose storage name is not derivable from its name; a declared
role(...) landing in entries.role is asserted TS-only (PSL has no
role block). A parity fixture (parity/rls/) additionally pins
byte-identical emitted contract.json for both surfaces through the
CLI emit path.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
The slice-1 RLS scenario authored via defineContract + the helpers,
run against live PGlite with the same observable behaviour as the PSL
twin: policies migrate on and filter rows under SET ROLE; a predicate
edit plans drop+create under the new wire name and the new predicate
enforces; a prefix rename with unchanged content plans a single
ALTER POLICY ... RENAME TO; policy removal plans a drop and verify is
clean; an out-of-band policy drop fails verify naming the wire name;
a TS-declared role absent from pg_roles fails verify naming the role
while an existing declared role verifies clean.

Lives in test/integration rather than beside the PSL twin in
adapter-postgres: @prisma-next/postgres already depends on
adapter-postgres, so the reverse devDependency would create a
workspace cycle.

The invisibility pin asserts the postgres contract-builder exports all
seven RLS helpers and the SQLite/Mongo contract-builders export none.

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

The extensions diff is net-new exports only (RLS handles + entities
input on the postgres contract-builder, supabase role handles); no
extension-author action required.

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 12, 2026 20:04
@coderabbitai

coderabbitai Bot commented Jul 12, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

Caution

Review failed

The head commit changed during the review from c62f8e8 to 401496d.

📝 Walkthrough

Walkthrough

Adds typed Postgres RLS handles and Supabase role exports, generic entity-handle lowering, PSL model storage-name resolution, and unit, parity, migration, and validation coverage.

Changes

RLS authoring API

Layer / File(s) Summary
Typed RLS handles and exports
packages/3-extensions/postgres/src/contract/..., packages/3-extensions/postgres/src/exports/..., packages/3-extensions/supabase/src/...
Adds frozen role, enablement, and policy handles with operation-specific predicate typing and runtime validation, then exposes them through Postgres and Supabase contract APIs.
Handle API validation
packages/3-extensions/postgres/test/contract-builder/rls-handles.test*
Verifies runtime immutability, predicate restrictions, operation typing, required predicates, role typing, and invalid input rejection.

Generic entity-handle lowering

Layer / File(s) Summary
Lowering contract and contract wiring
packages/2-sql/1-core/contract/..., packages/2-sql/2-authoring/contract-ts/src/...
Adds entity-handle lowering types and hooks, forwards handles through direct and factory contract definitions, resolves model references, and merges lowered rows with collected entities.
Postgres lowering and registration
packages/3-targets/3-targets/postgres/src/core/...
Registers the Postgres lowering hook and batches RLS, policy, and role handles into namespaced contract entities with target, duplicate, and prefix validation.
Lowering validation
packages/2-sql/2-authoring/contract-ts/test/..., packages/3-extensions/postgres/test/contract-builder/rls-entities.test.ts
Covers batching, resolved reference variants, missing hooks, unknown kinds, collisions, entity shapes, serializer round trips, diagnostics, and storage-name resolution.

PSL storage resolution

Layer / File(s) Summary
Extension model-reference resolution
packages/2-sql/2-authoring/contract-psl/src/interpreter.ts, packages/3-targets/3-targets/postgres/src/core/authoring.ts
Resolves same-namespace model references before extension factories, emits unresolved-reference diagnostics, and uses resolved table names when lowering policies.
PSL validation coverage
packages/3-targets/3-targets/postgres/test/psl-rls-authoring.test.ts
Verifies unresolved targets produce diagnostics and mapped model names are used consistently for RLS keys and policy table names.

Parity and runtime integration coverage

Layer / File(s) Summary
TS/PSL parity fixtures
test/integration/test/authoring/parity/rls/*, test/integration/test/authoring/parity/ts-psl-rls-parity.test.ts
Adds matching TypeScript and PSL RLS contracts, expected output, and parity assertions for policies, roles, hashes, predicates, and mapped tables.
Migration and schema behavior
test/integration/test/rls-ts-walking-skeleton.integration.test.ts
Exercises RLS migrations, filtering, predicate edits, prefix renames, drift recovery, policy removal, and declared-role verification.
Surface and upgrade checks
test/integration/test/rls-helper-invisibility.test.ts, skills/extension-author/.../instructions.md, test/integration/package.json
Checks Postgres-only helper exposure, documents the authoring surface, and adds integration workspace dependencies.

Estimated code review effort: 4 (Complex) | ~60 minutes

Sequence Diagram(s)

sequenceDiagram
  participant Author
  participant ContractBuilder
  participant postgresLowerEntityHandles
  participant PostgresContract
  Author->>ContractBuilder: defineContract with models and RLS entities
  ContractBuilder->>postgresLowerEntityHandles: resolve and lower entity handles
  postgresLowerEntityHandles->>PostgresContract: produce policy, rls, and role entries
  ContractBuilder->>PostgresContract: build merged contract
Loading

Possibly related PRs

Suggested reviewers: wmadden

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 30.77% 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 captures the main change: TypeScript RLS policy authoring with PSL-identical wire names.
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 unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch slice/rls-ts-authoring
⚔️ Resolve merge conflicts
  • Resolve merge conflict in branch slice/rls-ts-authoring

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 12, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@prisma-next/extension-author-tools

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

@prisma-next/mongo-runtime

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

@prisma-next/family-mongo

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

@prisma-next/sql-runtime

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

@prisma-next/family-sql

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

@prisma-next/extension-arktype-json

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

@prisma-next/middleware-cache

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

@prisma-next/mongo

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

@prisma-next/extension-paradedb

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

@prisma-next/extension-pgvector

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

@prisma-next/extension-postgis

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

@prisma-next/postgres

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

@prisma-next/sql-orm-client

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

@prisma-next/sqlite

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

@prisma-next/extension-supabase

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

@prisma-next/target-mongo

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

@prisma-next/adapter-mongo

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

@prisma-next/driver-mongo

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

@prisma-next/contract

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

@prisma-next/utils

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

@prisma-next/config

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

@prisma-next/errors

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

@prisma-next/framework-components

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

@prisma-next/operations

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

@prisma-next/ts-render

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

@prisma-next/contract-authoring

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

@prisma-next/ids

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

@prisma-next/psl-parser

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

@prisma-next/psl-printer

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

@prisma-next/cli

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

@prisma-next/cli-telemetry

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

@prisma-next/config-loader

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

@prisma-next/emitter

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

@prisma-next/language-server

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

@prisma-next/migration-tools

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

prisma-next

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

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

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

@prisma-next/mongo-codec

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

@prisma-next/mongo-contract

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

@prisma-next/mongo-value

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

@prisma-next/mongo-contract-psl

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

@prisma-next/mongo-contract-ts

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

@prisma-next/mongo-emitter

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

@prisma-next/mongo-schema-ir

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

@prisma-next/mongo-query-ast

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

@prisma-next/mongo-orm

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

@prisma-next/mongo-query-builder

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

@prisma-next/mongo-lowering

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

@prisma-next/mongo-wire

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

@prisma-next/sql-contract

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

@prisma-next/sql-errors

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

@prisma-next/sql-operations

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

@prisma-next/sql-schema-ir

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

@prisma-next/sql-contract-psl

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

@prisma-next/sql-contract-ts

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

@prisma-next/sql-contract-emitter

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

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

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

@prisma-next/sql-relational-core

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

@prisma-next/sql-builder

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

@prisma-next/target-postgres

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

@prisma-next/target-sqlite

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

@prisma-next/adapter-postgres

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

@prisma-next/adapter-sqlite

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

@prisma-next/driver-postgres

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

@prisma-next/driver-sqlite

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

commit: 401496d

@github-actions

github-actions Bot commented Jul 12, 2026 •

Copy link
Copy Markdown

size-limit report 📦

Path Size
postgres / no-emit 157.28 KB (+0.87% 🔺)
postgres / emit 131.09 KB (+0.1% 🔺)
mongo / no-emit 98.71 KB (0%)
mongo / emit 89.43 KB (0%)
cf-worker / no-emit 184.35 KB (+0.78% 🔺)
cf-worker / emit 155.53 KB (+0.09% 🔺)

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

🧹 Nitpick comments (1)
packages/3-extensions/postgres/src/contract/rls.ts (1)

128-167: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low value

Use ifDefined for the optional policy fields.
@prisma-next/utils/defined is already available here, and the same helper is used elsewhere in packages/3-extensions/postgres, so these spreads can follow the existing pattern.

♻️ Proposed refactor
+import { ifDefined } from '`@prisma-next/utils/defined`';

...
-    ...(descriptor.using !== undefined ? { using: descriptor.using } : {}),
-    ...(descriptor.withCheck !== undefined ? { withCheck: descriptor.withCheck } : {}),
+    ...ifDefined('using', descriptor.using),
+    ...ifDefined('withCheck', descriptor.withCheck),
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/3-extensions/postgres/src/contract/rls.ts` around lines 128 - 167,
Update buildPolicyHandle to use the available ifDefined helper when
conditionally adding descriptor.using and descriptor.withCheck to the frozen
policy handle, following the existing pattern in the Postgres extension;
preserve the current omission of undefined optional fields and validation
behavior.

Source: Learnings

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

Nitpick comments:
In `@packages/3-extensions/postgres/src/contract/rls.ts`:
- Around line 128-167: Update buildPolicyHandle to use the available ifDefined
helper when conditionally adding descriptor.using and descriptor.withCheck to
the frozen policy handle, following the existing pattern in the Postgres
extension; preserve the current omission of undefined optional fields and
validation behavior.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

Run ID: dbb77526-25e9-4f4a-8e73-408ada4aac82

📥 Commits

Reviewing files that changed from the base of the PR and between 3b9da2e and d96008d.

⛔ Files ignored due to path filters (3)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
  • projects/postgres-rls/slices/rls-ts-authoring/plan.md is excluded by !projects/**
  • projects/postgres-rls/slices/rls-ts-authoring/spec.md is excluded by !projects/**
📒 Files selected for processing (25)
  • 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-ts/src/exports/contract-builder.ts
  • packages/3-extensions/postgres/src/contract/define-contract.ts
  • packages/3-extensions/postgres/src/contract/rls-lowering.ts
  • packages/3-extensions/postgres/src/contract/rls.ts
  • packages/3-extensions/postgres/src/exports/contract-builder.ts
  • packages/3-extensions/postgres/test/contract-builder/rls-entities.test.ts
  • packages/3-extensions/postgres/test/contract-builder/rls-handles.test-d.ts
  • packages/3-extensions/postgres/test/contract-builder/rls-handles.test.ts
  • packages/3-extensions/supabase/src/contract/roles.ts
  • packages/3-extensions/supabase/src/exports/contract.ts
  • packages/3-extensions/supabase/test/contract-roles.test.ts
  • packages/3-targets/3-targets/postgres/src/core/authoring.ts
  • packages/3-targets/3-targets/postgres/src/exports/rls-canonicalize.ts
  • packages/3-targets/3-targets/postgres/test/psl-rls-authoring.test.ts
  • skills/extension-author/prisma-next-extension-upgrade/upgrades/0.14-to-0.15/instructions.md
  • test/integration/package.json
  • test/integration/test/authoring/parity/rls/contract.ts
  • test/integration/test/authoring/parity/rls/expected.contract.json
  • test/integration/test/authoring/parity/rls/packs.ts
  • test/integration/test/authoring/parity/rls/schema.prisma
  • test/integration/test/authoring/parity/ts-psl-rls-parity.test.ts
  • test/integration/test/rls-helper-invisibility.test.ts
  • test/integration/test/rls-ts-walking-skeleton.integration.test.ts

Comment on lines +178 to +188
/**
* Resolves a model's declared storage name (its `@@map` value, or the
* target's default naming when `@@map` is absent) from the model's bare
* name. Populated by the family interpreter from the parsed document,
* scoped to the namespace the calling block belongs to. A factory that
* needs the storage name of a model it references (by ref parameter) must
* read it here rather than deriving one from the model name itself, which
* would silently ignore `@@map`. Returns `undefined` when the name does
* not resolve to a model in scope.
*/
readonly resolveModelStorageName?: (modelName: string) => string | undefined;

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.

This looks like it's too close to sql-specific

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Resolved in c51cf5f — the field is deleted from the framework context entirely. Replacement representation (per the design discussion): ref conversion is the lowering's job over typed data. The PSL interpreter resolves the descriptor-declared target model ref to a table coordinate during extension-block lowering and hands the factory a resolved ref (resolvedModelRefs); an unresolved or missing target is the interpreter's diagnostic and the factory is never invoked. No storage-name lookup exists on any context, framework or family.

Comment on lines +60 to +66
> & {
/**
* RLS handles (`policy*`, `rlsEnabled`, `role`) lowered into the generic
* pack-entities channel at build time, mirroring the PSL `policy_*` /
* `@@rls` lowering key-for-key and wire-name-for-wire-name.
*/
readonly entities?: readonly RlsEntityHandle[];

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.

Why do we have special case RLS handling? It should be a generic entity type carried throug hgeneric mechanisms

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Resolved in 239dda2 — entities is now a generic channel. The kind-agnostic walk lives in contract-ts: it groups handles by the pack that registered each entityKind (the same discriminator index the PSL interpreter uses), pre-resolves declared model refs to table coordinates via the build's own model maps (the relation-lowering representation), and invokes the owning pack's batch lowering hook (lowerEntityHandles, a SQL-family contributions extension). defineContract carries zero kind logic; an unclaimed kind errors naming it (an RLS handle passed to sqlite's defineContract now fails exactly that way, pinned by test). The RLS lowering moved into target-postgres beside the PSL block lowering.

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.

Why is this whole file new? Didn't we already have most of this machinery?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fair challenge — audited. The genuinely-new part is the typed constructor surface (branded handles + per-operation descriptor types), which had no precedent anywhere. But the file also carried duplicated machinery: a copy of the predicate matrix, a re-implementation of the PSL predicate rejection, and (in the sibling rls-lowering.ts) a mirror of the PSL hash assembly. As of 239dda2 that duplication is gone: POLICY_OPERATION_PREDICATES and the hash assembly (buildRlsPolicyEntity) are single-homed in target-postgres and consumed by both the PSL block factory and the TS handle hook; rls-lowering.ts is deleted. What remains here is only the constructors and their static typing.

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.

Use vitest type matchers

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Done in b22364c — zero @ts-expect-error left; negatives are expectTypeOf matcher forms (.not.toExtend, .not.toHaveProperty, .parameter(0).toEqualTypeOf). One note: a literal-only excess property (permissive smuggled into a call site) isn't expressible as a type relation, so that case is carried by the property-absence assertions on the descriptor types plus the runtime backstop.

…nnel, ref() vetoed

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
using/withCheck accept string only; the function-form predicate type,
the ref() evaluation machinery, and the tests pinning ref behaviour
are deleted (spec D4 amended, AC-3 struck). Renaming a table
referenced inside predicate SQL no longer updates the predicate on
either surface — raw SQL's normal contract. The rename-changes-hash
property remains covered by the lifecycle tests in their string form.

Also converts the type-level negatives to expectTypeOf matchers per
the vitest-expect-typeof rule and switches the optional predicate
spreads in buildPolicyHandle to ifDefined.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
The entities handle list is now a kind-agnostic input on the generic
contract build. A handle is { entityKind, refs? }; the walk in
contract-ts groups handles by the pack that registered each entityKind
(the same entityTypes discriminator index the PSL interpreter uses;
an unclaimed kind is an error naming the kind), resolves each declared
model ref to a storage table coordinate through the build's own model
maps (identity-first; cross-space handles annotate spaceId; unresolved
refs are marked, never guessed), and calls the owning pack's batch
lowering hook once — batch so cross-entity diagnostics can see sibling
handles. Returned rows fold into packEntities ahead of the existing
collision guards. The hook type is a SQL-family contributions
extension (entity-handle-lowering-hook, beside the value-set
derivation hook precedent).

The RLS lowering itself now lives in target-postgres beside
lowerRlsPolicyFromBlock, sharing one predicate matrix (single-homed in
rls/canonicalize) and one hash-assembly body (buildRlsPolicyEntity)
with the PSL path; all diagnostics keep their wording. The extension's
rls-lowering.ts is deleted; the postgres defineContract only narrows
the entities element type and contains zero entity-kind logic. Handles
carry their model refs under refs.target. Wire names, entries keys,
and parity fixtures are byte-identical throughout; an RLS handle in
sqlite's defineContract now fails the generic unclaimed-kind check.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
resolveModelStorageName is deleted from AuthoringEntityContext — a
storage-name oracle on the authoring context was the operator-rejected
representation. Ref conversion is the lowering's job over typed data:
the interpreter's extension-block pass resolves each block-descriptor
parameter declared { kind: 'ref', refKind: 'model' } to the referenced
model's storage table name and annotates the block with
resolvedModelRefs (a SQL-family annotation type) before invoking the
factory. A required model ref that is missing or does not resolve is
the interpreter's diagnostic (PSL_EXTENSION_MODEL_REF_UNRESOLVED,
naming the block and the model, span on the parameter) and the factory
is skipped — so lowerRlsPolicyFromBlock now just reads the resolved
coordinate and asserts it exists. The W1 regression behaviour (an
@@Map'd model's policy keys to the declared storage name; a typo'd
target is a diagnostic, not a crash) is pinned unchanged.

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

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

Inline comments:
In `@packages/3-targets/3-targets/postgres/src/core/authoring.ts`:
- Around line 778-792: Update lowerRlsPolicyFromBlock to deduplicate policy role
references before sorting the roles array, matching the deduplicated roles
behavior in the TS authoring path. Preserve the existing role-name ordering and
pass the resulting unique names to buildRlsPolicyEntity.
🪄 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: d5cb0f41-e01e-484d-9b63-b44ac8ba03a7

📥 Commits

Reviewing files that changed from the base of the PR and between d96008d and c51cf5f.

⛔ Files ignored due to path filters (3)
  • projects/postgres-rls/slices/rls-ts-authoring/plan.md is excluded by !projects/**
  • projects/postgres-rls/slices/rls-ts-authoring/spec.md is excluded by !projects/**
  • projects/postgres-rls/spec.md is excluded by !projects/**
📒 Files selected for processing (22)
  • packages/2-sql/1-core/contract/package.json
  • packages/2-sql/1-core/contract/src/entity-handle-lowering-hook.ts
  • packages/2-sql/1-core/contract/src/exports/entity-handle-lowering-hook.ts
  • packages/2-sql/1-core/contract/tsdown.config.ts
  • packages/2-sql/2-authoring/contract-psl/src/interpreter.ts
  • packages/2-sql/2-authoring/contract-ts/src/contract-builder.ts
  • packages/2-sql/2-authoring/contract-ts/src/contract-dsl.ts
  • packages/2-sql/2-authoring/contract-ts/src/contract-lowering.ts
  • packages/2-sql/2-authoring/contract-ts/test/entity-handle-lowering.test.ts
  • packages/3-extensions/postgres/src/contract/define-contract.ts
  • packages/3-extensions/postgres/src/contract/rls.ts
  • packages/3-extensions/postgres/src/exports/contract-builder.ts
  • packages/3-extensions/postgres/test/contract-builder/rls-entities.test.ts
  • packages/3-extensions/postgres/test/contract-builder/rls-handles.test-d.ts
  • packages/3-extensions/postgres/test/contract-builder/rls-handles.test.ts
  • packages/3-targets/3-targets/postgres/src/core/authoring.ts
  • packages/3-targets/3-targets/postgres/src/core/descriptor-meta.ts
  • packages/3-targets/3-targets/postgres/src/core/rls/canonicalize.ts
  • packages/3-targets/3-targets/postgres/src/exports/rls-canonicalize.ts
  • packages/3-targets/3-targets/postgres/test/psl-rls-authoring.test.ts
  • skills/extension-author/prisma-next-extension-upgrade/upgrades/0.14-to-0.15/instructions.md
  • test/integration/test/rls-helper-invisibility.test.ts
💤 Files with no reviewable changes (1)
  • packages/3-extensions/postgres/src/exports/contract-builder.ts
🚧 Files skipped from review as they are similar to previous changes (4)
  • packages/3-targets/3-targets/postgres/src/exports/rls-canonicalize.ts
  • test/integration/test/rls-helper-invisibility.test.ts
  • skills/extension-author/prisma-next-extension-upgrade/upgrades/0.14-to-0.15/instructions.md
  • packages/3-targets/3-targets/postgres/test/psl-rls-authoring.test.ts

Comment on lines +778 to +792
const roleNames = [...new Set(policy.roles.map((roleHandle) => roleHandle.name))].sort();
rows.push({
namespaceId: coordinate.namespaceId,
entityKind: 'policy',
key: prefix,
entity: buildRlsPolicyEntity({
prefix,
tableName: coordinate.tableName,
namespaceId: coordinate.namespaceId,
operation: policy.operation,
roles: roleNames,
...ifDefined('using', policy.using),
...ifDefined('withCheck', policy.withCheck),
}),
});

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.

🗄️ Data Integrity & Integration | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
rg -nP '\breadListRefParams\b' packages/3-targets -C3
rg -nP "readListRefParams\(block, 'roles'\)" packages/3-targets/3-targets/postgres/src/core/authoring.ts -C2

Repository: prisma/prisma-next

Length of output: 3909


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '\n== authoring slice ==\n'
sed -n '160,240p' packages/3-targets/3-targets/postgres/src/core/authoring.ts

printf '\n== policy entity/hashing/search ==\n'
rg -n "computeContentHash|PostgresRlsPolicy|roles" packages/3-targets/3-targets/postgres/src -g '!**/*.map' -C 2

printf '\n== PSL policy test slice ==\n'
sed -n '1,260p' packages/3-targets/3-targets/postgres/test/psl-policy-authoring.test.ts

Repository: prisma/prisma-next

Length of output: 50374


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '\n== buildRlsPolicyEntity / PostgresRlsPolicy definitions ==\n'
rg -n "buildRlsPolicyEntity|class PostgresRlsPolicy|type PostgresRlsPolicy|interface PostgresRlsPolicy|roles:" packages/3-targets/3-targets/postgres/src -C 3

printf '\n== PSL parsing / validation for list items ==\n'
rg -n "kind === 'list'|list items|duplicate|Set\\(|roles" packages/3-targets/3-targets/postgres packages/3-targets -g '!**/*.map' -C 2

printf '\n== authoring file outline ==\n'
ast-grep outline packages/3-targets/3-targets/postgres/src/core/authoring.ts --view expanded

Repository: prisma/prisma-next

Length of output: 50375


🏁 Script executed:

#!/bin/bash
set -euo pipefail

printf '\n== files mentioning roles list parsing ==\n'
rg -n "roles.*list|list.*roles|unique.*roles|duplicate.*roles|roles" packages -g '!**/*.map' -g '!**/dist/**' -C 2

printf '\n== parser/grammar candidates ==\n'
fd -HI '.*(grammar|parser|ast|schema).*' packages | head -n 200

Repository: prisma/prisma-next

Length of output: 50375


Dedup policy roles in packages/3-targets/3-targets/postgres/src/core/authoring.ts:185. lowerRlsPolicyFromBlock sorts the list but keeps duplicate refs, so the PSL path can carry a different roles array than the TS authoring path. Dedup here or reject duplicates upstream.

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

In `@packages/3-targets/3-targets/postgres/src/core/authoring.ts` around lines 778
- 792, Update lowerRlsPolicyFromBlock to deduplicate policy role references
before sorting the roles array, matching the deduplicated roles behavior in the
TS authoring path. Preserve the existing role-name ordering and pass the
resulting unique names to buildRlsPolicyEntity.

Comment on lines +507 to +508
...ifDefined('packEntities', mergedPackEntities),
...ifDefined('entities', mergedEntities.length > 0 ? mergedEntities : undefined),

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.

Wait why do we have entities and packEntities both?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Consolidated in 0adcacd — the public packEntities input is removed; entities is now the only generic pack-entity channel.

They overlapped: packEntities (a map keyed namespace→kind→name, taking pre-constructed entities) had no real author — every reference was test-only, and native enums never used it (they ride column refs into a separate internal accumulator). entities (a list of handles lowered by the pack hook) strictly subsumes it: the hook computes the key/hash and runs validation, instead of making the author hand-construct the entity and its name. So packEntities was the "do the pack's job yourself" form that consequently attracted zero authors.

Removed the public field from every input/scaffold/factory overload + the PackEntitiesInput export; kept the internal column-ref accumulator (renamed so it no longer reads as a public mirror) that native enums depend on. Emitted contracts are byte-identical — entities folds through the same internal carrier the removed field used, so this is author-surface-only. Tests that authored the map moved onto entities handles.

The public packEntities input on the contract had no real author: every
reference was test-only, and native enums enter through column refs into
a separate internal accumulator, never the public field. The entities
handle channel (plus the pack lowering hook) strictly subsumes it, so
collapse to one public channel.

Removed: the packEntities field from every contract input/scaffold/
factory/bound-definition type; its scaffold+factory merge
(mergePackEntities and helpers); the factory-returned packEntities path;
the PackEntitiesInput public export. Factories now return entities, or
nothing of this kind.

Kept, renamed internal-only: the column-ref accumulator
(CollectedPackEntities -> CollectedColumnEntities,
collectPackEntityFromColumn -> collectEntityFromColumn) that native
enums ride, and the merge that folds it with the entities-channel
attachments (mergeCollectedPackEntities -> mergeColumnAndAttached
Entities). The lowered entities carrier on ContractDefinition is
renamed packEntities -> attachedEntities (type PackEntitiesInput ->
AttachedEntities); it is build IR, never an author input. git grep
packEntities is now empty across source and tests.

Tests migrated to the entities channel: the TML-2965 attachment +
value-set-derivation + managed-kind-guard tests now author via
entities through a synthetic pack's lowerEntityHandles hook; the
collision guard is re-expressed as an intra-entities name clash.
Native-enum and RLS parity fixtures and all wire names are
byte-identical.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Integrates origin/main (which merged #957 PSL role blocks + the
native-enum and dependency PRs) into the slice. Conflicts resolved
preserving both intents:

- supabase roles.ts: keep #957 SupabaseRole enumType (+ JWT claim key
  + isSupabaseRole, the runtime vocabulary source of truth) AND our
  anon/authenticated role() reference handles; the handles reference
  the same anon/authenticated identities SupabaseRole declares.
- supabase contract-roles.test.ts (add/add): merge #957 contract-shape
  test (__unbound__ role slot == SupabaseRole.values) with our
  anon/authenticated handle-shape test.
- interpreter.ts: reconcile #957 refactor (lowerExtensionBlocksForName
  space takes a blocks map; top-level extension blocks pass) with our
  resolved-model-refs threading (composedPslBlockDescriptors +
  per-namespace table resolver), threaded through both call sites.
- postgres authoring.ts auto-merged: #957 role block (lowerRoleFrom
  Block, outside-unbound rejection) coexists with our policy_* and the
  entity-handle hook.
- upgrade instructions: keep all three per-PR notes as separate blocks.

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

The postgres entity-handle hook lowered a TS role() under the model
default namespace (public); roles are cluster-scoped, so they belong
in __unbound__ — matching #957 PSL role blocks (lowerRoleFromBlock)
and the PostgresRole class contract. Flip both the new PostgresRole
namespaceId and the rows.push namespaceId in postgresLowerEntityHandles
to UNBOUND_NAMESPACE_ID.

Verify keys roles by name at the root, so a missing declared role
still fails verify (walking skeleton green) — only the emitted slot
moves. Parity strengthened: a role is now authored in BOTH surfaces
(TS role(app_role) in entities vs PSL namespace unbound { role app_role
{} }) and asserted to lower to an identical PostgresRole under
__unbound__.entries.role — the inline whole-contract toEqual and the
emit-parity fixture both cover it byte-identically.

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

Copy link
Copy Markdown
Contributor Author

Rebased onto current main (merge commit) and resolved the interaction with #957 (standalone PSL role blocks), which merged after approval:

  • Roles now land in __unbound__ on both surfaces. TML-2501: declare Supabase roles via a standalone PSL role block #957 declares Supabase roles via namespace unbound { role … } → PostgresRole in __unbound__. The TS role() helper had been filing declared roles under the default namespace; it now lowers to UNBOUND_NAMESPACE_ID, so a role authored in TS and one authored in PSL produce an identical PostgresRole. (Emitted-slot only — verify keys roles by name at the root, so no plan/verify behaviour change; the walking-skeleton missing-role check is unaffected.)
  • supabase/src/contract/roles.ts keeps both TML-2501: declare Supabase roles via a standalone PSL role block #957's SupabaseRole enum (runtime vocab) and this PR's anon/authenticated reference handles, pointing at the same identities.
  • Parity strengthened: now that PSL has a role block, the parity test authors a role in both surfaces and pins an identical PostgresRole under __unbound__ — the previously TS-only role assertion is now genuine cross-surface parity.

Full gate re-run green on the merged state; git diff vs main is only this slice's surface (fixtures byte-identical, #957's example unregressed).

@wmadden-electric
wmadden-electric added this pull request to the merge queue Jul 15, 2026
Merged via the queue into main with commit 1ebef7f Jul 15, 2026
28 of 29 checks passed
@wmadden-electric
wmadden-electric deleted the slice/rls-ts-authoring branch July 15, 2026 13:55
wmadden-electric added a commit that referenced this pull request Jul 15, 2026
All eight slices merged (final: TS RLS authoring, #959); long-lived docs
promoted to docs/ in the preceding commits. Per the projects/ lifecycle,
transient project artifacts (spec, plan, handoff, slice specs/plans,
dispatches, trace) delete with the project.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
wmadden-electric added a commit that referenced this pull request Jul 15, 2026
All eight slices merged (final: TS RLS authoring, #959); long-lived docs
promoted to docs/ in the preceding commits. Per the projects/ lifecycle,
transient project artifacts (spec, plan, handoff, slice specs/plans,
dispatches, trace) delete with the project.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
wmadden-electric added a commit that referenced this pull request Jul 15, 2026
All eight slices merged (final: TS RLS authoring, #959); long-lived docs
promoted to docs/ in the preceding commits. Per the projects/ lifecycle,
transient project artifacts (spec, plan, handoff, slice specs/plans,
dispatches, trace) delete with the project.

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