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

feat(sql-runtime): derive static ExecutionContext from descriptors only (TML-1827) - #133

Merged
wmadden merged 75 commits into
mainfrom
tml-1827-runtime-dx-derive-static-sql-executioncontext-from
Feb 9, 2026
Merged

wmadden merged 75 commits into
mainfrom
tml-1827-runtime-dx-derive-static-sql-executioncontext-from

Conversation

@wmadden

@wmadden wmadden commented Feb 6, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Enable a static SQL ExecutionContext (contract + codec/operation registries + type helpers) to be created from descriptors only — no adapter/extension instantiation required. This unblocks an app structure where importing query roots (sql, orm, schema, tables) has zero runtime side-effects.

  • Descriptor-level static contributions: Target, adapter, and extension runtime-plane descriptors now implement a required SqlStaticContributions interface (codecs(), operationSignatures(), parameterizedCodecs()). No method is optional; descriptors with nothing to contribute return empty values.
  • createExecutionContext from descriptors-only stack: Accepts { contract, stack } where stack is descriptors-only. Merges contributions deterministically (target → adapter → extensions), validates parameterized codecs, and returns { contract, operations, codecs, types }.
  • Wafer-thin createRuntime: No longer instantiates stack components, derives context, or constructs drivers. Caller provides ExecutionStackInstance, ExecutionContext, and a SqlDriver.
  • Operations layering cleanup: Removed OperationManifest, LoweringSpecManifest, and ComponentMetadata.operations from framework contract types. SQL operations with lowering are family-owned via SqlOperationSignature.
  • Instance contribution surface removed: SqlRuntimeExtensionInstance is now identity-only — contributions live exclusively on descriptors.
  • Demo refactored: context.ts (static setup + query roots) and runtime.ts (dynamic wiring) are cleanly separated.

What changed

1. Operations layering (strip manifest hangover)

  • Removed OperationManifest / LoweringSpecManifest from @prisma-next/contract
  • Removed ComponentMetadata.operations from framework components
  • SQL tooling assembly now builds OperationRegistry from descriptor operationSignatures()

2. Descriptor-level static contributions

  • Defined SqlStaticContributions interface in @prisma-next/sql-runtime
  • Added SqlRuntimeTargetDescriptor, SqlRuntimeAdapterDescriptor, SqlRuntimeExtensionDescriptor types extending core descriptors with required contributions
  • Updated concrete descriptors: target-postgres, adapter-postgres, extension-pgvector

3. createExecutionContext from descriptors-only stack

  • New signature: createExecutionContext({ contract, stack })
  • Deterministic merge order: target → adapter → extensions
  • Parameterized codec validation: duplicate detection, storage.types validation, inline column typeParams validation
  • types registry always present (may be empty)

4. Wafer-thin createRuntime

  • Accepts { stackInstance, context, driver, verify, plugins }
  • Removed: driverOptions plumbing, offline driver defaulting, context derivation, instantiation

5. Demo refactor

  • context.ts: validates contract, defines descriptors-only stack, exports query roots
  • runtime.ts: instantiates stack + driver, calls wafer-thin createRuntime

6. Tests

  • Unit tests for descriptor-based derivation (codec IDs + operations from all contributors)
  • Adapter descriptor/instance codec parity test (in @prisma-next/adapter-postgres)
  • Parameterized codec validation tests (storage.types, inline typeParams, duplicates)
  • context.types always-present assertion
  • Demo smoke tests (static import, runtime execution)

7. Instance contribution surface removed

  • SqlRuntimeExtensionInstance stripped of codecs?(), operations?(), parameterizedCodecs?()
  • pgvector create() returns identity-only instance
  • All test instances updated to identity-only

8. Docs & ADR updates

  • sql-runtime README updated with new two-phase API (static context + dynamic runtime)
  • Subsystem 4 (Runtime & Plugin Framework) updated with new API patterns
  • ADR 152 updated with SQL static contributions section

Why

  • Side-effect-free imports: Importing query roots must not trigger adapter/extension instantiation
  • Single source of truth: Codecs/operations/types come from descriptors, not duplicated on instances
  • Cleaner layering: Framework contract types stay family-agnostic; SQL lowering is family-owned
  • Simpler runtime: createRuntime does one thing — wire up pre-built components

Test plan

  • pnpm --filter @prisma-next/sql-runtime test — 33 tests pass
  • pnpm --filter @prisma-next/adapter-postgres test — 142 tests pass (includes parity test)
  • pnpm --filter @prisma-next/extension-pgvector test — 29 tests pass
  • pnpm --filter prisma-next-demo test — 22 tests pass (including integration)
  • pnpm lint:deps — 0 violations
  • Docs & ADR updates

Summary by CodeRabbit

  • New Features

    • Static context creation from descriptor-level contributions (codecs, operations, parameterized codecs)
    • Descriptor APIs expose operation signatures and codec registries for runtime wiring
  • Bug Fixes

    • Robust PostgreSQL array parsing with proper quoting/escaping
  • Documentation

    • New spec, ADR and README detailing descriptor-based static context derivation and two‑phase runtime flow
  • Refactor

    • Split static context derivation from runtime construction; runtime now requires explicit driver and context
    • Examples and demos updated to the new descriptor-driven APIs

@linear

linear Bot commented Feb 6, 2026

Copy link
Copy Markdown
TML-1827 Runtime DX: derive static SQL ExecutionContext from descriptors

Summary

Refactor SQL runtime-plane composition so a static SQL ExecutionContext (contract + codec registry + operation registry + type helpers) can be created from descriptors only (no adapter/extension instantiation).

This unblocks clean demo/app DX: a context.ts that exports query roots without needing runtime instantiation.

Links

  • Spec: docs/specs/2026-01-19-static-context-codecs-from-descriptors/spec.md

Scope

  • Add descriptor-level static contributions:
    • Adapter descriptor: codecs?(): CodecRegistry
    • Extension descriptor: codecs?(), operations?(), parameterizedCodecs?()
  • Update SQL createExecutionContext to build registries from descriptors-only stack.
  • Keep runtime instantiation semantics intact.

Acceptance criteria

  • Descriptor-based registry derivation yields the same codec IDs and operations as instance-based derivation.
  • Parameterized codec validation still runs for storage.types and inline typeParams.
  • Demo can build query roots from static context.

@coderabbitai

coderabbitai Bot commented Feb 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

Refactors the SQL execution plane to derive a static ExecutionContext from descriptor-level static contributions (codecs, operationSignatures, parameterizedCodecs) without instantiating runtime components. Runtime creation now requires an explicit driver and precomputed context; manifest-based operation types and related exports are removed or migrated to descriptor surfaces.

Changes

