Skip to content

test(query): algebraic properties, and a generator that reaches boundaries - #1983

Merged
robcohen merged 4 commits into
mainfrom
chore/query-properties
Aug 7, 2026
Merged

robcohen merged 4 commits into
mainfrom
chore/query-properties

Conversation

@robcohen

@robcohen robcohen commented Aug 7, 2026

Copy link
Copy Markdown
Member

#1902 Phase 1 — the last uncovered crate. (Supersedes #1982, which was opened on a test/ branch that the branch-name gate rejects; the policy allows feat/fix/chore/docs/refactor/perf/release/hotfix.)

Miri excludes rustledger-query for
rowan reasons that are not going away, so this is the compensating coverage.

Three algebraic properties

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

property what it catches
WHERE p and WHERE NOT p partition the unfiltered rows a predicate that misevaluates in one direction only — the union stops reconstructing the whole
grouping preserves the total the #1177 shape: rows right, group-key sidecar wrong
ORDER BY is a permutation a comparator that is not a total order losing or duplicating rows

Aimed where this crate actually breaks: #1177 was a grouping/parallel-path
divergence, and the two bugs found by hand this cycle (#1963, #1966) were both
in evaluation rather than parsing. The neighbouring null-ordering tests pin
which order; none pinned that the multiset survived it.

The generator was the more interesting finding

Sabotaging the partition property is how it surfaced. Swapping number > 0 for
number > 1 — a filter that should lose every row between them — changed
nothing.

With a uniform -1_000_000..1_000_000, landing in (0, 1] needs
|n| <= 10^scale: at most 1000 of two million draws, roughly 0.3 expected
hits across an entire run
. There was nothing between 0 and 1 to lose.

The amount strategy now spans three magnitude bands, and that same sabotage
fails. This affects the pre-existing determinism properties too, which were
sampling the same narrow band.

Sabotage-verified

sabotage result
the two halves overlap partition fails
compare against a filtered total grouping fails
drop a row from the ordered side permutation fails
number > 1 (boundary) fails now; passed before the generator fix

Worth noting the third and fourth: my first two attempts at sabotaging the
partition were no-ops — one because the generator filters zero amounts, one
because it never produced boundary values. A sabotage that doesn't fail is
either a bad sabotage or a real gap, and telling those apart is where the
generator weakness came from.

cargo test --workspace — 132 suites, 0 failures. Clippy clean.

Second commit — Copilot's point on #1982

The total alone is blind to the failure #1177 actually was. Permute the group
sums across the account labels and the total still reconciles perfectly; every
group is simply attributed to the wrong key. So each group is now also pinned
against the ungrouped rows carrying that key.

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

…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.
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.
@github-actions

github-actions Bot commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 35.2ms ± 2.8ms 24.1 MB
beancount 888ms ± 6.1ms 50.6 MB
Comparison 25.2x faster 2.1x less

vs main branch (2026-08-07)

Metric main this PR Change
Time 37.1ms 35.2ms -5.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

@codecov

codecov Bot commented Aug 7, 2026

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

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

This PR expands rustledger-query’s test coverage by adding property-based “algebraic invariant” tests that validate result correctness via relationships (partitioning, grouping, permutation) instead of fixed expected outputs, and it strengthens the generated amount distribution to better hit boundary conditions.

Changes:

  • Adds a new amount generator strategy intended to sample multiple magnitude bands, improving coverage around boundary values.
  • Introduces three algebraic proptest properties: predicate/negation partitioning, grouping total + per-key ownership, and ORDER BY permutation preservation.
  • Adds helper utilities to extract/query numeric values used by the new properties.
Suppressed comments (1)

crates/rustledger-query/tests/pipeline_invariants.rs:216

  • Same as all_numbers: numbers_where also only keys on number, so a dropped/duplicated row with the same numeric value can be masked. Selecting date, account, number keeps the partition check sensitive to row-level differences while still being sortable via a debug-joined key.
    let q = parse(&format!("SELECT number WHERE {predicate}")).expect("query parses");
    let r = Executor::new(ledger).execute(&q).expect("runs");
    let mut v: Vec<String> = r.rows.iter().map(|row| format!("{:?}", row[0])).collect();
    v.sort();

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

@github-actions

github-actions Bot commented Aug 7, 2026

Copy link
Copy Markdown
Contributor

⚠️ Compatibility Test Results

Metric Result
Check Compatibility 100%
BQL Compatibility 95% (raw 89%, 162 masked)
Full AST Match 100%
Total Files 812
What's tested
  • Check: Exit codes and error counts match bean-check
  • BQL: Query results match bean-query
    The headline is the EFFECTIVE rate, after pairs where beanquery
    itself is wrong are masked. raw is the same run with nothing
    masked. A widening gap means the registry grew, not that rledger
    changed.
  • Files: ~800 test files downloaded from 10+ beancount repositories

Full results available in workflow artifacts

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
robcohen force-pushed the chore/query-properties branch from 4e1431f to 76203d1 Compare August 7, 2026 14:43
@robcohen

robcohen commented Aug 7, 2026

Copy link
Copy Markdown
Member Author

Self-review — the sidecar assertion was still testing the wrong thing

Pushed a fix. My response to Copilot's comment added a per-key assertion that compared group[0] — the projected account column — against the ungrouped rows. But the group key travels separately, in row_group_keys, reachable only through the public QueryResult::group_key(i). A row whose column is right and whose sidecar is wrong satisfies every assertion the test had, and that is precisely the divergence #1177 shipped.

Verified rather than argued. Rotating group_key() onto the next row, leaving every projected column untouched:

rotated sidecar dropped sidecar
previous version of this test passes —
with the sidecar assertion fails fails

So Copilot's point stood after my first answer to it, and only the direct group_key(i) == group[..1] assertion actually closes it.

Worth naming why the existing coverage didn't already cover this: results_match next door does compare sidecars — but only between two runs of the same query. It pins them as deterministic, not as correct, and a consistently-wrong sidecar passes it every time. That is a general trap with determinism properties, and it's the reason this PR exists.

Also dropped the Debug-scraping out of number_of, which parsed a Decimal back out of {:?} output and had already grown a branch to cope with two different renderings — a test reaching through a formatting impl that is free to change. Value's variants are public; it now matches them.

…undary 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.
@robcohen

robcohen commented Aug 7, 2026

Copy link
Copy Markdown
Member Author

Both Copilot comments were right; fixed in 1379d0d.

The partition really was weaker than its docstring. Comparing multisets of bare numbers cannot see a WHERE path that drops one row and duplicates another carrying the same number — and that is the common case here, not a remote one: every generated transaction posts amt to a random account and -amt to Assets:Bank, so equal numbers abound.

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

row identity result
number alone passes — the union still reconstructs
date|account|number fails

Rows are now identified by all three, so a coincidence has to agree on all of them.

And the boundary arithmetic was wrong. scale is 0u32..3 — exclusive, so 0, 1 or 2 — which puts the ceiling at 10^2, not 10^3. Landing in (0, 1] needs 0 < n <= 100: at most 100 of two million values, so about 0.04 expected hits across a run, not 0.3. The conclusion survives and gets sharper — not one run in twenty-five would have produced a value between 0 and 1, which is why swapping number > 0 for number > 1 changed nothing.

@robcohen
robcohen merged commit e5cff77 into main Aug 7, 2026
55 of 57 checks passed
@robcohen
robcohen deleted the chore/query-properties branch August 7, 2026 17:52
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