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

fix(extension-arktype-json, sql-runtime): correctness gaps from ADR 208 landing - #418

Merged
wmadden merged 31 commits into
mainfrom
fix/arktype-json-runtime-correctness
May 12, 2026
Merged

wmadden merged 31 commits into
mainfrom
fix/arktype-json-runtime-correctness

Conversation

@jkomyno

@jkomyno jkomyno commented May 4, 2026 •

Copy link
Copy Markdown
Contributor

Focused follow-up to #402. This PR fixes the arktype-json runtime path that ADR 208 exposed: Postgres writes need runtime cast metadata, Postgres reads need to tolerate driver-preparsed jsonb, codec errors need to preserve stable runtime envelopes, and the docs need to say what no-emit can actually type today.

Changes

  • Arktype-json wire behavior: Widened the codec wire type from string to string | JsonValue and normalized both raw JSON text and driver-preparsed JSONB values on decode. The previous JSON.parse(wire) assumption was wrong because pg returns jsonb as JavaScript values by default. Decode and decodeJson are now the schema-validation boundary; encode intentionally stays JSON.stringify only, because schema-validating on encode would make the codec parameter-dependent while params still carry only codecId. Decode also preserves "…"-bounded strings byte-exact (previously the isJsonStringText heuristic silently unwrapped them, truncating user data whose literal first/last characters were ").
  • Runtime codec metadata: Registered the arktype-json metadata shim on the runtime descriptor through types.codecTypes.codecDescriptors, and gave it meta.db.sql.postgres.nativeType = 'jsonb'. The old "emit-only" shape was incomplete: the Postgres renderer reads codec metadata at runtime to decide whether $N::jsonb casts are required, so the first arktype-json write or filter could fail before codec dispatch even ran.
  • Parameterized encode dispatch: The runtime codec registry continues to reject ambiguous multi-instance forCodecId(codecId) lookups for parameterized codecs (e.g. two vector(N) columns or two arktypeJson(schema) columns with different schemas under the same id). Encode-time dispatch routes through forColumn(table, column) per-instance for parameterized ParamRefs; the validateParamRefRefs validator pass already enforces refs on every parameterized ParamRef before encode runs, so there is no ambiguous fallback path in practice. An earlier draft of this PR added a CodecDescriptor.encodeIsParamsIndependent opt-out and a registry-level fallback for it; both were removed (the column-bound path is sufficient and the flag was load-bearing for no shipped codec).
  • Runtime error envelopes: Updated the encode runtime path to pass through any runtimeError-built envelope unchanged (matching the symmetric decode-side guard). The previous behavior wrapped every codec error in RUNTIME.ENCODE_FAILED, which hid stable codec-authored codes like RUNTIME.JSON_SCHEMA_VALIDATION_FAILED and double-wrapped envelopes whose details were already authored by the codec.
  • Arktype compatibility guard: Changed expression mismatch from a warning to RUNTIME.TYPE_PARAMS_INVALID and pinned arktype to ~2.1.29. A warning was too late: if ark.schema(jsonIr).expression diverges from serialized typeParams.expression, contract.d.ts may already be stale relative to the runtime schema. Failing at codec materialization is the more honest behavior.
  • Data integrity documentation: Added a "Data integrity: validate-on-decode, not on encode" section to the arktype-json README spelling out the consequence of skipping schema validation on encode — a schema-invalid write commits the row before failing on RETURNING decode — and pointing at two mitigations (withTransaction rollback, or pre-validation via schema.allows(value)).
  • Docs: Updated ADR 208, the no-emit subsystem doc, and the arktype-json README to mark parameterized no-emit output as partial. Today no-emit still resolves through the codec base output (vector(1536) becomes number[], arktypeJson(schema) becomes unknown); precise schema-shaped output comes from emitted contract.d.ts until TML-2357 lands.
  • Codec encode hot path: Split serializeToJsonSafe into serializeWire (for encode) and serializeJson (for encodeJson). The original function returned both halves, but each caller used only one; the unused JSON.parse round-trip on the encode path was pure waste (~150-250ms per 1000-param batched insert at 100KB payloads).
  • Tests: Added coverage for runtime metadata lookup, jsonb cast metadata, pre-parsed JSONB objects and string primitives, byte-exact preservation of quote-bounded strings on decode, expression mismatch hard-fail, runtime error pass-through, and the Embedding.profile ORM round trip through Postgres.

Why

The previous implementation mixed up control-plane and runtime responsibilities. It carried enough metadata for emission, but not enough metadata for Postgres lowering; it documented the intended no-emit resolver, but the resolver still uses codec base outputs; and it assumed the driver returned JSONB as strings, even though the default pg behavior is the opposite.

This version keeps those boundaries explicit. Encode stays parameter-independent until ParamRef.refs can identify the target column. Decode validates the schema because stored JSON can come from this writer, another service, manual SQL, or an older schema. Runtime metadata lives where the renderer actually reads it. The docs now distinguish shipped behavior from the remaining TML-2357 work.

Summary by CodeRabbit

  • New Features

    • arktype-json codec now accepts pre-parsed JSON objects with enhanced schema validation.
  • Documentation

    • Updated ADR 208 and no-emit workflow documentation for parameterized codec handling.
    • Added compatibility and no-emit caveats to arktype-json extension documentation.
  • Bug Fixes

    • Improved error handling for codec encoding operations.
  • Chores

    • Tightened arktype dependency version constraint.
    • Simplified environment variable handling in Cloudflare worker example.

Review Change Stack

@coderabbitai

coderabbitai Bot commented May 4, 2026 •

Copy link
Copy Markdown
Contributor

Note

Reviews paused

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

Use the following commands to manage reviews:

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

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

This PR implements parameterized codec dispatch infrastructure and overhauls the arktype-json extension. It adds an encodeIsParamsIndependent flag to CodecDescriptor, enabling parameterized codecs with schema-independent encoding to fall back to codec-id dispatch. arktype-json is updated to widen wire types, split encode/decode validation boundaries, add SQL metadata, and declare params independence. Registry logic, error handling, tests, and documentation are updated accordingly. The PR also consolidates environment setup in the Cloudflare worker example.

Changes

Parameterized Codec Dispatch & arktype-json

Layer / File(s) Summary
Codec Descriptor Interface
packages/1-framework/1-core/framework-components/src/shared/codec-descriptor.ts
Add optional encodeIsParamsIndependent?: boolean flag to both CodecDescriptor<P> and CodecDescriptorImpl<TParams> to declare params-independent wire encoding.
Contract Codec Registry Logic
packages/2-sql/5-runtime/src/sql-context.ts, packages/2-sql/5-runtime/test/contract-codec-registry.test.ts
Update buildContractCodecRegistry to conditionally mark codec IDs as ambiguous only when descriptor lacks encodeIsParamsIndependent. Add tests verifying forCodecId throws without the flag and succeeds with it, while forColumn maintains per-instance dispatch.
arktype-json Wire Types & Parsing
packages/3-extensions/arktype-json/src/core/arktype-json-codec.ts
Widen ArktypeJsonCodec wire type from string to string | JsonValue. Add parseWireValue helper to normalize driver-returned pre-parsed jsonb via JSON.parse with fallback.
arktype-json Encode/Decode Split
packages/3-extensions/arktype-json/src/core/arktype-json-codec.ts
Move schema validation from encode to decode only. Update serializeToJsonSafe to throw plain Error (not runtimeError) for non-JSON-representable values. decode validates after parseWireValue; encode remains schema-independent.
arktype-json Emit Codec & Descriptor
packages/3-extensions/arktype-json/src/core/arktype-json-codec.ts
Add SQL-native-type metadata (meta.db.sql.postgres.nativeType: 'jsonb') to arktypeJsonEmitCodec. Set encodeIsParamsIndependent: true in descriptor. Change typeParams.expression mismatch from console.warn to hard runtimeError throw with RUNTIME.TYPE_PARAMS_INVALID.
arktype-json Runtime Descriptor
packages/3-extensions/arktype-json/src/exports/runtime.ts
Import arktypeJsonEmitCodec and augment arktypeJsonRuntimeDescriptor with types.codecTypes.codecInstances: [arktypeJsonEmitCodec].
Encode Error Handling
packages/2-sql/5-runtime/src/codecs/encoding.ts
Update encodeParamValue to pass through codec runtime errors with JSON_SCHEMA_VALIDATION_FAILED or ENCODE_FAILED codes unchanged; prevents double-wrapping.
arktype-json Codec Tests
packages/3-extensions/arktype-json/test/arktype-json-codec.test.ts
Expand test suite: pre-parsed jsonb objects, schema validation on decoded jsonb, JSON-safe normalization, non-representable value rejection, jsonb primitives, and factory expression mismatch enforcement.
Extension Descriptor & Registry Tests
packages/3-extensions/arktype-json/test/extension-descriptors.test.ts, packages/3-extensions/pgvector/test/manifest.test.ts
Add runtime descriptor codec instances assertions, contract registry edge-case tests for forCodecId behavior, and pgvector encodeIsParamsIndependent verification.
E2E Round-Trip Test
test/e2e/framework/test/arktype-json.test.ts
Add end-to-end test: bootstrap Postgres, load contract, insert/read Embedding with typed JSON profile via ORM, assert round-trip equality.
Architecture Documentation
docs/architecture/adrs/ADR 208...md, docs/architecture/subsystems/9. No-Emit Workflow.md, packages/3-extensions/arktype-json/README.md
Update ADR 208 dispatch trade-offs, document partial no-emit implementation status with TML-2357 tracking, add no-emit caveat and compatibility round-trip invariant in README.
arktype Dependency Pinning
packages/3-extensions/arktype-json/package.json
Update arktype from ^2.1.29 to ~2.1.29 to enforce patch-only upgrades without re-emit.

Environment Setup Consolidation

Layer / File(s) Summary
Shared Environment Module
examples/prisma-next-cloudflare-worker/scripts/env.ts
Create new module with Hyperdrive env var constants (HYPERDRIVE_VAR, CLOUDFLARE_HYPERDRIVE_VAR) and loadLocalEnv helper.
Script & Config Updates
examples/prisma-next-cloudflare-worker/package.json, prisma-next.config.ts, scripts/seed.ts, scripts/setup-schema.ts, test/global-setup.ts, vitest.config.ts
Update all files to import and use shared loadLocalEnv and env constants; remove local dotenv/fs parsing logic and dotenv devDependency.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~75 minutes

Possibly related PRs

  • prisma/prisma-next#402: Implements the unified parameterized-codec descriptor-driven model that this PR extends with encodeIsParamsIndependent dispatch logic and arktype-json updates.
  • prisma/prisma-next#417: Overlaps in CodecDescriptor interface changes and runtime registry dispatch logic for parameterized codec handling.

Poem

🐇 A schema split in twain, now encode stands free,
While decode keeps the vigil—validation's decree.
Params fade from wire's form, through forColumn we see,
arktype rings true, from dispatch to decree.
Springtime refactors old paths, let shared helpers be! 🌱

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 43.75% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Title check ✅ Passed The title directly and accurately summarizes the main change: fixing correctness gaps discovered in the arktype-json extension and sql-runtime following ADR 208 implementation.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.

✏️ Tip: You can configure your own custom pre-merge checks in the settings.

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch fix/arktype-json-runtime-correctness

Tip

💬 Introducing Slack Agent: The best way for teams to turn conversations into code.

Slack Agent is built on CodeRabbit's deep understanding of your code, so your team can collaborate across the entire SDLC without losing context.

  • Generate code and open pull requests
  • Plan features and break down work
  • Investigate incidents and troubleshoot customer tickets together
  • Automate recurring tasks and respond to alerts with triggers
  • Summarize progress and report instantly

Built for teams:

  • Shared memory across your entire org—no repeating context
  • Per-thread sandboxes to safely plan and execute work
  • Governance built-in—scoped access, auditability, and budget controls

One agent for your entire SDLC. Right inside Slack.

👉 Get started


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.

❤️ Share

Comment @coderabbitai help to get the list of available commands and usage tips.

@pkg-pr-new

pkg-pr-new Bot commented May 4, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@prisma-next/mongo-runtime

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

@prisma-next/family-mongo

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

@prisma-next/sql-runtime

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

@prisma-next/family-sql

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

@prisma-next/extension-arktype-json

npm i https://pkg.pr.new/@prisma-next/extension-arktype-json@418

@prisma-next/extension-cipherstash

npm i https://pkg.pr.new/@prisma-next/extension-cipherstash@418

@prisma-next/middleware-telemetry

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

@prisma-next/mongo

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

@prisma-next/extension-paradedb

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

@prisma-next/extension-pgvector

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

@prisma-next/postgres

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

@prisma-next/sql-orm-client

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

@prisma-next/sqlite

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

@prisma-next/target-mongo

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

@prisma-next/adapter-mongo

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

@prisma-next/driver-mongo

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

@prisma-next/contract

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

@prisma-next/utils

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

@prisma-next/config

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

@prisma-next/errors

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

@prisma-next/framework-components

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

@prisma-next/operations

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

@prisma-next/ts-render

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

@prisma-next/contract-authoring

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

@prisma-next/ids

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

@prisma-next/psl-parser

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

@prisma-next/psl-printer

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

@prisma-next/cli

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

@prisma-next/emitter

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

@prisma-next/migration-tools

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

prisma-next

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

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

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

@prisma-next/mongo-codec

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

@prisma-next/mongo-contract

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

@prisma-next/mongo-value

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

@prisma-next/mongo-contract-psl

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

@prisma-next/mongo-contract-ts

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

@prisma-next/mongo-emitter

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

@prisma-next/mongo-schema-ir

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

@prisma-next/mongo-query-ast

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

@prisma-next/mongo-orm

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

@prisma-next/mongo-query-builder

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

@prisma-next/mongo-lowering

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

@prisma-next/mongo-wire

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

@prisma-next/sql-contract

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

@prisma-next/sql-errors

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

@prisma-next/sql-operations

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

@prisma-next/sql-schema-ir

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

@prisma-next/sql-contract-psl

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

@prisma-next/sql-contract-ts

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

@prisma-next/sql-contract-emitter

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

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

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

@prisma-next/sql-relational-core

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

@prisma-next/sql-builder

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

@prisma-next/target-postgres

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

@prisma-next/target-sqlite

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

@prisma-next/adapter-postgres

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

@prisma-next/adapter-sqlite

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

@prisma-next/driver-postgres

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

@prisma-next/driver-sqlite

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

commit: eac08ad

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
docs/architecture docs/adrs/ADR 208 - Higher-order codecs for parameterized types.md (1)

116-120: ⚡ Quick win

Trim the resolver mechanics from the ADR.

This section is drifting into implementation flow (typeRef traversal, CodecInstanceContext application, Js extraction). The ADR reads cleaner if it stays at the architectural contract level and leaves the step-by-step resolver behavior to the subsystem docs.
As per coding guidelines: ADRs in prisma/prisma-next should document architectural design decisions and the key constraints/assumptions only; avoid implementation algorithms and step-by-step derivation/migration rules.

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

In `@docs/architecture` docs/adrs/ADR 208 - Higher-order codecs for parameterized
types.md around lines 116 - 120, Remove the low-level resolver steps from the
ADR and keep it at the architectural-contract level: delete or reword the
paragraph that describes following typeRef through storage.types, synthetically
applying CodecInstanceContext, and extracting the Js parameter; instead state
that FieldOutputType<Definition, Model, Field> will be able to resolve
parameterized column types via the ColumnTypeDescriptor's authoring-only type
slot (type: (ctx: CodecInstanceContext) => Codec<…, Js>) and that for
non-parameterized columns it will fall back to CodecTypes[codecId]['output'],
while nullability is preserved—leave the step-by-step traversal and application
details to subsystem documentation.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@docs/architecture` docs/adrs/ADR 208 - Higher-order codecs for parameterized
types.md:
- Around line 116-120: Remove the low-level resolver steps from the ADR and keep
it at the architectural-contract level: delete or reword the paragraph that
describes following typeRef through storage.types, synthetically applying
CodecInstanceContext, and extracting the Js parameter; instead state that
FieldOutputType<Definition, Model, Field> will be able to resolve parameterized
column types via the ColumnTypeDescriptor's authoring-only type slot (type:
(ctx: CodecInstanceContext) => Codec<…, Js>) and that for non-parameterized
columns it will fall back to CodecTypes[codecId]['output'], while nullability is
preserved—leave the step-by-step traversal and application details to subsystem
documentation.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

Run ID: 98367176-41fe-4e0e-9a95-53b519c6db44

📥 Commits

Reviewing files that changed from the base of the PR and between 1d8b709 and eecca73.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (11)
  • docs/architecture docs/adrs/ADR 208 - Higher-order codecs for parameterized types.md
  • docs/architecture docs/subsystems/9. No-Emit Workflow.md
  • packages/2-sql/5-runtime/src/codecs/decoding.ts
  • packages/2-sql/5-runtime/test/json-schema-validation.test.ts
  • packages/3-extensions/arktype-json/README.md
  • packages/3-extensions/arktype-json/package.json
  • packages/3-extensions/arktype-json/src/core/arktype-json-codec.ts
  • packages/3-extensions/arktype-json/src/exports/runtime.ts
  • packages/3-extensions/arktype-json/test/arktype-json-codec.test-d.ts
  • packages/3-extensions/arktype-json/test/arktype-json-codec.test.ts
  • packages/3-extensions/arktype-json/test/extension-descriptors.test.ts

jkomyno added a commit that referenced this pull request May 4, 2026
…amily

The previous fix typed `arktypeJsonEmitCodec` against the SQL `Codec`
extension solely to gain the optional `meta` field. That coupled the
family-agnostic `codecInstances` slot to the SQL family — a future
non-SQL arktype variant (Mongo, etc.) would need a parallel stub or a
refactor of which interface owns `meta`.

Drop the SQL `Codec` import. Type the stub as the framework `Codec`
intersected with a co-located `SqlNativeTypeMeta` structural shape that
mirrors what the SQL renderer reads. The renderer's existing
`as SqlCodec | undefined` cast at the lookup boundary consumes `meta`
structurally regardless of the source declaration, so behavior is
unchanged.

Refs #418 self-review (subideal item #1).
jkomyno added a commit that referenced this pull request May 4, 2026
…ugh codec.encode

Symmetric to the decode-side guard added in 0574f04. Per-library JSON-
with-schema codecs validate inside `encode` (same shape as their
`decode` validation per ADR 208 § Case J) and throw the stable code
directly. Without this rethrow, `wrapEncodeFailure` re-wraps it as
`RUNTIME.ENCODE_FAILED` and the documented stable-code contract breaks
on the write side too.

Adds a regression test mirroring the decode-side one: a stub codec whose
`encode` throws `RUNTIME.JSON_SCHEMA_VALIDATION_FAILED`, asserted to
pass through `encodeParam` unchanged.

Refs #418 self-review (encode-side gap surfaced while writing the e2e
schema-rejection test).
jkomyno added a commit that referenced this pull request May 4, 2026
The `Embedding.profile` column has been in the e2e fixture since the
arktype-json landing but no test ever wrote or read it — which is why
the runtime cast lookup gap and the JSON.parse decode mismatch slipped
through. Add direct coverage:

1. Happy round-trip — `Embedding.create({ profile: { ... } })` followed
   by a where-eq read. Exercises the full encode path (schema validate
   → JSON.stringify → SQL renderer cast lookup → driver write) and the
   full decode path (driver read with pre-parsed jsonb → schema validate
   → ORM result).
2. Schema rejection on write — confirms `RUNTIME.JSON_SCHEMA_VALIDATION_FAILED`
   surfaces unchanged through the encode-side rethrow guard.

Decode-side rejection is already covered by the unit test in
sql-runtime/test/json-schema-validation.test.ts; not duplicated here.

Refs #418 self-review (subideal item #2).
jkomyno added a commit that referenced this pull request May 4, 2026
…k fires

The README's Compatibility section explained the round-trip invariant
and the version pin but didn't say when the runtime defense actually
runs. Add one sentence: the factory runs at execution-context
construction time (typically `runtime.connect()`), so a stale-but-shape-
valid contract.json fails fast at startup rather than on first query
or — worse — by silently returning wrong types.

Resolves the self-review concern about hard-fail timing: there is no
earlier hook to use without architectural changes (the round-trip
check requires materializing the schema, which neither paramsSchema
validation nor `prisma-next verify` does today).

Refs #418 self-review (subideal item #3).

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@packages/2-sql/5-runtime/src/codecs/encoding.ts`:
- Around line 126-140: The catch block in codec.encode currently only preserves
RUNTIME.JSON_SCHEMA_VALIDATION_FAILED; update it to also pass-through existing
RUNTIME.ENCODE_FAILED envelopes so they are not re-wrapped. Concretely, in the
catch for codec.encode, check if isRuntimeError(error) and if error.code is
either 'RUNTIME.JSON_SCHEMA_VALIDATION_FAILED' or 'RUNTIME.ENCODE_FAILED' then
rethrow the error; otherwise call wrapEncodeFailure(error, metadata, paramIndex,
codec.id). This uses the existing symbols codec.encode, isRuntimeError, and
wrapEncodeFailure to locate and modify the logic.
🪄 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: 2514a56f-f827-4262-9205-60a0ad1599aa

📥 Commits

Reviewing files that changed from the base of the PR and between eecca73 and e551a6c.

📒 Files selected for processing (5)
  • packages/2-sql/5-runtime/src/codecs/encoding.ts
  • packages/2-sql/5-runtime/test/json-schema-validation.test.ts
  • packages/3-extensions/arktype-json/README.md
  • packages/3-extensions/arktype-json/src/core/arktype-json-codec.ts
  • test/e2e/framework/test/arktype-json.test.ts
🚧 Files skipped from review as they are similar to previous changes (1)
  • packages/3-extensions/arktype-json/README.md

jkomyno added a commit that referenced this pull request May 4, 2026
…r flag

The runtime registry rejects `forCodecId(codecId)` lookups when multiple
distinct resolved instances share a parameterized codec id (e.g. two
`vector(N)` columns of different lengths, or two `arktypeJson(...)`
columns with different schemas). Today's encode dispatch carries only
the codec id (no `(table, column)` ref — TML-2357 § AC-5), so without
the rejection a DSL-param could silently bind to the wrong instance.

But for codecs whose `encode` is structurally equivalent across all
resolved instances (pgvector, arktype-json with schema-independent
encode), the rejection is over-conservative: any registered instance
encodes correctly, so picking one is safe. Without an opt-out, contracts
with multiple parameterized columns of the same codec id break at
encode time before `ParamRef.refs` lands.

Add `encodeIsParamsIndependent?: boolean` to `CodecDescriptor`. The
runtime registry skips the ambiguity-marker for descriptors that opt
in. Decode dispatch still uses `forColumn(table, column)` to get the
instance-specific schema, so the per-column type check remains correct.
The flag becomes vestigial when AC-5 lands.

Adds two unit tests in `contract-codec-registry.test.ts`: the default
ambiguity rejection (proves the guard still fires) and the
`encodeIsParamsIndependent` opt-out path (proves multi-instance
contracts work end-to-end at the registry level).

Refs Codex review of #418 (F01 enabling change).
jkomyno added a commit that referenced this pull request May 4, 2026
…rate pre-parsed JSON primitives

Two correctness gaps Codex's review of #418 surfaced:

F01 — encode is now params-dependent. Pre-existing on origin/main
(`8edf6cde0`): `serializeToJsonSafe` validated against the per-instance
schema. With multiple `arktypeJson(...)` columns the resolved codecs
differ by reference, the registry's ambiguity guard fires under any
codec-id-only encode lookup, and ordinary creates/updates/filters throw
`RUNTIME.TYPE_PARAMS_INVALID` before encoding can run. Drop the
encode-side `validateSchema(json)` call. Validation runs on decode only,
matching the JSON-validator philosophy: payloads can come from any
source (this writer, a previous schema version, a manual SQL `INSERT`),
so validate when reading. Pair with the new `encodeIsParamsIndependent`
descriptor flag (previous commit) — `arktypeJsonCodec` opts in.

F02 — pre-parsed JSON string primitives fail decode. The `pg` driver
returns `jsonb` cells as already-parsed JS values by default, including
primitives. For an arktype `type('string')` schema, a stored `"alice"`
arrives as the bare JS string `alice` and `JSON.parse(wire)` throws
SyntaxError before the schema gets a chance. Replace the binary
`typeof === 'string' ? JSON.parse : passthrough` branch with a
`parseWireValue` helper that tries `JSON.parse` first and falls back
to the original wire on parse failure. Covers raw-JSON-text drivers,
pre-parsed objects/arrays/numbers/bools/null, and pre-parsed JSON
string primitives. Documented edge case: a stored JSON string `"123"`
arrives pre-parsed as `123`, parses to the number `123` — collision
matches what `pgJsonbCodec` does today and is intrinsic to the
driver-mode ambiguity.

Test changes:
- arktype-json-codec.test.ts: encode-validation expectations updated to
  the round-trip-only contract (existing tests where the runtime check
  was pinning encode-side schema rejection are reframed as encode
  normalization tests). Three new F02 tests: pre-parsed string
  primitive happy path, raw-JSON-text wire still parses, pre-parsed
  primitive fails schema validation.
- e2e arktype-json.test.ts: schema-rejection test rewritten — write
  with a schema-violating payload commits, the subsequent read throws
  `RUNTIME.JSON_SCHEMA_VALIDATION_FAILED`. Mirrors the new validate-on-
  read contract.

Refs Codex review of #418 (F01, F02).
jkomyno added a commit that referenced this pull request May 4, 2026
Three sections still reflected the pre-PR-418 state of the world:

- "Type fidelity end-to-end" claimed `vector(1536)` and
  `arktypeJson(schema)` resolve in the no-emit path. They don't —
  the resolver wiring is tracked under TML-2357 and the partial-
  status block earlier in the ADR already says so. Update the
  consequence to match.

- "Encode-side `forCodecId` legacy fallback" said arktype-json's
  encode is `JSON.stringify` (true) and that the fallback works
  because encode is per-instance-stateless w.r.t. params. The
  PR-418 review surfaced that this required keeping encode
  schema-independent, which is now an explicit design choice. Add
  the `encodeIsParamsIndependent` flag mechanism that lets multi-
  column contracts work pre-AC-5.

- "Per-library JSON extensions" section said the descriptor's factory
  "validates internally in `decode`". Make the asymmetry explicit:
  validation runs on decode only; encode is `JSON.stringify` with no
  schema check, matching the validate-on-read philosophy.

- "Resolves" bullet for TML-2229 claimed both no-emit AND emit paths
  resolve correctly. Only emit ships in #402; no-emit waits for
  TML-2357. Split the bullet to reflect the partial state.

These updates close Codex's F03. The previously-added partial-status
block at § "No-emit type resolution" stays — this commit just brings
the rest of the ADR into agreement with it.

Refs Codex review of #418 (F03).
jkomyno added a commit that referenced this pull request May 4, 2026
…r descriptor

Pgvector's wire format `[v1,v2,...]` is dimension-independent. Today
the parameterized factory dodges the registry's reference-based
ambiguity check by returning `sharedVectorCodec` for every params, so
two `vector(N)` columns of different lengths happen to share one codec
instance. That keeps multi-vector contracts working without the new
`encodeIsParamsIndependent` opt-out — but only by accident of the
factory being a constant.

The comment on `vectorFactory` already foreshadows a refactor that
would close over `params` (e.g. capping wire length to declared
dimension). Such a refactor would produce reference-distinct instances
and trip the registry's ambiguity guard, breaking multi-vector
contracts silently.

Declare `encodeIsParamsIndependent: true` on the parameterized vector
descriptor to pin the encode-equivalence guarantee at the descriptor
level. Future implementation changes either preserve the invariant or
remove the flag — the registry will tell you which.

Adds a regression test in `manifest.test.ts` asserting the flag is
declared.

Refs Codex review of #418 (encodeIsParamsIndependent applied beyond
arktype-json).
jkomyno added 14 commits May 4, 2026 14:18
Postgres `pg` returns `jsonb` cells as already-parsed JS values by default.
The arktype-json codec was hardcoded to `JSON.parse(wire)` and would
SyntaxError on every read where the driver pre-parsed. Mirror
`pgJsonbCodec`'s `string | JsonValue` tolerance so selects against
arktypeJson columns work end-to-end.