Cohort / File(s) Summary
New lint rule & specs
/.cursor/rules/mermaid-compat.mdc, agent-os/specs/2026-01-19-static-context-codecs-from-descriptors/*
Adds Mermaid-compat lint rule and new spec/planning/tasks/visuals for static-context-from-descriptors refactor.
Contract framework types
packages/1-framework/1-core/shared/contract/src/exports/..., packages/1-framework/1-core/shared/contract/src/types.ts, packages/1-framework/1-core/shared/contract/package.json, packages/1-framework/1-core/shared/contract/tsdown.config.ts
Removes manifest-related manifest types and re-exports; drops pack-manifest-types export; adds TypeRenderer API and removes legacy descriptor/instance base types.
SQL tooling: assembly & control
packages/2-sql/3-tooling/family/src/core/assembly.ts, .../control-descriptor.ts, .../control-instance.ts, .../migrations/types.ts
Introduces SqlControlDescriptorWithContributions/SqlControlStaticContributions and refactors operation registry and type-import extraction to read descriptor-level contributions (operationSignatures, codec/type imports).
SQL tooling: verify & exports
packages/2-sql/3-tooling/family/src/core/verify.ts, .../exports/control.ts, .../exports/test-utils.ts
Simplifies descriptor signatures for verification helpers; adds exports for new SqlControl* types; removes convertOperationManifest re-export.
SQL family tests (tooling)
packages/2-sql/3-tooling/family/test/*
Updates mocks/tests to use SQL-specific descriptor shapes and to provide operationSignatures()/codecs() at descriptor level; removes/relocates some tests.
SQL runtime: context & runtime surface
packages/2-sql/5-runtime/src/sql-context.ts, packages/2-sql/5-runtime/src/sql-runtime.ts, packages/2-sql/5-runtime/src/exports/index.ts, packages/2-sql/5-runtime/README.md
Adds SqlStaticContributions and SqlExecutionStack types; createExecutionContext now accepts a descriptors-only stack and aggregates codecs/operations from descriptors; createRuntime requires context and a driver instance (removes contract/driverOptions/offline paths).
SQL runtime tests
packages/2-sql/5-runtime/test/*
Reworks tests to construct descriptor-based stacks, provide static contributions on descriptors, remove instantiateExecutionStack usage, and pass driver+context into runtime creation.
SQL lanes tests
packages/2-sql/4-lanes/sql-lane/test/*
Adds returning capability gating tests and vector-op tests; moves/adjusts deleted test suites accordingly.
Family tooling test utils & integration
test/integration/*, test/integration/utils/*
Removes convertOperationManifest argument from assembleOperationRegistry calls; updates test utilities and descriptor bundles to new SqlControl* descriptor shapes and descriptor-based APIs.
Targets & adapters (Postgres)
packages/3-targets/3-targets/postgres/..., packages/3-targets/6-adapters/postgres/..., packages/3-targets/6-adapters/postgres/package.json
Adds operationSignatures/codecs/parameterizedCodecs to target/adapter/runtime descriptors, switches to SqlRuntime* descriptor types, adds createCodecRegistry helpers, adds sql-runtime workspace dependency and a descriptor-parity test.
Adapters: enum parsing
packages/3-targets/6-adapters/postgres/src/core/enum-control-hooks.ts, .../test/enum-control-hooks.basic.test.ts
Improves parsePostgresArray to handle quoted/escaped elements and adds tests covering quoting/escaping cases.
PGVector extension
packages/3-extensions/pgvector/src/*, packages/3-extensions/pgvector/test/*
Moves operation signatures and codecs to descriptor static methods (operationSignatures, codecs); removes runtime extension instance class; adds createPgvectorCodecRegistry and updates tests to call descriptor methods directly.
Demo apps & queries
examples/prisma-next-demo/src/prisma/context.ts, .../query.ts, .../runtime.ts, examples/prisma-next-demo/scripts/seed.ts, examples/prisma-next-demo/src/queries/*, examples/prisma-orm-demo/*
Splits static context into context.ts (exports schema/tables/sql/orm) and empties old query.ts; updates demos and queries to import from context; runtime and tests updated to use descriptor-based stack and driver-based runtime creation; small API change in orm-writes (added kind field).
Demo tests
examples/prisma-next-demo/test/*, examples/prisma-next-demo/src/kysely/*
Refactors runtime integration tests to use static context and driver-derived runtime; replaces offline runtime test with static-context plan tests; updates import paths.
Docs & ADRs
docs/architecture/.../ADR 152...md, docs/architecture/.../4. Runtime & Plugin Framework.md
Documents SqlStaticContributions, two-phase static/dynamic flow, new createExecutionContext/createRuntime signatures, and rationale for descriptor-level static contributions.
Misc: exports & packaging
packages/2-sql/5-runtime/src/exports/index.ts, various test helpers and small files`
Adds/adjusts public exports for new Sql* runtime/context/descriptor types; updates many test helpers to reflect new shapes and signatures.

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

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

Caution

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

⚠️ Outside diff range comments (3)
packages/2-sql/5-runtime/test/async-iterable-result.test.ts (1)

160-164: 🧹 Nitpick | 🔵 Trivial

Prefer assertion over defensive check.

After asserting rows.length is 1, rows[0] is guaranteed to exist. The if (rows[0]) check is unnecessary defensive coding.

As per coding guidelines: "Prefer assertions over defensive checks when data is guaranteed to be valid."

♻️ Suggested refactor
     expect(rows.length).toBe(1);
-    if (rows[0]) {
-      expect(typeof rows[0].id).toBe('number');
-      expect(typeof rows[0].email).toBe('string');
-    }
+    expect(typeof rows[0]!.id).toBe('number');
+    expect(typeof rows[0]!.email).toBe('string');
examples/prisma-next-demo/test/runtime.integration.test.ts (1)

268-284: 🧹 Nitpick | 🔵 Trivial

Consider extracting repeated driver creation pattern.

The driver creation pattern executionStack.driver!.create({ connect: { pool }, cursor: { disabled: true } }) is repeated across multiple test cases. Consider extracting a helper function for readability.

♻️ Optional helper extraction
function createTestDriver(pool: Pool) {
  return executionStack.driver!.create({
    connect: { pool },
    cursor: { disabled: true },
  });
}
packages/2-sql/4-lanes/sql-lane/test/sql-dml.test.ts (1)

503-504: 🛠️ Refactor suggestion | 🟠 Major

Split this test file; it now exceeds the 500‑line limit.

The file is at ~504 lines; split by concern (e.g., move the vector operation or returning() capability tests into separate sql-dml.*.test.ts files).

As per coding guidelines: "**/*.test.ts: 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."

Comment on lines +46 to +71
4. **Operations representation (remove manifest hangover; keep framework clean)**
- Remove the obsolete “manifest” representation for operations:
- strip `OperationManifest` / `LoweringSpecManifest` from `@prisma-next/contract/*`
- remove `ComponentMetadata.operations` from `@prisma-next/contract/framework-components`
- Keep the framework operation building blocks:
- `OperationSignature` and `OperationRegistry` remain in `@prisma-next/operations` and must stay family-agnostic (no lowering).
- Make family-owned operation definitions the source of truth:
- SQL uses `SqlOperationSignature` (extends `OperationSignature` + adds SQL `lowering`) in `@prisma-next/sql-operations`.
- SQL descriptors expose operation definitions via required `operationSignatures(): ReadonlyArray<SqlOperationSignature>`.
- Contract emission/type generation must continue to work:
- keep `types.operationTypes` import specs on component metadata for `contract.d.ts` generation
- if any tooling needs an operation registry, it must assemble `OperationRegistry` from SQL descriptor `operationSignatures()` (not from framework metadata).

4. **Demo refactor**
- Add `examples/prisma-next-demo/src/prisma/context.ts`:
- validates/loads contract
- defines configuration for static context
- exports query roots (`sql`, `orm`, `schema`, `tables`)
- exports any helper needed by runtime constructor (e.g., contract, stack descriptors)
- Update `examples/prisma-next-demo/src/prisma/runtime.ts`:
- imports from `context.ts`
- constructs runtime (instantiates adapter/driver as needed)
- `examples/prisma-next-demo/src/main.ts` continues to:
- validate env/config (arktype)
- call runtime constructor
- close runtime

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

Minor numbering inconsistency.

Section numbering has a duplicate: there are two sections numbered "4" (Operations representation and Demo refactor). The Demo refactor section should be numbered "5".

