Skip to content
This repository was archived by the owner on Nov 25, 2026. It is now read-only.

feat(codec-model-unification): higher-order codecs end-to-end - #390

Closed
wmadden wants to merge 79 commits into
mainfrom
tml-2229-no-emit-path-restore-parameterized-output-types-in
Closed

wmadden wants to merge 79 commits into
mainfrom
tml-2229-no-emit-path-restore-parameterized-output-types-in

Conversation

@wmadden

@wmadden wmadden commented Apr 28, 2026 •

Copy link
Copy Markdown
Contributor

Closes TML-2229 (the no-emit path's failure to resolve vector(1536) to Vector<1536> and json(productSchema) to its schema's inferred output) and the deferred no-emit fix from ADR 186. Also locks the forward-compat surface for stateful column-scoped codecs (CipherStash) so they can author against (params, ctx) today, with the runtime per-instance materialization wiring landing under TML-2330.

This PR was originally opened as a shaping-only artifact (spec / plan / design docs); the entire codec-model-unification project (M1 → M5) ended up landing on this branch. The original shaping artifacts under projects/codec-model-unification/ were absorbed into ADR 205 and deleted at close-out per the project workflow.

Targets worktree/op-registry-ts (the operations-side function-as-signature precedent in PR #374). Will rebase onto main when #374 lands.

Intent

Replace the optional-fields-on-base-Codec shape (paramsSchema? / init? / renderOutputType? on the SQL Codec and Mongo MongoCodec extensions; per-codec hand-rolled column factories whose return types collapse to a generic ColumnTypeDescriptor) with a first-class higher-order codec (HoC) factory model. A parameterized codec is now a curried (params) => (ctx: Ctx) => Codec<…, Js> function whose TypeScript signature is the type-level surface (read by the no-emit FieldOutputType resolver) and whose body is the runtime implementation (invoked once per storage.types instance at contract load). A small sister ParameterizedCodecDescriptor<P> registers the function with the framework and carries the framework-facing metadata (paramsSchema for JSON-boundary validation, optional renderOutputType for the emit path).

The shape is the operations-side ADR 204 ("function is the signature") applied to codecs.

Key snippet

// BEFORE — three optional, drift-prone fields on the base Codec, plus
// per-codec column factories that strip type information.
interface Codec<Id, Traits, Wire, Js> {
  // ...encode / decode / traits / meta...
  readonly paramsSchema?: Type<Record<string, unknown>>;
  readonly renderOutputType?: (params: Record<string, unknown>) => string;
  readonly init?: (params: Record<string, unknown>) => unknown;
}

function vector<N extends number>(length: N): ColumnTypeDescriptor & {
  typeParams: { length: N };
} { /* ... */ }
// AFTER — one curried factory per parameterized codec; descriptor carries
// the framework-facing metadata; base Codec is parameterization-free.
export interface Ctx {
  readonly name: string;
  readonly usedAt: ReadonlyArray<{ readonly table: string; readonly column: string }>;
}

export interface ParameterizedCodecDescriptor<P = Record<string, unknown>> {
  readonly codecId: string;
  readonly paramsSchema: StandardSchemaV1<P>;
  readonly renderOutputType?: (params: P) => string;
  readonly factory: (params: P) => (ctx: Ctx) => Codec;
}

// Pack-author surface — single source of truth, used by both column-author
// site and framework registration.
export function vectorCodecForLength<N extends number>(
  _length: N,
): (ctx: Ctx) => Codec<'pg/vector@1', readonly ['equality'], string, Vector<N>> { /* ... */ }

export function vector<N extends number>(length: N): ColumnTypeDescriptor & {
  readonly typeParams: { readonly length: N };
  readonly type: (ctx: Ctx) => VectorCodec<N>;
} {
  return { codecId: 'pg/vector@1', nativeType: 'vector',
           typeParams: { length }, type: vectorCodecForLength(length) };
}

export const pgVectorCodec: ParameterizedCodecDescriptor<{ readonly length: number }> = {
  codecId: 'pg/vector@1',
  paramsSchema: type({ length: 'number > 0' }),
  renderOutputType: ({ length }) => `Vector<${length}>`,
  factory: ({ length }) => vectorCodecForLength(length),
};

The story

The PR delivers the project across five milestones plus close-out and post-merge follow-ups. Each is summarized at the conceptual-step level; per-commit detail is in the commit log.

  1. M1 — HoC primitives + base codec parameterization-free. Introduces Ctx and ParameterizedCodecDescriptor<P> in @prisma-next/framework-components/codec. Removes paramsSchema? and init? from the SQL Codec extension. The runtime parameterizedCodecs slot widens to carry the new descriptor shape. The SQL runtime's initializeTypeHelpers invokes descriptor.factory(validatedParams)({ name, usedAt }) once per storage.types instance; buildJsonSchemaValidatorRegistry does the same per inline-typeParams column (synthesizing <anon:${table}.${column}>). Production codecs ship with stub factories at this stage.
  2. M2 — No-emit FieldOutputType rewrite. @prisma-next/sql-contract-ts follows typeRef through Definition['types'], then synthetically applies Ctx to the column's type: (ctx: Ctx) => Codec factory at the type level and reads Js off the resulting Codec<Id, Traits, Wire, Js>. Falls through to CodecTypes[codecId]['output'] for non-parameterized columns. Synthetic fixture (vector / json / cipherstash-shaped / nullable / typeRef) drives every variant. No production codec touched yet.
  3. M3 — Schema-typed json(schema) factory. New json<S extends StandardSchemaV1>(schema) and jsonb<S>(schema) in @prisma-next/adapter-postgres returning (ctx) => Codec<…, InferOutput<S>>. decode validates wire payloads via schema['~standard'].validate; failures throw RUNTIME.JSON_SCHEMA_VALIDATION_FAILED (uniform with the existing JSON-validator-registry envelope). Async validators rejected with the same error code. Sister descriptor pgJsonCodec reads schema.expression for renderOutputType, falling back to 'unknown'.
  4. M4 — Migrate every parameterized codec; clean up transitional fields. Pgvector, every Postgres parameterized codec (numeric / timestamp / timestamptz / time / timetz / char / varchar / bit / varbit / interval / json / jsonb), and Mongo's vector all migrate. The contract-authoring ColumnTypeDescriptor gains a type?: (ctx: Ctx) => Codec first-class slot. The emitter's resolveFieldType reads descriptor.renderOutputType exclusively (no more duck-typed as cast). Transitional renderOutputType? fields on the SQL Codec and Mongo MongoCodec extensions are removed. A new 'json-validator' CodecTrait gates per-instance validator extraction so the runtime narrows from unknown to a typed JsonValidatorCodec view structurally. Postgres surface segregation lands for pg/json@1 (column-author / control-plane emit / runtime — three coexisting descriptors registered through different framework slots; rationale documented in three places with TML-2330 unification roadmap).
  5. M5 — Documentation and close-out. ADR 205 extends ADR 186 and references ADR 204. Subsystem docs 2. Contract Emitter & Types.md and 9. No-Emit Workflow.md carry the operational picture. Pack-author README sections land in framework-components, extension-pgvector, adapter-postgres, adapter-mongo. Typecheck re-measure: sql-relational-core −0.9% / sql-contract-ts −2.8% (well within ±20%). All in-source projects/codec-model-unification cross-references rewrite to ADR 205. The project directory deletes.
  6. Close-out review. Fresh-spawn reviewer ran drive-pr-local-review over the entire branch per the close-out checkpoint codified in 247e5507a. Verdict: APPROVE WITH FOLLOW-UPS, 8/8 ACs PASS. Three findings filed and closed: shell-escape artifacts swept from comments (d19885655), production-source comment headers rewritten to ADR 205 pointers (0436a1ae0), surface-segregation pattern documented in framework-components/README.md (ce82ab146).
  7. Post-merge follow-ups. Cloud-agent boot-time git identity from Cursor secrets (95216c91f). ADR 205 narrative-flow rewrite (1f20aceb2).

Acceptance criteria

AC Status Evidence
AC-1 — HoC factories type-resolve correctly PASS 714f6bd86 (synthetic), f2a1f1953 4d5ca532f (json), 57a08384f (pgvector production)
AC-2 — No-emit FieldOutputType resolves correctly PASS 46648d3c1, fe80847ef, 57a08384f
AC-3 — Authoring-side ctx is supplied to factories PASS 49c44b85a (runtime), 4942a6c6a (authoring)
AC-4 — Existing parameterized codecs migrated; emit byte-identical PASS 57a08384f, d95adc224, 51923bf30, c41227d4e (baseline)
AC-5 — JSON factory ships PASS f2a1f1953, 4d5ca532f
AC-6 — CipherStash forward-compat surface locked PASS 714f6bd86
AC-7 — Build performance acceptable (±20% of baseline) PASS sql-relational-core −0.9% / sql-contract-ts −2.8%
AC-8 — Documentation lands PASS 8a2af2123 (ADR 205), 042104e38 (subsystem), ebade5247 ce82ab146 (READMEs), 1f20aceb2 (ADR 205 narrative rewrite)

Verification

  • pnpm typecheck — 70 packages green
  • pnpm lint:deps — clean (630 modules / 1265 dependencies)
  • pnpm test:packages — 111 turbo task suites green
  • pnpm test:e2e — 46 tests green
  • pnpm build — 61 build tasks green
  • Emit snapshots byte-identical against M0.3 baseline (12 contracts: 6 .json + 6 .d.ts)

Compatibility / migration / risk

  • No backwards-compat shims. Hard cut on paramsSchema? / init? / renderOutputType? from the codec interfaces. The migration is structural — TypeScript catches unmigrated codecs at compile time.
  • Contract IR is unchanged. descriptor.type is authoring-time only; never serialized. Emit byte-identical against M0.3 baseline. Storage / execution / profile hashes stable.
  • Three coexisting JSON descriptors per pg/json@1. Surface segregation is the deliberate transitional state pending TML-2330's IR-shape unification. No runtime selection between descriptors; each is registered through a different framework slot.

Follow-ups (captured in ADR 205 § Future work)

  • TML-2330 — collapse the IR typeParams shape so a single descriptor handles all three resolution surfaces (column-author / emit / runtime), retiring the pgJsonCodec + pgJsonLegacyCodec + pgJsonRuntimeFactory triplet.
  • Mongo control-plane parameterizedCodecs slot — surgical addition to let Mongo's vector(N) register through control the same way Postgres does.
  • pgEnumCodec placeholder factory audit — ensure no future runtime path invokes the placeholder by iterating over allPostgresParameterizedCodecs.

TML-2329 (CipherStash G9 — trait-gated wire redaction) remains a separate follow-up not addressed by this project.

Note on ride-along skill-system commits

Two commits ship drive-orchestrate-plan skill-system changes alongside the codec project: 702daa007 adds the skill (the operational pattern that produced this PR), and 247e5507a codifies the project close-out checkpoint inside that skill (the post-mortem captured before the project's lessons fade). The codec changes are independent of these two commits; if the team prefers skill-system changes through dedicated PRs going forward, factor them out before merge.

Summary by CodeRabbit

  • New Features

    • Parameterized codec system enabling higher-order codec factories that preserve type parameters in TypeScript output types
    • arktype-json extension providing type-safe JSON columns with schema-based validation and runtime narrowing
    • Enhanced field output type resolution supporting both inline and named storage type instances
  • Refactor

    • Operation model restructured from declarative args/returns to function-signature-based impl pattern
    • Codec architecture separated: descriptors handle metadata/validation, runtime factories instantiate per-column codecs
  • Documentation

    • Architecture decision records (ADRs 203–205) documenting operations-as-functions and higher-order codecs
    • Updated subsystem and extension documentation reflecting parameterized codec patterns

SevInf and others added 9 commits April 23, 2026 18:52
Replaces the declarative `{args, returns, lowering}` operation record with a
TypeScript function `impl` paired with a minimal `self` dispatch hint. The
function's signature is the type-level surface; the function's body builds
the AST expression node via `toExpr` + `buildOperation`. Adapters and
extensions ship operation contributions as CT-generic factories whose impls
use `CodecExpression<CodecId, N, CT>` or `TraitExpression<Traits, N, CT>`
for argument types, letting authors use TypeScript's full expressivity
(generics, conditional returns, non-DB argument types).

Column handles on the ORM model accessor now implement `Expression<T>`
directly — carrying `returnType` and `buildAst()` on a single plain-object
literal — unlocking cross-column composition like
`db.a.embedding.cosineDistance(db.b.embedding)`. The old
`new ExpressionImpl(column, { codecId: '', nullable: false })` hack in the
extension-method factory is gone; `numericAgg`'s downcast
`(expr as ExpressionImpl).field.codecId` reads `expr.returnType.codecId`
off the Expression interface.

The ORM Proxy returns `undefined` for unknown fields (plain JS object
semantics). The relation-shorthand iterator throws explicitly on unknown
predicate keys so typos surface loudly instead of silently filtering
nothing.

Ported ops: `postgres/ilike`, `pgvector/cosineDistance`,
`pgvector/cosineSimilarity`, and `mongo-adapter/near`.

ADR 204 documents the decision.

Breaking change for extensions that shipped declarative operation records —
rewrite to a CT-generic factory returning `{method, self?, impl}`.
Replaces biome-ignore + `as any` casts in the two negative tests with
`@ts-expect-error`. The assertion under test is specifically that
`SelfSpec` rejects these shapes at the type level — @ts-expect-error
makes that a compile-time check instead of a runtime-only check.
Add unit coverage for the new toExpr / buildOperation helpers in
relational-core and invoke the mongoVectorNearOperation placeholder
impl so both files reach their coverage thresholds.
Promote codec parameterization to a first-class ParameterizedCodec interface with a co-located CodecBrand (this[Input] HKT idiom), a single columnFor authoring helper, and Standard-Schema-driven JSON inference. Rewrites the no-emit FieldOutputType once against the brand so parameterized columns (vector(1536), char(36), JSON-shaped scalars) resolve to their precise branded types in both the emit and no-emit paths.

Resolves the root cause behind TML-2229; the original ticket was deliberately re-scoped from "restore parameterized output types in StagedFieldOutputTypes" to address why the no-emit path keeps drifting.

Branch is based on PR #374 (origin/worktree/op-registry-ts) so the brand mechanism plugs directly into Expression<T> / CodecExpression<...> as those land.
…sign docs

Tighten spec.md to requirements + acceptance criteria, point at
companion design docs for rationale. Update plan.md milestones to
reflect the new doc layout, the FR8 init signature, and the M0
baseline-measurement step.

Add three design docs under projects/codec-model-unification/design/:

- codec-interface-and-brand.md  Codec / ParameterizedCodec split,
  the CodecBrand + Apply HKT mechanism, the rewritten no-emit
  FieldOutputType, rejected alternatives.

- authoring-ergonomics.md  columnFor and jsonCodec helpers,
  storage.types vs typeRef, before/after worked examples for
  pgvector / char(N) / JSON-with-schema, pack-author guidance
  preview.

- runtime-contract-and-compatibility.md  the per-instance
  materialization contract we declare without implementing,
  CipherStash G1/G16/G6 alignment, explicit out-of-scope
  extension points (G4, G10, G9, G2/G3), rebase strategy off
  PR #374.

Also commit the CipherStash framework-gaps analysis as a project
asset; it is referenced from the runtime-contract doc.
… the decision

Rewrite the spec and plan and reorder the three design docs so each
opens with the decision being made, builds the concept up with linked
design-doc detail, and ends with alternatives considered. Removes the
reverse-engineer-from-FRs structure that the previous draft had.

spec.md
- Open with a Decision section (one paragraph + before/after diagram).
- Replace FR1-FR8 with a How-it-works narrative that introduces each
  concept and links to design-doc detail at the right moments.
- Add a Glossary so a fresh reader has the vocabulary up front.
- Recast acceptance criteria as observable properties only (AC-1..AC-8).
- Move alternatives considered into the spec (was design-doc-only).

plan.md
- Make M0 status-explicit: Done vs Remaining.
- Drop type-definition code blocks duplicated from the design docs;
  link instead.
- Add a milestone graph and per-milestone spec-AC links.
- Refresh risks (TS depth, brand cast scope, emit regression).

design/codec-interface-and-brand.md
- Lead with a Decision block showing the final interface shape.
- Move Background to a subordinate Why split section.
- Keep Rejected alternatives at the end.

design/authoring-ergonomics.md
- Lead with a Decision showing the columnFor / jsonCodec call shapes.
- Drop the Background opener.

design/runtime-contract-and-compatibility.md
- Lead with the declared runtime contract as the Decision.
- Move Background reasoning to Why declare without implementing.
…e cases

Surface the codecs we know we must support (Case V vector, Case J JSON-
with-schema, Case C CipherStash column-scoped encryption) as the design-
pinning constraints. Each design decision in the spec and design docs
now names the case(s) it answers to, and each case has worked code
showing the design end-to-end.

spec.md
- Add Cases that pin the design section (V, J, C) between Why and How
  it works. Each case names what it pins.
- Annotate each How it works subsection with its driving case(s).
- Reframe Requirements satisfied as Outcomes; map each outcome back
  to a case.

authoring-ergonomics.md
- Rename Worked example: pgvector  Case V; Worked example: char(N)
  -> Case V (variant); Worked example: JSON  Case J.
- Add What this case pins callouts to V and J listing the constraints
  each one places on the design.

runtime-contract-and-compatibility.md
- Replace the abstract CipherStash compatibility prose with a Case C
  case study: actual codec source, init(params, instance) deriving a
  column-scoped key, the encryptedJson<T> compound subcase, and a
  ships-now / deferred-to-TML-2330 table.

codec-interface-and-brand.md
- Add Driving cases section to Decision listing V/J/C with links to
  worked code.
- Annotate Brand mechanism, Init signature, and Rewriting the
  no-emit FieldOutputType subsections with their driving cases.
…locks

The side-by-side ASCII diagram in spec.md was hard to read at narrow
widths; split into separate Before: and After: blocks so each fits
without horizontal scrolling.
@coderabbitai

coderabbitai Bot commented Apr 28, 2026 •

Copy link
Copy Markdown
Contributor

Note

Reviews paused

It looks like this branch is under active development. To avoid overwhelming you with review comments due to an influx of new commits, CodeRabbit has automatically paused this review. You can configure this behavior by changing the reviews.auto_review.auto_pause_after_reviewed_commits setting.

Use the following commands to manage reviews:

  • @coderabbitai resume to resume automatic reviews.
  • @coderabbitai review to trigger a single review.

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

This PR implements a substantial refactor of parameterized codecs and operations architecture across the Prisma Next framework. Key changes include introducing framework-level CodecDescriptor<P> with curried factories and paramsSchema validation, replacing operation metadata models from args/returns/lowering to self/impl function-based signatures, establishing new Expression types with toExpr and buildOperation primitives, reorganizing pgvector codec implementations, introducing a new arktype-json extension, and adding comprehensive orchestrator skill documentation for AI agent workflows.

Changes

Cohort / File(s) Summary
Codec Descriptor System
packages/1-framework/1-core/framework-components/src/codec-types.ts, packages/1-framework/1-core/framework-components/src/exports/codec.ts, packages/1-framework/1-core/framework-components/src/control-stack.ts, packages/1-framework/2-authoring/contract/src/descriptors.ts
Introduces CodecDescriptor<P> and ParameterizedCodecDescriptor<P> types backed by StandardSchemaV1 for parameter validation, with renderOutputType and curried factory functions replacing codec-level rendering. Removes renderOutputType from Codec interface. Adds parameterizedCodecLookup to ControlStack and parameterizedCodecs field to ComponentMetadata.types.codecTypes.
Operations Registry Refactor
packages/1-framework/1-core/operations/src/index.ts, packages/1-framework/1-core/operations/test/operations-registry.test.ts, packages/2-sql/1-core/operations/src/index.ts, packages/2-sql/1-core/operations/test/operations-registry.test.ts, packages/2-sql/1-core/contract/src/types.ts, packages/2-sql/1-core/contract/src/exports/types.ts
Replaces operation entry model from args: ParamSpec[] and returns: ReturnSpec to self?: SelfSpec and impl: (...args: never[]) => unknown, with SelfSpec enforcing either codecId or traits (but not both). Updates SqlOperationEntry to use QueryOperationTypeEntry from contract types.
Expression Primitives & Types
packages/2-sql/4-lanes/relational-core/src/expression.ts, packages/2-sql/4-lanes/relational-core/src/exports/expression.ts, packages/2-sql/4-lanes/sql-builder/src/expression.ts, packages/2-sql/4-lanes/sql-builder/src/runtime/expression-impl.ts, packages/2-sql/4-lanes/sql-builder/src/scope.ts
Introduces Expression<T extends ScopeField>, CodecExpression, TraitExpression types; toExpr for AST embedding; buildOperation for operation construction. Updates ExpressionImpl to expose returnType instead of field. Replaces local expression types with relational-core imports.
SQL Functions & Builders
packages/2-sql/4-lanes/sql-builder/src/runtime/functions.ts, packages/2-sql/4-lanes/sql-builder/src/runtime/builder-base.ts, packages/2-sql/4-lanes/sql-builder/test/runtime/functions.test.ts
Refactors numeric aggregates and boolean operators to use CodecExpression, introduces ExprOrVal based on CodecExpression, replaces extension-operation builder with direct op.impl invocation, updates createFunctions and createAggregateFunctions to accept operations dict.
Codec Trait Expansion
packages/2-sql/4-lanes/relational-core/src/ast/codec-types.ts, packages/2-sql/4-lanes/relational-core/src/ast/sql-codecs.ts, packages/2-sql/4-lanes/relational-core/test/ast/codec-types.test.ts, packages/2-sql/4-lanes/relational-core/test/ast/sql-codecs.test.ts
Removes parameterized codec fields (paramsSchema, init, renderOutputType) from runtime Codec interface. Simplifies SQL codec definitions (char, varchar, timestamp) by removing parameter validation and type rendering logic. Adds 'json-validator' trait to CodecTrait.
Type Emission Pipeline
packages/1-framework/3-tooling/emitter/src/domain-type-generation.ts, packages/1-framework/3-tooling/emitter/src/emit-types.ts, packages/1-framework/3-tooling/emitter/src/generate-contract-dts.ts, packages/1-framework/3-tooling/emitter/src/emit.ts
Shifts output-type rendering to use parameterizedCodecLookup descriptor lookup instead of codec-object methods. Adds FieldTypeParamsResolver SPI for model/field-specific typeParams resolution. Threads parameterizedCodecLookup through type generation functions.
Runtime Codec Registry Refactor
packages/2-sql/5-runtime/src/sql-context.ts, packages/2-sql/5-runtime/src/codecs/decoding.ts, packages/2-sql/5-runtime/src/codecs/encoding.ts, packages/2-sql/5-runtime/src/codecs/validation.ts, packages/2-sql/5-runtime/src/sql-runtime.ts
Replaces CodecRegistry with ContractCodecRegistry (column-aware dispatch via forColumn/forCodecId). Migrates parameter validation from paramsSchema/init hooks to curried factory(params)(ctx). Adds codecDescriptors registry to ExecutionContext for metadata/trait lookups.
SQL Adapter Codecs - Postgres
packages/3-targets/6-adapters/postgres/src/codecs/postgres-codec-descriptors.ts, packages/3-targets/6-adapters/postgres/src/core/parameterized-codec-factories.ts, packages/3-targets/6-adapters/postgres/src/exports/column-types.ts, packages/3-targets/6-adapters/postgres/src/core/adapter.ts, packages/3-targets/6-adapters/postgres/src/exports/runtime.ts, packages/3-targets/6-adapters/postgres/src/core/json-schema-* (removed)
Introduces postgres-codec-descriptors.ts with parameterized descriptors and allPostgresParameterizedCodecs array. Creates parameterized-codec-factories.ts with curried codec factories. Updates column-type descriptors to include higher-order codec factories. Removes JSON schema validator/type-expression utilities and Standard Schema support for JSON columns.
pgvector Extension Reorganization
packages/3-extensions/pgvector/src/core/vector-codec.ts, packages/3-extensions/pgvector/src/core/control-extension-descriptor.ts, packages/3-extensions/pgvector/src/core/runtime-extension-descriptor.ts, packages/3-extensions/pgvector/src/core/query-operations.ts, packages/3-extensions/pgvector/src/exports/*
Consolidates parameterized vector codec into vector-codec.ts with vectorCodecForLength factory and pgVectorCodec descriptor. Creates separate control/runtime extension descriptors. Refactors query operations with self+impl model. Removes prior module-level implementations.
arktype-json Extension (New)
packages/3-extensions/arktype-json/*
New extension package implementing JSON validation via arktype schemas. Includes arktypeJsonCodec descriptor with schema serialization (expression/jsonIr) and runtime rehydration. Provides column-author surface (arktypeJson), control/runtime descriptors, and comprehensive tests. Fully structures codec types, exports, and framework integration.
MongoDB Vector Codec
packages/3-mongo-target/2-mongo-adapter/src/codecs/vector-factory.ts, packages/3-mongo-target/2-mongo-adapter/src/core/codecs.ts, packages/3-mongo-target/2-mongo-adapter/src/exports/codecs.ts
Adds parameterized mongoVectorCodec descriptor with factory-based codec generation. Removes renderOutputType from base MongoDB vector codec. Updates operation descriptor for mongoVectorNearOperation to use self+impl model.
SQL ORM Client Updates
packages/3-extensions/sql-orm-client/src/model-accessor.ts, packages/3-extensions/sql-orm-client/src/types.ts, packages/3-extensions/sql-orm-client/src/filters.ts, packages/3-extensions/sql-orm-client/test/*
Updates operation dispatch to use self instead of args[0]. Adds returnType to expression metadata. Derives argument/return typing from operation impl signatures. Accesses codec traits via codecDescriptors registry. Updates scalar field accessor types to include Expression<ScopeField> intersection.
Contract Type Resolution
packages/2-sql/2-authoring/contract-ts/src/contract-types.ts, packages/2-sql/2-authoring/contract-ts/test/contract-types.field-output.test-d.ts, packages/2-sql/2-authoring/contract-ts/test/fixtures/codec-resolver-fixture.ts
Implements parameterized StorageColumn.type factory for higher-order codec resolution. Updates FieldOutputType to resolve through both inline descriptors and typeRef-based storage types. Adds comprehensive type-level test fixtures for codec resolution scenarios.
Test & Configuration Updates
examples/prisma-next-demo/prisma/contract.ts, examples/prisma-next-demo/package.json, examples/prisma-next-demo/src/prisma/*, test/e2e/framework/test/fixtures/*, test/integration/*, architecture.config.json
Integrates arktype-json extension into demo and E2E fixtures. Updates QueryOperationTypes to be generic over CodecTypes. Adds pgvector core descriptor files to architecture config. Updates contract types and runtime initialization for new codec dispatch model.
Skill Documentation
.agents/skills/drive-orchestrate-plan/SKILL.md, .agents/skills/drive-orchestrate-plan/agents/implementer.md, .agents/skills/drive-orchestrate-plan/agents/reviewer.md, .agents/skills/drive-orchestrate-plan/learnings.md, .agents/skills/drive-orchestrate-plan/templates/*
Comprehensive orchestrator skill specification defining subcommand flow (iterate, implement, review), subagent delegation protocol, artifact contracts (code-review.md, system-design-review.md, walkthrough.md), loop algorithm with intent-validation and verdict triage, unattended mode with decision-log scaffold, and close-out checkpoint procedures.
Environment & Build Config
.cursor/environment.json, .cursor/start.sh, docs/architecture/adrs/ADR 20*, docs/architecture/subsystems/*
Adds Cursor VM boot script for git config. Introduces ADR 203 (operation traits/codecId), ADR 204 (operations as TypeScript functions), ADR 205 (higher-order codecs). Updates architecture subsystem docs for parameterized codecs and no-emit workflow. Updates ADR index.

Sequence Diagram(s)

Sequence diagrams are not generated for this diff because although it introduces new architecture, the changes primarily involve structural refactoring (type system changes, code reorganization) rather than establishing novel multi-component interaction flows that would benefit from sequential visualization. The parameterized codec and operations changes are architectural redesigns that modify internal type contracts rather than new control-flow interactions.

Estimated code review effort

🎯 5 (Critical) | ⏱️ ~120 minutes

Possibly related PRs

Poem

🐰 Hops with glee at schemas stacked,
Codecs curried, traits retracked!
Self and impl dance anew,
Expressions bloom in every hue,
Arktype whispers validation's song, 🎵
All orchestrated, flowing strong!

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch tml-2229-no-emit-path-restore-parameterized-output-types-in

@pkg-pr-new

pkg-pr-new Bot commented Apr 28, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@prisma-next/mongo-runtime

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-runtime@390

@prisma-next/family-mongo

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/family-mongo@390

@prisma-next/sql-runtime

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-runtime@390

@prisma-next/family-sql

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/family-sql@390

@prisma-next/middleware-telemetry

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/middleware-telemetry@390

@prisma-next/mongo

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo@390

@prisma-next/extension-paradedb

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/extension-paradedb@390

@prisma-next/extension-pgvector

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/extension-pgvector@390

@prisma-next/postgres

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/postgres@390

@prisma-next/sql-orm-client

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-orm-client@390

@prisma-next/sqlite

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sqlite@390

@prisma-next/target-mongo

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/target-mongo@390

@prisma-next/adapter-mongo

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/adapter-mongo@390

@prisma-next/driver-mongo

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/driver-mongo@390

@prisma-next/contract

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/contract@390

@prisma-next/utils

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/utils@390

@prisma-next/config

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/config@390

@prisma-next/errors

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/errors@390

@prisma-next/framework-components

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/framework-components@390

@prisma-next/operations

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/operations@390

@prisma-next/ts-render

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/ts-render@390

@prisma-next/contract-authoring

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/contract-authoring@390

@prisma-next/ids

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/ids@390

@prisma-next/psl-parser

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/psl-parser@390

@prisma-next/psl-printer

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/psl-printer@390

@prisma-next/cli

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/cli@390

@prisma-next/emitter

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/emitter@390

@prisma-next/migration-tools

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/migration-tools@390

prisma-next

npm i https://pkg.pr.new/prisma/prisma-next@390

@prisma-next/vite-plugin-contract-emit

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/vite-plugin-contract-emit@390

@prisma-next/runtime-executor

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/runtime-executor@390

@prisma-next/mongo-codec

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-codec@390

@prisma-next/mongo-contract

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-contract@390

@prisma-next/mongo-value

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-value@390

@prisma-next/mongo-contract-psl

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-contract-psl@390

@prisma-next/mongo-contract-ts

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-contract-ts@390

@prisma-next/mongo-emitter

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-emitter@390

@prisma-next/mongo-schema-ir

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-schema-ir@390

@prisma-next/mongo-query-ast

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-query-ast@390

@prisma-next/mongo-orm

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-orm@390

@prisma-next/mongo-query-builder

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-query-builder@390

@prisma-next/mongo-lowering

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-lowering@390

@prisma-next/mongo-wire

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/mongo-wire@390

@prisma-next/sql-contract

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-contract@390

@prisma-next/sql-errors

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-errors@390

@prisma-next/sql-operations

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-operations@390

@prisma-next/sql-schema-ir

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-schema-ir@390

@prisma-next/sql-contract-psl

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-contract-psl@390

@prisma-next/sql-contract-ts

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-contract-ts@390

@prisma-next/sql-contract-emitter

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-contract-emitter@390

@prisma-next/sql-lane-query-builder

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-lane-query-builder@390

@prisma-next/sql-relational-core

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-relational-core@390

@prisma-next/sql-builder

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-builder@390

@prisma-next/target-postgres

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/target-postgres@390

@prisma-next/target-sqlite

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/target-sqlite@390

@prisma-next/adapter-postgres

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/adapter-postgres@390

@prisma-next/adapter-sqlite

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/adapter-sqlite@390

@prisma-next/driver-postgres

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/driver-postgres@390

@prisma-next/driver-sqlite

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/driver-sqlite@390

commit: 1f20ace

wmadden added 2 commits April 28, 2026 15:50
…terminology fixes)

The "brand" terminology in the design docs was misleading. In TS
convention a "branded type" is a nominal type marked by a phantom
property/symbol (e.g. `Vector<N> = number[] & { __vectorLength?: N }`),
not a function from input to output.

What the codec carried in its `Brand` field was actually a *type-level
function* from `Params` to the output type. Rename to match what it is:

- `CodecBrand<P>`           -> `CodecOutputTypeFn<P>` (function shape)
- `Brand` field on codec    -> `OutputType` (the slot)
- `VectorBrand` etc.        -> `VectorOutputType` etc. (per-codec)
- File `codec-interface-and-brand.md` -> `codec-interface-and-output-types.md`

The actual branded type usage stays: `Vector<N>` IS a branded type
(produced *by* an output-type function). Glossary now distinguishes the
two concepts explicitly.

Also:

- Spec before/after diagrams switched from ASCII pseudo-code to actual
  TypeScript interface declarations.
- Removed the false claim that JSON columns "never had" schema-driven
  inference; clarified TML-2229 *restores* this behavior (it existed
  before the no-emit path was introduced).
- Cross-doc anchor and link updates throughout.
…unctions

Replace the type-level brand / OutputType-HKT / ParameterizedCodec-split
design with a simpler model: a parameterized codec is a curried higher-
order TypeScript function (params) -> (ctx) -> Codec, paired with a
sister ParameterizedCodecDescriptor that carries paramsSchema and
renderOutputType. Following ADR 204, the function is the single behavior-
bearing artifact for both the no-emit type-level resolution and the
runtime instantiation; init disappears as a separate hook because the
factory closure IS init.

Rewrites spec, plan, and all three design docs end to end. Renames
design/codec-interface-and-output-types.md to higher-order-codecs.md.
Decision-led structure preserved; alternatives section now records the
rejected HKT/init/columnFor approaches.
@cursor cursor Bot changed the title docs(projects): shape codec-model-unification project docs(projects): shape codec-model-unification (higher-order codecs) Apr 28, 2026
… drop renderOutputType from base Codec

Introduces the higher-order codec model from the codec-model-unification project (M1):

- `Ctx` — column context the contract-authoring API supplies when applying a curried
  factory: `{ name, usedAt: ReadonlyArray<{ table, column }> }`. Locks the open
  question on Ctx shape (CipherStash forward-compat, ADR 204 precedent).
- `ParameterizedCodecDescriptor<P>` — sister registration descriptor for a curried
  higher-order codec factory: `{ codecId, paramsSchema: StandardSchemaV1<P>,
  renderOutputType?, factory: (P) => (Ctx) => Codec }`. Lives next to the existing
  `Codec` interface so non-SQL families can reuse it (open question 1 default).
- `renderOutputType` is removed from the base `Codec` interface and migrated to
  `ParameterizedCodecDescriptor.renderOutputType` (open question 2, locked).

Adds `@standard-schema/spec` as a runtime dependency (already present in the lockfile
via vitest). Adds a type-only test fixture covering AC-1 (vector(1536) typechecks as
(ctx) => Codec<…, VectorN<1536>>) and AC-6 (a Ctx-aware factory typechecks).

Refs codec-model-unification spec.md/plan.md M1, ADR 204.
… keep renderOutputType as M1 holding place

Removes paramsSchema and init from the SQL `Codec` interface and the `codec()` factory.
paramsSchema migrates to `ParameterizedCodecDescriptor.paramsSchema` (framework-components),
init is absorbed by the curried higher-order factory closure introduced in M4.

Strips `paramsSchema:` / `init:` fields from production codec objects in `sql-codecs.ts`;
they are temporarily inert (no behavior depends on them until M4 wires the new factory
through TML-2330). renderOutputType stays on the SQL `Codec` extension as a transient
holding place — the long-term home is `ParameterizedCodecDescriptor.renderOutputType`,
M4 migrates production codecs to descriptors and removes the field from the SQL extension.

Updates AST tests to drop the paramsSchema/init presence assertions; the codec object
no longer carries those fields. Production codecs still build.

Refs codec-model-unification plan.md M1.
…ction codec configs and adapter helpers

The `codec()` factory no longer accepts `paramsSchema`/`init`. Production codec configs
(numeric, timestamp, timestamptz, time, timetz, bit, varbit, interval, jsonb) drop those
fields; the unused arktype schemas (`numericParamsSchema`, `precisionParamsSchema`,
`lengthParamsSchema`) are removed. `aliasCodec` no longer threads them through.

The Postgres adapter no longer derives parameterized codec descriptors from
`codec.paramsSchema`; the runtime descriptor at `exports/runtime.ts` is the single
source of truth post-M1. The instance-method `parameterizedCodecs()` returns an empty
ParameterizedCodecDescriptor[] for now (no consumers on the legacy SPI surface).

Tests: removes paramsSchema/init presence assertions on production codecs; production
codec migration to the curried factory ships in M4 (TML-2330).

Refs codec-model-unification plan.md M1.
…zedCodecDescriptor

`RuntimeParameterizedCodecDescriptor` is now an alias for the new
`ParameterizedCodecDescriptor<P>` from `@prisma-next/framework-components/codec`,
extended with a transitional optional `init?` field (replaced by the curried factory
closure in M4). `paramsSchema` widens from arktype `Type<P>` to `StandardSchemaV1<P>`;
no behavior change at runtime since arktype already implements Standard Schema.

`validateTypeParams` now consults the `~standard.validate` hook directly (no arktype
import), surfacing Standard Schema issues with the same RUNTIME.TYPE_PARAMS_INVALID
error envelope.

Test fixtures add a stub `factory` (the M1 placeholder that throws "TML-2330 not yet
implemented") wherever they construct a `RuntimeParameterizedCodecDescriptor` literal.
No runtime path exercises the factory yet; production codec migration ships in M4.

Refs codec-model-unification plan.md M1, TML-2330.
…meterizedCodecDescriptor entries

The new `ParameterizedCodecDescriptor` shape requires a `factory: (P) => (Ctx) => Codec`.
For M1, pgvector and the Postgres JSON/JSONB descriptors carry a stub factory that
throws "TML-2330 not yet implemented" if invoked. No runtime path exercises the
factory yet (production codecs continue to flow through the transitional `init`
field on the runtime descriptor); M4 wires the new factory through and removes the
init compat field.

Refs codec-model-unification plan.md M1, TML-2330.
… M1 transition

`renderOutputType` is removed from the base `Codec` interface (codec-model-unification
M1, open question 2 locked). The emit path duck-types the optional field off the
codec object so existing pgvector/SQL/Mongo codec authoring continues to drive emit
correctly until production codecs migrate to ParameterizedCodecDescriptor in M4.

Mongo `MongoCodec` extension declares its own `renderOutputType?` field as the
transient holding place (mirroring the SQL `Codec` extension); long-term home is
the descriptor. Updates the emitter test stub helper to type the ad-hoc field.

Refs codec-model-unification plan.md M1.
…iptor (F02 from M1 round 1 review)

Spec § Decision is unambiguous: "no separate init hook." Round 1 carried the
field on the runtime descriptor as a transitional helper, but two consumers
(`initializeTypeHelpers`, `buildJsonSchemaValidatorRegistry`) actively read it,
which recreates the design the spec rejected. Round 2 retires the field and
moves the per-instance state into the curried factory closure where the spec
puts it.

Concretely:

- `RuntimeParameterizedCodecDescriptor<P>` is now a plain alias for
  `ParameterizedCodecDescriptor<P>`. There is no `init` hook anywhere in the
  shared descriptor type or its supertype.
- `initializeTypeHelpers` now invokes `descriptor.factory(validatedParams)(ctx)`
  for each `storage.types` entry and stores the resolved codec in
  `context.types[typeName]`. `ctx.usedAt` is aggregated by walking the contract
  for `typeRef`-keyed columns; `ctx.name` is the storage-types instance name —
  this matches the runtime materialization contract documented in
  `runtime-contract-and-compatibility.md` § Runtime materialization contract.
- `buildJsonSchemaValidatorRegistry` reads `validate` directly off the resolved
  codec for both typeRef and inline-typeParams cases (calling
  `descriptor.factory(typeParams)(<anon ctx>)` for inline columns), replacing
  the pre-M1 `descriptor.init` path.
- The Postgres JSON / JSONB descriptors ship a real factory whose body compiles
  the JSON-schema validator and attaches it to the resolved Codec — narrowly
  scoped per the round-1 reviewer note ("ship the production-codec factory
  now ... carve-out scoped to *only* the codecs that previously had init").
- The pgvector descriptor ships a real (stateless) factory that returns the
  static `pg/vector@1` codec; this is byte-equivalent at the runtime path
  because pgvector never used `init` (length is metadata only).
- The arktype-typed `init` consumers in `parameterized-types.test.ts` and
  `json-schema-validation.test.ts` are reworked to drive the same behavior
  through the curried factory; tests now assert that `ctx.name` and
  `ctx.usedAt` are passed correctly and that `validate` is read off the
  resolved codec rather than off a separate `init` hook.

`pnpm test:packages` (89 tests in `@prisma-next/sql-runtime`) and
`pnpm test:e2e` (46 tests across SQL/SQLite) remain green.

Refs codec-model-unification spec.md § Decision and § Rejected alternatives,
runtime-contract-and-compatibility.md § Runtime materialization contract,
TML-2330.
…ts for descriptor.factory (F04)

Round 1 reviewer F04: the AC-1.e check only asserted the abstract shape of
`ParameterizedCodecDescriptor.factory`. Round 2 adds:

- A positive assignability test: a typed factory function whose params and
  resolved Codec match the descriptor is assignable to the descriptor`s
  `factory` slot via `expectTypeOf<typeof vectorFactory>().toExtend<DescFactory>()`.
- A negative test using `@ts-expect-error`: a factory with wider params (an
  extra required field) does NOT assign — the descriptor`s caller cannot
  satisfy the extra field, so contravariance rejects.
- A negative test using `@ts-expect-error`: a factory whose inner function
  returns a non-Codec value does NOT assign — the descriptor demands
  `(ctx: Ctx) => Codec`.

These tests pin the property AC-1.e actually wants: "a fully-typed factory
function is assignable to the descriptor`s `factory` slot," with both the
expected shape preservation and rejection of malformed factories.

Refs codec-model-unification spec.md § AC-1, M1 round 1 code-review F04.
…ML-2330 (M1 round 1 soft warning)

Round 1 reviewer noted that the residual `renderOutputType?` fields and the
emitter duck-typed cast are appropriately tagged as transitional but lack a
Linear-issue anchor — making it harder to audit the carve-out and risking
"transitional" becoming "permanent." Round 2:

1. Adds a TML-2330-anchored sentence to each transitional comment:
   - SQL `Codec` extension`s `renderOutputType?` field at
     `packages/2-sql/4-lanes/relational-core/src/ast/codec-types.ts`.
   - `MongoCodec` extension`s `renderOutputType?` field at
     `packages/2-mongo-family/1-foundation/mongo-codec/src/codecs.ts`.
   - The emitter`s duck-typed access site at
     `packages/1-framework/3-tooling/emitter/src/domain-type-generation.ts`.

2. Adds a "M4 Cleanups (carve-outs from M1, TML-2330)" sub-section to
   `projects/codec-model-unification/plan.md § M4` enumerating the exact items
   the M4 PR must remove: the two extension-level `renderOutputType?` fields,
   the emitter duck-typed cast, and the per-codec inline `renderOutputType`
   configurations on production codec objects.

No code-behavior change.

Refs codec-model-unification plan.md § M4, TML-2330.
wmadden and others added 6 commits April 28, 2026 20:14
…-order codec factory return type (M2)

The pre-M2 `FieldOutputType` consulted only the codec registry's base output —
parameterized columns collapsed to `readonly number[]` instead of `Vector<1536>`,
and JSON columns lost their schema-derived inference (`InferOutput<S>`). The M2
rewrite follows `Col["typeRef"]` through `Definition["types"]`, then — when the
resolved column carries a `type` slot whose TS type is `(ctx: Ctx) => Codec<…>` —
synthetically applies `Ctx` and reads `Js` off the resulting codec. Non-
parameterized columns still fall through to the codec base output.

Mechanics:

- `DescriptorTypeFactory<Descriptor>` extracts the factory off a column
  descriptor or `storage.types` entry.
- `ResolveFieldColumnTypeFactory<Definition, FieldState>` lifts the factory
  through `ResolveFieldDescriptor` so it is reachable from
  `ModelStorageColumn`.
- `StorageColumn` gains an optional `TypeFactory` parameter that surfaces the
  factory as the column's `type` slot.
- `ResolveTypeRef<Definition, Col>` follows `Col["typeRef"]` through
  `Definition["types"]` and reattaches the column's nullability flag.
- `CodecJs<C>` extracts `Js` from `Codec<Id, Traits, Wire, Js>`; `ApplyCtx<F>`
  applies a synthetic `Ctx` to the partially applied factory; `ApplyNullable`
  unifies nullability handling across both paths.
- `FieldOutputType` itself is now: resolve typeRef → if `type` slot present,
  read `Js` from the factory's return type; else fall through to today's
  `CodecTypes[id]["output"]` lookup.

This is a type-only rewrite — no runtime behavior changes. M1's runtime path
already calls `factory(params)(ctx)` in `initializeTypeHelpers` and
`buildJsonSchemaValidatorRegistry`; M2 adds the matching type-level resolver.
M4 ([TML-2330]) wires production codec authoring to the new shape so columns
actually carry the `type` slot at the column site.

Refs codec-model-unification spec § AC-2, design/higher-order-codecs.md
§ Rewriting the no-emit FieldOutputType.
…ests for the M2 FieldOutputType rewrite

Synthetic test fixture for M2: type-only stubs that mimic the eventual M4 column-
authoring shape (a curried higher-order codec factory plus the descriptor and
storage.types entries that carry it). The fixture covers the three driving
spec cases:

- Case V — `vector(N)`: literal numeric inference (`vector(1536) -> VectorN<1536>`,
  not `VectorN<number>`).
- Case J — `json(schema)`: `StandardSchemaV1.InferOutput<S>` flows through the
  factory's return type to the column's resolved Js.
- Case C — `cipherStashLike(params)`: `(ctx: Ctx) => Codec<…>` shape locks for
  forward-compat.

Type tests exercise the AC-2 sub-bullets:

- AC-2.a inline factory call resolves through the factory's return type.
- AC-2.b literal numeric flows through (rejects `VectorN<number>`).
- AC-2.c JSON column with a Standard-Schema schema infers its output.
- AC-2.d non-parameterized column falls through to codec base output.
- AC-2.e nullable inline parameterized column resolves to `Js | null`.
- AC-2.f `typeRef` column resolves through `storage.types` to the same Js as
  the inline form.
- AC-2.g nullable typeRef column resolves to `Js | null`.

Plus a guarded regression test: `@ts-expect-error` on an `IsEqual<Resolved,
codecBase>` assertion stops failing if the rewrite ever regresses to the
M1 behavior of reading the codec's base output for parameterized columns.

A companion test in `@prisma-next/family-sql` confirms `ComputeColumnJsType`
delegates through `ExtractFieldOutputTypes<Contract>` transparently, matching
the spec § Non-goals item "ComputeColumnJsType rework — Already delegates …
picks up the fix transparently".

`@standard-schema/[email protected]` is added as a `devDependency` of
`@prisma-next/sql-contract-ts` (already a transitive dep via vitest); only
the synthetic fixture imports it.

Refs codec-model-unification spec § AC-2, plan § M2.
…+ pgJsonCodec descriptor (M3)

The pack-author surface for JSON columns: users write `json(productSchema)` at a
column site, and the column's TS type resolves to
`StandardSchemaV1.InferOutput<typeof productSchema>` via M2's no-emit
`FieldOutputType` resolver. The same schema validates wire payloads at runtime
inside `decode`. AC-5 from `projects/codec-model-unification/spec.md` is met.

What ships:

- `json<S extends StandardSchemaV1>(schema: S)` — curried higher-order codec
  factory whose return is `(ctx: Ctx) => Codec<"pg/json@1", readonly ["equality"],
  string, StandardSchemaV1.InferOutput<S>>`. The factory body uses
  `schema["~standard"].validate` to validate the parsed JSON; on failure it
  throws `RUNTIME.JSON_SCHEMA_VALIDATION_FAILED` via the framework runtime
  error envelope, matching the existing JSON validator registry path at
  `@prisma-next/sql-runtime`.
- `pgJsonCodec: ParameterizedCodecDescriptor<{ schema: StandardSchemaV1 }>` —
  sister descriptor that registers the factory with the framework. `paramsSchema`
  is an inline Standard Schema validator that asserts the params object carries
  a `~standard`-branded `schema` field (kept dependency-free of any one validator
  library). `renderOutputType` reads the schema's `expression` (Arktype-style)
  and falls back to `"unknown"` for schemas without a TS-source surface, per
  `design/authoring-ergonomics.md § JSON factory`. The descriptor's `factory`
  unwraps `params.schema` and delegates to `json(schema)`.
- New export entry `@prisma-next/adapter-postgres/codecs` exposing both `json`
  and `pgJsonCodec` (plus the `JsonCodec<S>` alias).

The legacy `json(schema?)` at `src/exports/column-types.ts` (a
`ColumnTypeDescriptor` factory pre-dating the higher-order model) and the
runtime descriptor at `src/exports/runtime.ts` (`buildJsonFactory(...)` keyed on
the serialized `{ schemaJson, type? }` shape) are NOT touched by M3 — the plan
gates production codec migration on M4. The new `json`/`pgJsonCodec` ship
side-by-side; M4 plumbs them through the contract-authoring builder and
deletes the legacy column-type helpers.

Tests:

- `test/json-factory.test-d.ts`: positive type tests asserting the factory's
  `Js` slot is `InferOutput<S>` for arktype schemas, the codec id is the
  literal `"pg/json@1"`, traits include `equality`, distinct schemas flow
  through with their own `InferOutput`, and the descriptor's `P` is
  `{ readonly schema: StandardSchemaV1 }`. Verified by probe (revert `Js` to
  `unknown` -> 4 type tests fail).
- `test/json-factory.test.ts`: 19 vitest cases — `decode` parses + validates,
  rejects payloads with missing fields and wrong types via the
  `RUNTIME.JSON_SCHEMA_VALIDATION_FAILED` error envelope, `encode` round-trips
  via `JSON.stringify`, factory invocation lifecycle (curried, independent
  instances), descriptor metadata (codecId match, `paramsSchema` rejects
  non-Standard-Schema values, `renderOutputType` reads `expression` and falls
  back to `"unknown"`), plus an inline snapshot of the rendered TS source for
  a representative arktype schema.

`@standard-schema/[email protected]` becomes a regular dep of `@prisma-next/adapter-postgres`
because `json`'s body imports the type at runtime in `decode`'s validator path.

Refs codec-model-unification spec § AC-5, design/authoring-ergonomics.md
§ JSON factory, plan § M3.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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/2-sql/3-tooling/emitter/src/index.ts`:
- Around line 350-357: The code is using forbidden blind casts (as unknown as
SqlStorage and as ContractModel<SqlModelStorage>) and an unsafe object literal
cast in the resolver path; replace these with explicit type predicate functions
(e.g. isSqlStorage(value): value is SqlStorage and isContractModelForSql(value):
value is ContractModel<SqlModelStorage>) and use them to narrow contract.storage
and model before accessing .storage.table/.fields, and also validate the table
and column exist via safe property checks rather than relying on mixed optional
chaining and null checks; update the resolution that computes column (currently
stored in variable column) to only index into sqlStorage.tables when
isSqlStorage and tableName/columnName are confirmed by the predicates.
🪄 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: 2b2b4a00-e4a7-4dd8-97fc-eff44fea07cd

📥 Commits

Reviewing files that changed from the base of the PR and between 161f7f1 and e949626.

📒 Files selected for processing (6)
  • examples/prisma-next-demo/src/prisma/contract.d.ts
  • packages/1-framework/1-core/framework-components/src/emission-types.ts
  • packages/1-framework/3-tooling/emitter/src/domain-type-generation.ts
  • packages/1-framework/3-tooling/emitter/src/generate-contract-dts.ts
  • packages/1-framework/3-tooling/emitter/test/domain-type-generation.test.ts
  • packages/2-sql/3-tooling/emitter/src/index.ts
🚧 Files skipped from review as they are similar to previous changes (4)
  • packages/1-framework/3-tooling/emitter/src/generate-contract-dts.ts
  • packages/1-framework/3-tooling/emitter/test/domain-type-generation.test.ts
  • examples/prisma-next-demo/src/prisma/contract.d.ts
  • packages/1-framework/3-tooling/emitter/src/domain-type-generation.ts

Comment on lines +350 to +357
const sqlStorage = contract.storage as unknown as SqlStorage | undefined;
const sqlModel = model as ContractModel<SqlModelStorage>;
const tableName = sqlModel.storage?.table;
const columnName = sqlModel.storage?.fields?.[fieldName]?.column;
if (!sqlStorage || !tableName || !columnName) return undefined;
const column = sqlStorage.tables?.[tableName]?.columns?.[columnName] as
| { readonly typeRef?: string }
| undefined;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Verify whether blind double-casts are present in the changed emitter file.
rg -n -C2 'as unknown as|as ContractModel<SqlModelStorage>|as\s*\|\s*\{\s*readonly typeRef\?: string\s*\}' packages/2-sql/3-tooling/emitter/src/index.ts

Repository: prisma/prisma-next

Length of output: 1456


🏁 Script executed:

sed -n '340,365p' packages/2-sql/3-tooling/emitter/src/index.ts

Repository: prisma/prisma-next

Length of output: 1288


Replace blind casts with type predicates in the resolver path.

Lines 350–357 use forbidden double-casts (as unknown as SqlStorage and as ContractModel<SqlModelStorage>) and an unsafe object literal cast. The code also mixes optional chaining with null checks inconsistently.

Replace with type predicates to narrow types safely:

Refactor
+function isSqlStorage(value: unknown): value is SqlStorage {
+  if (typeof value !== 'object' || value === null) return false;
+  return Object.hasOwn(value, 'tables') && Object.hasOwn(value, 'types');
+}
+
+function hasSqlModelStorage(model: ContractModel): model is ContractModel<SqlModelStorage> {
+  const storage = model.storage;
+  if (typeof storage !== 'object' || storage === null) return false;
+  return Object.hasOwn(storage, 'table') && Object.hasOwn(storage, 'fields');
+}
+
   resolveFieldTypeParams(
     _modelName: string,
     fieldName: string,
     model: ContractModel,
     contract: Contract,
   ): Record<string, unknown> | undefined {
@@
-    const sqlStorage = contract.storage as unknown as SqlStorage | undefined;
-    const sqlModel = model as ContractModel<SqlModelStorage>;
-    const tableName = sqlModel.storage?.table;
-    const columnName = sqlModel.storage?.fields?.[fieldName]?.column;
-    if (!sqlStorage || !tableName || !columnName) return undefined;
-    const column = sqlStorage.tables?.[tableName]?.columns?.[columnName] as
-      | { readonly typeRef?: string }
-      | undefined;
+    if (!isSqlStorage(contract.storage) || !hasSqlModelStorage(model)) return undefined;
+    const tableName = model.storage.table;
+    const columnName = model.storage.fields[fieldName]?.column;
+    if (!tableName || !columnName) return undefined;
+    const column = contract.storage.tables[tableName]?.columns[columnName];
     const typeRef = column?.typeRef;
     if (!typeRef) return undefined;
-    const typeInstance = sqlStorage.types?.[typeRef];
+    const typeInstance = contract.storage.types[typeRef];
     return typeInstance?.typeParams;
   },

Violates: "No blind casts in production code: as unknown as X is forbidden outside tests."

📝 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.

Suggested change
const sqlStorage = contract.storage as unknown as SqlStorage | undefined;
const sqlModel = model as ContractModel<SqlModelStorage>;
const tableName = sqlModel.storage?.table;
const columnName = sqlModel.storage?.fields?.[fieldName]?.column;
if (!sqlStorage || !tableName || !columnName) return undefined;
const column = sqlStorage.tables?.[tableName]?.columns?.[columnName] as
| { readonly typeRef?: string }
| undefined;
function isSqlStorage(value: unknown): value is SqlStorage {
if (typeof value !== 'object' || value === null) return false;
return Object.hasOwn(value, 'tables') && Object.hasOwn(value, 'types');
}
function hasSqlModelStorage(model: ContractModel): model is ContractModel<SqlModelStorage> {
const storage = model.storage;
if (typeof storage !== 'object' || storage === null) return false;
return Object.hasOwn(storage, 'table') && Object.hasOwn(storage, 'fields');
}
resolveFieldTypeParams(
_modelName: string,
fieldName: string,
model: ContractModel,
contract: Contract,
): Record<string, unknown> | undefined {
if (!isSqlStorage(contract.storage) || !hasSqlModelStorage(model)) return undefined;
const tableName = model.storage.table;
const columnName = model.storage.fields[fieldName]?.column;
if (!tableName || !columnName) return undefined;
const column = contract.storage.tables[tableName]?.columns[columnName];
const typeRef = column?.typeRef;
if (!typeRef) return undefined;
const typeInstance = contract.storage.types[typeRef];
return typeInstance?.typeParams;
}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/2-sql/3-tooling/emitter/src/index.ts` around lines 350 - 357, The
code is using forbidden blind casts (as unknown as SqlStorage and as
ContractModel<SqlModelStorage>) and an unsafe object literal cast in the
resolver path; replace these with explicit type predicate functions (e.g.
isSqlStorage(value): value is SqlStorage and isContractModelForSql(value): value
is ContractModel<SqlModelStorage>) and use them to narrow contract.storage and
model before accessing .storage.table/.fields, and also validate the table and
column exist via safe property checks rather than relying on mixed optional
chaining and null checks; update the resolution that computes column (currently
stored in variable column) to only index into sqlStorage.tables when
isSqlStorage and tableName/columnName are confirmed by the predicates.

…forColumn (Phase 3)

Pre-Phase-3, the SQL runtime had two parallel codec resolution paths.
Encode/decode dispatch did codecRegistry.get(codecId) for every cell on
every row through the legacy codecs: registry, which returns one shared
codec per codecId — so for parameterized codecs (vector with different
lengths in different columns; json with different schemas) the legacy
registry could not carry per-instance state. Per-instance state lived in
a separate parameterizedCodecs: descriptor registry consumed only by
initializeTypeHelpers and buildJsonSchemaValidatorRegistry. The two
registries could diverge.

This commit lands the unified dispatch interface.

New ContractCodecRegistry (in
packages/2-sql/4-lanes/relational-core/src/ast/codec-types.ts):

  interface ContractCodecRegistry {
    forColumn(table: string, column: string): Codec | undefined;
    forCodecId(codecId: string): Codec | undefined;
  }

forColumn(table, column) is the primary lookup for column-aware sites.
forCodecId(codecId) is the fallback for sites that do not carry the
(table, column) ref through to the encode/decode call site (the
SQL-builder param-encoding path is the load-bearing example: every
ParamRef carries codecId but not the column it relates to).

Built once at createExecutionContext via buildContractCodecRegistry,
which walks contract.storage.tables[].columns[] and resolves each
column to either:

- the per-instance codec for typeRef columns (reuses the named-instance
  codec already materialized by initializeTypeHelpers, so multiple
  columns sharing a typeRef share one codec instance);
- the per-instance codec for inline-typeParams columns (calls
  descriptor.factory(typeParams)({ name: "<anon:t.c>", usedAt: [...] })
  once per column);
- the shared codec from the legacy codecs: registry for
  non-parameterized columns.

The walk also derives the JSON-schema validator registry by extracting
the validate function off each per-column resolved codec via the
'json-validator' trait gate. Pre-Phase-3, buildJsonSchemaValidatorRegistry
walked the contract a second time and re-invoked descriptor.factory for
every inline-typeParams column; Phase 3 collapses that into the same
walk.

ExecutionContext gains a contractCodecs field alongside the existing
codecs field. Both stay: codecs is the source of shared, non-
parameterized codec instances and is used by the SQL builder + ORM
client for codec-level metadata (traits, scalar mapping, iteration);
contractCodecs is the dispatch interface for runtime encode/decode.

encoding.ts and decoding.ts now take a ContractCodecRegistry. The
encode-side prefers paramDescriptor.refs (when present), falling back
to paramDescriptor.codecId. The decode-side prefers the column ref
extracted from plan.meta.projection or plan.meta.refs.columns, falling
back to plan.meta.annotations.codecs[alias] / plan.meta.projectionTypes[alias].

The legacy codecs: registration of parameterized codec representative
instances stays in place; it is now the codec-id fallback source rather
than the primary dispatch path. Retiring it entirely is deferred per
the pushback in the Phase 3 implementer report (paramDescriptor.refs
is not populated by the SQL builder today; encode-side parameterized
dispatch needs the codec-id fallback to keep working until the param
descriptor builder is updated).

Tests: all 89 sql-runtime tests pass (including the parameterized-types
and json-schema-validation suites). All 111 test:packages task suites
pass. No emit-relevant changes.

Refs codec-registry-unification Phase 3.
…T3.6)

Six tests asserting the dispatch shape introduced in Phase 3:

- forColumn returns the per-instance codec for inline-typeParams
  parameterized columns (vector with literal length 768 — the resolved
  codec carries `length` on its meta, observably different from the
  codec-id fallback);
- forColumn returns the same per-instance codec for typeRef columns
  sharing a named storage type (two columns referencing the same
  Vector1536 entry resolve to one codec instance, so per-instance
  state survives the column-set);
- forColumn returns the shared legacy codec for non-parameterized
  columns (one codec instance shared across every column with that
  codec id);
- forColumn returns undefined for unknown columns / tables;
- forCodecId returns the legacy-registry codec by id (codec-id
  fallback path, used by encode-side sites that don't carry a column
  ref through to the dispatch call site);
- forCodecId returns undefined for unknown codec ids.

The vector test uses a custom `meta.length` field on the resolved
codec to make per-instance differentiation observable; the non-
parameterized test uses a custom `test/scalar@1` codec id to avoid
colliding with the default test target descriptor's pre-registered
codecs.

Refs codec-registry-unification Phase 3.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

🧹 Nitpick comments (1)
packages/2-sql/5-runtime/test/json-schema-validation.test.ts (1)

279-283: These tests still bypass the primary forColumn() path.

Because this wrapper hardcodes forColumn() to undefined, every encode/decode assertion in this file still runs through the legacy codec-id fallback. Add one case where forColumn() returns a different codec than forCodecId() and assert the runtime picks the column-bound instance, otherwise regressions in the new dispatch path will slip through here.

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/2-sql/5-runtime/test/json-schema-validation.test.ts` around lines
279 - 283, The tests are bypassing the primary dispatch path because
asContractCodecRegistry() returns forColumn: () => undefined; change the test
setup to include a case where forColumn() returns a distinct codec instance that
differs from forCodecId() and assert the runtime uses the column-bound codec;
specifically, modify asContractCodecRegistry (or create a variant in the test)
so forColumn(column) returns a mapped codec for a particular column name/type
while forCodecId(id) still returns the registry.get(id), then add one test that
encodes/decodes using that column and asserts the column-bound codec instance
(the one returned by forColumn) was used rather than the codec returned by
forCodecId.
🤖 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/codecs/encoding.ts`:
- Around line 16-25: The encode path currently falls back from
registry.forColumn(...) to registry.forCodecId(...) which drops per-instance
encoder state; update the logic in encoding.ts to stop using
registry.forCodecId(...) as a compatibility fallback and instead require a
resolved per-column codec or explicit ref on the ParamDescriptor. Thread either
the column ref (ParamDescriptor.refs) or the resolved codec instance onto
ParamDescriptor at construction sites so encode can always call the
column-resolved codec (registry.forColumn(...)) and remove the forCodecId
fallback from the encode path; update all call sites that create ParamDescriptor
to populate refs or attach the resolved codec so higher-order codecs that depend
on typeParams/Ctx retain their instance state.

In `@packages/2-sql/5-runtime/src/sql-context.ts`:
- Around line 389-424: The current logic silently falls back to
codecRegistry.get(column.codecId) even when a descriptor was found but
per-instance materialization failed; change it so that if descriptor is present
and we couldn't produce a per-column Codec (resolvedCodec is still falsy after
attempting column.typeRef and column.typeParams resolution), you do not call
codecRegistry.get and instead surface a clear runtime error: throw (or return a
failing Result) that includes the codecId, tableName and columnName and a
message about missing/invalid type parameters; keep the existing fallback to
codecRegistry.get(column.codecId) only when no descriptor was found (i.e.,
descriptor is undefined). Ensure this change touches the resolution block around
resolvedCodec, descriptor, validateTypeParams, descriptor.factory and
codecRegistry.get so unresolved parameterized declarations fail fast.

---

Nitpick comments:
In `@packages/2-sql/5-runtime/test/json-schema-validation.test.ts`:
- Around line 279-283: The tests are bypassing the primary dispatch path because
asContractCodecRegistry() returns forColumn: () => undefined; change the test
setup to include a case where forColumn() returns a distinct codec instance that
differs from forCodecId() and assert the runtime uses the column-bound codec;
specifically, modify asContractCodecRegistry (or create a variant in the test)
so forColumn(column) returns a mapped codec for a particular column name/type
while forCodecId(id) still returns the registry.get(id), then add one test that
encodes/decodes using that column and asserts the column-bound codec instance
(the one returned by forColumn) was used rather than the codec returned by
forCodecId.
🪄 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: a8249b16-2c45-4671-89ff-712a1714df37

📥 Commits

Reviewing files that changed from the base of the PR and between e949626 and ba07ad1.

📒 Files selected for processing (9)
  • packages/2-sql/4-lanes/relational-core/src/ast/codec-types.ts
  • packages/2-sql/4-lanes/relational-core/src/query-lane-context.ts
  • packages/2-sql/4-lanes/relational-core/test/utils.ts
  • packages/2-sql/5-runtime/src/codecs/decoding.ts
  • packages/2-sql/5-runtime/src/codecs/encoding.ts
  • packages/2-sql/5-runtime/src/sql-context.ts
  • packages/2-sql/5-runtime/src/sql-runtime.ts
  • packages/2-sql/5-runtime/test/contract-codec-registry.test.ts
  • packages/2-sql/5-runtime/test/json-schema-validation.test.ts

Comment on lines +16 to 25
if (paramDescriptor.refs) {
const codec = registry.forColumn(paramDescriptor.refs.table, paramDescriptor.refs.column);
if (codec) {
return codec;
}
}

if (paramDescriptor.codecId) {
const codec = registry.get(paramDescriptor.codecId);
const codec = registry.forCodecId(paramDescriptor.codecId);
if (codec) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

forCodecId() fallback drops per-instance encoder state.

ParamDescriptor.refs is still optional, so most parameterized params will hit this fallback and encode through a representative codec instead of the column’s resolved instance. That means any higher-order codec whose encode depends on typeParams or Ctx will silently serialize the wrong wire value here. Please thread the column ref or resolved codec onto param descriptors and remove the compatibility fallback on the encode path.

As per coding guidelines, "Do not add backward-compatibility shims; update call sites instead".

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/2-sql/5-runtime/src/codecs/encoding.ts` around lines 16 - 25, The
encode path currently falls back from registry.forColumn(...) to
registry.forCodecId(...) which drops per-instance encoder state; update the
logic in encoding.ts to stop using registry.forCodecId(...) as a compatibility
fallback and instead require a resolved per-column codec or explicit ref on the
ParamDescriptor. Thread either the column ref (ParamDescriptor.refs) or the
resolved codec instance onto ParamDescriptor at construction sites so encode can
always call the column-resolved codec (registry.forColumn(...)) and remove the
forCodecId fallback from the encode path; update all call sites that create
ParamDescriptor to populate refs or attach the resolved codec so higher-order
codecs that depend on typeParams/Ctx retain their instance state.

Comment on lines +389 to +424
if (descriptor) {
if (column.typeRef) {
// The named instance was already materialized once by
// `initializeTypeHelpers`; reuse it so multiple columns sharing
// the same typeRef share one codec instance (and any per-instance
// helper state on it).
const helper = types[column.typeRef];
// The TypeHelperRegistry stores either the resolved Codec or, when
// no descriptor matched the named instance, the StorageTypeInstance
// verbatim. The Codec branch is identified by its `id` field.
if (helper && typeof helper === 'object' && 'id' in helper && 'decode' in helper) {
resolvedCodec = helper as Codec;
}
} else if (column.typeParams) {
const validatedParams = validateTypeParams(column.typeParams, descriptor, {
tableName,
columnName,
});
resolvedCodec = descriptor.factory(validatedParams)({
name: `<anon:${tableName}.${columnName}>`,
usedAt: [{ table: tableName, column: columnName }],
});
}
continue;
}

// Case 2: inline typeParams with schema → compile via init hook
if (column.typeParams) {
const descriptor = codecDescriptors.get(column.codecId);
if (descriptor?.init) {
const helper = descriptor.init(column.typeParams) as
| { validate?: JsonSchemaValidateFn }
| undefined;
if (helper?.validate) {
validators.set(key, helper.validate);
}
// Non-parameterized columns (or parameterized columns whose descriptor
// hasn't been registered) fall back to the legacy registry. The legacy
// registry is the source of shared codec instances for non-
// parameterized codec ids; for parameterized ids it carries the
// representative instance the runtime descriptor still registers
// (Phase 3 keeps that registration as a `forCodecId` fallback for
// sites that don't carry `(table, column)` through to the dispatch
// call site).
if (!resolvedCodec) {
resolvedCodec = codecRegistry.get(column.codecId);
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Don't silently downgrade unresolved parameterized columns to the shared codec.

If descriptor exists but the column's per-instance codec cannot be materialized, Line 422 falls back to codecRegistry.get(column.codecId). That turns a broken parameterized declaration into a "successful" shared-codec match, so the column can be encoded, decoded, and JSON-validated with the wrong instance instead of failing fast.

Suggested fix
       if (descriptor) {
         if (column.typeRef) {
           // The named instance was already materialized once by
           // `initializeTypeHelpers`; reuse it so multiple columns sharing
           // the same typeRef share one codec instance (and any per-instance
           // helper state on it).
           const helper = types[column.typeRef];
           // The TypeHelperRegistry stores either the resolved Codec or, when
           // no descriptor matched the named instance, the StorageTypeInstance
           // verbatim. The Codec branch is identified by its `id` field.
           if (helper && typeof helper === 'object' && 'id' in helper && 'decode' in helper) {
             resolvedCodec = helper as Codec;
           }
         } else if (column.typeParams) {
           const validatedParams = validateTypeParams(column.typeParams, descriptor, {
             tableName,
             columnName,
           });
           resolvedCodec = descriptor.factory(validatedParams)({
             name: `<anon:${tableName}.${columnName}>`,
             usedAt: [{ table: tableName, column: columnName }],
           });
         }
+        if (!resolvedCodec) {
+          throw runtimeError(
+            'RUNTIME.PARAMETERIZED_CODEC_RESOLUTION_FAILED',
+            `Column '${tableName}.${columnName}' declares parameterized codec '${column.codecId}' but no per-instance codec could be resolved.`,
+            {
+              tableName,
+              columnName,
+              codecId: column.codecId,
+              typeRef: column.typeRef,
+              typeParams: column.typeParams,
+            },
+          );
+        }
       }
 
       // Non-parameterized columns (or parameterized columns whose descriptor
       // hasn't been registered) fall back to the legacy registry.
       if (!resolvedCodec) {
         resolvedCodec = codecRegistry.get(column.codecId);
       }

As per coding guidelines, "Do not treat missing type parameters as a successful match when the contract declares them."

🤖 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 389 - 424, The
current logic silently falls back to codecRegistry.get(column.codecId) even when
a descriptor was found but per-instance materialization failed; change it so
that if descriptor is present and we couldn't produce a per-column Codec
(resolvedCodec is still falsy after attempting column.typeRef and
column.typeParams resolution), you do not call codecRegistry.get and instead
surface a clear runtime error: throw (or return a failing Result) that includes
the codecId, tableName and columnName and a message about missing/invalid type
parameters; keep the existing fallback to codecRegistry.get(column.codecId) only
when no descriptor was found (i.e., descriptor is undefined). Ensure this change
touches the resolution block around resolvedCodec, descriptor,
validateTypeParams, descriptor.factory and codecRegistry.get so unresolved
parameterized declarations fail fast.

Late-add the project artifacts for the codec-registry-unification
follow-up. The spec and plan codify the unified CodecDescriptor
design that emerged mid-project after the user surfaced two
structural defects in the prior framing:

(1) A parameterized codec without parameters is structurally
meaningless, but the legacy codec registry was registering exactly
that for parameterized codec ids — pgVectorRepresentativeCodec is a
length-1 placeholder vector codec that exists solely so codec-id-
keyed metadata reads keep working. Functions for pgvector by
coincidence (vector wire format is length-independent); broken for
any future codec whose encode/decode actually depends on parameters.

(2) The descriptor/instance pattern is the structural answer to
static-vs-instance data, and applying it uniformly subsumes the
parameterized/non-parameterized branching that the orchestrator was
trying to patch around. Every codec is described by a single
CodecDescriptor<P = void>, where P = void is the degenerate
non-parameterized case.

The spec records the design (CodecDescriptor<P = void>; descriptor
map as single source of codec-id-keyed metadata; forColumn as
column-aware dispatch; JsonSchemaValidatorRegistry deletion;
per-library JSON extensions). The plan records the remaining work
(Phase 3.5 unified descriptor migration; Phase 4 arktype-json
extension; Phase 5 ADR update + close-out).

Phases 1, 2, 3 already landed on this branch:
- 161f7f1 — pgvector file consolidation (Phase 1)
- ee82929 + e949626 — typeRef emit-path bug fix (Phase 2)
- 245c861 + 8a9311c + ba07ad1 — ContractCodecRegistry.forColumn
  dispatch interface (Phase 3, with deferred T3.4 retirement).

The remaining phases need the spec and plan as a stable reference
because the design solidified mid-project and the implementer and
reviewer subagents were operating on stale orchestrator framing
otherwise.
…uire traits/targetTypes (Phase 3.5 T3.5.1)

Define the unified CodecDescriptor type in framework-components and alias
ParameterizedCodecDescriptor to it. Every descriptor must now ship traits
and targetTypes — the descriptor is the single source of truth for codec-
id-keyed metadata.

Existing descriptor instances (postgres parameterized codecs, pgvector,
mongo vector, JSON descriptors) lift their codec-id-keyed metadata onto
the descriptor literal. No runtime behavior change yet — the runtime Codec
instance still carries id/traits/targetTypes redundantly; the metadata
narrowing of Codec lands separately.

Per spec: every codec is a descriptor; non-parameterized codecs are the
degenerate case (P = void).

Refs codec-registry-unification spec § Decision; AC-1.
…For (Phase 3.5 T3.5.5-T3.5.8)

Build a CodecDescriptorRegistry at SQL execution-context construction —
parameterized descriptors land directly; non-parameterized codecs registered
through the legacy `codecs:` slot are synthesized into CodecDescriptor<void>
via framework-components synthesizeNonParameterizedDescriptor. Both kinds
share one map keyed by codecId, no branching.

Migrate codec-id-keyed metadata reads onto the descriptor map:
- sql-orm-client model-accessor and filters consult
  context.codecDescriptors.descriptorFor(codecId).traits, replacing the
  CodecRegistry.traitsOf branch and the codecs.values() iteration.
- validateCodecRegistryCompleteness consults the descriptor map.

The legacy CodecRegistry stays as the source of shared codec instances for
non-parameterized codecs and as the back-compat ParamRef.codecId fallback;
the descriptor map subsumes it for codec-id-keyed metadata reads.

Refs codec-registry-unification spec § Decision; ACs 3, 4, 6.
…(Phase 3.5 T3.5.6)

Rewire buildContractCodecRegistry to consult the unified descriptor map
for every column. Non-parameterized columns now call descriptor.factory()
(constant for non-parameterized codecs) and cache the result by codec id —
columns sharing a non-parameterized codec id share one resolved Codec
without explicit caching. Parameterized columns continue to use their per-
instance factory invocation (typeRef → cached named instance; typeParams
→ per-column anonymous instance).

forCodecId returns the contract-walk-derived codec, falling back to the
legacy codec registry only for parameterized codec ids whose contract
columns lack typeRef/typeParams (where the descriptor cannot instantiate).
This narrow fallback retires once ParamRef.refs is threaded everywhere
(future Phase 3.5 T3.5.9-T3.5.11).

Refs codec-registry-unification spec § AC-4.
…(Phase 3.5 T3.5.14)

Add CodecDescriptorRegistry test suite asserting non-branching reads:
descriptorFor returns the registered descriptor for parameterized AND non-
parameterized codec ids using the same call shape, traits/targetTypes are
the descriptor-keyed source of truth, and values() iterates every
descriptor including synthesized ones for legacy-registered codecs.

Refs codec-registry-unification spec § Decision; AC-3.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 3

♻️ Duplicate comments (4)
packages/3-targets/6-adapters/postgres/src/codecs/json-factory.ts (1)

82-137: ⚠️ Potential issue | 🟠 Major

Expose validate + 'json-validator' on the materialized codec.

At Line 91 and Line 95, the codec validates only inside decode and does not expose a validate hook/trait, so validator-registry extraction can skip this codec and encode-side JSON schema validation is lost.

Suggested patch
     return (_ctx) => {
       type JsType = StandardSchemaV1.InferOutput<S>;
+      const validatePayload = (value: unknown): JsType => {
+        const result = schema['~standard'].validate(value);
+        if (result instanceof Promise) {
+          throw runtimeError(
+            'RUNTIME.JSON_SCHEMA_VALIDATION_FAILED',
+            `JSON schema validation failed: schema for codec '${codecId}' returned a Promise; runtime validation requires a synchronous Standard Schema validator.`,
+            { codecId },
+          );
+        }
+        if (result.issues) {
+          const issues = result.issues.map((issue) => issue.message).join('; ');
+          throw runtimeError(
+            'RUNTIME.JSON_SCHEMA_VALIDATION_FAILED',
+            `JSON schema validation failed for codec '${codecId}': ${issues}`,
+            { codecId, issues: result.issues },
+          );
+        }
+        return result.value as JsType;
+      };
       return {
         id: codecId,
         targetTypes: [nativeType] as const,
-        traits: ['equality'] as const,
+        traits: ['equality', 'json-validator'] as const,
         encode(value: JsType): string {
           return JSON.stringify(value);
         },
         decode(wire: string): JsType {
-          const parsed: unknown = JSON.parse(wire);
-          const result = schema['~standard'].validate(parsed);
-          ...
-          return result.value as JsType;
+          return validatePayload(JSON.parse(wire));
+        },
+        validate(jsonValue: JsonValue): void {
+          validatePayload(jsonValue);
         },
🤖 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/codecs/json-factory.ts` around
lines 82 - 137, The codec returned by buildJsonHoCFactory currently only
validates inside decode, so add a synchronous validate hook and the
'json-validator' trait to the materialized codec so validator registries detect
it and encode-side validation is preserved: update the returned object
(identified by buildJsonHoCFactory and codecId) to include 'json-validator' in
traits and implement a validate(value: unknown) method that calls
schema['~standard'].validate(value), mirrors the existing Promise/issues
runtimeError handling, and returns the validated value (or throws on failure);
also invoke this validate method from encode before JSON.stringify to ensure
encode-side JSON schema validation runs.
packages/2-sql/5-runtime/src/sql-context.ts (1)

461-512: ⚠️ Potential issue | 🟠 Major

Fail fast when a parameterized codec column cannot be materialized.

When a descriptor exists but no per-column instance is resolved, forCodecId() can still return the legacy fallback codec. That masks invalid/missing params instead of surfacing a contract/runtime error.

Suggested fix
       if (descriptor) {
         const isParameterized = parameterizedDescriptors.has(column.codecId);
@@
-        // else: parameterized codec id with no typeRef and no typeParams.
-        // The column is missing the params the descriptor needs to
-        // instantiate. Leave `resolvedCodec` undefined; encode/decode for
-        // this column will produce raw values.
+        if (isParameterized && !resolvedCodec) {
+          throw runtimeError(
+            'RUNTIME.PARAMETERIZED_CODEC_RESOLUTION_FAILED',
+            `Column '${tableName}.${columnName}' declares parameterized codec '${column.codecId}' but no per-instance codec could be resolved.`,
+            {
+              tableName,
+              columnName,
+              codecId: column.codecId,
+              typeRef: column.typeRef,
+              typeParams: column.typeParams,
+            },
+          );
+        }
       }

As per coding guidelines, "Do not treat missing type parameters as a successful match when the contract declares them."

Also applies to: 542-550

🤖 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 461 - 512, When a
descriptor exists but we couldn't produce a per-column codec instance (no
typeRef and no typeParams), fail fast instead of letting forCodecId()/legacy
fallbacks mask missing params: after the existing descriptor/parameterized logic
in sql-context.ts (the block that checks
parameterizedDescriptors.has(column.codecId) and sets resolvedCodec), add a
guard that if parameterizedDescriptors.has(column.codecId) is true and
resolvedCodec is still undefined, throw a descriptive runtime error including
the tableName, columnName and column.codecId so missing/invalid type parameters
are surfaced immediately; apply the same guard in the analogous branch around
lines 542-550.
packages/3-extensions/pgvector/src/core/vector-codec.ts (1)

105-120: ⚠️ Potential issue | 🟠 Major

Enforce N at runtime inside vectorCodecForLength() and remove blind JSON/vector casts.

The current factory ignores length, so Vector<3> and Vector<1536> behave identically at runtime. This leaks invalid dimensions through encode/decodeJson while preserving a branded type.

Suggested hardening
+function assertVectorLength<N extends number>(value: readonly number[], length: N): Vector<N> {
+  if (value.length !== length) {
+    throw new RangeError(`pgvector: expected ${length} dimensions, got ${value.length}`);
+  }
+  return value as Vector<N>;
+}
+
-export function vectorCodecForLength<N extends number>(_length: N): (ctx: Ctx) => VectorCodec<N> {
+export function vectorCodecForLength<N extends number>(length: N): (ctx: Ctx) => VectorCodec<N> {
   return (_ctx: Ctx) => ({
@@
-    encode: encodeVector,
-    decode: decodeVector as (wire: string) => Vector<N>,
-    encodeJson: (value: Vector<N>) => value as unknown as JsonValue,
-    decodeJson: (json: JsonValue) => json as unknown as Vector<N>,
+    encode: (value: Vector<N>) => encodeVector(assertVectorLength(value, length)),
+    decode: (wire: string) => assertVectorLength(decodeVector(wire), length),
+    encodeJson: (value: Vector<N>) => [...assertVectorLength(value, length)],
+    decodeJson: (json: JsonValue) => {
+      if (!Array.isArray(json) || !json.every((v) => typeof v === 'number')) {
+        throw new TypeError('pgvector: decodeJson expected number[]');
+      }
+      return assertVectorLength(json, length);
+    },

As per coding guidelines, "No blind casts in production code: as unknown as X is forbidden outside tests. Prefer type predicates or fix the type surface."

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/3-extensions/pgvector/src/core/vector-codec.ts` around lines 105 -
120, vectorCodecForLength currently ignores the generic N and uses blind casts
(encodeJson/decodeJson and decode), so vectors of wrong length slip through;
update vectorCodecForLength (and its returned object's
encode/decode/encodeJson/decodeJson handlers) to validate the runtime length
equals the provided _length: implement a small runtime guard/helper (e.g.,
assertVectorLength or isVectorOfLength) that checks the wire/JSON value is an
array of numbers of length N and throws or returns an error when mismatched, use
that guard in encode to reject incorrect-length inputs, in decode/decodeJson to
validate before casting to Vector<N>, and remove all `as unknown as` blind casts
so the only cast occurs after a successful runtime check inside
vectorCodecForLength.
packages/1-framework/1-core/framework-components/test/codec-types.types.test-d.ts (1)

145-148: ⚠️ Potential issue | 🟡 Minor

Replace deprecated toMatchTypeOf() in this type test.

Use the repo’s approved never assertion form.

Suggested fix
 test('renderOutputType is removed from the base Codec interface', () => {
-  type Keys = keyof Codec;
-  expectTypeOf<Keys>().not.toMatchTypeOf<'renderOutputType'>();
+  expectTypeOf<Extract<keyof Codec, 'renderOutputType'>>().toEqualTypeOf(undefined as never);
 });

As per coding guidelines, "**/*.test-d.ts: Do not use the deprecated toMatchTypeOf() matcher in Vitest's expectTypeOf API."

🤖 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/test/codec-types.types.test-d.ts`
around lines 145 - 148, The test should stop using the deprecated toMatchTypeOf
and instead assert that 'renderOutputType' cannot be extracted from Keys;
replace the expectTypeOf line with an assertion using Extract and the repo's
never matcher, e.g. assert Extract<Keys, 'renderOutputType'> is never by calling
expectTypeOf<Extract<Keys, 'renderOutputType'>>().toBeNever(); keep the same
test name and references to Codec, Keys and 'renderOutputType' so the intent is
unchanged.
🤖 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/4-lanes/relational-core/src/query-lane-context.ts`:
- Around line 15-30: Replace the use of the any generic and the biome-ignore
lint comments on the public registry interface by changing all occurrences of
CodecDescriptor<any> to CodecDescriptor<unknown> and removing the three
biome-ignore suppression lines; update the signatures for descriptorFor, values,
and byTargetType to use CodecDescriptor<unknown> so callers still access base
properties (codecId, traits, targetTypes) without disabling lints.

In `@packages/2-sql/5-runtime/src/codecs/validation.ts`:
- Around line 39-48: validateContractCodecMappings currently only checks
codecDescriptors.descriptorFor(codecId) but must also ensure the codec is
resolvable via contractCodecs.forColumn(table, column) to prevent runtime
fallback; update validateContractCodecMappings (and use
extractCodecIdsFromColumns output) to, for each invalid match, split the key
into table and column, then call the contract's codec resolver
(contract.contractCodecs.forColumn or contractCodecs.forColumn) and treat it as
invalid if that resolver returns undefined/unresolved—add those entries to
invalidCodecs and keep the existing error reporting logic so startup fails when
either the descriptor is missing or the column-level codec cannot be resolved.

In
`@packages/3-targets/6-adapters/postgres/src/codecs/postgres-codec-descriptors.ts`:
- Around line 297-299: The value jsonLegacyParamsSchema is being force-cast via
"as unknown as StandardSchemaV1<JsonLegacyParams>", which hides a real type
mismatch; instead remove the blind double-cast on jsonLegacyParamsSchema and
make the types align: either change the declared type of jsonLegacyArktype (the
source) to the correct StandardSchemaV1<JsonLegacyParams>, or adapt/transform
jsonLegacyArktype into a proper StandardSchemaV1<JsonLegacyParams> (e.g., build
a wrapper or mapping function that produces the correct shape) or implement a
type predicate/converter that validates and returns
StandardSchemaV1<JsonLegacyParams>; ensure the final exported symbol
jsonLegacyParamsSchema has an accurate static type without using "as unknown
as".

---

Duplicate comments:
In
`@packages/1-framework/1-core/framework-components/test/codec-types.types.test-d.ts`:
- Around line 145-148: The test should stop using the deprecated toMatchTypeOf
and instead assert that 'renderOutputType' cannot be extracted from Keys;
replace the expectTypeOf line with an assertion using Extract and the repo's
never matcher, e.g. assert Extract<Keys, 'renderOutputType'> is never by calling
expectTypeOf<Extract<Keys, 'renderOutputType'>>().toBeNever(); keep the same
test name and references to Codec, Keys and 'renderOutputType' so the intent is
unchanged.

In `@packages/2-sql/5-runtime/src/sql-context.ts`:
- Around line 461-512: When a descriptor exists but we couldn't produce a
per-column codec instance (no typeRef and no typeParams), fail fast instead of
letting forCodecId()/legacy fallbacks mask missing params: after the existing
descriptor/parameterized logic in sql-context.ts (the block that checks
parameterizedDescriptors.has(column.codecId) and sets resolvedCodec), add a
guard that if parameterizedDescriptors.has(column.codecId) is true and
resolvedCodec is still undefined, throw a descriptive runtime error including
the tableName, columnName and column.codecId so missing/invalid type parameters
are surfaced immediately; apply the same guard in the analogous branch around
lines 542-550.

In `@packages/3-extensions/pgvector/src/core/vector-codec.ts`:
- Around line 105-120: vectorCodecForLength currently ignores the generic N and
uses blind casts (encodeJson/decodeJson and decode), so vectors of wrong length
slip through; update vectorCodecForLength (and its returned object's
encode/decode/encodeJson/decodeJson handlers) to validate the runtime length
equals the provided _length: implement a small runtime guard/helper (e.g.,
assertVectorLength or isVectorOfLength) that checks the wire/JSON value is an
array of numbers of length N and throws or returns an error when mismatched, use
that guard in encode to reject incorrect-length inputs, in decode/decodeJson to
validate before casting to Vector<N>, and remove all `as unknown as` blind casts
so the only cast occurs after a successful runtime check inside
vectorCodecForLength.

In `@packages/3-targets/6-adapters/postgres/src/codecs/json-factory.ts`:
- Around line 82-137: The codec returned by buildJsonHoCFactory currently only
validates inside decode, so add a synchronous validate hook and the
'json-validator' trait to the materialized codec so validator registries detect
it and encode-side validation is preserved: update the returned object
(identified by buildJsonHoCFactory and codecId) to include 'json-validator' in
traits and implement a validate(value: unknown) method that calls
schema['~standard'].validate(value), mirrors the existing Promise/issues
runtimeError handling, and returns the validated value (or throws on failure);
also invoke this validate method from encode before JSON.stringify to ensure
encode-side JSON schema validation runs.
🪄 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: b9a9e3d8-9196-442b-972c-0fa39f550b3c

📥 Commits

Reviewing files that changed from the base of the PR and between ba07ad1 and 8b8099f.

⛔ Files ignored due to path filters (2)
  • projects/codec-registry-unification/plan.md is excluded by !projects/**
  • projects/codec-registry-unification/spec.md is excluded by !projects/**
📒 Files selected for processing (20)
  • packages/1-framework/1-core/framework-components/src/codec-types.ts
  • packages/1-framework/1-core/framework-components/src/exports/codec.ts
  • packages/1-framework/1-core/framework-components/test/codec-types.types.test-d.ts
  • packages/1-framework/3-tooling/emitter/test/domain-type-generation.test.ts
  • packages/2-sql/4-lanes/relational-core/src/query-lane-context.ts
  • packages/2-sql/4-lanes/relational-core/test/utils.ts
  • packages/2-sql/5-runtime/src/codecs/validation.ts
  • packages/2-sql/5-runtime/src/sql-context.ts
  • packages/2-sql/5-runtime/src/sql-runtime.ts
  • packages/2-sql/5-runtime/test/contract-codec-registry.test.ts
  • packages/2-sql/5-runtime/test/json-schema-validation.test.ts
  • packages/2-sql/5-runtime/test/parameterized-types.test.ts
  • packages/3-extensions/pgvector/src/core/vector-codec.ts
  • packages/3-extensions/sql-orm-client/src/filters.ts
  • packages/3-extensions/sql-orm-client/src/model-accessor.ts
  • packages/3-extensions/sql-orm-client/test/model-accessor.test.ts
  • packages/3-mongo-target/2-mongo-adapter/src/codecs/vector-factory.ts
  • packages/3-targets/6-adapters/postgres/src/codecs/json-factory.ts
  • packages/3-targets/6-adapters/postgres/src/codecs/postgres-codec-descriptors.ts
  • packages/3-targets/6-adapters/postgres/src/exports/runtime.ts
🚧 Files skipped from review as they are similar to previous changes (3)
  • packages/3-mongo-target/2-mongo-adapter/src/codecs/vector-factory.ts
  • packages/1-framework/3-tooling/emitter/test/domain-type-generation.test.ts
  • packages/2-sql/5-runtime/test/contract-codec-registry.test.ts

Comment on lines +15 to +30
// biome-ignore lint/suspicious/noExplicitAny: descriptors carry distinct param shapes per codec; the registry is heterogeneous and the consumer narrows per codec.
descriptorFor(codecId: string): CodecDescriptor<any> | undefined;
/**
* All registered descriptors. Used by `validateCodecRegistryCompleteness`
* and other startup-time consumers that enumerate descriptors.
*/
// biome-ignore lint/suspicious/noExplicitAny: heterogeneous descriptor map; consumer narrows per codec.
values(): IterableIterator<CodecDescriptor<any>>;
/**
* Descriptors indexed by `targetTypes[i]` (each scalar type the codec
* advertises). Used by sql-orm-client's scalar→codec lookups in place of
* `CodecRegistry.getByScalar`. Multiple descriptors may map to the same
* scalar type; ordering reflects registration order.
*/
// biome-ignore lint/suspicious/noExplicitAny: heterogeneous descriptor map; consumer narrows per codec.
byTargetType(targetType: string): readonly CodecDescriptor<any>[];

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

find packages -name "query-lane-context.ts" -type f

Repository: prisma/prisma-next

Length of output: 200


🏁 Script executed:

sed -n '1,35p' packages/2-sql/4-lanes/relational-core/src/query-lane-context.ts

Repository: prisma/prisma-next

Length of output: 2006


🏁 Script executed:

cat packages/2-sql/4-lanes/relational-core/src/query-lane-context.ts | head -40

Repository: prisma/prisma-next

Length of output: 2221


🏁 Script executed:

grep -r "Never use the.*any.*type" --include="*.{md,txt}" . 2>/dev/null | head -5

Repository: prisma/prisma-next

Length of output: 44


🏁 Script executed:

# Check if there are any documented exceptions or patterns for heterogeneous registries
rg "CodecDescriptor.*unknown" --type ts -A 2 -B 2

Repository: prisma/prisma-next

Length of output: 1089


🏁 Script executed:

# Check how CodecDescriptor is used elsewhere in the codebase
rg "CodecDescriptor<" packages/2-sql --type ts | head -20

Repository: prisma/prisma-next

Length of output: 1182


🏁 Script executed:

# Check for any documented exceptions or patterns for heterogeneous types
rg "heterogeneous" --type ts -B 3 -A 3 packages/2-sql

Repository: prisma/prisma-next

Length of output: 3141


🏁 Script executed:

# Look for guidance on type narrowing patterns
rg "consumer narrows" --type ts -B 5 -A 5

Repository: prisma/prisma-next

Length of output: 4408


🏁 Script executed:

# Check how CodecDescriptorRegistry methods are actually used
rg "descriptorFor\(" packages/2-sql --type ts -B 2 -A 3 | head -40

Repository: prisma/prisma-next

Length of output: 3272


🏁 Script executed:

# Check usage of values() and byTargetType()
rg "\.values\(\)|\.byTargetType\(" packages/2-sql --type ts -B 2 -A 3

Repository: prisma/prisma-next

Length of output: 6043


🏁 Script executed:

# Check CodecDescriptor definition to understand the generic parameter
rg "interface CodecDescriptor" packages/1-framework --type ts -A 10

Repository: prisma/prisma-next

Length of output: 1415


🏁 Script executed:

# Check if similar patterns exist elsewhere without suppressions
rg "CodecDescriptor<unknown>" packages --type ts

Repository: prisma/prisma-next

Length of output: 44


🏁 Script executed:

# Verify that accessing properties on unknown-typed descriptors is type-safe
rg "descriptor\?.codecId|descriptor\?.traits|descriptor\?.targetTypes" packages --type ts | head -10

Repository: prisma/prisma-next

Length of output: 1635


Remove any type and Biome suppression from the public registry interface.

The interface can stay heterogeneous using CodecDescriptor<unknown> without suppressions. Callers only access base properties (codecId, traits, targetTypes) that exist regardless of the generic parameter.

Type-only fix
 export interface CodecDescriptorRegistry {
-  // biome-ignore lint/suspicious/noExplicitAny: descriptors carry distinct param shapes per codec; the registry is heterogeneous and the consumer narrows per codec.
-  descriptorFor(codecId: string): CodecDescriptor<any> | undefined;
+  descriptorFor(codecId: string): CodecDescriptor<unknown> | undefined;
@@
-  // biome-ignore lint/suspicious/noExplicitAny: heterogeneous descriptor map; consumer narrows per codec.
-  values(): IterableIterator<CodecDescriptor<any>>;
+  values(): IterableIterator<CodecDescriptor<unknown>>;
@@
-  // biome-ignore lint/suspicious/noExplicitAny: heterogeneous descriptor map; consumer narrows per codec.
-  byTargetType(targetType: string): readonly CodecDescriptor<any>[];
+  byTargetType(targetType: string): readonly CodecDescriptor<unknown>[];
 }

Per coding guidelines: "Never use the any type in TypeScript" and "Never suppress biome lints."

🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/2-sql/4-lanes/relational-core/src/query-lane-context.ts` around
lines 15 - 30, Replace the use of the any generic and the biome-ignore lint
comments on the public registry interface by changing all occurrences of
CodecDescriptor<any> to CodecDescriptor<unknown> and removing the three
biome-ignore suppression lines; update the signatures for descriptorFor, values,
and byTargetType to use CodecDescriptor<unknown> so callers still access base
properties (codecId, traits, targetTypes) without disabling lints.

Comment on lines 39 to 48
export function validateContractCodecMappings(
registry: CodecRegistry,
codecDescriptors: CodecDescriptorRegistry,
contract: Contract<SqlStorage>,
): void {
const codecIds = extractCodecIdsFromColumns(contract);
const invalidCodecs: Array<{ table: string; column: string; codecId: string }> = [];

for (const [key, codecId] of codecIds.entries()) {
if (!registry.has(codecId)) {
if (codecDescriptors.descriptorFor(codecId) === undefined) {
const parts = key.split('.');

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Validate resolvable contract codecs, not just descriptor presence.

At Line 47, descriptor existence alone is insufficient for runtime safety. A descriptor can exist while contractCodecs.forColumn(table, column) is unresolved, which lets startup pass but causes silent encode/decode fallback later.

Suggested direction
-export function validateContractCodecMappings(
-  codecDescriptors: CodecDescriptorRegistry,
-  contract: Contract<SqlStorage>,
-): void {
+export function validateContractCodecMappings(
+  codecDescriptors: CodecDescriptorRegistry,
+  contractCodecs: ContractCodecRegistry,
+  contract: Contract<SqlStorage>,
+): void {
   const codecIds = extractCodecIdsFromColumns(contract);
-  const invalidCodecs: Array<{ table: string; column: string; codecId: string }> = [];
+  const invalidCodecs: Array<{ table: string; column: string; codecId: string; reason: string }> = [];

   for (const [key, codecId] of codecIds.entries()) {
+    const [table, column] = key.split('.');
     if (codecDescriptors.descriptorFor(codecId) === undefined) {
-      ...
-      invalidCodecs.push({ table, column, codecId });
+      invalidCodecs.push({ table: table ?? '', column: column ?? '', codecId, reason: 'descriptor-missing' });
+      continue;
+    }
+    if (!table || !column || contractCodecs.forColumn(table, column) === undefined) {
+      invalidCodecs.push({ table: table ?? '', column: column ?? '', codecId, reason: 'column-codec-unresolved' });
     }
   }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/2-sql/5-runtime/src/codecs/validation.ts` around lines 39 - 48,
validateContractCodecMappings currently only checks
codecDescriptors.descriptorFor(codecId) but must also ensure the codec is
resolvable via contractCodecs.forColumn(table, column) to prevent runtime
fallback; update validateContractCodecMappings (and use
extractCodecIdsFromColumns output) to, for each invalid match, split the key
into table and column, then call the contract's codec resolver
(contract.contractCodecs.forColumn or contractCodecs.forColumn) and treat it as
invalid if that resolver returns undefined/unresolved—add those entries to
invalidCodecs and keep the existing error reporting logic so startup fails when
either the descriptor is missing or the column-level codec cannot be resolved.

The codec-registry-unification work delivered the read-surface
unification (descriptorFor / forColumn non-branching at every
consumer) but stopped short of the registration-side migration
(every codec ships a native descriptor; legacy slot deletes;
ParamRef refs plumbing; JsonSchemaValidatorRegistry deletion).

The user accepted Option B (practical stopping point) and asked
that the deferred work be tracked as a real Linear ticket rather
than as in-project follow-up. TML-2357 created with concrete
scope (file paths, line numbers, suggested PR split). The
project spec ACs 1, 2, 5, 6 are now explicitly deferred to
TML-2357; the project ships ACs 3, 4, 7 (still to land in
Phase 4), 8 (Phase 5), 9.

Phase 3.5 split into 3.5a (landed: read-surface unification)
and the deferred remainder (now TML-2357).
… (full)

Follow-up to 92085f0 which only captured a partial subset of the
intended diff. Adds the remaining AC-5 / AC-6 deferral notes and the
plan.md Phase 3.5a section.
…ase 4 T4.1-T4.4 + T4.7)

New @prisma-next/extension-arktype-json package shipping:

- arktypeJson<S>(schema): column-author factory returning ColumnTypeDescriptor
  with eagerly-extracted typeParams { expression, jsonIr } and a curried
  (ctx) => Codec<arktype/json@1, [equality], string, S[infer]> factory.
- arktypeJsonCodec: framework-registration descriptor with internal
  validation in decode (no JsonSchemaValidatorRegistry consultation),
  renderOutputType returning the schema TS-source expression for the emit
  path, and ark.schema(jsonIr) rehydration.
- Pack metadata, control-extension, and runtime-extension descriptors
  following the post-Phase-1 pgvector layout (pure re-exports under
  exports/, first-class implementation under core/).
- Type-level (test-d) and runtime tests covering the type slot, decode
  validation, encode/decode roundtrip, descriptor metadata,
  paramsSchema validation, factory rehydration, and serialize/rehydrate
  symmetry.

Serialization deviates from the prompt: typeParams ships {expression, jsonIr}
where jsonIr is arktype schema.json (the IR; lossless, rehydratable via
ark.schema()) rather than schema.toJsonSchema() (lossy; not rehydratable).
expression is read by renderOutputType for the emit path.

The codec is library-bound (arktype/json@1), not target-bound, per the
codec-registry-unification spec § Case J. No legacy codecs: registration —
the unified descriptor map (Phase 3.5a) is the codec-id-keyed read surface.

Refs codec-registry-unification spec § AC-7; project plan § Phase 4
T4.1, T4.2, T4.3, T4.4, T4.7.
…e 4 T4.5)

