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

feat(migrations): add contract-to-contract planner and abstract ops IR - #179

Closed
saevarb wants to merge 9 commits into
mainfrom
feat/on-disk-migrations
Closed

saevarb wants to merge 9 commits into
mainfrom
feat/on-disk-migrations

Conversation

@saevarb

@saevarb saevarb commented Feb 25, 2026 •

Copy link
Copy Markdown
Contributor

closes TML-1936

Goal

Implement Milestone 1 of on-disk migrations: a pure, offline contract-to-contract diff planner that produces abstract migration operation IR. This is the foundation — M2 (persistence/DAG) and M3 (CLI commands) build on top.

The planner answers "what changed between schema A and schema B?" without a database connection. The existing introspection-based planner answers "what's different between the contract and the live DB?" — they serve different purposes.

Before / After

// BEFORE — only introspection-based planning (requires DB)
const schemaIR = await familyInstance.introspect({ driver });
const result = planner.plan({ contract, schema: schemaIR, policy, frameworkComponents });
// produces SQL directly
// AFTER — also contract-to-contract planning (no DB needed)
import { planContractDiff } from '@prisma-next/family-sql/control';

const result = planContractDiff({
  from: previousContract.storage,  // or null for new project
  to: currentContract.storage,
});
// result.ops → AbstractOp[] (target-agnostic IR, resolved to SQL at apply time)

What changed and why

  • Abstract ops IR (core-control-plane/abstract-ops): 8 operation types (enableExtension, createStorageType, createTable, addColumn, addPrimaryKey, addUniqueConstraint, createIndex, addForeignKey) with typed args, ADR 044 structured pre/post checks, and ContractDiffResult union. Lives in the framework domain since it's target-agnostic — any SQL target can resolve these to concrete DDL.

  • Contract planner (family-sql/contract-planner): planContractDiff() diffs two SqlStorage states and produces ops in deterministic order (extensions → types → tables → columns → PKs → uniques → indexes → FKs). Detects non-additive conflicts (type changes, column removal, nullability tightening) and returns structured failures. Extension detection via codec→extension mapping (pgvector).

  • 20 unit tests covering all op types, conflict cases, determinism, edge cases (NOT NULL with/without defaults, PK addition on existing tables, constraint name generation).

  • Spec and plan docs for the full 4-milestone project in projects/on-disk-migrations/.

Summary by CodeRabbit

Release Notes

  • New Features

    • Added offline contract-to-contract migration planning that analyzes SQL state differences and generates ordered migration operations.
    • Introduced on-disk migration persistence infrastructure with deterministic operation ordering and conflict detection for additive-only changes.
  • Documentation

    • Added comprehensive specification for on-disk migration format, directory layout, and CLI workflows.
    • Added detailed migration implementation plan outlining multi-milestone approach.

Sævar Berg added 2 commits February 24, 2026 15:52
Define the spec and plan for on-disk migration persistence, covering
contract-to-contract diffing, abstract ops IR, migration file management,
DAG reconstruction, and CLI commands (migration plan, new, verify, db update).

Key decisions: offline contract-to-contract planner (no DB for migration plan),
abstract op IR on disk resolved to SQL at apply time, sha256:empty sentinel,
direct contract IR diffing (not via SqlSchemaIR conversion).
…R (M1)

Implement Milestone 1 of on-disk migrations: a pure contract-to-contract
diff planner that produces abstract migration operation IR.

Abstract ops IR (core-control-plane):
- 8 operation types: enableExtension, createStorageType, createTable,
  addColumn, addPrimaryKey, addUniqueConstraint, createIndex, addForeignKey
- ADR 044 structured pre/post check vocabulary (14 check types)
- ContractDiffResult union (success with ops, failure with conflicts)
- EMPTY_CONTRACT_HASH sentinel for new projects

Contract planner (family-sql):
- planContractDiff({ from, to }) diffs two SqlStorage states
- Deterministic op ordering matching existing Postgres planner
- Semantic satisfaction for constraints (unique satisfies index, etc.)
- Conflict detection: type change, nullability tightening, column/table
  removal, PK change → failure with structured conflicts
