linq_fold group_by: fuse upstream where_/select* into per-element loop#2725
Merged
Conversation
Closes the explicit deferred-bail from PR #2721 onward: any upstream call between source and group_by_lazy used to cascade to tier 2. PR-B walks the upstream segment and fuses chains of where_*/select* into the per-element table-update loop. Walk: - For each `select`: bind the previous projection (if any) to a fresh `var v_N := projection_{N-1}` intermediate, then compute the new projection peeled to reference the latest bind name. Update elemType to the post-projection type so the table value-type witness matches what the key block will receive. - For each `where_`: bind any pending projection first (so the predicate references a stable name — no double-eval), then AND-merge the peeled predicate into whereCond. - Anything else (distinct, order_by, etc.): bail. Final bind: if a projection is still unbound after the walk, bind it now so itName (the post-projection name) is stable. The inner-select reducer recognizer (PR-A1/A2) folds its inner lambda body against this itName — without the bind, the recognizer would dangle on a name the typer hasn't seen. Per-element emission split into core + wrapping. The 3-stmt core (`let k = invoke(key, it); let uk = unique_key(k); unsafe { table update }`) is wrapped with `if (whereCond) { core }`, then prepended with intermediateBinds, and spliced into the for-loop body via $b(bodyStmts). The for-loop bind name is now `srcItName` (was `itName`); `itName` aliases the post-projection name (== srcItName when no upstream selects). Tests: - 8 new parity tests in test_group_by_upstream_fusion_fold_parity: where-only, select-only, where→select, select→where, chained selects, Person-fixture parity, empty result, count terminator. - 4 new AST-shape tests: G11 (upstream where, no runtime where_ call), G12 (upstream select, no runtime select call), G13 (combined where+select), distinct-upstream cascade fingerprint. All PR-A1/PR-A2 baselines (groupby_count, groupby_sum, groupby_min, groupby_max, groupby_first, groupby_multi_reducer) hold parity — the per-element-body split into core + wrapping is observationally equivalent when intermediateBinds is empty and whereCond is null. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
…re/select fusion 3 new 100K-row benchmarks (m1 SQL / m3 plain LINQ / m3f splice): - groupby_where_count: 75 / 65 / 23 ns/op (2.8× over m3, 3.3× over SQL) - groupby_where_sum: 86 / 80 / 23 ns/op (3.5× over m3, 3.7× over SQL) - groupby_select_sum: — / 110 / 58 ns/op (1.9× over m3; m1 omitted — _sql LINQ-to-SQL requires `_group_by(_.Field)`, no expression keys) The where-fused benchmarks drop to ~23 ns/op — faster than the no-upstream groupby_count (36 ns/op) because the where filter halves the table-update count (only ~50% pass `price > 500`). Fewer hash ops × same per-survivor cost = lower per-element averaged time. LINQ.md: refreshed Phase status table, baseline rows, Phase 3+ subsection. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
4d0159f to
26ebee5
Compare
Contributor
There was a problem hiding this comment.
Pull request overview
This PR extends linq_fold group_by planning so upstream where_ and select chains can be fused into the generated per-element aggregation loop instead of cascading to the default tier.
Changes:
- Adds upstream
where_/selectwalking and fused emission inplan_group_by. - Adds functional and AST-shape tests for fused group_by upstream operators and fallback behavior.
- Adds benchmark cases and updates LINQ benchmark documentation for the new fused shapes.
Reviewed changes
Copilot reviewed 7 out of 7 changed files in this pull request and generated 2 comments.
Show a summary per file
| File | Description |
|---|---|
daslib/linq_fold.das |
Implements upstream where/select fusion for group_by loop emission. |
tests/linq/test_linq_fold.das |
Adds parity tests for group_by fusion combinations. |
tests/linq/test_linq_fold_ast.das |
Adds AST tests verifying runtime calls are eliminated or cascaded. |
benchmarks/sql/LINQ.md |
Documents PR-B benchmark results and coverage status. |
benchmarks/sql/groupby_where_sum.das |
Adds benchmark for filtered group_by sum. |
benchmarks/sql/groupby_where_count.das |
Adds benchmark for filtered group_by count. |
benchmarks/sql/groupby_select_sum.das |
Adds benchmark for projected group_by sum. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
…ard)
Fix correctness bug in PR-B's per-element emission: the initial walk
collected all binds into a flat intermediateBinds list and a single
AND-merged whereCond, then emitted `binds...; if (whereCond) { core }`.
That executes EVERY select before any where guard, so a chain like:
_where(_ != 0)._select(10 / _)._group_by(...)
would run `10 / _` for ALL source elements, including `_ == 0` (divide
by zero). Reference LINQ evaluates `select` lazily per element — so a
select that follows a where must only run on where-survivors.
Fix: segment-based walk + inside-out emission. The walk produces
(binds, trailing_where) pairs — a `where` closes the current segment
with itself as trailing_where; a `select` that follows a where starts
a new segment (its bind is emitted INSIDE the where's guard).
Consecutive wheres with no intervening select AND-merge into the same
segment's trailing_where. Final emission walks segments in reverse,
wrapping the core body inside-out so each where's `if { ... }` brackets
exactly the binds + nested guards that follow it.
Regression tests added FIRST (per feedback_correctness_bug_add_test_first):
- where → select with side-effect counter: asserts the projection fires
EXACTLY once per where-survivor (5), not once per source element (10).
- select → where → select: asserts only the FIRST select runs
unconditionally; the SECOND fires only on the where's survivors.
Both tests failed on the broken implementation (got 10, expected 5) and
pass after the fix. All 269 parity + 106 AST + 18 group_by tests stay
green; all 6 PR-A1/PR-A2/PR-B benchmarks unchanged — the lazy emission
has zero perf cost (same hash ops + slot mutations per survivor).
LINQ.md: refreshed the BufferGroupBy core row (Copilot caught the
inconsistency with PR-A2/PR-B's new rows below it — the core row still
claimed upstream where/select bailed, contradicting subsequent rows).
Single current status for the phase-table.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Comment on lines
+444
to
+448
| 1. **Walk upstream calls** (between `top` and `group_by_lazy`) in source-to-leaf order. For `select`: bind the previous projection (if any) to a fresh `var v_N := projection_{N-1}` intermediate, then compute the new projection peeled to reference the latest bind name. Update `elemType` to the post-projection type so the table value type witness (`default<elemType>`) matches what the key block will receive. For `where_`: bind any pending projection first (so the predicate references a stable name — no double-eval), then AND-merge the peeled predicate into `whereCond`. For anything else (`distinct`, `order_by`, etc.): bail to tier 2. | ||
|
|
||
| 2. **Final bind** before recognizer call: if a projection is still unbound after the walk, bind it now so `itName` (the post-projection name) is stable. Inner-select reducer recognition uses this `itName` to fold the inner lambda body — without the bind, the recognizer would dangle on a name that the typer hasn't seen. | ||
|
|
||
| 3. **Per-element emission split into core + wrapping.** The 3-stmt core (`let k = invoke(key, it); let uk = unique_key(k); unsafe { table update }`) is wrapped with `if (whereCond) { core }`, then prepended with `intermediateBinds`. The result splices into the for-loop body via `$b(bodyStmts)`. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
Closes the explicit deferred-bail tracked since PR #2721: any upstream call between source and
group_by_lazywould cascade to tier 2. PR-B walks the upstream segment and fuses chains ofwhere_*andselect*into the per-element table-update loop.Walk:
select: bind the previous projection (if any) to a freshvar v_N := projection_{N-1}intermediate, then compute the new projection peeled to reference the latest bind name. UpdateelemTypeto the post-projection type so the table value-type witness matches what the key block receives.where_: bind any pending projection first (so the predicate references a stable name — no double-eval), then AND-merge the peeled predicate intowhereCond.distinct,order_by, etc.): bail to tier 2.Final bind: if a projection is still unbound after the walk, bind it now so
itName(the post-projection name) is stable. The inner-select reducer recognizer (PR-A1/A2) folds its inner lambda body against thisitName— without the bind, the recognizer would dangle on a name the typer hasn't seen.Per-element emission split into core + wrapping. The 3-stmt core (
let k = invoke(key, it); let uk = unique_key(k); unsafe { table update }) is wrapped withif (whereCond) { core }, then prepended withintermediateBinds, and spliced into the for-loop body via$b(bodyStmts). The for-loop bind name is nowsrcItName(wasitName);itNamealiases the post-projection name (==srcItNamewhen no upstream selects).Headline (100K rows, INTERP)
_sqlneeds_group_by(_.Field), no expression keys)The
where-fused benchmarks drop to ~23 ns/op — faster than the no-upstreamgroupby_count(36 ns/op) because the where halves the table-update count (only ~50% passprice > 500). Fewer hash ops × same per-survivor cost = lower per-element averaged time.Test plan
tests/linq/test_linq_fold.das— 266 tests pass (8 new intest_group_by_upstream_fusion_fold_parity: where-only, select-only, where→select, select→where, chained selects, Person fixture parity, empty result, count terminator)tests/linq/test_linq_fold_ast.das— 106 tests pass (4 new: G11 upstream where, G12 upstream select, G13 combined where+select, distinct-upstream cascade)tests/linq/test_linq_group_by.das— 18 tests pass (regression check)test_aot -use-aot) — 266 + 106 tests passmcp__daslang__lint)mcp__daslang__format_file)Deferred follow-ups
having_*betweengroup_byandselect(group_proj)(HAVING clause — needs to defer the predicate to the result-build loop rather than the per-element loop)distinct,order_by,skip/take(rare inarr → group_byshapes)averagereducer (2-slot per-key acc + post-process division)reverse_takebackward index loop on array sources (PR-C)🤖 Generated with Claude Code