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

TML-2777: control policy — gate migration DDL on each object's control policy - #693

Merged
wmadden-electric merged 9 commits into
mainfrom
tml-2777-control-policy-slice-3-planner-dispatch
Jun 2, 2026
Merged

wmadden-electric merged 9 commits into
mainfrom
tml-2777-control-policy-slice-3-planner-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'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 (#694), TS/PSL authoring (#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.

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.

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

coderabbitai Bot commented Jun 2, 2026 •

Copy link
Copy Markdown
Contributor

Review Change Stack

📝 Walkthrough

Walkthrough

This PR introduces generic control policy call filtering for schema migrations. A new ControlPolicySubject type and filterCallsByControlPolicy function enable filtering migration operations by table and enum control policies. Postgres-specific resolution maps op-factory calls to their control subjects, integrates into both structural and field-event DDL planners, and includes comprehensive tests validating managed/tolerated/external/observed policy modes.

Changes

Control Policy Call Filtering Integration

Layer / File(s) Summary
Storage table lookup utility
packages/2-sql/1-core/contract/src/ir/sql-storage.ts, packages/2-sql/1-core/contract/src/types.ts, packages/2-sql/1-core/contract/src/exports/types.ts
New storageTableAt helper safely retrieves a StorageTable from contract namespaces using optional chaining, returning undefined when namespace or table is missing.
Generic control policy filtering
packages/2-sql/9-family/src/core/migrations/control-policy.ts, packages/2-sql/9-family/src/exports/control.ts, packages/2-sql/9-family/test/control-policy.test.ts
ControlPolicySubject interface and filterCallsByControlPolicy function implement a generic pattern for filtering operations by control policy. Policies force external when contract default is external, otherwise delegate to effectiveControlPolicy. Permits calls conditionally: all under managed, only creation under tolerated, none under external/observed. Tests validate all policy modes and external-floor override behavior.
Postgres DDL subject resolution
packages/3-targets/3-targets/postgres/src/core/migrations/control-policy.ts
resolvePostgresCallControlPolicySubject maps Postgres op-factory calls to control subjects by extracting schema/table/column/type fields, resolving applicable namespaceId via storage lookup, determining object-creation via factory-name set, and extracting explicit enum policies from storage.
Issue planner DDL filtering
packages/3-targets/3-targets/postgres/src/core/migrations/issue-planner.ts
Integrates control policy filtering into planIssues to gate structural DDL calls using Postgres subject resolver before returning success result.
Planner field-event filtering
packages/3-targets/3-targets/postgres/src/core/migrations/planner.ts
Wires control policy filtering into codec-hook field-event DDL emission by casting ops to PostgresOpFactoryCall[], gating via subject resolver, and concatenating filtered results after structural calls.
Integration tests
packages/3-targets/3-targets/postgres/test/migrations/control-policy-planner.test.ts
Validates table control modes (managed/tolerated/external/observed) drive DDL differently, confirms external defaultControl suppresses managed DDL while emitting diagnostics, and verifies planning succeeds despite suppressed DDL.

Estimated code review effort

🎯 3 (Moderate) | ⏱️ ~25 minutes

Possibly related PRs

  • prisma/prisma-next#699: The PR's control policy filtering uses the effectiveControlPolicy helper that this PR renames from effectiveControl.
  • prisma/prisma-next#691: The PR depends on control-policy IR primitives introduced in this PR (ControlPolicy type, Contract.defaultControl, and per-node control fields).
  • prisma/prisma-next#692: The PR filters DDL by control policy using contract-derived subjects, while this PR extends the TS contract authoring surface to lower defaultControl and per-table control into the generated Contract<SqlStorage>.

Suggested reviewers

  • wmadden

Poem

🐰 Hops through DDL with careful grace,
Control policies find their place,
Managed, tolerated, observed with care,
No DDL leaks—it's all declared!
The floor is external, the rules are clear,
Schema evolution without fear! 🌿

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 9.76% 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
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The PR title directly and specifically describes the main change: gating migration DDL on each object's control policy, which is the core feature added across all modified files.
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.

✏️ 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-2777-control-policy-slice-3-planner-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.

@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.01% 🔽)
postgres / emit 108.81 KB (-0.01% 🔽)
mongo / no-emit 75.77 KB (0%)
mongo / emit 70.78 KB (0%)
cf-worker / no-emit 166.3 KB (-0.01% 🔽)
cf-worker / emit 134.51 KB (+0.01% 🔺)

@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@693

@prisma-next/mongo-runtime

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

@prisma-next/family-mongo

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

@prisma-next/sql-runtime

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

@prisma-next/family-sql

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

@prisma-next/extension-arktype-json

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

@prisma-next/middleware-cache

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

@prisma-next/mongo

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

@prisma-next/extension-paradedb

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

@prisma-next/extension-pgvector

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

@prisma-next/extension-postgis

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

@prisma-next/postgres

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

@prisma-next/sql-orm-client

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

@prisma-next/sqlite

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

@prisma-next/target-mongo

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

@prisma-next/adapter-mongo

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

@prisma-next/driver-mongo

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

@prisma-next/contract

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

@prisma-next/utils

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

@prisma-next/config

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

@prisma-next/errors

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

@prisma-next/framework-components

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

@prisma-next/operations

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

@prisma-next/ts-render

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

@prisma-next/contract-authoring

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

@prisma-next/ids

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

@prisma-next/psl-parser

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

@prisma-next/psl-printer

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

@prisma-next/cli

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

@prisma-next/cli-telemetry

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

@prisma-next/emitter

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

@prisma-next/migration-tools

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

prisma-next

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

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

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

@prisma-next/mongo-codec

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

@prisma-next/mongo-contract

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

@prisma-next/mongo-value

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

@prisma-next/mongo-contract-psl

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

@prisma-next/mongo-contract-ts

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

@prisma-next/mongo-emitter

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

@prisma-next/mongo-schema-ir

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

@prisma-next/mongo-query-ast

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

@prisma-next/mongo-orm

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

@prisma-next/mongo-query-builder

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

@prisma-next/mongo-lowering

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

@prisma-next/mongo-wire

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

@prisma-next/sql-contract

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

@prisma-next/sql-errors

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

@prisma-next/sql-operations

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

@prisma-next/sql-schema-ir

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

@prisma-next/sql-contract-psl

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

@prisma-next/sql-contract-ts

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

@prisma-next/sql-contract-emitter

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

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

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

@prisma-next/sql-relational-core

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

@prisma-next/sql-builder

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

@prisma-next/target-postgres

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

@prisma-next/target-sqlite

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

@prisma-next/adapter-postgres

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

@prisma-next/adapter-sqlite

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

@prisma-next/driver-postgres

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

@prisma-next/driver-sqlite

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

commit: 5ebc21a

@wmadden-electric
wmadden-electric force-pushed the tml-2777-control-policy-slice-3-planner-dispatch branch from abe8ac4 to f61b22c Compare June 2, 2026 13:32
@wmadden-electric wmadden-electric changed the title TML-2777: control policy — planner DDL gate + external-namespace safety floor TML-2777: control policy — gate migration DDL on 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.

Do a full review with the architect. This is introducing contractions that muddy our ubiquitous language. The property key may be control but it determines the "control policy". You don't "resolve control", you resolve the control policy

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 3

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
packages/3-targets/3-targets/postgres/src/core/migrations/issue-planner.ts (1)

890-955: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Run the control gate before raising operation-class conflicts.

This ordering can reject plans that should succeed with suppressed calls. The recipe strategies called out below can emit helper dataTransform / setNotNull steps for a missing object; under tolerated or external, gateCallsByControlPolicy() should drop those steps, but keepIfAllowed() records conflicts first and return notOk(conflicts) exits before the control gate runs.

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/3-targets/3-targets/postgres/src/core/migrations/issue-planner.ts`
around lines 890 - 955, The conflict check is happening before control gating,
so dropped steps that should be suppressed by gateCallsByControlPolicy still
produce conflicts; to fix, run gateCallsByControlPolicy first and then perform
the operation-class conflict filtering on the gated calls: call
gateCallsByControlPolicy(...) (using the same resolveSubject/options.toContract)
to obtain gated.calls and gated.warnings, then build combinedBucketable/from
those gated.calls and apply the keepIfAllowed/conflictForDisallowedCall logic
against that gated set (or skip keepIfAllowed entirely if gate already removed
disallowed steps); update the function references where conflicts are pushed
(keepIfAllowed, conflictForDisallowedCall, allowedOperationClasses,
gateCallsByControlPolicy, conflicts) so the early return notOk(conflicts) only
happens after control gating has been applied.
🧹 Nitpick comments (1)
packages/2-sql/9-family/test/control-policy-ddl-gate.test.ts (1)

86-205: ⚡ Quick win

Consider adding direct unit coverage for the warning/gating core.

This foundation test exercises schemaIssueDdlIntent, controlPolicyAllowsDdlIntent, shouldEmitSchemaIssue, and resolveControlForSchemaIssue, but not gateCallsByControlPolicy or warningForSuppressedSchemaIssue — the functions that produce the control_managed_in_external_space diagnostic and perform warning dedup. These are currently only validated indirectly via the postgres planner suite; a local unit (including the external-floor managed-override path and the dedup key) would pin the foundation behavior independently.

Want me to draft these unit tests?

🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/2-sql/9-family/test/control-policy-ddl-gate.test.ts` around lines 86
- 205, Add unit tests that directly exercise gateCallsByControlPolicy and
warningForSuppressedSchemaIssue (in addition to the existing tests for
schemaIssueDdlIntent, controlPolicyAllowsDdlIntent, shouldEmitSchemaIssue, and
resolveControlForSchemaIssue). Specifically, add cases that: 1) verify the
control_managed_in_external_space diagnostic is produced when a managed table
exists in an external enum/namespace (exercise the external-floor
managed-override path), and 2) verify warning deduplication by calling
warningForSuppressedSchemaIssue multiple times with the same dedup key and
asserting duplicates are suppressed. Use the same helpers (e.g., makeContract,
SqlStorage build) and the existing SchemaIssue shapes to construct controlled
scenarios; assert both the presence/absence of DDL gating via
gateCallsByControlPolicy and the dedup behavior of
warningForSuppressedSchemaIssue.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/2-sql/9-family/src/core/migrations/control-policy-ddl-gate.ts`:
- Around line 206-217: The function shouldEmitFieldEvent currently
short-circuits when contract.defaultControl === 'external', preventing per-table
managed overrides from reaching the control-policy gate; remove that early
return and always compute table = ctx.newTable ?? ctx.priorTable, compute
control = effectiveControl(table?.control, contract.defaultControl), then call
the existing gate logic (controlPolicyAllowsDdlIntent or the
gateCallsByControlPolicy path that uses fieldEventDdlIntent(event)) so
table-level managed overrides are evaluated and allowed to emit the
control_managed_in_external_space warning while still suppressing the call when
appropriate.

In
`@packages/3-targets/3-targets/postgres/src/core/migrations/control-policy-ddl-resolve.ts`:
- Around line 67-99: In postgresCallDdlIntent update the branch handling
'addEnumValues' so it returns 'alter' instead of 'create' (locate the switch in
function postgresCallDdlIntent and the case 'addEnumValues')—this ensures ALTER
TYPE ... ADD VALUE is treated as an alter operation and won't be incorrectly
allowed through as a create by the managed/tolerated policy logic.

In
`@packages/3-targets/3-targets/postgres/test/migrations/control-policy-planner.test.ts`:
- Around line 8-10: The tests currently call planIssues() directly and skip the
planner-level logic in planner.ts; add at least one integration test that uses
createPostgresMigrationPlanner().plan() (not planIssues) to exercise the gating
and merging behavior from planFieldEventOperations(), ensure
gatedFieldEvents.warnings are merged into the planner result, and assert that
PostgresPlanResult.warnings contains those warnings; implement the test by
constructing a planner via createPostgresMigrationPlanner(), provide a codec
hook that triggers a gated warning from planFieldEventOperations(), call
planner.plan(), and assert the returned result includes the merged warnings.

---

Outside diff comments:
In `@packages/3-targets/3-targets/postgres/src/core/migrations/issue-planner.ts`:
- Around line 890-955: The conflict check is happening before control gating, so
dropped steps that should be suppressed by gateCallsByControlPolicy still
produce conflicts; to fix, run gateCallsByControlPolicy first and then perform
the operation-class conflict filtering on the gated calls: call
gateCallsByControlPolicy(...) (using the same resolveSubject/options.toContract)
to obtain gated.calls and gated.warnings, then build combinedBucketable/from
those gated.calls and apply the keepIfAllowed/conflictForDisallowedCall logic
against that gated set (or skip keepIfAllowed entirely if gate already removed
disallowed steps); update the function references where conflicts are pushed
(keepIfAllowed, conflictForDisallowedCall, allowedOperationClasses,
gateCallsByControlPolicy, conflicts) so the early return notOk(conflicts) only
happens after control gating has been applied.

---

Nitpick comments:
In `@packages/2-sql/9-family/test/control-policy-ddl-gate.test.ts`:
- Around line 86-205: Add unit tests that directly exercise
gateCallsByControlPolicy and warningForSuppressedSchemaIssue (in addition to the
existing tests for schemaIssueDdlIntent, controlPolicyAllowsDdlIntent,
shouldEmitSchemaIssue, and resolveControlForSchemaIssue). Specifically, add
cases that: 1) verify the control_managed_in_external_space diagnostic is
produced when a managed table exists in an external enum/namespace (exercise the
external-floor managed-override path), and 2) verify warning deduplication by
calling warningForSuppressedSchemaIssue multiple times with the same dedup key
and asserting duplicates are suppressed. Use the same helpers (e.g.,
makeContract, SqlStorage build) and the existing SchemaIssue shapes to construct
controlled scenarios; assert both the presence/absence of DDL gating via
gateCallsByControlPolicy and the dedup behavior of
warningForSuppressedSchemaIssue.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

Run ID: 72218e61-8529-4190-8c2f-7cee50576719

📥 Commits

Reviewing files that changed from the base of the PR and between e939a7a and f61b22c.

⛔ Files ignored due to path filters (2)
  • projects/control-policy/slices/planner-dispatch/plan.md is excluded by !projects/**
  • projects/control-policy/slices/planner-dispatch/spec.md is excluded by !projects/**
📒 Files selected for processing (8)
  • packages/2-sql/9-family/src/core/migrations/control-policy-ddl-gate.ts
  • packages/2-sql/9-family/src/core/migrations/field-event-planner.ts
  • packages/2-sql/9-family/src/exports/control.ts
  • packages/2-sql/9-family/test/control-policy-ddl-gate.test.ts
  • packages/3-targets/3-targets/postgres/src/core/migrations/control-policy-ddl-resolve.ts
  • packages/3-targets/3-targets/postgres/src/core/migrations/issue-planner.ts
  • packages/3-targets/3-targets/postgres/src/core/migrations/planner.ts
  • packages/3-targets/3-targets/postgres/test/migrations/control-policy-planner.test.ts

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

Lousy quality

wmadden added 9 commits June 2, 2026 20:15
Per-node gate in the SQL family migration seam (field-event planner,
issue planner, call-level filter): managed keeps full CREATE/ALTER/DROP,
tolerated allows CREATE-if-missing only, external/observed emit nothing.

When defaultControl is external, suppress all DDL in the contract space
and surface a warn diagnostic if a per-object managed override would
have emitted DDL; the plan still succeeds.

Signed-off-by: Will Madden <[email protected]>
Replace five bare `as` casts in the control-policy DDL gate and the
Postgres call resolver with type-safe narrowing:

- the two `ns.enum as Record<...>` index casts drop the cast entirely
  because the namespace `enum` slot is already typed as
  `Readonly<Record<string, PostgresEnumStorageEntry>>`
- the `rawSql` intent classifier reads `call.op` directly, since the
  switch over `factoryName` narrows the call to `RawSqlCall`
- the `call as {...field?}` coordinate read becomes a `postgresCallFields`
  accessor that narrows the discriminated union per field via `in`
- the partial `StrategyContext` cast is replaced by a local
  storage-based `ddlSchemaNameForNamespace` helper (identical logic to
  resolveDdlSchemaForNamespace) so no fabricated context is needed

Type-safety only; behaviour unchanged. Keeps the lint:casts ratchet at
delta 0.

Signed-off-by: Will Madden <[email protected]>
…elper

Introduce a free-function `isStorageTable` type guard beside the existing
`isPostgresEnumStorageEntry`, and a shared `storageTableAt` lookup helper, so
the migration control-policy resolvers stop hand-rolling byte-identical
`instanceof StorageTable` table lookups in two packages.

Signed-off-by: Will Madden <[email protected]>
Rebuild the per-node control-policy DDL gate on the framework migration
taxonomy instead of a parallel one. Each control policy now maps to a set of
allowed `MigrationOperationClass` values (managed=all, tolerated=additive-only,
external/observed=none) and gating reads `call.operationClass` directly, so the
bespoke `DdlIntent` axis and its two `factoryName`/`SchemaIssue` derivations are
gone.

The `external` namespace floor is now a single, fail-closed enforcement point:
under an external default every op is dropped, including ops whose subject does
not resolve and the lifted codec field-event ops — the safe default on an
unrecognised op is suppress, not emit.

Delete the dead `SqlPlannerControlWarning` diagnostic and all its plumbing (it
was produced, threaded onto plan results, and read by nobody; the framework
success result has no warnings channel). Surfacing the mis-declaration
diagnostic is deferred to a follow-up; this slice ships the floor behaviour
(zero DDL into an external namespace, plan still proceeds).

Rename the modules to `control-policy.ts` in each package, rename the
policy-meaning identifiers off the ambiguous bare `control` onto
`controlPolicy`, drop the `gate*` jargon in favour of
`filterCallsByControlPolicy`, and consolidate subject resolution onto the
single op-call path.

Signed-off-by: Will Madden <[email protected]>
…ive policies

The operationClass reframe gated tolerated on `["additive"]`, but additive
covers additive ALTERs on existing objects (addColumn, createIndex, constraint
adds, additive setDefault). operationClass is a danger axis, not a
create-vs-modify lifecycle axis, so it cannot express tolerated. That let
tolerated emit ALTERs on existing objects, contradicting its create-if-absent
contract.

Gate tolerated on a "creates a whole new top-level storage object" predicate
instead. The target resolves a `createsNewObject` flag from an explicit,
fail-closed set of object-creation factory calls (createTable, createEnumType,
createSchema); any call not in the set — including unrecognised or
extension-contributed ops — is treated as not object-creation and suppressed
under tolerated. This is a single yes/no question, not a revived lossy
create/alter/drop classification with a permissive default.

Generalise the fail-closed floor beyond external: a call is kept only when its
effective control policy positively allows it, so observed (no DDL) drops
unresolved-subject ops (e.g. createExtension) just like external, and tolerated
drops anything not provably object-creation (including unresolved subjects).
The external default remains an un-overridable floor.

Remove the now-unused exports resolveControlPolicyForSchemaIssue,
resolveNamespaceId, and controlPolicyAllowedOperationClasses (and the helpers
they pulled in). Restore AC1: tolerated emits createTable for an absent table
and emits nothing for an existing table missing a column or with drift.

Signed-off-by: Will Madden <[email protected]>
…fensive instanceof

Rename ResolvedControlSubject to ControlPolicySubject (and resolveSubject to resolveControlPolicySubject / resolvePostgresCallControlPolicySubject) so the type names the object a control policy governs rather than inventing vague jargon; rewrite the doc comment off the "control-relevant facts" phrasing.

Trust the validated contract in storageTableAt: the indexed access is already typed StorageTable | undefined, so return it directly and delete the now-unused isStorageTable instanceof guard.

Use the ifDefined helper for the optional-property spreads in the postgres control-policy resolver.

Add a planner-level test driving createPostgresMigrationPlanner().plan(...) end-to-end to prove a tolerated table's non-create add-column is suppressed through the real planner entry point.

Signed-off-by: Will Madden <[email protected]>
@wmadden-electric
wmadden-electric force-pushed the tml-2777-control-policy-slice-3-planner-dispatch branch from 634fd4e to 5ebc21a Compare June 2, 2026 18:18

@coderabbitai coderabbitai Bot 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.

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/3-targets/3-targets/postgres/src/core/migrations/issue-planner.ts`:
- Around line 932-941: The control-policy filtering currently applied by
filterCallsByControlPolicy (using resolvePostgresCallControlPolicySubject) runs
after mapIssueToCall, so unsupported unmanaged issues are already turned into
hard conflicts; fix by resolving control-policy subjects earlier and skipping
conflict generation for suppressed issues: either call
resolvePostgresCallControlPolicySubject for each issue before mapIssueToCall and
skip mapping when the control policy marks the subject as
tolerated/external/observed, or add control-aware checks inside mapIssueToCall
(and specifically inside the non-missing branches that produce conflicts and the
type_values_mismatch branch) to suppress creating conflict calls when the
control policy indicates they should be ignored. Ensure you update references to
filterCallsByControlPolicy/mapIssueToCall and the resolver
resolvePostgresCallControlPolicySubject accordingly so suppressed issues never
reach conflict-generation code paths.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

Run ID: 9ad29a87-204c-41b4-84b2-a93db4aa5e67

📥 Commits

Reviewing files that changed from the base of the PR and between f61b22c and 5ebc21a.

📒 Files selected for processing (9)
  • packages/2-sql/1-core/contract/src/exports/types.ts
  • packages/2-sql/1-core/contract/src/ir/sql-storage.ts
  • packages/2-sql/1-core/contract/src/types.ts
  • packages/2-sql/9-family/src/core/migrations/control-policy.ts
  • packages/2-sql/9-family/src/exports/control.ts
  • packages/2-sql/9-family/test/control-policy.test.ts
  • packages/3-targets/3-targets/postgres/src/core/migrations/control-policy.ts
  • packages/3-targets/3-targets/postgres/src/core/migrations/issue-planner.ts
  • packages/3-targets/3-targets/postgres/src/core/migrations/planner.ts

@wmadden-electric
wmadden-electric merged commit 40e44e5 into main Jun 2, 2026
20 checks passed
@wmadden-electric
wmadden-electric deleted the tml-2777-control-policy-slice-3-planner-dispatch branch June 2, 2026 18:35
medz pushed a commit to medz/prisma-next that referenced this pull request Jun 5, 2026
…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]>
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