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

TML-2657: remove multi-query include strategy from the read path - #619

Merged
aqrln merged 12 commits into
mainfrom
tml-2657-sql-orm-remove-multi-query-include-strategy-from-read-path
May 29, 2026
Merged

aqrln merged 12 commits into
mainfrom
tml-2657-sql-orm-remove-multi-query-include-strategy-from-read-path

Conversation

@tensordreams

@tensordreams tensordreams commented May 29, 2026 •

Copy link
Copy Markdown
Contributor

Linked issue

Refs TML-2657.

Unblocked by the now-merged TML-2594 (nested includes), TML-2595 (combine()/count()), and TML-2656 (distinct() on non-leaf include) — together they made every in-tree SQL target lateral/correlated-capable, so the multi-query fallback became unreachable on reads.

At a glance

export type IncludeStrategy = 'lateral' | 'correlated';

export function selectIncludeStrategy(contract: Contract<SqlStorage>): IncludeStrategy {
  return capabilityFlag(contract, 'lateral') ? 'lateral' : 'correlated';
}

Previously this returned a third arm, 'multiQuery', which dispatched to a JS-side stitcher that fired one SELECT per relation per depth level (N+1) and stitched the results in memory. That arm — and its entire stitcher — is gone.

Summary

This PR removes the multi-query include strategy from the SQL ORM. The deliverable is three things, not one:

  1. Read path: one include strategy, capability-gated to two single-query builders — lateral (Postgres) or correlated subqueries (any other jsonAgg target). The 'multiQuery' arm of selectIncludeStrategy and the IncludeStrategy type both narrow to 'lateral' | 'correlated'.
  2. Mutation read-back migration (scope expansion — see reviewer notes): the mutation path's .include() read-back (create/createAll/update/updateAll/upsert) no longer uses the stitcher. It now resolves relations with a single follow-up SELECT keyed by the mutated rows' identity, lowered through the same lateral/correlated builders the read path uses. delete/deleteAll + .include() reads a pre-delete snapshot before issuing the DELETE.
  3. Deletion: with no remaining caller, dispatchWithMultiQueryIncludes, the whole stitchX chain, and the stitcher-only compileRelationSelect planner helper are deleted.

Per ADR 164, mutation orchestration (CREATE-without-RETURNING, nested creates, FK cascades — transaction() / connection()) is untouched; only the include read-back changed.

Notes for the reviewer

  • Scope deviation from the ticket — read this first. The ticket said "mutation path: untouched" and listed the stitcher symbols as dead-on-read. That premise was wrong: collection-mutation-dispatch.ts imported stitchIncludes and used it in every mutation read-back. So the stitchers were not dead. Rather than relocate them (keeping two divergent include-loading codepaths and the N+1 read-back), we migrated the mutation read-back onto the single-query builders so the stitcher could be deleted outright. This was an explicit, agreed scope expansion.
  • Delete + include is a deliberate semantic refinement. A parent-anchored single-query include read can't observe an already-deleted row, so delete now reads the row together with its relations before the DELETE and returns that snapshot. Net effect: relations reflect their pre-delete state (e.g. cascade-deleted children come back as they were, rather than as an empty array from a post-delete child query). No prior test pinned the old post-delete behavior; there was no delete+include coverage at all before this PR.
  • SQLite. The correlated path (SQLite and any lateral-less jsonAgg target) is covered at the unit/compile level (compileSelectWithIncludeStrategy(..., 'correlated')). The ORM integration harness here is PGlite-only, so there is no separate SQLite integration leg to run.
  • Biggest diff is collection-dispatch.ts. Worth spot-checking that the kept single-query decode helpers (decodeIncludePayload, decodeCombineIncludePayload, coerceSingleQueryIncludeResult, emptyScalarResult) survived the deletion intact.
  • Identity-keyed read-back handles single-column identity via IN (...) and composite identity via OR of per-row AND-equals; the bucketing key is bigint-safe.

