Skip to content

fix(loader): options in an included file no longer govern the ledger - #2159

Merged
robcohen merged 5 commits into
mainfrom
fix/options-scope-across-includes
Aug 27, 2026
Merged

robcohen merged 5 commits into
mainfrom
fix/options-scope-across-includes

Conversation

@robcohen

Copy link
Copy Markdown
Member

Closes #2151.

An option set in an included sub-ledger applied to the whole tree, last one included winning. Two of those change numbers:

option in an included file bean-query before after
booking_method "LIFO" error, ambiguous reduction books the 20.00 lot, exit 0 error, exit 1
inferred_tolerance_default "USD:0.05" 0.04 residual fails balances fails
title master's value last include's value master's value

An included file could make an unbalanced transaction pass, and could change which lot every other entity's sales consumed.

Scoped per option, not by one blanket rule

Options that describe the file declaring them still accumulate: operating_currency, documents, insert_pythonpath, display_precision, and plugins (which never routed through here). Everything else comes from the top-level ledger.

The split is deliberately not the repeatable-option list. Repeating within one file and crossing an include are different properties, and conflating them is the bug: inferred_tolerance_default accumulates within a file and must still not cross an include.

This does not undo #1546, and its implementation was not at fault

#1546 asked for two things. The first is right and stays: E7003 should not be a hard error. The second, last-wins extended to include trees, it requested explicitly:

Implement beancount last-wins ... For an include tree this gives natural precedence — the most-recently-included / nearest declaration wins.

That rested on "beancount permits redefining a scalar option with last-wins" -- true inside one file, false across include, where the loader takes the top-level file's options and aggregates only three (operating_currency, dcontext, insert_pythonpath). The request was reasonable; the belief behind it was not. This is a decision to revisit, not a regression to revert.

#1546's own repro is the evidence. It has option "title" "Combined" in the master and a title in each sub-ledger. It already exited 0 before this change, so its actual complaint was fixed by the warning alone -- and it resolved to "Entity B", whichever file was included last. It now resolves to "Combined", matching bean-check, still exiting 0.

Deliberately not copying beancount wholesale

Its uniform rule also discards plugins from included files:

plugin "beancount.plugins.auto_accounts"   (declared in the include)

beancount:  plugin list [], does not run, 2 ValidationErrors for unopened accounts
rustledger: runs, accounts auto-opened, exit 0

A sub-ledger declaring the transformation it needs is legitimate. We are right here, so "match beancount" could not be the rule. That behaviour is unchanged and tested.

E7003's wording was wrong

"Option X can only be specified once" is false -- bean-check accepts a redefinition and takes the last value, which is why #1546 asked for it to stop being an error. Within a file it now says the last value wins; across an include it says the value was ignored and the top-level ledger governs, so a reader can tell why their setting had no effect.

CACHE_VERSION 29 -> 30

Options is part of the cached payload, so a v29 cache replays the old resolution and resurrects the leak. Found the hard way: the verification matrices kept diverging until the stale caches were cleared, which is exactly the failure the version exists to prevent.

The two archived-layout tripwires advance to fixture version 30 with their byte arrays untouched -- this changes which options resolve, not how anything is encoded. That is the point of those tripwires, and they forced the question rather than letting it pass.

Checks

  • Every row of all four matrices verified against bean-query 3.2.3.
  • Booked-value gate: known 34, found 34, new 0 across 761 files.
  • Both proofs real: reverting the scope flag brings the leak back end-to-end (exit 0 again), and disabling the check fails the new unit tests.
  • Full workspace tests green; 104 in rustledger-loader.
  • Clippy clean on 1.96 and CI's 1.97; RUSTDOCFLAGS="-D warnings" cargo doc clean -- it caught a private intra-doc link that cargo test does not.

🤖 Generated with Claude Code

https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr

Closes #2151.

An option set in an included sub-ledger applied to the whole tree, last one
included winning. `booking_method` decides which lot a sale consumes and
`inferred_tolerance_default` decides what counts as balanced, so a sub-ledger
silently changed results for every other entity, including the master's own
transactions. An included file could make an unbalanced transaction pass.

Scoped per option, by what the option governs rather than by one blanket
rule. Options describing the file that declares them still accumulate:
`operating_currency`, `documents`, `insert_pythonpath`, `display_precision`,
and plugins, which never routed through here. Everything else now comes from
the top-level ledger.

