Skip to content

fix(cli): refuse to report on a file that failed to parse - #1912

Merged
robcohen merged 2 commits into
mainfrom
fix/query-fail-on-parse-errors
Jul 31, 2026
Merged

robcohen merged 2 commits into
mainfrom
fix/query-fail-on-parse-errors

Conversation

@robcohen

Copy link
Copy Markdown
Member

Closes #1908.

query and report exited 0 on a file with parse errors and printed numbers derived from the partial parse. check refused the same file, so the CLI contradicted itself — one command called a file unusable while another reported on it and claimed success.

This is a deliberate deviation, and I verified that before changing it

bean-query does exactly what rledger did:

$ bean-query broken.beancount "SELECT account, sum(number) AS n GROUP BY account" ; echo "exit=$?"
account   n
--------  -
Assets:A  0
exit=0

Byte-identical output and exit code. beancount's loader likewise returns the transaction it managed to parse past a LexerError. The rledger code said so explicitly:

// Report errors to stderr (matching bean-query behavior)
// Continue with successfully parsed directives rather than bailing

So this was not a bug — it was faithful compatibility. I filed #1908 as a plain bug, corrected the record there once I checked, and asked before deviating.

We deviate because the output is not merely incomplete, it is plausible. Assets:A 0 looks like an answer, carries a success status, and lands on stdout that another program is probably consuming. For a tool whose whole job is producing figures people rely on, confidently wrong is worse than loudly broken. CLAUDE.md's compatibility policy has a bucket for exactly this.

Scoped narrowly, on purpose

file before after
parse error exit 0, prints Assets:A 0 exit 1, no output, stderr says why
validation error only (unopened account) exit 0, prints rows unchanged

Validation errors leave the entry stream complete and the arithmetic sound. Real ledgers are full of accounts missing an open, and refusing those would be a genuine compatibility loss for no safety gain. There is a test pinning that half of the contract, because narrowing the deviation is what makes it acceptable.

CLAUDE.md deviation checklist

  • Inline comment naming the deviation — on bail_on_parse_errors and both call sites
  • Regression tests pinning the stricter behaviour — 3, all verified to fail without the guard
  • KNOWN_RUST_DIVERGENCES entry — deliberately not added. The BQL suite's load_valid_files already requires python_ok AND rust_ok, so a file neither tool parses never reaches that comparison. An entry would imply a divergence the metric cannot observe. My first draft of the doc comment claimed it was registered; that was wrong and is fixed.

Single shared helper rather than duplicated logic at the two call sites.

Provenance

