Skip to content

fix(check): render validation errors with source snippets (closes #901) - #906

Merged
robcohen merged 1 commit into
mainfrom
fix/issue-901-validation-error-format
Apr 24, 2026
Merged

robcohen merged 1 commit into
mainfrom
fix/issue-901-validation-error-format

Conversation

@robcohen

Copy link
Copy Markdown
Member

Summary

Fixes #901. rledger check validation errors now show a miette-rendered source snippet of the offending directive with proper file:line:col location, rather than a one-liner that doesn't tell the user which transaction broke.

Before

main.beancount: error[E3001]: [E3001] Transaction does not balance: residual -1 USD
✗ 1 error

After

E3001

  x Transaction does not balance: residual -1 USD
   ,-[main.beancount:4:1]
 3 │
 4 │ ,-> 2026-04-07 * "my expense"
 5 │ │     Expenses:Expense                                    10 USD
 6 │ │->   Assets:Wallet                                      -11 USD
   : `---- here
   `----
✗ 1 error

(Color+unicode variant in a real terminal; NO_COLOR=1 shown here for readability.)

This matches information parity with Python beancount (file:line: message + transaction echo) and is actually more informative — line numbers, span highlighting, and color support. The same miette::GraphicalReportHandler path that parse errors already use.

Scope of changes

Three fixes, all using infrastructure that already existed:

  1. [E1234] duplication — ValidationError's Display impl was #[error("[{code}] {message}")], which the CLI then wrapped with error[{code}]:, producing error[E3001]: [E3001] .... Changed to #[error("{message}")]. (crates/rustledger-validate/src/error.rs)

  2. Missing location — run_validation in loader/src/process.rs was hardcoding location: None when converting ValidationError → LedgerError, even though ValidationError.span + file_id were available. Now populated via source_map.get().line_col(). (crates/rustledger-loader/src/process.rs)

  3. No source snippet — Added source_span and file_id fields to LedgerError so the check.rs CLI has the data miette needs. Added a render_ledger_error helper in report.rs that uses the existing miette handler when span info is present, falls back to a one-liner when not. (crates/rustledger/src/report.rs, crates/rustledger/src/cmd/check.rs)

Also marked LedgerError #[non_exhaustive] so future field additions don't break downstream struct-literal users.

Side-effect bug fixes

The snapshot-test updates exposed three pre-existing bugs that are now fixed as a consequence:

  • Warnings were being emitted as error[E1004] instead of warning[E1004].
  • JSON diagnostics reported line: 1, column: 1 for all validation errors (location was never propagated at all).
  • JSON message field included the [CODE] prefix inside the message body.

Test plan

  • 565 tests pass across rustledger-validate, rustledger-loader, rustledger
  • cargo fmt --check clean
  • Manual run against the reporter's exact fixture — output matches the "After" above
  • Snapshot tests updated (5 snapshots) reflecting the new output

Closes #901

Copilot AI review requested due to automatic review settings April 24, 2026 02:37
@robcohen
robcohen requested a review from a team as a code owner April 24, 2026 02:37

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 improves rledger check diagnostics by propagating validation error locations/spans into LedgerError and using miette::GraphicalReportHandler to render rich source snippets (closing #901), while also cleaning up duplicated [E1234] prefixes and fixing severity/message formatting in snapshots/JSON output.

Changes:

  • Stop duplicating error codes in ValidationError display output so CLI/JSON renderers can prepend codes consistently.
  • Propagate span + file_id into LedgerError (and derive file:line:col from SourceMap) so downstream renderers can locate errors precisely.
  • Add render_ledger_error and switch check text output to miette-based snippet rendering when span data is available (with a one-line fallback).

Reviewed changes

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

Show a summary per file
File Description
crates/rustledger/src/report.rs Adds render_ledger_error to render LedgerError via miette when span+file_id are present.
crates/rustledger/src/cmd/check.rs Switches text-mode error printing to render_ledger_error and uses the ledger SourceMap for snippet rendering.
crates/rustledger-loader/src/process.rs Extends LedgerError with source_span/file_id, propagates location info from validation errors, and marks LedgerError non-exhaustive.
crates/rustledger-validate/src/error.rs Removes [CODE] prefix from ValidationError’s Display to avoid double-tagging.
crates/rustledger/tests/snapshots/*.snap Updates CLI snapshot outputs (text + JSON) to reflect new rich rendering and corrected location/severity/message fields.
Comments suppressed due to low confidence (1)

crates/rustledger/src/cmd/check.rs:554

  • let source_map = ledger.source_map; moves the source_map field out of ledger, but ledger is still used later in this scope (e.g. for err in &ledger.errors, and under python-plugin-wasm ledger.options). This will fail to compile due to a partial move. Consider keeping ledger as mut and borrowing &ledger.source_map when rendering, or destructure ledger once into the individual fields you need (directives/errors/options/source_map) so you don’t access a partially moved value.
    let source_map = ledger.source_map;

    // Convert process errors to diagnostics, using the phase field to
    // split into parse/validate/plugin categories.
    for err in &ledger.errors {

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

Comment thread crates/rustledger/src/report.rs Resolved
Comment thread crates/rustledger/src/report.rs Resolved
Comment thread crates/rustledger/src/report.rs Resolved
@robcohen
robcohen force-pushed the fix/issue-901-validation-error-format branch from a8512e0 to b46700e Compare April 24, 2026 02:44
@codecov

codecov Bot commented Apr 24, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 93.93939% with 6 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger-loader/src/process.rs 77.27% 5 Missing ⚠️
crates/rustledger/src/report.rs 98.46% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

@github-actions

github-actions Bot commented Apr 24, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 32.8ms ± 0.3ms 21.5 MB
beancount 755.2ms ± 10.3ms 50.1 MB
Comparison 23x faster 2.3x less

vs main branch (2026-04-24)

Metric main this PR Change
Time 27.4ms 32.8ms +19.7% 🔴
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

@robcohen
robcohen force-pushed the fix/issue-901-validation-error-format branch from b46700e to d8bcae2 Compare April 24, 2026 02:50
@github-actions

github-actions Bot commented Apr 24, 2026 •

Copy link
Copy Markdown
Contributor

✅ Compatibility Test Results

Metric Result
Check Compatibility 99%
BQL Compatibility 100%
Full AST Match 99%
Total Files 782
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 force-pushed the fix/issue-901-validation-error-format branch from d8bcae2 to 04f9a2e Compare April 24, 2026 16:00
Closes #901.

Before:
    main.beancount: error[E3001]: [E3001] Transaction does not balance: residual -1 USD
    ✗ 1 error

After (miette-rendered, NO_COLOR=1 for clarity):
    E3001

      x Transaction does not balance: residual -1 USD
       ,-[main.beancount:4:1]
     3 |
     4 | ,-> 2026-04-07 * "my expense"
     5 | |     Expenses:Expense                                    10 USD
     6 | |->   Assets:Wallet                                      -11 USD
       : `---- here
       `----
    ✗ 1 error

Three fixes, all using infrastructure that already existed:

1. Remove the `[E1234]` prefix from ValidationError's Display impl. CLI
   and IDE renderers prepend `error[CODE]:` themselves, so the bare
   message is what Display should produce. Eliminates the double tag.

2. Populate LedgerError.location (previously hardcoded to None) from
   ValidationError's span + file_id during run_validation. The source
   map lookup and span->line:col conversion already existed in the same
   file; just wire them up.

3. Add `source_span` and `file_id` fields to LedgerError and render
   validation errors through miette's GraphicalReportHandler (the same
   path parse errors already use) when both are present. Falls back to
   a single `file:line:col: error[CODE]: message` line when not.

Also marks LedgerError #[non_exhaustive] so future field additions
don't break downstream struct-literal users.

Snapshot tests updated to reflect the new output; three pre-existing
bugs were exposed and fixed as a side effect:
- Warnings were emitted as `error[E1004]` instead of `warning[E1004]`.
- JSON diagnostics reported line 1 for all validation errors (no
  location was propagated at all).
- JSON message field included the `[CODE]` prefix in the message body.

All 565 tests in the affected crates pass.
@robcohen
robcohen force-pushed the fix/issue-901-validation-error-format branch from 04f9a2e to 4ec28e6 Compare April 24, 2026 16:14
@robcohen
robcohen added this pull request to the merge queue Apr 24, 2026
Merged via the queue into main with commit 9b8a1c3 Apr 24, 2026
33 of 35 checks passed
@robcohen
robcohen deleted the fix/issue-901-validation-error-format branch April 24, 2026 17:06
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]: Highlight which transaction is erroring out

2 participants