Note the split is NOT the repeatable-option list. Repeating within one file
and crossing an include are different properties, and conflating them is the
bug: `inferred_tolerance_default` accumulates within a file and must still not
cross an include.

This does not undo #1546 and its implementation was not at fault. #1546 asked
for two things: E7003 should not be a hard error, which is right and stays,
and last-wins extended to include trees, which it requested explicitly. That
second request rested on "beancount permits redefining a scalar option with
last-wins", true inside one file and false across `include`, where beancount
takes the top-level file's options and aggregates only three. The request was
reasonable; the belief behind it was not.

#1546's own repro is the clearest evidence. It has `option "title" "Combined"`
in the master and a title in each sub-ledger. It already exited 0 before this
change, so its actual complaint was fixed by the warning alone, and it
resolved to "Entity B", the last file included. It now resolves to "Combined",
matching bean-check, while still exiting 0.

Deliberately NOT copying beancount wholesale. Its uniform rule also discards
plugins declared in included files, which leaves the user with validation
errors about accounts a plugin they did declare would have opened. We run
them, and that stays.

E7003's wording was wrong in both spellings and is fixed: "can only be
specified once" is false, since bean-check accepts a redefinition and takes
the last value. Within a file it now says the last value wins; across an
include it says the value was ignored and the top-level ledger governs, so a
reader can tell why their setting had no effect.

CACHE_VERSION 29 to 30, with the wasm pin. `Options` is part of the cached
payload, so a v29 cache replays the old resolution and resurrects the leak.
Found the hard way: the verification matrices kept diverging until the stale
caches were cleared. The two archived-layout tripwires advance to fixture
version 30 with their byte arrays untouched, which is the point of them:
this changes which options resolve, not how anything is encoded.

Verified against bean-query on all three rows of both value-changing options,
plus title and the plugin case. Booked-value gate reports `known 34, found
34, new 0` across 761 files. Both proofs are real: reverting the scope flag
brings the leak back end-to-end, and disabling the check fails the unit tests.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
@robcohen
robcohen requested a review from a team as a code owner August 26, 2026 18:38
Copilot AI lite review requested due to automatic review settings August 26, 2026 18:38
@codecov

codecov Bot commented Aug 26, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.85057% with 1 line in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger-loader/src/options.rs 98.80% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

@github-actions

github-actions Bot commented Aug 26, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 49.8ms ± 5.4ms 750.3ms ± 4.0ms 15.1x 55.1 MB / 50.1 MB
investment 73.6ms ± 3.5ms 2829.9ms ± 17.4ms 38.5x 59.2 MB / 58.1 MB
fifo 69.5ms ± 3.6ms 16211.9ms ± 223.6ms 233.1x 61.2 MB / 57.8 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 47.1ms ± 3.4ms 49.8ms ± 5.4ms +5.6% ✅ within noise 55.1 MB → 55.1 MB (+0.0%)
investment 70.4ms ± 3.0ms 73.6ms ± 3.5ms +4.5% ✅ within noise 59.0 MB → 59.2 MB (+0.3%)
fifo 69.5ms ± 4.1ms 69.5ms ± 3.6ms +0.0% ✅ within noise 61.0 MB → 61.2 MB (+0.4%)

A difference counts only when it clears the combined spread of the two measurements, per shape (2σ: simple 2.9ms, investment 2.0ms, fifo 2.4ms), 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

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 rustledger-loader option scoping so that options declared in included sub-ledgers no longer govern the entire include tree (preventing included files from silently changing booking/balancing behavior), while still allowing explicitly “file-describing” options (e.g., operating_currency, documents, etc.) to accumulate across includes. This aligns resolution with the stated intent in #2151 and bumps the loader cache version to prevent stale caches from replaying the old behavior.

Changes:

  • Add include-scope-aware option application (Options::set_scoped) and wire the loader to use it based on include depth.
  • Update E7003 duplicate-option wording to reflect “last value wins” semantics within a file; add unit tests for include scoping.
  • Bump loader cache version (29 → 30) and update WASM-side pin/fixtures accordingly.

Reviewed changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated 3 comments.

File Description
crates/rustledger-loader/src/options.rs Introduces include-aware option setting, new scoping list, updated E7003 duplicate wording, and adds tests for include scoping behavior.
crates/rustledger-loader/src/lib.rs Computes top_level from include_stack depth and routes parsed options through set_scoped.
crates/rustledger-loader/src/cache.rs Bumps cache version to 30 and updates fixture version commentary to reflect the option-resolution semantic change.
crates/rustledger-wasm/src/cache.rs Updates the loader cache version pin used by WASM cache tests to match the loader’s bumped version.

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

Comment thread crates/rustledger-loader/src/options.rs Resolved
Comment thread crates/rustledger-loader/src/options.rs Resolved
Comment thread crates/rustledger-loader/src/options.rs Resolved
@github-actions

Copy link
Copy Markdown
Contributor

✅ Compatibility Test Results

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

robcohen and others added 4 commits August 26, 2026 19:31
…recations

Three review findings on #2159, and a regression the third one exposed.

The scope notice reused E7003. That code means "specified twice, last value
wins" and maps downstream to `ErrorCode::DuplicateOption`, but an option
ignored for coming from an included file may be the only one of its name in
the tree. It now has E7009, documented alongside the others.

Giving it a code was not enough, and this is the part worth recording.
`cmd::check` classified severity as `warning.code != "E7003"`, so the new code
was an error, and #1546's own repro started exiting non-zero again -- the
exact complaint that issue was filed about, reintroduced by fixing a
different problem. Every unit test still passed. What caught it was running
that ledger end to end, and there was already a test doing exactly that:
`test_check_multi_entity_include_duplicate_option_ok`. Confirmed by reverting
the classification and watching it fail. That test now also asserts the
resolved title is "Combined", which is what the ledger asked for and what
#2151 makes it get.

The scope check also swallowed more specific diagnostics. `option "plugin"`
is deprecated and raises E7004, which `check` treats as an error; reporting
only the ignore notice would have made an included file the one place a
deprecated option stopped failing the build. Deprecation is now raised first,
from a shared table so the scope branch cannot drift from the three arms that
already had those messages inline.

Also moves `REPEATABLE_OPTIONS`'s doc comment back onto it. The new constant
was inserted between the comment and the item it documented, so the list
about include scoping was introduced as "Options that can be specified
multiple times". Same mistake as the one review caught on #2148.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
…n option

The note on `ACCUMULATE_ACROSS_INCLUDES` said plugins are absent from the list
because they "never route through here". True of the `plugin "name"`
DIRECTIVE, which is collected separately and accumulates from any file. Not
true of the deprecated `option "plugin"` form, which is a known option, does
route through `set_scoped`, and is scoped out like everything else.

The distinction is the reason the include-scope branch re-raises E7004 two
screens below, so a reader who believed the old sentence would have found
that code path unexplained. Verified both halves: `option "plugin"` in an
included file now reports E7004 and E7009 together, while a `plugin`
directive in an included file still runs and the ledger still checks clean.

Third PR running where reading the finished diff end to end turned up a
comment whose "why" had stopped being true. The pattern is consistent enough
to be worth naming: comments that restate code age harmlessly, comments that
explain why something must be a certain way go actively wrong.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
Four sites spelled out the E7004 push: the three arms for deprecated options
and the include-scope branch added with #2151. The arms reached it through
`deprecation_message(key).unwrap_or_default()`, which is the shape worth
removing: an entry dropped from the table would have produced an E7004 with
an EMPTY message rather than any visible failure, and an empty diagnostic is
worse than a missing one because it still counts as an error.

`warn_if_deprecated` now owns raising it and reports whether it fired, so the
message can only come from the table and the table is the only thing to keep
in step.

Verified each of the three still reports its own text at top level, and that
a deprecated option inside an include still reports E7004 and E7009 together
with neither message empty.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
It reported whether it had fired, and none of its four callers looked. A
return value nothing consumes is a standing invitation to assume it matters,
and the doc said "reporting whether it was" as though someone acted on it.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
@robcohen
robcohen merged commit 713350c into main Aug 27, 2026
88 checks passed
@robcohen
robcohen deleted the fix/options-scope-across-includes branch August 27, 2026 02:02
robcohen added a commit that referenced this pull request Aug 28, 2026
Review catches on #2174, all three from Copilot.

The gated set is FOUR columns -- entry, meta, _entry_meta, _posting_meta
-- not five. I wrote five in the code comment, the commit message and the
PR body.

Inserting expr_calls_any_function above query_references_column detached
that function's doc comment onto the new one, leaving
query_references_column undocumented and the new helper described by
someone else's prose. Third time I have done this exact thing (#2148,
#2159), and the shape is always the same: adding an item directly above
one that already had a doc comment.

The metadata-function test looped over three of the four dispatched
names, omitting POSTING_META, so a gate that forgot it would have passed.
Confirmed the test now fails when POSTING_META alone is dropped from the
detected list.
robcohen added a commit that referenced this pull request Aug 28, 2026
* perf(query): skip #postings columns the query cannot observe

Five of this table's 31 columns hold most of its cost: the structured
`entry` object and the three metadata maps (`meta`, `_entry_meta`,
`_posting_meta`). They are now built only when the query can observe
them.

On a 40k-posting ledger, best of three:

    SELECT count(account) FROM #postings   433ms/227MB -> 240ms/131MB
    SELECT account FROM #postings          484ms/229MB -> 296ms/133MB
    SELECT meta('k') FROM #postings        482ms/228MB -> 290ms/135MB
    SELECT * FROM #postings               1617ms/844MB -> 1419ms/766MB

With #2173 that is 681ms/517MB -> 240ms/131MB for the first, -65% and
-75%.

The other 26 columns were measured and left alone: stubbing both
`StringSet` columns moved 443ms to 437ms. Gating them would cost more in
review surface than it saves.

Three ways to reach a gated column, each of which fails SILENTLY when the
gate is too tight -- a missed one yields Null, not an error:

  * By name, including through an attribute: `entry.narration` reaches
    `entry` because `expr_references_column` recurses into
    `Attribute`/`Subscript` operands.
  * By FUNCTION: `META`, `ENTRY_META`, `ANY_META` and `POSTING_META` are
    dispatched by name and then read `_posting_meta` / `_entry_meta` off
    the row. A query calling `meta('key')` names neither column, so
    gating on column references alone drops the data it needs. Detected
    with a new `query_calls_any_function`, which mirrors
    `query_references_column`'s clause coverage and walks the OVER
    clause -- the case Copilot caught on #1085.
  * By wildcard, which forces on only what `SELECT *` can SHOW. This
    table's wildcard emits `meta` but omits `entry` and the underscore
    helpers, since `wildcard_hidden` drops the structured entry column to
    match beanquery. Forcing all five was the first attempt and left
    `SELECT *` with no improvement at all.

Verified by diffing query output against a main-built binary across 17
shapes, including `SELECT *, entry.narration` and
`SELECT * ORDER BY entry.narration`, and re-run after the clippy
refactor rather than assumed. Each of the three gates is confirmed to
fail its own assertion when removed.

Closes #2169

* fix(query): correct the gated-column count and re-attach a doc comment

Review catches on #2174, all three from Copilot.

The gated set is FOUR columns -- entry, meta, _entry_meta, _posting_meta
-- not five. I wrote five in the code comment, the commit message and the
PR body.

Inserting expr_calls_any_function above query_references_column detached
that function's doc comment onto the new one, leaving
query_references_column undocumented and the new helper described by
someone else's prose. Third time I have done this exact thing (#2148,
#2159), and the shape is always the same: adding an item directly above
one that already had a doc comment.

The metadata-function test looped over three of the four dispatched
names, omitting POSTING_META, so a gate that forgot it would have passed.
Confirmed the test now fails when POSTING_META alone is dropped from the
detected list.

* test(query): cover query_calls_any_function directly

Review addition on #2174. The new walker was only exercised through
#postings queries, and two of its arms cannot be reached that way:
`meta('k') BETWEEN ...` type-errors before the gate matters, and window
functions are rejected outright with an explicit FROM #postings. A direct
unit test now covers every clause and every expression shape, mirroring
the sibling test for query_references_column.

Each arm was confirmed to fail the test when made to return false.
Removing an arm outright does not compile: the match is exhaustive with
no catch-all, so a future Expr variant is a build error rather than a
silent false -- worth having, since a false negative here materializes
nothing and meta('k') returns Null with no error.

Also corrects the claim that walking the OVER clause was load-bearing
here. It mirrors expr_references_column so the two stay
interchangeable; this call site cannot reach it.

* docs(query): record the instruction-count measurement

Review addition on #2174. The wall-clock numbers were the only evidence,
and they move with machine load. Callgrind on the profiling harness puts
the combined #2169 + #2173 effect at 457.4M -> 244.2M instructions, -47%,
which does not.

It also closes the loop on the harness gap #2173 fixed: the system-table
shapes added there are exactly the ones that improved, so the harness now
measures the path it previously could not see.
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.

Options set in an included file override the master ledger, silently changing booking method and balance tolerance

2 participants