Skip to content

test(loader): bound exact_decimal by digits scanned, not wall-clock time - #2950

Merged
robcohen merged 5 commits into
mainfrom
test/exact-decimal-work-count
Nov 12, 2026
Merged

robcohen merged 5 commits into
mainfrom
test/exact-decimal-work-count

Conversation

@robcohen

@robcohen robcohen commented Nov 11, 2026 •

Copy link
Copy Markdown
Member

What changed

  • crates/rustledger-loader/src/options.rs: a #[cfg(test)] thread-local SCANNED counter and a note_scanned(n) hook, following the BQL parser's LITERAL_BUDGET / note_literal_parsed pattern. Outside tests the hook is an empty inlined const fn.
  • The option-number readers read the value only through scan_bytes / scan_chars. These are bytes() / chars() with an inspect that counts each item as it is yielded. That covers every scan in parse_tolerance_map, parse_beancount_decimal, exact_decimal, parse_exponent, is_python_number_part, and the new trim_python_space, which replaces trim_matches(is_python_space).
  • exact_decimal reads the coefficient in place and no longer copies it into a Vec.
  • test_exact_decimal_is_linear_on_long_input is now test_exact_decimal_linear_digit_scans_on_long_input, with no timing. Each call must scan between 1 and 10 times per input byte. The seven inputs are 4,000 zeros a side, a long fraction, trailing whitespace, a long exponent, separators with surrounding whitespace, and a tolerance map with 4,000 colons.
  • New crates/rustledger-loader/tests/option_number_allocation.rs: under dhat's counting global allocator, Options::set on each long option value may allocate at most 20 bytes per input byte. This catches quadratic copying, which no scan counter sees. dhat is already a workspace dependency; it is added to the loader's [dev-dependencies] only.

Why

The wall-clock bound flaked once on a heavily loaded machine (#2948). A work count is deterministic, so load cannot fail it. A quadratic scan through the hooks counts thousands of scans per byte, against a bound of 10.

No production behavior change. All existing option tests pass unchanged.

How to test

cargo test -p rustledger-loader --lib -- options::
cargo test -p rustledger-loader --test option_number_allocation

Review round 1

  • Hooks: every scan now counts inside its iterator instead of noting a length afterwards. The hook's doc states the contract: every scan of the value in these functions must go through scan_bytes / scan_chars. A scan that does not, or work that is not a scan (copying or shifting a buffer), is invisible to the guard.
  • Bound: 10 per input byte, up from 3. The measured ratios are 3.0 to 7.0, and the highest is the plain long multiplier. The doc says "per input byte".
  • Lower bound: the comment now says it only catches every hook being dropped.
  • Kept-digit parse: the count on it is gone. That parse reads at most 29 digits, as the comment says.
  • Mutations: each was run in its own copy of the tree with a fresh target dir.
Mutation Result
M1 coefficient rebuilt one digit at a time, re-reading from the start fails, 32,060,041 scans / 8,005 bytes
M2 leading zeros stripped one at a time fails, 8,054,041 / 8,005
M3 leading zeros rescanned per trailing zero (the original bug) fails, 16,056,041 / 8,005
M4 trailing zeros counted by rescanning each suffix fails, 32,056,041 / 8,005
M5 the dot in exact_decimal found by re-reading per byte fails, 32,056,041 / 8,005
M6 the _ filter re-reads the text per character fails, 32,060,040 / 8,001
M7 the all-zeros check rescans each prefix fails, 8,058,040 / 8,001
M8 parse_exponent skips leading zeros by re-reading per byte fails, 8,018,021 / 4,004
M9 is_python_number_part counts the dots at every byte fails, 64,068,042 / 8,005
M10 the first line found by rescanning each prefix fails, 32,088,051 / 8,005
M11b comma/space cleaning re-reads the value per character fails, 32,060,040 / 8,001
M11a comma/space cleaning accumulated by repeated format! passes (survives)
M12 / M13 a harmless second linear pass pass, as they should

What remains: M1's original form (concatenating into the coefficient Vec) and M2's original form (Vec::remove(0)) have nothing left to mutate, because that Vec is gone. M11a survived round 1: its quadratic is in copying, not scanning, and no scan counter can see it. Round 2 catches it with an allocation count (below).

Review round 2

  • The review compared this branch with main on 58M differential inputs: 0 mismatches.
  • Correction: round 1 said catching M11a needs unsafe impl GlobalAlloc, ruled out by #![forbid(unsafe_code)]. That was wrong. dhat::Alloc is a safe counting global allocator, dhat is already a workspace dependency, and an integration test is its own crate, outside the loader's forbid(unsafe_code) and outside scripts/check-unsafe-invariant.sh (which scans src/).
  • New test tests/option_number_allocation.rs, test_options_set_long_number_allocation_is_linear: sets the long tolerance map, the long multiplier and the separated value through Options::set under dhat::Profiler::builder().testing(), and bounds each call's total_bytes at 20 per input byte. The file holds exactly one test, because dhat's profiler is process-global. It is ignored under Miri, where it checks nothing about memory safety.
  • Measured: 80,902 bytes for the 8,005-byte tolerance map (10.1 per byte), 73,487 for the 8,001-byte multiplier (9.2), 24,704 for the 12,003-byte separated value (2.1).
  • Many colons: test_exact_decimal_linear_digit_scans_on_long_input gains USD:1 followed by :a 4,000 times (2.0 scans per byte).
Mutation Result
M11a comma/space cleaning accumulated by repeated format! allocation test fails, 96,069,091 bytes / 8,001; scan-count test still passes
M14 parse_tolerance_map rescans the rest of the line at every colon scan-count test fails on the new colon input, 16,024,012 scans / 8,005; every other input stays under the bound

Closes #2948

🤖 Generated with Claude Code

The linearity guard for exact_decimal asserted a 2 s bound on a
160,000-digit input and flaked on a loaded machine. Count the digits
exact_decimal and parse_beancount_decimal scan instead, in a cfg(test)
thread-local (the BQL parser's LITERAL_BUDGET pattern); outside tests the
counter is an empty const fn. The renamed test asserts each call scans
between one and three times its input length, so a quadratic scan fails
deterministically and load cannot.

Closes #2948

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@robcohen
robcohen requested a review from a team as a code owner November 11, 2026 13:48
@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

@github-actions

github-actions Bot commented Nov 11, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 39.8ms ± 0.5ms 569.3ms ± 3.2ms 14.3x 44.8 MB / 50.9 MB
investment 60.5ms ± 0.5ms 2117.6ms ± 8.6ms 35.0x 46.9 MB / 59.0 MB
fifo 59.0ms ± 0.3ms 11729.5ms ± 28.7ms 198.8x 48.8 MB / 58.7 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 39.9ms ± 1.4ms 39.8ms ± 0.5ms -0.3% ✅ within noise 45.0 MB → 44.8 MB (-0.3%)
investment 62.6ms ± 5.9ms 60.5ms ± 0.5ms -3.4% ✅ within noise 46.9 MB → 46.9 MB (+0.1%)
fifo 58.5ms ± 0.8ms 59.0ms ± 0.3ms +0.8% ✅ within noise 49.0 MB → 48.8 MB (-0.4%)

A difference counts only when it clears the combined spread of the two measurements, per shape (2σ: simple 0.7ms, investment 2.6ms, fifo 0.4ms), 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 11, 2026 •

Copy link
Copy Markdown

Codecov Report

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

Files with missing lines Patch % Lines
crates/rustledger-loader/src/options.rs 98.94% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

robcohen and others added 4 commits November 11, 2026 09:50
Review round 1 on #2950. The counter noted lengths after the fact, so a
quadratic rewrite of a hooked site still counted linearly. Every scan of
the value in parse_tolerance_map, parse_beancount_decimal, exact_decimal,
parse_exponent and is_python_number_part now reads through scan_bytes /
scan_chars, which count each byte or character as it is yielded.
exact_decimal no longer copies the coefficient into a Vec, so there is
no buffer to grow by concatenation or shift with remove(0). The bound is
10 scans per input byte (measured 3.0 to 7.0), and the inputs now cover
trailing whitespace, a long exponent, and separators.

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

The scan counter cannot see quadratic copying (review round 1's surviving
M11a: the comma/space cleaning accumulated by repeated `format!`). A new
integration test installs `dhat::Alloc`, a safe counting global allocator,
and bounds the bytes `Options::set` allocates for the long tolerance map,
the long multiplier and the separated value at 20 per input byte
(measured 10.1, 9.2 and 2.1). It is its own crate, so the loader keeps
`#![forbid(unsafe_code)]`; it holds exactly one test because dhat's
profiler is process-global.

The scan-count test gains a tolerance map with 4,000 colons, which
catches a per-colon rescan in `parse_tolerance_map`.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@robcohen
robcohen merged commit e6c8054 into main Nov 12, 2026
71 of 72 checks passed
@robcohen
robcohen deleted the test/exact-decimal-work-count branch November 12, 2026 02:11
robcohen added a commit that referenced this pull request Nov 12, 2026
#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 added a commit that referenced this pull request Nov 12, 2026
#2945, which this branch carried, is squash-merged as 526f833; its
hunks take main's final form (loader cache v71, `escape_untrusted_text`
in `rledger query`, its CHANGELOG notes).

With #2947: the FFI's `semantic_validation_errors` keeps #2947's
`booking_refused` set-aside and its `is_advisory_only` filter, which
replaces this branch's equivalent one. `convert::surface_agreement` now
matches each finding's code too (the 4.0.0 wire error carries it) and
runs `validate-file` and `load-file` over the shared cases, so the file
surfaces are pinned to leave out E1004 and set a refused transaction
aside.

No cache moves: the loader cache stores only error-free raw loads, and
this branch changes no WASM output.

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.

test(loader): make the exact_decimal linearity test count work instead of wall-clock time

1 participant