- Extension detection via codec→extension mapping (pgvector)
- Pre/post check generation per ADR 044

20 unit tests covering all additive op types, conflict cases,
determinism, edge cases (NOT NULL with/without defaults, PK addition).
pnpm lint:deps passes with no violations.
@linear

linear Bot commented Feb 25, 2026

Copy link
Copy Markdown
TML-1936 [PN] M1: Planner + abstract ops IR

Contract-to-contract diff planner that produces abstract operation IR. No DB connection needed — pure, offline diffing of two SqlStorage states.\n\nDelivered:\n- Abstract ops IR types (8 op types, 14 ADR 044 check types) in @prisma-next/core-control-plane/abstract-ops\n- planContractDiff() planner in @prisma-next/family-sql/control\n- 20 unit tests covering all additive op types, conflict detection, determinism\n- pnpm lint:deps clean\n\nSee projects/on-disk-migrations/plans/plan.md Milestone 1.

@coderabbitai

coderabbitai Bot commented Feb 25, 2026 •

Copy link
Copy Markdown
Contributor

Important

Review skipped

Draft detected.

Please check the settings in the CodeRabbit UI or the .coderabbit.yaml file in this repository. To trigger a single review, invoke the @coderabbitai review command.

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review

Walkthrough

This change introduces the abstract operations intermediate representation (IR) for on-disk migrations and a contract-to-contract planner that determines DDL operations required to evolve a database schema from one state to another. It includes supporting documentation and comprehensive test coverage.

Changes

Cohort / File(s) Summary
Framework Abstract Operations IR
packages/1-framework/1-core/migration/control-plane/package.json, packages/1-framework/1-core/migration/control-plane/src/abstract-ops.ts, packages/1-framework/1-core/migration/control-plane/src/exports/abstract-ops.ts, packages/1-framework/1-core/migration/control-plane/tsdown.config.ts
Defines target-agnostic migration operation IR with checks (existence, nullability, extension installation), column defaults (literal, function, sequence), and operation types (enable extension, create storage type, create/alter table operations). Re-exports consolidated public API and configures build entry point.
SQL Tooling Contract Planner
packages/2-sql/3-tooling/family/src/core/migrations/contract-planner.ts, packages/2-sql/3-tooling/family/src/exports/control.ts
Implements deterministic contract-to-contract diff planning that accepts two SQL storage states and produces ordered abstract operations or conflict results. Enforces additive-only MVP policy with comprehensive conflict detection for removals and incompatible changes.
Contract Planner Test Suite
packages/2-sql/3-tooling/family/test/contract-planner.test.ts
Comprehensive vitest suite covering schema evolution scenarios including table/column/constraint additions, deterministic ordering, extension handling, nullability constraints, defaults, and conflict scenarios with ADR 044 pre/post check validation.
On-Disk Migrations Documentation
projects/on-disk-migrations/spec.md, projects/on-disk-migrations/plans/plan.md
Specification and multi-milestone plan for on-disk migration persistence, defining data formats, directory layout, DAG reconstruction, CLI commands (migration plan, migration new, migration verify, db update), edge attestation, and integration strategy across framework/SQL/CLI layers.

Tip

Try Coding Plans. Let us write the prompt for your AI agent so you can ship faster (with fewer bugs).
Share your feedback on Discord.


Note

🎁 Summarized by CodeRabbit Free

Your organization is on the Free plan. CodeRabbit will generate a high-level summary and a walkthrough for each pull request. For a comprehensive line-by-line review, please upgrade your subscription to CodeRabbit Pro by visiting https://app.coderabbit.ai/login.

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

@pkg-pr-new

pkg-pr-new Bot commented Feb 25, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@prisma-next/runtime-executor

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/runtime-executor@179

@prisma-next/sql-runtime

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

@prisma-next/integration-kysely

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/integration-kysely@179

@prisma-next/extension-pgvector

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

@prisma-next/sql-orm-client

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

@prisma-next/contract-authoring

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

@prisma-next/contract-psl

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

@prisma-next/contract-ts

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

@prisma-next/ids

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

@prisma-next/cli

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

@prisma-next/emitter

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

@prisma-next/eslint-plugin

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/eslint-plugin@179

