Skip to content

feat(query): add six missing beanquery BQL functions - #2155

Merged
robcohen merged 7 commits into
mainfrom
feat/bql-missing-functions
Aug 26, 2026
Merged

robcohen merged 7 commits into
mainfrom
feat/bql-missing-functions

Conversation

@robcohen

@robcohen robcohen commented Aug 25, 2026 •

Copy link
Copy Markdown
Member

Closes #2153, except for repr, which I argue below should stay absent.

What was missing, and why they differ

Five had no implementation at all: COMMODITY, COMMODITY_META, CURRENCY_META, FINDFIRST, YEARMONTH.

HAS_ACCOUNT is a different case and the more interesting one. It has always worked as a FROM predicate and was simply unreachable from a projection:

$ rledger query t.beancount "BALANCES FROM has_account('Assets')"     # worked
$ rledger query t.beancount "SELECT has_account('Assets')"            # no function matches

So this is one name that resolved on one path and not its sibling.

Placement

evaluate_function already documents the split: functions needing the row's context stay on the lazy path, everything else goes through the shared value registry. HAS_ACCOUNT asks about the whole entry, so it joins META and WEIGHT on the lazy path. The other five need only their argument values.

COMMODITY_META / CURRENCY_META answer from the commodity directive rather than from any posting, so the executor now collects that metadata in the same directive walk that already builds account_info. Both constructors were updated -- missing new_with_sources would have left the sourced-directives path returning Null for every currency while the plain path worked.

Verified against bean-query 3.2.3

call bean-query rustledger
commodity(units(position)) 'USD' USD
commodity_meta("USD","name") 'US Dollar' US Dollar
commodity_meta("USD","asset-class") 'cash' cash
currency_meta("HOOL","name") 'Hooli Inc' Hooli Inc
commodity_meta("NOPE","name") None None
findfirst("z", tags) 'zz' zz
findfirst("nomatch", tags) None None
yearmonth(date) datetime.date(2024, 2, 1) 2024-02-01
has_account("Assets") True true
has_account("Nope") False false

The negative rows are deliberate. An early version of this check used a ledger with no commodity directive, so commodity_meta returned Null on both sides and the row proved nothing. The fixture now carries real commodity directives with metadata, and the Null cases are pinned separately.

Coverage, measured the same way #2153 was:

before: 7 of 67 beanquery functions unreachable
after:  1 of 67 (repr, deliberately)

Why repr is not implemented

beanquery's repr returns Python's own object syntax:

repr(number)  ->  "Decimal('10.00')"
repr(date)    ->  'datetime.date(2024, 2, 1)'
repr(tags)    ->  "frozenset({'t1'})"

Matching that means emitting CPython type names from Rust. It describes another language's runtime rather than the ledger, and it would pin us to CPython's formatting for every value type we ever add. I would rather leave it absent and say so than ship a function whose contract is "guess what CPython prints".

The reasoning is recorded in the test that covers the other six, so the next person to notice the gap finds the argument rather than re-deriving it.

One known difference

The one-argument form returns the directive's metadata without bean-query's synthetic filename / lineno keys. That difference is pre-existing and not specific to these functions, and it runs both ways: entry_meta("filename") returns a path here and None in bean-query. Aligning metadata modelling is a separate question from adding these functions.

Review rounds

Two defects found reviewing my own first commit against bean-query, before the automated review landed:

  • Duplicate commodity directives resolved to the first, not the last. or_insert_with kept January's metadata where bean-query answers with June's. Nothing else in query output reveals which directive was used, so this was invisible without a side-by-side run. Now insert, pinned by a test confirmed to fail against the old behaviour (left: "First", right: "Second").
  • COMMODITY accepted a position. bean-query types it commodity(Amount) and rejects commodity(position), so we were accepting an input it refuses. The comment justifying the extra arm claimed cost() "may hand back either"; it does not, which commodity(cost(position)) proves by returning the COST currency. Arm removed, and the rejection is now asserted.

