Skip to content

fix(price): multi-quote price: metadata + clobber post-fetch dedup + --undeclared txn walk - #985

Merged
robcohen merged 5 commits into
mainfrom
fix/price-multi-quote-clobber-undeclared-cleanups
May 4, 2026
Merged

robcohen merged 5 commits into
mainfrom
fix/price-multi-quote-clobber-undeclared-cleanups

Conversation

@robcohen

@robcohen robcohen commented May 4, 2026

Copy link
Copy Markdown
Member

Summary

Closes the three known limitations from #967's audit punch list in one PR.

1. Multi-currency price: metadata (USD:yahoo/AAPL CAD:google/AAPL)

Before: parser produced two specs but DiscoveredCommodity.quote_currency only retained the first — CAD price was silently dropped.
After: DiscoveredCommodity carries quote_specs: Vec<QuoteSpec>; the fetch loop, source-cmd loop, and --dry-run plan iterate quote_specs, emitting one job per (base, quote) pair (matches bean-price). Per-iteration mapping override prevents source bleed-through between quotes. Legacy mapping/quote_currency fields kept as first-spec mirrors for back-compat.

2. --clobber date-mismatch dedup

Before: existing-prices check used the requested date. Sources that return a different effective date for "latest" (ECB on weekends, source-cmd JSON output) could still emit duplicates.
After: add a post-fetch re-check against the response date in both the network and source-cmd paths.

3. --undeclared transaction walking

Before: rledger walked commodity directives only; bean-price walks transactions. Held commodities without a commodity directive were missed.
After: add a transaction-walk pass that unions unit / at-cost / price-annotation currencies. Ticker-shape filter is still applied to transaction-derived currencies — preserves the #962 protection that keeps BAM / EUR-style codes out of stock sources.

Differential coverage

crates/rustledger/tests/bean_price_compat.rs gains FIXTURE_MULTI_CURRENCY (EUR priced in USD via yahoo and CAD via oanda — sources both binaries ship). The harness asserts rledger -n and bean-price -n produce the same ordered (symbol, currency, source, ticker) chains. Pre-fix this fixture had rledger emitting one job to bean-price's two; the test would have failed.

Test plan

  • cargo test -p rustledger — all 272+ tests pass
  • cargo clippy --all-features --all-targets -- -D warnings clean
  • cargo fmt --check clean
  • Pre-push hook runs bean-price compat tests end-to-end inside nix develop
  • New unit test: discover_picks_up_multi_currency_price_metadata
  • New harness fixture: rledger_and_bean_price_resolve_same_attempts_multi_currency
  • Existing --undeclared tests (undeclared_walks_transactions_for_ticker_shaped_currencies, _picks_up_at_cost_currency, _lowercase_or_long_names_still_excluded) continue to pass

Docs

docs/commands/price.md's --undeclared divergence note + table updated to reflect the new transaction-walk + ticker-shape behavior.

Closes #967 audit "Known limitations" 1, 2, 3.

🤖 Generated with Claude Code

…--undeclared txn walk

Closes the three known limitations from the #967 audit punch list:

1. **Multi-currency `price:` metadata** — `USD:yahoo/AAPL CAD:google/AAPL`
   now produces one fetch per declared (base, quote) pair, matching
   bean-price's per-(base, quote) job model. Pre-fix, only the first quote
   was retained and the CAD price was silently dropped.

   `DiscoveredCommodity` gains `quote_specs: Vec<QuoteSpec>`; the legacy
   `mapping`/`quote_currency` fields are kept as first-spec mirrors so
   single-quote callers don't break. The fetch loop, source-cmd loop, and
   `dump_fetch_plan` all iterate `quote_specs`, with each iteration
   building a one-shot mapping override so per-spec sources don't leak
   across iterations.

2. **`--clobber` date-mismatch** — sources whose returned date differs
   from the requested date (ECB on weekends, source-cmd JSON output) could
   slip past the pre-fetch dedup. Add a post-fetch re-check against the
   *response* date; mirrored in both the network and source-cmd paths.