@prisma-next/migration-tools

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

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

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

@prisma-next/sql-contract

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

@prisma-next/sql-errors

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

@prisma-next/sql-operations

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

@prisma-next/sql-schema-ir

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

@prisma-next/sql-contract-ts

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

@prisma-next/sql-contract-emitter

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

@prisma-next/family-sql

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

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

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

@prisma-next/sql-relational-core

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

@prisma-next/sql-lane

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-lane@179

@prisma-next/target-postgres

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

@prisma-next/adapter-postgres

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

@prisma-next/driver-postgres

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

@prisma-next/postgres

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

@prisma-next/core-control-plane

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/core-control-plane@179

@prisma-next/core-execution-plane

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/core-execution-plane@179

@prisma-next/contract

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

@prisma-next/operations

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

@prisma-next/plan

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

@prisma-next/utils

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

commit: e881fec

Sævar Berg and others added 2 commits February 25, 2026 12:31
…irst draft)

New package @prisma-next/migration-tools with four export subpaths:
- ./types: MigrationManifest, MigrationOps, MigrationPackage, MigrationGraph
- ./io: read/write migration packages, directory naming, collision handling
- ./attestation: computeEdgeId, attestMigration, verifyMigration
- ./dag: reconstructGraph, findLeaf, findPath, detectCycles, detectOrphans

55 unit tests covering all functionality. All existing tests pass.

Co-authored-by: Cursor <[email protected]>
… codes

Introduce MigrationToolsError with stable codes following ADR 027
NAMESPACE.SUBCODE convention (MIGRATION.DIR_EXISTS, MIGRATION.FILE_MISSING,
etc.). Each error carries code, category, why, fix, and details for
agent-friendly error handling.

Register 7 new tooling-time codes in ADR 027 and document as RD-16 in spec.

Co-authored-by: Cursor <[email protected]>
@saevarb
saevarb marked this pull request as draft February 25, 2026 12:10
Sævar Berg and others added 5 commits February 25, 2026 13:20
Rewrite M3 plan with concrete implementation details (file paths,
option interfaces, step-by-step logic, error boundary patterns).
Defer db update to follow-on project. Document that planContractDiff
is the intended single diff engine — the introspection-based path
should eventually convert to contract IR and feed through the same
engine (RD-3). Remove "parity with introspection planner" framing
from acceptance criteria in favor of correctness.

Co-authored-by: Cursor <[email protected]>
Add `migration plan`, `migration verify`, and `migration new` CLI
commands with config support, control plane integration, and tests.

- Add migrations.dir to PrismaNextConfig
- Wire planContractDiff through TargetMigrationsCapability and
  ControlClient to respect framework/sql layering
- Implement migration-plan (offline contract diff, DAG leaf resolution,
  write migration package)
- Implement migration-verify (recompute edgeId, attest drafts)
- Implement migration-new (scaffold empty draft package)
- Add unit and e2e tests for all three commands

Co-authored-by: Cursor <[email protected]>
- Add migration apply (limited) to scope; remove from non-goals
- Change RD-6 from abstract ops IR to direct SQL on disk
- Update RD-5 rationale for contract-level diffing
- Resolve all open questions (control plane wiring, draft vs
  attested, abstract ops vs SQL lowering)
- Remove db update from scope, add to non-goals
- Fix FR-8/FR-9 descriptions (were marked out of scope but
  are implemented)
- Add FR-10 for migration apply
- Add M4 (apply) and M5 (close-out) milestones to plan
- Clean up stale TODOs and notes from EM discussion

Co-authored-by: Cursor <[email protected]>
Add detailed task plan for replacing abstract ops IR with direct SQL
lowering. Includes 5-phase breakdown (prep, emitter, planner, consumers,
cleanup), SqlEmitter interface design for layering compliance, and
complete file-level blast radius.

Also cleans up spec (consolidate user flows, remove graph.index.json
from FR-2, fix cosmetic blank line) and updates plan.md to reference the
new task plan.

Made-with: Cursor
@saevarb

saevarb commented Feb 26, 2026

Copy link
Copy Markdown
Contributor Author

Superseded by #184 — reduced scope, consolidated all milestones into a single PR.