The generic Standard-Schema-driven `json(schema)` / `jsonb(schema)` factory
proved lossy for narrowed types — validating only the JSON Schema subset
of arktype/zod/valibot inputs and producing surprising behavior for
custom narrows or branded types. Per Phase 4 of codec-registry-unification,
schema-typed JSON columns ship from per-library extension packages
(@prisma-next/extension-arktype-json is the first); the postgres adapter
retains only the non-parameterized raw-JSONB codecs.

Deletes:
- src/codecs/json-factory.ts (M3 schema-typed HoC factory + descriptors).
- src/codecs/json-runtime-factory.ts (M3 runtime validator factory).
- src/core/json-schema-validator.ts (Ajv-backed compile helper).
- src/core/json-schema-type-expression.ts (JSON-Schema → TS expression renderer).
- src/core/standard-schema.ts (legacy adapter-local Standard Schema helpers).
- src/exports/codecs.ts (no remaining export surface).
- pgJsonLegacyCodec / pgJsonbLegacyCodec descriptors and their registration
  through the control adapter.
- All M3 JSON tests and the codecs export entrypoint from package.json/tsdown.

Refactors:
- json() / jsonb() in src/exports/column-types.ts now return the static
  raw-JSONB descriptor; the schema parameter is gone.
- Runtime descriptor exposes parameterizedCodecs: () => [] (the JSON path
  is not registered through the runtime; per-library extensions register
  their own codec ids).