Widens `ArktypeJsonCodec`'s `TWire` from `string` to `string | JsonValue`
to match the runtime tolerance. Adds two test cases covering both wire
shapes for `decode`.

Refs #402 review (P1 #2).
… lookup

The arktype-json runtime descriptor did not expose
`types.codecTypes.codecInstances`, so the postgres adapter's
`extractCodecLookup` (called at execution time, not control time) had no
entry for `arktype/json@1`. The first query touching an arktypeJson column
failed in `renderTypedParam` with "assembled codec lookup has no entry"
before encode/decode dispatch ever ran. pgvector's runtime descriptor
already follows the correct pattern.

Two changes:

1. `arktypeJsonRuntimeDescriptor.types.codecTypes.codecInstances` surfaces
   `arktypeJsonEmitCodec` so the runtime cast lookup resolves.
2. `arktypeJsonEmitCodec` now carries `meta.db.sql.postgres.nativeType =
   'jsonb'`. The framework `Codec` type doesn't expose `meta`; switch
   the declaration to the SQL `Codec` extension which does. Without this,
   `renderTypedParam` would emit `$N` instead of `$N::jsonb` — and `jsonb`
   is deliberately excluded from `POSTGRES_INFERRABLE_NATIVE_TYPES`, so
   the cast is required for filter expressions.