@saevarb saevarb closed this Feb 26, 2026
saevarb pushed a commit that referenced this pull request Mar 4, 2026
#184)

Supersedes #179

closes [TML-1936](https://linear.app/prisma-company/issue/TML-1936)
refs [TML-1937](https://linear.app/prisma-company/issue/TML-1937)
refs [TML-1938](https://linear.app/prisma-company/issue/TML-1938)

## Summary

End-to-end on-disk migration support: plan migrations offline, serialize
them to disk, and apply them against a live database.

- **Offline migration planning** (`migration plan`): Diffs two contracts
without a DB connection. Uses `contractToSchemaIR()` to synthesize a
`SqlSchemaIR` from the previous contract, then feeds it into the
existing `PostgresMigrationPlanner` — no new planner needed. Supports
additive, widening, and destructive operations.
- **On-disk migration format**: `migration.json` + `ops.json`
serialization, edge attestation (`computeEdgeId`, `attestMigration`,
`verifyMigration`), DAG reconstruction with cycle/orphan detection.
- **CLI commands**:
  - `migration plan` — offline diff → attested package
- `migration apply` — read pending migrations from DAG, execute
sequentially against a live DB via `ControlClient`
  - `migration verify` — re-attest / validate integrity
- **Destructive change detection**: Hash-diff heuristic catches
removals; the planner catches type changes and nullability tightening as
conflicts.
- **Migration apply**: Reads on-disk packages, determines pending
migrations via DAG path from DB marker to leaf, executes each in its own
transaction with full execution checks (prechecks, postchecks,
idempotency). Resume-safe — re-run after failure picks up from the last
successful migration. Warns when contract.json is stale (storageHash
differs from DAG leaf).


## Architecture

```
contract.ts → emit → contract.json
                           ↓
                 migration plan (offline):
                   contractToSchemaIR(from) + planner.plan(to)
                           ↓
                 migrations/<timestamp>_<name>/
                   ├── migration.json  (manifest + edge attestation)
                   └── ops.json        (SQL operations)
                           ↓
                 migration apply (online):
                   read marker → find pending path → ControlClient.migrationApply() per edge
                           ↓
                 DB updated, marker at new hash
```

### Key implementation details (migration apply)

- Routes through `ControlClient`, consistent with `db init` and `db
update`
- `origin: null` for first migration (runner expects no marker on fresh
DB, not `EMPTY_CONTRACT_HASH`)
- Destination contract validated via
`familyInstance.validateContractIR()` before passing to runner
- Framework components built from config for schema verification
- One transaction per migration with all execution checks enabled
- Policy-agnostic: passes all operation classes to the runner (policy
gate is at plan time)
- Stale-plan detection: warns when contract.json storageHash differs
from DAG leaf

## Test plan

- [x] Unit tests for `contractToSchemaIR` conversion (15 tests)
- [x] Unit tests for `detectDestructiveChanges` (7 tests)
- [x] Planner integration tests (9 tests)
- [x] CLI command unit tests for migration-plan, migration-verify
- [x] Migration apply unit tests — DAG path resolution (6 tests)
- [x] Migration plan CLI e2e tests (7 tests)
- [x] Migration apply CLI e2e tests against real Postgres (5 tests:
single apply, idempotency, multi-migration, destructive, resume)
- [x] Migration tools tests (attestation, DAG, I/O round-trips)
- [x] NativeTypeExpander tests (with and without expander)
- [x] `pnpm test:all` passes
- [x] `pnpm lint:deps` clean
- [x] `pnpm typecheck` clean

<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **New Features**
* CLI: add migration commands — plan, show, status, verify, and apply
for offline on-disk migrations
* On-disk migrations: persistent migration packages with
content-attested edge IDs and DAG-based chaining
  * Runtime API: read marker and apply migrations programmatically

* **Documentation**
* Comprehensive migration docs, ADRs, and user stories for on-disk
workflow

* **Tests**
* Extensive unit and end-to-end tests covering planning, attestation,
DAGs, verification, and apply flows

* **Chores**
  * Added migrations config option and minor ignore-file updates
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: Cursor <[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.

1 participant