How it fits together

  1. Narrow the selector. selectIncludeStrategy drops the jsonAgg-fallback logic and keys purely on the lateral capability; IncludeStrategy becomes 'lateral' | 'correlated'. dispatchWithIncludeStrategy collapses to a single call into the single-query path.
  2. Add the mutation read-back. loadIncludesForMutationRows takes the rows a mutation's RETURNING produced, builds an identity IN (...) filter, compiles one lateral/correlated SELECT carrying the include columns, decodes the JSON aggregates, and assigns them onto each parent — bucketed by identity. It runs on the caller's already-acquired scope so it observes the just-written rows in the same connection/transaction.
  3. Route mutations through it. The three mutation dispatchers call the helper instead of stitchIncludes; collection.ts augments the mutation RETURNING with identity columns when includes are present. delete/deleteAll take the read-before-delete branch.
  4. Delete the dead path. dispatchWithMultiQueryIncludes, the stitcher chain, and compileRelationSelect (plus its re-export) come out.
  5. Retarget tests. Strategy cases recast to correlated; mutation-dispatch unit tests rewritten to the read-back shape; multi-query fallback tests deleted; PG integration coverage added for create/update/delete + include.

Behavior changes & evidence

Testing performed

  • pnpm --filter @prisma-next/sql-orm-client typecheck — clean
  • pnpm lint:deps — clean (994 modules, 2056 dependencies)
  • pnpm build — full Turbo build, 66 tasks
  • pnpm --filter @prisma-next/sql-orm-client test — 515 passed, 3 skipped
  • pnpm test:integration (sql-orm-client suite, PGlite) — 172 passed across 23 files
  • Pre-existing/unrelated: the cli-telemetry "populates the agent field for Gemini CLI sessions" test fails only because the suite runs inside Claude Code and detects 'Claude Code' instead of the simulated agent. Not touched by this PR.

Skill update

n/a — internal only. Nothing in sql-orm-client's public exports changed; the affected symbols (dispatchWithMultiQueryIncludes, the stitchers, compileRelationSelect, IncludeStrategy) are all package-internal.

Follow-ups

  • "Drop LATERAL in favour of correlated-everywhere?" — separate ticket, not yet filed, gated on benchmark + query-plan analysis of the top-N-per-parent shape (posts.include({ comments: { take: 5 } })) on Postgres, where LATERAL is the canonical pattern and correlated-with-json_agg-over-LIMIT has weaker planner-decorrelation guarantees.

Alternatives considered

  • Relocate the stitcher into a mutation-owned module and keep multi-query for the mutation read-back. Rejected: it preserves two divergent include-loading codepaths and the N+1 read-back, and only half-meets the ticket's deletion goal. Migrating the read-back to single-query removes both at once.
  • Keep multi-query as a fallback for targets without jsonAgg. Rejected per the ticket's accepted constraint: every supported SQL target now provides jsonAgg; targets without it are out of scope on the read path by policy.
  • For delete, extend the lateral/correlated builders to anchor on a VALUES key-set so relations could be loaded after the DELETE (preserving exact post-delete semantics). Rejected: more invasive (it touches builders the ticket deliberately keeps as-is) and the pre-delete snapshot is the more intuitive contract for "return the row I just deleted, with its relations."

Checklist

  • All commits are signed off (git commit -s) per the DCO.
  • I read CONTRIBUTING.md and the change is scoped to one logical concern.
  • Tests are updated.
  • The PR title is in TML-NNNN: <sentence-case title> form.
  • The Skill update section above is filled in (n/a — internal only).

Summary by CodeRabbit

  • New Features

    • Mutations (create/update/delete) now return included relations via a reliable read-back, with pre-delete snapshots for deletes.
  • Behavior Changes

    • Include dispatch now consistently uses two single-query strategies (lateral or correlated) for predictable include results.
  • Bug Fixes

    • Improved handling of empty includes, identity-based re-selection after mutations, and clearer scalar/null decoding semantics.
  • Tests

    • Updated and added integration/unit tests exercising include read-back across mutation flows.

Review Change Stack

@tensordreams
tensordreams requested a review from a team as a code owner May 29, 2026 10:37
@coderabbitai

coderabbitai Bot commented May 29, 2026 •

