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

TML-2594: depth-2+ ORM includes use lateral/correlated single-query paths - #555

Merged
aqrln merged 19 commits into
mainfrom
tml-2594-sql-orm-nested-includes-depth-2-fall-back-to-multi-query
May 21, 2026
Merged

aqrln merged 19 commits into
mainfrom
tml-2594-sql-orm-nested-includes-depth-2-fall-back-to-multi-query

Conversation

@tensordreams

@tensordreams tensordreams commented May 20, 2026 •

Copy link
Copy Markdown
Contributor

Linked issue

Refs TML-2594

At a glance

Before this PR, depth-2+ includes always emitted one IN-batched SQL statement per depth level, regardless of what the contract advertised. After, the same query collapses to a single statement on Postgres (lateral) and SQLite (correlated):

// User-land query, unchanged
await db.orm.User
  .include('posts', (posts) => posts.include('comments'))
  .all();
-- 1 SQL execution on capable targets (was 3)
SELECT users.id, users.name, ..., posts_lateral.posts
FROM users
LEFT JOIN LATERAL (
  SELECT coalesce(json_agg(json_build_object(
    'id', posts__rows.id, ..., 'comments', posts__rows.comments
  )), json_build_array()) AS posts
  FROM (
    SELECT posts.id, ..., comments_lateral.comments
    FROM posts
    LEFT JOIN LATERAL (
      SELECT coalesce(json_agg(json_build_object(...)), json_build_array()) AS comments
      FROM (SELECT comments.* FROM comments WHERE comments.post_id = posts.id) AS comments__rows
    ) AS comments_lateral ON TRUE
    WHERE posts.user_id = users.id
  ) AS posts__rows
) AS posts_lateral ON TRUE

The same shape works on SQLite via nested correlated subqueries. Targets advertising neither lateral nor jsonAgg retain today's IN-batched multi-query fallback.

Decision

  1. Drop the hasNestedIncludes arm of dispatchWithIncludeStrategy. Nested row includes no longer force a fallback to multi-query — strategy selection now honours the contract's declared capabilities at any depth.
  2. Recurse the single-query builders into IncludeExpr.nested.includes. Each depth contributes one nested artifact (LATERAL JOIN under lateral, correlated subquery under correlated) plus one entry in the parent's inner json_object. The outer aggregate picks them up automatically; no changes were needed to the outer-builder callers beyond threading the strategy through.
  3. Tighten the remaining gate to walk the include tree recursively. hasComplexIncludeDescriptors now catches nested count() / combine() at any depth, so the still-broken combine/scalar surface (sibling ticket TML-2595) stays on multi-query without leaking into the lateral builder's explicit throw.

How it fits together

  1. Gate (src/collection-dispatch.ts). dispatchWithIncludeStrategy no longer short-circuits on nested row includes. The only remaining early-return is hasComplexIncludeDescriptors, which now recurses. After this gate, selectIncludeStrategy(contract) decides between 'lateral', 'correlated', and 'multiQuery' just as it does for depth-1 today.
  2. SQL emission (src/query-plan-select.ts). A new buildNestedIncludeArtifacts(contract, parentTableRef, includes, strategy) walks the nested includes and returns { joins, projections } shaped to match the strategy. buildIncludeChildRowsSelect now takes a strategy parameter, calls the new helper against childTableRef, merges nested joins/projections into the inner SELECT, and exposes them on childProjection so the outer aggregate's JsonObjectExpr gains an entry per nested aggregate column without any caller change.
  3. Decoding (src/collection-dispatch.ts). dispatchWithSingleQueryIncludes factors child-row decode into a new recursive decodeIncludePayload helper that walks the include tree in sync with the parsed JSON tree: parse the column, mapStorageRowToModelFields per child, recurse into nested aggregate columns, then coerce to to-one or to-many via the existing coerceSingleQueryIncludeResult.
  4. Aliasing carries through. The existing self-relation alias (${relationName}__child when the child table equals the parent) propagates per level because the recursion passes childTableRef as the next parentTableRef. The depth-2 self-relation integration tests pin this — both invitedUsers → invitedUsers and invitedBy → invitedBy resolve in one SQL execution.
  5. Decoding mirrors emission. The recursive decoder consumes the same shape the recursive builders emit. After the outer JSON.parse, nested aggregate columns are already JS arrays/objects — parseIncludedRows recognises both the top-level string form and the inner array form, so the recursion threads through transparently.

Behavior changes & evidence

  • Depth-2+ row includes collapse to one SQL execution on lateral/jsonAgg-capable targets. Implementation: src/query-plan-select.ts, src/collection-dispatch.ts. Evidence: test/integration/nested-includes-strategy.test.ts — depth-{2,3} under {lateral,correlated} capabilities runs a single SQL execution; depth-2 self-relation single-execution under both strategies.
  • Empty-capability contracts still resolve correctly via IN-batched multi-query. Implementation unchanged on the multi-query path. Evidence: same file — depth-2 under empty capabilities runs 3 SQL executions (multi-query fallback), depth-3 under empty capabilities runs 4 SQL executions (multi-query fallback).
  • All three strategies return byte-identical result trees over the same data. Evidence: test/integration/nested-includes-strategy.test.ts — depth-2 {lateral,correlated,multi-query} path produces the canonical result tree.
  • Refinements (orderBy, take, where, select) on the nested level apply inside the inner SELECT. Implementation: buildIncludeChildRowsSelect was already wiring child state into the inner SELECT; the recursion threads the same wiring per depth. Evidence: test/integration/nested-includes-refinements.test.ts — all four refinement cases plus three edge cases (empty parent, missing grandchildren, unsatisfied FK).
  • combine() and count() still route to multi-query, including when nested. Implementation: hasComplexIncludeDescriptors recursion in src/collection-dispatch.ts. Evidence: test/integration/nested-includes-strategy.test.ts — top-level combine() stays on multi-query under lateral capabilities, nested scalar at depth 2 stays on multi-query under lateral capabilities (recursive gate). These tests assert .toBeGreaterThan(1); TML-2595 will flip them to .toBe(1).

Reviewer notes

  • Largest commit is the test corpus (1.5k LOC across four files). The implementation commit is 4 files / +483/-21 — the query-plan-select.ts recursion is the most concentrated change, ~70 LOC; everything else is local. Spot-check buildNestedIncludeArtifacts and the new strategy parameter threading in buildIncludeChildRowsSelect.
  • Three integration files instead of one — deliberate. prisma/dev's PGlite worker pool becomes unreliable past ~13 tests per file (the same threshold every other test/integration/ file in the package respects). The split keeps each file deterministic in isolation; a shared nested-includes-helpers.ts carries the collectionWithCapabilities factory + capability constants. The threshold is documented at the top of the helpers file. Pre-existing test files (codec-async.test.ts, nested-mutations.test.ts) intermittently flake on the same infrastructure under parallel load — out of scope for this PR.
  • The hasComplexIncludeDescriptors recursion is forward-compat with TML-2595. Without it, dropping hasNestedIncludes would route depth-2 trees containing a nested count() straight into the lateral builder's throw new Error('single-query include strategy does not support scalar include selectors or combine()'). The two coexistence tests pin this behaviour.
  • Polymorphism unchanged. compileSelectWithIncludeStrategy calls buildMtiJoins only for the parent; nested includes into polymorphic relations remain as-is (same constraint that depth-1 already has). No regressions because no test was relying on nested-polymorphic.
  • MTI / hidden join columns. augmentSelectionForJoinColumns is still only applied at the parent level. At the child level the inner WHERE references columns via ColumnRef directly, which don't need to be in the projection. Existing select() restriction at depth 2 covered by the refinements test.

Verification

  • pnpm typecheck (sql-orm-client) — clean.
  • pnpm lint (sql-orm-client) — clean.
  • pnpm lint:deps (repo root) — clean: 955 modules / 1974 dependencies, no violations.
  • pnpm test (sql-orm-client full package) — 646 tests pass, 3 skipped (pre-existing deferred async-codec stubs).
  • Each of the three new integration files in isolation: 11 / 7 / 13 tests, all green.
  • Full integration suite re-run 3× — green run 1; sporadic 1–2 failures in runs 2 and 3, distributed across both new files and pre-existing files (codec-async.test.ts, nested-mutations.test.ts). Confirmed pre-existing prisma/dev infrastructure flakiness under parallel load, not a regression from this PR.

