Repository navigation
TML-2883: TS RLS policy authoring with PSL-identical wire names - #959
Conversation
Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…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]>
📝 WalkthroughWalkthroughAdds typed Postgres RLS handles and Supabase role exports, generic entity-handle lowering, PSL model storage-name resolution, and unit, parity, migration, and validation coverage. ChangesRLS authoring API
Generic entity-handle lowering
PSL storage resolution
Parity and runtime integration coverage
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
Possibly related PRs
Suggested reviewers: 🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✨ Finishing Touches🧪 Generate unit tests (beta)
⚔️ Resolve merge conflicts
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
@prisma-next/extension-author-tools
@prisma-next/mongo-runtime
@prisma-next/family-mongo
@prisma-next/sql-runtime
@prisma-next/family-sql
@prisma-next/extension-arktype-json
@prisma-next/middleware-cache
@prisma-next/mongo
@prisma-next/extension-paradedb
@prisma-next/extension-pgvector
@prisma-next/extension-postgis
@prisma-next/postgres
@prisma-next/sql-orm-client
@prisma-next/sqlite
@prisma-next/extension-supabase
@prisma-next/target-mongo
@prisma-next/adapter-mongo
@prisma-next/driver-mongo
@prisma-next/contract
@prisma-next/utils
@prisma-next/config
@prisma-next/errors
@prisma-next/framework-components
@prisma-next/operations
@prisma-next/ts-render
@prisma-next/contract-authoring
@prisma-next/ids
@prisma-next/psl-parser
@prisma-next/psl-printer
@prisma-next/cli
@prisma-next/cli-telemetry
@prisma-next/config-loader
@prisma-next/emitter
@prisma-next/language-server
@prisma-next/migration-tools
prisma-next
@prisma-next/vite-plugin-contract-emit
@prisma-next/mongo-codec
@prisma-next/mongo-contract
@prisma-next/mongo-value
@prisma-next/mongo-contract-psl
@prisma-next/mongo-contract-ts
@prisma-next/mongo-emitter
@prisma-next/mongo-schema-ir
@prisma-next/mongo-query-ast
@prisma-next/mongo-orm
@prisma-next/mongo-query-builder
@prisma-next/mongo-lowering
@prisma-next/mongo-wire
@prisma-next/sql-contract
@prisma-next/sql-errors
@prisma-next/sql-operations
@prisma-next/sql-schema-ir
@prisma-next/sql-contract-psl
@prisma-next/sql-contract-ts
@prisma-next/sql-contract-emitter
@prisma-next/sql-lane-query-builder
@prisma-next/sql-relational-core
@prisma-next/sql-builder
@prisma-next/target-postgres
@prisma-next/target-sqlite
@prisma-next/adapter-postgres
@prisma-next/adapter-sqlite
@prisma-next/driver-postgres
@prisma-next/driver-sqlite
commit: |
size-limit report 📦
|
There was a problem hiding this comment.
🧹 Nitpick comments (1)
packages/3-extensions/postgres/src/contract/rls.ts (1)
128-167: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueUse
ifDefinedfor the optional policy fields.
@prisma-next/utils/definedis already available here, and the same helper is used elsewhere inpackages/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
⛔ Files ignored due to path filters (3)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yamlprojects/postgres-rls/slices/rls-ts-authoring/plan.mdis excluded by!projects/**projects/postgres-rls/slices/rls-ts-authoring/spec.mdis excluded by!projects/**
📒 Files selected for processing (25)
packages/1-framework/1-core/framework-components/src/shared/framework-authoring.tspackages/2-sql/2-authoring/contract-psl/src/interpreter.tspackages/2-sql/2-authoring/contract-ts/src/exports/contract-builder.tspackages/3-extensions/postgres/src/contract/define-contract.tspackages/3-extensions/postgres/src/contract/rls-lowering.tspackages/3-extensions/postgres/src/contract/rls.tspackages/3-extensions/postgres/src/exports/contract-builder.tspackages/3-extensions/postgres/test/contract-builder/rls-entities.test.tspackages/3-extensions/postgres/test/contract-builder/rls-handles.test-d.tspackages/3-extensions/postgres/test/contract-builder/rls-handles.test.tspackages/3-extensions/supabase/src/contract/roles.tspackages/3-extensions/supabase/src/exports/contract.tspackages/3-extensions/supabase/test/contract-roles.test.tspackages/3-targets/3-targets/postgres/src/core/authoring.tspackages/3-targets/3-targets/postgres/src/exports/rls-canonicalize.tspackages/3-targets/3-targets/postgres/test/psl-rls-authoring.test.tsskills/extension-author/prisma-next-extension-upgrade/upgrades/0.14-to-0.15/instructions.mdtest/integration/package.jsontest/integration/test/authoring/parity/rls/contract.tstest/integration/test/authoring/parity/rls/expected.contract.jsontest/integration/test/authoring/parity/rls/packs.tstest/integration/test/authoring/parity/rls/schema.prismatest/integration/test/authoring/parity/ts-psl-rls-parity.test.tstest/integration/test/rls-helper-invisibility.test.tstest/integration/test/rls-ts-walking-skeleton.integration.test.ts
| /** | ||
| * 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; |
There was a problem hiding this comment.
This looks like it's too close to sql-specific
There was a problem hiding this comment.
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.
| > & { | ||
| /** | ||
| * 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[]; |
There was a problem hiding this comment.
Why do we have special case RLS handling? It should be a generic entity type carried throug hgeneric mechanisms
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
Why is this whole file new? Didn't we already have most of this machinery?
There was a problem hiding this comment.
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.
There was a problem hiding this comment.
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]>
There was a problem hiding this comment.
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
⛔ Files ignored due to path filters (3)
projects/postgres-rls/slices/rls-ts-authoring/plan.mdis excluded by!projects/**projects/postgres-rls/slices/rls-ts-authoring/spec.mdis excluded by!projects/**projects/postgres-rls/spec.mdis excluded by!projects/**
📒 Files selected for processing (22)
packages/2-sql/1-core/contract/package.jsonpackages/2-sql/1-core/contract/src/entity-handle-lowering-hook.tspackages/2-sql/1-core/contract/src/exports/entity-handle-lowering-hook.tspackages/2-sql/1-core/contract/tsdown.config.tspackages/2-sql/2-authoring/contract-psl/src/interpreter.tspackages/2-sql/2-authoring/contract-ts/src/contract-builder.tspackages/2-sql/2-authoring/contract-ts/src/contract-dsl.tspackages/2-sql/2-authoring/contract-ts/src/contract-lowering.tspackages/2-sql/2-authoring/contract-ts/test/entity-handle-lowering.test.tspackages/3-extensions/postgres/src/contract/define-contract.tspackages/3-extensions/postgres/src/contract/rls.tspackages/3-extensions/postgres/src/exports/contract-builder.tspackages/3-extensions/postgres/test/contract-builder/rls-entities.test.tspackages/3-extensions/postgres/test/contract-builder/rls-handles.test-d.tspackages/3-extensions/postgres/test/contract-builder/rls-handles.test.tspackages/3-targets/3-targets/postgres/src/core/authoring.tspackages/3-targets/3-targets/postgres/src/core/descriptor-meta.tspackages/3-targets/3-targets/postgres/src/core/rls/canonicalize.tspackages/3-targets/3-targets/postgres/src/exports/rls-canonicalize.tspackages/3-targets/3-targets/postgres/test/psl-rls-authoring.test.tsskills/extension-author/prisma-next-extension-upgrade/upgrades/0.14-to-0.15/instructions.mdtest/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
| 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), | ||
| }), | ||
| }); |
There was a problem hiding this comment.
🗄️ 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 -C2Repository: 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.tsRepository: 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 expandedRepository: 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 200Repository: 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.
| ...ifDefined('packEntities', mergedPackEntities), | ||
| ...ifDefined('entities', mergedEntities.length > 0 ? mergedEntities : undefined), |
There was a problem hiding this comment.
Wait why do we have entities and packEntities both?
There was a problem hiding this comment.
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.
Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
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]>
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]>
|
Rebased onto current main (merge commit) and resolved the interaction with #957 (standalone PSL
Full gate re-run green on the merged state; |
c62f8e8 to
97b8d32
Compare
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]>
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]>
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]>
…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]>
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
(Real code — trimmed from test/integration/test/authoring/parity/rls/contract.ts.) Before this PR, RLS policies, roles, and
@@rlsenablement 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:
policySelect/policyInsert/policyUpdate/policyDelete/policyAll(mirroring the five PSL keywords), plusrlsEnabled(model)(the@@rlsequivalent) androle(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.entitieslist on the postgresdefineContract. 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.contract.json, including the content-addressed policy names.using/withChecktakestringonly — never parsed, validated, or interpolated, matching PSL. (An earlier revision shipped aref()interpolation helper; it was vetoed in review and removed — see## Review restructurebelow.)@@map— so an@@map'd model got its@@rlsmarker keyed to the real table and its policies keyed to a nonexistent one. It now resolves the declared storage name, and a policy whosetargetdoesn't resolve gets a load diagnostic instead of lowering silently wrong.anon/authenticatedhandles from@prisma-next/supabase/contract, imported likeAuthUser.Reviewer notes
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.rlsEnabledtargets. Deliberate: you can'tCREATE POLICYon 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/policyAlltake at least one predicate, not both. PSL accepts apolicy_updatewith onlyusing(Postgres falls back toUSINGforWITH CHECK), and the hash omits the absent predicate — requiring both in TS would have made such policies unauthorable and forked their wire names.How it fits together
withCheckonpolicySelectis a compile error) and at construction for plain-JS callers.entitieswalk incontract-ts(contract-lowering.ts) groups handles by the pack that registered eachentityKind, 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-rlsEnabledmodel, duplicate role, over-long prefix) error here, naming the policy prefix and never the hash.AuthoringEntityContext, populated by the PSL interpreter; a resolution miss is the newPSL_RLS_POLICY_TARGET_UNRESOLVEDdiagnostic.role(...)handle inentitiesdeclares it into the contract, which is what makes a missing live role faildb verify.SET ROLE, edit/rename/drop lifecycle, drift and missing-role verify failures).Behavior changes & evidence
contract.jsonthrough the CLI emit path.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.@@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.Testing performed
On the final HEAD (rebased onto current
main):pnpm build(68 tasks) · forced full-repotypecheck(143/143)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(+--prevat the merge base),check:release-notes --mode prpnpm fixtures:check— clean, no fixture driftpnpm 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:examplesincluding 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):
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 unresolvedtargetis the interpreter's diagnostic.entitiesis a generic channel (239dda283) — kind-agnostic walk incontract-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'srls-lowering.tsdeleted.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.expectTypeOfmatchers (b22364ceb) — no@ts-expect-errornegatives remain.Skill update
The new public surface is all additive (
policySelect/policyInsert/policyUpdate/policyDelete/policyAll/rlsEnabled/roleon@prisma-next/postgres/contract-builder;anon/authenticatedon@prisma-next/supabase/contract); the extension-author upgrade instructions record it as no-action-required (instructions.md).Follow-ups
Alternatives considered
policies/rolesslots on the postgresdefineContract— rejected in design discussion: per-kind named slots multiply surface; the genericentitieslist rides the existing pack-entity channel and stays kind-agnostic (native enums can adopt it later).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..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)..add()/register()on the built contract — rejected: contracts are assembled and frozen; partial-contract values could escape.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.Checklist
TML-NNNN: <description>conventionSummary by CodeRabbit
anon,authenticated).