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

feat(sql-contract-psl): close PSL-TS contract parity gaps - #229

Merged
wmadden merged 52 commits into
mainfrom
psl-capabilities-and-extensions
Mar 11, 2026
Merged

wmadden merged 52 commits into
mainfrom
psl-capabilities-and-extensions

Conversation

@wmadden

@wmadden wmadden commented Mar 6, 2026 •

Copy link
Copy Markdown
Contributor

closes TML-2039

Key snippets

Before / After — Vector type representation in contract storage

// BEFORE — nativeType embeds dimension; typeRef triggers quoteIdentifier in planner
namedTypeDescriptors.set(declaration.name, {
  codecId: 'pg/vector@1',
  nativeType: `vector(${length})`,
  typeRef: declaration.name,
});
// AFTER — nativeType is base type only; typeParams carries dimension; no typeRef
namedTypeDescriptors.set(declaration.name, {
  codecId: 'pg/vector@1',
  nativeType: 'vector',
  typeParams: { length },
});

New — Provider merges framework metadata into PSL-emitted contracts

const extensionPacks = options?.extensionPacks
  ? mergePlainObjects(interpreted.value.extensionPacks, options.extensionPacks)
  : interpreted.value.extensionPacks;

const mergedCapabilities = mergeCapabilities(
  interpreted.value.capabilities,
  mergeCapabilitiesFromSources(options?.capabilitySources),
);

return ok({
  ...interpreted.value,
  extensionPacks: sortDeepTyped(extensionPacks),
  capabilities: sortDeepTyped(mergedCapabilities),
});

Intent

Bring PSL contract authoring to parity with TypeScript contract authoring for the behaviors exercised by the demo app: framework metadata (extension packs, capabilities), parameterized vector DDL, and FK constraint naming. The end goal is that examples/prisma-next-demo can switch between TS and PSL as its contract source with no behavioral difference — proven by a dual-mode emit test.

Change map

The story

  1. Lock in regressions with tests first. Before making fixes, new test cases and updated fixtures capture the precise failure modes (empty extensionPacks/capabilities, parameterized nativeType shape, unsupported @relation(map: ...)).

  2. Fix the vector type representation across the stack. The root cause of the "vector(1536)" DDL bug was a conflation of two concerns: the PSL interpreter embedded the dimension in nativeType ('vector(1536)') and set typeRef, which caused the planner's quoteIdentifier path to produce "vector(1536)". The fix separates concerns: nativeType holds only the base type name, typeParams carries parameters, and target adapter expansion reassembles them into SQL. This convention is recorded in ADR 170.

  3. Provide a control-plane expandNativeType hook for pgvector. The pgvector control descriptor now exposes an expandNativeType codec hook, ensuring schema verification also expands vector + length → vector(1536) consistently with the planner.

  4. Support @relation(map: ...) for FK constraint naming. The interpreter's relation attribute parser is extended to accept the map argument, parse it as a quoted string, and flow it through the foreignKey() builder. The planner already uses foreignKey.name when present.

  5. Add framework metadata emission to the PSL provider. The interpreter produces contract IR without extensionPacks/capabilities (it has no PSL surface for these). The provider merges them from explicit options (extensionPacks, capabilitySources), deep-merging and sorting keys for deterministic output. capabilitySources is typed as readonly CapabilitySource[] with an exported interface.

  6. Switch the demo to PSL-first and prove dual-mode equivalence. The demo config switches from typescriptContract(...) to prismaContract('./prisma/schema.prisma', ...). A second config (prisma-next.config.ts-contract.ts) preserves the TS path. The test:dual-mode script emits from each source in turn and runs the demo test suite against each, proving behavioral equivalence.

Behavior changes & evidence

Compatibility / migration / risk

  • Breaking contract shape: The nativeType change from 'vector(1536)' to 'vector' changes storage hashes. Users must re-emit contracts via prisma-next contract emit.
  • New fields in contract JSON: extensionPacks and capabilities are now populated where they were previously {}. Hash changes expected.
  • Demo config change: The demo requires @prisma-next/sql-contract-psl as a new dependency. The TS contract (prisma/contract.ts) remains for the no-emit workflow and dual-mode testing.

Follow-ups / open questions

  • The typeRef → quoteIdentifier(nativeType) path in the planner remains for non-parameterized named types (e.g., enums). Any future parameterized extension type that uses typeRef would hit the same quoting issue — a systemic fix is deferred.
  • Automatic capability derivation from target/extension packs (without explicit capabilitySources) is deferred (spec Open Question 1).

Non-goals / intentionally out of scope

  • Full Prisma ORM PSL surface area parity (e.g., implicit many-to-many).
  • New extension packs or SQL operations beyond pgvector.
  • Automatic capability derivation from composed packs (requires a discovery mechanism).

Summary by CodeRabbit

  • New Features

    • Added support for parameterized native types in contracts (e.g., vector embeddings with configurable dimensions).
    • Introduced dual-mode contract emission for PSL and TypeScript with new emit scripts and validation workflows.
    • Enhanced pgvector integration in example application with embedding field support.
  • Documentation

    • Added ADR 170 documenting parameterized native types architecture and implementation approach.
    • Added glossary defining core concepts and terminology for Prisma Next.

@coderabbitai

coderabbitai Bot commented Mar 6, 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 pull request implements ADR 170: Parameterized Native Types in Contracts, where parameterized storage types now store the base native type name separately from parameters. Type expansion is refactored from centralized logic to codec-hook-driven expansion, contract source providers accept a context parameter with composed extension packs, and contract enrichment merges framework capabilities with extension metadata.

Changes

Cohort / File(s) Summary
Architecture & ADR Documentation
docs/architecture/adrs/ADR 170 - Parameterized native types in contracts.md
Introduces ADR 170 specifying parameterized native type handling via nativeType + typeParams with codec-hook-driven expansion.
Contract Source Context
packages/1-framework/1-core/shared/config/src/contract-source-types.ts, packages/1-framework/1-core/shared/config/src/exports/config-types.ts
Adds ContractSourceContext interface with composedExtensionPacks; updates ContractSourceProvider signature to accept context parameter.
PSL Contract Provider
packages/2-sql/2-authoring/contract-psl/src/provider.ts, packages/2-sql/2-authoring/contract-psl/src/interpreter.ts, packages/2-sql/2-authoring/contract-psl/test/*
Updates prismaContract to use context-driven composedExtensionPacks; adds constraintName to relation attributes; changes vector nativeType from vector(1536) to vector with typeParams; updates foreign key handling with constraint names.
TypeScript Contract Provider
packages/2-sql/2-authoring/contract-ts/src/config-types.ts, packages/2-sql/2-authoring/contract-ts/test/config-types.test.ts
Updates typescriptContract source signature to accept context parameter with composedExtensionPacks.
Contract Enrichment & CLI
packages/1-framework/3-tooling/cli/src/control-api/contract-enrichment.ts, packages/1-framework/3-tooling/cli/src/control-api/client.ts, packages/1-framework/3-tooling/cli/src/control-api/operations/contract-emit.ts, packages/1-framework/3-tooling/cli/src/exports/control-api.ts, packages/1-framework/3-tooling/cli/test/control-api/contract-enrichment.test.ts
Introduces enrichContractIR function to merge framework-derived capabilities and extension pack metadata into ContractIR; threads enrichment through emit workflows.
PostgreSQL Adapter Type Expansion
packages/3-targets/6-adapters/postgres/src/core/parameterized-types.ts, packages/3-targets/6-adapters/postgres/src/core/descriptor-meta.ts, packages/3-targets/6-adapters/postgres/src/exports/control.ts, packages/3-targets/6-adapters/postgres/test/parameterized-types.test.ts, packages/3-targets/6-adapters/postgres/test/descriptor-meta.test.ts
Removes centralized expandParameterizedNativeType; implements codec-specific hooks (expandLength, expandPrecision, expandNumeric) in descriptor-meta for length-based, numeric, and temporal types.
PostgreSQL Migration Planner
packages/3-targets/3-targets/postgres/src/core/migrations/planner.ts, packages/3-targets/3-targets/postgres/src/core/migrations/planner-reconciliation.ts, packages/3-targets/3-targets/postgres/src/exports/control.ts, packages/3-targets/3-targets/postgres/test/migrations/planner.case1.test.ts, packages/3-targets/3-targets/postgres/test/migrations/planner.contract-to-schema-ir.test.ts, packages/3-targets/3-targets/postgres/test/migrations/planner.reconciliation-unit.test.ts
Threads codecHooks through migration planner; replaces direct type expansion with hook-based approach via CodecControlHooks; updates contractToSchema to build NativeTypeExpander from framework components.
pgvector Extension
packages/3-extensions/pgvector/src/exports/column-types.ts, packages/3-extensions/pgvector/src/exports/control.ts, packages/3-extensions/pgvector/test/column-types.test.ts
Implements vectorControlPlaneHooks with expandNativeType logic; updates vector factory to emit nativeType vector with typeParams.length; extends pgvectorExtensionDescriptor with codecTypes.controlPlaneHooks.
Demo Application Configuration
examples/prisma-next-demo/prisma-next.config.ts, examples/prisma-next-demo/prisma-next.config.ts-contract.ts, examples/prisma-next-demo/package.json, examples/prisma-next-demo/README.md
Adds dual-mode emit configuration (PSL and TypeScript); imports prismaContract from psl provider; adds emit:psl, emit:ts, test:dual-mode scripts; documents workflow changes.
Demo Application Schema & Context
examples/prisma-next-demo/prisma/schema.prisma, examples/prisma-next-demo/src/prisma-no-emit/context.ts, examples/prisma-next-demo/src/prisma/contract.d.ts, examples/prisma-next-demo/src/prisma/contract.json
Adds Embedding1536 type with pgvector; updates User/Post models with embedding field; adds pgvector to extensionPacks; updates contract hashes and embedding storage representation.
Demo Application Queries
examples/prisma-next-demo/src/queries/similarity-search.ts, examples/prisma-next-demo/src/queries/similarity-search.test-d.ts, examples/prisma-next-demo/src/queries/similarity-search.types.test.ts, examples/prisma-next-demo/src/queries/get-user-posts.types.test.ts, examples/prisma-next-demo/test/utils/control-client.ts
Simplifies similaritySearch by removing type guards; converts type assertions from runtime (expectTypeOf) to compile-time (Equal/Expect); improves error reporting for dbInit failures.
Test Fixtures - Contract Hashes & Capabilities
test/integration/test/authoring/parity/*/expected.contract.json (10 files), test/integration/test/authoring/parity/core-surface/..., test/integration/test/authoring/parity/map-attributes/..., test/integration/test/authoring/parity/pgvector-named-type/...
Updates profileHash across all expected contract fixtures; adds capabilities structure with postgres (jsonAgg, lateral, limit, orderBy, returning) and sql (enums) flags.
Schema & Contract Parity Tests
test/integration/test/authoring/parity/map-attributes/schema.prisma, test/integration/test/authoring/parity/map-attributes/contract.ts, test/integration/test/authoring/parity/map-attributes/expected.contract.json, test/integration/test/authoring/parity/pgvector-named-type/contract.ts, test/integration/test/authoring/parity/pgvector-named-type/expected.contract.json
Adds map constraint names to foreign key relations; updates vector types from vector(1536) to vector with typeParams; includes pgvector extensionPacks metadata.
Integration Tests
test/integration/test/authoring/psl.pgvector-dbinit.test.ts, test/integration/test/authoring/cli.emit-parity-fixtures.test.ts, test/integration/test/cli.emit-command.test.ts, test/integration/test/cli.emit-contract.test.ts
Adds new pgvector dbInit test; updates source invocations to pass ContractSourceContext; threads enrichContractIR into emit test helpers.
Test Configuration & Utilities
test/integration/test/authoring/templates/prisma-next.config.parity-psl.ts, test/utils/src/typed-expectations.ts, packages/3-targets/3-targets/postgres/package.json
Removes composedExtensionPacks from contract options; adds Equal/Expect type utilities for compile-time assertions; adds pgvector devDependency to postgres adapter.
Documentation & Repository
docs/README.md, docs/glossary.md, .gitignore
Adds glossary link and comprehensive glossary file defining Prisma Next terminology; ignores local review artifact directories.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

The changes span multiple architectural layers (contract authoring, type expansion, migration planning, extension system) with dense logic around codec hooks and contract enrichment. While there is repetition in test fixture updates, the heterogeneous nature of edits across contract source providers, the planner, adapters, and extensions demands careful review of integration points and hook wiring. Approximately 70+ affected files with significant logic modifications.

Poem

🐰 Hoppy hops through parameterized fields,
Where vectors no longer hold lengths revealed,
Hooks expand types with codec's delight,
Enriched contracts glow in the light,
From PSL to TypeScript, a dual-mode feast! ✨

🚥 Pre-merge checks | ✅ 2 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 18.37% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (2 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title clearly and specifically describes the main change: closing PSL-TS contract parity gaps through feature implementation of parameterized types and capability handling.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Post copyable unit tests in a comment
  • Commit unit tests in branch psl-capabilities-and-extensions

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

@pkg-pr-new

pkg-pr-new Bot commented Mar 6, 2026 •

Copy link
Copy Markdown

Open in StackBlitz

@prisma-next/runtime-executor

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

@prisma-next/sql-runtime

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

@prisma-next/extension-paradedb

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

@prisma-next/extension-pgvector

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

@prisma-next/postgres

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

@prisma-next/sql-orm-client

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

@prisma-next/contract-authoring

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

@prisma-next/contract-ts

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

@prisma-next/ids

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

@prisma-next/psl-parser

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

@prisma-next/cli

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

@prisma-next/emitter

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

@prisma-next/eslint-plugin

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/eslint-plugin@229

@prisma-next/migration-tools

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

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

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

@prisma-next/sql-contract

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

@prisma-next/sql-errors

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

@prisma-next/sql-operations

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

@prisma-next/sql-schema-ir

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

@prisma-next/sql-contract-psl

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

@prisma-next/sql-contract-ts

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

@prisma-next/sql-contract-emitter

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

@prisma-next/family-sql

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

@prisma-next/sql-kysely-lane

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-kysely-lane@229

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

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

@prisma-next/sql-relational-core

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

@prisma-next/sql-lane

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/sql-lane@229

@prisma-next/target-postgres

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

@prisma-next/adapter-postgres

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

@prisma-next/driver-postgres

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

@prisma-next/core-control-plane

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/core-control-plane@229

@prisma-next/core-execution-plane

npm i https://pkg.pr.new/prisma/prisma-next/@prisma-next/core-execution-plane@229

@prisma-next/config

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

@prisma-next/contract

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

@prisma-next/operations

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

@prisma-next/plan

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

@prisma-next/utils

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

commit: 42a0a55

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 5

🧹 Nitpick comments (6)
docs/architecture docs/adrs/ADR 170 - Parameterized native types in contracts.md (1)

45-45: Use the canonical architectural term for control-plane ownership.

Consider replacing “composed framework components” with “SQL family instance” to match established architecture vocabulary and reduce ambiguity.

Suggested wording tweak
-- Where schema verification is codec-hook driven, parameterized type expansion should be provided via control-plane codec hooks on the composed framework components.
+- Where schema verification is codec-hook driven, parameterized type expansion should be provided via control-plane codec hooks on the SQL family instance.

Based on learnings: preserve the domain-specific term "SQL family instance" when referring to an instantiated SqlControlFamilyInstance that provides control-plane operations.

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

In `@docs/architecture` docs/adrs/ADR 170 - Parameterized native types in
contracts.md at line 45, Replace the ambiguous phrase "composed framework
components" with the canonical term "SQL family instance" throughout the
sentence and any related text so the document consistently refers to an
instantiated SqlControlFamilyInstance that provides control-plane operations;
update the sentence currently reading "Where schema verification is codec-hook
driven, parameterized type expansion should be provided via control-plane codec
hooks on the composed framework components." to use "SQL family instance" and
ensure any nearby references or examples that imply control-plane ownership
reference SqlControlFamilyInstance explicitly.
test/integration/test/authoring/templates/prisma-next.config.parity-ts.ts (2)

48-58: Use ifDefined() for conditional spread fields.

The inline ...(cond ? { ... } : {}) patterns here should be converted to ifDefined() for consistency with repo conventions.
As per coding guidelines, "{packages,examples,test}/**/*.{ts,tsx}: Use ifDefined() from @prisma-next/utils/defined for conditional object spreads instead of inline conditional spread patterns."

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

In `@test/integration/test/authoring/templates/prisma-next.config.parity-ts.ts`
around lines 48 - 58, Replace the inline conditional object spreads for
descriptor['capabilities'] and types.codecTypes with the repo's ifDefined
helper: import ifDefined from '@prisma-next/utils/defined' (or use existing
import) and change the two occurrences where code uses
"...(descriptor['capabilities'] ? { capabilities: descriptor['capabilities'] } :
{})" and the nested "...(types ? { types: { ... } } : {})" / "codecTypes ? {
...codecTypes, controlPlaneHooks: undefined } : undefined" to use ifDefined(...)
so the object uses ifDefined(descriptor['capabilities'], value => ({
capabilities: value })) and similarly wrap types and codecTypes with ifDefined
to produce the same conditional spreads consistently.

