Repository navigation
Conversation
📝 WalkthroughWalkthroughAdds opt-in async encode/decode support across codecs, types, runtime, and ORM: codec generics and registry, contract input/output typing, param encoding (sync vs async), per-field decoding with promise-valued fields and post-decode JSON-schema validation, plus tests and helpers. Changes
Sequence Diagram(s)sequenceDiagram
participant Client
participant Runtime as SQL Runtime
participant CodecReg as Codec Registry
participant ParamEnc as Param Encoder
participant Driver as Database Driver
participant Result as Query Result
Client->>Runtime: executeAgainstQueryable(plan, params)
Runtime->>Runtime: resolveAsyncParamEncoding(plan)
alt async encoding required
Runtime->>ParamEnc: encodeParamsAsync(plan, params)
ParamEnc->>CodecReg: getCodec(paramDescriptor)
CodecReg-->>ParamEnc: codec
ParamEnc->>CodecReg: codec.encode(param)
CodecReg-->>ParamEnc: Promise<wire>
ParamEnc->>ParamEnc: await wire
ParamEnc-->>Runtime: encodedParams[]
else sync encoding only
Runtime->>ParamEnc: encodeParams(plan, params)
ParamEnc->>CodecReg: codec.encode(param)
CodecReg-->>ParamEnc: wire
ParamEnc-->>Runtime: encodedParams[]
end
Runtime->>Driver: rootExecute(plan, encodedParams)
Driver-->>Result: rows[]
Runtime->>Runtime: decodeRow(row)
Runtime->>CodecReg: getCodec(field)
CodecReg-->>Runtime: codec
alt codec.decode returns Promise
Runtime->>CodecReg: codec.decode(wire)
CodecReg-->>Runtime: Promise<value>
Runtime->>Runtime: attach post-resolution validation chain
else sync decode
Runtime->>CodecReg: codec.decode(wire)
CodecReg-->>Runtime: value
Runtime->>Runtime: validateDecodedValue(value)
end
Runtime-->>Client: row with mix of values and Promise fields
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
@prisma-next/mongo-runtime
@prisma-next/family-mongo
@prisma-next/sql-runtime
@prisma-next/family-sql
@prisma-next/middleware-telemetry
@prisma-next/mongo
@prisma-next/extension-paradedb
@prisma-next/extension-pgvector
@prisma-next/postgres
@prisma-next/sql-orm-client
@prisma-next/sqlite
@prisma-next/target-mongo
@prisma-next/adapter-mongo
@prisma-next/driver-mongo
@prisma-next/contract
@prisma-next/utils
@prisma-next/config
@prisma-next/errors
@prisma-next/framework-components
@prisma-next/operations
@prisma-next/ts-render
@prisma-next/contract-authoring
@prisma-next/ids
@prisma-next/psl-parser
@prisma-next/psl-printer
@prisma-next/cli
@prisma-next/emitter
@prisma-next/migration-tools
prisma-next
@prisma-next/vite-plugin-contract-emit
@prisma-next/runtime-executor
@prisma-next/mongo-codec
@prisma-next/mongo-contract
@prisma-next/mongo-value
@prisma-next/mongo-contract-psl
@prisma-next/mongo-contract-ts
@prisma-next/mongo-emitter
@prisma-next/mongo-schema-ir
@prisma-next/mongo-query-ast
@prisma-next/mongo-orm
@prisma-next/mongo-query-builder
@prisma-next/mongo-lowering
@prisma-next/mongo-wire
@prisma-next/sql-contract
@prisma-next/sql-errors
@prisma-next/sql-operations
@prisma-next/sql-schema-ir
@prisma-next/sql-contract-psl
@prisma-next/sql-contract-ts
@prisma-next/sql-contract-emitter
@prisma-next/sql-lane-query-builder
@prisma-next/sql-relational-core
@prisma-next/sql-builder
@prisma-next/target-postgres
@prisma-next/target-sqlite
@prisma-next/adapter-postgres
@prisma-next/adapter-sqlite
@prisma-next/driver-postgres
@prisma-next/driver-sqlite
commit: |
|
|
||
| expect(result['id']).toBe(7); | ||
| expect(result['secret']).toBeInstanceOf(Promise); | ||
| await expect(result['secret'] as Promise<unknown>).resolves.toBe('Alice'); |
There was a problem hiding this comment.
Why do we need result['secret'] as Promise<unknown>?
| export type CodecRuntimeBehavior = { | ||
| readonly encode?: 'async'; | ||
| readonly decode?: 'async'; | ||
| }; |
There was a problem hiding this comment.
This is currently explicit, but it can also be possible to keep it implicit and infer it from the returned values.
Let's keep it explicit for now though.
| /** Converts an app-facing value to a JSON-safe representation for contract serialization. Called during contract emission. */ | ||
| encodeJson(value: TInput): JsonValue; | ||
| /** Converts a JSON representation back to the app-facing write/input type. Called during contract loading via `validateContract`. */ | ||
| decodeJson(json: JsonValue): TInput; |
There was a problem hiding this comment.
Note to the reviewer: Coarse contract-level (de)serialization is still sync-only.
| // @ts-expect-error Mongo async codec runtime support is deferred to a follow-up | ||
| decode: async (wire: string) => wire, | ||
| encode: (value: string) => value, |
There was a problem hiding this comment.
Mongo async codec support will be provided in a follow-up PR. Let's unlock Postgres/SQL codecs first.
There was a problem hiding this comment.
Actionable comments posted: 1
🧹 Nitpick comments (4)
packages/1-framework/1-core/framework-components/src/codec-types.ts (1)
16-34: Stale JSDoc referencesTJsafter the input/output split.The docstring still says "JS (
TJs): the JavaScript type used in application code", but the interface no longer has aTJsgeneric — it was split intoTInput(write-side) andTOutput(read-side), withTEncodeAsync/TDecodeAsyncflags determining whetherencode/decodeyield promises. Worth updating so the doc matches the new shape (and briefly notes the async semantics introduced viaCodecRuntimeBehavior).📝 Suggested doc update
/** * Base codec interface for all target families. * - * A codec maps between three representations of a value: - * - **JS** (`TJs`): the JavaScript type used in application code - * - **Wire** (`TWire`): the format sent to/from the database driver - * - **JSON** (`JsonValue`): the JSON-safe form stored in contract artifacts + * A codec maps between representations of a value: + * - **Input** (`TInput`): the app-facing write-side type used for encode inputs, JSON (de)serialization, and query args + * - **Output** (`TOutput`): the app-facing read-side type produced by `decode` (may be wrapped in `Promise` when `TDecodeAsync` is `true`) + * - **Wire** (`TWire`): the format sent to/from the database driver (may be wrapped in `Promise` when `TEncodeAsync` is `true`) + * - **JSON** (`JsonValue`): the JSON-safe form stored in contract artifacts (always synchronous) * * Family-specific codec interfaces (SQL `Codec`, Mongo `MongoCodec`) extend * this base to add family-specific metadata. */🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/1-framework/1-core/framework-components/src/codec-types.ts` around lines 16 - 34, Update the JSDoc on the Codec interface to remove the stale "TJs" reference and describe the current split into TInput (write-side) and TOutput (read-side), and note that encode/decode may be async controlled by TEncodeAsync and TDecodeAsync (and/or CodecRuntimeBehavior) so consumers understand async semantics; specifically edit the comment above the export interface Codec to replace the JS (`TJs`) bullet with explanations for TInput and TOutput and add a short line about TEncodeAsync/TDecodeAsync governing promise-returning encode/decode.packages/3-extensions/sql-orm-client/src/collection-dispatch.ts (1)
531-603: Consolidate decode helpers withpackages/2-sql/5-runtime/src/codecs/decoding.ts.
isPromiseLike,isJsonSchemaValidationError,wirePreview, anddecodeFailurehere are effectively duplicates of the helpers indecoding.ts(see context snippets from lines 82-110 of that file).validateIncludedJsonValuealso overlaps substantially withvalidateDecodedValue, differing mainly in how the(table, column)ref is resolved (direct args here vs. projection/fallback index in runtime). As async codec behavior evolves, two implementations will drift.Consider exporting these from
@prisma-next/sql-runtime(or a small shared internal module) and importing them in the ORM client, so the error shape, preview rules, and schema-validation message format stay in lockstep.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/3-extensions/sql-orm-client/src/collection-dispatch.ts` around lines 531 - 603, The duplicated decode/validation helpers (isPromiseLike, isJsonSchemaValidationError, wirePreview, decodeFailure, validateIncludedJsonValue) should be consolidated with the canonical implementations in packages/2-sql/5-runtime/src/codecs/decoding.ts: export the helpers (or create a small shared internal module under `@prisma-next/sql-runtime`) and replace the local copies in collection-dispatch.ts with imports; ensure validateIncludedJsonValue delegates to or reuses validateDecodedValue (or the exported validator) so alias/codec error shapes, wirePreview behavior and JSON schema failure metadata remain identical across runtime and ORM client.packages/2-sql/5-runtime/src/codecs/encoding.ts (1)
75-88: Simplify the sync-encode flow to avoid re-detecting your own error.The current shape throws
unexpectedAsyncEncodeFailure(which itself usesRUNTIME.ENCODE_FAILED) inside thetryand then relies on a string-code check incatchto avoid double-wrapping. Splitting the two concerns removes the cast and makes intent obvious.♻️ Proposed refactor
if (codec.encode) { + let encoded: unknown; try { - const encoded = codec.encode(value); - if (isPromiseLike(encoded)) { - throw unexpectedAsyncEncodeFailure(codec, paramDescriptor, paramIndex); - } - return encoded; + encoded = codec.encode(value); } catch (error) { - throw error instanceof Error && - 'code' in error && - (error as Error & { code: string }).code === 'RUNTIME.ENCODE_FAILED' - ? error - : encodeFailure(codec, paramDescriptor, paramIndex, error); + throw encodeFailure(codec, paramDescriptor, paramIndex, error); } + if (isPromiseLike(encoded)) { + throw unexpectedAsyncEncodeFailure(codec, paramDescriptor, paramIndex); + } + return encoded; }🤖 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 75 - 88, The sync-encode flow is currently detecting its own thrown unexpectedAsyncEncodeFailure inside the same try/catch; refactor by splitting the steps: first call codec.encode(value) inside a try block and store the result (in a local variable), handle real encode exceptions in the catch by delegating to encodeFailure (using the same Error.code check as now), then after the try/catch check isPromiseLike(encoded) and only then throw unexpectedAsyncEncodeFailure(codec, paramDescriptor, paramIndex) if it is async; finally return the encoded value. Reference symbols: codec.encode, isPromiseLike, unexpectedAsyncEncodeFailure, encodeFailure, paramDescriptor, paramIndex.packages/3-extensions/sql-orm-client/test/collection-dispatch.test.ts (1)
359-365: Use an object matcher for related row fields.This block checks multiple related fields one-by-one; using a single object matcher is clearer and aligns with test style guidance.
♻️ Suggested refactor
- const post = rows[0]?.['posts'] as Record<string, unknown>[] | undefined; - expect(post).toBeDefined(); - expect(post?.[0]?.['id']).toBe(10); - expect(post?.[0]?.['title']).toBe('Post A'); - expect(post?.[0]?.['userId']).toBe(1); + const post = rows[0]?.['posts'] as Record<string, unknown>[] | undefined; + expect(post?.[0]).toMatchObject({ + id: 10, + title: 'Post A', + userId: 1, + }); await expect(post?.[0]?.['secret']).resolves.toBe('alpha'); await expect(post?.[0]?.['metadata']).resolves.toEqual({ title: 'A' });As per coding guidelines:
**/*.test.ts: Prefer object matchers (toMatchObject) over multiple individual expect().toBe() calls when checking 2 or more related values in tests.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/3-extensions/sql-orm-client/test/collection-dispatch.test.ts` around lines 359 - 365, The test checks multiple fields on the related row via separate expects; replace those with a single object matcher on the extracted related row to improve clarity and follow test style. Locate the variable post (from rows[0]?.['posts']) and change the assertions to assert post is defined and then use a single matcher like toMatchObject (or toEqual/toStrictEqual as appropriate) against an object containing id: 10, title: 'Post A', userId: 1, secret: 'alpha', metadata: { title: 'A' } for post?.[0] so all related fields are validated in one assertion.
🤖 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/2-authoring/contract-ts/test/contract-builder.dsl.types.test.ts`:
- Around line 33-41: asyncTargetPack's use of "as const satisfies
TargetPackRef<'sql','postgres'> & { readonly __codecTypes?: AsyncCodecTypes }"
loses the optional phantom __codecTypes property due to a TS satisfies
limitation; replace the satisfies expression with an explicit type annotation on
the variable so the phantom property is preserved (e.g., declare asyncTargetPack
with the type TargetPackRef<'sql','postgres'> & { readonly __codecTypes?:
AsyncCodecTypes } and assign the { ... } as const value), ensuring
CodecTypesFromDefinition and Definition lookups now see the __codecTypes and
yield Promise<string> for async outputs.
---
Nitpick comments:
In `@packages/1-framework/1-core/framework-components/src/codec-types.ts`:
- Around line 16-34: Update the JSDoc on the Codec interface to remove the stale
"TJs" reference and describe the current split into TInput (write-side) and
TOutput (read-side), and note that encode/decode may be async controlled by
TEncodeAsync and TDecodeAsync (and/or CodecRuntimeBehavior) so consumers
understand async semantics; specifically edit the comment above the export
interface Codec to replace the JS (`TJs`) bullet with explanations for TInput
and TOutput and add a short line about TEncodeAsync/TDecodeAsync governing
promise-returning encode/decode.
In `@packages/2-sql/5-runtime/src/codecs/encoding.ts`:
- Around line 75-88: The sync-encode flow is currently detecting its own thrown
unexpectedAsyncEncodeFailure inside the same try/catch; refactor by splitting
the steps: first call codec.encode(value) inside a try block and store the
result (in a local variable), handle real encode exceptions in the catch by
delegating to encodeFailure (using the same Error.code check as now), then after
the try/catch check isPromiseLike(encoded) and only then throw
unexpectedAsyncEncodeFailure(codec, paramDescriptor, paramIndex) if it is async;
finally return the encoded value. Reference symbols: codec.encode,
isPromiseLike, unexpectedAsyncEncodeFailure, encodeFailure, paramDescriptor,
paramIndex.
In `@packages/3-extensions/sql-orm-client/src/collection-dispatch.ts`:
- Around line 531-603: The duplicated decode/validation helpers (isPromiseLike,
isJsonSchemaValidationError, wirePreview, decodeFailure,
validateIncludedJsonValue) should be consolidated with the canonical
implementations in packages/2-sql/5-runtime/src/codecs/decoding.ts: export the
helpers (or create a small shared internal module under
`@prisma-next/sql-runtime`) and replace the local copies in collection-dispatch.ts
with imports; ensure validateIncludedJsonValue delegates to or reuses
validateDecodedValue (or the exported validator) so alias/codec error shapes,
wirePreview behavior and JSON schema failure metadata remain identical across
runtime and ORM client.
In `@packages/3-extensions/sql-orm-client/test/collection-dispatch.test.ts`:
- Around line 359-365: The test checks multiple fields on the related row via
separate expects; replace those with a single object matcher on the extracted
related row to improve clarity and follow test style. Locate the variable post
(from rows[0]?.['posts']) and change the assertions to assert post is defined
and then use a single matcher like toMatchObject (or toEqual/toStrictEqual as
appropriate) against an object containing id: 10, title: 'Post A', userId: 1,
secret: 'alpha', metadata: { title: 'A' } for post?.[0] so all related fields
are validated in one assertion.
🪄 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: 8dfba52c-5590-4c0c-97f8-3ee8ab21e7cd
📒 Files selected for processing (22)
docs/architecture docs/adrs/ADR 030 - Result decoding & codecs registry.mdpackages/1-framework/1-core/framework-components/src/codec-types.tspackages/1-framework/1-core/framework-components/src/exports/codec.tspackages/2-mongo-family/1-foundation/mongo-codec/src/codecs.tspackages/2-mongo-family/1-foundation/mongo-codec/test/codecs.test-d.tspackages/2-sql/2-authoring/contract-ts/src/contract-types.tspackages/2-sql/2-authoring/contract-ts/test/contract-builder.dsl.types.test.tspackages/2-sql/4-lanes/relational-core/src/ast/codec-types.tspackages/2-sql/4-lanes/relational-core/test/ast/codec-types.test.tspackages/2-sql/4-lanes/sql-builder/test/playground/async-codecs.test-d.tspackages/2-sql/5-runtime/src/codecs/decoding.tspackages/2-sql/5-runtime/src/codecs/encoding.tspackages/2-sql/5-runtime/src/sql-runtime.tspackages/2-sql/5-runtime/test/json-schema-validation.test.tspackages/2-sql/5-runtime/test/seeded-secret-codec.tspackages/2-sql/5-runtime/test/sql-runtime.test.tspackages/3-extensions/sql-orm-client/src/collection-dispatch.tspackages/3-extensions/sql-orm-client/src/collection.tspackages/3-extensions/sql-orm-client/src/exports/index.tspackages/3-extensions/sql-orm-client/src/types.tspackages/3-extensions/sql-orm-client/test/async-codecs.test-d.tspackages/3-extensions/sql-orm-client/test/collection-dispatch.test.ts
There was a problem hiding this comment.
🧹 Nitpick comments (2)
packages/2-sql/2-authoring/contract-ts/test/contract-builder.dsl.helpers.test.ts (1)
110-135: Consider retaining theTargetPackRefstructural check on the base constant.Unlike
contract-builder.dsl.portability.test.ts, which keeps theTargetPackRefshape enforced viaPortableTargetPack<T>(an intersection that includesTargetPackRef<'sql', T>), this file now typespostgresTargetPackpurely fromtypeof postgresTargetPackBase. Nothing in the type system checks that the base still conforms toTargetPackRef<'sql', 'postgres'>— a future typo infamilyId/targetId/kindwould silently widen the literal type instead of failing at compile time.If the goal was to expose the full literal type of
authoring(so consumers see precise preset keys) while still validating the pack contract, you can keep both by re-addingsatisfieson the base:♻️ Optional refactor to restore structural validation
-import type { ExtensionPackRef, FamilyPackRef } from '@prisma-next/framework-components/components'; +import type { + ExtensionPackRef, + FamilyPackRef, + TargetPackRef, +} from '@prisma-next/framework-components/components'; @@ -} as const; - -const postgresTargetPack: typeof postgresTargetPackBase & { - readonly __codecTypes?: PortableSqlCodecTypes; -} = postgresTargetPackBase; +} as const satisfies TargetPackRef<'sql', 'postgres'>; + +const postgresTargetPack: typeof postgresTargetPackBase & { + readonly __codecTypes?: PortableSqlCodecTypes; +} = postgresTargetPackBase;🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/2-sql/2-authoring/contract-ts/test/contract-builder.dsl.helpers.test.ts` around lines 110 - 135, The base constant postgresTargetPackBase currently lacks a compile-time check against the expected pack shape; restore the structural validation by using the TypeScript satisfies operator with the appropriate TargetPackRef/PortableTargetPack type (e.g., satisfy TargetPackRef<'sql','postgres'> or PortableTargetPack<...>) on postgresTargetPackBase so familyId/targetId/kind remain validated, while keeping the existing postgresTargetPack declaration (typeof postgresTargetPackBase & { readonly __codecTypes?: PortableSqlCodecTypes }) to expose the literal authoring shape to consumers.packages/2-sql/5-runtime/src/sql-runtime.ts (1)
187-198: Caching pattern looks correct; consider tightening theplanparameter type.The WeakMap-by-plan-identity approach is sound for skipping registry walks on sync-only plans, and the secondary cache entry for
executablePlanis safely inert when callers always start from an un-loweredSqlQueryPlan.One minor nit:
plan: objectis looser than necessary — at the only call site (line 206) this is alwaysExecutionPlan<Row> | SqlQueryPlan<Row>. Tightening it documents intent and avoids accidental non-plan objects being cached.Proposed tightening
- private resolveAsyncParamEncoding(plan: object, executablePlan: ExecutionPlan<unknown>): boolean { + private resolveAsyncParamEncoding( + plan: ExecutionPlan<unknown> | SqlQueryPlan<unknown>, + executablePlan: ExecutionPlan<unknown>, + ): boolean {🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/2-sql/5-runtime/src/sql-runtime.ts` around lines 187 - 198, Tighten the loose plan parameter type to a plan-specific union/generic so non-plan objects can't be cached: change the signature of resolveAsyncParamEncoding from plan: object to a typed union (e.g. make the method generic and use plan: ExecutionPlan<T> | SqlQueryPlan<T> and executablePlan: ExecutionPlan<T>) and update internal references (asyncEncodingCache.get/set and the hasAsyncParamEncoding call) to use that generic T; this preserves behavior while documenting intent and preventing accidental caching of non-plan objects.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Nitpick comments:
In
`@packages/2-sql/2-authoring/contract-ts/test/contract-builder.dsl.helpers.test.ts`:
- Around line 110-135: The base constant postgresTargetPackBase currently lacks
a compile-time check against the expected pack shape; restore the structural
validation by using the TypeScript satisfies operator with the appropriate
TargetPackRef/PortableTargetPack type (e.g., satisfy
TargetPackRef<'sql','postgres'> or PortableTargetPack<...>) on
postgresTargetPackBase so familyId/targetId/kind remain validated, while keeping
the existing postgresTargetPack declaration (typeof postgresTargetPackBase & {
readonly __codecTypes?: PortableSqlCodecTypes }) to expose the literal authoring
shape to consumers.
In `@packages/2-sql/5-runtime/src/sql-runtime.ts`:
- Around line 187-198: Tighten the loose plan parameter type to a plan-specific
union/generic so non-plan objects can't be cached: change the signature of
resolveAsyncParamEncoding from plan: object to a typed union (e.g. make the
method generic and use plan: ExecutionPlan<T> | SqlQueryPlan<T> and
executablePlan: ExecutionPlan<T>) and update internal references
(asyncEncodingCache.get/set and the hasAsyncParamEncoding call) to use that
generic T; this preserves behavior while documenting intent and preventing
accidental caching of non-plan objects.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yml
Review profile: CHILL
Plan: Pro
Run ID: e4fc89ce-399c-47d3-ac52-9af27fca603e
📒 Files selected for processing (12)
packages/2-sql/2-authoring/contract-ts/src/contract-types.tspackages/2-sql/2-authoring/contract-ts/test/contract-builder.dsl.helpers.test.tspackages/2-sql/2-authoring/contract-ts/test/contract-builder.dsl.portability.test.tspackages/2-sql/2-authoring/contract-ts/test/contract-builder.dsl.types.test.tspackages/2-sql/2-authoring/contract-ts/test/helpers/column-descriptor.tspackages/2-sql/5-runtime/package.jsonpackages/2-sql/5-runtime/src/codecs/decoding.tspackages/2-sql/5-runtime/src/codecs/json-schema-validation.tspackages/2-sql/5-runtime/src/exports/index.tspackages/2-sql/5-runtime/src/sql-runtime.tspackages/2-sql/5-runtime/test/json-schema-validation.test.tspackages/3-extensions/sql-orm-client/src/collection-dispatch.ts
✅ Files skipped from review due to trivial changes (1)
- packages/2-sql/5-runtime/package.json
🚧 Files skipped from review as they are similar to previous changes (2)
- packages/2-sql/2-authoring/contract-ts/test/contract-builder.dsl.types.test.ts
- packages/2-sql/5-runtime/src/codecs/decoding.ts
There was a problem hiding this comment.
Actionable comments posted: 1
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (1)
packages/3-extensions/sql-orm-client/src/types.ts (1)
207-218:⚠️ Potential issue | 🟡 MinorAdd documentation to clarify why
CodecArgJsTypelacks theAwaited<O>fallback thatFieldInputJsTypeprovides.
CodecArgJsType(lines 207–218) resolves tounknownwhen a codec declares onlyoutput, whileFieldInputJsType(sql-orm-client/src/types.ts:683–692) falls back toAwaited<FieldJsType<...>>in the same scenario. Since output-only codec types exist in tests and operation arguments depend onCodecArgJsTypeviaMapArgsToJsTypes, users registering output-only codecs will see silently-typed operation args asunknown.If this strictness is intentional—requiring operation authors to declare
inputexplicitly—add a comment explaining the design (e.g.,// input required for operations; fallback differs from FieldInputJsType by design). Otherwise, alignCodecArgJsTypewithFieldInputJsType's fallback pattern for consistency.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/3-extensions/sql-orm-client/src/types.ts` around lines 207 - 218, CodecArgJsType currently resolves to unknown when a codec exposes only output, causing operation args that rely on MapArgsToJsTypes to become silently unknown; either document this intentional strictness or make the type consistent with FieldInputJsType by adding the same Awaited<Fallback> behavior. To fix: locate the type alias CodecArgJsType and either (A) add a brief inline comment explaining that input is required for operation arg typing and that the lack of an Awaited fallback is intentional, referencing FieldInputJsType for readers, or (B) update the conditional branches so that when a codec key exists but only defines output you fall back to the same Awaited<FieldJsType<...>> pattern used by FieldInputJsType (ensuring MapArgsToJsTypes then receives the expected JS type); pick one approach and apply it to CodecArgJsType for consistency or clarity.
🧹 Nitpick comments (4)
packages/3-extensions/sql-orm-client/src/collection-dispatch.ts (2)
544-554: Prefer importingCodecdirectly overReturnType<...>gymnastics.
ReturnType<CollectionContext<Contract<SqlStorage>>['context']['codecs']['get']>is an indirect way to expressCodec | undefined. ImportingCodecfrom@prisma-next/sql-relational-core/ast(already imported for other symbols in the file's neighborhood) would make the interface self-documenting.🔧 Proposed fix
+import type { Codec } from '@prisma-next/sql-relational-core/ast'; ... interface IncludeDecodeColumn { readonly columnName: string; readonly fieldName: string; - readonly codec: ReturnType<CollectionContext<Contract<SqlStorage>>['context']['codecs']['get']>; + readonly codec: Codec | undefined; }🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/3-extensions/sql-orm-client/src/collection-dispatch.ts` around lines 544 - 554, Replace the awkward ReturnType expression in the IncludeDecodeColumn interface with an explicit Codec type: import Codec from '@prisma-next/sql-relational-core/ast' (alongside the other imports in this file) and change the codec property type from ReturnType<CollectionContext<Contract<SqlStorage>>['context']['codecs']['get']> to Codec | undefined; update any affected references to IncludeDecodeColumn/IncludeDecodePlan accordingly so the interfaces remain self-documenting.
585-590:_contractparameter is unused indecodeIncludedRow.The first argument is neither read nor passed through. Drop it from the signature and the call site at Line 166 to keep the API minimal.
🔧 Proposed fix
-function decodeIncludedRow( - _contract: Contract<SqlStorage>, - context: CollectionContext<Contract<SqlStorage>>['context'], - plan: IncludeDecodePlan, - row: Record<string, unknown>, -): Record<string, unknown> { +function decodeIncludedRow( + context: CollectionContext<Contract<SqlStorage>>['context'], + plan: IncludeDecodePlan, + row: Record<string, unknown>, +): Record<string, unknown> {…and at the call site:
- ? decodeIncludedRow(contract, context, plan, childRow) + ? decodeIncludedRow(context, plan, childRow)🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/3-extensions/sql-orm-client/src/collection-dispatch.ts` around lines 585 - 590, The parameter _contract in function decodeIncludedRow is unused—remove the first parameter from decodeIncludedRow's signature and eliminate the corresponding argument at its call site (where decodeIncludedRow is invoked) so the function accepts (context, plan, row) only; update all callers to pass the remaining three arguments and run tests/TS compile to ensure no other usages remain.packages/2-sql/5-runtime/src/codecs/decoding.ts (1)
94-98: Minor: truncation indicator is only applied for strings.For non-string values that stringify to more than 100 characters (e.g., a large Buffer, bigint, or object with custom
toString), the preview is silently truncated without the...suffix that strings get. Consider normalizing so truncated non-string previews are also visibly marked:🔧 Proposed normalization
export function wirePreview(value: unknown): string { - return typeof value === 'string' && value.length > 100 - ? `${value.substring(0, 100)}...` - : String(value).substring(0, 100); + const asString = typeof value === 'string' ? value : String(value); + return asString.length > 100 ? `${asString.substring(0, 100)}...` : asString; }🤖 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/decoding.ts` around lines 94 - 98, The wirePreview function currently only appends "..." for string inputs, causing non-string values that stringify to >100 chars to be truncated without an ellipsis; change wirePreview (function name) to normalize by calling String(value) into a single string variable, check its length, and if >100 return the first 100 characters plus "..." otherwise return the full string so all truncated previews (string or not) include the "..." indicator.coverage.config.json (1)
14-22: Well-documented warning-only entry with reproduction steps.Entry includes expiry, reason, and a reproducible verification command against
main. Consider also filing the Linear ticket for the follow-up coverage work so thelinear: nullslot is populated before the 60-day expiry.🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@coverage.config.json` around lines 14 - 22, The entry in coverage.config.json is fine but leaves "linear": null; create a Linear ticket for the follow-up coverage work and update the "linear" field with that ticket ID (or URL) in the same object so the follow-up is tracked before the 60-day expiry; ensure you keep the existing "reason", "addedDate", and "expiryDays" values and only replace the null "linear" value for the package "3-extensions/sql-orm-client".
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.
Inline comments:
In `@packages/3-extensions/sql-orm-client/src/collection-dispatch.ts`:
- Around line 572-583: The loop in the function building IncludeDecodeColumn
uses defensive optional chaining on column (column?.codecId) even though
Object.entries(table.columns) guarantees defined column objects; change the
access to use column.codecId (and any other properties accessed with ?.)
directly, e.g., replace column?.codecId with column.codecId and keep resolving
codec via context.codecs.get(codecId) so columns.push still uses columnName,
fieldName, and codec as before.
---
Outside diff comments:
In `@packages/3-extensions/sql-orm-client/src/types.ts`:
- Around line 207-218: CodecArgJsType currently resolves to unknown when a codec
exposes only output, causing operation args that rely on MapArgsToJsTypes to
become silently unknown; either document this intentional strictness or make the
type consistent with FieldInputJsType by adding the same Awaited<Fallback>
behavior. To fix: locate the type alias CodecArgJsType and either (A) add a
brief inline comment explaining that input is required for operation arg typing
and that the lack of an Awaited fallback is intentional, referencing
FieldInputJsType for readers, or (B) update the conditional branches so that
when a codec key exists but only defines output you fall back to the same
Awaited<FieldJsType<...>> pattern used by FieldInputJsType (ensuring
MapArgsToJsTypes then receives the expected JS type); pick one approach and
apply it to CodecArgJsType for consistency or clarity.
---
Nitpick comments:
In `@coverage.config.json`:
- Around line 14-22: The entry in coverage.config.json is fine but leaves
"linear": null; create a Linear ticket for the follow-up coverage work and
update the "linear" field with that ticket ID (or URL) in the same object so the
follow-up is tracked before the 60-day expiry; ensure you keep the existing
"reason", "addedDate", and "expiryDays" values and only replace the null
"linear" value for the package "3-extensions/sql-orm-client".
In `@packages/2-sql/5-runtime/src/codecs/decoding.ts`:
- Around line 94-98: The wirePreview function currently only appends "..." for
string inputs, causing non-string values that stringify to >100 chars to be
truncated without an ellipsis; change wirePreview (function name) to normalize
by calling String(value) into a single string variable, check its length, and if
>100 return the first 100 characters plus "..." otherwise return the full string
so all truncated previews (string or not) include the "..." indicator.
In `@packages/3-extensions/sql-orm-client/src/collection-dispatch.ts`:
- Around line 544-554: Replace the awkward ReturnType expression in the
IncludeDecodeColumn interface with an explicit Codec type: import Codec from
'@prisma-next/sql-relational-core/ast' (alongside the other imports in this
file) and change the codec property type from
ReturnType<CollectionContext<Contract<SqlStorage>>['context']['codecs']['get']>
to Codec | undefined; update any affected references to
IncludeDecodeColumn/IncludeDecodePlan accordingly so the interfaces remain
self-documenting.
- Around line 585-590: The parameter _contract in function decodeIncludedRow is
unused—remove the first parameter from decodeIncludedRow's signature and
eliminate the corresponding argument at its call site (where decodeIncludedRow
is invoked) so the function accepts (context, plan, row) only; update all
callers to pass the remaining three arguments and run tests/TS compile to ensure
no other usages remain.
🪄 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: 34e613b7-f78f-443b-8063-0f936236fa21
📒 Files selected for processing (16)
coverage.config.jsonpackages/1-framework/1-core/framework-components/src/codec-types.tspackages/1-framework/1-core/framework-components/src/exports/codec.tspackages/2-mongo-family/1-foundation/mongo-codec/src/codecs.tspackages/2-sql/2-authoring/contract-ts/src/contract-types.tspackages/2-sql/2-authoring/contract-ts/test/contract-builder.dsl.types.test.tspackages/2-sql/4-lanes/relational-core/src/ast/codec-types.tspackages/2-sql/4-lanes/relational-core/test/ast/codec-types.test.tspackages/2-sql/5-runtime/src/codecs/decoding.tspackages/2-sql/5-runtime/src/codecs/json-schema-validation.tspackages/2-sql/5-runtime/src/sql-runtime.tspackages/2-sql/5-runtime/test/json-schema-validation.test.tspackages/2-sql/5-runtime/test/seeded-secret-codec.tspackages/2-sql/5-runtime/test/sql-runtime.test.tspackages/3-extensions/sql-orm-client/src/collection-dispatch.tspackages/3-extensions/sql-orm-client/src/types.ts
✅ Files skipped from review due to trivial changes (1)
- packages/1-framework/1-core/framework-components/src/exports/codec.ts
🚧 Files skipped from review as they are similar to previous changes (6)
- packages/2-sql/2-authoring/contract-ts/test/contract-builder.dsl.types.test.ts
- packages/2-sql/5-runtime/src/codecs/json-schema-validation.ts
- packages/2-sql/5-runtime/test/sql-runtime.test.ts
- packages/2-sql/4-lanes/relational-core/test/ast/codec-types.test.ts
- packages/1-framework/1-core/framework-components/src/codec-types.ts
- packages/2-sql/4-lanes/relational-core/src/ast/codec-types.ts
| const columns: IncludeDecodeColumn[] = []; | ||
| for (const [columnName, column] of Object.entries(table.columns)) { | ||
| const codecId = column?.codecId; | ||
| const codec = codecId ? context.codecs.get(codecId) : undefined; | ||
| columns.push({ | ||
| columnName, | ||
| fieldName: columnToField[columnName] ?? columnName, | ||
| codec, | ||
| }); | ||
| } | ||
| return { tableName, modelName, columns }; | ||
| } |
There was a problem hiding this comment.
Remove defensive optional chaining on column.
Object.entries(table.columns) yields defined values, so column?.codecId is never reachable with column === undefined. As per coding guidelines: "Remove optional chaining and conditional property spreading for properties that are guaranteed to exist after validation - access required properties directly without ?. operators."
🔧 Proposed fix
const columnToField = getColumnToFieldMap(contract, modelName);
const columns: IncludeDecodeColumn[] = [];
for (const [columnName, column] of Object.entries(table.columns)) {
- const codecId = column?.codecId;
+ const codecId = column.codecId;
const codec = codecId ? context.codecs.get(codecId) : undefined;As per coding guidelines: "Remove optional chaining and conditional property spreading for properties that are guaranteed to exist after validation - access required properties directly without ?. operators."
📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| const columns: IncludeDecodeColumn[] = []; | |
| for (const [columnName, column] of Object.entries(table.columns)) { | |
| const codecId = column?.codecId; | |
| const codec = codecId ? context.codecs.get(codecId) : undefined; | |
| columns.push({ | |
| columnName, | |
| fieldName: columnToField[columnName] ?? columnName, | |
| codec, | |
| }); | |
| } | |
| return { tableName, modelName, columns }; | |
| } | |
| const columns: IncludeDecodeColumn[] = []; | |
| for (const [columnName, column] of Object.entries(table.columns)) { | |
| const codecId = column.codecId; | |
| const codec = codecId ? context.codecs.get(codecId) : undefined; | |
| columns.push({ | |
| columnName, | |
| fieldName: columnToField[columnName] ?? columnName, | |
| codec, | |
| }); | |
| } | |
| return { tableName, modelName, columns }; |
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@packages/3-extensions/sql-orm-client/src/collection-dispatch.ts` around lines
572 - 583, The loop in the function building IncludeDecodeColumn uses defensive
optional chaining on column (column?.codecId) even though
Object.entries(table.columns) guarantees defined column objects; change the
access to use column.codecId (and any other properties accessed with ?.)
directly, e.g., replace column?.codecId with column.codecId and keep resolving
codec via context.codecs.get(codecId) so columns.push still uses columnName,
fieldName, and codec as before.
Addresses P1/P2 findings from the review of projects/async-codecs. - decoding: extract shared `decodeField` helper and export `isPromiseLike`, `wirePreview`, `decodeFailure`, `isJsonSchemaValidationError` from the sql runtime barrel. Collapse the per-field `.then().catch()` pair into a single async IIFE (one microtask per async field instead of two). Attach an idempotent no-op `.catch` to silence Node's `unhandledRejection` when a consumer never reads a promise-valued row field; consumers that do await still receive the rejection. - json-schema-validation: accept a `redactValues` flag; when true, drop validator-supplied `message` strings from both the thrown summary and `details.errors`. `decodeField` sets the flag from `codec.runtime?.decode === 'async'` so decrypted plaintext cannot leak through schema-violation telemetry (spec NFR-4). - sql-runtime: memoize `hasAsyncParamEncoding` by plan identity in a `WeakMap` so sync-only plans skip the per-execute registry walk (spec NFR-1). - sql-orm-client `collection-dispatch`: consume the shared `decodeField`; delete the verbatim helper duplicates (~130 LOC removed). - sql-runtime package: drop `test` from the published `files` array; the `./test/utils` export already resolves through `dist/test/utils.mjs`, so removing it does not break downstream consumers. Corresponding review todos in `todos/`: 001, 002, 003, 005, 007, 008.
… fallback
Todo 009 — Codec async type parameters
The base `Codec` interface grew two boolean generics (`TEncodeAsync`,
`TDecodeAsync`) and the SQL `Codec` carried nine positional parameters. Every
positional extractor (`CodecId`, `CodecInput`, `CodecOutput`, `CodecTraits`,
`AnyCodec`) listed nine `infer` slots — reordering silently corrupts
extraction. Collapse the two booleans into one `TRuntime extends
CodecRuntimeBehavior | undefined = undefined` type parameter:
- base `Codec`: 7 params → 6
- SQL `Codec`: 9 params → 8
- `codec()` factory: drops `RuntimeEncodeIsAsync` / `RuntimeDecodeIsAsync`
conditional helpers and passes `TRuntime` directly to the result type
- `CodecEncodeResult<TWire, TRuntime>` / `CodecDecodeResult<TOutput, TRuntime>`
key off `TRuntime extends { readonly encode: 'async' }` (etc.) instead of
the boolean; both helpers are now exported from `framework-components/codec`
and re-exported from `sql-relational-core/ast`
- `MongoCodec` narrows via `BaseCodec<..., undefined>` (was `..., false, false`)
- The `runtime?` *field* is decoupled from `TRuntime` and typed as
`CodecRuntimeBehavior` so a generic `Codec` reference (default
`TRuntime = undefined`) still lets consumers inspect
`codec.runtime?.decode === 'async'` at runtime — no cast required
Todo 006 — Awaited<> fallback for FieldInput types
When a codec type-map entry exposes only `output` (no `input`), the fallback
arm in `FieldInputType` (contract-ts) and `FieldInputJsType` (sql-orm-client)
previously produced `Promise<T>` for async-decode codecs — writes would then
demand `Promise<T>` on mutation inputs, filters, and cursors. Wrap the
fallback in `Awaited<>` so async codec fields stay plain `T` on the write
side. Sync codecs are unaffected (`Awaited<T>` is `T` when `T` is not a
thenable). Regression covered by a new case in
`contract-builder.dsl.types.test.ts` that builds a contract from a type map
with only `output`.
The prior P1 commit dropped `test/` from the sql-runtime package `files`
array, but the fixture itself was still copy-paste-unsafe: it derived the
AES-GCM IV deterministically from the plaintext, which collapses
confidentiality under chosen-plaintext and breaks integrity on IV reuse.
- Randomize the IV per encryption (12 bytes from `crypto.getRandomValues`)
and store `iv:ciphertext`. Decryption is unchanged.
- Add a TEST-ONLY banner at the top of the file describing the limits of
the fixture (seed-derived key, no KMS, no AAD, no rotation) so a reader
who stumbles into it cannot mistake it for a shipping codec.
- Add a load-time guard: throw if `NODE_ENV === 'production'`.
- Switch the two assertions that previously compared exact ciphertext
bytes to round-trip through `decryptSecret`, since the ciphertext is
no longer deterministic.
- Apply the same random-IV change to the near-duplicate helper inlined
in `relational-core/test/ast/codec-types.test.ts` so both copies stop
modelling an insecure pattern; update its `expect(wire).toBe(await
encode('cleartext'))` assertion to compare the two distinct ciphertexts
and round-trip both through decode.
…CI coverage
Todo 004 — codec error.message redaction
`decodeFailure` previously interpolated `error.message` from the codec's own
throw into the human-readable `RUNTIME.DECODE_FAILED` envelope. A sloppy or
hostile codec that embedded plaintext in its error (e.g.
`throw new Error('decrypt failed for value=<plaintext>')`) bypassed
`wirePreview` redaction. Drop `error.message` from the envelope text and
attach the original error via the standard `cause` chain so developer
diagnostics stay reachable but telemetry-serialized fields cannot leak
decoded values. Regression test asserts the leaky substring is absent from
`.message` and `details` while `cause` still surfaces it.
Todo 010 — hoist per-column codec lookup
`decodeIncludedRow` resolved `columnName → codecId → codec` once per child
row per parent, causing O(parents × children × columns) registry walks and
`getColumnToFieldMap` calls even though the result depends only on the
included table. Precompute an `IncludeDecodePlan`
(`{ columnName, fieldName, codec }` per column) once per include in
`dispatchWithSingleQueryIncludes`, then iterate it per row. The plan also
iterates contract column order (stable, well-typed) instead of
`Object.entries(row)`, so decode visits every expected field even when the
wire aggregate omits a column. A trailing pass preserves any extra wire-only
keys so extension packs that ship synthetic aggregate columns still flow
through untouched.
CI coverage unblock
`3-extensions/sql-orm-client` has pre-existing branch-coverage gaps (verified
by `git checkout main -- packages/3-extensions/sql-orm-client` followed by
`vitest run --coverage --typecheck=false`, which reproduces identical
percentages on `collection.ts`, `filters.ts`, `model-accessor.ts`,
`query-plan-meta.ts`, `query-plan-mutations.ts`, `query-plan-select.ts`, and
`types.ts`). The feat/async-codecs work did not introduce these gaps. Add a
60-day `warningOnly` entry with a scoped reason + reproduction instructions
so CI demotes the failures to warnings until follow-up coverage work lands.
Todo 011 — precedence divergence The top-level row path consults the full precedence chain (lane hint → contract → adapter → driver) via `resolveRowCodec` in `packages/2-sql/5-runtime/src/codecs/decoding.ts`. The SQL ORM's single-query include strategies (`lateral`, `correlated`) decode nested JSON aggregates inside the ORM extension using contract-declared codecs only, bypassing lane hints at include depth. Document the divergence in ADR 030 so users who attach `hintCodec` to an include branch aren't surprised it's ignored, and so the follow-up work to unify include decoding with the runtime's full precedence has a clear starting point. Decoding *semantics* (null short-circuit, promise-valued async fields, JSON-schema validation, error redaction) are unchanged — only codec *selection* differs.
- Drop the `biome-ignore noExplicitAny` in `relational-core/src/ast/codec-types.ts`:
the prior `const dataTypes = {} as any` is unnecessary — narrow to
`Record<string, string>` during construction, then cast to the
literal-keyed return shape at the end. Same pattern already used for the
sibling `codecTypes` local.
- `CodecOutput<T>` double-wrap guard: apply `Awaited<>` to the codec-declared
`TOutput` before re-wrapping on the async branch. If a codec author types
`decode: async (wire) => Promise<User>` explicitly, TS infers
`TOutput = Promise<User>` — without the guard the extractor returned
`Promise<Promise<User>>`. Sync branch also applies `Awaited<>` for
consistency.
- Rename `codecDefinitions[K].jsType` → `outputType`. The old name conflated
"plain JS value" with "read-side decoded type" now that `output` can be
`Promise<T>` for async codecs. Only in-repo consumer was the relational-core
test.
- Inline `isPromiseLike` at the three call sites and drop the helper +
barrel export. `value instanceof Promise` is shorter than the import line,
no external consumer was pulling the helper from `@prisma-next/sql-runtime`.
- Add multi-query include × async-codec regression test in
`sql-orm-client/test/collection-dispatch.test.ts`. The ORM's multi-query
path delegates child-row decode to the runtime, so the unit test stands in
a `Promise<string>` for the `secret` column to prove the ORM stitching
does not unwrap or drop promise-valued fields from child rows.
- Document the codec-author contract for `runtime.encode` in ADR 030: a
codec returning a `Promise` from its `encode` hook without declaring
`runtime.encode: 'async'` triggers `RUNTIME.ENCODE_FAILED` before the
driver call. The sync path never awaits, so a silent Promise would
otherwise ship to the driver as the parameter value.
f6e1e18 to
d32fd93
Compare
There was a problem hiding this comment.
Actionable comments posted: 3
🧹 Nitpick comments (2)
packages/2-sql/2-authoring/contract-ts/test/contract-builder.dsl.helpers.test.ts (1)
110-135: RestoreTargetPackRefconformance check onpostgresTargetPack.Dropping
satisfies TargetPackRef<'sql', 'postgres'>(and theTargetPackRefimport) means the literal is no longer structurally verified against the pack-ref contract — a typo inkind/familyId/targetIdor a missing required field would now slip through. The siblingcontract-builder.dsl.types.test.tskeeps this constraint viaTargetPackRef<'sql', 'postgres'> & { readonly __codecTypes?: ... }. You can keep the literal types and the optional__codecTypesextension while restoring the check by combiningas const satisfieson the base.♻️ Proposed change
-import type { ExtensionPackRef, FamilyPackRef } from '@prisma-next/framework-components/components'; +import type { + ExtensionPackRef, + FamilyPackRef, + TargetPackRef, +} from '@prisma-next/framework-components/components'; @@ -const postgresTargetPackBase = { +const postgresTargetPackBase = { kind: 'target', id: 'postgres', familyId: 'sql', targetId: 'postgres', version: '0.0.1', authoring: { type: { enum: { kind: 'typeConstructor', args: [{ kind: 'string' }, { kind: 'stringArray' }], output: { codecId: 'pg/enum@1', nativeType: { kind: 'arg', index: 0 }, typeParams: { values: { kind: 'arg', index: 1 }, }, }, }, }, }, -} as const; +} as const satisfies TargetPackRef<'sql', 'postgres'>; const postgresTargetPack: typeof postgresTargetPackBase & { readonly __codecTypes?: PortableSqlCodecTypes; } = postgresTargetPackBase;🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed. In `@packages/2-sql/2-authoring/contract-ts/test/contract-builder.dsl.helpers.test.ts` around lines 110 - 135, Restore the structural check by applying the TargetPackRef conformance to the base literal: change postgresTargetPackBase to use "as const satisfies TargetPackRef<'sql','postgres'>" (and re-add the TargetPackRef import), then keep the existing postgresTargetPack declaration that extends the base with "& { readonly __codecTypes?: PortableSqlCodecTypes }" so the literal is type-checked for kind/familyId/targetId while still allowing the optional __codecTypes override.packages/2-sql/5-runtime/src/codecs/encoding.ts (1)
150-172:encodeParamsAsyncserializes independent encodes.Each param is awaited sequentially, so N async-encoding params with M ms cost each take O(N·M) wall time even though param encodings are independent. Consider
Promise.allfor the async path.♻️ Proposed fix
export async function encodeParamsAsync( plan: ExecutionPlan, registry: CodecRegistry, ): Promise<readonly unknown[]> { if (plan.params.length === 0) { return plan.params; } - const encoded: unknown[] = []; - - for (let i = 0; i < plan.params.length; i++) { - const paramValue = plan.params[i]; - const paramDescriptor = plan.meta.paramDescriptors[i]; - - if (paramDescriptor) { - encoded.push(await encodeParamAsync(paramValue, paramDescriptor, i, registry)); - } else { - encoded.push(paramValue); - } - } - - return Object.freeze(encoded); + const encoded = await Promise.all( + plan.params.map((paramValue, i) => { + const paramDescriptor = plan.meta.paramDescriptors[i]; + return paramDescriptor + ? encodeParamAsync(paramValue, paramDescriptor, i, registry) + : paramValue; + }), + ); + return Object.freeze(encoded); }🤖 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 150 - 172, encodeParamsAsync currently awaits each encodeParamAsync serially which makes independent async encodings run in series; change encodeParamsAsync to build an array of promises by mapping over plan.params and for each index calling encodeParamAsync(paramValue, paramDescriptor, i, registry) when paramDescriptor exists (or wrapping the raw paramValue in Promise.resolve), then await Promise.all on that array to run encodes in parallel, preserve original ordering, freeze the resulting array and return it; reference functions/values: encodeParamsAsync, encodeParamAsync, plan.params, plan.meta.paramDescriptors, ExecutionPlan, CodecRegistry.
🤖 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 368-377: Remove the redundant `output` property from the
`codecDefinitions` structure: the interface keyed by `ScalarNames` should only
expose `outputType: CodecOutput<ScalarNames[K]>` (remove `output`), update any
getter/initializer that constructs entries in `codecDefinitions` to stop
creating/assigning an `output` field (only assign `outputType`), and update
tests that assert on `output` (e.g., in codec-types.test.ts) to assert on
`outputType` instead; ensure all references to the removed `output` symbol are
eliminated and types remain `CodecOutput<ScalarNames[K]>` where previously
duplicated.
In `@packages/2-sql/5-runtime/src/codecs/encoding.ts`:
- Around line 71-85: When a codec.encode call returns a Promise that may already
be rejected, avoid leaving an unhandled rejection by attaching a noop catcher
before throwing; inside the encode path where you detect encoded instanceof
Promise (in the block around codec.encode and the unexpectedAsyncEncodeFailure
throw), call encoded.catch(() => {}) to swallow the eventual rejection, then
throw unexpectedAsyncEncodeFailure(codec, paramDescriptor, paramIndex); keep the
existing catch logic that maps errors to encodeFailure(codec, paramDescriptor,
paramIndex, error) intact.
- Around line 23-38: The encodeFailure function currently injects the codec's
raw error.message into the human-facing runtimeError and omits the original
error as a cause; update encodeFailure to redact the codec error text in the
user-facing message (use a bounded/generic message like "Failed to encode
parameter X") and attach the original error as the cause property of the
runtimeError (wrap non-Error values into an Error if needed). Locate
encodeFailure and adjust the runtimeError call to supply the redacted message,
keep the metadata { label, codec: codec.id }, and include the original error
under a cause field so tooling and debuggers can access the original error chain
without leaking plaintext in the envelope.
---
Nitpick comments:
In
`@packages/2-sql/2-authoring/contract-ts/test/contract-builder.dsl.helpers.test.ts`:
- Around line 110-135: Restore the structural check by applying the
TargetPackRef conformance to the base literal: change postgresTargetPackBase to
use "as const satisfies TargetPackRef<'sql','postgres'>" (and re-add the
TargetPackRef import), then keep the existing postgresTargetPack declaration
that extends the base with "& { readonly __codecTypes?: PortableSqlCodecTypes }"
so the literal is type-checked for kind/familyId/targetId while still allowing
the optional __codecTypes override.
In `@packages/2-sql/5-runtime/src/codecs/encoding.ts`:
- Around line 150-172: encodeParamsAsync currently awaits each encodeParamAsync
serially which makes independent async encodings run in series; change
encodeParamsAsync to build an array of promises by mapping over plan.params and
for each index calling encodeParamAsync(paramValue, paramDescriptor, i,
registry) when paramDescriptor exists (or wrapping the raw paramValue in
Promise.resolve), then await Promise.all on that array to run encodes in
parallel, preserve original ordering, freeze the resulting array and return it;
reference functions/values: encodeParamsAsync, encodeParamAsync, plan.params,
plan.meta.paramDescriptors, ExecutionPlan, CodecRegistry.
🪄 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: d73be12e-1fe9-4aea-a3bc-ceaa32df2239
📒 Files selected for processing (29)
coverage.config.jsondocs/architecture docs/adrs/ADR 030 - Result decoding & codecs registry.mdpackages/1-framework/1-core/framework-components/src/codec-types.tspackages/1-framework/1-core/framework-components/src/exports/codec.tspackages/2-mongo-family/1-foundation/mongo-codec/src/codecs.tspackages/2-mongo-family/1-foundation/mongo-codec/test/codecs.test-d.tspackages/2-sql/2-authoring/contract-ts/src/contract-types.tspackages/2-sql/2-authoring/contract-ts/test/contract-builder.dsl.helpers.test.tspackages/2-sql/2-authoring/contract-ts/test/contract-builder.dsl.portability.test.tspackages/2-sql/2-authoring/contract-ts/test/contract-builder.dsl.types.test.tspackages/2-sql/2-authoring/contract-ts/test/helpers/column-descriptor.tspackages/2-sql/4-lanes/relational-core/src/ast/codec-types.tspackages/2-sql/4-lanes/relational-core/test/ast/codec-types.test.tspackages/2-sql/4-lanes/sql-builder/test/playground/async-codecs.test-d.tspackages/2-sql/5-runtime/package.jsonpackages/2-sql/5-runtime/src/codecs/decoding.tspackages/2-sql/5-runtime/src/codecs/encoding.tspackages/2-sql/5-runtime/src/codecs/json-schema-validation.tspackages/2-sql/5-runtime/src/exports/index.tspackages/2-sql/5-runtime/src/sql-runtime.tspackages/2-sql/5-runtime/test/json-schema-validation.test.tspackages/2-sql/5-runtime/test/seeded-secret-codec.tspackages/2-sql/5-runtime/test/sql-runtime.test.tspackages/3-extensions/sql-orm-client/src/collection-dispatch.tspackages/3-extensions/sql-orm-client/src/collection.tspackages/3-extensions/sql-orm-client/src/exports/index.tspackages/3-extensions/sql-orm-client/src/types.tspackages/3-extensions/sql-orm-client/test/async-codecs.test-d.tspackages/3-extensions/sql-orm-client/test/collection-dispatch.test.ts
✅ Files skipped from review due to trivial changes (5)
- packages/3-extensions/sql-orm-client/src/exports/index.ts
- packages/2-sql/5-runtime/src/exports/index.ts
- packages/2-sql/5-runtime/package.json
- packages/2-sql/5-runtime/test/seeded-secret-codec.ts
- packages/3-extensions/sql-orm-client/test/collection-dispatch.test.ts
🚧 Files skipped from review as they are similar to previous changes (10)
- 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/1-framework/1-core/framework-components/src/exports/codec.ts
- packages/2-sql/2-authoring/contract-ts/test/contract-builder.dsl.portability.test.ts
- packages/2-sql/2-authoring/contract-ts/test/helpers/column-descriptor.ts
- packages/1-framework/1-core/framework-components/src/codec-types.ts
- packages/3-extensions/sql-orm-client/src/collection-dispatch.ts
- packages/2-sql/5-runtime/src/codecs/json-schema-validation.ts
- packages/2-sql/5-runtime/test/json-schema-validation.test.ts
- docs/architecture docs/adrs/ADR 030 - Result decoding & codecs registry.md
| readonly codecDefinitions: { | ||
| readonly [K in keyof ScalarNames]: { | ||
| readonly typeId: ScalarNames[K] extends Codec<infer Id extends string> ? Id : never; | ||
| readonly typeId: CodecId<ScalarNames[K]> & string; | ||
| readonly scalar: K; | ||
| readonly codec: ScalarNames[K]; | ||
| readonly input: CodecInput<ScalarNames[K]>; | ||
| readonly output: CodecOutput<ScalarNames[K]>; | ||
| readonly jsType: CodecOutput<ScalarNames[K]>; | ||
| readonly outputType: CodecOutput<ScalarNames[K]>; | ||
| }; | ||
| }; |
There was a problem hiding this comment.
🧩 Analysis chain
🏁 Script executed:
#!/bin/bash
# Find consumers of the legacy `output` and the new `outputType` fields on codecDefinitions
rg -nP --type=ts -C2 '\bcodecDefinitions\b'
rg -nP --type=ts -C2 '\.outputType\b'
rg -nP --type=ts -C2 '\.codecDefinitions\b\s*\.\s*\w+\s*\.\s*output\b'Repository: prisma/prisma-next
Length of output: 50374
🏁 Script executed:
# Search for explicit access to .output and .outputType fields on codecDefinitions entries
rg -nP --type=ts "\.output\b\s*(?!\w)" | head -50
rg -nP --type=ts "\.outputType\b" | head -50Repository: prisma/prisma-next
Length of output: 6565
🏁 Script executed:
# Read the codec-types.test.ts file around the line that uses both .output and .outputType
sed -n '580,605p' packages/2-sql/4-lanes/relational-core/test/ast/codec-types.test.tsRepository: prisma/prisma-next
Length of output: 1388
🏁 Script executed:
# Search for production code (excluding tests) that accesses .output or .outputType on codecDefinitions
rg -nP --type=ts '\.output\b' --glob='!**/*.test.ts' --glob='!**/test/**' packages/2-sql/4-lanes/relational-core/src/ packages/3-targets/ packages/3-extensions/
rg -nP --type=ts '\.outputType\b' --glob='!**/*.test.ts' --glob='!**/test/**' packages/2-sql/4-lanes/relational-core/src/ packages/3-targets/ packages/3-extensions/Repository: prisma/prisma-next
Length of output: 832
🏁 Script executed:
# Read the codec-types.ts file to see how codecDefinitions is actually built
cat -n packages/2-sql/4-lanes/relational-core/src/ast/codec-types.ts | sed -n '360,490p'Repository: prisma/prisma-next
Length of output: 5431
🏁 Script executed:
# Check if there are any comments near the field definitions explaining the duplication
cat -n packages/2-sql/4-lanes/relational-core/src/ast/codec-types.ts | sed -n '365,385p'
# Also check if there's a git log mentioning these fields
cd packages/2-sql/4-lanes/relational-core/src/ast && git log --oneline -n 20 codec-types.ts
</parameter>Repository: prisma/prisma-next
Length of output: 1048
🏁 Script executed:
# Search across entire codebase to see if anything accesses these fields differently or has logic checking for one vs the other
rg -nP --type=ts 'codecDefinitions\.\w+\.(output|outputType)'Repository: prisma/prisma-next
Length of output: 387
Remove redundant output field from codecDefinitions — keep only outputType.
Both output and outputType (lines 374-375) have identical type CodecOutput<ScalarNames[K]> and are initialized with the same value (lines 481-482). No production code differentiates between them; only test assertions reference these fields (lines 592-593 in codec-types.test.ts), and both expect identical types. Per coding guidelines, remove parallel implementations entirely rather than maintain both. Update the interface definition, the getter implementation, and test expectations to use only outputType.
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.
In `@packages/2-sql/4-lanes/relational-core/src/ast/codec-types.ts` around lines
368 - 377, Remove the redundant `output` property from the `codecDefinitions`
structure: the interface keyed by `ScalarNames` should only expose `outputType:
CodecOutput<ScalarNames[K]>` (remove `output`), update any getter/initializer
that constructs entries in `codecDefinitions` to stop creating/assigning an
`output` field (only assign `outputType`), and update tests that assert on
`output` (e.g., in codec-types.test.ts) to assert on `outputType` instead;
ensure all references to the removed `output` symbol are eliminated and types
remain `CodecOutput<ScalarNames[K]>` where previously duplicated.
| function encodeFailure( | ||
| codec: Codec, | ||
| paramDescriptor: ParamDescriptor, | ||
| paramIndex: number, | ||
| error: unknown, | ||
| ): Error { | ||
| const label = paramLabel(paramDescriptor, paramIndex); | ||
| return runtimeError( | ||
| 'RUNTIME.ENCODE_FAILED', | ||
| `Failed to encode parameter ${label} with codec '${codec.id}': ${error instanceof Error ? error.message : String(error)}`, | ||
| { | ||
| label, | ||
| codec: codec.id, | ||
| }, | ||
| ); | ||
| } |
There was a problem hiding this comment.
Encode-side error envelope leaks codec error messages and drops cause.
Inconsistent with the PR-wide hardening on the decode side (decodeFailure in packages/2-sql/5-runtime/src/codecs/decoding.ts:96-117), which drops the codec's error.message from the human envelope and attaches the original via cause. Per PR objectives: “Redacted codec error messages from human-facing envelopes (attach original error via cause) to prevent plaintext leakage”. Codec-authored errors on the encode side can embed sensitive plaintext (e.g. seeded-secret codec, anything that encrypts a value) — this envelope will surface them through any telemetry pipeline that logs Error.message. Also missing cause, so debugger tooling loses the original chain.
🔒️ Proposed fix: bound the message and attach the original error as `cause`
function encodeFailure(
codec: Codec,
paramDescriptor: ParamDescriptor,
paramIndex: number,
error: unknown,
): Error {
const label = paramLabel(paramDescriptor, paramIndex);
- return runtimeError(
+ const envelope = runtimeError(
'RUNTIME.ENCODE_FAILED',
- `Failed to encode parameter ${label} with codec '${codec.id}': ${error instanceof Error ? error.message : String(error)}`,
+ `Failed to encode parameter ${label} with codec '${codec.id}'`,
{
label,
codec: codec.id,
},
);
+ (envelope as Error).cause = error;
+ return envelope;
}🤖 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 23 - 38, The
encodeFailure function currently injects the codec's raw error.message into the
human-facing runtimeError and omits the original error as a cause; update
encodeFailure to redact the codec error text in the user-facing message (use a
bounded/generic message like "Failed to encode parameter X") and attach the
original error as the cause property of the runtimeError (wrap non-Error values
into an Error if needed). Locate encodeFailure and adjust the runtimeError call
to supply the redacted message, keep the metadata { label, codec: codec.id },
and include the original error under a cause field so tooling and debuggers can
access the original error chain without leaking plaintext in the envelope.
| if (codec.encode) { | ||
| try { | ||
| return codec.encode(value); | ||
| const encoded = codec.encode(value); | ||
| if (encoded instanceof Promise) { | ||
| throw unexpectedAsyncEncodeFailure(codec, paramDescriptor, paramIndex); | ||
| } | ||
| return encoded; | ||
| } catch (error) { | ||
| const label = paramDescriptor.name ?? `param[${paramIndex}]`; | ||
| throw new Error( | ||
| `Failed to encode parameter ${label}: ${error instanceof Error ? error.message : String(error)}`, | ||
| ); | ||
| throw error instanceof Error && | ||
| 'code' in error && | ||
| (error as Error & { code: string }).code === 'RUNTIME.ENCODE_FAILED' | ||
| ? error | ||
| : encodeFailure(codec, paramDescriptor, paramIndex, error); | ||
| } | ||
| } |
There was a problem hiding this comment.
Sync path leaves a rejecting Promise dangling.
If a codec's encode() synchronously returns Promise.reject(...), control reaches Line 75 and throws unexpectedAsyncEncodeFailure. The original encoded promise is never awaited or .catch-ed, so Node will emit an unhandledRejection (and may terminate the process under --unhandled-rejections=strict). The async helper decodeField already mitigates this with promise.catch(() => {}); (decoding.ts:170); apply the same here before throwing.
🛡️ Proposed fix
const encoded = codec.encode(value);
if (encoded instanceof Promise) {
+ encoded.catch(() => {});
throw unexpectedAsyncEncodeFailure(codec, paramDescriptor, paramIndex);
}
return encoded;📝 Committable suggestion
‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.
| if (codec.encode) { | |
| try { | |
| return codec.encode(value); | |
| const encoded = codec.encode(value); | |
| if (encoded instanceof Promise) { | |
| throw unexpectedAsyncEncodeFailure(codec, paramDescriptor, paramIndex); | |
| } | |
| return encoded; | |
| } catch (error) { | |
| const label = paramDescriptor.name ?? `param[${paramIndex}]`; | |
| throw new Error( | |
| `Failed to encode parameter ${label}: ${error instanceof Error ? error.message : String(error)}`, | |
| ); | |
| throw error instanceof Error && | |
| 'code' in error && | |
| (error as Error & { code: string }).code === 'RUNTIME.ENCODE_FAILED' | |
| ? error | |
| : encodeFailure(codec, paramDescriptor, paramIndex, error); | |
| } | |
| } | |
| if (codec.encode) { | |
| try { | |
| const encoded = codec.encode(value); | |
| if (encoded instanceof Promise) { | |
| encoded.catch(() => {}); | |
| throw unexpectedAsyncEncodeFailure(codec, paramDescriptor, paramIndex); | |
| } | |
| return encoded; | |
| } catch (error) { | |
| throw error instanceof Error && | |
| 'code' in error && | |
| (error as Error & { code: string }).code === 'RUNTIME.ENCODE_FAILED' | |
| ? error | |
| : encodeFailure(codec, paramDescriptor, paramIndex, error); | |
| } | |
| } |
🤖 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 71 - 85, When a
codec.encode call returns a Promise that may already be rejected, avoid leaving
an unhandled rejection by attaching a noop catcher before throwing; inside the
encode path where you detect encoded instanceof Promise (in the block around
codec.encode and the unexpectedAsyncEncodeFailure throw), call encoded.catch(()
=> {}) to swallow the eventual rejection, then throw
unexpectedAsyncEncodeFailure(codec, paramDescriptor, paramIndex); keep the
existing catch logic that maps errors to encodeFailure(codec, paramDescriptor,
paramIndex, error) intact.
wmadden
left a comment
There was a problem hiding this comment.
Code Review Response — Async codec runtime support
We recommend not merging this direction. The full alternative design proposal is in the follow-up comment below.
Decision
We recommend not merging this direction.
The objection is to the API shape, not the implementation quality. PR #375 extends a sync-first codec contract with a per-codec async opt-in. To preserve the synchronous hot path under that shape, the public Codec interface gains a discriminator, the type system gains conditional return types, the SQL runtime gains a dual-code-path mechanism, and the ORM client splits its read-side and write-side type maps. None of that machinery is reversible without breaking changes once shipped.
The companion design (in the follow-up comment below) makes the public Codec interface uniform, lets the runtime always-await, and contains the cost of supporting both modes inside the runtime's two codec invocation loops. It ships the same user-visible capability with substantially less of the machinery above, and it leaves the door open to a synchronous fast path as a non-breaking additive opt-in.
The security work in this PR (envelope redaction, validator-message redaction, the seeded-secret-codec test fixture, JSON-Schema failure shape, include-aggregate test patterns) is independent of the async-shape decision and translates to either design — a separate concern from the architectural choice argued here.
What the choice looks like
The clearest way to see the difference is to look at what a codec author writes and what a query consumer sees.
Today's PR. Async codecs declare themselves and the read surface differs from the write surface:
codec({
id: 'pg/secret@1',
encode: async (v) => encrypt(v),
decode: async (w) => decrypt(w),
runtime: { encode: 'async', decode: 'async' },
});
const user = await db.User.where({ id: 1 }).first();
const secret: Promise<string> = user!.secret;
await secret;
await db.User.where({ id: 1 }).update({ secret: 'plaintext' });Proposed alternative. Authors write whatever shape they like; consumers see plain values uniformly:
codec({
id: 'pg/secret@1',
encode: async (v) => encrypt(v),
decode: async (w) => decrypt(w),
});
codec({
id: 'pg/text@1',
encode: (v) => v,
decode: (w) => w,
});
const user = await db.User.where({ id: 1 }).first();
const secret: string = user!.secret;
await db.User.where({ id: 1 }).update({ secret: 'plaintext' });The runtime awaits codec results before the row yields. There's no runtime flag on codecs, no Promise<T> on row fields, and no read/write type-map split.
Why we want a different shape
The argument is in four moves: direction (which way is reversible?), where the cost lives, where the seam falls, and what the sync path actually saves.
Direction: async-first preserves both options; sync-first forecloses async
Async machinery can dispatch sync codecs — the factory lifts (v) => v to async (v) => v at construction time, and the runtime always awaits. Sync machinery can't dispatch async codecs without growing a discriminator. So:
- Sync-first → adding async is exactly what PR #375 does. A
runtimeflag on the publicCodecinterface, aTRuntimegeneric, conditional return types, a dual-path runtime, a read/write type-map split, aninstanceof Promisecheck per cell, a Mongo type-pin. That shape lives on the public surface and can't be unwound without breaking changes. - Async-first → adding a sync fast path is purely additive. A
codecSync()factory entry, an invisible brand symbol, a predicate, and a fast-path branch each indecodeFieldandencodeParam. No public type changes, no codec author migrates, no existing call site breaks. The brand is invisible to consumers.
Both paths arrive at the same hot-path performance characteristic eventually — sync codec invocation in the runtime's tight loops. The difference is what the trip costs in mechanism and what's reversible. Async-first costs one Promise allocation per cell today (bounded by the Performance assumptions section of the follow-up comment) and is reversible. Sync-first costs PR #375's machinery today and is permanent.
Where the cost lives
PR #375 distributes the cost of supporting both sync and async codecs across the public interface and every consumer:
runtimefield on the publicCodecinterface;TRuntimegeneric.- Conditional return types (
Promise<T> | T) onencode/decode. - ORM client read-side type map splits into "possibly Promise" vs. "plain" forms (
FieldOutputTypesdistinct fromFieldInputTypes). - SQL runtime classifies queries via a plan-walker, caches the result in a
WeakMap, and dispatches to a separate async path. - Decode branches on
instanceof Promiseper cell and silences floating rejections. - Mongo locked out at the type level via
TRuntime: undefinedand a defensive@ts-expect-errortest.
The bill is paid by every contract author, the ORM client's type infrastructure, every runtime path that touches a codec, and the Mongo runtime author — not by the codec author writing a sync function. And it's paid whether or not any async codec is in use.
The alternative localizes the cost to one Promise allocation per cell, paid only for cells we actually decode, removable later via the walk-back. No discriminator on the public interface, no type-map split, no plan-walker, no Mongo type-pin.
Where the seam falls
The codec interface has five methods that sit on either side of a natural boundary that predates async:
- Query-time (
encode,decode): runs per-row, per-statement, against wire values. This is where async actually matters — encryption, KMS-resolved keys, deferred lookups, anything that crosses an IO boundary on every row. - Build-time (
encodeJson,decodeJson,renderOutputType): runs at contract-emission, contract-load, and codegen time, against the contract artifact. Pulling async into these would forcevalidateContractto become async with downstream ripples through client construction, in service of no codec we have or expect.
PR #375 doesn't draw the line there. Its line runs within the query-time methods: each codec opts in via runtime: { encode: 'async', decode: 'async' }, and the type system threads a discriminator through every query-time call site. The complexity in the public interface, the runtime, and the type maps is in service of preserving that within-query-time asymmetry — not in service of any structural boundary the codebase already had.
The alternative drops the asymmetry: query-time methods are uniformly Promise-returning at the boundary, the factory lifts sync author functions, and the runtime always awaits. Build-time methods stay synchronous as they were. The seam the design picks is the seam that was already there.
What does the sync path actually save?
A Promise allocation per cell. Microtask scheduling is batched by Promise.all to one tick per row regardless of cell count, so the latency overhead is one tick per row plus the codec body work. The cost lives in allocation pressure under sustained high throughput, not in per-call latency, and not in stack traces (the error envelope already redacts codec messages and routes the original through cause) or streaming (the runtime already exposes AsyncIterableResult).
That allocation pressure is real, and at sufficient scale it will become load-bearing for the cell-count-dominant codecs (text, int, uuid, similar passthroughs). It's also exactly what the sync fast-path opt-in eliminates, additively, without breaking anything. Until then the cost is bounded by actual decode work; PR #375's mechanisms are paid whether or not any async codec is ever defined.
Recommendation
- Pause merging this PR.
- Read the alternative design in the follow-up comment below.
- If we agree on the alternative, implement it on a fresh branch off
main. The security work and the test patterns (envelope redaction, validator-message redaction, theseeded-secret-codecfixture, include-aggregate cases, JSON-Schema failure shape) translate directly — they're independent of the async-shape decision. - When the always-async overhead becomes load-bearing under production workloads — at scale, for the cell-count-dominant codecs, it will — add the sync fast path as the additive opt-in described in the alternative.
This isn't a reflection of the implementation quality. The recommendation is about direction, made before more code is built on a shape we don't think we should ship.
Alternatives considered
- Merge the PR as-is and accept the dual-path design. Rejected for the reasons above: the cost lives on the public interface, the seam runs through the wrong place, and the directional asymmetry makes this the more expensive entry point.
- Refactor PR #375 in place to address only the smaller concerns (test gaps, ADR redaction policy, validator-message assertions). Doesn't address the architectural concern; we'd be polishing a shape we don't think we should ship.
- Ship a sync fast-path opt-in alongside the single-path design today (
codec()+codecSync()+ predicates). Premature now but expected later. We don't yet have a load-bearing system where the always-async overhead shows up as a real cost, and the addition is purely additive when we land it. Ship the simpler shape now; layer the optimization on the codecs that need it when production tells us which ones do. - Have the factory auto-detect sync vs async (e.g., via
fn.constructor.name === 'AsyncFunction'). Unsafe — sync-shaped functions that return Promises (caching layers, conditional async paths) get misclassified silently. The reliable form of detection isinstanceof Promiseper call, which is what the PR's dual-path runtime already does; auto-detection at factory time doesn't reduce complexity, only relocates it. - Use a different spelling for the discriminator (a brand symbol on the public type, a
kindfield, a method-name convention likeencodeAsync). Cosmetic — the underlying problem of a sync/async split threaded through the type system at every query-time call site is the same regardless of how the discriminator is spelled.
Codec Async Support — Single-Path DesignFollow-up to the rejecting review above. Eventual home: ADR superseding the async-runtime parts of ADR 030. ContextCodecs translate between database wire values and the values consumers see. The codec runtime today is purely synchronous: every codec method runs on the call stack of the query that invoked it, and rows are assembled out of plain values. A small but real class of codecs needs asynchronous work — KMS-resolved encryption keys, externally-resolved secrets, deferred reference lookups, secret rotation. These are minority cases, but they're concrete enough that the runtime needs to accommodate them. This document specifies a design for adding asynchronous codec support. Other shapes were weighed; their evaluation is in Alternatives considered. The rationale for the shape proposed here is in Why this shape. DecisionA single-path codec runtime:
We accept a small per-codec runtime overhead — one Promise allocation per cell, with microtask cost batched per row via When that overhead becomes load-bearing for the cell-count-dominant codecs (the pass-through built-ins for native database types — Landing always-async today and layering the sync fast path on when we need it preserves both options as the system evolves. That's the two-way door this proposal is built around. Performance assumptionsThe design's tradeoff calculus rests on three claims about how Node/V8 handle async machinery. They're stated up front so reviewers can stress-test them once; if any don't hold, the rest of the doc's reasoning needs revisiting. The empirical claims below are grounded in V8/Node behavior. We target Node, Bun, and Deno; Deno is V8 (claims apply directly), Bun is JavaScriptCore-derived with documented fast-async parity goals (claims are presumed to apply but unverified for the specific behaviors below). 1.
|
| Resource | Cost | Source |
|---|---|---|
| Memory | N Promise allocations (one per cell) | Claim 1 |
| Latency | 1 microtask tick per row plus the codec body work | Claim 3 (Promise.all batches resumption) |
| CPU per cell (overhead) | Negligible — Promise alloc + GC handling | Claim 2 (resolved-await is one tick) |
The load-bearing cost at sustained high throughput is allocation pressure (cells decoded × Promise size), not microtask scheduling or per-call latency. That's the cost the future sync fast-path opt-in eliminates for the codecs that dominate.
Where these claims could be wrong
- Bun's microtask and resolved-await behavior. Bun's async machinery is a different implementation from V8's. The claims above are presumed to translate but are not verified against JavaScriptCore for the specific microtask and resolved-await behaviors under sustained-throughput workloads. If a deployed Bun runtime shows a materially different cost ledger for the same workload, the structural design (always-async at the boundary, factory-lift, walk-back) is unaffected, but the per-cell cost numbers would need re-grounding for that runtime.
- Older Node versions. The fast-async optimization landed in Node 10+. The repo's
engines.nodeenforces a much higher floor, so this is settled for our Node targets. - Allocation pressure under sustained high throughput. This is the expected cost trajectory. Industry-style decode benchmarks (e.g. the Drizzle benchmark) push sustained per-cell decode rates where Promise allocation becomes a measurable fraction of CPU time, GC reclaim work climbs, and the heap can fill faster than the young generation can keep up. The design accepts this — when the load-bearing case shows up, the response is the sync fast-path opt-in described in Why we trust this design, targeted at the cell-count-dominant codecs. The walk-back is the answer; the design itself doesn't need to.
These claims are documented; we have not built a microbenchmark suite. Reviewers can verify against the V8 design docs or a one-off measurement if needed.
Why this shape
The design optimizes for one property: the cost of supporting async codecs is contained at the runtime invocation site, not distributed across the public interface, the type system, or consumer-facing types. Two design choices flow from that property — the seam between query-time and build-time methods, and the uniform Promise-returning shape on the query-time side.
The seam
The codec interface has five methods that sit on either side of a natural boundary that predates the async question:
- Query-time (
encode,decode): runs per-row, per-statement, against wire values. This is where async actually matters — encryption, KMS-resolved keys, deferred lookups, anything that crosses an IO boundary on every row. - Build-time (
encodeJson,decodeJson,renderOutputType): runs at contract-emission, contract-load, and codegen time, against the contract artifact. Pulling async into these methods would forcevalidateContractto become async, with downstream ripples through client construction — a much larger change in service of no codec we have or expect.
The seam is structural; the async question lands cleanly on it. The public interface treats those two groups uniformly: query-time methods are Promise-returning at the boundary; build-time methods are synchronous.
The cost lives at the runtime, not on the public surface
Async codecs introduce per-cell async work; sync codecs do not. Supporting both in the same runtime requires something to bridge that gap. The design's central choice is to put the bridge in one specific place — the runtime's two codec invocation loops (encodeParam, decodeField) — and leave the rest of the system uniform.
Concretely:
- The factory lifts sync author functions to Promise-shaped methods at construction time. Authors don't annotate; the runtime sees one shape.
- The runtime always awaits — uniform dispatch, no per-codec branching at invocation sites.
- The public
Codecinterface is identical across codecs — same method signatures, no per-codec async marker, no generic discriminator on async-ness, no conditional return types. - Consumer-facing types (row shapes, ORM input/output maps) are plain
Tregardless of which codec produced the value.
The runtime cost of this choice is bounded — one Promise allocation per cell, microtask cost batched per row via Promise.all — and grounded by Performance assumptions. It scales linearly with decode work and disappears for the codecs that adopt the synchronous fast path described in Why we trust this design.
What this preserves
Because the cost lives at the runtime invocation site:
- Row types are plain
T, regardless of which codec produced them. - Adding async to an existing codec is non-breaking — consumer code doesn't change.
- ORM client read and write types share one type-map.
- The Mongo and SQL families share the same
Codecshape. - The runtime has one encode path and one decode path.
- Adding a new async codec is a
codec({ encode: async, decode: async })call with no annotations.
These properties hold whether the codec population is 1% async, 10% async, or 99% async; nothing in the public interface scales with the async population.
Surface examples
Codec author
A trivial sync codec:
codec({
id: 'pg/text@1',
targetTypes: ['text'],
encode: (v: string) => v,
decode: (w: string) => w,
encodeJson: (v) => v,
decodeJson: (j) => j as string,
});A real async codec:
codec({
id: 'pg/secret@1',
targetTypes: ['text'],
encode: async (v: string) => encrypt(v),
decode: async (w: string) => decrypt(w),
encodeJson: (v) => v,
decodeJson: (j) => j as string,
});The spec is the methods themselves — no extra metadata, no opt-in flag, no factory variant. The factory accepts both shapes and produces a Codec whose query-time methods are Promise-returning.
Query consumer
const user = await db.User.where({ id: 1 }).first();
const id: number = user!.id;
const secret: string = user!.secret;
await db.User.where({ id: 1 }).update({ secret: 'new-plaintext' });
for await (const row of db.User.where({ active: true }).all()) {
console.log(row.secret);
}Row fields are plain values regardless of which codec produced them. .all() already returns an AsyncIterableResult<Row> that's both await-able (collects to an array) and for await-iterable (streams row-by-row); the runtime awaits all codec work for a row before yielding it. Inputs to write/filter/cursor surfaces are plain values.
Design
The codec interface
The public Codec interface is uniform on each side of the build-time vs. query-time seam: query-time methods are Promise-returning at the boundary; build-time methods are synchronous.
export interface Codec<
Id extends string = string,
TTraits extends readonly CodecTrait[] = readonly CodecTrait[],
TWire = unknown,
TInput = unknown,
TOutput = TInput,
> {
readonly id: Id;
readonly targetTypes: readonly string[];
readonly traits?: TTraits;
// Query-time: per-row, async-capable, factory lifts sync author functions.
encode(value: TInput): Promise<TWire>;
decode(wire: TWire): Promise<TOutput>;
// Build-time / contract-load / codegen: synchronous.
encodeJson(value: TInput): JsonValue;
decodeJson(json: JsonValue): TInput;
renderOutputType?(typeParams: Record<string, unknown>): string | undefined;
}encode and decode are both required — every codec has well-defined behaviour in both directions, so consumers never have to ask "is method X defined?" The factory accepts each as sync or async; see The factory. encodeJson and decodeJson are required for the same reason; renderOutputType is optional because it only fires for codecs that participate in codegen of richer output types. The Mongo codec module exports the same Codec interface — see Cross-family portability.
The factory
The factory accepts encode and decode as either sync or async author functions and lifts sync ones to Promise-shaped methods. encode is optional in the spec — when omitted, the factory installs an identity passthrough — but always present on the constructed Codec. The build-time methods are passed through as written.
export function codec<I, W, O>(spec: {
id: string;
targetTypes: readonly string[];
traits?: readonly CodecTrait[];
encode?: (value: I) => W | Promise<W>;
decode: (wire: W) => O | Promise<O>;
encodeJson: (value: I) => JsonValue;
decodeJson: (json: JsonValue) => I;
renderOutputType?: (typeParams: Record<string, unknown>) => string | undefined;
}): Codec<…> {
// When `encode` is omitted, the codec is declaring "input value is the wire value",
// so I and W are interchangeable for this codec. The cast is the type-system
// expression of that declaration.
const userEncode = spec.encode ?? ((value: I) => value as unknown as W);
return {
...spec,
encode: async (value) => userEncode(value),
decode: async (wire) => spec.decode(wire),
};
}The identity default for encode is a deliberate cast — codecs that omit encode are by definition declaring "the input value is already the wire value," so I and W are interchangeable for that codec. The factory's job is to normalize the query-time methods: every constructed Codec has both encode and decode, both Promise-returning, regardless of how the author wrote the spec. The runtime sees one shape on the query-time side; the author writes whichever shape is natural per method.
The runtime
Encoding parameters
encodeParams is async and dispatches all parameter codecs concurrently via Promise.all. Because encode is required on the constructed Codec, the runtime never has to check for its presence — codecs that don't transform the wire value got an identity encode from the factory. Errors are wrapped as RUNTIME.ENCODE_FAILED with { label, codec, paramIndex }; the codec's original error is on cause.
export async function encodeParams(
paramDescriptors: readonly ParamDescriptor[],
args: readonly unknown[],
registry: CodecRegistry,
): Promise<readonly unknown[]> {
return Promise.all(
paramDescriptors.map((desc, i) => encodeParam(desc, args[i], i, registry)),
);
}Promise.all matters here even when most codecs are sync underneath: every lifted-sync encode resolves on the next microtask tick, and a sequential for await would serialize those ticks for every parameter on every statement. Issuing them concurrently lets the microtask queue drain in one pass per statement. For statements with N parameters that's O(1) ticks instead of O(N). There is no plan-walker, no WeakMap cache, no separate sync and async entry points, and no defensive guard for sync codecs returning Promises (the factory always returns Promise-shaped methods, so the footgun doesn't exist).
Decoding rows
decodeRow is async. It decodes every cell concurrently via Promise.all, then assembles the resolved values into a plain row:
export async function decodeRow(
row: RawRow,
projection: Projection,
registry: CodecRegistry,
): Promise<Row> {
const decoded = await Promise.all(
projection.map(([alias, fieldSpec]) =>
decodeField(row[alias], fieldSpec, registry),
),
);
const out: Row = {};
projection.forEach(([alias], i) => {
out[alias] = decoded[i];
});
return out;
}Same reasoning as encodeParams: dispatching the field codecs concurrently keeps the per-row microtask cost at O(1) ticks regardless of column count.
decodeField is single-armed: call the codec, await, run JSON-Schema validation on the resolved value, return the plain value:
async function decodeField(
rawValue: unknown,
fieldSpec: FieldSpec,
registry: CodecRegistry,
): Promise<unknown> {
const codec = registry.get(fieldSpec.codec);
if (codec === undefined) return rawValue;
let decoded: unknown;
try {
decoded = await codec.decode(rawValue);
} catch (err) {
throw decodeFailure(codec, fieldSpec, rawValue, err);
}
if (fieldSpec.jsonSchema) {
validateJsonValue(decoded, fieldSpec.jsonSchema, {
table: fieldSpec.table,
column: fieldSpec.column,
direction: 'decode',
codecId: codec.id,
redactValues: shouldRedact(codec, fieldSpec),
});
}
return decoded;
}shouldRedact is the redaction-trigger predicate; its concrete spelling is independent of this design and lives with the redaction policy itself. What matters here is that the row resolves fully before yielding — every codec is awaited, and the value handed to JSON-Schema validation is the resolved decoded value, not a Promise.
Streaming
AsyncIterableResult<Row> yields one row at a time. Each row's fields are plain values. Consumers iterate with for await.
Read/write type surfaces
Outputs on DefaultModelRow / InferRootRow are plain T (the runtime awaited before yielding). Inputs on DefaultModelInputRow / MutationUpdateInput / CreateInput / UniqueConstraintCriterion / ShorthandWhereFilter are also plain T. The read and write surfaces share a single field type-map.
If a contract author needs to differentiate input/output shapes for unrelated reasons (e.g., a codec that decodes to a richer type than it accepts on input), that's a separate type-mapping feature in the contract DSL — orthogonal to async.
Validation at boot
validateContract stays synchronous. It calls decodeJson per field to canonicalize column defaults stored in the contract artifact (see validate.ts). Those decoded defaults flow into migration tooling (DDL emission, schema-diff comparison) — they do not bypass encode to become wire values. Runtime mutation defaults that do end up as INSERT parameters live in execution.mutations.defaults, where a generator produces a value at write time and the row then flows through encode like any other parameter. The path that needs async (encryption, KMS, deferred lookups) is the encode path, and that's already covered.
If a future codec genuinely needs decodeJson to resolve a remote reference at contract-load time, the same factory-lift technique applies: decodeJson becomes Promise-returning at the boundary, the factory accepts sync or async, and validateContract becomes async — with downstream changes to client construction (postgres({...}) and equivalents). The change is contained and additive; we just don't carry it now because no codec needs it.
Cross-family portability
Codecs in both families — SQL and Mongo — operate identically against this contract. That's a hard requirement of the design. The Mongo Codec interface is the same shape as the SQL one: same generic parameters, same query-time Promise-returning methods, same synchronous build-time methods, same factory entry point. A codec author writes one codec({...}) call; the resulting object is usable in either family's runtime.
The Mongo runtime's internal implementation (whether it follows the same Promise.all-per-row pattern as SQL or uses a different concurrency strategy) is separable from the codec interface and is a Mongo-runtime decision. Whatever it picks, the codec contract is the same.
Why we trust this design
The single property worth establishing is that the design doesn't paint the system into a corner if always-async runtime overhead ever becomes a real cost. The synchronous fast path is non-breaking to add, additive on top of the design above, and surgical in scope.
The walk-back is purely additive
When always-async overhead becomes a load-bearing cost — and we know it will, at sufficient scale, for the cell-count-dominant codecs — a sync fast path is a non-breaking addition. We ship a new factory entry that requires sync return types and stamps an invisible brand on the codec, plus predicate functions that hot-path consumers can opt into:
export function codecSync<I, W, O>(spec: {
encode?: (value: I) => W; // sync return required at the type level
decode: (wire: W) => O;
…
}): Codec<…> & SyncBrand;
export function isSyncEncoder<…>(c: Codec<…>): c is SyncEncoderCodec<…>;
export function isSyncDecoder<…>(c: Codec<…>): c is SyncDecoderCodec<…>;What actually changes when we ship the fast path
The candidates for the sync fast path are the cell-count-dominant codecs — overwhelmingly the pass-through built-ins for native database types: pg/text@1, pg/int@1, pg/uuid@1, pg/bool@1, pg/timestamptz@1, pg/numeric@1, the rest of the numerics. Maybe 10–20 codec definitions across the built-in codec packages.
What changes:
- Codec definitions for built-ins: each one swaps
codec({ ... })forcodecSync({ ... })in its definition file. ~10–20 single-line edits. - Runtime hot loops:
decodeFieldandencodeParameach gain one fast-path branch —if (isSyncDecoder(codec)) { decoded = codec.decode(rawValue); } else { decoded = await codec.decode(rawValue); }. Two branches, total.
What doesn't change:
- The public
Codecinterface — no new fields, no new generic parameters, no conditional return types. - Any consumer of
Codec— contract loading, ORM client, query-plan compilation, dispatch. - Any contract author who isn't writing a built-in codec.
- Any application using the ORM client — row shapes are still plain
T, write surfaces are still plainT, error envelopes are unchanged. - Streaming semantics (
AsyncIterableResult).
Adding a new codec that wants the fast path is one factory-call swap (codec → codecSync); no consumer of that codec needs to know. Adding a new async codec later is a codec({ encode: async, decode: async }) call with no annotations — also consumer-invisible. The brand is visible only to runtime code that explicitly tests for it; everything else sees a uniform Codec shape.
Constraints to preserve the walk-back
The walk-back stays a two-way door as long as the design today doesn't lock in the following:
- No sync/async marker on the public
Codecinterface (noruntime, nokind, no equivalent). - One factory function:
codec(). NocodecSync/codecAsyncvariants today. - No exported predicates (no
isSyncEncoder/isAsyncDecoder) until they're needed. - No conditional return types tied to async-ness on the public interface.
- No
TRuntimegeneric onCodec. - Documentation frames the author surface as "you may write sync or async; the factory accepts both" — not as "codec functions return Promises."
- Public guarantees are framed in terms that don't depend on async (errors are wrapped in the standard envelope, not "errors arrive via promise rejection").
Each constraint is a non-action: choose minimalism over premature flexibility.
Implementation outline
A sketch sufficient to scope the work; not a step-by-step plan. The work spans the codec interface, factory, SQL runtime, ORM client types, and Mongo codec module — roughly twelve file-level changes, building from main.
- Branch off
main. - Codec interface (packages/1-framework/1-core/framework-components/src/codec-types.ts): the public
Codec<Id, Traits, Wire, Input, Output>shape with query-time methods (encode,decode) returningPromise<...>and synchronous build-time methods (encodeJson,decodeJson,renderOutputType).encodeanddecoderequired;renderOutputTypeoptional. - Codec factory (packages/2-sql/4-lanes/relational-core/src/ast/codec-types.ts): accepts
encodeanddecodeas eitherT => UorT => Promise<U>and lifts sync ones viaasync (x) => fn(x).encodeis optional in the spec (identity default);decodeis required. Build-time methods are passed through as written. - Runtime encoding (packages/2-sql/5-runtime/src/codecs/encoding.ts):
encodeParamsis async and dispatches all parameter codecs concurrently viaPromise.all. Errors wrapped asRUNTIME.ENCODE_FAILED. - Runtime decoding (packages/2-sql/5-runtime/src/codecs/decoding.ts):
decodeRowis async and dispatches per-cell viaPromise.all.decodeFieldis single-armed: codec → await → JSON-Schema validation → plain value. Errors wrapped asRUNTIME.DECODE_FAILED. - JSON-Schema validation (packages/2-sql/5-runtime/src/codecs/json-schema-validation.ts):
validateJsonValueruns against the codec's declared JSON schema;redactErrorMessageapplies the redaction policy when triggered. The redaction-trigger spelling is independent of this design. - SQL runtime entry (packages/2-sql/5-runtime/src/sql-runtime.ts): one async path per direction; no per-query plan-walking for codec async-ness.
- ORM client types (packages/3-extensions/sql-orm-client/src/types.ts): one type-map covers both input and output sides; row types and write surfaces both expose plain
T. - ORM dispatch (packages/3-extensions/sql-orm-client/src/collection-dispatch.ts): per-row decoding awaits uniformly. Single-query include precomputation and multi-query stitching are independent of the async work.
- Mongo codec & runtime (packages/2-mongo-family/1-foundation/mongo-codec/src/codecs.ts, and the Mongo runtime entry points): Mongo codecs adopt the same
Codecshape, the same factory, and the same Promise-returning query-time methods. The Mongo runtime's internal codec invocation pattern is its own decision; the codec contract is identical to SQL's. - Tests: cross-family parity tests assert the same codec module works against both SQL and Mongo runtimes. Per-method tests cover the sync-and-async forms accepted by the factory. A seeded-secret-codec fixture exercises a realistic crypto path end-to-end (the redaction policy in the runtime is independent of the async-shape decision but verified by these tests).
- ADR: a new ADR (or update to ADR 030 if appropriate) documenting the single-path query-time design, the cross-family portability requirement, and the build-time vs. query-time seam.
Acceptance criteria
The design is correct when:
Codec interface and factory:
- The public
Codecinterface is uniform across codecs:encodeanddecodeare required and Promise-returning at the boundary;encodeJsonanddecodeJsonare required and synchronous;renderOutputTypeis optional and synchronous. The interface carries no per-codec async marker on its public type. - There is exactly one factory function,
codec(). Authors may omitencodefrom the spec; the factory installs an identity default. The factory acceptsencodeanddecodein either sync or async form and produces aCodecwhose query-time methods are Promise-returning. - A codec author can write
codec({ encode: (v) => v, decode: (w) => w, encodeJson, decodeJson })with sync functions and the codec works through the runtime; replacing the query-time functions withasync (...)versions also works without further changes.
Runtime:
- The runtime has one encoding path and one decoding path; both are async and dispatch codec work concurrently via
Promise.all. - Rows yielded by the runtime have plain field values. No promise-valued fields reach user code.
validateContractstays synchronous; client construction (postgres({...})and equivalents) is unchanged.- Encode and decode failures are wrapped in the standard envelope (
RUNTIME.ENCODE_FAILED/RUNTIME.DECODE_FAILED) with the original error reachable viacause.
Cross-family parity:
- A given
codec({...})value is structurally usable in both SQL and Mongo runtimes. The Mongo codec module exports the sameCodecinterface as the SQL codec module. A test exists that imports a single codec module and exercises it against both runtimes.
Documentation and walk-back preservation:
- The relevant ADR documents the single-path query-time design, the cross-family portability requirement, and the build-time vs. query-time seam.
- Adding
codecSync()+isSyncEncoder()/isSyncDecoder()predicates as a future opt-in is non-breaking: no existing codec author migrates, no call site breaks, no public type changes.
Open questions
- Mongo runtime invocation pattern. Mongo codecs adopt the same
Codecinterface as SQL (a hard requirement, see Cross-family portability). Whether the Mongo runtime invokes them via the samePromise.all-per-row pattern as SQL or uses a different internal concurrency strategy is a Mongo-runtime decision, not a codec-contract decision. Both runtimes see the same Promise-returning query-time methods either way. - Async build-time methods, if ever needed. Not in scope today. If a codec ever needs
decodeJsonto resolve a remote reference at contract-load time, the same factory-lift technique used forencode/decodeextends todecodeJson: factory accepts sync or async, public boundary becomes Promise-returning,validateContractbecomes async, and client-construction call sites integrate the await. The build-time vs. query-time seam stays in place; the change is contained when we need it. We don't pull it in now because no codec needs it, andvalidateContractgoing async has a wider blast radius than this branch should carry.
Alternatives considered
- Per-codec async opt-in. Each codec declares whether its query-time methods are sync or async via a discriminator (e.g., a
runtimeflag), threaded through the type system as a generic parameter, with conditional return types onencode/decode. The runtime branches on the flag at dispatch time; the synchronous hot path is preserved. This is the shape PR #375 implements. The objection is summarized in code-review-response.md; it lands the cost of supporting both modes on the public interface, the type system, and the ORM client's type maps, where the design above localizes the cost to the runtime invocation site. - Have the factory auto-detect sync vs async. Unsafe — sync-shaped functions that return Promises (caching layers, conditional async paths) get misclassified silently. The reliable form of detection (
instanceof Promiseper call) just relocates the per-cell branching from a marker check to a value check; it doesn't reduce complexity. - Ship the sync fast-path opt-in alongside the single-path design today. Premature now but inevitable later. We don't yet have a load-bearing deployment where the always-async overhead shows up as a real cost, and the addition is purely additive when we land it. Ship the simpler shape now; layer the optimization on the codecs that need it when production (or a benchmark like the Drizzle decode benchmark) tells us which ones do.
- Use an interface-and-predicate split today (e.g.,
SyncEncoder | AsyncEncoderwithisAsyncEncoderpredicate). The interface split still requires a runtime discriminator; it's the same dual-path complexity sealed under a nicer abstraction. The single-path design has zero discriminators and is the simpler shape. Predicates can be added in the walk-back without committing to them now. - Different spelling for the discriminator (a brand symbol on the public type, a
kindfield, a method-name convention likeencodeAsync). Cosmetic; the underlying property is the same — async-ness becomes part of the public surface.
Make the deferred-test comments self-contained: describe what each it.skip would assert under the always-await runtime without referring to a historical PR. ADR 204 already tracks the redaction follow-up referenced by the json-schema-validation case.
Summary
Validation
Deferred
Summary by CodeRabbit
New Features
Bug Fixes
Documentation
Tests
Chores