Repository navigation
TML-2595: single-query include aggregates in SQL ORM client - #596
Conversation
|
Note Reviews pausedIt 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 Use the following commands to manage reviews:
Use the checkboxes below for quick actions:
📝 WalkthroughWalkthroughThis PR enables scalar aggregate selectors and combine() includes to compile and decode into a single SQL execution by changing wire decoding, removing descriptor-based dispatch gating, adding payload decoders, extending query-plan builders, and updating tests. ChangesSingle-query scalar and combine includes
Estimated code review effort🎯 4 (Complex) | ⏱️ ~60 minutes Possibly related PRs
Suggested reviewers
Poem
🚥 Pre-merge checks | ✅ 4 | ❌ 1❌ Failed checks (1 warning)
✅ Passed checks (4 passed)
✏️ Tip: You can configure your own custom pre-merge checks in the settings. ✨ Finishing Touches📝 Generate docstrings
🧪 Generate unit tests (beta)
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
ESLint skipped: no ESLint configuration detected in root package.json. To enable, add 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. Comment |
@prisma-next/extension-author-tools
@prisma-next/mongo-runtime
@prisma-next/family-mongo
@prisma-next/sql-runtime
@prisma-next/family-sql
@prisma-next/extension-arktype-json
@prisma-next/extension-cipherstash
@prisma-next/middleware-cache
@prisma-next/mongo
@prisma-next/extension-paradedb
@prisma-next/extension-pgvector
@prisma-next/extension-postgis
@prisma-next/postgres
@prisma-next/sql-orm-client
@prisma-next/sqlite
@prisma-next/target-mongo
@prisma-next/adapter-mongo
@prisma-next/driver-mongo
@prisma-next/contract
@prisma-next/utils
@prisma-next/config
@prisma-next/errors
@prisma-next/framework-components
@prisma-next/operations
@prisma-next/ts-render
@prisma-next/contract-authoring
@prisma-next/ids
@prisma-next/psl-parser
@prisma-next/psl-printer
@prisma-next/cli
@prisma-next/cli-telemetry
@prisma-next/emitter
@prisma-next/migration-tools
prisma-next
@prisma-next/vite-plugin-contract-emit
@prisma-next/mongo-codec
@prisma-next/mongo-contract
@prisma-next/mongo-value
@prisma-next/mongo-contract-psl
@prisma-next/mongo-contract-ts
@prisma-next/mongo-emitter
@prisma-next/mongo-schema-ir
@prisma-next/mongo-query-ast
@prisma-next/mongo-orm
@prisma-next/mongo-query-builder
@prisma-next/mongo-lowering
@prisma-next/mongo-wire
@prisma-next/sql-contract
@prisma-next/sql-errors
@prisma-next/sql-operations
@prisma-next/sql-schema-ir
@prisma-next/sql-contract-psl
@prisma-next/sql-contract-ts
@prisma-next/sql-contract-emitter
@prisma-next/sql-lane-query-builder
@prisma-next/sql-relational-core
@prisma-next/sql-builder
@prisma-next/target-postgres
@prisma-next/target-sqlite
@prisma-next/adapter-postgres
@prisma-next/adapter-sqlite
@prisma-next/driver-postgres
@prisma-next/driver-sqlite
commit: |
There was a problem hiding this comment.
Actionable comments posted: 1
♻️ Duplicate comments (1)
packages/3-extensions/sql-orm-client/src/collection-dispatch.ts (1)
571-607:⚠️ Potential issue | 🟠 Major | ⚡ Quick winDon't silently coerce malformed scalar/combine payloads to empty results.
For non-null payloads, an unexpected envelope shape here currently becomes
0/null/ empty branch data instead of a decode failure. That hides planner/query regressions behind plausible-looking results and can silently corrupt user-visible data. Please fail loudly once a parsed payload is present but is not the declared scalar/combine shape.🤖 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 571 - 607, The current helpers silently coerce malformed non-null include payloads into empty results; instead, in parseCombineEnvelope and decodeScalarIncludePayload detect and fail loudly when parseIncludePayload(raw) returns a value that is not the expected envelope shape. Keep the existing early-return behavior for raw === null/undefined (return undefined from parseCombineEnvelope and emptyScalarResult(scalar.fn) in decodeScalarIncludePayload), but if parseIncludePayload(raw) yields a non-null/non-array non-object or an object that lacks the expected envelope keys (e.g. parseCombineEnvelope expects a Record<string,unknown>, decodeScalarIncludePayload expects an object with a defined value field), throw a descriptive TypeError (including the function name and the unexpected parsed shape) instead of calling emptyScalarResult or returning undefined; reference parseIncludePayload, parseCombineEnvelope, decodeScalarIncludePayload, and emptyScalarResult when applying this change so the failure surface is consistent and debuggable.
🤖 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/query-plan-select.ts`:
- Around line 641-664: The child scalar select is incorrectly including cursor
bounds because buildStateWhere(contract, childTableRef, scalar.state, {
filterTableName: include.relatedTableName }) currently folds cursor into
childWhere; change buildIncludeChildScalarSelect to call buildStateWhere with a
state that has cursor removed (or pass an option to ignore cursor) so the
childWhere reflects filters but not cursor pagination, and add a regression test
mirroring the existing take/skip test that verifies include(..., p =>
p.orderBy(...).cursor(...).count()) returns the full pre-cursor aggregate.
---
Duplicate comments:
In `@packages/3-extensions/sql-orm-client/src/collection-dispatch.ts`:
- Around line 571-607: The current helpers silently coerce malformed non-null
include payloads into empty results; instead, in parseCombineEnvelope and
decodeScalarIncludePayload detect and fail loudly when parseIncludePayload(raw)
returns a value that is not the expected envelope shape. Keep the existing
early-return behavior for raw === null/undefined (return undefined from
parseCombineEnvelope and emptyScalarResult(scalar.fn) in
decodeScalarIncludePayload), but if parseIncludePayload(raw) yields a
non-null/non-array non-object or an object that lacks the expected envelope keys
(e.g. parseCombineEnvelope expects a Record<string,unknown>,
decodeScalarIncludePayload expects an object with a defined value field), throw
a descriptive TypeError (including the function name and the unexpected parsed
shape) instead of calling emptyScalarResult or returning undefined; reference
parseIncludePayload, parseCombineEnvelope, decodeScalarIncludePayload, and
emptyScalarResult when applying this change so the failure surface is consistent
and debuggable.
🪄 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: e83cdf07-72b2-43b4-95f7-0b632bae2b56
⛔ Files ignored due to path filters (2)
projects/sql-orm-include-aggregates/plan.mdis excluded by!projects/**projects/sql-orm-include-aggregates/spec.mdis excluded by!projects/**
📒 Files selected for processing (7)
packages/2-sql/5-runtime/src/codecs/decoding.tspackages/3-extensions/sql-orm-client/src/collection-dispatch.tspackages/3-extensions/sql-orm-client/src/include-tree-predicates.tspackages/3-extensions/sql-orm-client/src/query-plan-select.tspackages/3-extensions/sql-orm-client/test/query-plan-select.test.tstest/integration/test/sql-orm-client/include.test.tstest/integration/test/sql-orm-client/nested-includes-strategy.test.ts
💤 Files with no reviewable changes (1)
- packages/3-extensions/sql-orm-client/src/include-tree-predicates.ts
There was a problem hiding this comment.
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/query-plan-select.ts`:
- Around line 720-739: The ROW_NUMBER dedup branch (using
wrapWithRowNumberDedup) currently drops the original remappedOrderBy before
pagination; restore the ordering by carrying the hidden order projections
through the wrapper and re-applying remappedOrderBy to the wrapped select before
applying limit/offset. Concretely, after calling wrapWithRowNumberDedup (the
call that produces rankedAlias), ensure the returned inner has remappedOrderBy
applied via inner.withOrderBy(remappedOrderBy) (or equivalent) so that
pagination (state.limit/state.offset with inner.withLimit/withOffset) happens on
the ordered deduped rows; keep references to remappedOrderBy, rankedAlias and
wrapWithRowNumberDedup to locate and modify the code.
🪄 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: 49aa5586-7482-46bc-9091-258de8b655e0
⛔ Files ignored due to path filters (3)
projects/sql-orm-include-aggregates/design-decisions.mdis excluded by!projects/**projects/sql-orm-include-aggregates/plan.mdis excluded by!projects/**projects/sql-orm-include-aggregates/spec.mdis excluded by!projects/**
📒 Files selected for processing (5)
packages/3-extensions/sql-orm-client/src/collection-dispatch.tspackages/3-extensions/sql-orm-client/src/query-plan-select.tspackages/3-extensions/sql-orm-client/test/query-plan-select.test.tstest/integration/test/sql-orm-client/include.test.tstest/integration/test/sql-orm-client/nested-includes-strategy.test.ts
🚧 Files skipped from review as they are similar to previous changes (4)
- test/integration/test/sql-orm-client/nested-includes-strategy.test.ts
- test/integration/test/sql-orm-client/include.test.ts
- packages/3-extensions/sql-orm-client/src/collection-dispatch.ts
- packages/3-extensions/sql-orm-client/test/query-plan-select.test.ts
14decf6 to
e50f092
Compare
…lude aggregates Slice closes TML-2595, TML-2588, TML-2498 in one PR by lowering include-scalar reducers (count/sum/avg/min/max) and combine() branches into the active single-query strategy (LATERAL on Postgres, correlated subquery on SQLite). TML-2498 is resolved by construction: aggregate scope is the where-filtered, unpaginated relation, matching root aggregate() semantics. Follow-ups tracked separately: TML-2657 (multi-query deletion, blocked by this slice merging); TML-2683 (polymorphic-target includes silently degrade — surfaced from this spec's design-discussion as a pre-existing gap, blocked by TML-2657). Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
…mposition Decomposes the slice into three M-sized dispatches: D1 lateral scalar reducers (count/sum/avg/min/max), D2 lateral combine() packing, D3 correlated mirror + lift gates + delete dead predicate. Each dispatch leaves the working tree green and ships an incrementally larger slice; correlated targets keep falling back to multi-query through D1+D2 and converge with lateral at D3. Threads F3/F4/F5 from failure-modes.md, the cross-cutting grep gates from grep-library.md, and per-dispatch model-tier choices from model-tier.md. Slice-DoD items mapped to specific dispatches; mid-dispatch I12 halt triggers pre-named for the four spec open questions. Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
Lateral combine() packing carries unresolved design surface that may settle mid-implementation (NULL/empty-relation handling location; branch-level WHERE reuse; spec Open Q 3 escape-hatch). Per model-tier.md non-fit row, routes to orchestrator tier rather than Sonnet. Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
…ucers Adds red unit-test cases for the lateral builder emitting json-wrapped AggregateExpr (count / sum / avg / min / max) over the where-filtered unpaginated relation, plus carved planner-throw cases that distinguish combine (still rejected) from scalar (accepted under lateral; still rejected under correlated). TML-2498 assertion (LIMIT/OFFSET from take()/skip() must not enter COUNT scope) is explicit. Nested-scalar-in-row-include emits its own LATERAL inside the parent row SELECT. Tests are red against current HEAD; implementation lands next. Refs TML-2595, TML-2588, TML-2498. Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
…query
Adds `buildIncludeChildScalarSelect` to the lateral builder. For each
scalar include descriptor (`count` / `sum` / `avg` / `min` / `max`) we
emit a `LEFT JOIN LATERAL (SELECT json_build_object('value', AGG(...)))`
correlated to the parent via the FK, scoped by the user-supplied
`where` only. `take` / `skip` from the refine are intentionally NOT
applied to the aggregate scope — that is the TML-2498 fix, baked in
by construction.
The JSON envelope lets the scalar value flow through the existing
include-payload decoder; the new `decodeScalarIncludePayload` branch
unwraps `.value` and applies the empty-relation default
(`0` for count, `null` for sum/avg/min/max). No JS-side `Number()`
coercion is introduced — JSON-level decoding handles the type.
Carves the dispatch gate in `dispatchWithIncludeStrategy` and the
planner throw in `compileSelectWithIncludeStrategy` to be
strategy-aware: combine still routes everywhere to multi-query
(D2 lifts), and correlated still falls back for scalar (D3 mirrors
emission).
Adds two sibling predicates (`hasScalarIncludeDescriptors`,
`hasCombineIncludeDescriptors`) alongside the existing combined
predicate (kept for downstream callers that want the union).
Refs TML-2595, TML-2588, TML-2498.
Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
…one SQL execution Flips the scalar `count()` / `sum()` integration tests from `toHaveLength(2)` (multi-query stitch) to `toHaveLength(1)` (lateral single-query). Flips the nested-scalar-at-depth-2 test (under lateral capabilities) from `toBeGreaterThan(1)` to `toHaveLength(1)` — the recursive predicate now lets the leaf fan out naturally. Adds an explicit TML-2498 regression test: `where().take().count()` on an include must return the unpaginated total. With 5 seed posts where 4 match the filter, the lateral builder ignores `take(2)` and returns 4, in 1 SQL execution. Combine() integration tests retain `toBeGreaterThan(1)` — combine still routes to multi-query until D2 / D3 land. Refs TML-2595, TML-2588, TML-2498. Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
…ce comments Per AGENTS.md ban on transient project IDs in code: rewrite D1/D2/D3 attributions in source / test comments to describe the constraint (which builder handles which descriptor) rather than the artefact that introduced it. No behaviour change. Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
…pen items Two decisions surfaced during D1 R1 review now have traceable homes: (1) bigint precision via codec routing deferred to TML-2684 with explicit trade-off grounds (JSON-envelope path is correct for the practical-cases majority; prior multi-query stitcher also bypassed the codec layer; decimal-precision is a bigger codec-routing question crossing root-level aggregate() too). (2) Suite-stability flake claim accepted as pre-existing environmental, recommended as a separate team ticket not owned by this slice. Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
…packing Red unit-test cases for the lateral combine builder. Refs TML-2595, TML-2588. Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
Adds buildIncludeChildCombineSelect to the lateral builder. For each
combine({ a, b, ... }) descriptor we emit one LEFT JOIN LATERAL whose
inner SELECT cross-joins per-branch derived tables and projects
json_build_object packing each branch by name. Branches share the
parent FK correlation transparently because the outer LATERAL scopes
to the parent SELECT.
Per-branch shape:
- Row branch: standard json_agg-of-json_build_object inner SELECT
(extracted as buildIncludeChildRowsAggregateSelect so both the
standalone row LATERAL and combines row branches share it).
- Scalar branch: D1s json_build_object(value, AGG(...)) envelope.
The envelope nests inside the combine outer json_build_object as
a sub-object; the decoder unwraps .value per scalar branch.
Distinct / take / skip inside a row branch fan out naturally because
the row builder is invoked with a synthetic IncludeExpr whose nested
state is the branchs state. No combine-specific distinct handling.
Carves the dispatch gate in dispatchWithIncludeStrategy and the
planner throws in compileSelectWithIncludeStrategy:
- Lateral now admits combine at any depth.
- Correlated still throws on scalar and on combine, with messages
scoped to the correlated strategy (D3 mirrors emission).
Removes the per-node defensive throw in decodeIncludePayload that
rejected nested combine. The recursive decode now dispatches on the
descriptor kind at every level.
Refs TML-2595, TML-2588.
Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
…QL execution
Flips the existing combine() integration tests from toHaveLength(4)
(multi-query stitcher: parent + N branches) to toHaveLength(1) (one
LATERAL packing branches via json_build_object).
Adds the TML-2595 worked example explicitly: combine({ recent: take(3),
count: count() }) over 4 posts for the parent. Asserts the count is
the unpaginated total (4) and the recent branch returns 3 rows in a
single execution.
Flips nested-includes-strategy.test.ts top-level-combine assertion
from toBeGreaterThan(1) to toHaveLength(1); updates the surrounding
describe block comment to reflect the new carve-out (lateral admits
both scalar and combine at any depth).
Refs TML-2595, TML-2588.
Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
…ck comment The combine() describe-block comment introduced in this dispatch referenced "the D1 scalar builder". Rephrase to "the standalone scalar builder" per the no-transient-project-ids-in-code rule. No behaviour change. Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
… and combine() packing
Adds red unit-test cases for the correlated builder mirroring D1+D2s
lateral-side coverage:
- Each scalar reducer (count / sum / avg / min / max) lowers to a
correlated subquery whose projection is the same
json_build_object(value, AGG(...)) envelope as lateral.
- TML-2498 mirror: take()/skip() do not enter the correlated
aggregates scope.
- Nested scalar inside a row include emits a nested correlated
subquery inside the parent row aggregation.
- combine({ rows, scalar }), two-scalar combine, and divergent-where
combine all pack into a single correlated subquery whose FROM
cross-joins per-branch derived tables and projects json_build_object
packing each branch.
Deletes the three planner-throw assertion tests for correlated. The
planner no longer throws on scalar or combine descriptors under any
strategy.
Tests are red against current HEAD; implementation lands next.
Refs TML-2595, TML-2588, TML-2498.
Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
…orrelated builder; remove dispatch gate and predicate file Extends buildCorrelatedIncludeProjection with scalar and combine branches that reuse buildIncludeChildScalarSelect and buildIncludeChildCombineSelect verbatim, wrapped in SubqueryExpr in the outer projection (the correlated analogue of the lateral builders LEFT JOIN LATERAL). Threads the strategy parameter through buildIncludeChildCombineSelect, buildIncludeChildCombineBranchSelect, and buildIncludeChildRowsAggregateSelect. Previously the row-aggregate helper hardcoded lateral, which would have emitted LATERAL primitives inside the correlated row path (the broken combination correlated capability assumes never exists). Now the strategy threads end-to-end. Removes the strategy-aware dispatch gate in dispatchWithIncludeStrategy that routed non-lateral + (scalar | combine) to multi-query. Both single-query builders handle every include shape; dispatch is purely capability-driven. Removes the planner throws in compileSelectWithIncludeStrategy that rejected combine and scalar under correlated. The planner no longer has any entry-level rejection. Deletes packages/3-extensions/sql-orm-client/src/include-tree-predicates.ts. All three predicates (hasScalarOrCombineIncludeDescriptors, hasScalarIncludeDescriptors, hasCombineIncludeDescriptors) are now unused; the import sites in collection-dispatch.ts and query-plan-select.ts are also removed. The multiQuery strategy arm and the multi-query dispatch path are preserved (unreachable from real targets but still in tree pending separate cleanup). Refs TML-2595, TML-2588, TML-2498. Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
…, not only arrays decodeIncludeAggregate is the runtime pre-parser for projection items whose expression kind is subquery or json-array-agg. Until now it asserted the parsed value must be an array, which held while every include projection was a row-aggregate (json_agg returning a JSON array). The single-query correlated builder now also emits scalar reducers and combine() descriptors as projection-level correlated subqueries whose value is a JSON object (json_build_object envelope). The array assertion rejected those with "Expected array for include alias". Widen the function to pre-parse the wire JSON (string → JSON.parse; already-parsed object → pass through) without asserting shape. Shape is the downstream decoder is responsibility — decodeIncludePayload in sql-orm-client dispatches on the IncludeExpr descriptor type and applies the per-shape decode (rows array, scalar value extract, combine sub-object walk). No behaviour change for existing row-include paths: an array wire value still flows through unchanged. Removes the now-incorrect array-shape assertion that would otherwise reject scalar / combine correlated payloads at the runtime boundary. Refs TML-2595, TML-2588. Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
…es mirroring the lateral coverage
Adds correlated single-query integration tests against CORRELATED_CAPABILITIES
(jsonAgg without lateral) hitting PGlite for end-to-end validation:
- scalar count() resolves in 1 execution under correlated capabilities
- TML-2498 mirror: count().take() returns the unpaginated total
- combine({ rows, count }) resolves in 1 execution under correlated
capabilities (the Pothos totalCount worked example, mirrored)
The CORRELATED_CAPABILITIES contract advertises jsonAgg without
lateral, so the strategy selector routes through the correlated
builder while still running against a real PG database.
Updates the surrounding describe blocks documentation to reflect
the post-D3 state: both single-query builders lower every include
descriptor shape; dispatch routes purely on capability flags.
Refs TML-2595, TML-2588, TML-2498.
Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
…ice falsified-assumption amendment TML-2498 was filed under the assumption that take(n).count() returning n-or-less under include is a silent miscount, and the slice was specified to fix it by emitting the aggregate over the where-filtered, unpaginated relation. During PR self-review the author re-read TML-2498 and concluded the framing was wrong: take(n).count() returning <=n is the natural compositional semantic of the refine chain. The ticket was closed as not-a-bug. Amends spec.md (edge-case row, Approach SQL example, SDoD3 sub-bullet, References), plan.md (D1 intent, edge-case coverage, slice-DoD mapping, post-slice handoff), and introduces design-decisions.md with the full I12 trail. Implementation reversal lands as part of A05 in the PR-review iteration loop alongside A01-A04 from the same review pass. Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
…eCombineIncludePayload Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
…r switch Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
The combine LATERAL / correlated subquery is built to always produce a single JSON object envelope. A missing envelope, an array, or any other non-object shape arriving in decodeCombineIncludePayload indicates a planner or decoder bug, not data variability — surface it as an Error naming the relation rather than papering over it with an empty per-branch shape (the only legitimate empty-envelope path bypasses the decoder via assignEmptyIncludeResult). Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
…r scalar reducers decodeScalarIncludePayload previously applied the empty-relation default in JS — '0' for count, 'null' for sum/avg/min/max — guarding both against a null raw envelope and against a null 'value' inside the envelope. The inner guard is dead: SQL semantics already drive both defaults. COUNT(*) over an empty input set returns 0 (never null); SUM / AVG / MIN / MAX over an empty input set return SQL NULL, which is exactly the documented null-in-TS default for those reducers. Drop the inner value-fallback and pass the parsed JSON 'value' through unchanged. The outer 'raw === null' branch stays as defensive cover. Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
… scope
The compositional semantic of
db.User.include('posts', p => p.where(W).take(N).count())
is that 'take(N)' shapes the row set the aggregate sees, so the result
is at most N. Update buildIncludeChildScalarSelect to honour that: when
the refine state carries take/skip/distinct, wrap the source in a
derived inner SELECT that materialises the paginated/deduped row set,
then aggregate over that. A top-level LIMIT on the aggregating SELECT
would only trim the (already one-row) output, not the rows being
aggregated, so the wrap is the only correct shape.
orderBy alone (no take/skip/distinct) stays dropped at the SQL level
since reordering does not change which rows are aggregated. Combine
scalar branches inherit the new shape via the existing dispatch in
buildIncludeChildCombineBranchSelect.
Tests: unit assertions for "LIMIT/OFFSET in COUNT scope" inverted to
prove the new shape (outer aggregating SELECT, inner derived table
carrying where + limit + offset). Integration assertions inverted to
match: with 5 seed posts where 4 match the filter and take(2), the
new expected count is 2, in 1 SQL execution.
Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
decodeScalarIncludePayload previously soft-handled an array or other
non-object envelope by returning the empty-relation default, mirroring
the pre-A03 parseCombineEnvelope behaviour. The scalar envelope is
built as json_build_object('value', AGG(...)) — always an object — so
arriving here with an array or primitive indicates a planner or
decoder bug, not data variability.
Mirror A03's strict shape gate: throw an Error naming the include
relation and the actual shape. The outer raw === null/undefined guard
stays — that is the legitimate assignEmptyIncludeResult no-LATERAL-row
short-circuit path.
Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
…in scalar path
The scalar include path wraps the source in a derived inner SELECT
when the refine state carries pagination or distinct, then aggregates
over that. For Prisma-style .distinct(cols), the wrap uses
wrapWithRowNumberDedup — which strips orderBy / limit from its base
and only encodes the partitioning. After the wrap returns, the outer
of the wrap has no contract about row order, so a subsequent
inner.withLimit(N) slices an implementation-defined subset.
For SUM / AVG / MIN / MAX over distinct(cols).orderBy(c).take(N), that
means aggregating an arbitrary N rows instead of the ordered top-N
— a real correctness bug surfaced by the round-1 reversal that
promoted pagination from "stripped at SQL level" to "composes through
to the aggregate scope".
The row-include lowering already does the right thing at
buildIncludeChildRowsSelect lines 429-454: project hidden order
columns through the wrap, then reapply withOrderBy on the wrapped
alias before LIMIT / OFFSET. Mirror that pattern in the scalar path:
build a hidden-order projection conditionally (only when distinct is
set with an orderBy), thread it through the wrap, and reapply
orderBy via ColumnRef.of(rankedAlias, "${relationName}__order_${idx}").
buildIncludeChildScalarSelect is shared by the lateral and correlated
strategies, so the single fix covers both paths. Combine scalar
branches inherit via the existing dispatch in
buildIncludeChildCombineBranchSelect.
Tests: unit assertions on both lateral and correlated strategies pin
the post-wrap inner SELECT has orderBy referencing the ranked alias
hidden column, plus the limit on the same scope. Integration tests on
both paths seed posts where the ordered-top-N sum (700) is distinct
from any plausible insertion-order slice (500 under the unfixed code)
to catch regressions end-to-end.
Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
D1's content (the TML-2498 reversal trail) lives in spec.md § Open Questions § 1 (resolved-mid-slice note) and in the PR description's § Alternatives considered. The transient slice-execution log is no longer load-bearing; delete it. spec.md and plan.md still reference design-decisions.md (link rot) — left to the orchestrator per the round-2 brief's read-only constraint on those files. The orchestrator will rewrite the references inline. Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
… at slice close-out Per the team projects/ lifecycle, the spec and plan are transient working artefacts; the durable trail lives in the PR description, commit messages, and Linear. Cleaning them up in this PR rather than a separate close-out PR. design-decisions.md was already removed in d53a5b4. The reviews/ subdirectory is gitignored and stays on disk locally. Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
…stead of bare as Replaces the two bare `as` casts the loud-throw envelope guards (parseCombineEnvelope at L588 and decodeScalarIncludePayload at L634) introduced. Extracts isPlainObjectEnvelope(value): value is Record<string, unknown> as the shared narrowing predicate so the post-throw branch is automatically narrowed by TypeScript — eliminating the casts per AGENTS.md (prefer explicit types over casts) and clearing the lint:casts ratchet (delta=0). value access on the narrowed Record<string, unknown> uses bracket notation (parsed["value"]) per the strictTypeAccessFromIndexSignature compiler setting. Signed-off-by: Alexey Orlenko's AI Agent <[email protected]>
e50f092 to
2d6cf71
Compare
There was a problem hiding this comment.
Actionable comments posted: 0
Caution
Some comments are outside the diff and can’t be posted inline due to platform limitations.
⚠️ Outside diff range comments (2)
packages/2-sql/5-runtime/src/codecs/decoding.ts (1)
122-122:⚠️ Potential issue | 🟡 Minor | ⚡ Quick winUpdate error message to reflect both array and object includes.
The error message says "JSON array" but
decodeIncludeAggregatenow handles both row include arrays (json_agg) and scalar/combine include envelopes (json_build_object) as noted in the comment at lines 144-145.💬 Proposed fix
- `Failed to parse JSON array for include alias '${alias}': ${message}`, + `Failed to parse JSON value for include alias '${alias}': ${message}`,🤖 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/2-sql/5-runtime/src/codecs/decoding.ts` at line 122, Update the error text in decodeIncludeAggregate to mention both JSON array and object include envelopes instead of only "JSON array"; locate the failure case that currently builds the message using the alias variable (the string starting with "Failed to parse JSON array for include alias ...") and change it to a more generic phrase such as "Failed to parse JSON include for alias '${alias}': ${message}'" so it covers row include arrays (json_agg) and scalar/object envelopes (json_build_object).packages/3-extensions/sql-orm-client/test/query-plan-select.test.ts (1)
1-1237: 🛠️ Refactor suggestion | 🟠 Major | 🏗️ Heavy liftSplit test file to comply with 500-line guideline.
This test file is 1237 lines, significantly exceeding the 500-line limit. The file should be split into multiple files by logical functionality to improve readability and navigability.
Suggested split structure using the pattern
query-plan-select.{category}.test.ts:
query-plan-select.basic.test.ts— cursor pagination, orderBy, extension operations, relation selects (lines ~65-348)query-plan-select.scalar-includes.test.ts— lateral and correlated scalar reducer tests (lines ~350-997)query-plan-select.combine-includes.test.ts— lateral and correlated combine() packing tests (lines ~999-1112)query-plan-select.mti.test.ts— MTI JOIN tests (lines ~1115-1237)Each split file must include all necessary imports, helper functions (e.g.,
codecForColumn,paramCodecs,expectSelectAst), and test fixtures to be independently runnable.As per coding guidelines, split at the natural boundaries defined by the top-level
describeblocks and the nested sub-describeblocks for scalar/combine strategies.🤖 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/query-plan-select.test.ts` around lines 1 - 1237, The test file is too large — split it into multiple test files by the top-level describe blocks and nested suites: create query-plan-select.basic.test.ts containing the "compileSelectWithIncludeStrategy" tests that cover cursor pagination, orderBy, extension operations and relation selects (include tests up to before "lateral scalar reducers"); query-plan-select.scalar-includes.test.ts containing the "lateral scalar reducers" and "correlated scalar reducers" suites; query-plan-select.combine-includes.test.ts containing the "lateral combine() packing" and "correlated combine() packing" suites; and query-plan-select.mti.test.ts containing the "compileSelect MTI JOINs" suite. For each new file, copy required imports and helper functions (codecForColumn, paramCodecs, expectSelectAst, expectSubqueryExpr, expectDerivedTableSource, extract helpers, createCollection/createCollectionFor, baseContract, buildMixedPolyContract, emptyState, bindWhereExpr) so each file is independently runnable and keep the original test names and assertions (functions referenced: compileSelectWithIncludeStrategy, compileSelect, compileRelationSelect, AggregateExpr, OrderByItem, ProjectionItem, SelectAst, JoinAst, ColumnRef, BinaryExpr, AndExpr, OrExpr, ListExpression, JsonObjectExpr, OperationExpr, ParamRef, SubqueryExpr). Ensure split points follow the nested describe boundaries exactly and export no additional symbols.
🤖 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/2-sql/5-runtime/src/codecs/decoding.ts`:
- Line 122: Update the error text in decodeIncludeAggregate to mention both JSON
array and object include envelopes instead of only "JSON array"; locate the
failure case that currently builds the message using the alias variable (the
string starting with "Failed to parse JSON array for include alias ...") and
change it to a more generic phrase such as "Failed to parse JSON include for
alias '${alias}': ${message}'" so it covers row include arrays (json_agg) and
scalar/object envelopes (json_build_object).
In `@packages/3-extensions/sql-orm-client/test/query-plan-select.test.ts`:
- Around line 1-1237: The test file is too large — split it into multiple test
files by the top-level describe blocks and nested suites: create
query-plan-select.basic.test.ts containing the
"compileSelectWithIncludeStrategy" tests that cover cursor pagination, orderBy,
extension operations and relation selects (include tests up to before "lateral
scalar reducers"); query-plan-select.scalar-includes.test.ts containing the
"lateral scalar reducers" and "correlated scalar reducers" suites;
query-plan-select.combine-includes.test.ts containing the "lateral combine()
packing" and "correlated combine() packing" suites; and
query-plan-select.mti.test.ts containing the "compileSelect MTI JOINs" suite.
For each new file, copy required imports and helper functions (codecForColumn,
paramCodecs, expectSelectAst, expectSubqueryExpr, expectDerivedTableSource,
extract helpers, createCollection/createCollectionFor, baseContract,
buildMixedPolyContract, emptyState, bindWhereExpr) so each file is independently
runnable and keep the original test names and assertions (functions referenced:
compileSelectWithIncludeStrategy, compileSelect, compileRelationSelect,
AggregateExpr, OrderByItem, ProjectionItem, SelectAst, JoinAst, ColumnRef,
BinaryExpr, AndExpr, OrExpr, ListExpression, JsonObjectExpr, OperationExpr,
ParamRef, SubqueryExpr). Ensure split points follow the nested describe
boundaries exactly and export no additional symbols.
ℹ️ Review info
⚙️ Run configuration
Configuration used: Path: .coderabbit.yml
Review profile: CHILL
Plan: Pro
Run ID: 795bde10-4a35-47ae-8916-aaadf87d6951
📒 Files selected for processing (7)
packages/2-sql/5-runtime/src/codecs/decoding.tspackages/3-extensions/sql-orm-client/src/collection-dispatch.tspackages/3-extensions/sql-orm-client/src/include-tree-predicates.tspackages/3-extensions/sql-orm-client/src/query-plan-select.tspackages/3-extensions/sql-orm-client/test/query-plan-select.test.tstest/integration/test/sql-orm-client/include.test.tstest/integration/test/sql-orm-client/nested-includes-strategy.test.ts
💤 Files with no reviewable changes (1)
- packages/3-extensions/sql-orm-client/src/include-tree-predicates.ts
🚧 Files skipped from review as they are similar to previous changes (4)
- test/integration/test/sql-orm-client/include.test.ts
- test/integration/test/sql-orm-client/nested-includes-strategy.test.ts
- packages/3-extensions/sql-orm-client/src/query-plan-select.ts
- packages/3-extensions/sql-orm-client/src/collection-dispatch.ts
Linked issue
Closes TML-2595, TML-2588 on merge.
Follow-ups filed during slice design + execution:
.include()silently degrades on polymorphic target models (pre-existing gap surfaced from this slice's design discussion).TML-2498 was initially in scope and would have closed on merge; reversed mid-slice during PR self-review and closed by the author as not-a-bug (see § Alternatives considered).
Summary
Lower include-scalar reducers (
count/sum/avg/min/max) andcombine()branches into the active single-query include strategy (LATERAL on Postgres, correlated subquery on SQLite + any future jsonAgg-capable target) instead of falling back to the multi-query stitcher. The aggregate runs over the refine's full state —where,take,skip,orderBy,distinctall compose through to the scalar scope, matching the natural pipeline semantic. After this PR merges, the multi-query include path is dead-on-read for every in-tree real-target contract — TML-2657 cleans it up as a follow-up.At a glance
The Pothos
totalCountconnection shape is the headline use case. Fromtest/integration/test/sql-orm-client/include.test.ts:Before this PR: 3 SQL executions per page (parent + recent + count, stitched in JS). After: 1 execution (parent + one LATERAL packing both branches into a single
json_build_object).SQL emission examples
Three illustrative shapes (column lists trimmed and aliases lightly renamed for legibility):
1. Lateral path —
combine({ recent: r.take(3), total: r.count() })on Postgres. One execution; both branches packed under onejson_build_object.2. Correlated path — same shape on SQLite (and any other jsonAgg-capable, LATERAL-less target).
json_build_objectbecomesjson_object;json_aggbecomesjson_group_array; the LATERAL becomes a correlated subquery in the projection.3. Compositional depth —
distinct(cols).orderBy(col).take(N).sum(field). This is the shape that exercises the full refine-state composition: dedup via ROW_NUMBER, reapply the user's order on the deduped set, take the top N, then aggregate. The reapply-orderBy-after-dedup step is load-bearing — without it, the aggregate would run over an arbitrary N-row slice instead of the ordered top N. (See § Notes for the reviewer item 5.)The innermost SELECT carries the FK correlation + ROW_NUMBER for the distinct-cols partitioning. The middle SELECT propagates the hidden order column through the dedup wrap and reapplies the user's ORDER BY + LIMIT (this is the ordering you'd lose if you applied LIMIT directly to the aggregating SELECT). The outermost SELECT runs the aggregate over the deduped, ordered, paginated derived table.
How it fits together
The work decomposed into three sequential dispatches, each landing one PR-internal commit cluster + a self-review round at the end.
Lateral scalar reducers. Extended
buildLateralIncludeArtifactsinquery-plan-select.tsto emit scalar branches asLEFT JOIN LATERAL (SELECT json_build_object('value', AGG(...)) ...). The dispatch gate indispatchWithIncludeStrategymoved from a single overloadedhasScalarOrCombineIncludeDescriptorsto two sibling predicates (hasScalarIncludeDescriptors,hasCombineIncludeDescriptors) so the carve could be strategy-aware: lateral-strategy targets with scalar-only descriptors route through single-query; correlated-strategy and any combine still fell back to multi-query. The decoder learned to unwrap the JSON envelope on the scalar branch.Lateral
combine()packing. Extended the same builder forcombine({...}): each branch becomes a derived table cross-joined into one outer LATERAL, with ajson_build_objectpacking all branches under one key (row-shaped and scalar-shaped coexist). The dispatch gate extended to admit lateral combine; the decoder gained adecodeCombineIncludePayloadthat unpacks the sub-object into branch-keyed values.Correlated mirror + cleanup. Mirrored both shapes into
buildCorrelatedIncludeProjection— same SQL primitives, wrapping difference (SubqueryExpr.of(...)in the projection rather thanLEFT JOIN LATERAL ... ON TRUE). The strategy-aware dispatch gate, the per-strategy planner throws, and the gating predicate file itself became fully redundant — all three removed in this dispatch.A subsequent self-review round addressed eight reviewer comments across two passes. Notably:
The TML-2498 reversal. The slice was initially specified to "fix TML-2498's silent count miscount under
take/skip" by emitting the aggregate over the where-filtered, unpaginated relation. On re-reading TML-2498 during PR self-review, the author concluded the framing was a misreading —take(N).count()returning ≤ N is the natural compositional semantic of refine chaining, not a bug. The implementation now appliestake/skip/distinct/orderByfrom the refine state to the scalar inner SELECT via a wrap-derived-select shape (see § Notes for the reviewer item 2). TML-2498 was closed as not-a-bug. The Pothoscombine({ recent: r.take(N), total: r.count() })shape composes correctly under the new semantic:recentcarries the take,totaldoesn't.The reapply-orderBy-after-dedup correctness fix (item 5 below) — surfaced by CodeRabbit; promoted from latent to active by the TML-2498 reversal.
Notes for the reviewer
A few things I expect a careful reviewer to push back on, surfaced proactively:
JSON-envelope wire format for scalars bypasses the codec layer. Scalars ride a
json_build_object('value', AGG(...))envelope (lateral) orSubqueryExprreturning the same shape (correlated), unwrapped via the existingparseIncludedRows → JSON.parsepipeline. The column's declared codec is NOT invoked for the scalar return value. The structural defence the spec promised ("no JS-sideNumbercoercion truncation") holds — the decoder makes noNumber()cast on the scalar path — but the broader framing ("codec layer decodes via the column's declared codec") is not met. Trade-off deliberately accepted during D1 R1 intent-validation; filed as TML-2684 (Medium, now unblocked once this PR merges). Grounds: the JSON path is correct for counts within JS-safe-integer range + sum/avg over int4 (the vast majority of practical cases); the prior multi-query stitcher ALSO bypassed the codec; decimal-precision cross-cuts root-levelaggregate()decoding too and is bigger than this slice.Pagination composes through to scalar aggregates — wrap-derived-select shape (commit
dedee515a).r.where(W).take(N).count()returns ≤ N: the aggregate runs over the row-set the chain selects. The SQL shape uses a wrap-derived-select: the source is wrapped in an innerSELECT * FROM <relation> WHERE <fk + user where> ORDER BY <user orderBy> LIMIT N OFFSET M, then the aggregate runs over that derived table (see § SQL emission examples item 3 for the full shape). A naïve "just call.withLimit()on the aggregating SELECT" would have been wrong — a top-level LIMIT trims the one-row aggregate output, not the rows being aggregated. The wrap is the only correct shape.One scope expansion:
packages/2-sql/5-runtime/src/codecs/decoding.ts(commitf6cf22533, +9/-11 lines). The runtime decoder'sdecodeIncludeAggregatehad an array-only shape assertion that broke once correlated scalar/combine flowed through it (correlated emission produces aSubqueryExprprojection of a JSON object, not array). The fix widens the pre-parser to accept any JSON shape and defers shape validation to per-shape downstream decoders (parseIncludedRows,parseCombineEnvelope,decodeScalarIncludePayload). Structurally correct: shape validation belongs in the per-shape decoders, not in the pre-parse step.A01's pushback on literal
COALESCE(COUNT(*), 0)(commit6a21bc5d0). The review comment suggested wrapping the count inCOALESCEat the SQL level. The codebase has noCoalesceExprAST node, andCOUNT(*)over empty input is already0per SQL spec — adding the AST infrastructure (new expr node + Postgres renderer + SQLite renderer + visitor integration) for a no-op wrap would be significant scope creep with zero behavior delta. The commit delivers the substantive value (drops the JS-sidevalue === nullfallback so SQL semantics drive the empty default) and surfaces the AST-addition deferral inline.Reapply
orderByafter the ROW_NUMBER dedup wrap — real correctness fix (commit805ca2cdb). Surfaced by CodeRabbit during the second review pass; promoted from latent to active by the TML-2498 reversal. Pre-reversal (when pagination didn't enter the aggregate scope), the row-include path already reappliedorderByafterwrapWithRowNumberDedup(an existing pattern atquery-plan-select.tslines 429-454), while the scalar path didn't — but the asymmetry had no user-visible effect because pagination never reached the aggregate. Post-reversal, the scalar-side gap produces wrong results fordistinct(cols).orderBy(c).take(N).sum/avg/min/max— the aggregate runs over an arbitrary N-row slice instead of the ordered top N. The fix mirrors the row-path's pattern (project hidden order columns through the dedup wrap; reapplywithOrderByon the wrapped alias before LIMIT/OFFSET). Regression test seeds 5 posts where the unfixed and fixed code produce distinguishable SUMs (500 vs 700 over adistinct(['title']).orderBy(views.desc()).take(2).sum('views')shape). Both lateral and correlated paths covered — they sharebuildIncludeChildScalarSelect, so a single source-side fix flows through.A06's loud-throw consistency (commit
84724b952). The scalar envelope's shape gate indecodeScalarIncludePayloadmatched A03's pattern at the combine site: throw loudly onarray | primitive | non-objectpayloads — those mean planner/decoder bugs, not data shapes to soft-handle. The legitimate "empty LATERAL row" case is still handled at the outerraw === nullshort-circuit.Sibling predicates were a deliberate carve, then deleted. D1 introduced
hasScalarIncludeDescriptors+hasCombineIncludeDescriptorsalongside the originalhasScalarOrCombineIncludeDescriptors; D3 deleted all three by removing the dispatch gate and the planner throws entirely. Theinclude-tree-predicates.tsfile is gone. The strategy switch indispatchWithIncludeStrategyis now purely capability-driven viaselectIncludeStrategy.What this PR does NOT touch (TML-2657's deletion scope).
dispatchWithMultiQueryIncludes, all stitcher helpers,compileRelationSelect, the'multiQuery'arm ofselectIncludeStrategy, theIncludeStrategytype union, and mutation-path code — all kept in tree, all now dead-on-read for every real-target contract. TML-2657 (now unblocked) deletes them in its own PR with its own review surface (call-graph reachability + test repurposing).Integration test flakiness in
pnpm test:integrationis pre-existing. Throughout the slice + both review rounds, implementer and reviewer independently observed PG portal-cleanup races (signature:portal "C_X" does not exist, non-overlapping fail-sets across re-runs). The slice's touched files are stably green in isolation. Not introduced by this PR.SQLite-driver end-to-end integration is partial coverage by design. The correlated builder is exercised against real Postgres via
CORRELATED_CAPABILITIES(a capability-flag override innested-includes-helpers.tsthat forces correlated emission — PG executes correlated subqueries fine, validating SQL correctness + execution). The SQLite-specific rendering divergence (json_object,json_group_array) is verified by SQLite adapter-renderer unit tests atpackages/3-targets/6-adapters/sqlite/test/adapter.test.ts. Extending sql-orm-client's integration suite to also run against an in-memory SQLite driver is a worthwhile follow-up (track alongside TML-2657) but infrastructure-scoped, not slice-DoD-blocking.Project-folder close-out. The slice's project folder (
projects/sql-orm-include-aggregates/) was cleaned up before flipping the PR to ready-for-review — the spec, plan, and design-decisions files were deleted in the final commit. Per the team'sprojects/lifecycle (transient working surface; the durable trail lives in the PR description, commit messages, and Linear), the close-out happens with the PR rather than as a separate cleanup PR. Thereviews/subdirectory is gitignored and doesn't ship.Testing performed
Cumulative across all three dispatches + the two review rounds:
pnpm typecheck— clean (137/137 packages via Turbo).pnpm test(inpackages/3-extensions/sql-orm-client) — 524+ passed / 3 skipped.pnpm test:packages(workspace) — clean modulo one pre-existing cipherstash flake that passes in isolation.pnpm test:integration(workspace) — pre-existing PGlite worker-pool flakes (different fail-sets across re-runs); all touched files stably green in isolation.pnpm lint:deps— clean (980 modules, 2024 deps cruised; module count down by 1 from baseline due to the deletedinclude-tree-predicates.ts).any, no@ts-expect-erroroutside.test-d.ts, no@ts-nocheck; multi-query path preserved at 2 hits;'multiQuery'arm preserved at 3 hits) — all clean.Skill update
n/a — internal only. The public ORM surface (
.include(),.count(),.sum(),.avg(),.min(),.max(),.combine()) is unchanged in API shape. The behavioural change (1 SQL execution instead of N+1; aggregate composes through the refine state) matches what the JSDoc on those methods already promises.Checklist
TML-NNNN: <sentence-case title>form.Alternatives considered
take(N).count()returns the unpaginated total. The slice was specified, planned, and implemented under this framing for D1–D3 (the structural defence inbuildIncludeChildScalarSelectexplicitly omittedwithLimit/withOffset). Reversed during PR self-review when the author re-read TML-2498 and concluded the framing was wrong: the page-capped count is the natural compositional semantic of refine chaining (each method acts on the previous's output). Users wanting the unpaginated total drop thetake; users wanting both shapes usecombine({ page: r.take(N), total: r.count() }). TML-2498 closed as not-a-bug.json_build_objectpacking shape under awkward mixes were all unresolved design questions at brief-write time. Routed to orchestrator tier per the team's model-tier discipline.json_build_array(...)to keep it array-shaped. Considered as the alternative to wideningdecodeIncludeAggregate. Rejected: shape validation structurally belongs in the per-shape downstream decoders, not in the pre-parser. The widening is the cleaner fix; the array-wrap would be a workaround that preserves a now-meaningless invariant.CoalesceExprAST node to make A01's empty-relation default explicit in SQL (the literal reading of "can't we use coalesce on the sql level?"). Considered during the review-round; rejected on scope-creep grounds.COUNT(*)over empty input is0per SQL spec — the explicit COALESCE would be a no-op. Adding the AST node would require new expr + Postgres renderer + SQLite renderer + visitor integration for zero behavior delta.Summary by CodeRabbit
New Features
count,sum,avg,min,max) andcombine()includes now execute efficiently in single SQL queries rather than requiring multiple database round trips.Refactor