Skip to content

fix(query): accounts and other_accounts are sorted sets; other_accounts excludes only the current posting - #2489

Merged
robcohen merged 8 commits into
mainfrom
fix/bql-accounts-set
Oct 8, 2026
Merged

robcohen merged 8 commits into
mainfrom
fix/bql-accounts-set

Conversation

@robcohen

@robcohen robcohen commented Oct 7, 2026 •

Copy link
Copy Markdown
Member

What changed

On the default postings table:

  • accounts is now the transaction's posting accounts as a sorted, deduped set (bean-query: {p.account for p in entry.postings}). It repeated an account posted to twice and kept posting order.
  • other_accounts now excludes only the current posting, by index, then sorts and dedupes (bean-query: sorted({p.account for p in entry.postings if p is not context.posting})). It dropped every posting whose account name matched the current one.

FROM #postings had the same other_accounts fault (name-based filter) and is fixed too. One helper, Executor::posting_account_set(txn, exclude) in system_tables.rs, now builds the set for the default table, #postings, #entries and #transactions; the three HashSet-then-sort copies are gone.

Verification

Ledger with two Expenses:Food postings and one Assets:Bank, plus a second transaction with three distinct accounts. SELECT date, account, accounts, other_accounts and the same FROM #postings now give exactly bean-query 0.2.0 / beancount 3.2.3's rows (e.g. Expenses:Food row: other_accounts = Assets:Bank, Expenses:Food; Assets:Bank row: Expenses:Food).

  • New test test_accounts_and_other_accounts_with_repeated_account (both tables). It fails without the fix (accounts was ["Expenses:Food", "Expenses:Food", "Assets:Bank"]) and passes with it.
  • cargo test -p rustledger-query --all-features, workspace clippy -D warnings, cargo doc -D warnings clean.

Performance (review follow-up, commit 073a7f8)

The first version of this PR made #postings slower on a large transaction: it rebuilt the account set twice for every posting, so one transaction of n postings cost O(n²). #postings now builds the sorted set, plus the accounts used by more than one posting, once per transaction, and derives other_accounts from them. The default table builds its per-row set with sort+dedup over borrowed names instead of a BTreeSet.

Release builds, run interleaved, median times. The machine was under load (load average about 16 on 8 cores), so small differences are noise:

ledger / query main first version now
one 5,000-posting txn + 2,000 small: SELECT account, other_accounts 11.2 s 0.77 s 0.67 s
same, ... FROM #postings 2.55 s 3.22 s 0.33 s
same, SELECT count(*) FROM #postings 1.81 s 2.47 s 0.16 s
60,000 three-posting txns: SELECT account, accounts, other_accounts 1.51 s 1.57 s 1.51 s
same, ... FROM #postings 2.47 s 2.50 s 2.44 s

The default table got faster on the big transaction because each row now carries about 51 deduped names instead of 5,001.

Instruction counts (cachegrind)

Wall time on the loaded machine was noisy, so these are instruction counts (valgrind --tool=cachegrind --cache-sim=no). All binaries are release builds with the shipping mimalloc feature, run with BEANCOUNT_DISABLE_LOAD_CACHE=1. Base is main 184e9d1; head is c6a840f.

ledger query main head change
one 5,000-posting txn + 2,000 small SELECT account, accounts, other_accounts 106.6 G 20.5 G −81%
same ... FROM #postings 15.9 G 1.31 G −92%
same SELECT count(*) FROM #postings 14.9 G 0.28 G −98%
same load only (SELECT count(*) WHERE false) 0.130 G 0.130 G 0
60,000 three-posting txns SELECT account, accounts, other_accounts 4.649 G 4.679 G +0.6%
same ... FROM #postings 7.40 G 7.10 G −4.0%
same SELECT count(*) FROM #postings 4.77 G 4.47 G −6.3%
same load only 2.981 G 2.981 G 0

The +0.6% on the default table is the price of a correct set: main collected the names unsorted and undeduped. One version I tried during review cost +2% there because it allocated an extra vector per call; deduping in place brought it down to +0.6%.

Follow-up, not in this PR: the default table is still quadratic within one transaction

