Skip to content

fix(core): keep a note's tags and links - #2185

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

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

Conversation

@robcohen

Copy link
Copy Markdown
Member

What

note accepts #tag and ^link, parsed clean, and discarded both. There was
no way to get them back — and no diagnostic either: convert_note does not
call reject_tags_and_links the way commodity and event do, so they were
accepted and silently dropped rather than rejected.

$ rledger query t.beancount "SELECT type, tags, links FROM #entries WHERE type='note'"
note,,                              # before
note,ntag,nlink                     # after — matching bean-query exactly

Note now carries them, mirroring Document, and convert_note collects them
with the same direct-child token walk convert_document uses.

Query surfaces

#notes registers tags and links as visible columns — bean-query's
wildcard is date, account, comment, tags, links — and #entries surfaces
them for notes. That arm was Document-only precisely because a note's tags
did not survive parsing, and its comment said so; both are now correct.

before after
census of bean-query's 55 columns 3 unselectable 1 (#balances.discrepancy, #2180)
SELECT * parity across ten tables 6/10 7/10

Cache version

CACHE_VERSION 30 → 31, with the wasm pin and both FIXTURE_VERSION
tripwires. The archived layout gained two fields; without the bump, a cache
written by an older binary deserializes into the new struct and every note
comes back untagged — the same bug, resurrected from disk.

Contracts left alone, deliberately

The FFI component's note-dir and the plugin's note record carry no tags or
links, though the corresponding document records do — the same asymmetry, one
layer out. Widening either is a versioned WIT break that forces rustfava to
adopt a new contract, and doing that immediately before v0.23.0 isn't warranted
when the reported bug doesn't require it. Notes arriving from those boundaries
get empty tags, with a comment at each site saying why.

A test predicted this

select_star_matches_bean_query_per_table, added during #2165's review, failed
with the message it was written to produce:

