Repository navigation
TML-2887: namespace entries becomes an open, kind-keyed dictionary (ADR 224/225) - #812
Conversation
|
Note Reviews pausedIt looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughStorage namespace IRs now use open kind-indexed ChangesNamespace entries and serializer transition
Sequence Diagram(s)sequenceDiagram
participant Authoring as Contract authoring
participant Serializer as PostgresContractSerializer
participant StorageIR as storage.namespaces[].entries
participant Validator as schema validation
participant Runtime as target/runtime call sites
Authoring->>Serializer: deserializeContract(...)
Serializer->>StorageIR: hydrate kind-indexed entries
Serializer->>Validator: validate entries registry
Validator->>StorageIR: resolve table/type/valueSet entries
Runtime->>Serializer: deserializeContract(...) at call sites
ChangesNamespace entries and serializer transition
Estimated code review effort🎯 5 (Critical) | ⏱️ ~120 minutes Possibly related issues
Possibly related PRs
Suggested reviewers
Poem
✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
|
@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/emitter
@prisma-next/migration-tools
prisma-next
@prisma-next/vite-plugin-contract-emit
@prisma-next/mongo-codec
@prisma-next/mongo-contract
@prisma-next/mongo-value
@prisma-next/mongo-contract-psl
@prisma-next/mongo-contract-ts
@prisma-next/mongo-emitter
@prisma-next/mongo-schema-ir
@prisma-next/mongo-query-ast
@prisma-next/mongo-orm
@prisma-next/mongo-query-builder
@prisma-next/mongo-lowering
@prisma-next/mongo-wire
@prisma-next/sql-contract
@prisma-next/sql-errors
@prisma-next/sql-operations
@prisma-next/sql-schema-ir
@prisma-next/sql-contract-psl
@prisma-next/sql-contract-ts
@prisma-next/sql-contract-emitter
@prisma-next/sql-lane-query-builder
@prisma-next/sql-relational-core
@prisma-next/sql-builder
@prisma-next/target-postgres
@prisma-next/target-sqlite
@prisma-next/adapter-postgres
@prisma-next/adapter-sqlite
@prisma-next/driver-postgres
@prisma-next/driver-sqlite
commit: |
size-limit report 📦
|
There was a problem hiding this comment.
Actionable comments posted: 6
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (3)
packages/2-sql/5-runtime/src/codecs/validation.ts (1)
24-29:⚠️ Potential issue | 🟠 Major | ⚡ Quick winNamespace collisions can hide missing codec mappings.
extractCodecIdsFromColumnskeys rows bytable.columnonly. If two namespaces share the same table+column names, one entry overwrites the other and missing codec detection can be skipped incorrectly.💡 Suggested fix
- for (const ns of Object.values(contract.storage.namespaces)) { - for (const [tableName, table] of Object.entries(namespaceTables(ns))) { + for (const [namespaceId, ns] of Object.entries(contract.storage.namespaces)) { + for (const [tableName, table] of Object.entries(namespaceTables(ns))) { for (const [columnName, column] of Object.entries(table.columns)) { const codecId = column.codecId; - const key = `${tableName}.${columnName}`; + const key = `${namespaceId}.${tableName}.${columnName}`; codecIds.set(key, codecId); } } }🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/2-sql/5-runtime/src/codecs/validation.ts` around lines 24 - 29, The current extractCodecIdsFromColumns implementation builds keys as `${tableName}.${columnName}` which allows collisions across different namespaces; update it to include the namespace identifier (e.g., `${namespaceName}.${tableName}.${columnName}` or similar) when creating the key so each column is uniquely keyed per namespace, ensuring codecIds.set uses a namespace-qualified key and prevents silent overwrites in functions that iterate contract.storage.namespaces and namespaceTables.packages/2-mongo-family/9-family/src/core/ir/mongo-contract-serializer-base.ts (1)
127-140:⚠️ Potential issue | 🟠 Major | ⚡ Quick winPreserve non-collection entry kinds during namespace hydration.
At Line 139, hydration rebuilds
entrieswith onlycollection, which silently drops otherentries[kind]maps when present. In an open-dictionary model this is a data-loss path across deserialization.💡 Suggested fix
return [ nsId, { ...nsEnvelope, id: nsEnvelope.id, - entries: { collection: hydratedCollections }, + entries: { + ...(nsEnvelope.entries as Record<string, unknown>), + collection: hydratedCollections, + }, }, ];🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the rest with a brief reason, keep changes minimal, and validate. In `@packages/2-mongo-family/9-family/src/core/ir/mongo-contract-serializer-base.ts` around lines 127 - 140, The hydration currently rebuilds nsEnvelope.entries with only a collection key, discarding any other entry kinds; update the logic in mongo-contract-serializer-base (the block using namespaceCollections, rawCollections, hydratedCollections and returning { ...nsEnvelope, entries: { collection: hydratedCollections } }) to merge the hydrated collection map into the existing nsEnvelope.entries object instead of replacing it—e.g., compute hydratedCollections as you do and then set entries = { ...nsEnvelope.entries, collection: hydratedCollections } so non-collection entry kinds are preserved; ensure you still convert raw items to MongoCollection (using MongoCollectionInput) as before.test/integration/test/cli.emit-cli-process.e2e.test.ts (1)
196-217:⚠️ Potential issue | 🟠 Major | ⚡ Quick winRestore hard presence assertions before comparing table columns.
On Line 196, the optional access plus
if (userTable && originalUserTable)allows this test to pass when either table is missing, so round-trip regressions can be missed.Suggested fix
- const tables = (validatedContract.storage as SqlStorage).namespaces['public']?.entries[ - 'table' - ] as Record<string, unknown> | undefined; + const tables = (validatedContract.storage as SqlStorage).namespaces['public']?.entries[ + 'table' + ] as Record<string, unknown> | undefined; const originalTables = (originalContract.storage as SqlStorage | undefined)?.namespaces[ 'public' ]?.entries['table'] as Record<string, unknown> | undefined; + expect(tables).toBeDefined(); + expect(originalTables).toBeDefined(); const userTable = tables?.['user'] as Record<string, unknown> | undefined; const originalUserTable = originalTables?.['user'] as Record<string, unknown> | undefined; - if (userTable && originalUserTable) { - const columns = userTable['columns'] as - | Record<string, { nativeType?: string; codecId?: string }> - | undefined; - const originalColumns = originalUserTable['columns'] as - | Record<string, { nativeType?: string; codecId?: string }> - | undefined; - if (columns && originalColumns) { - expect(columns['id']?.codecId).toBe(originalColumns['id']?.codecId); - expect(columns['email']?.codecId).toBe(originalColumns['email']?.codecId); - expect(columns['id']?.nativeType).toBe(originalColumns['id']?.nativeType); - expect(columns['email']?.nativeType).toBe(originalColumns['email']?.nativeType); - } - } + expect(userTable).toBeDefined(); + expect(originalUserTable).toBeDefined(); + const columns = userTable?.['columns'] as + | Record<string, { nativeType?: string; codecId?: string }> + | undefined; + const originalColumns = originalUserTable?.['columns'] as + | Record<string, { nativeType?: string; codecId?: string }> + | undefined; + expect(columns).toBeDefined(); + expect(originalColumns).toBeDefined(); + expect(columns?.['id']?.codecId).toBe(originalColumns?.['id']?.codecId); + expect(columns?.['email']?.codecId).toBe(originalColumns?.['email']?.codecId); + expect(columns?.['id']?.nativeType).toBe(originalColumns?.['id']?.nativeType); + expect(columns?.['email']?.nativeType).toBe(originalColumns?.['email']?.nativeType);🤖 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 `@test/integration/test/cli.emit-cli-process.e2e.test.ts` around lines 196 - 217, The test currently uses conditional guards that let it silently pass if the tables or columns are missing; change that to hard assertions: replace the if-checks around userTable and originalUserTable with explicit expects (e.g., expect(userTable).toBeDefined() and expect(originalUserTable).toBeDefined()) and likewise assert columns and originalColumns exist (expect(columns).toBeDefined(), expect(originalColumns).toBeDefined()) before comparing codecId/nativeType values so the test fails if anything is absent; keep the subsequent compares of columns['id'] and columns['email'] as-is.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.
Inline comments:
In
`@packages/2-mongo-family/1-foundation/mongo-contract/src/ir/build-mongo-namespace.ts`:
- Around line 34-38: The fast-path that returns MongoUnboundNamespace.instance
when input.id === UNBOUND_NAMESPACE_ID and collectionCount === 0 skips
validating input.entries kinds; update the logic in build-mongo-namespace (the
function handling input.entries, collectionMap, UNBOUND_NAMESPACE_ID and
MongoUnboundNamespace.instance) to first validate that Object.keys(input.entries
|| {}) contains only allowed kinds (e.g., 'collection') and if any unknown kind
is present, do NOT take the unbound singleton fast-path — let the normal
constructor/validation path run (or throw) so unknown kinds are caught. Ensure
you reference input.entries, collectionMap, UNBOUND_NAMESPACE_ID and
MongoUnboundNamespace.instance when adding the check.
In `@packages/2-sql/1-core/contract/src/index-type-validation.ts`:
- Around line 13-14: The explicit cast "rawTable as StorageTable" is redundant
because namespaceTables(ns) already yields StorageTable values; remove the bare
cast by assigning const table = rawTable (or, if a cast is truly required for
type-system reasons, replace the bare cast with the sanctioned helper, e.g.
blindCast<StorageTable, "namespaceTables-return">(rawTable) or
castAs<StorageTable>(rawTable)); update the assignment in the loop that uses
namespaceTables, rawTable and table accordingly.
In `@packages/2-sql/1-core/contract/src/ir/build-sql-namespace.ts`:
- Around line 33-37: fromTablesInput currently takes the unbound fast-path when
input.id === UNBOUND_NAMESPACE_ID and only checks counts for 'table'/'valueSet',
which lets unknown entry kinds bypass validation; update the early-return logic
in fromTablesInput to detect any unknown keys in input.entries (i.e., keys other
than 'table' and 'valueSet') and avoid returning SqlUnboundNamespace.instance if
unknown kinds exist so that the normal constructor validation (the namespace
constructor that validates entry kinds and throws) runs; alternatively,
explicitly throw on unknown entry kinds in fromTablesInput after computing
allowedKinds to ensure invalid kinds are rejected rather than skipped.
In `@packages/2-sql/3-tooling/emitter/src/index.ts`:
- Around line 118-119: The code uses bare TypeScript "as" casts (e.g.,
"(namespaceTables(nsForTable)[tableName] as StorageTable | undefined)") which
violates the repo policy; replace these with the approved helpers by wrapping
the value with blindCast<T, "Reason"> or castAs<T> as appropriate (for nullable
cases use blindCast<StorageTable | undefined, "explain why cast is safe">(...)
or castAs<StorageTable | undefined>(...)). Search for similar bare casts in the
same file (the other occurrences that cast to StorageTable or related types) and
update each to use blindCast with a clear reason string or castAs to preserve
intent and traceability; keep the original runtime value and only change the
cast wrapper around namespaceTables(nsForTable)[tableName], the other cast
sites, and any comparable expressions.
In
`@packages/3-targets/3-targets/sqlite/src/core/migrations/planner-strategies.ts`:
- Around line 65-68: The code in tableAt uses a bare TypeScript cast
"(namespaceTables(ns)[tableName] as StorageTable | undefined)"; replace that
with the project's safe caster (blindCast or castAs) to satisfy the cast rule:
retrieve the value via namespaceTables(ns)[tableName] and wrap it with
blindCast(...) or castAs<StorageTable | undefined>(...) (depending on which
utility is used elsewhere) before returning, keeping the same conditional
structure around storage.namespaces[namespaceId] and preserving the StorageTable
| undefined signature.
In `@packages/3-targets/3-targets/sqlite/src/core/sqlite-unbound-database.ts`:
- Around line 137-140: The fast-path returns SqliteUnboundDatabase.instance
based solely on tableCount and therefore silently accepts inputs that contain
unknown kinds (e.g. entries['bogus']) when there are zero tables; change the
guard to ensure the fast-path only triggers when input.entries contains no keys
other than 'table' (or when entries has exactly 'table' key), i.e. inspect
Object.keys(input.entries) and verify all keys are either 'table' or none before
returning SqliteUnboundDatabase.instance (use the existing variables tableKind,
tableCount, input.entries, SqliteUnboundDatabase.instance and castAs to
implement the check).
---
Outside diff comments:
In
`@packages/2-mongo-family/9-family/src/core/ir/mongo-contract-serializer-base.ts`:
- Around line 127-140: The hydration currently rebuilds nsEnvelope.entries with
only a collection key, discarding any other entry kinds; update the logic in
mongo-contract-serializer-base (the block using namespaceCollections,
rawCollections, hydratedCollections and returning { ...nsEnvelope, entries: {
collection: hydratedCollections } }) to merge the hydrated collection map into
the existing nsEnvelope.entries object instead of replacing it—e.g., compute
hydratedCollections as you do and then set entries = { ...nsEnvelope.entries,
collection: hydratedCollections } so non-collection entry kinds are preserved;
ensure you still convert raw items to MongoCollection (using
MongoCollectionInput) as before.
In `@packages/2-sql/5-runtime/src/codecs/validation.ts`:
- Around line 24-29: The current extractCodecIdsFromColumns implementation
builds keys as `${tableName}.${columnName}` which allows collisions across
different namespaces; update it to include the namespace identifier (e.g.,
`${namespaceName}.${tableName}.${columnName}` or similar) when creating the key
so each column is uniquely keyed per namespace, ensuring codecIds.set uses a
namespace-qualified key and prevents silent overwrites in functions that iterate
contract.storage.namespaces and namespaceTables.
In `@test/integration/test/cli.emit-cli-process.e2e.test.ts`:
- Around line 196-217: The test currently uses conditional guards that let it
silently pass if the tables or columns are missing; change that to hard
assertions: replace the if-checks around userTable and originalUserTable with
explicit expects (e.g., expect(userTable).toBeDefined() and
expect(originalUserTable).toBeDefined()) and likewise assert columns and
originalColumns exist (expect(columns).toBeDefined(),
expect(originalColumns).toBeDefined()) before comparing codecId/nativeType
values so the test fails if anything is absent; keep the subsequent compares of
columns['id'] and columns['email'] as-is.
🪄 Autofix (Beta)
Fix all unresolved CodeRabbit comments on this PR:
- Push a commit to this branch (recommended)
- Create a new PR with the fixes
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yml
Review profile: CHILL
Plan: Pro
Run ID: 411c5c57-eb4a-4eb1-9a63-1dbd7b3cdef5
📒 Files selected for processing (116)
docs/architecture docs/adrs/ADR 221 - Contract IR two planes with uniform entity coordinate and pack-contributed entity kinds.mddocs/architecture docs/subsystems/1. Data Contract.mddocs/architecture docs/subsystems/2. Contract Emitter & Types.mddocs/architecture docs/subsystems/5. Adapters & Targets.mddocs/reference/typescript-patterns.mdexamples/prisma-next-demo/migrations/app/20260422T0748_migration/migration.tsexamples/prisma-next-demo/test/migration-integrity.test.tsexamples/retail-store/migrations/app/20260513T0505_initial/migration.tsexamples/retail-store/migrations/app/20260513T0508_backfill_product_status/migration.tspackages/2-mongo-family/1-foundation/mongo-contract/src/contract-types.tspackages/2-mongo-family/1-foundation/mongo-contract/src/exports/index.tspackages/2-mongo-family/1-foundation/mongo-contract/src/ir/build-mongo-namespace.tspackages/2-mongo-family/1-foundation/mongo-contract/src/ir/mongo-storage.tspackages/2-mongo-family/1-foundation/mongo-contract/src/ir/mongo-unbound-namespace.tspackages/2-mongo-family/1-foundation/mongo-contract/src/validate-storage.tspackages/2-mongo-family/1-foundation/mongo-contract/test/element-coordinates.test.tspackages/2-mongo-family/1-foundation/mongo-contract/test/mongo-storage.test.tspackages/2-mongo-family/2-authoring/contract-ts/test/contract-builder.control-policy.test.tspackages/2-mongo-family/2-authoring/contract-ts/test/contract-builder.dsl.test.tspackages/2-mongo-family/2-authoring/contract-ts/test/contract-builder.polymorphism.test.tspackages/2-mongo-family/3-tooling/emitter/src/index.tspackages/2-mongo-family/9-family/src/core/contract-to-schema.tspackages/2-mongo-family/9-family/src/core/ir/mongo-contract-serializer-base.tspackages/2-mongo-family/9-family/src/core/ir/mongo-schema-verifier-base.tspackages/2-mongo-family/9-family/src/core/schema-verify/verify-mongo-schema.tspackages/2-sql/1-core/contract/src/exports/types.tspackages/2-sql/1-core/contract/src/index-type-validation.tspackages/2-sql/1-core/contract/src/ir/build-sql-namespace.tspackages/2-sql/1-core/contract/src/ir/sql-storage.tspackages/2-sql/1-core/contract/src/ir/sql-unbound-namespace.tspackages/2-sql/1-core/contract/src/resolve-storage-table.tspackages/2-sql/1-core/contract/src/types.tspackages/2-sql/1-core/contract/src/validators.tspackages/2-sql/1-core/contract/test/build-sql-namespace-map.test.tspackages/2-sql/1-core/contract/test/namespace-entry-registry.test.tspackages/2-sql/1-core/contract/test/sql-namespace-entries.test.tspackages/2-sql/1-core/contract/test/storage-value-set.test.tspackages/2-sql/2-authoring/contract-psl/test/interpreter.enum2.test.tspackages/2-sql/2-authoring/contract-psl/test/interpreter.namespaces.test.tspackages/2-sql/2-authoring/contract-psl/test/interpreter.polymorphism.test.tspackages/2-sql/2-authoring/contract-psl/test/interpreter.test.tspackages/2-sql/2-authoring/contract-psl/test/psl-ts-namespace-parity.test.tspackages/2-sql/2-authoring/contract-psl/test/ts-psl-parity.test.tspackages/2-sql/2-authoring/contract-psl/test/unbound-tables.tspackages/2-sql/2-authoring/contract-ts/test/check-constraint.authoring.test.tspackages/2-sql/2-authoring/contract-ts/test/contract-builder.cross-namespace-same-table.test.tspackages/2-sql/2-authoring/contract-ts/test/contract-builder.namespaces.test.tspackages/2-sql/2-authoring/contract-ts/test/contract-builder.per-model-namespace.test.tspackages/2-sql/2-authoring/contract-ts/test/contract.integration.test.tspackages/2-sql/2-authoring/contract-ts/test/contract.logic.test.tspackages/2-sql/2-authoring/contract-ts/test/cross-space-relation.test.tspackages/2-sql/2-authoring/contract-ts/test/enum-type.authoring.test.tspackages/2-sql/2-authoring/contract-ts/test/enum-type.codec-encoding.test.tspackages/2-sql/2-authoring/contract-ts/test/unbound-tables.tspackages/2-sql/3-tooling/emitter/src/index.tspackages/2-sql/3-tooling/emitter/test/emitter-hook.structure.test.tspackages/2-sql/4-lanes/sql-builder/src/runtime/resolve-table.tspackages/2-sql/4-lanes/sql-builder/src/types/db.tspackages/2-sql/5-runtime/src/codecs/validation.tspackages/2-sql/5-runtime/src/sql-context.tspackages/2-sql/9-family/src/core/control-instance.tspackages/2-sql/9-family/src/core/ir/sql-contract-serializer-base.tspackages/2-sql/9-family/src/core/migrations/contract-to-schema-ir.tspackages/2-sql/9-family/src/core/migrations/field-event-planner.tspackages/2-sql/9-family/src/core/schema-verify/verify-sql-schema.tspackages/2-sql/9-family/test/namespace-hydration-registry.test.tspackages/2-sql/9-family/test/value-set-roundtrip.test.tspackages/3-extensions/pgvector/test/descriptor.test.tspackages/3-extensions/postgres/test/psl-namespace-qualifier-routing.test.tspackages/3-extensions/sql-orm-client/src/collection-contract.tspackages/3-extensions/sql-orm-client/test/mutation-executor.test.tspackages/3-extensions/sql-orm-client/test/unbound-tables.tspackages/3-extensions/supabase/test/contract-handles.test.tspackages/3-mongo-target/1-mongo-target/src/core/mongo-target-contract-serializer.tspackages/3-mongo-target/1-mongo-target/src/core/mongo-target-database.tspackages/3-mongo-target/1-mongo-target/test/mongo-target-contract-serializer.test.tspackages/3-mongo-target/1-mongo-target/test/mongo-target-database-entries.test.tspackages/3-mongo-target/1-mongo-target/test/mongo-target-database.test.tspackages/3-targets/3-targets/postgres/src/core/migrations/control-policy.tspackages/3-targets/3-targets/postgres/src/core/migrations/issue-planner.tspackages/3-targets/3-targets/postgres/src/core/migrations/planner-strategies.tspackages/3-targets/3-targets/postgres/src/core/postgres-contract-serializer.tspackages/3-targets/3-targets/postgres/src/core/postgres-schema.tspackages/3-targets/3-targets/postgres/test/element-coordinates.test.tspackages/3-targets/3-targets/postgres/test/postgres-contract-serializer.test.tspackages/3-targets/3-targets/postgres/test/postgres-schema.test.tspackages/3-targets/3-targets/sqlite/src/core/migrations/planner-strategies.tspackages/3-targets/3-targets/sqlite/src/core/sqlite-unbound-database.tspackages/3-targets/3-targets/sqlite/test/element-coordinates.test.tspackages/3-targets/3-targets/sqlite/test/sqlite-contract-serializer-hydration.test.tspackages/3-targets/3-targets/sqlite/test/sqlite-contract-serializer.test.tspackages/3-targets/3-targets/sqlite/test/sqlite-unbound-database.test.tspackages/3-targets/6-adapters/postgres/src/core/sql-renderer.tspackages/3-targets/6-adapters/postgres/test/adapter.test.tsskills/extension-author/prisma-next-extension-upgrade/upgrades/0.13-to-0.14/instructions.mdskills/upgrade/prisma-next-upgrade/upgrades/0.13-to-0.14/instructions.mdtest/integration/test/authoring/side-by-side-contracts.test.tstest/integration/test/cli.emit-cli-process.e2e.test.tstest/integration/test/contract-space-fixture-mongo/descriptor.test.tstest/integration/test/contract-space-fixture/descriptor.test.tstest/integration/test/cross-package/middleware-cache.test.tstest/integration/test/family.schema-verify.basic.integration.test.tstest/integration/test/family.schema-verify.dependencies.integration.test.tstest/integration/test/family.schema-verify.helpers.tstest/integration/test/family.schema-verify.mismatches.integration.test.tstest/integration/test/family.schema-verify.types.test.tstest/integration/test/family.sign-database.test.tstest/integration/test/family.verify-database.basic.test.tstest/integration/test/family.verify-database.errors.test.tstest/integration/test/mongo/migration-psl-authoring.test.tstest/integration/test/namespaced-accessors-e2e.integration.test.tstest/integration/test/referential-actions.integration.test.tstest/integration/test/rewriting-middleware.integration.test.tstest/integration/test/runtime.verify-marker.missing-table.integration.test.tstest/integration/test/sql-builder/raw-sql.integration.test.tstest/integration/test/utils/cli-test-helpers.ts
entries dictionary (ADR 224/225)entries becomes an open, kind-keyed dictionary (ADR 224/225)
wmadden
left a comment
There was a problem hiding this comment.
What is this namespaceCollections(namespace) that's now everywhere?
Decision: a storage namespace stores its entities in one open dictionary — keyed by entity kind, then by entity name — and that path is the only way the framework addresses, validates, and hydrates them. This PR makes the runtime types and the validation/hydration machinery match that model (ADR 224/225). Nothing persisted changes: the wire format was already this shape, byte for byte.
Here is a namespace exactly as it sits in a committed
contract.jsontoday (unchanged by this PR):Every entity has a coordinate —
(plane, namespaceId, entityKind, entityName)— and one expression resolves any coordinate, for any entity kind, including kinds a target or extension pack contributes that the framework has never heard of:The problem
The persisted JSON was already open, but the runtime types were not. Each namespace class declared a closed object with one named field per kind it knew about:
A closed type forces every consumer to know every kind. The validator hardcoded
table?/type?/valueSet?schema fields; the postgres serializer hydrated thetypemap through a lookup keyed by the node tag'postgres-enum'; generic code that received a coordinate had to switch on the kind to pick a property. Adding a new entity kind (the RLS branch needs policies and roles) meant editing framework and family code — or smuggling the kind past the closed types, which is what that branch currently does.The change
The entity kind is the
entrieskey —table,type,valueSet,collection— exactly the strings already persisted. Everything dispatches on that one string.Open types that keep typed property access.
entriesis typed as the open dictionary intersected with its known kinds as optional keys:Unknown kinds remain valid (walkers iterate
Object.entriesas before), butns.entries.tableis ordinary typed property access — no helper layer, no per-call-site casts. Class instances additionally expose non-enumerable per-kind getters (schema.type,db.collection), soJSON.stringifyemits onlyid+entries. Repo-wide there are exactly two read styles: generic walkers useentries[kind][name]; typed code uses property access or the getters. ~50 production and ~190 test call sites moved.Construction is permissive-carry; the JSON boundary fails closed. This split is the heart of the open model, so be explicit about where each rule applies:
table,collection, …) into IR instances and freezes-and-carries any other kind's map untouched. It does not enforce a closed kind list. This is required by the open model: a pack-contributed kind (an RLS policy, a Postgres role) must pass throughbuildSqlNamespace/buildMongoNamespacewithout the family layer knowing its name — if construction threw on unknown kinds, pack kinds would be un-authorable, which is the closed-list behavior this PR exists to remove. The carry tests that assert a synthetic unknown kind survives construction (frozen, present inJSON.stringify, yielded byelementCoordinates) are pinning this promise on purpose.build*call.Construction also accepts input literals only — the
Instance | Inputunions and theirv instanceof X ? v : new X(v)normalization are gone (hydration constructs from validated JSON; authoring passes literals; the one caller that fed constructed instances was migrated).Validation dispatches through one kind→schema registry. This is the fail-closed boundary above. Validation walks
Object.entries(entries)and validates each inner map against the schema registered for that kind. The SQL core registerstableandvalueSetinto the same registry the postgres pack registerstypeinto — one tier, no privileged built-in fallback — and the postgres pack ownsPostgresEnumTypeSchemaoutright, so the family layer contains zero target-kind knowledge. A kind nobody registered fails validation with an error naming the kind and namespace id. Hydration is also kind-dispatched and fail-closed (thehydrateEntriesKindhook, which a target overrides per kind), and namespace construction carries unknown kinds and builds the kinds it owns — but both of those still use per-kind code (ahydrateEntriesKindhook and anif (kind === …)construction switch) rather than the validation registry. Unifying construction and hydration onto one shared kind→factory registry is the explicit follow-up TML-2890; this PR delivers the registry on the validation path only.One canonical lookup.
entityAt(storage, coordinate)lives besideelementCoordinatesin the framework; the hand-rolled two-step lookups (emitter FK validation and siblings) are gone.Docs follow the code, and one ADR bug is fixed on the way: ADR 221 §115 stated the cross-plane reference invariant backwards. The correct direction — a domain entity may reference a storage entity, never the reverse, because the migration planner/runner must consume the storage plane in isolation — already misled one project design; the parenthetical now matches reality.
One breaking change for downstream code
The family-generic
SqlContractSerializerno longer knows the postgrestypekind (per ADR 225, the family carries no target knowledge), so it rejects postgres contracts with a clear error naming the kind. The fix is one line, and contract deserialization is now properly generic — no cast:SQLite and table-only contracts are unaffected. Upgrade instructions are recorded via the repo's upgrade-instructions process; the examples in this PR show the migration. The
as Contractcasts are swept from the demo, retail-store, and mongo-demo apps (three sites inmulti-extension-monorepoare a recorded follow-up).What deliberately does not change
storageHashis content-addressed over the entries subtree, so the persisted shape — keys, key order, presence semantics — is preserved exactly.pnpm fixtures:checkpasses with zero committed-artifact diffs (and earned its keep: it caught the one hash-drift regression introduced mid-review and forced the correct fix).kindtags, including the two that don't match their entries key ('postgres-enum'undertype,'mongo-collection'undercollection). They sit inside hash-covered node bodies, and nothing dispatches on them anymore — see Alternatives.elementCoordinates— the framework's coordinate walker already readentriesstructurally; it is the consumer this refactor had to keep working unchanged, and it did.Verification
All acceptance criteria carry committed tests: exact-shape serialization per concretion (getters absent from JSON), deep-freeze, unknown-kind rejection at construction/validation/hydration, round-trip unchanged, and a coordinate-resolution test asserting every
elementCoordinatestuple resolves throughentries[entityKind][entityName]for representative postgres, sqlite, and mongo contracts. Local gates: build, typecheck (138/138), lint (79/79),lint:deps,fixtures:check(clean tree, zero contract diffs); cast ratchet net negative vs merge-base. Integration suites run on this PR's CI.Known follow-ups (tracked, deliberately not in this PR)
Review surfaced three refinements that are real but are each a distinct, higher-blast-radius change; bundling them into this already-large branch is what produced the one regression this PR hit, so they ship as focused PRs:
if (kind === …)switches in the 8 construction/hydration files, so dispatch is uniform everywhere, not just in validation. (RLS adds itspolicyconstruction as a registration rather than a switch branch once this lands — it is not blocked on it.)SqlBoundNamespace/buildSqlNamespace/SqlNamespaceTablesInput; SQL namespaces become always-target concretions; supabase emitspostgres-schema. This is a wire-format change (committed contracts regenerate) and must land in isolation; the reverted item-Ginstanceofguard resolves here.Contract/Storageaccessor for collections/tables by name, so migrations stop reaching throughnamespaces.__unbound__.entries.collection.Out of scope (deliberate)
RLS (its branch rebases onto this and deletes its workarounds); the migration planner;
ValueSetRef(settled in #805); the domain plane's flatmodels/valueObjectsshape and the namespace-kind serializer strings (recorded follow-ups); the ADR 225/126 rewrite batch.Alternatives considered
namespaceTables()/namespaceValueSets()/namespaceCollections()to give typed reads over a fully-widenedentries. Rejected in review and deleted: the helpers were a parallel per-kind API duplicating the getters, and they existed only because the type had been over-widened — the intersection keeps the dictionary open while making plain property access type-safe.Instance | Inputconstruction unions. Also shipped early, also deleted: theinstanceof-normalization they force is unreadable and hides which paths actually carry what. One shape per path needs no normalization.'postgres-enum'→'type','mongo-collection'→'collection') so the kind is literally one string everywhere. Rejected: the tags are persisted inside hash-covered node bodies, so the rename would churn every committed contract andstorageHash— and the postgres-enum machinery is deleted by the enums cutover (TML-2853) regardless. New kinds (e.g.valueSet, post-TML-2882: transitional enum2 block makes the new enum PSL-authorable #805) use one string across coordinate, entries key, node tag, and registration from day one.entrySlotNameapproach the RLS branch had to invent). Rejected: both are the same translation table in disguise; ADR 224 explicitly rejects boundary reshaping, and the open dictionary makes the mapping unnecessary.Linear: TML-2887