Skip to content

perf(parser): parse a line of mid-line #!, #+ or % in linear time - #2991

Merged
robcohen merged 1 commit into
mainfrom
fix/midline-hashbang-linear
Nov 15, 2026
Merged

robcohen merged 1 commit into
mainfrom
fix/midline-hashbang-linear

Conversation

@robcohen

Copy link
Copy Markdown
Member

What

A line that repeats a mid-line #!, #+ or % (1#!1#!..., x #+#+..., x %x %x ...), and a file of many indented #+x lines, now parse in linear time. Output is unchanged: tokens, the CST and every error are byte-identical to main.

Why

Two quadratics, both in the handling #2928 added for a #! / #+ / % that is not a column-0 comment (beancount reads it as a # or % and the characters after it):

  1. Lexer (TokenIter::next, crates/rustledger-parser/src/logos_lexer.rs). logos lexed each one as a Shebang / EmacsDirective / PercentComment token to the end of its line, then next kept only the first character and restarted the lexer after it. A line of N such markers lexed the rest of the line N times.
  2. Error naming (name_mid_line_hash_comments, crates/rustledger-parser/src/cst/convert.rs). For each marker it did rfind('\n') back to the line start, a blank check over the same span, and errors.iter_mut().find(..) from the front of the error list. A line of N markers cost its length N times, and a file of N indented #+ lines (one error each) cost N errors per line.

The issue saw only the first; with it fixed, timing showed crate::parse still quadratic on the same inputs, and a pass-by-pass timing put all of it in name_mid_line_hash_comments.

How

  1. TokenIter::split_comment_start decides from the bytes, before logos runs, whether the lexer stands on a #! / #+ / % that next would split (the same conditions as the existing rewrites: not a column-0 #! / #+; not a % that starts a column-0 line beancount ignores). If so it emits the one-character Hash / Flag("%") token and bumps the lexer by one byte; the token then goes through every later step of next, so an indented one still gets its Indent. The old post-lex rewrites stay as a fallback and are counted.
  2. name_mid_line_hash_comments carries the line start forward from the previous marker (markers come in order), finds each line's first non-blank once, and, when the error list is sorted by start (as parse_via_cst_inner leaves it; checked on entry), walks it with a cursor. Each marker's window (line_start..=at, or at alone) never starts before the previous one's, and an error moved to a marker's # lies before every later window, so the cursor finds exactly the first match the front-to-back search found. An unsorted list falls back to that search.

While in logos_lexer.rs, the doc comment of error_later_in_run that #2988 left above lexer_at is moved back to its function (no code change).

Identity

parse_error_lines output and a hash of the full CST debug tree plus the AST parse result, main (c434a08110e) vs this branch:

Set Inputs Differences
Every UTF-8 *.beancount / *.bean in the repo and the fetched compat corpus 1,130 0
Generated (3 seeds): 1 to 5 lines of #!, #+, #, ;, %, tags, links, quotes, BOM, \r, lone capitals, dates, accounts, at line start and mid-line, LF/CRLF, with and without a final newline, a leading BOM 300,000 0
Generated, marker-dense (2 seeds): 3 to 25 lines, extra #! / #+ / indented #+x pieces 100,000 0

corpus_baseline (strict, against the fetched compat corpus) and the BOM matrix pass unchanged.

Timing

Release parse_error_lines, seconds, one input per shape:

Shape main 20k 40k 80k 160k branch 20k 40k 80k 160k
1#! run 0.23 1.15 4.00 16.06 0.01 0.01 0.02 0.04
x #!#! run 0.16 0.72 2.81 10.72 0.01 0.01 0.01 0.02
#!T after a flag (2024-01-02 P#!T...) 0.24 0.98 3.93 16.17 0.01 0.02 0.03 0.06
x #+#+ run 0.19 0.73 2.85 11.57 0.01 0.01 0.02 0.03
x % words 0.15 0.57 2.18 8.11 0.02 0.04 0.08 0.16
indented #+x lines 0.41 1.66 7.31 55.71 0.06 0.13 0.25 0.51
blanks then a #+ run 0.50 1.97 7.26 26.72 0.00 0.01 0.01 0.03
A#! run 0.00 0.00 0.00 0.00 0.00 0.00 0.00 0.00
A#+ run 0.00 0.00 0.00 0.01 0.00 0.00 0.00 0.00
A;x words (#2988) 0.02 0.04 0.08 0.15 0.02 0.04 0.08 0.15
A%x words (#2988) 0.02 0.04 0.07 0.15 0.02 0.03 0.07 0.16
T#! words (#2990) 0.02 0.04 0.08 0.16 0.02 0.04 0.08 0.15
flag-led "x"T (#2990) 0.01 0.01 0.02 0.04 0.01 0.01 0.02 0.04
column-0 #! / % / #+ lines 0.01 0.01 0.02 0.04 0.01 0.01 0.02 0.03

Guards

  • test_tokenize_lossless_split_comment_is_not_lexed_to_its_line_end counts the comment bytes the fallback rewrites lex (SPLIT_COMMENT_LEXED_BYTES) on ten shapes. With split_comment_start disabled it fails (1#! run: 600,030,000 bytes for a 60,002-byte input).
  • test_parse_mid_line_markers_are_named_in_linear_steps counts the source bytes and errors name_mid_line_hash_comments steps over (MID_LINE_MARKER_STEPS) on five shapes. It fails with the cursor disabled (indented #+ lines: 800,159,996 steps for 120,000 bytes) and with the first-non-blank cache disabled (blanks then #+: 400,059,999 steps for 60,001 bytes).

Caches

No bump. Parsed directives, errors and their spans and messages are byte-identical (above), so nothing either cache stores changes.

How to test

cargo test -p rustledger-parser --lib split_comment_is_not_lexed_to_its_line_end mid_line_markers_are_named_in_linear_steps
cargo test -p rustledger-parser

Closes #2989

🤖 Generated with Claude Code

A #!, #+ or % that is not a column-0 comment is split into its first
character (#2928). logos lexed each as a comment token to the line end
first, so a line repeating them relexed the rest of the line per
repetition. TokenIter::next now splits the character off from the bytes
before lexing (split_comment_start), with the old rewrite kept as a
counted fallback.

name_mid_line_hash_comments then scanned back to each marker's line
start and searched the error list from the front, so a file of indented
#+ lines was quadratic too. It now carries the line start forward,
finds each line's first non-blank once, and walks a start-sorted error
list with a cursor (falling back to the old search if unsorted).

Tokens, CST and every error are byte-identical to main on 1,130 real
ledgers and 400,000 generated inputs. Two byte-counter tests guard both
halves and fail when either fix is undone.

Closes #2989

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

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 52.4ms ± 0.7ms 837.3ms ± 15.7ms 16.0x 45.0 MB / 51.1 MB
investment 79.4ms ± 1.0ms 2955.3ms ± 31.4ms 37.2x 47.0 MB / 59.1 MB
fifo 75.9ms ± 1.3ms 14736.3ms ± 83.4ms 194.1x 49.1 MB / 58.9 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 52.1ms ± 0.5ms 52.4ms ± 0.7ms +0.4% ✅ within noise 45.1 MB → 45.0 MB (-0.2%)
investment 78.5ms ± 1.3ms 79.4ms ± 1.0ms +1.1% ✅ within noise 47.1 MB → 47.0 MB (-0.1%)
fifo 75.3ms ± 0.8ms 75.9ms ± 1.3ms +0.9% ✅ within noise 49.2 MB → 49.1 MB (-0.2%)

A difference counts only when it clears the combined spread of the two measurements, per shape (2σ: simple 0.4ms, investment 0.7ms, fifo 0.7ms), 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 88.70968% with 14 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger-parser/src/logos_lexer.rs 86.07% 11 Missing ⚠️
crates/rustledger-parser/src/cst/convert.rs 93.33% 3 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

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.

perf(parser): a long run of mid-line #! or #+ with no blank lexes in quadratic time

1 participant