Skip to content

fix(format): keep currency, cost and price on a numberless posting - #2145

Merged
robcohen merged 3 commits into
mainfrom
fix/format-preserves-incomplete-posting
Aug 25, 2026
Merged

robcohen merged 3 commits into
mainfrom
fix/format-preserves-incomplete-posting

Conversation

@robcohen

Copy link
Copy Markdown
Member

Closes #2142.

emit_posting rendered the amount only when amount_number_text yielded a number, and the currency, cost spec and price annotation all sat inside that branch. A posting without a number lost every one of them — not reformatted, deleted:

  Assets:Investments:MSFT            MSFT @@ 2000.00 USD
  Assets:Investments:MSFT

Worse than the issue first recorded

While fixing it I found the bug reaches valid input:

2024-01-15 * "x"
  Assets:Bank  -5.00 USD
  Assets:Other USD          ; valid: constrains interpolation to USD

Both engines accept this and interpolate Assets:Other 5.00 USD. Formatting deleted the USD. So this was data loss on correct input, not only on malformed input — I filed the issue believing otherwise, and the fix and its tests cover both.

The malformed shapes still matter, because format runs on editor save: mistyping a units number and saving deleted the rest of the line, and the surviving diagnostic got worse for it (BOOK became E1001 twice, once the evidence of intent was gone).

The fix

Numberless postings emit their parts with two spaces rather than the aligned number column. There is no number to align, and compute_alignment deliberately excludes these postings from the column width so a long currency-only account cannot widen the file — the existing transaction_currency_only_posting_does_not_widen_amount_column test still passes.

Testing

The regression test covers all four shapes — currency only, total price, cost, per-unit price — and asserts idempotence on each, so a fix that re-emitted tokens in a shape it could not reparse would fail here rather than silently.

Verified it fails against the old code: reverting gives formatting deleted "@@ 2000.00 USD".

The corpus property sweep that found this now reports 3 fewer drifts (5 → 2). The 2 remaining are artifacts of formatting to a temp file, which breaks relative include and plugin paths — not formatter bugs.

Parser tests green, workspace green except the pre-existing corpus_parity failure, clippy clean on 1.97.

🤖 Generated with Claude Code

https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr

`emit_posting` rendered the amount only when `amount_number_text` yielded a
number, and the currency, cost spec and price annotation all sat inside that
branch. A posting without a number therefore lost every one of them. The
tokens were not reformatted, they were deleted, and what the author wrote
could not be recovered from the output.

Worse than the issue first recorded: `Assets:Other USD` is VALID beancount
that constrains interpolation to USD, and both engines accept it, so this was
data loss on CORRECT input rather than only on malformed input. The malformed
shapes still matter, because `format` runs on editor save: mistyping a units
number and saving deleted the rest of the line, and the remaining diagnostic
got worse for it (BOOK became E1001 twice, since the evidence of intent was
gone).

Numberless postings emit their parts with two spaces rather than the aligned
number column: there is no number to align, and `compute_alignment`
deliberately excludes them from the column width so a long currency-only
account cannot widen the file.

The regression test covers all four shapes -- currency only, total price,
cost, per-unit price -- and asserts idempotence on each, so a fix that
re-emitted tokens in a shape it could not reparse would fail here rather than
silently. Reverting the fix fails it with "formatting deleted
\"@@ 2000.00 USD\"".

Found by checking two properties across the 735-file compatibility corpus:
`format(format(x)) == format(x)`, and `check(format(x))` reporting the same
diagnostic codes as `check(x)`. That sweep now reports 3 fewer drifts; the
2 remaining are artifacts of formatting to a temp file, which breaks relative
include and plugin paths.

Closes #2142.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
@robcohen
robcohen requested a review from a team as a code owner August 25, 2026 03:13
Copilot AI lite review requested due to automatic review settings August 25, 2026 03:13
@codecov

