Skip to content

linq_fold group_by: fuse upstream where_/select* into per-element loop#2725

Merged
borisbat merged 3 commits into
masterfrom
bbatkin/linq-fold-groupby-upstream-fusion
May 19, 2026
Merged

linq_fold group_by: fuse upstream where_/select* into per-element loop#2725
borisbat merged 3 commits into
masterfrom
bbatkin/linq-fold-groupby-upstream-fusion

Conversation

@borisbat
Copy link
Copy Markdown
Collaborator

@borisbat borisbat commented May 19, 2026

Summary

Closes the explicit deferred-bail tracked since PR #2721: any upstream call between source and group_by_lazy would cascade to tier 2. PR-B walks the upstream segment and fuses chains of where_* and 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 receives.
  • 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 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 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).

Headline (100K rows, INTERP)

Benchmark m1 SQL m3 LINQ m3f splice Win
groupby_where_count 75 65 23 2.8× over m3 / 3.3× over SQL
groupby_where_sum 86 80 23 3.5× over m3 / 3.7× over SQL
groupby_select_sum 110 58 1.9× over m3 (m1 omitted — _sql needs _group_by(_.Field), no expression keys)
groupby_count (regression check) 142 71 36 parity — core split preserves PR-A1 splice
groupby_sum (regression check) 170 101 36 parity — PR-A1 inner-select-sum preserved
groupby_multi_reducer (regression check) 189 139 53 parity — PR-A2 multi-reducer preserved

The where-fused benchmarks drop to ~23 ns/op — faster than the no-upstream groupby_count (36 ns/op) because the where halves the table-update count (only ~50% pass price > 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 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)
  • 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)
  • AOT mode (test_aot -use-aot) — 266 + 106 tests pass
  • Lint clean (mcp__daslang__lint)
  • Format clean (mcp__daslang__format_file)
  • All 3 new benchmarks plus PR-A1/PR-A2 regression checks run cleanly

Deferred follow-ups

  • having_* between group_by and select(group_proj) (HAVING clause — needs to defer the predicate to the result-build loop rather than the per-element loop)
  • Other upstream ops: distinct, order_by, skip/take (rare in arr → group_by shapes)
  • average reducer (2-slot per-key acc + post-process division)
  • reverse_take backward index loop on array sources (PR-C)

🤖 Generated with Claude Code

borisbat and others added 2 commits May 18, 2026 22:28
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>
@borisbat borisbat force-pushed the bbatkin/linq-fold-groupby-upstream-fusion branch from 4d0159f to 26ebee5 Compare May 19, 2026 05:28
@borisbat borisbat changed the base branch from bbatkin/linq-fold-min-max-first-multi-reducer to master May 19, 2026 05:29
@borisbat borisbat requested a review from Copilot May 19, 2026 05:30
Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

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_/select walking and fused emission in plan_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.

Comment thread daslib/linq_fold.das Outdated
Comment thread benchmarks/sql/LINQ.md Outdated
…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>
Copy link
Copy Markdown
Contributor

Copilot AI left a comment

Choose a reason for hiding this comment

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

Pull request overview

Copilot reviewed 7 out of 7 changed files in this pull request and generated 1 comment.

Comment thread benchmarks/sql/LINQ.md
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)`.
@borisbat borisbat merged commit 47303d2 into master May 19, 2026
32 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants