Repository navigation
TML-2229: unified CodecDescriptor + per-library JSON extensions (ADR 208) - #402
Conversation
📝 WalkthroughWalkthroughUnifies codec metadata into a higher-order Changes
Sequence DiagramsequenceDiagram
participant Author as Field Author
participant Emitter as Emitter
participant Desc as CodecDescriptor
participant Context as ExecutionContext
participant Runtime as SQL Runtime
participant Codec as Codec Instance
Note over Author,Runtime: Parameterized codec emit → runtime flow
Author->>Emitter: Emit contract (field with codecId / optional typeParams)
Emitter->>Desc: Lookup descriptor by codecId via CodecLookup
Desc->>Emitter: Return CodecDescriptor<P>
Emitter->>Desc: Validate params via paramsSchema['~standard'].validate
Emitter->>Desc: renderOutputType(validatedParams)
Emitter->>Author: Emit specialized TypeScript field type
Author->>Context: Runtime initialization (build execution context)
Context->>Desc: Enumerate descriptors → CodecDescriptorRegistry
Context->>Context: For each column: materialize codec = descriptor.factory(params)(CodecInstanceContext{ name, usedAt? })
Context->>Runtime: Provide contractCodecs registry (forColumn/forCodecId)
Note over Runtime: Query execution
Runtime->>Context: Encode/decode request with plan
Context->>Context: Resolve codec via contractCodecs.forColumn(table,column) or forCodecId
Context->>Codec: Use codec.encode/decode
Codec->>Runtime: Return encoded/decoded value
Estimated code review effort🎯 4 (Complex) | ⏱️ ~50 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)
Review rate limit: 4/5 reviews remaining, refill in 12 minutes. Comment |
@prisma-next/mongo-runtime
@prisma-next/family-mongo
@prisma-next/sql-runtime
@prisma-next/family-sql
@prisma-next/extension-arktype-json
@prisma-next/middleware-telemetry
@prisma-next/mongo
@prisma-next/extension-paradedb
@prisma-next/extension-pgvector
@prisma-next/postgres
@prisma-next/sql-orm-client
@prisma-next/sqlite
@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/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: |
There was a problem hiding this comment.
Actionable comments posted: 13
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
test/integration/test/contract-builder.types.test-d.ts (1)
395-435:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winAlign the test name with the asserted
neverbehaviorLine 395 says this preserves
JsonValuefallback, but Line 433-434 explicitly assertnever. Renaming the test to reflect the currentnevergap will prevent misleading future readers.Suggested rename
-test('arktypeJson and jsonbColumn preserve JsonValue fallback in no-emit type path', () => { +test('arktypeJson and jsonbColumn currently resolve to never in no-emit type path (known gap)', () => {🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@test/integration/test/contract-builder.types.test-d.ts` around lines 395 - 435, The test name "arktypeJson and jsonbColumn preserve JsonValue fallback in no-emit type path" is misleading because the assertions expect never for Row['payload'] and Row['meta']; rename the test title to reflect the current behavior (e.g., indicate the no-emit path falls back to never) and update any adjacent inline comment if necessary so the name matches the asserted never behavior; locate the test by the existing test(...) call in contract-builder.types.test-d.ts and change only the string description.packages/3-extensions/sql-orm-client/test/model-accessor.test.ts (1)
493-520:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winKeep the descriptor override consistent across all custom-trait tests.
These updates fix the equality/order/textual cases, but the later
syntheticquery-operation test still constructsctxwith onlycodecs. That leaves trait gating sourced from the defaultcontext.codecDescriptors, so the test can pass without exercising the custom trait set it just registered.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/3-extensions/sql-orm-client/test/model-accessor.test.ts` around lines 493 - 520, The test sometimes registers custom codecs with makeRegistry but fails to pass the matching codecDescriptors into createModelAccessor, causing trait gating to use the default context.codecDescriptors; update the later "synthetic" query-operation test (and any other custom-trait tests) to construct the accessor using the same codecDescriptors you created (i.e., call createModelAccessor({ ...context, codecs, codecDescriptors }, ...) or include codecDescriptors in the test ctx) so trait checks use the overridden descriptor set created by makeDescriptors; refer to makeRegistry, makeDescriptors, and createModelAccessor to locate and fix the calls.
🧹 Nitpick comments (4)
packages/3-targets/6-adapters/postgres/src/exports/runtime.ts (1)
39-49: ⚡ Quick winTrim the migration narrative comment block.
The added block is very long for a stable runtime export surface. Prefer concise naming and keep historical/contextual detail in ADR/docs to match repo style.
As per coding guidelines: "Don't add comments if avoidable; prefer code which expresses its intent."
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/3-targets/6-adapters/postgres/src/exports/runtime.ts` around lines 39 - 49, The long narrative comment starting with "Phase C of codec-registry-unification" and referencing "parameterizedCodecDescriptors" should be trimmed to a concise one- or two-sentence summary that states the current behavior (e.g., "Postgres adapter now only retains static raw-JSON/JSONB column descriptors; schema-typed JSON lives in per-library extension packages.") and a note to consult ADR/docs for history; remove the migration/history details from the runtime export surface and keep historical/contextual detail in repository ADRs or docs.packages/3-targets/6-adapters/postgres/README.md (1)
134-140: ⚡ Quick winDrop transition-history phrasing from the user-facing README.
Line 139 adds internal rollout history (“retired in Phase C”), which dilutes the usage-focused guidance. Keep this section strictly on current API behavior and link ADRs for rationale.
As per coding guidelines, "
**/README.md: ... keep README.md focused on what the package does, when to use it, and a few concrete examples. Avoid internal implementation detail unless it materially affects usage".🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/3-targets/6-adapters/postgres/README.md` around lines 134 - 140, Remove the rollout/history phrasing from the README: in the paragraph that documents jsonColumn and jsonbColumn, delete the "previously shipped here retired in Phase C of the codec-registry-unification project" fragment and replace it (if rationale is needed) with a short link to the ADR or migration guide; ensure the entry only states current behavior and directs users to the per-library extension (e.g. `@prisma-next/extension-arktype-json`) for schema-typed JSON overloads such as json(schema)/jsonb(schema).docs/architecture docs/adrs/ADR 207 - Higher-order codecs for parameterized types.md (1)
113-121: 🏗️ Heavy liftTrim implementation playbook details from the ADR body.
This ADR includes step-by-step runtime algorithm flow and granular migration task breakdowns. Keep ADR 207 centered on the decision, constraints, and architectural consequences; move procedural/migration mechanics to subsystem docs or tracked tasks.
Based on learnings, ADRs here should document architectural decisions/constraints only and avoid implementation algorithms or step-by-step migration rules.
Also applies to: 193-200
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@docs/architecture` docs/adrs/ADR 207 - Higher-order codecs for parameterized types.md around lines 113 - 121, Remove procedural implementation and migration-playbook text from ADR 207: strip the step-by-step runtime algorithm and migration tasks described in the paragraph that walks how the descriptor map is built, including references to synthesizeNonParameterizedDescriptor, the descriptor map keyed by codecId, and the four numbered steps under "forColumn" (typeRef reuse, inline-typeParams validate/factory, non-parameterized factory/cache). Keep only the decision, constraints, rationale, and architectural consequences in the ADR; relocate the detailed algorithm and migration checklist into a subsystem design doc or task tracker.packages/1-framework/3-tooling/emitter/src/domain-type-generation.ts (1)
325-333: ⚡ Quick winCall
resolveFieldTypeParamsonly for scalar fields.Line 332 invokes the resolver even for non-scalar fields, though only scalar paths consume codec type params. Narrowing this call avoids unnecessary resolver work and accidental resolver-side errors on unsupported field kinds.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/1-framework/3-tooling/emitter/src/domain-type-generation.ts` around lines 325 - 333, The code currently calls resolveFieldTypeParams for every field; change it so resolveFieldTypeParams is only invoked for scalar fields: keep computing inlineTypeParams as done, then set resolvedTypeParams to inlineTypeParams ?? (field.type.kind === 'scalar' ? resolveFieldTypeParams?.(modelName, fieldName) : undefined) so resolveFieldTypeParams is never called for non-scalar kinds before passing resolvedTypeParams into resolveFieldType; reference resolveFieldTypeParams, resolveFieldType, model.fields, field.type.kind and inlineTypeParams when making the change.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@docs/architecture` docs/subsystems/2. Contract Emitter & Types.md:
- Around line 266-267: The paragraph wrongly implies resolveFieldTypeParams
overrides inline typeParams; edit it to state the precedence clearly:
renderOutputType (via CodecLookup) uses inline field.typeParams first, and only
if a column references a named storage type via typeRef and inline typeParams
are absent will the family-specific emitter callback
EmissionSpi.resolveFieldTypeParams(modelName, fieldName, model, contract) walk
storage.fields → storage.tables → storage.types to return that named instance's
typeParams; the framework consults this resolver as a fallback for
typeRef-backed fields before any other defaults so that typeRef recovery does
not supersede explicitly provided inline typeParams.
In `@packages/1-framework/1-core/framework-components/src/codec-types.ts`:
- Around line 174-179: The validate function on voidParamsSchema currently
coerces any input to undefined; update validate in the voidParamsSchema
(StandardSchemaV1<void>) to reject when any typeParams value is provided:
inspect the incoming parameter to validate and if it is not undefined (or not
absent) return a validation failure (an error result) instead of ({ value:
undefined }), otherwise return the successful ({ value: undefined }); make the
error message clear (e.g., "unexpected typeParams for void codec") and ensure
you modify only the validate implementation for voidParamsSchema.
In `@packages/1-framework/3-tooling/emitter/src/generate-contract-dts.ts`:
- Around line 71-83: Add unit tests for resolveFieldTypeParams behavior: one
test where contract.models does not contain the requested model (exercise the
branch where model is missing and ensure the wrapper resolveFieldTypeParams
returns undefined), and another test where emitter.resolveFieldTypeParams is
defined (mock it) to ensure the wrapper delegates to
emitter.resolveFieldTypeParams with the exact parameters (modelName, fieldName,
model, contract) and returns its value; target the wrapper created in
generate-contract-dts.ts (the resolveFieldTypeParams constant) and also assert
interactions with generateBothFieldTypesMaps to ensure the resolver is passed
through.
In `@packages/2-sql/4-lanes/relational-core/src/query-lane-context.ts`:
- Around line 20-34: The public descriptor registry API currently exposes
CodecDescriptor<any> and uses biome-ignore suppressions; update the three
signatures—descriptorFor, values, and byTargetType—to use
CodecDescriptor<unknown> (i.e., descriptorFor(codecId: string):
CodecDescriptor<unknown> | undefined; values():
IterableIterator<CodecDescriptor<unknown>>; byTargetType(targetType: string):
readonly CodecDescriptor<unknown>[]), and remove the biome-ignore lint comments
above those declarations so the public interface no longer uses any or
suppressed lints.
In `@packages/2-sql/5-runtime/src/sql-context.ts`:
- Around line 519-538: The fallback in ContractCodecRegistry.forCodecId
currently returns the first entry from byCodecId and may silently reuse the
wrong codec when a parameterized codecId maps to multiple resolved instances;
change the byCodecId tracking to detect and record multiple distinct resolved
codecs per codecId (e.g., store an array or track a duplicate flag when setting
in the resolution loop), then update forCodecId to: if the codecId is
parameterized (detect via whatever project convention for parameterized ids used
elsewhere) and more than one distinct resolved codec exists, throw a clear error
instead of returning a single instance; otherwise keep the existing behavior
(return the single resolved codec or fallback to legacyCodecRegistry.get).
Ensure references: update the map handling where byCodecId is set and the
ContractCodecRegistry.forCodecId implementation to enforce this guard.
In `@packages/3-extensions/arktype-json/src/core/arktype-json-codec.ts`:
- Around line 120-143: The decodeJson path currently just casts parsed JSON to
TInferred and bypasses validation; update decodeJson to run the same arktype
schema check as decode by calling schema(json), handling the ArkErrors result
the same way (throwing runtimeError with
'RUNTIME.JSON_SCHEMA_VALIDATION_FAILED', include result.summary and { codecId:
ARKTYPE_JSON_CODEC_ID, issues: result.summary }) and otherwise returning the
validated value as TInferred; reference decodeJson, schema, runtimeError,
ARKTYPE_JSON_CODEC_ID and ArkErrors to locate and mirror the existing decode
logic.
In `@packages/3-extensions/arktype-json/src/core/control-extension-descriptor.ts`:
- Around line 19-34: Write a small unit test that imports
arktypeJsonExtensionDescriptor and asserts two things: (1) the
descriptor.types.codecTypes.controlPlaneHooks has a property keyed by
ARKTYPE_JSON_CODEC_ID whose value strictly equals arktypeJsonControlPlaneHooks,
and (2) calling arktypeJsonExtensionDescriptor.create() returns an object with
familyId === 'sql' and targetId === 'postgres'; use the existing test framework
and assertion helpers in the package to ensure the mapping and create() contract
are covered.
- Around line 14-19: The control-plane descriptor arktypeJsonExtensionDescriptor
currently defined in src/core imports control-plane code
(arktypeJsonControlPlaneHooks) and must be moved out of core; keep
ARKTYPE_JSON_CODEC_ID and arktypeJsonPackMeta and any pure metadata/hook helpers
in core, then create a new control-only module (e.g., exports/control.ts) that
imports those core exports plus arktypeJsonControlPlaneHooks and
constructs/exports arktypeJsonExtensionDescriptor:
SqlControlExtensionDescriptor<'postgres'>; update any consumers to import the
descriptor from the new control-only module while leaving core files free of
migration/runtime imports.
In `@packages/3-extensions/arktype-json/src/core/pack-meta.ts`:
- Around line 9-14: The comment above the metadata block incorrectly states that
codecInstances is empty while the implementation registers arktypeJsonEmitCodec;
update the comment to reflect that codecInstances contains arktypeJsonEmitCodec
(i.e., that arktype-json registers an emit codec alongside the unified
descriptor) and mirror this correction where the same header appears (also at
the second occurrence), referencing codecInstances, arktypeJsonEmitCodec, and
descriptorFor('arktype/json@1') so readers understand both the unified
descriptor and the registered emit codec are present.
In `@packages/3-extensions/arktype-json/src/core/runtime-extension-descriptor.ts`:
- Around line 24-38: Add unit tests that exercise the
arktypeJsonRuntimeDescriptor to cover parameterizedCodecs, codecs, and create:
write tests that import arktypeJsonRuntimeDescriptor and assert
parameterizedCodecs() returns an array containing arktypeJsonCodec, that codecs
(createArktypeJsonCodecRegistry) is a function (and optionally produces the
expected codec registry when invoked), and that create() returns an object with
familyId 'sql' and targetId 'postgres'; ensure tests live inside the package
test suite so they run in CI and raise coverage above 0%.
In `@packages/3-extensions/arktype-json/test/arktype-json-codec.test.ts`:
- Around line 54-55: Remove the "biome-ignore" suppression in the negative tests
that call arktypeJson and instead perform a test-boundary cast (e.g., cast the
value to unknown or do a double-cast like unknown as any) to produce the
deliberate wrong type; update the two occurrences around the failing negative
cases that currently use "biome-ignore lint/suspicious/noExplicitAny" so they
cast via unknown/double-cast rather than disabling Biome lints, keeping the
negative test logic intact and referencing the arktypeJson calls to locate the
changes.
In `@packages/3-extensions/sql-orm-client/src/filters.ts`:
- Line 76: Add unit tests that exercise the new descriptor-based trait branch
around the shorthand equality filtering logic: create one test where
context.codecDescriptors.descriptorFor(codecId) returns a descriptor object
containing a traits array and assert the shorthand equality filter behaves as
expected, and another test where descriptorFor(codecId) returns undefined (or
null) to exercise the fallback to [] and assert the filter still works. In each
test, set codecId appropriately, stub/mocking
context.codecDescriptors.descriptorFor to return the descriptor or undefined,
invoke the shorthand equality filtering entry point that references the const
traits = codecId ? (context.codecDescriptors.descriptorFor(codecId)?.traits ??
[]) : []; and assert the resulting filter output or behavior for both branches.
Ensure these tests are added to the package test suite so CI branch coverage
includes both descriptor-present and descriptor-missing paths.
In `@packages/3-extensions/sql-orm-client/src/model-accessor.ts`:
- Around line 75-78: Add targeted unit tests to the existing test suite for
model-accessor to cover the three descriptor-based branches: (1) a test where a
descriptor in context.codecDescriptors has descriptor.traits that include all
entries in self.traits so registerOp is called with descriptor.codecId (exercise
the self.traits matching path), (2) a test simulating a missing descriptor to
trigger the fallback branch (ensure code handles absent descriptor and the
fallback behavior is asserted), and (3) a test for the return-trait predicate
gating path that verifies the predicate blocks or allows registration as
expected; locate the code paths via context.codecDescriptors, descriptor.traits,
self.traits, registerOp and descriptor.codecId and assert side effects or return
values accordingly.
---
Outside diff comments:
In `@packages/3-extensions/sql-orm-client/test/model-accessor.test.ts`:
- Around line 493-520: The test sometimes registers custom codecs with
makeRegistry but fails to pass the matching codecDescriptors into
createModelAccessor, causing trait gating to use the default
context.codecDescriptors; update the later "synthetic" query-operation test (and
any other custom-trait tests) to construct the accessor using the same
codecDescriptors you created (i.e., call createModelAccessor({ ...context,
codecs, codecDescriptors }, ...) or include codecDescriptors in the test ctx) so
trait checks use the overridden descriptor set created by makeDescriptors; refer
to makeRegistry, makeDescriptors, and createModelAccessor to locate and fix the
calls.
In `@test/integration/test/contract-builder.types.test-d.ts`:
- Around line 395-435: The test name "arktypeJson and jsonbColumn preserve
JsonValue fallback in no-emit type path" is misleading because the assertions
expect never for Row['payload'] and Row['meta']; rename the test title to
reflect the current behavior (e.g., indicate the no-emit path falls back to
never) and update any adjacent inline comment if necessary so the name matches
the asserted never behavior; locate the test by the existing test(...) call in
contract-builder.types.test-d.ts and change only the string description.
---
Nitpick comments:
In `@docs/architecture` docs/adrs/ADR 207 - Higher-order codecs for parameterized
types.md:
- Around line 113-121: Remove procedural implementation and migration-playbook
text from ADR 207: strip the step-by-step runtime algorithm and migration tasks
described in the paragraph that walks how the descriptor map is built, including
references to synthesizeNonParameterizedDescriptor, the descriptor map keyed by
codecId, and the four numbered steps under "forColumn" (typeRef reuse,
inline-typeParams validate/factory, non-parameterized factory/cache). Keep only
the decision, constraints, rationale, and architectural consequences in the ADR;
relocate the detailed algorithm and migration checklist into a subsystem design
doc or task tracker.
In `@packages/1-framework/3-tooling/emitter/src/domain-type-generation.ts`:
- Around line 325-333: The code currently calls resolveFieldTypeParams for every
field; change it so resolveFieldTypeParams is only invoked for scalar fields:
keep computing inlineTypeParams as done, then set resolvedTypeParams to
inlineTypeParams ?? (field.type.kind === 'scalar' ?
resolveFieldTypeParams?.(modelName, fieldName) : undefined) so
resolveFieldTypeParams is never called for non-scalar kinds before passing
resolvedTypeParams into resolveFieldType; reference resolveFieldTypeParams,
resolveFieldType, model.fields, field.type.kind and inlineTypeParams when making
the change.
In `@packages/3-targets/6-adapters/postgres/README.md`:
- Around line 134-140: Remove the rollout/history phrasing from the README: in
the paragraph that documents jsonColumn and jsonbColumn, delete the "previously
shipped here retired in Phase C of the codec-registry-unification project"
fragment and replace it (if rationale is needed) with a short link to the ADR or
migration guide; ensure the entry only states current behavior and directs users
to the per-library extension (e.g. `@prisma-next/extension-arktype-json`) for
schema-typed JSON overloads such as json(schema)/jsonb(schema).
In `@packages/3-targets/6-adapters/postgres/src/exports/runtime.ts`:
- Around line 39-49: The long narrative comment starting with "Phase C of
codec-registry-unification" and referencing "parameterizedCodecDescriptors"
should be trimmed to a concise one- or two-sentence summary that states the
current behavior (e.g., "Postgres adapter now only retains static raw-JSON/JSONB
column descriptors; schema-typed JSON lives in per-library extension packages.")
and a note to consult ADR/docs for history; remove the migration/history details
from the runtime export surface and keep historical/contextual detail in
repository ADRs or docs.
🪄 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: 299ceb06-8a4c-49ec-99e4-8719e69f6fab
⛔ Files ignored due to path filters (3)
pnpm-lock.yamlis excluded by!**/pnpm-lock.yamltest/e2e/framework/test/fixtures/generated/contract.d.tsis excluded by!**/generated/**test/e2e/framework/test/fixtures/generated/contract.jsonis excluded by!**/generated/**
📒 Files selected for processing (73)
docs/architecture docs/adrs/ADR 207 - Higher-order codecs for parameterized types.mddocs/architecture docs/subsystems/2. Contract Emitter & Types.mddocs/architecture docs/subsystems/9. No-Emit Workflow.mdexamples/prisma-next-demo/src/prisma/contract.d.tspackages/1-framework/1-core/framework-components/README.mdpackages/1-framework/1-core/framework-components/package.jsonpackages/1-framework/1-core/framework-components/src/codec-types.tspackages/1-framework/1-core/framework-components/src/emission-types.tspackages/1-framework/1-core/framework-components/src/exports/codec.tspackages/1-framework/3-tooling/emitter/src/domain-type-generation.tspackages/1-framework/3-tooling/emitter/src/generate-contract-dts.tspackages/1-framework/3-tooling/emitter/test/domain-type-generation.test.tspackages/2-sql/3-tooling/emitter/src/index.tspackages/2-sql/3-tooling/emitter/test/emitter-hook.typeref-resolver.test.tspackages/2-sql/4-lanes/relational-core/src/ast/codec-types.tspackages/2-sql/4-lanes/relational-core/src/query-lane-context.tspackages/2-sql/4-lanes/relational-core/test/utils.tspackages/2-sql/5-runtime/src/codecs/decoding.tspackages/2-sql/5-runtime/src/codecs/encoding.tspackages/2-sql/5-runtime/src/codecs/validation.tspackages/2-sql/5-runtime/src/sql-context.tspackages/2-sql/5-runtime/src/sql-runtime.tspackages/2-sql/5-runtime/test/contract-codec-registry.test.tspackages/2-sql/5-runtime/test/json-schema-validation.test.tspackages/2-sql/5-runtime/test/parameterized-types.test.tspackages/3-extensions/arktype-json/README.mdpackages/3-extensions/arktype-json/biome.jsoncpackages/3-extensions/arktype-json/package.jsonpackages/3-extensions/arktype-json/src/core/arktype-json-codec.tspackages/3-extensions/arktype-json/src/core/control-extension-descriptor.tspackages/3-extensions/arktype-json/src/core/control-hooks.tspackages/3-extensions/arktype-json/src/core/pack-meta.tspackages/3-extensions/arktype-json/src/core/runtime-extension-descriptor.tspackages/3-extensions/arktype-json/src/exports/codec-types.tspackages/3-extensions/arktype-json/src/exports/codecs.tspackages/3-extensions/arktype-json/src/exports/column-types.tspackages/3-extensions/arktype-json/src/exports/control.tspackages/3-extensions/arktype-json/src/exports/pack.tspackages/3-extensions/arktype-json/src/exports/runtime.tspackages/3-extensions/arktype-json/src/types/codec-types.tspackages/3-extensions/arktype-json/test/arktype-json-codec.test-d.tspackages/3-extensions/arktype-json/test/arktype-json-codec.test.tspackages/3-extensions/arktype-json/tsconfig.jsonpackages/3-extensions/arktype-json/tsconfig.prod.jsonpackages/3-extensions/arktype-json/tsdown.config.tspackages/3-extensions/arktype-json/vitest.config.tspackages/3-extensions/pgvector/README.mdpackages/3-extensions/pgvector/src/exports/runtime.tspackages/3-extensions/sql-orm-client/src/filters.tspackages/3-extensions/sql-orm-client/src/model-accessor.tspackages/3-extensions/sql-orm-client/test/model-accessor.test.tspackages/3-targets/3-targets/postgres/src/core/codecs.tspackages/3-targets/3-targets/postgres/src/core/json-schema-type-expression.tspackages/3-targets/3-targets/postgres/test/codec-render-output-type.test.tspackages/3-targets/3-targets/postgres/test/json-schema-type-expression.test.tspackages/3-targets/6-adapters/postgres/README.mdpackages/3-targets/6-adapters/postgres/package.jsonpackages/3-targets/6-adapters/postgres/src/core/json-schema-validator.tspackages/3-targets/6-adapters/postgres/src/core/standard-schema.tspackages/3-targets/6-adapters/postgres/src/exports/column-types.tspackages/3-targets/6-adapters/postgres/src/exports/runtime.tspackages/3-targets/6-adapters/postgres/test/column-types.test.tspackages/3-targets/6-adapters/postgres/test/json-schema-validator.test.tspackages/3-targets/6-adapters/postgres/test/standard-schema.test.tstest/e2e/framework/package.jsontest/e2e/framework/test/fixtures/contract.tstest/e2e/framework/test/fixtures/prisma-next.config.tstest/e2e/framework/test/transaction-orm.test.tstest/e2e/framework/test/utils.tstest/integration/package.jsontest/integration/test/contract-builder.types.test-d.tstest/integration/test/fixtures/cli/cli-e2e-test-app/fixtures/db-update-scenarios/contract-add-project-slug.tstest/integration/test/fixtures/cli/cli-e2e-test-app/fixtures/db-update-scenarios/contract.ts
💤 Files with no reviewable changes (7)
- packages/3-targets/6-adapters/postgres/test/json-schema-validator.test.ts
- packages/3-targets/6-adapters/postgres/test/standard-schema.test.ts
- packages/3-targets/6-adapters/postgres/src/core/json-schema-validator.ts
- packages/3-targets/3-targets/postgres/src/core/json-schema-type-expression.ts
- packages/3-targets/6-adapters/postgres/src/core/standard-schema.ts
- packages/3-targets/6-adapters/postgres/package.json
- packages/3-targets/3-targets/postgres/test/json-schema-type-expression.test.ts
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (2)
packages/2-sql/5-runtime/src/sql-context.ts (1)
529-549:⚠️ Potential issue | 🟠 Major | ⚡ Quick winGuard
forCodecId()against ambiguous parameterized instances.
byCodecIdis currently first-write-wins. If multiple resolved instances share a codec id (e.g., different params), codec-id fallback can return the wrong instance.🔧 Proposed fix
const byColumn = new Map<string, Codec>(); const byCodecId = new Map<string, Codec>(); + const ambiguousCodecIds = new Set<string>(); @@ - if (!byCodecId.has(column.codecId)) { - byCodecId.set(column.codecId, resolvedCodec); - } + const existing = byCodecId.get(column.codecId); + if (!existing) { + byCodecId.set(column.codecId, resolvedCodec); + } else if (parameterizedDescriptors.has(column.codecId) && existing !== resolvedCodec) { + ambiguousCodecIds.add(column.codecId); + } @@ forCodecId(codecId) { + if (ambiguousCodecIds.has(codecId)) { + throw runtimeError( + 'RUNTIME.AMBIGUOUS_CODEC_FALLBACK', + `Codec '${codecId}' resolves to multiple parameterized instances; column-aware dispatch is required.`, + { codecId }, + ); + } return byCodecId.get(codecId) ?? legacyCodecRegistry.get(codecId); },🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/2-sql/5-runtime/src/sql-context.ts` around lines 529 - 549, forCodecId currently returns the first entry from byCodecId which can be wrong when multiple resolved instances share the same codecId (parameterized variants); change forCodecId to only return the byCodecId result when that codecId maps to a single unambiguous resolved instance (e.g., track duplicates when building byCodecId or mark ambiguous entries), and otherwise skip the ambiguous byCodecId entry and fall back to legacyCodecRegistry.get(codecId); update the logic in ContractCodecRegistry.forCodecId to perform this uniqueness check before returning byCodecId.get(codecId).packages/1-framework/1-core/framework-components/src/codec-types.ts (1)
176-181:⚠️ Potential issue | 🟠 Major | ⚡ Quick winReject non-
undefinedinput invoidParamsSchema.validate.The current validator always succeeds, so unexpected
typeParamson non-parameterized codecs are silently accepted instead of failing fast.🔧 Proposed fix
export const voidParamsSchema: StandardSchemaV1<void> = { '~standard': { version: 1, vendor: 'prisma-next', - validate: () => ({ value: undefined }), + validate: (input: unknown) => + input === undefined + ? { value: undefined } + : { + issues: [{ message: 'unexpected typeParams for non-parameterized codec' }], + }, }, };🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/1-framework/1-core/framework-components/src/codec-types.ts` around lines 176 - 181, Update voidParamsSchema.validate to reject any provided input instead of always succeeding: change the validate implementation on the voidParamsSchema object to accept an input parameter, and if that input is not strictly undefined return a failure result (an object indicating an error/rejection) and only return { value: undefined } when the input is exactly undefined. Reference voidParamsSchema and its '~standard'.validate to locate and modify the validator.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/2-sql/5-runtime/src/sql-context.ts`:
- Around line 517-520: The code currently leaves resolvedCodec undefined when
encountering a parameterized codec id that provides neither typeRef nor
typeParams, causing caller logic to fall back to forCodecId and potentially
match the wrong instance; update the branch that handles "parameterized codec id
with no typeRef and no typeParams" to fail fast by throwing or returning a clear
error (e.g. throw new Error / return a validation error) when both typeRef and
typeParams are missing, and ensure the error message references the codec id and
indicates missing type parameters so callers of resolvedCodec and forCodecId
cannot silently accept an invalid contract.
---
Duplicate comments:
In `@packages/1-framework/1-core/framework-components/src/codec-types.ts`:
- Around line 176-181: Update voidParamsSchema.validate to reject any provided
input instead of always succeeding: change the validate implementation on the
voidParamsSchema object to accept an input parameter, and if that input is not
strictly undefined return a failure result (an object indicating an
error/rejection) and only return { value: undefined } when the input is exactly
undefined. Reference voidParamsSchema and its '~standard'.validate to locate and
modify the validator.
In `@packages/2-sql/5-runtime/src/sql-context.ts`:
- Around line 529-549: forCodecId currently returns the first entry from
byCodecId which can be wrong when multiple resolved instances share the same
codecId (parameterized variants); change forCodecId to only return the byCodecId
result when that codecId maps to a single unambiguous resolved instance (e.g.,
track duplicates when building byCodecId or mark ambiguous entries), and
otherwise skip the ambiguous byCodecId entry and fall back to
legacyCodecRegistry.get(codecId); update the logic in
ContractCodecRegistry.forCodecId to perform this uniqueness check before
returning byCodecId.get(codecId).
🪄 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: 08881e83-ccb9-49c6-8dfa-973f377c205a
📒 Files selected for processing (19)
docs/architecture docs/adrs/ADR 208 - Higher-order codecs for parameterized types.mddocs/architecture docs/subsystems/2. Contract Emitter & Types.mddocs/architecture docs/subsystems/9. No-Emit Workflow.mdpackages/1-framework/1-core/framework-components/README.mdpackages/1-framework/1-core/framework-components/src/codec-types.tspackages/1-framework/1-core/framework-components/src/exports/codec.tspackages/2-sql/4-lanes/relational-core/src/ast/codec-types.tspackages/2-sql/5-runtime/src/sql-context.tspackages/2-sql/5-runtime/test/contract-codec-registry.test.tspackages/2-sql/5-runtime/test/parameterized-types.test.tspackages/3-extensions/arktype-json/README.mdpackages/3-extensions/arktype-json/src/core/arktype-json-codec.tspackages/3-extensions/arktype-json/src/core/pack-meta.tspackages/3-extensions/arktype-json/test/arktype-json-codec.test-d.tspackages/3-extensions/arktype-json/test/arktype-json-codec.test.tspackages/3-extensions/pgvector/README.mdpackages/3-extensions/pgvector/src/exports/runtime.tspackages/3-extensions/sql-orm-client/test/model-accessor.test.tspackages/3-targets/6-adapters/postgres/README.md
✅ Files skipped from review due to trivial changes (3)
- docs/architecture docs/subsystems/9. No-Emit Workflow.md
- packages/3-extensions/arktype-json/test/arktype-json-codec.test.ts
- packages/2-sql/5-runtime/test/contract-codec-registry.test.ts
🚧 Files skipped from review as they are similar to previous changes (8)
- packages/3-extensions/pgvector/src/exports/runtime.ts
- packages/1-framework/1-core/framework-components/src/exports/codec.ts
- docs/architecture docs/subsystems/2. Contract Emitter & Types.md
- packages/3-extensions/arktype-json/README.md
- packages/3-extensions/arktype-json/src/core/pack-meta.ts
- packages/3-extensions/arktype-json/test/arktype-json-codec.test-d.ts
- packages/3-targets/6-adapters/postgres/README.md
- packages/3-extensions/pgvector/README.md
| // else: parameterized codec id with no typeRef and no typeParams | ||
| // — the column is missing the params the descriptor needs. Leave | ||
| // `resolvedCodec` undefined; encode/decode for this column will | ||
| // fall through to `forCodecId` (the AC-5-deferred carve-out). |
There was a problem hiding this comment.
Fail fast when a parameterized codec column provides neither typeRef nor typeParams.
This path currently leaves resolvedCodec undefined and defers to forCodecId() fallback, which can mask invalid contracts and route to an unrelated instance.
🔧 Proposed fix
- // else: parameterized codec id with no typeRef and no typeParams
- // — the column is missing the params the descriptor needs. Leave
- // `resolvedCodec` undefined; encode/decode for this column will
- // fall through to `forCodecId` (the AC-5-deferred carve-out).
+ else {
+ throw runtimeError(
+ 'RUNTIME.TYPE_PARAMS_INVALID',
+ `Column '${tableName}.${columnName}' uses parameterized codec '${column.codecId}' but provides neither typeRef nor typeParams.`,
+ { tableName, columnName, codecId: column.codecId },
+ );
+ }As per coding guidelines: "Do not treat missing type parameters as a successful match when the contract declares them."
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| // else: parameterized codec id with no typeRef and no typeParams | |
| // — the column is missing the params the descriptor needs. Leave | |
| // `resolvedCodec` undefined; encode/decode for this column will | |
| // fall through to `forCodecId` (the AC-5-deferred carve-out). | |
| else { | |
| throw runtimeError( | |
| 'RUNTIME.TYPE_PARAMS_INVALID', | |
| `Column '${tableName}.${columnName}' uses parameterized codec '${column.codecId}' but provides neither typeRef nor typeParams.`, | |
| { tableName, columnName, codecId: column.codecId }, | |
| ); | |
| } |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@packages/2-sql/5-runtime/src/sql-context.ts` around lines 517 - 520, The code
currently leaves resolvedCodec undefined when encountering a parameterized codec
id that provides neither typeRef nor typeParams, causing caller logic to fall
back to forCodecId and potentially match the wrong instance; update the branch
that handles "parameterized codec id with no typeRef and no typeParams" to fail
fast by throwing or returning a clear error (e.g. throw new Error / return a
validation error) when both typeRef and typeParams are missing, and ensure the
error message references the codec id and indicates missing type parameters so
callers of resolvedCodec and forCodecId cannot silently accept an invalid
contract.
There was a problem hiding this comment.
Actionable comments posted: 2
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
test/integration/test/contract-builder.types.test-d.ts (1)
395-434:⚠️ Potential issue | 🟠 Major | 🏗️ Heavy liftThis test locks in the exact no-emit regression this PR is supposed to remove.
The PR objective here is preserving parameterized output types in the no-emit path, including schema-narrowed JSON. Asserting
neverfor bothpayloadandmetamakes the suite green with the broken inference path instead of catching it.payloadshould stay schema-shaped andmetashould stay the raw JSONB fallback type, not collapse tonever.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@test/integration/test/contract-builder.types.test-d.ts` around lines 395 - 434, The test currently asserts both Row['payload'] and Row['meta'] are never, which masks the no-emit regression; update the assertions so payload is asserted to equal the arktype-derived schema shape and meta is asserted to equal the JSONB fallback type instead of never: locate payloadSchema and the contract built with arktypeJson and jsonbColumn, then change expectTypeOf(Row['payload']) to compare against the arktype() output type (the codec/type produced by payloadSchema) and change expectTypeOf(Row['meta']) to compare against the pack's raw JSONB fallback type (the jsonbColumn codec output / pack JSON type) so the test fails when schema-narrowing or raw JSON fallback are lost.
🧹 Nitpick comments (1)
packages/3-extensions/sql-orm-client/test/filters.test.ts (1)
154-155: ⚡ Quick winUse mock-boundary double casts for the stubbed contexts.
Line 154 and Line 180 use direct casts (
as typeof context). For test mocks/proxies here, useas unknown as typeof contextat the boundary.Proposed patch
- } as typeof context; + } as unknown as typeof context; ... - } as typeof context; + } as unknown as typeof context;As per coding guidelines: "Use double casts (
as unknown as X) for mocks and dynamic proxies in tests instead of direct casts".Also applies to: 180-180
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/3-extensions/sql-orm-client/test/filters.test.ts` around lines 154 - 155, Replace the direct cast used for the stubbed test contexts (currently written as "as typeof context") with a mock-boundary double cast "as unknown as typeof context" wherever the test creates proxy/mocked contexts (e.g., the variable named context in this test file and the other stub at the second occurrence); update both occurrences so the test mocks use "as unknown as typeof context" to satisfy the guideline for mock/proxy boundary casts.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/1-framework/3-tooling/emitter/test/emitter.test.ts`:
- Around line 406-434: The test's description claims to exercise the
resolveFieldTypeParams wrapper's "model missing" return-undefined branch, but
because createTestContract({ storage: { tables: {} } }) removes models earlier
in field-map generation the wrapper is never invoked; update the test to reflect
the actual behavior by renaming the spec and its comment to state that the
wrapper is built but never called (asserting resolverInvocations remains 0 when
emit is called with hookWithResolver), referencing resolveFieldTypeParams,
createTestContract, emit, resolverInvocations and hookWithResolver so future
readers understand the asserted branch is "wrapper never invoked" rather than
"wrapper returns undefined due to missing model."
In `@packages/3-extensions/arktype-json/src/core/arktype-json-codec.ts`:
- Around line 198-210: The factory arktypeJson currently validates expression
and jsonIr but then blindly casts schema to ArktypeSchemaLike before building
the descriptor; add a callable check (e.g. ensure typeof schema === 'function'
or implement a type predicate isCallableSchema(schema)) and reject non-callable
lookalikes before casting so objects shaped like {expression,json} fail early;
update arktypeJson to validate schema is callable, throw a descriptive Error if
not, and only then call arktypeJsonCodecForSchema and set typeParams (replace
the blind cast with the predicate/guard).
---
Outside diff comments:
In `@test/integration/test/contract-builder.types.test-d.ts`:
- Around line 395-434: The test currently asserts both Row['payload'] and
Row['meta'] are never, which masks the no-emit regression; update the assertions
so payload is asserted to equal the arktype-derived schema shape and meta is
asserted to equal the JSONB fallback type instead of never: locate payloadSchema
and the contract built with arktypeJson and jsonbColumn, then change
expectTypeOf(Row['payload']) to compare against the arktype() output type (the
codec/type produced by payloadSchema) and change expectTypeOf(Row['meta']) to
compare against the pack's raw JSONB fallback type (the jsonbColumn codec output
/ pack JSON type) so the test fails when schema-narrowing or raw JSON fallback
are lost.
---
Nitpick comments:
In `@packages/3-extensions/sql-orm-client/test/filters.test.ts`:
- Around line 154-155: Replace the direct cast used for the stubbed test
contexts (currently written as "as typeof context") with a mock-boundary double
cast "as unknown as typeof context" wherever the test creates proxy/mocked
contexts (e.g., the variable named context in this test file and the other stub
at the second occurrence); update both occurrences so the test mocks use "as
unknown as typeof context" to satisfy the guideline for mock/proxy boundary
casts.
🪄 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: 76d066d6-99b9-4457-9358-8faae8176b9f
📒 Files selected for processing (14)
docs/architecture docs/subsystems/2. Contract Emitter & Types.mdpackages/1-framework/1-core/framework-components/src/codec-types.tspackages/1-framework/3-tooling/emitter/test/emitter.test.tspackages/2-sql/4-lanes/relational-core/src/query-lane-context.tspackages/2-sql/5-runtime/src/sql-context.tspackages/3-extensions/arktype-json/src/core/arktype-json-codec.tspackages/3-extensions/arktype-json/src/core/pack-meta.tspackages/3-extensions/arktype-json/src/exports/control.tspackages/3-extensions/arktype-json/src/exports/runtime.tspackages/3-extensions/arktype-json/test/arktype-json-codec.test.tspackages/3-extensions/arktype-json/test/extension-descriptors.test.tspackages/3-extensions/sql-orm-client/test/filters.test.tspackages/3-extensions/sql-orm-client/test/model-accessor.test.tstest/integration/test/contract-builder.types.test-d.ts
✅ Files skipped from review due to trivial changes (1)
- packages/3-extensions/arktype-json/src/core/pack-meta.ts
🚧 Files skipped from review as they are similar to previous changes (2)
- packages/3-extensions/arktype-json/src/exports/control.ts
- docs/architecture docs/subsystems/2. Contract Emitter & Types.md
There was a problem hiding this comment.
🧹 Nitpick comments (2)
packages/3-extensions/arktype-json/src/core/arktype-json-codec.ts (2)
305-309: 💤 Low valueInconsistent defensive behavior in emit-only stub.
encode/decodecorrectly reject with an error, butencodeJson/decodeJsonsilently pass through. If this stub is mistakenly used at runtime, the JSON methods would succeed without validation while the wire methods throw.♻️ Suggested fix for consistency
encode: () => Promise.reject(new Error(ARKTYPE_JSON_RUNTIME_DISPATCH_ERROR)), decode: () => Promise.reject(new Error(ARKTYPE_JSON_RUNTIME_DISPATCH_ERROR)), - encodeJson: (value) => value as never, - decodeJson: (json) => json as unknown, + encodeJson: () => { + throw new Error(ARKTYPE_JSON_RUNTIME_DISPATCH_ERROR); + }, + decodeJson: () => { + throw new Error(ARKTYPE_JSON_RUNTIME_DISPATCH_ERROR); + },🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/3-extensions/arktype-json/src/core/arktype-json-codec.ts` around lines 305 - 309, The encodeJson and decodeJson stub implementations are currently passthroughs while encode/decode reject, so make them consistently defensive by replacing the passthroughs with synchronous errors: have encodeJson and decodeJson throw new Error(ARKTYPE_JSON_RUNTIME_DISPATCH_ERROR) (matching the ARKTYPE_JSON_RUNTIME_DISPATCH_ERROR used by encode/decode) so the emit-only stub fails fast at runtime; keep renderArktypeJsonOutputTypeFromUnknownParams unchanged.
202-217: 💤 Low valueConsider a type predicate to eliminate the blind cast.
After the validation guards, the
schemais known to satisfyArktypeSchemaLikestructurally. A type predicate would let the compiler narrow the type without theas unknown ascast at line 217.♻️ Suggested refactor with type predicate
+function isArktypeSchemaLike(value: unknown): value is ArktypeSchemaLike { + return ( + typeof value === 'function' && + typeof (value as { expression?: unknown }).expression === 'string' + ); +} + export function arktypeJson<S extends Type<unknown>>( schema: S, ): ColumnTypeDescriptor & { // ... } { if (typeof schema !== 'function') { throw new Error('arktypeJson(schema) expects a callable arktype Type.'); } const expression: unknown = (schema as { readonly expression?: unknown }).expression; const jsonIr: unknown = (schema as { readonly json?: unknown }).json; if (typeof expression !== 'string') { throw new Error('arktypeJson(schema) expects an arktype Type (missing `expression: string`).'); } if (jsonIr === null || typeof jsonIr !== 'object') { throw new Error('arktypeJson(schema) expects an arktype Type (missing `json` IR).'); } + if (!isArktypeSchemaLike(schema)) { + // Unreachable after above guards, but satisfies the type predicate path + throw new Error('arktypeJson(schema) expects a valid arktype Type.'); + } return { codecId: ARKTYPE_JSON_CODEC_ID, nativeType: ARKTYPE_JSON_NATIVE_TYPE, typeParams: { expression, jsonIr }, - type: arktypeJsonCodecForSchema<S['infer']>(schema as unknown as ArktypeSchemaLike), + type: arktypeJsonCodecForSchema<S['infer']>(schema), } as const; }As per coding guidelines: "Replace blind casts with type predicates to improve type safety."
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/3-extensions/arktype-json/src/core/arktype-json-codec.ts` around lines 202 - 217, The code performs runtime checks on schema but then uses a blind cast to ArktypeSchemaLike when calling arktypeJsonCodecForSchema; add a type predicate function (e.g., isArktypeSchemaLike(schema): schema is ArktypeSchemaLike) that encapsulates the existing runtime checks (callable, has string expression, has non-null object json IR) and use that predicate to narrow schema so you can call arktypeJsonCodecForSchema(schema) without the as unknown as cast; update the return to rely on the predicate for type narrowing and remove the blind cast.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In `@packages/3-extensions/arktype-json/src/core/arktype-json-codec.ts`:
- Around line 305-309: The encodeJson and decodeJson stub implementations are
currently passthroughs while encode/decode reject, so make them consistently
defensive by replacing the passthroughs with synchronous errors: have encodeJson
and decodeJson throw new Error(ARKTYPE_JSON_RUNTIME_DISPATCH_ERROR) (matching
the ARKTYPE_JSON_RUNTIME_DISPATCH_ERROR used by encode/decode) so the emit-only
stub fails fast at runtime; keep renderArktypeJsonOutputTypeFromUnknownParams
unchanged.
- Around line 202-217: The code performs runtime checks on schema but then uses
a blind cast to ArktypeSchemaLike when calling arktypeJsonCodecForSchema; add a
type predicate function (e.g., isArktypeSchemaLike(schema): schema is
ArktypeSchemaLike) that encapsulates the existing runtime checks (callable, has
string expression, has non-null object json IR) and use that predicate to narrow
schema so you can call arktypeJsonCodecForSchema(schema) without the as unknown
as cast; update the return to rely on the predicate for type narrowing and
remove the blind cast.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yml
Review profile: CHILL
Plan: Pro
Run ID: bdbb09eb-a266-4f64-8a70-42eccd037fd8
📒 Files selected for processing (3)
packages/1-framework/3-tooling/emitter/test/emitter.test.tspackages/3-extensions/arktype-json/src/core/arktype-json-codec.tspackages/3-extensions/arktype-json/test/arktype-json-codec.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
- packages/3-extensions/arktype-json/test/arktype-json-codec.test.ts
There was a problem hiding this comment.
Actionable comments posted: 1
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/3-extensions/arktype-json/src/core/arktype-json-codec.ts`:
- Around line 156-166: Unify the encode and encodeJson behavior by making
encodeJson produce the same JSON-normalized payload that encode produces (e.g.
serialize then parse) and validate that normalized payload with validateSchema
instead of doing a blind cast; update encode to continue using
JSON.stringify(value) and implement encodeJson to run
JSON.parse(JSON.stringify(value)) → validateSchema(...) → return the validated
JsonValue (or throw if validation fails), removing the `as unknown as JsonValue`
cast and ensuring decode/decodeJson both use validateSchema so non-JSON-safe
values are rejected consistently; consider adding an upfront schema check in
arktypeJson if you prefer rejecting non-JSON-safe schemas early.
🪄 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: 22529e4a-f0a8-4eea-b3ac-0fca14b9ed25
📒 Files selected for processing (3)
packages/3-extensions/arktype-json/src/core/arktype-json-codec.tspackages/3-extensions/arktype-json/test/arktype-json-codec.test.tspackages/3-extensions/sql-orm-client/test/filters.test.ts
e3984a8 to
b85db7c
Compare
b85db7c to
d76234c
Compare
…ok (Phase A TA.1-TA.2) The framework emit path renders parameterized output types by consulting `field.type.typeParams` inline. SQL columns authored via a named `storage.types` entry carry a family-specific `typeRef` on the storage column instead, so the inline field has no typeParams and the renderer falls back to the generic `CodecTypes[id][output]` accessor. Add an optional `EmissionSpi.resolveFieldTypeParams(modelName, fieldName, model, contract)` hook so families can recover those typeParams without the framework having to know about target-specific shapes. The hook is consulted only when `field.type.typeParams` is empty; inline typeParams always take precedence. Plumbed through `resolveFieldType`, `generateBothFieldTypesMaps`, and `generateContractDts` (the SPI-aware adapter wraps the hook into a modelName/fieldName closure for the per-field iteration). Phase A of the codec-registry-unification project (AC-9: typeRef-shaped parameterized columns render via the codec's `renderOutputType`).
…Types (Phase A TA.3) `sqlEmission.resolveFieldTypeParams` walks the SQL family-specific storage shape: domain field name → `storage.fields[name].column` → `storage.tables[t].columns[c]` → either inline `typeParams` or a `typeRef` resolved through `storage.types[ref].typeParams`. Returns undefined when any link is missing (column not present, no typeParams, no typeRef). The framework path then falls back to the generic `CodecTypes[id][output]` accessor, preserving today behavior for non-parameterized columns. Mongo and other families that do not use named storage types simply do not implement the optional hook.
…eFieldType (Phase A TA.4) Two new tests on `generateBothFieldTypesMaps`: 1. resolver path: when the domain field has no inline `typeParams`, `resolveFieldTypeParams(modelName, fieldName)` is consulted and the resolved typeParams flow through to the codec's `renderOutputType`. This is the typeRef case that ships in production via the SQL emitter (TA.3). 2. inline precedence (regression guard): when the domain field has inline `typeParams`, those win even if the resolver returns a different value. Pins today shape so a later refactor cannot quietly route inline columns through the family resolver.
…(Phase A TA.5) Two columns flip from the generic `CodecTypes[id][output]` fallback to their codec-rendered output type: - `Post.embedding`: `CodecTypes[pg/vector@1][output] | null` → `Vector<1536> | null` (typeRef Embedding1536, length 1536) - `User.kind`: `CodecTypes[pg/enum@1][output]` → `admin | user` (typeRef user_type, enum values) `contract.json` is byte-identical (the IR was already correct; only the rendering pass changes). All hashes (storage / execution / profile) match pre-fix.
…esis bridge (Phase B TB.1)
Introduce the unified-descriptor types per codec-registry-unification spec
§ Decision:
- CodecDescriptor<P = void> — the unified registration record (codec id +
static metadata + Standard Schema params validator + curried higher-order
factory (P) => (Ctx) => Codec). Covers parameterized codecs (non-empty
P) and non-parameterized codecs (P = void) under one shape.
- Ctx — column context threaded through the curried factory:
{ name; usedAt: ReadonlyArray<{table; column}> }. Supplies named-instance
identity (typeRef) or anonymous-instance / shared sentinel for inline
and non-parameterized columns respectively.
- voidParamsSchema — StandardSchemaV1<void> for the synthesizer.
- synthesizeNonParameterizedDescriptor(codec) — wraps a Codec (with main's
async encode/decode unchanged) into a CodecDescriptor<void> whose
constant factory returns the same shared codec instance for every
column. The bridge keeps non-parameterized codec contributors on the
legacy codecs: slot while the descriptor map remains the single read
surface for codec-id-keyed metadata (TML-2357 retires the bridge).
- 'json-validator' CodecTrait — gates extraction of per-instance validate
from a resolved codec into the JSON-schema validator registry; replaces
the old init-hook-derived materialization path.
Adds @standard-schema/spec dependency. The arktype Type<P> already
implements StandardSchemaV1<P>, so existing parameterized-codec
descriptors satisfy the new paramsSchema slot without code changes.
…istry interfaces (Phase B TB.2-TB.3) Two new registry interfaces consumed at the SQL runtime boundary: - CodecDescriptorRegistry — codec-id-keyed metadata map (descriptorFor(codecId) + values() + byTargetType(targetType)). Single read source for traits / targetTypes / meta. Non-branching for parameterized vs. non-parameterized codec ids. Spec § AC-3. - ContractCodecRegistry — contract-bound dispatch (forColumn(table, column) + forCodecId(codecId)). Built once at context construction by walking storage.tables[].columns[] and resolving each to a per-instance codec. forColumn is the primary path for column-bound encode/decode dispatch; forCodecId is the AC-5-deferred fallback for refs-less DSL-param encode (the carve-out documented in spec § Non-functional constraints, retired by TML-2357). Spec § AC-4. Both registries surface as new fields on ExecutionContext (contractCodecs, codecDescriptors). The legacy codecs: CodecRegistry stays alongside as both the synthesis-bridge input for non-parameterized codecs and the codec-id fallback when the contract walk can't resolve a codec id. The relational-core test fixture (createTestContext) gains stub implementations of the two new registries for tests that don't need full runtime materialization.
…actory shape (Phase B TB.4)
The pgvector parameterized descriptor moves from the predecessor
{codecId, paramsSchema} shape to the unified
{codecId, traits, targetTypes, paramsSchema, renderOutputType, factory}.
The factory returns the same shared codec instance for every (length)
instance — pgvector's encode is parameter-independent (the wire format
[v1,v2,...] doesn't care about declared length), so per-instance
materialization yields the same codec object. The closure is the place
to add per-instance state in the future (e.g. capping wire length to
declared dimension); today it just threads Ctx through unused.
Adds renderOutputType inline on the descriptor as Vector<N> — this
mirrors the codec-object hook today (see ADR 186) and gives the unified
descriptor a single home for emit-path rendering.
… unified factory (Phase B TB.5)
The postgres parameterized JSON descriptors move from
{codecId, paramsSchema, init: (P) => {validate}} to the unified
{codecId, traits, targetTypes, paramsSchema, factory: (P) => (Ctx) => Codec}.
The factory wraps the existing async json/jsonb codec from the legacy
codecs: slot and attaches the compiled JSON-Schema validator as
per-instance state on the resolved codec. The resolved codec also picks
up the new 'json-validator' CodecTrait, which gates the framework's
extractValidator helper that builds the JSON-schema validator registry
from per-column resolved codecs at context-construction time.
The wire-format encode/decode is unchanged (JSON.stringify / JSON.parse),
which is why the AC-5-deferred forCodecId fallback works for encode
without column refs (encode is per-instance-stateless w.r.t. params; only
decode-time validation depends on the compiled validator). Spec
§ Phase B § Risks.
The JsonSchemaValidatorRegistry is unchanged structurally — the runtime
extracts validate from each resolved codec carrying the trait rather than
calling init(typeParams) eagerly, but the registry's get(table.column) →
JsonSchemaValidateFn surface and the decode-time consumer behavior are
preserved. Spec deferred T3.5.12 (full registry deletion) to TML-2357.
…ry into ExecutionContext (Phase B TB.6-TB.8)
Substantive sql-context rewrite to materialize the two new registries:
- buildCodecDescriptorRegistry — combines parameterized descriptors from
contributors with synthesized CodecDescriptor<void> entries auto-lifted
from each contributor's legacy codecs: registry. Parameterized
descriptors take precedence; the descriptor map is the single read
source for codec-id-keyed metadata.
- buildContractCodecRegistry — walks contract.storage.tables[].columns[]
and resolves each column to a per-instance codec through the unified
descriptor map:
- typeRef columns reuse the resolved codec materialized once by
initializeTypeHelpers for the storage.types entry.
- inline-typeParams parameterized columns get descriptor.factory(p)(ctx)
with an anonymous instance ctx.
- non-parameterized columns share one resolved codec per codec id (the
synthesized descriptor's factory is constant).
Returns both the dispatch registry (forColumn / forCodecId) and the
derived JSON-schema validator registry — extracted from each resolved
codec carrying the 'json-validator' trait.
- initializeTypeHelpers now invokes the unified factory(validatedParams)(ctx)
rather than the legacy init(validatedParams) hook. context.types stores
the resolved codec for typed instances (or the raw StorageTypeInstance
when no parameterized descriptor matches the codec id).
- validateTypeParams switches from arktype's callable Type<P> shape to
Standard Schema's ~standard.validate, with a sync-only assertion (we
reject Promise-returning validators with RUNTIME.TYPE_PARAMS_INVALID).
arktype Types implement StandardSchemaV1 so existing descriptors keep
working.
- RuntimeParameterizedCodecDescriptor<P> aliases the framework's
CodecDescriptor<P>; the predecessor THelper type parameter retires
along with init.
ExecutionContext gains contractCodecs: ContractCodecRegistry and
codecDescriptors: CodecDescriptorRegistry alongside the existing
codecs: CodecRegistry (kept for the synthesis bridge to consume from
non-parameterized contributors).
Updates the test fixtures in parameterized-types.test.ts and
json-schema-validation.test.ts to use the unified factory shape instead
of init. The "init hook for type helpers" describe block is renamed
"factory for type helpers" and the assertions verify
context.types[typeName] receives the resolved codec from
factory(validatedParams)(ctx).
Spec ACs: AC-1 (parameterized portion via TB.4 / TB.5 plus this commit's
synthesis bridge for non-parameterized codecs), AC-3, AC-4.
…torFor (Phase B TB.9) Migrate the four metadata read sites from context.codecs.traitsOf / context.codecs.values to context.codecDescriptors.descriptorFor / context.codecDescriptors.values: - model-accessor.ts: trait-gated extension-operation registration (iterating descriptors instead of legacy registry codecs), per-column trait read for comparison-method gating, and return-type trait read for predicate detection. - filters.ts: equality-trait gate for relation shorthand filters. The descriptor map is non-branching for parameterized vs. non-parameterized codec ids — every codec, parameterized or synthesized, exposes traits via descriptorFor(codecId).traits. Spec § AC-3. Updates the model-accessor trait-gating tests to also override context.codecDescriptors when overriding context.codecs (the trait read now consults the descriptor map, not the legacy registry).
… descriptor map (Phase B TB.10) validateContractCodecMappings / validateCodecRegistryCompleteness gain a union-typed registry parameter (CodecRegistry | CodecDescriptorRegistry) and adapt the descriptor registry into the same has(id) shape internally. SqlRuntimeImpl now passes context.codecDescriptors at startup-validate and on-first-use, consistent with TB.9's metadata-read migration: the descriptor map is the single source of truth for codec-id-keyed reads. Backwards-compatible at the API surface — existing CodecRegistry callers still work — but the production callsites (sql-runtime.ts) move to the descriptor map.
…Registry (Phase B TB.11-TB.12) decoding.ts:resolveRowCodec now consults contractCodecs.forColumn(table, column) first when a column ref is available for the alias (refs are plumbed via plan.meta.refs.columns and projection mappings), falling back to forCodecId(codecId) and finally to the legacy CodecRegistry.get for codec ids the contract walk couldn't resolve. The per-column path delivers per-instance state on the resolved codec — for JSON-with-schema columns, the validate function attached at materialization is exercised during decode-time JSON-Schema validation. encoding.ts:resolveParamCodec consults contractCodecs.forCodecId(codecId) first, falling back to the legacy registry. ParamRef.refs is not on ParamDescriptor today, so encode-side dispatch is codec-id-only — the AC-5-deferred carve-out documented in the spec § Non-functional constraints. For Phase B's parameterized codecs (pgvector, postgres json/jsonb), encode is per-instance-stateless w.r.t. params, so the codec-id-keyed lookup yields a structurally equivalent encoder. TML-2357 retires the fallback by threading ParamRef.refs through column-bound construction sites. Both contractCodecs and the legacy codecs registry are threaded through encodeParams / encodeParam / decodeRow / decodeField (contractCodecs as optional last argument; existing tests passing only the legacy registry keep working).
…or map, and SQL emitter typeRef-resolver (Phase B TB.13 + Phase A F01)
Adds two new test files:
- packages/2-sql/5-runtime/test/contract-codec-registry.test.ts: 12 tests
covering both Phase B registries:
- ContractCodecRegistry.forColumn returns the per-instance codec for
inline-typeParams parameterized columns.
- typeRef columns sharing one named storage type share one codec
instance (per-instance state survives across the column set).
- Non-parameterized columns share one codec instance per codec id.
- forColumn returns undefined for unknown columns; forCodecId returns
undefined for unknown codec ids.
- forCodecId surfaces the legacy CodecRegistry codec for non-
parameterized codec ids.
- CodecDescriptorRegistry.descriptorFor returns the parameterized
descriptor for parameterized codec ids and the synthesized
descriptor for non-parameterized codec ids — same call shape, no
branching at the read site.
- values() iterates every registered descriptor; byTargetType returns
descriptors indexed by target type.
- packages/2-sql/3-tooling/emitter/test/emitter-hook.typeref-resolver.test.ts:
Phase A reviewer's F01 follow-up. Two integration tests calling
generateContractDts(ir, sqlEmission, ...) end-to-end with a contract
whose post.embedding is a typeRef'd parameterized column referencing
storage.types.Embedding1536. Confirms the SQL resolver
(sqlEmission.resolveFieldTypeParams) walks the storage to the named
instance's typeParams and that the framework emit path consults the
codec's renderOutputType to render Vector<1536>. A second test pins
inline-typeParams precedence (regression guard for the resolver path).
Tighter feedback loop than the demo round-trip; lives at the SQL
emitter package boundary so future regressions surface here first.
…? as TML-2357 retirement targets (Phase B F03) The adapter-level Codec.init? slot and the CodecParamsDescriptor type both still ship the predecessor "init hook" framing in JSDoc despite Phase B's runtime migration to the unified factory shape. Reviewer's F03: add 2-line notes naming each as legacy adapter-level surface and pointing at TML-2357 (T3.5.2 / T3.5.4) for retirement. The runtime descriptor (RuntimeParameterizedCodecDescriptor in @prisma-next/sql-runtime) is already on factory: (P) => (Ctx) => Codec; this commit just keeps the docs accurate at the relational-core boundary where adapter compile-time validation still consumes CodecParamsDescriptor. No behavior change.
…lock Project 1 scope
Promotes cipherstash-extension and middleware-param-transform from standalone
projects into the cipherstash-integration umbrella, and adds two new task
specs covering the PSL constructor surface and migration factories.
Project 1 scope is locked end-to-end-tested: EncryptedString only (3 argument
shapes, nullable + non-nullable), eq + ilike operators, EQL bundle install via
databaseDependencies.init, hand-authored migration.ts using rawSql({...}) for
EQL search-config installation. Other column types (Number/Date/Boolean/Json),
other operator families (orderAndRange, searchableJson), and planner-driven
per-column DDL are deferred to Project 2.
Key design corrections vs the prior drafts:
- Codec descriptor uses post-#402 RuntimeParameterizedCodecDescriptor<P> with
arktype-validated params (mirrors pgvector's length plumbing).
- PSL surface is namespaced constructors (cipherstash.EncryptedString(...)),
not attribute form (@cipherstash.encrypted(...)) — attributes can't couple
legal arguments to the field's scalar type at the grammar level.
- Migration factories ride on the pre-existing Postgres rawSql({...}) escape
hatch with operationClass: 'additive', not DataTransformOperation. PR #404
is therefore an indirect (Project-2-only) dependency, not Project 1.
…h middleware-param-transform cross-refs Rewrites envelope-codec-extension.spec.md against the post-#402 codec API and the locked Project 1 scope: - Codec uses RuntimeParameterizedCodecDescriptor<P> with arktype paramsSchema for { equality, freeTextSearch }, registered separately from the codec body itself (mirrors pgvector's plumbing for length). - Constrains the column-type surface to EncryptedString only (3 argument shapes, nullable + non-nullable). Removes EncryptedJson, EncryptedNumber, and other types from scope — those land in Project 2 alongside their codec round-trip / search-operator / migration tests. - Adds the EQL bundle install via databaseDependencies.init, sourced from the first-attempt repo's eql-bundle.ts. Same shape pgvector uses for CREATE EXTENSION vector. - Adds operator lowering for eq and ilike, deferring the canonical SQL function names to the first-attempt's operation-templates.ts. - Native type is eql_v2_encrypted (not text), reflecting EQL's actual storage type. - Acceptance criteria expanded to cover end-to-end live-Postgres+EQL tests for round-trip, bulk amortization, nullable handling, and cancellation. Refreshes middleware-param-transform.spec.md cross-references: - Path depth bumped (../../ → ../../../) for the new specs/ subdirectory location. - Adds back-reference to the umbrella spec. - Updates the cipherstash-extension cross-reference to point at the new envelope-codec-extension.spec.md path. - Annotates ADR 207 reference as forthcoming with PR #400.
… with high-level plan Restructure the cipherstash-integration project from a single-spec layout into a three-component umbrella: - project-1/: searchable-encryption MVP (the previous umbrella spec rescoped as Project 1, plus its 5 task specs moved under specs/) - project-2/: planner-driven DDL + expanded surface (new stub) - sql-raw-factory/: public raw\`...\` template-literal factory (moved from projects/sql-raw-factory/) New artifacts at the umbrella level: - spec.md: scope of the umbrella, why three components, cross-component design decisions (RawSqlExpr ownership, DataTransformOperation choice, end-to-end-tested-only scope), in-flight framework dependency status (PRs #400/#402 merged 2026-05-01; #404/#409 still open). - plan.md: component-level sequencing. Phase A is Project 1 (critical path, gated externally on #404 + #409); phase B is sql-raw-factory and Project 2 in parallel afterwards, each with its own gating story (sql-raw-factory blocks on Project 1's RawSqlExpr AST node landing; Project 2 blocks on Project 1 + TML-2338 + TML-2339). Project 1's spec is reframed: drop "this is the umbrella" language, add a header pointing to the new umbrella, repath all relative references for the new directory depth (3-up from project-1/, 4-up from project-1/specs/, 3-up from sql-raw-factory/). Resolve the previously- open question about Project 2's on-disk slug. No content changes to the per-task specs beyond reference repaths.
…lock Project 1 scope
Promotes cipherstash-extension and middleware-param-transform from standalone
projects into the cipherstash-integration umbrella, and adds two new task
specs covering the PSL constructor surface and migration factories.
Project 1 scope is locked end-to-end-tested: EncryptedString only (3 argument
shapes, nullable + non-nullable), eq + ilike operators, EQL bundle install via
databaseDependencies.init, hand-authored migration.ts using rawSql({...}) for
EQL search-config installation. Other column types (Number/Date/Boolean/Json),
other operator families (orderAndRange, searchableJson), and planner-driven
per-column DDL are deferred to Project 2.
Key design corrections vs the prior drafts:
- Codec descriptor uses post-#402 RuntimeParameterizedCodecDescriptor<P> with
arktype-validated params (mirrors pgvector's length plumbing).
- PSL surface is namespaced constructors (cipherstash.EncryptedString(...)),
not attribute form (@cipherstash.encrypted(...)) — attributes can't couple
legal arguments to the field's scalar type at the grammar level.
- Migration factories ride on the pre-existing Postgres rawSql({...}) escape
hatch with operationClass: 'additive', not DataTransformOperation. PR #404
is therefore an indirect (Project-2-only) dependency, not Project 1.
…h middleware-param-transform cross-refs Rewrites envelope-codec-extension.spec.md against the post-#402 codec API and the locked Project 1 scope: - Codec uses RuntimeParameterizedCodecDescriptor<P> with arktype paramsSchema for { equality, freeTextSearch }, registered separately from the codec body itself (mirrors pgvector's plumbing for length). - Constrains the column-type surface to EncryptedString only (3 argument shapes, nullable + non-nullable). Removes EncryptedJson, EncryptedNumber, and other types from scope — those land in Project 2 alongside their codec round-trip / search-operator / migration tests. - Adds the EQL bundle install via databaseDependencies.init, sourced from the first-attempt repo's eql-bundle.ts. Same shape pgvector uses for CREATE EXTENSION vector. - Adds operator lowering for eq and ilike, deferring the canonical SQL function names to the first-attempt's operation-templates.ts. - Native type is eql_v2_encrypted (not text), reflecting EQL's actual storage type. - Acceptance criteria expanded to cover end-to-end live-Postgres+EQL tests for round-trip, bulk amortization, nullable handling, and cancellation. Refreshes middleware-param-transform.spec.md cross-references: - Path depth bumped (../../ → ../../../) for the new specs/ subdirectory location. - Adds back-reference to the umbrella spec. - Updates the cipherstash-extension cross-reference to point at the new envelope-codec-extension.spec.md path. - Annotates ADR 207 reference as forthcoming with PR #400.
… with high-level plan Restructure the cipherstash-integration project from a single-spec layout into a three-component umbrella: - project-1/: searchable-encryption MVP (the previous umbrella spec rescoped as Project 1, plus its 5 task specs moved under specs/) - project-2/: planner-driven DDL + expanded surface (new stub) - sql-raw-factory/: public raw\`...\` template-literal factory (moved from projects/sql-raw-factory/) New artifacts at the umbrella level: - spec.md: scope of the umbrella, why three components, cross-component design decisions (RawSqlExpr ownership, DataTransformOperation choice, end-to-end-tested-only scope), in-flight framework dependency status (PRs #400/#402 merged 2026-05-01; #404/#409 still open). - plan.md: component-level sequencing. Phase A is Project 1 (critical path, gated externally on #404 + #409); phase B is sql-raw-factory and Project 2 in parallel afterwards, each with its own gating story (sql-raw-factory blocks on Project 1's RawSqlExpr AST node landing; Project 2 blocks on Project 1 + TML-2338 + TML-2339). Project 1's spec is reframed: drop "this is the umbrella" language, add a header pointing to the new umbrella, repath all relative references for the new directory depth (3-up from project-1/, 4-up from project-1/specs/, 3-up from sql-raw-factory/). Resolve the previously- open question about Project 2's on-disk slug. No content changes to the per-task specs beyond reference repaths.
… descriptor (M2.a AC-CODEC1..5)
`createCipherstashStringCodec(sdk)` builds the SQL codec via the
existing `codec({ ... })` factory in
`@prisma-next/sql-relational-core/ast`:
- `typeId: "cipherstash/string@1"`, `targetTypes:
["eql_v2_encrypted"]`, `traits: ["equality"]`, and
`meta.db.sql.postgres.nativeType: "eql_v2_encrypted"` (AC-CODEC1).
- `decode(wire, ctx)` requires `ctx.column` and constructs an
`EncryptedString.fromInternal({ciphertext, table, column, sdk})`
capturing the codec`s SDK reference for read-side single-cell
decrypt (AC-CODEC2).
- `encode(envelope, ctx)` reads the ciphertext from the
envelope`s handle and surfaces a clear error if the bulk-encrypt
middleware did not run before encode (AC-CODEC3).
- `renderOutputType` returns `"EncryptedString"` (AC-CODEC4).
The codec is constructed *per SDK binding*, not as a module
singleton: cipherstash`s codec depends on the SDK at decode time,
so multi-tenant deployments construct one extension descriptor per
tenant, each with its own captured SDK. This differs from
pgvector (whose codec is fully stateless and can be a module
singleton).
`createParameterizedCodecDescriptors(sdk)` exposes the
`RuntimeParameterizedCodecDescriptor<{equality, freeTextSearch}>`
shape via the unified post-#402 model in `@prisma-next/sql-runtime`:
- `paramsSchema` is an arktype `{equality: boolean,
freeTextSearch: boolean}` schema validated at the JSON boundary
(AC-CODEC5).
- `factory(params)(ctx)` returns the shared codec — the
search-mode flags do not affect the per-cell encode body on the
write side (the middleware did the actual encryption); they
affect operator lowering and the migration factories (M3/M4).
Future per-instance state can move into the closure without
changing the descriptor shape.
`createCipherstashRuntimeDescriptor({ sdk })` assembles a
`SqlRuntimeExtensionDescriptor<"postgres">` mirroring pgvector`s
`runtime.ts`: codec registry, `parameterizedCodecs`,
`types.codecTypes.codecInstances`, `create()` returning the SQL
extension instance.
Tests:
- `test/codecs.test.ts` exercises AC-CODEC1..4 (registration
shape, decode reads ctx.column, encode reads the handle, error
when ctx.column is missing or ciphertext is empty,
renderOutputType).
- `test/runtime.test.ts` exercises AC-CODEC5 (descriptor list
shape, params-schema acceptance/rejection, factory wiring).
Phase: M2.a (cipherstash-integration / project-1).
Signed-off-by: Will Madden <[email protected]>
VerdictSolid design, real correctness bugs in the runtime path. The ADR is thorough and honest. The arktype-json extension as shipped is broken on the happy path: ordinary writes and reads will fail before the codec ever encodes/decodes anything. One ADR claim ("no-emit P1 — correctness1. arktype-json codec metadata isn't registered at runtime. 2. P2 — visible behavior3. 4. ADR claim doesn't match the no-emit resolver. ADR 208 line 116: "`FieldOutputType` follows `typeRef` through `storage.types`, then synthetically applies `CodecInstanceContext` to the column's `type` slot at the type level and reads the `Js` parameter off the resulting `Codec<…, Js>`." sql-contract-ts still resolves through `CodecTypesFromDefinition[codecId]['output']`, and `arktype-json`'s codec-types map uses `unknown`. Users who import the TS contract directly get `unknown`, not the schema's inferred shape. Either implement the resolver and update the codec-types map, or downgrade the ADR text to "emit-only today, no-emit tracked under TML-2357" and update `9. No-Emit Workflow.md` to match. Other concerns (lower stakes)
Bottom lineP1s are blocking — the extension as merged doesn't function end-to-end for writes or reads of arktype-json columns under typical Postgres driver behavior. P2 #3 means the documented stable error contract is broken on the new path. P2 #4 means at least one ADR guarantee overstates what shipped. The architectural direction is right; the landing has correctness bugs that integration tests with a real driver and a real write/read round-trip should have caught. |
…lock Project 1 scope
Promotes cipherstash-extension and middleware-param-transform from standalone
projects into the cipherstash-integration umbrella, and adds two new task
specs covering the PSL constructor surface and migration factories.
Project 1 scope is locked end-to-end-tested: EncryptedString only (3 argument
shapes, nullable + non-nullable), eq + ilike operators, EQL bundle install via
databaseDependencies.init, hand-authored migration.ts using rawSql({...}) for
EQL search-config installation. Other column types (Number/Date/Boolean/Json),
other operator families (orderAndRange, searchableJson), and planner-driven
per-column DDL are deferred to Project 2.
Key design corrections vs the prior drafts:
- Codec descriptor uses post-#402 RuntimeParameterizedCodecDescriptor<P> with
arktype-validated params (mirrors pgvector's length plumbing).
- PSL surface is namespaced constructors (cipherstash.EncryptedString(...)),
not attribute form (@cipherstash.encrypted(...)) — attributes can't couple
legal arguments to the field's scalar type at the grammar level.
- Migration factories ride on the pre-existing Postgres rawSql({...}) escape
hatch with operationClass: 'additive', not DataTransformOperation. PR #404
is therefore an indirect (Project-2-only) dependency, not Project 1.
…h middleware-param-transform cross-refs Rewrites envelope-codec-extension.spec.md against the post-#402 codec API and the locked Project 1 scope: - Codec uses RuntimeParameterizedCodecDescriptor<P> with arktype paramsSchema for { equality, freeTextSearch }, registered separately from the codec body itself (mirrors pgvector's plumbing for length). - Constrains the column-type surface to EncryptedString only (3 argument shapes, nullable + non-nullable). Removes EncryptedJson, EncryptedNumber, and other types from scope — those land in Project 2 alongside their codec round-trip / search-operator / migration tests. - Adds the EQL bundle install via databaseDependencies.init, sourced from the first-attempt repo's eql-bundle.ts. Same shape pgvector uses for CREATE EXTENSION vector. - Adds operator lowering for eq and ilike, deferring the canonical SQL function names to the first-attempt's operation-templates.ts. - Native type is eql_v2_encrypted (not text), reflecting EQL's actual storage type. - Acceptance criteria expanded to cover end-to-end live-Postgres+EQL tests for round-trip, bulk amortization, nullable handling, and cancellation. Refreshes middleware-param-transform.spec.md cross-references: - Path depth bumped (../../ → ../../../) for the new specs/ subdirectory location. - Adds back-reference to the umbrella spec. - Updates the cipherstash-extension cross-reference to point at the new envelope-codec-extension.spec.md path. - Annotates ADR 207 reference as forthcoming with PR #400.
… with high-level plan Restructure the cipherstash-integration project from a single-spec layout into a three-component umbrella: - project-1/: searchable-encryption MVP (the previous umbrella spec rescoped as Project 1, plus its 5 task specs moved under specs/) - project-2/: planner-driven DDL + expanded surface (new stub) - sql-raw-factory/: public raw\`...\` template-literal factory (moved from projects/sql-raw-factory/) New artifacts at the umbrella level: - spec.md: scope of the umbrella, why three components, cross-component design decisions (RawSqlExpr ownership, DataTransformOperation choice, end-to-end-tested-only scope), in-flight framework dependency status (PRs #400/#402 merged 2026-05-01; #404/#409 still open). - plan.md: component-level sequencing. Phase A is Project 1 (critical path, gated externally on #404 + #409); phase B is sql-raw-factory and Project 2 in parallel afterwards, each with its own gating story (sql-raw-factory blocks on Project 1's RawSqlExpr AST node landing; Project 2 blocks on Project 1 + TML-2338 + TML-2339). Project 1's spec is reframed: drop "this is the umbrella" language, add a header pointing to the new umbrella, repath all relative references for the new directory depth (3-up from project-1/, 4-up from project-1/specs/, 3-up from sql-raw-factory/). Resolve the previously- open question about Project 2's on-disk slug. No content changes to the per-task specs beyond reference repaths.
Three sections still reflected the pre-PR-418 state of the world: - "Type fidelity end-to-end" claimed `vector(1536)` and `arktypeJson(schema)` resolve in the no-emit path. They don't — the resolver wiring is tracked under TML-2357 and the partial- status block earlier in the ADR already says so. Update the consequence to match. - "Encode-side `forCodecId` legacy fallback" said arktype-json's encode is `JSON.stringify` (true) and that the fallback works because encode is per-instance-stateless w.r.t. params. The PR-418 review surfaced that this required keeping encode schema-independent, which is now an explicit design choice. Add the `encodeIsParamsIndependent` flag mechanism that lets multi- column contracts work pre-AC-5. - "Per-library JSON extensions" section said the descriptor's factory "validates internally in `decode`". Make the asymmetry explicit: validation runs on decode only; encode is `JSON.stringify` with no schema check, matching the validate-on-read philosophy. - "Resolves" bullet for TML-2229 claimed both no-emit AND emit paths resolve correctly. Only emit ships in #402; no-emit waits for TML-2357. Split the bullet to reflect the partial state. These updates close Codex's F03. The previously-added partial-status block at § "No-emit type resolution" stays — this commit just brings the rest of the ADR into agreement with it. Refs Codex review of #418 (F03).
Postgres `pg` returns `jsonb` cells as already-parsed JS values by default. The arktype-json codec was hardcoded to `JSON.parse(wire)` and would SyntaxError on every read where the driver pre-parsed. Mirror `pgJsonbCodec`'s `string | JsonValue` tolerance so selects against arktypeJson columns work end-to-end. Widens `ArktypeJsonCodec`'s `TWire` from `string` to `string | JsonValue` to match the runtime tolerance. Adds two test cases covering both wire shapes for `decode`. Refs #402 review (P1 #2).
… lookup The arktype-json runtime descriptor did not expose `types.codecTypes.codecInstances`, so the postgres adapter's `extractCodecLookup` (called at execution time, not control time) had no entry for `arktype/json@1`. The first query touching an arktypeJson column failed in `renderTypedParam` with "assembled codec lookup has no entry" before encode/decode dispatch ever ran. pgvector's runtime descriptor already follows the correct pattern. Two changes: 1. `arktypeJsonRuntimeDescriptor.types.codecTypes.codecInstances` surfaces `arktypeJsonEmitCodec` so the runtime cast lookup resolves. 2. `arktypeJsonEmitCodec` now carries `meta.db.sql.postgres.nativeType = 'jsonb'`. The framework `Codec` type doesn't expose `meta`; switch the declaration to the SQL `Codec` extension which does. Without this, `renderTypedParam` would emit `$N` instead of `$N::jsonb` — and `jsonb` is deliberately excluded from `POSTGRES_INFERRABLE_NATIVE_TYPES`, so the cast is required for filter expressions. Renames the codec from "emit-only shim" to "metadata-only stub" to reflect that it now serves both emit-path renderOutputType lookup AND runtime cast policy. Encode/decode are still sentinels that throw if invoked — runtime materialization goes through the unified descriptor map's `factory(params)(ctx)`. Adds three regression assertions in `extension-descriptors.test.ts` covering: presence in `codecInstances`, resolution through `extractCodecLookup`, and the `jsonb` native-type metadata field. Refs #402 review (P1 #1).
…ugh codec.decode ADR 208 § Case J says per-library JSON-with-schema codecs (e.g. `arktype/json@1`) validate inside `decode` and surface the stable `RUNTIME.JSON_SCHEMA_VALIDATION_FAILED` code unchanged. The runtime did not honor that contract: `decodeField` caught all `codec.decode` errors and rewrapped them as `RUNTIME.DECODE_FAILED`. The rethrow guard for the schema-validation code only existed for the legacy post-decode `validateJsonValue` path. Add the same guard to the codec-decode catch arm. Adds a regression test in `json-schema-validation.test.ts` that registers a stub codec whose `decode` throws `RUNTIME.JSON_SCHEMA_VALIDATION_FAILED` and asserts the code passes through `decodeRow` unchanged. Refs #402 review (P2 #3).
…-implemented ADR 208 § "No-emit type resolution" and the No-Emit Workflow subsystem described `FieldOutputType` as following `typeRef` and applying the column's authoring-time `type` slot to produce `Vector<1536>` and arktype- schema-shaped types in no-emit mode. The resolver isn't wired up: `@prisma-next/sql-contract-ts`'s `FieldOutputType` resolves through `CodecTypesFromDefinition[codecId]['output']` only, and the arktype-json codec-types map declares the `arktype/json@1` `output` as `unknown`. So authors who skip `pnpm emit` get codec-base types, not the parameterized refinements that emit produces. Mark the resolver as not-yet-implemented in the ADR, the no-emit subsystem, and the arktype-json README. Reference TML-2357 for tracked follow-up. The eventual target shape stays in the docs as the design intent — what changed is the status, not the design. Refs #402 review (P2 #4).
…ent round-trip stability The codec's emit-path output is derived from `schema.expression`. Runtime rehydration via `ark.schema(typeParams.jsonIr)` reproduces that string only as long as arktype's IR-to-expression rendering doesn't change. A minor or major arktype bump can therefore stale-render existing `contract.json` blobs without a corresponding re-emit. Pin the dependency to `~2.1.29` (patch range only) and add a "Compatibility" section to the README explaining the invariant and what consumers should do when they bump arktype outside this range. Refs #402 review (other concerns — arktype version pinning).
Previously, when the rehydrated schema's `expression` didn't match `typeParams.expression`, the factory emitted a `console.warn` and kept going. The branch was wrapped in `c8 ignore`, which made it untested. Two problems with the warning approach. First, by the time the runtime materializes the codec, the bad `contract.d.ts` has already been emitted and shipped — a runtime warning fires after the wrong types are in consumer code. Second, the expression-vs-rehydrated round-trip is exactly the invariant the package's arktype version pin protects. A silent warning is the wrong response when the invariant breaks. Throw `RUNTIME.TYPE_PARAMS_INVALID` instead, with a message that points the caller at re-running `pnpm emit`. Removes the `c8 ignore` so the branch is testable; adds two tests (one for divergence, one for the matching happy path). Refs #402 review (other concerns — expression divergence handler).
Three sections still reflected the pre-PR-418 state of the world: - "Type fidelity end-to-end" claimed `vector(1536)` and `arktypeJson(schema)` resolve in the no-emit path. They don't — the resolver wiring is tracked under TML-2357 and the partial- status block earlier in the ADR already says so. Update the consequence to match. - "Encode-side `forCodecId` legacy fallback" said arktype-json's encode is `JSON.stringify` (true) and that the fallback works because encode is per-instance-stateless w.r.t. params. The PR-418 review surfaced that this required keeping encode schema-independent, which is now an explicit design choice. Add the `encodeIsParamsIndependent` flag mechanism that lets multi- column contracts work pre-AC-5. - "Per-library JSON extensions" section said the descriptor's factory "validates internally in `decode`". Make the asymmetry explicit: validation runs on decode only; encode is `JSON.stringify` with no schema check, matching the validate-on-read philosophy. - "Resolves" bullet for TML-2229 claimed both no-emit AND emit paths resolve correctly. Only emit ships in #402; no-emit waits for TML-2357. Split the bullet to reflect the partial state. These updates close Codex's F03. The previously-added partial-status block at § "No-emit type resolution" stays — this commit just brings the rest of the ADR into agreement with it. Refs Codex review of #418 (F03).
The "writes succeed, reads enforce" test failed in CI: I missed that `db.orm.Embedding.create` returns a decoded row via `RETURNING`, so schema enforcement happens during create itself rather than on a subsequent read. There's no single ORM call that cleanly demonstrates the validate-on-read contract end-to-end without raw-SQL bypass infrastructure the fixture doesn't expose. Drop the failing case. Decode-side schema rejection is already covered at: - arktype-json unit tests (decode rejects pre-parsed payloads that violate the schema, decode rejects pre-parsed primitives that violate the schema) - sql-runtime json-schema-validation tests (runtime preserves RUNTIME.JSON_SCHEMA_VALIDATION_FAILED thrown from codec.decode without rewrapping) The happy-path e2e round-trip stays as the single end-to-end smoke test; it exercises the full encode → cast lookup → driver write → driver read (pre-parsed jsonb) → decode pipeline that originally shipped broken in #402.
… (M2 R1 T2.3; AC-CODEC1..5) Re-author of PR #416 commit fab1593 against the TML-2397 package shape, plus the wire-format fix from commit 1bd1a36 applied directly to the encode/decode paths. `createCipherstashStringCodec(sdk)` builds the SQL codec via the existing `codec({...})` factory in `@prisma-next/sql-relational-core/ast`: - `typeId: cipherstash/string@1`, `targetTypes: [eql_v2_encrypted]`, `traits: [equality]`, and `meta.db.sql.postgres.nativeType: eql_v2_encrypted` (AC-CODEC1). - `decode(wire, ctx)` requires `ctx.column` and constructs an `EncryptedString.fromInternal({ ciphertext, table, column, sdk })` capturing the codec SDK reference for read-side single-cell decrypt (AC-CODEC2). - `encode(envelope, ctx)` reads the ciphertext from the envelope handle and surfaces a clear error if the bulk-encrypt middleware did not run before encode (AC-CODEC3). - `renderOutputType` returns `EncryptedString` (AC-CODEC4). The codec is recreated per SDK binding rather than as a module singleton because cipherstash depends on the SDK at decode time; multi-tenant deployments construct one extension instance per tenant each with its own captured SDK. Wire-format fix: EQL defines `eql_v2_encrypted` as `CREATE TYPE eql_v2_encrypted AS (data jsonb)` — a Postgres composite type, not a domain over jsonb. The default `pg` driver encodes JS objects as JSON which Postgres then rejects when coercing into the composite. Encode wraps the ciphertext payload in the composite literal `("...escaped JSON...")`; decode unwraps the same shape and also accepts the pre- parsed `{ data: ... }` row some pg clients return. Mirrors the reference Drizzle integration. `createParameterizedCodecDescriptors(sdk)` exposes the `RuntimeParameterizedCodecDescriptor<{ equality, freeTextSearch }>` shape via the unified post-#402 model in `@prisma-next/sql-runtime` (AC-CODEC5): - `paramsSchema` is an arktype `{ equality: boolean, freeTextSearch: boolean }` schema validated at the JSON boundary. - `factory(params)(ctx)` returns the shared codec — the search-mode flags do not affect the per-cell encode body on the write side (the middleware does the actual encryption); they affect operator lowering (M3) and the codec lifecycle hook on the control plane. Future per-instance state can move into the closure without changing the descriptor shape. The `./runtime` entry point now re-exports `EncryptedString`, the `CipherstashSdk` type surface, the codec factory, the parameterized- descriptor list, and the params schema. The control plane in `./control` (TML-2397 stub) is untouched in this round; the codec hook flag-name alignment is deferred to a later round (T2.9). Adds `@prisma-next/sql-relational-core`, `@prisma-next/sql-runtime` and `arktype` (catalog) as workspace deps; mirrors the dep wiring in `packages/3-extensions/pgvector/package.json`. Phase: M2 R1 (cipherstash-integration / project-1).
Brings forward the cipherstash extension from `tml-2373-project-1-on-2397`
adapted to the current `main` framework surface.
Highlights:
- Real ZeroKMS-backed integration via `@cipherstash/stack` (replaces the
earlier reference SDK shim).
- `EncryptedString` envelope using a SecretBox-style `#private` field +
`expose()` + redaction overrides (toString / valueOf / inspect / JSON).
See README + `src/execution/envelope.ts`.
- PSL + TS authoring helpers ship with `equality: true, freeTextSearch:
true` defaults; users opt out explicitly.
- PSL contract source colocated under `src/contract/contract.prisma`;
emitter outputs land alongside as `contract.{json,d.ts}`.
- Bulk-encrypt middleware lifts envelope ciphertexts via the new
`SqlParamRefMutator` seam (added in earlier framework commits).
Adaptation against current `main`:
- Codec rewritten as `CipherstashStringCodec extends CodecImpl` (matches
the post-#402 unified `CodecDescriptor` / `CodecImpl` surface). The
legacy `codec({...})` helper removal is absorbed here.
- `RuntimeParameterizedCodecDescriptor` carries the new
`isParameterized: true` field.
- `exports/control.ts` uses `ContractSpace<Contract<SqlStorage>>` and
`OnDiskMigrationPackage` (replaces the removed `ExtensionContractSpace`
type and `MigrationPackage.dirPath`).
- `exports/runtime.ts` ships codec descriptors via
`types.codecTypes.codecDescriptors` (replaces removed
`codecInstances` slot).
- The `cipherstash:string@1` codec lifecycle hook (`onFieldEvent`) is
typed against the current `SqlMigrationPlanOperation<unknown>[]` SPI
signature; the `*Call` classes already satisfy that shape
structurally. The CR-1 OpFactoryCall promotion (postgres planner
dispatch on `operationClass`) is deferred — without it, cipherstash
contributions render as `rawSql({...})` blocks in `migration.ts`
instead of factory calls. See `projects/cipherstash-integration/
project-1-rebase-followups.md`.
Tests are excluded from `tsconfig.json` for this commit; substantial
test surface is broken against the current framework state and will be
restored as a follow-up.
Adds `[email protected]` to `trustPolicyExclude` (transitive dep of
`@cipherstash/stack`).
Refs: TML-2373
Brings forward the cipherstash extension from `tml-2373-project-1-on-2397`
adapted to the current `main` framework surface.
Highlights:
- Real ZeroKMS-backed integration via `@cipherstash/stack` (replaces the
earlier reference SDK shim).
- `EncryptedString` envelope using a SecretBox-style `#private` field +
`expose()` + redaction overrides (toString / valueOf / inspect / JSON).
See README + `src/execution/envelope.ts`.
- PSL + TS authoring helpers ship with `equality: true, freeTextSearch:
true` defaults; users opt out explicitly.
- PSL contract source colocated under `src/contract/contract.prisma`;
emitter outputs land alongside as `contract.{json,d.ts}`.
- Bulk-encrypt middleware lifts envelope ciphertexts via the new
`SqlParamRefMutator` seam (added in earlier framework commits).
Adaptation against current `main`:
- Codec rewritten as `CipherstashStringCodec extends CodecImpl` (matches
the post-#402 unified `CodecDescriptor` / `CodecImpl` surface). The
legacy `codec({...})` helper removal is absorbed here.
- `RuntimeParameterizedCodecDescriptor` carries the new
`isParameterized: true` field.
- `exports/control.ts` uses `ContractSpace<Contract<SqlStorage>>` and
`OnDiskMigrationPackage` (replaces the removed `ExtensionContractSpace`
type and `MigrationPackage.dirPath`).
- `exports/runtime.ts` ships codec descriptors via
`types.codecTypes.codecDescriptors` (replaces removed
`codecInstances` slot).
- The `cipherstash:string@1` codec lifecycle hook (`onFieldEvent`) is
typed against the current `SqlMigrationPlanOperation<unknown>[]` SPI
signature; the `*Call` classes already satisfy that shape
structurally. The CR-1 OpFactoryCall promotion (postgres planner
dispatch on `operationClass`) is deferred — without it, cipherstash
contributions render as `rawSql({...})` blocks in `migration.ts`
instead of factory calls. See `projects/cipherstash-integration/
project-1-rebase-followups.md`.
Tests are excluded from `tsconfig.json` for this commit; substantial
test surface is broken against the current framework state and will be
restored as a follow-up.
Adds `[email protected]` to `trustPolicyExclude` (transitive dep of
`@cipherstash/stack`).
Refs: TML-2373
Brings forward the cipherstash extension from `tml-2373-project-1-on-2397`
adapted to the current `main` framework surface.
Highlights:
- Real ZeroKMS-backed integration via `@cipherstash/stack` (replaces the
earlier reference SDK shim).
- `EncryptedString` envelope using a SecretBox-style `#private` field +
`expose()` + redaction overrides (toString / valueOf / inspect / JSON).
See README + `src/execution/envelope.ts`.
- PSL + TS authoring helpers ship with `equality: true, freeTextSearch:
true` defaults; users opt out explicitly.
- PSL contract source colocated under `src/contract/contract.prisma`;
emitter outputs land alongside as `contract.{json,d.ts}`.
- Bulk-encrypt middleware lifts envelope ciphertexts via the new
`SqlParamRefMutator` seam (added in earlier framework commits).
Adaptation against current `main`:
- Codec rewritten as `CipherstashStringCodec extends CodecImpl` (matches
the post-#402 unified `CodecDescriptor` / `CodecImpl` surface). The
legacy `codec({...})` helper removal is absorbed here.
- `RuntimeParameterizedCodecDescriptor` carries the new
`isParameterized: true` field.
- `exports/control.ts` uses `ContractSpace<Contract<SqlStorage>>` and
`OnDiskMigrationPackage` (replaces the removed `ExtensionContractSpace`
type and `MigrationPackage.dirPath`).
- `exports/runtime.ts` ships codec descriptors via
`types.codecTypes.codecDescriptors` (replaces removed
`codecInstances` slot).
- The `cipherstash:string@1` codec lifecycle hook (`onFieldEvent`) is
typed against the current `SqlMigrationPlanOperation<unknown>[]` SPI
signature; the `*Call` classes already satisfy that shape
structurally. The CR-1 OpFactoryCall promotion (postgres planner
dispatch on `operationClass`) is deferred — without it, cipherstash
contributions render as `rawSql({...})` blocks in `migration.ts`
instead of factory calls. See `projects/cipherstash-integration/
project-1-rebase-followups.md`.
Tests are excluded from `tsconfig.json` for this commit; substantial
test surface is broken against the current framework state and will be
restored as a follow-up.
Adds `[email protected]` to `trustPolicyExclude` (transitive dep of
`@cipherstash/stack`).
Refs: TML-2373
Brings forward the cipherstash extension from `tml-2373-project-1-on-2397`
adapted to the current `main` framework surface.
Highlights:
- Real ZeroKMS-backed integration via `@cipherstash/stack` (replaces the
earlier reference SDK shim).
- `EncryptedString` envelope using a SecretBox-style `#private` field +
`expose()` + redaction overrides (toString / valueOf / inspect / JSON).
See README + `src/execution/envelope.ts`.
- PSL + TS authoring helpers ship with `equality: true, freeTextSearch:
true` defaults; users opt out explicitly.
- PSL contract source colocated under `src/contract/contract.prisma`;
emitter outputs land alongside as `contract.{json,d.ts}`.
- Bulk-encrypt middleware lifts envelope ciphertexts via the new
`SqlParamRefMutator` seam (added in earlier framework commits).
Adaptation against current `main`:
- Codec rewritten as `CipherstashStringCodec extends CodecImpl` (matches
the post-#402 unified `CodecDescriptor` / `CodecImpl` surface). The
legacy `codec({...})` helper removal is absorbed here.
- `RuntimeParameterizedCodecDescriptor` carries the new
`isParameterized: true` field.
- `exports/control.ts` uses `ContractSpace<Contract<SqlStorage>>` and
`OnDiskMigrationPackage` (replaces the removed `ExtensionContractSpace`
type and `MigrationPackage.dirPath`).
- `exports/runtime.ts` ships codec descriptors via
`types.codecTypes.codecDescriptors` (replaces removed
`codecInstances` slot).
- The `cipherstash:string@1` codec lifecycle hook (`onFieldEvent`) is
typed against the current `SqlMigrationPlanOperation<unknown>[]` SPI
signature; the `*Call` classes already satisfy that shape
structurally. The CR-1 OpFactoryCall promotion (postgres planner
dispatch on `operationClass`) is deferred — without it, cipherstash
contributions render as `rawSql({...})` blocks in `migration.ts`
instead of factory calls. See `projects/cipherstash-integration/
project-1-rebase-followups.md`.
Tests are excluded from `tsconfig.json` for this commit; substantial
test surface is broken against the current framework state and will be
restored as a follow-up.
Adds `[email protected]` to `trustPolicyExclude` (transitive dep of
`@cipherstash/stack`).
Refs: TML-2373
Implements ADR 208. 23 commits, five phases, all on top of current
main.Resolves
StagedFieldOutputTypes." Filed as a narrow bug:vector(1536)resolved tonumber[]instead ofVector<1536>,char(36)resolved tostringinstead ofChar<36>, andjsonb(schema)resolved toJsonValueinstead of the schema's narrowed shape, when the contract definition was imported directly without runningpnpm emit. PR feat(codec-model-unification): higher-order codecs end-to-end #390 (closed; superseded by this one) re-scoped the ticket to address the underlying registration model, but was authored against the synchronousCodecinterface that pre-dated ADR 204. This PR carries the same design end-to-end on top of currentmain's async baseline. The original bug closes through the typeRef emit-path SPI fix (Phase A) plus the unified descriptor model (Phases B–E); demo'sPost.embeddingnow rendersVector<1536> | nullandUser.kindrenders'admin' | 'user', matching the no-emitFieldOutputTyperesolver's output.Follow-up work tracked under TML-2357 (the registration-side migration this PR deliberately defers; see § Follow-ups below).
At a glance
A user authors one line of TypeScript:
Three surfaces resolve from that single function call:
Document.embeddingisVector<1536> | null— literal1536preserved.pnpm emitwrites the same type intocontract.d.ts.'[1.2, 3.4, …]'produces a value the type system already namedVector<1536>.The same pattern generalises to JSON-with-schema via per-library extensions:
User.profileresolves to{ name: string; age: number }end-to-end;decodevalidates against the schema at runtime, throwingRUNTIME.JSON_SCHEMA_VALIDATION_FAILEDon a mismatch.Decision
Every codec ships as a single descriptor type:
The runtime exposes two APIs over a unified descriptor map:
descriptorFor(codecId)for codec-id-keyed metadata reads (sql-orm-client trait gating, startup validation, the emit path's renderer lookup) andforColumn(table, column)for column-aware encode/decode dispatch. Both are non-branching — every codec resolves through the same lookup, parameterized or not.Parameterized codecs use non-empty
P. Non-parameterized codecs useP = voidand a constant factory that returns the same shared codec instance for every column. Whether a codec id "is parameterized" stops being a registration-time distinction; it's a property ofPon the descriptor.CodecInstanceContextis family-agnostic ({ name }); SQL-runtime materialization threadsSqlCodecInstanceContext extends CodecInstanceContext, which addsusedAt: ReadonlyArray<{ table; column }>. This mirrors PR #400's already-mergedCodecCallContext/SqlCodecCallContextfamily-extension pattern for the per-call codec context.Why
Two pre-existing problems shaped the design:
The no-emit TypeScript type didn't reflect parameterization for typeRef-shaped columns. Demo's
Post.embedding(a typeRef'dVector(1536)column) rendered asCodecTypes['pg/vector@1']['output']instead ofVector<1536>. The emit-path resolver checkedfield.type.typeParamsinline; for typeRef-shaped columns, typeParams lives on the namedstorage.types[ref]entry, not on the field — so the renderer fell through to the generic accessor. This is the bug TML-2229 originally filed.Parameterized codecs without parameters were structurally meaningless but the legacy registry registered exactly that — placeholder length-1 vector codecs existed solely so codec-id-keyed metadata reads kept working, only functional for codecs whose wire format happened to be parameter-independent. The descriptor map's heterogeneous
Pis the right answer: every codec is described by a descriptor that knows its own params; the runtime materializes a per-instance codec from those params.ADR 186 had already established codec ownership of
renderOutputType; this PR moves it to the descriptor and eliminates the branch. ADR 204 established the async codec runtime baseline; this PR composes cleanly with it (the descriptor's factory returns aCodecwhose async surface is unchanged). ADR 206 established the function-is-signature precedent; this PR applies it to codecs.Phases
The work landed in five phases on top of
main:EmissionSpi.resolveFieldTypeParamshook; SQL emitter implements it by walkingstorage.fields → storage.tables → storage.types; demo'sPost.embeddingrenders correctly. This is the direct fix for TML-2229's filed bug. 4 commits.CodecDescriptor+ContractCodecRegistry+ parameterized-descriptor migration. IntroducesCodecInstanceContext,CodecDescriptor<P = void>,synthesizeNonParameterizedDescriptor,descriptorFor,forColumn. Migrates pgvector + postgres json/jsonb parameterized descriptors frominit: (P) => THelpertofactory: (P) => (ctx: CodecInstanceContext) => Codec. Migrates sql-orm-client metadata reads (4 sites) todescriptorFor. Switches encode/decode dispatch throughforColumn(decode primary; encode falls back toforCodecIdper the AC-5 carve-out). 9 commits.@prisma-next/extension-arktype-jsonextension. New extension package shippingarktypeJson(schema)+arktypeJsonCodec. Codec idarktype/json@1(library-bound). Lossless serialize/rehydrate via arktype's expression + internal IR. Postgres adapter's M3 schema-typed JSON surface deletes (ajv dep dropped). 6 commits.2. Contract Emitter & Types.md,9. No-Emit Workflow.md, four package READMEs. 2 commits.CodecInstanceContextfamily-extension split + ADR renumber. The per-instance context's SQL-specificusedAtfield moves out offramework-componentsinto aSqlCodecInstanceContext extends CodecInstanceContextSQL-domain type, mirroring PR TML-2330: add per-query codec call context + AbortSignal #400'sCodecCallContext/SqlCodecCallContextprecedent. ADR renumbered 207 → 208 (PR TML-2330: add per-query codec call context + AbortSignal #400 / TML-2330 claimed 207 on a parallel branch viacfe1b6dee). 2 commits.Acceptance criteria
CodecDescriptor)06c6c4bcf,ca79ef27c,6470ecc83)b74b1381d,9c4380ddcforColumn)b30c8c412,316319c4aParamRef.refsplumbing)JsonSchemaValidatorRegistrydeletes)07eecfcb5,d8e81a23e, e2e fixture verification329628930(ADR authored),209ee6681(renumbered 207 → 208),5901a8e51(subsystem docs + READMEs)contract.jsonbyte-identical againstmain; democontract.d.tsreflects the Phase A typeRef SPI fix onlyVerification
pnpm typecheck— 122 taskspnpm lint:deps— clean (705 modules / 1389 dependencies)pnpm test:packages— 110 packagespnpm test:integration— 105 files / 532 testspnpm test:e2e— 13 files / 91 tests (real Postgres)pnpm build— 61 packagesPost.embeddingrendersVector<1536> | null;User.kindrenders'admin' | 'user';contract.jsonbyte-identical againstmainEmbedding.profile(arktype-json column) renders{ age: number; name: string }Compatibility / migration / risk
paramsSchema?andinit?removed from the SQLCodecextension's parameterized-descriptor surface; pgvector + postgres json/jsonb migrated to the unified factory shape. Spec § Non-functional constraints carves out the encode-sideforCodecIdlegacy fallback explicitly (the only "if descriptor not found, fall back" branch the spec permits, AC-5-deferred).typeslot is authoring-time only; never serialized. Democontract.jsonbyte-identical againstmain. Postgres json/jsonb's typeParams shape unchanged on existing columns; arktype-json'sarktype/json@1is a new codec id with its own{ expression, jsonIr }typeParams shape.json(schema)API removed: the postgres adapter previously bundled a generic Standard-Schema-drivenjson(schema)factory atcolumn-types.ts:167-227. This deletes; users migrate toarktypeJson(schema)(or future per-library extensions for zod, valibot when each ships a clean serialize/rehydrate story).jsonColumn/jsonbColumn(the static raw-JSONB descriptors) remain.ajvdependency dropped from@prisma-next/adapter-postgres(no surviving consumer post-Phase-C).Follow-ups (tracked under TML-2357)
codecs:slot (T3.5.4).Codecruntime-instance narrowing — removeid,traits,targetTypes,metafrom the frameworkCodecinterface (T3.5.2).ParamRef.refsplumbing for encode-sideforColumndispatch (T3.5.9-11); retires theforCodecIdlegacy fallback for parameterized codec ids.JsonSchemaValidatorRegistrydeletion (T3.5.12); validation moves into the resolved codec'sdecodebody (matching the arktype-json pattern shipped in Phase C).descriptorFor(codecId).renderOutputType(retires the per-library emit-only Codec shim Phase C added).Non-goals (intentionally out of scope)
forColumnplumbing — Mongo's adapter doesn't have parameterized codecs that benefit today.Process note
PR #390 (now closed) was the first attempt at TML-2229's re-scoped design — it shipped 74 commits of equivalent work on
tml-2229-no-emit-path-restore-parameterized-output-types-inbut was structurally incompatible with currentmain(authored against the synchronousCodecinterface that pre-dated ADR 204). After gap analysis the work was re-scoped againstmaindirectly: Phase A (typeRef SPI fix), Phase B (unified descriptor + parameterized migration), Phase C (arktype-json extension + M3 deletion), Phase D (ADR + docs), Phase E (Ctx→CodecInstanceContextfamily-extension split + ADR renumber). The async surface impedance was uniformly mechanical, not structural.Summary by CodeRabbit
New Features
Refactor
Tests