Repository navigation
TML-2868: SELECT RLS policies, dependable end-to-end — authored in PSL, enforced, drift fails verify - #771
Conversation
…lates Refresh the weeks-stale postgres-rls artifacts (TML-2501) against landed dependencies and the current slice-based Drive layout: - Reconcile every stale spec assumption to landed code (SchemaNodeBase-> IRNodeBase/SqlNode; policies/roles on PostgresSchema.entries, not a table class; __unspecified__->__unbound__; entityTypes; control-policy two-layer dispatch). Findings in specs/reconciliation-2026-06-08.md. - Settle the RLS authoring surface (D3) as a top-level Postgres-contributed helper (the enum mechanism), invisible off-Postgres, mirroring the PSL top-level shape — not a chained builder method. Rationale + rejected options in specs/design-rls-authoring-surface.md. - Adopt per-operation PSL keywords (policy_select/...) to align with the landed target-contributed-psl-blocks substrate. - Recompose into a 4-slice Sandwich diamond (foundation -> authoring || migration-ops -> verifier+skeleton): TML-2868/2869/2870/2871. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
…-2 scope
A policy_*'s `roles = [anon, authenticated]` are static references to declared
`role` entities, not strings — confirmed against the landed PSL-block substrate
(the `declarative-policy-select-extension` fixture already declares
`roles: { kind: list, of: { kind: ref, refKind: role, scope: cross-space } }`).
Fold the consequences into the plan + spec:
- Slice 1 must register `PostgresRole` as a `role` entity kind populating
`entries[role]` (not just an IR class) — refs resolve by entries[refKind][name].
- Slice 2 owns cross-space role-ref resolution: the substrate defers cross-space
ref enforcement to its first consumer (us), wired via the
(spaceId, namespaceId, role, name) coordinate, reusing cross-contract-refs
machinery. Same-space role refs resolve without it. Also adds the role-
declaration authoring surface (TS RoleRef / PSL identifiers).
- Correct the spec's stale "cross-contract-refs is consumer-side only" claim:
cross-space role resolution is integration work this project owns.
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…-2868) Slice 1 of 4. Chosen design grounded in the reconciliation anchors: PostgresRlsPolicy/PostgresRole following the PostgresEnumType precedent (entityTypes-registered, PostgresSchema.entries role/rlsPolicy slots); StorageTable.rls; canonicalize.ts (normalizer + 8-hex content-hash); serializer round-trip; SchemaIssue union widening. Four dispatches: D1 IR+registration, D2 normalizer+hash, D3 serializer, D4 union widening. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
…le.rls + entityTypes registration Introduces the two Postgres-target-only RLS IR classes and the table-level RLS toggle, following the PostgresEnumType precedent exactly. Reachable only through synthetic test fixtures — no authoring helper, no planner, no verifier. - packages/3-targets/3-targets/postgres/src/core/postgres-rls-policy.ts: new PostgresRlsPolicy class extending SqlNode, frozen, kind='postgres-rls-policy' - packages/3-targets/3-targets/postgres/src/core/postgres-role.ts: new PostgresRole class extending SqlNode, frozen, kind='postgres-role' - packages/3-targets/3-targets/postgres/src/core/postgres-schema.ts: add role and rlsPolicy slots to PostgresSchema.entries and PostgresSchemaInput - packages/3-targets/3-targets/postgres/src/core/authoring.ts: register role and rlsPolicy entity kinds in postgresAuthoringEntityTypes - packages/2-sql/1-core/contract/src/ir/storage-table.ts: add rls?: RlsMode field (absent-when-default 'auto', mirrors control? discipline) - packages/2-sql/1-core/contract/src/types.ts: export RlsMode - packages/2-sql/1-core/contract/src/exports/types.ts: re-export RlsMode - packages/3-targets/3-targets/postgres/src/exports/types.ts: export new classes - packages/3-targets/3-targets/postgres/test/rls-ir-kinds.test.ts: synthetic fixture + freeze/immutability tests for all new surfaces Gates: typecheck ✓, pnpm --filter target-postgres test (300 passed) ✓, lint:deps ✓ Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
…race Dispatch D1 (IR kinds) of slice foundation: implementer commit 935d8a5, reviewer verdict SATISFIED, zero findings. Records the dispatch brief, the code-review round note + DC scoreboard (DC-3 lint:deps PASS), the persistent implementer/reviewer subagent IDs, and the dispatch/round trace events. Carry-forward: D3/slice-2 must decide validator schemas for the new entity kinds. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: Will Madden <[email protected]>
Edge-case corpus for normalizePredicate + computeContentHash covering: whitespace variants, keyword lowercase, outer-paren trim, comment stripping (line and block), string-literal data preservation, role ordering/dedup, operation/permissive distinctness, and tuple encoding stability. Red per TDD — implementation follows. Signed-off-by: Will Madden <[email protected]>
normalizePredicate: char scanner strips line/block comments while preserving string literals, then collapses whitespace, lowercases, and trims fully-enclosing outer parens (repeated). No SQL grammar parser — see normalizer stability notes in canonicalize.ts. computeContentHash: SHA-256 over JSON-encoded tuple [canonical(using), canonical(withCheck), sortedRoles, operation, permissive] — first 8 lowercase hex chars. node:crypto only. Also fixes tuple ordering in the stability-assertion test (using is tuple position 0, not 1). Signed-off-by: Will Madden <[email protected]>
The blanket .toLowerCase() at the end of normalizePredicate lowercased the contents of single-quoted literals along with SQL keywords. This collapsed 'Admin' and 'admin' to the same canonical form, producing identical content hashes for semantically different predicates (Postgres string comparison is case-sensitive). Fold lowercasing into the char scanner (stripCommentsAndLowercase): bytes outside literals are lowercased; bytes inside single-quoted literals are copied verbatim. Remove the trailing .toLowerCase(). Tests updated: - 'AND OR NOT NULL' inside a literal is now expected to preserve case. - Added assertion that keyword lowercasing applies outside but not inside literals (WHERE x = 'Admin' → where x = 'Admin'). - Inverted the 'AND'/'and' hash test to assert they differ. - Added 'Admin'/'admin' hash distinctness assertion. Signed-off-by: Will Madden <[email protected]>
- Add rls? to StorageTableSchema so 'enabled'/'disabled' tables round-trip - Add PostgresRoleSchema and PostgresRlsPolicySchema to validators.ts - Extend createNamespaceEntrySchema entries to accept role? and rlsPolicy? slots with fragment-dispatched per-kind validation (same pattern as type?) - Register the new schemas as validatorSchema on the role/rlsPolicy entries in postgresAuthoringEntityTypes Co-Authored-By: Claude Sonnet 4.6 <[email protected]> Signed-off-by: Will Madden <[email protected]>
…olicy slots - serializePostgresNamespace emits role and rlsPolicy maps alongside table/type - hydrateSqlNamespaceEntry extracts and factory-dispatches role/rlsPolicy entries from raw input; UNBOUND short-circuit now checks all four slots are empty - Round-trip property tests: permissive + restrictive; using-only + using+withCheck; single + multi-role; frozen instances; rls omit-when-auto; negative tests for bad operation literal and missing permissive field Co-Authored-By: Claude Sonnet 4.6 <[email protected]> Signed-off-by: Will Madden <[email protected]>
Add RlsPolicyRenamedIssue, RlsPolicyTamperedIssue, and RlsNotEnabledIssue payload interfaces to the framework SchemaIssue union, following the EnumValuesChangedIssue precedent. Fix the one forced exhaustive switch (classifySqlVerifierIssueKind) with provisional category assignments for slice 4 to confirm. Add type-level tests asserting all three kinds are members of SchemaIssue. Co-Authored-By: Claude Sonnet 4.6 <[email protected]> Signed-off-by: Will Madden <[email protected]>
Extend the existing enum_values_changed guards in issueLocation, isMissing, classifyIssue, and buildRecreatePostchecks to also exclude the three new RLS kinds. These functions access BaseSchemaIssue fields (table, column, actual, etc.) that the RLS interfaces do not carry; narrowing them out restores the type invariant without adding any RLS-specific planner logic. Export the three new payload interfaces from the framework-components control entrypoint. Co-Authored-By: Claude Sonnet 4.6 <[email protected]> Signed-off-by: Will Madden <[email protected]>
Co-Authored-By: Will Madden <[email protected]> Signed-off-by: Will Madden <[email protected]>
…near project Drive build-loop artifacts for slice `foundation` (TML-2868): D2–D4 dispatch briefs, the closed trace.jsonl (4 dispatches / 6 rounds / 6 briefs, backstop green), and the spec/plan update pointing at the dedicated Postgres RLS Linear project. D1 artifacts already committed in 1f4e81e. Signed-off-by: Will Madden <[email protected]> Co-Authored-By: Claude Opus 4.8 <[email protected]>
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughAdds end-to-end PostgreSQL Row-Level Security support: introduces a generic ChangesPostgreSQL RLS end-to-end flow
Estimated code review effort🎯 5 (Critical) | ⏱️ ~120 minutes Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
@prisma-next/extension-author-tools
@prisma-next/mongo-runtime
@prisma-next/family-mongo
@prisma-next/sql-runtime
@prisma-next/family-sql
@prisma-next/extension-arktype-json
@prisma-next/middleware-cache
@prisma-next/mongo
@prisma-next/extension-paradedb
@prisma-next/extension-pgvector
@prisma-next/extension-postgis
@prisma-next/postgres
@prisma-next/sql-orm-client
@prisma-next/sqlite
@prisma-next/extension-supabase
@prisma-next/target-mongo
@prisma-next/adapter-mongo
@prisma-next/driver-mongo
@prisma-next/contract
@prisma-next/utils
@prisma-next/config
@prisma-next/errors
@prisma-next/framework-components
@prisma-next/operations
@prisma-next/ts-render
@prisma-next/contract-authoring
@prisma-next/ids
@prisma-next/psl-parser
@prisma-next/psl-printer
@prisma-next/cli
@prisma-next/cli-telemetry
@prisma-next/config-loader
@prisma-next/emitter
@prisma-next/language-server
@prisma-next/migration-tools
prisma-next
@prisma-next/vite-plugin-contract-emit
@prisma-next/mongo-codec
@prisma-next/mongo-contract
@prisma-next/mongo-value
@prisma-next/mongo-contract-psl
@prisma-next/mongo-contract-ts
@prisma-next/mongo-emitter
@prisma-next/mongo-schema-ir
@prisma-next/mongo-query-ast
@prisma-next/mongo-orm
@prisma-next/mongo-query-builder
@prisma-next/mongo-lowering
@prisma-next/mongo-wire
@prisma-next/sql-contract
@prisma-next/sql-errors
@prisma-next/sql-operations
@prisma-next/sql-schema-ir
@prisma-next/sql-contract-psl
@prisma-next/sql-contract-ts
@prisma-next/sql-contract-emitter
@prisma-next/sql-lane-query-builder
@prisma-next/sql-relational-core
@prisma-next/sql-builder
@prisma-next/target-postgres
@prisma-next/target-sqlite
@prisma-next/adapter-postgres
@prisma-next/adapter-sqlite
@prisma-next/driver-postgres
@prisma-next/driver-sqlite
commit: |
size-limit report 📦
|
The shipped foundation slice (TML-2868) had no consumer — reachable only through synthetic fixtures — so it proved layers in isolation, not that they connect. Re-cut the remaining slices "tracer bullet first, then thicken": slice 2 is now a thin vertical PSL→IR→CREATE POLICY→PGlite thread that demonstrates RLS filtering rows, with breadth (full authoring; full ops + verifier) and the Supabase walking skeleton + cross-space roles following. Plan diagram/composition/sequencing updated; lesson captured in learnings.md (L1). Linear slices re-scoped to match (TML-2869 tracer, 2870 authoring breadth, 2871 migration+verifier breadth, 2876 supabase skeleton). Signed-off-by: Will Madden <[email protected]> Co-Authored-By: Claude Opus 4.8 <[email protected]>
Rewrite for a fresh implementer with no project context. Spec now leads with six stated design decisions (data model, content-addressed naming, dual authoring surfaces, roles-as-refs, planner/verifier) — each naming the requirement it satisfies and giving one authoritative IR definition — instead of making the reader reverse-engineer the design from functional requirements. Alternatives (authoring-surface options, naming options, settled defaults, still-open items) consolidated at the end. Inlined insider shorthand (Option C, D1/D3, Q2-Q5, OC/C codes); removed slice-sequencing from the spec (plan owns it) and stale "four slices" references. Plan de-jargoned and given a slicing-alternatives section. Signed-off-by: Will Madden <[email protected]> Co-Authored-By: Claude Opus 4.8 <[email protected]>
…leton slice 1
Replace the leaky verifier design (framework SchemaIssue widening +
StorageTable.rls in SQL core) with a generic SchemaIR<->SchemaIR differ:
issues become {coordinate, outcome}, node identity()/isEqualTo() are virtual
methods, planning is per-node create/delete/update -> OpFactoryCall. The
framework/SQL-family never reference RLS. Spec D5 rewritten; D1 drops the
StorageTable.rls leak; layering invariant tightened; alternatives record the
union-widening and cross-hierarchy-diff rejections.
Plan merged to four slices: slice 1 is the RLS walking skeleton (thin PSL
policy_select through the new differ to PGlite row-filtering, stripping the
foundation leaks as part of building the right path), then authoring breadth,
verify/plan breadth, supabase skeleton. The 25-kind relational port and
dependency-aware planner ordering are named independent follow-on projects
that never gate RLS.
Signed-off-by: Will Madden <[email protected]>
Co-Authored-By: Claude Opus 4.8 <[email protected]>
Durable record of the design discussion: the leak and its root cause, the generic SchemaIR<->SchemaIR differ, identity-vs-equality as node virtual methods, derivation-holds-the-smarts, per-node planner dispatch, coarse-vs- dependency ordering, scope (top-level layer for RLS; relational port + dependency planner deferred), and the ground-truth research anchors. Signed-off-by: Will Madden <[email protected]> Co-Authored-By: Claude Opus 4.8 <[email protected]>
…ive) File-by-file slice spec for slice 1 (the generic-differ walking skeleton): the leak-removal manifest (exact file:line), the framework SchemaDiffIssue + DiffableNode + diffNodes design, PostgresRlsPolicy/Role implementing DiffableNode, pg_policies/pg_roles introspection into annotations.pg, per-node CreateRlsPolicy/EnableRowLevelSecurity ops mirrored on AddForeignKeyCall, the policy_select PSL descriptor from the landed fixture, the verify extension channel, and the end-to-end PGlite SET-ROLE row-filtering test. Binary ACs + halt conditions. Pinned to real seams via the integration-seam research. Signed-off-by: Will Madden <[email protected]> Co-Authored-By: Claude Opus 4.8 <[email protected]>
…brief Signed-off-by: Will Madden <[email protected]> Co-Authored-By: Claude Opus 4.8 <[email protected]>
…rs to postgres target - Remove RlsPolicyRenamedIssue, RlsPolicyTamperedIssue, RlsNotEnabledIssue interfaces and their SchemaIssue union members from framework-components - Remove their exports from control.ts - Remove the three RLS case arms from classifySqlVerifierIssueKind in verifier-disposition.ts - Remove RLS narrowing guards from SQLite planner (issue-planner.ts, planner-strategies.ts, operations/tables.ts) and Postgres planner (issue-planner.ts) - Remove StorageTable.rls / RlsMode from storage-table.ts, types.ts, exports/types.ts, and StorageTableSchema in validators.ts - Move PostgresRoleSchema and PostgresRlsPolicySchema into packages/3-targets/3-targets/postgres/src/core/postgres-validators.ts - Add entrySlotName to AuthoringEntityTypeDescriptor so targets declare their own namespace entry slots - Wire postgres role/rlsPolicy descriptors with entrySlotName via the entityTypes fragment channel - Generalize createNamespaceEntrySchema and createSqlContractSchema to accept validatorEntrySlots, removing hardcoded role/rlsPolicy slots from SQL family core - Update tests to remove assertions for deleted features Co-Authored-By: Will Madden <[email protected]> Signed-off-by: Will Madden <[email protected]>
…tch) Signed-off-by: Will Madden <[email protected]> Co-Authored-By: Claude Opus 4.8 <[email protected]>
Adds `schema-diff.ts` to the framework with `SchemaDiffOutcome`, `SchemaDiffIssue`, `DiffableNode`, and `diffNodes` — fully RLS-agnostic; no Postgres imports. Exports all three from `exports/control.ts`. `PostgresRlsPolicy` and `PostgresRole` implement `DiffableNode`: `identity()` returns an `EntityCoordinate` with the appropriate `entityKind` (`rlsPolicy` / `role`) and the wire name as `entityName`; `isEqualTo` compares by name. Both methods are prototype-defined so they survive `freezeNode`. The policy node gains a nullable `namespaceId` field (defaults to `UNBOUND_NAMESPACE_ID`) to populate the coordinate. Unit tests cover: missing/extra/mismatch/clean + deterministic order for the differ; identity/isEqualTo/freeze survival for both Postgres node types. Co-Authored-By: Claude Sonnet 4.6 <[email protected]> Signed-off-by: Will Madden <[email protected]>
Signed-off-by: Will Madden <[email protected]> Co-Authored-By: Claude Opus 4.8 <[email protected]>
…ovider The interpreter no longer falls back to target.authoring.createNamespace (removed when the target type narrowed to the framework TargetPackRef during the #851 merge). That broke the PSL emit path for configs that lower extension entities (e.g. examples/supabase RLS policy) without explicitly passing createNamespace, surfacing as 'extension entities lowered but the target supplies no createNamespace factory'. Restore the fallback in the PSL provider: read createNamespace off the target pack's authoring descriptor (a typed view via blindCast, since the framework AuthoringContributions type does not declare this SQL-specific field) and pass it to the interpreter when the caller does not supply one explicitly. Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
Multi-space db verify runs per space, each with its own contract, but the live schema introspection returns RLS policies across every DB schema. Without scoping, a space that owns only auth/storage (the supabase extension space) reported the application space's public.* policies as extra and failed verify. Filter the introspected policies to the namespaces the verified contract declares before diffing. Cross-space / external policies are ignored; a genuine extra in an owned namespace still surfaces, and a missing owned policy still fails (covered by the supabase drift-fails-verify e2e). Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…diff The previous scoping commit compared raw namespace slot keys, but a single-namespace contract carries the late-bound `__unbound__` id while its introspected policies (and the migration planner's schema IR) may carry either `__unbound__` or the resolved `public` schema name. Comparing raw ids filtered out owned policies, regressing rls-collect-extension-issues and rls-planner (extra/missing/edit cases). Normalize both the owned-namespace set and each introspected policy's namespaceId through the same unbound -> public resolution before the ownership check. Cross-space policies (e.g. the app's `public.*` seen by the supabase space that owns only auth/storage) are still ignored; owned-namespace extra/missing still surface. Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…harAt `biome check --error-on-warnings` flagged 11 `noNonNullAssertion` warnings in the RLS predicate canonicalizer (`sql[i]!`, `out[out.length-1]!`), failing `pnpm lint:packages` for @prisma-next/target-postgres. These indexed reads are inside `while (i < length)` guards, so String.prototype.charAt(i) is an exact equivalent that returns `string` without the assertion. No behavior change; all 479 target-postgres tests pass. Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…ross-ns test
`pnpm lint:packages` (biome --error-on-warnings) flagged two warnings in
@prisma-next/adapter-postgres RLS code:
- control-adapter.ts: noNonNullAssertion on the policy-name regex match group —
replace `hashSuffixMatch[1]!` with `hashSuffixMatch?.[1] ?? row.policyname`
- cross-namespace-fk.integration.test.ts: useIndexOf — replace
`findIndex((id) => id === 'schema.auth')` with `indexOf('schema.auth')`
No behavior change.
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
…thresholds The alwaysApply rule added in this PR pushed the rules footprint over three thresholds (main left them right at the limit). Trim the rule from 43 to ~18 lines — keep the essence (missing @prisma-next/* is a build/install-state issue; verify with require.resolve since pnpm links per-consumer, not at repo root; then pnpm build for stale dist / pnpm install for a new dep), drop the long sub-sections. Bump the three exceeded thresholds in rules-footprint.config.json minimally with small headroom for the trimmed rule (sanctioned for intentional additions per the check message). Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…nges: []) check:upgrade-coverage requires a per-PR declaration whenever the PR touches examples/ or packages/3-extensions/. This PR's touches there are the additive Postgres RLS demo (supabase contract re-emit, profile-queries, skeleton test, bootstrap helper) plus merge regeneration — no downstream breaking change. Keep changes: [] in both 0.14-to-0.15 instruction files and add an HTML-comment note (matching the existing TML-2787/2929/2794 style) recording the TML-2868 incidental diff: RLS is opt-in, existing schemas emit/verify unchanged, no user or extension-author action — re-emit absorbs the contract shape. Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…olds Revert the earlier threshold bump (back to alwaysApply 605 lines / 33000 bytes, total 203500 bytes) and instead cut always-loaded rule content to fit. main left the always-loaded footprint at the limit with zero headroom, so the new workspace-package-not-found rule overflowed; keeping it requires cutting equivalent content. - workspace-package-not-found-run-pnpm-install.mdc: 18 -> ~13 lines (bare steps) - prefer-psl-in-design-docs.mdc: 70 -> ~28 lines (drop worked examples, keep the lead-with-PSL guidance, the prisma-not-psl fence rule, and the superset/design rationale) - no-transient-project-ids-in-code.mdc: 68 -> ~40 lines (condense the forbidden/allowed lists and how-to-comply; keep the grep check) Footprint now: alwaysApply 522 lines / 27.6 KB, total 194.4 KB — all under the original thresholds with headroom. No rule guidance lost, only verbose prose and restated examples. Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…r blindCast The PSL provider read the target's createNamespace through a blindCast over the framework AuthoringContributions (which doesn't declare the SQL-specific field). Replace it with a real SQL-family type: - Add SqlNamespaceFactory + SqlAuthoringContributions (extends the framework AuthoringContributions with the optional createNamespace) and a isSqlAuthoringContributions type predicate to @prisma-next/sql-contract's sql-storage module; export both. createNamespace stays out of the framework AuthoringContributions (SQL-specific). - The predicate narrows cast-free via Object.hasOwn + Reflect.get. - provider.targetCreateNamespace now narrows target.authoring with the predicate and returns createNamespace — no blindCast, no bare as. supabase emit still resolves createNamespace via the target fallback (config does not pass it explicitly); build, typecheck, contract-psl/sql-contract tests, lint:packages, lint:casts, lint:deps all green. Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…matching Operator decision: there is no tamper detection. The content hash exists to avoid comparing predicate bodies — the wire name (prefix + 8-hex hash) is the only equivalence relation, and the hash is never recomputed from an introspected body. So the reprint-matching normalization had no purpose. Cut canonicalize.ts from 445 to 48 lines: keep ContentHashParts, RlsPolicyOperation, computeContentHash, and a minimal normalizePredicate that only trims and collapses internal whitespace of the authored predicate. Remove stripCommentsAndLowercase, normalizeCastAliases, stripRedundantCastParens, stripTopLevelAndParens, isOuterParenWrapped, and the hasTopLevel* helpers. Minimal normalization is also safer for the no-collision property — it never collapses two distinct predicates onto one hash. Tests: drop the reprint-equivalence cases (lowercasing, paren-strip, comment- strip, cast-alias, ::text) that asserted a Postgres-reprinted form hashes the same as the authored form — that scenario no longer exists. Keep the distinct-predicate counter-corpus and the whitespace-equivalence + role order/dedup cases. Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
The minimal predicate normalizer changes the content hash, so the example's RLS policy wire name re-suffixes (profile_owner_read_3486711c → _9f8e536e). Slice 1 hasn't shipped, so there is no compat concern. Regenerated via prisma-next contract emit. Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
Reflect the operator decision that there is no tamper detection. The content hash addresses the authored predicate and the wire name is the only equivalence relation; the framework never recomputes the hash from an introspected body and never compares predicate bodies. - spec.md: normalizer description → minimal (collapse internal whitespace + trim); drop the "tamper detection is cheap / recompute from introspected row" bullet; rewrite the no-false-drift blockquote to justify content addressing without claiming the normalizer matches Postgres's reprint; drop the recomputed-hash-mismatch acceptance clause and the rls_policy_tampered issue kind; add an explicit non-goal that out-of-band ALTER POLICY on a hashed policy is unsupported (surfaces as an ordinary extra → drop, not a tamper signal). Rename handling kept throughout. - adr-content-addressed-policy-names.md: hash-input + cross-kind normalizer descriptions → minimal; verifier semantics use the generic differ outcomes (rename/missing/extra/mismatch) instead of framework rls_* issue kinds; remove the tamper issue kind and the "cheap tamper detection" benefit. - plan.md: slice 2 drops the tamper variation (rename, role traversal, managed/external kept). Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
Per review: type guards must narrow structurally, not by instanceof, and take the abstract base type as input. - isPostgresSchemaIR(schema: SqlSchemaIR): schema is PostgresSchemaIR — input is the base SqlSchemaIR (was unknown); narrows on the postgres-only own field rlsPolicies via 'rlsPolicies' in schema + Array.isArray (cast-free). Removed the instanceof branch. Still narrows the projectSchemaToSpace spread-into- plain-object case (the field is enumerable so it survives the spread; the family kind discriminator is shared and non-enumerable, so unusable). - PostgresRlsPolicy.isEqualTo now guards with the structural isPostgresRlsPolicy instead of `other instanceof PostgresRlsPolicy`. - Simplified isPostgresRlsPolicy + assertPostgresRlsPolicy to read node.kind cast-free after the 'kind' in node narrow, dropping the blindCast + its import. No instanceof in these guards; no bare as. build/typecheck/target-postgres(446)/ adapter-postgres(648) + multi-space scoping path green. Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…criminant Per review: the 'rlsPolicies' in schema duck-type is brittle (breaks if rlsPolicies is ever made optional). Replace it with a reliable target discriminant. - Add SqlSchemaTarget = 'sql' | 'postgres' and an enumerable readonly nodeTarget field on the schema-root IR: SqlSchemaIR carries 'sql' (optional on the type so existing plain-data SqlSchemaIR literals still satisfy it without restating the field), PostgresSchemaIR carries 'postgres'. nodeTarget is a plain class-field initializer (enumerable, unlike the shared non-enumerable kind), so it survives the projectSchemaToSpace spread the multi-space verify path relies on. - isPostgresSchemaIR(schema: SqlSchemaIR): schema is PostgresSchemaIR now returns schema.nodeTarget === 'postgres' — no 'rlsPolicies' in …, no instanceof, no cast. Export SqlSchemaTarget from both schema-ir type barrels. build/typecheck/target-postgres(446)/adapter-postgres(648, incl multi-space scoping)/lint:packages/fixtures:check all green. No snapshot churn from the new field. 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]>
What this delivers
SELECT row-level security (RLS) policies for Postgres — authored in PSL and
dependable against a live database. A policy is created on migrate, edits replace
it, and any out-of-band change makes
prisma db verifyfail. Proven end-to-endin the
examples/supabaseapp.Scope — what works
policy_selectblock lowers, through the productioncontract emitpath, into the contract as a first-class Postgres-target IR node.db init/db update: the planner emitsENABLE ROW LEVEL SECURITY+CREATE POLICY; editing a predicate creates the new policy and drops the old(exactly one active afterward); a policy removed from the contract on a managed
table is dropped (strict reconcile).
db verify: reports policy drift (missing, orphaned, or out-of-bandchanged) and exits non-zero, naming the policy.
examples/supabase: rows arefiltered under
SET ROLE authenticated, and an out-of-bandDROP POLICYfailsverify.
Known limitation — disclosed, not silent
migration plandoes not yet emit RLS. Generating a migration offline buildsthe schema from contracts, and the contract→schema derivation does not yet carry
target-specific objects such as policies. Rather than silently produce a
migration with no RLS,
migration planfails with a clear error when thecontract declares policies, pointing you at
db init/db update. The genericseam that removes this limitation is the next slice (
entity-kind-migration-seam,"slice 1.5"); design seed in
projects/postgres-rls/specs/extension-migration-participation.md.How it works
Verification and planning derive policy nodes from the contract, introspect the
live database into the same node types, and compare them with a generic differ:
nodes answer
identity()/isEqualTo(), and the differ emits only{ coordinate, outcome: missing | extra | changed }. No RLS symbol appears inthe framework or SQL-family layers — enforced by a structural test, because
import-direction linting can't catch this leak class.
profile_owner_read);an 8-hex hash of the normalized policy body is appended
(
profile_owner_read_dc40c58a). Identity is name-equality, so Postgresreprinting a predicate never reads as drift; a real body change does. The
normalizer collapses only reprint artifacts (casing, comments,
::textannotations, redundant parens) and is pinned by a counter-case corpus so two
different predicates can't collide on one name.
policy not present in the contract is dropped — there is no per-policy "is this
ours" flag. (Table-level
managed/externalgrading is slice 2.)Deferred — tracked in
projects/postgres-rls/plan.mdcontribution (project-from-contract + project-from-database) so a contributed
kind works on every command, removing the
migration planlimitation above.managed/externaltable grading andDISABLE ROW LEVEL SECURITYon removal.Verification
examples/supabase): authored PSL →db init→ rowsfiltered under
SET ROLE authenticated→db verifyok → out-of-bandDROP POLICY→db verifyexits non-zero naming the policy.removal-and-drift fails verify; the content-addressing counter-case corpus; and
a structural test asserting no RLS symbol in
packages/1-framework/packages/2-sql.🤖 Generated with Claude Code