95-96: Avoid the force-cast on result.value at Line 95.

Prefer a type-guarded path (isPlainObject) to extract capabilities instead of as casting.
As per coding guidelines, "**/*.{ts,tsx}: Replace blind casts with type predicates instead of as casts."

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

In `@test/integration/test/authoring/templates/prisma-next.config.parity-ts.ts`
around lines 95 - 96, Replace the blind cast on result.value when reading
capabilities with a type-guarded extraction: use the isPlainObject predicate to
check result.value, confirm it has a capabilities key, and only then read and
assign capabilities as a Record<string, unknown>; otherwise fallback to {}.
Update the code around result.value and capabilities to import/use
isPlainObject, perform the guard (e.g. if (isPlainObject(result.value) &&
'capabilities' in result.value) …), and remove the force-cast so capabilities is
safely typed without using as on result.value.
test/integration/test/authoring/templates/prisma-next.config.parity-psl.ts (2)

9-39: Consider sharing extensionPackMetaFromDescriptor across parity templates.

This helper now duplicates the same transformation logic used in test/integration/test/authoring/templates/prisma-next.config.parity-ts.ts (Lines 31-60), which can drift over time.

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

In `@test/integration/test/authoring/templates/prisma-next.config.parity-psl.ts`
around lines 9 - 39, Duplicate helper extensionPackMetaFromDescriptor is present
in multiple parity templates; extract it into a single shared utility and import
it from both templates to avoid drift. Create a shared module exporting
extensionPackMetaFromDescriptor (preserving its signature and behavior,
including the types/codecTypes handling and the controlPlaneHooks removal),
replace the local implementation in prisma-next.config.parity-psl.ts and
prisma-next.config.parity-ts.ts with an import and use the shared function, and
update any exports/typing so both templates compile unchanged.

27-38: Switch inline conditional spreads to ifDefined().

Both metadata shaping and conditional contract-option injection use spread ternaries that should follow the repo’s ifDefined() convention.
As per coding guidelines, "{packages,examples,test}/**/*.{ts,tsx}: Use ifDefined() from @prisma-next/utils/defined for conditional object spreads instead of inline conditional spread patterns."

Also applies to: 54-59

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

In `@test/integration/test/authoring/templates/prisma-next.config.parity-psl.ts`
around lines 27 - 38, Replace the inline conditional spread patterns with the
project's ifDefined() helper from `@prisma-next/utils/defined`: instead of using
...(record['capabilities'] ? { capabilities: record['capabilities'] } : {}) and
the ternary around types/codecTypes, call ifDefined(record['capabilities'], v =>
({ capabilities: v })) and ifDefined(types, t => ({ types: { ...t, codecTypes:
t.codecTypes ? { ...t.codecTypes, controlPlaneHooks: undefined } : undefined
}})); apply the same ifDefined transformation to the similar block at lines
referenced (54-59) so all conditional object spreads follow the repo convention.
examples/prisma-next-demo/src/queries/get-user-posts.types.test.ts (1)

10-18: Prefer Vitest expectTypeOf matchers over local Equal/Expect/NotNever helpers in *.test.ts.

This keeps type tests consistent with the repo standard and avoids duplicated custom type-assertion utilities.

♻️ Proposed refactor
-import { test } from 'vitest';
+import { expectTypeOf, test } from 'vitest';
@@
-type Equal<A, B> =
-  (<T>() => T extends A ? 1 : 2) extends <T>() => T extends B ? 1 : 2 ? true : false;
-type Expect<T extends true> = T;
 type NotNever<T> = [T] extends [never] ? false : true;
@@
-  // Compile-time assertions
-  type Assertions = [
-    Expect<Equal<Row['embedding'], Vector<1536> | null>>,
-    Expect<Equal<Row['id'], Char<36>>>,
-    Expect<Equal<Row['title'], string>>,
-    Expect<Equal<Row['userId'], string>>,
-    Expect<NotNever<Row['createdAt']>>,
-  ];
-  const assertions = null as unknown as Assertions;
-  void assertions;
+  expectTypeOf<Row['embedding']>().toEqualTypeOf<Vector<1536> | null>();
+  expectTypeOf<Row['id']>().toEqualTypeOf<Char<36>>();
+  expectTypeOf<Row['title']>().toEqualTypeOf<string>();
+  expectTypeOf<Row['userId']>().toEqualTypeOf<string>();
+  type CreatedAtIsNotNever = NotNever<Row['createdAt']>;
+  expectTypeOf<CreatedAtIsNotNever>().toEqualTypeOf<true>();

As per coding guidelines: **/*.{test,spec}.{ts,tsx}: “Use type test patterns with vitest; prefer expectTypeOf for type assertions.”

Also applies to: 46-55

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

In `@examples/prisma-next-demo/src/queries/get-user-posts.types.test.ts` around
lines 10 - 18, Replace the local type-assertion helpers Equal, Expect, and
NotNever in get-user-posts.types.test.ts with Vitest's expectTypeOf matchers:
locate the type helpers (Equal, Expect, NotNever) and any assertions that use
them, then convert those assertions to use expectTypeOf<typeof
SomeType>().toEqualTypeOf<OtherType>() or expectTypeOf<T>().not.toBeNever() /
.toBeNever() equivalents; ensure imports use Vitest's expectTypeOf and remove
the now-unused helper type declarations (Equal, Expect, NotNever).
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@examples/prisma-next-demo/src/queries/similarity-search.test-d.ts`:
- Around line 8-13: The file defines custom type helpers Equal and Expect;
replace this pattern with Vitest's built-in expectTypeOf: remove the type
aliases Equal and Expect and add an import for expectTypeOf from 'vitest', then
rewrite any assertions that used Expect<Equal<...>> to use
expectTypeOf(...).toMatchTypeOf(...) or the appropriate expectTypeOf matcher
against the subject (e.g., db or specific types used in the test). Update
occurrences referencing Equal or Expect accordingly (search for the symbols
Equal and Expect and replace those assertions with expectTypeOf-based calls).

In `@packages/2-sql/2-authoring/contract-psl/src/interpreter.ts`:
- Around line 1028-1040: The code currently parses constraintNameRaw into
constraintName for all relation attributes (constraintNameRaw, constraintName,
parseQuotedStringLiteral) but never errors when a map is supplied on a
backrelation-list field (the backrelation-list validation branch), causing a
silent no-op; update the backrelation-list validation branch to check if
constraintNameRaw is present and, if so, push the same
PSL_INVALID_RELATION_ATTRIBUTE diagnostic (with the same message and span using
input.modelName, input.fieldName, input.sourceId, input.attribute.span) and
return undefined so that `@relation`(map: ...) on list-side backrelations is
rejected; apply the same guard for the other occurrence around 1080-1085.

In `@packages/3-targets/3-targets/postgres/test/migrations/planner.case1.test.ts`:
- Line 300: Replace the unsafe cast 'sha256:profile' as never with the typed
constructor call profileHash('sha256:profile'); update the object property
currently set to "profileHash: 'sha256:profile' as never" to "profileHash:
profileHash('sha256:profile')" using the imported profileHash function so the
value is properly typed and consistent with other tests.

In `@test/integration/test/authoring/psl.pgvector-dbinit.test.ts`:
- Around line 1-3: The test imports join from 'node:path' but the repo
standardizes on 'pathe'; replace the import of join so it comes from 'pathe'
instead of 'node:path' (i.e., change "import { join } from 'node:path';" to
"import { join } from 'pathe';") while leaving the other fs imports (existsSync,
rmSync, writeFileSync) and the postgresAdapter import untouched so path
utilities use pathe's cross-runtime behavior.
- Around line 71-100: The test uses withDevDatabase (pglite) which lacks
pgvector extension support; replace the test harness so the DDL in
client.dbInit({ mode: 'apply' }) runs against a real PostgreSQL instance that
supports extensions. Concretely, swap out withDevDatabase(...) for your
real-Postgres test helper (e.g., withPostgresDatabase or the project’s real-DB
fixture) that yields a connectionString to a PostgreSQL server with extension
installation privileges, keep createControlClient(...) and the dbInit calls
(plan and apply) as-is, and ensure the test setup/teardown provisions that the
pgvector extension is available before running client.dbInit({ mode: 'apply' }).

---

Nitpick comments:
In `@docs/architecture` docs/adrs/ADR 170 - Parameterized native types in
contracts.md:
- Line 45: Replace the ambiguous phrase "composed framework components" with the
canonical term "SQL family instance" throughout the sentence and any related
text so the document consistently refers to an instantiated
SqlControlFamilyInstance that provides control-plane operations; update the
sentence currently reading "Where schema verification is codec-hook driven,
parameterized type expansion should be provided via control-plane codec hooks on
the composed framework components." to use "SQL family instance" and ensure any
nearby references or examples that imply control-plane ownership reference
SqlControlFamilyInstance explicitly.

In `@examples/prisma-next-demo/src/queries/get-user-posts.types.test.ts`:
- Around line 10-18: Replace the local type-assertion helpers Equal, Expect, and
NotNever in get-user-posts.types.test.ts with Vitest's expectTypeOf matchers:
locate the type helpers (Equal, Expect, NotNever) and any assertions that use
them, then convert those assertions to use expectTypeOf<typeof
SomeType>().toEqualTypeOf<OtherType>() or expectTypeOf<T>().not.toBeNever() /
.toBeNever() equivalents; ensure imports use Vitest's expectTypeOf and remove
the now-unused helper type declarations (Equal, Expect, NotNever).

In `@test/integration/test/authoring/templates/prisma-next.config.parity-psl.ts`:
- Around line 9-39: Duplicate helper extensionPackMetaFromDescriptor is present
in multiple parity templates; extract it into a single shared utility and import
it from both templates to avoid drift. Create a shared module exporting
extensionPackMetaFromDescriptor (preserving its signature and behavior,
including the types/codecTypes handling and the controlPlaneHooks removal),
replace the local implementation in prisma-next.config.parity-psl.ts and
prisma-next.config.parity-ts.ts with an import and use the shared function, and
update any exports/typing so both templates compile unchanged.
- Around line 27-38: Replace the inline conditional spread patterns with the
project's ifDefined() helper from `@prisma-next/utils/defined`: instead of using
...(record['capabilities'] ? { capabilities: record['capabilities'] } : {}) and
the ternary around types/codecTypes, call ifDefined(record['capabilities'], v =>
({ capabilities: v })) and ifDefined(types, t => ({ types: { ...t, codecTypes:
t.codecTypes ? { ...t.codecTypes, controlPlaneHooks: undefined } : undefined
}})); apply the same ifDefined transformation to the similar block at lines
referenced (54-59) so all conditional object spreads follow the repo convention.

In `@test/integration/test/authoring/templates/prisma-next.config.parity-ts.ts`:
- Around line 48-58: Replace the inline conditional object spreads for
descriptor['capabilities'] and types.codecTypes with the repo's ifDefined
helper: import ifDefined from '@prisma-next/utils/defined' (or use existing
import) and change the two occurrences where code uses
"...(descriptor['capabilities'] ? { capabilities: descriptor['capabilities'] } :
{})" and the nested "...(types ? { types: { ... } } : {})" / "codecTypes ? {
...codecTypes, controlPlaneHooks: undefined } : undefined" to use ifDefined(...)
so the object uses ifDefined(descriptor['capabilities'], value => ({
capabilities: value })) and similarly wrap types and codecTypes with ifDefined
to produce the same conditional spreads consistently.
- Around line 95-96: Replace the blind cast on result.value when reading
capabilities with a type-guarded extraction: use the isPlainObject predicate to
check result.value, confirm it has a capabilities key, and only then read and
assign capabilities as a Record<string, unknown>; otherwise fallback to {}.
Update the code around result.value and capabilities to import/use
isPlainObject, perform the guard (e.g. if (isPlainObject(result.value) &&
'capabilities' in result.value) …), and remove the force-cast so capabilities is
safely typed without using as on result.value.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

Run ID: de947a95-ff66-4b8e-924d-708e4e6dbb76

📥 Commits

Reviewing files that changed from the base of the PR and between ab54257 and 783f828.

⛔ Files ignored due to path filters (6)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
  • projects/psl-contract-authoring/plans/psl-contract-parity-missing-behaviors-plan.md is excluded by !projects/**
  • projects/psl-contract-authoring/specs/psl-contract-parity-missing-behaviors.spec.md is excluded by !projects/**
  • projects/psl-contract-authoring/specs/reviews/code-review.md is excluded by !projects/**
  • projects/psl-contract-authoring/specs/reviews/system-design-review.md is excluded by !projects/**
  • projects/psl-contract-authoring/specs/reviews/walkthrough.md is excluded by !projects/**
📒 Files selected for processing (33)
  • docs/architecture docs/adrs/ADR 170 - Parameterized native types in contracts.md
  • examples/prisma-next-demo/README.md
  • examples/prisma-next-demo/package.json
  • examples/prisma-next-demo/prisma-next.config.ts
  • examples/prisma-next-demo/prisma-next.config.ts-contract.ts
  • examples/prisma-next-demo/prisma/schema.prisma
  • examples/prisma-next-demo/src/prisma-no-emit/context.ts
  • examples/prisma-next-demo/src/prisma/contract.d.ts
  • examples/prisma-next-demo/src/prisma/contract.json
  • examples/prisma-next-demo/src/queries/get-user-posts.types.test.ts
  • examples/prisma-next-demo/src/queries/similarity-search.test-d.ts
  • examples/prisma-next-demo/src/queries/similarity-search.ts
  • examples/prisma-next-demo/src/queries/similarity-search.types.test.ts
  • examples/prisma-next-demo/test/utils/control-client.ts
  • packages/2-sql/2-authoring/contract-psl/src/interpreter.ts
  • packages/2-sql/2-authoring/contract-psl/src/provider.ts
  • packages/2-sql/2-authoring/contract-psl/test/interpreter.diagnostics.test.ts
  • packages/2-sql/2-authoring/contract-psl/test/interpreter.relations.test.ts
  • packages/2-sql/2-authoring/contract-psl/test/provider.test.ts
  • packages/3-extensions/pgvector/src/exports/column-types.ts
  • packages/3-extensions/pgvector/src/exports/control.ts
  • packages/3-extensions/pgvector/test/column-types.test.ts
  • packages/3-targets/3-targets/postgres/test/migrations/planner.case1.test.ts
  • packages/3-targets/6-adapters/postgres/src/core/parameterized-types.ts
  • packages/3-targets/6-adapters/postgres/test/parameterized-types.test.ts
  • test/integration/test/authoring/parity/map-attributes/contract.ts
  • test/integration/test/authoring/parity/map-attributes/expected.contract.json
  • test/integration/test/authoring/parity/map-attributes/schema.prisma
  • test/integration/test/authoring/parity/pgvector-named-type/contract.ts
  • test/integration/test/authoring/parity/pgvector-named-type/expected.contract.json
  • test/integration/test/authoring/psl.pgvector-dbinit.test.ts
  • test/integration/test/authoring/templates/prisma-next.config.parity-psl.ts
  • test/integration/test/authoring/templates/prisma-next.config.parity-ts.ts

@wmadden
wmadden force-pushed the psl-capabilities-and-extensions branch from 783f828 to e383b36 Compare March 6, 2026 16:52

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

♻️ Duplicate comments (1)
packages/2-sql/2-authoring/contract-psl/src/interpreter.ts (1)

1028-1040: ⚠️ Potential issue | 🟡 Minor

Reject @relation(map: ...) on backrelation-list fields to avoid silent no-op.

map is now parsed into constraintName, but list-side backrelations still only reject fields/references and onDelete/onUpdate. This allows invalid list-side map usage to pass silently and then be ignored.

🐛 Suggested guard in backrelation-list validation branch
         if (parsedRelation.onDelete || parsedRelation.onUpdate) {
           diagnostics.push({
             code: 'PSL_INVALID_RELATION_ATTRIBUTE',
             message: `Backrelation list field "${model.name}.${field.name}" cannot declare onDelete/onUpdate; define referential actions on the FK-side relation field`,
             sourceId,
             span: relationAttribute.span,
           });
           continue;
         }
+        if (parsedRelation.constraintName) {
+          diagnostics.push({
+            code: 'PSL_INVALID_RELATION_ATTRIBUTE',
+            message: `Backrelation list field "${model.name}.${field.name}" cannot declare map; define FK constraint names on the FK-side relation field`,
+            sourceId,
+            span: relationAttribute.span,
+          });
+          continue;
+        }
         relationName = parsedRelation.relationName;
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/2-sql/2-authoring/contract-psl/src/interpreter.ts` around lines 1028
- 1040, The backrelation-list validation branch currently rejects only
fields/references and onDelete/onUpdate but misses rejecting a `map` argument,
so add a guard that treats a non-empty `constraintNameRaw` (and thus
`constraintName`) as invalid on list-side backrelations: in the
backrelation-list validation code path (the branch that already pushes
diagnostics for fields/references and onDelete/onUpdate), check `if
(constraintNameRaw)` and push a diagnostic with code
'PSL_INVALID_RELATION_ATTRIBUTE' and the same message pattern used above
(`Relation field "${input.modelName}.${input.fieldName}" map argument must be a
quoted string literal` or appropriate text rejecting map usage), then return
undefined—using the existing `input`, `constraintNameRaw`, `constraintName`,
`input.diagnostics`, and `input.attribute.span` symbols to implement the check.
🧹 Nitpick comments (5)
packages/3-extensions/pgvector/src/exports/control.ts (1)

74-82: Preserve existing controlPlaneHooks entries when extending the map.

Line 78 currently replaces the full controlPlaneHooks object. Merging existing entries first avoids accidentally dropping hooks if pgvectorPackMeta.types.codecTypes.controlPlaneHooks grows later.

Proposed diff
   types: {
     ...pgvectorPackMeta.types,
     codecTypes: {
       ...pgvectorPackMeta.types.codecTypes,
       controlPlaneHooks: {
+        ...(pgvectorPackMeta.types.codecTypes.controlPlaneHooks ?? {}),
         [PGVECTOR_CODEC_ID]: vectorControlPlaneHooks,
       },
     },
   },
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/3-extensions/pgvector/src/exports/control.ts` around lines 74 - 82,
The code currently overwrites
pgvectorPackMeta.types.codecTypes.controlPlaneHooks instead of merging new
entries; update the build of types.codecTypes.controlPlaneHooks to spread the
existing pgvectorPackMeta.types.codecTypes.controlPlaneHooks first and then add
the new entry [PGVECTOR_CODEC_ID]: vectorControlPlaneHooks so existing hooks are
preserved (reference symbols:
pgvectorPackMeta.types.codecTypes.controlPlaneHooks, PGVECTOR_CODEC_ID,
vectorControlPlaneHooks).
packages/2-sql/2-authoring/contract-psl/src/provider.ts (1)

181-194: Validate extensionPacks payloads before emitting merged contract output.

extensionPacks is merged as Record<string, unknown> with no JSON-shape guard. If a non-serializable value slips in, emitted metadata can degrade silently.

Proposed hardening
+function isJsonValue(value: unknown): boolean {
+  if (value === null) return true;
+  if (typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean') return true;
+  if (Array.isArray(value)) return value.every(isJsonValue);
+  if (!isPlainObject(value)) return false;
+  return Object.values(value).every(isJsonValue);
+}
+
       const extensionPacks = options?.extensionPacks
         ? mergePlainObjects(interpreted.value.extensionPacks, options.extensionPacks)
         : interpreted.value.extensionPacks;
+
+      if (!isJsonValue(extensionPacks)) {
+        return notOk({
+          summary: 'Invalid extensionPacks payload: value must be JSON-serializable',
+          diagnostics: [{ code: 'PSL_EXTENSION_PACKS_INVALID', message: 'Non-JSON value found in extensionPacks' }],
+          meta: { schemaPath },
+        });
+      }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/2-sql/2-authoring/contract-psl/src/provider.ts` around lines 181 -
194, The merged extensionPacks currently accepts any Record<string, unknown> and
can silently include non-serializable values; before merging/interpolating
extensionPacks (the logic around interpreted.value.extensionPacks,
options.extensionPacks, mergePlainObjects, and the final sortDeepTyped call),
validate each entry is JSON-serializable (or matches the expected plain-JSON
shape) and either reject or filter out invalid entries and log/return an error
via the ok/err flow; implement a small guard (e.g.,
isJsonSerializable/isPlainJson) and apply it to options.extensionPacks and
interpreted.value.extensionPacks prior to mergePlainObjects so the returned
object only contains safe, serializable payloads.
test/integration/test/authoring/templates/prisma-next.config.parity-psl.ts (1)

27-37: Replace inline conditional spreads with ifDefined() for consistency.

These new spreads use ...(cond ? { ... } : {}). In this repo, conditional properties should use ifDefined() in TypeScript files under test/**.

♻️ Proposed refactor
+import { ifDefined } from '@prisma-next/utils/defined';
+
 function extensionPackMetaFromDescriptor(descriptor: unknown): Record<string, unknown> {
@@
   return {
     kind: record['kind'],
     id: record['id'],
     familyId: record['familyId'],
     targetId: record['targetId'],
     version: record['version'],
-    ...(record['capabilities'] ? { capabilities: record['capabilities'] } : {}),
-    ...(types
-      ? {
-          types: {
-            ...types,
-            codecTypes: types.codecTypes
-              ? { ...types.codecTypes, controlPlaneHooks: undefined }
-              : undefined,
-          },
-        }
-      : {}),
+    ...ifDefined('capabilities', record['capabilities']),
+    ...ifDefined(
+      'types',
+      types
+        ? {
+            ...types,
+            ...ifDefined(
+              'codecTypes',
+              types.codecTypes
+                ? { ...types.codecTypes, controlPlaneHooks: undefined }
+                : undefined,
+            ),
+          }
+        : undefined,
+    ),
   };
 }
@@
   contract: prismaContract('./schema.prisma', {
     output: 'output/contract.json',
     composedExtensionPacks: extensionPacks.map((pack) => pack.id),
-    ...(extensionPacks.length > 0
-      ? {
-          extensionPacks: extensionPacksMeta,
-          capabilitySources: [postgresAdapter, ...Object.values(extensionPacksMeta)],
-        }
-      : {}),
+    ...ifDefined('extensionPacks', extensionPacks.length > 0 ? extensionPacksMeta : undefined),
+    ...ifDefined(
+      'capabilitySources',
+      extensionPacks.length > 0 ? [postgresAdapter, ...Object.values(extensionPacksMeta)] : undefined,
+    ),
   }),
 });

As per coding guidelines, "Use ifDefined() from @prisma-next/utils/defined for conditional object spreads instead of inline conditional spread patterns".

Also applies to: 54-59

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

In `@test/integration/test/authoring/templates/prisma-next.config.parity-psl.ts`
around lines 27 - 37, Replace the inline conditional spreads like
...(record['capabilities'] ? { capabilities: record['capabilities'] } : {}) and
the types block using ...(types ? { types: { ... } } : {}) with the
repo-standard ifDefined() helper from `@prisma-next/utils/defined`; specifically,
import ifDefined and wrap conditional properties (capabilities, types, and
nested codecTypes controlPlaneHooks removal) with ifDefined(...) so the object
construction uses ifDefined(record['capabilities'], ...) and ifDefined(types,
...) (and handle codecTypes similarly) instead of ternary spread expressions to
match test/** TypeScript conventions.
examples/prisma-next-demo/src/queries/similarity-search.types.test.ts (1)

9-15: Prefer expectTypeOf over custom Equal/Expect helpers for type assertions in this test.

Using Vitest’s built-in matcher API keeps type tests consistent and removes local helper maintenance.

♻️ Proposed refactor
-import { test } from 'vitest';
+import { expectTypeOf, test } from 'vitest';
 ...
-type Equal<A, B> =
-  (<T>() => T extends A ? 1 : 2) extends <T>() => T extends B ? 1 : 2 ? true : false;
-type Expect<T extends true> = T;
 ...
-  // Compile-time assertions
-  type Assertions = [
-    Expect<Equal<Row['distance'], number>>,
-    Expect<Equal<Row['id'], Char<36>>>,
-    Expect<Equal<Row['title'], string>>,
-  ];
-  const assertions = null as unknown as Assertions;
-  void assertions;
+  expectTypeOf<Row['distance']>().toEqualTypeOf<number>();
+  expectTypeOf<Row['id']>().toEqualTypeOf<Char<36>>();
+  expectTypeOf<Row['title']>().toEqualTypeOf<string>();

As per coding guidelines: **/*.{test,spec}.{ts,tsx}: “Use type test patterns with vitest; prefer expectTypeOf for type assertions.”

