linq_fold Phase 2B: aggregates + early-exit terminators (+ ICE 50609 defuse)#2696
Merged
Conversation
Splice-mode planner now folds ten more terminator operators into fused
single-loop invokes via two new lanes:
Ring 1 (accumulator): sum, min, max, average, long_count
Ring 2 (early-exit): first, first_or_default, any, all, contains
LinqLane dispatch in plan_loop_or_count routes by terminator; per-lane
helpers (emit_counter_lane / emit_array_lane / emit_accumulator_lane /
emit_early_exit_lane) factor the emission. min/max use workhorse-branch
direct < / > on workhorse types and _::less on non-workhorse. any with
no predicate emits !empty(src) shortcut. long_count piggybacks on the
existing length() shortcut. All accumulator/early-exit paths preserve
linq.das empty-source semantics (sum→0, min/max→default<T>, average→NaN,
first→panic, first_or_default→d, any→false, all→true, contains→false).
Functional + AST shape coverage:
tests/linq/test_linq_fold.das — Ring 1 ~25 cases, all cross-
checked _fold == _old_fold
tests/linq/test_linq_fold_ast.das — 8 Ring 1 + 8 Ring 2 shape tests,
asserts workhorse-branch ops,
length/empty shortcuts, fall-
through on out-of-scope chains
tests/linq/test_linq_fold_ring2.das — Ring 2 functional tests; lives
in own file as workaround for
ICE 50609 ("multiple instances
of linq.all / linq.contains")
— see follow-up commit
Three new 4-way benchmarks at 100K rows
(long_count_aggregate, first_or_default_match, contains_match);
existing Ring 1/2 benchmark m3f columns move from m3-parity (~25-30 ns)
to single-digit ns/op with zero allocations.
LINQ.md updated with Phase 2B delta tables.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Phase 2B Ring 2 (commit 0851ea0) had to keep its tests in a separate file because both `linq.all` and `linq.contains` ICE with `error[50609]: multiple instances of <gen>` when a single module hits the same op from both a mut-element source (`each(arr)` → `iterator<T -&>`) and a const-element source (iterator comprehensions → `iterator<T const -&>`). Root cause: the generic-name mangler ignores inner element-constness, so two genuinely distinct instantiations hash to one symbol. Pointer-like variance fact (verified empirically; see tests/type_traits/test_iterator_variance.das): `iterator<T -&>` flows into `iterator<T const -&>`, not the reverse. So declaring the iterator overload as `iterator<auto(TT) const>` lets both source flavors converge on a single instantiation per op — the collision becomes impossible. Scope deliberately narrow: only `all` and `contains` are constified (the two known ICE triggers). A blanket sweep of all ~78 iterator overloads caused real cascading breakage — select_impl moves `it` via emplace (can't from const), select_many iterates `it` (needs mutable handle), multiple downstream AOT codegen issues with const struct default-init, and user-defined non-const operators (ComplexType.==). The full fix belongs in the C++ mangler (separate PR); this commit is the narrowest library-side defuse for the two demonstrably broken ops. Side effects: - tests/linq/_common.das: ComplexType `==` and `!=` made `def const` (was `def`); the const-element form of contains() iterates const values and needs a const-callable equality op. This is a legitimate operator-design improvement, not a workaround. - tests/linq/test_linq_fold_ring2.das (134 lines, Ring 2 functional tests) merged into tests/linq/test_linq_fold.das; the workaround file is no longer needed. All 133 fold tests pass. - tests/type_traits/test_iterator_variance.das: new 3-case language regression test pinning the variance rule (positive case, comprehension case, cross-flavor case — the same scenario that ICEs without the fix). - CLAUDE.md: two bullets under `### Iterators and `each`` documenting the variance fact and the mangler pitfall + library workaround. Verification: 695 INTERP + 695 AOT + 695 JIT tests in tests/linq pass. ICE no longer reproducible in the working tree. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Contributor
There was a problem hiding this comment.
Pull request overview
Phase 2B of the linq_fold planner: adds two new emit lanes (single-pass accumulators for sum/min/max/average/long_count, and early-exit terminators for first/first_or_default/any/all/contains), refactors plan_loop_or_count into a dispatcher over per-lane emit_* helpers, and ships a deliberately narrow library-level workaround for an upstream generic-mangler ICE (50609) by constifying the iterator element type on all and contains.
Changes:
- Introduces
LinqLane+classify_terminatordispatcher and fouremit_*helpers (emit_counter_lane/emit_array_lane/emit_accumulator_lane/emit_early_exit_lane), plusemit_length_shortcut/emit_any_empty_shortcutfor zero-loop fast paths. - Constifies the iterator-overload element type on
linq.allandlinq.contains(iterator<auto(TT) const>) to collapse mut/const-ref instantiations into one generic instance; documents the variance rule and mangler pitfall inCLAUDE.mdand pins it with a newtests/type_traits/test_iterator_variance.das. - Adds ~51 functional tests and 14 AST shape tests for the new lanes, three new 4-way benchmarks (
long_count_aggregate,first_or_default_match,contains_match), and Phase 2B delta tables inLINQ.md.tests/linq/_common.dasmakesComplexType.==/!=def constto satisfy const-callable equality required by the constifiedcontains.
Reviewed changes
Copilot reviewed 11 out of 11 changed files in this pull request and generated no comments.
Show a summary per file
| File | Description |
|---|---|
| daslib/linq_fold.das | Adds LinqLane/classify_terminator and the four lane emitters; plan_loop_or_count becomes a dispatcher. |
| daslib/linq.das | long_count body uses _ loop var; all/contains iterator overloads take iterator<auto(TT) const> as ICE workaround. |
| tests/linq/test_linq_fold.das | ~51 Ring 1 + Ring 2 functional cases plus _old_fold parity checks. |
| tests/linq/test_linq_fold_ast.das | Generic AST walkers (count_op2 / count_call / count_op1) and 14 shape tests for the new lanes. |
| tests/linq/_common.das | ComplexType.==/!= made def const so const-element contains() can call them. |
| tests/type_traits/test_iterator_variance.das | New 3-case regression test pinning iterator<T -&> → iterator<T const -&> variance and the post-fix single-instance behavior. |
| benchmarks/sql/{long_count_aggregate,first_or_default_match,contains_match}.das | New 4-way benchmarks at 100K rows. |
| benchmarks/sql/LINQ.md | Phase 2B Ring 1 / Ring 2 sections with delta tables; checklist row updated. |
| CLAUDE.md | Two iterator-variance / mangler-pitfall bullets under "Iterators and each". |
Key risk factors that argue for human review:
- The
all/containssignature change is a public-API surface change in a core library to work around an upstream compiler bug; the PR explicitly notes the broader sweep cascades into other breakage and that a real mangler fix is deferred. Validating that no downstream user code relies on the previous mut-element form needs human judgment. - The planner refactor is large (~500 added lines in
linq_fold.das) and the lane emitters carry significanttopIsItershape duplication that future maintainers will need to keep in sync; correctness depends on AST shape tests rather than on direct equivalence proofs againstlinq.dassemantics. - The ICE workaround leaves ~76 other iterator overloads with the same latent vulnerability; the PR documents this as known but a follow-up regression in user code remains possible until the mangler fix lands.
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Every emit lane in linq_fold.das had a pair of qmacro templates that
differed only in `typedecl($e(topExpr)) - const` vs plain
`typedecl($e(topExpr))` on the invoke block's `$src` parameter. The
strip-when-iter logic was identical across lanes; the duplication had
no real branching purpose beyond "I couldn't conditionally append the
modifier inside a single qmacro template."
New `invoke_src_param_type(top)` helper computes the param TypeDecl
once — clone top._type, strip outer `constant` flag when isIterator —
and the emit lanes splice it with `$t(srcParamType)` instead of
`typedecl($e(topExpr)) - const` / `typedecl($e(topExpr))`.
Collapsed:
- emit_counter_lane: 2 arms → 1
- emit_array_lane: 3 arms → 3 (still need 3 — the axes split on
`expr._type.isIterator` for the return path AND `sourceHasLength`
for the reserve hint; param type itself is now uniform)
- emit_accumulator_lane: 10 arms (5 ops × 2) → 5 (one per op)
- emit_early_exit_lane: 10 arms (5 ops × 2) → 5 (one per op)
Net -89 lines. Behavior unchanged: 133 fold tests, 66 AST shape tests,
695 INTERP, 695 AOT, 695 JIT all pass.
Boris flagged the duplication during the iterator-variance discussion
("why do we still have two versions?"); deferred while we landed the
ICE 50609 defuse, picked back up now.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Cognitive load pass on linq_fold.das. Net -66 lines (504 changed).
Patterns collapsed:
1. push/push_clone workhorse splits (2 sites in plan_loop_or_count array
lane) — use push_clone everywhere. For workhorse types clone == copy
(no allocation, same byte cost as push); for non-workhorse it deep-
clones, which is what we want anyway.
2. emit_length_shortcut: 2 op-arms (count vs long_count) collapse to one
via `$c(castName)(length(src))` where castName is "int" (identity for
int) or "int64". `$c` splices the function name at call position.
3. emit_accumulator_lane: 4 op-arms (long_count / sum / average / min-max)
collapse to one invoke template. Per-op variation is built into 3 lists
(preludeStmts, perMatchStmts, returnExpr); all flattened into a single
bodyStmts list spliced via $b. This shares scope under one wrapping
block — splitting decls / for / return into separate splice points
would put each in its own sub-block, hiding the accumulator (caught by
AST dump under `options log_infer_passes`).
4. emit_early_exit_lane: 5 op-arms (first / first_or_default / any / all
/ contains) collapse the same way — preludeStmts + perMatchStmts +
tailStmts → single bodyStmts → single $b.
5. Multi-stmt-per-op cases use `qmacro_block_to_array() { stmt1; stmt2 }`
to express the prelude/per-match as one literal block instead of N
separate `qmacro_expr() { stmt }` pushes. Roughly halves the line
count for ops with 2+ stmts (average, min/max).
New private helpers (all `[macro_function]`):
- prepend_binds(stmts, intermediateBinds) — shared chain-bind prefix.
- stmts_to_expr(stmts) — collapse N stmts to a single expression
(pass through when N==1, wrap in qmacro_block when N>1). Used by
every lane that builds a per-element block whose length is data-
dependent.
- wrap_with_condition(body, cond) — `if (cond) { body }` when cond
is non-null; pass-through otherwise. Replaces the if/else dance
every lane had for fusing the upstream `where_` predicate.
- min_max_compare(workhorse, opName, valName, accName) — emits the
perf-critical compare. Workhorse types use direct `<` / `>`
(single instruction); non-workhorse uses `_::less` with operand
flip for max. Replaces a 4-arm if/elif inline ladder.
Tests: 133 fold + 66 AST + 695 INTERP + 695 AOT + 695 JIT all pass.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Same pattern as the accumulator + early-exit lanes from prior commit. Three arms (isIter / sourceHasLength / else) become one invoke template with a per-axis stmt list: - var $i(accName) : array<T> (always) - reserve(length(src)) (only when sourceHasLength && !isIter) - for-loop (always) - return <- acc.to_sequence_move() (when isIter) - return <- acc (else) All stmts share scope under the single $b(bodyStmts) splice. Same shape applies across all four emit lanes in the file now. Tests: 133 fold + 66 AST + 695 INTERP + 695 AOT all pass. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
6 tasks
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
Two stacked commits on this branch:
Commit 1 (
0851ea03e) — linq_fold Phase 2B Rings 1+2Splice-mode planner now folds ten more terminator operators into fused single-loop invokes via two new lanes:
sum,min,max,average,long_countreturnfrom insideinvoke($block { ... })):first,first_or_default,any,all,containsclassify_terminatordispatches the chain to one of four per-lane emit helpers (emit_counter_lane/emit_array_lane/emit_accumulator_lane/emit_early_exit_lane).min/maxuse workhorse-branch direct</>on workhorse types and fall back to_::lessfor non-workhorse. Predicate-freeanyshort-circuits to!empty(src).long_countpiggybacks on the existing length() shortcut for pure-projection chains. All accumulator/early-exit paths preservelinq.dasempty-source semantics (sum→0,min/max→default<T>,average→NaN,first→panic,first_or_default→d,any→false,all→true,contains→false).Coverage:
tests/linq/test_linq_fold.das, cross-checked_fold == _old_fold.tests/linq/test_linq_fold_ast.das(workhorse-branch ops, length/empty shortcuts, fall-through assertions).test_linq_fold_ring2.dasfile as a workaround for ICE 50609 (see Commit 2 below).long_count_aggregate.das,first_or_default_match.das,contains_match.das.Phase 2B benchmark m3f columns move from m3-parity (~25-30 ns) to single-digit ns/op with zero allocations.
Commit 2 (
cd1b5655f) — defuse ICE 50609 forall/containsPhase 2B Ring 2 tests originally lived in a separate file because
linq.allandlinq.containswould ICE witherror[50609]: multiple instances of <gen>when a single module hit the same op from both a mut-element source (each(arr)→iterator<T -&>) and a const-element source (iterator comprehensions →iterator<T const -&>). Root cause: the generic-name mangler ignores inner element-constness, so two genuinely distinct instantiations hash to one symbol.Pointer-like variance fact (verified empirically; see
tests/type_traits/test_iterator_variance.das):iterator<T -&>flows intoiterator<T const -&>, not the reverse. So declaring the iterator overload asiterator<auto(TT) const>lets both source flavors converge on a single instantiation per op — collision becomes impossible.Scope deliberately narrow. Only
allandcontainsare constified (the two known ICE triggers). A blanket sweep of all ~78 iterator overloads caused real cascading breakage:select_implmovesitviaemplace(can't move from const)select_manyiteratesit(needs mutable iterator handle)ComplexType.==) failThe general fix belongs in the C++ mangler (separate follow-up PR). This commit is the narrowest library-side defuse for the two demonstrably-broken ops.
Side effects:
tests/linq/_common.das:ComplexType.==/!=madedef const(wasdef) — legitimate operator-design improvement, since the const-element form ofcontains()iterates const values and needs a const-callable equality op.tests/linq/test_linq_fold_ring2.dasmerged intotests/linq/test_linq_fold.das; workaround file deleted.tests/type_traits/test_iterator_variance.das: new 3-case language regression test pinning the variance rule.CLAUDE.md: two bullets under### Iterators and \each`` documenting the variance fact and the mangler pitfall + library workaround.Test plan
mcp__daslang__run_test tests/linq/test_linq_fold.das— 133 tests pass (107 from Ring 1 + 26 merged-in Ring 2)./bin/test_aot -use-aot dastest/dastest.das -- --use-aot --test tests/linq— 695 tests pass (afterrm -rf tests/linq/_aot_generated/ daslib/_aot_generated/to regenerate stubs against the new signatures)./bin/daslang dastest/dastest.das -jit -- --jit --test tests/linq— 695 tests passmcp__daslang__lint daslib/linq.dasclean; format clean🤖 Generated with Claude Code