Renames the codec from "emit-only shim" to "metadata-only stub" to
reflect that it now serves both emit-path renderOutputType lookup AND
runtime cast policy. Encode/decode are still sentinels that throw if
invoked — runtime materialization goes through the unified descriptor
map's `factory(params)(ctx)`.

Adds three regression assertions in `extension-descriptors.test.ts`
covering: presence in `codecInstances`, resolution through
`extractCodecLookup`, and the `jsonb` native-type metadata field.

Refs #402 review (P1 #1).
…ugh codec.decode

ADR 208 § Case J says per-library JSON-with-schema codecs (e.g.
`arktype/json@1`) validate inside `decode` and surface the stable
`RUNTIME.JSON_SCHEMA_VALIDATION_FAILED` code unchanged. The runtime did
not honor that contract: `decodeField` caught all `codec.decode` errors
and rewrapped them as `RUNTIME.DECODE_FAILED`. The rethrow guard for the
schema-validation code only existed for the legacy post-decode
`validateJsonValue` path.

Add the same guard to the codec-decode catch arm. Adds a regression test
in `json-schema-validation.test.ts` that registers a stub codec whose
`decode` throws `RUNTIME.JSON_SCHEMA_VALIDATION_FAILED` and asserts the
code passes through `decodeRow` unchanged.

