Skip to content

fix(parser): read a lone capital glued to a non-blank as one invalid token, as beancount does - #2990

Merged
robcohen merged 2 commits into
mainfrom
fix/currency-glued-word
Nov 15, 2026
Merged

robcohen merged 2 commits into
mainfrom
fix/currency-glued-word

Conversation

@robcohen

@robcohen robcohen commented Nov 15, 2026 •

Copy link
Copy Markdown
Member

What

A lone capital glued to a non-blank (U~SD, U?SD, V,, T#!) is now, with the rest of its run, one invalid token, as in beancount 3.2.3, also where the run otherwise lexes. Fixes the per-line counts of #2982: a line that already holds an invalid token ( Assets:A $ U~SD, 2024-01-02 balance Assets:A 2x U?SD) now counts beancount's 2, not 1.

The beancount rule (lexer.l, beancount 3.2.3)

[A-Z][A-Z0-9\'\.\_\-]*[A-Z0-9] { return TOKEN(CURRENCY, yytext, yyleng); }
...
[A-Z]/[ \t\n] { yylval->character = yytext[0]; return CAPITAL; }
...
{ACCOUNTTYPE}(:{ACCOUNTNAME})+ { return TOKEN(ACCOUNT, yytext); }
...
 /* Default rule. {bf253a29a820} */
. { unput(*yytext); BEGIN(INVALID); }
...
<INVALID>[^ \t\n\r]+ { build_lexer_error(yylloc, builder, "Invalid token: '%U'", input); BEGIN(INITIAL); return YYerror; }

A capital is CAPITAL only before a space, a tab or \n. Glued to anything else, a two-or-more-character CURRENCY (a later letter or digit in [A-Z0-9'._-]) or an ACCOUNT can still take it (US~D is US, ~, D; U.SD is a currency). Otherwise no rule matches, the default rule enters INVALID, and the run up to the next space, tab, \r or \n is ONE invalid token. Confirmed with lex_iter_string and bean-check on every shape in the tests.

Why it was off

The lexer here kept such a capital a token whenever the rest of its run lexed (a one-letter currency, then ~, then SD), and the parser's glued one-letter rules reported it: one error, which matched beancount's one on a clean line. After an earlier invalid token on the same line, quiet_after_invalid_tokens quiets the line's construct checks, those rules with them, so the word went uncounted. And a line whose first glued capital was reported through grammar errors (sometimes two) before the line's first invalid token miscounted a later one.

Fix

TokenIter::next (crates/rustledger-parser/src/logos_lexer.rs): after the existing lookahead (error_later_in_run, which still handles runs with an error later in them and #2966's stray-\r chains), a lone capital followed by a non-blank that is not a \r is the error; the Err arm runs it to the next blank, as it does for every invalid token. No new scan, so lexing stays linear.

Left as it was: a transaction's flag position (flag_position, and runs a flag leads via capital_rule_applies), where txn_header's glued-flag rule reports the flag and keeps the transaction (2024-01-02 P;c), and an indented date's flag keeps beancount's two errors (#2966's identify_directive arm reads only a one-letter error token as a flag). A capital before a \r stays with #2966's rule, and one at the end of the source with the existing rules.

Real-ledger control

All 1,130 .beancount files in the repository and the fetched compatibility corpus (one fava file is not UTF-8 and was skipped), main fa3680ade0a against this branch: 1,034 error-free on main, 0 flip between error-free and erroring, 0 change any per-line count. corpus_baseline (which hashes the full parse result, directives included) drifts on one file, parser-lima/test-cases_SyntaxErrors.ErrorInTransactionLine.beancount, already an error file: its A:*:B after the narration is now the invalid token beancount reports (Invalid token: 'A:*:B'), one error before and after, with the invalid-token message in place of the header one. Both baselines are updated for that line only (four ledger2beancount rows that a local fetch flags as upstream content changes are left out, as in #2988).

Caches

  • Loader: stays at 75. No input changed between error-free and erroring (0 of 450,000 generated, 0 of 1,130 ledgers): every such capital was already reported by the glued one-letter rules, and an error-free source holds none, so its tokens and directives are unchanged.
  • Web: 121 to 122, as both payloads archive parse errors.

Parity corpus (pinned fuzz 9bc79f4, matrix, tracked, compat)

Counted from the manifests (main's on origin/main, this branch's after --update): main 82,699 matching, this PR 82,828. 249 inputs newly match, 120 no longer match, and 116 that mismatch on both change category; --check passes with no regressions. (The report table's "Match" column, 82,846 here, counts all 111,341 inputs including four ledger2beancount files whose upstream content a local fetch changed and the manifest does not pin, so it is not the figure to compare.)

Of the 120: 109 count exactly what main counts with each glued run written as an ordinary invalid token ($q). 22 of those are matrix rows such as P Assets:#B, where a capital-led word that is no account is now one invalid token, as in beancount. The other 11 are fuzz lines of R:R... / :K shapes, a capital right after a :, which the analog script does not rewrite: the same mechanism.

Generated differential

Three seeds of 150,000 inputs each (about 120,000 with a lone capital glued to every ASCII punctuation, digits, é, €, Ü or a BOM, in postings, costs, prices, balances, opens, commodities, transaction headers and flags, customs, options, metadata and bare lines, after 0 to 3 earlier pieces including invalid ones, then LF, CRLF or end of file, with following postings or metadata; about 30,000 controls with capitals only before blanks). beancount 3.2.3 (the harness's run_beancount), main and branch, per line:

Seed Gained Closer Regressed Further Sideways
1 35,989 4,858 339 28 203
2 35,718 5,068 334 25 213
3 35,511 4,976 361 23 196

Documented families (all 1,722 regressed, further and sideways inputs)

  • Main counted right only by missing the word (1,662, 96.5%). The line already counts an error beancount does not report (most often a mid-line invalid date counted twice, a BOM-led account's P0006 and P0026, a glued flag before |), and the uncounted word made up for it. Each counts exactly what main counts with every glued run written as $q. None changes another line or drops a directive.
  • A glued capital in a transaction's flag position (32). Left to the glued-flag rule by design; with a | after it (2024-01-02 J|{1,50 X}~) that line already reports the flag and the deprecated pipe, one more than beancount, and a later glued word on it is now counted.
  • A BOM inside the run (11). The run also gets the BOM diagnostic, the family fix(parser): read a lone capital glued to a string past its word as one invalid token, as beancount does #2988 documented.
  • A capital right after :, (, [ or { (8), real glued runs that the analog script does not rewrite, and 9 others of the same off-by-one shape on one line.

BOM combination matrix

Regenerated with BOM_MATRIX_UPDATE=1 BOM_MATRIX_RELABEL=1: matching rows 11,004 to 11,164, known list 2,432 to 2,272. 213 rows keep their counts and gain T#! among their token texts. 44 rows count a line further from beancount than recorded, each with a hand-written reason in the known list for exactly its new counts: all hold a T#!, now counted, on a line already off by its other errors. In the further-than-main list, 20 rows main no longer beats are removed and 18 added, each accepted by a new check, main_missed_glued_capitals: main's count is exactly rledger's less the line's capital-led invalid runs (as main_read_less does for #2928's #!).

Speed

Linear. Seconds for parse_error_lines, main against this branch, at 20k / 40k / 80k / 160k repetitions:

Shape main branch
flag-led 2024-01-02 P + "x"T repeated 0.01 / 0.01 / 0.03 / 0.05 0.01 / 0.01 / 0.04 / 0.06
flag-led 2024-01-02 P@ + T@ repeated 0.01 / 0.01 / 0.02 / 0.05 0.01 / 0.01 / 0.03 / 0.05
date-glued 2024-01-02P@ + T@ repeated 0.01 / 0.01 / 0.03 / 0.05 0.01 / 0.01 / 0.03 / 0.05
indented 2024-01-02 P@ + T@ repeated 0.01 / 0.01 / 0.03 / 0.05 0.01 / 0.02 / 0.03 / 0.05
U~SD words on one line 0.01 / 0.02 / 0.03 / 0.06 0.02 / 0.04 / 0.09 / 0.21
V, run with no blank 0.01 / 0.01 / 0.02 / 0.03 0.00 / 0.00 / 0.00 / 0.00
X( words on one line 0.01 / 0.01 / 0.03 / 0.05 0.03 / 0.05 / 0.10 / 0.20
$ U~SD lines 0.03 / 0.07 / 0.13 / 0.27 0.06 / 0.12 / 0.23 / 0.50
T#! words on one line 0.49 / 2.04 / 7.86 / 29.53 0.03 / 0.05 / 0.10 / 0.23
A;x words on one line 0.03 / 0.05 / 0.10 / 0.18 0.03 / 0.05 / 0.09 / 0.19

The first version was quadratic on a run a transaction's flag leads (round-1 review: 15.8 s at 160k on the first shape). It asked capital_rule_applies, which scans back to the run's start, for every capital before the cheap next-byte test, and in a flag-led run every capital stays a token, so each one rescanned the run. The next-byte test now comes first, and a flag-led run is remembered to its end (flag_led_run_until), so it is scanned once. test_tokenize_lossless_flag_led_run_is_decided_once pins it with a byte counter (CAPITAL_RULE_SCANNED_BYTES) on the four flag-led shapes.

A blank-free run of A#! (#2989) is linear now too, as the capital makes the run one token (main 0.09 / 0.36 / 1.42 s at 10k / 20k / 40k, 0.00 here). A run of 1#!, with no capital, is unchanged (1.43 s at 40k), so #2989 stays open.

Note

10 U,SD in a posting now also gets a BOOK "cannot infer currency" error after its parse error, as main already gives 10 U$D: once U,SD is an invalid token the posting has no currency. Such a file has a parse error either way.

Tests

How to test

cargo test -p rustledger-parser --test capital_led_invalid_word
cargo test -p rustledger-parser
cargo test -p rustledger-wasm --lib cache
python -I scripts/compat-parse-error-parity.py --rledger target/release/examples/parse_error_lines --fuzz-dir <fuzz> --fuzz-commit 9bc79f4f35f52c50813164f43307e7d151d70d8c --compat-dir tests/compatibility/files --check

Closes #2982

🤖 Generated with Claude Code

…token, as beancount does

beancount lexes a lone capital (CAPITAL) only before a space, a tab or a
line break ([A-Z]/[ \t\n]). Glued to anything that starts no longer
CURRENCY or ACCOUNT, no rule takes it, and its default rule reads the run
to the next blank as one invalid token: U~SD, U?SD, V, and T#! each are.
The lexer here kept such a capital a token whenever the rest of its run
lexed, and the parser glued one-letter rules reported it. That matched on
a clean line, but after an earlier invalid token those rules are quieted
with the line other construct checks, so the word went uncounted.

The run is now the invalid token beancount reads, wherever it stands; a
transaction flag position keeps the glued-flag rule. No error-free file
changes (1,130 repository and compatibility ledgers, 450,000 generated
inputs). Web cache 121 to 122; loader cache unchanged.

Closes #2982

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

github-actions Bot commented Nov 15, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 52.6ms ± 4.6ms 808.8ms ± 2.7ms 15.4x 44.2 MB / 51.1 MB
investment 77.3ms ± 0.6ms 2936.2ms ± 28.1ms 38.0x 47.1 MB / 59.1 MB
fifo 74.9ms ± 1.2ms 14756.0ms ± 46.5ms 197.1x 49.1 MB / 58.9 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 51.5ms ± 0.3ms 52.6ms ± 4.6ms +2.2% ✅ within noise 45.1 MB → 44.2 MB (-1.8%)
investment 77.3ms ± 1.0ms 77.3ms ± 0.6ms +0.0% ✅ within noise 47.0 MB → 47.1 MB (+0.3%)
fifo 74.4ms ± 0.6ms 74.9ms ± 1.2ms +0.6% ✅ within noise 48.5 MB → 49.1 MB (+1.4%)

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

@codecov

codecov Bot commented Nov 15, 2026 •

Copy link
Copy Markdown

Codecov Report

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

Files with missing lines Patch % Lines
crates/rustledger-parser/src/logos_lexer.rs 97.91% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

@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

The glued-capital rule asked capital_rule_applies, which scans back to the
start of the blank-free run, for every lone capital, before the cheap
next-byte test. In a run a transaction flag leads every capital stays a
token, so the lexer goes on inside the run and each later capital rescanned
it: quadratic (2024-01-02 P followed by "x"T repeated: 15.8 s at 160k
against 45 ms on main). The next-byte test now comes first, and a flag-led
run is remembered to its end (flag_led_run_until), so it is scanned once. A
byte-counter test pins it on four flag-led shapes.

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.

compat(parser): a word like U~SD after an invalid token is one error fewer than beancount

1 participant