Refs codec-registry-unification spec § AC-7; project plan § Phase 4 T4.5.
…Json (Phase 4 T4.6)

Demo TS contract: Users.address is now a schema-validated arktype-json
column instead of an unbranded jsonb. The TS-emit path renders address
as `{ city: string; country: string; street: string; zip?: string } | null`
via arktypes `expression`-driven `renderOutputType`. The PSL contract
(default emit) is unchanged — Address there is a value-object type.

Demo control + runtime configs include the new arktype-json extension
through `extensionPacks: [pgvector, arktypeJson]` and
`extensions: [pgvector, arktypeJson]` respectively.

Test fixtures updated:
- test/integration: contract-builder.types.test-d.ts uses arktypeJson()
  in place of the deleted jsonb(schema) factory; same no-emit-path
  type assertions hold.
- test/e2e/framework: contract.ts replaces the hand-rolled fake
  Standard Schema in `Embedding.profile` with a real arktype schema
  and arktypeJson(profileSchema).

Refs codec-registry-unification spec § AC-7; project plan § Phase 4 T4.6.
…block TS portability (Phase 4 follow-up)

Add a dedicated `./codec-types` entrypoint to the extension package
(matching the pgvector layout) so the pack metadatas
`types.codecTypes.import` reference resolves to a stable public path.
Re-export `ArktypeJsonCodec` and `ArktypeJsonTypeParams` from
`column-types` too so any consumer importing `arktypeJson` has the
related types nameable from the same import.

