Repository navigation
feat: window-primitive price source architecture (#1802) - #1803
Conversation
Rearchitects the PriceSource trait per the #1802 proposal, grounded in a primary-source survey of beanprice, pricehist, Finance::Quote, and ccxt: - Sources now implement the date-free fetch_latest(&PricePair) and, when the provider has a history API, fetch_window(&PricePair, DateWindow) -> Vec<PricePoint> plus a historical_coverage() declaration (None / Since(date) / Full — capability as data, the ccxt/pricehist pattern, not beanprice's ambiguous None). - fetch_price becomes a PROVIDED trait method: the one canonical dispatch (identity pair -> coverage check -> cache-free window fetch with on-or-before selection -> latest fallback for today -> refusal). Sources return raw dated points and cannot mislabel a response: the #1794 invariant now lives in one function with one set of tests instead of ten guarded copies. The per-source reject_historical_date guards and ecb/ratesapi identity branches are deleted; a latest-only source's fetch signature cannot even express a requested date. - yahoo: parse_chart splits into parse_latest and parse_points (raw bars, exchange-timezone classified); selection moves to the dispatch. - coinbase and ratesapi gain real historical support (#1802 table rows 1-2): coinbase via spot?date=, ratesapi via the dated path (coverage Since 1999-01-04). Dated fetches on them now succeed instead of refusing. - external command source is the one sanctioned fetch_price override (trust contract unchanged, documented at both sites); it declares Full coverage since RLEDGER_DATE is forwarded. - guard_wiring_tests become capability_wiring_tests: latest-only builtins must declare None AND refuse hermetically; capable builtins' declarations are pinned. New dispatch_tests exercise refusal, today routing, window selection, empty-window error, Since refusal messaging, and no-fetch identity through mock sources. Follow-ups tracked in #1802: typed SourceError for the fallback chain, window write-through into the price cache, remaining source ports (ecb 90-day feed, quandl, tsp, eastmoneyfund, alphavantage). Co-Authored-By: Claude Fable 5 <[email protected]> Claude-Session: https://claude.ai/code/session_013gJH7uBBF9Xw9et9QFRcsU
Codecov Report❌ Patch coverage is 📢 Thoughts on this report? Let us know! |
📊 Benchmark Results
vs main branch (2026-07-18)
What do these numbers mean?
|
There was a problem hiding this comment.
Pull request overview
This PR rearchitects the rledger price source system around a single canonical date-dispatch path (PriceSource::fetch_price), moving sources to a date-free “latest” primitive plus an optional historical “window” primitive. This aims to make historical-date labeling bugs structurally impossible by centralizing all date semantics (identity pairs, coverage checks, on-or-before selection, response labeling) in one place.
Changes:
- Introduces
PricePair,PricePoint,DateWindow, andHistoricalCoverage, and rewritesPriceSourceintofetch_latest+ optionalfetch_windowwith a provided canonicalfetch_pricedispatcher. - Upgrades
coinbaseandratesapito provide real historical quotes via the window primitive; refactorsyahooto return raw dated points and rely on the dispatcher for selection/labeling. - Updates remaining built-in sources to the new
fetch_latestAPI shape and adjusts/expands tests to validate dispatch behavior and capability declarations.
Reviewed changes
Copilot reviewed 14 out of 14 changed files in this pull request and generated 2 comments.
Show a summary per file
| File | Description |
|---|---|
| docs/commands/price.md | Updates CLI documentation to reflect new historical-capable sources and latest-only behavior. |
| crates/rustledger/src/cmd/price/external.rs | Adapts external command source to the new trait while intentionally retaining its fetch_price override (trust contract). |
| crates/rustledger/src/cmd/price/sources/mod.rs | Core redesign: new types, HistoricalCoverage, canonical dispatch logic, and new dispatch/capability tests. |
| crates/rustledger/src/cmd/price/sources/yahoo.rs | Splits parsing into latest vs. raw historical points; implements fetch_latest/fetch_window and moves selection/labeling to dispatch. |
| crates/rustledger/src/cmd/price/sources/coinbase.rs | Adds dated spot support via window primitive; implements declared historical coverage. |
| crates/rustledger/src/cmd/price/sources/ratesapi.rs | Adds dated endpoint support and Since(1999-01-04) historical coverage; implements window primitive via single dated request. |
| crates/rustledger/src/cmd/price/sources/ecb.rs | Moves to fetch_latest; relies on canonical dispatch for identity/dates. |
| crates/rustledger/src/cmd/price/sources/alphavantage.rs | Moves to fetch_latest and removes per-source date guarding in favor of dispatch. |
| crates/rustledger/src/cmd/price/sources/coincap.rs | Moves to fetch_latest and removes per-source date guarding in favor of dispatch. |
| crates/rustledger/src/cmd/price/sources/coinmarketcap.rs | Moves to fetch_latest and removes per-source date guarding in favor of dispatch. |
| crates/rustledger/src/cmd/price/sources/eastmoneyfund.rs | Moves to fetch_latest and removes per-source date guarding in favor of dispatch. |
| crates/rustledger/src/cmd/price/sources/oanda.rs | Moves to fetch_latest and removes per-source date guarding in favor of dispatch. |
| crates/rustledger/src/cmd/price/sources/quandl.rs | Moves to fetch_latest and removes per-source date guarding in favor of dispatch. |
| crates/rustledger/src/cmd/price/sources/tsp.rs | Moves to fetch_latest and removes per-source date guarding in favor of dispatch. |
💡 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 |
- refuse FUTURE dates on every source before coverage routing - latch the midnight-straddle day on any dated fetch - clamp straddle-accepted latest labels to the requested day - clamp Since-coverage windows to the declared epoch - ratesapi dated fallback and weekend label clamp - coinbase/ratesapi today-parity delegation to latest - identity currency uppercased - yahoo exchange timezone resolved once per response
|
Round-1 deep review (27 agents, adversarial verification): 10 findings (8 confirmed, 2 plausible), all fixed in 1ab1190. The refactor's canonical dispatch had dropped several guarantees main's per-source guards provided:
Also addressed from Copilot's review (7db71d4): the refusal message no longer calls a 617 tests green, clippy/ |
- scope the straddle label clamp to CURRENT-day (local-clock) labels only, via a pure clamp_local_label: genuine ahead-of-clock feed labels (eastmoneyfund China civil day) pass through untouched - bound the midnight straddle by elapsed time since the first dated fetch (6h) so a day-old latch from a covered fetch cannot reopen yesterday in long-lived processes; latch moved before the identity arm so all-identity prefixes still latch - canonical same_day_latest_point helper replaces the two drifting window.end==today delegations; the point date is clamped to the window end so a midnight race cannot yield a spurious no-quote error; ratesapi applies eu_reference_label to the delegated label too - coinbase coverage is Since(2015-01-01), not Full: pre-exchange dates get the clean capability refusal instead of raw provider errors - price_cmd self-referential skips are case-insensitive, matching the dispatch identity arm (a -c usd run emitted price USD 1 USD) - eu_reference_label documents the weekend-blend trade-off; the capability test comment no longer claims unwired introspection callers exist
|
Round-2 deep review (18 agents, targeted at the round-1 fixes): 10 findings (8 confirmed, 2 plausible), addressed in 3b19303. The round-1 fixes had the classic follow-on regressions:
618 tests green, clippy/doc clean. |
Round-3 deep review showed every straddle mechanism (label clamps, process-wide latches, elapsed-time bounds) trades one #1794-class mislabel for another: the scoped clamp reopened the midnight race AND rewrote genuine feed-ahead labels during the straddle; the latch missed external sources; the 6h bound broke long rate-limited batches; and a straddle-accepted live quote could be frozen in the cache as a settled close. The straddle only ever existed as a workaround for missing historical support - which this PR adds - so it is deleted wholesale: - dispatch: future refuses, TODAY routes to fetch_latest uniformly on every source (the honest answer for a day in progress, labeled with the quote own date), covered PAST dates take the window path, and a completed day on a latest-only source refuses honestly - deleted: FIRST_DATED_FETCH, STRADDLE_MAX_SECS, latest_date_window_ok, clamp_local_label, same_day_latest_point, and the coinbase/ratesapi same-day delegations (window.end is now always a completed day) - price_cmd: dedup_key normalizes currency case at the existing_prices build site and all six lookup sites; the dry-run self-pair guard is case-insensitive like the fetch loop - Since refusal message no longer suggests yahoo (asset-specific); docs note coinbase 2015-01-01 epoch
|
Round-3 deep review (20 agents, targeted at the round-2 fixes): 9 confirmed findings — and they forced a design decision rather than another patch. Addressed in e4d41a7. Three of the findings showed the midnight-straddle machinery is unfixable by refinement: the scoped label clamp simultaneously reopened the midnight race (a stale dispatch clock means a Resolution: the straddle is deleted wholesale. It only ever existed (in #1801) as a workaround for missing historical support — which this PR adds. The dispatch is now:
A batch crossing midnight keeps working on every window-capable source through the dated path; latest-only sources refuse the completed day honestly, and the refusal names the alternative. Deleted: The remaining findings: 617 tests green, clippy/doc clean. |
- oanda: label the daily candle with its own RFC3339 time field, not the local fetch day (a Saturday fetch recorded Friday close under Saturday - the #1794 class, pre-existing but newly load-bearing) - yahoo: parse_latest refuses a response with no regularMarketTime instead of guessing local today (newly reachable via --date today) - coinbase/coincap/coinmarketcap: clock-labeled latest quotes read the clock BEFORE network I/O, and price_cmd never caches a response dated after its key date - together closing the midnight-race path that could freeze a D+1-labeled spot as day D settled cache entry - dispatch window arm uppercases the fallback currency like the identity arm; dedup_key uppercases the symbol too; cache_key normalizes its currency segment with paired cross-references - ratesapi: the weekend label clamp applies to fetch_latest as well as the window path - stale straddle-era comments removed; arm-6 comment no longer contradicts the None-arm message; dispatch tests carry an explicit note on the accepted midnight-flake window
|
Round-4 deep review (18 agents, verifying the round-3 straddle deletion): 10 findings, all addressed in d1b7035. The deletion itself held up — no finding asked for the straddle back — but it made two dormant #1794-class labeling bugs load-bearing and left case/race residue:
617 tests green, clippy/doc clean. Round summary across the PR: 10 → 10 → 9 (resolved by deleting the mechanism) → 10 (two pre-existing bugs surfaced + residue). The dispatch itself is now small enough that rounds are finding per-source labeling debt rather than architecture problems. |
- oanda: candle_trading_day converts the candle OPEN time to the 17:00 America/New_York session boundary and rolls forward - the raw time field dated every quote one trading day early (Friday close emitted under Thursday); fallback clock read hoisted pre-fetch - coincap/coinmarketcap: the round-4 pre-fetch clock hoist had moved only the comment; the reads now actually execute before network I/O - dispatch arms 2 and 4 uppercase the response currency on the way out, closing the last lowercase-commodity emission paths; coinbase fetch_spot returns Option currency so a feed omission no longer shadows the canonical fallback with the raw request value - write_price uppercases the emitted symbol in beancount mode (rledger price aapl -b wrote an unparsable lowercase commodity) - external: fetch_latest and fetch_price both delegate to an inherent run_command, removing the mutual-recursion shape that only terminated because the override existed - yahoo regularMarketTime refusal kept as deliberate (documented): a visible error beats a silently mislabeled directive
|
Round-5 deep review (21 agents, convergence check on the round-4 fixes): 8 findings, addressed in 91ea906.
618 tests green, clippy/doc clean. Deliberate behavioral deltas vs main, for the record: uniform today→latest routing (including yahoo), no midnight-straddle acceptance (window-capable sources carry dated batches across midnight instead), future dates refused everywhere, coinbase/ratesapi historical support with declared epochs, refusal messages naming coverage, and identity/emission case normalization. |
What
Rearchitects
PriceSourcearound the design proposed in #1802 (grounded in a primary-source survey of beanprice, pricehist, Finance::Quote, and ccxt — see the issue comment for the evidence):reject_historical_dateguards and the ecb/ratesapi identity branches are deleted; a latest-only source's fetch signature (PricePair, no date field) cannot even express a requested date.None/Since(date)/Full), validated before any network I/O — the ccxthas-dictionary / pricehisttypes()+start()pattern, replacing beanprice's ambiguous-Nonesignaling that its own author documents as a flaw.coinbase(spot?date=) andratesapi(dated path, coverage since 1999-01-04) now serve real historical quotes where they previously refused.yahoo's selection logic moves out ofparse_chartinto the dispatch; its parsers return raw exchange-timezone-classified bars.--source-cmdkeeps its documented trust contract as the one sanctionedfetch_priceoverride.Behavior changes
rledger price --date <past> -s coinbase|ratesapinow succeeds (was: refusal).dispatch_testswith mock sources;capability_wiring_testsasserting declarations match hermetic refusal behavior; yahoo fixtures asserting raw-point parsing + canonical selection).Follow-ups (tracked in #1802)
Typed
SourceErrorfor fallback chains, window write-through into the price cache, and the remaining source ports (ecb 90-day feed, quandl, tsp, eastmoneyfund, alphavantage).Part of #1802.
🤖 Generated with Claude Code
https://claude.ai/code/session_013gJH7uBBF9Xw9et9QFRcsU