Follow-ups

  • TML-2595 — sibling bug. combine() / scalar count() still route to multi-query through the recursive hasComplexIncludeDescriptors gate. Two coexistence tests in nested-includes-strategy.test.ts carry .toBeGreaterThan(1) assertions that flip to .toBe(1) when TML-2595 lands.
  • Nested includes into polymorphic relations: no MTI joins inside the child SELECT today. Existing limitation, not introduced here, but worth a follow-up ticket once a real consumer surfaces.

Alternatives considered

  • Land the combine/scalar lowering in the same PR. The two are gated by the same arm and share infrastructure, and the ticket suggests "land in series". I kept them separate because the combine surface needs a different shape (branch-aware projection + scalar reducers, plus the multi-query stitchCombinedInclude already does non-trivial work) and conflating them would make the diff harder to review. The recursive hasComplexIncludeDescriptors is the seam.
  • Make buildIncludeChildRowsSelect strategy-agnostic and lift the lateral-vs-correlated choice to the callers per level. Less recursion in the helper, but every caller would need to know how to nest into the next level — duplicating the strategy switch. Threading strategy through the recursion keeps the policy in one place.
  • Pre-flatten the include tree before dispatching. Tempting because the multi-query stitcher already walks the tree level-by-level, but it would force the lateral / correlated paths to give up structural locality (one inner SELECT per parent) and rebuild correlations from scratch. The recursive emission preserves the natural locality of LATERAL JOIN scoping.
  • Use vitest's concurrent for the integration corpus to keep one file. Would have made the prisma/dev contention worse, not better. The file-count split is the cheaper fix and matches the package's existing per-file convention (every other test/integration/ file is ≤ 13 tests).

Skill update

n/a — internal only. No user-visible CLI / API / config surface changes; the fix is observable purely as fewer SQL round-trips for the same include() calls.

Checklist

  • All commits are signed off (git commit -s) per the DCO. The DCO status check will block merge if any commit is missing a Signed-off-by: trailer.
  • I read CONTRIBUTING.md and the change is scoped to one logical concern.
  • Tests are updated (or n/a if the change is doc-only / refactor with no behavioural delta).
  • The PR title is in TML-NNNN: <sentence-case title> form (Linear ticket prefix + concise title naming the concrete deliverable). See .claude/skills/create-pr/SKILL.md for the full convention.
  • The Skill update section above is filled in (or stated n/a — internal only).

Summary by CodeRabbit

  • New Features

    • Depth‑2+ nested include support with single‑query strategies (lateral and correlated) that can collapse nested projections into one SQL execution when the target supports it.
  • Bug Fixes

    • Recursive validation now routes scalar/combine selectors and non‑leaf distinct() to multi‑query, avoiding incorrect single‑query decoding and preserving correct results.
  • Tests

    • Expanded unit and integration suites validating nested shapes, strategy routing, execution counts, refinements, and edge cases.
  • Documentation

    • Upgrade notes describing 0.11 behavior and new safety gates for nested includes.

Review Change Stack

@tensordreams
tensordreams requested a review from a team as a code owner May 20, 2026 20:42
@coderabbitai

coderabbitai Bot commented May 20, 2026 •

Copy link
Copy Markdown
Contributor

Note

Reviews paused

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

Use the following commands to manage reviews:

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

Use the checkboxes below for quick actions:

  • ▶️ Resume reviews
  • 🔍 Trigger review
📝 Walkthrough

Walkthrough

This PR implements nested includes at depth ≥ 2 by refactoring include dispatch to detect complex descriptors anywhere in the include tree, adding recursive single-query decoding via decodeIncludePayload, and extending SQL plan generation to build nested aggregates for lateral and correlated strategies, with capability-driven unit and integration tests.

Changes

Nested includes at depth ≥ 2

Layer / File(s) Summary
Include dispatch refactoring and single-query decoding
src/collection-dispatch.ts
Simplify multi-query gate to detect scalar/combine() descriptors at any depth and non-leaf distinct(); add recursive decodeIncludePayload helper to parse single-query JSON include payloads and recursively decode nested includes.
SQL query plan generation for nested includes
src/query-plan-select.ts
Add buildNestedIncludeArtifacts to recursively construct nested include artifacts (lateral joins + projections or correlated subquery projections). Update buildIncludeChildRowsSelect to accept a strategy, build a scalar childProjection, recurse into nested includes, merge nested projections into the child SELECT projection, and attach nested joins for lateral/correlated strategies; enforce planner invariants across the entire include tree.
Test infrastructure for capability-driven dispatch
test/integration/nested-includes-helpers.ts
Introduce collectionWithCapabilities helper and capability constants (LATERAL_CAPABILITIES, CORRELATED_CAPABILITIES, MULTI_QUERY_CAPABILITIES) enabling tests to exercise different dispatch strategies against the same runtime by overriding contract capabilities.
Unit tests for nested include dispatch
test/collection-dispatch.test.ts
Add tests validating depth-2 nested includes under emitted-shape capabilities (users → posts → comments and users → posts → author) resolve with a single SQL execution and correct nested shapes, plus a regression multi-query fallback test when capabilities are absent.
Basic integration tests for depth-2 includes
test/integration/include.test.ts
Add integration tests asserting depth-2 includes resolve in a single SQL execution under lateral+jsonAgg and correlated-only modes, and expect a 3-execution multi-query fallback when neither capability is declared.
Integration tests for nested include refinements
test/integration/nested-includes-refinements.test.ts
Add suite validating depth-2 refinements (orderBy, take, where, select) are applied inside nested aggregates, and edge cases (empty arrays, missing grandchildren, orphan FK) produce correct shapes without errors.
Cross-strategy validation and coexistence tests
test/integration/nested-includes-strategy.test.ts
Add comprehensive validation asserting depth-2 and depth-3 nested includes produce canonical result trees across lateral/correlated/multi-query strategies, pinning SQL execution counts per strategy and covering self-relations, scalar/combine() coexistence gating, and non-leaf distinct() regression cases.
Comprehensive nested include traversal tests
test/integration/nested-includes.test.ts
Add suite covering depth-2 and depth-3+ traversal patterns (hasMany→hasMany, hasMany→belongsTo, hasOne→belongsTo, self-relations, siblings) resolving to correctly nested JSON outputs with proper empty-array and null handling.

🎯 4 (Complex) | ⏱️ ~60 minutes


A rabbit hops through includes so deep,
Building SQL queries we can keep—
Lateral joins and correlations dance,
While nested trees take their rightful stance!
Depth two, three, and more unfold with grace,
Single queries claim the testing place. 🐰

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 33.33% which is insufficient. The required threshold is 80.00%. Write docstrings for the functions missing them to satisfy the coverage threshold.
✅ Passed checks (4 passed)
Check name Status Explanation
Description Check ✅ Passed Check skipped - CodeRabbit’s high-level summary is enabled.
Title check ✅ Passed The title accurately describes the main change: enabling depth-2+ nested ORM includes to use lateral/correlated single-query paths instead of multi-query fallback, which is the primary behavioral change across all modified files.
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.

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

✨ Finishing Touches
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch tml-2594-sql-orm-nested-includes-depth-2-fall-back-to-multi-query

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

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

@pkg-pr-new

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

Copy link
Copy Markdown

Open in StackBlitz

@prisma-next/extension-author-tools

npm i https://pkg.pr.new/@prisma-next/extension-author-tools@555

@prisma-next/mongo-runtime

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

@prisma-next/family-mongo

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

@prisma-next/sql-runtime

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

@prisma-next/family-sql

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

@prisma-next/extension-arktype-json

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

@prisma-next/extension-cipherstash

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

@prisma-next/middleware-cache

npm i https://pkg.pr.new/@prisma-next/middleware-cache@555

@prisma-next/mongo

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

@prisma-next/extension-paradedb

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

@prisma-next/extension-pgvector

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

@prisma-next/extension-postgis

npm i https://pkg.pr.new/@prisma-next/extension-postgis@555

@prisma-next/postgres

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

@prisma-next/sql-orm-client

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

@prisma-next/sqlite

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

@prisma-next/target-mongo

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

@prisma-next/adapter-mongo

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

@prisma-next/driver-mongo

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

@prisma-next/contract

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

@prisma-next/utils

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

@prisma-next/config

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

@prisma-next/errors

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

@prisma-next/framework-components

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

@prisma-next/operations

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

@prisma-next/ts-render

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

@prisma-next/contract-authoring

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