Demo `prisma/contract.ts` adds `import type {} from
@prisma-next/extension-arktype-json/codec-types` to bring the public
codec-types entrypoint into TS module-graph scope. Without this,
TypeScript flagged TS2742 portability warnings on the inferred contract
type (the type literal flowed through `arktypeJsonPackMetas
__codecTypes?: CodecTypes` reference, and the codec-types chunk was
not nameable from the consumer site without an explicit reference).

Refs codec-registry-unification spec § AC-7; project plan § Phase 4.
…Type hook + register extension in e2e (Phase 4 follow-up)

The migration planner requires every parameterized codec id to register
an `expandNativeType` hook through the control-plane `controlPlaneHooks`
slot — even when the codec carries typeParams that do not affect the DDL
shape (`jsonb` is a bare type regardless of the arktype schema). Add an
identity hook for `arktype/json@1` and register it from the control
extension descriptor.

E2E test fixture updates:
- prisma-next.config.ts: include the arktype-json control descriptor in
  extensionPacks so the migration planner sees the hook registration.
- utils.ts: include the arktype-json runtime descriptor in the test
  control client and runtime contexts so the runtime resolves
  arktype/json@1 columns through the unified descriptor map.
- generated/contract.{json,d.ts}: re-emit reflecting the migration from
  jsonb(profileSchema) to arktypeJson(profileSchema). The Embedding.profile
  field now carries codecId=arktype/json@1, typeParams={expression, jsonIr}.

Refs codec-registry-unification spec § AC-7; project plan § Phase 4.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 11

Caution

Some comments are outside the diff and can’t be posted inline due to platform limitations.

⚠️ Outside diff range comments (1)
test/e2e/framework/test/utils.ts (1)

32-35: ⚠️ Potential issue | 🟡 Minor

Update the helper docstring to reflect arktype-json support.

Line 33 still describes the stack as “Postgres + pgvector”, but the helper now configures three packs.

Suggested doc fix
- * Creates a control client configured for the e2e test stack (Postgres + pgvector).
+ * Creates a control client configured for the e2e test stack
+ * (Postgres + pgvector + arktype-json).
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@test/e2e/framework/test/utils.ts` around lines 32 - 35, The docstring above
the control client helper still says "Postgres + pgvector" but the helper now
configures three packs including arktype-json; update the comment so it
accurately lists all configured packs (e.g., Postgres, pgvector, arktype-json)
and mentions it's used for dbInit/database initialization in this e2e stack to
avoid confusion; update the text near the helper declaration (the comment block
that starts "Creates a control client configured for the e2e test stack...") and
keep the reference to dbInit intact.
🧹 Nitpick comments (2)
packages/3-targets/6-adapters/postgres/src/exports/column-types.ts (1)

133-145: Avoid as never in numericColumn return path

Line 144 suppresses type checking for typeParams; this makes future shape regressions easier to miss. Prefer overloads/branch-specific returns so each branch typechecks without casts.

♻️ Refactor sketch (cast-free)
+export function numericColumn<P extends number>(
+  precision: P,
+): ColumnTypeDescriptor & {
+  readonly codecId: typeof PG_NUMERIC_CODEC_ID;
+  readonly nativeType: 'numeric';
+  readonly typeParams: { readonly precision: P };
+  readonly type: (ctx: Ctx) => NumericCodec<P, undefined>;
+};
+export function numericColumn<P extends number, S extends number>(
+  precision: P,
+  scale: S,
+): ColumnTypeDescriptor & {
+  readonly codecId: typeof PG_NUMERIC_CODEC_ID;
+  readonly nativeType: 'numeric';
+  readonly typeParams: { readonly precision: P; readonly scale: S };
+  readonly type: (ctx: Ctx) => NumericCodec<P, S>;
+};
 export function numericColumn<P extends number, S extends number | undefined = undefined>(
   precision: P,
   scale?: S,
-)...
+) {
+  if (scale === undefined) {
+    return {
+      codecId: PG_NUMERIC_CODEC_ID,
+      nativeType: 'numeric',
+      typeParams: { precision },
+      type: numericCodecForParams(precision),
+    } as const;
+  }
+  return {
+    codecId: PG_NUMERIC_CODEC_ID,
+    nativeType: 'numeric',
+    typeParams: { precision, scale },
+    type: numericCodecForParams(precision, scale),
+  } as const;
+}

As per coding guidelines, “No blind casts in production code... Prefer type predicates or fix the type surface.”

🤖 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/column-types.ts` around
lines 133 - 145, The return currently uses a blind cast ("typeParams: typeParams
as never") which hides type mismatches; update numericColumn (and its return
type) so each branch returns a correctly typed object instead of casting: keep
the runtime conditional building of the local variable typeParams, but in the
undefined-scale branch return an object typed for precision-only and in the
defined-scale branch return an object typed for precision+scale (use overloads
on numericColumn or narrow the return with two separate return statements),
ensuring the returned objects use the PG_NUMERIC_CODEC_ID, nativeType 'numeric',
and numericCodecForParams(precision, scale) exactly as now but without the as
never cast so TypeScript validates typeParams shape.
packages/3-targets/6-adapters/postgres/src/codecs/postgres-codec-descriptors.ts (1)

