Repository navigation
fix: price sources must honor --date or refuse it - #1801
Conversation
The Yahoo source hardcoded range=1d, read regularMarketPrice (the LIVE quote), and stamped request.date onto it — so any --date emitted the current market price labeled as that historical date, silently corrupting price archives (the report demonstrated identical prices for 2000-01-03 and 2025-01-02). The audit found the same stamp-the-requested-date pattern across most sources; ECB even OVERRODE the real rate date it already had. Two-tier fix: - Yahoo gets real historical support, mirroring beanprice's get_historical_price: a five-day period1/period2 window ending at the requested date, the LAST non-null close on or before that date, emitted under the quote's OWN date (a Saturday request yields Friday's close dated Friday), and a hard error when the window holds no usable quote — never the latest price under a historical label. Parsing is a pure parse_chart() unit-tested against fixture JSON (weekend resolution, null-close holidays, empty-window refusal, latest path). - Every latest-only source (alphavantage, coinbase, coincap, coinmarketcap, eastmoneyfund, ecb, oanda, quandl, ratesapi, tsp) now REFUSES a historical --date via a shared reject_historical_date guard instead of mislabeling (today's date is allowed — the latest quote genuinely belongs to today). Per-source historical support where the APIs allow it is tracked separately. - ECB additionally labels with the feed's own reference date instead of the requested one (on weekends the latest rate is Friday's and must say so). Closes #1794 Co-Authored-By: Claude Fable 5 <[email protected]>
Codecov Report❌ Patch coverage is 📢 Thoughts on this report? Let us know! |
📊 Benchmark Results
vs main branch (2026-07-17)
What do these numbers mean?
|
There was a problem hiding this comment.
Pull request overview
Fixes a class of silent price-archive corruption where “latest-only” sources stamped the live quote with an arbitrary --date, and adds true historical support for Yahoo charts. This touches the rledger price command’s built-in sources to ensure dates are either honored correctly or rejected explicitly.
Changes:
- Implement historical quote retrieval for Yahoo via a 5-day
period1/period2window and fixture-tested parsing that emits the provider quote’s effective date (not the requested date). - Add a shared
reject_historical_date()guard so latest-only sources refuse historical--daterequests with an actionable error. - Adjust ECB to label output with the feed’s own reference date (direct/inverted/cross), rather than
request.date.
Reviewed changes
Copilot reviewed 12 out of 12 changed files in this pull request and generated 1 comment.
Show a summary per file
| File | Description |
|---|---|
| crates/rustledger/src/cmd/price/sources/yahoo.rs | Adds historical URL construction and robust chart parsing with unit tests to prevent mislabeling live quotes as historical. |
| crates/rustledger/src/cmd/price/sources/mod.rs | Introduces reject_historical_date() guard and adds tests for guard behavior. |
| crates/rustledger/src/cmd/price/sources/ecb.rs | Uses ECB feed reference dates consistently and refuses historical --date requests. |
| crates/rustledger/src/cmd/price/sources/alphavantage.rs | Refuses historical --date via shared guard (latest-only behavior). |
| crates/rustledger/src/cmd/price/sources/coinbase.rs | Refuses historical --date via shared guard (latest-only behavior). |
| crates/rustledger/src/cmd/price/sources/coincap.rs | Refuses historical --date via shared guard (latest-only behavior). |
| crates/rustledger/src/cmd/price/sources/coinmarketcap.rs | Refuses historical --date via shared guard (latest-only behavior). |
| crates/rustledger/src/cmd/price/sources/eastmoneyfund.rs | Refuses historical --date via shared guard (latest-only behavior). |
| crates/rustledger/src/cmd/price/sources/oanda.rs | Refuses historical --date via shared guard (latest-only behavior). |
| crates/rustledger/src/cmd/price/sources/quandl.rs | Refuses historical --date via shared guard (latest-only behavior). |
| crates/rustledger/src/cmd/price/sources/ratesapi.rs | Refuses historical --date via shared guard (latest-only behavior). |
| crates/rustledger/src/cmd/price/sources/tsp.rs | Refuses historical --date via shared guard (latest-only behavior). |
Comments suppressed due to low confidence (1)
crates/rustledger/src/cmd/price/sources/ratesapi.rs:58
reject_historical_date()is called before the same-currency fast-path. This makesrledger price EUR --currency EUR --date <historical>fail even though returning1.0is correct for any date and doesn’t risk mislabeling a provider quote. Move the same-currency branch above the guard (or exempt it) so historical identity conversions keep working.
fn fetch_price(&self, request: &PriceRequest) -> Result<PriceResponse> {
// Latest-only source: a historical --date must refuse, not
// mislabel the current quote (#1794).
super::reject_historical_date(self.name(), request)?;
// If ticker and currency are the same, return 1.0
if request.ticker.to_uppercase() == request.currency.to_uppercase() {
let date = request.date.unwrap_or_else(|| jiff::Zoned::now().date());
return Ok(PriceResponse {
price: Decimal::ONE,
currency: request.currency.clone(),
date,
source: self.name().to_string(),
});
}
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
✅ Compatibility Test Results
What's tested
Full results available in workflow artifacts |
Fixed past date for the rejection case; a clock-stability retry loop for the today-passes case (the guard re-reads the clock internally). Co-Authored-By: Claude Fable 5 <[email protected]>
Ten confirmed findings from the multi-agent review of #1801; the top three were severe: - Yahoo classified quote bars by UTC civil date; NZX/ASX sessions cross UTC midnight, so Tuesday's bar masqueraded as Monday and overwrote Monday's real close — re-introducing the exact wrong-date corruption #1794 fixed, for Pacific exchanges. Bars are now classified by the EXCHANGE's civil date via meta.gmtoffset (beanprice's semantics), the fetch window is padded a day each side (bounds are slop; classification decides), the sortedness assumption is gone (track max date <= requested), and an NZX fixture pins it. - The price cache sits ABOVE the sources, so pre-fix poisoned entries (live quotes stored under historical dates) would be served forever after upgrading. The cache file is now a versioned envelope (CACHE_SCHEMA_VERSION 2); the old bare-map format fails the parse and loads as empty, discarding every poisoned entry. A regression test pins the legacy format being rejected. - The guard now rejects ANY explicit --date (including today's), matching beanprice — a dated fetch requires historical support — and eliminating the per-fetch local-clock comparison that flipped behavior mid-batch across midnight. Also from the review: - Identity branches (ratesapi ticker==currency, ECB EUR->EUR) moved ABOVE the guard: 1.0 is correct for any date and the guard must not remove previously-correct dated answers. - ECB cross-rates reconcile both legs' reference dates (min) instead of silently discarding the currency leg's. - Yahoo's latest path labels with the quote's own trading day (regularMarketTime + gmtoffset); ratesapi uses the feed's "date" field; alphavantage uses "07. latest trading day" — a weekend fetch dates the price Friday everywhere. - ExternalCommandSource documented as deliberately unguarded: the date is forwarded via RLEDGER_DATE, so historical semantics belong to the external fetcher. - New drift guard: every latest-only builtin's fetch_price must fire the shared guard on a dated request (hermetic — the guard precedes all network I/O). Co-Authored-By: Claude Fable 5 <[email protected]>
Co-Authored-By: Claude Fable 5 <[email protected]>
|
Deep multi-agent review completed (26 verified findings → 10 distinct, all CONFIRMED) — all fixed in 55589ce..47c4bc5. The top three were severe enough that the original fix would have shipped broken: Severe:
Also fixed: identity branches (ratesapi ticker==currency, ECB EUR→EUR) moved above the guard — 1.0 is date-independent and previously-correct dated answers must survive; ECB cross-rates reconcile both legs' reference dates (min) instead of discarding one; Yahoo's latest path labels with Full suite green, clippy clean. |
Round 2 of the #1794 review found the fix itself introduced regressions and left the bug class alive in two paths: - alphavantage: forex/crypto still dated quotes with the local clock; both paths now share one CURRENCY_EXCHANGE_RATE fetch that labels from the feed's "6. Last Refreshed" field (the two copies had drifted from the fixed stock path). - ecb: cross-rate legs from two fetches can straddle the daily publication; min()-labeling the quotient asserted a rate valid for no date. Mismatched leg dates now refuse with a retry hint. The identity exemption widens from EUR/EUR to any ticker==currency pair, restoring the pre-#1801 dated USD/USD = 1 answer. - guard: --date <today> is allowed again on latest-only sources; the latest quote is a valid answer for today and directives are emitted with the response's own date. Past and future dates still refuse (nightly `--date $(date +%F)` runs worked before #1801 and must keep working). - cache: discarding a legacy/mismatched file now marks the cache dirty so the next save() replaces the poisoned pre-#1801 file on disk even when the run fetches nothing; load is path-injectable and the legacy test asserts the real load()+save() observables instead of a re-implemented parse; save() no longer deep-clones the entries map. - registry: a fallback chain reports every source's failure instead of letting a trailing source's "latest quote only" refusal mask the real error from a historical-capable source. - yahoo: bar classification prefers meta.exchangeTimezoneName (DST-safe per-instant offsets) with gmtoffset as fallback; fixture comments corrected (NZST is UTC+12) and a DST-transition regression test added. - clobber cache-hit test: pre-writes the current v2 envelope (the bare map was silently discarded, passing the test vacuously) and asserts the "skipped from cache" verbose marker so the exercised path is pinned. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_013gJH7uBBF9Xw9et9QFRcsU
|
Round-2 deep review (26 agents, adversarial verification; targeted at whether the round-1 fixes were themselves correct): 10 confirmed defects, all fixed in c608b6e. The headline findings were regressions the round-1 fixes introduced, plus the #1794 bug class surviving in touched code:
Full crate suite green (595 passed), clippy |
Round 3 targeted round 2's fixes and confirmed six correctness defects: - cache: a transient read error (EACCES, network home dir) no longer marks the cache dirty — round 2's dirty-on-discard let a recoverable I/O hiccup destroy a healthy cache on save(). Files with a NEWER schema version are likewise loaded as empty but left untouched on disk, so an older binary no longer wipes a newer binary's cache on every run; only genuinely poisoned (older/unversioned) files are queued for rewrite. - cache: dated keys are TTL-exempt only when the date is strictly in the past. A --date <today> fetch is an intraday quote; under the old rule the morning's value froze permanently as the day's price of record and same-day re-runs served it from cache. - guard: "today" is latched once per process (OnceLock) so a --date $(date +%F) batch straddling midnight no longer flips from accepted to refused mid-run with misleading drop---date advice. - ecb: the cross-rate leg-date-mismatch error no longer claims the cause is always a transient publication straddle — for a currency the ECB stopped publishing (HRK, RUB) the mismatch is permanent and the fix is a different source, so the message now says both. - yahoo: jiff now bundles the tz database (tzdb-bundle-always) so exchange-timezone classification works in tzdata-less environments (containers, the nix sandbox) instead of silently degrading to the DST-unsafe gmtoffset fallback — which also makes the DST regression test hermetic per the repo rule. - tsp/quandl: removed the stranded request.date fallback in the date label — dead under today's guard, but it was the exact #1794 mislabeling pattern lying in wait for the next guard relaxation. Cleanups from the same review: the feed-date-else-today extraction is now one canonical helper (sources::feed_date_or_today) used by alphavantage/ratesapi/ecb/tsp/quandl instead of five drifting copies; CACHE_SCHEMA_VERSION is pub and the clobber cache-hit fixture references it instead of a literal that would go stale on the next bump; the stale line-numbered TTL cross-reference in price_cmd.rs is line-number-free and reflects the new settled-date rule. Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_013gJH7uBBF9Xw9et9QFRcsU
|
Round-3 deep review (25 agents, adversarial verification; targeted at the round-2 fixes): 6 confirmed correctness defects + 4 cleanups, all fixed in 082a8fe. The two most severe were cache-destruction paths the round-2 dirty-on-discard fix introduced:
Cleanups: the stranded Full crate suite green (600 passed), clippy |
Round 4 targeted round 3's fixes and confirmed ten defects, the worst in the cache layer: - cache: settledness is now decided by the entry's OWN fetch day (cached_at), not the live clock. A quote keyed under date D but fetched ON day D is an intraday snapshot forever; the live-clock rule promoted it to a never-expiring "settled" price at midnight, serving stale intraday quotes as the historical price of record before any source guard could run — #1794 resurrected through the cache. - cache: load classification is now four-way (current / newer / poisoned / corrupt). Newer-schema files — including future envelopes whose shape no longer parses but whose version field is readable — put the cache in READONLY mode, so even a run that fetches cannot clobber a newer binary's cache (round 3 only protected no-fetch runs). Plain corruption (truncated write) is no longer queued for destruction on no-fetch runs. - guard: the process-wide "today" latch is replaced by a one-day midnight-straddle window (accept today, or yesterday only when the run's first fetch happened on it), so long-lived library embedders no longer freeze "today" at process start; decision logic extracted as a pure function with tests. - identity: ecb/ratesapi identity answers (X/X = 1.0) refuse FUTURE date labels via a shared identity_label_date helper — they bypass the main guard, and --date 2030-01-01 previously emitted and cached a fabricated future directive. - ecb: a cross-rate leg-date gap over five days is now diagnosed as a frozen/discontinued series (HRK, RUB) naming the stale leg, instead of useless "retry" advice. - eastmoneyfund: the last un-canonical feed-date parse (with the request.date mislabeling fallback) now routes through feed_date_or_today. - external: the --source-cmd trust contract is documented at the divergence site and in docs/commands/price.md — dateless output formats are trusted to answer for RLEDGER_DATE; scripts that cannot honor it should emit the dated beancount form. - docs: docs/commands/price.md now states which sources accept --date, the today-only rule for latest-only sources, and the settled vs intraday cache-expiry split (CHANGELOG is release-managed in this repo, so no entry). Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_013gJH7uBBF9Xw9et9QFRcsU
|
Round-4 deep review (24 agents, adversarial verification; targeted at the round-3 fixes): 10 confirmed findings, all addressed in ed3a4bd. The cache layer was again the hot spot — round 3's fixes each had a hole:
Note: a bot pushed a cargo-vet exemptions regeneration (69baeac) for the round-3 lockfile change; round 4 is rebased on top. Full crate suite green (607 passed), clippy |
What
#1794 reported the Yahoo source ignoring
--dateand stamping the LIVE quote with the requested historical date — silent corruption of price archives (the report's repro: identical prices for2000-01-03and2025-01-02). Auditing all 11 sources showed it's a class: most stamprequest.dateonto a latest quote, and ECB even overrides the real rate date it already parsed.Two-tier fix
Yahoo gets real historical support, mirroring beanprice's
get_historical_price:--date→ a five-dayperiod1/period2epoch window ending at the requested date (weekends/holidays resolve to the preceding trading day).parse_chart()unit-tested against fixture JSON: weekend resolution, null-close holidays skipped, empty-window refusal, latest path unchanged.Every latest-only source refuses a historical
--datevia a sharedreject_historical_dateguard (alphavantage, coinbase, coincap, coinmarketcap, eastmoneyfund, ecb, oanda, quandl, ratesapi, tsp) with an actionable message pointing at yahoo. Today's date passes — the latest quote genuinely belongs to today. This stops the corruption class everywhere immediately; per-source historical support where the provider APIs allow it (Coinbase?date=, exchangerate.host historical endpoints, quandlstart_date/end_date) is tracked in the follow-up issue.ECB additionally now labels rates with the feed's own reference date in all three branches (direct/inverted/cross) — on weekends the latest rate is Friday's and must say so.
Testing
Yahoo: URL construction both modes (epoch window pinned), four fixture-JSON parse tests. Guard: rejects yesterday with a source-naming error, passes today/absent. Full crate suite, clippy
-D warnings, fmt clean. (Provider correctness remains untestable in CI without a mock-HTTP harness — noted in the follow-up issue.)Closes #1794
🤖 Generated with Claude Code