Refs #402 review (P2 #3).
…-implemented

ADR 208 § "No-emit type resolution" and the No-Emit Workflow subsystem
described `FieldOutputType` as following `typeRef` and applying the
column's authoring-time `type` slot to produce `Vector<1536>` and arktype-
schema-shaped types in no-emit mode. The resolver isn't wired up:
`@prisma-next/sql-contract-ts`'s `FieldOutputType` resolves through
`CodecTypesFromDefinition[codecId]['output']` only, and the arktype-json
codec-types map declares the `arktype/json@1` `output` as `unknown`. So
authors who skip `pnpm emit` get codec-base types, not the parameterized
refinements that emit produces.

Mark the resolver as not-yet-implemented in the ADR, the no-emit
subsystem, and the arktype-json README. Reference TML-2357 for tracked
follow-up. The eventual target shape stays in the docs as the design
intent — what changed is the status, not the design.

Refs #402 review (P2 #4).
…ent round-trip stability

The codec's emit-path output is derived from `schema.expression`. Runtime
rehydration via `ark.schema(typeParams.jsonIr)` reproduces that string
only as long as arktype's IR-to-expression rendering doesn't change. A
minor or major arktype bump can therefore stale-render existing
`contract.json` blobs without a corresponding re-emit.

Pin the dependency to `~2.1.29` (patch range only) and add a
"Compatibility" section to the README explaining the invariant and what
consumers should do when they bump arktype outside this range.

