Skip to content

fix(target-postgres): bytea and vector literal defaults verify after they are applied (TML-3283) - #30603

Merged
wmadden merged 11 commits into
mainfrom
tml-3283-read-defaults-back-through-codec
Oct 5, 2026
Merged

wmadden merged 11 commits into
mainfrom
tml-3283-read-defaults-back-through-codec

Conversation

@wmadden-electric

@wmadden-electric wmadden-electric commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

At a glance

model Doc {
  id    Int     @id
  blob  Bytes   @default("aGVsbG8=")
  blobs Bytes[] @default(["aGVsbG8="])
}

On main, prisma db init writes this table correctly and then rolls it back with MIGRATION.SCHEMA_VERIFY_FAILED. Both defaults are reported as mismatches: the contract expects "aGVsbG8=" and the database has "\x68656c6c6f".

aGVsbG8= is the base64 form of the bytes of hello, which the contract stores. \x68656c6c6f is the same bytes as Postgres prints them. The schema check that runs after applying compared the two spellings as they stood, so every Bytes literal default failed db init, db update and db migrate. A pgvector vector(3)[] list default failed the same way.

With this PR all three commands apply these defaults, and db verify --strict is clean.

Refs: TML-3283

The decision

Each Postgres data type that Postgres prints differently from the contract already says how to read that text. interval, timetz, the date types, int8 and numeric each declare a toCanonicalForm, and the default comparison applies it to both sides before comparing (#30532). This PR adds the same for bytea and for pgvector's vector. It does not add a new mechanism.

How it fits together

  • pg/bytea reads base64 or Postgres's \x hex and returns the base64 the contract stores. As for the date types, the same function is the type's cast from text. So a PSL Bytes default may be written either way, and is stored as base64: @default("\\x68656c6c6f") stores aGVsbG8=. The backslash is doubled because \x68 inside a PSL string is the letter h. The refusal message for a malformed value shows that spelling.
  • pgvector's vector reads Postgres's [1,2,3] text into the number array the contract stores, and reads -0 as 0.
  • Introspection pins bytea_output = 'hex', beside TimeZone, DateStyle and IntervalStyle, and restores the caller's value afterwards. A server set to escape prints a bytea default as 'hello'::bytea, which the canonical form could not read as hex.
  • A raw SQL bytea default is read as Postgres bytea input. The text inside a SQL string literal for a bytea column is hex or escape format, never base64. So the Postgres default parser turns it into the base64 of its bytes. Without this, sql`'aGVsbG8='::bytea, which holds the 8 ASCII bytes of that text, would have compared equal to hello. As a result, sql`'hello'::bytea now applies and verifies; on main it failed too.

parsePostgresDefault gains only the bytea input reading. The shared SQL family code and the codecs are unchanged.

What users see change

contract infer now prints a bytea default as a literal, @default("aGVsbG8="), where it printed @default(sql`'\x68656c6c6f'::bytea`). The sql defaults it printed before still verify. Re-inferring gives a contract with a new storage hash. The upgrade note in upgrade-instructions/pending/bytea-defaults-verify/ says how to sign or migrate to it.

Escape-format text in a raw SQL default is read as UTF-8, which matches Postgres on a UTF-8 database.

Testing performed

Manual, through the CLI in a project made with prisma orm init, against a PostgreSQL 15 server logging every statement:

  • contract emit stores aGVsbG8= for "aGVsbG8=", ["aGVsbG8="] and "\\x68656c6c6f". db init succeeds, db verify --strict is clean, and an inserted row holds the bytes of hello.
  • Adding those defaults to existing columns with migration plan and db migrate succeeds and verifies clean.
  • With bytea_output = 'escape' set on the database and on the role, verify is still clean. The server log shows the CLI switching to hex and restoring escape.
  • contract infer on a hand-made table prints @default("aGVsbG8="). The inferred schema emits and verifies clean.
  • Malformed hex and base64 fail contract emit with PSL_INVALID_LITERAL, naming the field and giving a correct example.
  • A pgvector vector(3)[] default through TypeScript authoring applies and verifies clean.

Automated:

  • A CLI journey covers emit, db init, migration plan then db migrate, strict verify, the stored bytes, and the contract infer round trip.
  • Runner tests on a real database:
    • bytea defaults written as raw SQL in escape and hex form, including octal escapes and lists, apply and verify.
    • A base64 raw SQL default no longer equals hello.
    • The vector(3)[] default applies and verifies, both when the table is created and through setDefault.
    • A bytea default applies and verifies in a session set to escape output.
  • Unit tests cover both canonical forms, including refusals, and the bytea input reading.
  • Each regression test failed on main before its fix.
  • Checks: pnpm build, pnpm typecheck, lint and coverage for every touched package, pnpm fixtures:check, pnpm lint:deps, pnpm check:upgrade-coverage, and the bytea, data-type-default and Prisma 7 integration files.

Not fixed here

  • TML-3383. inet written as /32 or in upper case, and tsquery written as fat & rat, still fail verify, because the contract keeps the written spelling. So does a vector value that real rounds.
  • TML-3464. With standard_conforming_strings = off, bytea defaults are written as the wrong bytes. This is already the case on main.
  • TML-3465. A list of vectors cannot be written in PSL.
  • TML-3455. The Prisma 7 reader still stores Bytes and DateTime defaults as raw SQL. Switching them to values changes contract hashes.

Alternatives considered

  • Read every introspected default back through the column's codec. Strip the SQL syntax, then call codec.decode and encodeJson. This was the earlier plan for TML-3283, and it does not fit:
    • Codec.decode is async, while the default comparison is synchronous.
    • The interval codec reads only ISO text, while introspection pins IntervalStyle = 'postgres'. So the interval defaults that verify today would fail.
    • contract infer has no contract, so it would have to choose a codec from a native type. That cannot build a parameterized codec such as vector(3).
    • Contracts already inferred with a bytea default would stop verifying.
  • A bytea rule in parsePostgresDefault alone. That would copy the codec's hex reading a third time, could not cover pgvector, and would leave PSL unable to accept hex.

Agent: atreides-42

🤖 Generated with Claude Code

Summary by CodeRabbit

  • New Features
    • PostgreSQL schema checks now recognize equivalent bytea defaults in hex and base64 forms, including defaults within arrays.
    • PostgreSQL vector values and defaults are compared consistently across array and printed-text formats.
    • PostgreSQL introspection uses a consistent hex format for bytea output and restores the original session settings afterward.
  • Upgrade Notes
    • Re-inferred bytea defaults may change the contract hash without changing the database. Re-emit the contract, then verify and sign the database or apply an empty migration before deploying.

wmadden-electric and others added 11 commits October 5, 2026 15:37
…(TML-3283)

pg/bytea gains a canonical form: the base64 its codec writes, read from
base64 or from the \x hex text PostgreSQL prints for a bytea default. The
schema check applies it to both sides, so a bytea default verifies after
it is applied, and contract infer prints it as a base64 literal. Like the
date and time types, the same function is the cast from pg/text, so a PSL
Bytes default may be written in PostgreSQL hex.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…rints (TML-3283)

pgvector/vector gains a canonical form: its array of numbers, kept as it
is or read from the [1,2,3] text PostgreSQL prints. The schema check
applies it to each element of a list default, so a vector(3)[] default
verifies after the runner applies it. It adds no cast from text.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…output = hex (TML-3283)

Postgres prints a bytea default in the session's bytea_output format, so a
session set to escape reported 'hello'::bytea where pg/bytea reads hex.
Introspection now pins bytea_output = hex beside TimeZone, DateStyle and
IntervalStyle, and restores the caller's value afterwards.

The codec literal defaults test now applies its migration through the
runner, since the schema check after it reads bytea defaults back.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
… CLI (TML-3283)

A journey writes Bytes and Bytes[] defaults in base64 and in PostgreSQL
hex, emits base64 for all of them, and runs db init, and separately
migration plan and db migrate onto existing columns; strict db verify is
clean and an inserted row holds the bytes of hello. contract infer prints
a bytea default as a base64 literal, and the inferred schema emits and
verifies clean. ADR 254 says which types read the text PostgreSQL prints.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
… it reads (TML-3283)

The canonical-form inventory needs a table of values for every type that
declares a canonical form, and pg/bytea now declares one.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
The app fragment covers the contract infer output change and the storage
hash it brings. Extensions need no change.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…es (TML-3283)

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…ytea input (TML-3283)

The text inside a SQL string literal for a bytea column is PostgreSQL
bytea input: \x hex, or the escape format, where \\ is a backslash, a
backslash and three octal digits is that byte, and any other character is
its UTF-8 bytes. The default parser now turns that text into the base64 of
its bytes, element by element for a list, and keeps text PostgreSQL
refuses as the raw expression.

Before, a raw SQL default 'aGVsbG8='::bytea was read as base64 and
reported equal to a database default holding hello, and 'hello'::bytea
failed the schema check after db init.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…it (TML-3283)

A PSL string reads \x68 as the character h, so Bytes @default("\x68656c6c6f")
reached the cast as h656c6c6f, and the refusal suggested the same
spelling the user wrote. The refusals now quote the value as a PSL string
and give hex as "\\x68656c6c6f" next to the base64 example. ADR 254 does
the same, and says a raw SQL bytea default is read as bytea input.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…-3283)