Copy link
Copy Markdown
Contributor

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Path: .coderabbit.yml

Review profile: CHILL

Plan: Pro

Run ID: 59e07392-565b-4e22-927f-9242428df23e

📥 Commits

Reviewing files that changed from the base of the PR and between 32c8302 and e39ba99.

📒 Files selected for processing (6)
  • packages/3-extensions/sql-orm-client/src/collection-dispatch.ts
  • packages/3-extensions/sql-orm-client/src/collection-mutation-dispatch.ts
  • packages/3-extensions/sql-orm-client/src/include-strategy.ts
  • test/integration/test/authoring/side-by-side-contracts.test.ts
  • test/integration/test/sql-orm-client/create.test.ts
  • test/integration/test/sql-orm-client/mutation-include-readback.test.ts
🚧 Files skipped from review as they are similar to previous changes (3)
  • test/integration/test/sql-orm-client/mutation-include-readback.test.ts
  • packages/3-extensions/sql-orm-client/src/collection-dispatch.ts
  • packages/3-extensions/sql-orm-client/src/collection-mutation-dispatch.ts

📝 Walkthrough

Walkthrough

This PR consolidates include dispatch onto single-query strategies, removes multi-query stitching, adds reloadMutationRowsByIdentities for mutation read-back by identity, updates mutation RETURNING projection logic and delete-with-includes snapshots, and adjusts unit and integration tests.

Changes

Multi-query removal and single-query mutation includes consolidation

Layer / File(s) Summary
All changes (include dispatch, mutation reload, projections, exports, tests)
packages/3-extensions/sql-orm-client/src/*, test/integration/test/sql-orm-client/*, packages/3-extensions/sql-orm-client/test/*
Remove multi-query include stitching and export, route non-empty .include() paths to single-query strategies via selectIncludeStrategy, add reloadMutationRowsByIdentities (identity-column resolution, IN / OR-of-tuples filter building, and reselect via dispatchCollectionRows), introduce #augmentMutationSelection() and pre-delete snapshot path, remove compileRelationSelect and related AST usage, and update unit/integration tests to reflect single-query include behavior and mutation read-back.

Estimated code review effort

🎯 4 (Complex) | ⏱️ ~60 minutes

Possibly related PRs

Suggested reviewers

  • aqrln

Poem

🐰 The rabbit hops through query paths, single-query takes the stage,

Identity keys guide the read, no more multi-query page,
Mutations return their relations, deletes snapshot what was there,
Tests now sing the simpler tune — fewer branches in the air.

🚥 Pre-merge checks | ✅ 4 | ❌ 1

❌ Failed checks (1 warning)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 36.36% 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 clearly and specifically describes the main change: removing the multi-query include strategy from the read path, which is the primary objective of this PR.
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 docstrings
  • Create stacked PR
  • Commit on current branch
🧪 Generate unit tests (beta)
  • Create PR with unit tests
  • Commit unit tests in branch tml-2657-sql-orm-remove-multi-query-include-strategy-from-read-path

Warning

There were issues while running some tools. Please review the errors and either fix the tool's configuration or disable the tool if it's a critical failure.

🔧 ESLint

If the error stems from missing dependencies, add them to the package.json file. For unrecoverable errors (e.g., due to private dependencies), disable the tool in the CodeRabbit configuration.

ESLint skipped: no ESLint configuration detected in root package.json. To enable, add eslint to devDependencies.


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.

@tensordreams
tensordreams force-pushed the tml-2657-sql-orm-remove-multi-query-include-strategy-from-read-path branch from 18d4bb5 to 55c703b Compare May 29, 2026 10:40
@pkg-pr-new

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

Copy link
Copy Markdown

Open in StackBlitz

@prisma-next/extension-author-tools

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

@prisma-next/mongo-runtime

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

@prisma-next/family-mongo

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

@prisma-next/sql-runtime

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

@prisma-next/family-sql

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

@prisma-next/extension-arktype-json

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

@prisma-next/extension-cipherstash

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

@prisma-next/middleware-cache

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

@prisma-next/mongo

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

@prisma-next/extension-paradedb

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

@prisma-next/extension-pgvector

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

@prisma-next/extension-postgis

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

@prisma-next/postgres

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

@prisma-next/sql-orm-client

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

@prisma-next/sqlite

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

@prisma-next/target-mongo

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

@prisma-next/adapter-mongo

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

@prisma-next/driver-mongo

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

@prisma-next/contract

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

@prisma-next/utils

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

@prisma-next/config

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

@prisma-next/errors

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

@prisma-next/framework-components

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

@prisma-next/operations

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

@prisma-next/ts-render

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

@prisma-next/contract-authoring

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

@prisma-next/ids

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

@prisma-next/psl-parser

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

@prisma-next/psl-printer

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

@prisma-next/cli

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

@prisma-next/cli-telemetry

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

@prisma-next/emitter

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

@prisma-next/migration-tools

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

prisma-next

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

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

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

@prisma-next/mongo-codec

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

@prisma-next/mongo-contract

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

@prisma-next/mongo-value

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

@prisma-next/mongo-contract-psl

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

@prisma-next/mongo-contract-ts

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

@prisma-next/mongo-emitter

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

@prisma-next/mongo-schema-ir

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

@prisma-next/mongo-query-ast

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

@prisma-next/mongo-orm

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

@prisma-next/mongo-query-builder

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

@prisma-next/mongo-lowering

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

@prisma-next/mongo-wire

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

@prisma-next/sql-contract

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

@prisma-next/sql-errors

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

@prisma-next/sql-operations

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

@prisma-next/sql-schema-ir

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

@prisma-next/sql-contract-psl

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

@prisma-next/sql-contract-ts

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

@prisma-next/sql-contract-emitter

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

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

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

@prisma-next/sql-relational-core

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

@prisma-next/sql-builder

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

@prisma-next/target-postgres

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

@prisma-next/target-sqlite

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

@prisma-next/adapter-postgres

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

@prisma-next/adapter-sqlite

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

@prisma-next/driver-postgres

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

@prisma-next/driver-sqlite

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

commit: 2d5162c

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

Caution

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

⚠️ Outside diff range comments (1)
test/integration/test/sql-orm-client/nested-includes-strategy.test.ts (1)

8-13: ⚠️ Potential issue | 🟡 Minor | ⚡ Quick win

Fix the stale “three strategies” wording in the header.

After removing the multi-query path, this suite only compares lateral vs correlated. Leaving “three strategies” here makes the contract comment inaccurate for future readers.

Suggested wording
-// benchmark drift. The cross-strategy equivalence tests then assert
-// that the three strategies produce byte-identical result trees over
-// the same data.
+// benchmark drift. The cross-strategy equivalence tests then assert
+// that both single-query strategies produce byte-identical result
+// trees over the same data.
🤖 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 `@test/integration/test/sql-orm-client/nested-includes-strategy.test.ts` around
lines 8 - 13, Update the stale header comment that refers to “three strategies”
in nested-includes-strategy.test.ts to reflect the current two-strategy
comparison (lateral vs correlated); locate the top comment block containing the
phrase "three strategies" and replace it with wording that states the suite pins
SQL-execution count per strategy for the two strategies (lateral and correlated)
and that cross-strategy equivalence asserts byte-identical result trees over the
same data.
🧹 Nitpick comments (1)
test/integration/test/sql-orm-client/update.test.ts (1)

130-145: ⚡ Quick win

Assert the exact projected row shape here.

This test currently proves the relations are bucketed correctly, but arrayContaining() would still pass if the internal identity columns added for read-back leaked back into the public payload. Since this PR changes that projection path, it’s worth pinning the exact keys returned by select('name').include(...).

One way to tighten the assertion
-        expect(updated).toEqual(
-          expect.arrayContaining([
-            {
-              name: 'Ready',
-              posts: [{ id: 10, title: 'Post A', userId: 1, views: 100, embedding: null }],
-            },
-            {
-              name: 'Ready',
-              posts: [
-                { id: 11, title: 'Post B', userId: 2, views: 200, embedding: null },
-                { id: 12, title: 'Post C', userId: 2, views: 300, embedding: null },
-              ],
-            },
-          ]),
-        );
-        expect(updated).toHaveLength(2);
+        const normalized = [...updated].sort(
+          (left, right) => left.posts[0]!.userId - right.posts[0]!.userId,
+        );
+        expect(normalized).toEqual([
+          {
+            name: 'Ready',
+            posts: [{ id: 10, title: 'Post A', userId: 1, views: 100, embedding: null }],
+          },
+          {
+            name: 'Ready',
+            posts: [
+              { id: 11, title: 'Post B', userId: 2, views: 200, embedding: null },
+              { id: 12, title: 'Post C', userId: 2, views: 300, embedding: null },
+            ],
+          },
+        ]);
🤖 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 `@test/integration/test/sql-orm-client/update.test.ts` around lines 130 - 145,
The test currently uses expect.arrayContaining which permits extra leaked keys;
replace that with an exact equality assertion on the updated variable so the
returned rows contain only the projected keys from select('name').include(...).
Concretely, update the assertion around the updated variable to
expect(updated).toEqual([...]) with the exact two-element array of objects (each
object only has name and posts, and each post only has id, title, userId, views,
embedding null), and remove or keep the toHaveLength(2) check as redundant; this
ensures no internal identity columns leak into the public payload.
🤖 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 `@test/integration/test/sql-orm-client/nested-includes.test.ts`:
- Around line 1-3: The top-of-file comment incorrectly claims coverage for "both
... lateral and correlated" strategies while the tests call
createUsersCollection(runtime) and never override capabilities, so update the
header/comment in nested-includes.test.ts to state it exercises the default
lateral path only (or "default lateral strategy"), and add a brief pointer that
cross-strategy coverage is in nested-includes-strategy.test.ts; reference the
file name and the createUsersCollection(runtime) calls to locate the tests to be
clarified.

---

Outside diff comments:
In `@test/integration/test/sql-orm-client/nested-includes-strategy.test.ts`:
- Around line 8-13: Update the stale header comment that refers to “three
strategies” in nested-includes-strategy.test.ts to reflect the current
two-strategy comparison (lateral vs correlated); locate the top comment block
containing the phrase "three strategies" and replace it with wording that states
the suite pins SQL-execution count per strategy for the two strategies (lateral
and correlated) and that cross-strategy equivalence asserts byte-identical
result trees over the same data.

---

Nitpick comments:
In `@test/integration/test/sql-orm-client/update.test.ts`:
- Around line 130-145: The test currently uses expect.arrayContaining which
permits extra leaked keys; replace that with an exact equality assertion on the
updated variable so the returned rows contain only the projected keys from
select('name').include(...). Concretely, update the assertion around the updated
variable to expect(updated).toEqual([...]) with the exact two-element array of
objects (each object only has name and posts, and each post only has id, title,
userId, views, embedding null), and remove or keep the toHaveLength(2) check as
redundant; this ensures no internal identity columns leak into the public
payload.
🪄 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: f0c9f9ff-8063-4786-8bc4-e45dc5a3fe30

📥 Commits

Reviewing files that changed from the base of the PR and between e15220b and 18d4bb5.

📒 Files selected for processing (18)
  • packages/3-extensions/sql-orm-client/src/collection-dispatch.ts
  • packages/3-extensions/sql-orm-client/src/collection-mutation-dispatch.ts
  • packages/3-extensions/sql-orm-client/src/collection.ts
  • packages/3-extensions/sql-orm-client/src/include-strategy.ts
  • packages/3-extensions/sql-orm-client/src/query-plan-select.ts
  • packages/3-extensions/sql-orm-client/src/query-plan.ts
  • packages/3-extensions/sql-orm-client/test/collection-dispatch.test.ts
  • packages/3-extensions/sql-orm-client/test/collection-mutation-dispatch.test.ts
  • packages/3-extensions/sql-orm-client/test/include-strategy.test.ts
  • packages/3-extensions/sql-orm-client/test/query-plan-select.test.ts
  • test/integration/test/sql-orm-client/create.test.ts
  • test/integration/test/sql-orm-client/delete.test.ts
  • test/integration/test/sql-orm-client/include.test.ts
  • test/integration/test/sql-orm-client/nested-includes-distinct.test.ts
  • test/integration/test/sql-orm-client/nested-includes-helpers.ts
  • test/integration/test/sql-orm-client/nested-includes-strategy.test.ts
  • test/integration/test/sql-orm-client/nested-includes.test.ts
  • test/integration/test/sql-orm-client/update.test.ts
💤 Files with no reviewable changes (1)
  • test/integration/test/sql-orm-client/include.test.ts

@tensordreams

Copy link
Copy Markdown
Contributor Author

@coderabbitai Re: the "outside diff range" finding on test/integration/test/sql-orm-client/nested-includes-strategy.test.ts (header at lines 8-13) — agreed. After removing the multi-query path the suite compares only the two single-query strategies (lateral vs correlated), so the "three strategies" wording is stale. Will reword the cross-strategy-equivalence sentence to reflect the two-strategy comparison. Addressing in this PR.

@tensordreams

Copy link
Copy Markdown
Contributor Author

@coderabbitai Re: the nitpick on test/integration/test/sql-orm-client/update.test.ts (lines 130-145) — good catch, taking it. Since this PR changes the read-back projection path, arrayContaining(...) would still pass if an internal identity column leaked into the public payload. I'll switch to an exact toEqual on a deterministically-sorted array so the test pins the exact projected keys. Addressing in this PR.

@coderabbitai

coderabbitai Bot commented May 29, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

@tensordreams: Sounds good — updating it to reflect the two-strategy (lateral vs correlated) comparison will keep the header consistent with the removed multi-query path. Thanks for the confirmation!


If you found this review helpful, would you consider giving us a shout-out on X?

Thank you for using CodeRabbit!

@coderabbitai

coderabbitai Bot commented May 29, 2026

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

@tensordreams: Sounds great — pinning the exact projected keys with toEqual on a sorted array is the right call here. Since this PR changes the read-back projection path, a leaking identity column (e.g. a hidden join key) would silently pass arrayContaining, so the stricter assertion provides much better safety net going forward. Thanks for taking it!

🐇 ✨


If you found this review helpful, would you consider giving us a shout-out on X?

Thank you for using CodeRabbit!

@tensordreams

Copy link
Copy Markdown
Contributor Author

Done in ec4e091 (CodeRabbit outside-diff comment on nested-includes-strategy.test.ts): fixed the stale 'three strategies' wording — only lateral and correlated remain after the multi-query path was removed, and the header now says both single-query strategies produce byte-identical result trees over the same data.

@tensordreams

Copy link
Copy Markdown
Contributor Author

Done in ba04dcf (CodeRabbit nitpick on update.test.ts): replaced expect.arrayContaining with an exact toEqual over a deterministically sorted array, so a read-back identity column leaking into the public payload now fails the test.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Actionable comments posted: 1

🤖 Prompt for all review comments with AI agents
Verify each finding against 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/src/collection-mutation-dispatch.ts`:
- Around line 129-137: The code incorrectly passes tableName to
mapStorageRowToModelFields causing wrong field mapping when model and table
names differ; update the call in the loop to pass modelName (instead of
tableName) to mapStorageRowToModelFields, and while here, ensure
stripHiddenMappedFields is also called with modelName for consistency with
dispatchMutationRows (which uses modelName); adjust the arguments to use the
modelName variable so mappings and hidden-field stripping use the model
identity, not the physical table name.
🪄 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: 689d5dce-13ba-44ca-84f6-107387e79322

📥 Commits

Reviewing files that changed from the base of the PR and between 55c703b and 32c8302.

📒 Files selected for processing (8)
  • packages/3-extensions/sql-orm-client/src/collection-dispatch.ts
  • packages/3-extensions/sql-orm-client/src/collection-mutation-dispatch.ts
  • packages/3-extensions/sql-orm-client/src/collection.ts
  • packages/3-extensions/sql-orm-client/test/collection-mutation-dispatch.test.ts
  • test/integration/test/sql-orm-client/mutation-include-readback.test.ts
  • test/integration/test/sql-orm-client/nested-includes-strategy.test.ts
  • test/integration/test/sql-orm-client/nested-includes.test.ts
  • test/integration/test/sql-orm-client/update.test.ts
✅ Files skipped from review due to trivial changes (1)
  • test/integration/test/sql-orm-client/nested-includes.test.ts
🚧 Files skipped from review as they are similar to previous changes (2)
  • test/integration/test/sql-orm-client/update.test.ts
  • test/integration/test/sql-orm-client/nested-includes-strategy.test.ts

@aqrln aqrln left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

There are two failing CI pipelines right now @tensordreams

@tensordreams

Copy link
Copy Markdown
Contributor Author

Acknowledged — the one actionable finding in this review (the tableName → modelName fix in dispatchSplitMutationRows, collection-mutation-dispatch.ts 129-137) is tracked and replied to on the inline thread; it will be fixed in this PR. The remaining content is autofix/run-info boilerplate, nothing else to action.

@tensordreams

Copy link
Copy Markdown
Contributor Author

Acknowledged — will get CI green before this is ready. The two red pipelines should resolve as the streaming / lazy-transform fixes from this round land; will confirm both are green after pushing.

@tensordreams

Copy link
Copy Markdown
Contributor Author

Both failing pipelines are fixed and pushed (e39ba99): Lint — the noNonNullAssertion in collection-dispatch.ts (from the prior commit) is gone now that the identity dedup was removed. Fixtures — the failure was a pre-existing flake: side-by-side-contracts.test.ts's 'loads the fixture files from disk' inherited the 100ms package default for what is local disk I/O; it now uses timeouts.vitestPackageDefault. Unrelated to the read-back change.

@aqrln aqrln left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Splendid

…e read path

The multi-query include strategy and its JS-side stitcher were dead on
the read path once every supported SQL target became lateral/correlated-
capable (TML-2594/2595/2656). Rather than relocate the stitcher — which
the mutation read-back still imported — migrate that read-back onto the
single-query lateral/correlated builders so the entire stitcher chain
can be deleted with no in-tree caller remaining.

- include-strategy: narrow IncludeStrategy to 'lateral' | 'correlated';
  selectIncludeStrategy keys purely on the `lateral` capability.
- collection-dispatch: delete dispatchWithMultiQueryIncludes and the
  whole stitcher chain; add loadIncludesForMutationRows — one
  single-query read-back keyed by identity IN (...).
- collection-mutation-dispatch / collection: attach mutation includes
  via the read-back; delete/deleteAll + include read a pre-delete
  snapshot before issuing the DELETE.
- query-plan-select: remove compileRelationSelect (stitcher-only).
- tests: recast strategy cases to correlated, rewrite mutation-dispatch
  to the read-back shape, drop multi-query fallback tests, add PG
  integration coverage for create/update/delete + include.

Refs: TML-2657
Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
Collapse the trivial dispatchWithIncludeStrategy wrapper into
dispatchWithIncludes (single-query is the only include path now) and
rewrite the routing comment to describe the lateral/correlated split
in plain words instead of citing transient tickets.

Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
Drop the trailing transient-ticket reference from the
loadIncludesForMutationRows JSDoc; the one-round-trip identity-keyed
read-back is already described directly.

Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
State explicitly that the include snapshot is drained into an array
via .toArray() while the rows still exist, so the yielded iteration
walks an in-memory array rather than a cursor over deleted rows. No
change to execution order.

Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
This suite only exercises the default lateral contract; reword the
header to say so and point at nested-includes-strategy.test.ts for
cross-strategy coverage.

Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
After the multi-query path was removed only lateral and correlated
remain; correct the cross-strategy-equivalence wording accordingly.

Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
Replace arrayContaining with an exact toEqual over a deterministically
sorted array so a read-back identity column leaking into the public
payload fails the test.

Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
Add an integration suite exercising every write that can carry
`.include()` — create / createAll / update / updateAll / upsert (both
branches) / delete / deleteAll — plus to-one, to-many, nested, scalar
count(), and combine() relations.

Two conventions make these a stable safety net for the upcoming
read-back consolidation (TML-2657): explicit `.select(...)` projections
at every level (so adding a model field never silently shifts an
expected shape) and whole-object/array `toEqual` assertions (so a leaked
read-back identity column, a mis-keyed relation, or a dropped field all
fail loudly).

Refs: TML-2657
Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
`loadIncludesForMutationRows` was a second include read-back
implementation living alongside the read path: it compiled a single-
query include plan, drained it, re-keyed by identity, and grafted the
decoded relations onto the RETURNING-derived rows. That duplicated the
read path's compile / map / decode / hidden-strip logic and could drift
from it.

Collapse it. With includes, a mutation now returns only its identity
columns; those rows are reloaded through `dispatchCollectionRows` —
re-selecting the caller's projection plus the relations, keyed by
`identity IN (...)`, on the same runtime (same transaction) the mutation
ran on. Scalars therefore come from the read-back, not RETURNING, which
is identical within the transaction. Behavioural equivalence is now
structural: one read path, not two. This is the consolidation the read
path's delete snapshot and nested-mutation reload already use.

- collection-dispatch: replace loadIncludesForMutationRows with
  reloadMutationRowsByIdentities (a thin caller of dispatchCollectionRows);
  drop the now-dead grafting helpers (assignEmptyMutationIncludes,
  emptyIncludeValue).
- collection-mutation-dispatch: include branches reload via identities;
  no-include branches unchanged.
- collection: #augmentMutationSelection returns identity-only RETURNING
  when includes are present; thread selectedFields to the dispatchers.
- tests: include read-back is now covered by the mutation-include-readback
  integration suite; drop the unit cases that pinned the old grafting.

Refs: TML-2657
Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
Address review of the read-path consolidation:

- reloadMutationRowsByIdentities returns the read-path AsyncIterableResult
  directly instead of `.toArray()`; the dispatchers `yield*` it and the
  single-row path advances it once, so nothing buffers the read-back into
  an array only to re-stream it.
- buildIdentityInFilter no longer dedups identities in JS — they come
  straight from RETURNING and are unique by construction; the database
  evaluates the IN list (or the composite-key OR). Drops the now-dead
  uniqueByKey / identityKey helpers and the noNonNullAssertion on the
  single-column branch.
- dispatchSplitMutationRows: real fix — the no-includes branch mapped via
  `tableName` where `modelName` is required (wrong field mapping when they
  differ); it now also transforms each plan's rows lazily rather than
  buffering per plan.
- include-strategy: drop the stale parenthetical history note from the
  selectIncludeStrategy JSDoc.

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

- createAll() with include() resolving non-empty relations (the existing
  create-include test only proved an empty relation).
- nested create() and deep nested create() read-backs, with explicit
  projections at every level, in the mutation-include-readback suite.

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

"loads the side-by-side fixture files from disk" inherited the 100ms
package default; reading + parsing the fixtures is local I/O that flakes
on cold CI workers (the Fixtures pipeline timed out here). Use
vitestPackageDefault, the helper documented for this exact case. Pre-
existing flake, unrelated to the read-back change.

Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
@tensordreams
tensordreams force-pushed the tml-2657-sql-orm-remove-multi-query-include-strategy-from-read-path branch from e39ba99 to 2d5162c Compare May 29, 2026 15:11
@github-actions

Copy link
Copy Markdown

size-limit report 📦

Path Size
postgres / no-emit 134.46 KB (-0.58% 🔽)
postgres / emit 124.28 KB (-0.6% 🔽)
mongo / no-emit 73.92 KB (0%)
mongo / emit 68.7 KB (0%)

@aqrln
aqrln enabled auto-merge (rebase) May 29, 2026 15:14
@aqrln
aqrln merged commit ca70e71 into main May 29, 2026
20 checks passed
@aqrln
aqrln deleted the tml-2657-sql-orm-remove-multi-query-include-strategy-from-read-path branch May 29, 2026 15:21
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