From the automated review, four more:

  • HAS_ACCOUNT was implemented twice, in the FROM predicate and the new projection arm, and had already drifted in error text after one commit. Both now call Executor::entry_has_account.
  • The test helper only asserted rows[0][0]. These evaluate per posting and the fixture has two rows, so a disagreeing second row would have passed. It now pins every row and names the offending index; confirmed by pointing it at SELECT account, whose rows legitimately differ.
  • FINDFIRST cloned the whole string set before scanning. Now scans borrowed and clones only the match.
  • A doc-comment grammar fix, already resolved by an earlier doc_markdown rewrite.

One residual asymmetry, pre-existing and left alone

HAS_ACCOUNT now shares its matching logic across both spellings, but argument handling still differs. The FROM path accepts an unquoted account, the projection path does not:

BALANCES FROM has_account(Assets)     rustledger: works      bean-query: CompilationError
SELECT HAS_ACCOUNT(Assets)            rustledger: error      bean-query: CompilationError

The projection side matches bean-query. The FROM side is more permissive than bean-query, and that is pre-existing: the same query behaves identically on main, before any change here. I left it rather than tighten it inside this PR, since rejecting it would break queries that work today and that is a compatibility decision worth making on its own.

Checks

  • New test asserts each function against the bean-query answer, plus the Null and false cases, plus that the FROM spelling still selects the entry the projection now reports true for.
  • The test was confirmed to fail before it was trusted: poisoning the YEARMONTH expectation to 2024-02-15 produced left: Date(2024-02-01), right: Date(2024-02-15), and restoring it returned to green.
  • cargo test -p rustledger-query: 174 passed, 0 failed.
  • Clippy clean under both the local nix 1.96 and CI's 1.97 (a doc_markdown finding on CPython only appeared under one of them).
  • The 34 query shapes swept while finding Seven beanquery BQL functions are unavailable in SELECT projections, and the compat corpus does not exercise any of them #2153 are unchanged.

🤖 Generated with Claude Code

https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr

Closes #2153, except for `repr`, which is argued against below.

`COMMODITY`, `COMMODITY_META`, `CURRENCY_META`, `FINDFIRST` and `YEARMONTH`
had no implementation. `HAS_ACCOUNT` did: it has always worked as a FROM
predicate, and was simply not reachable from a projection, so
`BALANCES FROM has_account('Assets')` returned rows while
`SELECT has_account('Assets')` raised `no function matches`.

Placement follows the split already documented in `evaluate_function`.
`HAS_ACCOUNT` asks about the whole entry, so like the META family and WEIGHT
it stays on the lazy path where the row's transaction is still in scope. The
other five need only their argument values and go through the shared value
registry.

`COMMODITY_META` / `CURRENCY_META` read the `commodity` directive rather than
any posting, so the executor now collects that metadata in the same directive
walk that already builds `account_info`. Both constructors were updated;
missing the second would have left the sourced-directives path answering Null
for every currency.

Each function is pinned against what bean-query 3.2.3 returns for the same
ledger, including the cases that are easy to fake: a currency with no
`commodity` directive is Null rather than an error, `FINDFIRST` with no match
is Null, and `HAS_ACCOUNT` is asserted false as well as true. The test also
asserts the FROM spelling still selects the entry the projection reports true
for, since those are now two paths to one answer.

Not implementing `repr`. beanquery's version returns Python's own object
syntax: `Decimal('10.00')`, `datetime.date(2024, 2, 1)`, `frozenset({'t1'})`.
Matching it means emitting CPython type names from Rust, which describes
another language's runtime rather than the ledger, and would pin us to
CPython's formatting for every value type we ever add. Left absent
deliberately, with the reasoning recorded in the test that covers the rest.

One known difference on the one-argument form: bean-query's metadata dicts
carry synthetic `filename` and `lineno` keys and ours do not. That is
pre-existing and not specific to these functions, and it points both ways --
`entry_meta("filename")` returns a path here and None in bean-query.

Verified: 7 of 67 beanquery functions were unreachable before this change,
1 after. Clippy clean on 1.96 and on CI's 1.97. The 34 query shapes swept
while finding #2153 are unchanged, and the new test was confirmed to fail on
a wrong expectation before being trusted.

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

codecov Bot commented Aug 25, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 82.69231% with 18 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger-query/src/executor/mod.rs 82.52% 18 Missing ⚠️

📢 Thoughts on this report? Let us know!

@github-actions

github-actions Bot commented Aug 25, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 49.9ms ± 4.4ms 830.6ms ± 12.4ms 16.6x 55.1 MB / 50.0 MB
investment 70.2ms ± 2.0ms 3094.3ms ± 36.8ms 44.1x 59.1 MB / 58.0 MB
fifo 69.6ms ± 4.3ms 15665.5ms ± 192.2ms 225.2x 61.0 MB / 57.7 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 48.8ms ± 3.9ms 49.9ms ± 4.4ms +2.3% ✅ within noise 54.7 MB → 55.1 MB (+0.6%)
investment 71.6ms ± 2.6ms 70.2ms ± 2.0ms -2.0% ✅ within noise 59.1 MB → 59.1 MB (-0.0%)
fifo 70.8ms ± 5.1ms 69.6ms ± 4.3ms -1.7% ✅ within noise 61.1 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.6ms, investment 1.5ms, fifo 3.0ms), 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

…ity must reject a position

Two defects found reviewing the previous commit against bean-query.

A currency declared twice resolved to the FIRST `commodity` directive. The
collection used `or_insert_with`, so a ledger with `commodity USD` at the top
of the year and again in June answered with January's metadata where
bean-query answers with June's. Nothing else in the query output reveals
which directive was used, so this would have been invisible outside a
side-by-side comparison. Now `insert`, in both constructors.

`COMMODITY` accepted a position. bean-query types it strictly as
`commodity(Amount)` and rejects `commodity(position)` at compile time, so we
were accepting an input it refuses. The comment justifying the extra arm said
`cost()` "may hand back either" an amount or a position; that is not true,
`cost()` yields an Amount, which the `commodity(cost(position))` case
demonstrates by returning the COST currency rather than the units currency.
The arm was added on a premise that does not hold, so it is gone and the
error message no longer advertises positions.

Both are now pinned. The duplicate-declaration test was confirmed to fail
against the old `or_insert_with` (`left: "First", right: "Second"`) before
being trusted, and `COMMODITY(position)` is asserted to error rather than
merely to return something.

Re-verified against bean-query 3.2.3: duplicate declaration gives Second on
both sides, `commodity(position)` errors on both, and
`commodity(cost(position))` / `commodity(units(position))` still give USD and
HOOL respectively.

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

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

Adds missing Beanquery BQL functions to the rustledger-query executor so they can be used in SELECT projections (and aligns HAS_ACCOUNT behavior between projection vs FROM usage), with new regression tests pinned to bean-query outputs.

Changes:

  • Extend the query executor with implementations for COMMODITY, COMMODITY_META/CURRENCY_META, FINDFIRST, YEARMONTH, and projection support for HAS_ACCOUNT.
  • Add executor-side caching of commodity directive metadata to back *_META lookups.
  • Add a new regression test covering the newly-supported functions and key null/false cases.

Reviewed changes

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

File Description
crates/rustledger-query/src/executor/mod.rs Adds commodity metadata caching and implements the missing/previously-unreachable BQL functions in the executor.
crates/rustledger-query/src/executor/tests.rs Adds a new regression test exercising the newly-supported functions against expected bean-query results.
Suppressed comments (1)

crates/rustledger-query/src/executor/mod.rs:286

  • Same as the non-sourced constructor: commodity_meta uses or_insert_with, which preserves only the first commodity directive per currency. This can make COMMODITY_META / CURRENCY_META return stale metadata if later directives override earlier ones.
                Directive::Commodity(commodity) => {
                    commodity_meta
                        .entry(commodity.currency.to_string())
                        .or_insert_with(|| commodity.meta.clone());
                }

💡 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

robcohen and others added 4 commits August 25, 2026 19:48
… the test

Review follow-ups on #2155.

`HAS_ACCOUNT` had two implementations after the previous commit: the FROM
predicate in `evaluate_from_filter` and the new projection arm. They answered
the same question about the same entry and had already drifted in their error
text, which is exactly how the pair would keep drifting. Both now call
`Executor::entry_has_account`.

The test's `one()` helper read `rows[0][0]`. These functions evaluate per
posting and the fixture has two, so a second row disagreeing with the first
would not have been noticed. It now asserts every row matches, and names the
offending index when one does not. Confirmed by pointing the helper at
`SELECT account`, whose rows legitimately differ: `row 1 disagrees with row 0`.

`FINDFIRST` cloned the whole string set before scanning. It now scans the
borrowed slice and clones only the element that matches, so a hit on the
first tag no longer copies the rest.

The FROM spelling still returns both accounts for `BALANCES FROM
has_account('Assets')` after the extraction, and the existing assertion that
the two spellings agree still passes.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
Codecov flagged 36 uncovered lines in `evaluate_function_on_values`, and
almost all of them were the guard arms added with these functions.

Those branches were verified by hand against bean-query while writing the
feature, which is worth nothing once someone refactors the match. Manual
verification does not survive; a test does.

Covers three shapes per function where they apply: wrong arity, wrong
argument type, and Null in. The Null rows are the ones worth having.
bean-query answers Null rather than raising for a Null input, so an arm that
errored instead would turn a query over a ledger with one missing payee into
a hard failure, and `payee` is genuinely Null on the fixture rather than a
hand-built value. Invalid regexes are asserted to error rather than to behave
as "matches nothing", which would silently answer false for a typo'd pattern.

Confirmed the error assertions fail for the intended reason and not because
the query failed to parse: each message names its own function
(`COMMODITY expects an amount`, `YEARMONTH expects a date`). Confirmed the
test bites by flipping a Null expectation to `Boolean(true)`
(`left: Null, right: Boolean(true)`).

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

Coverage pointed at the one block of #2153's change that no test reached:
the `Directive::Commodity` arm inside `new_with_sources`.

That is the arm the commit adding it singled out as easy to miss, on the
grounds that the two constructors build their own caches and a lookup added
to one and not the other fails only on the path that constructor serves.
The claim was right and went untested, which is the same shape as the bug it
warns about. `new_with_sources` is the CLI and LSP path, so it is where a
user would actually hit it.

Deleting that arm now fails the new test with `left: Null, right: "US
Dollar"`, which is exactly the described failure: metadata resolves under
`Executor::new` and comes back Null under the sourced constructor. Verified
by removing it, running, and restoring.

Also covers the one-argument form returning a populated metadata map. The
existing tests only reached that spelling on the missing-currency path, where
it returns Null and the `Value::Metadata` construction never runs.

Patch coverage went 65% to 82% with the previous commit; this takes the
remaining structural gap.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
Six user-facing functions landed with no way to discover them. The BQL
reference keeps curated tables per category and none of the six appeared in
any of them, so the only route to `yearmonth` or `commodity_meta` was reading
the executor.

Each entry states something checked against the running binary rather than
inferred from the implementation:

- `commodity()` versus `currency()` is the entry most worth having. They
  overlap and are not interchangeable. `commodity()` takes an amount, which
  is bean-query's spelling, so `commodity(units(position))` and
  `commodity(cost(position))` separate the units currency from the cost
  currency -- `HOOL` and `USD` on `2 HOOL {10.00 USD}`. `currency(position)`
  takes a position, always answers about units, and is a rustledger extension
  that bean-query rejects outright. Anyone writing a query to run under both
  wants `commodity()`, and nothing said so.
- `has_account()` asks about the ENTRY, so it is true on every row of a
  matching transaction, including postings to other accounts. Verified: on a
  transaction touching Assets:A and Equity:O, both rows report true. Without
  that sentence the natural reading is per-posting, which would quietly make
  `WHERE has_account(...)` look broken.
- Commodity metadata gets its own table next to the meta family, because it
  resolves from a `commodity` directive rather than from a transaction or
  posting, and the existing section is entirely about that distinction. The
  last-declaration-wins rule is stated there too, since it is otherwise only
  discoverable by declaring a currency twice.

`repr` stays undocumented, matching its absence from the implementation.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
@robcohen
robcohen merged commit 6ae7b84 into main Aug 26, 2026
61 checks passed
@robcohen
robcohen deleted the feat/bql-missing-functions branch August 26, 2026 03:13
robcohen added a commit that referenced this pull request Aug 26, 2026
…low-up

Reading the finished diff end to end turned up a doc describing a design
this branch had already replaced.

`build_entries_table` still explained that `meta` and `_entry_meta` carry the
same value and that the underscore copy cannot be renamed. Both sentences
were true when written and false two commits later: the duplicate column was
removed precisely because storing the map twice cost a deep clone per entry.
A reader would have gone looking for `_entry_meta` in that table's column
list and not found it.

Now describes what is there: metadata in one column, `ENTRY_META` resolving
through the fallback, and why `#postings` still needs its own `_entry_meta`
(there `meta` is the POSTING's metadata and `_entry_meta` the TRANSACTION's,
two different maps on one row).

This is the same defect an automated reviewer caught on #2155, where a
comment justified an argument type using a premise that no longer held. A
stale comment that merely repeats the code is noise; one that explains why
something must be a certain way, after that stopped being true, actively
misleads.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
robcohen added a commit that referenced this pull request Aug 26, 2026
* fix(query): give #entries the five columns bean-query exposes

`SELECT * FROM #entries` returned 11 columns against bean-query's 16.
Missing: `year`, `month`, `day`, `description`, `meta`.

None of them needed building. Every name already resolved against
`#postings`, and `description` is the same "payee | narration" shape that
table already produces. The `#entries` schema simply did not list them, so
`SELECT year FROM #entries` -- a query that runs under bean-query -- failed
here with `column 'year' not found`.

Column order now matches bean-query position for position, not just as a set.
`SELECT *` is positional for anyone reading rows as tuples, so getting the
membership right and the order wrong would still break them.

Date parts come from the entry's own date rather than from a transaction, so
they are populated for every directive type: bean-query reports `year` on an
`open`, and now so do we. `description` is Null on a non-transaction, matching
how `payee` and `narration` already behave there.

`meta` and `_entry_meta` deliberately hold the same value. The underscore copy
cannot be renamed: `ENTRY_META` resolves through it, and `wildcard_hidden`
uses the underscore prefix to keep helpers out of `SELECT *`. Verified the
hidden spelling still answers, that `ENTRY_META` / `ANY_META` still work, and
that `_entry_meta` still does not leak into the wildcard now that a visible
`meta` sits beside it.

Values checked row by row against bean-query 3.2.3 on a ledger mixing opens,
a payee transaction, a narration-only transaction and a note: identical on
all five columns. The test asserts order and was confirmed to fail with
`year` removed before being trusted.

`#transactions.meta` is left for #2154. bean-query carries it as a column but
excludes it from `SELECT *`, and `wildcard_hidden` keys on the name alone
with no table context. Adding it visibly would trade a missing column for a
wildcard that returns 8 where bean-query returns 7, which is a worse bug than
the one being fixed.

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

* refactor(query): one description helper, and stop storing entry metadata twice

Review follow-ups on #2157.

`"payee | narration"` was written out twice, once for `#entries` and once for
`#postings`. Both describe the same transaction, so a change to the separator
or the no-payee case on one side would have produced two tables disagreeing
about the same row. Now one `transaction_description`.

`#entries` stored its metadata in two columns, `meta` and `_entry_meta`,
holding the same map. That cost a deep clone per entry on every query that
touches the table, projected or not. The table now carries it once, and
`eval_meta_on_table_row` falls back to the visible `meta` when the helper
column is absent.

The fallback cannot misfire on `#postings`, which is the case that matters:
that table carries `meta`, `_entry_meta` and `_posting_meta` as three
DISTINCT values, so the helper column is present and the fallback is never
reached. Confirmed by comparing against main rather than by reading the code
-- `ANY_META("postkey")` returns `postval` on both, and `META` / `ENTRY_META`
still separate posting metadata from entry metadata on the same row.

`ENTRY_META` and `ANY_META` now resolve on `#entries` too, returning the
transaction's value and Null on directives that carry none.

The test previously asserted `_entry_meta` was addressable on `#entries`.
That was pinning the duplicate storage, so it now asserts the opposite, plus
the part a user actually depends on: the functions that used to read it still
answer.

`SELECT *` unchanged at 31 columns for `#postings` and 16 for `#entries`.

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

* test(query): pin that the entries metadata fallback leaves #postings alone

Coverage showed the untested half of the fallback was the branch that takes
the helper column when it IS present. That is the branch the safety argument
rests on, so the claim "cannot misfire on #postings" was the part with no
test behind it.

`#postings` is where a wrong answer would be silent rather than loud: `meta`
there is the POSTING's metadata and `_entry_meta` is the TRANSACTION's, two
different maps on one row. Resolving `ENTRY_META` through `meta` would return
posting metadata and look plausible.

The fixture sets the same key at both levels with different values, so an
accessor reading the wrong column returns the wrong string rather than Null,
and all three of `META`, `ENTRY_META` and `ANY_META` are pinned on the same
row.

Confirmed it bites before trusting it: making the fallback unconditional
fails with `ENTRY_META on #postings must read the transaction's metadata, not
the posting's`.

The one remaining uncovered line is the `_ => (Null, Null, Null)` arm for
date parts. Every directive variant maps to `Value::Date`, so it is
defensive rather than reachable; the alternative is an unwrap, which is
worse.

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

* docs(query): correct the entries-table note left stale by its own follow-up

Reading the finished diff end to end turned up a doc describing a design
this branch had already replaced.

`build_entries_table` still explained that `meta` and `_entry_meta` carry the
same value and that the underscore copy cannot be renamed. Both sentences
were true when written and false two commits later: the duplicate column was
removed precisely because storing the map twice cost a deep clone per entry.
A reader would have gone looking for `_entry_meta` in that table's column
list and not found it.

Now describes what is there: metadata in one column, `ENTRY_META` resolving
through the fallback, and why `#postings` still needs its own `_entry_meta`
(there `meta` is the POSTING's metadata and `_entry_meta` the TRANSACTION's,
two different maps on one row).

This is the same defect an automated reviewer caught on #2155, where a
comment justified an argument type using a premise that no longer held. A
stale comment that merely repeats the code is noise; one that explains why
something must be a certain way, after that stopped being true, actively
misleads.

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

---------

Co-authored-by: Claude Opus 5 <[email protected]>
robcohen added a commit that referenced this pull request Aug 26, 2026
Reading the finished diff turned up a doc describing a design this branch
tried and abandoned.

`lookup_dated_at` said the chained lookup needs the rate's date "so it can
value the second leg as of that same moment". That was true of the anchoring
attempt and false once it was backed out: both legs are dated the caller's
way now, and the date is used for RANKING paths rather than for pinning one
leg to the other. A reader would have gone looking for anchoring logic that
is not there.

Same defect as the one an automated reviewer caught on #2155 and I caught on
#2157: a comment that merely restates code is noise, but one explaining why
something must be a certain way, after that stopped being true, actively
misleads.

Also folds two near-verbatim copies of the ranking rationale into one.
`get_chained_price` and `best_chain` each carried the full explanation of
path selection and the stale-chain policy; the caller now points at the
function that owns the logic. Two copies of an argument drift the same way
two copies of a sort do, which is what this branch already fixed in the code.

Co-Authored-By: Claude Opus 5 <[email protected]>
Claude-Session: https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr
robcohen added a commit that referenced this pull request Aug 26, 2026
)

* test(query): pin the chained-price tie-break, and say what it is

Two of the three items in #2152. The third is left deliberately, below.

`get_chained_price` documents that "intermediates are tried in sorted order
so the result is deterministic when several paths exist". Nothing tested it.
The three existing chained-price tests each build a single chain, so the sort
could have been dropped in a refactor and all three would still pass. Both
`get_chained_price` and `get_chained_latest_price` carry their own copy of
the sort line, so both were unheld.

The new test builds two complete same-dated paths worth deliberately
different amounts, 20.00 via AAA and 50.00 via MMM, and asserts the
alphabetically first wins in both functions. Equal-valued paths would have
passed whichever way iteration went, which is the property being detected.
It also rebuilds the database eight times, because the underlying map is a
hash map and insertion-order luck shows up across constructions rather than
within one run.

