Repository navigation
TML-2776: control policy — make schema verification react to each object's control policy - #694
Conversation
📝 WalkthroughWalkthroughThis PR introduces verifier issue categorization and control-policy-driven disposition logic, integrating it throughout MongoDB and SQL schema verification to support managed/tolerated/external/observed control modes. Dispositions (fail/warn/suppress) are computed per control policy and issue kind, enabling selective downgrading or suppression of schema drift findings while maintaining strict enforcement where needed. ChangesControl-Policy Schema Verification
Sequence Diagram(s)sequenceDiagram
participant Verifier as Schema Verifier
participant Disposition as verifierDisposition
participant EmitHelper as pushControlledFinding
participant Issues as Issues Array
participant Nodes as Nodes Array
Verifier->>Disposition: (control, issue_kind)
Disposition-->>Verifier: fail | warn | suppress
alt suppress
Verifier->>EmitHelper: returns early
else fail or warn
Verifier->>EmitHelper: issue, node, disposition
EmitHelper->>Issues: push(issue)
EmitHelper->>Nodes: push(node with status=disposition)
end
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 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 📦
|
| @@ -40,6 +43,19 @@ export abstract class MongoSchemaVerifierBase< | |||
| return { ok: issues.length === 0, issues }; | |||
| } | |||
|
|
|||
| protected effectiveCollectionControl( | |||
There was a problem hiding this comment.
Same naming failure: effectiveCollectionControlPolicy()
| return effectiveControl(collection?.control, contract.defaultControl); | ||
| } | ||
|
|
||
| protected collectionControlForName(contract: TContract, collectionName: string): ControlPolicy { |
| } from '@prisma-next/framework-components/control'; | ||
|
|
||
| function mongoVerifierDisposition( | ||
| control: ControlPolicy, |
There was a problem hiding this comment.
controlPolicy: ControlPolicy,!
| return verifierDisposition(control, issueKind); | ||
| } | ||
|
|
||
| export function pushMongoControlledFinding( |
There was a problem hiding this comment.
Wtf is a "controlled finding"?
| @@ -35,7 +37,13 @@ export function verifyMongoSchema(options: VerifyMongoSchemaOptions): VerifyData | |||
| schema, | |||
| expectedIR, | |||
| ); | |||
| const { root, issues, counts } = diffMongoSchemas(canonicalLive, canonicalExpected, strict); | |||
| const collectionControl = resolveMongoCollectionControl(contract); | |||
There was a problem hiding this comment.
omg collectionControlPolicy
c17bccd to
022713e
Compare
|
Reworked in Your pinned spots:
Swept the whole slice diff (SQL + Mongo): no bare Also in this push (beyond naming): verifier-severity machinery moved out of |
Signed-off-by: Will Madden <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Wire effectiveControl through verifySqlSchema and family helpers so managed/tolerated/external/observed map existing issue kinds to fail, warn, or suppression per the severity table. Postgres supplies a conservative columnsCompatible hook for external type checks. Signed-off-by: Will Madden <[email protected]>
Apply the same verifierDisposition mapping in diffMongoSchemas and expose collection control helpers on MongoSchemaVerifierBase, preserving legacy non-strict managed warn behaviour for extra drift kinds. Signed-off-by: Will Madden <[email protected]>
Enum storage findings now run through the same control-policy disposition as tables and columns: external/observed enums no longer hard-fail on value drift (external suppresses internal value-set drift, observed warns) while existence stays required. Also threads the target-supplied columnsCompatible relation through the runtime verify path so it agrees with the migration planner/runner, and adds direct postgresColumnsCompatible tests plus an end-to-end columnsCompatible threading test. Signed-off-by: Will Madden <[email protected]>
…control context Relocate VerifierIssueCategory, classifyVerifierIssueKind and verifierDisposition out of foundation contract and next to SchemaIssue/SchemaVerificationNode in framework-components/control. The classifier is now typed on SchemaIssue["kind"] with an exhaustive switch and no default arm, so a new issue kind fails to compile until it is graded. Disposition is modelled as VerificationStatus | "suppress" (reusing the canonical status), dropping the parallel enum. Signed-off-by: Will Madden <[email protected]>
…y base The abstract columnsCompatible on SqlSchemaVerifierBase was never invoked; the live seam is SqlControlAdapter.columnsCompatible, threaded into verifySqlSchema. Drop the dead abstract method and its Postgres/SQLite implementations so there is one seam, not two, and future SQL targets are not taxed with a no-op method. Signed-off-by: Will Madden <[email protected]>
… external extra tables Rename every policy-meaning identifier spelled bare ...Control to ...ControlPolicy (tableControlPolicy, extraTableControlPolicy, the pushTypeNode parameter, the effectiveControlPolicy stragglers), keeping the wire keys control/defaultControl. Rename the opaque emit helpers to emitIssueAndNodeUnderControlPolicy / emitIssueUnderControlPolicy, have them return the resolved outcome, and consume that in verifyPrimaryKey so the disposition is computed once (drops dispositionToPkStatus). external now suppresses extra_table so an undeclared live table under external is ignored. Adds tolerated type-mismatch-fail and external extra-table-ignored integration tests. Signed-off-by: Will Madden <[email protected]>
…iquitous language Replace the legacyNonStrictWarn flag and the !strict && managed special-case with one reconciliation point: the control policy decides first, and only a fail is reconciled against the caller-stamped base status (strict ? fail : warn for live-only extras). tolerated/observed no longer diverge from managed on a non-strict extra index. external suppresses extra collections (mirroring SQL). Rename effectiveCollectionControlPolicy / collectionControlPolicyForName, the controlPolicy parameter, the collectionControlPolicy locals, and the emit helper emitMongoIssueAndNodeUnderControlPolicy. Adds Mongo managed, external missing-collection, external extra-collection, and non-strict extra-index tests. Signed-off-by: Will Madden <[email protected]>
… Mongo families The verifier-disposition module welded two concerns together: the target-neutral policy grading and a relational kind classifier (extra_foreign_key, extra_unique_constraint, primary_key_mismatch, ...) that can only occur in SQL. Relational vocabulary does not belong in the target-agnostic framework domain. Split, behaviour-preserving: - Framework keeps the policy primitive only: VerificationStatus, VerifierOutcome, and a target-neutral VerifierIssueCategory (declaredMissing, declaredIncompatible, valueDrift, extraNestedElement, extraAuxiliary, extraTopLevelObject) graded by a new dispositionForCategory(controlPolicy, category). classifyVerifierIssueKind and the kind-based verifierDisposition are removed from the framework. - SQL family owns classifySqlVerifierIssueKind (the exhaustive relational switch) plus a thin verifierDisposition = dispositionForCategory(classify). - Mongo family owns its own classifier over the kinds Mongo emits, with its own thin verifierDisposition. It does not import the SQL classifier; both families depend only on framework dispositionForCategory. Every (controlPolicy, kind) -> outcome is identical to before. The SchemaIssue union is untouched. Signed-off-by: Will Madden <[email protected]>
59ffb25 to
99356f4
Compare
…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 manages a given database object — from
managed(fully owned) toexternal(known about but never touched — think Supabase'sauth.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.usersand marks that tableexternal. 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 asmanaged, so any such divergence is an error. After this PR it branches oneffectiveControl(node.control, contract.defaultControl)and maps the existing issue kinds onto pass / warn / fail / suppressed — no new issue kinds, no result-shape change:managedtoleratedexternalobservedThe decision
Strict by default. A non-
managedpolicy does not soften checks on the columns you actually declared —toleratedandexternalstill fail on a declared column that's missing or type-incompatible; they only relax what they say about undeclared extras. Onlyobserveddowngrades everything towarn.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:
external: Postgres'scolumnsCompatibleis identical-or-explicitly-listed, and the list is empty in v0.1 — sovarcharvstextis still afailtoday. Widening the compatible set later is additive and safe.externalrequires existence: anexternalobject (or enum) that is absent entirely is afail— 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/contractfoundation package so both the SQL and Mongo families consume the same table with no upward import (mirroring theeffectiveControlprecedent from slice 1). Each family base calls it through thinpushControlled*emit helpers.The compatible-shape relation is a target-supplied hook: abstract on the family base, concrete
postgresColumnsCompatibleon 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 (#693), TS/PSL authoring (#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:depsclean,pnpm lint:castsdelta 0.Alternatives considered
tolerated/externalsoften 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.SchemaIssuekinds 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.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.verifyCommonSqlSchemais still an empty SPI-migration stub, so the class-basedcolumnsCompatibleis reached via theverifySqlSchemafunction option rather than the abstract method — two seams for one concept, to consolidate when the SPI migration lands. Whole extra tables/collections stillfailundertolerated/external(the severity table is column/constraint-grained) — defensible under strict-by-default.