Skip to content

fix(format): stop deleting a note's tags and links - #2192

Merged
robcohen merged 4 commits into
mainfrom
fix/format-note-tags
Aug 30, 2026
Merged

robcohen merged 4 commits into
mainfrom
fix/format-note-tags

Conversation

@robcohen

Copy link
Copy Markdown
Member

Closes #2184.

What was happening

$ cat f.bean
2024-01-05 note Assets:A "note text" #ntag ^nlink
2024-01-06 document Assets:A "/tmp/x.pdf" #dtag ^dlink

$ rledger format f.bean
2024-01-05 note Assets:A "note text"                      <- tags deleted
2024-01-06 document Assets:A "/tmp/x.pdf" #dtag ^dlink    <- kept

Formatting is supposed to preserve meaning. This silently deleted user data on every run.

Which formatter

The issue points at format_note_lines in rustledger-core. That is not the code that runs — rledger format calls rustledger_parser::format::format_source, the CST formatter. That is also why a document's tags survived: emit_document there carried a direct-child token walk re-emitting the header's TAG / LINK tokens, and emit_note carried nothing.

Fix

Both now share emit_header_tags_and_links — the document walk unchanged, including its two hard-won details: skip leading trivia (a blank line before a non-first directive attaches its NEWLINE inside the node) and skip leading comment lines for the same reason. The converter had the identical bug from the identical cause (#2189).

Why nothing caught it

The formatter's own IDEMPOTENCE_MATRIX asserts that formatting twice equals formatting once. Dropping a note's tags is perfectly idempotent — the property cannot see data loss. Stability is not fidelity.

The new test asserts fidelity: parse → format → parse → compare models.

That alone is still not enough, and not hypothetically. Run it on a tree whose converter also drops these tags (#2189, unmerged) and both sides come back tagless and equal, while every tag in the file has been deleted — the assertion passes while the bug is live. It therefore also asserts on the formatter's output text, which is the thing under change and cannot be satisfied by a matching pair of empty models.

Verification

  • Reverting the one emit_note line fails the new test (control).
  • Fixture covers a note after a blank line, after a comment line, with metadata, and a document — the trivia cases that broke the equivalent walk before.
  • format-idempotence.sh: checked=693 skipped=42 non_idempotent=0 diagnostics_changed=0
  • format-preserves-comments.sh: checked=693 dropped_comments_in=0
  • corpus_parity divergences: 20, unchanged from main (pre-existing).
  • clippy 1.97 workspace clean; fmt, typos, cargo doc clean.

Found on the way: #2191

The same fidelity check over the whole matrix fails on balance_with_arithmetic_and_tolerance — the formatter emits 0.25 + 0.75 ~ 0.01 USD, which no longer parses. That is a parser inconsistency (it accepts ~ TOL CURRENCY after a number but not after an expression), filed as #2191. The matrix-wide harness lands with that fix rather than behind an allow-list here.

🤖 Generated with Claude Code

https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr

`rledger format` uses the CST formatter, not the model formatter #2184
points at. There, `emit_document` carried a direct-child token walk that
re-emits the header's TAG / LINK tokens and `emit_note` carried nothing,
so formatting a note silently deleted whatever the author had written on
its header. Formatting is supposed to preserve meaning.

Both now share `emit_header_tags_and_links`. The walk is the document
one unchanged, including its two hard-won details: skip LEADING trivia,
because a blank line before a non-first directive attaches its NEWLINE
inside the node, and skip leading COMMENT lines for the same reason. The
converter had the identical bug from the identical cause (#2189).

The formatter's own IDEMPOTENCE_MATRIX could never have caught this:
dropping a note's tags is perfectly idempotent, and the matrix asserts
stability, not fidelity.

So the new test asserts fidelity -- parse, format, parse, compare
models. That alone is still not enough, and not hypothetically: run it
on a tree whose CONVERTER also drops these tags and both sides come back
tagless and equal while every tag in the file has been deleted. It
therefore also asserts on the formatter's output text, which is the
thing under change and cannot be satisfied by a matching pair of empty
models.

Verified: reverting the `emit_note` line fails the test; corpus scripts
report checked=693 non_idempotent=0 dropped_comments_in=0.

The same fidelity check over the WHOLE matrix fails on
`balance_with_arithmetic_and_tolerance`, where the formatter emits a
balance that no longer parses. That is a parser inconsistency, filed as
#2191, and the matrix-wide harness lands with its fix rather than behind
an allow-list here.

Closes #2184

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 30, 2026 05:15
Copilot AI lite review requested due to automatic review settings August 30, 2026 05:15
@codecov

codecov Bot commented Aug 30, 2026 •

Copy link
Copy Markdown

Codecov Report

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

Files with missing lines Patch % Lines
crates/rustledger-parser/src/cst/format.rs 96.70% 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%, 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

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.

🟢 Approval recommended

The fix is narrowly scoped to CST formatting, includes a focused regression test, and the remaining feedback is a small maintainability hardening suggestion.

Pull request overview

This PR fixes a CST-formatter fidelity bug in rustledger-parser where rledger format could silently drop #tag / ^link tokens from note directive headers, preserving user data and aligning note behavior with document formatting.

Changes:

  • Emit trailing header #tag / ^link tokens for note directives during CST formatting.
  • Factor the header tag/link re-emission logic into a shared helper used by both note and document.
  • Add a regression test that checks parse → format → parse model fidelity and asserts the formatted output text still contains the tags/links.
File summaries
File Description
crates/rustledger-parser/src/cst/format.rs Re-emits note header tags/links via a shared token-walk helper and adds a targeted round-trip fidelity test.
Review details
  • Files reviewed: 1/1 changed files
  • Comments generated: 1
  • Review effort level: Lite

💡 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 30, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 50.0ms ± 4.1ms 858.1ms ± 6.2ms 17.1x 55.1 MB / 50.1 MB
investment 73.9ms ± 3.9ms 3181.8ms ± 51.5ms 43.0x 59.0 MB / 58.0 MB
fifo 72.0ms ± 3.2ms 16230.4ms ± 238.2ms 225.3x 59.0 MB / 57.7 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 54.3ms ± 6.2ms 50.0ms ± 4.1ms -7.8% 🟢 faster 55.0 MB → 55.1 MB (+0.3%)
investment 71.9ms ± 1.5ms 73.9ms ± 3.9ms +2.9% ✅ within noise 59.1 MB → 59.0 MB (-0.3%)
fifo 73.5ms ± 4.3ms 72.0ms ± 3.2ms -2.1% ✅ within noise 61.1 MB → 59.0 MB (-3.3%)

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

Review feedback: `emit_header_tags_and_links` bailed out of the loop on
the first `NodeOrToken::Node`, so it did not walk all direct-child
tokens the way its name claims.

Harmless for the two callers it has -- a note's or document's only child
node is a META_ENTRY, which sits past the header newline the walk has
already broken on -- but the failure mode if a header ever gains a child
node is that every tag after it disappears with nothing to say so. This
helper exists because exactly that kind of silent drop shipped twice.

Behavior is unchanged today: full parser suite, and 693 corpus files
still report non_idempotent=0 and dropped_comments_in=0.
@robcohen

Copy link
Copy Markdown
Member Author

Good catch — applied in e0111a3.

You're right that the name promised a full walk and the code did not deliver one. Harmless for the two callers it has (a note's or document's only child node is a META_ENTRY, which sits past the header newline the walk has already broken on), but the failure mode if a header ever gains a child node is that every tag after it disappears silently — and this helper exists precisely because that kind of silent drop shipped twice already.

A Node now marks seen_content and continues. Behavior is unchanged today: full parser suite green, and 693 corpus files still report non_idempotent=0 / dropped_comments_in=0.

robcohen and others added 2 commits August 30, 2026 06:16
There are TWO live formatters, and the commit before this one fixed one
of them. `format_source` is what `rledger format` runs.
`canonicalize_directives` is what `rledger add`, `rledger extract` and
the FFI `format.entry` / `format.entries` endpoints run, and it
synthesizes its intermediate text through
`rustledger_core::format::format_directives` -- where
`format_note_lines` and `format_document_lines` emitted a header with no
tags and no links.

So a note built in memory and canonicalized still lost them, and a
DOCUMENT lost them here as well: the CST emitter at least kept a
document's tags, which is why `rledger format` looked correct for
documents while this path was not.

#2184's own text warned about this -- "worth establishing which
formatter actually runs before changing either". Establishing that
`rledger format` uses the CST one answered which to fix first, not which
was the only one that mattered.

Both now share `write_tags_and_links`, in the order the transaction
emitter already used.

Verified through the shim rather than the function: a fixture with a
tagged note, document and transaction canonicalizes with every marker
intact and re-parses to the same directives. Reverting the note line
alone fails it.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
The fidelity test added with the note-tag fix exercises `format_source`.
It cannot see `canonicalize_directives`, which renders through a
different emitter, so the second data-loss path this branch fixes went
unnoticed by it.

This is the same check aimed at the other emitter: parse every fixture,
render it typed, re-parse, compare models.

It needed a fixture change to be worth anything. `note_directive` was
`2024-01-15 note Assets:Cash "a note"` -- no tags -- so no harness in
this file could see a note losing them, which is precisely how the bug
survived. It now carries a tag and a link, and `document_directive`
gains a link next to the tag it already had.

That thin fixture is the whole reason to write this down: the harnesses
were sound and the input made them blind. Verified in both directions --
dropping the note or document tags from the typed emitter fails this
test, dropping them from the CST emitter fails the other one, and each
control fails only its own.

693 corpus files still report non_idempotent=0.
@robcohen

Copy link
Copy Markdown
Member Author

Correction to the verification notes on this PR.

I reported corpus_parity divergences as "20, unchanged from main (pre-existing)". That measurement was wrong. The test loads a prebuilt target/wasm32-wasip2/debug/rustledger_ffi_component.wasm, and no test command rebuilds it — the copy on my disk was three weeks old, so it was comparing today's native code against a stale component.

After cargo build -p rustledger-ffi-component --target wasm32-wasip2:

cargo test -p rustledger-ffi-component-tests   ->  ok, 0 divergences
cargo test --workspace                          ->  green

So there is no known-failing test here at all; the actual state is better than I described. The tell I missed was the number's stability — it stayed 20 because the component never changed, not because the failure was inherent. Every other verification figure I quoted (clippy, fmt, typos, the 693-file format scripts, the baselines) was measured directly and stands.

@robcohen
robcohen merged commit 1ef068d into main Aug 30, 2026
63 of 64 checks passed
@robcohen
robcohen deleted the fix/format-note-tags branch August 30, 2026 08:25
robcohen added a commit that referenced this pull request Aug 30, 2026
Review feedback on #2192 was that `emit_header_tags_and_links` bailed
out of its walk at the first child NODE, so it did not scan the whole
header. I fixed that there and then wrote `has_top_level_tilde` with the
identical `break` a few hours later.

Harmless today for the same reason it was harmless there -- a price's
only child node is a META_ENTRY, whose tokens are not direct children,
so nothing here can see a `~` written inside metadata. But a header that
ever gains a child node would stop being scanned at all, and the whole
point of this function is to refuse a tolerance rather than skip past
one.

Also records a blind spot in the format-fidelity test, found while
checking whether the tolerance clause is validated at all (it is not,
#2193): a model comparison cannot see data the model never held. `balance
X 1.00 USD ~ 0.01 EUR` formats to `1.00 ~ 0.01 USD`, erasing the EUR
from the file, and the test passes -- both sides lost it in the parser.
Which is exactly why the note-tag test also asserts on output text.
robcohen added a commit that referenced this pull request Aug 30, 2026
Four PRs shipped user-visible behavior changes without an entry: the
two formatter tag losses (#2192), the blank-line tag drop (#2189), the
same-date pad (#2187), and this branch's tolerance grammar (#2195).

The changelog already carries the direct sibling of the first one --
"`rledger format` no longer deletes a posting's currency, cost or price
when it has no units number" (#2142) -- so the omission was mine, not a
question of whether this class belongs here.

Each entry records the cache versions that moved with it, which is the
part a reader upgrading actually needs and the part not recoverable from
the diff.
robcohen added a commit that referenced this pull request Aug 30, 2026
* fix(parser): a balance tolerance may follow an arithmetic amount

`directive_arithmetic_value` scanned to the first top-level CURRENCY and
treated everything before it as the amount expression. With no currency
between the amount and the tolerance, that swallowed the tolerance:
`0.25 + 0.75 ~ 0.01 USD` was handed to the expression parser as
`0.25 + 0.75 ~ 0.01`, which is not arithmetic, so the whole value was
reported malformed.

Only the currency-less arithmetic form reached that state. With a
currency after the expression the scan stopped there and parsed, which
is why `100.00 ~ 0.01 USD` and `0.25 + 0.75 USD ~ 0.01 USD` both worked
and `0.25 + 0.75 ~ 0.01 USD` did not. `~` now ends the expression, which
is what it means; the tolerance is read separately as it always was.

This is what made `rledger format` emit a balance that no longer parses
(#2191): the formatter emits the single-trailing-currency form, which
is the beancount form and the one the parser already accepted for a
plain number.

Tested for VALUES, not just for parsing. An earlier bug in this same
scan fell back to "take the first NUMBER" and turned `(1 + 5) / 2.1`
into a silent assertion against 1 -- parsed cleanly, asserted the wrong
thing -- so each of the seven accepted forms is checked against the
amount it should evaluate to, with a ledger holding 0.25 confirming that
`0.25 + 0.75` does not match it.

Brings in the matrix-wide format-fidelity harness that #2192 could not
land: it fails on `balance_with_arithmetic_and_tolerance` without this
fix, which is how the bug was found.

Closes #2191

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

* fix(parser): a price rejects a tolerance instead of discarding it

Review of the commit before this one caught a regression it introduced.
`directive_arithmetic_value` is shared by `balance` and `price`, so
making `~` end the amount expression applied to both -- and a price has
no tolerance. `price USD 1.10 + 0.05 ~ 0.01 EUR` went from a
malformed-value error to silently evaluating 1.15 and dropping the
tolerance on the floor. Trading a diagnosed error for a silent
half-reading of the author's input is a bad trade.

`ToleranceForm` now says which grammar is being parsed: `balance` stops
at `~`, `price` does not.

That restores the old handling of the arithmetic form and leaves the
plain one, `price USD 1.10 ~ 0.01 EUR`, which main ALREADY accepted the
same silent way -- `~` is not an arithmetic operator, so the scan took
the fast path and fell back to the first NUMBER, yielding 1.10 with the
rest discarded. Fixing only the half I broke would leave the identical
silent truncation one keystroke away, so a top-level `~` on a price is
now diagnosed outright.

Both forms are covered, and so are the three tolerance-free price forms
with the values they must evaluate to -- an error path that also stopped
accepting valid input would pass a test that only asserted rejection.

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

* test(format): raise the round-trip floor to what actually round-trips

The fidelity harness guards against going quiet by asserting a minimum
number of fixtures reached the comparison. `> 20` was a third of the way
down from the real figure: 37 of the 42 fixtures round-trip today, the
other 5 being error fixtures, so ten could start failing to parse and be
skipped without the floor noticing. Skipping is exactly how this test
would go quiet.

Measured rather than guessed, and set just under the measured value so
adding fixtures does not churn it.

* test(parser): census which directives keep tags and which refuse them

The failure this session kept turning up is a third state between the
two: accept the tag, then drop it because the model has nowhere to put
it. `note` was in it (#2160), both formatters were in it (#2184), and a
price's tolerance was in it.

So this counts the directives rather than testing one. Seven refuse,
three keep, and each refusal is checked against its tag-free form too --
a rejection that also rejected valid input would satisfy an
assertion that only looked for an error.

`query` is in neither set: it accepts a tag and discards it. That is
asserted here as CURRENT behavior, not as correct behavior. Which way it
should go needs `bean-check` (beancount's `Query` has no tags field,
which argues for refusing; a parser-lima corpus file uses the form,
which argues it appears in the wild) and the container is not built
here. Filed as #2194. Written as an assertion so the day it changes this
fails and the census gets updated rather than quietly going stale.

I implemented the refusal and backed it out: it makes
`parser-lima/examples_data_full.beancount` error, and an unverifiable
strictness increase does not belong in a PR about tolerance parsing.

* chore(cache): bump the versions the tolerance changes invalidate

Loader 32 -> 33, wasm 17 -> 18, pin 33.

Parser OUTPUT moves in both directions here, which is why both caches
have to: a v32/v17 blob holds a parse error where this build now
produces a balance directive, and holds a silently truncated 1.10 where
this build now produces an error. Either way the cache would serve a
reading the binary no longer agrees with.

Both `CostNumber` and `MetaValue` fixture tripwires move version only --
balance and price amounts are `Decimal`s on the directive and take part
in neither archived layout, and the assertions after each comment prove
that rather than take the comment's word for it.

* fix(parser): a child node no longer stops the tilde scan

Review feedback on #2192 was that `emit_header_tags_and_links` bailed
out of its walk at the first child NODE, so it did not scan the whole
header. I fixed that there and then wrote `has_top_level_tilde` with the
identical `break` a few hours later.

Harmless today for the same reason it was harmless there -- a price's
only child node is a META_ENTRY, whose tokens are not direct children,
so nothing here can see a `~` written inside metadata. But a header that
ever gains a child node would stop being scanned at all, and the whole
point of this function is to refuse a tolerance rather than skip past
one.

Also records a blind spot in the format-fidelity test, found while
checking whether the tolerance clause is validated at all (it is not,
#2193): a model comparison cannot see data the model never held. `balance
X 1.00 USD ~ 0.01 EUR` formats to `1.00 ~ 0.01 USD`, erasing the EUR
from the file, and the test passes -- both sides lost it in the parser.
Which is exactly why the note-tag test also asserts on output text.

* test(parser): match the price-tolerance error on its kind, not its Debug

Review feedback: the assertion stringified the whole `ParseError` with
`{e:?}` and searched that. Debug output carries the span and context
fields too, so the test was coupled to formatting it does not care
about.

It now matches `ParseErrorKind::SyntaxError(m)` and searches `m`, which
is the part the test is actually about. Still pins the wording --
rewording the message fails it -- so this narrows what the assertion is
brittle to rather than weakening it.

* docs: record this run's fixes in the changelog

Four PRs shipped user-visible behavior changes without an entry: the
two formatter tag losses (#2192), the blank-line tag drop (#2189), the
same-date pad (#2187), and this branch's tolerance grammar (#2195).

The changelog already carries the direct sibling of the first one --
"`rledger format` no longer deletes a posting's currency, cost or price
when it has no units number" (#2142) -- so the omission was mine, not a
question of whether this class belongs here.

Each entry records the cache versions that moved with it, which is the
part a reader upgrading actually needs and the part not recoverable from
the diff.

---------

Co-authored-by: Claude Opus 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.

rledger format silently drops a note's tags and links; bean-format keeps them

2 participants