Also applies to: 46-53

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

In `@examples/prisma-next-demo/src/queries/similarity-search.types.test.ts` around
lines 9 - 15, This test file defines local type helpers Equal and Expect for
type assertions; replace them with Vitest's built-in expectTypeOf to follow
project guidelines: remove the custom type helpers (Equal, Expect) and instead
import and use expectTypeOf from 'vitest' in the tests (e.g., use
expectTypeOf<Actual>().toEqualTypeOf<Expected>() or other expectTypeOf matchers)
so the type assertions in similarity-search.types.test.ts use Vitest's matcher
API consistently.
examples/prisma-next-demo/src/queries/get-user-posts.types.test.ts (1)

10-17: Use expectTypeOf for these type assertions instead of custom helper types.

This keeps type tests aligned with the project’s Vitest-based assertion pattern and avoids custom assertion utilities.

♻️ Proposed refactor
-import { test } from 'vitest';
+import { expectTypeOf, test } from 'vitest';
 ...
-type Equal<A, B> =
-  (<T>() => T extends A ? 1 : 2) extends <T>() => T extends B ? 1 : 2 ? true : false;
-type Expect<T extends true> = T;
-type NotNever<T> = [T] extends [never] ? false : true;
 ...
-  // Compile-time assertions
-  type Assertions = [
-    Expect<Equal<Row['embedding'], Vector<1536> | null>>,
-    Expect<Equal<Row['id'], Char<36>>>,
-    Expect<Equal<Row['title'], string>>,
-    Expect<Equal<Row['userId'], string>>,
-    Expect<NotNever<Row['createdAt']>>,
-  ];
-  const assertions = null as unknown as Assertions;
-  void assertions;
+  expectTypeOf<Row['embedding']>().toEqualTypeOf<Vector<1536> | null>();
+  expectTypeOf<Row['id']>().toEqualTypeOf<Char<36>>();
+  expectTypeOf<Row['title']>().toEqualTypeOf<string>();
+  expectTypeOf<Row['userId']>().toEqualTypeOf<string>();
+  expectTypeOf<Row['createdAt']>().not.toEqualTypeOf<never>();

