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

feat(codec): single-path async codec runtime - #379

Merged
wmadden merged 71 commits into
mainfrom
feat/codec-async-single-path
Apr 27, 2026
Merged

wmadden merged 71 commits into
mainfrom
feat/codec-async-single-path

Conversation

@wmadden

@wmadden wmadden commented Apr 26, 2026 •

Copy link
Copy Markdown
Contributor

closes https://linear.app/prisma-company/issue/TML-2304/pn-support-async-codecs

single-path async codec runtime

Grounding example

A user wants a secret column that's encrypted before insert and decrypted on read using a real async crypto API. They author a codec:

const secretCodec = codec({
  id: 'app/secret@1',
  encode: async (plain: string) => aesGcmEncrypt(plain, key),
  decode: async (cipher: Uint8Array) => aesGcmDecrypt(cipher, key),
  encodeJson: (value) => /* sync, build-time */ ...,
  decodeJson: (json) => /* sync, build-time */ ...,
});

They register it on a column. Their application code stays ordinary:

await users.create({ secret: 'hello' });
const row = await users.first({ where: { id } });
row.secret; // string — plain T, no Promise leaks into user code

This wasn't possible before: Codec.encode and Codec.decode were synchronous, and the runtime called them in tight for loops.

Decision

Make Codec.encode and Codec.decode always return Promise<T> at the public boundary. The runtime always awaits them and dispatches per-row codec calls concurrently with Promise.all. Codec authors keep writing whichever shape is natural — sync or async — and the factory (codec() / mongoCodec()) lifts both uniformly. Build-time methods (encodeJson, decodeJson, optional renderOutputType) stay synchronous because they don't run per-row.

The canonical decision record is ADR 204 — Single-Path Async Codec Runtime.

Narrative

A codec author's natural unit of work is "encode this one value" or "decode this one cell". When that work is synchronous (e.g. a JSON serializer) authoring is simple; when it's asynchronous (crypto, network-backed redaction policy, contract-side computed defaults that consult IO) the author needs to await inside encode / decode without worrying whether the runtime knows what to do with the result.

Two shapes were on the table:

  • Per-codec sync/async marker: every codec carries a runtime: 'sync' | 'async' discriminator on the public surface; every call site branches on it.
  • Always-async at the public boundary: every encode / decode returns Promise<T>; the runtime always awaits.

We chose the second. The discriminator pushes complexity into every consumer of Codec: the runtime's per-row dispatcher, the SQL DSL's encode-once-per-statement path, the Mongo encode lowering, the ORM's row-yielding generator, and downstream tests. Each call site has to handle both shapes, usually via conditional return types and instanceof Promise guards. Always-async pushes the cost into one place — the factory, which lifts a sync author function to async (x) => fn(x) once. The runtime then has a single arm (await codec.encode(...), await codec.decode(...)) and uses Promise.all to dispatch per-row work concurrently. From the user's point of view nothing changes: rows yielded by collections still hold plain T, and write inputs still accept plain T.

The Codec interface stays at four generics: Codec<Id, TTraits, TWire, TInput>. An earlier draft introduced a fifth TOutput = TInput parameter to express the asymmetric TInput ≠ TOutput case, but every consumer used the symmetric form, so the parameter was collapsed back to four generics in commit be04ceaeb. If a real asymmetric case lands later it can be reintroduced as an additive widening.

The Mongo family aligns with the same shape. MongoCodec is structurally identical to the framework BaseCodec (same four generics, same order, same defaults), so a single codec({...}) value works against both registries. MongoAdapter.lower(plan) becomes Promise<AnyMongoWireCommand> because lowering walks codecs as it produces the wire shape.

Behavior changes & evidence

Change Before After Evidence
Codec.encode / Codec.decode sync Promise<T> at the public boundary framework-components/src/codec-types.ts (L34–L56); type tests
codec() / mongoCodec() factory sync-only authoring accepts sync, async, or mixed; uniformly lifts to Promise-returning relational-core/src/ast/codec-types.ts (L215–L263); mongo-codec/src/codecs.ts (L55–L93)
Codec generic count 4 (Id, TTraits, TWire, TJs) 4 (Id, TTraits, TWire, TInput) — TJs renamed to TInput; same arity framework-components/src/codec-types.ts (L34–L39); MongoCodec aligned in mongo-codec/src/codecs.ts (L17–L22)
SQL runtime dispatch sync for-loop always-await + Promise.all per encode/decode site encoding.ts (L74–L103), decoding.ts (L206–L273); codec-async.test.ts
Error envelopes on encode/decode failure raw thrown errors RUNTIME.ENCODE_FAILED / RUNTIME.DECODE_FAILED with cause chaining; existing RUNTIME.JSON_SCHEMA_VALIDATION_FAILED envelope re-raised verbatim when matched wrapEncodeFailure (L23–L38), wrapDecodeFailure (L94–L114); envelope tests in codec-async.test.ts (L145–L580)
MongoAdapter.lower(plan) sync Promise<AnyMongoWireCommand> so adapters can run async codec encodes before producing the wire shape mongo-lowering/src/adapter-types.ts (L1–L6); adapter-mongo tests
resolveValue (Mongo encode-side) not the dispatch concentration site await codec.encode(...) per MongoParamRef leaf; Promise.all over array elements and object children; encode failures wrapped in RUNTIME.ENCODE_FAILED envelope resolve-value.ts (L20–L56); resolve-value.test.ts (L87–L183)
Cross-family BaseCodec seam divergent shapes between SQL Codec and Mongo MongoCodec both align on BaseCodec with structurally-identical four-generic shape cross-family-codec.test.ts; mongo-codec/test/codecs.test-d.ts (L62–L82)
Real AES-GCM crypto round-trip (security probe) only synthetic Promise.resolve(...) codecs in tests seeded-secret-codec fixture: real AES-GCM with deterministic test key, end-to-end through encodeParams and decodeRow, asserts no Promise leaks into yielded rows seeded-secret-codec.ts; codec-async.test.ts (L618–L703)

What stays the same

Downstream changes

Observable to anyone authoring adapters or codec implementations outside this PR. End-users of the ORM / SQL DSL surfaces don't have to do anything.

  • Codec authors. Codec.encode / Codec.decode are now Promise-returning at the type level. The factory lifts both sync and async author functions; you don't have to write async if your codec is synchronous, but you do have to migrate any direct implementation of the Codec interface (rare). Recipe: decode: (wire) => wire → decode: async (wire) => wire; or use the factory.
  • Codec authors with non-JsonValue TInput. encodeJson / decodeJson are now required when TInput is not assignable to JsonValue (e.g. Date, Uint8Array, bigint). Sync identity defaults still apply when TInput extends JsonValue. Recipe: implement encodeJson / decodeJson returning a JSON-safe representation (ISO string for Date, base64 for Uint8Array, decimal string for bigint, etc.).
  • Mongo adapter authors. MongoAdapter.lower(plan) now returns Promise<AnyMongoWireCommand> instead of AnyMongoWireCommand. Recipe: change lower(plan) { ... } → async lower(plan) { ... }. The runtime and runner already await the result.
  • Adapter authors who call codec.encode(...) / codec.decode(...) directly. Both calls now return Promises. Recipe: prefix call sites with await; convert any direct expect(...).toThrow(...) assertions to await expect(...).rejects.toThrow(...).

Compatibility / migration / risk

  • Promise.all failure semantics are partial fail-fast. The first rejected dispatch surfaces as the error envelope; remaining dispatched bodies still run to completion (they cannot be cancelled in standard Promise.all) but their outputs are discarded. From the user's point of view this matches the prior for-loop's "throw on first failure" behavior. Concurrency control for KMS-backed codecs (rate limiting / AbortSignal) is tracked separately under TML-2330.
  • Allocation pressure. Every codec dispatch allocates a Promise; for a query returning N rows × M codec'd cells, that's N × M allocations. The walk-back path below is preserved precisely to keep this cost recoverable without breaking the public surface. Sync fast-path is tracked under TML-2331.
  • Error-envelope cleartext leaks. The expanded encrypting-codec surface means error envelopes can leak plaintext via error.message / details.errors. Trait-gated redaction is tracked under TML-2329; ADR 204 §"Risks & mitigations" defers the spelling.
  • Walk-back stays open. Because no sync/async discriminator was introduced on the public surface, a future synchronous fast path can be added additively as codecSync(). ADR 204 transcribes the seven walk-back constraints verified absent across this project: no per-codec async marker; no codecSync / codecAsync variants today; no isSync* predicates; no conditional return types on Promise-returning methods; no TRuntime generic on Codec or MongoCodec; no async-dependent author-surface docs; no async-dependent build-time guarantees.
  • Test fixtures updated mechanically. Inline Codec-shaped fixtures across framework-components, sql-contract-ts, cli, integration-tests, pgvector, adapter-postgres, and adapter-sqlite were updated by recipe: decode: (wire) => wire → decode: async (wire) => wire; add encode: async (value) => value when missing; prefix call sites with await; convert expect(...).toThrow(...) to await expect(...).rejects.toThrow(...). No production-source escape hatches were needed; the factory's lift normalizes any combination of sync and async author functions.
  • No backwards-compatibility shims. Per AGENTS.md § Golden Rules. The legacy MongoCodecJsType<T> extractor was replaced by MongoCodecInput<T> (mirroring SQL's CodecInput<T>) without an alias.

Alternatives considered

  • Per-codec runtime: 'async' marker. Rejected. The cost lives in the wrong place: every call site (runtime dispatcher, SQL DSL, Mongo lowering, ORM generator, tests) has to handle both shapes via conditional return types and runtime branching. The seam is wrong: sync-vs-async cuts across query-time methods rather than aligning with the build-time-vs-query-time boundary the codec interface already has. Cross-family portability is harder: every codec definition has to be reshaped per family. And there is no clean walk-back path — once a marker is on the public surface, removing it is breaking.
  • Defer the change entirely. Rejected. Async codecs unblock real work already on the roadmap: column-level encryption, redaction policy that consults external sources, and contract-side computed defaults that may need IO. Deferring forces consumers to wrap codecs around the runtime instead of inside it.

Non-goals / intentionally out of scope

  • Synchronous fast path. A future codecSync() opt-in is preserved as an additive non-breaking change; not landed in this project. Tracked under TML-2331.
  • Mongo decode-side codec dispatch. Mongo doesn't decode rows today; ADR 204 records the future pattern (mirror SQL's decodeRow). Tracked under TML-2324.
  • Include-aggregate child-codec dispatch. Orthogonal ORM feature; deferred.
  • Redaction-trigger spelling. Orthogonal redaction-policy work; tracked under TML-2329.
  • Concurrency control for KMS-backed codecs. No rate limiting or AbortSignal plumbing today; tracked under TML-2330.

Summary by CodeRabbit

  • New Features

    • Codec query-time encode/decode are now Promise-based and always awaited by the runtime; build-time helpers remain synchronous.
    • Async lowering/encoding for SQL and Mongo paths so parameter encoding and pipeline lowering run concurrently.
  • Bug Fixes

    • Prevents Promise leakage into driver/consumer outputs; async codec failures are wrapped with structured runtime error envelopes.
  • Documentation

    • ADRs and READMEs updated to describe the async codec runtime contract and usage.
  • Tests

    • Expanded suites and type-tests ensuring async codec behavior and cross-family parity.

