Repository navigation
fix(format): stop deleting a note's tags and links - #2192
Conversation
`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
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
✅ Compatibility Test Results
What's tested
Full results available in workflow artifacts |
There was a problem hiding this comment.
🟢 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/^linktokens fornotedirectives during CST formatting. - Factor the header tag/link re-emission logic into a shared helper used by both
noteanddocument. - 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.
📊 Benchmark Results
vs base, measured in this run
A difference counts only when it clears the combined spread of the two measurements, per shape (2σ: What do these numbers mean?
|
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.
|
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 A |
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.
|
Correction to the verification notes on this PR. I reported After 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. |
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.
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.
* 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]>
Closes #2184.
What was happening
Formatting is supposed to preserve meaning. This silently deleted user data on every run.
Which formatter
The issue points at
format_note_linesinrustledger-core. That is not the code that runs —rledger formatcallsrustledger_parser::format::format_source, the CST formatter. That is also why a document's tags survived:emit_documentthere carried a direct-child token walk re-emitting the header's TAG / LINK tokens, andemit_notecarried 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_MATRIXasserts 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
emit_noteline fails the new test (control).format-idempotence.sh:checked=693 skipped=42 non_idempotent=0 diagnostics_changed=0format-preserves-comments.sh:checked=693 dropped_comments_in=0corpus_paritydivergences: 20, unchanged from main (pre-existing).cargo docclean.Found on the way: #2191
The same fidelity check over the whole matrix fails on
balance_with_arithmetic_and_tolerance— the formatter emits0.25 + 0.75 ~ 0.01 USD, which no longer parses. That is a parser inconsistency (it accepts~ TOL CURRENCYafter 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