Skip to content

fix: price sources must honor --date or refuse it - #1801

Merged
robcohen merged 10 commits into
mainfrom
fix/price-sources-honor-date
Jul 17, 2026
Merged

robcohen merged 10 commits into
mainfrom
fix/price-sources-honor-date

Conversation

@robcohen

Copy link
Copy Markdown
Member

What

#1794 reported the Yahoo source ignoring --date and stamping the LIVE quote with the requested historical date — silent corruption of price archives (the report's repro: identical prices for 2000-01-03 and 2025-01-02). Auditing all 11 sources showed it's a class: most stamp request.date onto 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-day period1/period2 epoch window ending at the requested date (weekends/holidays resolve to the preceding trading day).
  • Emits the last non-null close on or before the date, under the quote's own date — a Saturday request yields Friday's close dated Friday, exactly like upstream.
  • Hard error when the window holds no usable quote — never the latest price under a historical label.
  • Parsing extracted into a pure 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 --date via a shared reject_historical_date guard (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, quandl start_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

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]>
@github-actions

github-actions Bot commented Jul 17, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 33.6ms ± 1.5ms 23.8 MB
beancount 905.3ms ± 3.9ms 50.7 MB
Comparison 26.9x faster 2.1x less

vs main branch (2026-07-17)

Metric main this PR Change
Time 34.6ms 33.6ms -2.9% ✅
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

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

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/period2 window 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 --date requests 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 makes rledger price EUR --currency EUR --date <historical> fail even though returning 1.0 is 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.

@github-actions

Copy link
Copy Markdown
Contributor

✅ Compatibility Test Results

Metric Result
Check Compatibility 100%
BQL Compatibility 100%
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
  • Files: ~800 test files downloaded from 10+ beancount repositories

Full results available in workflow artifacts

robcohen and others added 3 commits July 17, 2026 02:18
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]>
@robcohen