wmadden added 30 commits April 26, 2026 16:06
Add the shaping artifacts for the single-path async codec runtime project,
the alternative direction adopted after the architectural review of PR #375
rejected its per-codec async opt-in.

The spec captures the public Codec interface uniform across families, the
build-time vs. query-time seam, the runtime always-await pattern with
Promise.all per row, the walk-back constraints that keep the future sync
fast path additive, and the cross-family parity requirement. The plan
breaks the work into five milestones (interface + factory; SQL runtime;
ORM client; cross-family parity including the Mongo encode-side reshape;
security tests + ADR + close-out) with internal review/refine gates
between milestones on a single branch.
Pre-flight for drive-orchestrate-plan: each milestone now carries
T<m>.<n> task identifiers and an explicit validation gate naming the
project pnpm harness commands. No scope changes; structural metadata
only so sub-agents can reference task IDs and gate commands directly
from the plan.
…ing codec query-time methods

Land failing tests for the public Codec interface and codec() factory shape
ahead of the implementation. The interface tests pin encode and decode as
required Promise-returning methods, encodeJson/decodeJson as required and
synchronous, renderOutputType as optional and synchronous, and assert the
full set of Codec keys carries no async marker (no runtime/kind field, no
TRuntime generic). The factory tests cover sync, async, and mixed
authoring of encode/decode, the identity default when encode is omitted,
and pass-through of the synchronous build-time methods.

Phase m1 (T1.1, T1.2).
…ec interface and factory

Phase m1 (T1.3-T1.4).

Update the public Codec interface to land on the build-time vs.
query-time seam:

- Query-time methods (encode, decode) are required and Promise-
  returning at the boundary.
- Build-time methods (encodeJson, decodeJson, renderOutputType) stay
  synchronous so validateContract and client construction remain
  synchronous.

Update the codec() factory to accept sync, async, or mixed query-time
author functions and lift them transparently via async (x) => fn(x).
encode is now optional (identity default); decode is required.

Introduce TInput/TOutput generic split on Codec with TOutput = TInput
default so existing 4-generic call sites continue to work.

Update immediate consumers within the two source packages:
  - framework-components/test/control-stack.test.ts: add async
    encode/decode to the inline CodecLookup test fixture so it
    satisfies the new Codec shape.
  - relational-core/test/ast/codec-types.test.ts and sql-codecs.test.ts:
    await codec.encode/decode at call sites.

Downstream packages that receive TWire synchronously today will need
to await codec.encode/decode in subsequent milestones; those reshapes
are deferred to M2-M4 per plan.
…scope

Capture the progressive-green pattern explicitly: codec-async-ness
propagates from interface (M1) through consumers (M2-M4); workspace
test gates therefore go green progressively. Each milestone now lists
in-scope packages (must be green) and expected residual packages
(scheduled for later milestones). Workspace pnpm lint:deps stays green
at every milestone boundary; M4 closes out the consumer reshape; M5
runs the definitive pnpm test:all.
…c interface (F2)

Two inline `CodecLookup` test fixtures construct `Codec`-shaped object literals
that became invalid after the m1 codec interface change: `encode` is now required
and both `encode` and `decode` are Promise-returning at the boundary.

Mirror the fix already applied in `framework-components/test/control-stack.test.ts`
(commit 97c5007): add `encode: async (value) => value` and convert `decode` to
async; preserve the existing `encodeJson` / `decodeJson` bodies.

Affected sites:
- packages/2-sql/2-authoring/contract-ts/test/contract-builder.contract-definition.test.ts
- packages/2-sql/2-authoring/contract-ts/test/contract-builder.value-objects.test.ts

Resolves F2 from projects/codec-async-single-path/reviews/code-review.md
(m1 / R1). Phase: m1, continuation of T1.4 consumer-test sweep.

`pnpm --filter @prisma-next/sql-contract-ts typecheck` and `... test` are now green.
…nc codec interface

Workspace audit (proactive sweep beyond F2) surfaced two additional inline `Codec`-shaped
test fixtures that became invalid after the m1 codec interface change. Both have the
same shape as F2: sync `encode` / `decode` (or missing `encode`) on a literal that is
assigned to a typed slot expecting the post-m1 `Codec` interface (Promise-returning
query-time methods, `encode` required).

Mechanical extension of T1.4 consumer-test sweep, identical fix to F2 and to
`framework-components/test/control-stack.test.ts:467` (97c5007).

Affected sites (both outside m1 expected-residual list):
- packages/1-framework/3-tooling/cli/test/control-api/contract-enrichment.test.ts
  (codecInstances literal: `encode` and `decode` were sync arrows; converted both to async)
- test/integration/test/mongo/migration-psl-authoring.test.ts
  (`mongoCodecLookup` fixture: `encode` was missing, `decode` was sync; added async
  identity `encode`, converted `decode` to async)

`pnpm --filter @prisma-next/cli typecheck` and `pnpm --filter @prisma-next/integration-tests typecheck` are now green.

Phase: m1, continuation of T1.4 consumer-test sweep (audit-discovered).
The drive-orchestrate-plan skill was updated this session to disallow
findings whose recommended action is not addressable in the current
implementer round. F1 (low/process, deferred to m4) no longer qualifies.

Re-recording the cast cleanup as part of m4 T4.2 makes it actionable in
the right phase and clears it from code-review.md as a non-actionable
open finding. The next reviewer round will close F1 with a bookkeeping
closure note.
… codec runtime (T2.1, T2.2, T2.7, T2.8)

T2.1 / T2.2: assert that encodeParams and decodeRow dispatch concurrently
via Promise.all, always await codec.encode/decode, propagate JSON-Schema
validation against resolved values, and wrap codec failures in
RUNTIME.ENCODE_FAILED / RUNTIME.DECODE_FAILED envelopes carrying
{ label, codec, paramIndex } and { table, column, codec } respectively
(plus cause). Single-armed decodeField is asserted by uniform behavior
across sync- and async-authored codecs.

T2.7 / T2.8: lock validateContract and postgres({...}) as synchronous
at both type-level (assignment to Contract<SqlStorage> / PostgresClient
without await) and runtime (no .then on the result).

Existing json-schema-validation tests are awaited to track the upcoming
async signatures of encodeParams and decodeRow.
… (T2.3-T2.6)

encodeParams now dispatches per-parameter codecs concurrently via
Promise.all and always awaits codec.encode, so a Promise can never leak
into the driver. Failures are wrapped in RUNTIME.ENCODE_FAILED carrying
{ label, codec, paramIndex } and the original error on cause.

decodeRow now dispatches per-cell codecs concurrently via Promise.all
through a single-armed decodeField (codec.decode → await → JSON-Schema
validate against the resolved value → return plain value). Failures are
wrapped in RUNTIME.DECODE_FAILED carrying { table, column, codec } when
the column ref is resolvable (with { alias } as fallback) and the
original error on cause. Include-aggregate parsing reuses the same
envelope shape.

The fallback column-ref index is now built whenever the projection
alias-to-ref mapping is unavailable (regardless of validator presence)
so that decode error envelopes can still surface { table, column } via
plan.meta.refs.columns.

sql-runtime executeAgainstQueryable awaits encodeParams and decodeRow
on a single async path per direction. There is no plan-walker, no
WeakMap cache, and no instanceof Promise defensive guard.
…nit tests

After m1 the Codec interface boundary requires Promise-returning encode
and decode. The adapter-postgres and adapter-sqlite codec unit tests
were poking at codec.encode / codec.decode synchronously through casts
to a sync shape. Update the casts to return Promise and await every
call so the in-scope packages typecheck cleanly against the m2 contract.

This is consumer-side reshape only — no production code changes — and
keeps the existing test scenarios verbatim (round-trip values, error
messages, native-type metadata).
…ain T (T3.1–T3.6)

Adds m3 coverage for the codec-async-single-path project: type-level proof
that the ORM read/write surfaces stay plain T even when columns flow through
Promise-returning codecs, plus an end-to-end integration test that runs the
real sql-runtime through a live Postgres driver to verify the same contract
on actual rows.

- sql-orm-client/test/codec-async.types.test-d.ts (T3.1, T3.2, T3.3):
  * DefaultModelRow / InferRootRow / Collection.first() / Collection.all()
    yield plain T for each codec-backed column (no Promise<T>).
  * CreateInput / MutationUpdateInput / UniqueConstraintCriterion /
    ShorthandWhereFilter accept plain T at write positions.
  * Negative IsPromiseLike<...> assertions on every read+write field
    position document the "no Promise<T> leak" invariant.
  * One-field-type-map check: Create/Update field types equal the matching
    DefaultModelRow field types, pinning the verification that no read/write
    split for codec output types was introduced.

- sql-orm-client/test/integration/codec-async.test.ts (T3.5, T3.6):
  * Real-DB roundtrip with pg/vector@1 and pg/jsonb@1 (lifted to async by
    relational-core's codec() factory).
  * Read paths: .first() and `for await ... of c.all()` yield plain values.
  * Write paths: create() and update() accept plain T and persist the
    encoded wire format produced through the runtime's async encode path.

- pgvector/test/codecs.test.ts (related):
  * Aligns the pgvector codec unit tests with the m1 codec contract by
    awaiting encode()/decode() through the Promise-returning shape.
…on-dispatch (T3.4)

m3/T3.4 verification — collection-dispatch.ts never invokes codec.encode or
codec.decode directly. Per-row decoding is owned by sql-runtime's async
generator (see executeAgainstQueryable in @prisma-next/sql-runtime), which
awaits codec.decode once per row before yielding. The dispatch layer's
for-await loops therefore see plain T cell values by construction.

Adds a header doc comment describing this linkage and pointing at the
covering m3 tests so future readers see why the dispatch layer is
codec-agnostic. No runtime change.
The T3.4 doc-comment commit (41e01b5) left two stacked top-level doc
blocks at the head of `collection-dispatch.ts`. The second block also
referenced `test/codec-async.e2e.test.ts`, which was deleted earlier in
m3 (commit 7505ef1) in favour of `test/integration/codec-async.test.ts`.

Replace them with a single header that keeps the substance of the first
block, folds in the ADR 030 cross-link from the second, and points test
references at the surviving files (`test/integration/codec-async.test.ts`
and `test/codec-async.types.test-d.ts`).

No runtime behavior changes; doc-comment cleanup only.

Phase 3 (T3.4) — m3 R2 F3 fix.
…olveValue, and Mongo client sync regression

Tests-first per AGENTS.md. These tests assert m4 behavior and fail
on the current code:

- T4.1 (test/integration/test/cross-package/cross-family-codec.test.ts):
  a single codec({...}) value registered in both a SQL CodecRegistry and
  a Mongo MongoCodecRegistry produces identical wire output, and the
  same codec round-trips through SQL decode.

- T4.4 (packages/3-mongo-target/2-mongo-adapter/test/resolve-value.test.ts):
  resolveValue is async, returns a Promise, and dispatches multiple
  codec-encoded leaves concurrently via Promise.all; identity passthrough
  for non-MongoParamRef values is preserved.

- T4.10 (packages/2-mongo-family/1-foundation/mongo-contract/test/validate.test.ts):
  validateMongoContract stays synchronous; type-level binding asserts
  the call site does not require await.

- T4.10 (packages/3-mongo-target/2-mongo-adapter/test/mongo-adapter.test.ts):
  createMongoAdapter() stays synchronous so client construction does not
  drift to Promise-returning.

Also updates the existing mongoCodec()/MongoCodecTraits unit tests to
assert the unified factory shape (traits omitted -> undefined; encode/
decode promise-returning) ahead of the T4.2 reshape.

Adds @prisma-next/mongo-codec and @prisma-next/mongo-value as deps of
the integration tests package so the cross-family test resolves.

Refs: codec-async-single-path/plan.md M4 (T4.1, T4.4, T4.10).
…2/T4.3)