200-202: Use the chained Arktype array API here.

Repo conventions prefer Schema.array() over DSL strings like string[] for array schemas.

As per coding guidelines "Use 'Schema.array()' for array definitions in Arktype (avoid tuple mistakes)."

🤖 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/codecs/postgres-codec-descriptors.ts`
around lines 200 - 202, The enumParamsSchema currently uses the DSL string
'string[]'—replace it with the chained Arktype array API by defining values as
Schema.array(Schema.string()) in the enumParamsSchema arktype call; update the
enumParamsSchema declaration (symbol: enumParamsSchema) to: arktype({ values:
Schema.array(Schema.string()) }) and ensure Schema is imported from 'arktype' if
not already.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@examples/prisma-next-demo/prisma/contract.ts`:
- Around line 45-47: Update the explanatory comment that references the
deprecated renderOutputType term: locate the comment block describing the
schema-validated JSON column in contract.ts and replace the phrase "arktype's
`expression`-driven `renderOutputType`" with wording that reflects the current
model—e.g., "arktype's descriptor-factory driven type inference (the schema's
inferred output via descriptor factories)"—so the note refers to descriptor
factories/type inference instead of the deprecated `renderOutputType`.

In `@packages/3-extensions/arktype-json/src/core/arktype-json-codec.ts`:
- Around line 106-143: The factory currently accepts any Arktype schema and only
validates at decode time; to prevent non-JSON-safe schemas (Date, bigint, etc.)
we should validate at creation by invoking schema.toJsonSchema() (or the
appropriate Arktype API) inside arktypeJsonCodecForSchema (or the top-level
arktypeJson factory that calls it), catching any errors or inspecting the
returned JSON Schema to detect unsupported types and throw a clear synchronous
error (e.g., a runtimeError or TypeError) that rejects the schema; update
arktypeJsonCodecForSchema/arktypeJson creation to call schema.toJsonSchema(),
handle fallback behavior per Arktype, and throw when the produced schema
indicates non-JSON-serializable constructs so invalid schemas fail fast instead
of mangling data at runtime.

In `@packages/3-extensions/arktype-json/src/core/control-extension-descriptor.ts`:
- Around line 7-10: The docblock in control-extension-descriptor.ts incorrectly
states there are no controlPlaneHooks; update the comment to reflect that the
descriptor does register controlPlaneHooks by referencing
arktypeJsonControlPlaneHooks (lines where arktypeJsonControlPlaneHooks is added
to controlPlaneHooks) so readers know this hook is required and intentionally
present; make the wording consistent (e.g., state that although jsonb is
built-in and has no DB extension, the descriptor registers
arktypeJsonControlPlaneHooks for control-plane behavior) and ensure the comment
aligns with the implementation where arktypeJsonControlPlaneHooks is registered.

In `@packages/3-extensions/arktype-json/src/core/control-hooks.ts`:
- Line 16: The import of CodecControlHooks into src/core/control-hooks.ts
crosses the plane boundary; remove the direct dependency on
'@prisma-next/family-sql/control' by moving the CodecControlHooks type (and any
control-specific implementations) into a control-plane export module or a
shared-plane type surface (e.g., a new/shared package or control-plane index)
and re-export it for consumers; then update control-hooks.ts to import
CodecControlHooks from that shared export instead of
'@prisma-next/family-sql/control' and adjust any references (CodecControlHooks,
any related function signatures) to use the new exported type so src/core
remains free of control-plane imports.

In `@packages/3-extensions/arktype-json/test/arktype-json-codec.test.ts`:
- Around line 48-56: The test currently casts the invalid schema using `as any`
and disables linting; remove the `biome-ignore` and the `as any` cast and
instead cast through `unknown` (e.g. `{ foo: 'bar' } as unknown as Type`) so the
unsafe boundary remains local; update the failing call site to use the
double-cast through `unknown` for the `arktypeJson` invocation (reference:
arktypeJson in arktype-json-codec.test.ts).

In `@packages/3-targets/6-adapters/postgres/package.json`:
- Line 34: Remove the unused dependency entry "@standard-schema/spec" from
package.json (the dependency listed on line with "@standard-schema/spec":
"1.1.0"), since types come via "@prisma-next/framework-components" and the
package does not import it directly; after removing the entry, run install to
update the lockfile (or regenerate yarn.lock/package-lock.json) and run the
package's build/tests to ensure no missing types or breakages.

In
`@packages/3-targets/6-adapters/postgres/src/codecs/postgres-codec-descriptors.ts`:
- Around line 204-225: The pgEnumCodec descriptor currently uses
enumPlaceholderFactory which always throws, but pgEnumCodec is now included in
runtime registration via allPostgresParameterizedCodecs →
types.codecTypes.parameterizedCodecs causing runtime instantiation failures; fix
by either (A) implementing a real factory for pgEnumCodec that, given params {
values } and ctx (Ctx), returns a proper Codec instance (for example by
delegating to the legacy codec registry/function used in core/codecs.ts or
constructing an enum codec that implements 'equality' and 'order'), ensuring the
factory name enumPlaceholderFactory is replaced with the real implementation, or
(B) keep this descriptor emit-only by removing pgEnumCodec from the runtime list
(allPostgresParameterizedCodecs) so it is not fed into
types.codecTypes.parameterizedCodecs; choose one approach and update references
to pgEnumCodec/enumPlaceholderFactory and the allPostgresParameterizedCodecs
inclusion accordingly.
- Around line 217-220: The renderOutputType implementation currently escapes
only backslashes and single quotes which fails for control characters; update
the function (renderOutputType) to stringify each enum value using
JSON.stringify(String(value)) instead of manual replace so the emitted union of
TypeScript string literals is fully escaped and produces valid contract.d.ts
output. Ensure you map over values and join with ' | ' as before, but use
JSON.stringify to produce each literal.

In `@packages/3-targets/6-adapters/postgres/src/exports/column-types.ts`:
- Around line 246-287: Update the docstrings to accurately distinguish JSON vs
JSONB: change the "Raw-JSONB" wording used for jsonColumn and the json() factory
to "Raw-JSON" (or similar) since they represent nativeType 'json', and ensure
the jsonbColumn and its factory (jsonbColumn / jsonb() if present) keep
"Raw-JSONB" wording; update the sentences in the comments for the symbols
jsonColumn and json() so they no longer say "JSONB" where the type is 'json' and
retain correct wording for jsonbColumn.
- Around line 279-289: The json() and jsonb() factories currently widen their
return type to the generic ColumnTypeDescriptor, losing the concrete descriptor
shape and the precise factory signature; update the function signatures to
return the exact descriptor types (use typeof jsonColumn for json() and typeof
jsonbColumn for jsonb()) so callers retain the concrete descriptor shape and
factory signature, e.g., change "export function json(): ColumnTypeDescriptor"
to "export function json(): typeof jsonColumn" (and likewise for jsonb) while
keeping the same returned values jsonColumn and jsonbColumn.

---