JSON cannot hold -0 and pgvector treats -0 and 0 as equal, but the
comparison wrote them differently, so a database default [-0,1,2] did
not match a contract [0,1,2].

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
…tea pin (TML-3283)

The Prisma 7 binding comment now gives the reason the reader keeps raw
SQL for Bytes and DateTime defaults: storing values changes contract
hashes (TML-3455). The README says the bytea_output pin also rewrites a
bytea constant in check, index and policy text on an escape server.
typeWrittenAsText becomes typeCanonicalFromText, and the comment that
repeated the introspection setting values is gone.

Signed-off-by: willbot <[email protected]>
Signed-off-by: Will Madden <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
@wmadden-electric
wmadden-electric requested a review from a team as a code owner October 5, 2026 14:25
@coderabbitai

coderabbitai Bot commented Oct 5, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Navigate logical layers of code changes, visualize relationships, and explore their blast radius.

🧰 Additional context used
📚 Code guidelines (2)
docs/README.md — auto-discovered
AGENTS.md — auto-discovered

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Repository: prisma/orm/.coderabbit.yml
  • Review profile: CHILL
  • Plan: Advanced
  • Run ID: beba0457-633f-4ec2-85e4-cad1a6358112
📥 Commits

Reviewing files that changed from the base of the PR and between 32de9e1 and 320ad67.

