Repository navigation
feat!: stored files carry a format version, and readers refuse what they do not know - #31200
Merged
Merged
Conversation
…ases Co-Authored-By: Claude Fable 5.2 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…ies formatVersion The contract foundation package reads a stored file's format version before anything else and throws a structured error for a newer or a missing version. The canonicalizer places the formatVersion that a family's printer writes first; the hash input keeps schemaVersion "1" so no hash changes. The upgrade guide links move to the utils package so the foundation can name them. Co-Authored-By: Claude Fable 5.2 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…ide links Co-Authored-By: Claude Fable 5.2 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…gh a unit per format version deserializeContract reads the format version first and hands the file to the version 1 parser; serializeContract prints version 1, with formatVersion first. Targets override the version 1 printer in place of serializeContract. A contract a caller already deserialized is validated again from what it prints. Co-Authored-By: Claude Fable 5.2 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…on, read through a unit per version Every reader of migration.json, ref files, head refs and contract snapshots reads the format version first; tolerant readers never treat a format version error as an absent or corrupt file. Ref readers refuse unknown fields. The migration hash leaves formatVersion out, so adding it changes no hash. Bundled extension files go through the same checks. Co-Authored-By: Claude Fable 5.2 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
… check for a stored document Co-Authored-By: Claude Fable 5.2 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…fold a format version error into another readContractEnvelope reads the format version before anything else. buildReadAggregate, migration check and the commands that wrap a failed contract read report a format version error as itself, naming the file. The control client prints a contract a caller already deserialized again before the family reads it. Re-running migration.ts reads the existing migration.json's format version first. Co-Authored-By: Claude Fable 5.2 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…SQL JSON schema follows the rename The SQL validator and family instance use the shared check for a stored document. Co-Authored-By: Claude Fable 5.2 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…when it carries a format version A contract.json passed straight to a client is checked for its format version before the target prints anything from it; a contract built in memory is printed in format version 1 and read back. Co-Authored-By: Claude Fable 5.2 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
Co-Authored-By: Claude Fable 5.2 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
Co-Authored-By: Claude Fable 5.2 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…ecords it amends say so Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…version Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
Rewritten by the stored-files-format-version upgrade script. Earlier upgrade scripts' fixtures and published guides are left as they shipped. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
The integration emit helper's default serializer writes formatVersion, the Mongo side-by-side test serializes its contracts before reading them back, and the inline and Mongo ORM fixture contracts name the version. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…w found false; slice plan for the hashes Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…check A client or the control API used to print again any value with neither formatVersion nor schemaVersion, so a stored contract.json with no version was accepted. A contract Prisma builds, by the contract builder or by deserializing a file, has its storage as an object of an IR class; parsed JSON has a plain object. isContractBuiltInMemory tells the two apart, and every client and the control API read anything else through its format version. The Mongo family serializer now builds its storage as a MongoStorage like the target's, and the test contract factory builds its storage as an object of a class. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
readContractDocument handed raw JSON to the control API without reading the format version, so a contract.json with no version field was applied to the database, and a refused one named no file. It now reads the version with the file's path. writeContractSnapshot refuses a contract with no known version, so no writer leaves an unversioned snapshot. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
… as absent A head ref with a field the format does not know was reported as a missing head ref, and a refused db ref made migration plan say there was no db ref. The loader now gives the refusal itself when an extension's contract is asked for, the integrity check reports only the refusal for that space, and every command that loads the aggregate refuses on an unreadable ref, naming the file. migration check, which lists every problem, still loads. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…ho can fix it An extension's bundled contract.json, migration.json and refs/head.json were checked without a path, so an outdated extension failed with "The contract file has no format version" and advice to run the upgrade script, which cannot change a file in node_modules. contractSpaceFromJson now takes the extension's spaceId; readFormatVersion takes the extension that ships a file, and its error names the extension and the file and says the extension must be upgraded or republished by its author. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…ored file it cannot handle A ref file, migration.json or contract the script recognised by its place but not by its content was left unchanged with exit 0 and "nothing changed". It now reports each one with what is wrong and what to do, and exits 1. A ref file with fields a ref does not have, which earlier releases ignored and dropped when they wrote the ref, has those fields dropped and listed. A symbolic link to a file or folder outside the project that holds a stored file is reported, since the script does not follow links. The final message no longer says nothing changed when a file was left unhandled. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…ntract, spaceId and the script's reports Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…on changes Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…r does not check Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
… storage hash input still has its fixed entry Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…igration.ts, not by deleting later migrations Where no database has applied the migration, running its migration.ts writes migration.json and ops.json again with a new creation time. The new migration hash is recorded only in the ledger of a database that applied it; later migrations and refs name contract hashes, which do not change. So the advice no longer deletes the migration and the ones after it, with any hand-written operations, to plan them again. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…mmand that owns it, never by naming the db contract by hand The db ref records the contract the database is at, so the advice moves it with db migrate --advance-ref db, or db sign when no migration ends at contract.json. An extension head ref is written again by contract emit. Only another ref is set by hand, and the advice says that whatever uses it, such as a deploy, then uses the contract named. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…s with it A ref other than db names an environment, so pointing it at another migration changes the contract a deploy that migrates to it brings its database to. The advice now says so in the same sentence. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…g to delete or move what follows from it A deleted migration folder leaves the next migration unreachable and a ref pointing at no migration. The advice for both now first restores, from version control, the migration that ends at the missing contract. Deleting an unreachable migration is offered only where no database has applied it, and a dangling db ref is never pointed at a contract by hand. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
… user gave, so it acts on the same database db sign <ref>, db update --to and db migrate --to advised db migrate --advance-ref db or db sign without the --db they were given. Those ran against the configured connection, which in CI is often absent and elsewhere can be another database. The advice now names --db <url> when --db was given, and says which database it acts on. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…r a migration the run applies The warning that the database records no contract for a migration was computed from every migration in the folder. So db update and db init warned about application migrations they never apply, every command warned about migrations the database had already applied, and dry runs warned too. The run now reports, just before it applies, each migration on its path whose snapshot is present but cannot be read, through a listener on the control client. Nothing is reported on a dry run or when nothing is pending. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…n mapContractAtError takes Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
… that now take the unrecorded-snapshot listener Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
A lost migration.json is written again by its migration.ts with a new hash where no database applied it; a ref no release wrote is written again by the command that owns it; the unrecorded-snapshot warning covers only the migrations a run applies. Record what the round saw outside its scope. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…m; record the final check's follow-ups Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
Releases up to and including 8.0.0-rc.20 wrote the schema field; rc.21 removed it. The test name said "before", which excluded rc.20 itself. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
wmadden-electric
marked this pull request as ready for review
November 27, 2026 22:41
wmadden-electric
enabled auto-merge
November 27, 2026 22:41
github-merge-queue
Bot
removed this pull request from the merge queue due to failed status checks
Nov 27, 2026
wmadden-electric
marked this pull request as draft
November 28, 2026 05:16
…type refuses with the data type's own error A column or storage type whose parameters its data type refuses is now refused with CONTRACT.TYPE_PARAMS_INVALID before the codec check folds it into a generic validation failure, as planning refused it before the read-time check existed. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…meters as itself Every place a command reads a contract already reported a format version error as itself. It now does the same for CONTRACT.TYPE_PARAMS_INVALID, so the user sees the data type and the parameter it refuses, not "failed to deserialize" with re-emit advice. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…s a data type refuses migration status, list, graph and ref read contract.json leniently: they report why they could not read it and list the migrations against its hash. Only a format version error stops them, since nothing in such a file can be interpreted. A data type refusing type parameters is reported as the reason again, as before. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…, and when the check runs Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…rameter error Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
wmadden-electric
marked this pull request as ready for review
November 28, 2026 06:36
wmadden-electric
enabled auto-merge
November 28, 2026 06:36
wmadden-electric
added a commit
that referenced
this pull request
Nov 28, 2026
Conflicts kept both sides: the CLI options take the Prisma space listener and the unrecorded-snapshot listener, and db update reports both the Prisma space and an unreadable origin snapshot. api-breaks.json records from both sides are kept, their reasons joined and fingerprints taken from the merged api.txt. main moved APP_UPGRADE_GUIDES_URL to @internal/utils/upgrade-guides, so the CLI imports it from there and @internal/errors/control no longer re-exports it. contractSpaceFromJson now takes the space id, and assertDescriptorSelfConsistency the bundled contract.json. Co-Authored-By: Claude Opus 5.5 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
Thegreatsura
pushed a commit
to Thegreatsura/prisma
that referenced
this pull request
Nov 29, 2026
…with every value the author wrote, then freeze the rules (changes every existing hash) (prisma#31203) ## At a glance **The decision: before `8.0.0`, Prisma changes how it computes a contract's hashes, in two ways, and from `8.0.0` those rules do not change again until Prisma 9.** Every existing hash changes once, in this release. A contract has three hashes. The **storage hash** identifies the database the contract describes: its tables, columns and indexes. The **profile hash** identifies the database features the contract requires, such as `RETURNING`. The **execution hash** identifies the defaults the client fills in when it writes a row. The storage hash matters most, because Prisma writes it into five places: ```text prisma/contract.json "storageHash": "6a0532b8…" migrations/app/20261124T0900_add_phone/migration.json "from": "09807bbe…", "to": "6a0532b8…" migrations/snapshots/6a0532b8…/contract.json a saved copy of the contract (a snapshot), named by its hash migrations/app/refs/production.json "hash": "6a0532b8…" the database's marker storage hash 6a0532b8… ``` The **marker** is a row Prisma keeps in the database to record which contract it matches. A **ref** names the contract an environment such as production should be at. The two changes: ```jsonc // Before: the storage hash was computed from the whole contract, with the other parts blanked out { "schemaVersion": "1", "targetFamily": "sql", "target": "postgres", "profileHash": "", "roots": {}, "domain": { "namespaces": {} }, "storage": { "...": "..." }, "capabilities": {}, "extensions": {}, "meta": {} } // After: from the storage section alone, with every value the author wrote { "storage": { "...": "..." } } ``` 1. **Each hash is computed from its own section of the contract only**: `storage`, `capabilities` or `execution`. 2. **No value the author wrote is left out.** The old rules dropped every `false`, `[]` and `{}`, so an index option such as `{ "fastupdate": false }` was lost from the file, the hash and the database. **The cost, once:** a project from a release candidate runs a script that rewrites the hashes in its files, and signs each database again with `prisma db sign`, which checks that the database matches the contract and records the new hashes in its marker. ## Why the rules change now, and only now If a later release computed a different hash for the same contract, all five places above would stop agreeing at once. Migrations would no longer chain from one to the next, saved copies would look edited, and every database would report that it does not match its contract. So within Prisma 8 the rules cannot change. Both defects below would be frozen in with them, so they are repaired now. ### Defect 1: the hash covered more than the section Because the storage hash was computed from a blanked copy of the whole contract, the first change to the file's format version, or a new field in any blanked part, would have changed every hash. The target and the family were in the input too. A **family** is a kind of database Prisma supports (SQL or MongoDB), and a **target** is one database in it (PostgreSQL, MySQL, MariaDB). A hash is only ever compared with hashes from the same project, or from an extension the project declares, and a project has one target. So the target in a hash changed no comparison. Its one effect showed after a project moved between two targets that write the same `storage`. MySQL and MariaDB share their type names, so their `storage` can be identical. After such a move, no migration ended at the new contract's hash, no saved copy was named by it, and the marker no longer matched, so the team had to start its migration history again. The family adds nothing a target does not already say. ### Defect 2: the rules dropped values the author wrote The old rule left out every `false` and empty value except at a list of known places. That is right for a family's own defaults. For example, a column's `many: false` (the column holds one value, not a list) means the same as no `many` at all. But a value that belongs to the database or to an extension is not a default the family can drop: ```json { "name": "posts_tags_idx", "type": "gin", "options": { "fastupdate": false } } ``` was written and hashed as `"options": {}`, so the migration created the index without the option, and an index with the option had the same hash as one without. A check of every place the old rule fired found these: | Value | What went wrong | | --- | --- | | A PostgreSQL index's options, `{ fastupdate: false }` | Written as `{}`; the index was created without the option | | A MongoDB partial index filter, `{ isAdmin: false }` | Written as `{}`, a filter that matches every document | | A MongoDB clustered collection, `clusteredIndex: {}` | Dropped, so the contract described an ordinary collection | | A MongoDB collation's `backwards: false`, where the locale's default is `true` | Dropped, so the locale's default applied | | A column type's parameters, `{ strict: false }` | Two contracts with different parameters had the same hash | | A default-value generator's parameters, `{ upper: false }` | Dropped, so the generator used its own default | | A `false` or empty value inside an entry an extension defines | Dropped, so the extension read a different setting | Now the framework leaves out nothing. Each family names the fields it defines as defaults, in one function, `normalizeStorage`, which is applied both when `storage` is written and when it is hashed. The full list is in [ADR 010](https://github.com/prisma/orm/blob/c3248f020d/docs/architecture%20docs/adrs/ADR%20010%20-%20Canonicalization%20Rules.md). ### Two smaller repairs Each of these also changes hashes, so this is their one chance: - **The SQL profile hash now covers the contract's capabilities.** It covered an empty list, so a database that lacked a required feature still matched. Flags that are off are left out, so writing a flag as `false` or leaving it out gives the same hash. - **Lists whose order means nothing are sorted before hashing:** a SQL table's checks, foreign keys, indexes and uniques, and a MongoDB collection's indexes. Reordering two relations in a model reorders their foreign keys, which used to ask for a migration that did nothing. ## What follows from these changes **A contract for the wrong target is caught by checks that name it.** Without the target in the hash, nothing about a hash says which target it was for. The hash caught a contract for the wrong target only by accident: a stale MySQL contract used against a database a MariaDB contract had signed did not match the marker, but the error said only that the database did not match, not that the target was wrong. And a stale contract used against a database it had signed itself matched. Explicit checks catch it in every case and say what is wrong: - the runtime refuses a contract for another target (`RUNTIME.CONTRACT_TARGET_MISMATCH`); - the extension loader refuses an extension built for another target (`MIGRATION.CONTRACT_SPACE_VIOLATION`); - new here: every command that loads the project's migrations and extensions, including `db sign`, `db init`, `db update`, `db migrate`, `migration plan` and `migration status`, refuses an app contract whose target is not the config's, with `CONTRACT.TARGET_MISMATCH`, the code `db verify` already reports. `contract emit`, which is how a stale contract is fixed, is not refused. The commands that change a database had no such check before. Two targets may write the same `storage` only if a migration planned by either one runs on the other, because after a move the project keeps its migrations. MariaDB plans with MySQL's planner, so this holds. A target built outside this repository takes on the same rule. After such a move the storage hashes, migrations, saved copies and refs stay as they are. The profile hash changes where the two targets' capabilities differ, as MySQL's and MariaDB's do, so each database is signed again with `prisma db sign`. **An extension's newest saved copy now follows the installed extension.** An extension can ship its own tables and migrations, and Prisma keeps a saved copy of the extension's contract next to the app's, named by its storage hash. A copy already on disk was never rewritten. So an extension whose capabilities changed while its storage did not, or a project that moved from MySQL to MariaDB, kept a copy with the old profile hash or target. `prisma db sign` recorded that stale profile hash in the database. Now the copy is replaced when the installed extension's contract differs. This fixed the stale saved copies in this repository's examples. **The freeze is held by tests, not by care.** Each family keeps saved contracts and their expected hashes as literals in a test. Changing one of those literals is changing the rules. `prisma contract emit` refuses to write a `storage` that does not hash to its storage hash, and the commands that render a saved contract's types refuse a contract file whose recorded hash does not match, with `CONTRACT.VALIDATION_FAILED` naming both hashes. Families and targets built outside this repository get `assertContractHashes`, which recomputes the hashes of their saved contracts and throws `CONTRACT.HASH_MISMATCH` naming each one that differs, because the freeze binds their part of the rules too. **Signing a database that only accepts migrations.** A database can carry a **change policy** that allows changes only through migrations, and it refuses `db sign`. `prisma db sign --force` overrides that one refusal for the upgrade. It still checks that the database matches the contract, changes no schema, and keeps the policy. No error message suggests it; only the upgrade instructions do. ## For users of a release candidate A project that starts on the release this ships in is not affected. A project from an earlier release candidate keeps reading its files and running queries (prisma#31200, merged, made later releases read those files). But the commands that compare the contract with a database refuse until it follows [the upgrade instructions](https://github.com/prisma/orm/blob/c3248f020d/upgrade-instructions/pending/contract-hash-inputs/app/instructions.md). Extensions have their own version of the instructions. 1. With the release the project is on now, deploy every pending migration, so each database is at the newest contract. 2. Upgrade Prisma, run the instructions' script, and run `prisma contract emit`, in either order. A run of the script that stops partway is finished by running it again. 3. In the deploy, sign each database with `prisma db sign --no-advance-ref`, then run `prisma db migrate`. The flag stops `db sign` from writing a ref file into the deploy's checkout. Add `--force` where the database allows only migrations. Two effects users will see: - **`prisma migration status` no longer shows the earlier migrations as applied.** The database's list of applied migrations holds their old hashes. Nothing is applied again, because `db migrate` works from the marker. - **The CLI refuses an extension built for an earlier release until the extension is rebuilt.** The error says what the application and the extension's author each do. The instructions also cover a value the release candidate dropped, such as the index option above. `contract emit` writes it back, so the contract now really differs from the database. The script lists each such contract, and the change ships as a migration; for an index option, which `prisma migration plan` cannot change in place, the instructions give a hand-written one. They also cover a database the deploy did not reach in time: it is signed at the last migration it applied, which `db sign` takes by that migration's directory name. ## Framework changes that need your agreement The repository's rules say changes to `packages/1-framework` need the reviewer's explicit agreement. These change what a family, target or tool built on the framework must call or implement: - `ContractSerializer` gets one required member, `normalizeStorage`, in place of three optional hooks, so every family supplies its own normal form. If it stayed optional, a family that supplied none would write and hash its content with no normal form, and nothing would tell it. - The canonicalizer, the code that turns a contract into the text that is hashed, loses the dropping rule and its lists of paths, so it only sorts and encodes. - `computeStorageHash`, `computeProfileHash`, `computeExecutionHash` and `buildExecutionSection` no longer take `target` or `targetFamily`. - `assertContractHashes` and its error `CONTRACT.HASH_MISMATCH` are published. - `writeContractSnapshot` takes `whenPresent: 'keep' | 'replace'`, so the step that writes an extension's newest saved copy can replace it. A replacement that fails and cannot put the old copy back throws a new error, `MIGRATION.CONTRACT_SNAPSHOT_REPLACE_FAILED`, which names where the old copy was left. The CLI's behaviour also changes, in the framework's CLI package: `db sign --force`, the refusal in `contract emit`, and the target check in the commands that load the project's migrations and extensions. None of these changes adds family or target vocabulary to the framework. ## How it was verified - **Expected hashes as literals.** Each family's test of the hash rules holds its expected hashes as literals, and fails when the target is added back to the hash input. - **Two implementations agree.** The upgrade script, which shares no code with the package, was run on four saved `8.0.0-rc.25` projects (one MongoDB, three PostgreSQL). Its output matched the package's for every contract, saved copy, migration and ref. Every contract, saved copy and migration this release writes was recomputed and agrees. The release-candidate fixtures keep their old hashes on purpose. - **The normal form is stable.** Each of 322 contracts this release emits, across all five databases, is byte-identical after being read and written again. - **Each row of the table** has a test that fails on the old rule, and every default a family names was checked against the database's own default. - **Each target check** has a test that fails without it: `db sign`, `db init`, `db migrate`, `migration plan`, `db verify` in both families, the extension loader, and a move from MySQL to MariaDB with an extension whose saved copy is stale. - **The upgrade.** The script's tests run on projects that `8.0.0-rc.25` itself emitted, planned and migrated, in both orders, interrupted at every point, and run twice. By hand, on real `8.0.0-rc.25` PostgreSQL and MongoDB projects and databases: both orders; a project with `fastupdate: false`, ending with the option set on the index; a migrations-only database with `--force`, and `--force` refusing a database whose schema does not match; a database one migration behind. - **Review.** Independent design and code reviews of each part, and of the final branch. - **CI** runs the package and end-to-end suites on the pull request. The integration suite runs in the merge queue. ## Known gaps Recorded in the project's [follow-up list](https://github.com/prisma/orm/blob/c3248f020d/projects/ga-compat-stored-files/deferred.md): - **A TypeScript contract used without emitting can log a wrong marker warning** when the config names an extension its source does not. No hash changes, so it can be fixed in any release. - **Some MongoDB validator lists keep an order that means nothing**, such as the branches of a derived `oneOf`. Sorting them could make the planner propose changing a validator that is already right in a live database, so they were left. After `8.0.0` that order is frozen until Prisma 9. ## API changes No application source code changes. These are for authors of a family, a target, an extension or a tool built on the toolchain. Each package's `api-breaks.json` records its breaks against `8.0.0-rc.25`. <details> <summary>The changed exports</summary> - `@prisma/orm-framework`: new `assertContractHashes`, `AssertContractHashesOptions`, `SavedContractHashes` and `HashedContractSections`. `ContractSerializer` has one required `normalizeStorage` (type `NormalizeStorage`) in place of the optional `shouldPreserveEmpty`, `sortStorage` and hash hooks. `CanonicalizeContractOptions` and the storage hash's arguments follow, and the hash functions and `buildExecutionSection` no longer take `target` or `targetFamily`. Removed with the dropping rule: `createPreserveEmptyPredicate`, `matchesPathPattern`, `PathPattern`, `PreserveEmptyPathSegment`, `PreserveEmptyPredicate` and `StorageSort`; `createStorageSort` now orders by name, then content. - `@prisma/orm-family-sql`: `sqlContractCanonicalizationHooks` is replaced by `normalizeSqlStorage` and `normalizeSqlDomain`, on a new entry `contract/normal-form`. `SqlContractSerializerBase` supplies `normalizeStorage`. - `@prisma/orm-family-mongo`: `mongoContractCanonicalizationHooks` is replaced by `normalizeMongoStorage` and `normalizeMongoDomain`, on `contract/normal-form`; `MongoContractSerializerBase` supplies `normalizeStorage`. - `@prisma/orm-postgres`, `@prisma/orm-mysql`, `@prisma/orm-mariadb`, `@prisma/orm-sqlite` and `@prisma/orm-mongo`: each re-exports the changed entries: `contract/hashing` changes, and `family-contract/normal-form` replaces `family-contract/canonicalization-hooks`. - `@prisma/orm-target-postgres`: `PostgresContractSerializer` no longer overrides which empty values are kept. - `@prisma/orm-target-mysql`, `@prisma/orm-target-sqlite` and `@prisma/orm-target-mongo`: each contract serializer inherits `normalizeStorage` from its family's base. - `@prisma/orm-toolchain`: `prisma db sign` gains `--force` (`DbSignOptions`, `ExecuteDbSignOptions`, `ExecuteDbSignSuccess`). `EmitOptions` takes the family's `normalizeStorage`. `createSnapshotContentVerifier` and `DescriptorSelfConsistencyInputs` take `normalizeStorage`, and `SnapshotCanonicalizationHooks` goes, because MongoDB snapshots are now checked like SQL ones. `writeContractSnapshot` takes `whenPresent`. `renderContractDts` refuses a contract file whose recorded storage hash does not match its storage, and its failure result carries the two hashes in an optional `storageHashMismatch`. - `@prisma/orm-extension-supabase`: no export changes; its bundled contract has new hashes, so the hash literal types in its `api.txt` changed. </details> ## Reviewing the diff <details> <summary>A suggested reading order</summary> About 1,400 of the changed files are the repository's own contracts, migrations, saved copies and refs, rewritten with new hashes. Read the rest in this order: 1. `packages/1-framework/0-foundation/contract/src/hashing.ts` and `canonicalization.ts`: the new inputs, and a canonicalizer that only sorts. 2. Each family's `normal-form.ts`, in `packages/2-sql-family/1-core/contract` and `packages/2-mongo-family/1-foundation/mongo-contract`, with their tests. 3. Each family's `hash-rules.fixed-answers.test.ts`. 4. `enrichContract` in the CLI and the SQL contract builder, where the profile hash gets the contract's capabilities. 5. The target check in `contract-space-aggregate-loader.ts`, and the snapshot replacement in `contract-snapshot-store.ts`. 6. `db sign --force` in the CLI. 7. The upgrade instructions and script, with the script's tests in `test/integration/test/upgrade-instructions/contract-hash-inputs/`. 8. ADR 332 and ADR 010. Two existing tests changed their expectations. The end-to-end test of a project exactly as the last release candidate left it keeps its assertions; its comment now says a database that release candidate signed needs the upgrade steps. Two examples expect foreign keys and MongoDB indexes in the sorted order. The sign-off check cannot read a pull request of more than 250 commits, so the earlier history was squashed into one commit; it is kept on `ga-compat-hashes-backup-pre-squash`. </details> ## Alternatives considered On the hash input: - **Keep the target and the family in each hash.** Rejected: no comparison needs them, and they cut a project off from its own migrations after a move between targets that write the same `storage`. A contract for the wrong target is better caught by a check that names the mistake than by a hash that only says the database does not match. - **Freeze the old input.** Rejected: the format version and the blanked parts would stay in every hash, so the first format change would change them all. - **Hash the file as written, by its format version's rules.** Rejected: the hash would change when a later format version lays out `storage` differently. - **Record which rules produced a hash, and support several.** Rejected: a project would hold hashes computed two ways, and every comparison would need converting. [Git's plan for a new hash function](https://git-scm.com/docs/hash-function-transition) rules out mixing two in one repository for the same reason. On what goes into each section: - **Keep the dropping rule and add the missing exceptions.** Rejected: the list grew with every defect found, and the next one would be found after the freeze. A rule that keeps everything fails loudly when a family forgets a default; the old one failed silently. - **Require that `false` and empty always mean absent inside values a family does not own.** Rejected: a convention nothing checks, put on outside authors, where a violation gives two different contracts one hash. - **Repair the SQL profile hash later, in the capabilities work.** Rejected: that work also lands before `8.0.0`, so the rules would change twice and every project would be signed twice. On moving existing databases: - **A migration from each old hash to its new one.** Rejected: one extra migration for every old hash a database could be at, each starting from a hash with no saved copy. - **Rewrite the database's list of applied migrations, so `migration status` keeps its history.** Rejected: a write to every database's history table only for what `migration status` displays; nothing reads that list to decide what to apply. - **Exempt `db sign` from the change policy.** Rejected: signing could then hide, on any database, that it left its migration history. `--force` keeps that a deliberate act, and the flag stays available for recovering a database the upgrade did not reach. Agent: alexvanhalen-55 🤖 Generated with [Claude Code](https://claude.com/claude-code) --------- Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]> Co-authored-by: Claude Opus 5.5 <[email protected]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
At a glance
The decision: every file Prisma stores in a project states the version of its format, a reader refuses a version or a field it does not know, and until
8.0.0it still reads the files a release candidate wrote.8.0.0is the first stable release of Prisma 8, which has not shipped; release candidates (8.0.0-rc.N) continue until then.Two things need the reviewer's decision:
migration checkcan pass a migration thatdb migraterefuses. Fixing it adds a hook to the framework. I recommend adding it, in this pull request or the next. Details are under "Known limits".Suppose Prisma
8.3changes how a migration is written, and a teammate on8.0pulls a migration that8.3wrote. Without this pull request,8.0could read it and apply only the part it understood. With it,8.0stops before it touches the database (an example of the output):To make that possible, every file Prisma writes into a project and reads back later starts with the version of its format:
What it costs and what it does not:
formatVersion. This release reads them as "format version 0" and converts them in memory. Each file becomes version 1 the next time a command writes it.8.0.0stops reading version 0, and a script in the upgrade instructions rewrites the files before that upgrade.8.0.0: a ref file a release candidate wrote is read with a stray key dropped, as the release candidates did.sortorreturnDocumenttorawFindOneAndUpdate, orsorttorawFindOneAndDelete, now sends them to the database. Earlier releases dropped them when they read the migration back, so the command ran without them. Applying such a migration to another database now does what its author wrote.readOperations, and a contract serializer overrides a different method. The full list is under "API changes".About 600 of the changed files are the repository's own contracts, snapshots, migrations and refs, rewritten by a script; each differs from
mainonly in the version field.A snapshot is the copy of a contract that a migration keeps beside it. A ref is a file that gives a contract a name, such as
production.ops.jsonholds the operations of a migration, beside itsmigration.json.The decisions
All are recorded in a new decision record, ADR 331.
contract.json, each snapshot,migration.jsonand each ref file carryformatVersion. A migration's version also covers itsops.json.8.0.0, files a release candidate wrote are read as version 0 and converted in memory. Until8.0.0the content of format 1 is also not final: a release candidate may still change it, with upgrade instructions.ops.jsonreads every shape of an operation that a release candidate wrote, for the whole of Prisma 8.Decisions 1 and 2: why the version and the refusal must be in
8.0.0The Prisma 8 compatibility policy promises (its page is a draft, #31193; the promise itself is agreed) that a later 8.x release reads every file an earlier one wrote, and the user regenerates nothing. An
8.0.0reader stays in use for the whole major. So it must already know how to recognise a file it cannot read, and it must already refuse what it does not understand. A reader that ignores an unknown key in8.0.0will ignore, for the whole major, a field a later release adds. Neither can be added afterwards.A reader is strict because a migration is an instruction to change a database. Acting on one that is only partly understood is the failure the rule prevents.
Decision 3: what "refuses a field it does not know" changed
Before this pull request several readers ignored unknown keys:
migration.jsonand ref filesops.jsonops.jsonmigration plandb migrate --toanddb update --tofor the snapshot a ref names, andmigration checkfor every snapshot a ref names or a graph ends at. A snapshot a command only records or identifies by hash is not readA family is the code shared by databases of one kind (SQL, MongoDB); a target is one database, such as PostgreSQL.
The rule stops at content Prisma carries for someone else, where any key is accepted. These are the open places:
meta,capabilities, an extension's own section, a generator's parameters, a literal default's value, an index's options, a SQL statement's parameters, and the MongoDB documents handed to the database as they are. ADR 331 lists them.SQL operations are read strictly by everything that acts on their statements: the runners, the statement preview, and the checks
db migrateruns on a recorded path.A command reads strictly what it interprets in that run, and no more.
db migraterecords the snapshot of each migration it applies as it is stored, andmigration status,list,graphandref setuse hashes only. This matters for old projects: one with a snapshot in a shape from before8.0.0-rc.1, which no reader of this release reads, still applies its migrations. The repository's telemetry app is such a project.A command that cannot read a stored file names it and says why, and never calls it unknown or missing. It refuses when it acts on the file;
migration list,graph,statusandcheckreport it and go on with the rest.db updateis the one command that goes on past a file it acts on: when the snapshot of the contract the database was last at cannot be read, it warns and continues as for a database with no recorded origin. Before this, several commands dropped such a file without a word:migration listandgraphleft out a migration,migration newstarted from the empty contract when its ref could not be read, andmigration checkreported the migrations after an unreadable one as unreachable, with advice to delete them. Every command and entry point that loads a stored file was listed and checked for this.The advice a refusal gives follows one rule: restore the file from version control first; name a command only where that command writes the file again, and say what else it does; never give a new hash to a migration a database has applied; never name a contract for the
dbref by hand. For example, a lostmigration.jsonis written again by running the migration'smigration.ts, which gives it a new hash, so that advice is offered only when no database has applied the migration. The database commands warn about a migration whose snapshot they cannot record only when the run applies it.Decision 5: why release-candidate files are read, and only until
8.0.0Release-candidate users have asked for fewer forced rewrites. Reading their files costs them nothing now. It also runs the "convert an earlier format" path on real files before the first format change after
8.0.0depends on it.A release-candidate file is recognised without guessing: a contract has
"schemaVersion": "1"and noformatVersion; amigration.jsonor ref has neither. Only a release candidate wrote those. A contract with neither field is refused, because no release wrote it. Version 0 has a converter and no printer, so no release writes it. A test fails if a release that is not a pre-release still reads version 0, so8.0.0cannot ship with it.#31203, built on this pull request, changes how contract hashes are computed. The parts of release-candidate reading that depend on that are there.
Decision 6: why older operation shapes are read for the whole major
From
8.0.0no release may change a migration's hash, andops.jsonis covered by that hash. So from8.0.0an older shape of an operation can only be read, never rewritten, and format 1 has to read it for the whole major. Before8.0.0a script could still have rewritten those shapes, because the hash rules change once before8.0.0(#31203). Reading them was chosen because it is small and costs users no step. The reader converts each to the current shape before it checks the operation, so nothing after it sees the older form:8.0.0-rc.19: every operation carried"schema": "main". It is dropped. Any other value is refused.8.0.0-rc.21andrc.22: an entry in a step'smetatells the runner to count the rows that still hold a removed enum value. In those releases it had fewer fields. The reader fills them in from the same places those releases' runners read them.sortandreturnDocumentonrawFindOneAndUpdateandsortonrawFindOneAndDelete, are now passed to the command. That changes what such a migration does when it is applied again: it now does what its author wrote.These were found by going through the history of every planner, operation class and serializer across all 485 published
8.0.0-rctags (each release candidate and the development builds between them), because the repository holds no saved file of most of them. Contract shapes from earlier release candidates need no such acceptance: published upgrade instructions already rewrite them.Known limits
Recorded in the project's follow-up list,
projects/ga-compat-stored-files/deferred.md:migration check,status,listandgraphdo not read a target's own operation fields. They loadops.jsonin the framework and use only the fields every target shares. Somigration checkcan pass a migration thatdb migraterefuses. Fixing it means the framework asks the family to read each operation when it loads the file, which adds to the framework. It is listed in ADR 331 as an alternative not chosen here, and it is the second decision asked of the reviewer above.db migratethen refuses, for the same reason.typeandoptionsare not checked when a contract is read, only by the TypeScript builder.db migraterefuses a migration, because the refusal comes after the database is opened to read its marker. That was so before this change.For users of a release candidate
Nothing to do for this change. The upgrade instructions, for applications and for extensions, still ship a script that rewrites every file to version 1. It is required before upgrading to
8.0.0, and optional until then:That is its path in this repository. A user gets it with the release's upgrade guide in the Prisma 8 skill and runs it from their project root.
It renames
schemaVersionin every contract and snapshot, addsformatVersionto everymigration.jsonand ref file, changes no other byte and no hash, removes an unknown field from a ref file and lists it, and changes nothing when run again.API changes
Application code changes nothing. The changes are for authors of a family, a target, an extension or a tool built on the toolchain.
@prisma/orm-framework: new entriescontract/format-version(convertContractDocument, which reads a stored contract's version and converts an earlier one;NEWEST_CONTRACT_FORMAT_VERSION, which a family writes into the contracts it prints;isFormatVersionError; and their types), so a family built outside this repository reads and writes a contract the way Prisma does (the same names are also on thecontractentry);contract/internal/format-version, the shared reader and its converters for every kind of file (readStoredDocument,StoredFormatand their types), which Prisma's own packages reach each other through and which is not for outside code; andutils/upgrade-guides, the addresses a refusal points to.CanonicalizeContractOptionslosesschemaVersion, becausecanonicalizeContractno longer takes or writes it.errorContractValidationFailedaccepts the file's path and what kind of file it is in its options, so a refused contract or snapshot names its file.@prisma/orm-postgres,@prisma/orm-mysql,@prisma/orm-mariadb,@prisma/orm-sqliteand@prisma/orm-mongo: each re-exports the three new framework entries, because a database package re-exports every framework entry so that code built on it needs no direct dependency on the framework. That includes theinternalentry, which Prisma's own packages use to reach each other and which is not for outside code.@prisma/orm-family-sql:SqlContractSerializerBasegains protectedparseContractV1andprintContractV1, the parser and printer of contract format 1; the base class reads and writes the version around them. New:createSqlOperationsReader,SqlOperationsReader,SqlTargetOperationsFormatandSqlOperationsLocation, the strict reader of SQL operations and what a target supplies to it; andprobeUnknownKeys,SQL_OPERATIONS_OPEN_PLACES,DocumentPlaceandUnknownKeyProbe, a test helper with which a SQL target's author checks that its reader refuses an unknown key everywhere outside the open places.SqlControlTargetDescriptorgains a requiredreadOperations, so a SQL target built outside this repository must now supply it. Itsapi-breaks.jsonrecords the breaks against8.0.0-rc.25.@prisma/orm-family-mongo:MongoContractSerializerBaseandMongoContractSerializergainparseContractV1andprintContractV1, for the same reason as the SQL base.@prisma/orm-target-postgres:PostgresContractSerializeroverridesprintContractV1where it overrodeserializeContract, because the base class now writes the version around it.@prisma/orm-target-mysql:MysqlContractSerializeroverridesprintContractV1for the same reason, and the target suppliesreadOperations. Itsapi-breaks.jsonrecords the breaks.@prisma/orm-target-sqlite:SqliteContractSerializeroverridesprintContractV1for the same reason.@prisma/orm-target-mongo:MongoTargetContractSerializeroverridesprintContractV1for the same reason.deserializeMongoOpstakes an optionalMongoOperationsLocation, so a refusal names the migration and the operation.@prisma/orm-toolchain: newparseMigrationMetadataDocument,printMigrationMetadataDocument,parseRefDocument,printRefDocumentand their document types, the parser and printer of each version ofmigration.jsonand ref files.computeMigrationHashacceptsformatVersionand leaves it out of the hash.contractSpaceFromJsonrequiresspaceId, so an error in a file an extension ships names the extension.assertDescriptorSelfConsistencytakes the wholecontractJson, so it can read the version first.buildReadAggregategainsonUnreadableFile, which refuses an unreadable ref or migration by default and lets a listing command report it and keep going.IntegrityViolation'scontractUnreadablegains the snapshot'shash, so a refusal names the file; the functions that carry that type are recorded as breaks for it.DbUpdateOptionsgains an optionalonUnreadableOrigin.enumerateCheckSpacestakes one options object (EnumerateCheckSpacesInputs) with the family's contract reader, andCheckSpacecarries that reader and the migrations that could not be read;checkSingleTargetandrunMigrationCheckfollow. Itsapi-breaks.jsonrecords these. The breaks recorded against8.0.0-rc.25arecontractSpaceFromJson,assertDescriptorSelfConsistency,buildReadAggregate,enumerateCheckSpaces,checkSingleTargetandrunMigrationCheck.The repository's rule is that the framework domain,
packages/1-framework, gains no new concepts. This pull request adds one there (the first decision asked of the reviewer above): the shared reader of a stored file's format version, with its converters. It is in the framework because some paths read a contract before any family sees it (the CLI's contract reader, the snapshot store, an extension's bundled files). The strict readers added nothing to the framework. This addition needs the reviewer's agreement.Reviewing the diff
A suggested reading order
packages/1-framework/0-foundation/contract/src/format-version.ts: the shared reader, the refusals and their advice, version 0.packages/1-framework/3-tooling/migration/src/formats/: one unit per version ofmigration.jsonand ref files.packages/2-sql-family/1-core/contract/src/validators.ts,packages/2-mongo-family/1-foundation/mongo-contract/src/contract-schema.ts).packages/2-sql-family/9-family/src/core/migrations/operations-reader.ts, and each SQL target'sread-operations.ts.packages/3-targets/mongo/1-target/src/core/migrations/mongo-ops-serializer.ts.test/integration/test/upgrade-instructions/stored-files-format-version/.How it was verified
ops.jsonof each target.contract.jsonand every saved SQL and MongoDBops.json, and fail on an empty list. They exclude, by name, 46 contracts in shapes from before8.0.0-rc.1, which the publishedrc.25reader refuses too, and the fixtures of earlier upgrade scripts. Stored contracts under other file names (112, mostly expected-output files of tests) are not in that test; a one-off run read all but one deliberate "before" fixture.rc.22runner's code.8.0.0-rc.25wrote are read file by file. The three tests onmainthat give anrc.25contract to a client pass.beforeandafterproject trees, a second run, and files it must refuse.8.0.0-rc.25PostgreSQL and MongoDB projects with no script run:contract emit,migration status,migration check,migration planof a change,db migrate,db verifyand a query worked, and only the files the commands wrote moved to version 1."schema": "main"applied and"schema": "other"was refused. On MongoDB, thesortof a raw command decided which document changed.--dband--config, and the project checked afterwards withmigration checkanddb migrate. Four review rounds found advice that refused, had side effects it did not state, or changed a hash; the last round fixed six such findings, and a final check covered only those six.varchar(0)as a generic "contract validation failed". It now reports the data type's ownCONTRACT.TYPE_PARAMS_INVALID, as main did. The CLI passes that error through as itself, alongside the format version errors. That is a list of codes chosen by name, not a rule for every library error: these are the read errors whose own message tells the user what to change, where the generic wrapper's advice (emit again) would not help. The commands that only list migrations still report it and go on.Alternatives considered
8.0.0.8.0.0and not chosen: reading the shapes is small and costs users no step. From8.0.0it is not possible, because a migration's hash may not change.ops.json. Not chosen here, because it adds to the framework. See "Known limits"."1.2". Rejected: a reader refuses any version it does not know, so there is no compatible minor step to express.contract.json, or one for the whole project. Rejected: migrations and refs are read on their own, and the files change independently.ops.json, by wrapping the array in an object. Rejected: it would change every migration's hash, andops.jsonis never read without itsmigration.json.formatVersionin the migration hash. Rejected: converting a migration to a later format would change its hash.Agent: alexvanhalen-55
🤖 Generated with Claude Code