📝 Suggested fix
-4. **Demo refactor**
+5. **Demo refactor**
📝 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
4. **Operations representation (remove manifest hangover; keep framework clean)**
- Remove the obsolete “manifest” representation for operations:
- strip `OperationManifest` / `LoweringSpecManifest` from `@prisma-next/contract/*`
- remove `ComponentMetadata.operations` from `@prisma-next/contract/framework-components`
- Keep the framework operation building blocks:
- `OperationSignature` and `OperationRegistry` remain in `@prisma-next/operations` and must stay family-agnostic (no lowering).
- Make family-owned operation definitions the source of truth:
- SQL uses `SqlOperationSignature` (extends `OperationSignature` + adds SQL `lowering`) in `@prisma-next/sql-operations`.
- SQL descriptors expose operation definitions via required `operationSignatures(): ReadonlyArray<SqlOperationSignature>`.
- Contract emission/type generation must continue to work:
- keep `types.operationTypes` import specs on component metadata for `contract.d.ts` generation
- if any tooling needs an operation registry, it must assemble `OperationRegistry` from SQL descriptor `operationSignatures()` (not from framework metadata).
4. **Demo refactor**
- Add `examples/prisma-next-demo/src/prisma/context.ts`:
- validates/loads contract
- defines configuration for static context
- exports query roots (`sql`, `orm`, `schema`, `tables`)
- exports any helper needed by runtime constructor (e.g., contract, stack descriptors)
- Update `examples/prisma-next-demo/src/prisma/runtime.ts`:
- imports from `context.ts`
- constructs runtime (instantiates adapter/driver as needed)
- `examples/prisma-next-demo/src/main.ts` continues to:
- validate env/config (arktype)
- call runtime constructor
- close runtime
4. **Operations representation (remove manifest hangover; keep framework clean)**
- Remove the obsolete "manifest" representation for operations:
- strip `OperationManifest` / `LoweringSpecManifest` from `@prisma-next/contract/*`
- remove `ComponentMetadata.operations` from `@prisma-next/contract/framework-components`
- Keep the framework operation building blocks:
- `OperationSignature` and `OperationRegistry` remain in `@prisma-next/operations` and must stay family-agnostic (no lowering).
- Make family-owned operation definitions the source of truth:
- SQL uses `SqlOperationSignature` (extends `OperationSignature` + adds SQL `lowering`) in `@prisma-next/sql-operations`.
- SQL descriptors expose operation definitions via required `operationSignatures(): ReadonlyArray<SqlOperationSignature>`.
- Contract emission/type generation must continue to work:
- keep `types.operationTypes` import specs on component metadata for `contract.d.ts` generation
- if any tooling needs an operation registry, it must assemble `OperationRegistry` from SQL descriptor `operationSignatures()` (not from framework metadata).
5. **Demo refactor**
- Add `examples/prisma-next-demo/src/prisma/context.ts`:
- validates/loads contract
- defines configuration for static context
- exports query roots (`sql`, `orm`, `schema`, `tables`)
- exports any helper needed by runtime constructor (e.g., contract, stack descriptors)
- Update `examples/prisma-next-demo/src/prisma/runtime.ts`:
- imports from `context.ts`
- constructs runtime (instantiates adapter/driver as needed)
- `examples/prisma-next-demo/src/main.ts` continues to:
- validate env/config (arktype)
- call runtime constructor
- close runtime

Comment on lines 36 to 47
//
// Assert that the stack's descriptors implement SqlControlStaticContributions.
// This is a runtime contract: SQL descriptors must provide operationSignatures().
const target = stack.target as unknown as SqlControlDescriptorWithContributions;
const adapter = stack.adapter as unknown as SqlControlAdapterDescriptor<TTargetId>;
const extensionPacks =
stack.extensionPacks as unknown as readonly SqlControlExtensionDescriptor<TTargetId>[];
return createSqlFamilyInstance({
target: stack.target,
adapter: stack.adapter,
extensionPacks: stack.extensionPacks,
target,
adapter,
extensionPacks,
});

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

Replace blind casts with runtime validation.

The as unknown as casts at lines 39-42 violate coding guidelines for production code. Since this is a "runtime contract" as the comment states, add runtime validation to ensure descriptors implement the required interface before use.

Consider adding a type guard or validation function:

🛡️ Proposed fix with runtime validation
+function assertSqlStaticContributions(
+  descriptor: unknown,
+  name: string,
+): asserts descriptor is SqlControlDescriptorWithContributions {
+  if (
+    typeof descriptor !== 'object' ||
+    descriptor === null ||
+    typeof (descriptor as SqlControlDescriptorWithContributions).operationSignatures !== 'function'
+  ) {
+    throw new Error(
+      `${name} descriptor must implement SqlControlStaticContributions (missing operationSignatures())`,
+    );
+  }
+}

   create<TTargetId extends string>(
     stack: ControlPlaneStack<'sql', TTargetId>,
   ): SqlControlFamilyInstance {
-    //
-    // Assert that the stack's descriptors implement SqlControlStaticContributions.
-    // This is a runtime contract: SQL descriptors must provide operationSignatures().
-    const target = stack.target as unknown as SqlControlDescriptorWithContributions;
-    const adapter = stack.adapter as unknown as SqlControlAdapterDescriptor<TTargetId>;
-    const extensionPacks =
-      stack.extensionPacks as unknown as readonly SqlControlExtensionDescriptor<TTargetId>[];
+    // Validate that the stack's descriptors implement SqlControlStaticContributions.
+    assertSqlStaticContributions(stack.target, 'target');
+    assertSqlStaticContributions(stack.adapter, 'adapter');
+    for (const ext of stack.extensionPacks) {
+      assertSqlStaticContributions(ext, `extension ${ext.id}`);
+    }
+    const target = stack.target as SqlControlDescriptorWithContributions;
+    const adapter = stack.adapter as SqlControlAdapterDescriptor<TTargetId>;
+    const extensionPacks = stack.extensionPacks as readonly SqlControlExtensionDescriptor<TTargetId>[];
     return createSqlFamilyInstance({
       target,
       adapter,
       extensionPacks,
     });
   }

As per coding guidelines: "Avoid blind casts like as unknown as X in production TypeScript code. Use type predicates (value is X) or type guards instead to let the compiler narrow types safely."

📝 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
//
// Assert that the stack's descriptors implement SqlControlStaticContributions.
// This is a runtime contract: SQL descriptors must provide operationSignatures().
const target = stack.target as unknown as SqlControlDescriptorWithContributions;
const adapter = stack.adapter as unknown as SqlControlAdapterDescriptor<TTargetId>;
const extensionPacks =
stack.extensionPacks as unknown as readonly SqlControlExtensionDescriptor<TTargetId>[];
return createSqlFamilyInstance({
target: stack.target,
adapter: stack.adapter,
extensionPacks: stack.extensionPacks,
target,
adapter,
extensionPacks,
});
function assertSqlStaticContributions(
descriptor: unknown,
name: string,
): asserts descriptor is SqlControlDescriptorWithContributions {
if (
typeof descriptor !== 'object' ||
descriptor === null ||
typeof (descriptor as SqlControlDescriptorWithContributions).operationSignatures !== 'function'
) {
throw new Error(
`${name} descriptor must implement SqlControlStaticContributions (missing operationSignatures())`,
);
}
}
create<TTargetId extends string>(
stack: ControlPlaneStack<'sql', TTargetId>,
): SqlControlFamilyInstance {
// Validate that the stack's descriptors implement SqlControlStaticContributions.
assertSqlStaticContributions(stack.target, 'target');
assertSqlStaticContributions(stack.adapter, 'adapter');
for (const ext of stack.extensionPacks) {
assertSqlStaticContributions(ext, `extension ${ext.id}`);
}
const target = stack.target as SqlControlDescriptorWithContributions;
const adapter = stack.adapter as SqlControlAdapterDescriptor<TTargetId>;
const extensionPacks = stack.extensionPacks as readonly SqlControlExtensionDescriptor<TTargetId>[];
return createSqlFamilyInstance({
target,
adapter,
extensionPacks,
});
}

template: '${self} <=> ${arg0}',
},
};
const mockVectorExtensionDescriptor: import('@prisma-next/sql-runtime').SqlRuntimeExtensionDescriptor<'postgres'> =

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

🧩 Analysis chain

🏁 Script executed:

# First, check if the file exists and read around line 327
wc -l packages/2-sql/4-lanes/sql-lane/test/sql-dml.test.ts

Repository: prisma/prisma-next

Length of output: 118


🏁 Script executed:

# Read the specific area around line 327
sed -n '320,335p' packages/2-sql/4-lanes/sql-lane/test/sql-dml.test.ts | cat -n

Repository: prisma/prisma-next

Length of output: 812


🏁 Script executed:

# Check the top-level imports in the file
head -50 packages/2-sql/4-lanes/sql-lane/test/sql-dml.test.ts | cat -n

Repository: prisma/prisma-next

Length of output: 2204


Replace the inline type import with a top-level import type statement.

Inline type imports are disallowed; move SqlRuntimeExtensionDescriptor to a named type import at the top of the file alongside other imports from @prisma-next/sql-runtime.

🔧 Proposed change
 import type { SqlContract, SqlStorage } from '@prisma-next/sql-contract/types';
+import type { SqlRuntimeExtensionDescriptor } from '@prisma-next/sql-runtime';
 import { validateContract } from '@prisma-next/sql-contract-ts/contract';
@@
-    const mockVectorExtensionDescriptor: import('@prisma-next/sql-runtime').SqlRuntimeExtensionDescriptor<'postgres'> =
+    const mockVectorExtensionDescriptor: SqlRuntimeExtensionDescriptor<'postgres'> =

@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

Comment thread packages/2-sql/5-runtime/README.md Resolved
Comment thread packages/2-sql/5-runtime/README.md Resolved

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Delete this

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

See if there's a mermaid skill available we can use!

Comment on lines 69 to 80
target: {
kind: 'target',
id: 'postgres',
version: '0.0.1',
familyId: 'sql' as const,
targetId: 'postgres' as const,
codecs: () => createCodecRegistry(),
operationSignatures: () => [],
parameterizedCodecs: () => [],
create() {
return { familyId: 'sql' as const, targetId: 'postgres' as const };
},

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

We can probably DRY up these mock framework component structures, perhaps in test/utils

@wmadden
wmadden force-pushed the tml-1827-runtime-dx-derive-static-sql-executioncontext-from branch from 44113e0 to cabf9e5 Compare February 6, 2026 14:12

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

Caution

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

⚠️ Outside diff range comments (5)
packages/3-extensions/pgvector/test/manifest.test.ts (1)

32-47: ⚠️ Potential issue | 🟡 Minor

Consolidate related assertions with an object matcher.
Use a single toMatchObject for the cosineDistance operation instead of multiple property assertions.

♻️ Suggested refactor
-    expect(cosineDistanceOp).toBeDefined();
-    expect(cosineDistanceOp?.args).toEqual([{ kind: 'param' }]);
-    expect(cosineDistanceOp?.returns).toEqual({ kind: 'builtin', type: 'number' });
-    expect(cosineDistanceOp?.lowering).toEqual({
-      targetFamily: 'sql',
-      strategy: 'function',
-      template: '1 - ({{self}} <=> {{arg0}})',
-    });
+    expect(cosineDistanceOp).toMatchObject({
+      args: [{ kind: 'param' }],
+      returns: { kind: 'builtin', type: 'number' },
+      lowering: {
+        targetFamily: 'sql',
+        strategy: 'function',
+        template: '1 - ({{self}} <=> {{arg0}})',
+      },
+    });
As per coding guidelines, "Prefer object comparison using `toEqual` or `toMatchObject` for assertions on objects, rather than property-by-property checks with `toHaveProperty` or individual property assertions."
packages/2-sql/3-tooling/family/test/emit-parameterized.test.ts (2)

70-77: 🛠️ Refactor suggestion | 🟠 Major

Use ifDefined() for conditional spreads.

Inline conditional spread for typesImport should use the shared helper for consistency.

♻️ Suggested change
+import { ifDefined } from '@prisma-next/utils/defined';
...
-        ...(config.typesImport ? { typeImports: [config.typesImport] } : {}),
+        ...ifDefined(config.typesImport, (typesImport) => ({
+          typeImports: [typesImport],
+        })),
As per coding guidelines, Use `ifDefined()` from `@prisma-next/utils/defined` for conditional object spreads instead of inline conditional spread patterns.

116-133: 🛠️ Refactor suggestion | 🟠 Major

Prefer createContractIR() factory for ContractIR test data.

Manual ContractIR construction is discouraged; using the factory avoids drift and keeps defaults consistent. 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.

packages/2-sql/5-runtime/test/parameterized-types.test.ts (1)

16-51: 🛠️ Refactor suggestion | 🟠 Major

Replace conditional spreads with ifDefined() in test helpers.

Use the shared helper for the optional types and init spreads to match repo conventions.

♻️ Suggested change
+import { ifDefined } from '@prisma-next/utils/defined';
...
-      ...(options?.types ? { types: options.types } : {}),
+      ...ifDefined(options?.types, (types) => ({ types })),
...
-          ...(options?.init ? { init: options.init } : {}),
+          ...ifDefined(options?.init, (init) => ({ init })),
As per coding guidelines, Use `ifDefined()` from `@prisma-next/utils/defined` for conditional object spreads instead of inline conditional spread patterns.

Also applies to: 106-116

packages/2-sql/5-runtime/test/sql-runtime.test.ts (1)

160-190: 🧹 Nitpick | 🔵 Trivial

Prefer object matchers for related assertions in these tests.

Multiple related toBeDefined() checks can be collapsed into a single toMatchObject for clarity.

✅ Suggested refactor
-    expect(runtime).toBeDefined();
-    expect(runtime.execute).toBeDefined();
-    expect(runtime.telemetry).toBeDefined();
-    expect(runtime.operations).toBeDefined();
-    expect(runtime.close).toBeDefined();
+    expect(runtime).toMatchObject({
+      execute: expect.any(Function),
+      telemetry: expect.any(Function),
+      operations: expect.any(Function),
+      close: expect.any(Function),
+    });

-    const ops = runtime.operations();
-    expect(ops).toBeDefined();
-    expect(ops.byType).toBeDefined();
+    const ops = runtime.operations();
+    expect(ops).toMatchObject({
+      byType: expect.any(Function),
+    });

As per coding guidelines: “Prefer object matchers (toMatchObject) over multiple individual expect().toBe() calls when checking 2 or more related values in tests.”

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

Comment thread packages/2-sql/5-runtime/test/utils.ts Resolved
…r-level static contributions

Introduce SqlStaticContributions interface that defines required methods for
SQL runtime-plane descriptors to contribute codecs, operations, and
parameterized codec descriptors to ExecutionContext.

Add SQL-specific descriptor types that extend core execution-plane types:
- SqlRuntimeTargetDescriptor
- SqlRuntimeAdapterDescriptor
- SqlRuntimeExtensionDescriptor

These types require descriptors to implement static contribution methods:
- codecs(): returns CodecRegistry
- operationSignatures(): returns SqlOperationSignature[] (renamed from
  operations() to avoid conflict with ComponentMetadata.operations)
- parameterizedCodecs(): returns RuntimeParameterizedCodecDescriptor[]

This enables static context creation without instantiating runtime components.
…y static contributions

Update postgres runtime target descriptor to implement the new
SqlRuntimeTargetDescriptor interface with required static contribution methods.

The target provides empty contributions since codecs and operations are
contributed by the adapter and extensions:
- codecs(): returns empty CodecRegistry
- operationSignatures(): returns empty array
- parameterizedCodecs(): returns empty array

Add sql-relational-core and sql-runtime dependencies to package.json.
…atic codec contributions

Update postgres runtime adapter descriptor to implement the new
SqlRuntimeAdapterDescriptor interface with required static contribution methods.

The adapter contributes codecs for all native postgres types:
- codecs(): creates registry from codecDefinitions (pg/text@1, pg/int4@1, etc.)
- operationSignatures(): returns empty array (adapter has no operations)
- parameterizedCodecs(): returns empty array (adapter has no parameterized codecs)

Extract createPostgresCodecRegistry helper to share codec registry creation
logic between static contributions and adapter instance.

Add sql-runtime dependency to package.json.
…descriptor

Update pgvector runtime extension descriptor to implement
SqlRuntimeExtensionDescriptor with static contributions on the descriptor
rather than instance methods.

The descriptor now provides:
- codecs(): pg/vector@1 codec for vector type
- operationSignatures(): cosineDistance operation for similarity search
- parameterizedCodecs(): vector params schema with length validation

The instance is now minimal (identity properties only) since no runtime
hooks require instance-level behavior.

Update tests to verify descriptor static contributions instead of
instance methods.
The framework contract should not define operation manifest types.
Operations are family-owned concerns (e.g. SQL family defines SqlOperationSignature).

- Remove ArgSpecManifest, ReturnSpecManifest, LoweringSpecManifest, OperationManifest
- Remove ComponentMetadata.operations property
- Delete pack-manifest-types.ts export entrypoint

This is the first step of operations layering - moving operation
definitions from framework to family-specific descriptor surfaces.
Define operationSignatures() method on SQL control plane descriptors.
This is the family-owned API for declaring operation signatures at
control plane initialization, replacing the generic OperationManifest.

- Add SqlControlStaticContributions interface with operationSignatures()
- Update SqlControlTargetDescriptor to extend SqlControlStaticContributions
- Update SqlControlAdapterDescriptor to extend SqlControlStaticContributions
- Update SqlControlExtensionDescriptor to extend SqlControlStaticContributions
- Export SqlControlDescriptorWithContributions from control.ts
The operation registry is now assembled by calling operationSignatures()
on each SQL descriptor, rather than converting OperationManifest.

- Remove convertOperationManifest from assembly and test-utils exports
- Update assembleOperationRegistry to take SqlControlDescriptorWithContributions
- Call descriptor.operationSignatures() and register each signature
- Cast generic ControlPlaneStack types to SQL-specific types at family boundary
- Simplify collectSupportedCodecTypeIds to accept minimal descriptor shape
Move operation definition from pack metadata to descriptor method.
The operation signature is now returned by operationSignatures()
on both control and runtime descriptors.

- Remove operations array from pgvectorPackMeta
- Add pgvectorOperationSignature as canonical SqlOperationSignature
- Implement operationSignatures() on control descriptor
- Update runtime descriptor to use pgvectorOperationSignature
Postgres target and adapter now implement SqlControlStaticContributions.
They return empty arrays since they do not contribute operations.

- Update postgres target descriptor with operationSignatures: () => []
- Update postgres adapter descriptor with operationSignatures: () => []
- Use SQL-specific descriptor types for better type safety
Test mocks and fixtures now implement SqlControlStaticContributions.
Remove convertOperationManifest usage from all integration tests.

- Add operationSignatures() to mock descriptors in family-sql tests
- Update sql-lane mock extension descriptor with codecs() and operationSignatures()
- Provide operations() on mock instance (required by createExecutionContext)
- Update pgvector manifest test to use operationSignatures()
- Update postgres planner tests with operationSignatures()
- Remove convertOperationManifest from integration test imports
- Update integration utils to use SQL-specific descriptor types
Change the signature from { contract, stackInstance } to
{ contract, stack } where stack is a SqlExecutionStack containing
SQL descriptors with required static contributions (codecs,
operationSignatures, parameterizedCodecs).

This enables static ExecutionContext creation without instantiating
adapter/extension instances, since all contributions are read
directly from descriptor methods.

Merge order is deterministic: target -> adapter -> extensionPacks.
Parameterized codec collection also follows this order across all
contributors, not just extensions.
Replace { contract, stackInstance } with { contract, stack } at every
createExecutionContext call site. Context is now derived from
descriptor static contributions, removing the need to instantiate
the execution stack just to build query roots.
Remove all internal plumbing from createRuntime:
- context is now required (no fallback derivation)
- driver is an explicit SqlDriver (no driverOptions/descriptor instantiation)
- Remove offline driver defaulting
- Remove driver type validation (isSqlDriver)
- Remove contract/stack assertion (already done in createExecutionContext)

Callers are now responsible for constructing the ExecutionContext
(via createExecutionContext) and the SqlDriver before calling
createRuntime. This eliminates the unsafe SqlExecutionStack cast
and clarifies the boundary between static setup and runtime wiring.
- Add missing RuntimeDriverInstance import in sql-context.ts
- Update schema-view test mocks to implement SqlControlStaticContributions

Both issues existed before Section 4 changes and were exposed
by the full build and test suite.
…ntime

Callers now construct drivers explicitly via descriptor.create()
instead of passing driverOptions. The contract parameter is removed
since it lives in context. The offline integration test is simplified
to test query plan building without a runtime, since static query
building no longer requires runtime construction.

@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

…onStack directly

createExecutionStack's generic inference broadens SqlRuntimeTargetDescriptor
(et al.) to RuntimeTargetDescriptor, losing SqlStaticContributions. Instead
of casting the result, construct SqlExecutionStack inline from the concrete
descriptor imports which preserve their SQL-specific types.
The casts work around createExecutionStack broadening SQL-specific descriptor
types to their generic base types. Comments explain this is a type inference
limitation, not a missing property (driver is not the issue).
parsePostgresArray previously split naively on commas, which would misparse
enum labels containing commas, double quotes, or backslashes. Implement
proper PostgreSQL array quoting rules where quoted elements use \" and \\
escape sequences. Add test coverage for these edge cases.
@wmadden
wmadden force-pushed the tml-1827-runtime-dx-derive-static-sql-executioncontext-from branch from 6ec9f81 to 7c99a81 Compare February 7, 2026 11:08

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

Caution

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

⚠️ Outside diff range comments (2)
packages/3-extensions/pgvector/test/operations.test.ts (1)

24-39: 🧹 Nitpick | 🔵 Trivial

Prefer object matchers for related field checks.
Consolidate property assertions into toMatchObject to align with test conventions.

♻️ Suggested refactor
-    const cosineDistanceOp = operations[0];
-    expect(cosineDistanceOp).toBeDefined();
-    expect(cosineDistanceOp?.forTypeId).toBe('pg/vector@1');
-    expect(cosineDistanceOp?.method).toBe('cosineDistance');
-    expect(cosineDistanceOp?.args).toEqual([{ kind: 'param' }]);
-    expect(cosineDistanceOp?.returns).toEqual({ kind: 'builtin', type: 'number' });
-    expect(cosineDistanceOp?.lowering).toEqual({
-      targetFamily: 'sql',
-      strategy: 'function',
-      template: '1 - ({{self}} <=> {{arg0}})',
-    });
+    const cosineDistanceOp = operations[0];
+    expect(cosineDistanceOp).toMatchObject({
+      forTypeId: 'pg/vector@1',
+      method: 'cosineDistance',
+      args: [{ kind: 'param' }],
+      returns: { kind: 'builtin', type: 'number' },
+      lowering: {
+        targetFamily: 'sql',
+        strategy: 'function',
+        template: '1 - ({{self}} <=> {{arg0}})',
+      },
+    });
@@
-    const instance = pgvectorDescriptor.create();
-    expect(instance.familyId).toBe('sql');
-    expect(instance.targetId).toBe('postgres');
+    const instance = pgvectorDescriptor.create();
+    expect(instance).toMatchObject({ familyId: 'sql', targetId: 'postgres' });

As per coding guidelines, **/*.test.ts: Prefer object matchers (toMatchObject) over multiple individual expect().toBe() calls when checking 2 or more related values in tests.

Also applies to: 70-74

packages/2-sql/5-runtime/src/sql-context.ts (1)

231-237: 🧹 Nitpick | 🔵 Trivial

Consider removing the generic default for TContract.

The default TContract extends SqlContract<SqlStorage> = SqlContract<SqlStorage> may cause type inference issues downstream. As per coding guidelines: "Using a generic type causes all subsequent type inference to fail, resulting in unknown types throughout the code."

Callers should always provide a fully-typed contract type for proper type inference in the returned ExecutionContext<TContract>.

♻️ Suggested change
 export function createExecutionContext<
-  TContract extends SqlContract<SqlStorage> = SqlContract<SqlStorage>,
+  TContract extends SqlContract<SqlStorage>,
   TTargetId extends string = string,
 >(options: {

Comment on lines 22 to 26
export const executionStackInstance = instantiateExecutionStack(executionStack);
export const executionContext = createExecutionContext({
contract,
stackInstance: executionStackInstance,
stack: executionStack as never,
});

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

🧩 Analysis chain

🏁 Script executed:

cat -n examples/prisma-next-demo/src/prisma-no-emit/query-no-emit.ts

Repository: prisma/prisma-next

Length of output: 1641


🏁 Script executed:

rg -n -B5 -A10 'createExecutionContext' examples/prisma-next-demo/src/prisma-no-emit/ --type ts

Repository: prisma/prisma-next

Length of output: 3048


🏁 Script executed:

rg -n -A5 'createExecutionContext\(' --type=ts

Repository: prisma/prisma-next

Length of output: 9880


🏁 Script executed:

cat -n examples/prisma-next-demo/src/prisma/context.ts | head -35

Repository: prisma/prisma-next

Length of output: 1956


🏁 Script executed:

rg -B3 -A3 'as never' examples/prisma-next-demo/src/prisma examples/prisma-orm-demo/src --type ts | head -40

Repository: prisma/prisma-next

Length of output: 1267


Add explanatory comment for the as never cast and remove unused executionStackInstance.

The as never cast on line 25 is necessary due to generic type inference, not a blind cast. Add the explanatory comment from context.ts to document why the cast is needed. Additionally, executionStackInstance (line 22) is exported but never used and should be removed.

Comment on lines +3 to +19
import { executionContext, executionStack, executionStackInstance } from './query-no-emit';

export function getRuntime(databaseUrl: string): Runtime {
const pool = new Pool({ connectionString: databaseUrl });

const driverDescriptor = executionStack.driver;
if (!driverDescriptor) {
throw new Error('Driver descriptor missing from execution stack');
}

return createRuntime({
stackInstance: executionStackInstance,
contract: executionContext.contract,
context: executionContext,
driverOptions: {
driver: driverDescriptor.create({
connect: { pool },
cursor: { disabled: true },
},
}),

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:

find . -type f -name "query-no-emit.ts" | head -5

Repository: prisma/prisma-next

Length of output: 125


🏁 Script executed:

fd "runtime-no-emit" -t f

Repository: prisma/prisma-next

Length of output: 125


🏁 Script executed:

fd "query-no-emit" -t f

Repository: prisma/prisma-next

Length of output: 123


🏁 Script executed:

cat -n examples/prisma-next-demo/src/prisma-no-emit/query-no-emit.ts

Repository: prisma/prisma-next

Length of output: 1641


🏁 Script executed:

cat -n examples/prisma-next-demo/src/prisma-no-emit/runtime-no-emit.ts

Repository: prisma/prisma-next

Length of output: 1240


🏁 Script executed:

rg "instantiateExecutionStack" --type ts -B 2 -A 2 | head -30

Repository: prisma/prisma-next

Length of output: 1772


🏁 Script executed:

sed -n '1,50p' packages/2-sql/5-runtime/test/utils.ts

Repository: prisma/prisma-next

Length of output: 2041


Avoid import-time stack instantiation in the no-emit runtime.

executionStackInstance is instantiated at module load in examples/prisma-next-demo/src/prisma-no-emit/query-no-emit.ts, so importing it here reintroduces side effects that the descriptor-based approach is trying to avoid. Instantiate the stack inside getRuntime and pass that instance to createRuntime instead.

Suggested change
-import { executionContext, executionStack, executionStackInstance } from './query-no-emit';
+import { instantiateExecutionStack } from '@prisma-next/core-execution-plane/stack';
+import { executionContext, executionStack } from './query-no-emit';

 export function getRuntime(databaseUrl: string): Runtime {
   const pool = new Pool({ connectionString: databaseUrl });

+  const stackInstance = instantiateExecutionStack(executionStack);
   const driverDescriptor = executionStack.driver;
   if (!driverDescriptor) {
     throw new Error('Driver descriptor missing from execution stack');
   }

   return createRuntime({
-    stackInstance: executionStackInstance,
+    stackInstance,
     context: executionContext,
     driver: driverDescriptor.create({
       connect: { pool },
       cursor: { disabled: true },
     }),

Comment on lines 23 to 29
// Cast needed: createExecutionStack's generic inference broadens SqlRuntimeTargetDescriptor
// (et al.) to RuntimeTargetDescriptor, losing the SqlStaticContributions interface that
// createExecutionContext requires. The concrete descriptors above do satisfy SqlExecutionStack.
export const executionContext = createExecutionContext({
contract,
stackInstance: executionStackInstance,
stack: executionStack as never,
});

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

🧩 Analysis chain

🏁 Script executed:

find . -type f -name "context.ts" | grep "prisma-next-demo"

Repository: prisma/prisma-next

Length of output: 111


🏁 Script executed:

cat -n examples/prisma-next-demo/src/prisma/context.ts

Repository: prisma/prisma-next

Length of output: 1956


🏁 Script executed:

# Find SqlExecutionStack type definition
rg "type SqlExecutionStack|interface SqlExecutionStack" --type ts

Repository: prisma/prisma-next

Length of output: 253


🏁 Script executed:

# Check imports in the context.ts file to understand what's available
head -30 examples/prisma-next-demo/src/prisma/context.ts

Repository: prisma/prisma-next

Length of output: 1502


🏁 Script executed:

# Check the SqlExecutionStack definition
sed -n '1,50p' packages/2-sql/5-runtime/src/sql-context.ts

Repository: prisma/prisma-next

Length of output: 1920


🏁 Script executed:

# Check createExecutionContext signature
rg "export (function|const) createExecutionContext" packages/2-sql/5-runtime/src -A 10

Repository: prisma/prisma-next

Length of output: 922


🏁 Script executed:

# Check if SqlExecutionStack is exported from `@prisma-next/sql-runtime`
rg "SqlExecutionStack" packages/2-sql/5-runtime/src/index.ts packages/2-sql/5-runtime/src/exports.ts 2>/dev/null || echo "Checking package exports..."

Repository: prisma/prisma-next

Length of output: 89


🏁 Script executed:

# Find the main export file for sql-runtime
find packages/2-sql/5-runtime -name "index.ts" -o -name "exports.ts" -o -name "package.json" | head -5

Repository: prisma/prisma-next

Length of output: 145


🏁 Script executed:

# Check the exports file
cat packages/2-sql/5-runtime/src/exports/index.ts

Repository: prisma/prisma-next

Length of output: 1223


🏁 Script executed:

# Also check if there's a main index.ts
cat packages/2-sql/5-runtime/src/index.ts 2>/dev/null || echo "No main index.ts"

Repository: prisma/prisma-next

Length of output: 78


🏁 Script executed:

# Check the complete SqlExecutionStack definition
sed -n '/^export interface SqlExecutionStack/,/^}/p' packages/2-sql/5-runtime/src/sql-context.ts

Repository: prisma/prisma-next

Length of output: 333


🏁 Script executed:

# Check assertExecutionStackContractRequirements to understand what it validates
rg "function assertExecutionStackContractRequirements" packages/2-sql/5-runtime/src -A 15

Repository: prisma/prisma-next

Length of output: 1227


Replace the as never cast with explicit SqlExecutionStack typing.

The cast bypasses type checking. Add an explicit type annotation to executionStack using SqlExecutionStack from @prisma-next/sql-runtime. This lets TypeScript validate the return type of createExecutionStack() against the expected interface and eliminates the need for the workaround cast and comment.

♻️ Suggested refactor
 import { createExecutionStack } from '@prisma-next/core-execution-plane/stack';
+import type { SqlExecutionStack } from '@prisma-next/sql-runtime';
 import postgresDriver from '@prisma-next/driver-postgres/runtime';
 import pgvectorDescriptor from '@prisma-next/extension-pgvector/runtime';
 import { validateContract } from '@prisma-next/sql-contract-ts/contract';
 import { sql as sqlBuilder } from '@prisma-next/sql-lane';
 import { orm as ormBuilder } from '@prisma-next/sql-orm-lane';
 import { schema as schemaBuilder } from '@prisma-next/sql-relational-core/schema';
 import { createExecutionContext } from '@prisma-next/sql-runtime';
 import postgresTarget from '@prisma-next/target-postgres/runtime';
 import type { Contract } from './contract.d';
 import contractJson from './contract.json' with { type: 'json' };

 const contract = validateContract<Contract>(contractJson);

-export const executionStack = createExecutionStack({
+export const executionStack: SqlExecutionStack = createExecutionStack({
   target: postgresTarget,
   adapter: postgresAdapter,
   driver: postgresDriver,
   extensionPacks: [pgvectorDescriptor],
 });
-
-// Cast needed: createExecutionStack's generic inference broadens SqlRuntimeTargetDescriptor
-// (et al.) to RuntimeTargetDescriptor, losing the SqlStaticContributions interface that
-// createExecutionContext requires. The concrete descriptors above do satisfy SqlExecutionStack.
 export const executionContext = createExecutionContext({
   contract,
-  stack: executionStack as never,
+  stack: executionStack,
 });

Comment on lines +1 to +2
import { describe, expect, it, vi } from 'vitest';
import { executionStack, sql, tables } from '../src/prisma/context';

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

🧩 Analysis chain

🏁 Script executed:

#!/bin/bash
# Search for mock restoration patterns in the codebase
echo "=== Searching for mock restoration patterns ==="
rg -n "restoreAllMocks|clearAllMocks" -g "*.{ts,js,cts,mts}" --max-count=20

echo -e "\n=== Checking vitest configuration ==="
find . -name "vitest.config.*" -type f 2>/dev/null

echo -e "\n=== Checking test setup files ==="
rg -n "setupFiles|setupFilesAfterEnv|vitest\.setup" -g "vitest.config.*" -A 3

Repository: prisma/prisma-next

Length of output: 2215


🏁 Script executed:

#!/bin/bash
# Examine the specific test file to see if it uses spies
echo "=== Examining the test file ==="
cat -n examples/prisma-next-demo/test/runtime.offline.integration.test.ts | head -50

Repository: prisma/prisma-next

Length of output: 1614


🏁 Script executed:

#!/bin/bash
# Check if there's a global vitest setup file
echo "=== Looking for vitest setup or config in examples/prisma-next-demo ==="
find examples/prisma-next-demo -name "vitest.config.*" -o -name "*.setup.*" -o -name "vitest.*.ts" 2>/dev/null | head -20

Repository: prisma/prisma-next

Length of output: 176


🏁 Script executed:

#!/bin/bash
# Search for any vi.spyOn usage in the specific test file
echo "=== Checking for spy usage in the test file ==="
rg -n "vi\.spy|spyOn" examples/prisma-next-demo/test/runtime.offline.integration.test.ts

Repository: prisma/prisma-next

Length of output: 346


🏁 Script executed:

#!/bin/bash
# Examine the vitest config for examples/prisma-next-demo
echo "=== Vitest config for examples/prisma-next-demo ==="
cat -n examples/prisma-next-demo/vitest.config.ts

Repository: prisma/prisma-next

Length of output: 507


🏁 Script executed:

#!/bin/bash
# Check if there's a shared vitest config at the root
echo "=== Root vitest.config.ts if it exists ==="
if [ -f ./vitest.config.ts ]; then
  cat -n ./vitest.config.ts
fi

echo -e "\n=== Check vitest.workspace.ts ==="
if [ -f ./vitest.workspace.ts ]; then
  cat -n ./vitest.workspace.ts | head -50
fi

Repository: prisma/prisma-next

Length of output: 139


🏁 Script executed:

#!/bin/bash
# Check the test file for any existing afterEach hooks
echo "=== Full test file to check for afterEach ==="
wc -l examples/prisma-next-demo/test/runtime.offline.integration.test.ts
cat -n examples/prisma-next-demo/test/runtime.offline.integration.test.ts

Repository: prisma/prisma-next

Length of output: 1698


Add mock restoration to prevent spy leakage across tests.

The test file creates spies at lines 18-20 but provides no cleanup mechanism. Since the vitest configuration for this example does not include global mock restoration setup, these spies will persist after the test completes and potentially affect other tests if added later.

🧹 Suggested fix (local restore)
-import { describe, expect, it, vi } from 'vitest';
+import { afterEach, describe, expect, it, vi } from 'vitest';
 import { executionStack, sql, tables } from '../src/prisma/context';

+afterEach(() => {
+  vi.restoreAllMocks();
+});

Comment on lines +15 to +17
// context.ts exports a descriptors-only stack — create() is never called.
// Spy on the descriptor create methods and verify they stay untouched
// while building query plans from the static context.

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 | 🔵 Trivial

Remove the inline comments and rely on the test name for intent.

These comments restate the test’s purpose and can be removed to keep the file concise.

✂️ Suggested cleanup
-    // context.ts exports a descriptors-only stack — create() is never called.
-    // Spy on the descriptor create methods and verify they stay untouched
-    // while building query plans from the static context.
     const adapterSpy = vi.spyOn(executionStack.adapter, 'create');
     const targetSpy = vi.spyOn(executionStack.target, 'create');
     const extensionSpies = executionStack.extensionPacks.map((ext) => vi.spyOn(ext, 'create'));

-    // Build a query plan — must NOT trigger any descriptor instantiation
     sql.from(tables.user).select({ id: tables.user.columns.id }).limit(1).build();

As per coding guidelines: “Don’t add comments if avoidable; prefer code which expresses its intent.”

Also applies to: 22-22

Comment on lines 286 to 304
export function createSqlFamilyInstance<TTargetId extends string>(
options: CreateSqlFamilyInstanceOptions<TTargetId>,
): SqlFamilyInstance {
const { target, adapter, extensionPacks: extensions = [] } = options;

// Build descriptors array for assembly
// Assembly functions only use manifest and id, so we can pass Control*Descriptor types directly
const descriptors = [target, adapter, ...extensions];
const descriptors: SqlControlDescriptorWithContributions[] = [target, adapter, ...extensions];

// Assemble operation registry, type imports, extension IDs, and parameterized renderers
const operationRegistry = assembleOperationRegistry(descriptors, convertOperationManifest);
const operationRegistry = assembleOperationRegistry(descriptors);
const codecTypeImports = extractCodecTypeImports(descriptors);
const operationTypeImports = extractOperationTypeImports(descriptors);
const extensionIds = extractExtensionIds(adapter, target, extensions);
const parameterizedRenderers = extractParameterizedRenderers(descriptors);
const parameterizedTypeImports = extractParameterizedTypeImports(descriptors);

// Build type metadata registry from manifests
const typeMetadataRegistry = buildSqlTypeMetadataRegistry({
target,
adapter,
extensionPacks: extensions,
target: target as DescriptorWithStorageTypes,
adapter: adapter as DescriptorWithStorageTypes & { readonly targetId: string },
extensionPacks: extensions as readonly DescriptorWithStorageTypes[],
});

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 | 🔵 Trivial

Type assertions are safe but consider type narrowing.

The assertions at lines 301-303 cast to DescriptorWithStorageTypes to satisfy the structural typing for buildSqlTypeMetadataRegistry. While safe (the source types satisfy the target structure), this could be cleaner with a type predicate or by having CreateSqlFamilyInstanceOptions directly extend DescriptorWithStorageTypes constraints.

♻️ Optional: Consider defining DescriptorWithStorageTypes as a constraint

If DescriptorWithStorageTypes is frequently used for type narrowing, consider making it a type constraint on the options interface directly, which would eliminate the need for assertions:

interface CreateSqlFamilyInstanceOptions<TTargetId extends string> {
  readonly target: TargetDescriptor<'sql', TTargetId> & SqlControlDescriptorWithContributions & DescriptorWithStorageTypes;
  // ...
}

Comment on lines +81 to +86
sql<Contract, CodecTypes>({ context: contextWithoutReturning })
.insert(tables.user, {
email: param('email'),
})
.returning(userColumns.id, userColumns.email);
}).toThrow('returning() requires returning capability');

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:

fd -t f "sql-dml-returning.test.ts" packages/2-sql/

Repository: prisma/prisma-next

Length of output: 124


🏁 Script executed:

cat -n packages/2-sql/4-lanes/sql-lane/test/sql-dml-returning.test.ts | head -200

Repository: prisma/prisma-next

Length of output: 7032


🏁 Script executed:

rg "sql<Contract,\s*CodecTypes" packages/2-sql/4-lanes/sql-lane/test/sql-dml-returning.test.ts -n

Repository: prisma/prisma-next

Length of output: 440


Remove CodecTypes from all sql<...> generic parameters in this file.
The coding guidelines require that sql() infer codec and operation types from the contract. Passing CodecTypes as a separate type parameter violates this pattern.

Required changes (5 occurrences)
- sql<Contract, CodecTypes>
+ sql<Contract>

Update lines: 81, 106, 127, 156, 181.

Comment on lines +137 to 157
function createTestSetup() {
const adapter = createStubAdapter();
const driver = createMockDriver();

const driverDescriptor: RuntimeDriverDescriptor<
'sql',
'postgres',
SqlRuntimeDriverInstance<'postgres'>
> = {
kind: 'driver',
id: 'test-driver',
version: '0.0.1',
familyId: 'sql' as const,
targetId: 'postgres' as const,
create() {
return Object.assign(
{ familyId: 'sql' as const, targetId: 'postgres' as const },
driver,
) as SqlRuntimeDriverInstance<'postgres'>;
},
};
const targetDescriptor = createTestTargetDescriptor();
const adapterDescriptor = createTestAdapterDescriptor(adapter);

const stack = createExecutionStack({
target: createTestTargetDescriptor(),
adapter: createTestAdapterDescriptor(adapter),
driver: driverDescriptor,
target: targetDescriptor,
adapter: adapterDescriptor,
extensionPacks: [],
});

const stackInstance = instantiateExecutionStack(stack);
return { stackInstance, driver };

const context = createExecutionContext({
contract: testContract,
stack: { target: targetDescriptor, adapter: adapterDescriptor, extensionPacks: [] },
});

return { stackInstance: stackInstance as never, context, driver };
}

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 | 🔵 Trivial

Clarify the as never cast or use a more descriptive escape.

Line 156 uses stackInstance as never which suppresses type checking. While test-only casts are acceptable, as never is unusually aggressive. Consider using a double cast with explanation:

return { 
  stackInstance: stackInstance as unknown as Parameters<typeof createRuntime>[0]['stackInstance'],
  context, 
  driver 
};

Or add a brief comment explaining why the type mismatch exists (e.g., test stub vs. full implementation).

createExecutionStack previously widened target/adapter/extension descriptors to the
base Runtime*Descriptor types, which caused SqlStaticContributions to be lost and
forced casts when passing stacks into sql-runtime createExecutionContext.

Update the function typing to keep the concrete descriptor types while still
returning an ExecutionStack shape.
…s and tests

With createExecutionStack now preserving SQL descriptor types, these call sites
can pass the stack directly to createExecutionContext without unsafe casts.
This keeps the demos and helpers type-safe while still using the shared stack
construction API.
…tack instantiation

Split the no-emit workflow into prisma-no-emit/context.ts (static stack + context + query roots)
and prisma-no-emit/runtime.ts (lazy runtime creation). This mirrors the emitted demo structure and
ensures instantiateExecutionStack is only called when getRuntime is invoked.

Update no-emit query imports and docs, and remove the old query-no-emit/runtime-no-emit modules.
Add afterEach restoration and remove redundant inline comments to keep the
no-runtime test focused on observable behavior.
CreateSqlFamilyInstanceOptions now includes DescriptorWithStorageTypes so the
metadata registry can be built without unsafe casts.
Drop CodecTypes from sql<> generics so codec and operation types are inferred
from the contract, matching the project guidelines.
Replace the as-never escape with a named ExecutionStackInstance type and a
single, focused cast to align with the test-only type mismatch.

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

Approved, with a few recommended changes

Comment on lines +120 to +133
}): Omit<
ExecutionStack<
FamilyIdOf<TTargetDescriptor>,
TargetIdOf<TTargetDescriptor>,
TAdapterInstance,
TDriverInstance,
TExtensionInstance
>,
'target' | 'adapter' | 'driver' | 'extensionPacks'
> & {
readonly target: TTargetDescriptor;
readonly adapter: TAdapterDescriptor;
readonly driver: TDriverDescriptor | undefined;
readonly extensionPacks: readonly TExtensionDescriptor[];

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.

Can we simplify createExecutionStack's return type? The Omit<ExecutionStack<...>, 'target' | 'adapter' | 'driver' | 'extensionPacks'> & { ... } removes all 4 properties and re-adds them, effectively making the Omit<...> side boil down to {}. This seems like a no-op that obscures readability.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Simplified a litte, also added SQL-specific factory functions so users themselves won't see this function.

return createRuntime({
stackInstance,
contract: fixtureContract,
stackInstance: stackInstance as never,

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.

Why is this cast as never?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Removed 👍🏻


// Create a test target descriptor
function createTestTargetDescriptor() {
function createTestTargetDescriptor(): SqlRuntimeTargetDescriptor<'postgres'> {

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.

Functions named createTestTargetDescriptor or createTestAdapterDescriptor are defined in many individual test files, with minor variations (if any). test/utils.ts already exports some shared versions of this. Can we DRY these definitions up?

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Done

Comment on lines +82 to +116
function parseArrayElements(input: string): string[] {
const result: string[] = [];
let i = 0;
while (i < input.length) {
if (input[i] === ',') {
i++;
continue;
}
if (input[i] === '"') {
i++;
let element = '';
while (i < input.length && input[i] !== '"') {
if (input[i] === '\\' && i + 1 < input.length) {
i++;
element += input[i];
} else {
element += input[i];
}
i++;
}
i++;
result.push(element);
} else {
const nextComma = input.indexOf(',', i);
if (nextComma === -1) {
result.push(input.slice(i).trim());
i = input.length;
} else {
result.push(input.slice(i, nextComma).trim());
i = nextComma;
}
}
}
return result;
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

This function silently consumes the rest of the input if an opening " quote has no matching close quote, which could produce incorrect enum values during migration planning. You should add unterminated-quote detection

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.

Also, we should have a migration planning test catching this

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

I'm gonna revert this change and skip the test. Ack?

Introduce a SQL-specific execution stack factory that preserves descriptor
contributions and exports a typed stack alias. Update sql-runtime tests and
examples in-package to use the new helper, and document the preferred usage.
Adopt the SQL-specific stack factory in the demo contexts and runtime helpers
so stacks keep SQL descriptor types without relying on the core generic factory.
Update guides and references to prefer createSqlExecutionStack in SQL examples
and extension setup, keeping consumer docs aligned with the new factory.
These files are local-only notes and should remain untracked.
Replace the omit-and-readd pattern with a straight ExecutionStack intersection
for improved readability while preserving the concrete descriptor types.
Replace local createTestTargetDescriptor and createTestAdapterDescriptor helpers
with the shared versions from test/utils to reduce duplication.
Bind the stack generics to explicit family/target parameters so the returned
ExecutionStack type aligns with the provided descriptors without relying on
conditional extraction helpers.
Drop explicit generic arguments so createExecutionStack infers the SQL descriptor
and instance types correctly under the new core stack signature.
Double the spin-up timeout for dev databases and apply it to all Kysely
integration tests to avoid false timeouts on slower environments.
@wmadden
wmadden merged commit 068b792 into main Feb 9, 2026
12 checks passed
@wmadden
wmadden deleted the tml-1827-runtime-dx-derive-static-sql-executioncontext-from branch February 9, 2026 15:47
jkomyno added a commit that referenced this pull request May 7, 2026
The project is fully delivered; per plan.md task #133, strip the
transient `projects/created-updated-at-authoring/` directory and
the lone in-test reference to spec.md.

The PR description, commit history, and the contract-psl tests
themselves are now the canonical record of what shipped.
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