📒 Files selected for processing (22)
  • docs/architecture docs/adrs/ADR 254 - Data types and casts.md
  • docs/architecture docs/subsystems/5. Adapters & Targets.md
  • packages/3-extensions/pgvector/src/core/data-types.ts
  • packages/3-extensions/pgvector/test/data-types.test.ts
  • packages/3-extensions/pgvector/test/migrations/vector-list-default.integration.test.ts
  • packages/3-extensions/postgres/README.md
  • packages/3-targets/3-targets/postgres/README.md
  • packages/3-targets/3-targets/postgres/src/core/codec-helpers.ts
  • packages/3-targets/3-targets/postgres/src/core/data-types.ts
  • packages/3-targets/3-targets/postgres/src/core/default-normalizer.ts
  • packages/3-targets/3-targets/postgres/src/core/prisma7-binding.ts
  • packages/3-targets/3-targets/postgres/test/bytea-canonical-form.test.ts
  • packages/3-targets/3-targets/postgres/test/date-time-codecs.canonical-form.test.ts
  • packages/3-targets/3-targets/postgres/test/default-normalizer.bytea.test.ts
  • packages/3-targets/3-targets/postgres/test/psl-infer/inferred-psl/inferred-psl.data-type-defaults.test.ts
  • packages/3-targets/6-adapters/postgres/src/core/control-adapter.ts
  • packages/3-targets/6-adapters/postgres/test/migrations/bytea-sql-defaults.integration.test.ts
  • packages/3-targets/6-adapters/postgres/test/migrations/codec-literal-defaults.integration.test.ts
  • packages/3-targets/6-adapters/postgres/test/migrations/schema-verify.session-output-settings.integration.test.ts
  • test/integration/test/cli-journeys/bytea-defaults.e2e.test.ts
  • upgrade-instructions/pending/bytea-defaults-verify/app/instructions.md
  • upgrade-instructions/pending/bytea-defaults-verify/extension/instructions.md