Refs #402 review (other concerns — arktype version pinning).
Previously, when the rehydrated schema's `expression` didn't match
`typeParams.expression`, the factory emitted a `console.warn` and kept
going. The branch was wrapped in `c8 ignore`, which made it untested.

Two problems with the warning approach. First, by the time the runtime
materializes the codec, the bad `contract.d.ts` has already been emitted
and shipped — a runtime warning fires after the wrong types are in
consumer code. Second, the expression-vs-rehydrated round-trip is
exactly the invariant the package's arktype version pin protects. A
silent warning is the wrong response when the invariant breaks.

Throw `RUNTIME.TYPE_PARAMS_INVALID` instead, with a message that points
the caller at re-running `pnpm emit`. Removes the `c8 ignore` so the
branch is testable; adds two tests (one for divergence, one for the
matching happy path).

Refs #402 review (other concerns — expression divergence handler).
…amily

The previous fix typed `arktypeJsonEmitCodec` against the SQL `Codec`
extension solely to gain the optional `meta` field. That coupled the
family-agnostic `codecInstances` slot to the SQL family — a future
non-SQL arktype variant (Mongo, etc.) would need a parallel stub or a
refactor of which interface owns `meta`.

Drop the SQL `Codec` import. Type the stub as the framework `Codec`
intersected with a co-located `SqlNativeTypeMeta` structural shape that
mirrors what the SQL renderer reads. The renderer's existing
`as SqlCodec | undefined` cast at the lookup boundary consumes `meta`
structurally regardless of the source declaration, so behavior is
unchanged.

Refs #418 self-review (subideal item #1).
…ugh codec.encode

Symmetric to the decode-side guard added in 0574f04. Per-library JSON-
with-schema codecs validate inside `encode` (same shape as their
`decode` validation per ADR 208 § Case J) and throw the stable code
directly. Without this rethrow, `wrapEncodeFailure` re-wraps it as
`RUNTIME.ENCODE_FAILED` and the documented stable-code contract breaks
on the write side too.

Adds a regression test mirroring the decode-side one: a stub codec whose
`encode` throws `RUNTIME.JSON_SCHEMA_VALIDATION_FAILED`, asserted to
pass through `encodeParam` unchanged.

Refs #418 self-review (encode-side gap surfaced while writing the e2e
schema-rejection test).
The `Embedding.profile` column has been in the e2e fixture since the
arktype-json landing but no test ever wrote or read it — which is why
the runtime cast lookup gap and the JSON.parse decode mismatch slipped
through. Add direct coverage:

1. Happy round-trip — `Embedding.create({ profile: { ... } })` followed
   by a where-eq read. Exercises the full encode path (schema validate
   → JSON.stringify → SQL renderer cast lookup → driver write) and the
   full decode path (driver read with pre-parsed jsonb → schema validate
   → ORM result).
2. Schema rejection on write — confirms `RUNTIME.JSON_SCHEMA_VALIDATION_FAILED`
   surfaces unchanged through the encode-side rethrow guard.

Decode-side rejection is already covered by the unit test in
sql-runtime/test/json-schema-validation.test.ts; not duplicated here.

Refs #418 self-review (subideal item #2).
…k fires

The README's Compatibility section explained the round-trip invariant
and the version pin but didn't say when the runtime defense actually
runs. Add one sentence: the factory runs at execution-context
construction time (typically `runtime.connect()`), so a stale-but-shape-
valid contract.json fails fast at startup rather than on first query
or — worse — by silently returning wrong types.

Resolves the self-review concern about hard-fail timing: there is no
earlier hook to use without architectural changes (the round-trip
check requires materializing the schema, which neither paramsSchema
validation nor `prisma-next verify` does today).

Refs #418 self-review (subideal item #3).
…r flag

The runtime registry rejects `forCodecId(codecId)` lookups when multiple
distinct resolved instances share a parameterized codec id (e.g. two
`vector(N)` columns of different lengths, or two `arktypeJson(...)`
columns with different schemas). Today's encode dispatch carries only
the codec id (no `(table, column)` ref — TML-2357 § AC-5), so without
the rejection a DSL-param could silently bind to the wrong instance.

But for codecs whose `encode` is structurally equivalent across all
resolved instances (pgvector, arktype-json with schema-independent
encode), the rejection is over-conservative: any registered instance
encodes correctly, so picking one is safe. Without an opt-out, contracts
with multiple parameterized columns of the same codec id break at
encode time before `ParamRef.refs` lands.

Add `encodeIsParamsIndependent?: boolean` to `CodecDescriptor`. The
runtime registry skips the ambiguity-marker for descriptors that opt
in. Decode dispatch still uses `forColumn(table, column)` to get the
instance-specific schema, so the per-column type check remains correct.
The flag becomes vestigial when AC-5 lands.

Adds two unit tests in `contract-codec-registry.test.ts`: the default
ambiguity rejection (proves the guard still fires) and the
`encodeIsParamsIndependent` opt-out path (proves multi-instance
contracts work end-to-end at the registry level).

Refs Codex review of #418 (F01 enabling change).
…rate pre-parsed JSON primitives

Two correctness gaps Codex's review of #418 surfaced:

F01 — encode is now params-dependent. Pre-existing on origin/main
(`8edf6cde0`): `serializeToJsonSafe` validated against the per-instance
schema. With multiple `arktypeJson(...)` columns the resolved codecs
differ by reference, the registry's ambiguity guard fires under any
codec-id-only encode lookup, and ordinary creates/updates/filters throw
`RUNTIME.TYPE_PARAMS_INVALID` before encoding can run. Drop the
encode-side `validateSchema(json)` call. Validation runs on decode only,
matching the JSON-validator philosophy: payloads can come from any
source (this writer, a previous schema version, a manual SQL `INSERT`),
so validate when reading. Pair with the new `encodeIsParamsIndependent`
descriptor flag (previous commit) — `arktypeJsonCodec` opts in.

