Repository navigation
TML-2778: control policy — set control/defaultControl from the TS contract builder - #692
Conversation
📝 WalkthroughWalkthroughThis PR extends the SQL contract authoring and building pipeline to accept and propagate optional ChangesControlPolicy Integration
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~20 minutes Possibly related PRs
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 docstrings
🧪 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/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/emitter
@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 📦
|
536a1ac to
75a6eb9
Compare
Read per-table control through sqlSpec in lowering (drop redundant RuntimeModelSpec field). Pin compile-time rejection of invalid per-table control literals and assert managed override is written on the table. Signed-off-by: Will Madden <[email protected]>
75a6eb9 to
b9bcbea
Compare
Read per-table control through sqlSpec in lowering (drop redundant RuntimeModelSpec field). Pin compile-time rejection of invalid per-table control literals and assert managed override is written on the table. Signed-off-by: Will Madden <[email protected]>
b9bcbea to
439b356
Compare
Signed-off-by: Will Madden <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Thread optional contract-level defaultControl through the SQL TS builder into Contract.defaultControl so extension authors can declare the default control policy once. Signed-off-by: Will Madden <[email protected]>
Thread optional control on the model sql stage into StorageTable.control and add tests that assert effective control via effectiveControl, including a mixed default plus per-table override contract that round-trips. Signed-off-by: Will Madden <[email protected]>
Address review nits: drop the loose expectTypeOf from the describe body (the type-level rejection assertion already lives in an it in the type-test file), add an explicit no-control/no-defaultControl omission test to pin the no-hash-churn guarantee at the authoring layer, and round-trip the mixed-control contract through validateSqlContractFully (the canonical SQL deserializer) instead of a bare JSON reshape. Signed-off-by: Will Madden <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Read per-table control through sqlSpec in lowering (drop redundant RuntimeModelSpec field). Pin compile-time rejection of invalid per-table control literals and assert managed override is written on the table. Signed-off-by: Will Madden <[email protected]>
…base on main Signed-off-by: Will Madden <[email protected]>
439b356 to
65720eb
Compare
Read per-table control through sqlSpec in lowering (drop redundant RuntimeModelSpec field). Pin compile-time rejection of invalid per-table control literals and assert managed override is written on the table. Signed-off-by: Will Madden <[email protected]>
…ect's control policy (prisma#694) ## At a glance **Control policy** is a per-object setting that says *how much the framework manages a given database object* — from `managed` (fully owned) to `external` (known about but never touched — think Supabase's `auth.users`). The policy lives on the contract IR already (slice 1). **This PR teaches the schema verifier to react to it**, instead of demanding every object match the contract exactly. The motivating case: an app declares a foreign key into Supabase's `auth.users` and marks that table `external`. The verifier should confirm the columns the app *declared* are present and shape-compatible — but ignore the dozens of columns Supabase adds that the app never mentioned. Today the verifier treats every object as `managed`, so any such divergence is an error. After this PR it branches on `effectiveControl(node.control, contract.defaultControl)` and maps the **existing** issue kinds onto pass / warn / fail / suppressed — no new issue kinds, no result-shape change: | Live-vs-declared | `managed` | `tolerated` | `external` | `observed` | |---|---|---|---|---| | Declared column missing | fail | fail | fail | warn | | Declared column type-incompatible | fail (exact) | fail (exact) | fail (compatible-shape) | warn | | Extra column | fail | suppress | suppress | warn | | Extra constraint / index | fail | fail | suppress | warn | | Enum value drift | fail | fail | suppress | warn | | Object absent entirely | fail | fail | fail | warn | ## The decision **Strict by default.** A non-`managed` policy does *not* soften checks on the columns you actually declared — `tolerated` and `external` still **fail** on a declared column that's missing or type-incompatible; they only relax what they say about *undeclared* extras. Only `observed` downgrades everything to `warn`. The reasoning is one-directional and the deciding factor: **loosening a check later (fail → warn) is a non-breaking change, but tightening one (warn → fail) turns previously-green builds red.** Starting strict keeps the cheaper evolution path open. Two supporting decisions follow the same instinct: - **Conservative compatible-shape for `external`:** Postgres's `columnsCompatible` is identical-or-explicitly-listed, and the list is empty in v0.1 — so `varchar` vs `text` is still a `fail` today. Widening the compatible set later is additive and safe. - **`external` requires existence:** an `external` object (or enum) that is absent entirely is a `fail` — declaring an external dependency that isn't there is a real error, not a tolerable divergence. ## How it works The severity mapping is one small pure pair — `verifierDisposition` / `classifyVerifierIssueKind` — placed in the framework-agnostic `@prisma-next/contract` foundation package so both the SQL and Mongo families consume the *same* table with no upward import (mirroring the `effectiveControl` precedent from slice 1). Each family base calls it through thin `pushControlled*` emit helpers. The compatible-shape relation is a **target-supplied hook**: abstract on the family base, concrete `postgresColumnsCompatible` on Postgres, threaded through both the migration-verify and runtime-verify paths so they agree. Enum (`PostgresEnumStorageEntry`) verification dispatches through the same table — the proof that target-contributed node kinds flow through one dispatch rather than a parallel hardcoded path. ## Scope **In:** four-way severity/suppression dispatch on the SQL + Mongo family verifier bases; the target-supplied compatible-shape hook + the conservative Postgres relation; enum dispatch; per-policy tests for both families. **Out (unchanged):** planner DDL gating (prisma#693), TS/PSL authoring (prisma#692 / slice 5), and widening the compatible-pair list. **Testing:** `pnpm typecheck` (contract, family-sql, target-postgres, adapter-postgres); package tests (contract 159, family-sql 309, target-postgres 331, adapter-postgres 537 + 4 expected-fail) with real status assertions per policy for SQL, Mongo, and enums; `pnpm lint:deps` clean, `pnpm lint:casts` delta 0. ## Alternatives considered - **Loosen by default** (let `tolerated`/`external` soften checks on declared columns too). Rejected on the one-directional argument above: we can always relax later without breaking anyone; we cannot tighten without breaking green builds. - **Introduce new `SchemaIssue` kinds for tolerated/external divergence.** Rejected: reusing the existing kinds plus a disposition keeps the result shape stable and avoids forcing every issue consumer to learn a new vocabulary. - **Aggressive compatible-shape** (treat `varchar`/`text`, `int4`/`int8`, etc. as compatible out of the gate). Deferred: starting from exact-equality and widening additively is safe; starting wide and narrowing is not. **Acknowledged transitional shapes (not blocking):** `PostgresSchemaVerifier.verifyCommonSqlSchema` is still an empty SPI-migration stub, so the class-based `columnsCompatible` is reached via the `verifySqlSchema` function option rather than the abstract method — two seams for one concept, to consolidate when the SPI migration lands. Whole extra tables/collections still `fail` under `tolerated`/`external` (the severity table is column/constraint-grained) — defensible under strict-by-default. --------- Signed-off-by: Will Madden <[email protected]> Co-authored-by: Will Madden <[email protected]>
…l policy (prisma#693) ## At a glance **Control policy** is a per-object setting that says *how much the framework's migration machinery is allowed to touch a given database object* — from `managed` (fully owned: create, alter, drop) to `external` (known about but never emitted — think Supabase's `auth.users`). The policy lives on the contract IR already (slice 1). **This PR teaches the migration planner to obey it.** Before, the planner treated every object as fully owned and emitted whatever DDL the diff implied. Now it consults `effectiveControl(node.control, contract.defaultControl)` for each object first: | Policy | DDL the planner will emit | |---|---| | `managed` | full lifecycle — `CREATE` / `ALTER` / `DROP` *(unchanged from today)* | | `tolerated` | `CREATE` if missing — never `ALTER` / `DROP` | | `external` | none | | `observed` | none | So a table marked `external` produces **no** migration DDL, even when the live database differs from the contract — which is exactly what you want for a table some other system owns. ## The decision On top of the per-object gate sits an **un-overridable safety floor**: when a contract space's `defaultControl` is `external`, the planner emits **zero** DDL into that space's namespaces *even if* an object inside carries a per-object `control: 'managed'`. A per-object override **cannot escalate above** the namespace floor. When the floor suppresses DDL that a `managed` declaration would otherwise have produced, the planner emits a **`warn`-level** diagnostic (`control_managed_in_external_space`) naming the object and namespace — and lets the plan proceed. We chose **`warn`, not `fail`**: the safe thing has already happened (nothing leaked into the external schema), so halting the entire plan would be heavier than a single mis-declaration warrants. And we made the floor **un-overridable** on purpose — an `external` space is precisely where a stray `managed` object must not be able to punch a hole. ## How it works The per-node gate is a pure function of effective control, placed on the SQL family seam so any SQL target inherits it; Postgres supplies the concrete planner wiring. The external-namespace floor is computed per namespace from the space's `defaultControl`, independent of the per-object values beneath it. The `warn` diagnostic is attached to the concrete `PostgresPlanResult`. Unit tests cover all four policy gates plus the mis-declaration (managed-in-external) case with real assertions. ## Scope **In:** per-node DDL gate (SQL family seam + Postgres planner), the external-namespace floor, the `warn`-level conflict diagnostic, and unit tests for all four policies + the mis-declaration case. **Out (unchanged):** verifier comparison strategies (prisma#694), TS/PSL authoring (prisma#692 / slice 5), the Mongo planner, and introspection defaulting. **Known follow-up (out of scope, tracked):** the `warn` diagnostic is produced on `PostgresPlanResult`, but the framework `MigrationPlannerResult` success variant has no `warnings` field yet, so nothing surfaces it to a user end-to-end. Wiring it through the framework result type + CLI is tracked in **TML-2792**. **Testing:** `pnpm typecheck` (`family-sql`, `target-postgres`), package tests (family-sql 309/309, target-postgres 339/339), `pnpm lint:casts` delta 0, `pnpm lint:deps` — all green. ## Alternatives considered - **`fail` instead of `warn` for managed-in-external.** Rejected: the unsafe outcome was already prevented, so a hard failure over-penalises a recoverable mis-declaration. - **Make the floor overridable by a per-object `managed`.** Rejected: that defeats the purpose of marking a whole space `external` — the floor exists so a single mis-declared object can't escalate the space back into "framework emits DDL here." - **Gate with bare `as` casts** (the first implementation). Replaced: an independent review flagged 5 net-new bare casts tripping the `lint:casts` ratchet; they were eliminated by narrowing (typed accessors / discriminated-union narrowing), leaving the ratchet delta at 0 with no `blindCast`. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit ## Release Notes * **New Features** * Control policy filtering now integrated into migration planning to respect table and schema management modes (managed, tolerated, external, observed). * Added public APIs for control policy filtering and resolution. * New helper utilities for safe table lookups in storage. * **Tests** * Added comprehensive test coverage for control policy filtering across all management modes. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Signed-off-by: Will Madden <[email protected]> Co-authored-by: Will Madden <[email protected]>
At a glance
Control policy is a per-object setting that says how much the framework's migration and verification machinery is allowed to touch a given database object — on a spectrum from
managed(the framework fully owns it: create, alter, drop) toexternal(the framework knows about it but must never emit DDL for it — think Supabase'sauth.users). The policy lives on the contract IR already, and the verifier and planner react to it (sibling PRs #694 and #693). This PR is the authoring surface — how a person actually sets the policy from the TypeScript contract builder:That is the entire surface: one contract-level
defaultControl, one per-tablecontroloverride. After this PR,effectiveControl(node.control, contract.defaultControl)(the resolver from slice 1) returnsmanagedforapp_userandexternalforuser_profile— exactly the value the verifier and planner branch on.The decision
Set the policy in two places, both of which lower straight to the IR with no authoring-time logic: a contract-level
defaultControlondefineContract({…})(the 80% path — an extension author sets it once for their whole space) and a per-tablecontrolon.sql({…})(the override). Critically, authoring does not validate combinations — amanagedtable inside adefaultControl: 'external'contract is accepted here, not rejected. The planner's safety floor (#693) is the audit trail for that case. Rejecting it here would duplicate that rule in a second place and force authors to learn it twice; we keep one source of truth.How it works
defaultControlis a new optional field on thedefineContractinput and lowers verbatim toContract.defaultControl. The per-tablecontrolrides on the existing.sql({…})stage spec — co-located with the other table-level storage metadata liketable:— and lowers toStorageTable.control. Both are typed to the fourControlPolicyliterals, so an invalid value ('mananged') is a compile error; a negative type test pins that.Because slice 1 omits
controlfrom the serialized form whenever it equals the effective default, the tests assert effective control through the resolver rather than raw field presence, and confirm the omit-when-default property survives a canonical round-trip (validateSqlContractFully). That is what keeps existingmanagedcontracts hashing identically — no fixture churn from this change.Scope
In: SQL TS
defaultControl+ per-tablecontrol, type-checked, lowering-only; an integration test mixing a contract default with per-table overrides and round-tripping through the canonical SQL deserializer.Out (deliberately): PSL authoring (slice 5, TML-2779 — the spelling is still an open question); per-column override (project non-goal); enum / Mongo TS authoring; any verifier or planner behaviour (#694, #693).
Testing:
pnpm typecheck+pnpm test(269) in@prisma-next/sql-contract-ts,pnpm lint:deps— all green. Independent review returned SATISFIED.Alternatives considered
managed-in-externalat authoring time. Rejected: the planner already enforces this floor at plan time (a per-object override cannot escalate above a namespace's external floor), so an authoring-time rejection would be a second copy of the same rule, in a layer that otherwise carries no policy logic..control(...)builder method instead of a.sql({ control })key. Rejected:controlis table-level storage metadata, liketable:and the target schema, so it belongs in the existing stage spec rather than introducing a new chained method.PostgresContractSerializer. Not available at this layer: that serializer lives in3-targetsand importing it into a2-authoringpackage would break layering. The test usesvalidateSqlContractFully— the canonical SQL deserialize path thatSqlContractSerializerBase.deserializeContractitself calls — which is the canonical path reachable here.