Included review availability: This review used your included allowance. Your plan provides up to 10 included reviews per hour; 8 remain after this review.


📝 Walkthrough

Walkthrough

This change adds canonicalization for PostgreSQL bytea and pgvector values, normalizes bytea defaults from PostgreSQL output, and pins bytea introspection output to hex. It adds migration, schema verification, inference, and CLI coverage, plus upgrade instructions for affected bytea defaults.

Changes

PostgreSQL Default Canonicalization

Layer / File(s) Summary
Canonical forms for bytea and vector values
docs/architecture docs/adrs/ADR 254 - Data types and casts.md, docs/architecture docs/subsystems/5. Adapters & Targets.md, packages/3-extensions/pgvector/src/core/data-types.ts, packages/3-targets/3-targets/postgres/src/core/codec-helpers.ts, packages/3-targets/3-targets/postgres/src/core/data-types.ts, packages/3-extensions/pgvector/test/data-types.test.ts, packages/3-targets/3-targets/postgres/test/bytea-canonical-form.test.ts, packages/3-targets/3-targets/postgres/test/date-time-codecs.canonical-form.test.ts
The bytea codec canonicalizes PostgreSQL hex and base64 text to base64. The vector codec accepts finite number arrays and PostgreSQL-printed vector text, and normalizes negative zero. Tests cover casts and comparisons of defaults.
Bytea introspection and default normalization
packages/3-targets/6-adapters/postgres/src/core/control-adapter.ts, packages/3-targets/3-targets/postgres/src/core/default-normalizer.ts, packages/3-extensions/postgres/README.md, packages/3-targets/3-targets/postgres/README.md, packages/3-targets/3-targets/postgres/src/core/prisma7-binding.ts, packages/3-targets/3-targets/postgres/test/default-normalizer.bytea.test.ts, packages/3-targets/3-targets/postgres/test/psl-infer/inferred-psl/inferred-psl.data-type-defaults.test.ts, packages/3-targets/6-adapters/postgres/test/migrations/schema-verify.session-output-settings.integration.test.ts
Introspection pins bytea_output to hex and reads and restores the caller’s setting. The default normalizer converts recognized bytea hex and escape input to base64; unrecognized scalar input remains a function expression. Tests cover parsing and session output settings.
Migration and CLI default workflows
packages/3-extensions/pgvector/test/migrations/vector-list-default.integration.test.ts, packages/3-targets/6-adapters/postgres/test/migrations/bytea-sql-defaults.integration.test.ts, packages/3-targets/6-adapters/postgres/test/migrations/codec-literal-defaults.integration.test.ts, test/integration/test/cli-journeys/bytea-defaults.e2e.test.ts, upgrade-instructions/pending/bytea-defaults-verify/app/instructions.md, upgrade-instructions/pending/bytea-defaults-verify/extension/instructions.md
Integration tests exercise vector and bytea defaults through migrations, schema verification, and CLI journeys. The upgrade instructions describe re-emitting affected bytea defaults and signing or migrating before deployment.

Priority: ➖ Normal

Estimated code review effort: 3 (Moderate) | ~25 minutes

Change: Bug fix

Suggested reviewers: tensordreams

Merge Risk: ⚪ Minimal · up to 320ad

No confirmed issue blocks merging. Follow the documented signing or migration steps when deploying re-emitted bytea contracts.

Security Architecture Review

Security architecture risk: 🔵 Low · up to 320ad

The change uses existing validation and comparison mechanisms without establishing a new privilege or authentication boundary. Risk is bounded mainly to shared-connection output settings and coordinating re-generated contracts with database markers before deployment.

Retained concerns

  • Low · reliability · inferred: For overlapping introspections using the same control driver, the snapshot/apply/read/restore sequence has no operation-level serialization. One invocation can capture another invocation’s pinned settings and restore them after the original caller settings were restored, leaving bytea_output changed or allowing catalog reads under the wrong output mode. This extends an existing date/time-setting ownership weakness to bytea; normal sequential restoration and aborted-transaction rollback are counterevidence, and no privilege escalation is established.
Security review details