Outside diff comments:
In `@test/e2e/framework/test/utils.ts`:
- Around line 32-35: The docstring above the control client helper still says
"Postgres + pgvector" but the helper now configures three packs including
arktype-json; update the comment so it accurately lists all configured packs
(e.g., Postgres, pgvector, arktype-json) and mentions it's used for
dbInit/database initialization in this e2e stack to avoid confusion; update the
text near the helper declaration (the comment block that starts "Creates a
control client configured for the e2e test stack...") and keep the reference to
dbInit intact.

---

Nitpick comments:
In
`@packages/3-targets/6-adapters/postgres/src/codecs/postgres-codec-descriptors.ts`:
- Around line 200-202: The enumParamsSchema currently uses the DSL string
'string[]'—replace it with the chained Arktype array API by defining values as
Schema.array(Schema.string()) in the enumParamsSchema arktype call; update the
enumParamsSchema declaration (symbol: enumParamsSchema) to: arktype({ values:
Schema.array(Schema.string()) }) and ensure Schema is imported from 'arktype' if
not already.

In `@packages/3-targets/6-adapters/postgres/src/exports/column-types.ts`:
- Around line 133-145: The return currently uses a blind cast ("typeParams:
typeParams as never") which hides type mismatches; update numericColumn (and its
return type) so each branch returns a correctly typed object instead of casting:
keep the runtime conditional building of the local variable typeParams, but in
the undefined-scale branch return an object typed for precision-only and in the
defined-scale branch return an object typed for precision+scale (use overloads
on numericColumn or narrow the return with two separate return statements),
ensuring the returned objects use the PG_NUMERIC_CODEC_ID, nativeType 'numeric',
and numericCodecForParams(precision, scale) exactly as now but without the as
never cast so TypeScript validates typeParams shape.
🪄 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: 168a7bd3-be5f-457e-899a-67dcf32f064f

📥 Commits

Reviewing files that changed from the base of the PR and between 8b8099f and 450b7f2.

⛔ Files ignored due to path filters (5)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
  • projects/codec-registry-unification/plan.md is excluded by !projects/**
  • projects/codec-registry-unification/spec.md is excluded by !projects/**
  • test/e2e/framework/test/fixtures/generated/contract.d.ts is excluded by !**/generated/**
  • test/e2e/framework/test/fixtures/generated/contract.json is excluded by !**/generated/**
📒 Files selected for processing (45)
  • examples/prisma-next-demo/package.json
  • examples/prisma-next-demo/prisma-next.config.ts-contract.ts
  • examples/prisma-next-demo/prisma/contract.ts
  • examples/prisma-next-demo/src/prisma/db.ts
  • packages/3-extensions/arktype-json/README.md
  • packages/3-extensions/arktype-json/biome.jsonc
  • packages/3-extensions/arktype-json/package.json
  • packages/3-extensions/arktype-json/src/core/arktype-json-codec.ts
  • packages/3-extensions/arktype-json/src/core/control-extension-descriptor.ts
  • packages/3-extensions/arktype-json/src/core/control-hooks.ts
  • packages/3-extensions/arktype-json/src/core/pack-meta.ts
  • packages/3-extensions/arktype-json/src/core/runtime-extension-descriptor.ts
  • packages/3-extensions/arktype-json/src/exports/codec-types.ts
  • packages/3-extensions/arktype-json/src/exports/codecs.ts
  • packages/3-extensions/arktype-json/src/exports/column-types.ts
  • packages/3-extensions/arktype-json/src/exports/control.ts
  • packages/3-extensions/arktype-json/src/exports/pack.ts
  • packages/3-extensions/arktype-json/src/exports/runtime.ts
  • packages/3-extensions/arktype-json/src/types/codec-types.ts
  • packages/3-extensions/arktype-json/test/arktype-json-codec.test-d.ts
  • packages/3-extensions/arktype-json/test/arktype-json-codec.test.ts
  • packages/3-extensions/arktype-json/tsconfig.json
  • packages/3-extensions/arktype-json/tsdown.config.ts
  • packages/3-extensions/arktype-json/vitest.config.ts
  • packages/3-targets/6-adapters/postgres/package.json
  • packages/3-targets/6-adapters/postgres/src/codecs/postgres-codec-descriptors.ts
  • packages/3-targets/6-adapters/postgres/src/core/json-schema-type-expression.ts
  • packages/3-targets/6-adapters/postgres/src/core/json-schema-validator.ts
  • packages/3-targets/6-adapters/postgres/src/core/standard-schema.ts
  • packages/3-targets/6-adapters/postgres/src/exports/column-types.ts
  • packages/3-targets/6-adapters/postgres/src/exports/control.ts
  • packages/3-targets/6-adapters/postgres/src/exports/runtime.ts
  • packages/3-targets/6-adapters/postgres/test/codec-render-output-type.test.ts
  • packages/3-targets/6-adapters/postgres/test/column-types.test.ts
  • packages/3-targets/6-adapters/postgres/test/json-schema-type-expression.test.ts
  • packages/3-targets/6-adapters/postgres/test/json-schema-validator.test.ts
  • packages/3-targets/6-adapters/postgres/test/postgres-codec-descriptors.test.ts
  • packages/3-targets/6-adapters/postgres/test/standard-schema.test.ts
  • packages/3-targets/6-adapters/postgres/tsdown.config.ts
  • test/e2e/framework/package.json
  • test/e2e/framework/test/fixtures/contract.ts
  • test/e2e/framework/test/fixtures/prisma-next.config.ts
  • test/e2e/framework/test/utils.ts
  • test/integration/package.json
  • test/integration/test/contract-builder.types.test-d.ts
💤 Files with no reviewable changes (6)
  • packages/3-targets/6-adapters/postgres/src/core/json-schema-validator.ts
  • packages/3-targets/6-adapters/postgres/test/standard-schema.test.ts
  • packages/3-targets/6-adapters/postgres/src/core/json-schema-type-expression.ts
  • packages/3-targets/6-adapters/postgres/test/json-schema-type-expression.test.ts
  • packages/3-targets/6-adapters/postgres/test/json-schema-validator.test.ts
  • packages/3-targets/6-adapters/postgres/src/core/standard-schema.ts
✅ Files skipped from review due to trivial changes (14)
  • examples/prisma-next-demo/package.json
  • test/e2e/framework/package.json
  • packages/3-extensions/arktype-json/biome.jsonc
  • test/integration/package.json
  • packages/3-extensions/arktype-json/src/exports/codec-types.ts
  • test/e2e/framework/test/fixtures/prisma-next.config.ts
  • packages/3-extensions/arktype-json/tsconfig.json
  • packages/3-extensions/arktype-json/src/types/codec-types.ts
  • packages/3-targets/6-adapters/postgres/tsdown.config.ts
  • packages/3-extensions/arktype-json/src/exports/codecs.ts
  • packages/3-extensions/arktype-json/README.md
  • packages/3-extensions/arktype-json/package.json
  • test/integration/test/contract-builder.types.test-d.ts
  • packages/3-extensions/arktype-json/src/exports/column-types.ts
🚧 Files skipped from review as they are similar to previous changes (3)
  • packages/3-targets/6-adapters/postgres/src/exports/runtime.ts
  • packages/3-targets/6-adapters/postgres/test/postgres-codec-descriptors.test.ts
  • packages/3-targets/6-adapters/postgres/test/codec-render-output-type.test.ts

Comment on lines +45 to +47
// Schema-validated JSON column via the per-library extension. The
// column's TS type resolves to the schema's inferred output through
// arktype's `expression`-driven `renderOutputType`.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Comment references deprecated renderOutputType terminology.

The explanatory note mentions renderOutputType, but this PR’s model centers on descriptor factories/type inference. Updating this wording will prevent confusion for readers.

Suggested wording update
-        // Schema-validated JSON column via the per-library extension. The
-        // column's TS type resolves to the schema's inferred output through
-        // arktype's `expression`-driven `renderOutputType`.
+        // Schema-validated JSON column via the per-library extension.
+        // The column's TS type resolves from the arktype schema inference
+        // through the higher-order codec descriptor.
📝 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.

Suggested change
// Schema-validated JSON column via the per-library extension. The
// column's TS type resolves to the schema's inferred output through
// arktype's `expression`-driven `renderOutputType`.
// Schema-validated JSON column via the per-library extension.
// The column's TS type resolves from the arktype schema inference
// through the higher-order codec descriptor.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@examples/prisma-next-demo/prisma/contract.ts` around lines 45 - 47, Update
the explanatory comment that references the deprecated renderOutputType term:
locate the comment block describing the schema-validated JSON column in
contract.ts and replace the phrase "arktype's `expression`-driven
`renderOutputType`" with wording that reflects the current model—e.g.,
"arktype's descriptor-factory driven type inference (the schema's inferred
output via descriptor factories)"—so the note refers to descriptor
factories/type inference instead of the deprecated `renderOutputType`.

Comment on lines +51 to +65
export type ArktypeJsonTypeParams = {
/**
* Arktype's TypeScript-source-like rendering of the schema. Read by
* `renderOutputType` to emit the column's TS type into `contract.d.ts`.
* Stable across the serialize/rehydrate cycle: the rehydrated schema's
* `expression` matches the source schema's.
*/
readonly expression: string;
/**
* Arktype's internal IR for the schema. Lossless; the rehydration source.
* Schema-shape — `ark.schema(jsonIr)` reconstructs a callable `Type`-like
* structurally identical to the original `type(definition)` output.
*/
readonly jsonIr: object;
};

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🌐 Web query:

In Arktype, what runtime shapes can Type["json"]produce for primitive, array, union, and object schemas? Doesark.schema(...) accept non-object JSON IR values?

💡 Result:

For Type["json"] (ArkType’s internal JSON representation), the runtime “shapes” it can produce map to the JSON structure/schema branches ArkType uses internally. In practice those branches correspond to JSON Schema node kinds: primitives, arrays, unions (anyOf), and objects. 1) Primitive schemas - Produces a JSON Schema “type” branch for JSON primitives, i.e. a JsonSchema with type in: "string", "integer", "number", "boolean", "null". 2) Array schemas - Produces a JSON Schema “type”: "array" schema node. - Those array nodes may include items / prefixItems (tuple support) and other array-related keywords, as defined in ArkType’s JsonSchema.Array type. 3) Union schemas - ArkType represents unions using JSON Schema composition keywords: - “union” → anyOf: readonly JsonSchema[] - “oneOf” / intersections / negations have their own dedicated node shapes (oneOf, allOf, not). 4) Object schemas - Produces a JSON Schema “type”: "object" schema node. - Those object nodes may include properties and required, plus index-signature-like keywords via additionalProperties / patternProperties. Does ark.schema(...) accept non-object JSON IR values? - Yes for non-object JSON IR values in the sense that ArkType’s internal “schema” parser entrypoints accept an arbitrary RootSchema-typed input; the repository’s scope code routes based on the schema “kind” inferred from the input rather than requiring an object. - However, what does NOT work is passing arbitrary non-JSON-serializable ArkType condition/morph logic; the conversion/hydration round-trip is limited to serializable parts of the type. Non-serializable conditions (e.g. morph/narrow functions) prevent correct conversion. Concrete guidance: - If you have a Type and you access .json / Type["json"], you can feed that into ArkType’s schema hydration flow so long as it corresponds to ArkType’s expected JSON IR shapes. - If the JSON IR contains non-serializable constraints/morphs, ArkType cannot re-hydrate reliably (and you’ll need workarounds such as using .in/.out or JSON Schema fallbacks for schema generation).

Citations:


Widen jsonIr type to accept all Arktype JSON IR shapes, not just objects.

The ArktypeJsonTypeParams.jsonIr type is defined as object, but Arktype's Type["json"] produces JSON Schema node kinds beyond objects. The web search confirms Type["json"] serializes primitive schemas to JSON Schema primitives (e.g., { type: "string" }), array schemas to array structures (e.g., { type: "array" }), and union schemas to composition nodes (e.g., { anyOf: [...] }). The runtime ark.schema(...) accepts these non-object shapes and correctly rehydrates them.

The current hard-coded object constraint on lines 64, 188, and 215 rejects valid Arktype schemas that serialize to primitive or array-shaped IR, even though the library can deserialize them. Change ArktypeJsonTypeParams and paramsSchema to accept the full union of schema node kinds that Type["json"] produces, ensuring all valid schemas can be stored and rehydrated correctly.

