Repository navigation
TML-2890: one descriptor per storage entity kind (replaces three parallel registries) - #826
Conversation
Add `createSqlEntryConstructionRegistry` + `dispatchEntriesToRegistry` in `@prisma-next/sql-contract/entry-construction-registry`. Mirrors the schema registry pattern: core registers `table` and `valueSet`, pack factories extend it. Refactor the construction switches in `build-sql-namespace.ts`, `postgres-schema.ts`, and `sqlite-unbound-database.ts` to dispatch via the registry. SQLite registers only `table` (valueSet stays carried raw per spec). Fixtures byte-clean; all construction tests pass. Co-Authored-By: Claude Fable 5 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
Replace the `hydrateEntriesKind` if/else switches in `SqlContractSerializerBase` and `PostgresContractSerializer` with registry dispatch. The base adds a 3rd constructor parameter `packEntryFactories` composed into `createSqlEntryConstructionRegistry`; the base's `hydrateEntriesKind` dispatches via that registry, returning `undefined` (fail-closed) for unregistered kinds. Postgres removes its `hydrateEntriesKind` override and instead passes the enum factory as `packEntryFactories['type']` to the base constructor. Fixtures byte-clean; 314 postgres tests pass. Co-Authored-By: Claude Fable 5 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
Add `entry-construction-registry` to `@prisma-next/mongo-contract`:
`createMongoEntryConstructionRegistry`, `dispatchMongoEntriesToRegistryCarrying`
(carry-on-unknown for construction), `dispatchMongoEntriesToRegistry`
(throw-on-unknown for hydration).
Refactor `MongoBoundNamespace`, `MongoTargetDatabase`, and
`MongoContractSerializerBase` to dispatch via the registry rather than
per-kind `if (kind === 'collection')` switches. Construction sites seed
`collection: {}` before dispatching so the key is always present (matches
prior behavior). Hydration site (serializer base) uses the throw variant —
preserving existing fail-closed semantics.
Wire-clean: `fixtures:check` exits 0.
Co-Authored-By: Claude Fable 5 <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Add `isPlainRecord` (strict prototype check) to framework-components `ir/storage.ts` and export it from the `ir` path. Replace the loose private `isRecord` in `entityAt` with this shared guard. Remove the duplicate `isPlainRecord` in `validators.ts` and import the shared one instead. In `createNamespaceEntrySchema`, precompute a `knownKinds` Set from the registry so the membership check is `Set.has()` and the schema lookup (post-guard) is non-nullable. Co-Authored-By: Claude Fable 5 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…rySchema Biome forbids bare `!` non-null assertions. Replace `registry.get(key)!` (safe after the `knownKinds.has(key)` guard) with `castAs<Type<unknown>>(...)`. Co-Authored-By: Claude Fable 5 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
📝 WalkthroughWalkthroughIntroduces ChangesEntity Kind Descriptor Registry
Sequence Diagram(s)sequenceDiagram
participant Caller
participant SerializerBase as SqlContractSerializerBase / MongoContractSerializerBase
participant hydrateNamespaceEntities
participant composeEntityKinds as composeSqlEntityKinds / composeMongoEntityKinds
participant Descriptor as EntityKindDescriptor
Caller->>SerializerBase: hydrate(namespace, id)
SerializerBase->>composeEntityKinds: lookup entryKinds map
composeEntityKinds-->>SerializerBase: ReadonlyMap<kind, Descriptor>
SerializerBase->>hydrateNamespaceEntities: hydrateNamespaceEntities(entriesInput, entryKinds, fail/carry, id)
loop for each entries[kind]
hydrateNamespaceEntities->>Descriptor: descriptor.construct(input) per inner entry
Descriptor-->>hydrateNamespaceEntities: constructed node
end
hydrateNamespaceEntities-->>SerializerBase: frozen Record<kind, Record<id, Node>>
SerializerBase-->>Caller: hydrated namespace entries
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
@prisma-next/extension-author-tools
@prisma-next/mongo-runtime
@prisma-next/family-mongo
@prisma-next/sql-runtime
@prisma-next/family-sql
@prisma-next/extension-arktype-json
@prisma-next/middleware-cache
@prisma-next/mongo
@prisma-next/extension-paradedb
@prisma-next/extension-pgvector
@prisma-next/extension-postgis
@prisma-next/postgres
@prisma-next/sql-orm-client
@prisma-next/sqlite
@prisma-next/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: 3
🧹 Nitpick comments (1)
packages/2-mongo-family/1-foundation/mongo-contract/test/entry-construction-registry.test.ts (1)
2-5: ⚡ Quick winAdd direct tests for
dispatchMongoEntriesToRegistryCarryingcarry/freeze semantics.This suite validates fail-closed dispatch, but it doesn’t directly cover the open-world dispatcher (
dispatchMongoEntriesToRegistryCarrying) that constructors now rely on. Adding one or two focused assertions here will lock in unknown-kind carry-through and freezing behavior.✅ Suggested test additions
import { createMongoEntryConstructionRegistry, dispatchMongoEntriesToRegistry, + dispatchMongoEntriesToRegistryCarrying, } from '../src/entry-construction-registry'; @@ describe('dispatchMongoEntriesToRegistry', () => { @@ }); + +describe('dispatchMongoEntriesToRegistryCarrying', () => { + it('carries unknown kinds unchanged and freezes the map', () => { + const reg = createMongoEntryConstructionRegistry(); + const result = dispatchMongoEntriesToRegistryCarrying( + { collection: {}, customKind: { x: { a: 1 } } }, + reg, + ); + expect(result.customKind).toEqual({ x: { a: 1 } }); + expect(Object.isFrozen(result.customKind!)).toBe(true); + }); +});Also applies to: 38-57
🤖 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/1-foundation/mongo-contract/test/entry-construction-registry.test.ts` around lines 2 - 5, Add direct test cases for the `dispatchMongoEntriesToRegistryCarrying` function to validate its carry/freeze semantics. Currently the test suite only covers fail-closed dispatch behavior but lacks focused assertions on the open-world dispatcher. Create one or two focused test assertions that verify unknown-kind entries are properly carried through and that freezing behavior is correctly applied when dispatching entries through the registry carrying dispatcher.
🤖 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/entry-construction-registry.ts`:
- Around line 45-56: Plain object literals like {} used for result and built
dictionaries are vulnerable to prototype pollution when storing dynamically
provided keys such as __proto__. Replace the initialization of result with
Object.create(null) instead of {}, and replace the initialization of built with
Object.create(null) instead of {}. The same fix must also be applied to the
similar dispatch function at lines 71-80 in the same file where comparable
dynamic key assignments occur, replacing those plain {} initializations with
Object.create(null) as well.
In
`@packages/2-mongo-family/9-family/src/core/ir/mongo-contract-serializer-base.ts`:
- Around line 136-139: The bare `as` cast on nsEnvelope.entries in the
dispatchMongoEntriesToRegistry call violates production code casting rules.
Replace this cast with blindCast from `@prisma-next/utils/casts`, ensuring you
provide a descriptive reason string explaining why the cast to
Readonly<Record<string, Readonly<Record<string, unknown>>>> is necessary. Ensure
blindCast is properly imported from `@prisma-next/utils/casts` if not already
present.
In `@packages/2-sql/1-core/contract/src/entry-construction-registry.ts`:
- Around line 58-64: The code at line 58 and line 63 creates plain objects using
{} that accumulate values from untrusted keys, which enables prototype pollution
attacks through keys like __proto__. Replace both the result variable
initialization at line 58 and the built variable initialization at line 63 with
null-prototype objects created using Object.create(null) instead of object
literals, ensuring that dynamically assigned keys cannot mutate the object
prototype chain.
---
Nitpick comments:
In
`@packages/2-mongo-family/1-foundation/mongo-contract/test/entry-construction-registry.test.ts`:
- Around line 2-5: Add direct test cases for the
`dispatchMongoEntriesToRegistryCarrying` function to validate its carry/freeze
semantics. Currently the test suite only covers fail-closed dispatch behavior
but lacks focused assertions on the open-world dispatcher. Create one or two
focused test assertions that verify unknown-kind entries are properly carried
through and that freezing behavior is correctly applied when dispatching entries
through the registry carrying dispatcher.
🪄 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: ff564ad6-ff07-4d9a-80a6-ba460ad0f737
📒 Files selected for processing (21)
packages/1-framework/1-core/framework-components/src/exports/ir.tspackages/1-framework/1-core/framework-components/src/ir/storage.tspackages/2-mongo-family/1-foundation/mongo-contract/package.jsonpackages/2-mongo-family/1-foundation/mongo-contract/src/entry-construction-registry.tspackages/2-mongo-family/1-foundation/mongo-contract/src/exports/entry-construction-registry.tspackages/2-mongo-family/1-foundation/mongo-contract/src/ir/build-mongo-namespace.tspackages/2-mongo-family/1-foundation/mongo-contract/test/entry-construction-registry.test.tspackages/2-mongo-family/1-foundation/mongo-contract/tsdown.config.tspackages/2-mongo-family/9-family/src/core/ir/mongo-contract-serializer-base.tspackages/2-sql/1-core/contract/package.jsonpackages/2-sql/1-core/contract/src/entry-construction-registry.tspackages/2-sql/1-core/contract/src/exports/entry-construction-registry.tspackages/2-sql/1-core/contract/src/ir/build-sql-namespace.tspackages/2-sql/1-core/contract/src/validators.tspackages/2-sql/1-core/contract/test/entry-construction-registry.test.tspackages/2-sql/1-core/contract/tsdown.config.tspackages/2-sql/9-family/src/core/ir/sql-contract-serializer-base.tspackages/3-mongo-target/1-mongo-target/src/core/mongo-target-database.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/sqlite/src/core/sqlite-unbound-database.ts
…izer-base The nsEnvelope.entries cast was flagged by the no-bare-cast ratchet. Replaced with blindCast, citing that the contract schema validates the shape before hydration reaches this point. Co-Authored-By: Claude Fable 5 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
wmadden
left a comment
There was a problem hiding this comment.
For such a small PR, this is a really unsatisfactory result.
… primitives - EntityKindDescriptor<Input,Node> + AnyEntityKindDescriptor + constructEntries in framework-components/src/ir/entity-kind.ts; exported via exports/ir.ts - Canonical isPlainRecord with strict proto check in @prisma-next/contract; new ./is-plain-record export + tsdown entry - framework-components storage.ts re-exports from canonical (no local def); contract hashing.ts + canonicalization-storage-sort.ts import local canonical Co-Authored-By: Claude Fable 5 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…tyKinds Replaces the SQL entry-construction registry and schema registry with the EntityKindDescriptor pattern from Phase 1: - entity-kinds.ts: tableEntityKind, valueSetEntityKind, composeSqlEntityKinds() (one collision throw, package.json + tsdown export added) - validators.ts: delete createSqlEntrySchemaRegistry; add schemaViewOf(kinds) derived view; createNamespaceEntrySchema/createSqlStorageSchema/createSqlContractSchema now take ReadonlyMap<string,AnyEntityKindDescriptor>; DEFAULT_SQL_KINDS inlines stubs to break the entity-kinds→validators→build-sql-namespace→entity-kinds cycle - build-sql-namespace.ts: delete module-level CORE_REGISTRY singleton; call composeSqlEntityKinds() per-construction (lazy — safe across the cycle) - sql-contract-serializer-base.ts: one packEntityKinds param; delete local isPlainRecord (import canonical from contract); delete hydrateEntriesKind; constructEntries(...,'fail') for hydration - Tests: entry-construction-registry.test.ts → entity-kinds.test.ts; namespace-entry-registry, check-constraint, control-field, validators tests updated to composeSqlEntityKinds() Wire-clean: no contract.json/contract.d.ts changes. 251 sql-contract tests + 379 family-sql tests pass. Co-Authored-By: Claude Fable 5 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…inds Postgres: - postgres-schema.ts: add typeEntityKind descriptor (PostgresEnumTypeSchema, new PostgresEnumType); replace typeFactory + POSTGRES_REGISTRY with POSTGRES_KINDS = composeSqlEntityKinds([typeEntityKind]); constructEntries carry - postgres-contract-serializer.ts: drop EntryFactory/POSTGRES_VALIDATOR_REGISTRY; pass [typeEntityKind] as packEntityKinds to super() SQLite: - sqlite-unbound-database.ts: replace _fullCoreRegistry filter hack with explicit SQLITE_KINDS = new Map([['table', tableEntityKind]]); constructEntries carry Wire-clean; postgres (314) + sqlite (129) + adapter-postgres (647) + adapter-sqlite (207) tests pass. Co-Authored-By: Claude Fable 5 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…tyKinds
- entity-kinds.ts: collectionEntityKind (StorageCollectionSchema, new MongoCollection);
composeMongoEntityKinds(packKinds=[]) with one collision throw; package.json +
tsdown entry added; entity-kinds.test.ts covers construct, compose, constructEntries
carry/fail behavior
- build-mongo-namespace.ts: inject composeMongoEntityKinds(), constructEntries('carry'),
preserve always-present collection key
- mongo-contract-serializer-base.ts: constructEntries('fail') replaces
dispatchMongoEntriesToRegistry; one packEntityKinds[] ctor param
- mongo-target-database.ts: inject composeMongoEntityKinds(), constructEntries('carry')
- param-ref-mutator.ts: redirect isPlainRecord to canonical @prisma-next/contract/
is-plain-record; remove local loose definition
- Delete mongo + sql entry-construction-registry.ts, exports/, tests — no external
consumers remain; all names (EntryFactory, createMongoEntryConstructionRegistry,
dispatchMongoEntriesToRegistry, createSqlEntryConstructionRegistry,
dispatchEntriesToRegistry) are gone
Wire-clean: no contract.json / contract.d.ts changes.
128 mongo-contract + 173 mongo-runtime + 420 target-mongo tests pass.
Co-Authored-By: Claude Fable 5 <[email protected]>
Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Add a code-review calibration smell: on any blindCast(), the reviewer asks (1) does the reason string name the invariant that makes the cast sound, and (2) is the cast necessary at all or can the type system carry the fact. Surfaced by the TML-2890 PR #826 review. Co-Authored-By: Claude Fable 5 <[email protected]> Signed-off-by: willbot <[email protected]>
… parameter `schema: Type<Input>` caused concrete descriptors (e.g. `EntityKindDescriptor<StorageTableInput, StorageTable>`) to fail assignability to `AnyEntityKindDescriptor` (= `EntityKindDescriptor<never, unknown>`) because arktype's `Type<T>` is invariant via `~standard`, making `Type<StorageTableInput>` incompatible with `Type<never>`. Fix: change `schema` to `Type<unknown>` (fixed, not parameterised). Both the concrete and the erased type now carry the same `schema` field type, so no per-descriptor cast is needed to assemble the descriptor map. Co-Authored-By: Claude Fable 5 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
The SQL entity-kinds.ts imported StorageTableSchema and StorageValueSetSchema from validators.ts. For validators.ts to import composeSqlEntityKinds from entity-kinds.ts (replacing the inline stub DEFAULT_SQL_KINDS), that would create a cycle. Fix: extract the entry-level schemas and all their sub-schemas (column, primary key, foreign key, etc.) into a new non-cyclic module src/ir/storage-entry-schemas.ts. Import direction is now: entity-kinds.ts → ir/storage-entry-schemas.ts validators.ts → entity-kinds.ts (for composeSqlEntityKinds) validators.ts → ir/storage-entry-schemas.ts (re-exports) No cycle. validators.ts re-exports the moved schemas so all existing consumers of @prisma-next/sql-contract keep working unchanged. Also removes all per-descriptor castAs calls from both SQL and Mongo entity-kinds.ts — after Bug A fix the schema field is Type<unknown> on the interface, so concrete Type<T> assigns without a cast. Co-Authored-By: Claude Fable 5 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 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-sql/9-family/src/core/ir/sql-contract-serializer-base.ts`:
- Around line 185-195: The code contains two bare `as` casts that violate the
repository's casting policy. Replace the bare `as` cast when assigning
entriesRaw to Record<string, unknown> (line 187) and the bare `as` cast when
assigning innerMap to Readonly<Record<string, unknown>> (line 195) with
`blindCast` from `@prisma-next/utils/casts`, providing an appropriate reason
string for each cast explaining why the type assertion is safe in that context.
🪄 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: 596b852c-8dff-45f3-bc2d-90210cfca76d
📒 Files selected for processing (37)
drive/code/README.mdpackages/1-framework/0-foundation/contract/package.jsonpackages/1-framework/0-foundation/contract/src/canonicalization-storage-sort.tspackages/1-framework/0-foundation/contract/src/exports/is-plain-record.tspackages/1-framework/0-foundation/contract/src/hashing.tspackages/1-framework/0-foundation/contract/src/is-plain-record.tspackages/1-framework/0-foundation/contract/tsdown.config.tspackages/1-framework/1-core/framework-components/src/exports/ir.tspackages/1-framework/1-core/framework-components/src/ir/entity-kind.tspackages/1-framework/1-core/framework-components/src/ir/storage.tspackages/1-framework/1-core/framework-components/test/entity-kind.test.tspackages/2-mongo-family/1-foundation/mongo-contract/package.jsonpackages/2-mongo-family/1-foundation/mongo-contract/src/contract-schema.tspackages/2-mongo-family/1-foundation/mongo-contract/src/entity-kinds.tspackages/2-mongo-family/1-foundation/mongo-contract/src/exports/entity-kinds.tspackages/2-mongo-family/1-foundation/mongo-contract/src/ir/build-mongo-namespace.tspackages/2-mongo-family/1-foundation/mongo-contract/test/entity-kinds.test.tspackages/2-mongo-family/1-foundation/mongo-contract/tsdown.config.tspackages/2-mongo-family/7-runtime/src/param-ref-mutator.tspackages/2-mongo-family/9-family/src/core/ir/mongo-contract-serializer-base.tspackages/2-sql/1-core/contract/package.jsonpackages/2-sql/1-core/contract/src/entity-kinds.tspackages/2-sql/1-core/contract/src/exports/entity-kinds.tspackages/2-sql/1-core/contract/src/ir/build-sql-namespace.tspackages/2-sql/1-core/contract/src/ir/storage-entry-schemas.tspackages/2-sql/1-core/contract/src/validators.tspackages/2-sql/1-core/contract/test/check-constraint.test.tspackages/2-sql/1-core/contract/test/control-field.test.tspackages/2-sql/1-core/contract/test/entity-kinds.test.tspackages/2-sql/1-core/contract/test/namespace-entry-registry.test.tspackages/2-sql/1-core/contract/test/validators.test.tspackages/2-sql/1-core/contract/tsdown.config.tspackages/2-sql/9-family/src/core/ir/sql-contract-serializer-base.tspackages/3-mongo-target/1-mongo-target/src/core/mongo-target-database.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/sqlite/src/core/sqlite-unbound-database.ts
✅ Files skipped from review due to trivial changes (3)
- packages/2-sql/1-core/contract/src/exports/entity-kinds.ts
- packages/2-mongo-family/1-foundation/mongo-contract/src/exports/entity-kinds.ts
- packages/1-framework/0-foundation/contract/src/canonicalization-storage-sort.ts
🚧 Files skipped from review as they are similar to previous changes (5)
- packages/2-sql/1-core/contract/package.json
- packages/2-mongo-family/1-foundation/mongo-contract/package.json
- packages/2-mongo-family/1-foundation/mongo-contract/tsdown.config.ts
- packages/1-framework/1-core/framework-components/src/ir/storage.ts
- packages/1-framework/1-core/framework-components/src/exports/ir.ts
Object.getPrototypeOf returns `any`; annotating the variable as `unknown` is sufficient — no cast needed. Co-Authored-By: Claude Fable 5 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…e per-kind casts to entries level - Rename `constructEntries` → `hydrateNamespaceEntities` across all 12 call sites - Remove module-scope composed maps (POSTGRES_KINDS, SQLITE_KINDS, MONGO_KINDS); compose per-call inside constructors - Replace per-kind blindCast extractions in constructors with a single cast on the whole dispatched result - Drop input-side blindCasts where the input type is directly assignable to the function parameter - Fix stale cast reason strings that referenced old constant names Co-Authored-By: Claude Fable 5 <[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/2-mongo-family/1-foundation/mongo-contract/src/ir/build-mongo-namespace.ts (1)
41-46: 💤 Low valueImprove
blindCastreason strings to name the type invariant.Per the
no-bare-castsrule, everyblindCast()reason string must name the invariant justifying why the cast is safe. The current reasons describe what the code does rather than why the type system cannot prove the narrowing:
- Line 41: The reason should explain why
hydrateNamespaceEntitiesoutput satisfiesMongoNamespaceEntries(e.g., "composeMongoEntityKinds registers collection → MongoCollection; other kinds are carried as-is per MongoNamespaceEntries' index signature").- Line 45: The reason should explain why
MongoNamespaceCollectionsInput.entriesis assignable toRecord<string, Readonly<Record<string, unknown>>>despite the type parameter difference.🤖 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/1-foundation/mongo-contract/src/ir/build-mongo-namespace.ts` around lines 41 - 46, The two blindCast reason strings in the buildMongoNamespace function do not adequately name the type invariants justifying why the casts are safe. Update the reason string in the outer blindCast (line 41) to explain why hydrateNamespaceEntities output satisfies MongoNamespaceEntries by referencing how composeMongoEntityKinds registers the collection kind and other kinds are preserved via the index signature. Update the reason string in the inner blindCast (line 45) to explain why MongoNamespaceCollectionsInput.entries is assignable to Record<string, Readonly<Record<string, unknown>>> despite any type parameter differences, rather than simply describing what the code does.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/2-mongo-family/1-foundation/mongo-contract/src/ir/build-mongo-namespace.ts`:
- Around line 41-46: The two blindCast reason strings in the buildMongoNamespace
function do not adequately name the type invariants justifying why the casts are
safe. Update the reason string in the outer blindCast (line 41) to explain why
hydrateNamespaceEntities output satisfies MongoNamespaceEntries by referencing
how composeMongoEntityKinds registers the collection kind and other kinds are
preserved via the index signature. Update the reason string in the inner
blindCast (line 45) to explain why MongoNamespaceCollectionsInput.entries is
assignable to Record<string, Readonly<Record<string, unknown>>> despite any type
parameter differences, rather than simply describing what the code does.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yml
Review profile: CHILL
Plan: Pro
Run ID: 1b3a0fe3-e94c-45d2-b586-028375891898
📒 Files selected for processing (13)
packages/1-framework/0-foundation/contract/src/is-plain-record.tspackages/1-framework/1-core/framework-components/src/exports/ir.tspackages/1-framework/1-core/framework-components/src/ir/entity-kind.tspackages/1-framework/1-core/framework-components/test/entity-kind.test.tspackages/2-mongo-family/1-foundation/mongo-contract/src/ir/build-mongo-namespace.tspackages/2-mongo-family/1-foundation/mongo-contract/test/entity-kinds.test.tspackages/2-mongo-family/9-family/src/core/ir/mongo-contract-serializer-base.tspackages/2-sql/1-core/contract/src/ir/build-sql-namespace.tspackages/2-sql/1-core/contract/test/entity-kinds.test.tspackages/2-sql/9-family/src/core/ir/sql-contract-serializer-base.tspackages/3-mongo-target/1-mongo-target/src/core/mongo-target-database.tspackages/3-targets/3-targets/postgres/src/core/postgres-schema.tspackages/3-targets/3-targets/sqlite/src/core/sqlite-unbound-database.ts
🚧 Files skipped from review as they are similar to previous changes (5)
- packages/1-framework/1-core/framework-components/test/entity-kind.test.ts
- packages/2-mongo-family/1-foundation/mongo-contract/test/entity-kinds.test.ts
- packages/1-framework/0-foundation/contract/src/is-plain-record.ts
- packages/3-targets/3-targets/postgres/src/core/postgres-schema.ts
- packages/2-sql/9-family/src/core/ir/sql-contract-serializer-base.ts
Merge origin/main tip 90d93bd (PR #816 Mongo migration DDL, PR #817 enum-as-domain-concept native machinery deletion) into tml-2890-uniform-kind-dispatch. Conflicts resolved: - validators.ts: took HEAD's version (main's changes were comment-only tweaks in lines HEAD had already deleted). - postgres-schema.ts: took main's version. HEAD's typeEntityKind referenced PostgresEnumType, which PR #817 deleted; retaining typeEntityKind would reference a non-existent type. - postgres-contract-serializer.ts: took main's version (no typeEntityKind import, plain super(storageTypesHydrators) call matching main). Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…ializer-base Two bare `as` casts in hydrateSqlNamespaceEntry used manual non-null/ object/non-array checks then cast. Replace both checks with isPlainRecord, which narrows to Record<string, unknown> making the cast unnecessary. Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…(drop manual per-kind casts) The merge resolution took main's PostgresSchema constructor, which uses a manual per-kind loop with two blindCasts (the exact smell TML-2890 removes) plus a bare `as` in the valueSet getter. Behaviorally correct but it dropped this branch's descriptor redesign. Re-apply the descriptor path: hydrateNamespaceEntities + composeSqlEntityKinds (no typeEntityKind — #817 deleted PostgresEnumType and the postgres `type` kind, so postgres now has only the SQL-family kinds table/valueSet). The constructor collapses to a single boundary blindCast; the getters become cast-free; the entries field narrows to SqlNamespaceEntries. Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…asts; kill stale registry vocabulary Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…hydrate in docs Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
Review round addressed — all threads resolved (0 open)Since the last review, every open thread (17 total) is replied-to with a commit citation and resolved. Summary of what changed: Merge with main (#816, #817). Rebased onto current main. #817 deleted Casts. The ~8 per-factory casts are gone — one documented boundary cast per concretion (open-dict hydrate output → the typed Naming. Duplicate-kind error no longer hardcodes Verification. Internal opus reviewer pass run; its must-fix list addressed. Gates green: Re-requesting review. |
…k slice status (#835) ## What & why Main's `projects/postgres-rls/` carried the **original M1–M5 layer-cut plan with nothing marked complete** — out of date. The project was re-cut on 2026-06-10 into four behaviour-named slices and has progressed substantially, but those doc updates were stuck behind #771's 85-commit code PR, so main never saw them. This brings the project tracking on main current, decoupled from the code PR. ## What changed (docs only) - **`plan.md`** → the current four-slice behaviour-cut (`select-policies-dependable`, `drift-handled-correctly`, `all-policy-types`, `typescript-authoring`), ported from #771. Plus two edits on top of #771's version: - Fixed the vestigial `## Slices / The five PRs below correspond to the five slices (M1–M5)` line that contradicted the re-cut. - Added an at-a-glance **Status:** marker per slice — Slice 1 🚧 in progress (PR #771; architecture + SELECT spine landed, remaining DoD items listed), Slices 2–4 ⬜ not started. - **`spec.md`** → the current, trimmed spec (the design-as-five-decisions version), ported from #771. - **`specs/design-rls-authoring-surface.md`**, **`specs/reconciliation-2026-06-08.md`** → added (the design docs the plan/spec link to; without them those links 404 on main). No code, no slice-execution artifacts (dispatches/, trace.jsonl stay with #771). ## Notes for the RLS owner - **One known staleness left as-is:** `spec.md` D1 still describes policies registering 'via the same `AuthoringContributions.entityTypes` mechanism `PostgresEnumType` already uses'. Since then #817 deleted `PostgresEnumType` and #826 (merged) added the `EntityKindDescriptor` seam for namespace `entries` kinds. I did **not** rewrite that design rationale — it's your call whether `policy` lands as a namespace-`entries` kind via `composeSqlEntityKinds([policyEntityKind])` or on the `storage.types` axis. Flagging so it gets reconciled when #771 next touches the spec. - **Pre-existing forward-ref:** `../cross-contract-refs/spec.md` resolves only once that sibling project merges — unchanged from main's previous plan, not introduced here. - When #771 merges, its copies of these files match this content (plus the two edits above), so the overlap is trivial. 🤖 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 4.8 <[email protected]>
After merging origin/main (#817 deleted PostgresEnumStorageEntry; #826 introduced the entity-kind seam), interpreter.ts had stale references and test files accessed entries.policy / entries.role directly instead of through the safe getters on PostgresSchema. - Add AuthoringEntityTypeDescriptor to the import type block - Remove the deleted PostgresEnumStorageEntry type and the second enumTypes param from createNamespace signatures - Switch test accesses of ns.entries.policy / ns.entries.role to the ns.policy / ns.role getters (which handle the optional type) Co-Authored-By: Claude Sonnet 4.6 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
…Namespace factory The path (entities lowered, no createNamespace) is NOT reachable post-#826: the only target that registers entity types (Postgres) also provides createNamespace. The guard is a forward-looking safety net for new targets that might register entityTypes without the matching factory. Co-Authored-By: Claude Sonnet 4.6 <[email protected]> Signed-off-by: willbot <[email protected]> Signed-off-by: Will Madden <[email protected]>
Decision: every storage entity kind —
table,valueSet, postgrestype, Mongocollection, the future RLSpolicy— is described by one descriptor that carries all of its behaviors: how it validates, how it constructs from input, how it hydrates from JSON. The framework reads that one descriptor everywhere it needs to act on a kind, so there is no per-kind branching anywhere. Pure refactor — zero wire change.At a glance
A kind, described once:
A target adds a kind the same way —
typeEntityKindin the postgres package,kind: 'type'— and composes it in:Everything that acts on entries — validation, namespace construction, deserialization — reads that descriptor set. One loop, no switch:
The problem
Before this PR, acting on an entity kind meant three separate places hardcoding the same kind list:
entriesbecomes an open, kind-keyed dictionary (ADR 224/225) #812).if (kind === 'table') new StorageTable(v) else if 'valueSet' … else carry, copied across the SQL and Mongo namespace classes.Three parallel string-keyed dispatchers for one concept. Adding a kind meant editing all three; the construction/hydration ones were type-erased
(unknown) => unknownfactories that needed a cast per kind. (An earlier round of this PR built construction as a fourth registry mirroring validation — see Alternatives for why that was the wrong shape and got reworked.)The change
One descriptor per kind.
EntityKindDescriptor<Input, Node>(framework-components) carrieskind,schema, andconstruct(input: Input): Node. Construction and hydration are the same operation — every IR constructor already accepts both the authoring-input and raw-JSON shapes — so one typedconstructserves both, and the per-kind duplication is gone.Type-safe, so the casts disappear.
constructis typed (Input → Node); the only cast in the whole mechanism is a single documented boundary cast inside the sharedconstructEntriesloop (theunknownentries value → the kind'sInput, sound because authoring passes that input type and hydration runs aftervalidateStorage). The descriptors and the composition are cast-free.schemaisType<unknown>rather thanType<Input>precisely so a kind whose wire shape can't be expressed as its input type (e.g.table, whosebigint/Datecolumn defaults aren't DSL-expressible) needs no declaration cast.One composition, one source of truth.
composeSqlEntityKinds/composeMongoEntityKindsbuild the descriptor set from family built-ins + pack contributions, with one collision throw (a pack can't shadow a core kind). Validation is now a view over that set, not a separate registry —createSqlEntrySchemaRegistryis deleted. No module-scoped registry singletons: each concretion composes its set at the seam (PostgresSchemaaddstype;SqliteDatabasegets a table-only set, which is how it keeps carryingvalueSetraw).Folded-in #812 review cleanups. The duplicate
isRecord/isPlainRecordguards collapse to one canonical strict guard in the foundation layer; the known-kind membership check is aSet.Changes
EntityKindDescriptor+ the sharedconstructEntries(entries, kinds, 'carry'|'fail')loop; canonicalisPlainRecord.tableEntityKind/valueSetEntityKind+composeSqlEntityKinds;validators.tsderives its schema view from the descriptor set;build-sql-namespace, the serializer base,PostgresSchema(typeEntityKind), andSqliteDatabaseall dispatch throughconstructEntries. The schemas moved out ofvalidators.tsso descriptors can own them without a cycle.collectionEntityKind+composeMongoEntityKinds; the namespace classes and serializer base dispatch throughconstructEntries; the per-targethydrateEntriesKindoverride hook is gone.Wire stability
Behavior-preserving refactor. Each concretion constructs exactly the kinds it did before (SQLite carries
valueSetraw; unknown kinds freeze-and-carry; always-present keys and fail-closed hydration —constructEntries(…, 'fail')— preserved).fixtures:checkbyte-clean; round-trip tests unchanged.Why it matters
This makes "every entity kind is treated by kind, no special-casing" true everywhere, not just in validation. Concretely: the RLS branch (#771) adds its
policykind by declaring onepolicyEntityKinddescriptor and composing it in — noelse if (kind === 'policy')branch in any constructor, validator, or serializer.Alternatives considered
createSqlEntryConstructionRegistryof(unknown) => unknownfactories keyed by string. Rejected in review: it's a third parallel registry for one concept, theunknown-erased factories force a cast per kind, and it ignores that these are entities the codebase already models with descriptors. The descriptor unifies all three concerns and restores the types.blindCastper descriptor + inline "stub" descriptors to break an import cycle. Rejected — that reintroduces exactly the casts this PR removes. The real fixes were a one-line variance fix (schema: Type<unknown>) and relocating the schemas to break the cycle.EntityKindDescriptor.schema: Type<Input>. Rejected: a kind's wire shape isn't always expressible as its input type (table'sbigint/Datedefaults), so this forces a declaration-site cast on every descriptor.Type<unknown>carries the schema without it;construct's signature carries the input type.AuthoringEntityTypeDescriptor. Rejected: that descriptor keys by authoringdiscriminator(postgres-enum) on the lowering axis and carries an authoring context; this keys byentrieskey (type) on the deserialize axis with no such context. Different concerns — a sibling type. The postgres pack derives itstypeEntityKindfrom the authoring descriptor's schema + constructor rather than redeclaring.Linear: TML-2890 — follow-up A to TML-2887.
Summary by CodeRabbit
New Features
entity-kinds(Mongo and SQL contract packages) and exposedis-plain-recordfor wider reuse.Refactor
entriesare hydrated across SQL and Mongo using a descriptor-driven approach, improving consistency and unknown-kind handling.Tests
Documentation
blindCastusage.Chores