codecov Bot commented Aug 25, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Fixes a formatter data-loss bug in rustledger-parser where postings missing a units number could lose their currency/cost/price tokens during rledger format, and adds a regression test plus a changelog entry.

Changes:

  • Update emit_posting to emit currency/cost/price even when the amount has no numeric component.
  • Add a regression test asserting preservation + idempotence for currency-only / cost / per-unit price / total price shapes.
  • Document the fix in CHANGELOG.md.

Reviewed changes

Copilot reviewed 2 out of 2 changed files in this pull request and generated 2 comments.

File Description
crates/rustledger-parser/src/cst/format.rs Formatter logic change in emit_posting plus new regression test for issue #2142
CHANGELOG.md Notes the formatter fix under “Fixed”

💡 Add a code-review agent skill or configure MCP servers for context-aware, tailored reviews. Learn more in the docs.

@github-actions

github-actions Bot commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 50.4ms ± 5.3ms 838.6ms ± 11.3ms 16.6x 55.3 MB / 50.0 MB
investment 72.4ms ± 3.2ms 3096.0ms ± 15.8ms 42.7x 59.0 MB / 58.1 MB
fifo 70.1ms ± 3.0ms 15484.0ms ± 159.3ms 220.9x 61.1 MB / 57.8 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 49.3ms ± 4.5ms 50.4ms ± 5.3ms +2.2% ✅ within noise 55.1 MB → 55.3 MB (+0.3%)
investment 71.3ms ± 2.7ms 72.4ms ± 3.2ms +1.5% ✅ within noise 59.1 MB → 59.0 MB (-0.1%)
fifo 70.1ms ± 1.7ms 70.1ms ± 3.0ms +0.0% ✅ within noise 61.1 MB → 61.1 MB (+0.0%)

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

@github-actions

Copy link
Copy Markdown
Contributor

✅ Compatibility Test Results

Metric Result
Check Compatibility 100%
BQL Compatibility 100% (raw 93%, 170 masked)
Full AST Match 100%
Total Files 811
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

Two defects Copilot found in the first cut, both real.

The fix was incomplete. The branch for a posting with no AMOUNT node handled
`cost_spec` and not `price_annotation`, so `Assets:MSFT @@ 2000.00 USD` still
lost its price while `Assets:MSFT {12.00 USD}` was kept. The CST attaches
both after the account whether or not an AMOUNT was recognized, so both must
be emitted; they are now listed together in one loop rather than as separate
branches, which is what let one be forgotten.

The regression test could pass without testing anything. The currency-only
case asserted only that the output contained "USD", which the OTHER posting
in the fixture ("-5.00 USD") satisfies, so the test would have stayed green
while the currency-only posting still lost its currency. Every expectation
now names the WHOLE posting line. Verified by mutation: dropping only the
currency, keeping cost and price, now fails with
`formatting deleted "Assets:Other  USD"`, where the old assertion passed.

Two cases added for the no-amount-node shape, which nothing covered.

A test written to prove content survives must not be satisfiable by unrelated
content -- the same defect I accepted a fix for on #2141 earlier today, in a
test of my own this time.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
@robcohen

Copy link
Copy Markdown
Member Author

Both correct, both fixed in c264780.

The fix was incomplete. The no-AMOUNT-node branch handled cost_spec and not price_annotation, so Assets:MSFT @@ 2000.00 USD still lost its price while Assets:MSFT {12.00 USD} was kept. Confirmed before fixing:

  Assets:MSFT              <- price deleted
  Assets:MSFT  {12.00 USD} <- cost kept

Both are now emitted from one loop rather than separate branches, which is what allowed one to be forgotten. Two regression cases added for that shape, which nothing covered.

The test could pass without testing anything. You are right that must_contain = "USD" is satisfied by the other posting's -5.00 USD, so the currency-only case would have stayed green while the currency was still being deleted. Every expectation now names the whole posting line.

