Skip to content

fix: never invent a cost number the author did not write - #2023

Merged
robcohen merged 1 commit into
mainfrom
fix/booking-missing-numbers
Aug 11, 2026
Merged

robcohen merged 1 commit into
mainfrom
fix/booking-missing-numbers

Conversation

@robcohen

Copy link
Copy Markdown
Member

The two booking-layer halves of #2008. They looked like separate problems and turned out to be one root cause: the parser manufactured a number where the source had none, and every layer downstream treated the invention as fact.

Case 5 — the rule was already there

{USD} / { # USD} loaded clean where beancount reports "Too many missing numbers for currency group". I expected to have to build per-currency-group accounting. I didn't — interpolation already enforces "at most one unknown per currency group" and already counts a cost spec with no determinable number as one unknown.

It never fired because of one line:

Some(CostNumber::Compound {
    per_unit: pre_hash.unwrap_or_default(),        // 0 when the author wrote nothing
    total: post_hash_total.unwrap_or_default(),    // 0 when the author wrote nothing
})

{ # USD} became Compound { per_unit: 0, total: 0 } — a perfectly determinable zero cost. A zero is not an unknown, so the count rule had nothing to count. Reporting None when both sides are absent makes the existing rule reject the fixture with no change to the booker at all.

The misdiagnosis — the same defect in different clothes

{, 100.0 USD, , } had its 100.0 scraped out of a spec we had just diagnosed as malformed, and rledger check then said:

E3001  Transaction does not balance: residual 980.10 USD

An arithmetic complaint about a typo, whose number this parser produced rather than the author. A malformed component list now yields no cost number at all, handing the posting to interpolation as an unknown. Both fixtures lose the E3001 and keep the parse error naming the real cause:

P0012  parse error: empty cost-spec component before ","…
E1001  Account Assets:Invest:AAPL was never opened      <- legitimate, kept

This reuses cost_spec_shape's rule rather than adding a second predicate: first_cost_spec_defect is now generic over the payload carried with each kind, so the diagnostic path passes byte ranges and the converter passes () and asks only is this malformed. One rule, two uses.

Scope, and what I deliberately did not touch

Only both sides of the # missing. {100 # USD} and {# 500 USD} still default the absent side to zero; beancount treats it as MISSING and would solve for it, which is a larger change I have no oracle to check against. The corpus says it isn't urgent — { # CCY} appears in exactly one file (the #2008 fixture), and the one-sided forms appear only in other parser-lima conformance fixtures.

Two verification failures worth reading

The new load-level test could never have failed. It asserted only that rledger check fails — but the fixture's accounts are never opened, so check exits non-zero on E1001 whatever the booker decides. Reverting the fix left it green. It now asserts the rejection contains the too-many-unknowns message.

And the sabotage run that should have caught that was itself invalid. The reverted binary kept passing because the parse cache still held the fixed build's output — reverting code doesn't change CACHE_VERSION. Only with BEANCOUNT_DISABLE_LOAD_CACHE=1 does removing the fix turn the test red:

ParseLots.CostTotalJustCurrency must be rejected FOR THE RIGHT REASON -
expected "multiple postings missing amounts" in the output.

That is the same cache that hid the #2020 diagnostics — twice in one issue now.

Verification

  • New cost_spec_unknowns.rs runs through load + process, because the parser change only matters if the pipeline reaches beancount's verdict. It includes both controls that matter: a single numberless spec must still interpolate clean (the off-by-one that would break real ledgers), and a well-formed spec that genuinely doesn't balance must still report E3001 (otherwise "no E3001" would be satisfied by having broken the validator).
  • Full workspace suite green; clippy 1.97.0 and fmt clean.
  • Baseline manifest: 3 rows, source hashes asserted unchanged.
  • Cache 26 → 27 (wasm 12 → 13). Unlike v25/v26 this changes archived values, not just which errors are emitted — a stale blob would serve the invented number to a build that no longer produces one.

Closes #2008

The two booking-layer halves of #2008. They looked like separate
problems and turned out to be one root cause: the parser manufactured a
number where the source had none, and every layer downstream treated the
invention as fact.

Case 5 (`{USD}` / `{ # USD}`) loaded clean where beancount reports "Too
many missing numbers for currency group". The rule was not missing -
interpolation already enforces "at most one unknown per currency group"
and counts a cost spec with no determinable number as one unknown. It
never fired because `{ # USD}` parsed as `Compound { per_unit: 0,
total: 0 }`: `unwrap_or_default()` on both sides of the `#`. A
determinable zero is not an unknown, so the count rule saw nothing to
count. With both sides reported as `None`, the existing rule rejects the
fixture unchanged.

The misdiagnosis was the same defect wearing different clothes.
`{, 100.0 USD, , }` had its `100.0` scraped out of a spec we had just
diagnosed as malformed, and `rledger check` then reported `E3001 does
not balance: residual 980.10 USD` - an arithmetic complaint about a
typo, whose number this parser produced rather than the author. A
malformed component list now yields no cost number at all, which hands
the posting to interpolation as an unknown. Both fixtures lose the
E3001 and keep the parse error that names the real cause.

That reuses `cost_spec_shape`'s rule rather than adding a second
predicate: `first_cost_spec_defect` is now generic over the payload
carried with each kind, so the diagnostic path passes byte ranges and
the converter passes `()` and asks only whether the spec is malformed.
One rule, two uses.

Scoped to BOTH sides of the `#` missing. `{100 # USD}` and `{# 500 USD}`
still default the absent side to zero; beancount treats it as MISSING
and would solve for it, which is a larger change I have no oracle to
check against. The corpus says it is not urgent: `{ # CCY}` appears in
exactly one file (the #2008 fixture) and the one-sided forms only in
other parser-lima conformance fixtures.

Two things about the verification are worth recording, because the first
version of both was wrong.

The new load-level test originally asserted only that `rledger check`
fails. That can never fail: the fixture's accounts are never opened, so
check exits non-zero on E1001 whatever the booker decides. Reverting the
fix left it green. It now asserts the rejection contains the
too-many-unknowns message.

And the sabotage run that should have caught THAT was itself invalid:
the reverted binary kept passing because the parse cache still held the
fixed build's output, and reverting code does not change CACHE_VERSION.
Only with `BEANCOUNT_DISABLE_LOAD_CACHE=1` does removing the fix turn
the test red. Same cache that hid the #2020 diagnostics, twice in one
issue.

Cache 26 -> 27 (wasm 12 -> 13). Unlike v25/v26 this one changes archived
VALUES rather than which errors are emitted, so a stale blob would serve
the invented number to a build that no longer produces one.

Closes #2008

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_018bGRsKA42peqSnz4VMreBG
Copilot AI lite review requested due to automatic review settings August 11, 2026 15:34
@robcohen
robcohen requested a review from a team as a code owner August 11, 2026 15:34
@github-actions

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 37.5ms ± 0.4ms 24 MB
beancount 762.8ms ± 7.2ms 50.7 MB
Comparison 20.3x faster 2.1x less

vs main branch (2026-08-11)

Metric main this PR Change
Time 27.9ms 37.5ms +34.4% 🔴
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

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 fixes a compatibility/correctness bug in the booking pipeline where the CST converter could manufacture a CostNumber (defaulting missing values to zero) for cost specs that did not actually contain a number, causing both incorrect acceptance of fixtures and downstream misdiagnostic balance errors. It also bumps loader/WASM cache versions because the archived directive values change when CostSpec.number is now correctly preserved as None.

Changes:

  • Update cost_spec_from_tokens to emit CostSpec.number = None for malformed component lists and for { # CCY} when both sides of # are missing, instead of inventing a zero compound number.
  • Refactor first_cost_spec_defect to be payload-generic so the same rule can be used both for diagnostics (with ranges) and conversion (shape check only).
  • Add/strengthen regression tests (pipeline-level) and bump cache versions/baselines to reflect the changed archived values and error surfaces.

Reviewed changes

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

Show a summary per file
File Description
tests/baselines/parser-corpus.manifest Updates baseline hashes for affected parser-lima fixtures now that parsing/archiving output changes.
crates/rustledger/tests/fixture_tests.rs Adds a load-level assertion for #2008 case 5 to check for the correct interpolation rejection message.
crates/rustledger-wasm/src/cache.rs Bumps WASM cache version and pins it to loader cache v27 due to archived value changes.
crates/rustledger-parser/src/cst/cost_spec_shape.rs Makes the cost-spec shape rule generic over payload to reuse it for conversion without duplicating logic.
crates/rustledger-parser/src/cst/convert.rs Stops inventing cost numbers when the component list is malformed or when { # CCY} has no numbers on either side.
crates/rustledger-loader/tests/cost_spec_unknowns.rs Adds end-to-end pipeline tests ensuring numberless/malformed cost specs remain unknown and don’t produce invented-number E3001 errors.
crates/rustledger-loader/src/cache.rs Bumps loader cache version + fixture pins to v27 because archived CostSpec values change.

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

@codecov

codecov Bot commented Aug 11, 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

Copy link
Copy Markdown
Contributor

⚠️ Compatibility Test Results

Metric Result
Check Compatibility 100%
BQL Compatibility 95% (raw 91%, 101 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

@robcohen

Copy link
Copy Markdown
Member Author

This one I'm declining — I believe it's a false positive, and it's checkable rather than a matter of opinion.

Iterating &[(&str, &str)] yields &(&str, &str), but Rust's default binding modes (match ergonomics) destructure through the reference: the pattern (stem, expected) matches the referenced tuple and binds each element as &&str. Both are then used in format!/contains, which take them by reference anyway, so nothing else needs to change.

The evidence is that it builds and runs:

test test_lima_2008_load_rejections ... ok
test result: ok. 1 passed; 0 failed

and clippy --workspace --all-features --all-targets -- -D warnings on 1.97.0 (CI's pinned version) is clean, so it isn't compiling with a suppressed lint either.

Happy to switch to for &(stem, expected) in … if you'd rather see the reference destructured explicitly — it's equivalent and arguably clearer about the binding mode — but the current form is correct as written, so I'd rather not churn the diff on a compile error that doesn't exist.

@robcohen
robcohen merged commit 5959acc into main Aug 11, 2026
64 of 68 checks passed
@robcohen
robcohen deleted the fix/booking-missing-numbers branch August 11, 2026 16:16
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.

[Compat]: parser accepts seven constructs beancount rejects, and misdiagnoses two of them

2 participants