Skip to content

fix(query): rank chained price paths by evidence, not by spelling - #2158

Merged
robcohen merged 3 commits into
mainfrom
fix/chained-price-tiebreak
Aug 26, 2026
Merged

robcohen merged 3 commits into
mainfrom
fix/chained-price-tiebreak

Conversation

@robcohen

@robcohen robcohen commented Aug 26, 2026 •

Copy link
Copy Markdown
Member

Closes #2152, except the general staleness question, which the research below argues is not specific to chaining.

The PR changed shape partway through. It started as tests-and-docs pinning the existing alphabetical tie-break; measuring the problem showed that tie-break was the wrong behaviour to pin.

What the corpus says

Across all 761 corpus files:

files with price directives 97
files where chaining is NEEDED 54
chainable pairs 1152
of those, multi-path 2 (0.17%)
leg date gap p50 0d, p90 184d, p99 5968d, max 5968d
gaps over one year 88 / 1154 (7.6%)

The tie-break reaches two pairs in the whole corpus. But the real one is ledger_prices.beancount, BTC to CNY:

via USD    BTC->USD 19107.45 (2020-11-24) x USD->CNY  6.5868 (2020-11-24) = 125,856 CNY
via USDT   BTC->USDT 10757.30 (2019-07-16) x USDT->CNY  6.95 (2019-07-16) =  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 better number because USD sorts before USDT -- right answer, wrong reason, and a currency named AUSDT would have flipped it.

The change

A chain is only as current as its oldest leg: a 2010 A -> B times a 2024 B -> C produces a figure that looks 2024-dated and rests on 2010 data. So paths are now ranked by

  1. most recent oldest-leg (the best-supported route),
  2. then smallest gap between the legs,
  3. then currency name, so the order is still total and independent of hash iteration.

Both lookups now share one ranking through best_chain. The latest-rate variant previously carried its own copy of the sort and could drift from the as-of one.

What I tried and backed out

I first ported beancount's prices.project() rule: anchor leg 2 to leg 1's date, and decline if no rate existed then. It is genuinely more conservative, and I had verified it refuses this issue's era-mixing fixture where we answer 20.00 USD.

A pre-existing test stopped it, correctly: test_chained_lookup_uses_newest_rate_per_leg. Two reasons it was the wrong rule to import.

Different question. project() synthesises a price SERIES at the base commodity's own dates, so "no FX rate on 07-10" is coherent for it. get_chained_price(base, quote, date) answers "value as of D". Under the ported rule we refused when leg 2 was merely NEWER -- valuing an 07-10 close with an 07-11 exchange rate -- which is ordinary, not suspect. (beancount refuses that too; it is right for project and wrong here.)

Inconsistent. A stale DIRECT price is returned without complaint: get_price(XCOIN, BRIDGE, 2024) returns the 2010 rate and nobody objects. Refusing only the chained case would be an inconsistent rule rather than a stricter one. Staleness is a general concern, not a chaining one, and #2152 stays open for it.

Prior art

chains? route choice leg dates
beancount get_price no n/a leaves the amount unconverted
beancount project() yes, explicit route caller names it anchored to leg 1; declines otherwise
hledger yes, automatic, any length shortest chain, forward preferred over reverse each leg latest <= query date
rustledger (before) yes, automatic, 1 hop alphabetical each leg latest <= query date
rustledger (after) yes, automatic, 1 hop best-supported, then closest, then name each leg latest <= query date

hledger returns 20.00 USD on the era-mixing fixture, identical to us, so we were never an outlier on leg dating. We were an outlier on the tie-break: hledger ranks by chain length and forward-over-reverse, a principled order, not by spelling.

Verification

  • Booked-value gate against beancount: known 34, found 34, new 0 across 761 files. No divergence moved.
  • Freshness case picks the 2020 route over the alphabetically-first 2019 one.
  • The era-mixing fixture is unchanged in value, deliberately, per the backed-out reasoning above.
  • Both ranking properties pinned, and both proofs are real rather than assumed: ranking name ahead of freshness fails with left: Some(74763.2350), right: Some(125856.951660), and removing the name tie-break fails the stability assertions.
  • 180 tests, clippy clean on local 1.96 and CI's 1.97, RUSTDOCFLAGS="-D warnings" cargo doc clean (this PR is doc-heavy and cargo test does not catch rustdoc errors), typos clean, workspace builds.

🤖 Generated with Claude Code

https://claude.ai/code/session_012nNGPA44Dt32NyxWem26xr

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
Copilot AI lite review requested due to automatic review settings August 26, 2026 15:29
@robcohen
robcohen requested a review from a team as a code owner August 26, 2026 15:29
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
@robcohen robcohen changed the title test(query): pin the chained-price tie-break, and say what it is fix(query): rank chained price paths by evidence, not by spelling Aug 26, 2026
@codecov

codecov Bot commented Aug 26, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.

📢 Thoughts on this report? Let us know!

@github-actions

github-actions Bot commented Aug 26, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

🔴 Slower than base on: simple

Shape rustledger beancount Speedup RSS (rledger / beancount)
simple 56.5ms ± 6.6ms 716.3ms ± 6.1ms 12.7x 55.1 MB / 50.0 MB
investment 74.0ms ± 3.0ms 2796.5ms ± 20.6ms 37.8x 59.0 MB / 58.0 MB
fifo 70.7ms ± 3.8ms 15923.0ms ± 118.9ms 225.3x 61.1 MB / 57.8 MB

vs base, measured in this run

Shape base this PR Change RSS base → PR
simple 50.8ms ± 3.2ms 56.5ms ± 6.6ms +11.3% 🔴 regression 55.3 MB → 55.1 MB (-0.4%)
investment 76.0ms ± 5.7ms 74.0ms ± 3.0ms -2.6% ✅ within noise 59.1 MB → 59.0 MB (-0.1%)
fifo 70.5ms ± 3.2ms 70.7ms ± 3.8ms +0.2% ✅ within noise 63.0 MB → 61.1 MB (-3.1%)

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

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.

Copilot encountered an error and was unable to review this pull request. You can try again by re-requesting a review.

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

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

Comment thread crates/rustledger-query/src/price.rs Resolved
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
robcohen merged commit 3f1c969 into main Aug 26, 2026
66 checks passed
@robcohen
robcohen deleted the fix/chained-price-tiebreak branch August 26, 2026 17:52
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.

Chained price lookup can mix rates from distant dates and resolves multi-path ambiguity alphabetically

2 participants