Found by comparing booked values against beancount (#1910) — invisible to the shape-only comparison, which only checks posting counts.

4403 tests · clippy clean at 1.97.0 · cargo doc -D warnings clean · fmt clean.

`query` and `report` exited 0 on a file with parse errors and printed
numbers derived from the partial parse. `check` refused the same file, so
the CLI contradicted itself: one command called a file unusable while
another reported on it and claimed success.

This is a DELIBERATE DEVIATION from Python beancount, verified rather
than assumed. bean-query does exactly what rledger did:

  $ bean-query broken.beancount "SELECT account, sum(number) ..."
  account   n
  --------  -
  Assets:A  0
  exit=0

byte-identical output and exit code, and beancount's loader likewise
returns the transactions it managed to parse past a LexerError. The
existing code said so: "matching bean-query behavior / Continue with
successfully parsed directives rather than bailing".

We deviate because the output is not merely incomplete, it is PLAUSIBLE.
`Assets:A 0` looks like an answer, carries a success status, and lands on
stdout that another program is probably consuming. For a tool whose whole
job is producing figures people rely on, confidently wrong is worse than
loudly broken.

Scoped to PARSE errors only. Validation errors — an account never opened,
a failed balance assertion — leave the entry stream complete and the
arithmetic sound, so they still report exactly as beancount does. Real
ledgers are full of those and refusing them would be a real
compatibility loss for no safety gain. A test pins that half of the
contract, because narrowing the deviation is what makes it acceptable.

No `KNOWN_RUST_DIVERGENCES` entry: the BQL suite's `load_valid_files`
already requires `python_ok AND rust_ok`, so a file neither tool parses
never reaches that comparison. An entry would imply a divergence the
metric cannot observe.

Found by comparing booked VALUES against beancount (#1910), which the
shape-only comparison could not see.

Verified the tests fail without the guard.

Closes #1908
@robcohen
robcohen requested a review from a team as a code owner July 31, 2026 14:19
Copilot AI review requested due to automatic review settings July 31, 2026 14:19
@codecov

codecov Bot commented Jul 31, 2026 •

Copy link
Copy Markdown

Codecov Report

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

Files with missing lines Patch % Lines
crates/rustledger/src/cmd/loadcache.rs 93.75% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

@github-actions

github-actions Bot commented Jul 31, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 38.1ms ± 1.5ms 24.1 MB
beancount 771.2ms ± 14.2ms 50.9 MB
Comparison 20.2x faster 2.1x less

vs main branch (2026-07-31)

Metric main this PR Change
Time 37.3ms 38.1ms +2.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

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 tightens the rledger CLI contract so query and report refuse to emit results (and exit non-zero) when the input ledger has parse errors, preventing plausible-but-wrong output derived from partial parses and aligning CLI behavior with check’s “file unusable” stance.

Changes:

  • Add a shared CLI helper (bail_on_parse_errors) to detect parse failures from the loader’s LoadResult and fail early.
  • Invoke the helper from query and report load paths so they exit non-zero and emit no result rows on parse errors.
  • Add integration tests pinning refusal-on-parse-error behavior (and intended non-refusal on validation-only failures).

Reviewed changes

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

File Description
crates/rustledger/src/cmd/loadcache.rs Introduces bail_on_parse_errors to hard-fail query/report on parse errors from the raw load result.
crates/rustledger/src/cmd/query/mod.rs Calls bail_on_parse_errors after cached load and before processing to prevent queries over partially-parsed ledgers.
crates/rustledger/src/cmd/report_cmd/mod.rs Calls bail_on_parse_errors after cached load and before processing to prevent reports over partially-parsed ledgers.
crates/rustledger/tests/parse_error_refusal_test.rs Adds CLI integration tests to enforce non-zero exit and empty stdout on parse errors, and to preserve reporting on parseable-but-invalid files.
Suppressed comments (2)

crates/rustledger/src/cmd/query/mod.rs:176

  • These comments still say the command continues on parse errors, but parse failures are now refused earlier via bail_on_parse_errors. Update the wording so it’s clear this block is only about non-parse diagnostics (e.g. validation/booking).
    crate::cmd::loadcache::bail_on_parse_errors(&raw, file)?;
    let ledger = rustledger_loader::process(raw, &options)
        .with_context(|| format!("failed to load {}", file.display()))?;

    // Report errors to stderr (matching bean-query behavior)

crates/rustledger/src/cmd/report_cmd/mod.rs:505

  • This comment block describes parse-failure diagnostics reaching the report output, but parse failures are now refused above via bail_on_parse_errors. As written, it’s misleading because the loop below now only emits non-parse diagnostics.
    crate::cmd::loadcache::bail_on_parse_errors(&raw, file)?;
    let ledger = rustledger_loader::process(raw, &options)
        .with_context(|| format!("failed to load {}", file.display()))?;

    // To the caller's sink, like every other diagnostic. These are the ones an

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

Comment thread crates/rustledger/src/cmd/loadcache.rs Resolved
@github-actions

Copy link
Copy Markdown
Contributor

⚠️ Compatibility Test Results

Metric Result
Check Compatibility 100%
BQL Compatibility 93%
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
  • Files: ~800 test files downloaded from 10+ beancount repositories

Full results available in workflow artifacts

@robcohen
robcohen enabled auto-merge (squash) July 31, 2026 15:05
Two review catches.

`parse_failures` counted `LoadError::ParseErrors` GROUPS — one per file —
so a file with three parse errors reported "1 parse error(s)", and a tree
of includes would have counted files rather than problems. Now sums the
inner `errors.len()`. Verified against a three-error file: the message and
`rledger check` now agree on 3.

`validation_errors_still_report_as_beancount_does` never asserted its
fixture actually FAILS validation, so it would have passed just as
happily against a clean file while pinning nothing about the intended
contract. It now requires `check` to refuse the file, and to refuse it on
validation rather than parsing — otherwise the test silently drifts onto
the branch it is meant to contrast with.
Copilot AI review requested due to automatic review settings July 31, 2026 15:11

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

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

Suppressed comments (3)

crates/rustledger/src/cmd/loadcache.rs:170

  • The refusal message says “refusing to report on a file that did not parse”, but LoadError::ParseErrors can come from included files (the root file may parse fine while an include fails). That wording can mislead users about what actually failed; consider phrasing this as “ledger contains parse errors” (or similar) while keeping the rledger check <root> guidance.
            "{}: {parse_failures} parse error(s); refusing to report on a file that \
             did not parse. Run `rledger check {}` to see them.",
            file.display(),
            file.display(),
        );

crates/rustledger/src/cmd/query/mod.rs:175

  • After adding bail_on_parse_errors, the later comment “Continue with successfully parsed directives rather than bailing” is no longer accurate for parse errors (they now hard-fail before process). Updating the comment avoids future confusion when someone reads this flow.
    // Deliberate deviation from bean-query (#1908) — see `bail_on_parse_errors`.
    crate::cmd::loadcache::bail_on_parse_errors(&raw, file)?;
    let ledger = rustledger_loader::process(raw, &options)
        .with_context(|| format!("failed to load {}", file.display()))?;

crates/rustledger/src/cmd/report_cmd/mod.rs:503

  • The comment above the for err in &ledger.errors loop still talks about parse failures reaching this point, but parse failures are now refused earlier via bail_on_parse_errors. Updating the comment to reflect that this loop is for remaining (non-parse) diagnostics would prevent misleading documentation.
    let (raw, _from_cache) = crate::cmd::loadcache::load_result_cached(file, no_cache, verbose)?;
    // Deliberate deviation from bean-query (#1908) — see `bail_on_parse_errors`.
    crate::cmd::loadcache::bail_on_parse_errors(&raw, file)?;
    let ledger = rustledger_loader::process(raw, &options)
        .with_context(|| format!("failed to load {}", file.display()))?;

@robcohen
robcohen merged commit f96c843 into main Jul 31, 2026
59 checks passed
@robcohen
robcohen deleted the fix/query-fail-on-parse-errors branch July 31, 2026 15:31
robcohen added a commit that referenced this pull request Aug 11, 2026
* fix(parser): reject transaction headers beancount refuses

Four of the seven constructs in #2008. All four live in the transaction
header, so one rule covers them:

  #3 `* #trip "Money from CC" ^610f`  string after a tag
  #4 `* "Dinner" A:*:B`               junk after the narration
  #6 `* "Mermaid Inn" "Nice dinner" "With Caroline"`
  #7 `* "A" "B" "C"`                  more than two strings

beancount's grammar is `DATE txn txn_strings tags_links eol`, so strings
come first and tags/links follow; more than two strings parses but the
builder rejects it with "Too many strings on transaction description".
Our CST parser is deliberately permissive - it is lossless and recovers
rather than rejecting - and nothing downstream re-imposed that shape.

Case 4 falls out of the same rule rather than needing lexer work: in
`* "Dinner" A:*:B` the `A` lexes as a one-character CURRENCY, which is a
valid flag in the flag position and junk after a string. Scoping the
flag position to "before any string/tag/link" is what catches it.

The rule is written once over `(SyntaxKind, Range)` pairs in a new
`cst::txn_header`, and the red and green walkers differ only in how they
enumerate tokens. The green/red mirrors are the drift source CLAUDE.md
names; the shared rule plus the parity corpus is the defense. Removing
the green call makes `parse_green_eq_red_corpus` fail, verified.

Kind and range are all the rule needs - even the one-character CURRENCY
flag is decided by `range.len() == 1` - so neither walker needs source
access to reach a verdict, only to word the message.

Scope was set by measurement, not by taste. Tallying every token kind
that appears in a transaction header across the 731-file corpus (~30k
transactions) gives DATE, STAR, PENDING_KW, TXN_KW, STRING, TAG, LINK,
WHITESPACE, COMMENT, one-character CURRENCY - and two COLONs, both
inside the case-4 fixture. So the allowlist is evidence, and sweeping
the corpus after the change produces exactly four diagnostics: the four
target fixtures, no false positives.

Deliberately NOT widened past the evidence: `2014-01-01 * * "x"` has two
flags and beancount rejects it, but it is not one of the seven and
guessing at extra strictness is how a compatibility fix starts breaking
real files. The `|` separator keeps its own DeprecatedPipeSymbol
diagnostic instead of being re-reported here.

Requires a cache bump, and this was observed rather than reasoned:
after the parser change the first `rledger check` against the fixtures
still reported only the old downstream E1001s, because the parse cache
held the permissive parse. Loader 24 -> 25, wasm 10 -> 11, the wasm pin
with it, and both archived-layout FIXTURE_VERSION tripwires - which fire
with instructions saying which case applies. This is v15's case: which
errors are emitted changed, how anything is archived did not.

`test_lima_tests_parse` did not catch any of this, and could not have.
Its allowlist branch is a bare `continue`, so listing a fixture only
permits an error and never checks one occurs. TagThenLink,
CostEmptyComponents and CostWithSlashes sat in that list for the
parser's whole life while producing no error at all. A new
LIMA_2008_CASES table replaces that with a two-sided assertion over all
seven cases: the three unfixed rows assert we are STILL permissive, so
finishing #2008 turns the test red and forces the row to flip.

28 allowlisted fixtures are in that same one-sided position today. 22
are `GrammarExceptions*`, whose intended semantics I have not verified,
so they are left alone and noted rather than guessed at.

Effect on compat: all four files now fail to load in `rledger query`
too (#1912), matching bean-query, which is the point - they were
returning rows here and erroring there.

Refs #2008

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

* chore(baselines): regenerate parser manifest for the four #2008 fixtures

The parser-output baseline gate reported drift on exactly the four
fixtures this branch now rejects, with their SOURCE hashes unchanged -
which is the confirmation, not a surprise: same input, different parser
output, and nothing else in the corpus moved.

Only those four rows are updated. A full `regen-corpus-baselines.sh`
run also wanted to add 17 `interpolation/` rows and rewrite
`donearm-ledger/accounts.beancount`'s SOURCE hash, neither of which
belongs in this commit: the interpolation fixtures are in-tree and
absent from the committed manifest today, which CI tolerates and which
is unrelated to this change, and a differing source hash means my local
corpus copy differs from the one CI fetches. Committing either would be
drift smuggled in under a green checkmark.

The four new hashes are cross-checked: CI's strict run reported the same
16-hex prefixes that the local regeneration produced in full.

Refs #2008

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

* fix(parser): address #2020 review

Four review comments, all taken.

The one that matters: `test_lima_2008_cases_have_expected_strictness`
skipped itself when the fixture directory was missing. Those 441
fixtures are committed to the repo, so a missing directory is a broken
checkout rather than an unavailable dependency - and a self-skipping
test is the exact failure mode CLAUDE.md warns about under
"Availability-gated tests must fail loudly somewhere". Worse, skipping
would hide the very thing this table exists to pin. Now a hard assert.
I quoted that same rule in the conformance test's module doc while
leaving this skip two files away.

Also:

- `first_header_defect`'s contract said tokens run "through (not past)"
  the terminating NEWLINE, which reads as "include it". Both callers
  exclude it. Says so now, and records that NEWLINE stays in the trivia
  set only so feeding one in cannot change the verdict.
- The `unwrap_or_default()` on a non-char-boundary slice would have
  rendered `unexpected "" in transaction header`, naming nothing. Token
  ranges are always char boundaries so it is unreachable, but the branch
  now falls back to the byte range and defect kind instead of an empty
  quote.
- "three constructs" then listed four cases. Cases 6 and 7 are two
  fixtures of one construct; the doc now says that instead of leaving
  the reader to work it out.

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

---------

Co-authored-by: Claude Opus 5 <[email protected]>
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.

query/report exit 0 and emit data from a file that failed to parse

2 participants