F02 — pre-parsed JSON string primitives fail decode. The `pg` driver
returns `jsonb` cells as already-parsed JS values by default, including
primitives. For an arktype `type('string')` schema, a stored `"alice"`
arrives as the bare JS string `alice` and `JSON.parse(wire)` throws
SyntaxError before the schema gets a chance. Replace the binary
`typeof === 'string' ? JSON.parse : passthrough` branch with a
`parseWireValue` helper that tries `JSON.parse` first and falls back
to the original wire on parse failure. Covers raw-JSON-text drivers,
pre-parsed objects/arrays/numbers/bools/null, and pre-parsed JSON
string primitives. Documented edge case: a stored JSON string `"123"`
arrives pre-parsed as `123`, parses to the number `123` — collision
matches what `pgJsonbCodec` does today and is intrinsic to the
driver-mode ambiguity.

Test changes:
- arktype-json-codec.test.ts: encode-validation expectations updated to
  the round-trip-only contract (existing tests where the runtime check
  was pinning encode-side schema rejection are reframed as encode
  normalization tests). Three new F02 tests: pre-parsed string
  primitive happy path, raw-JSON-text wire still parses, pre-parsed
  primitive fails schema validation.
- e2e arktype-json.test.ts: schema-rejection test rewritten — write
  with a schema-violating payload commits, the subsequent read throws
  `RUNTIME.JSON_SCHEMA_VALIDATION_FAILED`. Mirrors the new validate-on-
  read contract.

Refs Codex review of #418 (F01, F02).
Three sections still reflected the pre-PR-418 state of the world:

- "Type fidelity end-to-end" claimed `vector(1536)` and
  `arktypeJson(schema)` resolve in the no-emit path. They don't —
  the resolver wiring is tracked under TML-2357 and the partial-
  status block earlier in the ADR already says so. Update the
  consequence to match.

- "Encode-side `forCodecId` legacy fallback" said arktype-json's
  encode is `JSON.stringify` (true) and that the fallback works
  because encode is per-instance-stateless w.r.t. params. The
  PR-418 review surfaced that this required keeping encode
  schema-independent, which is now an explicit design choice. Add
  the `encodeIsParamsIndependent` flag mechanism that lets multi-
  column contracts work pre-AC-5.

- "Per-library JSON extensions" section said the descriptor's factory
  "validates internally in `decode`". Make the asymmetry explicit:
  validation runs on decode only; encode is `JSON.stringify` with no
  schema check, matching the validate-on-read philosophy.

- "Resolves" bullet for TML-2229 claimed both no-emit AND emit paths
  resolve correctly. Only emit ships in #402; no-emit waits for
  TML-2357. Split the bullet to reflect the partial state.

These updates close Codex's F03. The previously-added partial-status
block at § "No-emit type resolution" stays — this commit just brings
the rest of the ADR into agreement with it.

Refs Codex review of #418 (F03).
…r descriptor

Pgvector's wire format `[v1,v2,...]` is dimension-independent. Today
the parameterized factory dodges the registry's reference-based
ambiguity check by returning `sharedVectorCodec` for every params, so
two `vector(N)` columns of different lengths happen to share one codec
instance. That keeps multi-vector contracts working without the new
`encodeIsParamsIndependent` opt-out — but only by accident of the
factory being a constant.

The comment on `vectorFactory` already foreshadows a refactor that
would close over `params` (e.g. capping wire length to declared
dimension). Such a refactor would produce reference-distinct instances
and trip the registry's ambiguity guard, breaking multi-vector
contracts silently.

Declare `encodeIsParamsIndependent: true` on the parameterized vector
descriptor to pin the encode-equivalence guarantee at the descriptor
level. Future implementation changes either preserve the invariant or
remove the flag — the registry will tell you which.

Adds a regression test in `manifest.test.ts` asserting the flag is
declared.

Refs Codex review of #418 (encodeIsParamsIndependent applied beyond
arktype-json).
@jkomyno
jkomyno force-pushed the fix/arktype-json-runtime-correctness branch from e5ba9f5 to 192a4ed Compare May 4, 2026 12:19
jkomyno added 3 commits May 4, 2026 14:26
The "writes succeed, reads enforce" test failed in CI: I missed that
`db.orm.Embedding.create` returns a decoded row via `RETURNING`, so
schema enforcement happens during create itself rather than on a
subsequent read. There's no single ORM call that cleanly demonstrates
the validate-on-read contract end-to-end without raw-SQL bypass
infrastructure the fixture doesn't expose.

Drop the failing case. Decode-side schema rejection is already covered
at:
- arktype-json unit tests (decode rejects pre-parsed payloads that
  violate the schema, decode rejects pre-parsed primitives that
  violate the schema)
- sql-runtime json-schema-validation tests (runtime preserves
  RUNTIME.JSON_SCHEMA_VALIDATION_FAILED thrown from codec.decode
  without rewrapping)

The happy-path e2e round-trip stays as the single end-to-end smoke
test; it exercises the full encode → cast lookup → driver write →
driver read (pre-parsed jsonb) → decode pipeline that originally
shipped broken in #402.
…gh unchanged

`encodeParams` and `decodeRow` already documented "no double wrap"
behavior for codec-stamped runtime envelopes, but the catch blocks
inside `encodeParamValue` and `decodeField` only special-cased
`RUNTIME.JSON_SCHEMA_VALIDATION_FAILED`. Anything else flowed through
`wrapEncodeFailure` / `wrapDecodeFailure`, including envelopes a codec
body had already stamped — dropping the author-supplied
`details`/`cause` contract and producing a misleading double-wrap.

Extend both guards to also pass `RUNTIME.ENCODE_FAILED` /
`RUNTIME.DECODE_FAILED` through unchanged. The code now matches the
existing doc.

Adds two regression tests pinning the pass-through: a codec whose
`encode` throws a stamped `RUNTIME.ENCODE_FAILED` (with custom
`details.codecAuthorContext`) reaches `encodeParam` unchanged, and the
symmetric case for `decodeRow`.

Refs PR #418 review (CodeRabbit r3181136080).

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

🧹 Nitpick comments (1)
test/e2e/framework/test/arktype-json.test.ts (1)

2-2: ⚡ Quick win

Prefer pathe over node:path for path manipulation.

dirname and resolve should be imported from pathe (drop-in replacement with identical API) rather than node:path. Note: node:url on line 3 stays — fileURLToPath has no pathe equivalent.

♻️ Proposed change
 import { readFile } from 'node:fs/promises';
-import { dirname, resolve } from 'node:path';
+import { dirname, resolve } from 'pathe';
 import { fileURLToPath } from 'node:url';

As per coding guidelines: "**/*.{ts,tsx,mts,cts}: Use pathe instead of node:path for path manipulation in TypeScript files... especially when code reads files/fixtures from disk."

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

In `@test/e2e/framework/test/arktype-json.test.ts` at line 2, Replace imports of
dirname and resolve from 'node:path' with imports from 'pathe': update the
import statement that currently pulls dirname and resolve from 'node:path' so it
instead imports those symbols from 'pathe' (leave fileURLToPath from 'node:url'
unchanged); ensure any usages of dirname and resolve remain the same since pathe
is a drop-in replacement.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@test/e2e/framework/test/arktype-json.test.ts`:
- Line 2: Replace imports of dirname and resolve from 'node:path' with imports
from 'pathe': update the import statement that currently pulls dirname and
resolve from 'node:path' so it instead imports those symbols from 'pathe' (leave
fileURLToPath from 'node:url' unchanged); ensure any usages of dirname and
resolve remain the same since pathe is a drop-in replacement.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

Run ID: 6cbb9930-0b82-4bda-95c7-86a13d6d26fe

📥 Commits

Reviewing files that changed from the base of the PR and between e5ba9f5 and 6a2e33b.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (18)
  • docs/architecture docs/adrs/ADR 208 - Higher-order codecs for parameterized types.md
  • docs/architecture docs/subsystems/9. No-Emit Workflow.md
  • packages/1-framework/1-core/framework-components/src/shared/codec-types.ts
  • packages/2-sql/5-runtime/src/codecs/decoding.ts
  • packages/2-sql/5-runtime/src/codecs/encoding.ts
  • packages/2-sql/5-runtime/src/sql-context.ts
  • packages/2-sql/5-runtime/test/contract-codec-registry.test.ts
  • packages/2-sql/5-runtime/test/json-schema-validation.test.ts
  • packages/3-extensions/arktype-json/README.md
  • packages/3-extensions/arktype-json/package.json
  • packages/3-extensions/arktype-json/src/core/arktype-json-codec.ts
  • packages/3-extensions/arktype-json/src/exports/runtime.ts
  • packages/3-extensions/arktype-json/test/arktype-json-codec.test-d.ts
  • packages/3-extensions/arktype-json/test/arktype-json-codec.test.ts
  • packages/3-extensions/arktype-json/test/extension-descriptors.test.ts
  • packages/3-extensions/pgvector/src/exports/runtime.ts
  • packages/3-extensions/pgvector/test/manifest.test.ts
  • test/e2e/framework/test/arktype-json.test.ts
✅ Files skipped from review due to trivial changes (7)
  • packages/3-extensions/pgvector/src/exports/runtime.ts
  • packages/3-extensions/pgvector/test/manifest.test.ts
  • packages/3-extensions/arktype-json/package.json
  • packages/1-framework/1-core/framework-components/src/shared/codec-types.ts
  • packages/3-extensions/arktype-json/README.md
  • packages/3-extensions/arktype-json/test/arktype-json-codec.test.ts
  • docs/architecture docs/subsystems/9. No-Emit Workflow.md
🚧 Files skipped from review as they are similar to previous changes (6)
  • packages/2-sql/5-runtime/test/contract-codec-registry.test.ts
  • packages/3-extensions/arktype-json/test/arktype-json-codec.test-d.ts
  • packages/3-extensions/arktype-json/test/extension-descriptors.test.ts
  • packages/3-extensions/arktype-json/src/core/arktype-json-codec.ts
  • packages/2-sql/5-runtime/src/sql-context.ts
  • packages/2-sql/5-runtime/src/codecs/encoding.ts

@wmadden wmadden left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

I want to hold off merging this until TML-2357 / PR #417 is merged. This PR adds an extra conditional flag to codec descriptors, encodeIsParamsIndependent, which is made redundant by #417

jkomyno added 2 commits May 11, 2026 10:18
# Conflicts:
#	docs/architecture docs/adrs/ADR 208 - Higher-order codecs for parameterized types.md
#	packages/1-framework/1-core/framework-components/src/shared/codec-types.ts
#	packages/2-sql/5-runtime/src/codecs/decoding.ts
#	packages/2-sql/5-runtime/test/json-schema-validation.test.ts
#	packages/3-extensions/arktype-json/src/core/arktype-json-codec.ts
#	packages/3-extensions/arktype-json/src/exports/runtime.ts
#	packages/3-extensions/arktype-json/test/arktype-json-codec.test-d.ts
#	packages/3-extensions/arktype-json/test/arktype-json-codec.test.ts
#	packages/3-extensions/pgvector/src/exports/runtime.ts
#	pnpm-lock.yaml
@jkomyno
jkomyno requested a review from a team as a code owner May 11, 2026 08:28

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 2

🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@examples/prisma-next-cloudflare-worker/vitest.config.ts`:
- Line 5: Call loadLocalEnv with the explicit example-root path instead of
relying on its default in files that may be run from subdirectories: update
vitest.config.ts (where loadLocalEnv() is currently called),
prisma-next.config.ts, scripts/setup-schema.ts and scripts/seed.ts to pass the
same computed root path that test/global-setup.ts uses (i.e., compute the
example root from import.meta.url and pass it into loadLocalEnv(root)), so all
callsites use a consistent, correct root regardless of the current working
directory.
- Around line 3-5: The vitest config currently calls loadLocalEnv() with no args
which defaults to process.cwd() and can differ from the example root used by
global-setup; compute the example root explicitly (using fileURLToPath and
import.meta.url to derive exampleRoot) and pass that exampleRoot into
loadLocalEnv(exampleRoot) so both the config and global-setup load the same .env
file (locate the call to loadLocalEnv in vitest.config.ts and update it
accordingly).
🪄 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: e3430170-5507-4b9d-a6f7-e3e6ee3eadea

📥 Commits

Reviewing files that changed from the base of the PR and between 6a2e33b and 9a855de.

📒 Files selected for processing (9)
  • docs/architecture docs/adrs/ADR 208 - Higher-order codecs for parameterized types.md
  • examples/prisma-next-cloudflare-worker/package.json
  • examples/prisma-next-cloudflare-worker/prisma-next.config.ts
  • examples/prisma-next-cloudflare-worker/scripts/env.ts
  • examples/prisma-next-cloudflare-worker/scripts/seed.ts
  • examples/prisma-next-cloudflare-worker/scripts/setup-schema.ts
  • examples/prisma-next-cloudflare-worker/test/global-setup.ts
  • examples/prisma-next-cloudflare-worker/vitest.config.ts
  • packages/1-framework/1-core/framework-components/src/shared/codec-descriptor.ts
💤 Files with no reviewable changes (1)
  • examples/prisma-next-cloudflare-worker/package.json
✅ Files skipped from review due to trivial changes (2)
  • examples/prisma-next-cloudflare-worker/scripts/env.ts
  • docs/architecture docs/adrs/ADR 208 - Higher-order codecs for parameterized types.md

@jkomyno

jkomyno commented May 11, 2026

Copy link
Copy Markdown
Contributor Author

Addressed the #417 follow-up from the changes-requested review:

  • 59f51b91a removes encodeIsParamsIndependent from the descriptor API and extension descriptors, and restores parameterized forCodecId handling to require column-aware dispatch.
  • 67ebcca5b resolves the Cloudflare Worker example env-root follow-up by centralizing EXAMPLE_ROOT and passing it to every loadLocalEnv callsite.

Validation:

  • Focused codec tests passed for @prisma-next/sql-runtime, @prisma-next/extension-arktype-json, and @prisma-next/extension-pgvector.
  • Focused builds/typechecks/lints passed for the touched packages, and pnpm lint:deps passed.
  • pnpm --filter prisma-next-cloudflare-worker lint and pnpm --filter prisma-next-cloudflare-worker typecheck passed.
  • pnpm test:packages still hit the full-suite parallel CLI timeout/unhandled-error flake; the failing CLI file passed in isolation.

jkomyno added 9 commits May 11, 2026 10:55
…t on decode

The previous `isJsonStringText` heuristic unwrapped any `"…"`-shaped wire
as JSON-encoded text. Under `pg` + `jsonb` (the documented native type),
the wire is already pre-parsed: pg returns the literal string content, so
the wire IS the user's value — including strings whose first and last
characters happen to be `"`. Unwrapping silently truncated them — the
7-character `"hello"` decoded to the 5-character `hello`.

Invert the priority: try `validateSchema(schema, wire)` on the raw wire
first. Fall back to `JSON.parse` only when schema validation rejects the
raw form, which covers object/array shapes received as raw JSON text
(legacy `json` text-OID adapters, or any code path that hands us
un-pre-parsed JSON).

`isJsonStringText` is deleted; `parseJsonText` retains its single caller
inside the catch branch.

Updates the test that codified the wrong behavior. The new test asserts
byte-exact preservation for `"bob"`, `"hello"`, and `""` — the literal
quote characters round-trip unchanged.
…d JSON.parse on encode

`serializeToJsonSafe` returned `{ wire, json }` but the two consumers used
disjoint halves: `encode` reads `.wire` only, `encodeJson` reads `.json`
only. The `JSON.parse(wire)` on the encode path produced a value that
was immediately discarded — pure waste, proportional to payload size.
For a 100KB JSON column at 1000-param batched insert this was on the
order of 150-250ms of unnecessary work per call.

Split into `serializeWire` (encode) and `serializeJson` (encodeJson). The
JSON.stringify → JSON.parse round-trip stays on the `encodeJson` path
where its deep-clone-as-JsonValue effect is needed (strips class
prototypes, normalizes `toJSON` side effects so the in-memory value
matches what the database would return).
The encode side enumerated two specific stable codes
(`RUNTIME.JSON_SCHEMA_VALIDATION_FAILED`, `RUNTIME.ENCODE_FAILED`) for
pass-through. The symmetric decode-side guard at decoding.ts:239 is one
line: `if (isRuntimeError(error)) throw error`. The enumeration on
encode was strictly more brittle — a future stable code thrown from a
codec body (e.g. `RUNTIME.ABORTED` via `CodecCallContext.signal`) would
be wrapped here but pass through on decode, an asymmetry with no
principled justification.

Any `runtimeError`-built envelope is stable by construction. Let them
all pass through unchanged; only foreign errors get the
`wrapEncodeFailure` envelope.
Schema validation runs only on `decode`. `encode` checks JSON
representability but does not invoke the schema (ADR 208 keeps encode
parameter-independent so it can be dispatched by `codecId`). The
consequence callers must plan for: a schema-invalid write commits the
row to the database, and only then fails on read-back through
`RETURNING` — leaving an unreadable row behind that crashes every
subsequent decode of the same column.

In a fully-typed call site the TypeScript types prevent this. The
footgun reaches production only when types are bypassed (`as never`,
runtime drift from a third-party feed, untyped inputs). Add a
"Data integrity" section to the README spelling out the failure mode
and pointing at two mitigations: wrap mutations in `withTransaction` so
the failed decode rolls back the INSERT, or pre-validate user input
with `schema.allows(value)`.

@wmadden wmadden left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This is a good, focused fix 👍🏻

There's only one point I think we should discuss:

F11 — parseWireValue is a heuristic workaround for a driver-configuration gap — [packages/3-extensions/arktype-json/src/core/arktype-json-codec.ts](packages/3-extensions/arktype-json/src/core/arktype-json-codec.ts) — lines 199–237

parseWireValue exists because pg pre-parses jsonb cells to JS values by default, so the codec cannot assume the wire is always a raw JSON-text string. The heuristic (try JSON.parse, fall back to the original string on SyntaxError) is consistent with what pgJsonbCodec and pgJsonCodec already do in packages/3-targets/3-targets/postgres/src/core/codecs.ts (lines 555–557, 573–575), but it introduces a documented data-loss edge case: a stored JSON string "123" arrives pre-parsed as the number 123, and JSON.parse("123") returns the number — so the original string is unrecoverable.

The cleaner architectural fix is to disable pg's JSON type parsers at driver-initialization time (analogous to disabling date pre-parsing), so the codec always receives a raw JSON-text string on decode. That approach would:

  • Eliminate parseWireValue entirely; decode becomes JSON.parse(wire).
  • Remove the "123" edge case entirely (no ambiguity when you always get raw text).
  • Require updating pgJsonbCodec and pgJsonCodec alongside arktypeJson (they have the same tolerant pattern).
  • Require a driver-level change: override pg's JSONB/JSON type parsers (OIDs 114/3802) at Pool/Client creation time in packages/3-targets/7-drivers/postgres/src/postgres-driver.ts.

Suggestion: Discuss timing with the PR author. The fix in this PR is correct and consistent with the existing builtin codecs. The driver-level approach is the principled long-term solution; it should land in the same PR as (or immediately after) any work that disables pg's date pre-parsing, so the approach is uniform across all non-text types.

Comment on lines +81 to +96
function serializeJson<TInferred>(value: TInferred): JsonValue {
// The stringify → parse round-trip both validates JSON-representability
// (matching `serializeWire`) and produces a deep-cloned `JsonValue` that
// strips class prototypes / `toJSON` side effects, so callers reading
// the in-memory `JsonValue` see exactly the shape that would round-trip
// through the database.
return JSON.parse(serializeWire(value)) as JsonValue;
}

function parseJsonText(wire: string): JsonValue | undefined {
try {
return JSON.parse(wire) as JsonValue;
} catch {
return undefined;
}
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Is it just me or do both the parse() and serialize() methods here do parsing?

@jkomyno

jkomyno commented May 11, 2026

Copy link
Copy Markdown
Contributor Author

@wmadden thanks for the approval and the thoughtful F11 — quick reply.

Quick note on the code reference: the function has since been restructured. What you reviewed as parseWireValue at lines 199-237 is now decodeWireValue at packages/3-extensions/arktype-json/src/core/arktype-json-codec.ts:102-132 (renamed in 5b9816746 fix(arktype-json): preserve parsed string primitives, before your approving review but easy to miss in the diff). The lines 199-237 you cited now hold ArktypeJsonDescriptor, which is unrelated.

On the "123" edge case: I don't think it applies to the current decoder. The order isn't "try JSON.parse, fall back to original on SyntaxError" — it's the inverse:

  1. Validate the wire as-is against the arktype schema.
  2. Only on RUNTIME.JSON_SCHEMA_VALIDATION_FAILED does it call JSON.parse(wire) and re-validate.

Walking through your scenario under that order:

  • Stored on disk: jsonb "123" (JSON string).
  • pg pre-parses to the JS string "123".
  • Schema is type('string') → step 1 accepts → returns the string "123". No data loss.
  • Schema is type('number') → step 1 rejects → fallback JSON.parse("123") returns 123 → step 2 accepts. The user explicitly typed the column as number; getting a number back is the right outcome.

The regression is locked at test/arktype-json-codec.test.ts:170-176:

it('decode preserves pre-parsed JSON-looking string primitives', async () => {
  const stringSchema = type('string');
  const codec = arktypeJsonColumn(stringSchema).codecFactory(SYNTH_CTX);
  for (const value of ['42', 'true', 'null', '{"x":1}']) {
    expect(await codec.decode(value, CALL_CTX)).toBe(value);
  }
});

Plus a quote-bounded variant at :178-189 ("bob" stays 5 chars, doesn't get unwrapped).

On the "consistent with pgJsonbCodec / pgJsonCodec" framing: those are plain pass-throughs — packages/3-targets/3-targets/postgres/src/core/codec-helpers.ts:130-135:

export const pgJsonDecode = (wire: string | JsonValue): JsonValue =>
  typeof wire === 'string' ? JSON.parse(wire) : wire;
export const pgJsonbDecode = (wire: string | JsonValue): JsonValue =>
  typeof wire === 'string' ? JSON.parse(wire) : wire;

No recovery on SyntaxError, no schema validation. They don't need arktype's heuristic because they return raw JsonValue — there's no runtime type to disambiguate against. Different shape, addressing different concerns. I'd avoid the "consistent" framing in future reviews because it implies the same recovery pattern exists at both ends; it doesn't.

On the architectural endgame: 100% agreed. Disabling pg's OID 114 / 3802 parsers at driver init (alongside the date pre-parser decision) unifies the wire contract — then decodeWireValue collapses to one line and pgJson*Decode simplifies too. Right place is packages/3-extensions/postgres/src/runtime/postgres.ts:28 where the Pool is instantiated; no existing setTypeParser calls to coordinate with.

I'll file a tracking issue so it doesn't drift, and I'd like to keep this PR scoped to the ADR-208 correctness gaps. Happy to add a comment in the codec source explicitly contrasting the heuristic with pg*Codec's pass-through so the next reviewer doesn't hit the same framing — let me know if you'd like that in this PR or as a follow-up.

@wmadden
wmadden merged commit 05f9406 into main May 12, 2026
15 of 16 checks passed
@wmadden
wmadden deleted the fix/arktype-json-runtime-correctness branch May 12, 2026 12:31
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants