Skip to content

fix(query): give #entries.meta its source keys, and empty meta a map - #2167

Merged
robcohen merged 2 commits into
mainfrom
fix/bql-meta-content-v2
Aug 27, 2026
Merged

robcohen merged 2 commits into
mainfrom
fix/bql-meta-content-v2

Conversation

@robcohen

@robcohen robcohen commented Aug 27, 2026 •

Copy link
Copy Markdown
Member

What

Two ways metadata reached a query differently from bean-query.

1. #entries.meta dropped filename and lineno

bean-query carries them alongside the user's keys:

bc: {'filename': '/tmp/f.bean', 'lineno': 4, 'mtxn': 'tv', '__tolerances__': {...}}
rl: {mtxn: tv}                                                    <-- before
rl: {filename: /tmp/f.bean, lineno: 4, mtxn: tv}                  <-- after

#postings already did this through the existing augmented_meta helper.
#entries had the same SourceLocation in scope — it builds the filename
and lineno columns from it — and simply did not use it for meta.

2. Absent metadata produced Null, not {}

$ bean-query -f csv f.bean "SELECT meta FROM #notes"      # note with no metadata
{}
$ rledger query -f csv f.bean "SELECT meta FROM #notes"   # before
                                                          # (empty)

These are distinct values in bean-query, which renders Null as an empty CSV
field — so meta IS NULL answered true for us and false there.

The scoping is the load-bearing part

The augmentation goes on #entries only. bean-query's per-table meta
columns — #notes, #balances, #events, #documents, #commodities —
exclude filename/lineno. Moving this into the shared metadata_to_value
would have broken the five tables #2161 just brought into agreement.

Verified explicitly, with a negative control so the check cannot pass
vacuously:

filename/lineno in meta?
#entries bean-query yes, ours yes
the five per-table columns bean-query no, ours no

Behaviour change worth stating

meta IS NULL now answers false for a directive with no metadata, where it
answered true before. That is the point of the fix on the bean-query-facing
columns, but it applies uniformly, including to our own hidden helper columns
_entry_meta / _posting_meta, which now report {} rather than Null for an
un-annotated transaction or posting. Those have no bean-query equivalent, so
there is nothing to match there; the uniform semantic is simply the correct
one. Verified on a file with four posting rows, two annotated and two not.

Nothing outside the query crate keys off metadata being Null — the
MetaValue::None handling in the FFI and core is about an individual metadata
value, not the map.

Scope of the match

The keys are right; their order is not, and cannot be here. bean-query
emits filename, lineno first then declaration order; we emit alphabetical,
because metadata_to_value collects into a BTreeMap. That is load-bearing:
Metadata is an FxHashMap, so the BTreeMap is the only thing making
SELECT meta deterministic. Declaration order is lost at parse time, so the
query layer cannot recover it. Recorded in #2168.

A user key named filename or lineno correctly wins over the injected one,
matching bean-query — augmented_meta only fills keys that are absent.
Verified.

Not replicated

bean-query also injects __tolerances__ into #entries.meta — its internal
per-currency inference cache. That is an implementation detail rather than
ledger content, and mirroring it would put beancount's internals into user
query results. Same reasoning that closed #2166.

Verification

Closes #2162

Two divergences from bean-query, both in how metadata reaches a query.

`#entries.meta` dropped `filename` and `lineno`. bean-query carries them
alongside the user's keys there. `#postings` already did this via
`augmented_meta`; `#entries` had the same source location in scope and
did not use it.

The augmentation belongs on `#entries` specifically. bean-query's
per-table `meta` columns -- #notes, #balances, #events, #documents,
#commodities -- exclude `filename`/`lineno`, which is verified here, so
moving this into the shared conversion would break the five tables #2161
brought into agreement. A regression check confirms those five still
match bean-query without the source keys while #entries has them.

Second, an absent metadata block produced `Null` where bean-query
produces `{}`. Those are distinguishable in bean-query -- it renders Null
as an empty CSV field -- so `meta IS NULL` answered true where
bean-query answers false.

Not replicated: bean-query also injects `__tolerances__` into
`#entries.meta`, its internal per-currency inference cache. That is an
implementation detail rather than ledger content, and exposing it would
put beancount's internals in user query results.

Neither fix was covered: reverting either passed the whole suite before
these tests. Both are confirmed to fail against their unfixed code.
@robcohen
robcohen requested a review from a team as a code owner August 27, 2026 14:28
Copilot AI lite review requested due to automatic review settings August 27, 2026 14:28
@codecov

codecov Bot commented Aug 27, 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

This PR fixes two BQL compatibility gaps with bean-query around how directive metadata is surfaced from system tables in rustledger-query.

Changes:

  • Ensure #entries.meta includes synthetic filename/lineno keys (without affecting per-table meta columns like #notes.meta).
  • Change empty metadata conversion from Null to an empty object/map ({}) so meta IS NULL matches bean-query semantics.
  • Add integration tests covering both behaviors.

Reviewed changes

Copilot reviewed 3 out of 3 changed files in this pull request and generated 1 comment.

File Description
crates/rustledger-query/tests/bql_integration_test.rs Adds regression tests for empty-metadata-as-{} and #entries.meta carrying filename/lineno.
crates/rustledger-query/src/executor/system_tables.rs Augments #entries.meta using augmented_meta(...) so it carries source keys.
crates/rustledger-query/src/executor/mod.rs Makes metadata_to_value return an empty object for empty metadata instead of Null.
Suppressed comments (1)

crates/rustledger-query/tests/bql_integration_test.rs:6763

  • This test asserts key presence by searching the Debug string, which is brittle (format changes can break it) and can also pass with empty placeholder values because the SourceMap has no file registered. Consider registering a file in the SourceMap and asserting directly on the returned Value::Object contents (and specific values for filename/lineno).
    let source_map = SourceMap::new();
    let mut executor = Executor::new_with_sources(&spanned, &source_map);
    let result = executor
        .execute(&parse("SELECT meta FROM #entries").expect("should parse"))
        .expect("query should execute");

    let rendered = format!("{:?}", result.rows[0][0]);
    assert!(
        rendered.contains("lineno"),
        "#entries.meta should carry lineno, got {rendered}"
    );
    assert!(
        rendered.contains("filename"),
        "#entries.meta should carry filename, got {rendered}"
    );

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

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 39.1ms ± 5.0ms 591.5ms ± 25.4ms 15.1x 55.1 MB / 49.9 MB
investment 54.6ms ± 2.6ms 2165.7ms ± 4.7ms 39.7x 59.0 MB / 58.1 MB
fifo 54.7ms ± 3.8ms 12043.3ms ± 72.0ms 220.4x 59.1 MB / 58.0 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 39.1ms ± 4.7ms 39.1ms ± 5.0ms -0.0% ✅ within noise 55.2 MB → 55.1 MB (-0.1%)
investment 54.1ms ± 1.9ms 54.6ms ± 2.6ms +0.8% ✅ within noise 59.1 MB → 59.0 MB (-0.2%)
fifo 54.1ms ± 4.9ms 54.7ms ± 3.8ms +1.1% ✅ within noise 60.9 MB → 59.1 MB (-3.1%)

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

Review catch on #2167. The empty-metadata test asserted only that the
value was not Null. That would still pass if per-table `meta` picked up
the synthetic `filename` / `lineno` keys -- the exact regression this
change's scoping exists to prevent. It now asserts the value IS an empty
map, and the #entries test inspects the map rather than a Debug string.

Adds the missing test for the split itself: the same directive, through
the same executor, must carry the source keys in `#entries.meta` and must
not carry them in `#notes.meta`.

Both directions confirmed by mutation. The first attempt at the
per-table direction passed `None` as the location, which `augmented_meta`
early-returns on, so it changed nothing and proved nothing; injecting the
keys inside the shared `metadata_to_value` is the realistic regression
shape and does fire the assertion.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

2 participants