Repository navigation
feat(price): --date as-of + harness source-resolution diff (refs #967) - #983
Conversation
84d9d44 to
de9c06e
Compare
Add boundary-date assertions for the as_of filter: - as_of exactly on buy date → buy applies, SHIB active - as_of exactly on sell date → both apply, SHIB inactive - as_of exactly on close date → close applies, DOGE inactive Pins down the inclusive `<=` comparison so a future change to `<` would break loudly with a focused test rather than only via integration. Also: comment on the harness's two-space skip-annotation strip noting it's coupled to dump_fetch_plan's exact output format. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Two follow-ups to PR #982 / issue #967. (item 4) --date as-of for the active-commodity filter ===================================================== Before this change, `rledger price -f file.beancount --date 2020-01-01` parsed the date and passed it to source requests, but the active filter that decides which commodities to include used the LATEST balances — so a commodity bought before 2020 and sold afterward was excluded from the historical fetch. Bean-price walks the file as-of `--date` for both balance computation and price lookup; this aligns rledger. Implementation: - discover_symbols and active_commodities now take Option<NaiveDate>. - Transactions with date > as_of are skipped from the balance roll-up. - Close directives after as_of are ignored (the account WAS open then). - price_cmd.rs parses args.date once, early, and threads it into discovery (was previously parsed only later for the source request). Tests: - as_of_filter_includes_holdings_at_that_date_only - as_of_ignores_close_directive_after_cutoff (harness extension) Source-resolution differential via --dry-run ================================================================ The compat harness (#978) previously compared only commodity discovery because rledger had no equivalent of `bean-price -n`. With #982's `rledger price -n` flag now landed, the harness can compare full (symbol, currency, source, ticker) resolution between the two binaries — covering source precedence (audit item 5), per-spec ticker preservation (#970), and fallback chains (#963/#970). Adds two new tests: - rledger_and_bean_price_resolve_same_attempts_basic - rledger_and_bean_price_resolve_same_attempts_mixed_currencies Both pass against the existing FIXTURE_BASIC and FIXTURE_MIXED_CURRENCIES fixtures. Docs: - Drop the --date row from the "Differences from bean-price" table — it's no longer a divergence. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Add boundary-date assertions for the as_of filter: - as_of exactly on buy date → buy applies, SHIB active - as_of exactly on sell date → both apply, SHIB inactive - as_of exactly on close date → close applies, DOGE inactive Pins down the inclusive `<=` comparison so a future change to `<` would break loudly with a focused test rather than only via integration. Also: comment on the harness's two-space skip-annotation strip noting it's coupled to dump_fetch_plan's exact output format. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
de9c06e to
daa011f
Compare
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
📊 Benchmark Results
vs main branch (2026-05-03)
What do these numbers mean?
|
There was a problem hiding this comment.
Pull request overview
This stacked PR continues the bean-price compatibility work around rledger price: it threads --date into historical discovery, expands the compat harness toward dry-run/source-resolution comparisons, and includes supporting stacked changes for dry-run/clobber behavior and CSV zero-amount import handling.
Changes:
- Pass
--dateinto commodity discovery so the active filter can operate as-of the requested date. - Extend price-command docs and the bean-price compatibility harness for dry-run/source-resolution comparisons.
- Carry supporting stacked changes for
--dry-run,--clobber, and zero-amount CSV import configuration/tests.
Reviewed changes
Copilot reviewed 4 out of 4 changed files in this pull request and generated 3 comments.
Show a summary per file
| File | Description |
|---|---|
docs/commands/price.md |
Updates price command docs, examples, precedence notes, and bean-price differences. |
crates/rustledger/tests/bean_price_compat.rs |
Expands the compat harness from symbol discovery to dry-run source-resolution comparisons. |
crates/rustledger/src/cmd/price_cmd.rs |
Threads parsed dates into discovery and adds dry-run/clobber execution paths. |
crates/rustledger/src/cmd/price/discovery.rs |
Adds as-of support to active commodity discovery and related regression tests. |
crates/rustledger/src/cmd/extract_cmd/mod.rs |
Wires the zero-amount import flag through CLI/importer config assembly. |
crates/rustledger-importer/src/csv_importer.rs |
Makes zero-row skipping configurable and tightens debit/credit parse handling. |
crates/rustledger-importer/src/config.rs |
Adds skip_zero_amounts to CSV importer configuration and builder defaults. |
Comments suppressed due to low confidence (3)
docs/commands/price.md:357
- This paragraph is now stale:
bean_price_compat.rsincludes a second dry-run layer (assert_same_attempts) that does compare source resolution. Leaving the docs as "not yet covered" will mislead readers about the current state of the compat harness.
Commodity discovery is exercised against `bean-price` directly via the differential harness in `crates/rustledger/tests/bean_price_compat.rs` (asserts the `(symbol, quote_currency)` set matches). Source-resolution / fallback-chain behavior is not yet covered by the harness — it relies on code inspection plus the unit tests in `price_cmd.rs`. Known intentional divergences:
crates/rustledger/src/cmd/price_cmd.rs:335
- This
--clobbergate keys off the requested date (today/--date) instead of the date the source actually returns. Sources like ECB can legally return the last published business day for a "latest" request, so an existingpricedirective for that real quote date will be missed and a duplicate will still be emitted.
// Limitation: this checks the REQUESTED date (`--date` or today). Some
// sources return a different effective date for "latest" — ECB, for
// instance, returns the last published business day on weekends. An
// existing directive dated to the source's actual quote date will not
// be matched here, so a duplicate may still be emitted. Fixing this
// requires a post-fetch re-check; tracked as a follow-up.
if !args.clobber {
let fetch_date = date.unwrap_or_else(|| jiff::Zoned::now().date());
if existing_prices.contains(&(symbol.clone(), effective_currency.clone(), fetch_date)) {
crates/rustledger/src/cmd/price_cmd.rs:659
- The external-command path has the same
--clobberproblem as the network path: it only checks the requested date before executing the command. If the command returns a different effective date in JSON/beancount output, an existing directive for that returned date will not be recognized and you'll still append a duplicate price.
// --clobber: skip when an existing price for this (symbol, currency, date)
// is already in the file. Same rule as the network fetch path.
if !args.clobber {
let fetch_date = date.unwrap_or_else(|| jiff::Zoned::now().date());
if existing_prices.contains(&(symbol.clone(), effective_currency.clone(), fetch_date)) {
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
|
| 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
… attempts) (#984) * fix(price): address late Copilot review on PR #983 PR #983 merged before three Copilot inline comments were addressed. Following up here: 1. (discovery.rs) `as_of` was only applied to the active-balance walk; the Commodity directive walk was unfiltered, so a commodity declared after the cutoff with `price:` metadata still triggered discovery. Add the missing filter, matching beanprice's `find_currencies_declared`'s `entry.date >= date: break` rule (commodity declared ON OR AFTER cutoff is excluded). Verified against the actual upstream source. New test: as_of_filters_commodity_directives_before_walking_them. 2. (bean_price_compat.rs) The harness's resolve-attempts comparison used `BTreeSet`, which discarded fallback-chain order. A regression that swapped `[ecbrates(GBP-EUR), ecb(GBP)]` to `[ecb(GBP), ecbrates(GBP-EUR)]` would silently pass. Switch to `BTreeMap<(symbol, currency), Vec<(source, ticker)>>` — keys still sorted (deterministic comparison), value `Vec` preserves chain order so swaps fail the test. 3. (Copilot's third comment about adding fallback-chain fixtures) Investigated and documented as not currently feasible: bean-price parses `price:` as `<curr>:<src1>,<src2>,...` (one currency block with multiple sources), while rledger parses it as `<curr>:<src>/<ticker>,<curr>:<src>/<ticker>,...` (each entry repeats the currency, per #963/#970). The two formats are incompatible — bean-price errors on rledger's syntax with "Invalid source name". So the differential harness can't currently exercise rledger's fallback-chain behavior end-to-end. The `Vec`-valued data structure is still load-bearing: when both binaries can speak the same chain syntax (a follow-up to extend rledger's parser to also accept bean-price's form), the harness will catch order regressions for free. Documented this in a comment where the fixture would otherwise live. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * feat(price): unify price: parser to accept both rledger and bean-price syntaxes After my previous comment claimed the formats were incompatible, the maintainer pointed out that they could be unified. They were right. Disambiguation rule: a comma-separated source entry is in rledger's redundant per-entry form if and only if its part BEFORE the first `/` contains `:`. Otherwise it's bean-price's bare `<source>/<ticker>` form and inherits the surrounding currency block. Strategy: 1. Split on whitespace/`;` → currency blocks (bean-price multi-currency) 2. Each block: `<currency>:<sources_part>` 3. sources_part: comma-separated entries, each either: - `<source>/<ticker>` (inherits block currency), or - `<currency>:<source>/<ticker>` (rledger's redundant form, overrides block currency) Handles all of these natively without a mode flag: USD:yahoo/AAPL USD:yahoo/AAPL,google/AAPL (bean-price multi-source) USD:yahoo/AAPL,USD:google/AAPL (rledger redundant) EUR:ecbrates/GBP-EUR,ecb/GBP (bean-price chain) USD:yahoo/AAPL CAD:google/AAPL (bean-price multi-currency) USD:google/NASDAQ:AAPL (ticker contains ':') New parser tests cover each variant + the embedded-colon-in-ticker case. Harness fallback fixture restored — both binaries now parse the same chain syntax. Used yahoo/oanda for sources (both ship in beanprice's sources/). Pass `--inactive` on both invocations so the resolution test isn't gated on bean-price's discovery filter. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> * fix(price): self-review on PR #984 — cleaner parser, document multi-currency limitation Two findings from a re-read of #984: 1. parse_price_metadata's match arm did a redundant double-split: the first match captured `before_slash` from `entry.split_once('/')` then immediately threw away its second component and re-split `entry` to recover an `after_first_colon`. Replaced with a single split that produces all three values (currency, source, ticker) directly. Same behavior, less work, easier to read. 2. Multi-currency `price:` metadata (e.g. `USD:yahoo/AAPL CAD:google/AAPL`) parses correctly into 2 specs, but downstream `build_mapping` and `DiscoveredCommodity.quote_currency` only retain the first spec's currency — so today rledger fetches a multi-currency commodity in only one of its declared quotes. Bean-price emits one job per (base, quote). Pre-existing limitation surfaced by my parser change; documented inline near the relevant test, not fixed here. Tracked as a follow-up. Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]> --------- Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
Summary
Two follow-ups from issue #967's punch list. Stacked on top of #982 (the bean-price audit bundle).
Item 4 from #967:
--dateas-of for the active-commodity filterBefore this change,
rledger price -f file.beancount --date 2020-01-01parsed the date and passed it to source requests, but the active filter that decides which commodities to include used the latest balances. A commodity bought before 2020 and sold afterward was excluded from the historical fetch. Bean-price walks the file as-of--datefor both balance computation and price lookup; this aligns rledger.discover_symbolsandactive_commoditiesnow takeOption<NaiveDate>.date > as_ofare skipped from the balance roll-up.Closedirectives afteras_ofare ignored (the account WAS open then).price_cmd.rsparsesargs.dateonce, early, and threads it into discovery.New regression tests:
as_of_filter_includes_holdings_at_that_date_only,as_of_ignores_close_directive_after_cutoff.Harness extension: source-resolution differential
The compat harness (#978) previously compared only commodity discovery — there was no rledger equivalent of
bean-price -n. With--dry-runnow landed in #982, the harness can compare the full(symbol, currency, source, ticker)resolution between the two binaries.That covers what the discovery-only layer couldn't:
New tests:
rledger_and_bean_price_resolve_same_attempts_basic,rledger_and_bean_price_resolve_same_attempts_mixed_currencies. Both pass against the existing fixtures.Docs
Dropped the
--daterow from the "Differences frombean-price" table since it's no longer a divergence.Test plan
cargo test -p rustledger --lib(263 passing, +2 new)cargo test -p rustledger --test bean_price_compat(5 passing, +2 new)cargo clippy --all-features --all-targets -- -D warningscleancargo fmt --all -- --checkcleanStacking
Based on
feat/bean-price-audit-bundle(#982). When #982 merges, this rebases cleanly onto main.Refs #967.