Copy link
Copy Markdown
Member Author

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:

  1. UTC-vs-exchange-timezone misclassification — I classified bars by UTC civil date, but NZX/ASX sessions cross UTC midnight, so Tuesday's bar masqueraded as Monday and overwrote Monday's real close: the exact wrong-date corruption [Bug]: Yahoo price source ignores --date and labels latest quote as historical #1794 describes, re-introduced for Pacific exchanges. Bars are now classified by the exchange's civil date via meta.gmtoffset (beanprice's semantics), window bounds are padded slop, the unsorted-timestamps assumption is gone, and an NZX fixture pins it.
  2. The cache bypassed the whole fix — it sits above the sources and never expires dated keys, so pre-fix poisoned entries (live quotes under historical dates) would be served forever post-upgrade. The cache file is now a versioned envelope (schema v2); the legacy bare-map format fails the parse and loads empty, discarding every poisoned entry. Pinned.
  3. Guard strictness — now rejects ANY explicit --date (today's included), matching beanprice (a dated fetch requires historical support) and eliminating the per-fetch local-clock comparison that flipped behavior mid-batch across midnight.

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 regularMarketTime's trading day, ratesapi with the feed's date field, alphavantage with 07. latest trading day (weekend fetches date Friday everywhere); ExternalCommandSource documented as deliberately unguarded (RLEDGER_DATE is forwarded — historical semantics belong to the external fetcher); and a hermetic drift guard asserts all ten latest-only builtins actually fire the shared guard from fetch_price.

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
@robcohen

Copy link
Copy Markdown
Member Author

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:

  1. alphavantage forex/crypto still used the local clock for the quote date (only the stock path was fixed) — a Saturday FX fetch emitted Friday's rate under Saturday's date, the exact [Bug]: Yahoo price source ignores --date and labels latest quote as historical #1794 mislabeling. Both paths were byte-identical copies of the same endpoint fetch; they now share one function that labels from the feed's 6. Last Refreshed field.
  2. ECB cross-rate min(ticker_date, currency_date) was unsound: the two legs are separate fetches, and when they straddle the ~16:00 CET publication, dividing Monday's rate by Friday's produces a number valid for no date. Mismatched leg dates now refuse with a retry hint.
  3. The strict guard removed ECB's previously-correct dated identity answer: USD/USD on any date returned 1.0 via the cross-rate path before this PR; the identity exemption now covers any ticker == currency pair (matching ratesapi), not just EUR/EUR.
  4. The guard also broke --date <today> on all ten latest-only sources — nightly --date $(date +%F) scripts that worked before this PR would hard-error. Today's date is now allowed (the latest quote is a valid answer for today, and the emitted directive carries the response's own date anyway); past and future dates still refuse.
  5. The poisoned pre-fix cache file survived on disk: discarding a legacy file didn't mark the cache dirty, so a run with no fetches never rewrote it, and an older binary could serve the corrupted entries again. Discard now marks dirty, so the next save() replaces the file with an empty v2 envelope. (Mixed old/new binaries sharing one cache file remain mutually unreadable — accepted, documented; keeping the legacy format readable would keep the poison alive.)
  6. Fallback-chain errors masked: with --date, a trailing latest-only source's "drop --date" refusal overwrote the historical-capable source's real (possibly transient) error. The registry now reports every attempted source's failure.
  7. clobber_cache_hit_skips_when_cached_date_matches_existing had gone vacuous: it pre-wrote the legacy bare-map format, which the v2 envelope discards, so the test passed via the date guard without ever touching the cache. It now writes the v2 envelope and asserts the skipped from cache verbose marker so the exercised path is pinned.
  8. The legacy-rejection cache test asserted a proxy (a re-implemented serde parse) instead of the real observable. load is now path-injectable and the test asserts load() returns empty + dirty and save() destroys the poisoned file.
  9. Yahoo DST hazard: meta.gmtoffset is a single response-time offset; a bar on the far side of a DST switch inside the 8-day window could shift a civil day (fatal for midnight-anchored FX bars). Classification now prefers meta.exchangeTimezoneName (per-instant offsets via the tz database) with gmtoffset as fallback, plus a DST-transition regression test.
  10. Cleanup: NZX fixture comments claimed NZST = UTC+13 (it's +12; constants recomputed), stale five-day-window doc on build_url, stranded duplicate guard comment in ecb.rs, and save() no longer deep-clones the entries map.

Full crate suite green (595 passed), clippy -D warnings clean.

@robcohen
robcohen enabled auto-merge (squash) July 17, 2026 03:12
@robcohen
robcohen disabled auto-merge July 17, 2026 03:31
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
@robcohen

Copy link
Copy Markdown
Member Author

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:

  1. A transient read error destroyed a healthy cache: Err(_) from read_to_string marked the cache dirty with empty entries, so a recoverable EACCES/NFS hiccup led save() to overwrite the file with an empty envelope. Read errors now leave the file alone.
  2. An older binary wiped a newer binary's cache on every run: files with version greater than the current schema were treated like poisoned pre-fix files and queued for rewrite. Newer-versioned files now load as empty but stay untouched on disk; only genuinely poisoned (older/unversioned) files are rewritten.
  3. --date <today> froze the morning quote as the day's price of record: dated cache keys never expire, so the first intraday fetch served all day. TTL exemption now applies only to settled dates (strictly before today); today-dated entries honor the TTL like :latest.
  4. Midnight-straddling batches half-failed: the guard re-read the clock per fetch, so a --date $(date +%F) run started at 23:59 refused every fetch after midnight with advice to "drop --date". "Today" is now latched once per process.
  5. The ECB mismatch error misdiagnosed permanent failures as transient: for currencies the ECB stopped publishing (HRK frozen 2022-12-30, RUB suspended 2022-03-01) the feed returns the frozen final observation forever, so "retry in a moment" could never help. The message now names both causes.
  6. The DST regression test asserted machine state: it needed a system tz database, which the nix build sandbox lacks — and worse, the runtime exchange-timezone classification silently degraded to the DST-unsafe gmtoffset fallback in any tzdata-less container. jiff now bundles the tzdb (tzdb-bundle-always, rledger crate only), fixing both; verified by running the test with TZDIR=/nonexistent.

Cleanups: the stranded request.date fallback in tsp/quandl date labels (the exact #1794 pattern waiting for the next guard relaxation) is gone; the five drifting copies of feed-date-else-today extraction are now one canonical sources::feed_date_or_today helper with unit tests; CACHE_SCHEMA_VERSION is pub and the clobber cache-hit fixture references it instead of a hardcoded 2; the stale line-numbered TTL cross-reference in price_cmd.rs is fixed.

Full crate suite green (600 passed), clippy -D warnings clean.

rustledger-bot Bot and others added 2 commits July 17, 2026 03:56
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
@robcohen

Copy link
Copy Markdown
Member Author

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:

  1. The settled-date TTL exemption resurrected [Bug]: Yahoo price source ignores --date and labels latest quote as historical #1794 through the cache: it classified by key date vs the live clock, so a --date <today> intraday quote was promoted to a never-expiring "settled" price at midnight and served as the historical price of record on later runs — before any source guard could fire, since the cache is checked ahead of the sources. Settledness is now decided by the entry's own fetch day (cached_at): only a quote fetched after its keyed day ended is a real close; a quote fetched on its own day is an intraday snapshot forever.
  2. The newer-schema preservation only covered no-fetch runs: one insert marked the cache dirty and save() clobbered the newer binary's file anyway. Newer-schema files (including future envelopes whose shape no longer parses but whose version field is readable) now put the cache in readonly mode — the run simply goes uncached.
  3. The discard catch-all destroyed plainly corrupt files (truncated write) on no-fetch runs. Load classification is now four-way: current / newer (readonly) / poisoned (rewrite) / corrupt (leave alone; a fetching run may overwrite — the data was unreadable anyway).
  4. The process-wide "today" latch broke long-lived embedders: the lib target is public, and a daemon embedding it would freeze "today" at first fetch forever. Replaced with a one-day midnight-straddle window (accept today, or yesterday only when the run's first fetch happened on it), extracted as a pure function with tests.
  5. Identity answers bypassed the guard for future dates: --date 2030-01-01 on an ecb/ratesapi identity pair emitted and cached 2030-01-01 price USD 1 USD. A shared identity_label_date helper now refuses future labels.
  6. ECB's frozen-series case got useless "retry" advice: a leg-date gap over five days is now diagnosed as a discontinued currency (HRK, RUB), naming the stale leg and pointing at a source change.
  7. eastmoneyfund still had the request.date mislabeling fallback in an un-canonical inline date parse — the last copy the round-3 consolidation missed; now routed through feed_date_or_today.
  8. --source-cmd dateless output silently trusts the requested date: this is inherent (rledger can't verify a user-authored command), so the trust contract is now stated explicitly at the divergence site and in docs/commands/price.md, with the escape hatch (emit the dated beancount form).
    9-10. Docs: docs/commands/price.md now documents which sources accept --date, the today-only rule for latest-only sources, and the settled-vs-intraday cache expiry split (including the cache_ttl knob for same-day re-runs against rate-limited APIs). CHANGELOG is release-managed in this repo (fix: stop stripping backslashes from BQL string literals #1798/feat: dotted attribute and string subscript access in BQL #1800 set the precedent), so no entry.

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 -D warnings clean.

@robcohen
robcohen merged commit adb8581 into main Jul 17, 2026
47 checks passed
@robcohen
robcohen deleted the fix/price-sources-honor-date branch July 17, 2026 11:30
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.

[Bug]: Yahoo price source ignores --date and labels latest quote as historical

2 participants