Verified the difference rather than assuming it: mutating the formatter to drop only the currency, keeping cost and price, now fails with formatting deleted "Assets:Other USD". The old assertion passed that same mutation.

That is the second time today I have accepted this exact correction — a test written to prove content survives must not be satisfiable by unrelated content. The first was on #2141, in someone else's shape; this one was mine.

Corpus sweep unchanged at 2 drifts, both known temp-file artifacts. Parser tests green, clippy clean on 1.97.

@robcohen

Copy link
Copy Markdown
Member Author

Self-review after the last fix, since the incomplete first cut suggested the shape space was worth enumerating rather than sampling.

Every combination of currency / cost / price on a numberless posting, and the two controls:

input output
Assets:A USD {12.00 USD} Assets:A USD {12.00 USD}
Assets:A USD @ 3.00 EUR Assets:A USD @ 3.00 EUR
Assets:A {12.00 USD} @ 3.00 EUR Assets:A {12.00 USD} @ 3.00 EUR
Assets:A Assets:A (auto-balance, correctly unchanged)
Assets:A 5 USD Assets:A 5 USD (normal alignment preserved)

No double-emission from the two branches, nothing dropped, and the bare-account and normal-amount controls behave as before.

All four numberless shapes are idempotent, which was the risk worth checking: emitting with two spaces rather than the aligned column could in principle reparse into something that formats differently again. It does not.

…idempotence

CI already ran `format-idempotence.sh` over the ~800-file corpus, which is
why #2142 slipped through: deleting the same tokens twice is perfectly
idempotent. The property that catches it is that formatting must not change
the set of diagnostic CODES a file produces, since formatting is a layout
change and `check` saying something different afterwards means content moved
or vanished.

Codes only, sorted. Message wording and spans legitimately move when layout
does; a code appearing or disappearing means the meaning changed.

The formatted copy is written BESIDE the original rather than in a temp
directory. A relative `include` or plugin path resolves against the file's
own directory, and moving the copy elsewhere breaks them: two corpus files
reported false drift until this was fixed, and I spent a while calling them
"harness artifacts" before noticing they were my own doing.

Verified in BOTH directions, which is the only way this is worth having:
against a binary built before the #2142 fix it reports the three affected
files and exits 1; against the fixed binary it reports none and exits 0.

That check earned its keep immediately. The first version grepped
`"code":"` while the JSON is pretty-printed as `"code": "E3004"`, so it
matched nothing, compared empty against empty, and passed every file
including the ones with the bug. It looked exactly like a clean run.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
@robcohen

Copy link
Copy Markdown
Member Author

Extended the fix with a corpus-level gate in 4b2c34b, after noticing why this class escaped in the first place.

CI already ran format-idempotence.sh over the corpus. That is exactly why #2142 got through: deleting the same tokens twice is perfectly idempotent. A unit test alone would leave the same blind spot for the next token.

The script now also checks that formatting does not change the set of diagnostic CODES a file produces. Formatting is a layout change; if check says something different afterwards, content moved or vanished. Codes only and sorted, since wording and spans legitimately move when layout does.

Both "harness artifacts" I reported earlier were my own doing. Writing the formatted copy to /tmp breaks relative include and plugin paths. Writing it beside the original resolves both, so the corpus is genuinely at 0 drifts, not 2, and this is a clean gate rather than one with permanent exceptions.

Verified in both directions, which is the only way it is worth having:

That second run earned its keep immediately. My first version grepped "code":" while the JSON is pretty-printed as "code": "E3004" — it matched nothing, compared empty against empty, and passed every file including the ones with the bug. It looked exactly like a clean run, and only running it against the known-bad binary exposed it.

@robcohen
robcohen merged commit ad74913 into main Aug 25, 2026
63 checks passed
@robcohen
robcohen deleted the fix/format-preserves-incomplete-posting branch August 25, 2026 13:34
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.

[Bug]: rledger format deletes the currency and price/cost annotation when a posting's units number is missing

2 participants