3. **`--undeclared` transaction walking** — adds a transaction-walk pass
   that unions unit currency, at-cost currency, and price-annotation
   currency, then applies the ticker-shape filter (preserves #962
   protection against \`BAM\`/\`EUR\`-style false positives). Covers the
   common case where a commodity is held without a \`commodity\` directive.

## Differential coverage

bean_price_compat.rs gains FIXTURE_MULTI_CURRENCY (EUR priced in USD
via yahoo and CAD via oanda — both sources ship in both binaries). The
harness asserts rledger -n and bean-price -n produce the same ordered
(symbol, currency, source, ticker) chains. Pre-fix this fixture showed
rledger emitting one job to bean-price's two.

## Tests

- discover_picks_up_multi_currency_price_metadata — quote_specs carries
  both USD and CAD with their respective sources/tickers
- bean-price harness: rledger_and_bean_price_resolve_same_attempts_multi_currency

## Docs

docs/commands/price.md --undeclared divergence note + table updated to
reflect the new transaction-walk + ticker-shape behavior.

Closes #967 audit Known Limitations 1, 2, 3.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Copilot AI review requested due to automatic review settings May 4, 2026 02:07
@robcohen
robcohen requested a review from a team as a code owner May 4, 2026 02:07

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

Aligns rledger price behavior more closely with bean-price by supporting multi-quote price: metadata, improving --clobber dedup semantics for “latest” sources that return an effective date, and extending --undeclared discovery to walk transactions.

Changes:

  • Add multi-currency quote support by carrying quote_specs through discovery and iterating one fetch job per (base, quote) pair.
  • Add post-fetch --clobber duplicate suppression based on the response date (network + --source-cmd paths).
  • Extend --undeclared to also discover ticker-shaped commodities referenced in transactions.

Reviewed changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated 7 comments.

File Description
docs/commands/price.md Updates --undeclared docs and the bean-price divergence table to reflect transaction walking.
crates/rustledger/tests/bean_price_compat.rs Adds a differential harness fixture covering multi-quote price: metadata.
crates/rustledger/src/cmd/price_cmd.rs Implements per-quote fetch planning, per-quote mapping override, and post-fetch dedup for --clobber.
crates/rustledger/src/cmd/price/discovery.rs Introduces QuoteSpec/quote_specs and adds transaction-walk discovery for --undeclared plus new unit tests.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread crates/rustledger/src/cmd/price_cmd.rs Resolved
Comment thread docs/commands/price.md Resolved
Comment thread docs/commands/price.md Resolved
Comment thread crates/rustledger/src/cmd/price_cmd.rs Resolved
Comment thread crates/rustledger/src/cmd/price_cmd.rs Resolved
@codecov

codecov Bot commented May 4, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 77.48227% with 127 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger/src/cmd/price_cmd.rs 66.77% 106 Missing ⚠️
crates/rustledger/src/cmd/price/discovery.rs 91.42% 21 Missing ⚠️

📢 Thoughts on this report? Let us know!

@github-actions

github-actions Bot commented May 4, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 33ms ± 1.7ms 21.6 MB
beancount 800.5ms ± 3.7ms 50.5 MB
Comparison 24.3x faster 2.3x less

vs main branch (2026-05-03)

Metric main this PR Change
Time 36.4ms 33ms -9.3% 🟢
10K transactions · 5 runs, 2 warmup · hyperfine
What do these numbers mean?
  • Time: Wall-clock time to parse and validate the ledger (± std dev)
  • Memory: Peak resident set size (RSS)
  • vs main: Compared to latest nightly benchmark on main branch

@github-actions

github-actions Bot commented May 4, 2026 •

Copy link
Copy Markdown
Contributor

⚠️ Compatibility Test Results

Metric Result
Check Compatibility 99%
BQL Compatibility 91%
Full AST Match 99%
Total Files 782
What's tested
  • Check: Exit codes and error counts match bean-check
  • BQL: Query results match bean-query
  • Files: ~800 test files downloaded from 10+ beancount repositories

Full results available in workflow artifacts

robcohen and others added 4 commits May 3, 2026 20:22
…i-quote, add coverage

Addresses three issues from the deep PR review.

## Bug fix: as-of off-by-one (discovery.rs)

transaction_walked_currencies used d <= cutoff (inclusive equality), but
both bean-price's find_currencies_* and the existing commodity walk in the
same file use entry.date >= date: break — i.e. strict less-than. A
transaction dated exactly on the as-of cutoff was contributing currencies
to the discovered set even though a commodity directive on the same date
was excluded. Internally inconsistent and divergent from upstream.

Fix: change to d < cutoff. New test
undeclared_transaction_walk_uses_strict_less_than_for_as_of pins the
behavior at the boundary date.

(active_commodities at line 524 also uses <= — that's a separate
inclusive-as-of choice for the active-balance check, kept as-is and
called out in the docstring so the two cutoff conventions don't drift.)

## Doc: --source × multi-quote interaction

Added an explicit note in docs/commands/price.md's precedence section: a
commodity declaring multiple quote currencies (USD:yahoo/AAPL CAD:google/AAPL)
plus --source X will fetch BOTH quotes from X, ignoring the per-spec sources
in the metadata. Drop --source if you want the per-spec sources to take
effect. The dry-run output shows one row per quote so the bypass behavior is
visible.

## Test coverage gaps

- dump_fetch_plan refactored to take &mut impl Write, enabling unit tests
  that capture output. Two new tests:
  - dump_fetch_plan_emits_one_row_per_declared_quote (multi-quote regression)
  - dump_fetch_plan_source_flag_overrides_per_spec_for_all_quotes (pins the
    documented bypass behavior)

- New integration test crates/rustledger/tests/price_clobber_post_fetch.rs:
  - clobber_post_fetch_skips_when_response_date_matches_existing — uses a
    --source-cmd stub that emits a date != requested date, with an
    existing price directive at the response date. Verifies the post-fetch
    re-check kicks in (pre-check would miss this).
  - clobber_post_fetch_emits_duplicate_when_clobber_is_set — confirms the
    skip is gated on !args.clobber.

## Non-issue called out in review

The "cache lookup miss on multi-source quotes" concern is mitigated by
existing code at price_cmd.rs:399: the fetch loop already stores responses
under both the actual-source key AND the default-source key. So the second
run hits even when actual_source != source_name_for_cache. No fix needed.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
…y (Copilot review)

Addresses 7 inline comments from Copilot's review of PR #985.

## Bug fix: cache-hit --clobber dedup (price_cmd.rs)

The post-fetch --clobber re-check only ran in the network-fetch branch.
The cache-hit branch wrote `cached` directly via `write_price` without
checking the cached response date against existing_prices.

Concrete failure mode: a "latest" request cached on Friday gets stored
under requested key date 2024-01-15 with response.date = 2024-01-10
(the source's last published date). Subsequent runs hit the cache and
re-emit the 2024-01-10 directive every time — even though the file
already has it.

Fix: apply the same `existing_prices.contains((symbol, currency,
cached.date))` check in the cache-hit branch before write_price.

New integration test clobber_cache_hit_skips_when_cached_date_matches_existing
pre-warms a JSON cache file under XDG_CACHE_HOME and runs --source coinbase
to force the cache-hit branch (skipping the network entirely).

## Perf: Cow-borrow combined_mapping in the common case

Previously cloned `combined_mapping` per fetch job even when there was no
per-spec override. For a ledger with 100+ symbols the redundant clone
dominated. Switched both the runtime fetch loop and dump_fetch_plan to
`Cow<'_, HashMap<...>>` — borrows when no override (the common case),
allocates only when a per-spec source needs to be installed.

## Doc/comment accuracy: --undeclared shape filter

Multiple places (`docs/commands/price.md` x2, discovery.rs comment +
test) overpromised that the ticker-shape filter "keeps currency codes
like EUR/BAM out of stock sources." The truth: `looks_like_ticker`
matches 3-letter uppercase, so EUR/BAM/USD all pass with --undeclared
set.

The actual #962 protection is the strict DEFAULT requiring `price:`
metadata. Opting into --undeclared is opting into the heuristic, which
has known false positives for currency codes. Updated all four affected
spots to clarify this.

The test undeclared_walks_transactions_for_ticker_shaped_currencies
now also asserts `with_undeclared.contains_key("BAM")` to pin this
behavior — pre-fix the assertion was missing and the test name implied
BAM would be excluded.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Two cleanups from a self-review of commit 52a14ce.

## Cache-hit integration test gated to linux

clobber_cache_hit_skips_when_cached_date_matches_existing relies on
XDG_CACHE_HOME redirecting where rledger reads its prices.json. The
`dirs` crate honors XDG_CACHE_HOME only on Linux:
- macOS: ~/Library/Caches via NSSearchPathForDirectoriesInDomains
- Windows: FOLDERID_LocalAppData

On those platforms the spawned rledger would miss our pre-warmed
entry and try to hit the real coinbase API. Gate with
#[cfg(target_os = "linux")] and document why in the test docstring.

The other two tests in the file use --source-cmd which doesn't touch
the cache, so they remain #[cfg(unix)].

## Stale doc comment on transaction_walked_currencies

The wording about "ticker-shape filter that keeps currency codes out of
stock-source dispatch (#962)" was updated everywhere else in the previous
commit but missed on the function-level docstring at discovery.rs:222.
Refreshed to match: 3-letter uppercase codes pass the heuristic, the #962
protection is the strict default requiring `price:` metadata.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Two minor follow-ups from a fresh-eyes review of PR #985.

## Dedup duplicate (source, ticker) entries in build_mapping

User typo `"USD:yahoo/AAPL,USD:yahoo/AAPL"` previously produced a
Fallback chain with two identical entries. Result was deterministic
but the runtime would re-invoke yahoo on the first attempt's failure
(wasted work) and `--dry-run` would print yahoo twice (misleading).

Dedup by `(source, ticker)` in build_mapping; first occurrence wins
(preserves order, which is significant for fallback semantics).
After dedup, a single-entry chain collapses to Single, matching what
the existing `specs.len() == 1` short-circuit would have produced.

Mixed cases like `yahoo,ecb,yahoo` correctly retain `[yahoo, ecb]`.

Two new tests pin both behaviors:
- build_mapping_dedups_identical_fallback_entries
- build_mapping_dedups_in_fallback_chain_preserves_distinct_entries

## Document cache-key trade-off near the dual-write

The dual-write at price_cmd.rs:422 stores responses under both the
actual-source key (e.g. ecb after yahoo failed) AND the global
default-source key (yahoo). This makes fallback-chain second-runs hit
the cache instead of re-attempting yahoo every time.

Trade-off: if a user changes their `price:` source for a (symbol,
currency), historical-date lookups (no TTL) keep returning the OLD
source's payload until `--clear-cache`. "Latest" lookups are fine
because the 30-min TTL on `:latest` keys catches them.

Documented inline near the dual-write call site so future readers
understand why the lookup uses the default-source key rather than the
per-spec source. Pre-existing behavior; this PR's multi-quote work
doesn't change it but slightly widens the surface area, so worth
noting.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@robcohen
robcohen merged commit 538f1e1 into main May 4, 2026
31 checks passed
@robcohen
robcohen deleted the fix/price-multi-quote-clobber-undeclared-cleanups branch May 4, 2026 02:56
robcohen added a commit that referenced this pull request Jul 10, 2026
…1750)

* feat(report): render numbers through the ledger DisplayContext (U4)

Balance-style reports (balances, balsheet, income, holdings, networth)
printed raw Decimal Display, whose precision is an artifact of booking
arithmetic rather than ledger convention: an integer-written posting
in a 2dp ledger showed "100 USD" where bean-query (and our own BQL
output, context-aware since #961/#985) shows "100.00 USD".

LoadedReport now carries the loader's DisplayContext (per-currency
inferred precision under the MostCommon policy, display_precision
overrides, render_commas) and the five reports format every units
number and total through format_amount_number — one rendering shared
by text, CSV, and JSON arms. Lot-cost annotations keep their existing
Display form (pinned to bean-query's Position string in #1728/#1733).

Verified byte-identical against beancount 3.2.3 bean-query BALANCES on
a mixed-precision fixture, including both directions of the MostCommon
policy: 2dp-dominant ledgers pad integers to 100.00, integer-dominant
ledgers render 2400 — matching bean-query in each case. New
integration test pins the padded rendering and CSV consistency; full
CLI suite (incl. the #1733 query==report parity guard) green.

Co-Authored-By: Claude Fable 5 <[email protected]>

* fix: csv-escape context-formatted amounts; square balsheet CSV row (review)

render_commas puts thousands separators inside formatted numbers, so
every CSV arm writing them raw produced rows with extra columns — all
five reports now csv_escape the numeric fields (RFC-4180 quoting).
Also the balsheet Net Worth CSV row gains its empty trailing cost
field to match the five-column header. New test drives
option "render_commas" "TRUE" end-to-end and asserts quoted amounts
plus quote-aware column counts on every row.

Co-Authored-By: Claude Fable 5 <[email protected]>

---------

Co-authored-by: Claude Fable 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.

[Compat]: align rustledger price discovery 1:1 with bean-price (audit + sweep)

2 participants