@prisma-next/ids

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

@prisma-next/psl-parser

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

@prisma-next/psl-printer

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

@prisma-next/cli

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

@prisma-next/cli-telemetry

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

@prisma-next/emitter

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

@prisma-next/migration-tools

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

prisma-next

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

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

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

@prisma-next/mongo-codec

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

@prisma-next/mongo-contract

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

@prisma-next/mongo-value

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

@prisma-next/mongo-contract-psl

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

@prisma-next/mongo-contract-ts

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

@prisma-next/mongo-emitter

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

@prisma-next/mongo-schema-ir

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

@prisma-next/mongo-query-ast

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

@prisma-next/mongo-orm

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

@prisma-next/mongo-query-builder

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

@prisma-next/mongo-lowering

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

@prisma-next/mongo-wire

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

@prisma-next/sql-contract

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

@prisma-next/sql-errors

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

@prisma-next/sql-operations

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

@prisma-next/sql-schema-ir

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

@prisma-next/sql-contract-psl

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

@prisma-next/sql-contract-ts

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

@prisma-next/sql-contract-emitter

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

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

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

@prisma-next/sql-relational-core

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

@prisma-next/sql-builder

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

@prisma-next/target-postgres

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

@prisma-next/target-sqlite

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

@prisma-next/adapter-postgres

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

@prisma-next/adapter-sqlite

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

@prisma-next/driver-postgres

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

@prisma-next/driver-sqlite

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

commit: e135aa2

@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

🧹 Nitpick comments (2)
packages/3-extensions/sql-orm-client/test/collection-dispatch.test.ts (1)

76-655: ⚖️ Poor tradeoff

Consider splitting this test file to stay under the 500-line guideline.

The file is now 655 lines, which exceeds the 500-line soft guideline by 155 lines. While this isn't a blocker, consider splitting the dispatch tests into multiple files organized by feature area (e.g., collection-dispatch.single-query.test.ts, collection-dispatch.multi-query.test.ts, collection-dispatch.nested.test.ts) to improve navigability and align with the repo's test organization conventions.

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

In `@packages/3-extensions/sql-orm-client/test/collection-dispatch.test.ts` around
lines 76 - 655, The test file collection-dispatch.test.ts is over the 500-line
guideline; split the large describe('collection-dispatch') suite into smaller,
focused test files (for example: collection-dispatch.single-query.test.ts,
collection-dispatch.multi-query.test.ts, collection-dispatch.nested.test.ts) by
grouping related tests that exercise dispatchCollectionRows and stitchIncludes
(e.g., single-query path tests that reference
withSingleQueryCapabilities/getTestContract, multi-query path tests that
reference withCapabilities/createCollectionFor, and nested include/regression
guards that reference withEmittedSqlCapabilities). Move the corresponding it
blocks (including tests that assert runtime.executions and include
parsing/mapping behavior) into the new files and keep helper imports
(createCollectionFor, dispatchCollectionRows, stitchIncludes, addConnection,
createMockRuntime, etc.) at the top of each new file so each new test file
remains self-contained and under 500 lines.
packages/3-extensions/sql-orm-client/test/integration/nested-includes-helpers.ts (1)

26-35: 💤 Low value

Consider double casts for test fixture modifications.

The single casts on lines 32-33 could be strengthened to double casts (as unknown as TestContract and as unknown as ExecutionContext<TestContract>) to align with the test code guideline for type assertions in test utilities. While these aren't traditional mocks or dynamic proxies, using double casts would make the type override more explicit and consistent with the repo's test patterns.