SELECT * FROM #notes changed. Note this is NOT full bean-query parity:
bean-query also returns tags and links, which our Note model drops at parse
time (#2160). If you just added it, update this expectation.

That instruction was for whoever eventually closed #2160. Its recorded gap is
now None.

Verification

  • The issue's own reproduction now matches bean-query, as does the #notes
    wildcard.
  • Parser and query tests each confirmed to fail against their own regression —
    the parser no longer collecting tags, and #entries reverting to its
    Document-only arm — checked separately.
  • Booked-value gate clean (known 34, found 34, new 0); corpus_parity
    divergences still exactly 20, matching main.
  • clippy at CI's 1.97, fmt, rustdoc clean; typos clean on every changed file
    (two findings elsewhere in crates/ are pre-existing). 417 query tests pass.

Filed, not folded in

rledger format drops a note's tags (#2184). It could not have done
otherwise before — there was nothing to render — and no formatter logic
changed here.

Closes #2160

`note` accepts `#tag` and `^link`, parsed clean, and discarded both.
`Note` had no fields to hold them, and `convert_note` does not call
`reject_tags_and_links` the way `commodity` and `event` do -- so they
were accepted and silently dropped rather than diagnosed.

`Note` now carries them, mirroring `Document`, and `convert_note`
collects them with the same direct-child token walk `convert_document`
uses. The query layer follows: `#notes` registers `tags` and `links` as
VISIBLE columns, matching bean-query's wildcard, and `#entries` surfaces
them for notes -- that arm was Document-only precisely because a note's
tags did not survive parsing, and its comment said so.

CACHE_VERSION 30 -> 31, with the wasm pin and both FIXTURE_VERSION
tripwires. The archived layout gained two fields; without the bump a
cache written by an older binary deserializes into the new struct and
every note comes back untagged -- the same bug, resurrected from disk.

Contracts left alone deliberately. The FFI component's `note-dir` and
the plugin's `note` record carry no tags or links, though the
corresponding `document` records do. Widening either is a versioned
break that forces rustfava to adopt a new WIT, which is not worth doing
immediately before a release when the reported bug does not require it.
Notes arriving from those boundaries get empty tags, with a comment
saying why.

Census against bean-query's 55 system-table columns: 3 unselectable
before, 1 now (`#balances.discrepancy`, #2180). `SELECT *` parity across
the ten tables goes 6/10 to 7/10.

Found while fixing this and filed rather than folded in: `rledger format`
drops a note's tags (#2184). It could not have done otherwise before --
there was nothing to render -- and no formatter logic changed here.

Closes #2160
@robcohen
robcohen requested a review from a team as a code owner August 30, 2026 00:41
Copilot AI lite review requested due to automatic review settings August 30, 2026 00:41
@codecov

codecov Bot commented Aug 30, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 67.60563% with 23 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger-core/src/visit.rs 16.66% 10 Missing ⚠️
crates/rustledger-core/src/directive.rs 20.00% 8 Missing ⚠️
crates/rustledger-core/src/shift_spans_impls.rs 0.00% 4 Missing ⚠️
crates/rustledger-parser/src/cst/convert.rs 93.75% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

@github-actions

github-actions Bot commented Aug 30, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 47.7ms ± 1.0ms 859.1ms ± 1.6ms 18.0x 55.2 MB / 50.1 MB
investment 73.8ms ± 3.7ms 3124.0ms ± 83.6ms 42.3x 59.0 MB / 58.0 MB
fifo 70.0ms ± 1.8ms 16035.7ms ± 175.1ms 228.9x 61.0 MB / 57.8 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 49.5ms ± 4.7ms 47.7ms ± 1.0ms -3.7% ✅ within noise 55.0 MB → 55.2 MB (+0.3%)
investment 71.3ms ± 1.4ms 73.8ms ± 3.7ms +3.6% ✅ within noise 59.0 MB → 59.0 MB (-0.0%)
fifo 70.2ms ± 2.3ms 70.0ms ± 1.8ms -0.3% ✅ within noise 61.0 MB → 61.0 MB (-0.0%)

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

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.

🟡 Changes recommended

The #notes table builder’s rustdoc in system_tables.rs is now outdated relative to the newly added tags/links columns and should be updated for correctness.

Once you've addressed the issues Copilot identified, you can request another Copilot review.

Pull request overview

This PR fixes data loss for note directives by persisting #tag and ^link tokens into the core Note model, then surfacing them through BQL system tables to match bean-query behavior. It also bumps cache versions to prevent older cached layouts from reintroducing the “tags/links silently disappear” bug on deserialization.

Changes:

  • Extend rustledger_core::Note to include tags and links, and populate them in the CST converter.
  • Expose tags/links in #notes and ensure #entries returns them for notes (previously Document-only).
  • Bump loader cache version (and WASM pin + fixture tripwires) to account for the archived layout change, and add regression tests in parser + query layers.
File summaries
File Description
crates/rustledger-core/src/directive.rs Add tags/links fields to Note plus builder helpers.
crates/rustledger-parser/src/cst/convert.rs Collect trailing TAG/LINK tokens for notes (mirrors document logic).
crates/rustledger-parser/tests/parser_integration_test.rs Regression test: note preserves tags/links through parsing.
crates/rustledger-query/src/executor/system_tables.rs Add tags/links columns to #notes and propagate note tags/links into #entries.
crates/rustledger-query/tests/bql_integration_test.rs Regression test: #notes wildcard/columns and #entries parity for note tags/links.
crates/rustledger-loader/src/cache.rs Cache version bump + fixture version updates with rationale.
crates/rustledger-wasm/src/cache.rs Update loader cache version pin used by WASM cache tests.
crates/rustledger-ffi-wasi/src/types/input.rs Initialize new note fields as empty for wire-shaped notes (contract unchanged).
crates/rustledger-plugin/src/convert/from_wrapper.rs Initialize new note fields as empty for plugin-shaped notes (contract unchanged).
crates/rustledger-plugin/src/convert/mod.rs Update plugin conversion tests for new note fields.
crates/rustledger-core/src/shift_spans_impls.rs Ensure span-shifting walks new note fields.
crates/rustledger-core/src/visit.rs Update visitor test fixtures for new note fields.
crates/rustledger-core/src/extract.rs Update extraction test fixtures for new note fields.
crates/rustledger-core/src/format/mod.rs Update formatting test fixtures for new note fields.
Review details
  • Files reviewed: 14/14 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

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

Review catch on #2185. `Note` gained tags and links, but `visit_tags` and
`visit_links` still enumerated only `Transaction` and `Document` -- their
doc comments listed the positions explicitly, and note was not among
them. So `extract_tags` and `extract_links`, and everything downstream of
them, would not have seen a note's tags: the data existed and the
collector did not know.

Also regenerates the parser baseline manifest, which the gate demands.

The diff carries drift that is NOT from this change, and the split is
exact: running the regen script on a clean `main` produces 3 modified
hashes and 20 new entries by itself. Of the 13 modified here, those 3 are
pre-existing and the other 10 are this change -- and all 10 contain
`note` directives, which is the whole reason they moved. The 20
additions are corpus files that never had a baseline.

Filed the staleness as #2186 rather than leaving it implicit in this
diff.
Review catch on #2185. I bumped both FIXTURE_VERSION constants to 31
without adding an entry to either running log -- and those logs exist
precisely to record, per bump, whether the pinned byte fixtures survive.

v31 is also the first entry in the first list that genuinely moves an
archived layout. v25 and v30 are "no layout moved"; this one is "the
layout that moved is not the one these fixtures pin". `Note` gained
`tags` and `links`; the fixtures pin `CostNumber` discriminants and
payload encodings, which `Note` does not participate in. Same for the
second site, whose hash covers `MetaValue`: the new fields are
`Vec<Tag>` and `Vec<Link>`, neither of which is a `MetaValue`.

Verified separately that the bump does its job end to end: a cache
written by a CACHE_VERSION 30 binary is rejected rather than
deserialized, so a note read back through it keeps its tags instead of
coming back empty. `test_load_cache_rejects_older_version` already
covers version rejection generically, so no new test.
Review catch on #2185 from Copilot. The build_notes_table rustdoc still
listed the pre-change columns and said a note's tags are dropped at parse
time -- which this PR is what stops being true. It now lists tags and
links, marks them visible rather than hidden, and puts the parse-time
discard in the past tense with the issue that ended it.

Swept the tree for other places making the same claim; this was the
only one.
@robcohen
robcohen merged commit 362c75b into main Aug 30, 2026
75 of 76 checks passed
@robcohen
robcohen deleted the fix/note-tags-links branch August 30, 2026 03:58
robcohen added a commit that referenced this pull request Aug 30, 2026
…2196)

* ci: report corpus baseline drift on a cadence instead of by accident

The manifest is current -- a fresh fetch of the corpus regenerates to
zero diff, and all 735 files have an entry. #2185/#2189 carried the
drift #2186 describes. What is left is the reason it accumulated.

The issue attributes it to a path filter on the baseline gate. There is
none: `parser-baselines.yml` runs on every PR. The actual mechanism is
two deliberate decisions meeting:

  * A downloaded corpus file with no manifest entry is a WARNING there,
    not a failure, and the comment saying so is right -- upstream can
    add a file at any moment and failing would fire on unrelated PRs.
    But the warning goes to a log nobody reads, so the file sits with no
    parser-output coverage at all.

  * That job restores the corpus from a cache keyed on the FETCH SCRIPT
    and skips the fetch on an exact key hit. CI's corpus is frozen at
    whatever was fetched when the key was created, while the upstream
    repositories it mirrors keep moving. Every PR sees the same stale
    corpus and agrees there is no drift.

Neither is wrong on its own, and tightening either has the cost its
comment already explains. So this adds the missing third thing: a weekly
job that fetches the corpus FRESH -- no cache, which is the entire point
-- and turns drift into an issue. It reports, never gates, and closes
its own issue when the manifest matches again.

The oracle is the repository's own `BASELINE_UPDATE=1` path plus `git
diff`, not a Python reimplementation of the fingerprint, which would be
a second implementation free to disagree with the Rust one in exactly
the cases that matter.

Modeled on `nightly-health.yml`, including the self-test that runs first
and IS allowed to fail the job: the live check exits 0 whatever it
finds, so a broken classifier would otherwise report a permanently
reassuring "no drift" -- the same silence this exists to break, wearing
a green check. Verified by breaking it two ways (rehash detection
disabled, everything reported clean); the self-test catches both.

Refs #2186

* fix(ci): do not report a short fetch as upstream deletions

Review of the commit before this one. Fetching FRESH is what makes this
workflow able to see drift, and it is also what makes it able to invent
some.

The fetch tolerates up to 15 best-effort clone failures. On the PR gate
that is harmless: it restores a cached corpus, so a failed clone still
leaves the previous copy on disk -- `fetch-compat-test-files.sh` only
`mkdir -p`s its destination and never clears it. This job deliberately
skips that cache, so it fetches into an EMPTY checkout, where every
tolerated failure is simply missing files. Regenerating against that
drops their manifest entries, and the report would have called them
"upstream deleted or renamed these" -- a confident lie, longer and more
alarming the more repositories happened to fail.

So the corpus is counted first, against the same 50-file slack the
"Verify corpus is populated" step in `parser-baselines.yml` uses for the
same reason. Short by more than that and the run reports nothing and
says why. A partial fetch cannot manufacture a false "added" or
"rehashed", but it does mean the run saw an unrepresentative corpus, and
silence with a reason beats a plausible wrong answer.

Two more fixes to `--dry-run`, which regenerates and therefore rewrites
the manifest: it now restores the file afterward, because a flag named
dry-run must not leave a modified file for someone to commit by
accident -- and it does NOT restore it when the manifest was already
modified before the run, because `git checkout --` would delete the
caller's edits. A reporting script has no business destroying someone's
work to keep its own promise.

The guard is self-tested in both directions: always-complete (the bug
above) and always-refuse (the over-correction that would silence the
workflow) each fail it.

* docs(baselines): explain why there are two baseline jobs

`tests/baselines/README.md` documents the CI behavior for this manifest
and is where someone goes to understand it, so a second workflow acting
on the same file belongs there. Without it the cadence job reads as
duplicate coverage, and the natural next move is to delete one.

The section names the two reasons the PR gate cannot see this class --
an unmanifested downloaded file warns rather than fails, and the corpus
cache is keyed on the fetch script rather than on upstream state -- so
the distinction survives past whoever remembers the incident.

Also two guards on the script: it refuses to run outside the repository
root, where its relative paths and its `git checkout --` would either
fail confusingly or resolve somewhere unintended; and the comment about
always exiting 0 now says what that covers. Drift is reported rather
than gated, but `regenerate()` runs under `check=True`, so a corpus file
that panics the parser still fails the step -- that is a real problem on
main and nightly-health picks it up from there.

* fix(ci): a gh failure must not read as "nothing to report"

`gh()` returned an empty string when the command failed, which is
indistinguishable from a successful empty result. For a job whose only
output is an issue, that conflation is the worst bug available:

  * a failed `issue list` looks like "no existing issue", so the next
    run opens a duplicate, every week;
  * a failed `issue create` yields a blank URL, prints "opened ", and
    leaves the workflow GREEN having reported nothing at all.

The second is exactly the silence this workflow exists to break, wearing
a green check -- the same failure `nightly-health.yml` was written for,
reproduced inside its sibling.

`gh()` now raises `GhError`, and `main` turns that into a non-zero exit.
Finding drift stays exit 0, because a red X for a successful report
would be one more failing scheduled workflow for nobody to notice;
failing to report is the opposite case. A job that cannot say what it
found must not look like a job that found nothing.

Self-tested in both directions by stubbing `subprocess.run`: returning
"" on failure fails the test, and so does raising on a successful empty
result, which is a real and different answer.

Also makes the two list-element string concatenations explicit --
CodeQL's `py/implicit-string-concatenation-in-list`, flagged in review.
Adjacent literals on consecutive lines inside a list read as a missing
comma, and in a list of issue-body paragraphs that is a plausible typo
rather than a pedantic one.

* test(ci): execute the part of the drift reporter that does the work

`_report` decides between opening, updating and closing the issue -- it
is the only code in the script that changes anything -- and nothing had
ever run it. `--dry-run` returns before reaching it, and a scheduled run
exercises exactly one branch per week, so three of its four paths would
have shipped unexecuted and the fourth would have been tried in
production.

All four now run against a recording stub: drift with no open issue
creates, drift with an open issue edits THAT issue number, clean with an
open issue comments then closes in that order, and clean with no issue
touches nothing at all.

Each is verified to fail for its own reason -- swapping edit for create,
dropping the close, and passing drift to the no-op case each break
exactly one assertion. The last one matters most: a `_report` that
opened an issue every clean week would still have passed a test that
only checked the drift paths.

Stdout is captured while they run. Left alone the stub prints "opened
https://github.com/x/y/issues/1" into a self-test log, which is the sort
of line someone skims and believes.

* docs(ci): record why this guard is stricter than the test's own

The baseline test already refuses to write a manifest from fewer than
`MIN_FULL_CORPUS_SIZE` (100) files, so a partial fetch cannot silently
produce a truncated manifest and a false "no drift" -- checked, and it
panics rather than skipping when `BASELINE_UPDATE` is set.

That backstop and this check are not redundant, and the note says why:
at a corpus of ~735 this one trips at ~685, so a merely partial fetch
gets a sentence explaining itself instead of a cargo stack trace, and
the test's assert stays what it was written to be -- a last resort
against truncating the committed manifest, not the routine path.

Someone reading either guard alone would reasonably conclude the other
is dead weight.

* fix(ci): say which hash moved instead of telling the reader to go look

The "Changed hashes" section told the reader "the diff says which: a
changed source hash is upstream churn; a changed output hash with an
unchanged source hash is a parser change that reached main without
regenerating" -- and then printed a list of paths and no diff. It knew
the answer and sent the reader to find it.

`classify` already had both sides of every changed line, so it now
compares the source hashes and splits the group in two. They are not a
matter of emphasis:

  * source hash moved   -> the file's contents changed upstream, a
                           different output hash is expected, routine.
  * source hash IDENTICAL, output hash moved -> this repository produces
                           different output for the same bytes than the
                           committed baseline records. That is a parser
                           change that reached main unregenerated, and it
                           is the reason this job exists.

Collapsed into one list they look the same and read as churn, which is
how the second kind gets skimmed past.

Self-tested in both directions: forcing every rehash to read as upstream
fails, and so does forcing every one to read as a parser change. The
second control is the one that matters -- a split that always cries
"parser change" would be noise nobody acts on within a month.

* style(ci): explicit string concatenation, and say why the except is empty

Two CodeQL findings from review, both in code this branch added.

`py/implicit-string-concatenation-in-list`: nine runs of adjacent string
literals now join with an explicit `+`. Wrapping them in parentheses was
not enough -- adjacency inside parentheses is still adjacency, and the
concern is real for these in particular, since they are paragraphs of an
issue body where a missing comma would silently merge two of them rather
than raise.

Verified the rewrite changed nothing: rendering the same diff through
the pre-rewrite and post-rewrite modules gives a byte-identical body
(sha e0194f7e3082a81a both sides).

`py/empty-except`: the self-test's `except GhError: pass` is the
assertion -- reaching that arm is the pass condition and the
`failures.append` above it is what runs otherwise -- but nothing said
so, and a bare `pass` under an `except` is worth explaining every time.
robcohen added a commit that referenced this pull request Oct 12, 2026
* fix(ffi)!: hash a note's tags and links in meta.hash

Notes carry tags and links since #2588, but compute_directive_hash left
both out of a note's digest, so two notes differing only in tags or
links shared an identity. Hash them exactly as a document's are: the
tag and link counts always, then each element length-prefixed. Every
note's meta.hash changes, untagged ones included (decided on #2598).

Closes #2598

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

* docs(ffi): date note tags and links to #2185 in the hash comments

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

---------

Co-authored-by: Claude Opus 5.5 (1M context) <[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.

note silently discards its tags and links: parsed, accepted, and never stored

2 participants