Skip to content

fix(parser): keep each header string in its own field after an invalid token - #2944

Merged
robcohen merged 10 commits into
mainfrom
fix/header-recovery-no-shift
Nov 12, 2026
Merged

robcohen merged 10 commits into
mainfrom
fix/header-recovery-no-shift

Conversation

@robcohen

@robcohen robcohen commented Nov 11, 2026 •

Copy link
Copy Markdown
Member

What changed

A transaction whose header holds an invalid token is kept under rledger's error recovery. An invalid token runs to the next blank, as in beancount's lexer, so it can swallow a string: in * "p" \x11"y" the "y" is part of the invalid token. Counting only the strings that survived then moved them to another field:

Header Before After
* "p" \x11"y" / * "p" \x11 no payee, narration p payee p, narration ""
txn "p" \x11 #t ^l no payee, narration p payee p, narration "", tags/links unchanged
* \x11"x" narration "" unchanged
* \x11 "n" / * \x11 "n" \x11 narration n unchanged
* 123 "n" \x11 / * 2024-01-03 "n" \x11 narration n unchanged
* \x11 "p" "n" / * "p" \x11 "n" payee p, narration n unchanged
* "n" #t \x11 narration n unchanged
* "Coffee" 5.00 USD (forgotten newline) narration Coffee unchanged

One rule decides the fields: txn_header::header_strings, documented in its rustdoc. It reads token kinds only and returns string indexes. Red convert_transaction, green convert_transaction_header, and the typed ast::Transaction::payee() / narration() accessors (read by the formatter) all use it.

  • A lone string right after the flag (nothing before it but the date and the flag), followed by an invalid token before any tag or link, is the payee with an empty narration. The invalid token stands where the narration was written.
  • Everything else keeps beancount's count rule: one string is the narration, two are the payee and the narration, and three or more keep the existing recovery.
  • Only an invalid token can have swallowed a string, so no other unexpected token (a number, a currency, an account, a later date, a second flag, #!) holds a slot. A mid-line BOM lexes as an invalid token.

Why

Issue decision: keep the transaction and never shift fields. The CLI refuses ledgers with parse errors, but the LSP (outline, folding, payee completion), WASM parse and FFI embedders load despite them and showed the shifted data. WASM BQL refuses on parse errors, so it is unaffected.

Error counts and spans are unchanged:

  • compat-parse-error-parity.py --check reports no regressions.
  • The STRICT parser and CST baselines pass with no manifest change. BASELINE_UPDATE=1 leaves lima's ErrorInTransactionLine entry as on main.

Over 30,000 random headers compared against origin/main (662aa9f), status, errors and formatter output are identical. Fields change on 130 headers, all of which hold an invalid token. Each change is the same: a lone narration X became payee X with an empty narration. No valid header changes.

Caches: WASM v102 is needed, because the WASM cache can hold a ledger with parse errors. Loader v73 only follows the pin convention, because the loader cache is never saved for a load with errors. Both sit above main (loader v71, WASM v99 after #2945). Holders of the skipped numbers: loader v72 is #2931 and v74 is #2946; WASM v100 is #2931, v101 is #2952 and v103 is #2946 (v98 was never released).

How to test

  • cargo test -p rustledger-parser --test txn_header_invalid_token_fields: payee, narration, tags, links, posting count, error count and first-error span, green/red parity, and the typed AST accessors. It covers invalid tokens and 16 other unexpected-token kinds after the string, before it, around it and after a tag.
  • cargo test -p rustledger-parser test_header_strings_moves_no_string test_convert_transaction_header_invalid_token_moves_no_string: the rule over every kind, and the green header walk itself compared against parse_red_only.
  • cargo test -p rustledger-lsp test_document_symbols_invalid_token_after_payee_keeps_the_payee
  • cd crates/rustledger-wasm && wasm-pack test --node (wasm_header_invalid_token.rs)

Review round 1

  • * <bad> "p" <bad> no longer moves p to the payee.
  • ast::Transaction::payee() / narration() read the shared rule.
  • The loader v73 note says the bump only follows the pin convention.
  • The count > 0 nit was removed in the rewrite.
  • Round 1 also made every unexpected token hold a slot. Round 2 reverts that (below).

Review round 2

  • Narrowed to invalid tokens. A number, currency, account, date, second flag or #! cannot swallow a quoted string, so it holds no slot and the count rule stands: * "Coffee" 5.00 USD keeps the narration. The tests/ast.rs flip and the lima manifest change are reverted, since neither header has an invalid token, and both files now match main. The unit, integration, green and WASM tables, the rustdoc, the red-side comment and the CHANGELOG are updated to match.
  • The DATE exception is gone. Only the transaction's own date is skipped. A later date before the string is an ordinary token, so * 2024-01-03 "n" \x11 gives narration n, as * 123 "n" \x11 does. More generally, the payee exception needs the string straight after the flag. The missing error for a date in the flag position is left for the separate fix.
  • Nits:
    • The dead k != DATE guard is gone.
    • The rule now reads kinds only, so the green walk no longer tracks offsets at all, which settles the offset-comment nit.
    • The cache notes name the actual holders.
  • Mutation checks: making every kind hold the slot fails the tests, so does making NUMBER hold it, and so does dropping the ERROR_TOKEN arm.
  • Merged origin/main (perf(lsp): coalesce diagnostics during bursts of edits #2941, test(ffi-component): find the component under CARGO_TARGET_DIR #2943).

Final round

Closes #2932

🤖 Generated with Claude Code

…d token

A transaction whose header holds an invalid token is kept under error
recovery, but its payee and narration were read by counting only the
strings that survived, so `* "p" <bad>` loaded with no payee and the
narration `p`. The LSP, WASM and FFI, which load despite parse errors,
showed the shifted fields.

Both walks (red `convert_transaction`, green `convert_transaction_header`)
now read the fields through one shared rule,
`txn_header::header_payee_narration`: an invalid token before the first
tag or link holds the string slot it sits in. A lone string followed by
one is the payee, with an empty narration; a lone string after one is the
narration; two strings are the payee and narration whatever surrounds
them. Error counts and spans are unchanged.

Loader cache v73, WASM cache v98.

Closes #2932

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@robcohen
robcohen requested a review from a team as a code owner November 11, 2026 07:11
@github-actions

github-actions Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

🔴 Slower than base on: simple

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 34.7ms ± 3.0ms 443.3ms ± 1.8ms 12.8x 45.1 MB / 50.9 MB
investment 50.3ms ± 1.6ms 1573.9ms ± 28.8ms 31.3x 47.0 MB / 59.0 MB
fifo 49.3ms ± 0.9ms 7922.9ms ± 49.0ms 160.6x 48.3 MB / 58.9 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 32.7ms ± 0.6ms 34.7ms ± 3.0ms +6.0% 🟡 slower 45.2 MB → 45.1 MB (-0.2%)
investment 51.1ms ± 2.6ms 50.3ms ± 1.6ms -1.5% ✅ within noise 47.3 MB → 47.0 MB (-0.5%)
fifo 51.6ms ± 2.3ms 49.3ms ± 0.9ms -4.4% ✅ within noise 49.1 MB → 48.3 MB (-1.6%)

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

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 826
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

…rule

Review round 1 of the header recovery fix (#2932):

- A lone string is the payee only when an unexpected token follows it and
  none comes before it, so `* <bad> "n" <bad>` keeps the narration `n`: a
  token written after a string no longer changes its field.
- Every token the header grammar has no place for holds its slot, not only
  an invalid token: a number, a currency, an account, `~`, `@`, a brace, a
  comma, a keyword, a second flag, a mid-line `#!`. `* "p" 123` keeps
  payee `p`, as `* "p" <bad>` does.
- The rule is `txn_header::header_strings`, which returns string indexes,
  so the typed `ast::Transaction::payee()` / `narration()` accessors use it
  too and cannot drift from the directive. Formatter output is unchanged.
- The loader cache v73 note says the bump only follows the pin convention:
  that cache is never saved for a load with errors.
- The parser corpus baseline entry for lima's ErrorInTransactionLine
  (`* "Dinner" A:*:B`) moves: `Dinner` is now the payee.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
robcohen and others added 4 commits November 11, 2026 08:21
…t the payee

Review round 2 of the header recovery fix (#2932):

- Narrow the rule to the one token that can have swallowed a string: an
  invalid token (a mid-line BOM lexes as one). A lone string right after
  the flag, followed by an invalid token, is the payee with an empty
  narration. Every other case keeps beancount's count rule, so
  `* "Coffee" 5.00 USD` (a forgotten newline) keeps the narration
  `Coffee`, and anything before the string (`* 123 "n" <bad>`,
  `* 2024-01-03 "n" <bad>`, `* <bad> "n" <bad>`) leaves it the narration.
- `header_strings` now reads token kinds only; the date and flag are told
  apart by position, so the green walk no longer tracks offsets and the
  dead `k != DATE` guard is gone.
- The `tests/ast.rs` flip and the lima parser-corpus manifest change are
  reverted: neither header has an invalid token.
- Cache notes name the actual holders of the skipped versions.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Reword the header_strings doc: a transaction node opens only on a flag
token, a string, a tag or a link, not on an invalid token. Add the
[date, bad, s, bad] case, so dropping the ERROR_TOKEN guard in the flag
arm (which would read the invalid token as the flag and move the string
to the payee) fails a test.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
robcohen added a commit that referenced this pull request Nov 11, 2026
… and escape query's option messages

Review round 3 of #2945.

- Loader CACHE_VERSION 69 -> 71 (WASM pin 71). Ignoring an included
  `documents` option (E7009) changes loader output: a v69 blob of a ledger
  whose include sets an existing `documents` root kept serving the
  `document` entries with no E7009. v70 is held by #2931 and v73 by #2944.
  The CostNumber and MetaValue fixture tripwires move to 71; no archived
  layout moved.
- rledger query escapes an option diagnostic's message on the terminal
  path, as Diagnostic::to_line does (#2538), with a test.
- CHANGELOG: ag-rledger query warnings carry optional file and line keys;
  rledger merge refuses a tree whose include sets documents.

Refs #2925

Co-Authored-By: Claude Opus 5.5 <[email protected]>
robcohen and others added 2 commits November 11, 2026 15:25
…id token

The control-chars load-error tests from #2922 use the header
`* "bell\u{7}" junk`. With this branch the invalid token after the
lone string keeps that string in the payee, so the control character is
reported in the payee rather than the narration.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@codecov

codecov Bot commented Nov 11, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 97.47475% with 5 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger-parser/src/cst/green.rs 93.10% 4 Missing ⚠️
crates/rustledger-lsp/src/handlers/symbols.rs 94.44% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

robcohen added a commit that referenced this pull request Nov 12, 2026
Brings in #2947. Conflicts resolved keeping both sides:
- CHANGELOG Fixed section: both entries kept.
- rustledger-wasm cache.rs: main's v97 note kept, this branch's v99
  note follows it (v98 is held by #2944). CACHE_VERSION stays 99.
- rustledger-wasm api.rs and parsed_ledger.rs: main's
  reported_ledger_errors (drops advisory-only E1004) plus this branch's
  located option diagnostics.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
…o-shift

# Conflicts:
#	CHANGELOG.md
#	crates/rustledger-wasm/src/cache.rs
robcohen added a commit that referenced this pull request Nov 12, 2026
…nd locate every option diagnostic (#2945)

* fix(loader)!: validate options in included files as beancount does, and locate every option diagnostic

beancount parses each included file with its own Builder and fresh
options: every value an option's converter rejects is an error at the
included file's line (bean-check exits 1), and only the top-level file's
values are kept. rledger reported every included option as the E7009
warning, valid or not, and exited 0.

set_scoped_inner now reads an included non-accumulating option into a
scratch Options, keeps its diagnostics and drops the value. E7009 is left
for a value the converter accepts. An included name_* root still does
not root that file's own accounts (E1005), a deliberate deviation now
commented and pinned.

Every option diagnostic (E7001 to E7011) carries the option's file and
line: OptionWarning gains `site`, stamped by set_scoped_at, and E7006 /
E7010 are located from the applied values. rledger check (text, JSON, and
ag-rledger check through it), the LSP (diagnostic on the option line, in
the file it is in), WASM option_errors and multi-file Ledger errors read
it. WASM validateMultiFile now reports option diagnostics at all.

Drift guards pin check's JSON and text, the LSP's two paths and WASM's
two multi-file paths to the loader's sites. WASM cache v99; the loader
cache never stores a ledger with option diagnostics, so it stays at v69.

Refs #2925

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(loader): one canonical option-diagnostic mapping, and keep a ledger's options off unrelated LSP buffers

Review round 1 of #2945.

- rustledger_loader::option_warnings_to_errors maps OptionWarning::site to
  LedgerError::location (column 1). rledger check, the LSP and WASM (via
  From<LedgerError>) read it; the WASM helper is a one-argument wrapper
  and single-source entry points drop the file with without_files.
- LSP: a buffer the ledger does not include gets its own options'
  diagnostics, never the ledger's drawn on its lines.
- LSP option range stops before a `; comment`; the live-buffer limitation
  is documented.
- Options::locate is by occurrence, so a repeated documents value is
  located at each of its lines.
- validate_with_filesystem reports option diagnostics beside a fatal load
  error or a processing failure.

Refs #2925

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(loader): ignore an included documents option as beancount does, and locate query's option diagnostics

Review round 2 of #2945.

- documents leaves ACCUMULATE_ACROSS_INCLUDES: beancount 3.2.3 keeps only
  the top-level file's (load_file gives documents == [] for an included
  root and bean-check exits 0 with it missing), so an included value is
  read by the scratch converter and ignored with E7009, never scanned or
  checked (no E7006).
- rledger query prints option diagnostics through the canonical mapping,
  with file and line; ag-rledger's query warnings carry them.
- WASM Ledger::from_file_map's processing-error arm keeps the option
  diagnostics, as validate_with_filesystem does.
- LSP option_error_file_id uses SourceFile::id.
- Tests pin site_of's last-line choice (E7010), without_locations
  clearing every site, and included documents.

Refs #2925

Co-Authored-By: Claude Opus 5.5 <[email protected]>

* fix(loader): bump the loader cache for the included documents option, and escape query's option messages

Review round 3 of #2945.

- Loader CACHE_VERSION 69 -> 71 (WASM pin 71). Ignoring an included
  `documents` option (E7009) changes loader output: a v69 blob of a ledger
  whose include sets an existing `documents` root kept serving the
  `document` entries with no E7009. v70 is held by #2931 and v73 by #2944.
  The CostNumber and MetaValue fixture tripwires move to 71; no archived
  layout moved.
- rledger query escapes an option diagnostic's message on the terminal
  path, as Diagnostic::to_line does (#2538), with a test.
- CHANGELOG: ag-rledger query warnings carry optional file and line keys;
  rledger merge refuses a tree whose include sets documents.

Refs #2925

Co-Authored-By: Claude Opus 5.5 <[email protected]>

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
#2945 took loader v71 and WASM v99, so this branch keeps loader v73 and
moves WASM to v102 (v100 and v101 are held by #2931 and #2952).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@robcohen
robcohen merged commit 8773d67 into main Nov 12, 2026
67 of 68 checks passed
@robcohen
robcohen deleted the fix/header-recovery-no-shift branch November 12, 2026 07:08
robcohen added a commit that referenced this pull request Nov 12, 2026
Resolve the CHANGELOG and WASM cache conflicts with #2944. Main is now at
WASM cache v102 (loader v73), so this PR moves its WASM CACHE_VERSION from
101 to 103, with its note after main's v102 note; v101 was never released.
LOADER_CACHE_VERSION_PIN stays at main's 73, since this PR does not move
the loader cache.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
robcohen added a commit that referenced this pull request Nov 12, 2026
robcohen added a commit that referenced this pull request Nov 12, 2026
Loader cache v74 and WASM cache v104 for #2931, above main's v73 / v102
(#2944) and #2952's WASM v103.

Co-Authored-By: Claude Opus 5.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.

fix(parser): an invalid token in a transaction header shifts the payee into the narration

1 participant