Confirmed it bites, once per function: removing the sort from
`get_chained_price` fails it, and so does removing the sort from
`get_chained_latest_price`. Two copies, two independent proofs.

The doc now says what the guarantee is worth. Deterministic is not
principled: 20.00 wins because `AAA` sorts before `MMM`, and nothing in the
output mentions that 50.00 was equally available. A reader of the old
sentence could reasonably assume the choice meant something. It also records
that legs are dated independently, so a 2010 leg times a 2024 leg yields a
current valuation with no diagnostic.

NOT fixing the staleness half. There is no precedent to align with: the only
age concept in the tree is the price-FETCH cache, which governs how long a
downloaded quote is reused rather than whether a rate is too old to value
with. A bound would be new user-facing policy -- someone has to choose a
window, choose error versus warn, and choose whether reports differ -- and
that is a decision to make deliberately, not to smuggle in as a bug fix.
#2152 stays open for it.

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

* fix(query): rank chained price paths by evidence, not by spelling

Replaces the alphabetical tie-break in chained lookups. When several one-hop
routes exist, the winner is now the one whose OLDEST leg is most recent, then
the one whose legs sit closest together, then the currency name so the order
stays total and independent of hash iteration.

A chain is only as current as its oldest leg. Multiplying a 2010 `A -> B` by
a 2024 `B -> C` yields a figure that looks 2024-dated and rests on 2010 data,
so ranking by that date is what makes the chosen path the best-supported one
rather than the alphabetically luckiest.

The corpus made the case. Chaining is needed in 54 of 761 files across 1152
pairs, and multi-path ambiguity reaches only 2 of them -- but the real one is
`ledger_prices.beancount`, BTC to CNY via USD or USDT, where the answers are
125,856 and 74,763 CNY. A 68% spread, and the paths do not disagree about
BTC: one route's quotes stop 16 months earlier. We returned the right number
because `USD` sorts before `USDT`. A currency named `AUSDT` would have flipped
it.

Both lookups now share one ranking through `best_chain`; the latest-rate
variant used to carry its own copy of the sort and could drift from the
as-of one.

NOT refusing stale chains, after trying it. beancount's `prices.project()`
anchors its second leg to the first leg's date and declines when no rate
existed then, and porting that rule here was wrong for two reasons. It is
built for a different question -- `project` synthesizes a price SERIES at the
base commodity's own dates, while this answers "value as of D" -- and it
refuses when the second leg is merely NEWER, which broke
`test_chained_lookup_uses_newest_rate_per_leg`: valuing an 07-10 close with
an 07-11 rate is ordinary, not suspect. More decisively, a stale DIRECT price
is returned here without complaint, so refusing only the chained case would
be an inconsistent rule rather than a stricter one.

Verified: the era-mixing fixture from #2152 is unchanged in value, the
freshness case now picks the 2020 route over the alphabetically-first 2019
one, and the booked-value gate against beancount reports `known 34, found 34,
new 0` across 761 files, so no divergence moved.

Both properties are pinned and both proofs are real: ranking the name ahead
of freshness fails with `left: 74763, right: 125856`, and removing the name
tie-break fails the stability assertions.

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

* docs(query): correct the note left stale by backing out anchoring

Reading the finished diff turned up a doc describing a design this branch
tried and abandoned.

`lookup_dated_at` said the chained lookup needs the rate's date "so it can
value the second leg as of that same moment". That was true of the anchoring
attempt and false once it was backed out: both legs are dated the caller's
way now, and the date is used for RANKING paths rather than for pinning one
leg to the other. A reader would have gone looking for anchoring logic that
is not there.

Same defect as the one an automated reviewer caught on #2155 and I caught on
#2157: a comment that merely restates code is noise, but one explaining why
something must be a certain way, after that stopped being true, actively
misleads.

Also folds two near-verbatim copies of the ranking rationale into one.
`get_chained_price` and `best_chain` each carried the full explanation of
path selection and the stale-chain policy; the caller now points at the
function that owns the logic. Two copies of an argument drift the same way
two copies of a sort do, which is what this branch already fixed in the code.

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

---------

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.

Seven beanquery BQL functions are unavailable in SELECT projections, and the compat corpus does not exercise any of them

2 participants