On the default table, each row builds its transaction's set from every posting, so one transaction of n postings costs O(n²): 20.5 G instructions for 5,000 postings, against 0.28–1.3 G on #postings. Main was quadratic too, with a 5× larger constant.

  • Fix: add a field such as txn_accounts: Option<Arc<TxnAccounts<String>>> to PostingContext (executor/types.rs). Fill it in scan_postings (executor/mod.rs, where each PostingContext is built), once per transaction (postings of one transaction are contiguous in the scan, as the #postings memo already relies on), and only when the query references accounts or other_accounts. That is a new ScanNeeds flag via query_references_column, which includes the WHERE clause because WHERE evaluates against the context before filtering. evaluate_column reads the field and falls back to TxnAccounts::of when it is None; the three dummy contexts in evaluation.rs and the one in dual_eval_parity.rs pass None. About 40 lines plus a test.
  • Why not a cache on Executor: default-table rows are evaluated in parallel (par_iter in execution.rs), so a shared cache needs a lock on the hot path. The column is also read from WHERE, GROUP BY, ORDER BY and aggregate paths, which only see the context. And a cache keyed by a transaction's address is unsafe once FROM OPEN ON synthesizes transactions whose memory can be reused.
  • Why it is a separate PR: PostingContext is public (rustledger_query::executor::PostingContext, every field pub, not #[non_exhaustive]), so adding a field breaks any caller that builds one with a struct literal. That needs a ### Breaking entry, or first making the struct #[non_exhaustive]. I did not want to slip an API break into a correctness fix.

One implementation

A single type, TxnAccounts, builds every accounts and other_accounts value: the default table, #postings, #entries and #transactions. It is generic over borrowed names (the default table: one set per row, with no copies until output) and owned names (#postings: one set per transaction, keyed by directive index like the existing last_entry memo). A unit test checks others against excluding the posting by index over four shapes, and fails when its repeated-account rule is mutated away.

Docs

docs/reference/bql.md described other_accounts with the old rule: "every account in the transaction except the current posting's own account". It now says the accounts of every other posting, sorted and deduped, so the current posting's account stays when another posting uses it. The accounts row was updated to match.

Synthesized postings

FROM OPEN ON synthesizes a transaction whose two postings share Equity:Opening-Balances (the opening-balances account summarized into itself). bean-query gives other_accounts = Equity:Opening-Balances there; main gave an empty set. This PR agrees with bean-query. On a ledger with a pad, OPEN ON, and OPEN ON ... CLOSE ON ... CLEAR, every row matches bean-query. New test other_accounts_on_a_synthesized_self_transfer fails on main. The two-transaction extension of test_accounts_and_other_accounts_with_repeated_account catches a per-transaction set that is never refreshed: I checked by mutating the cache key, and the test failed.

Closes #2483

🤖 Generated with Claude Code

https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr

…nly the current posting

On the default postings table `accounts` repeated an account a
transaction posts to twice and kept posting order, and `other_accounts`
dropped every posting sharing the current posting's account name. Both
are now sorted, deduped sets, and `other_accounts` excludes only the
current posting by index, matching bean-query. `#postings` had the same
`other_accounts` fault; one helper now builds the set for every table.

Closes #2483

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
@robcohen
robcohen requested a review from a team as a code owner October 7, 2026 20:04
@codecov

codecov Bot commented Oct 7, 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 Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 36.1ms ± 2.5ms 578.1ms ± 6.1ms 16.0x 51.2 MB / 50.1 MB
investment 54.4ms ± 1.0ms 2164.9ms ± 13.3ms 39.8x 55.0 MB / 58.1 MB
fifo 52.1ms ± 1.3ms 12059.1ms ± 110.2ms 231.3x 55.4 MB / 57.8 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 34.8ms ± 0.4ms 36.1ms ± 2.5ms +3.6% ✅ within noise 51.3 MB → 51.2 MB (-0.0%)
investment 53.7ms ± 0.6ms 54.4ms ± 1.0ms +1.4% ✅ within noise 55.1 MB → 55.0 MB (-0.2%)
fifo 52.1ms ± 0.7ms 52.1ms ± 1.3ms +0.1% ✅ within noise 55.1 MB → 55.4 MB (+0.5%)

A difference counts only when it clears the combined spread of the two measurements, per shape (2σ: simple 1.1ms, investment 0.5ms, fifo 0.6ms), and is at least 5%.
10,000 transactions per shape · 20 runs, 3 warmup · hyperfine

What do these numbers mean?
  • simple — Two-posting transfers, one currency. The historical workload — keep as the floor, not as the benchmark.
  • investment — Cost specs, per-unit prices and lot reductions. Exercises booking and inventory, which simple leaves at 0.3%.
  • fifo — Bare {} reductions against a FIFO account — how FIFO sells are normally written. The other four shapes reach the ordered-selection path twice in 2k transactions between them, so it was effectively unprofiled until it turned out to be quadratic (plan_ordered scans every lot per reduction: FIFO ledgers are quadratic (8.8s at 20k transactions) #2083).
  • vs base: the PR and the base-branch commit it is built on, built and measured in the same job
  • RSS: peak resident set size, a single sample — reported without a verdict because there is no spread to test it against
  • A shape with no beancount column is one bean-check reports errors on; it is timed for rledger only

@github-actions

github-actions Bot commented Oct 7, 2026 •

Copy link
Copy Markdown
Contributor

✅ Compatibility Test Results

Metric Result
Check Compatibility 100%
BQL Compatibility 100% (raw 93%, 179 masked)
Full AST Match 100%
Total Files 819
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

Review follow-up. `#postings` rebuilt the account set for every posting,
twice, so a transaction of n postings cost O(n^2) (slower than main on a
5,000-posting transaction). It now builds the sorted set and the
repeated accounts once per transaction and derives `other_accounts`
from them. The default table builds its sets with sort+dedup instead of
a BTreeSet. Tests pin a second transaction (a stale per-transaction set
would show) and an OPEN ON synthesized self-transfer.

Refs #2483

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
@robcohen

robcohen commented Oct 8, 2026 •

Copy link
Copy Markdown
Member Author

Review (final: 5 passes)

Passes 1–3:

  • Fixed a quadratic slowdown in #postings: the set is now built once per transaction instead of twice per posting.
  • Instruction counts (cachegrind; the table is in the PR body). One 5,000-posting transaction: count(*) FROM #postings 14.9 G → 0.28 G; default table 106.6 G → 20.5 G. 60k ordinary transactions: default table +0.6%, #postings −4% to −6%.
  • One generic TxnAccounts now serves all four tables. A unit test checks it against excluding the posting by index.
  • The default table's remaining quadratic needs a field on the public PostingContext, so it stays a follow-up; robcohen confirmed that.

Pass 4 (after merging main, which now has #2492 and #2494; merge commit 2c3cdb3, CHANGELOG kept both entries):

  • Merged tree: 794 query tests pass across 36 binaries; clippy and fmt are clean; private and public docs report 0 errors.
  • Interaction with fix(query): order BALANCES rows by account_sortkey #2492/docs(query): resolve the private intra-doc links in rustledger-query #2494: none. BALANCES ordering does not touch these columns, and docs(query): resolve the private intra-doc links in rustledger-query #2494's link fixes merged cleanly.
  • Thread safety: TxnAccounts is never shared across threads. The #postings cache is a local in a sequential loop. Default-table rows each build their own borrowed TxnAccounts<&str>, which holds no state and no lock, so par_iter is safe.
  • Same helper everywhere: #entries and #transactions both call TxnAccounts::of(txn).accounts(), the same code as the default table and #postings. Pad and other non-transaction directives build their small sets separately, from different inputs.
  • Real finding, fixed in b5f382f: docs/reference/bql.md still described other_accounts with the old name-based rule ("every account … except the current posting's own account"). It now describes the accounts of every other posting.

Pass 5 (main merged again at c0606c3, after #2497, #2487, #2496 and #2488 landed; CHANGELOG kept both entries): nothing found.

  • Merged tree: 794 query tests pass across 36 binaries; clippy and fmt are clean; private and public docs report 0 errors.
  • Every place that documents accounts / other_accounts, searched with git grep over tracked files:
    • docs/reference/bql.md (fixed in pass 4)
    • the interactive .describe postings table, which lists names and types only (other_accounts (set), accounts (set[str])), so it is correct
  • Nothing else mentions them: no other docs page, LSP hover text, wasm/ffi bindings or packages/.
  • Pre-existing gap, not this PR: the query completion list (rustledger-query/src/completions.rs) offers neither column, and it also omits description, posting_flag, price, filename and others. That is a separate follow-up.

…l time

Review follow-up. The wall-clock figure was taken on a loaded machine;
cachegrind instruction counts (mimalloc release, load cache off) are the
reproducible measure: 14.9 to 0.27 billion for `SELECT count(*) FROM
#postings` over one 5,000-posting transaction.

Refs #2483

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
…ts column

Review follow-up. The account set had two implementations: a per-row
helper and the per-transaction struct `#postings` uses, whose doc
claimed equivalence. There is now one, generic over borrowed names
(per row, no copies until output) and owned ones (`#postings`, one per
transaction, now keyed by directive index instead of an address). A
unit test checks `others` against excluding the posting by index over
several shapes.

Refs #2483

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
@robcohen
robcohen force-pushed the fix/bql-accounts-set branch from 66e2001 to c6a840f Compare October 8, 2026 02:32
robcohen and others added 4 commits October 8, 2026 03:50
…s them

Review follow-up. docs/reference/bql.md still said `other_accounts` is
"every account in the transaction except the current posting's own
account", the name-based rule #2483 replaces; it now says the accounts
of every other posting, sorted and deduped, so the current posting's
account stays when another posting uses it.

Refs #2483

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
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.

BQL: accounts and other_accounts on the postings table repeat accounts, and other_accounts drops same-account postings

1 participant