Comment on lines +106 to +143
function arktypeJsonCodecForSchema<TInferred>(
schema: ArktypeSchemaLike,
): (ctx: Ctx) => ArktypeJsonCodec<TInferred> {
return (_ctx) => ({
id: ARKTYPE_JSON_CODEC_ID,
targetTypes: [ARKTYPE_JSON_NATIVE_TYPE] as const,
traits: ['equality'] as const,
encode(value: TInferred): string {
return JSON.stringify(value);
},
decode(wire: string): TInferred {
const parsed: unknown = JSON.parse(wire);
const result = schema(parsed);
if (result instanceof ArkErrors) {
throw runtimeError(
'RUNTIME.JSON_SCHEMA_VALIDATION_FAILED',
`arktype-json schema validation failed (decode): ${result.summary}`,
{ codecId: ARKTYPE_JSON_CODEC_ID, issues: result.summary },
);
}
// arktype's call-result is `inferOut | ArkErrors`; the ArkErrors branch
// is excluded above. The cast threads the caller-supplied generic onto
// the structurally-typed validation output.
return result as TInferred;
},
encodeJson(value: TInferred): JsonValue {
// The contract IR's JSON-side surface is typed against `JsonValue`;
// arktype outputs may include narrowed types (literal unions, branded
// types, …) that aren't structurally `JsonValue`. The cast is a wire-
// level identity by contract: the caller agrees the value is JSON-safe.
return value as JsonValue;
},
decodeJson(jsonValue: JsonValue): TInferred {
// Symmetric with `encodeJson`. Runtime validation lives in `decode`
// above (driver wire path), not on the contract-load JSON path —
// contract.json is trusted authoring output.
return jsonValue as TInferred;
},

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🌐 Web query:

Does Arktype expose a supported way to constrain a Typeso its inferred output is JSON-safe (compatible withJSON.stringify/JsonValue)? If not, what is the recommended pattern for rejecting non-JSON-serializable schemas in a JSON-backed codec?

💡 Result:

No. ArkType does not (as far as its public API/docs indicate) expose a dedicated “JSON-safe Type constraint” that would make the inferred output automatically JSON.stringify/JsonValue-compatible. What ArkType does support is (a) generating JSON Schema from a Type via toJsonSchema, and (b) rejecting or handling “non-serializable” constraints during JSON Schema generation using a configurable fallback strategy. Recommended pattern: validate first, then only emit/accept JSON-serializable output by using an output-shaped Type (Thing.out) and/or configure toJsonSchema fallback for incompatible constraints. Concretely: 1) Build a JSON-backed codec that decodes unknown input with an ArkType (Thing) and then encodes/returns only the JSON-safe “out” shape: - Use morph pipelines like "base |> ..." so the normalized output (Thing.out) is the shape your JSON codec will work with. - When generating JSON Schema or interop, prefer Thing.in.toJsonSchema / Thing.out.toJsonSchema rather than Thing.toJsonSchema if morphs are involved. 2) If you need to reject non-JSON-serializable schemas (i.e., you rely on JSON Schema / JSON serialization as a serialization format), treat JSON-schema generation as the “gate”: - Call Thing.toJsonSchema({ fallback: ctx => ctx.base }) to “ignore” incompatible constraints rather than attempting to accept them as-is. - If you want strict rejection, let toJsonSchema throw by default (it throws when a feature doesn’t have a JSON Schema equivalent unless you provide fallback handlers). Alternatively, provide a fallback handler that throws for specific non-serializable codes (the docs describe the fallback mechanism and its default-throw behavior). Why this is the right framing in ArkType terms: - ArkType explicitly documents that some features don’t have JSON Schema equivalents and toJsonSchema throws by default; it also documents a fallback config to handle incompatibilities. - GitHub discussion/issues around non-JSON-serializable predicates (e.g., parse predicates) show that these constraints are not convertible to JSON Schema and require either fallback or different type keywords that have JSON Schema representations. Example strict rejection approach (conceptual): - Keep your codec’s schema generation strict by default (don’t configure fallback), so any non-JSON-serializable constraints cause toJsonSchema to throw. - Or, if you must configure fallback, set fallback.default to ctx.base (“ignore incompatibilities”), which is explicitly documented as the way to “just make it work”.

Citations:


🏁 Script executed:

# First, let's check the file size and read the full context
wc -l packages/3-extensions/arktype-json/src/core/arktype-json-codec.ts

Repository: prisma/prisma-next

Length of output: 132


🏁 Script executed:

# Read the full file to understand the implementation
cat -n packages/3-extensions/arktype-json/src/core/arktype-json-codec.ts

Repository: prisma/prisma-next

Length of output: 14368


🏁 Script executed:

# Also search for toJsonSchema usage in the arktype-json package
rg "toJsonSchema" packages/3-extensions/arktype-json/ -A 3 -B 3

Repository: prisma/prisma-next

Length of output: 44


🏁 Script executed:

# Search for any schema validation patterns in the file
rg "schema" packages/3-extensions/arktype-json/src/core/arktype-json-codec.ts -A 2 -B 2

Repository: prisma/prisma-next

Length of output: 8021


🏁 Script executed:

# Search for toJsonSchema usage in the entire arktype-json package
rg "toJsonSchema" packages/3-extensions/arktype-json/

Repository: prisma/prisma-next

Length of output: 44


🏁 Script executed:

# Check if there are any type predicates or validation utilities for JSON-safety
rg "JSON" packages/3-extensions/arktype-json/src/core/ -B 2 -A 2

Repository: prisma/prisma-next

Length of output: 13011


🏁 Script executed:

# Look for any imports from arktype that might be relevant for validation
rg "import.*arktype" packages/3-extensions/arktype-json/ -A 2

Repository: prisma/prisma-next

Length of output: 3776


Validate schemas for JSON-safety at creation time using Arktype's toJsonSchema() method.

The arktypeJson() factory accepts any Type<unknown> but lacks validation that the schema only infers JSON-serializable values. Schemas that infer Date, bigint, or other non-JSON-safe types will compile without error but silently fail or mangle data at runtime, creating a type safety gap. Add a validation check during arktypeJson(schema) creation by calling schema.toJsonSchema() (with appropriate fallback handling per Arktype's API) to reject non-JSON-serializable constraints upfront instead of deferring to runtime decode failures.

🤖 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 106 - 143, The factory currently accepts any Arktype schema and only
validates at decode time; to prevent non-JSON-safe schemas (Date, bigint, etc.)
we should validate at creation by invoking schema.toJsonSchema() (or the
appropriate Arktype API) inside arktypeJsonCodecForSchema (or the top-level
arktypeJson factory that calls it), catching any errors or inspecting the
returned JSON Schema to detect unsupported types and throw a clear synchronous
error (e.g., a runtimeError or TypeError) that rejects the schema; update
arktypeJsonCodecForSchema/arktypeJson creation to call schema.toJsonSchema(),
handle fallback behavior per Arktype, and throw when the produced schema
indicates non-JSON-serializable constructs so invalid schemas fail fast instead
of mangling data at runtime.

Comment on lines +7 to +10
* Unlike pgvector, arktype-json has no database extension to install
* (`jsonb` is a built-in Postgres type), no `controlPlaneHooks` (the
* codec doesn't expand its native type with params at DDL time — `jsonb`
* is dimension-free), and no query operations. The descriptor's only

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟡 Minor

Docblock contradicts implementation about control hooks

Line 8 says there are no controlPlaneHooks, but Lines 32-34 register arktypeJsonControlPlaneHooks. Please update the comment to match behavior so future refactors don’t remove this required hook by mistake.

Also applies to: 32-34

🤖 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/control-extension-descriptor.ts`
around lines 7 - 10, The docblock in control-extension-descriptor.ts incorrectly
states there are no controlPlaneHooks; update the comment to reflect that the
descriptor does register controlPlaneHooks by referencing
arktypeJsonControlPlaneHooks (lines where arktypeJsonControlPlaneHooks is added
to controlPlaneHooks) so readers know this hook is required and intentionally
present; make the wording consistent (e.g., state that although jsonb is
built-in and has no DB extension, the descriptor registers
arktypeJsonControlPlaneHooks for control-plane behavior) and ensure the comment
aligns with the implementation where arktypeJsonControlPlaneHooks is registered.

* error when the column carries typeParams.
*/

import type { CodecControlHooks } from '@prisma-next/family-sql/control';

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

Keep src/core free of control-plane imports.

Line 16 pulls CodecControlHooks from @prisma-next/family-sql/control inside src/core, which crosses the plane boundary. Move this typing/implementation to a control-plane export module (or a shared-plane type surface) to preserve layering constraints.

As per coding guidelines, packages/**/src/core/** must remain free of migration/runtime imports and depend only on shared-plane packages.

🤖 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/control-hooks.ts` at line 16, The
import of CodecControlHooks into src/core/control-hooks.ts crosses the plane
boundary; remove the direct dependency on '@prisma-next/family-sql/control' by
moving the CodecControlHooks type (and any control-specific implementations)
into a control-plane export module or a shared-plane type surface (e.g., a
new/shared package or control-plane index) and re-export it for consumers; then
update control-hooks.ts to import CodecControlHooks from that shared export
instead of '@prisma-next/family-sql/control' and adjust any references
(CodecControlHooks, any related function signatures) to use the new exported
type so src/core remains free of control-plane imports.

Comment on lines +204 to +225
const enumPlaceholderFactory =
(_params: { readonly values: readonly string[] }) =>
(_ctx: Ctx): Codec => {
throw new Error(
'pgEnumCodec.factory is registration-only at M4 (the enum codec lives in the legacy codec registry).',
);
};

export const pgEnumCodec: ParameterizedCodecDescriptor<{ readonly values: readonly string[] }> = {
codecId: PG_ENUM_CODEC_ID,
traits: ['equality', 'order'] as const,
targetTypes: ['enum'] as const,
paramsSchema: enumParamsSchema,
renderOutputType: ({ values }) =>
values
.map((value) => `'${String(value).replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'`)
.join(' | '),
// The enum codec is registered through the legacy codec registry today
// (see `core/codecs.ts`); the descriptor exists only to provide
// `renderOutputType` to the emitter. The factory placeholder satisfies the
// descriptor shape; M4's emit path never invokes it.
factory: enumPlaceholderFactory,

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🔴 Critical

Don't register a parameterized codec whose factory always throws.

packages/3-targets/6-adapters/postgres/src/exports/control.ts now feeds allPostgresParameterizedCodecs into types.codecTypes.parameterizedCodecs, so this is no longer emitter-only in practice. Any pgEnumCodec resolved through the HoC path will fail during runtime instantiation. Please either provide a real factory here or keep emit-only enum descriptors out of the runtime registry.

🤖 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/codecs/postgres-codec-descriptors.ts`
around lines 204 - 225, The pgEnumCodec descriptor currently uses
enumPlaceholderFactory which always throws, but pgEnumCodec is now included in
runtime registration via allPostgresParameterizedCodecs →
types.codecTypes.parameterizedCodecs causing runtime instantiation failures; fix
by either (A) implementing a real factory for pgEnumCodec that, given params {
values } and ctx (Ctx), returns a proper Codec instance (for example by
delegating to the legacy codec registry/function used in core/codecs.ts or
constructing an enum codec that implements 'equality' and 'order'), ensuring the
factory name enumPlaceholderFactory is replaced with the real implementation, or
(B) keep this descriptor emit-only by removing pgEnumCodec from the runtime list
(allPostgresParameterizedCodecs) so it is not fed into
types.codecTypes.parameterizedCodecs; choose one approach and update references
to pgEnumCodec/enumPlaceholderFactory and the allPostgresParameterizedCodecs
inclusion accordingly.

Comment on lines +217 to +220
renderOutputType: ({ values }) =>
values
.map((value) => `'${String(value).replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'`)
.join(' | '),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

cat -n packages/3-targets/6-adapters/postgres/src/codecs/postgres-codec-descriptors.ts | sed -n '210,230p'

Repository: prisma/prisma-next

Length of output: 1146


🏁 Script executed:

# Search for where renderOutputType is called and what enum values are used
rg -B 5 -A 5 "renderOutputType" packages/3-targets/6-adapters/postgres/src/codecs/postgres-codec-descriptors.ts

Repository: prisma/prisma-next

Length of output: 6095


🏁 Script executed:

fd -e test.ts -e spec.ts packages/3-targets/6-adapters/postgres | xargs rg -l "renderOutputType\|enum.*literal" 2>/dev/null | head -5

Repository: prisma/prisma-next

Length of output: 520


🏁 Script executed:

python3 << 'EOF'
import json

# Test cases for enum values with special characters
test_values = [
    "simple",           # normal case
    "with'quote",       # single quote
    'with"doublequote', # double quote  
    "with\\backslash",  # backslash
    "with\nnewline",    # newline (control character)
    "with\ttab",        # tab (control character)
    "with\rcarriage",   # carriage return
]

print("=" * 60)
print("CURRENT APPROACH (manual escaping):")
print("=" * 60)
for value in test_values:
    # Current escaping: replace \\ first, then '
    escaped = value.replace("\\", "\\\\").replace("'", "\\'")
    result = f"'{escaped}'"
    print(f"Input: {repr(value)}")
    print(f"Output: {result}")
    print()

print("=" * 60)
print("JSON.stringify APPROACH:")
print("=" * 60)
for value in test_values:
    result = json.dumps(value)
    print(f"Input: {repr(value)}")
    print(f"Output: {result}")
    print()

# Now test the actual union generation
print("=" * 60)
print("UNION GENERATION COMPARISON:")
print("=" * 60)
enum_values = ["Active", "Inactive", "with\nnewline"]

# Current approach
current_union = " | ".join(f"'{v.replace(chr(92), chr(92)*2).replace(chr(39), chr(92)+chr(39))}'" for v in enum_values)
print(f"Current union: {current_union}")

# JSON.stringify approach
json_union = " | ".join(json.dumps(v) for v in enum_values)
print(f"JSON union: {json_union}")
EOF

Repository: prisma/prisma-next

Length of output: 1263


🏁 Script executed:

cat -n packages/3-targets/6-adapters/postgres/src/codecs/postgres-codec-descriptors.ts | sed -n '200,240p'

Repository: prisma/prisma-next

Length of output: 2236


🏁 Script executed:

rg -B 10 "renderOutputType" packages/3-targets/6-adapters/postgres/src/codecs/postgres-codec-descriptors.ts

Repository: prisma/prisma-next

Length of output: 6009


Emit enum unions with fully escaped TypeScript string literals.

The current escaping handles only \ and ', but enum labels containing control characters (newlines, tabs, etc.) generate invalid TypeScript in contract.d.ts. Use JSON.stringify(String(value)) which properly escapes all special characters and is the safe standard approach.

Proposed fix
   renderOutputType: ({ values }) =>
     values
-      .map((value) => `'${String(value).replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'`)
+      .map((value) => JSON.stringify(String(value)))
       .join(' | '),
📝 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.

Suggested change
renderOutputType: ({ values }) =>
values
.map((value) => `'${String(value).replace(/\\/g, '\\\\').replace(/'/g, "\\'")}'`)
.join(' | '),
renderOutputType: ({ values }) =>
values
.map((value) => JSON.stringify(String(value)))
.join(' | '),
🤖 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/codecs/postgres-codec-descriptors.ts`
around lines 217 - 220, The renderOutputType implementation currently escapes
only backslashes and single quotes which fails for control characters; update
the function (renderOutputType) to stringify each enum value using
JSON.stringify(String(value)) instead of manual replace so the emitted union of
TypeScript string literals is fully escaped and produces valid contract.d.ts
output. Ensure you map over values and join with ' | ' as before, but use
JSON.stringify to produce each literal.

Comment on lines +279 to +289
export function json(): ColumnTypeDescriptor {
return jsonColumn;
}

export function jsonb(schema?: StandardSchemaLike): ColumnTypeDescriptor {
return _jsonb(schema);
/**
* Raw-JSONB column factory. Returns the bare {@link jsonbColumn} descriptor;
* payload is unvalidated. For schema-validated JSON columns, use
* `arktypeJson(schema)` from `@prisma-next/extension-arktype-json`.
*/
export function jsonb(): ColumnTypeDescriptor {
return jsonbColumn;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚠️ Potential issue | 🟠 Major

json() / jsonb() currently erase descriptor type precision

Both factories return ColumnTypeDescriptor, which widens away the concrete descriptor shape (including the specific type factory signature). That can weaken no-emit type extraction at call sites.

💡 Proposed fix
-export function json(): ColumnTypeDescriptor {
+export function json(): typeof jsonColumn {
   return jsonColumn;
 }

-export function jsonb(): ColumnTypeDescriptor {
+export function jsonb(): typeof jsonbColumn {
   return jsonbColumn;
 }
📝 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.

Suggested change
export function json(): ColumnTypeDescriptor {
return jsonColumn;
}
export function jsonb(schema?: StandardSchemaLike): ColumnTypeDescriptor {
return _jsonb(schema);
/**
* Raw-JSONB column factory. Returns the bare {@link jsonbColumn} descriptor;
* payload is unvalidated. For schema-validated JSON columns, use
* `arktypeJson(schema)` from `@prisma-next/extension-arktype-json`.
*/
export function jsonb(): ColumnTypeDescriptor {
return jsonbColumn;
export function json(): typeof jsonColumn {
return jsonColumn;
}
/**
* Raw-JSONB column factory. Returns the bare {`@link` jsonbColumn} descriptor;
* payload is unvalidated. For schema-validated JSON columns, use
* `arktypeJson(schema)` from `@prisma-next/extension-arktype-json`.
*/
export function jsonb(): typeof jsonbColumn {
return jsonbColumn;
}
🤖 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/column-types.ts` around
lines 279 - 289, The json() and jsonb() factories currently widen their return
type to the generic ColumnTypeDescriptor, losing the concrete descriptor shape
and the precise factory signature; update the function signatures to return the
exact descriptor types (use typeof jsonColumn for json() and typeof jsonbColumn
for jsonb()) so callers retain the concrete descriptor shape and factory
signature, e.g., change "export function json(): ColumnTypeDescriptor" to
"export function json(): typeof jsonColumn" (and likewise for jsonb) while
keeping the same returned values jsonColumn and jsonbColumn.

… Phase 4 M3 deletion (F09)

Postgres-adapter README:
- Replace the "json(schema) / jsonb(schema)" docs in the column-types
  Exports list with a note that json() / jsonb() are zero-arg raw-JSONB
  factories.
- Replace the JSON and JSONB support sections deleted-helper code sample
  with a side-by-side table of raw-JSONB vs schema-validated JSON, plus
  a worked arktypeJson(schema) example.
- Drop json(schema) / jsonb(schema) from the Higher-order codec authoring
  section (the deleted M3 surface) and add a sentence pointing at the
  per-library extension pattern.
- Drop the ./codecs entrypoint from the Exports list (no longer shipped)
  and refresh the ./runtime entry to reflect the empty parameterized-
  codecs list.

Source comments:
- column-types.ts: tighten the deletion-rationale comment on jsonColumn
  to lead with the per-library extension pointer.
- parameterized-codec-factories.ts: drop the stale "../codecs/json-factory.ts
  (M3)" reference; rewrite to point at per-library extensions.

Demo:
- Annotate the import type {} from .../codec-types workaround with a
  comment explaining its TS2742 portability purpose.

Arktype-json README:
- Add a "TS2742 portability workaround" section so consumers running into
  the warning have a documented one-line fix.

Refs codec-registry-unification review F09; project plan § Phase 4 close-out.
The codec-model-unification project landed a sister `ParameterizedCodecDescriptor`
in the M5 close-out; the codec-registry-unification project superseded it
with the unified `CodecDescriptor<P = void>` (Phase 3.5a — descriptor-map
read-surface unification, with the registration-side migration tracked
under TML-2357 as Phase 3.5b). The decision section, Composes section,
Consequences section, Supersedes section, and Future-work section update
substance to reflect the unified design without restructuring the ADR.

Substantive changes:
- Decision section introduces CodecDescriptor<P = void> as the unified
  type; explicitly calls out non-parameterized codecs as the degenerate
  case (P = void, constant factory).
- How-it-composes section adds the descriptor map + descriptorFor +
  forColumn read APIs and the EmissionSpi.resolveFieldTypeParams
  callback for typeRef-based emit-path resolution.
- Surface-segregation framing deletes; replaced with a per-library
  extension model (arktype-json as the first such extension; the
  postgres adapter retains only raw-JSONB codecs).
- TML-2330 misattributions strip; the registration-side migration is
  attributed to TML-2357 (its actual ticket; the previous TML-2330
  references conflated this work with KMS dispatch concurrency, which
  is the genuine TML-2330 scope).
- Supersedes/Resolves/References sections refresh to name CodecDescriptor
  and to mention the typeRef emit-path fix from Phase 2.

Refs codec-registry-unification spec § Decision; project plan § Phase 5 T5.1.
… TML-2330 misattribution (Phase 5 T5.2-T5.4)

Subsystem docs:
- "Contract Emitter & Types § Parameterized codecs and the FieldOutputTypes
  map": replace ParameterizedCodecDescriptor with the unified
  CodecDescriptor<P>; add the descriptor map + descriptorFor + forColumn
  read APIs; document the EmissionSpi.resolveFieldTypeParams callback for
  typeRef-based emit-path resolution; replace json(productSchema) example
  with arktypeJson(ProductSchema).
- "No-Emit Workflow § Parameterized columns": same name updates.

Package READMEs:
- framework-components: rewrite "Higher-order codec primitives" to lead
  with CodecDescriptor<P = void>, name the synthesizeNonParameterizedDescriptor
  helper, replace the "Multiple descriptors per codecId / surface
  segregation" subsection with a "Per-library JSON-with-schema extensions"
  one. Add Codec primitives entry to the package overview list. Note
  ParameterizedCodecDescriptor as a deprecated alias retained during the
  TML-2357 registration-side migration.
- extension-pgvector: rename ParameterizedCodecDescriptor to CodecDescriptor
  in the codec-authoring section.
- adapter-mongo: same.

TML-2330 misattribution sweep:
- packages/3-targets/6-adapters/postgres/test/codecs.test.ts: drop the
  [TML-2330] inline citation and the "M4" milestone reference; the
  comment described the codec-model-unification work, which is now
  shipped under codec-registry-unification (the original ticket misattributed
  the registration-side migration to TML-2330; TML-2330 is genuinely about
  KMS dispatch concurrency and unrelated to this work).

Refs codec-registry-unification spec § Decision; project plan § Phase 5 T5.2, T5.3, T5.4.
…ps (F10)

Phase 4 deleted the M3 schema-typed JSON surface in commit 3c9aefd
(json-factory.ts, json-runtime-factory.ts, json-schema-validator.ts,
json-schema-type-expression.ts, standard-schema.ts, exports/codecs.ts).
Those were the only consumers of ajv (Ajv-backed JSON-Schema validator
compile helper) and @standard-schema/spec (Standard Schema input typing
on the deleted column-author surface). Both deps have survived in
package.json since the deletion.

Verified zero surviving consumers via:
- git grep "from .ajv." packages/3-targets/6-adapters/postgres/
- git grep "from .@standard-schema/spec." packages/3-targets/6-adapters/postgres/

(Both return no matches.)

`pnpm --filter @prisma-next/adapter-postgres remove ajv @standard-schema/spec`
removes the entries from package.json and pnpm-lock.yaml. The lockfile
churn is minimal: the adapter-postgres importer block loses both entries,
and the unique [email protected] pinned version drops from snapshots
([email protected] stays — consumed elsewhere). Other workspaces still pull
@standard-schema/spec via their own dependency declarations; only the
adapter-postgres importer block changes.

Refs codec-registry-unification close-out review F10.
…registry-unification

Per drive-orchestrate-plan/SKILL.md § Project close-out checkpoint:

Step 1 (migration audit): verified every load-bearing decision in
the rolling artifacts (wip/codec-registry-unification-review/) has
a durable on-disk home — ADR 205 (rewritten in bc9bb8b to capture
the unified CodecDescriptor design); subsystem doc 2 + 9 (refreshed
in 85ac5f1); package READMEs (refreshed in 85ac5f1); arktype-
json README (Phase 4); TML-2357 (filed for the deferred Phase 3.5b
scope).

Step 2 (branch-scoped close-out review): fresh-spawn reviewer ran
drive-pr-local-review over the cumulative diff (ce82ab1..HEAD,
17 commits). Verdict: APPROVE WITH FOLLOW-UPS. 5 of 9 ACs PASS;
4 deferred to TML-2357 (honestly captured); F10 closed in 9f9e714;
F11 deferred to TML-2357 PR 2.

Step 3 (authorize close-out): one repo-wide reference to the
project path survived (in arktype-json/README.md § See also);
rewritten to point at ADR 205 only. Project directory deletes here.

The ADR 205 + subsystem docs + READMEs + TML-2357 collectively are
the durable record of this project. The rolling artifacts under
wip/ persist as local audit trails.
…s to wip/ instead of deleting

The close-out checkpoint previously sequenced as: delete the
project directory first, then delegate the close-out review via
drive-pr-local-review. The reviewer arrived at a branch with no
in-repo canonical spec and inferred one from PR body + diff +
commit messages — verifying the inferred spec's ACs against the
diff was tautologically PASS. The original spec, with its rejected
alternatives, locked decisions, and non-goals, was deleted before
the reviewer could read it.

The fix splits the close-out into:

- Step 2: move projects/<project>/ to wip/<project>/ (single
  git mv; destination is gitignored; project content untracked
  from git but locally retained on disk).
- Step 3: delegate the close-out review with the canonical spec
  at its moved location (wip/<project>/spec.md) explicitly passed
  as input. Reviewer does NOT write a new spec.md; the canonical
  one was authored by the user during shaping and is the source
  of truth for ACs.

Move-not-delete has a second benefit: the user can grep, read,
or copy from the moved project artifacts locally without recovering
from git show. Useful for filing follow-up tickets that reference
original task IDs, auditing decisions made during the loop, or
recovering a finding's context.

Adds learnings.md § The infer-the-spec-you-just-deleted pattern
capturing the defect and origin (codec-registry-unification close-
out, where the user flagged the circular-verification immediately
after the inferred-spec close-out review landed).
… — git rm --cached + mv, not git mv

The previous version of SKILL.md § Step 2 described the close-out
move as "single git mv to a gitignored destination" without
verifying the primitive. Empirical test: git mv records a rename in
the index regardless of .gitignore — the moved files remain tracked
under the new path. .gitignore is a filter for untracked paths, not
an ejector for tracked ones.

The correct sequence is git rm --cached -r (untrack from index;
files stay on disk) followed by plain mv (filesystem rename,
invisible to git). After the commit: git ls-files reports the
project gone; find lists every file at the new wip/<project>/
location; git check-ignore confirms the new path is recognized as
gitignored.

Updates SKILL.md § Step 2 with the corrected primitive, a code
block showing the four-command sequence, and three verification
checks. Adds an explicit do-not-use-git-mv warning citing the
empirical reason (git tracking is path-independent).

Adds learnings.md § The git mv-to-gitignored-path pattern
documenting the trap, the verification approach, and the origin
(user skepticism after the previous SKILL update assumed git mv
without verifying).
@wmadden
wmadden marked this pull request as draft April 30, 2026 08:30
@wmadden

wmadden commented Apr 30, 2026

Copy link
Copy Markdown
Contributor Author

Superseded by #402. This branch was authored against the synchronous Codec interface that pre-dated ADR 204's single-path async codec runtime. After ADR 204 landed on main, the rebase surface became "rewrite every codec body" — gap analysis confirmed the cleaner path was to re-implement the codec-registry-unification work directly against current main's async baseline. PR #402 carries the equivalent design (ADR 207 — Higher-order codecs for parameterized types) end-to-end.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants