Skip to content

fix(extract): write statements oldest-first, keeping the within-day order - #2526

Merged
robcohen merged 5 commits into
mainfrom
fix/extract-output-order
Oct 9, 2026
Merged

robcohen merged 5 commits into
mainfrom
fix/extract-output-order

Conversation

@robcohen

@robcohen robcohen commented Oct 8, 2026

Copy link
Copy Markdown
Member

What changed

rledger extract now writes each statement oldest-first and keeps the export's own sequence within a day. This is option C as decided on #2319.

rustledger_importer::order::chronological runs once per input file, right after the importer and before --existing dedup:

  1. It counts the steps between consecutive transactions' dates in file order, up or down. Same-date neighbors are not counted.
  2. If there are more steps down than up, the export is newest-first, and the rows are reversed.
  3. It stable-sorts by rustledger_core::booking_sort_key, the canonical (date, directive type) order. Same date and type keep their post-reversal position.

This applies to the CSV, OFX and WASM importers alike, since it runs on ImportResult::directives whichever importer produced them.

  • Oldest-first files come out unchanged, byte for byte.
  • A tie, including a file whose rows all share one date, keeps file order.
  • Dedup runs after the ordering, so its "skipped …" report lists rows in output order.
  • The --balance assertion is appended after both, so it stays last.
  • An OFX LEDGERBAL assertion is not a row. It does not vote on direction and is placed by the sort, dated the day after DTASOF, so normally last.

Documented in docs/commands/extract.md ("Output Order"), including the assumption: a newest-first export is assumed newest-first within a day too, because no time of day survives import to check. CHANGELOG says newest-first exports now come out oldest-first.

Why

A newest-first export (#2319) was written backwards. A plain stable sort by date, which is what beangulp does, would fix the days but leave each day's rows newest-first. The reporter asked to keep the sequence, so the plain sort was rejected.

How tested

rustledger-importer (order::tests):

  • Proptest, the reversal property: for any monotonic statement F with at least two dates, extract(F) == extract(reverse(F)) == F, through the real CSV importer.
  • Proptest: for an ascending statement, chronological returns the importer's directives unchanged as values, which makes the output byte-identical to before.
  • Descending, reversed within each day; unsorted, and grouped by payee, date-sorted with same-day file order; single date, kept as is; tie (down == up), sorted without reversal; OFX with LEDGERBAL, where the balance does not vote and lands by date.

rustledger CLI (tests/cli_commands_test.rs):

  • A newest-first CSV with --existing and --balance: stdout is oldest-first, the two skip lines are in output order, and the --balance assertion (dated before every row) is still last.
  • Two files: extract takes one input file per run, so "several files each keep their own block" means separate runs appended to one ledger. The test does that, and each file's block stays separate and in import order, even when the second file is older.

Shown to fail without the fix: without the reversal (plain sort), the descending test and the reversal proptest fail. With no ordering at all, 6 of the 9 order tests fail. The 3 that pass either way are the "unchanged" checks: ascending, single date, ascending-as-is.

Existing extract_cmd tests pass unchanged. Clippy (workspace, all targets, -D warnings) and rustdoc (-D warnings) are clean for both crates.

Closes #2319

🤖 Generated with Claude Code

https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr

…rder

Per input file, count the steps between consecutive transactions' dates;
when more go down than up, reverse the rows, then stable-sort by the
canonical booking_sort_key. A newest-first export now comes out
oldest-first with each day's rows in true order, an oldest-first one is
unchanged, and a tie (or a single date) keeps file order. Runs once, for
every importer type, after the importer and before --existing dedup; the
--balance assertion is still appended last.

Closes #2319

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
@robcohen
robcohen requested a review from a team as a code owner October 8, 2026 17:57
@codecov

codecov Bot commented Oct 8, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 98.39572% with 3 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger-importer/src/order.rs 98.37% 3 Missing ⚠️

📢 Thoughts on this report? Let us know!

@github-actions

github-actions Bot commented Oct 8, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 29.2ms ± 1.2ms 425.8ms ± 25.0ms 14.6x 50.9 MB / 50.1 MB
investment 43.2ms ± 1.0ms 1548.3ms ± 64.0ms 35.9x 57.4 MB / 58.1 MB
fifo 41.6ms ± 0.9ms 7946.4ms ± 47.8ms 191.0x 55.0 MB / 57.9 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 27.9ms ± 0.6ms 29.2ms ± 1.2ms +4.9% ✅ within noise 51.5 MB → 50.9 MB (-1.2%)
investment 43.1ms ± 0.9ms 43.2ms ± 1.0ms +0.1% ✅ within noise 57.2 MB → 57.4 MB (+0.5%)
fifo 41.9ms ± 1.9ms 41.6ms ± 0.9ms -0.7% ✅ within noise 55.0 MB → 55.0 MB (+0.0%)

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

github-actions Bot commented Oct 8, 2026

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

…heck

Beancount and rledger check evaluate a balance at the start of its date,
whatever line it is on, and the ordering uses the same (date, type) key,
so an importer-emitted assertion dated on the last row's date is written
ahead of that day's rows. Pinned by a test; verified with bean-check
that both placements give identical results.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
@robcohen

robcohen commented Oct 8, 2026 •

Copy link
Copy Markdown
Member Author

Review (adversarial pass)

Balance placement (concern: sorting a balance by date could make an import that used to pass rledger check fail). It can't. Beancount and rledger check both evaluate a balance at the start of its date, before that day's transactions, whatever line it is written on, because the loader sorts by (date, directive type) and a balance ranks ahead of a transaction. This PR sorts by the same booking_sort_key. Verified with both tools:

case written after the day's txns written before them
balance dated on the last txn's date, amount = opening figure rledger ✓, bean-check ✓ rledger ✓, bean-check ✓
same, amount = closing figure (the "some banks" case) rledger ✗, bean-check ✗ rledger ✗, bean-check ✗

So a closing figure dated on the last day fails on main too, and was never correct. The OFX importer already dates LEDGERBAL at DTASOF + 1. A newest-first OFX statement with DTASOF on its last transaction's date passes rledger check and bean-check on both main and this branch. No code fix was needed. e9c57c7 documents why moving a balance cannot change the check, in chronological and in docs/commands/extract.md, and adds a_same_date_balance_is_written_before_that_days_transactions to pin the placement. That test pins existing behavior, so there is no fail-without-fix.

Cross-PR integration (applies to #2524, #2526, #2527, #2531, #2532, #2533)

All six PRs were merged onto origin/main 25fc6be in two orders: 2524→2526→2527→2531→2532→2533, and the reverse.

@robcohen
robcohen merged commit 7536909 into main Oct 9, 2026
49 of 50 checks passed
@robcohen
robcohen deleted the fix/extract-output-order branch October 9, 2026 02:36
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.

Should rledger extract mandate a transaction ordering?

1 participant