Aligns the Mongo codec entry point with the unified codec() factory in
relational-core so a single codec definition can be reused across SQL
and Mongo registries:

- MongoCodec is now a direct alias of the framework BaseCodec; the
  redundant `readonly traits: TTraits` override is removed.
- mongoCodec() accepts sync or async encode/decode and lifts uniformly
  to Promise-returning methods via `async (x) => fn(x)`, mirroring the
  SQL codec() factory exactly.
- Optional fields (traits, renderOutputType) flow through `ifDefined`
  rather than the previous `as unknown as TTraits` empty-array cast at
  the trait default site (resolves F1 from the m1 review).
- Built-in Mongo codecs in adapter-mongo unchanged; their existing sync
  encode/decode authors are now lifted to Promise-returning methods by
  the factory. Their unit tests are updated to await the boundary.

Refs: codec-async-single-path/plan.md M4 (T4.2 incl. F1 cleanup, T4.3).
…patch (m4 T4.5/T4.6/T4.9)

resolveValue() and MongoAdapterImpl.lower() are now Promise-returning so
codec.encode() can be awaited at the encode boundary. Object/array nodes
dispatch their child resolutions concurrently via Promise.all, mirroring
the SQL runtime always-await + concurrent-dispatch shape from m2.

The full encode-side lowering chain (lowerFilter, lowerStage,
lowerPipeline, mongo-adapter.lower, MongoAdapterImpl.#resolveDocument
and #lowerUpdate) becomes async. Independent siblings (filter + update
for update commands; per-document encoding for insertMany; per-stage
lowering for pipelines and $facet) are dispatched concurrently rather
than serially.

Existing fixtures in resolve-value.test.ts, mongo-adapter.test.ts, and
lowering.test.ts are awaited per T4.9.
…it it (m4 T4.7/T4.8)

The MongoAdapter interface (mongo-lowering) now declares
lower(plan): Promise<AnyMongoWireCommand>, completing the encode-side
async signature change. Both consumers are updated to await:

- mongo-runtime: execute() awaits adapter.lower(plan) before handing the
  wire command to the driver. Middleware ordering is unchanged; the
  await happens between beforeExecute and driver.execute.
- mongo-runner: the two adapter.lower call sites in
  executeDataTransform and evaluateDataTransformChecks are awaited so
  data-transform migrations and read-only data-transform checks flow
  through the same async lowering boundary as runtime queries.

Closes the encode-side parity gap with the SQL runtime: Mongo now has a
single Promise-returning lower() boundary that codec authors can rely
on for asynchronous work.
…m4 T4.9)

After T4.7 made MongoAdapter.lower Promise-returning, the
StubMongoAdapter in test/mongo-runner.test.ts must mirror that shape so
ts-c can verify the runner code path types end-to-end. The stub now
returns Promise<WireCommand>, and the local WireCommand type alias
unwraps the adapter return type with Awaited<...> so it still names the
non-promised wire command shape.

Mongo runner unit tests pass; no functional change.
The `MongoAdapter.lower` signature in `adapter-types.ts` became
`Promise<AnyMongoWireCommand>` in m4 (async-codec single path), but the
package README still narrated the pre-m4 sync return. Update the
narration to match the post-m4 reality and call out the await-required
boundary so consumers do not infer a sync path from the docs.

Project: codec-async-single-path; Phase: m4 R2 (F4).
The pre-m4 `MongoCodec` had four generics (`<Id, TTraits, TWire, TJs>`),
while the framework `BaseCodec` (and SQL `Codec`) carry five
(`<Id, TTraits, TWire, TInput, TOutput = TInput>`) so input and output
JS types can diverge on a single codec. Cross-family parity (AC-CX1)
calls for the Mongo `Codec` interface to be structurally identical to
the SQL one; the permissive 4-generic alias passed via the canonical
TInput=TOutput case but failed the strict structural-identity reading.

Widen `MongoCodec` and the `mongoCodec()` factory to the same 5-generic
shape, keep `TOutput = TInput` as the default so all existing call
sites (built-in codecs, mongo-codec tests, mongo-adapter tests, the
cross-family parity test) continue to compile unchanged. Replace the
single `MongoCodecJsType<T>` extractor with `MongoCodecInput<T>` and
`MongoCodecOutput<T>`, mirroring SQLs `CodecInput<T>` / `CodecOutput<T>`
positional pattern.

Add type-level tests pinning the 5-generic shape, the
`TOutput = TInput` default, the asymmetric `TInput ≠ TOutput` case is
expressible at the method-signature level, and the new extractors
behave correctly on the canonical symmetric case.

Project: codec-async-single-path; Phase: m4 R2 (orchestrator-absorbed
generic-asymmetry decision).
…IED)

Reflect post-R2 state at HEAD `47ce86a6f` across all three reviewer
artifacts:

- code-review.md: F4 marked resolved (commit `6f567afa3`); AC-CX1 evidence
  promoted from permissively PASS to strictly PASS at the BaseCodec seam;
  m4 R2 round notes appended (verdict SATISFIED, no open findings,
  validation gates green workspace-wide).
- system-design-review.md: scope updated to m1+m2+m3+m4 snapshot at HEAD
  `47ce86a6f`; new section M4 R2 narrates strict cross-family parity at
  the BaseCodec seam and F4 closure; the M4.7.1 open question
  (4-vs-5 generic asymmetry) is recorded as resolved by widening.
- walkthrough.md: scope updated to current HEAD; new m4 R2 delta narrates
  the two commits (`6f567afa3` README fix and `47ce86a6f` MongoCodec
  widening) with semantic narrative, behavior changes & evidence,
  validation gates, compatibility, and follow-ups.

Force-added (`git add -f`) because `projects/**/reviews/` is gitignored
as transient/local artifacts per `.gitignore` lines 23–30; surfacing
the gitignore-vs-commit-instruction tension to the orchestrator in the
return message.

Phase 4 (m4 R2) — reviewer artifact refresh; SATISFIED.
…4 R2

Second-pass reviewer ran the m4 R2 verification independently against
on-disk state at HEAD 0d7bd78. The orchestrator delegation cited the
implementation HEAD (47ce86a) one commit prior to the artifact-commit
that landed the m4 R2 review narratives, so this pass reconciles the
snapshot drift by re-inspecting cited sources and re-running every
validation gate, rather than re-doing already-committed review work.

All 14 validation gates re-ran green (mongo-codec 18/18; adapter-mongo
215/215; target-mongo 366/366 with no CAS-flake reproduction;
mongo-contract 76/76; mongo-lowering types-only typecheck; cross-family
codec 3/3; workspace typecheck 120/120; test:packages 111/111;
test:integration 104 files / 521 tests; lint:deps 606 modules /
1198 deps no violations).

AC-CX1 strictly PASS confirmed; F4 closure confirmed; no drift between
artifact narratives and on-disk source state. No new findings filed.

Adds an "independent re-verification" subsection to:
- code-review.md (under m4 R2 round notes)
- system-design-review.md (M4 R2.10)
- walkthrough.md (under m4 R2 follow-ups)

Verdict: m4 R2 SATISFIED (reaffirmed).
Translated verbatim from PR #375 with the per-codec async marker dropped: the
single-path runtime always awaits, so codec authors hand `codec()` raw async
functions and the factory exposes Promise-returning encode/decode without
an opt-in flag. This fixture is the canonical realistic-crypto path for
the M5 envelope-redaction and JSON-Schema tests.
…ts (m5 T5.1/T5.3)

- sql-runtime.test.ts: add createRuntime tests for async parameter
  encoding before driver execution and RUNTIME.ENCODE_FAILED wrapping
  before the driver runs.
- codec-async.test.ts: add seeded-secret-codec roundtrip suite covering
  encodeParams encryption, decodeRow decryption, and DECODE_FAILED
  envelope shape (cause + bounded wirePreview) on async crypto failures.
- json-schema-validation.test.ts: add an async-decoder JSON-Schema
  failure case to confirm validation runs against the resolved value.

Drops PR #375 artifacts (no runtime: async/sync discriminator, no
kind: async marker, no per-codec branching). Uses single-path always-
await runtime via createCodecRegistry/codec() factory.
… T5.2, deferred)

