Repository navigation
TML-2981: serialize the whole namespace entries dict, not a branch per kind - #931
Conversation
…L-2981) Slice spec + plan entry for O1 from the PR #906 review — make the SQL contract serializer iterate the namespace `entries` dict generically (symmetric with the already-generic hydrate path) so extension-contributed entity kinds round-trip without a serializer edit. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
The SQL contract serializer round-tripped entity kinds asymmetrically: hydration already iterated the registered kinds generically (`hydrateNamespaceEntities(entriesInput, this.entryKinds, …)`), but serialization hardcoded one branch per kind in each target, so an extension-contributed kind hydrated for free yet was silently dropped on serialize unless someone edited the target serializer (PR #906 review, O1). Make serialization symmetric: a new `SqlContractSerializerBase.serializeNamespaceEntries` walks `Object.entries(ns.entries)` — naming only `table`, the universal base kind (always emitted; other kinds emitted only when non-empty). The Postgres and SQLite serializers delegate to it and their unbound-slot branches; the JSON round-trip helpers move down to the base alongside it. `native_enum` stays excluded for free — it is non-enumerable on `ns.entries`, so `Object.entries` skips it. Output is byte-identical: the emitted contract is canonicalized (recursive key sort) after serialization, so the generic walk order is irrelevant, and the emitted key set is unchanged. A pack-contributed kind now round-trips serialize with no serializer edit (proven by a base-level test with a synthetic `widget` kind + a non-enumerable `native_enum`). typecheck 143/143; family-sql + target-postgres + target-sqlite tests green; fixtures:check zero drift; lint:casts flat (1031); lint:deps clean. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
📝 WalkthroughWalkthroughAdds shared namespace-entry serialization helpers to ChangesNamespace Entries Serialization Refactor
Estimated code review effort: 2 (Simple) | ~15 minutes Possibly related PRs
Suggested reviewers: 🚥 Pre-merge checks | ✅ 5✅ Passed checks (5 passed)
✨ 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 |
size-limit report 📦
|
@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/extension-supabase
@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/config-loader
@prisma-next/emitter
@prisma-next/language-server
@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: |
entries dict generically- F01 (correctness): guard the generic entries walk against a null/undefined record. `PostgresSchema` can carry an enumerable `valueSet: undefined` own-key (its empty-valueSet normalization); `Object.keys(undefined)` threw. Latent today (generated paths drop empty valueSets) but reachable via the public class — the old serializer was immune because it read through getters. Adds a base-level test planting an enumerable `undefined` slot. - F02: `serializeEntries` → `private` (only called from `serializeNamespaceEntries`). - F03 + family-blindness: the two Postgres namespace-serialize paths were byte-identical, so fold them into one loop and drop `serializePostgresNamespace` + its orphaned native-enum JSDoc; de-Postgres the family-base doc comment so it names no target concept. typecheck 143/143; family-sql 337/337; target-postgres 686/686; target-sqlite 168/168; fixtures:check zero drift; lint:casts flat (1031); lint:deps clean. Co-Authored-By: Claude Opus 4.8 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
There was a problem hiding this comment.
🧹 Nitpick comments (1)
packages/3-targets/3-targets/postgres/src/core/postgres-contract-serializer.ts (1)
112-115: 📐 Maintainability & Code Quality | 🔵 Trivial | 💤 Low valueTrim the avoidable part of this comment per coding guidelines.
Lines 112–113 restate what the code already expresses (
id,kind,entries). Only the native-enum exclusion explanation (lines 113–115) carries non-obvious context worth keeping. As per coding guidelines, don't add comments if avoidable — prefer code that expresses its intent.♻️ Suggested trim
- // Each namespace serializes to its id, its schema-kind tag, and the - // base's generic entries walk. Native enums are excluded upstream — - // carried non-enumerable on `PostgresSchema.entries`, so the walk - // never sees them. + // Native enums are excluded upstream — carried non-enumerable on + // `PostgresSchema.entries`, so the generic walk never sees them. for (const [nsId, ns] of Object.entries(storage.namespaces)) {🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/3-targets/3-targets/postgres/src/core/postgres-contract-serializer.ts` around lines 112 - 115, Trim the comment in postgres-contract-serializer’s namespace serialization logic so it only keeps the non-obvious native-enum exclusion context; the parts describing id, schema-kind, and entries are already self-evident from the code. Update the comment near the namespace serialization walk to remove the redundant explanation and retain only the note about native enums being excluded upstream and carried non-enumerable on PostgresSchema.entries.Source: Coding guidelines
🤖 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.
Nitpick comments:
In
`@packages/3-targets/3-targets/postgres/src/core/postgres-contract-serializer.ts`:
- Around line 112-115: Trim the comment in postgres-contract-serializer’s
namespace serialization logic so it only keeps the non-obvious native-enum
exclusion context; the parts describing id, schema-kind, and entries are already
self-evident from the code. Update the comment near the namespace serialization
walk to remove the redundant explanation and retain only the note about native
enums being excluded upstream and carried non-enumerable on
PostgresSchema.entries.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yml
Review profile: CHILL
Plan: Pro
Run ID: ca9fb6d5-baed-483b-bb4e-7d0ee650e183
📒 Files selected for processing (3)
packages/2-sql/9-family/src/core/ir/sql-contract-serializer-base.tspackages/2-sql/9-family/test/namespace-entries-serialization.test.tspackages/3-targets/3-targets/postgres/src/core/postgres-contract-serializer.ts
🚧 Files skipped from review as they are similar to previous changes (2)
- packages/2-sql/9-family/test/namespace-entries-serialization.test.ts
- packages/2-sql/9-family/src/core/ir/sql-contract-serializer-base.ts
….json (prisma#946) > **Stacked on prisma#944** (`infer-native-enum-adoption`). Review/merge that first; this branch rebases onto main once it lands. The net diff below is against prisma#944's head. ## What this does A `native_enum` entity used to be **authoring-time-only** — carried non-enumerable on `PostgresSchema.entries`, so the serializer, the hashing pipeline, and `contract.json` all walked past it. Only the *derived* `entries.valueSet` survived. That was Phase 1's "no readers after emit" assumption, and it has expired twice: 1. **Phase 2 owns DDL for these types** (`CREATE TYPE`/`ADD VALUE`). The migration planner must derive the expected type — name and *ordered* members — from the storage segment of `contract.json` alone (storage-only planning, ADR 004/199). It can't, if the entity isn't there. 2. **Pack-owned enum subtraction was blind on hydrated contracts.** prisma#944 taught `contract infer` to omit an introspected enum type that a stack pack already declares — but only when the pack's contract was *in memory*. In production, `describedContracts` hydrate from `contract.json`, which carried no enum type names, so the subtraction silently matched nothing. After this PR, `entries.native_enum` serializes like `role`/`policy`: ```jsonc "entries": { "native_enum": { "AalLevel": { "kind": "postgres-enum", "typeName": "aal_level", "members": ["aal1", "aal2", "aal3"] } }, "valueSet": { "AalLevel": { /* derived, unchanged */ } } } ``` and a JSON-hydrated Supabase pack contract exposes `aal_level` to the infer subtraction — closing prisma#944's follow-up the production way. ## The change is a deletion The entity was excluded from `contract.json` by exactly one thing: a non-enumerable-property trick in `postgres-schema.ts`. The generic serializer (TML-2981, prisma#931) already iterates the entries dict; hydration already composes `nativeEnumEntityKind`. So the fix is **deleting the carve-out** — the entity then serializes, hydrates, and is captured by `storageHash` with no serializer or validator edit. Confirmed by reading the machinery, not assuming it. **Hash coherence is preserved, inverted.** The carve-out's own comment said its purpose was keeping `computeStorageHash`'s `JSON.stringify` walking past the entity, so the hash matched serialized bytes. Enumerability restores that coherence in the inclusive direction: bytes and hash now move *together*, and only for enum-bearing contracts. A storageHash-differ test fails RED under the old carve-out and passes only after the deletion — the coherence proof can't false-pass. **`contract.d.ts` type surface is unchanged.** The generic-collapse review removed raw-slot emission from the `.d.ts`; that stays true. The only `.d.ts` movement is the `StorageHash` literal (the hash is baked into the type), and it matches the moved `storageHash` in `contract.json` byte-for-byte. ## Commits 1. **`native-enums(D1)`** — delete the carve-out; the entity flows through the generic serialize/hydrate/hash path. Round-trip + absent-key-tolerance + enum-free-byte-identity tests. 2. **`native-enums(D2)`** — prove the payoff production-shaped: an infer-entry test builds the Supabase-shaped described contract, round-trips it through serialize→JSON→hydrate, and asserts `contract infer` omits the pack-owned `aal_level` while emitting a non-pack-owned `factor_type` in the same run (selective, not blanket). No change to the subtraction code — D1 was the whole enabler. 3. **`native-enums(D3)`** — regenerate the artifacts the byte/hash change touches (Supabase pack `contract.{json,d.ts}`, parity `expected.contract.json`) via `pnpm fixtures:emit`; drift reviewed to be exactly `+ entries.native_enum + moved hashes` on enum-bearing contracts, enum-free artifacts and all example ledgers byte-identical. ## What's out of scope (deliberately) - **Phase-2 planner/differ/ops.** The entity is now *available* to the planner from storage; nothing reads it yet. Slice A wires the projection + `CREATE TYPE`/`ADD VALUE`. - **Multi-namespace infer** (TML-2958) and the **CLI schema-selection limitation** — separate follow-ups; this PR makes the subtraction *capable* on hydrated contracts, which those will exercise at scale. ## Verification Full gate run (independently re-run by the coordinator on top of the implementer's logged runs): `pnpm build`, `pnpm typecheck`, `lint:casts` (−1), `lint:deps`, `lint:framework-vocabulary` (836/836), `pnpm fixtures:check` (clean post-regeneration), `pnpm test:packages`, `pnpm test:integration`, PSL↔TS parity, and the Supabase example suite (db-verify passes against the regenerated pack). Residual test failures were the repo's known flake families (PGlite portal-race, `/var`→`/private/var` macOS symlink, 100ms teardown timeouts), each passing on isolation rerun — the diff is regeneration-only, so no failure can be a logic regression. 🤖 Generated with [Claude Code](https://claude.com/claude-code) <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit - **New Features** - PostgreSQL native enum definitions are now preserved in contract data and remain available after serialization and rehydration. - Contract outputs now include native enum metadata, including names, members, and database type names. - Storage hashes now reflect changes to native enum definitions. - **Bug Fixes** - Improved compatibility with contracts that omit native enum information. - Preserved correct enum handling when identifying pack-owned and externally defined enums. <!-- end of auto-generated comment: release notes by coderabbit.ai --> --------- Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
At a glance
Serializing a namespace's entity kinds used to mean one hand-written branch per kind, repeated in every SQL target:
Now it means walking the whole
entriesdict once, in the shared base:The decision
Serialize a namespace's entity kinds by iterating the
entriesdict generically, inSqlContractSerializerBase— no target names a kind. This makes writing a contract match how we already read one: hydration has always iterated the entity-kind registry, so an entity kind now round-trips in both directions with no serializer edit.Why — the asymmetry we're fixing
Deserialize was already generic — it walks the registered kinds:
Serialize was not — each target listed
table/valueSet/role/policyby hand. The consequence: an extension that contributes a new entity kind reads back for free but is silently dropped on the way out, until someone remembers to edit the target serializer. There was no signal that the write path needed touching — the kind just quietly vanished fromcontract.json.What changes
SqlContractSerializerBase.serializeNamespaceEntrieswalksObject.entries(entries). The Postgres and SQLite serializers — and their unbound-slot branches — delegate to it; the JSON round-trip helpers move down into the base beside it.tableis the one kind still named: it is the universal SQL base kind, always emitted even when empty. Every other kind is emitted only when it holds an entry — the exact rule the old branches applied by hand.entriesand already hydrated via the registry, so it now serializes with zero serializer edits.The one thing to trust: output is byte-identical
The old code emitted kinds in a fixed order; the new walk uses insertion order. That does not change the emitted file, because the contract is canonicalized — recursive key sort — after serialization on every path that writes or hashes it, so walk order never reaches disk. The emitted key set is unchanged too (
tablealways; others only when non-empty).fixtures:checkshows zero drift.Two details keep it that way:
native_enumstays excluded. It is authoring-time-only, carried non-enumerable onentries(its values survive via the derivedvalueSet), soObject.entriesskips it with no special case.sql.enums: false, so its only non-tableslot is always empty and stays omitted; a future SQLite kind would round-trip instead of being dropped.Tests
A base-level test serializes a namespace whose
entriescarrytable, a real non-tablekind, a synthetic extensionwidgetkind, an empty kind, and a non-enumerablenative_enum— asserting the extension kind round-trips whilenative_enumand the empty kind drop out. Existing target-serializer tests plusfixtures:checkare the byte-identical proof.Alternatives considered
alwaysPresentflag to the kind descriptor instead of namingtabledirectly. Rejected: speculative generality for a set of size one.tableis the only universal base kind; naming it is honest and cheaper than a descriptor field one kind would ever set.entryKindsregistry (mirroring hydrate's exact mechanism) rather thanObject.entries. The enumerable-key walk is simpler and getsnative_enumexclusion for free via non-enumerability; consulting the registry would add a lookup the write path doesn't need.Origin: review point O1 on #906. Shaping spec:
projects/native-postgres-enums/slices/generic-namespace-entries-serialization/spec.md.🤖 Generated with Claude Code
Summary by CodeRabbit