As per coding guidelines: **/*.{test,spec}.{ts,tsx}: “Use type test patterns with vitest; prefer expectTypeOf for type assertions.”

Also applies to: 46-55

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

In `@examples/prisma-next-demo/src/queries/get-user-posts.types.test.ts` around
lines 10 - 17, The test file defines custom type helpers (Equal, Expect,
NotNever) for type assertions; replace these with Vitest's expectTypeOf by
importing expectTypeOf from 'vitest' and converting each assertion: use
expectTypeOf<Actual>().toEqualTypeOf<Expected>() in place of Equal/Expect
patterns and use expectTypeOf<Actual>().not.toBeNever() instead of NotNever;
remove the Equal/Expect/NotNever type aliases and update all occurrences
(including the other block around lines 46-55) to the new expectTypeOf calls so
the file follows the project's Vitest type-test pattern.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Duplicate comments:
In `@packages/2-sql/2-authoring/contract-psl/src/interpreter.ts`:
- Around line 1028-1040: The backrelation-list validation branch currently
rejects only fields/references and onDelete/onUpdate but misses rejecting a
`map` argument, so add a guard that treats a non-empty `constraintNameRaw` (and
thus `constraintName`) as invalid on list-side backrelations: in the
backrelation-list validation code path (the branch that already pushes
diagnostics for fields/references and onDelete/onUpdate), check `if
(constraintNameRaw)` and push a diagnostic with code
'PSL_INVALID_RELATION_ATTRIBUTE' and the same message pattern used above
(`Relation field "${input.modelName}.${input.fieldName}" map argument must be a
quoted string literal` or appropriate text rejecting map usage), then return
undefined—using the existing `input`, `constraintNameRaw`, `constraintName`,
`input.diagnostics`, and `input.attribute.span` symbols to implement the check.

---

Nitpick comments:
In `@examples/prisma-next-demo/src/queries/get-user-posts.types.test.ts`:
- Around line 10-17: The test file defines custom type helpers (Equal, Expect,
NotNever) for type assertions; replace these with Vitest's expectTypeOf by
importing expectTypeOf from 'vitest' and converting each assertion: use
expectTypeOf<Actual>().toEqualTypeOf<Expected>() in place of Equal/Expect
patterns and use expectTypeOf<Actual>().not.toBeNever() instead of NotNever;
remove the Equal/Expect/NotNever type aliases and update all occurrences
(including the other block around lines 46-55) to the new expectTypeOf calls so
the file follows the project's Vitest type-test pattern.

In `@examples/prisma-next-demo/src/queries/similarity-search.types.test.ts`:
- Around line 9-15: This test file defines local type helpers Equal and Expect
for type assertions; replace them with Vitest's built-in expectTypeOf to follow
project guidelines: remove the custom type helpers (Equal, Expect) and instead
import and use expectTypeOf from 'vitest' in the tests (e.g., use
expectTypeOf<Actual>().toEqualTypeOf<Expected>() or other expectTypeOf matchers)
so the type assertions in similarity-search.types.test.ts use Vitest's matcher
API consistently.

In `@packages/2-sql/2-authoring/contract-psl/src/provider.ts`:
- Around line 181-194: The merged extensionPacks currently accepts any
Record<string, unknown> and can silently include non-serializable values; before
merging/interpolating extensionPacks (the logic around
interpreted.value.extensionPacks, options.extensionPacks, mergePlainObjects, and
the final sortDeepTyped call), validate each entry is JSON-serializable (or
matches the expected plain-JSON shape) and either reject or filter out invalid
entries and log/return an error via the ok/err flow; implement a small guard
(e.g., isJsonSerializable/isPlainJson) and apply it to options.extensionPacks
and interpreted.value.extensionPacks prior to mergePlainObjects so the returned
object only contains safe, serializable payloads.

In `@packages/3-extensions/pgvector/src/exports/control.ts`:
- Around line 74-82: The code currently overwrites
pgvectorPackMeta.types.codecTypes.controlPlaneHooks instead of merging new
entries; update the build of types.codecTypes.controlPlaneHooks to spread the
existing pgvectorPackMeta.types.codecTypes.controlPlaneHooks first and then add
the new entry [PGVECTOR_CODEC_ID]: vectorControlPlaneHooks so existing hooks are
preserved (reference symbols:
pgvectorPackMeta.types.codecTypes.controlPlaneHooks, PGVECTOR_CODEC_ID,
vectorControlPlaneHooks).

In `@test/integration/test/authoring/templates/prisma-next.config.parity-psl.ts`:
- Around line 27-37: Replace the inline conditional spreads like
...(record['capabilities'] ? { capabilities: record['capabilities'] } : {}) and
the types block using ...(types ? { types: { ... } } : {}) with the
repo-standard ifDefined() helper from `@prisma-next/utils/defined`; specifically,
import ifDefined and wrap conditional properties (capabilities, types, and
nested codecTypes controlPlaneHooks removal) with ifDefined(...) so the object
construction uses ifDefined(record['capabilities'], ...) and ifDefined(types,
...) (and handle codecTypes similarly) instead of ternary spread expressions to
match test/** TypeScript conventions.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

Run ID: de5f543f-9c52-4dae-8318-0fdc88cc2177

📥 Commits

Reviewing files that changed from the base of the PR and between 783f828 and e383b36.

⛔ Files ignored due to path filters (6)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
  • projects/psl-contract-authoring/plans/psl-contract-parity-missing-behaviors-plan.md is excluded by !projects/**
  • projects/psl-contract-authoring/specs/psl-contract-parity-missing-behaviors.spec.md is excluded by !projects/**
  • projects/psl-contract-authoring/specs/reviews/code-review.md is excluded by !projects/**
  • projects/psl-contract-authoring/specs/reviews/system-design-review.md is excluded by !projects/**
  • projects/psl-contract-authoring/specs/reviews/walkthrough.md is excluded by !projects/**
📒 Files selected for processing (33)
  • docs/architecture docs/adrs/ADR 170 - Parameterized native types in contracts.md
  • examples/prisma-next-demo/README.md
  • examples/prisma-next-demo/package.json
  • examples/prisma-next-demo/prisma-next.config.ts
  • examples/prisma-next-demo/prisma-next.config.ts-contract.ts
  • examples/prisma-next-demo/prisma/schema.prisma
  • examples/prisma-next-demo/src/prisma-no-emit/context.ts
  • examples/prisma-next-demo/src/prisma/contract.d.ts
  • examples/prisma-next-demo/src/prisma/contract.json
  • examples/prisma-next-demo/src/queries/get-user-posts.types.test.ts
  • examples/prisma-next-demo/src/queries/similarity-search.test-d.ts
  • examples/prisma-next-demo/src/queries/similarity-search.ts
  • examples/prisma-next-demo/src/queries/similarity-search.types.test.ts
  • examples/prisma-next-demo/test/utils/control-client.ts
  • packages/2-sql/2-authoring/contract-psl/src/interpreter.ts
  • packages/2-sql/2-authoring/contract-psl/src/provider.ts
  • packages/2-sql/2-authoring/contract-psl/test/interpreter.diagnostics.test.ts
  • packages/2-sql/2-authoring/contract-psl/test/interpreter.relations.test.ts
  • packages/2-sql/2-authoring/contract-psl/test/provider.test.ts
  • packages/3-extensions/pgvector/src/exports/column-types.ts
  • packages/3-extensions/pgvector/src/exports/control.ts
  • packages/3-extensions/pgvector/test/column-types.test.ts
  • packages/3-targets/3-targets/postgres/test/migrations/planner.case1.test.ts
  • packages/3-targets/6-adapters/postgres/src/core/parameterized-types.ts
  • packages/3-targets/6-adapters/postgres/test/parameterized-types.test.ts
  • test/integration/test/authoring/parity/map-attributes/contract.ts
  • test/integration/test/authoring/parity/map-attributes/expected.contract.json
  • test/integration/test/authoring/parity/map-attributes/schema.prisma
  • test/integration/test/authoring/parity/pgvector-named-type/contract.ts
  • test/integration/test/authoring/parity/pgvector-named-type/expected.contract.json
  • test/integration/test/authoring/psl.pgvector-dbinit.test.ts
  • test/integration/test/authoring/templates/prisma-next.config.parity-psl.ts
  • test/integration/test/authoring/templates/prisma-next.config.parity-ts.ts
🚧 Files skipped from review as they are similar to previous changes (16)
  • packages/2-sql/2-authoring/contract-psl/test/interpreter.diagnostics.test.ts
  • examples/prisma-next-demo/test/utils/control-client.ts
  • packages/2-sql/2-authoring/contract-psl/test/provider.test.ts
  • examples/prisma-next-demo/package.json
  • docs/architecture docs/adrs/ADR 170 - Parameterized native types in contracts.md
  • test/integration/test/authoring/templates/prisma-next.config.parity-ts.ts
  • packages/3-targets/6-adapters/postgres/test/parameterized-types.test.ts
  • test/integration/test/authoring/parity/map-attributes/schema.prisma
  • packages/3-extensions/pgvector/test/column-types.test.ts
  • packages/3-targets/3-targets/postgres/test/migrations/planner.case1.test.ts
  • packages/2-sql/2-authoring/contract-psl/test/interpreter.relations.test.ts
  • examples/prisma-next-demo/src/prisma-no-emit/context.ts
  • packages/3-targets/6-adapters/postgres/src/core/parameterized-types.ts
  • packages/3-extensions/pgvector/src/exports/column-types.ts
  • test/integration/test/authoring/psl.pgvector-dbinit.test.ts
  • test/integration/test/authoring/parity/map-attributes/expected.contract.json

@wmadden
wmadden force-pushed the psl-capabilities-and-extensions branch from 7c52e14 to 8c431d1 Compare March 8, 2026 08:43

@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

Caution

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

⚠️ Outside diff range comments (1)
packages/3-targets/3-targets/postgres/src/core/migrations/planner.ts (1)

801-825: ⚠️ Potential issue | 🟠 Major

Don't silently drop declared type params when a codec hook is missing.

If column.typeParams is set but codecHooks has no expandNativeType for that codec, this path falls back to the bare nativeType. That can emit incorrect DDL for valid contracts (vector instead of vector(1536), numeric instead of numeric(10,2)) and hide a broken framework composition. Please fail planning here instead of degrading silently. The same guard should be mirrored in buildNativeTypeExpander() so offline contractToSchema() stays aligned.

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

Also applies to: 827-846

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

In `@packages/3-targets/3-targets/postgres/src/core/migrations/planner.ts` around
lines 801 - 825, The code in buildColumnTypeSql currently falls back to the bare
nativeType when column.typeParams are present but the codecHooks map lacks an
expandNativeType hook for the codec, which silently drops declared type
parameters; change buildColumnTypeSql to detect when column.typeParams is
non-empty and the codecHooks entry does not provide an expandNativeType (or
codecHooks has no entry) and throw/abort planning with a clear error instead of
returning column.nativeType; also add the same guard in buildNativeTypeExpander
so contractToSchema/offline planning fails consistently when type params are
declared but no expander exists, referencing buildColumnTypeSql and
buildNativeTypeExpander to locate the fixes.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@packages/3-targets/6-adapters/postgres/src/core/descriptor-meta.ts`:
- Around line 61-87: The helpers (expandLength, expandPrecision, expandNumeric)
currently swallow malformed params by returning the bare nativeType; instead,
detect when a type parameter key is present but invalid and throw a clear error
so a malformed parameterized contract fails fast. Update expandLength and
expandPrecision to: if typeParams has the 'length'/'precision' key but
isValidTypeParamNumber(...) is false, throw an Error naming the nativeType and
param; otherwise behave as now. Update expandNumeric to: if 'precision' is
present and invalid throw; if 'scale' is present and invalid throw; if precision
valid and scale valid return nativeType(precision,scale); if precision valid and
scale absent return nativeType(precision); if precision absent return
nativeType.

---

Outside diff comments:
In `@packages/3-targets/3-targets/postgres/src/core/migrations/planner.ts`:
- Around line 801-825: The code in buildColumnTypeSql currently falls back to
the bare nativeType when column.typeParams are present but the codecHooks map
lacks an expandNativeType hook for the codec, which silently drops declared type
parameters; change buildColumnTypeSql to detect when column.typeParams is
non-empty and the codecHooks entry does not provide an expandNativeType (or
codecHooks has no entry) and throw/abort planning with a clear error instead of
returning column.nativeType; also add the same guard in buildNativeTypeExpander
so contractToSchema/offline planning fails consistently when type params are
declared but no expander exists, referencing buildColumnTypeSql and
buildNativeTypeExpander to locate the fixes.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

Run ID: 4e4714c0-f137-41a6-81e6-5e8be8a801bb

📥 Commits

Reviewing files that changed from the base of the PR and between 7c52e14 and 8c431d1.

📒 Files selected for processing (12)
  • docs/architecture docs/adrs/ADR 170 - Parameterized native types in contracts.md
  • packages/1-framework/1-core/migration/control-plane/src/migrations.ts
  • packages/1-framework/3-tooling/cli/src/commands/migration-plan.ts
  • packages/3-targets/3-targets/postgres/src/core/migrations/planner-reconciliation.ts
  • packages/3-targets/3-targets/postgres/src/core/migrations/planner.ts
  • packages/3-targets/3-targets/postgres/src/exports/control.ts
  • packages/3-targets/3-targets/postgres/test/migrations/planner.case1.test.ts
  • packages/3-targets/3-targets/postgres/test/migrations/planner.contract-to-schema-ir.test.ts
  • packages/3-targets/6-adapters/postgres/src/core/descriptor-meta.ts
  • packages/3-targets/6-adapters/postgres/src/core/parameterized-types.ts
  • packages/3-targets/6-adapters/postgres/src/exports/control.ts
  • packages/3-targets/6-adapters/postgres/test/parameterized-types.test.ts
💤 Files with no reviewable changes (2)
  • packages/3-targets/6-adapters/postgres/src/core/parameterized-types.ts
  • packages/3-targets/6-adapters/postgres/test/parameterized-types.test.ts
🚧 Files skipped from review as they are similar to previous changes (3)
  • docs/architecture docs/adrs/ADR 170 - Parameterized native types in contracts.md
  • packages/1-framework/3-tooling/cli/src/commands/migration-plan.ts
  • packages/3-targets/3-targets/postgres/test/migrations/planner.case1.test.ts

@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

Caution

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

⚠️ Outside diff range comments (1)
packages/3-targets/3-targets/postgres/test/migrations/planner.case1.test.ts (1)

144-144: ⚠️ Potential issue | 🟡 Minor

Use profileHash() constructor instead of as never cast.

The file already imports profileHash and uses it correctly at line 21 in createTestContract. Apply the same pattern here for consistency and type safety.

Suggested fix
-      profileHash: 'sha256:profile' as never,
+      profileHash: profileHash('sha256:profile'),
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/3-targets/3-targets/postgres/test/migrations/planner.case1.test.ts`
at line 144, Replace the unsafe cast "sha256:profile" as never with the proper
constructor call using the imported profileHash function (the same pattern used
in createTestContract); locate the object that sets profileHash and call
profileHash('sha256:profile') to ensure consistent type safety and remove the as
never cast.
🧹 Nitpick comments (4)
examples/prisma-next-demo/src/prisma-no-emit/context.ts (1)

11-11: Consider removing the inline comment.

The code change is self-documenting—adding pgvector to extensionPacks clearly expresses the intent. The rationale ("parity with emit workflow") is better captured in the commit message or PR description than in an inline comment that will remain after the context is forgotten.

As per coding guidelines: "Don't add comments if avoidable; prefer code which expresses its intent."

🔧 Suggested diff
-// pgvector was previously missing here; added for parity with the emit workflow config.
 export const stack = createSqlExecutionStack({
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@examples/prisma-next-demo/src/prisma-no-emit/context.ts` at line 11, Remove
the inline comment that explains why pgvector was added—since the change is
self-explanatory by adding "pgvector" to extensionPacks, delete the comment line
in the same file so only the code (the extensionPacks array containing
"pgvector") remains; retain the change itself and move any rationale into the
PR/commit message instead.
packages/1-framework/3-tooling/cli/src/control-api/contract-enrichment.ts (1)

10-24: Consider using a well-established library for deep merging.

This custom mergePlainObjects implementation handles basic nested object merging. While functional, using a battle-tested library like Lodash's merge or mergeWith would provide more robust handling of edge cases and reduce maintenance burden.

However, if bundle size is a concern and this simple merge suffices for the known use cases, the current implementation is acceptable.

Based on learnings: "In Prisma-next's TypeScript codebase, prefer using well-established utility libraries (e.g., Lodash) rather than building custom utilities for complex object operations such as deep freezing or deep cloning."

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

In `@packages/1-framework/3-tooling/cli/src/control-api/contract-enrichment.ts`
around lines 10 - 24, Replace the custom deep-merge in mergePlainObjects with a
well-tested utility: remove or stop using the mergePlainObjects function and
instead import and call a battle-tested deep merge (e.g., lodash.merge or
lodash.mergeWith) wherever mergePlainObjects is used; if bundle size is a
concern, explicitly document the limited behavior of mergePlainObjects and add
unit tests covering edge cases (arrays, non-plain objects, prototypes) and a
TODO to switch to lodash.merge when acceptable. Ensure references to
mergePlainObjects in this module are updated to use the chosen merge function
and keep the same return shape (Record<string, unknown>).
packages/3-targets/3-targets/postgres/test/migrations/planner.case1.test.ts (1)

78-78: Consider splitting this test file in a follow-up.

At 694 lines, the file exceeds the 500-line guideline. The distinct describe blocks (empty database, composite unique, column defaults) could be split into separate files like planner.empty-db.test.ts, planner.unique-constraints.test.ts, and planner.defaults.test.ts.

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

In `@packages/3-targets/3-targets/postgres/test/migrations/planner.case1.test.ts`
at line 78, The file is too large and should be split by the major describe
blocks: extract the "PostgresMigrationPlanner - when database is empty" suite
into a new planner.empty-db.test.ts, move the "composite unique" suite into
planner.unique-constraints.test.ts, and move the "column defaults" suite into
planner.defaults.test.ts; when splitting, preserve each describe(...) block and
its contained tests, update/retain any shared helper imports (e.g.,
setup/teardown helpers, factory functions) at the top of each new file, ensure
exported/used symbols like PostgresMigrationPlanner or helper functions remain
imported from their original modules, and run the test runner to confirm no
missing imports or duplicated globals.
packages/3-targets/6-adapters/postgres/test/descriptor-meta.test.ts (1)

5-6: Derive the hook types from the source instead of redefining them locally.

ExpandFn/HooksMap widen the real descriptor surface here, and the Record<string, ...> cast drops literal-key typing. That makes this test less effective at catching renamed codec IDs or hook-signature drift. Prefer typeof postgresAdapterDescriptorMeta.types.codecTypes.controlPlaneHooks or an exported hook/input type from the source module.

Also applies to: 105-105

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

In `@packages/3-targets/6-adapters/postgres/test/descriptor-meta.test.ts` around
lines 5 - 6, Replace the local redefinitions ExpandFn and HooksMap with types
derived from the source so they track real descriptor shapes: import or
reference typeof
postgresAdapterDescriptorMeta.types.codecTypes.controlPlaneHooks (or the
exported hook/input type) and use that instead of Record<string,...>/manual
function type; update any usages (including the other occurrence around the
block that starts near line 105) to use the derived type so literal keys and
signatures are preserved and tests will catch renames/signature drift.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@packages/3-targets/3-targets/postgres/src/core/migrations/planner.ts`:
- Around line 823-824: The current code lets renderParameterizedTypeSql(column,
codecHooks) fall back to column.nativeType, which silently drops declared type
parameters; instead, when renderParameterizedTypeSql returns null/undefined
(i.e., codec hook missing), fail planning by throwing an error or asserting—do
this in the same spot where assertSafeNativeType(column.nativeType) is called.
Replace the fallback return of column.nativeType with a clear failure that
references the column (e.g., column.name/type) and mentions the missing codec
hook in codecHooks so the migration fails rather than emitting an
unparameterized native type; apply the same change to the other occurrences in
the block handling renderParameterizedTypeSql (the 827–842 region).

In `@packages/3-targets/6-adapters/postgres/test/descriptor-meta.test.ts`:
- Around line 107-197: The tests currently only exercise one codec key per block
(e.g. hooks['sql/char@1'], hooks['pg/timestamp@1'], hooks['pg/numeric@1']) —
convert each block to table-driven tests that iterate over every advertised
codec id for that family and run the same assertions against
hooks[<codecId>]!.expandNativeType; specifically, for expandLength iterate ids
['sql/char@1','sql/varchar@1','pg/char@1','pg/varchar@1','pg/bit@1','pg/varbit@1'],
for expandPrecision iterate
['pg/timestamp@1','pg/timestamptz@1','pg/time@1','pg/timetz@1','pg/interval@1'],
and keep expandNumeric using hooks['pg/numeric@1'] (or iterate if there are
additional numeric ids); replace the single const expand = ... with a forEach
over the id array and run each existing it(...) assertion body against expand =
hooks[id]!.expandNativeType, so every mapped codec ID is validated by the same
test cases.

---

Outside diff comments:
In `@packages/3-targets/3-targets/postgres/test/migrations/planner.case1.test.ts`:
- Line 144: Replace the unsafe cast "sha256:profile" as never with the proper
constructor call using the imported profileHash function (the same pattern used
in createTestContract); locate the object that sets profileHash and call
profileHash('sha256:profile') to ensure consistent type safety and remove the as
never cast.

---

Nitpick comments:
In `@examples/prisma-next-demo/src/prisma-no-emit/context.ts`:
- Line 11: Remove the inline comment that explains why pgvector was added—since
the change is self-explanatory by adding "pgvector" to extensionPacks, delete
the comment line in the same file so only the code (the extensionPacks array
containing "pgvector") remains; retain the change itself and move any rationale
into the PR/commit message instead.

In `@packages/1-framework/3-tooling/cli/src/control-api/contract-enrichment.ts`:
- Around line 10-24: Replace the custom deep-merge in mergePlainObjects with a
well-tested utility: remove or stop using the mergePlainObjects function and
instead import and call a battle-tested deep merge (e.g., lodash.merge or
lodash.mergeWith) wherever mergePlainObjects is used; if bundle size is a
concern, explicitly document the limited behavior of mergePlainObjects and add
unit tests covering edge cases (arrays, non-plain objects, prototypes) and a
TODO to switch to lodash.merge when acceptable. Ensure references to
mergePlainObjects in this module are updated to use the chosen merge function
and keep the same return shape (Record<string, unknown>).

In `@packages/3-targets/3-targets/postgres/test/migrations/planner.case1.test.ts`:
- Line 78: The file is too large and should be split by the major describe
blocks: extract the "PostgresMigrationPlanner - when database is empty" suite
into a new planner.empty-db.test.ts, move the "composite unique" suite into
planner.unique-constraints.test.ts, and move the "column defaults" suite into
planner.defaults.test.ts; when splitting, preserve each describe(...) block and
its contained tests, update/retain any shared helper imports (e.g.,
setup/teardown helpers, factory functions) at the top of each new file, ensure
exported/used symbols like PostgresMigrationPlanner or helper functions remain
imported from their original modules, and run the test runner to confirm no
missing imports or duplicated globals.

In `@packages/3-targets/6-adapters/postgres/test/descriptor-meta.test.ts`:
- Around line 5-6: Replace the local redefinitions ExpandFn and HooksMap with
types derived from the source so they track real descriptor shapes: import or
reference typeof
postgresAdapterDescriptorMeta.types.codecTypes.controlPlaneHooks (or the
exported hook/input type) and use that instead of Record<string,...>/manual
function type; update any usages (including the other occurrence around the
block that starts near line 105) to use the derived type so literal keys and
signatures are preserved and tests will catch renames/signature drift.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

Run ID: e85bc2e0-61a8-4e85-8bf7-c9ed8a747525

📥 Commits

Reviewing files that changed from the base of the PR and between 8c431d1 and a0bc847.

⛔ Files ignored due to path filters (1)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
📒 Files selected for processing (38)
  • docs/README.md
  • docs/glossary.md
  • examples/prisma-next-demo/prisma-next.config.ts
  • examples/prisma-next-demo/src/prisma-no-emit/context.ts
  • examples/prisma-next-demo/src/queries/get-user-posts.types.test.ts
  • examples/prisma-next-demo/src/queries/similarity-search.test-d.ts
  • examples/prisma-next-demo/src/queries/similarity-search.types.test.ts
  • packages/1-framework/1-core/shared/config/src/contract-source-types.ts
  • packages/1-framework/1-core/shared/config/src/exports/config-types.ts
  • packages/1-framework/3-tooling/cli/src/control-api/client.ts
  • packages/1-framework/3-tooling/cli/src/control-api/contract-enrichment.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/contract-emit.ts
  • packages/1-framework/3-tooling/cli/src/exports/config-types.ts
  • packages/1-framework/3-tooling/cli/src/exports/control-api.ts
  • packages/1-framework/3-tooling/cli/test/config-types.test.ts
  • packages/1-framework/3-tooling/cli/test/control-api/contract-enrichment.test.ts
  • packages/2-sql/2-authoring/contract-psl/src/provider.ts
  • packages/2-sql/2-authoring/contract-psl/test/provider.test.ts
  • packages/2-sql/2-authoring/contract-ts/src/config-types.ts
  • packages/2-sql/2-authoring/contract-ts/test/config-types.test.ts
  • packages/3-targets/3-targets/postgres/package.json
  • packages/3-targets/3-targets/postgres/src/core/migrations/planner.ts
  • packages/3-targets/3-targets/postgres/test/migrations/planner.case1.test.ts
  • packages/3-targets/6-adapters/postgres/test/descriptor-meta.test.ts
  • test/integration/test/authoring/cli.emit-parity-fixtures.test.ts
  • test/integration/test/authoring/parity/core-surface/expected.contract.json
  • test/integration/test/authoring/parity/default-cuid-2/expected.contract.json
  • test/integration/test/authoring/parity/default-dbgenerated/expected.contract.json
  • test/integration/test/authoring/parity/default-nanoid-16/expected.contract.json
  • test/integration/test/authoring/parity/default-nanoid/expected.contract.json
  • test/integration/test/authoring/parity/default-ulid/expected.contract.json
  • test/integration/test/authoring/parity/default-uuid-v4/expected.contract.json
  • test/integration/test/authoring/parity/default-uuid-v7/expected.contract.json
  • test/integration/test/authoring/parity/map-attributes/expected.contract.json
  • test/integration/test/authoring/parity/relation-backrelation-list/expected.contract.json
  • test/integration/test/authoring/psl.pgvector-dbinit.test.ts
  • test/integration/test/authoring/templates/prisma-next.config.parity-psl.ts
  • test/integration/test/cli.emit-command.test.ts
💤 Files with no reviewable changes (1)
  • test/integration/test/authoring/templates/prisma-next.config.parity-psl.ts
✅ Files skipped from review due to trivial changes (1)
  • docs/glossary.md
🚧 Files skipped from review as they are similar to previous changes (2)
  • examples/prisma-next-demo/prisma-next.config.ts
  • examples/prisma-next-demo/src/queries/similarity-search.test-d.ts

@wmadden
wmadden force-pushed the psl-capabilities-and-extensions branch from 9f2b805 to 00d4764 Compare March 8, 2026 20:03

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 5

Caution

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

⚠️ Outside diff range comments (1)
test/integration/test/cli.emit-contract.test.ts (1)

11-19: ⚠️ Potential issue | 🟡 Minor

Don’t bake an empty ContractSourceContext into the helper.

This helper now resolves every contract source as if no extension packs were composed. That means this integration suite will miss regressions in context-aware sources and can diverge from the real emit path as soon as a fixture depends on composedExtensionPacks. Please thread the actual context in from the loaded config instead of hardcoding [].

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

In `@test/integration/test/cli.emit-contract.test.ts` around lines 11 - 19, The
helper resolveContractIR currently calls the contract source with a hardcoded
composedExtensionPacks: [] which hides regressions for context-aware sources;
update resolveContractIR to accept or obtain the real ContractSourceContext from
the loaded config and pass its composedExtensionPacks through to source instead
of an empty array (e.g., thread the context returned by loadConfig into
resolveContractIR and call source({ composedExtensionPacks:
actualContext.composedExtensionPacks }) so the helper mirrors the real emit
path).
♻️ Duplicate comments (1)
packages/2-sql/2-authoring/contract-psl/src/interpreter.ts (1)

1028-1040: ⚠️ Potential issue | 🟡 Minor

Reject @relation(map: ...) on backrelation-list fields.

Parsing map here makes it valid on every relation attribute, but the list-side backrelation branch later only rejects fields/references and referential actions. @relation(map: ...) on the navigation-list side is therefore accepted and silently dropped, so users can think they've named the FK when the emitted contract still uses the default.

💡 Proposed fix
         if (parsedRelation.onDelete || parsedRelation.onUpdate) {
           diagnostics.push({
             code: 'PSL_INVALID_RELATION_ATTRIBUTE',
             message: `Backrelation list field "${model.name}.${field.name}" cannot declare onDelete/onUpdate; define referential actions on the FK-side relation field`,
             sourceId,
             span: relationAttribute.span,
           });
           continue;
         }
+        if (parsedRelation.constraintName) {
+          diagnostics.push({
+            code: 'PSL_INVALID_RELATION_ATTRIBUTE',
+            message: `Backrelation list field "${model.name}.${field.name}" cannot declare map; define FK constraint names on the FK-side relation field`,
+            sourceId,
+            span: relationAttribute.span,
+          });
+          continue;
+        }
         relationName = parsedRelation.relationName;

Also applies to: 1080-1085

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

In `@packages/2-sql/2-authoring/contract-psl/src/interpreter.ts` around lines 1028
- 1040, The parser currently accepts a `@relation`(map: "...") on the
navigation-list (backrelation) side because it only validates quoted-string
syntax; change the logic that reads constraintNameRaw/constraintName to reject
the presence of a map argument when the relation attribute is the
list/backrelation side: detect the backrelation-list case using the existing
input metadata (the same flags used later to reject fields/references and
referential actions) and if constraintNameRaw is present push a diagnostic (code
'PSL_INVALID_RELATION_ATTRIBUTE', message indicating map is not allowed on the
backrelation-list for input.modelName.input.fieldName, include sourceId and
attribute.span) and return undefined; apply the same rejection at the other
symmetric spot mentioned (around the later 1080-1085 block) so both places
consistently disallow `@relation`(map: ...) on list/backrelation fields.
🧹 Nitpick comments (6)
examples/prisma-next-demo/src/prisma-no-emit/context.ts (1)

11-11: Consider removing the explanatory comment.

The comment provides historical context, but per coding guidelines, comments should be avoided when code can express intent. The addition of pgvector to extensionPacks is self-explanatory alongside the import.

🧹 Proposed removal
-// pgvector was previously missing here; added for parity with the emit workflow config.
 export const stack = createSqlExecutionStack({
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@examples/prisma-next-demo/src/prisma-no-emit/context.ts` at line 11, Remove
the historical/explanatory comment that reads about "pgvector was previously
missing here; added for parity with the emit workflow config." and leave the
import and the addition to extensionPacks as-is; locate the comment near the
pgvector import and the extensionPacks array in this file (reference symbols:
pgvector, extensionPacks) and delete that single-line comment so the code itself
expresses the intent.
packages/3-extensions/pgvector/src/exports/control.ts (1)

74-82: Preserve existing controlPlaneHooks entries when extending codecTypes.

This currently replaces codecTypes.controlPlaneHooks outright. If pgvectorPackMeta.types.codecTypes ever carries another hook, it gets dropped here. Merge the existing map before adding PGVECTOR_CODEC_ID.

♻️ Proposed change
   types: {
     ...pgvectorPackMeta.types,
     codecTypes: {
       ...pgvectorPackMeta.types.codecTypes,
       controlPlaneHooks: {
+        ...(pgvectorPackMeta.types.codecTypes.controlPlaneHooks ?? {}),
         [PGVECTOR_CODEC_ID]: vectorControlPlaneHooks,
       },
     },
   },
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/3-extensions/pgvector/src/exports/control.ts` around lines 74 - 82,
The current assignment of codecTypes.controlPlaneHooks overwrites any existing
entries; update the merge to preserve existing hooks by spreading the existing
map before adding our entry — when building types use
pgvectorPackMeta.types.codecTypes.controlPlaneHooks (if present) and spread it,
then add [PGVECTOR_CODEC_ID]: vectorControlPlaneHooks so other controlPlaneHooks
are retained.
packages/1-framework/3-tooling/cli/test/control-api/contract-enrichment.test.ts (2)

22-45: Make the descriptor mocks explicit test-only escapes.

Both helpers end with direct casts to TargetBoundComponentDescriptor<...>. In test code we standardize on keeping the unsafe boundary explicit with as unknown as ... at the mock return site, rather than a direct cast that hides how partial the fixture is.

As per coding guidelines, "Use double casts (as unknown as X) for mocks and dynamic proxies in tests instead of direct casts" and "Place type casts at mock boundaries (return statements), not sprinkled throughout the test."

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

In
`@packages/1-framework/3-tooling/cli/test/control-api/contract-enrichment.test.ts`
around lines 22 - 45, The two test helper functions makeAdapter and
makeExtension currently use direct casts to
TargetBoundComponentDescriptor<'sql','postgres'> which hides the partial nature
of the fixtures; update their return assertions to use the explicit test-only
escape pattern by changing the cast to "as unknown as
TargetBoundComponentDescriptor<'sql','postgres'>" at the return site so the
unsafe boundary is explicit for these mocks.

6-20: Use the shared createContractIR() fixture instead of hand-building IR objects.

makeIR() duplicates the base ContractIR shape in a new test file, which makes this suite more brittle as the IR evolves. Please switch this helper to the shared factory so defaults and required fields stay centralized.

As per coding guidelines, "Use factory functions like createContractIR() instead of manual object creation for ContractIR objects in tests to avoid duplication, ensure all required fields are present with proper defaults, and simplify refactoring."

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

In
`@packages/1-framework/3-tooling/cli/test/control-api/contract-enrichment.test.ts`
around lines 6 - 20, The test defines a local makeIR() that hand-builds a
ContractIR; replace it by importing and using the shared factory
createContractIR() (and remove the local makeIR) so the test uses centralized
defaults and required fields; update any calls that passed overrides to call
createContractIR(overrides) (or createContractIR({...}) as needed) and add the
appropriate import for createContractIR at the top of the file, referencing the
existing ContractIR type only if needed for typing.
packages/3-targets/3-targets/postgres/test/migrations/planner.case1.test.ts (1)

231-283: Split this test file before adding more planner scenarios.

This file is already well past the 500-line limit and now mixes additive planning, parameterized/native-type rendering, composite-unique DDL, and default rendering in one place. Please move the new parameterized-type cases into a focused file such as planner.parameterized-types.test.ts so the suite stays navigable.

As per coding guidelines, "Keep test files under 500 lines to maintain readability and navigability. If a test file exceeds this limit, it should be split into multiple files." and "Split test files when they exceed 500 lines, contain multiple distinct concerns that can be logically separated, or have multiple top-level describe blocks that can be split by functionality."

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

In `@packages/3-targets/3-targets/postgres/test/migrations/planner.case1.test.ts`
around lines 231 - 283, The test file has grown too large and mixes multiple
planner concerns; extract parameterized/native-type rendering tests (e.g., the
"renders pgvector vector(N) column types in DDL" it-block that uses
createPostgresMigrationPlanner, planner.plan, and pgvectorDescriptor) into a new
focused test file (suggested name: planner.parameterized-types.test.ts). Move
only the parameterized-type cases and their fixtures (contract objects,
emptySchema, INIT_ADDITIVE_POLICY, and any descriptors like pgvectorDescriptor)
into the new file, keep imports/setup the same, and remove those tests from the
original file so each file stays under 500 lines and focuses on a single
concern.
packages/1-framework/3-tooling/cli/src/control-api/contract-enrichment.ts (1)

41-43: Narrow sortDeepTyped() to the shapes it actually preserves.

sortDeep() rebuilds arrays and plain objects, so as T overpromises that the original static type survives unchanged. I’d constrain this helper to the record-like IR shapes it actually handles, or narrow at the call sites instead of hiding the conversion behind a generic cast.

As per coding guidelines, “Replace blind casts with type predicates instead of as casts.”

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

In `@packages/1-framework/3-tooling/cli/src/control-api/contract-enrichment.ts`
around lines 41 - 43, The helper sortDeepTyped currently lies about preserving
arbitrary T by casting sortDeep(value) as T; change its signature and usages to
reflect the actual shapes handled (plain objects and arrays) — e.g., restrict
the parameter to Record<string, unknown> | unknown[] (or create explicit
overloads) and return the same narrowed type instead of using a blind generic
cast; alternatively implement a type predicate (isPlainObjectOrArray) and narrow
at call sites before calling sortDeepTyped so you no longer need the unsafe `as
T` cast.
🤖 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/1-framework/3-tooling/cli/src/control-api/contract-enrichment.ts`:
- Around line 90-93: The code currently sets base['types'] to a clone that only
removes controlPlaneHooks at the codecTypes object level, but you need to remove
controlPlaneHooks from each codec descriptor inside types.codecTypes so hook
functions don't propagate; update the logic where base['types'] is assigned (the
branch that checks types.codecTypes) to iterate over types.codecTypes entries
(or map its values) and for each codec descriptor produce a shallow clone with
controlPlaneHooks omitted, then assign the new codecTypes map into the cloned
types object before putting it on base; reference symbols: base, types,
codecTypes, controlPlaneHooks.

In `@packages/2-sql/2-authoring/contract-psl/test/provider.test.ts`:
- Around line 257-268: The test's assertion uses optional chaining
storage.tables['document']?.columns['embedding'] which will silently pass if the
embedding column is missing; change the check to access the column directly
(storage.tables['document'].columns['embedding']) so it will throw if the column
is absent, and ensure you assert the column exists before testing properties
(use the already-validated shape from the previous expect on storage.tables to
justify direct access). This targets the storage.tables -> 'document' -> columns
-> 'embedding' path and removes the optional chaining to make the typeRef
assertion meaningful and fail when embedding is missing.

In `@packages/3-targets/3-targets/postgres/src/exports/control.ts`:
- Around line 18-34: The buildNativeTypeExpander currently silently falls back
to input.nativeType which loses parameter information; update
buildNativeTypeExpander (and the similar code at the other occurrence) so that
it still returns a callable expander but it fails fast when typeParams are
present and cannot be expanded: keep returning input.nativeType only when there
are no typeParams; if input.typeParams exists and frameworkComponents is
missing, codecId is missing, or there is no expandNativeType hook on
codecHooks.get(codecId), throw a descriptive Error indicating that native type
expansion failed for the given codecId and typeParams (include codecId and
typeParams in the message) so callers like contractToSchema cannot synthesize
lossy types silently.

In `@packages/3-targets/6-adapters/postgres/src/core/descriptor-meta.ts`:
- Around line 87-115: The function expandNumeric currently allows a lone "scale"
param to be ignored; update expandNumeric to treat a present scale without
precision as an error: inside expandNumeric (function name: expandNumeric,
symbols: nativeType, typeParams, hasPrecision, hasScale) if hasScale is true and
hasPrecision is false throw a descriptive Error (e.g., "Invalid type parameters
for \"numeric\": scale provided without precision") rather than returning
nativeType; keep existing numeric validation logic for precision/scale when both
are present.

In `@test/integration/test/authoring/cli.emit-parity-fixtures.test.ts`:
- Around line 115-124: The PSL path is currently built using the TS fixture's
framework stack (tsConfig -> frameworkComponents) and validated with the TS
family, which can mask drift; change the PSL branch to construct its own
frameworkComponents from the PSL fixture (use pslConfig.target,
pslConfig.adapter, pslConfig.extensionPacks) and pass that into enrichContractIR
when creating enrichedPsl, and then validate normalizedPsl with the PSL family
instance (pslFamilyInstance.validateContractIR) instead of
familyInstance.validateContractIR so the PSL capabilities/extensionPacks are
accurately tested.

---

Outside diff comments:
In `@test/integration/test/cli.emit-contract.test.ts`:
- Around line 11-19: The helper resolveContractIR currently calls the contract
source with a hardcoded composedExtensionPacks: [] which hides regressions for
context-aware sources; update resolveContractIR to accept or obtain the real
ContractSourceContext from the loaded config and pass its composedExtensionPacks
through to source instead of an empty array (e.g., thread the context returned
by loadConfig into resolveContractIR and call source({ composedExtensionPacks:
actualContext.composedExtensionPacks }) so the helper mirrors the real emit
path).

---

Duplicate comments:
In `@packages/2-sql/2-authoring/contract-psl/src/interpreter.ts`:
- Around line 1028-1040: The parser currently accepts a `@relation`(map: "...") on
the navigation-list (backrelation) side because it only validates quoted-string
syntax; change the logic that reads constraintNameRaw/constraintName to reject
the presence of a map argument when the relation attribute is the
list/backrelation side: detect the backrelation-list case using the existing
input metadata (the same flags used later to reject fields/references and
referential actions) and if constraintNameRaw is present push a diagnostic (code
'PSL_INVALID_RELATION_ATTRIBUTE', message indicating map is not allowed on the
backrelation-list for input.modelName.input.fieldName, include sourceId and
attribute.span) and return undefined; apply the same rejection at the other
symmetric spot mentioned (around the later 1080-1085 block) so both places
consistently disallow `@relation`(map: ...) on list/backrelation fields.

---

Nitpick comments:
In `@examples/prisma-next-demo/src/prisma-no-emit/context.ts`:
- Line 11: Remove the historical/explanatory comment that reads about "pgvector
was previously missing here; added for parity with the emit workflow config."
and leave the import and the addition to extensionPacks as-is; locate the
comment near the pgvector import and the extensionPacks array in this file
(reference symbols: pgvector, extensionPacks) and delete that single-line
comment so the code itself expresses the intent.

In `@packages/1-framework/3-tooling/cli/src/control-api/contract-enrichment.ts`:
- Around line 41-43: The helper sortDeepTyped currently lies about preserving
arbitrary T by casting sortDeep(value) as T; change its signature and usages to
reflect the actual shapes handled (plain objects and arrays) — e.g., restrict
the parameter to Record<string, unknown> | unknown[] (or create explicit
overloads) and return the same narrowed type instead of using a blind generic
cast; alternatively implement a type predicate (isPlainObjectOrArray) and narrow
at call sites before calling sortDeepTyped so you no longer need the unsafe `as
T` cast.

In
`@packages/1-framework/3-tooling/cli/test/control-api/contract-enrichment.test.ts`:
- Around line 22-45: The two test helper functions makeAdapter and makeExtension
currently use direct casts to TargetBoundComponentDescriptor<'sql','postgres'>
which hides the partial nature of the fixtures; update their return assertions
to use the explicit test-only escape pattern by changing the cast to "as unknown
as TargetBoundComponentDescriptor<'sql','postgres'>" at the return site so the
unsafe boundary is explicit for these mocks.
- Around line 6-20: The test defines a local makeIR() that hand-builds a
ContractIR; replace it by importing and using the shared factory
createContractIR() (and remove the local makeIR) so the test uses centralized
defaults and required fields; update any calls that passed overrides to call
createContractIR(overrides) (or createContractIR({...}) as needed) and add the
appropriate import for createContractIR at the top of the file, referencing the
existing ContractIR type only if needed for typing.

In `@packages/3-extensions/pgvector/src/exports/control.ts`:
- Around line 74-82: The current assignment of codecTypes.controlPlaneHooks
overwrites any existing entries; update the merge to preserve existing hooks by
spreading the existing map before adding our entry — when building types use
pgvectorPackMeta.types.codecTypes.controlPlaneHooks (if present) and spread it,
then add [PGVECTOR_CODEC_ID]: vectorControlPlaneHooks so other controlPlaneHooks
are retained.

In `@packages/3-targets/3-targets/postgres/test/migrations/planner.case1.test.ts`:
- Around line 231-283: The test file has grown too large and mixes multiple
planner concerns; extract parameterized/native-type rendering tests (e.g., the
"renders pgvector vector(N) column types in DDL" it-block that uses
createPostgresMigrationPlanner, planner.plan, and pgvectorDescriptor) into a new
focused test file (suggested name: planner.parameterized-types.test.ts). Move
only the parameterized-type cases and their fixtures (contract objects,
emptySchema, INIT_ADDITIVE_POLICY, and any descriptors like pgvectorDescriptor)
into the new file, keep imports/setup the same, and remove those tests from the
original file so each file stays under 500 lines and focuses on a single
concern.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

Run ID: 3e24f6c0-50a8-43fd-bb90-fa4e45e8ad70

📥 Commits

Reviewing files that changed from the base of the PR and between a0bc847 and 00d4764.

⛔ Files ignored due to path filters (6)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
  • projects/psl-contract-authoring/plans/psl-contract-parity-missing-behaviors-plan.md is excluded by !projects/**
  • projects/psl-contract-authoring/specs/psl-contract-parity-missing-behaviors.spec.md is excluded by !projects/**
  • projects/psl-contract-authoring/specs/reviews/code-review.md is excluded by !projects/**
  • projects/psl-contract-authoring/specs/reviews/system-design-review.md is excluded by !projects/**
  • projects/psl-contract-authoring/specs/reviews/walkthrough.md is excluded by !projects/**
📒 Files selected for processing (68)
  • docs/README.md
  • docs/architecture docs/adrs/ADR 170 - Parameterized native types in contracts.md
  • docs/glossary.md
  • examples/prisma-next-demo/README.md
  • examples/prisma-next-demo/package.json
  • examples/prisma-next-demo/prisma-next.config.ts
  • examples/prisma-next-demo/prisma-next.config.ts-contract.ts
  • examples/prisma-next-demo/prisma/schema.prisma
  • examples/prisma-next-demo/src/prisma-no-emit/context.ts
  • examples/prisma-next-demo/src/prisma/contract.d.ts
  • examples/prisma-next-demo/src/prisma/contract.json
  • examples/prisma-next-demo/src/queries/get-user-posts.types.test.ts
  • examples/prisma-next-demo/src/queries/similarity-search.test-d.ts
  • examples/prisma-next-demo/src/queries/similarity-search.ts
  • examples/prisma-next-demo/src/queries/similarity-search.types.test.ts
  • examples/prisma-next-demo/test/utils/control-client.ts
  • packages/1-framework/1-core/migration/control-plane/src/migrations.ts
  • packages/1-framework/1-core/shared/config/src/contract-source-types.ts
  • packages/1-framework/1-core/shared/config/src/exports/config-types.ts
  • packages/1-framework/3-tooling/cli/src/commands/migration-plan.ts
  • packages/1-framework/3-tooling/cli/src/control-api/client.ts
  • packages/1-framework/3-tooling/cli/src/control-api/contract-enrichment.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/contract-emit.ts
  • packages/1-framework/3-tooling/cli/src/exports/config-types.ts
  • packages/1-framework/3-tooling/cli/src/exports/control-api.ts
  • packages/1-framework/3-tooling/cli/test/config-types.test.ts
  • packages/1-framework/3-tooling/cli/test/control-api/contract-enrichment.test.ts
  • packages/2-sql/2-authoring/contract-psl/src/interpreter.ts
  • packages/2-sql/2-authoring/contract-psl/src/provider.ts
  • packages/2-sql/2-authoring/contract-psl/test/interpreter.diagnostics.test.ts
  • packages/2-sql/2-authoring/contract-psl/test/interpreter.relations.test.ts
  • packages/2-sql/2-authoring/contract-psl/test/provider.test.ts
  • packages/2-sql/2-authoring/contract-ts/src/config-types.ts
  • packages/2-sql/2-authoring/contract-ts/test/config-types.test.ts
  • packages/3-extensions/pgvector/src/exports/column-types.ts
  • packages/3-extensions/pgvector/src/exports/control.ts
  • packages/3-extensions/pgvector/test/column-types.test.ts
  • packages/3-targets/3-targets/postgres/package.json
  • packages/3-targets/3-targets/postgres/src/core/migrations/planner-reconciliation.ts
  • packages/3-targets/3-targets/postgres/src/core/migrations/planner.ts
  • packages/3-targets/3-targets/postgres/src/exports/control.ts
  • packages/3-targets/3-targets/postgres/test/migrations/planner.case1.test.ts
  • packages/3-targets/3-targets/postgres/test/migrations/planner.contract-to-schema-ir.test.ts
  • packages/3-targets/3-targets/postgres/test/migrations/planner.reconciliation-unit.test.ts
  • packages/3-targets/6-adapters/postgres/src/core/descriptor-meta.ts
  • packages/3-targets/6-adapters/postgres/src/core/parameterized-types.ts
  • packages/3-targets/6-adapters/postgres/src/exports/control.ts
  • packages/3-targets/6-adapters/postgres/test/descriptor-meta.test.ts
  • packages/3-targets/6-adapters/postgres/test/parameterized-types.test.ts
  • test/integration/test/authoring/cli.emit-parity-fixtures.test.ts
  • test/integration/test/authoring/parity/core-surface/expected.contract.json
  • test/integration/test/authoring/parity/default-cuid-2/expected.contract.json
  • test/integration/test/authoring/parity/default-dbgenerated/expected.contract.json
  • test/integration/test/authoring/parity/default-nanoid-16/expected.contract.json
  • test/integration/test/authoring/parity/default-nanoid/expected.contract.json
  • test/integration/test/authoring/parity/default-ulid/expected.contract.json
  • test/integration/test/authoring/parity/default-uuid-v4/expected.contract.json
  • test/integration/test/authoring/parity/default-uuid-v7/expected.contract.json
  • test/integration/test/authoring/parity/map-attributes/contract.ts
  • test/integration/test/authoring/parity/map-attributes/expected.contract.json
  • test/integration/test/authoring/parity/map-attributes/schema.prisma
  • test/integration/test/authoring/parity/pgvector-named-type/contract.ts
  • test/integration/test/authoring/parity/pgvector-named-type/expected.contract.json
  • test/integration/test/authoring/parity/relation-backrelation-list/expected.contract.json
  • test/integration/test/authoring/psl.pgvector-dbinit.test.ts
  • test/integration/test/authoring/templates/prisma-next.config.parity-psl.ts
  • test/integration/test/cli.emit-command.test.ts
  • test/integration/test/cli.emit-contract.test.ts
💤 Files with no reviewable changes (3)
  • packages/3-targets/6-adapters/postgres/src/core/parameterized-types.ts
  • test/integration/test/authoring/templates/prisma-next.config.parity-psl.ts
  • packages/3-targets/6-adapters/postgres/test/parameterized-types.test.ts
✅ Files skipped from review due to trivial changes (1)
  • examples/prisma-next-demo/README.md
🚧 Files skipped from review as they are similar to previous changes (20)
  • packages/3-targets/3-targets/postgres/package.json
  • test/integration/test/authoring/parity/core-surface/expected.contract.json
  • examples/prisma-next-demo/prisma-next.config.ts
  • examples/prisma-next-demo/prisma-next.config.ts-contract.ts
  • examples/prisma-next-demo/src/queries/similarity-search.types.test.ts
  • test/integration/test/authoring/parity/map-attributes/contract.ts
  • test/integration/test/cli.emit-command.test.ts
  • packages/1-framework/3-tooling/cli/test/config-types.test.ts
  • examples/prisma-next-demo/src/queries/similarity-search.test-d.ts
  • packages/3-extensions/pgvector/src/exports/column-types.ts
  • packages/2-sql/2-authoring/contract-psl/test/interpreter.relations.test.ts
  • packages/2-sql/2-authoring/contract-psl/test/interpreter.diagnostics.test.ts
  • test/integration/test/authoring/parity/default-dbgenerated/expected.contract.json
  • packages/1-framework/3-tooling/cli/src/control-api/operations/contract-emit.ts
  • packages/3-extensions/pgvector/test/column-types.test.ts
  • packages/1-framework/3-tooling/cli/src/exports/config-types.ts
  • docs/glossary.md
  • packages/1-framework/3-tooling/cli/src/control-api/client.ts
  • examples/prisma-next-demo/src/queries/get-user-posts.types.test.ts
  • test/integration/test/authoring/parity/pgvector-named-type/contract.ts

@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)
packages/3-targets/6-adapters/postgres/src/core/descriptor-meta.ts (1)

93-127: Unreachable fallback at line 126.

The return nativeType at line 126 is unreachable: if we reach line 107, hasPrecision is guaranteed true (due to the early return at lines 97-99 and the throw at lines 101-105), so the function always returns from within the if (hasPrecision) block.

This doesn't affect correctness but could be simplified.

♻️ Suggested simplification
   if (hasPrecision) {
     const precision = typeParams['precision'];
     if (!isPositiveInteger(precision)) {
       throw new Error(
         `Invalid "precision" type parameter for "${nativeType}": expected a positive integer, got ${JSON.stringify(precision)}`,
       );
     }
     if (hasScale) {
       const scale = typeParams['scale'];
       if (!isNonNegativeInteger(scale)) {
         throw new Error(
           `Invalid "scale" type parameter for "${nativeType}": expected a non-negative integer, got ${JSON.stringify(scale)}`,
         );
       }
       return `${nativeType}(${precision},${scale})`;
     }
     return `${nativeType}(${precision})`;
   }
-
-  return nativeType;
+  // Unreachable: hasPrecision is guaranteed true here due to early returns above
 }
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/3-targets/6-adapters/postgres/src/core/descriptor-meta.ts` around
lines 93 - 127, The final fallback return in expandNumeric is unreachable;
simplify the function by removing the redundant "return nativeType" at the end
and adjust control flow so all code paths return inside the existing checks
(keep the initial early return when both hasPrecision and hasScale are false,
the throw when scale is present without precision, and the returns inside the if
(hasPrecision) block). This targets the expandNumeric function and ensures no
dead code remains while preserving existing validation and error messages.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Nitpick comments:
In `@packages/3-targets/6-adapters/postgres/src/core/descriptor-meta.ts`:
- Around line 93-127: The final fallback return in expandNumeric is unreachable;
simplify the function by removing the redundant "return nativeType" at the end
and adjust control flow so all code paths return inside the existing checks
(keep the initial early return when both hasPrecision and hasScale are false,
the throw when scale is present without precision, and the returns inside the if
(hasPrecision) block). This targets the expandNumeric function and ensures no
dead code remains while preserving existing validation and error messages.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

Run ID: 65bc8193-38da-47c8-8f7e-28426b2a34cc

📥 Commits

Reviewing files that changed from the base of the PR and between 70d6eda and 60c868e.

📒 Files selected for processing (8)
  • examples/prisma-next-demo/src/queries/get-user-posts.types.test.ts
  • examples/prisma-next-demo/src/queries/similarity-search.test-d.ts
  • examples/prisma-next-demo/src/queries/similarity-search.types.test.ts
  • packages/2-sql/2-authoring/contract-psl/test/provider.test.ts
  • packages/3-targets/3-targets/postgres/src/exports/control.ts
  • packages/3-targets/6-adapters/postgres/src/core/descriptor-meta.ts
  • packages/3-targets/6-adapters/postgres/test/descriptor-meta.test.ts
  • test/utils/src/typed-expectations.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • examples/prisma-next-demo/src/queries/similarity-search.test-d.ts
  • packages/3-targets/3-targets/postgres/src/exports/control.ts

wmadden added 13 commits March 11, 2026 14:53
Add failing coverage for framework metadata emission, pgvector vector(N) type expansion,
and Prisma-style relation map FK naming so we can implement fixes with confidence.
Allow PSL contract source to carry configured extension pack metadata and a merged
capability matrix, so emitted contracts are complete without app-level enrichment.
Teach the Postgres parameterized type expander to render vector(length) for pgvector
columns, so migration DDL uses valid parameterized types without quoting.
Represent pgvector columns and aliases as nativeType "vector" with typeParams.length,
so planners can safely expand to vector(N) without quoting or unsafe nativeType strings.
Accept Prisma-style relation map arguments on FK-side relations and propagate the
constraint name into contract storage so migrations can create stable FK names.
Make vector(N) descriptors use nativeType "vector" plus typeParams.length so Postgres
DDL expansion can render vector(N) without tripping native type safety checks.
Align TS/PSL parity fixtures with pgvector parameterized native type normalization,
provider-emitted framework metadata, and @relation(map: ...) FK constraint naming.
Switch the demo emit workflow to use prismaContract(schema.prisma) and rely on core
provider metadata/vector handling, then re-emit contract artifacts and adjust type tests.
Remove the options cast so the provider test exercises the real prismaContract API
surface for extensionPacks and capabilitySources.
Make capabilitySources a typed interface and merge/sort metadata without casting the
interpreted ContractIR, keeping provider enrichment type-safe and self-documenting.
Add a PSL→emit→dbInit integration test for dimensioned pgvector columns, and teach
pgvector control-plane hooks to expand vector(N) so schema verification matches DDL.
…scriptor

Move vector(N) native type expansion hooks onto the control extension descriptor so
schema verification can expand expected types without embedding functions in pack metadata.
wmadden added 23 commits March 11, 2026 14:56
@wmadden
wmadden force-pushed the psl-capabilities-and-extensions branch from 60c868e to 05f27ff Compare March 11, 2026 14:00

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

♻️ Duplicate comments (1)
packages/3-targets/3-targets/postgres/src/exports/control.ts (1)

18-24: ⚠️ Potential issue | 🟠 Major

Don't drop the expander when frameworkComponents is missing.

Returning undefined here reopens the lossy path for parameterized contracts: contractToSchema() passes no expandNativeType, so callers that omit frameworkComponents can still collapse character(36) / vector(1536) to the bare native type instead of failing fast. Keep returning an expander and make the "no components" case throw whenever typeParams are present. As per coding guidelines, "Do not treat missing type parameters as a successful match when the contract declares them."

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

In `@packages/3-targets/3-targets/postgres/src/exports/control.ts` around lines 18
- 24, The current buildNativeTypeExpander returns undefined when
frameworkComponents is missing which allows lossy matches; change
buildNativeTypeExpander to always return an expander function (rather than
undefined) and, when frameworkComponents is absent, have that expander throw if
the provided native type descriptor includes typeParams; locate
buildNativeTypeExpander and its use of extractCodecControlHooks and modify the
returned closure so it validates typeParams and raises an error for any
parameterized native type, while still delegating to extractCodecControlHooks
when frameworkComponents are present.
🧹 Nitpick comments (4)
examples/prisma-next-demo/src/queries/get-user-posts.types.test.ts (1)

15-16: Consider extracting NotNever to shared utilities.

This helper type is useful for verifying a type resolved to something other than never. If this pattern is needed elsewhere, consider adding it to @prisma-next/test-utils/typed-expectations alongside Equal and Expect.

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

In `@examples/prisma-next-demo/src/queries/get-user-posts.types.test.ts` around
lines 15 - 16, The type alias NotNever<T> used in get-user-posts.types.test.ts
should be moved into the shared test utilities so it can be reused; create (or
add) NotNever in the `@prisma-next/test-utils/typed-expectations` module alongside
Equal and Expect, export it, then replace the local declaration in
get-user-posts.types.test.ts with an import of NotNever from that module (keep
the exact type name NotNever to match usages).
packages/2-sql/2-authoring/contract-psl/src/provider.ts (1)

52-56: Consider simplifying the result handling.

The explicit check and re-wrap could be simplified since interpreted is already a Result. However, this pattern is acceptable if there's a need for additional processing or type narrowing in the future.

// Current (explicit)
if (!interpreted.ok) {
  return interpreted;
}
return ok(interpreted.value);

// Simplified alternative
return interpreted;
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@packages/2-sql/2-authoring/contract-psl/src/provider.ts` around lines 52 -
56, The code in provider.ts performs an unnecessary explicit check and re-wrap
for the Result held in the local variable `interpreted`; replace the if-block
that checks `if (!interpreted.ok) { return interpreted; } return
ok(interpreted.value);` with a single `return interpreted;` (leave that
simplification in the function/method where `interpreted` is produced) unless
you intend to add extra processing or type narrowing later.
test/integration/test/cli.emit-contract.test.ts (1)

2-2: Consider using pathe instead of node:path.

Based on learnings, prefer pathe over node:path for path operations in TypeScript files for consistent cross-platform behavior.

Suggested import change
-import { dirname, join, resolve } from 'node:path';
+import { dirname, join, resolve } from 'pathe';
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@test/integration/test/cli.emit-contract.test.ts` at line 2, Replace the
import from 'node:path' with equivalent imports from 'pathe' and update usages
accordingly: import dirname, join, resolve from 'pathe' instead of 'node:path'
so functions dirname, join, and resolve in the test (e.g., in
cli.emit-contract.test.ts) use pathe's cross-platform implementations; ensure
any existing calls using these symbols continue to work without further changes.
test/integration/test/cli.emit-command.test.ts (1)

2-2: Consider using pathe instead of node:path.

Based on learnings, prefer pathe over node:path for path operations in TypeScript files for consistent cross-platform behavior.

Suggested import change
-import { join } from 'node:path';
+import { join } from 'pathe';
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@test/integration/test/cli.emit-command.test.ts` at line 2, The import in
cli.emit-command.test.ts currently pulls join from 'node:path'; change it to
import join from 'pathe' (or import { join } from 'pathe' to match usage) to
ensure consistent cross-platform path handling; update any other path utility
imports in this file (e.g., uses of join) to rely on the pathe import and run
the tests to verify no type or runtime changes are needed.
🤖 Prompt for all review comments with AI agents
Verify each finding against the current code and only fix it if needed.

Inline comments:
In `@docs/architecture` docs/adrs/ADR 170 - Parameterized native types in
contracts.md:
- Around line 27-33: Update the ADR to document the enforced validation/error
semantics: state that CodecControlHooks.expandNativeType must be provided for
any codec that exposes parameterized native types, that missing expandNativeType
support is a hard error (no fallback to stringly rendering), and that invalid
parameter sets returned/encountered during expansion are rejected with an error;
mention where this enforcement applies (DDL/migrations migration planner, schema
verifier’s expected-type expansion, and contractToSchema/NativeTypeExpander
offline planning) and add the same text to the implementation notes and decision
sections (also apply the update to the corresponding paragraphs around lines
45-48).
- Around line 39-40: Update the overgeneralized sentence about adapter coupling
to clarify that "no adapter changes needed" applies only to extension-owned
parameterized native types that implement an expandNativeType hook on their
controlPlaneHooks; state that adapter-owned built-in native types still require
adapter hook changes. Specifically, revise the two bullet points referencing
expandNativeType and controlPlaneHooks to narrowly qualify the decoupling
guarantee and mention adapter-owned native types as an exception so the ADR no
longer overstates the claim.

In `@docs/glossary.md`:
- Around line 3-5: The glossary currently mixes stable public names with planned
renames (e.g., prismaSchema(), typescriptSchema(), schema:) which confuses
consumers; update docs/glossary.md by splitting content into two clear sections
— "Current public terms" containing only the terminology safe to use today, and
"Planned/Refactor terminology" containing the tracker entries like
prismaSchema(), typescriptSchema(), and schema:, or alternatively move the
entire tracker block into a separate architecture/refactor document; ensure each
section is labeled and add a brief note indicating the stability status next to
any planned term.
- Around line 89-92: Update the "Capability" glossary entry to describe
capability matching as an adapter-reported, connect-time negotiation rather than
a startup check: rephrase the sentence that currently says "Prisma Next checks
these match at startup" to indicate that the adapter reports provided
capabilities at connect time and Prisma Next negotiates/validates the contract's
required capabilities against those provided by the adapter when establishing
the connection; ensure the wording frames the contract's capabilities as
requirements the contract declares and the adapter's capabilities as what it
provides.

In `@examples/prisma-next-demo/prisma-next.config.ts`:
- Around line 16-18: The relative schema path passed to prismaContract is
resolved from the process CWD, so change the call to compute an absolute path
anchored to this config file (e.g. require('path').resolve(__dirname,
'./prisma/schema.prisma')) and pass that resolved path into prismaContract
(update the prismaContract(...) invocation). This ensures prismaContract
receives an absolute schemaPath regardless of where the process is started.

In
`@packages/3-targets/3-targets/postgres/test/migrations/planner.contract-to-schema-ir.test.ts`:
- Around line 25-30: The test helper expandParameterizedNativeType currently
returns input.nativeType when codecId is missing or hook lookup fails, masking
parameterized-type failures; update it to mirror production fail-fast semantics
used in control.ts by (1) rejecting/throwing when input.codecId is falsy, (2)
throwing if adapterCodecHooks.get(input.codecId) is undefined or if
hooks.expandNativeType is undefined, and only calling
hooks.expandNativeType(input) when present; reference the functions/values
expandParameterizedNativeType, extractCodecControlHooks, and adapterCodecHooks
(or alternatively route the test to use the public adapter descriptor path) so
missing type parameters cause test failures instead of silently returning
input.nativeType.

In `@packages/3-targets/6-adapters/postgres/src/core/descriptor-meta.ts`:
- Around line 80-90: expandPrecision currently rejects precision 0 by using
isPositiveInteger; change validation to allow zero for PostgreSQL temporal
types. In the expandPrecision function (signature ExpandNativeTypeInput) detect
temporal native types ("timestamp", "timestamptz", "time", "timetz", "interval")
and validate precision with a non-negative integer check (allow 0) for those
types, while keeping the existing isPositiveInteger validation for other native
types; ensure the error message still includes the invalid value via
JSON.stringify. Also update the corresponding tests in
packages/3-targets/6-adapters/postgres/test/descriptor-meta.test.ts to cover
precision 0 for the temporal codecs and maintain existing numeric tests.

---

Duplicate comments:
In `@packages/3-targets/3-targets/postgres/src/exports/control.ts`:
- Around line 18-24: The current buildNativeTypeExpander returns undefined when
frameworkComponents is missing which allows lossy matches; change
buildNativeTypeExpander to always return an expander function (rather than
undefined) and, when frameworkComponents is absent, have that expander throw if
the provided native type descriptor includes typeParams; locate
buildNativeTypeExpander and its use of extractCodecControlHooks and modify the
returned closure so it validates typeParams and raises an error for any
parameterized native type, while still delegating to extractCodecControlHooks
when frameworkComponents are present.

---

Nitpick comments:
In `@examples/prisma-next-demo/src/queries/get-user-posts.types.test.ts`:
- Around line 15-16: The type alias NotNever<T> used in
get-user-posts.types.test.ts should be moved into the shared test utilities so
it can be reused; create (or add) NotNever in the
`@prisma-next/test-utils/typed-expectations` module alongside Equal and Expect,
export it, then replace the local declaration in get-user-posts.types.test.ts
with an import of NotNever from that module (keep the exact type name NotNever
to match usages).

In `@packages/2-sql/2-authoring/contract-psl/src/provider.ts`:
- Around line 52-56: The code in provider.ts performs an unnecessary explicit
check and re-wrap for the Result held in the local variable `interpreted`;
replace the if-block that checks `if (!interpreted.ok) { return interpreted; }
return ok(interpreted.value);` with a single `return interpreted;` (leave that
simplification in the function/method where `interpreted` is produced) unless
you intend to add extra processing or type narrowing later.

In `@test/integration/test/cli.emit-command.test.ts`:
- Line 2: The import in cli.emit-command.test.ts currently pulls join from
'node:path'; change it to import join from 'pathe' (or import { join } from
'pathe' to match usage) to ensure consistent cross-platform path handling;
update any other path utility imports in this file (e.g., uses of join) to rely
on the pathe import and run the tests to verify no type or runtime changes are
needed.

In `@test/integration/test/cli.emit-contract.test.ts`:
- Line 2: Replace the import from 'node:path' with equivalent imports from
'pathe' and update usages accordingly: import dirname, join, resolve from
'pathe' instead of 'node:path' so functions dirname, join, and resolve in the
test (e.g., in cli.emit-contract.test.ts) use pathe's cross-platform
implementations; ensure any existing calls using these symbols continue to work
without further changes.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

Run ID: c644e868-0bf9-4a88-83b7-4f5d83d74683

📥 Commits

Reviewing files that changed from the base of the PR and between 60c868e and 05f27ff.

⛔ Files ignored due to path filters (3)
  • pnpm-lock.yaml is excluded by !**/pnpm-lock.yaml
  • projects/psl-contract-authoring/plans/psl-contract-parity-missing-behaviors-plan.md is excluded by !projects/**
  • projects/psl-contract-authoring/specs/psl-contract-parity-missing-behaviors.spec.md is excluded by !projects/**
📒 Files selected for processing (68)
  • .gitignore
  • docs/README.md
  • docs/architecture docs/adrs/ADR 170 - Parameterized native types in contracts.md
  • docs/glossary.md
  • examples/prisma-next-demo/README.md
  • examples/prisma-next-demo/package.json
  • examples/prisma-next-demo/prisma-next.config.ts
  • examples/prisma-next-demo/prisma-next.config.ts-contract.ts
  • examples/prisma-next-demo/prisma/schema.prisma
  • examples/prisma-next-demo/src/prisma-no-emit/context.ts
  • examples/prisma-next-demo/src/prisma/contract.d.ts
  • examples/prisma-next-demo/src/prisma/contract.json
  • examples/prisma-next-demo/src/queries/get-user-posts.types.test.ts
  • examples/prisma-next-demo/src/queries/similarity-search.test-d.ts
  • examples/prisma-next-demo/src/queries/similarity-search.ts
  • examples/prisma-next-demo/src/queries/similarity-search.types.test.ts
  • examples/prisma-next-demo/test/utils/control-client.ts
  • packages/1-framework/1-core/shared/config/src/contract-source-types.ts
  • packages/1-framework/1-core/shared/config/src/exports/config-types.ts
  • packages/1-framework/3-tooling/cli/src/control-api/client.ts
  • packages/1-framework/3-tooling/cli/src/control-api/contract-enrichment.ts
  • packages/1-framework/3-tooling/cli/src/control-api/operations/contract-emit.ts
  • packages/1-framework/3-tooling/cli/src/exports/config-types.ts
  • packages/1-framework/3-tooling/cli/src/exports/control-api.ts
  • packages/1-framework/3-tooling/cli/test/config-types.test.ts
  • packages/1-framework/3-tooling/cli/test/control-api/contract-enrichment.test.ts
  • packages/2-sql/2-authoring/contract-psl/src/interpreter.ts
  • packages/2-sql/2-authoring/contract-psl/src/provider.ts
  • packages/2-sql/2-authoring/contract-psl/test/interpreter.diagnostics.test.ts
  • packages/2-sql/2-authoring/contract-psl/test/interpreter.relations.test.ts
  • packages/2-sql/2-authoring/contract-psl/test/provider.test.ts
  • packages/2-sql/2-authoring/contract-ts/src/config-types.ts
  • packages/2-sql/2-authoring/contract-ts/test/config-types.test.ts
  • packages/3-extensions/pgvector/src/exports/column-types.ts
  • packages/3-extensions/pgvector/src/exports/control.ts
  • packages/3-extensions/pgvector/test/column-types.test.ts
  • packages/3-targets/3-targets/postgres/package.json
  • packages/3-targets/3-targets/postgres/src/core/migrations/planner-reconciliation.ts
  • packages/3-targets/3-targets/postgres/src/core/migrations/planner.ts
  • packages/3-targets/3-targets/postgres/src/exports/control.ts
  • packages/3-targets/3-targets/postgres/test/migrations/planner.case1.test.ts
  • packages/3-targets/3-targets/postgres/test/migrations/planner.contract-to-schema-ir.test.ts
  • packages/3-targets/3-targets/postgres/test/migrations/planner.reconciliation-unit.test.ts
  • packages/3-targets/6-adapters/postgres/src/core/descriptor-meta.ts
  • packages/3-targets/6-adapters/postgres/src/core/parameterized-types.ts
  • packages/3-targets/6-adapters/postgres/src/exports/control.ts
  • packages/3-targets/6-adapters/postgres/test/descriptor-meta.test.ts
  • packages/3-targets/6-adapters/postgres/test/parameterized-types.test.ts
  • test/integration/test/authoring/cli.emit-parity-fixtures.test.ts
  • test/integration/test/authoring/parity/core-surface/expected.contract.json
  • test/integration/test/authoring/parity/default-cuid-2/expected.contract.json
  • test/integration/test/authoring/parity/default-dbgenerated/expected.contract.json
  • test/integration/test/authoring/parity/default-nanoid-16/expected.contract.json
  • test/integration/test/authoring/parity/default-nanoid/expected.contract.json
  • test/integration/test/authoring/parity/default-ulid/expected.contract.json
  • test/integration/test/authoring/parity/default-uuid-v4/expected.contract.json
  • test/integration/test/authoring/parity/default-uuid-v7/expected.contract.json
  • test/integration/test/authoring/parity/map-attributes/contract.ts
  • test/integration/test/authoring/parity/map-attributes/expected.contract.json
  • test/integration/test/authoring/parity/map-attributes/schema.prisma
  • test/integration/test/authoring/parity/pgvector-named-type/contract.ts
  • test/integration/test/authoring/parity/pgvector-named-type/expected.contract.json
  • test/integration/test/authoring/parity/relation-backrelation-list/expected.contract.json
  • test/integration/test/authoring/psl.pgvector-dbinit.test.ts
  • test/integration/test/authoring/templates/prisma-next.config.parity-psl.ts
  • test/integration/test/cli.emit-command.test.ts
  • test/integration/test/cli.emit-contract.test.ts
  • test/utils/src/typed-expectations.ts
💤 Files with no reviewable changes (3)
  • packages/3-targets/6-adapters/postgres/test/parameterized-types.test.ts
  • test/integration/test/authoring/templates/prisma-next.config.parity-psl.ts
  • packages/3-targets/6-adapters/postgres/src/core/parameterized-types.ts
🚧 Files skipped from review as they are similar to previous changes (26)
  • packages/2-sql/2-authoring/contract-psl/test/interpreter.relations.test.ts
  • packages/1-framework/3-tooling/cli/src/control-api/client.ts
  • test/integration/test/authoring/parity/default-ulid/expected.contract.json
  • test/integration/test/authoring/parity/default-uuid-v7/expected.contract.json
  • packages/1-framework/3-tooling/cli/src/control-api/operations/contract-emit.ts
  • examples/prisma-next-demo/README.md
  • packages/3-targets/3-targets/postgres/package.json
  • test/integration/test/authoring/psl.pgvector-dbinit.test.ts
  • packages/2-sql/2-authoring/contract-psl/test/provider.test.ts
  • examples/prisma-next-demo/package.json
  • packages/1-framework/3-tooling/cli/src/exports/control-api.ts
  • test/integration/test/authoring/parity/map-attributes/contract.ts
  • packages/3-extensions/pgvector/src/exports/control.ts
  • test/integration/test/authoring/parity/default-cuid-2/expected.contract.json
  • packages/2-sql/2-authoring/contract-ts/src/config-types.ts
  • test/integration/test/authoring/parity/relation-backrelation-list/expected.contract.json
  • packages/3-targets/6-adapters/postgres/src/exports/control.ts
  • packages/1-framework/3-tooling/cli/test/control-api/contract-enrichment.test.ts
  • packages/3-targets/3-targets/postgres/test/migrations/planner.reconciliation-unit.test.ts
  • packages/3-extensions/pgvector/test/column-types.test.ts
  • packages/2-sql/2-authoring/contract-psl/src/interpreter.ts
  • examples/prisma-next-demo/src/prisma-no-emit/context.ts
  • examples/prisma-next-demo/test/utils/control-client.ts
  • test/integration/test/authoring/parity/default-nanoid-16/expected.contract.json
  • test/integration/test/authoring/parity/default-dbgenerated/expected.contract.json
  • test/integration/test/authoring/cli.emit-parity-fixtures.test.ts

Comment on lines +27 to +33
Expansion to a parameterized SQL type string (for example `vector(1536)`) is the responsibility of each component (adapter or extension) that owns the codec, via `CodecControlHooks.expandNativeType`:

- DDL/migrations: the migration planner extracts codec hooks from framework components and uses them when rendering column types.
- Schema verification: the schema verifier uses the same hooks to expand the *expected* type before comparing to introspected schema types.
- `contractToSchema`: receives framework components to build a `NativeTypeExpander` from hooks for offline planning.

No centralized dispatch function is used. Each component declares its own expansion logic alongside its codec hook definitions.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Document the enforced validation/error behavior.

The ADR explains who expands parameterized types, but it does not mention the new enforcement semantics from this PR: invalid parameter sets are rejected, and missing expandNativeType support is an error rather than falling back to stringly rendering. That behavior is part of the contract of this design now, so it should be captured in either the decision or implementation notes.

As per coding guidelines, "Keep docs current (READMEs, rules, links) - see .cursor/rules/doc-maintenance.mdc."

Also applies to: 45-48

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

In `@docs/architecture` docs/adrs/ADR 170 - Parameterized native types in
contracts.md around lines 27 - 33, Update the ADR to document the enforced
validation/error semantics: state that CodecControlHooks.expandNativeType must
be provided for any codec that exposes parameterized native types, that missing
expandNativeType support is a hard error (no fallback to stringly rendering),
and that invalid parameter sets returned/encountered during expansion are
rejected with an error; mention where this enforcement applies (DDL/migrations
migration planner, schema verifier’s expected-type expansion, and
contractToSchema/NativeTypeExpander offline planning) and add the same text to
the implementation notes and decision sections (also apply the update to the
corresponding paragraphs around lines 45-48).

Comment on lines +39 to +40
- **Extensibility**: new parameterized types can follow the same pattern by adding an `expandNativeType` hook to their component's `controlPlaneHooks` — no adapter changes needed.
- **No adapter coupling**: the adapter does not reference extension-owned codecs. Each component owns its expansion logic.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Qualify the “no adapter changes needed” claim.

Line 39 overgeneralizes the consequence. This is true for extension-owned parameterized types, but new built-in adapter-owned native types still need adapter hook changes. Narrowing the wording here would keep the ADR from overstating the decoupling guarantee.

As per coding guidelines, "Keep docs current (READMEs, rules, links) - see .cursor/rules/doc-maintenance.mdc."

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

In `@docs/architecture` docs/adrs/ADR 170 - Parameterized native types in
contracts.md around lines 39 - 40, Update the overgeneralized sentence about
adapter coupling to clarify that "no adapter changes needed" applies only to
extension-owned parameterized native types that implement an expandNativeType
hook on their controlPlaneHooks; state that adapter-owned built-in native types
still require adapter hook changes. Specifically, revise the two bullet points
referencing expandNativeType and controlPlaneHooks to narrowly qualify the
decoupling guarantee and mention adapter-owned native types as an exception so
the ADR no longer overstates the claim.

Comment thread docs/glossary.md Resolved
Comment thread docs/glossary.md
Comment on lines +89 to +92
### Capability

A specific feature that a database may or may not support (e.g., `RETURNING` clauses, vector indexes). Your contract declares which capabilities it needs; the adapter reports which ones the database provides. Prisma Next checks these match at startup, so you find out about missing features immediately rather than at query time.

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟡 Minor

Describe capability matching as connect-time negotiation.

This currently says missing capabilities are checked "at startup", but the docs convention is adapter-reported capabilities negotiated when connecting. Tightening that wording will better match the architecture here.

✏️ Proposed wording
-A specific feature that a database may or may not support (e.g., `RETURNING` clauses, vector indexes). Your contract declares which capabilities it needs; the adapter reports which ones the database provides. Prisma Next checks these match at startup, so you find out about missing features immediately rather than at query time.
+A specific feature that a database may or may not support (e.g., `RETURNING` clauses, vector indexes). Your contract declares which capabilities it requires; the adapter reports which ones the connected database provides. Prisma Next negotiates those requirements at connect time, so you find out about missing features before queries run.

As per coding guidelines, "Describe capabilities as adapter-reported and negotiated at connect time" and "Frame contract capabilities as requirements, not definitions".

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

In `@docs/glossary.md` around lines 89 - 92, Update the "Capability" glossary
entry to describe capability matching as an adapter-reported, connect-time
negotiation rather than a startup check: rephrase the sentence that currently
says "Prisma Next checks these match at startup" to indicate that the adapter
reports provided capabilities at connect time and Prisma Next
negotiates/validates the contract's required capabilities against those provided
by the adapter when establishing the connection; ensure the wording frames the
contract's capabilities as requirements the contract declares and the adapter's
capabilities as what it provides.

Comment on lines +16 to +18
contract: prismaContract('./prisma/schema.prisma', {
output: 'src/prisma/contract.json',
}),

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
set -euo pipefail

echo "Provider implementation:"
sed -n '1,40p' packages/2-sql/2-authoring/contract-psl/src/provider.ts

echo
echo "Demo config call site:"
sed -n '1,30p' examples/prisma-next-demo/prisma-next.config.ts

Repository: prisma/prisma-next

Length of output: 2415


Anchor the Prisma schema path to this config file.

prismaContract() resolves its schemaPath with resolve(schemaPath) in packages/2-sql/2-authoring/contract-psl/src/provider.ts:20, so ./prisma/schema.prisma is interpreted relative to the current working directory, not examples/prisma-next-demo/prisma-next.config.ts. Running the demo from the repo root will point at the wrong file or fail to read the schema.

🛠️ Suggested fix
+import { fileURLToPath } from 'node:url';
+
+const schemaPath = fileURLToPath(new URL('./prisma/schema.prisma', import.meta.url));
+
 export default defineConfig({
   family: sql,
   target: postgres,
   driver: postgresDriver,
   adapter: postgresAdapter,
   extensionPacks: [pgvector],
-  contract: prismaContract('./prisma/schema.prisma', {
+  contract: prismaContract(schemaPath, {
     output: 'src/prisma/contract.json',
   }),
📝 Committable suggestion

‼️ IMPORTANT
Carefully review the code before committing. Ensure that it accurately replaces the highlighted code, contains no missing lines, and has no issues with indentation. Thoroughly test & benchmark the code to ensure it meets the requirements.

Suggested change
contract: prismaContract('./prisma/schema.prisma', {
output: 'src/prisma/contract.json',
}),
import { fileURLToPath } from 'node:url';
const schemaPath = fileURLToPath(new URL('./prisma/schema.prisma', import.meta.url));
export default defineConfig({
family: sql,
target: postgres,
driver: postgresDriver,
adapter: postgresAdapter,
extensionPacks: [pgvector],
contract: prismaContract(schemaPath, {
output: 'src/prisma/contract.json',
}),
});
🤖 Prompt for AI Agents
Verify each finding against the current code and only fix it if needed.

In `@examples/prisma-next-demo/prisma-next.config.ts` around lines 16 - 18, The
relative schema path passed to prismaContract is resolved from the process CWD,
so change the call to compute an absolute path anchored to this config file
(e.g. require('path').resolve(__dirname, './prisma/schema.prisma')) and pass
that resolved path into prismaContract (update the prismaContract(...)
invocation). This ensures prismaContract receives an absolute schemaPath
regardless of where the process is started.

Comment on lines +80 to +90
function expandPrecision({ nativeType, typeParams }: ExpandNativeTypeInput): string {
if (!typeParams || !('precision' in typeParams)) {
return nativeType;
}
const precision = typeParams['precision'];
if (!isPositiveInteger(precision)) {
throw new Error(
`Invalid "precision" type parameter for "${nativeType}": expected a positive integer, got ${JSON.stringify(precision)}`,
);
}
return `${nativeType}(${precision})`;

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

⚠️ Potential issue | 🟠 Major

🧩 Analysis chain

🌐 Web query:

Does PostgreSQL allow a precision of 0 for timestamp, timestamptz, time, timetz, and interval type modifiers?

💡 Result:

Yes.

PostgreSQL’s date/time type modifiers allow an optional precision p (fractional digits in the seconds field) for:

  • timestamp(p) / timestamptz(p)
  • time(p) / timetz(p) (i.e., time [ (p) ] with/without time zone)
  • interval(p)

…and the allowed range of p is 0 to 6, so (...)(0) is valid for all of the types you listed. [1]

Example: timestamp(0), timestamptz(0), time(0), timetz(0), interval(0). [1]

Sources
[1] PostgreSQL Documentation — Date/Time Types (datatype-datetime): precision p allowed range 0 to 6. (postgresql.org)

Citations:


Allow 0 precision for temporal type modifiers in expandPrecision().

expandPrecision() rejects precision 0 via isPositiveInteger(), but PostgreSQL allows precision values from 0 to 6 for temporal types: timestamp(0), timestamptz(0), time(0), timetz(0), and interval(0) are all valid. The corresponding precisionRenderer() already accepts 0, creating an inconsistency where the type-side code is more permissive than the control-plane hook. Split validation to allow non-negative integers for temporal codecs while keeping numeric precision strictly positive. Update companion tests in packages/3-targets/6-adapters/postgres/test/descriptor-meta.test.ts accordingly.

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

In `@packages/3-targets/6-adapters/postgres/src/core/descriptor-meta.ts` around
lines 80 - 90, expandPrecision currently rejects precision 0 by using
isPositiveInteger; change validation to allow zero for PostgreSQL temporal
types. In the expandPrecision function (signature ExpandNativeTypeInput) detect
temporal native types ("timestamp", "timestamptz", "time", "timetz", "interval")
and validate precision with a non-negative integer check (allow 0) for those
types, while keeping the existing isPositiveInteger validation for other native
types; ensure the error message still includes the invalid value via
JSON.stringify. Also update the corresponding tests in
packages/3-targets/6-adapters/postgres/test/descriptor-meta.test.ts to cover
precision 0 for the temporal codecs and maintain existing numeric tests.

@wmadden
wmadden merged commit 97be17c into main Mar 11, 2026
11 checks passed
@wmadden
wmadden deleted the psl-capabilities-and-extensions branch March 11, 2026 14:29
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