Security Blast Radius

  • inferred — The session-ownership concern is bounded to callers sharing one control connection and the namespaces inspected through it. The inspected change affects value interpretation and schema reporting, not database-role privileges; broader tenant or deployment exposure is not established.

Security Findings and Attack Paths

  • inferred — No injection or privilege-escalation path was established in the inspected canonicalization flow. Schema-authored values and catalog text reach bounded representation parsers and default comparison. This conclusion does not establish complete security coverage.

Trust Boundaries and Controls

  • observed — Bytea canonicalization validates complete hex or base64 spellings before decoding. Runtime bytea wire decoding remains restricted to byte arrays or validated PostgreSQL hex. Vector canonicalization requires complete numeric tokens and finite numbers.

Resilience and Maintainability Implications

  • observed — Callback errors are rethrown even when attempted restoration fails. Inside an aborted transaction, the documented recovery owner is the caller, whose rollback restores local settings. These mechanisms do not prove restoration after every interruption or overlapping invocation.

Hardening Proposals

  • proposed — Give each pin/read/restore operation exclusive ownership of its control connection, and define a rollback or connection-discard policy when restoration cannot complete. This would contain configuration drift without changing canonical-value semantics.
🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 24.14% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 29 functions across 16 files. (6 skipped:… Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly summarizes the main change: PostgreSQL bytea and vector literal defaults now verify after application.
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.
Full details: Docstring Coverage

Explanation

Docstring coverage is 24.14% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 29 functions across 16 files. (6 skipped: 6 unsupported.)

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
  • Autopilot · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

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

@pkg-pr-new

pkg-pr-new Bot commented Oct 5, 2026

Copy link
Copy Markdown

Open in StackBlitz

@prisma/orm-extension-arktype-json

npm i https://pkg.pr.new/@prisma/orm-extension-arktype-json@30603

@prisma/orm-extension-middleware-cache

npm i https://pkg.pr.new/@prisma/orm-extension-middleware-cache@30603

@prisma/orm-extension-paradedb

npm i https://pkg.pr.new/@prisma/orm-extension-paradedb@30603

@prisma/orm-extension-pgvector

npm i https://pkg.pr.new/@prisma/orm-extension-pgvector@30603

@prisma/orm-extension-postgis

npm i https://pkg.pr.new/@prisma/orm-extension-postgis@30603

@prisma/orm-extension-supabase

npm i https://pkg.pr.new/@prisma/orm-extension-supabase@30603

@prisma/orm-family-mongo

npm i https://pkg.pr.new/@prisma/orm-family-mongo@30603

@prisma/orm-family-sql

npm i https://pkg.pr.new/@prisma/orm-family-sql@30603

@prisma/orm-framework

npm i https://pkg.pr.new/@prisma/orm-framework@30603

@prisma/orm-mongo

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

@prisma/orm-postgres

npm i https://pkg.pr.new/@prisma/orm-postgres@30603

@prisma/orm-sqlite

npm i https://pkg.pr.new/@prisma/orm-sqlite@30603

@prisma/orm-target-mongo

npm i https://pkg.pr.new/@prisma/orm-target-mongo@30603

@prisma/orm-target-postgres

npm i https://pkg.pr.new/@prisma/orm-target-postgres@30603

@prisma/orm-target-sqlite

npm i https://pkg.pr.new/@prisma/orm-target-sqlite@30603

@prisma/orm-toolchain

npm i https://pkg.pr.new/@prisma/orm-toolchain@30603

commit: 320ad67

@github-actions

github-actions Bot commented Oct 5, 2026

Copy link
Copy Markdown
Contributor

size-limit report 📦

Path Size
postgres / no-emit 216.33 KB (+0.25% 🔺)
postgres / emit 193.72 KB (+0.26% 🔺)
mongo / no-emit 196.09 KB (0%)
mongo / emit 175.19 KB (0%)
cf-worker / no-emit 272.27 KB (+0.21% 🔺)
cf-worker / emit 247.04 KB (+0.2% 🔺)

@wmadden
wmadden added this pull request to the merge queue Oct 5, 2026
Merged via the queue into main with commit 5767530 Oct 5, 2026
27 checks passed
@wmadden
wmadden deleted the tml-3283-read-defaults-back-through-codec branch October 5, 2026 16:10
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants