Repository navigation
TML-2775: add control-policy IR primitive (control field + effectiveControl) - #691
Conversation
|
Caution Review failedThe pull request is closed. ℹ️ Recent review info⚙️ Run configurationConfiguration used: Path: .coderabbit.yml Review profile: CHILL Plan: Pro Run ID: ⛔ Files ignored due to path filters (4)
📒 Files selected for processing (17)
📝 WalkthroughWalkthroughThis PR adds a ControlPolicy type and effectiveControl resolution, wires optional per-node ChangesControl Policy Implementation
Estimated code review effort🎯 3 (Moderate) | ⏱️ ~25 minutes Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate 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 📦
|
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (1)
packages/1-framework/0-foundation/contract/src/control-policy.ts (1)
10-24: ⚡ Quick winExport the canonical control-policy value list from the foundation layer.
ControlPolicyis now hard-coded again in both Mongo and SQL Arktype schemas. That gives you a compile/runtime drift path: adding a new policy here will typecheck everywhere, but validators will still reject it until every schema is updated manually. Export a shared tuple/value source here and derive the type and downstream schemas from it instead.♻️ Possible direction
-export type ControlPolicy = 'managed' | 'tolerated' | 'external' | 'observed'; +export const controlPolicies = ['managed', 'tolerated', 'external', 'observed'] as const; + +export type ControlPolicy = (typeof controlPolicies)[number];Then build each validator from
controlPoliciesinstead of repeating the string union.🤖 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/1-framework/0-foundation/contract/src/control-policy.ts` around lines 10 - 24, Export a single canonical array/tuple of allowed policy strings (e.g., controlPolicies) from this module and derive the ControlPolicy type from it (use a string literal union from the tuple) instead of hard-coding the union; update any consumers/validators (Mongo and SQL Arktype schema builders) to import controlPolicies and build their validators/enums from that array rather than repeating the string union; keep effectiveControl as-is but ensure it accepts ControlPolicy | undefined derived from the new tuple.
🤖 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/test/postgres-contract-serializer.test.ts`:
- Around line 171-246: The test currently only leaves email.control unset so it
can't catch a serializer that preserves an explicit default-valued control;
update makeMixedControlContractJson to explicitly set the email column's control
to 'tolerated' (matching defaultControl) and keep the round-trip assertions:
after serialize→deserialize using PostgresContractSerializer, assert
effectiveControl(emailColumn.control, reparsed.defaultControl) is 'tolerated'
and assert the email column does NOT have a 'control' property (testing
omit-when-default). Refer to makeMixedControlContractJson,
PostgresContractSerializer, effectiveControl, and the emailColumn/table/ns
variables in the test to locate and change the fixture and assertions.
---
Nitpick comments:
In `@packages/1-framework/0-foundation/contract/src/control-policy.ts`:
- Around line 10-24: Export a single canonical array/tuple of allowed policy
strings (e.g., controlPolicies) from this module and derive the ControlPolicy
type from it (use a string literal union from the tuple) instead of hard-coding
the union; update any consumers/validators (Mongo and SQL Arktype schema
builders) to import controlPolicies and build their validators/enums from that
array rather than repeating the string union; keep effectiveControl as-is but
ensure it accepts ControlPolicy | undefined derived from the new tuple.
🪄 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: e5798517-9ca3-46a8-8b25-e70861180e67
⛔ Files ignored due to path filters (4)
projects/control-policy/plan.mdis excluded by!projects/**projects/control-policy/slices/ir-primitive/plan.mdis excluded by!projects/**projects/control-policy/slices/ir-primitive/spec.mdis excluded by!projects/**projects/control-policy/spec.mdis excluded by!projects/**
📒 Files selected for processing (17)
packages/1-framework/0-foundation/contract/src/contract-types.tspackages/1-framework/0-foundation/contract/src/control-policy.tspackages/1-framework/0-foundation/contract/src/exports/types.tspackages/1-framework/0-foundation/contract/test/control-policy.test.tspackages/2-mongo-family/1-foundation/mongo-contract/src/contract-schema.tspackages/2-mongo-family/1-foundation/mongo-contract/src/ir/mongo-collection.tspackages/2-mongo-family/1-foundation/mongo-contract/test/ir/control-field.test.tspackages/2-sql/1-core/contract/src/ir/postgres-enum-storage-entry.tspackages/2-sql/1-core/contract/src/ir/storage-column.tspackages/2-sql/1-core/contract/src/ir/storage-table.tspackages/2-sql/1-core/contract/src/validators.tspackages/2-sql/1-core/contract/test/control-field.test.tspackages/3-mongo-target/1-mongo-target/test/mongo-target-contract-serializer.test.tspackages/3-targets/3-targets/postgres/src/core/postgres-enum-type.tspackages/3-targets/3-targets/postgres/test/control-field.test.tspackages/3-targets/3-targets/postgres/test/postgres-contract-serializer.test.tspackages/3-targets/3-targets/sqlite/test/sqlite-contract-serializer.test.ts
| describe('control-policy round-trip fidelity', () => { | ||
| function makeMixedControlContractJson() { | ||
| const base = createSqlContract({ | ||
| storage: { | ||
| namespaces: { | ||
| [UNBOUND_NAMESPACE_ID]: { | ||
| id: UNBOUND_NAMESPACE_ID, | ||
| tables: { | ||
| user: { | ||
| columns: { | ||
| id: { | ||
| nativeType: 'int4', | ||
| codecId: 'pg/int4@1', | ||
| nullable: false, | ||
| control: 'observed', | ||
| }, | ||
| email: { nativeType: 'text', codecId: 'pg/text@1', nullable: false }, | ||
| }, | ||
| primaryKey: { columns: ['id'] }, | ||
| uniques: [], | ||
| indexes: [], | ||
| foreignKeys: [], | ||
| control: 'external', | ||
| }, | ||
| }, | ||
| }, | ||
| }, | ||
| }, | ||
| }); | ||
| return { | ||
| ...base, | ||
| defaultControl: 'tolerated', | ||
| storage: { | ||
| ...base.storage, | ||
| namespaces: { | ||
| [UNBOUND_NAMESPACE_ID]: { | ||
| ...base.storage.namespaces[UNBOUND_NAMESPACE_ID]!, | ||
| enum: { | ||
| Role: { | ||
| kind: 'postgres-enum', | ||
| name: 'Role', | ||
| nativeType: 'role', | ||
| values: ['admin', 'user'], | ||
| control: 'managed', | ||
| }, | ||
| }, | ||
| }, | ||
| }, | ||
| }, | ||
| }; | ||
| } | ||
|
|
||
| it('preserves effective control per node across serialize → deserialize', () => { | ||
| const serializer = new PostgresContractSerializer(); | ||
| const input = makeMixedControlContractJson(); | ||
|
|
||
| const contract = serializer.deserializeContract(input); | ||
| const reparsed = JSON.parse(JSON.stringify(serializer.serializeContract(contract))); | ||
|
|
||
| expect(reparsed.defaultControl).toBe('tolerated'); | ||
|
|
||
| const ns = reparsed.storage.namespaces[UNBOUND_NAMESPACE_ID]; | ||
| const table = ns.tables.user; | ||
| const idColumn = table.columns.id; | ||
| const emailColumn = table.columns.email; | ||
| const enumEntry = ns.enum.Role; | ||
|
|
||
| const def = reparsed.defaultControl; | ||
| expect(effectiveControl(table.control, def)).toBe('external'); | ||
| expect(effectiveControl(idColumn.control, def)).toBe('observed'); | ||
| expect(effectiveControl(emailColumn.control, def)).toBe('tolerated'); | ||
| expect(effectiveControl(enumEntry.control, def)).toBe('managed'); | ||
|
|
||
| // Omit-when-default holds: the unset column never grows a control property. | ||
| expect(emailColumn).not.toHaveProperty('control'); | ||
| }); |
There was a problem hiding this comment.
Exercise the explicit default-matching override case.
This fixture only covers an unset email.control, so the not.toHaveProperty('control') assertion proves omit-when-unset, not omit-when-default. A serializer that preserved an explicit control: 'tolerated' would still pass here.
Suggested test tweak
user: {
columns: {
id: {
nativeType: 'int4',
codecId: 'pg/int4@1',
nullable: false,
control: 'observed',
},
- email: { nativeType: 'text', codecId: 'pg/text@1', nullable: false },
+ email: {
+ nativeType: 'text',
+ codecId: 'pg/text@1',
+ nullable: false,
+ control: 'tolerated',
+ },
},
primaryKey: { columns: ['id'] },
uniques: [],
indexes: [],
foreignKeys: [],
@@
- // Omit-when-default holds: the unset column never grows a control property.
+ // Explicit overrides that match the inherited default are canonicalized away.
expect(emailColumn).not.toHaveProperty('control');🤖 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/test/postgres-contract-serializer.test.ts`
around lines 171 - 246, The test currently only leaves email.control unset so it
can't catch a serializer that preserves an explicit default-valued control;
update makeMixedControlContractJson to explicitly set the email column's control
to 'tolerated' (matching defaultControl) and keep the round-trip assertions:
after serialize→deserialize using PostgresContractSerializer, assert
effectiveControl(emailColumn.control, reparsed.defaultControl) is 'tolerated'
and assert the email column does NOT have a 'control' property (testing
omit-when-default). Refer to makeMixedControlContractJson,
PostgresContractSerializer, effectiveControl, and the emailColumn/table/ns
variables in the test to locate and change the fixture and assertions.
…mplates Restructure the control-policy project artefacts to the current Drive project-spec / project-plan shape: the spec now carries only durable system-level intent (purpose, non-goals, place in the world, cross-cutting requirements, transitional-shape constraints, project-DoD), with per-slice dispatch detail and acceptance criteria pushed down to the slice issues. The plan carries slice composition (one substrate slice + a parallel consumer fan + a deferrable PSL slice) with conceptual focus only. Reconcile the design with ADR 221: control lives on storage-plane entities, not domain models. Record the namespace-level-inheritance deferral with its promotion trigger. Refs: TML-2493 Signed-off-by: Will Madden <[email protected]>
Slice spec + 3-dispatch plan for TML-2775: ControlPolicy type + effective -control resolver (foundation), uniform control? fan-out across storage-plane IR nodes + validators, then cross-target round-trip + no-hash-churn verification. Refs: TML-2775 Signed-off-by: Will Madden <[email protected]>
…n-only Fold all arktype validator wiring (per-node control + contract-level defaultControl) into dispatch 2, where the validators already get touched, so dispatch 1 stays foundation-only (typecheck + unit-test gate, no cross-package surface). Refs: TML-2775 Signed-off-by: Will Madden <[email protected]>
Adds the ControlPolicy string-literal union and the effectiveControl pure function to @prisma-next/contract, exported via the ./types barrel. Also adds readonly defaultControl?: ControlPolicy to the Contract interface. Resolver precedence: node value → contract default → managed. Signed-off-by: Will Madden <[email protected]>
Adds the optional control?: ControlPolicy field to every storage-plane IR leaf (SQL StorageTable/StorageColumn, PostgresEnumStorageEntry interface + PostgresEnumType class, Mongo MongoCollection) using the declare-readonly + assign-if-defined idiom so an unset value never serializes. Teaches each entity arktype validator to accept an optional control constrained to the four ControlPolicy literals, and the SQL + Mongo contract-shape validators to accept an optional defaultControl. No behaviour change; the resolver consumers wire in later. Signed-off-by: Will Madden <[email protected]>
Add serialize/deserialize round-trip tests for Postgres, SQLite, and Mongo asserting that per-node control and the top-level defaultControl survive a round-trip with effective control preserved per node (oracle: effectiveControl). Each suite mixes set and unset carriers and asserts unset nodes never grow a control property, exercising the omit-when-default no-churn mechanism. Signed-off-by: Will Madden <[email protected]>
691381c to
95c94c5
Compare
…-2800) (prisma#707) ## At a glance ```ts // before const contract = defineContract({ ..., defaultControl: 'tolerated' }); // after const contract = defineContract({ ..., defaultControlPolicy: 'tolerated' }); ``` A pure mechanical rename of the contract-level default field. No behaviour change. ## The decision The control-policy primitive (`ControlPolicy = 'managed' | 'tolerated' | 'external' | 'observed'`) introduced a contract-level default named `defaultControl`. Reading the merged slice PRs as a fresh team member, "control" is overloaded: the codebase already uses **control plane** as a load-bearing term, and the contract was using bare "control" as shorthand for "control **policy**". This rename completes the [`effectiveControl → effectiveControlPolicy`](prisma#699) cleanup landed in prisma#699 — the field-name half of the same ubiquitous-language pass. After this PR, every policy-bearing identifier on the storage plane reads `…ControlPolicy` rather than bare `…Control` (the per-node `.control` IR field is the deliberate exception — renaming it would change every node's serialized contract hash, see "Alternatives considered"). ## Scope In: - `defaultControl` → `defaultControlPolicy` on the contract IR (`@prisma-next/contract` and the Mongo contract foundation), its arktype validators, the TS authoring builder option, and every reader (verifier, planner). - The serialized JSON key on the contract — and a regeneration of the one committed example contract that exercises it (`projects/supabase-integration/example/migrations/supabase/contract.{json,d.ts}`). - Test fixtures and helpers that reference the old name. Out (deliberately): - The per-node `.control` field — renaming it would alter the serialized JSON of every contract that uses control policies, regardless of the value. The collision the rename addresses is the **default**-side identifier; the per-node field stays `.control` for now. ## Hash impact The feature was merged to `main` only yesterday (prisma#691 on 2026-06-02). No downstream contract is yet using a non-default `defaultControl` value. The omit-when-default idiom means the JSON key only appears when the author explicitly sets a non-default policy; existing contracts in the wild that don't set it will be byte-for-byte unchanged. ## Verification - `@prisma-next/contract`, `@prisma-next/mongo-contract`, and `@prisma-next/sql-contract` rebuilt — `dist/*.d.mts` exports the new field. - Tests green: contract (160), sql-contract (129), mongo-contract (117), sql-contract-ts (270), family-sql (333), family-mongo (148), target-postgres (377), target-sqlite (104), target-mongo (404) — **2042 passing**. - Typecheck green across all touched packages. - `pnpm lint:deps` clean. - No stale `defaultControl` token remains in source/tests (the design docs under `projects/control-policy/` continue to spell the pre-rename name — they describe pre-rename state and are deleted at project close-out, mirroring the precedent prisma#699 set for `plan.md`). ## Alternatives considered - **Carry the rename inside the e2e demonstration slice (TML-2796)** — no extra PR, but risks colliding with any open branch that reads the field; landing it as substrate-first matches how prisma#699 sequenced `effectiveControl`, removing the rebase hazard entirely. - **Also rename the per-node `.control` field → `.controlPolicy`** — would alter the serialized JSON of every node carrying a control policy, churning contract hashes for every consumer regardless of value. Not required to resolve the default-side ambiguity. Deliberately out of scope. Linear: TML-2800 <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **Refactor** * Standardized contract control policy property naming across MongoDB, SQL, and related packages for improved consistency and clarity in contract definitions. <!-- end of auto-generated comment: release notes by coderabbit.ai --> Signed-off-by: Will Madden <[email protected]> Co-authored-by: Will Madden <[email protected]>
Linked issue
Refs TML-2775 — first slice of the Control Policy project, umbrella TML-2493. No GitHub issue (tracked in Linear).
At a glance
Every persisted object in a contract can now declare a
controlpolicy, and the contract carries adefaultControl. A single pure resolver computes the effective policy:In a contract that looks like this — the motivating shape for an externally-managed schema such as Supabase's
authtables:{ "target": "postgres", "defaultControl": "external", "storage": { "namespaces": { "auth": { "tables": { "users": { "control": "external", "columns": { /* … */ } } } } } } }Absent any
control/defaultControl, behaviour and serialized output are byte-for-byte identical to today (managed), so existing contracts hash unchanged.Decision
This PR lands the control-policy IR primitive — the substrate the rest of the project (verifier dispatch, planner dispatch, TS/PSL authoring) builds on. Concretely it ships, in order:
ControlPolicy— a framework-locked four-value vocabulary (managed | tolerated | external | observed) in the foundation contract package.effectiveControl(node, default)— one pure, family-agnostic resolver (node → contract default → 'managed') that the verifier and planner will both call, so the policy is resolved in exactly one place.control?on every storage-plane IR node — SQLStorageTable/StorageColumn, the Postgres target-only enum kind, and MongoMongoCollection— plusdefaultControl?on the top-levelContract.Per ADR 221 the policy lives on storage-plane entities (the persistence projection), not domain models. Because the framework
Namespaceinterface is{ id, kind }only, there is no single base to hangcontrolon — it is added to each concrete storage leaf, following the repo's three-layer polymorphic IR pattern.As the project's first PR it also carries the project shaping docs under
projects/control-policy/(spec + plan); see Reviewer notes for the close-out plan.How it fits together
ControlPolicytype, theeffectiveControlresolver (with unit tests pinning the three precedence rungs), and theContract.defaultControltype field land in@prisma-next/contract, exported via its./typesbarrel. No other package changes yet.control?is threaded through every storage-plane leaf using the idiom those classes already use for optional fields (declare readonly x?+if (input.x !== undefined) this.x = input.x), so an unset value is never assigned, never enumerated, never serialized. Every affected arktype validator gains an optionalcontrol, and the SQL + Mongo contract-shape validators gaindefaultControl.controlplus adefaultControl, then assert per-node effective control survives — using the resolver itself as the oracle.pnpm fixtures:checkconfirms zero hash churn.What lands in this PR
a2785ee69projects/)d4991ab8bprojects/)36fdb4c47projects/)354249f59ControlPolicytype +effectiveControlresolver +Contract.defaultControl(foundation)adb4ea556control?fanned across storage-plane IR + validators (defaultControl?on contract validators)ce1fcc928This is substrate: no verify/plan/authoring behaviour changes, and the resolver intentionally ships with no production callers yet — its consumers arrive in later slices. It is exercised by its own unit tests, so it is not dead code.
Reviewer notes
projects/control-policy/(spec + plan) is part of this PR; the per-round review log underprojects/control-policy/reviews/is gitignored and not in the diff. Both are transient and migrate to durable docs (or drop) at project close-out.control, and all three serializers preserve top-leveldefaultControlthrough their spread. The round-trip commit is test-only.PostgresEnumStorageEntryis an interface, so itscontrol?field is mirrored onto the concretePostgresEnumTypeclass (+ its input) where the runtime idiom lives.ControlPolicyvalidator union is duplicated as a one-line module-local constant in the SQL and Mongo validator files rather than a shared export — there is no cross-package validator-schema barrel and the four-value vocabulary is framework-locked, so drift risk is negligible.distbuild cascade. A cold worktree can surface a transient module-resolution failure in@prisma-next/postgres+ sibling extensions on firstpnpm typecheck; rebuilding the changed contract/target packages clears it. It is environmental build state, not a code issue (verified by stashing the diff — typecheck clean).Testing performed
Run on final HEAD:
pnpm typecheck(workspace) — 135/135 tasks.pnpm fixtures:check— clean, zero churn.pnpm --filter @prisma-next/contract test; SQL contract / Mongo contract / Postgres / SQLite / Mongo target suites — all green.pnpm lint:deps— 972 modules, 0 violations.Skill update
n/a — internal IR substrate. This PR adds no user-facing authoring surface (TS/PSL authoring of
controllands in later slices) and changes no runtime behaviour.Checklist
git commit -s).TML-NNNN: <sentence-case title>form.Alternatives considered
controlinheritance (mark a namespaceexternal, contents inherit). Deferred: policy boundaries align with contract-space boundaries in v0.1 (each space ships its owndefaultControl), so no current consumer mixes policies within one space. Additive on the wire later — an optional namespace field + one rung in the resolver.control. Not available — ADR 221'sNamespaceinterface is{ id, kind }only; the field goes on each concrete storage leaf instead.effectiveControltaking a node/IR object. Rejected in favour of two rawControlPolicy | undefinedvalues, so the resolver is family-agnostic and callable identically from the verifier and the planner without importing their node types.Summary by CodeRabbit
New Features
Tests