Adds the verbatim codec-authored error.message redaction assertion
from PR #375 § json-schema-validation.test.ts, scoped to async decode
via the single-path runtime. The test is intentionally `it.skip` because
implementing the redaction trigger is out of scope per spec.md § Open
Items ("Redaction-trigger spelling — independent of this design;
tracked separately"). Current `wrapDecodeFailure` embeds error.message
into the wrapped envelope; activating this test will require a separate
redaction policy change.
…ild-row codec decoding

Translates the single-query include redaction tests from PR #375 as
`it.skip` placeholders against the single-path async runtime contract:
child cells should surface plain decoded values (no Promises), with
codec-driven JSON-Schema failures and DECODE_FAILED envelopes preserved.

The current `dispatchCollectionRows` single-query include path only
JSON-parses the aggregated payload and applies field-name mapping; it
does not invoke codec query-time methods on child cells. Adding child
codec decoding to the single-query include path is orthogonal ORM work
outside this project's scope (codec async-shape decision). The skips
keep the translated assertions discoverable for future activation.

PR #375 test 8 (promise-valued child cells) is intentionally dropped:
the single-path runtime always awaits decodeRow and yields plain T.
Documents the canonical decision: codec query-time methods (`encode`,
`decode`) are uniformly Promise-returning at the public boundary, the
runtime always awaits them, and the codec factory transparently lifts
sync author functions. Build-time methods (`encodeJson`, `decodeJson`,
`renderOutputType`) stay synchronous so `validateContract` and client
construction remain sync.

Includes:
- Context: what the rejected per-codec async marker (PR #375) tried and
  why architectural review rejected it (cost in the wrong place, no
  walk-back path, wrong seam, harder cross-family portability).
- Decision: uniform Codec interface, single `codec()` / `mongoCodec()`
  factory, always-await runtime with per-row `Promise.all`, sync
  build-time, uniform ORM type surfaces, cross-family parity.
- Architecture: interface shape, factory lift mechanics, runtime
  always-await pattern with concurrent `Promise.all`, Mongo encode-side
  parity (`resolveValue`, `MongoAdapter.lower()`, `MongoRuntime.execute()`).
- Walk-back framing: future additive `codecSync()` opt-in plus
  predicates plus runtime sync fast-path arm; lists the seven walk-back
  constraints from spec NFR #5 verbatim and explains why the design
  today preserves all of them.
- Trade-offs: per-cell Promise allocation overhead, mitigated by V8/JSC
  fast-async paths and the future opt-in; net-neutral or improved
  type-check time.
- Cross-family scope: Mongo encode-side in scope; Mongo decode path
  explicitly out of scope (Mongo does not currently decode rows);
  documents where future Mongo-row-decoding work plugs in.
- References: ADR 030 (registry model unchanged; runtime parts
  superseded), 027 (envelope codes), 131 (five-generic shape), 184
  (build-time seam), V8 fast-async post.

Born in `docs/architecture docs/adrs/` so it stands as canonical
source-of-truth without dependence on transient project artifacts.
Names the specific runtime-shape sections of ADR 030 that are
superseded by ADR 204 (codec method signatures, Decoding pipeline
row-by-row sync loop, Streaming and cursors "codecs must be synchronous"
statement) while keeping the registry model, precedence rules, lane
hints, error-mapping codes, and PPg policy in force. Pointer is placed
immediately after the title heading per the existing ADR convention
(see ADR 174 for precedent).
wmadden added 3 commits April 27, 2026 15:00
…ross-family test

P3.11 cleanup from jkomyno review:
- give the SQL `codec()` factory the same `TTraits = readonly []` default as
  `mongoCodec()` (and matching `TWire = unknown`/`TInput = unknown` defaults)
  so callers without traits land identically across both factories.
- drop the `mongoCodecLookup?.encode`/`sqlCodec.encode!(...)` asymmetry in
  the cross-family parity test now that `encode` is required on the
  unified `Codec` interface.
…odecs

Follow-up to P2.8 from jkomyno review: now that JsonRoundTripConfig
requires encodeJson/decodeJson when TInput is not assignable to
JsonValue, the SQLite blob (Uint8Array), datetime (Date), and bigint
codecs need explicit JSON serialization. Encode blobs as base64,
datetimes as ISO-8601, and bigints as decimal strings.
@wmadden

wmadden commented Apr 27, 2026

Copy link
Copy Markdown
Contributor Author

Thanks @jkomyno — substantive review, addressed below.

Triage doc with one row per finding (final dispositions, commit shas, ticket ids): projects/codec-async-single-path/reviews/jkomyno-actions.md.

Addressed in this PR

  • P1.1 (4-vs-5 generics doc drift) — 4bd3e3283 reconciles ADR 204 + PR body + mongo-codec/README.md to the four-generic shape (Id, TTraits, TWire, TInput); TOutput was deliberately collapsed in be04ceaeb and we don't restore it.
  • P1.2 (MongoAdapter.lower() async — undocumented breaking change) — added a "Downstream changes" section to the PR body with one-line migration recipes for codec authors, codec authors with non-JsonValue TInput, Mongo adapter authors, and adapter authors who call codec.encode/decode directly.
  • P1.4 (Mongo runtime missing encode envelope) — f6a31d7f4 wraps codec encode failures in resolve-value.ts with RUNTIME.ENCODE_FAILED ({ label, codec } + cause), mirroring SQL's wrapEncodeFailure. Caveat: closes the encode-side parity gap only. Mongo doesn't decode rows today (driver pass-through), so the decode-side parity hole remains tracked under TML-2324. The cross-family parity claim is now accurate for the encode-side.
  • P2.7 (seeded-secret-codec test fixture in tarball) — 594d7df38 drops "test" from packages/2-sql/5-runtime/package.json and packages/1-framework/3-tooling/emitter/package.json. Both packages route their ./test/utils export through dist/test/utils.mjs already, so the published ./test/utils subpath is unaffected. Audited the rest of the workspace; no other packages had this pattern.
  • P2.8 (encodeJson/decodeJson identity defaults unsound) — 2d639ce16 introduces JsonRoundTripConfig<TInput> on both factory call signatures: encodeJson / decodeJson are optional iff TInput extends JsonValue, otherwise required. Follow-up 5a00f9a57 supplies explicit encodeJson / decodeJson for SQLite blob/datetime/bigint codecs that the new conditional now flagged. Identity defaults remain sound at runtime.
  • P2.9 (hygiene bundle):
    • P2.9a (stale line ranges) — refreshed in this PR's body (codec-types L34–L56, factory L215–L263 + L55–L93, encoding L74–L103, decoding L206–L273 / wrapDecodeFailure L94–L114, resolveValue L20–L56, all the test-file ranges).
    • P2.9c (stale MongoCodecOutput<T> advert in mongo-codec/README.md:10) — bundled into the P1.1 doc reconciliation (4bd3e3283); the README no longer advertises MongoCodecOutput<T> (which was never exported anyway).
    • P2.9f (PR-Add async codec runtime support across SQL surfaces #375 references in test comments) — 968a03404 rewrites the comments in collection-dispatch.test.ts:398-428 and json-schema-validation.test.ts:611 with self-contained context about deferred work, no PR-numbers.
  • P3.10 (TypeScript cleanups bundle) — 98e4a909a in one commit:
    • drops the dead if (!codec.encode) return value; branch (encoding.ts);
    • introduces isRuntimeError(err) in framework-components/runtime and rewires isJsonSchemaValidationError to use it (no more string-literal duck typing);
    • tightens the encode-identity cast to as unknown as TWire in both factories (the synchronous identity returns immediately);
    • drops the defensive (x as { then?: unknown })?.then checks from codec-async.test.ts;
    • adds expectTypeOf<...> sync-return regression tests for validateContract and postgres({...}), symmetrical to the existing createMongoAdapter and validateMongoContract regressions.
  • P3.11 (cross-family integration test asymmetry) — 614b054d0 aligns the SQL codec() TTraits default with the Mongo mongoCodec() default (both readonly [] now), and removes the mongoCodecLookup?.encode / sqlCodec.encode!('abc-123') asymmetry in cross-family-codec.test.ts (both lookups now use the same null-handling, and encode is unconditionally available on the Codec interface).
  • ADR 204 §"Risks & mitigations" — bd1cd9ac0 adds a new section that explicitly transcribes the cleartext-leakage risk and the unbounded Promise.all dispatch risk so the trade we accepted is on record (your P2.6 concern about KMS-backed codecs is now visible in the design doc, not just on the deferred-tickets list).

Filed as follow-up tickets

  • P2.5 (cleartext leak in error envelopes) — TML-2329: "Trait-gated cleartext redaction in codec error envelopes & JSON-Schema validator". ADR 204 §"Error envelopes (unchanged)" + the new §"Risks & mitigations" both defer this; the existing it.skip at json-schema-validation.test.ts:622-659 pins the seam.
  • P2.6 (Promise.all codec dispatch unsafe for KMS-backed codecs) — TML-2330: "Codec dispatch concurrency control: rate limit + AbortSignal for KMS-backed codecs". ADR 204 §"Risks & mitigations" now records this risk.
  • P2.9b (vestigial output field in ExtractCodecTypes) — TML-2332: "Drop vestigial output mirror from ExtractCodecTypes and downstream emitter outputs". Reclassified from will_address → defer_with_ticket: dropping output cascades through the contract emitter (domain-type-generation.ts), every generated contract.d.ts fixture (10+ across packages and example apps), and the user-facing fieldOutputTypes/fieldInputTypes contract surface. Right scope is a small follow-up project, not a hygiene drive-by on this PR.
  • P3.12 (perf hygiene) — TML-2331: "Codec runtime perf hygiene: benchmark, Bun verification, sync fast-path". ADR 204 already qualifies these as future work; the sync fast-path in lowerFilter/resolveValue is sized in the ticket.

Pushing back

  • P2.9 (projects/migration-control-adapter-di/spec.md + other projects/migration-* directories) — these came in via the merge of origin/main (commits f0470b502 and d6459a839), not bundled by this PR. They're on main and out of scope here; the merge brings them along but doesn't introduce them.
  • P2.9d (projects/codec-async-single-path/spec.md + plan.md retention) — the maintainer previously asked to retain spec + plan and delete only reviews/ (which landed in 811d6c146). The "delete on close-out" is the project workflow's own internal rule — close-out is a separate PR that migrates the durable bits into docs/architecture docs/ and then deletes the project directory. Will be deleted in the close-out PR; not unilaterally deleting here.

Pending user disposition

  • P1.3 (factory shape async (v) => fn(v) vs ADR's Promise.resolve(fn(v))) — surfaced for the maintainer to decide. The two valid landings are (a) change the factory to (v) => Promise.resolve(fn(v)) to match the ADR's cost ledger (~3× per-cell allocation delta on the sync-lifted hot path, one-line surgical edit per factory), or (b) update ADR 204's §"Promise allocation in the always-await path" to honestly describe the shipped async (v) => form. Not blocking the loop; full trade-off write-up is on the maintainer's queue.

Final commit: bd1cd9ac0. CI run: https://github.com/prisma/prisma-next/actions/runs/24997514709 (pending at time of reply on the freshly-pushed ADR commit; will confirm green before merge).

@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: 5

♻️ Duplicate comments (1)
docs/architecture docs/adrs/ADR 204 - Single-Path Async Codec Runtime.md (1)

41-45: ⚠️ Potential issue | 🟠 Major

This ADR still codifies unbounded codec fan-out.

Making both encode and decode dispatch with raw Promise.all means one wide row or large param list can issue an arbitrary number of external codec calls at once. The current walk-back only helps future sync codecs; it does not mitigate KMS/secret-manager style async codecs that need backpressure or a concurrency cap.

Also applies to: 109-147, 181-190

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

In `@docs/architecture` docs/adrs/ADR 204 - Single-Path Async Codec Runtime.md
around lines 41 - 45, The ADR currently permits unbounded parallel codec calls
by using raw Promise.all in encodeParams and decodeRow (and calls to
decodeField), which can overwhelm async codecs (e.g., KMS/secret-manager);
update the design to enforce a configurable concurrency cap instead of
Promise.all: describe using a bounded concurrency executor (e.g., a p-map style
worker pool or semaphore) that schedules codec invocations from encodeParams and
decodeRow and still awaits each decodeField result single-armed; state that
AsyncIterableResult streaming should apply the same limiter to provide
backpressure and ensure rows yielded to user code remain plain values after
awaited decoding.
🧹 Nitpick comments (2)
packages/3-mongo-target/2-mongo-adapter/test/resolve-value.test.ts (1)

6-10: Consider using isRuntimeError type guard instead of local interface.

The RuntimeErrorShape interface duplicates the shape validated by the new isRuntimeError type guard from @prisma-next/framework-components/runtime. Consider importing and using isRuntimeError for type narrowing, then accessing properties directly.

♻️ Optional: Use framework type guard
+import { isRuntimeError } from '@prisma-next/framework-components/runtime';
-interface RuntimeErrorShape extends Error {
-  code?: string;
-  details?: Record<string, unknown>;
-  cause?: unknown;
-}

// In tests:
-const err = rejection as RuntimeErrorShape;
-expect(err.code).toBe('RUNTIME.ENCODE_FAILED');
+expect(isRuntimeError(rejection)).toBe(true);
+if (isRuntimeError(rejection)) {
+  expect(rejection.code).toBe('RUNTIME.ENCODE_FAILED');
+  // ...
+}
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/3-mongo-target/2-mongo-adapter/test/resolve-value.test.ts` around
lines 6 - 10, Replace the locally declared RuntimeErrorShape with the framework
type guard: import isRuntimeError from
'@prisma-next/framework-components/runtime' and use isRuntimeError(error) to
narrow the error before accessing .code, .details, or .cause in tests (e.g. in
resolve-value.test.ts). Remove the RuntimeErrorShape interface and update any
assertions or property accesses to occur only after the isRuntimeError check so
TypeScript understands the narrowed type.
docs/architecture docs/adrs/ADR 204 - Single-Path Async Codec Runtime.md (1)

109-135: Trim the runtime pseudo-code out of the ADR.

These snippets are implementation algorithms, not the decision itself, so they will drift faster than the architectural constraints around them. I’d keep the invariants here and move the step-by-step control flow to subsystem/runtime docs instead.

Based on learnings, "ADRs in prisma/prisma-next should document architectural design decisions and the key constraints/assumptions only. Do not include implementation algorithms, emitter derivation logic, or step-by-step derivation/migration rules."

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

In `@docs/architecture` docs/adrs/ADR 204 - Single-Path Async Codec Runtime.md
around lines 109 - 135, Remove the implementation pseudo-code block (the
encodeParams, decodeRow, decodeField examples and any direct call details like
registry.get, assembleRow, validateAgainst) from the ADR and replace it with a
short, declarative statement of the runtime invariants (e.g., "single
encoding/decoding path; runtime is async and dispatches codec work concurrently;
per-row concurrency semantics") leaving out step-by-step control flow and
function-level algorithms; move the detailed algorithmic examples and the exact
control flow to the runtime/subsystem documentation where functions like
encodeParams, decodeRow, and decodeField can be shown and discussed in detail.
🤖 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/ast/codec-types.ts`:
- Around line 258-259: The encode/decode factory wrappers use async arrow
functions which add unnecessary async state; replace the async wrappers in the
codec factory so they return Promise.resolve of the underlying user functions
instead — e.g. change encode: async (value) => userEncode(value) and decode:
async (wire) => userDecode(wire) to encode: (value) =>
Promise.resolve(userEncode(value)) and decode: (wire) =>
Promise.resolve(userDecode(wire)) (apply the same change for the corresponding
mongo-codec factories and any other occurrences referencing
userEncode/userDecode).

In `@packages/2-sql/5-runtime/src/codecs/encoding.ts`:
- Around line 85-99: Validate the descriptor list before launching any async
encodes: in encodeParams (or the function containing tasks[], the loop that
calls encodeParam), check that plan.meta.paramDescriptors exists and contains an
entry for every param (e.g., descriptorCount === paramCount or iterate to ensure
no undefined entries) and throw the runtimeError for
RUNTIME.MISSING_PARAM_DESCRIPTOR if the check fails, then only after that create
tasks[] and call encodeParam(paramValue, paramDescriptor, i, registry) for each
index; this prevents starting background encodes before confirming descriptor
completeness.

In `@packages/3-extensions/postgres/test/postgres.test.ts`:
- Around line 133-140: The test currently uses a local ad-hoc type CallShape
which tautologically returns PostgresClient; instead bind the assertions to the
real exported function shape by referencing the actual postgres symbol (e.g.,
use typeof postgres or declare const call: typeof postgres) and then assert on
ReturnType<typeof postgres> — replace expectTypeOf<ReturnType<CallShape>>() and
the Promise-negation with expectTypeOf<ReturnType<typeof
postgres>>().toEqualTypeOf<PostgresClient<Contract<SqlStorage>>>() and
expectTypeOf<ReturnType<typeof
postgres>>().not.toEqualTypeOf<Promise<PostgresClient<Contract<SqlStorage>>>>();
this ensures the test validates the actual postgres(...) return shape rather
than a locally defined type.

In `@packages/3-targets/6-adapters/sqlite/src/core/codecs.ts`:
- Around line 56-62: The decodeJson function currently calls Buffer.from(json,
'base64') which silently accepts malformed input; update decodeJson (and keep
encodeJson unchanged) to first verify the incoming json is a string and matches
a strict base64 pattern (allowed A–Z a–z 0–9 + / with optional = padding and
length rules, e.g. /^[A-Za-z0-9+/]+={0,2}$/ and length % 4 === 0) and if it
fails throw a TypeError with the same sqlite/blob@1 contract message; only call
Buffer.from(json, 'base64') after the validation so malformed base64 is rejected
instead of producing corrupted Uint8Array.
- Around line 79-85: The decodeJson implementation for the sqlite/datetime codec
currently constructs a Date from the input string but doesn't reject invalid ISO
strings (new Date('bad') yields an Invalid Date), so update decodeJson (in the
codec object alongside encodeJson) to first assert json is a string, then create
the Date and check its validity (e.g., const d = new Date(json); if
(Number.isNaN(d.getTime())) throw new TypeError(...)) and throw a clear
TypeError for malformed datetime strings; keep the existing error message
text/intent but make it conditional on an invalid date rather than relying on
Date to throw.

---

Duplicate comments:
In `@docs/architecture` docs/adrs/ADR 204 - Single-Path Async Codec Runtime.md:
- Around line 41-45: The ADR currently permits unbounded parallel codec calls by
using raw Promise.all in encodeParams and decodeRow (and calls to decodeField),
which can overwhelm async codecs (e.g., KMS/secret-manager); update the design
to enforce a configurable concurrency cap instead of Promise.all: describe using
a bounded concurrency executor (e.g., a p-map style worker pool or semaphore)
that schedules codec invocations from encodeParams and decodeRow and still
awaits each decodeField result single-armed; state that AsyncIterableResult
streaming should apply the same limiter to provide backpressure and ensure rows
yielded to user code remain plain values after awaited decoding.

---

Nitpick comments:
In `@docs/architecture` docs/adrs/ADR 204 - Single-Path Async Codec Runtime.md:
- Around line 109-135: Remove the implementation pseudo-code block (the
encodeParams, decodeRow, decodeField examples and any direct call details like
registry.get, assembleRow, validateAgainst) from the ADR and replace it with a
short, declarative statement of the runtime invariants (e.g., "single
encoding/decoding path; runtime is async and dispatches codec work concurrently;
per-row concurrency semantics") leaving out step-by-step control flow and
function-level algorithms; move the detailed algorithmic examples and the exact
control flow to the runtime/subsystem documentation where functions like
encodeParams, decodeRow, and decodeField can be shown and discussed in detail.

In `@packages/3-mongo-target/2-mongo-adapter/test/resolve-value.test.ts`:
- Around line 6-10: Replace the locally declared RuntimeErrorShape with the
framework type guard: import isRuntimeError from
'@prisma-next/framework-components/runtime' and use isRuntimeError(error) to
narrow the error before accessing .code, .details, or .cause in tests (e.g. in
resolve-value.test.ts). Remove the RuntimeErrorShape interface and update any
assertions or property accesses to occur only after the isRuntimeError check so
TypeScript understands the narrowed type.
🪄 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: 9695af67-35c3-4917-8185-c49070dc08e4

📥 Commits

Reviewing files that changed from the base of the PR and between baab1b9 and 5a00f9a.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (25)
  • docs/architecture docs/adrs/ADR 204 - Single-Path Async Codec Runtime.md
  • packages/1-framework/1-core/framework-components/README.md
  • packages/1-framework/1-core/framework-components/src/exports/runtime.ts
  • packages/1-framework/1-core/framework-components/src/runtime-error.ts
  • packages/1-framework/3-tooling/emitter/package.json
  • packages/2-mongo-family/1-foundation/mongo-codec/README.md
  • packages/2-mongo-family/1-foundation/mongo-codec/src/codecs.ts
  • packages/2-mongo-family/1-foundation/mongo-codec/test/codecs.test-d.ts
  • packages/2-mongo-family/1-foundation/mongo-codec/test/codecs.test.ts
  • packages/2-sql/1-core/contract/test/validate.test.ts
  • packages/2-sql/4-lanes/relational-core/src/ast/codec-types.ts
  • packages/2-sql/5-runtime/package.json
  • packages/2-sql/5-runtime/src/codecs/decoding.ts
  • packages/2-sql/5-runtime/src/codecs/encoding.ts
  • packages/2-sql/5-runtime/test/codec-async.test.ts
  • packages/2-sql/5-runtime/test/json-schema-validation.test.ts
  • packages/2-sql/5-runtime/test/utils.ts
  • packages/3-extensions/postgres/test/postgres.test.ts
  • packages/3-extensions/sql-orm-client/test/collection-dispatch.test.ts
  • packages/3-extensions/sql-orm-client/test/model-accessor.test.ts
  • packages/3-mongo-target/2-mongo-adapter/src/core/codecs.ts
  • packages/3-mongo-target/2-mongo-adapter/src/resolve-value.ts
  • packages/3-mongo-target/2-mongo-adapter/test/resolve-value.test.ts
  • packages/3-targets/6-adapters/sqlite/src/core/codecs.ts
  • test/integration/test/cross-package/cross-family-codec.test.ts
✅ Files skipped from review due to trivial changes (5)
  • packages/1-framework/3-tooling/emitter/package.json
  • packages/2-sql/5-runtime/package.json
  • packages/3-extensions/sql-orm-client/test/model-accessor.test.ts
  • packages/1-framework/1-core/framework-components/README.md
  • packages/3-extensions/sql-orm-client/test/collection-dispatch.test.ts
🚧 Files skipped from review as they are similar to previous changes (4)
  • test/integration/test/cross-package/cross-family-codec.test.ts
  • packages/2-mongo-family/1-foundation/mongo-codec/test/codecs.test.ts
  • packages/2-mongo-family/1-foundation/mongo-codec/src/codecs.ts
  • packages/2-sql/5-runtime/test/json-schema-validation.test.ts

Comment on lines +85 to 99
const tasks: Promise<unknown>[] = new Array(paramCount);
for (let i = 0; i < paramCount; i++) {
const paramValue = plan.params[i];
const paramDescriptor = plan.meta.paramDescriptors[i];

if (paramDescriptor) {
encoded.push(encodeParam(paramValue, paramDescriptor, i, registry));
} else {
encoded.push(paramValue);
if (!paramDescriptor) {
throw runtimeError(
'RUNTIME.MISSING_PARAM_DESCRIPTOR',
`Missing paramDescriptor for parameter at index ${i} (plan has ${paramCount} params, ${descriptorCount} descriptors). The planner must emit one descriptor per param; this is a contract violation.`,
{ paramIndex: i, paramCount, descriptorCount },
);
}

tasks[i] = encodeParam(paramValue, paramDescriptor, i, registry);
}

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 descriptor completeness before starting any encode tasks.

This loop starts earlier encodeParam(...) calls before it knows the descriptor list is complete. If a later index hits the missing-descriptor branch, encodeParams() rejects immediately while the already-started encodes keep running in the background; any later rejection from those promises is never observed.

Suggested fix
   const descriptorCount = plan.meta.paramDescriptors.length;
   const paramCount = plan.params.length;

-  const tasks: Promise<unknown>[] = new Array(paramCount);
   for (let i = 0; i < paramCount; i++) {
-    const paramValue = plan.params[i];
     const paramDescriptor = plan.meta.paramDescriptors[i];

     if (!paramDescriptor) {
       throw runtimeError(
         'RUNTIME.MISSING_PARAM_DESCRIPTOR',
@@
         { paramIndex: i, paramCount, descriptorCount },
       );
     }
+  }
+
+  const tasks: Promise<unknown>[] = new Array(paramCount);
+  for (let i = 0; i < paramCount; i++) {
+    const paramValue = plan.params[i];
+    const paramDescriptor = plan.meta.paramDescriptors[i]!;
 
     tasks[i] = encodeParam(paramValue, paramDescriptor, i, registry);
   }
🤖 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 85 - 99,
Validate the descriptor list before launching any async encodes: in encodeParams
(or the function containing tasks[], the loop that calls encodeParam), check
that plan.meta.paramDescriptors exists and contains an entry for every param
(e.g., descriptorCount === paramCount or iterate to ensure no undefined entries)
and throw the runtimeError for RUNTIME.MISSING_PARAM_DESCRIPTOR if the check
fails, then only after that create tasks[] and call encodeParam(paramValue,
paramDescriptor, i, registry) for each index; this prevents starting background
encodes before confirming descriptor completeness.

Comment on lines +133 to +140
type CallShape = (options: {
contract: Contract<SqlStorage>;
url: string;
}) => PostgresClient<Contract<SqlStorage>>;
expectTypeOf<ReturnType<CallShape>>().toEqualTypeOf<PostgresClient<Contract<SqlStorage>>>();
expectTypeOf<ReturnType<CallShape>>().not.toEqualTypeOf<
Promise<PostgresClient<Contract<SqlStorage>>>
>();

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

Type-level regression is currently tautological (doesn’t validate postgres).

Line 133 defines a local function type that already returns PostgresClient, so the expectTypeOf assertions will pass even if postgres later returns a Promise. Please bind the assertion to the actual postgres(...) call shape.

Suggested fix
-    type CallShape = (options: {
-      contract: Contract<SqlStorage>;
-      url: string;
-    }) => PostgresClient<Contract<SqlStorage>>;
-    expectTypeOf<ReturnType<CallShape>>().toEqualTypeOf<PostgresClient<Contract<SqlStorage>>>();
-    expectTypeOf<ReturnType<CallShape>>().not.toEqualTypeOf<
+    const typedClient: PostgresClient<Contract<SqlStorage>> = postgres({
+      contract,
+      url: 'postgres://localhost:5432/db',
+    });
+    expectTypeOf<typeof typedClient>().toEqualTypeOf<PostgresClient<Contract<SqlStorage>>>();
+    expectTypeOf<typeof typedClient>().not.toEqualTypeOf<
       Promise<PostgresClient<Contract<SqlStorage>>>
     >();

As per coding guidelines, "Avoid tautological tests that only restate fixture input - tests must verify behavior, not mirror object shape passed by the test itself."

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

In `@packages/3-extensions/postgres/test/postgres.test.ts` around lines 133 - 140,
The test currently uses a local ad-hoc type CallShape which tautologically
returns PostgresClient; instead bind the assertions to the real exported
function shape by referencing the actual postgres symbol (e.g., use typeof
postgres or declare const call: typeof postgres) and then assert on
ReturnType<typeof postgres> — replace expectTypeOf<ReturnType<CallShape>>() and
the Promise-negation with expectTypeOf<ReturnType<typeof
postgres>>().toEqualTypeOf<PostgresClient<Contract<SqlStorage>>>() and
expectTypeOf<ReturnType<typeof
postgres>>().not.toEqualTypeOf<Promise<PostgresClient<Contract<SqlStorage>>>>();
this ensures the test validates the actual postgres(...) return shape rather
than a locally defined type.

Comment on lines +56 to +62
encodeJson: (value: Uint8Array): string => Buffer.from(value).toString('base64'),
decodeJson: (json: JsonValue): Uint8Array => {
if (typeof json !== 'string') {
throw new TypeError('sqlite/blob@1 contract value must be a base64 string');
}
return new Uint8Array(Buffer.from(json, 'base64'));
},

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 Node.js, does Buffer.from(input, 'base64') throw on malformed base64, or can it decode invalid input silently?

💡 Result:

In Node.js, Buffer.from(input, 'base64') does not throw on malformed base64 input. It silently decodes invalid input by ignoring non-base64 characters (like '?') and whitespace, producing a Buffer from the valid portions. This is the documented and intentional behavior for performance and compatibility with real-world base64 variants (e.g., missing padding, whitespace). For strict validation, use a separate base64 validator library before decoding. Example: Buffer.from('ai?73', 'base64').toString('base64') === 'ai73=' // Ignores '?' Official docs confirm whitespace is ignored, and GitHub issues/StackOverflow examples show invalid chars are skipped without error.

Citations:


Validate base64 input before decoding to prevent silent data corruption.

Buffer.from(json, 'base64') silently accepts malformed base64 and ignores invalid characters, which can result in incorrect decoded data without throwing an error.

Proposed fix
   decodeJson: (json: JsonValue): Uint8Array => {
     if (typeof json !== 'string') {
       throw new TypeError('sqlite/blob@1 contract value must be a base64 string');
     }
+    const base64 = json.trim();
+    const base64Pattern =
+      /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
+    if (!base64Pattern.test(base64)) {
+      throw new TypeError('sqlite/blob@1 contract value must be valid base64');
+    }
-    return new Uint8Array(Buffer.from(json, 'base64'));
+    return new Uint8Array(Buffer.from(base64, 'base64'));
   },
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/3-targets/6-adapters/sqlite/src/core/codecs.ts` around lines 56 -
62, The decodeJson function currently calls Buffer.from(json, 'base64') which
silently accepts malformed input; update decodeJson (and keep encodeJson
unchanged) to first verify the incoming json is a string and matches a strict
base64 pattern (allowed A–Z a–z 0–9 + / with optional = padding and length
rules, e.g. /^[A-Za-z0-9+/]+={0,2}$/ and length % 4 === 0) and if it fails throw
a TypeError with the same sqlite/blob@1 contract message; only call
Buffer.from(json, 'base64') after the validation so malformed base64 is rejected
instead of producing corrupted Uint8Array.

Comment on lines +79 to +85
encodeJson: (value: Date): string => value.toISOString(),
decodeJson: (json: JsonValue): Date => {
if (typeof json !== 'string') {
throw new TypeError('sqlite/datetime@1 contract value must be an ISO-8601 string');
}
return new Date(json);
},

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

Reject invalid datetime strings in decodeJson.

new Date(json) does not throw for invalid input; it returns Invalid Date. This currently accepts malformed contract values.

Proposed fix
   decodeJson: (json: JsonValue): Date => {
     if (typeof json !== 'string') {
       throw new TypeError('sqlite/datetime@1 contract value must be an ISO-8601 string');
     }
-    return new Date(json);
+    const parsed = new Date(json);
+    if (Number.isNaN(parsed.getTime())) {
+      throw new TypeError('sqlite/datetime@1 contract value must be a valid ISO-8601 string');
+    }
+    return parsed;
   },
In JavaScript, does new Date('invalid') throw, or does it return an Invalid Date object (NaN time value)?
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/3-targets/6-adapters/sqlite/src/core/codecs.ts` around lines 79 -
85, The decodeJson implementation for the sqlite/datetime codec currently
constructs a Date from the input string but doesn't reject invalid ISO strings
(new Date('bad') yields an Invalid Date), so update decodeJson (in the codec
object alongside encodeJson) to first assert json is a string, then create the
Date and check its validity (e.g., const d = new Date(json); if
(Number.isNaN(d.getTime())) throw new TypeError(...)) and throw a clear
TypeError for malformed datetime strings; keep the existing error message
text/intent but make it conditional on an invalid date rather than relying on
Date to throw.

wmadden added 3 commits April 27, 2026 15:26
…tch ADR 204 cost ledger

P1.3 from jkomyno's review of #379. The factories were using `async (v) => fn(v)`
which allocates 2 promises per cell on the sync-lifted hot path. Switching to
`(v) => Promise.resolve(fn(v))` allocates 1 — matching the ledger ADR 204
documents. No observable behaviour change; user-authored async functions
unwrap identically (a Promise of a Promise flattens).

Both factories changed in lockstep:
- packages/2-sql/4-lanes/relational-core/src/ast/codec-types.ts
- packages/2-mongo-family/1-foundation/mongo-codec/src/codecs.ts
The bare `(v) => Promise.resolve(userEncode(v))` shape from the previous
commit broke a real semantic the prior `async (v) => userEncode(v)` shape
provided: synchronously-thrown errors inside user-authored encode/decode
bodies were converted to rejected promises by the async wrapper. With bare
Promise.resolve, sync throws escape *before* Promise.resolve is called and
bubble up as synchronous exceptions — violating the public Codec interface
contract `encode(v): Promise<TWire>`.

Surfaced by `@prisma-next/extension-pgvector` test failures on CI for the
preceding commit `84daad86d`: pgvectors `encode`/`decode` throw synchronously
on invalid input, and direct callers using `await expect(...).rejects.toThrow(...)`
no longer matched.

Fix: wrap the lift in `try { Promise.resolve(fn(v)) } catch { Promise.reject(e) }`.
Preserves both:
- The ADR 204 cost ledger (one Promise per cell on the sync-lifted hot path,
  identical allocation count to the bare-resolve form).
- The boundary contract (encode/decode always return a Promise, never throw
  synchronously, regardless of how the user authored the body).

Same change in lockstep across:
- packages/2-sql/4-lanes/relational-core/src/ast/codec-types.ts
- packages/2-mongo-family/1-foundation/mongo-codec/src/codecs.ts
Closes the coverage gap introduced by P2.8 (commit 2d639ce) which added
encodeJson/decodeJson to mongoDateCodec but left the decodeJson error branch
(non-string input throwing "expected ISO date string") uncovered.

Brings packages/3-mongo-target/2-mongo-adapter/src/core/codecs.ts from
87.10/77.78/88.24% (statements/branches/functions) to 100/100/100, unblocking
the Coverage CI check on this PR.
@wmadden

wmadden commented Apr 27, 2026

Copy link
Copy Markdown
Contributor Author

@jkomyno — P1.3 landed in dbfa9eb56 (with follow-up 27aac5249 for a coverage gap surfaced by the change): both factories now use Promise.resolve(...) to match ADR 204's cost ledger (one promise per cell on the sync-lifted hot path instead of two).

A subtle gotcha worth noting for posterity: bare (v) => Promise.resolve(fn(v)) lets sync throws inside user-authored encode/decode bodies escape before Promise.resolve is called, which violates the public Codec.encode(v): Promise<TWire> interface contract (the prior async (v) => fn(v) shape converted those throws into rejected promises uniformly). The shipped lift is try { return Promise.resolve(fn(v)); } catch (e) { return Promise.reject(e); } — same Promise allocation count as the bare form on both paths, but always returns a Promise at the boundary. Surfaced by @prisma-next/extension-pgvector's codec tests on the first pass; the follow-up commit fixes the regression.

CI green: https://github.com/prisma/prisma-next/actions/runs/24999164036

@wmadden
wmadden merged commit 88613fa into main Apr 27, 2026
15 checks passed
@wmadden
wmadden deleted the feat/codec-async-single-path branch April 27, 2026 15:35
wmadden added a commit that referenced this pull request Apr 27, 2026
…rename

Conflict-resolution follow-up to rebase onto origin/main: PR #379
(`feat(codec): single-path async codec runtime`) added
`test/codec-async.test.ts` referencing `ExecutionPlan` from
`@prisma-next/contract/types`, which TML-2242 removed when migrating
the SQL family to `SqlExecutionPlan` from `@prisma-next/sql-relational-
core/plan`. Update the test to import `SqlExecutionPlan` so it lines up
with the post-rebase types.

Pure conflict-resolution; no behavior change.
wmadden added a commit that referenced this pull request Apr 28, 2026
…rename

Conflict-resolution follow-up to rebase onto origin/main: PR #379
(`feat(codec): single-path async codec runtime`) added
`test/codec-async.test.ts` referencing `ExecutionPlan` from
`@prisma-next/contract/types`, which TML-2242 removed when migrating
the SQL family to `SqlExecutionPlan` from `@prisma-next/sql-relational-
core/plan`. Update the test to import `SqlExecutionPlan` so it lines up
with the post-rebase types.

Pure conflict-resolution; no behavior change.
cursor Bot pushed a commit that referenced this pull request May 1, 2026
`docs/reference/framework-gaps.md` is a transient audit document — it
captures one team's snapshot of post-#379 framework friction at a moment
in time and disappears once the gaps close. ADRs are durable. ADR 207
referenced `framework-gaps.md` in four places (Status, Why, Non-goals,
References); each is replaced with self-contained narrative or direct
TML-ticket links so the ADR stands alone.

Status. The decode-side gap is described in narrative ('the decode-side
column-identity gap') and the concurrency-cap follow-up is linked to
TML-2330 directly.

Why -> decode-side column identity. The framework-gaps anchor is replaced
with the actual problem statement inline: when the same JS data type
backs multiple columns, the decoder cannot tell which column produced a
given wire value, so any inference from the value alone misattributes
cells.

Non-goals -> no concurrency cap. The framework-gaps anchor is dropped;
TML-2330 already tracks the work.

References. The three framework-gaps bullets are dropped; TML-2330 and
TML-2359 are kept as durable tracking links.

The ADR now references only other ADRs, Linear tickets, WHATWG, and
in-source file paths in the implementation pointer paragraph.
cursor Bot pushed a commit that referenced this pull request May 1, 2026
`docs/reference/framework-gaps.md` is a transient audit document — it
captures one team's snapshot of post-#379 framework friction at a moment
in time and disappears once the gaps close. ADRs are durable. ADR 207
referenced `framework-gaps.md` in four places (Status, Why, Non-goals,
References); each is replaced with self-contained narrative or direct
TML-ticket links so the ADR stands alone.

Status. The decode-side gap is described in narrative ('the decode-side
column-identity gap') and the concurrency-cap follow-up is linked to
TML-2330 directly.

Why -> decode-side column identity. The framework-gaps anchor is replaced
with the actual problem statement inline: when the same JS data type
backs multiple columns, the decoder cannot tell which column produced a
given wire value, so any inference from the value alone misattributes
cells.

Non-goals -> no concurrency cap. The framework-gaps anchor is dropped;
TML-2330 already tracks the work.

References. The three framework-gaps bullets are dropped; TML-2330 and
TML-2359 are kept as durable tracking links.

The ADR now references only other ADRs, Linear tickets, WHATWG, and
in-source file paths in the implementation pointer paragraph.
cursor Bot pushed a commit that referenced this pull request May 1, 2026
`docs/reference/framework-gaps.md` is a transient audit document — it
captures one team's snapshot of post-#379 framework friction at a moment
in time and disappears once the gaps close. ADRs are durable. ADR 207
referenced `framework-gaps.md` in four places (Status, Why, Non-goals,
References); each is replaced with self-contained narrative or direct
TML-ticket links so the ADR stands alone.

Status. The decode-side gap is described in narrative ('the decode-side
column-identity gap') and the concurrency-cap follow-up is linked to
TML-2330 directly.

Why -> decode-side column identity. The framework-gaps anchor is replaced
with the actual problem statement inline: when the same JS data type
backs multiple columns, the decoder cannot tell which column produced a
given wire value, so any inference from the value alone misattributes
cells.

Non-goals -> no concurrency cap. The framework-gaps anchor is dropped;
TML-2330 already tracks the work.

References. The three framework-gaps bullets are dropped; TML-2330 and
TML-2359 are kept as durable tracking links.

The ADR now references only other ADRs, Linear tickets, WHATWG, and
in-source file paths in the implementation pointer paragraph.
wmadden pushed a commit that referenced this pull request May 1, 2026
`docs/reference/framework-gaps.md` is a transient audit document — it
captures one team's snapshot of post-#379 framework friction at a moment
in time and disappears once the gaps close. ADRs are durable. ADR 207
referenced `framework-gaps.md` in four places (Status, Why, Non-goals,
References); each is replaced with self-contained narrative or direct
TML-ticket links so the ADR stands alone.

Status. The decode-side gap is described in narrative ('the decode-side
column-identity gap') and the concurrency-cap follow-up is linked to
TML-2330 directly.

Why -> decode-side column identity. The framework-gaps anchor is replaced
with the actual problem statement inline: when the same JS data type
backs multiple columns, the decoder cannot tell which column produced a
given wire value, so any inference from the value alone misattributes
cells.

Non-goals -> no concurrency cap. The framework-gaps anchor is dropped;
TML-2330 already tracks the work.

References. The three framework-gaps bullets are dropped; TML-2330 and
TML-2359 are kept as durable tracking links.

The ADR now references only other ADRs, Linear tickets, WHATWG, and
in-source file paths in the implementation pointer paragraph.
wmadden added a commit that referenced this pull request May 4, 2026
closes
https://linear.app/prisma-company/issue/TML-2304/pn-support-async-codecs

# single-path async codec runtime

## Grounding example

A user wants a `secret` column that's encrypted before insert and
decrypted on read using a real async crypto API. They author a codec:

```ts
const secretCodec = codec({
  id: 'app/secret@1',
  encode: async (plain: string) => aesGcmEncrypt(plain, key),
  decode: async (cipher: Uint8Array) => aesGcmDecrypt(cipher, key),
  encodeJson: (value) => /* sync, build-time */ ...,
  decodeJson: (json) => /* sync, build-time */ ...,
});
```

They register it on a column. Their application code stays ordinary:

```ts
await users.create({ secret: 'hello' });
const row = await users.first({ where: { id } });
row.secret; // string — plain T, no Promise leaks into user code
```

This wasn't possible before: `Codec.encode` and `Codec.decode` were
synchronous, and the runtime called them in tight `for` loops.

## Decision

Make `Codec.encode` and `Codec.decode` always return `Promise<T>` at the
public boundary. The runtime always awaits them and dispatches per-row
codec calls concurrently with `Promise.all`. Codec authors keep writing
whichever shape is natural — sync or async — and the factory (`codec()`
/ `mongoCodec()`) lifts both uniformly. Build-time methods
(`encodeJson`, `decodeJson`, optional `renderOutputType`) stay
synchronous because they don't run per-row.

The canonical decision record is [ADR 204 — Single-Path Async Codec
Runtime](docs/architecture%20docs/adrs/ADR%20204%20-%20Single-Path%20Async%20Codec%20Runtime.md).

## Narrative

A codec author's natural unit of work is "encode this one value" or
"decode this one cell". When that work is synchronous (e.g. a JSON
serializer) authoring is simple; when it's asynchronous (crypto,
network-backed redaction policy, contract-side computed defaults that
consult IO) the author needs to `await` inside `encode` / `decode`
without worrying whether the runtime knows what to do with the result.

Two shapes were on the table:

- **Per-codec sync/async marker**: every codec carries a `runtime:
'sync' | 'async'` discriminator on the public surface; every call site
branches on it.
- **Always-async at the public boundary**: every `encode` / `decode`
returns `Promise<T>`; the runtime always awaits.

We chose the second. The discriminator pushes complexity into every
consumer of `Codec`: the runtime's per-row dispatcher, the SQL DSL's
encode-once-per-statement path, the Mongo encode lowering, the ORM's
row-yielding generator, and downstream tests. Each call site has to
handle both shapes, usually via conditional return types and `instanceof
Promise` guards. Always-async pushes the cost into one place — the
factory, which lifts a sync author function to `async (x) => fn(x)`
once. The runtime then has a single arm (`await codec.encode(...)`,
`await codec.decode(...)`) and uses `Promise.all` to dispatch per-row
work concurrently. From the user's point of view nothing changes: rows
yielded by collections still hold plain `T`, and write inputs still
accept plain `T`.

The `Codec` interface stays at four generics: `Codec<Id, TTraits, TWire,
TInput>`. An earlier draft introduced a fifth `TOutput = TInput`
parameter to express the asymmetric `TInput ≠ TOutput` case, but every
consumer used the symmetric form, so the parameter was collapsed back to
four generics in commit `be04ceaeb`. If a real asymmetric case lands
later it can be reintroduced as an additive widening.

The Mongo family aligns with the same shape. `MongoCodec` is
structurally identical to the framework `BaseCodec` (same four generics,
same order, same defaults), so a single `codec({...})` value works
against both registries. `MongoAdapter.lower(plan)` becomes
`Promise<AnyMongoWireCommand>` because lowering walks codecs as it
produces the wire shape.

## Behavior changes & evidence

| Change | Before | After | Evidence |
|---|---|---|---|
| `Codec.encode` / `Codec.decode` | sync | `Promise<T>` at the public
boundary | [framework-components/src/codec-types.ts
(L34–L56)](packages/1-framework/1-core/framework-components/src/codec-types.ts);
[type
tests](packages/1-framework/1-core/framework-components/test/codec-types.types.test-d.ts)
|
| `codec()` / `mongoCodec()` factory | sync-only authoring | accepts
sync, async, or mixed; uniformly lifts to Promise-returning |
[relational-core/src/ast/codec-types.ts
(L215–L263)](packages/2-sql/4-lanes/relational-core/src/ast/codec-types.ts);
[mongo-codec/src/codecs.ts
(L55–L93)](packages/2-mongo-family/1-foundation/mongo-codec/src/codecs.ts)
|
| `Codec` generic count | 4 (`Id, TTraits, TWire, TJs`) | 4 (`Id,
TTraits, TWire, TInput`) — `TJs` renamed to `TInput`; same arity |
[framework-components/src/codec-types.ts
(L34–L39)](packages/1-framework/1-core/framework-components/src/codec-types.ts);
`MongoCodec` aligned in [mongo-codec/src/codecs.ts
(L17–L22)](packages/2-mongo-family/1-foundation/mongo-codec/src/codecs.ts)
|
| SQL runtime dispatch | sync `for`-loop | always-await + `Promise.all`
per encode/decode site | [encoding.ts
(L74–L103)](packages/2-sql/5-runtime/src/codecs/encoding.ts),
[decoding.ts
(L206–L273)](packages/2-sql/5-runtime/src/codecs/decoding.ts);
[codec-async.test.ts](packages/2-sql/5-runtime/test/codec-async.test.ts)
|
| Error envelopes on encode/decode failure | raw thrown errors |
`RUNTIME.ENCODE_FAILED` / `RUNTIME.DECODE_FAILED` with `cause` chaining;
existing `RUNTIME.JSON_SCHEMA_VALIDATION_FAILED` envelope re-raised
verbatim when matched | [wrapEncodeFailure
(L23–L38)](packages/2-sql/5-runtime/src/codecs/encoding.ts),
[wrapDecodeFailure
(L94–L114)](packages/2-sql/5-runtime/src/codecs/decoding.ts); envelope
tests in [codec-async.test.ts
(L145–L580)](packages/2-sql/5-runtime/test/codec-async.test.ts) |
| `MongoAdapter.lower(plan)` | sync | `Promise<AnyMongoWireCommand>` so
adapters can run async codec encodes before producing the wire shape |
[mongo-lowering/src/adapter-types.ts
(L1–L6)](packages/2-mongo-family/6-transport/mongo-lowering/src/adapter-types.ts);
[adapter-mongo
tests](packages/3-mongo-target/2-mongo-adapter/test/mongo-adapter.test.ts)
|
| `resolveValue` (Mongo encode-side) | not the dispatch concentration
site | `await codec.encode(...)` per `MongoParamRef` leaf; `Promise.all`
over array elements and object children; encode failures wrapped in
`RUNTIME.ENCODE_FAILED` envelope | [resolve-value.ts
(L20–L56)](packages/3-mongo-target/2-mongo-adapter/src/resolve-value.ts);
[resolve-value.test.ts
(L87–L183)](packages/3-mongo-target/2-mongo-adapter/test/resolve-value.test.ts)
|
| Cross-family `BaseCodec` seam | divergent shapes between SQL `Codec`
and Mongo `MongoCodec` | both align on `BaseCodec` with
structurally-identical four-generic shape |
[cross-family-codec.test.ts](test/integration/test/cross-package/cross-family-codec.test.ts);
[mongo-codec/test/codecs.test-d.ts
(L62–L82)](packages/2-mongo-family/1-foundation/mongo-codec/test/codecs.test-d.ts)
|
| Real AES-GCM crypto round-trip (security probe) | only synthetic
`Promise.resolve(...)` codecs in tests | seeded-secret-codec fixture:
real AES-GCM with deterministic test key, end-to-end through
`encodeParams` and `decodeRow`, asserts no Promise leaks into yielded
rows |
[seeded-secret-codec.ts](packages/2-sql/5-runtime/test/seeded-secret-codec.ts);
[codec-async.test.ts
(L618–L703)](packages/2-sql/5-runtime/test/codec-async.test.ts) |

## What stays the same

- **ORM read / write surfaces yield and accept plain `T`.** Rows from
`.first()`, `for await ... of c.all()`, and `.firstOrThrow()` hold plain
decoded values; write inputs (`CreateInput`, `MutationUpdateInput`,
`UniqueConstraintCriterion`, `ShorthandWhereFilter`) accept plain `T`.
Pinned by 21 type tests in
[sql-orm-client/test/codec-async.types.test-d.ts](packages/3-extensions/sql-orm-client/test/codec-async.types.test-d.ts)
and live-Postgres integration in
[test/integration/codec-async.test.ts](packages/3-extensions/sql-orm-client/test/integration/codec-async.test.ts).
- **Build-time stays synchronous.** `validateContract`,
`validateMongoContract`, `postgres({...})`, and `createMongoAdapter()`
all return synchronously — regression-locked at the type and runtime
levels in [contract validate.test.ts
(L882–L893)](packages/2-sql/1-core/contract/test/validate.test.ts),
[postgres.test.ts
(L128–L141)](packages/3-extensions/postgres/test/postgres.test.ts),
[mongo-contract validate.test.ts
(L662–L681)](packages/2-mongo-family/1-foundation/mongo-contract/test/validate.test.ts),
and [mongo-adapter.test.ts
(L460–L475)](packages/3-mongo-target/2-mongo-adapter/test/mongo-adapter.test.ts).
- **Build-time codec methods stay synchronous** — `encodeJson(value):
JsonValue`, `decodeJson(json): TInput`, `renderOutputType?(...) : string
| undefined`. They don't run per-row.
- **Existing error-envelope shapes are unchanged.**
`RUNTIME.JSON_SCHEMA_VALIDATION_FAILED` is preserved verbatim. The new
`RUNTIME.ENCODE_FAILED` / `RUNTIME.DECODE_FAILED` envelopes follow the
existing structured-details + `cause` pattern.

## Downstream changes

Observable to anyone authoring **adapters** or **codec implementations**
outside this PR. End-users of the ORM / SQL DSL surfaces don't have to
do anything.

- **Codec authors.** `Codec.encode` / `Codec.decode` are now
Promise-returning at the type level. The factory lifts both sync and
async author functions; you don't have to write `async` if your codec is
synchronous, but you do have to migrate any direct implementation of the
`Codec` interface (rare). Recipe: `decode: (wire) => wire` → `decode:
async (wire) => wire`; or use the factory.
- **Codec authors with non-`JsonValue` `TInput`.** `encodeJson` /
`decodeJson` are now required when `TInput` is not assignable to
`JsonValue` (e.g. `Date`, `Uint8Array`, `bigint`). Sync identity
defaults still apply when `TInput extends JsonValue`. Recipe: implement
`encodeJson` / `decodeJson` returning a JSON-safe representation (ISO
string for `Date`, base64 for `Uint8Array`, decimal string for `bigint`,
etc.).
- **Mongo adapter authors.** `MongoAdapter.lower(plan)` now returns
`Promise<AnyMongoWireCommand>` instead of `AnyMongoWireCommand`. Recipe:
change `lower(plan) { ... }` → `async lower(plan) { ... }`. The runtime
and runner already `await` the result.
- **Adapter authors who call `codec.encode(...)` / `codec.decode(...)`
directly.** Both calls now return Promises. Recipe: prefix call sites
with `await`; convert any direct `expect(...).toThrow(...)` assertions
to `await expect(...).rejects.toThrow(...)`.

## Compatibility / migration / risk

- **`Promise.all` failure semantics are partial fail-fast.** The first
rejected dispatch surfaces as the error envelope; remaining dispatched
bodies still run to completion (they cannot be cancelled in standard
`Promise.all`) but their outputs are discarded. From the user's point of
view this matches the prior `for`-loop's "throw on first failure"
behavior. Concurrency control for KMS-backed codecs (rate limiting /
`AbortSignal`) is tracked separately under
[TML-2330](https://linear.app/prisma-company/issue/TML-2330).
- **Allocation pressure.** Every codec dispatch allocates a Promise; for
a query returning N rows × M codec'd cells, that's N × M allocations.
The walk-back path below is preserved precisely to keep this cost
recoverable without breaking the public surface. Sync fast-path is
tracked under
[TML-2331](https://linear.app/prisma-company/issue/TML-2331).
- **Error-envelope cleartext leaks.** The expanded encrypting-codec
surface means error envelopes can leak plaintext via `error.message` /
`details.errors`. Trait-gated redaction is tracked under
[TML-2329](https://linear.app/prisma-company/issue/TML-2329); ADR 204
§"Risks & mitigations" defers the spelling.
- **Walk-back stays open.** Because no sync/async discriminator was
introduced on the public surface, a future synchronous fast path can be
added additively as `codecSync()`. ADR 204 transcribes the seven
walk-back constraints verified absent across this project: no per-codec
async marker; no `codecSync` / `codecAsync` variants today; no `isSync*`
predicates; no conditional return types on Promise-returning methods; no
`TRuntime` generic on `Codec` or `MongoCodec`; no async-dependent
author-surface docs; no async-dependent build-time guarantees.
- **Test fixtures updated mechanically.** Inline `Codec`-shaped fixtures
across `framework-components`, `sql-contract-ts`, `cli`,
`integration-tests`, `pgvector`, `adapter-postgres`, and
`adapter-sqlite` were updated by recipe: `decode: (wire) => wire` →
`decode: async (wire) => wire`; add `encode: async (value) => value`
when missing; prefix call sites with `await`; convert
`expect(...).toThrow(...)` to `await expect(...).rejects.toThrow(...)`.
No production-source escape hatches were needed; the factory's lift
normalizes any combination of sync and async author functions.
- **No backwards-compatibility shims.** Per `AGENTS.md` § Golden Rules.
The legacy `MongoCodecJsType<T>` extractor was replaced by
`MongoCodecInput<T>` (mirroring SQL's `CodecInput<T>`) without an alias.

## Alternatives considered

- **Per-codec `runtime: 'async'` marker.** Rejected. The cost lives in
the wrong place: every call site (runtime dispatcher, SQL DSL, Mongo
lowering, ORM generator, tests) has to handle both shapes via
conditional return types and runtime branching. The seam is wrong:
sync-vs-async cuts across query-time methods rather than aligning with
the build-time-vs-query-time boundary the codec interface already has.
Cross-family portability is harder: every codec definition has to be
reshaped per family. And there is no clean walk-back path — once a
marker is on the public surface, removing it is breaking.
- **Defer the change entirely.** Rejected. Async codecs unblock real
work already on the roadmap: column-level encryption, redaction policy
that consults external sources, and contract-side computed defaults that
may need IO. Deferring forces consumers to wrap codecs around the
runtime instead of inside it.

## Non-goals / intentionally out of scope

- **Synchronous fast path.** A future `codecSync()` opt-in is preserved
as an additive non-breaking change; not landed in this project. Tracked
under [TML-2331](https://linear.app/prisma-company/issue/TML-2331).
- **Mongo decode-side codec dispatch.** Mongo doesn't decode rows today;
ADR 204 records the future pattern (mirror SQL's `decodeRow`). Tracked
under [TML-2324](https://linear.app/prisma-company/issue/TML-2324).
- **Include-aggregate child-codec dispatch.** Orthogonal ORM feature;
deferred.
- **Redaction-trigger spelling.** Orthogonal redaction-policy work;
tracked under
[TML-2329](https://linear.app/prisma-company/issue/TML-2329).
- **Concurrency control for KMS-backed codecs.** No rate limiting or
`AbortSignal` plumbing today; tracked under
[TML-2330](https://linear.app/prisma-company/issue/TML-2330).


<!-- This is an auto-generated comment: release notes by coderabbit.ai
-->
## Summary by CodeRabbit

* **New Features**
* Codec query-time encode/decode are now Promise-based and always
awaited by the runtime; build-time helpers remain synchronous.
* Async lowering/encoding for SQL and Mongo paths so parameter encoding
and pipeline lowering run concurrently.

* **Bug Fixes**
* Prevents Promise leakage into driver/consumer outputs; async codec
failures are wrapped with structured runtime error envelopes.

* **Documentation**
* ADRs and READMEs updated to describe the async codec runtime contract
and usage.

* **Tests**
* Expanded suites and type-tests ensuring async codec behavior and
cross-family parity.
<!-- end of auto-generated comment: release notes by coderabbit.ai -->

---------

Co-authored-by: jkomyno <[email protected]>
wmadden added a commit that referenced this pull request May 4, 2026
…rename

Conflict-resolution follow-up to rebase onto origin/main: PR #379
(`feat(codec): single-path async codec runtime`) added
`test/codec-async.test.ts` referencing `ExecutionPlan` from
`@prisma-next/contract/types`, which TML-2242 removed when migrating
the SQL family to `SqlExecutionPlan` from `@prisma-next/sql-relational-
core/plan`. Update the test to import `SqlExecutionPlan` so it lines up
with the post-rebase types.

Pure conflict-resolution; no behavior change.
wmadden pushed a commit that referenced this pull request May 4, 2026
`docs/reference/framework-gaps.md` is a transient audit document — it
captures one team's snapshot of post-#379 framework friction at a moment
in time and disappears once the gaps close. ADRs are durable. ADR 207
referenced `framework-gaps.md` in four places (Status, Why, Non-goals,
References); each is replaced with self-contained narrative or direct
TML-ticket links so the ADR stands alone.

Status. The decode-side gap is described in narrative ('the decode-side
column-identity gap') and the concurrency-cap follow-up is linked to
TML-2330 directly.

Why -> decode-side column identity. The framework-gaps anchor is replaced
with the actual problem statement inline: when the same JS data type
backs multiple columns, the decoder cannot tell which column produced a
given wire value, so any inference from the value alone misattributes
cells.

Non-goals -> no concurrency cap. The framework-gaps anchor is dropped;
TML-2330 already tracks the work.

References. The three framework-gaps bullets are dropped; TML-2330 and
TML-2359 are kept as durable tracking links.

The ADR now references only other ADRs, Linear tickets, WHATWG, and
in-source file paths in the implementation pointer paragraph.
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.

2 participants