Skip to content

fix(query): row_group_keys invariant in parallel non-DISTINCT path (closes #1175) - #1177

Merged
robcohen merged 2 commits into
mainfrom
fix/query-sidecar-invariant
May 21, 2026
Merged

robcohen merged 2 commits into
mainfrom
fix/query-sidecar-invariant

Conversation

@robcohen

Copy link
Copy Markdown
Member

Summary

Fixes #1175 — SELECT … WHERE … ORDER BY panicked on any ledger with ≥1000 postings.

Root cause

The parallel evaluation fast path in executor/execution.rs:167 bulk-assigned rows without keeping the row_group_keys sidecar in lockstep:

```rust
if query.distinct {
// ...uses add_row() — correct, updates both vectors
} else {
result.rows = rows; // ← BUG: skips the sidecar
}
```

QueryResult has a row_group_keys: Vec<Option<Vec<Value>>> sidecar that must stay in lockstep with rows. The add_row() / add_aggregate_row() constructors both maintain the invariant; this fast path bypassed them.

Then ORDER BY (or the implicit GROUP BY default sort) triggered QueryResult::sort_by, which has a load-bearing assert_eq! on the lengths — boom.

Why it hit users but slipped through tests

Three conditions are needed:

  1. ≥ PARALLEL_THRESHOLD (1000) postings → triggers the parallel branch
  2. Non-DISTINCT → skips add_row()
  3. Subsequent sort → triggers the assertion

No existing test exercises all three. Real ledgers do (the reporter had 1360 matching rows).

Fix

Two lines: resize the sidecar to None per row after the bulk assignment, matching what add_row() would do for non-aggregate rows.

Test plan

  • Added test_query_with_order_by_above_parallel_threshold that materializes 1100 postings and runs the reporter's exact query shape
  • Verified the test fails pre-fix with the same panic from the bug report (rows.len() != row_group_keys.len(), left: 1100, right: 0)
  • Verified the test passes post-fix
  • cargo clippy -p rustledger-query --all-features --all-targets -- -D warnings clean
  • CI full workspace

🤖 Generated with Claude Code

…T path (closes #1175)

The parallel evaluation fast path bulk-assigned
`result.rows = rows` without updating the `row_group_keys` sidecar
vector. Any subsequent ORDER BY (or the implicit GROUP BY default
sort) then hit the load-bearing `assert_eq!` in
`QueryResult::sort_by` and panicked with:

  assertion `left == right` failed: QueryResult invariant violated:
  rows.len() must equal row_group_keys.len()

The bug only triggered above PARALLEL_THRESHOLD = 1000 postings on
non-DISTINCT paths that later sort, which is exactly why it hit
real-world ledgers but slipped through the test suite. The DISTINCT
branch right above the buggy code correctly used `add_row()` to
maintain the invariant.

Fix: resize the sidecar to `None` per row after the bulk assignment,
matching what `add_row` would do for non-aggregate rows.

Regression test reproduces the user's exact query shape (SELECT …
WHERE … ORDER BY date DESC) against 1100 postings. Verified the
test fails pre-fix with the original panic and passes post-fix.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@robcohen
robcohen requested a review from a team as a code owner May 21, 2026 13:36
Copilot AI review requested due to automatic review settings May 21, 2026 13:36

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

Pull request overview

Fixes a panic in SELECT … WHERE … ORDER BY queries on large ledgers by restoring the QueryResult invariant that rows and the row_group_keys sidecar must remain the same length, including in the parallel non-DISTINCT fast path (closes #1175).

Changes:

  • Keep row_group_keys in lockstep with rows when bulk-assigning results in the parallel non-DISTINCT execution branch.
  • Add an integration regression test that exceeds the parallel threshold and exercises ORDER BY on a non-DISTINCT query.

Reviewed changes

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

File Description
crates/rustledger-query/src/executor/execution.rs Ensures the parallel non-DISTINCT bulk assignment also initializes row_group_keys to preserve QueryResult invariants and prevent ORDER BY panics.
crates/rustledger-query/tests/bql_integration_test.rs Adds a regression test reproducing the large-ledger ORDER BY panic conditions from #1175.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

@codecov

codecov Bot commented May 21, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@github-actions

github-actions Bot commented May 21, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 36.2ms ± 0.7ms 25.1 MB
beancount 750.9ms ± 6ms 50.7 MB
Comparison 20.7x faster 2.0x less

vs main branch (2026-05-21)

Metric main this PR Change
Time 35.8ms 36.2ms +1.1% ✅
10K transactions · 5 runs, 2 warmup · hyperfine
What do these numbers mean?
  • Time: Wall-clock time to parse and validate the ledger (± std dev)
  • Memory: Peak resident set size (RSS)
  • vs main: Compared to latest nightly benchmark on main branch

@github-actions

github-actions Bot commented May 21, 2026 •

Copy link
Copy Markdown
Contributor

✅ Compatibility Test Results

Metric Result
Check Compatibility 100%
BQL Compatibility 100%
Full AST Match 100%
Total Files 786
What's tested
  • Check: Exit codes and error counts match bean-check
  • BQL: Query results match bean-query
  • Files: ~800 test files downloaded from 10+ beancount repositories

Full results available in workflow artifacts

Addresses Copilot review on #1177. The comment said the test
materializes 1100 transactions; it actually materializes 550
transactions producing 1100 postings, which is what crosses the
PARALLEL_THRESHOLD = 1000 postings threshold.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@robcohen
robcohen merged commit 4026e3c into main May 21, 2026
41 checks passed
@robcohen
robcohen deleted the fix/query-sidecar-invariant branch May 21, 2026 13:52
robcohen added a commit that referenced this pull request Jun 15, 2026
Addresses review feedback on the query-determinism invariant:

- The small generated ledgers (<=22 postings) never crossed the executor's
  `PARALLEL_THRESHOLD` (1000 postings), so the original test never actually
  ran the parallel grouping branch — the exact #1177 risk. Add
  `large_ledger_query_is_deterministic`, which builds a 1200-posting ledger
  (with a sanity assert on the count), forcing the parallel path, and
  re-executes each query 10x against the baseline.
- Comparison now checks the per-row `group_key` sidecar in addition to
  `rows`; a divergence in the parallel `row_group_keys` vector is precisely
  the #1177 failure mode and would otherwise slip past a rows-only check.
- Reworded the module doc: the executor uses deterministic `rustc_hash` and
  insertion-order grouping, so the test guards against hash-iteration-order
  / parallel-scheduling dependence, not a per-run hashing seed.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
robcohen added a commit that referenced this pull request Jun 15, 2026
Adds crates/rustledger-query/tests/pipeline_invariants.rs: the same query
over the same generated ledger must yield identical rows (including stable
ordering) across runs. A fresh Executor per run gives each an independent
hashing seed, so non-deterministic row ordering for grouping/aggregation
surfaces here -- the invariant the parallel non-DISTINCT row_group_keys
bug (#1177) violated. Covers GROUP BY/SUM, DISTINCT, ORDER BY, and plain
projection over generated ledgers (128 cases).

Part of #1235 (pipeline-boundary property tests).

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
robcohen added a commit that referenced this pull request Jun 15, 2026
Addresses review feedback on the query-determinism invariant:

- The small generated ledgers (<=22 postings) never crossed the executor's
  `PARALLEL_THRESHOLD` (1000 postings), so the original test never actually
  ran the parallel grouping branch — the exact #1177 risk. Add
  `large_ledger_query_is_deterministic`, which builds a 1200-posting ledger
  (with a sanity assert on the count), forcing the parallel path, and
  re-executes each query 10x against the baseline.
- Comparison now checks the per-row `group_key` sidecar in addition to
  `rows`; a divergence in the parallel `row_group_keys` vector is precisely
  the #1177 failure mode and would otherwise slip past a rows-only check.
- Reworded the module doc: the executor uses deterministic `rustc_hash` and
  insertion-order grouping, so the test guards against hash-iteration-order
  / parallel-scheduling dependence, not a per-run hashing seed.

Co-Authored-By: Claude Opus 4.8 (1M context) <[email protected]>
robcohen added a commit that referenced this pull request Aug 7, 2026
…aries

#1902 Phase 1, the last uncovered crate. Miri excludes this one for
rowan reasons that are not going away, so this is the compensating
coverage.

The existing properties ask whether the same input gives the same
answer twice. These ask whether the answer is RIGHT, via relationships
that hold whatever the ledger contains - so they need no expected
value, which is what makes them checkable over generated input:

- WHERE p and WHERE NOT p must PARTITION the unfiltered rows. Neither
  half may invent, lose or double-count. A predicate that misevaluates
  in one direction only shows up as a union that no longer
  reconstructs the whole.
- Grouping must preserve the total: SUM(number) GROUP BY account,
  summed back over groups, equals the ungrouped SUM. That is the
  invariant #1177 broke - rows right, group-key sidecar wrong.
- ORDER BY must permute, never add, drop or alter. Sorting is where a
  comparator that is not a total order loses rows, and the
  null-ordering tests next door pin WHICH order rather than that the
  multiset survived.

Aimed where this crate actually breaks: #1177 was a grouping/parallel
divergence, and the two bugs found by hand this cycle (#1963, #1966)
were both in evaluation rather than parsing.

Also widens the amount generator, which sabotaging the partition
property is how I found. Swapping `number > 0` for `number > 1`
changed NOTHING - because with a uniform -1_000_000..1_000_000 range,
landing in (0, 1] needs |n| <= 10^scale, at most 1000 of two million
draws, about 0.3 expected hits across a whole run. There was nothing
between 0 and 1 to lose. Now three magnitude bands, and that same
sabotage fails.

Every property sabotage-verified: overlapping halves fail the
partition, a wrong total fails the grouping, a dropped row fails the
permutation, and the boundary case fails now where it did not before.
robcohen added a commit that referenced this pull request Aug 7, 2026
Self-review of this PR. The per-key assertion added for Copilot compared
 - the projected  COLUMN - against the ungrouped
rows. But the group key travels separately, in ,
reachable only through . A row whose column is right and
whose sidecar is wrong satisfies every assertion in the test and is
exactly the divergence #1177 shipped.

Verified rather than assumed: rotating  onto the next row,
leaving the columns untouched, PASSES the previous version of this test
and fails the new one. Dropping the sidecar entirely fails it too.

 next door does compare sidecars, but only between two
runs - it pins them as DETERMINISTIC, not correct, and a
consistently-wrong sidecar passes it every time.

Also drops the Debug-scraping out of , which parsed a decimal
back out of  and had already grown a branch for two different
renderings. s variants are public; match them.
robcohen added a commit that referenced this pull request Aug 7, 2026
Self-review of this PR. The per-key assertion added for Copilot compared
`group[0]` - the projected `account` COLUMN - against the ungrouped
rows. But the group key travels separately, in `row_group_keys`,
reachable only through `group_key(i)`. A row whose column is right and
whose sidecar is wrong satisfies every assertion in the test and is
exactly the divergence #1177 shipped.

Verified rather than assumed: rotating `group_key()` onto the next row,
leaving the columns untouched, PASSES the previous version of this test
and fails the new one. Dropping the sidecar entirely fails it too.

`results_match` next door does compare sidecars, but only between two
runs - it pins them as DETERMINISTIC, not correct, and a
consistently-wrong sidecar passes it every time.

Also drops the Debug-scraping out of `number_of`, which parsed a decimal
back out of `{:?}` and had already grown a branch for two different
renderings. `Value`'s variants are public; match them.
robcohen added a commit that referenced this pull request Aug 7, 2026
…aries (#1983)

* test(query): algebraic properties, and a generator that reaches boundaries

#1902 Phase 1, the last uncovered crate. Miri excludes this one for
rowan reasons that are not going away, so this is the compensating
coverage.

The existing properties ask whether the same input gives the same
answer twice. These ask whether the answer is RIGHT, via relationships
that hold whatever the ledger contains - so they need no expected
value, which is what makes them checkable over generated input:

- WHERE p and WHERE NOT p must PARTITION the unfiltered rows. Neither
  half may invent, lose or double-count. A predicate that misevaluates
  in one direction only shows up as a union that no longer
  reconstructs the whole.
- Grouping must preserve the total: SUM(number) GROUP BY account,
  summed back over groups, equals the ungrouped SUM. That is the
  invariant #1177 broke - rows right, group-key sidecar wrong.
- ORDER BY must permute, never add, drop or alter. Sorting is where a
  comparator that is not a total order loses rows, and the
  null-ordering tests next door pin WHICH order rather than that the
  multiset survived.

Aimed where this crate actually breaks: #1177 was a grouping/parallel
divergence, and the two bugs found by hand this cycle (#1963, #1966)
were both in evaluation rather than parsing.

Also widens the amount generator, which sabotaging the partition
property is how I found. Swapping `number > 0` for `number > 1`
changed NOTHING - because with a uniform -1_000_000..1_000_000 range,
landing in (0, 1] needs |n| <= 10^scale, at most 1000 of two million
draws, about 0.3 expected hits across a whole run. There was nothing
between 0 and 1 to lose. Now three magnitude bands, and that same
sabotage fails.

Every property sabotage-verified: overlapping halves fail the
partition, a wrong total fails the grouping, a dropped row fails the
permutation, and the boundary case fails now where it did not before.

* test(query): pin each group against the rows that carry its key

Copilot: the total alone is blind to the failure #1177 actually was.
Permute the sums across account labels and the total still reconciles
perfectly, with every group attributed to the wrong key.

Sabotage-verified by doing exactly that - rotating each group sum onto
the next key. The total assertion stays green; only the new per-key one
fires.

Also reattaches a doc comment that ended up over amount_strategy
instead of txn_strategy.

* test(query): assert the group-key SIDECAR, not just the projected column

Self-review of this PR. The per-key assertion added for Copilot compared
`group[0]` - the projected `account` COLUMN - against the ungrouped
rows. But the group key travels separately, in `row_group_keys`,
reachable only through `group_key(i)`. A row whose column is right and
whose sidecar is wrong satisfies every assertion in the test and is
exactly the divergence #1177 shipped.

Verified rather than assumed: rotating `group_key()` onto the next row,
leaving the columns untouched, PASSES the previous version of this test
and fails the new one. Dropping the sidecar entirely fails it too.

`results_match` next door does compare sidecars, but only between two
runs - it pins them as DETERMINISTIC, not correct, and a
consistently-wrong sidecar passes it every time.

Also drops the Debug-scraping out of `number_of`, which parsed a decimal
back out of `{:?}` and had already grown a branch for two different
renderings. `Value`'s variants are public; match them.

* test(query): identify partition rows by three columns, and fix the boundary math

Both from Copilot, both real.

The partition compared multisets of bare NUMBERS, so a WHERE path that
dropped one row and duplicated another carrying the same number
reconstructed perfectly and the property said nothing. Not a remote
shape here: every generated transaction posts `amt` to a random account
and `-amt` to Assets:Bank, so equal numbers are the common case.

Verified by modeling exactly that - find two rows sharing a number,
drop one, duplicate the other:

  keys = number alone      -> passes
  keys = date|account|number -> fails

Rows are now identified by all three, so a coincidence needs all three
to agree.

And the boundary arithmetic in `amount_strategy` was wrong. `scale` is
`0u32..3`, which is EXCLUSIVE - 0, 1 or 2 - so the ceiling is 10^2, not
10^3. Landing in (0, 1] needs 0 < n <= 100, at most 100 of two million
values, about 0.04 expected hits across a run rather than 0.3. The
conclusion holds and gets stronger: not one run in twenty-five would
have produced a value between 0 and 1.
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.

[Bug]: Query errors out

2 participants