♻️ Optional refactor for consistency
-  const contract = { ...base, capabilities } as TestContract;
-  const context = { ...getTestContext(), contract } as ExecutionContext<TestContract>;
+  const contract = { ...base, capabilities } as unknown as TestContract;
+  const context = { ...getTestContext(), contract } as unknown as ExecutionContext<TestContract>;
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In
`@packages/3-extensions/sql-orm-client/test/integration/nested-includes-helpers.ts`
around lines 26 - 35, The test helper uses single TypeScript casts for modifying
test fixtures (contract and context); update the casts to the repo's preferred
double-cast pattern by changing the assignments that create contract and context
to use "as unknown as TestContract" for contract (created from getTestContract()
spread plus capabilities) and "as unknown as ExecutionContext<TestContract>" for
context (created from getTestContext() spread plus contract) so the Collection
instantiation still receives the same runtime/context but with the stronger
double-cast type assertions on contract and context.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In
`@packages/3-extensions/sql-orm-client/test/integration/nested-includes-strategy.test.ts`:
- Line 365: The test suite name in the describe call currently includes a
transient task ID ("TML-2595"); rename the describe label string in the file's
describe('coexistence with TML-2595 (scalar/combine still on multi-query)', ...)
to a stable, descriptive name without the task ID (for example "coexistence with
scalar/combine on multi-query" or "coexistence: scalar/combine on multi-query")
so the test name no longer references transient project artifacts; update only
the string argument to the describe invocation in
nested-includes-strategy.test.ts (leave the describe block and its tests
unchanged).

---

Nitpick comments:
In `@packages/3-extensions/sql-orm-client/test/collection-dispatch.test.ts`:
- Around line 76-655: The test file collection-dispatch.test.ts is over the
500-line guideline; split the large describe('collection-dispatch') suite into
smaller, focused test files (for example:
collection-dispatch.single-query.test.ts,
collection-dispatch.multi-query.test.ts, collection-dispatch.nested.test.ts) by
grouping related tests that exercise dispatchCollectionRows and stitchIncludes
(e.g., single-query path tests that reference
withSingleQueryCapabilities/getTestContract, multi-query path tests that
reference withCapabilities/createCollectionFor, and nested include/regression
guards that reference withEmittedSqlCapabilities). Move the corresponding it
blocks (including tests that assert runtime.executions and include
parsing/mapping behavior) into the new files and keep helper imports
(createCollectionFor, dispatchCollectionRows, stitchIncludes, addConnection,
createMockRuntime, etc.) at the top of each new file so each new test file
remains self-contained and under 500 lines.

In
`@packages/3-extensions/sql-orm-client/test/integration/nested-includes-helpers.ts`:
- Around line 26-35: The test helper uses single TypeScript casts for modifying
test fixtures (contract and context); update the casts to the repo's preferred
double-cast pattern by changing the assignments that create contract and context
to use "as unknown as TestContract" for contract (created from getTestContract()
spread plus capabilities) and "as unknown as ExecutionContext<TestContract>" for
context (created from getTestContext() spread plus contract) so the Collection
instantiation still receives the same runtime/context but with the stronger
double-cast type assertions on contract and context.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

Run ID: 156bca44-9cb6-480e-a5d4-d420627c1216

📥 Commits

Reviewing files that changed from the base of the PR and between bf663db and 9f07033.

📒 Files selected for processing (8)
  • packages/3-extensions/sql-orm-client/src/collection-dispatch.ts
  • packages/3-extensions/sql-orm-client/src/query-plan-select.ts
  • packages/3-extensions/sql-orm-client/test/collection-dispatch.test.ts
  • packages/3-extensions/sql-orm-client/test/integration/include.test.ts
  • packages/3-extensions/sql-orm-client/test/integration/nested-includes-helpers.ts
  • packages/3-extensions/sql-orm-client/test/integration/nested-includes-refinements.test.ts
  • packages/3-extensions/sql-orm-client/test/integration/nested-includes-strategy.test.ts
  • packages/3-extensions/sql-orm-client/test/integration/nested-includes.test.ts

aqrln pushed a commit that referenced this pull request May 21, 2026
…e rejection (PR #555 review)

Apply both findings from the code review of PR #555 / TML-2594.

F01: route non-leaf includes carrying `distinct()` to multi-query. Under the
single-query strategies the child SELECT carries nested JSON aggregate
columns, and `SELECT DISTINCT` over those fails on Postgres (`json` has no
equality operator). The multi-query stitcher applies distinct to scalar-only
rows before grandchildren are joined, which is the semantically correct
behavior we preserve. `distinctOn` is intentionally excluded -- Postgres
only compares the `ON (...)` expressions for equality.

F02: make `compileSelectWithIncludeStrategy` reject scalar/combine
descriptors at every depth, not just the top level. The dispatch path
already gates these via `hasComplexIncludeDescriptors` recursively, but
the planner is an exported helper called directly by tests and rich-plan
callers, so it must enforce the same invariant or a nested `count()`
inside a row include would silently produce a malformed plan instead of
failing fast at the boundary.

Tests:
- query-plan-select.test.ts: add nested scalar + nested combine rejection
  cases mirroring the existing top-level rejection test.
- nested-includes-strategy.test.ts: add the reviewers exact regression
  query under LATERAL_CAPABILITIES, the same shape under
  CORRELATED_CAPABILITIES, and a depth-2 recursive case.
aqrln pushed a commit that referenced this pull request May 21, 2026
…tural ScalarOrCombineIncludeDescriptors

Apply the architect-review typology note from PR #555: `Complex` is a
fuzzy qualifier, and the actual distinction the gate makes is structural
(scalar reducer / combine() descriptor, regardless of where it sits in
the include tree). Rename both parallel predicates -- the dispatch-side
`hasComplexIncludeDescriptors` and the planner-side
`hasScalarOrCombineIncludeAnywhere` -- to a single shared name
`hasScalarOrCombineIncludeDescriptors`. Same name on both layers makes
the parallel enforcement explicit; the boundary between dispatch policy
and planner validity is preserved by their separate locations.

Update inline comments in both source files and in the strategy /
query-plan-select tests that referenced the old name.

No behavior change.

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

Caution

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

⚠️ Outside diff range comments (1)
packages/3-extensions/sql-orm-client/src/query-plan-select.ts (1)

547-578: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Mirror the non-leaf distinct() gate in the exported planner.

dispatchWithIncludeStrategy() now routes non-leaf distinct() includes to multi-query, but compileSelectWithIncludeStrategy() still accepts the same shape and can build a single-query plan directly. Because this helper is exported, direct callers can still hit the invalid SELECT DISTINCT ..., <nested json aggregate> path that this PR is trying to avoid.

Suggested fix
+function hasNonLeafIncludeWithDistinct(includes: readonly IncludeExpr[]): boolean {
+  return includes.some(
+    (include) =>
+      ((include.nested.distinct?.length ?? 0) > 0 &&
+        include.nested.includes.length > 0) ||
+      hasNonLeafIncludeWithDistinct(include.nested.includes),
+  );
+}
+
 export function compileSelectWithIncludeStrategy(
   contract: Contract<SqlStorage>,
   tableName: string,
   state: CollectionState,
   strategy: 'lateral' | 'correlated',
   modelName?: string,
 ): SqlQueryPlan<Record<string, unknown>> {
   if (hasScalarOrCombineIncludeAnywhere(state.includes)) {
     throw new Error(
       'single-query include strategy does not support scalar include selectors or combine()',
     );
   }
+  if (hasNonLeafIncludeWithDistinct(state.includes)) {
+    throw new Error(
+      'single-query include strategy does not support non-leaf distinct() includes',
+    );
+  }
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/3-extensions/sql-orm-client/src/query-plan-select.ts` around lines
547 - 578, The exported planner compileSelectWithIncludeStrategy can still build
invalid single-query plans when a non-leaf distinct() appears in nested
includes; mirror the dispatchWithIncludeStrategy behavior by rejecting any
include that sets distinct on a non-leaf (i.e., distinct === true and
include.nested.includes is non-empty). Add a check (either a new helper like
hasNonLeafDistinctIncludeAnywhere or extend hasScalarOrCombineIncludeAnywhere)
and throw a clear error inside compileSelectWithIncludeStrategy (similar to the
existing scalar/combine check) so callers cannot produce a SELECT DISTINCT with
nested JSON aggregates.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@packages/3-extensions/sql-orm-client/src/query-plan-select.ts`:
- Around line 547-578: The exported planner compileSelectWithIncludeStrategy can
still build invalid single-query plans when a non-leaf distinct() appears in
nested includes; mirror the dispatchWithIncludeStrategy behavior by rejecting
any include that sets distinct on a non-leaf (i.e., distinct === true and
include.nested.includes is non-empty). Add a check (either a new helper like
hasNonLeafDistinctIncludeAnywhere or extend hasScalarOrCombineIncludeAnywhere)
and throw a clear error inside compileSelectWithIncludeStrategy (similar to the
existing scalar/combine check) so callers cannot produce a SELECT DISTINCT with
nested JSON aggregates.

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

Run ID: e88b7d2d-a6d8-48a0-a1d2-b75a6c51391e

📥 Commits

Reviewing files that changed from the base of the PR and between 9f07033 and a3e47f5.

📒 Files selected for processing (4)
  • packages/3-extensions/sql-orm-client/src/collection-dispatch.ts
  • packages/3-extensions/sql-orm-client/src/query-plan-select.ts
  • packages/3-extensions/sql-orm-client/test/integration/nested-includes-strategy.test.ts
  • packages/3-extensions/sql-orm-client/test/query-plan-select.test.ts

aqrln pushed a commit that referenced this pull request May 21, 2026
…e rejection (PR #555 review)

Apply both findings from the code review of PR #555 / TML-2594.

F01: route non-leaf includes carrying `distinct()` to multi-query. Under the
single-query strategies the child SELECT carries nested JSON aggregate
columns, and `SELECT DISTINCT` over those fails on Postgres (`json` has no
equality operator). The multi-query stitcher applies distinct to scalar-only
rows before grandchildren are joined, which is the semantically correct
behavior we preserve. `distinctOn` is intentionally excluded -- Postgres
only compares the `ON (...)` expressions for equality.

F02: make `compileSelectWithIncludeStrategy` reject scalar/combine
descriptors at every depth, not just the top level. The dispatch path
already gates these via `hasComplexIncludeDescriptors` recursively, but
the planner is an exported helper called directly by tests and rich-plan
callers, so it must enforce the same invariant or a nested `count()`
inside a row include would silently produce a malformed plan instead of
failing fast at the boundary.

Tests:
- query-plan-select.test.ts: add nested scalar + nested combine rejection
  cases mirroring the existing top-level rejection test.
- nested-includes-strategy.test.ts: add the reviewers exact regression
  query under LATERAL_CAPABILITIES, the same shape under
  CORRELATED_CAPABILITIES, and a depth-2 recursive case.

Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
aqrln pushed a commit that referenced this pull request May 21, 2026
…tural ScalarOrCombineIncludeDescriptors

Apply the architect-review typology note from PR #555: `Complex` is a
fuzzy qualifier, and the actual distinction the gate makes is structural
(scalar reducer / combine() descriptor, regardless of where it sits in
the include tree). Rename both parallel predicates -- the dispatch-side
`hasComplexIncludeDescriptors` and the planner-side
`hasScalarOrCombineIncludeAnywhere` -- to a single shared name
`hasScalarOrCombineIncludeDescriptors`. Same name on both layers makes
the parallel enforcement explicit; the boundary between dispatch policy
and planner validity is preserved by their separate locations.

Update inline comments in both source files and in the strategy /
query-plan-select tests that referenced the old name.

No behavior change.

Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
@aqrln
aqrln force-pushed the tml-2594-sql-orm-nested-includes-depth-2-fall-back-to-multi-query branch from 93d086c to 5433ef7 Compare May 21, 2026 11:33
@tensordreams

Copy link
Copy Markdown
Contributor Author

Triage of CodeRabbit nitpick on packages/3-extensions/sql-orm-client/test/collection-dispatch.test.ts (lines 76-655, “split the file under the 500-line guideline”): out of scope for this PR.

This is a real but orthogonal concern. CodeRabbit itself tagged it ⚖️ Poor tradeoff. The file grew here only by the nested-includes regression cases TML-2594 needs; the bulk of the 654 lines predates this PR. Re-shaping collection-dispatch.test.ts into feature-area files (*.single-query.test.ts, *.multi-query.test.ts, *.nested.test.ts) is its own piece of work — doing it inside a behaviour-change PR would balloon the diff and entangle test-organisation churn with the depth-≥2 single-query collapse.

If/when we want to schedule that split, it should land as a separate prep PR before further suite growth.

@tensordreams

Copy link
Copy Markdown
Contributor Author

Triage of CodeRabbit nitpick on packages/3-extensions/sql-orm-client/test/integration/nested-includes-helpers.ts (lines 26-35, “strengthen the single casts to double casts as unknown as TestContract / as unknown as ExecutionContext<TestContract>”): won't address.

This conflicts with the typesafety rule in our AGENTS.md:

Minimize type casts: prefer explicit types that make casts unnecessary. If unavoidable, narrow the cast as far as possible — never cast a whole object/class when casting one property would suffice. as unknown as SomeOtherType is a last resort and must be accompanied by a comment explaining why.

The current ... as TestContract / ... as ExecutionContext<TestContract> is the weaker, structurally-validated override the rule prefers. as unknown as X is reserved for the case where TypeScript actively rejects the single cast — which it does not here. Strengthening to a double cast would silence more checks than necessary, against the rule.

CodeRabbit itself self-tagged this as 💤 Low value, which lines up with the call.

@tensordreams

Copy link
Copy Markdown
Contributor Author

Triage of CodeRabbit outside-diff comment on packages/3-extensions/sql-orm-client/src/query-plan-select.ts (lines 547-578, “mirror the non-leaf distinct() gate in the exported planner”): will address in this PR.

Good catch. dispatchWithIncludeStrategy (private) routes non-leaf distinct() includes to multi-query, but compileSelectWithIncludeStrategy (exported, called directly by tests and rich-plan consumers) only gates scalar/combine descriptors today — so a direct caller can still build an invalid SELECT DISTINCT ..., <nested json aggregate> plan that Postgres will reject for lack of a json equality operator.

Plan to address:

  • Add a recursive hasNonLeafIncludeWithDistinct check inside compileSelectWithIncludeStrategy that throws the same kind of clear, fail-fast error we already throw for scalar/combine.
  • Reuse the existing hasNonLeafIncludeWithDistinct helper that lives in collection-dispatch.ts rather than duplicating — likely by lifting it to a shared module both files import.
  • Add a regression test in test/query-plan-select.test.ts covering the throw.

@tensordreams

Copy link
Copy Markdown
Contributor Author

On it — lifting hasNonLeafIncludeWithDistinct into a shared module and mirroring the gate in compileSelectWithIncludeStrategy, with a regression test in test/query-plan-select.test.ts.

@tensordreams

Copy link
Copy Markdown
Contributor Author

Done in 3ba642d.

  • Lifted hasNonLeafIncludeWithDistinct out of collection-dispatch.ts into a new shared src/include-tree-predicates.ts module; both dispatchWithIncludeStrategy and compileSelectWithIncludeStrategy import from it (no duplication).
  • compileSelectWithIncludeStrategy now throws single-query include strategy does not support distinct() on a non-leaf include recursively at every depth — same shape as the existing scalar/combine gate sitting one branch above it.
  • Regression test in test/query-plan-select.test.ts covers the throw at the top level and at depth 2 (invitedUsers → posts.distinct('title').include('comments')).

pnpm --filter @prisma-next/sql-orm-client typecheck and the filtered package test run for test/query-plan-select.test.ts (18/18) and test/collection-dispatch.test.ts (13/13, 3 skipped) all pass; biome lint is clean. The dispatch-path routing for these shapes (to multi-query) is unchanged.

@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

🧹 Nitpick comments (1)
packages/3-extensions/sql-orm-client/src/collection-dispatch.ts (1)

481-494: ⚡ Quick win

Extract the recursive scalar/combine gate into include-tree-predicates.ts.

This predicate now exists here and in query-plan-select.ts. The non-leaf distinct() bug fixed in this PR is the same kind of planner/dispatcher drift this duplication can reintroduce, so I'd centralize it next to hasNonLeafIncludeWithDistinct and have both callers import the shared helper.

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

In `@packages/3-extensions/sql-orm-client/src/collection-dispatch.ts` around lines
481 - 494, The predicate hasScalarOrCombineIncludeDescriptors is duplicated and
should be extracted into a shared module (create include-tree-predicates.ts) so
both collection-dispatch.ts and query-plan-select.ts import the same
implementation; move the recursive function into that new file (exporting it by
its existing name), update callers in collection-dispatch
(hasScalarOrCombineIncludeDescriptors) and query-plan-select to import from
include-tree-predicates, and ensure the new module sits alongside
hasNonLeafIncludeWithDistinct so both predicates are co-located and maintained
in one place.
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Inline comments:
In `@packages/3-extensions/sql-orm-client/test/collection-dispatch.test.ts`:
- Line 251: The test uses an extension-dependent field "embedding" in its
fixture/assertion object (the array entry [{ id: 10, title: 'Post A', user_id:
1, views: 1, embedding: null }]) even though this test is verifying
include-strategy fallback and not extension behavior; remove the embedding
property from both the test fixture and the matching expectation (the objects at
the two occurrences in collection-dispatch.test.ts) so the test only asserts id,
title, user_id, and views.
- Line 122: Three test titles include a ticket ID (TML-2594); update the
`it(...)` description strings to remove the ticket ID and keep them
behavior-focused. Locate the `it` declarations for the tests named like
"dispatchCollectionRows() depth-2 nested include with emitted-shape capabilities
fires a single SQL execution (TML-2594)" (and the two similar occurrences later
in the file) and edit the string arguments to remove "(TML-2594)" while
preserving the descriptive behavior text.

In `@packages/3-extensions/sql-orm-client/test/integration/include.test.ts`:
- Line 757: Remove the transient task ID from the test names that include
"(TML-2594)"; locate the two it(...) labels whose descriptions contain
"TML-2594" (e.g., "depth-2 include uses correlated subqueries when only jsonAgg
is enabled (TML-2594)") and edit the strings to omit the "(TML-2594)" suffix so
the descriptions read without the task ID. Ensure both occurrences are updated
(the one shown and the other at the later occurrence) and run tests to confirm
no other changes are needed.

---

Nitpick comments:
In `@packages/3-extensions/sql-orm-client/src/collection-dispatch.ts`:
- Around line 481-494: The predicate hasScalarOrCombineIncludeDescriptors is
duplicated and should be extracted into a shared module (create
include-tree-predicates.ts) so both collection-dispatch.ts and
query-plan-select.ts import the same implementation; move the recursive function
into that new file (exporting it by its existing name), update callers in
collection-dispatch (hasScalarOrCombineIncludeDescriptors) and query-plan-select
to import from include-tree-predicates, and ensure the new module sits alongside
hasNonLeafIncludeWithDistinct so both predicates are co-located and maintained
in one place.
🪄 Autofix (Beta)

Fix all unresolved CodeRabbit comments on this PR:

  • Push a commit to this branch (recommended)
  • Create a new PR with the fixes

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

Run ID: e271c025-5856-45f6-afea-a70773608474

📥 Commits

Reviewing files that changed from the base of the PR and between 93d086c and 3ba642d.

📒 Files selected for processing (10)
  • packages/3-extensions/sql-orm-client/src/collection-dispatch.ts
  • packages/3-extensions/sql-orm-client/src/include-tree-predicates.ts
  • packages/3-extensions/sql-orm-client/src/query-plan-select.ts
  • packages/3-extensions/sql-orm-client/test/collection-dispatch.test.ts
  • packages/3-extensions/sql-orm-client/test/integration/include.test.ts
  • packages/3-extensions/sql-orm-client/test/integration/nested-includes-helpers.ts
  • packages/3-extensions/sql-orm-client/test/integration/nested-includes-refinements.test.ts
  • packages/3-extensions/sql-orm-client/test/integration/nested-includes-strategy.test.ts
  • packages/3-extensions/sql-orm-client/test/integration/nested-includes.test.ts
  • packages/3-extensions/sql-orm-client/test/query-plan-select.test.ts

@tensordreams

Copy link
Copy Markdown
Contributor Author

Triage of CodeRabbit nitpick on packages/3-extensions/sql-orm-client/src/collection-dispatch.ts (lines 481-494, “extract the recursive scalar/combine gate into include-tree-predicates.ts”): will address in this PR.

Good call, and a natural follow-up to the A03a fix — that one lifted hasNonLeafIncludeWithDistinct into the new src/include-tree-predicates.ts precisely to prevent planner/dispatcher drift on the gate set, but it left hasScalarOrCombineIncludeDescriptors duplicated between collection-dispatch.ts:481 and query-plan-select.ts:559. The two copies are structurally identical and serve the same invariant, so the same argument for centralizing applies.

Plan to address:

  • Move hasScalarOrCombineIncludeDescriptors into src/include-tree-predicates.ts alongside hasNonLeafIncludeWithDistinct.
  • Import from both call sites; delete the local copies.
  • No behavior change expected; the existing rejection tests in test/query-plan-select.test.ts and test/collection-dispatch.test.ts cover the gate.

@tensordreams

Copy link
Copy Markdown
Contributor Author

Done — lifted hasScalarOrCombineIncludeDescriptors into the shared src/include-tree-predicates.ts next to hasNonLeafIncludeWithDistinct, and imported it from both collection-dispatch.ts and query-plan-select.ts. The symmetric tidy-up to A03a — both gates now share their definition, so planner / dispatcher cannot drift on the predicate body. No behaviour change.

rg 'function hasScalarOrCombineIncludeDescriptors|const hasScalarOrCombineIncludeDescriptors' packages/3-extensions/sql-orm-client/src/ shows exactly one definition (in include-tree-predicates.ts).

Validation:

  • pnpm --filter @prisma-next/sql-orm-client typecheck — clean
  • pnpm --filter @prisma-next/sql-orm-client lint — clean
  • vitest run test/collection-dispatch.test.ts test/query-plan-select.test.ts — 31 passed, 3 skipped

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

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/sql-orm-client/src/query-plan-select.ts (1)

271-324: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Remap child orderBy to the self-relation alias before emitting the nested SELECT.

When childTableAlias is introduced for a self-relation, childState.orderBy still points at include.relatedTableName. The nested SELECT then orders by a table name that is no longer in scope, so single-query self-relations with nested orderBy will emit invalid SQL.

Suggested fix
   const childState = include.nested;
   const childTableAlias =
     include.relatedTableName === parentTableName ? `${include.relationName}__child` : undefined;
   const childTableRef = childTableAlias ?? include.relatedTableName;
   const rowsAlias = `${include.relationName}__rows`;
+  const childOrderByInput =
+    childTableAlias && childState.orderBy
+      ? childState.orderBy.map(
+          (item) =>
+            new OrderByItem(
+              item.expr.rewrite(
+                createTableRefRemapper(include.relatedTableName, childTableRef),
+              ),
+              item.dir,
+            ),
+        )
+      : childState.orderBy;
   const scalarProjection = buildProjection(
     contract,
     include.relatedTableName,
     childState.selectedFields,
     childTableRef,
   );
   const { childOrderBy, hiddenOrderProjection, aggregateOrderBy } = buildIncludeOrderArtifacts(
     include.relationName,
     rowsAlias,
-    childState.orderBy,
+    childOrderByInput,
   );
🤖 Prompt for AI Agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

In `@packages/3-extensions/sql-orm-client/src/query-plan-select.ts` around lines
271 - 324, The nested SELECT can reference an out-of-scope table name when a
self-relation alias (childTableAlias) is used because childState.orderBy still
points at include.relatedTableName; fix by remapping childState.orderBy to use
childTableRef before calling buildIncludeOrderArtifacts (and before passing it
into buildStateWhere if needed). Concretely, transform the orderBy entries on
childState (or create a remapped copy) so their table identifiers equal
childTableRef when childTableAlias is defined, then pass that remapped orderBy
into buildIncludeOrderArtifacts (and ensure buildStateWhere/getters use
childTableRef as the filterTableName as already done).
packages/3-extensions/sql-orm-client/src/collection-dispatch.ts (1)

256-259: ⚠️ Potential issue | 🟠 Major | ⚡ Quick win

Preserve nested join keys on the multi-query fallback path.

stitchIncludes() reads each nested include's localColumn from child.raw, but resolveRowsByParent() only forces include.targetColumn into selectedForQuery. If a child select omits a grandchild join key, the fallback sees only undefined join values and silently returns empty nested results. That breaks the new depth-2+ parity whenever we route to multi-query for missing capabilities, nested combine(), or non-leaf distinct().

Suggested fix
 async function resolveRowsByParent(
   scope: RuntimeScope,
   contract: Contract<SqlStorage>,
   include: IncludeExpr,
   state: CollectionState,
   parentJoinValues: readonly unknown[],
 ): Promise<Map<unknown, Record<string, unknown>[]>> {
+  const nestedJoinColumns = collectNestedLocalJoinColumns(state.includes);
   const { selectedForQuery: childSelectedForQuery, hiddenColumns: hiddenChildColumns } =
-    augmentSelectionForJoinColumns(state.selectedFields, [include.targetColumn]);
+    augmentSelectionForJoinColumns(state.selectedFields, [
+      include.targetColumn,
+      ...nestedJoinColumns,
+    ]);
@@
   return childByParentJoin;
 }
+
+function collectNestedLocalJoinColumns(includes: readonly IncludeExpr[]): string[] {
+  return [...new Set(
+    includes.flatMap((include) => [
+      include.localColumn,
+      ...collectNestedLocalJoinColumns(include.nested.includes),
+    ]),
+  )];
+}

Also applies to: 385-408

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

In `@packages/3-extensions/sql-orm-client/src/collection-dispatch.ts` around lines
256 - 259, resolveRowsByParent is only forcing include.targetColumn into
selectedForQuery which drops nested join keys that stitchIncludes expects on
child.raw; update resolveRowsByParent so that for each include you also ensure
include.localColumn is selected (i.e., add include.localColumn to
selectedForQuery or otherwise request both include.targetColumn and
include.localColumn) so child.raw contains the nested join key used by
stitchIncludes(), and apply the same change in the other multi-query fallback
block (the similar logic around the 385-408 region).
🤖 Prompt for all review comments with AI agents
Verify each finding against current code. Fix only still-valid issues, skip the
rest with a brief reason, keep changes minimal, and validate.

Outside diff comments:
In `@packages/3-extensions/sql-orm-client/src/collection-dispatch.ts`:
- Around line 256-259: resolveRowsByParent is only forcing include.targetColumn
into selectedForQuery which drops nested join keys that stitchIncludes expects
on child.raw; update resolveRowsByParent so that for each include you also
ensure include.localColumn is selected (i.e., add include.localColumn to
selectedForQuery or otherwise request both include.targetColumn and
include.localColumn) so child.raw contains the nested join key used by
stitchIncludes(), and apply the same change in the other multi-query fallback
block (the similar logic around the 385-408 region).

In `@packages/3-extensions/sql-orm-client/src/query-plan-select.ts`:
- Around line 271-324: The nested SELECT can reference an out-of-scope table
name when a self-relation alias (childTableAlias) is used because
childState.orderBy still points at include.relatedTableName; fix by remapping
childState.orderBy to use childTableRef before calling
buildIncludeOrderArtifacts (and before passing it into buildStateWhere if
needed). Concretely, transform the orderBy entries on childState (or create a
remapped copy) so their table identifiers equal childTableRef when
childTableAlias is defined, then pass that remapped orderBy into
buildIncludeOrderArtifacts (and ensure buildStateWhere/getters use childTableRef
as the filterTableName as already done).

ℹ️ Review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

Run ID: 67e28bfc-5dbf-4e10-b02b-8bde054fb1a0

📥 Commits

Reviewing files that changed from the base of the PR and between 3ba642d and 22a06e5.

📒 Files selected for processing (7)
  • packages/3-extensions/sql-orm-client/src/collection-dispatch.ts
  • packages/3-extensions/sql-orm-client/src/include-tree-predicates.ts
  • packages/3-extensions/sql-orm-client/src/query-plan-select.ts
  • packages/3-extensions/sql-orm-client/test/collection-dispatch.test.ts
  • packages/3-extensions/sql-orm-client/test/integration/include.test.ts
  • skills/extension-author/prisma-next-extension-upgrade/upgrades/0.10-to-0.11/instructions.md
  • skills/upgrade/prisma-next-upgrade/upgrades/0.10-to-0.11/instructions.md
✅ Files skipped from review due to trivial changes (2)
  • skills/upgrade/prisma-next-upgrade/upgrades/0.10-to-0.11/instructions.md
  • skills/extension-author/prisma-next-extension-upgrade/upgrades/0.10-to-0.11/instructions.md

aqrln pushed a commit that referenced this pull request May 21, 2026
…e rejection (PR #555 review)

Apply both findings from the code review of PR #555 / TML-2594.

F01: route non-leaf includes carrying `distinct()` to multi-query. Under the
single-query strategies the child SELECT carries nested JSON aggregate
columns, and `SELECT DISTINCT` over those fails on Postgres (`json` has no
equality operator). The multi-query stitcher applies distinct to scalar-only
rows before grandchildren are joined, which is the semantically correct
behavior we preserve. `distinctOn` is intentionally excluded -- Postgres
only compares the `ON (...)` expressions for equality.

F02: make `compileSelectWithIncludeStrategy` reject scalar/combine
descriptors at every depth, not just the top level. The dispatch path
already gates these via `hasComplexIncludeDescriptors` recursively, but
the planner is an exported helper called directly by tests and rich-plan
callers, so it must enforce the same invariant or a nested `count()`
inside a row include would silently produce a malformed plan instead of
failing fast at the boundary.

Tests:
- query-plan-select.test.ts: add nested scalar + nested combine rejection
  cases mirroring the existing top-level rejection test.
- nested-includes-strategy.test.ts: add the reviewers exact regression
  query under LATERAL_CAPABILITIES, the same shape under
  CORRELATED_CAPABILITIES, and a depth-2 recursive case.

Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
aqrln pushed a commit that referenced this pull request May 21, 2026
…tural ScalarOrCombineIncludeDescriptors

Apply the architect-review typology note from PR #555: `Complex` is a
fuzzy qualifier, and the actual distinction the gate makes is structural
(scalar reducer / combine() descriptor, regardless of where it sits in
the include tree). Rename both parallel predicates -- the dispatch-side
`hasComplexIncludeDescriptors` and the planner-side
`hasScalarOrCombineIncludeAnywhere` -- to a single shared name
`hasScalarOrCombineIncludeDescriptors`. Same name on both layers makes
the parallel enforcement explicit; the boundary between dispatch policy
and planner validity is preserved by their separate locations.

Update inline comments in both source files and in the strategy /
query-plan-select tests that referenced the old name.

No behavior change.

Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
@aqrln
aqrln force-pushed the tml-2594-sql-orm-nested-includes-depth-2-fall-back-to-multi-query branch from 22a06e5 to 406b659 Compare May 21, 2026 12:39
…WithIncludeStrategy

Lift hasNonLeafIncludeWithDistinct from collection-dispatch.ts into a
shared include-tree-predicates module, and apply the same recursive
gate in the exported planner so direct callers (tests, rich-plan
consumers) fail fast instead of building an invalid SELECT DISTINCT
over a nested json_agg projection.

Refs: TML-2594
Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
…ludes single-query collapse

Records the 0.10 → 0.11 upgrade-instructions directory in both the
user-skill and extension-author-skill packages, so
pnpm check:upgrade-coverage --mode pr passes on this PR.

- skills/extension-author/prisma-next-extension-upgrade/upgrades/0.10-to-0.11/
  carries the real entry describing the SQL ORM client behaviour shift
  (nested includes at depth ≥ 2 collapse to single-query on capable
  targets; non-leaf .distinct() with nested includes now throws).

- skills/upgrade/prisma-next-upgrade/upgrades/0.10-to-0.11/ ships with
  changes: [] — the only examples/ diff in this branch is incidental
  devDep cleanup, no user-facing behaviour change.

Refs: TML-2594
Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
…patch test labels

Renames three `it(...)` labels in collection-dispatch.test.ts so test
titles stay behaviour-focused per the test-naming guideline (same rule
we honoured in A01 for nested-includes-strategy.test.ts):

- "...fires a single SQL execution (TML-2594)"   →  drop suffix
- "...mixed cardinality (...) (TML-2594)"        →  drop suffix
- "...stays on multi-query (TML-2594 fallback)"  →  drop suffix

Forward-looking code comments that reference TML-2594/TML-2595 stay —
the rule only forbids transient ticket ids in test names.

Refs: TML-2594
Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
…clude test labels

Renames the two `it(...)` labels in
test/integration/include.test.ts (lines 757 and 846) so test titles
stay behaviour-focused per the test-naming guideline. Same shape as
A05 on collection-dispatch.test.ts.

The forward-looking code comment at line 747 stays — the rule only
forbids transient ticket ids in test names.

Refs: TML-2594
Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
…uery-fallback fixture

The multi-query-fallback test exercises include-strategy selection,
not pgvector behaviour. The `embedding` column on the Post fixture
row (and the matching `expect(...).toEqual` shape) is extension-
dependent and has no bearing on what the test asserts (parent + posts
+ comments = 3 executions, irrespective of column shape).

Drops `embedding: null` from both the `runtime.setNextResults(...)`
row at line 251 and the corresponding expectation at line 276. The
test still passes (13/13 in this file, 3 skipped).

Refs: TML-2594
Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
…o shared include-tree-predicates

Both `dispatchWithIncludeStrategy` (in `collection-dispatch.ts`) and
the exported `compileSelectWithIncludeStrategy` (in
`query-plan-select.ts`) were carrying their own private copies of
the same recursive predicate, with the same body. The symmetric tidy-
up to A03a (which lifted `hasNonLeafIncludeWithDistinct` into
`include-tree-predicates.ts`) — without it, future drift between the
planner and the dispatcher could reintroduce a mismatch where one
seam accepts a descriptor the other rejects.

Moves the function (plus a merged doc-comment that covers both
call sites) into `src/include-tree-predicates.ts` next to
`hasNonLeafIncludeWithDistinct`, and imports it from both consumers.
No behaviour change — the predicate body is identical to both prior
copies.

Validation (filtered to the affected suites):
- pnpm --filter @prisma-next/sql-orm-client typecheck → clean
- pnpm --filter @prisma-next/sql-orm-client lint → clean
- vitest run test/collection-dispatch.test.ts test/query-plan-select.test.ts
  → 31 passed, 3 skipped

Refs: TML-2594
Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
…nt tests

Replaces two projected-slice assertions with whole-result
`expect(rows).toEqual([...])` blocks so the tests pin the entire
stitched shape (ids, scalars, AND the nested include arrays), not
just a sub-tree:

- where() filter on depth-2 child (line 78-ish): was
  `expect(rows[0]?.posts).toEqual([...])` → now asserts the parent
  User shape too.
- orderBy on parent and on depth-2 child (line 117-ish): was
  `expect(rows.map(r => r.id)).toEqual([1, 2])` plus
  `expect(rows[1]?.posts[0]?.comments.map(c => c.id))` → now asserts
  the full parent+posts+comments shape across both rows.

Mirrors the whole-result style already used by the depth-2 edge-case
tests further down in the same suite.

Refs: TML-2594
Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
… scalar/combine tests

Replaces two projected-slice assertions in nested-includes-strategy.test.ts
with whole-result expect(rows).toEqual([...]) blocks so the tests pin
the entire stitched shape, not just one sub-tree value:

- top-level combine() stays on multi-query under lateral capabilities
  (line 392-393): was expect(rows[0]?.posts.total) plus
  expect(rows[0]?.posts.items).toHaveLength(2) → now asserts the
  parent User row plus the combined { items: [...full posts...],
  total: 2 } shape.
- nested scalar at depth 2 stays on multi-query (line 423): was
  expect(rows[0]?.posts[0]?.comments).toBe(2) → now asserts the
  parent row, the post row, and that the c.count() include slot
  resolves to the scalar 2.

The execution-count guard (expect(runtime.executions.length)
.toBeGreaterThan(1)) is preserved unchanged on both — that pin is
what keeps the dispatch gate honest across future refactors.

A13/A14/A15 (the distinct()-on-non-leaf cases) will receive the
same whole-result treatment in a follow-up commit after A19b lands
the resolveRowsByParent fix that lets nested comments populate when
the parent .select(...) omits the join column.

Refs: TML-2594
Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
… per review

Trims the sql-orm-client-nested-includes-single-query-at-depth-2
section in skills/extension-author/prisma-next-extension-upgrade/
upgrades/0.10-to-0.11/instructions.md per @aqrln review:

- Drop the seam-internal bullet list (dispatchWithIncludeStrategy /
  compileSelectWithIncludeStrategy enumeration). Internal entry-point
  names are not part of the upgrade story for extension authors; the
  one consumer-relevant mention of compileSelectWithIncludeStrategy
  stays in Who is affected. (A16)

- Drop the New safety gate / non-leaf .distinct() entry. That gate
  is a transitional measure scheduled to lift before 0.11 GA, so
  documenting it as a permanent migration step would mislead. The
  recursive scalar/combine generalisation, which is the load-bearing
  recursion change actually shipping, is kept under a smaller header
  with the gate description tightened. (A17)

- Replace the verbose three-bullet Who is affected enumeration with
  a short note framing the change as a bugfix that aligns behaviour
  with the documented surface, and pointing the small subset of
  plan-shape-introspecting extensions at strategy pinning if a
  specific shape is needed. (A18)

pnpm check:upgrade-coverage --mode pr remains green.

Refs: TML-2594
Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
…hildRowsSelect

When `include.relatedTableName === parentTableName` (self-relations),
`buildIncludeChildRowsSelect` already renames the inner FROM source via
`childTableAlias` and remaps `state.filters` / `state.cursor` through
`createTableRefRemapper(include.relatedTableName, childTableRef)` via
the `filterTableName` option to `buildStateWhere`. The user-supplied
`childState.orderBy` was missing from that remap, so the hidden order
projection inside the inner rows-subselect emitted a ColumnRef against
the original outer table name (`users`) that is no longer in scope.

In a lateral / correlated subquery PG resolves the outer-scope name
silently, which means ORDER BY correlates against the outer row
(constant per parent) instead of the inner child rows — order becomes
indeterminate within each parent group. Symptom: nested self-relation
includes with an `orderBy(...)` clause return children in insertion
order, not the requested order.

Fix mirrors the existing `filterTableName` remap shape exactly:
when `childTableAlias` is set, rewrite every `OrderByItem` in
`childState.orderBy` through the same `createTableRefRemapper` before
passing into `buildIncludeOrderArtifacts`.

Regression test (`test/integration/self-relations.test.ts`): a
self-relation include with `invitedUsers.orderBy(u => u.id.desc())`
on out-of-id-order seeded children. Before the fix the children come
back in insertion order [2, 4, 3]; after the fix in id-desc order
[4, 3, 2]. The test also asserts the hidden order projection in
the emitted SQL references `"invitedUsers__child"."id"`, not the
outer `"users"."id"`.

Refs: TML-2594
Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
…selectedForQuery

In `resolveRowsByParent`, when `state.includes` is non-empty the
downstream `stitchIncludes(scope, contract, childRows, state.includes)`
call reads `child.raw[grandchildInclude.localColumn]` for every
immediate include to bucket children by join value. Until now the
augmented child `selectedForQuery` only forced `include.targetColumn`
in. So a user-supplied `.select(...)` on the child that omitted any
of those grandchild join keys silently yielded `undefined` for the
join value, and depth >= 2 nested arrays came back empty.

Collect every direct `state.includes[i].localColumn` and union them
with `include.targetColumn` into the required-columns set passed to
`augmentSelectionForJoinColumns`. The next level of recursion repeats
the same augmentation for its own children. `augmentSelectionForJoinColumns`
already handles the strip on the way out, so the user-visible mapped
shape stays exactly what `.select(...)` asked for.

Regression test (`test/integration/nested-includes-refinements.test.ts`):
depth-2 multi-query path (empty capabilities) with
`posts.select(\"title\").include(\"comments\")`. Before the fix
`comments: []` because `Post.id` is not in the child query`s SELECT;
after the fix `comments: [{ id: 100, body: \"hi\", postId: 10 }]`.
Verified the test fails on the unfixed substrate.

Refs: TML-2594
Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
…ests

Replaces the projected-slice assertions in the three
non-leaf-distinct() tests with whole-result expect(rows).toEqual([...])
blocks now that A19b populates comments correctly when the parent
.select(...) omits the join key:

- distinct() on a non-leaf include stays on multi-query under lateral
  capabilities (line 469-471): was three partial assertions
  (toHaveLength + map+sort). Adds .orderBy((p) => p.title.asc()) to
  the posts include to lock order, then asserts the parent row plus
  posts [{title: A, comments: [...]}, {title: B, comments: []}].
- distinct() under correlated capabilities (line 498-499): was
  toHaveLength(1) + toBe(A). Now asserts the parent and the single
  post with its single comment.
- distinct() nested at depth 2 (line 529): was no row assertion at
  all (just executions.length > 1). Adds .orderBy((u) => u.id.asc())
  on the outer collection, then asserts the full two-row shape
  including the empty invitedUsers for Child.

Each test keeps its expect(runtime.executions.length).toBeGreaterThan(1)
guard so the dispatch gate stays pinned.

Refs: TML-2594
Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
@aqrln
aqrln force-pushed the tml-2594-sql-orm-nested-includes-depth-2-fall-back-to-multi-query branch from 1030268 to a8eca57 Compare May 21, 2026 13:56
The `@prisma-next/sql-orm-client` package only exports `Collection`,
`orm`, `all`/`and`/`not`/`or`, `GroupedCollection`, and a set of
type-only surface types. The internal planner / dispatcher seams the
removed entry documented (`compileSelectWithIncludeStrategy`,
`dispatchWithIncludeStrategy`, the shared `include-tree-predicates`
helpers) are not reachable from outside the package. No extension
author can be affected by the strategy-selection or gate changes, so
documenting them as a migration step is misleading.

The directory still carries the three valid 0.10-to-0.11 entries
(`namespace-kind-required-on-handcrafted-contract-literals`,
`facade-add-close-and-async-dispose`, `mongo-close-ownership-rule`),
so `pnpm check:upgrade-coverage --mode pr` continues to pass.

Refs: TML-2594
Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
… + self-relation tests

Four partial-result assertions left in this PR after the iter-4 sweep:

- `nested-includes-refinements.test.ts:42` (orderBy + take on depth-2
  child) asserted only on `rows[0]?.posts[0]?.comments`. Now asserts
  the full Alice row with the single post containing both ordered
  comments.
- `nested-includes-refinements.test.ts:240` (depth-1 present but no
  depth-2 grandchildren) asserted only on `rows[0]?.posts`. Now
  asserts the full Alice row with the empty-comments post.
- `nested-includes-refinements.test.ts:269` (descendant-localColumn
  regression test for A19b) asserted only on `rows[0]?.posts`. Now
  asserts the full Alice row with the selected `title` and the
  stitched depth-2 comment.
- `self-relations.test.ts:101` (childTableRef-orderBy regression test
  for A19a) asserted only `rows[0]?.invitedUsers.map((u) => u.id)`.
  Now asserts the full Alice row with all three invitedUsers in
  desc-id order, each with every scalar column. The hidden-orderBy
  SQL assertion immediately below it is preserved.

Refs: TML-2594
Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
@aqrln
aqrln enabled auto-merge (rebase) May 21, 2026 14:17
@aqrln
aqrln merged commit f5b0bb9 into main May 21, 2026
16 checks passed
aqrln pushed a commit that referenced this pull request May 21, 2026
…e rejection (PR #555 review)

Apply both findings from the code review of PR #555 / TML-2594.

F01: route non-leaf includes carrying `distinct()` to multi-query. Under the
single-query strategies the child SELECT carries nested JSON aggregate
columns, and `SELECT DISTINCT` over those fails on Postgres (`json` has no
equality operator). The multi-query stitcher applies distinct to scalar-only
rows before grandchildren are joined, which is the semantically correct
behavior we preserve. `distinctOn` is intentionally excluded -- Postgres
only compares the `ON (...)` expressions for equality.

F02: make `compileSelectWithIncludeStrategy` reject scalar/combine
descriptors at every depth, not just the top level. The dispatch path
already gates these via `hasComplexIncludeDescriptors` recursively, but
the planner is an exported helper called directly by tests and rich-plan
callers, so it must enforce the same invariant or a nested `count()`
inside a row include would silently produce a malformed plan instead of
failing fast at the boundary.

Tests:
- query-plan-select.test.ts: add nested scalar + nested combine rejection
  cases mirroring the existing top-level rejection test.
- nested-includes-strategy.test.ts: add the reviewers exact regression
  query under LATERAL_CAPABILITIES, the same shape under
  CORRELATED_CAPABILITIES, and a depth-2 recursive case.

Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
@aqrln
aqrln deleted the tml-2594-sql-orm-nested-includes-depth-2-fall-back-to-multi-query branch May 21, 2026 14:20
aqrln pushed a commit that referenced this pull request May 21, 2026
…tural ScalarOrCombineIncludeDescriptors

Apply the architect-review typology note from PR #555: `Complex` is a
fuzzy qualifier, and the actual distinction the gate makes is structural
(scalar reducer / combine() descriptor, regardless of where it sits in
the include tree). Rename both parallel predicates -- the dispatch-side
`hasComplexIncludeDescriptors` and the planner-side
`hasScalarOrCombineIncludeAnywhere` -- to a single shared name
`hasScalarOrCombineIncludeDescriptors`. Same name on both layers makes
the parallel enforcement explicit; the boundary between dispatch policy
and planner validity is preserved by their separate locations.

Update inline comments in both source files and in the strategy /
query-plan-select tests that referenced the old name.

No behavior change.

Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
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