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

TML-2776: control policy — make schema verification react to each object's control policy - #694

Merged
wmadden-electric merged 10 commits into
mainfrom
tml-2776-control-policy-slice-2-verifier-dispatch
Jun 2, 2026
Merged

wmadden-electric merged 10 commits into
mainfrom
tml-2776-control-policy-slice-2-verifier-dispatch

Conversation

@wmadden-electric

@wmadden-electric wmadden-electric commented Jun 2, 2026 •

Copy link
Copy Markdown
Contributor

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 (#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: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.

@wmadden-electric
wmadden-electric requested a review from a team as a code owner June 2, 2026 13:04
@coderabbitai

coderabbitai Bot commented Jun 2, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

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

Changes

Control-Policy Schema Verification

Layer / File(s) Summary
Verifier issue classification and disposition contracts
packages/1-framework/0-foundation/contract/src/control-policy.ts, src/exports/types.ts, test/control-policy.test.ts
Introduces VerifierIssueCategory (declaredMissing, incompatible, typeValueDrift, extraColumn, extraConstraint, extraTable) and VerifierDisposition (fail, warn, suppress) types. Adds classifyVerifierIssueKind to map issue strings to categories and verifierDisposition to compute disposition from control policy and issue kind (observed→warn, tolerated suppresses extra-column, external suppresses extra/type-drift, others fail). Tests validate disposition outcomes across control modes.
MongoDB collection-level control infrastructure
packages/2-mongo-family/9-family/src/core/ir/mongo-schema-verifier-base.ts
Extends MongoSchemaVerifierBase generic constraint to include optional defaultControl?: ControlPolicy. Adds protected helpers effectiveCollectionControl and collectionControlForName to compute and resolve collection-specific control from contract defaults or namespace collection config.
MongoDB schema diffing with controlled findings
packages/2-mongo-family/9-family/src/core/schema-diff.ts
Updates diffMongoSchemas signature to accept collectionControl: (collectionName: string) => ControlPolicy callback. Refactors missing/extra collection, index, validator, and options drift detection to emit controlled findings via pushMongoControlledFinding instead of direct node/issue pushes. Helper functions diffIndexes, diffValidator, diffOptions now thread control and return node lists.
MongoDB controlled emission and verification wiring
packages/2-mongo-family/9-family/src/core/schema-verify/mongo-control-verify-emit.ts, verify-mongo-schema.ts
Introduces mongoVerifierDisposition for Mongo-specific disposition overrides (extra_table/extra_index/extra_validator→warn in non-strict managed mode). Implements pushMongoControlledFinding for disposition-aware node/issue emission. Wires resolveMongoCollectionControl resolver into verifyMongoSchema to pass per-collection control into diffMongoSchemas.
MongoDB control-policy test coverage
packages/2-mongo-family/9-family/test/schema-diff.test.ts, schema-verify.control-policy.test.ts
Updates 20+ existing schema-diff tests to use diffMongoSchemasManaged wrapper. Adds new verifyMongoSchema control policy suite with three test cases: tolerated fails on missing collection, external suppresses extra indexes, observed downgrades drift to warnings.
MongoDB target schema verification integration
packages/3-mongo-target/1-mongo-target/src/core/mongo-target-schema-verifier.ts
Updates verifyNamespace to pass namespace-scoped collectionControl callback into diffMongoSchemas.
SQL control adapter and base abstraction
packages/2-sql/9-family/src/core/control-adapter.ts, control-instance.ts, ir/sql-schema-verifier-base.ts
Extends SqlControlAdapter with optional columnsCompatible?: ColumnsCompatible hook. Adds abstract columnsCompatible(declared, live) method to SqlSchemaVerifierBase. Wires adapter's columnsCompatible into verifySqlSchema call.
SQL controlled finding emission helpers
packages/2-sql/9-family/src/core/schema-verify/control-verify-emit.ts
Introduces pushControlledFinding to compute disposition, suppress when applicable, or push issue/node with status set to disposition. Introduces pushControlledIssueOnly for issue-only emission returning warn boolean. Both use verifierDisposition to determine outcome.
SQL constraint verification with control-policy disposition
packages/2-sql/9-family/src/core/schema-verify/verify-helpers.ts
Updates verifyPrimaryKey, verifyForeignKeys, verifyUniqueConstraints, verifyIndexes to accept tableControl: ControlPolicy. Replaces direct issue/node pushes with controlled-emission helpers. Primary key now returns `'pass'
SQL schema verification with control-policy and column compatibility
packages/2-sql/9-family/src/core/schema-verify/verify-sql-schema.ts
Introduces ColumnsCompatible type for target-specific native type compatibility. Routes storage types, table/column presence, type/nullability/default mismatches through disposition-aware emission via pushControlledFinding and verifierDisposition. Enables relaxed type matching (columnsCompatible) when table control is external. Updates storage-type summary status to reflect warn outcomes alongside failures.
SQL control-policy test coverage
packages/2-sql/9-family/test/schema-verify.helpers.ts, schema-verify.control-policy.test.ts
Extends test helpers createTestContract and createContractTable to support defaultControl and per-table control options. Adds comprehensive control-policy test suite with 12+ test cases covering managed/tolerated/external/observed behaviors, enum value drift, and columnsCompatible callback threading.
Postgres column-type compatibility implementation
packages/3-targets/3-targets/postgres/src/core/column-type-compatibility.ts, exports/column-type-compatibility.ts, postgres-schema-verifier.ts, control-adapter.ts
Introduces postgresColumnsCompatible(declared, live) function checking exact equality then explicit bidirectional type-pair mappings (currently empty). Exports via ./column-type-compatibility subpath. Integrates into PostgresSchemaVerifier and PostgresControlAdapter to enable column-compatibility checks in external control mode.
Postgres migration tooling integration
packages/3-targets/3-targets/postgres/src/core/migrations/planner.ts, runner.ts, tsdown.config.ts, package.json
Wires postgresColumnsCompatible into both migration planner and runner schema verification calls. Adds column-type-compatibility export entry to package.json and tsdown build config.
Postgres and SQLite column-compatibility tests
packages/3-targets/3-targets/postgres/test/column-type-compatibility.test.ts, sqlite/src/core/sqlite-schema-verifier.ts
Adds test suite for postgresColumnsCompatible validating identical-type matching and incompatibility of dissimilar types. Implements SQLite's columnsCompatible requiring exact string equality.

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
Loading

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

  • prisma/prisma-next#691: Foundational control-policy and effective-control primitives that this PR's disposition logic builds upon.
  • prisma/prisma-next#632: Both PRs modify enum/type verification behavior; this PR routes through verifierDisposition-driven controlled emit while #632 adds namespace awareness to enum issue payloads.

Poem

🐰 Control and disposition, a schema's true mission—
with tolerated quiet, external wide, and observed warnings inside,
rigid and managed, or softly engaged,
each drift now has a voice across the database page!

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 21.05% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title directly and accurately summarizes the main objective of the PR: implementing control policy-driven schema verification dispatch across different control modes (managed/tolerated/external/observed).

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
📝 Generate docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch tml-2776-control-policy-slice-2-verifier-dispatch

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@pkg-pr-new

pkg-pr-new Bot commented Jun 2, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@prisma-next/extension-author-tools

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

@prisma-next/mongo-runtime

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

@prisma-next/family-mongo

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

@prisma-next/sql-runtime

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

@prisma-next/family-sql

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

@prisma-next/extension-arktype-json

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

@prisma-next/middleware-cache

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

@prisma-next/mongo

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

@prisma-next/extension-paradedb

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

@prisma-next/extension-pgvector

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

@prisma-next/extension-postgis

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

@prisma-next/postgres

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

@prisma-next/sql-orm-client

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

@prisma-next/sqlite

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

@prisma-next/target-mongo

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

@prisma-next/adapter-mongo

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

@prisma-next/driver-mongo

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

@prisma-next/contract

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

@prisma-next/utils

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

@prisma-next/config

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

@prisma-next/errors

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

@prisma-next/framework-components

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

@prisma-next/operations

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

@prisma-next/ts-render

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

@prisma-next/contract-authoring

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

@prisma-next/ids

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

@prisma-next/psl-parser

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

@prisma-next/psl-printer

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

@prisma-next/cli

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

@prisma-next/cli-telemetry

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

@prisma-next/emitter

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

@prisma-next/migration-tools

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

prisma-next

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

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

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

@prisma-next/mongo-codec

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

@prisma-next/mongo-contract

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

@prisma-next/mongo-value

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

@prisma-next/mongo-contract-psl

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

@prisma-next/mongo-contract-ts

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

@prisma-next/mongo-emitter

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

@prisma-next/mongo-schema-ir

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

@prisma-next/mongo-query-ast

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

@prisma-next/mongo-orm

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

@prisma-next/mongo-query-builder

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

@prisma-next/mongo-lowering

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

@prisma-next/mongo-wire

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

@prisma-next/sql-contract

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

@prisma-next/sql-errors

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

@prisma-next/sql-operations

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

@prisma-next/sql-schema-ir

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

@prisma-next/sql-contract-psl

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

@prisma-next/sql-contract-ts

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

@prisma-next/sql-contract-emitter

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

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

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

@prisma-next/sql-relational-core

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

@prisma-next/sql-builder

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

@prisma-next/target-postgres

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

@prisma-next/target-sqlite

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

@prisma-next/adapter-postgres

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

@prisma-next/adapter-sqlite

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

@prisma-next/driver-postgres

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

@prisma-next/driver-sqlite

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

commit: 99356f4

@github-actions

github-actions Bot commented Jun 2, 2026 •

Copy link
Copy Markdown

size-limit report 📦

Path Size
postgres / no-emit 137.29 KB (+0.58% 🔺)
postgres / emit 108.81 KB (0%)
mongo / no-emit 75.77 KB (0%)
mongo / emit 70.78 KB (0%)
cf-worker / no-emit 166.3 KB (+0.55% 🔺)
cf-worker / emit 134.51 KB (0%)

@wmadden-electric wmadden-electric changed the title TML-2776: control policy — verifier dispatch (per-policy comparison + compatible-shape hook) TML-2776: control policy — make schema verification react to each object's control policy Jun 2, 2026

@wmadden wmadden left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Full of naming errors

@@ -40,6 +43,19 @@ export abstract class MongoSchemaVerifierBase<
return { ok: issues.length === 0, issues };
}

protected effectiveCollectionControl(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Same naming failure: effectiveCollectionControlPolicy()

return effectiveControl(collection?.control, contract.defaultControl);
}

protected collectionControlForName(contract: TContract, collectionName: string): ControlPolicy {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

and here

} from '@prisma-next/framework-components/control';

function mongoVerifierDisposition(
control: ControlPolicy,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

controlPolicy: ControlPolicy,!

return verifierDisposition(control, issueKind);
}

export function pushMongoControlledFinding(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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);

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

omg collectionControlPolicy

@wmadden-electric
wmadden-electric force-pushed the tml-2776-control-policy-slice-2-verifier-dispatch branch from c17bccd to 022713e Compare June 2, 2026 15:09
@wmadden-electric

Copy link
Copy Markdown
Contributor Author

Reworked in 022713ebf — addresses the naming review plus the full architect/PE pass.

Your pinned spots:

  • effectiveCollectionControl → effectiveCollectionControlPolicy
  • collectionControlForName → collectionControlPolicyForName
  • mongo-control-verify-emit.ts param control: ControlPolicy → controlPolicy: ControlPolicy
  • verify-mongo-schema.ts local collectionControl → collectionControlPolicy
  • "controlled finding" / pushControlledIssueOnly → emitIssueUnderControlPolicy (+ emitIssueAndNodeUnderControlPolicy, and the Mongo equivalents)

Swept the whole slice diff (SQL + Mongo): no bare …Control identifier that means the control policy remains; only genuine control-plane names (extractCodecControlHooks, controlPlaneHooks, ensureControlTables) are left untouched. Wire keys control/defaultControl kept.

Also in this push (beyond naming): verifier-severity machinery moved out of 0-foundation/contract into framework-components/control with an exhaustive typed classifier (no default arm); dead columnsCompatible base hook removed (single live adapter seam); disposition collapsed onto the canonical VerificationStatus | 'suppress'; extra_table/extra_collection under external now ignored (Supabase case) with tests; Mongo strict×control reconciled through one path. Tests/typecheck/lint:deps green.

wmadden added 10 commits June 2, 2026 18:45
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]>
@wmadden-electric
wmadden-electric force-pushed the tml-2776-control-policy-slice-2-verifier-dispatch branch from 59ffb25 to 99356f4 Compare June 2, 2026 16:48
@wmadden-electric
wmadden-electric merged commit 6ffdac2 into main Jun 2, 2026
20 checks passed
@wmadden-electric
wmadden-electric deleted the tml-2776-control-policy-slice-2-verifier-dispatch branch June 2, 2026 16:59
medz pushed a commit to medz/prisma-next that referenced this pull request Jun 5, 2026
…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]>
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants