Skip to content

feat(price): --date as-of + harness source-resolution diff (refs #967) - #983

Merged
robcohen merged 2 commits into
mainfrom
fix/price-date-asof-and-harness
May 3, 2026
Merged

robcohen merged 2 commits into
mainfrom
fix/price-date-asof-and-harness

Conversation

@robcohen

@robcohen robcohen commented May 3, 2026

Copy link
Copy Markdown
Member

Summary

Two follow-ups from issue #967's punch list. Stacked on top of #982 (the bean-price audit bundle).

Item 4 from #967: --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. 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.

  • 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.

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-run now 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 --date row from the "Differences from bean-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 warnings clean
  • cargo fmt --all -- --check clean
  • Pre-push hook ran the bean-price compat harness (passed)

Stacking

Based on feat/bean-price-audit-bundle (#982). When #982 merges, this rebases cleanly onto main.

Refs #967.

@robcohen
robcohen requested a review from a team as a code owner May 3, 2026 15:30
Base automatically changed from feat/bean-price-audit-bundle to main May 3, 2026 15:54
Copilot AI review requested due to automatic review settings May 3, 2026 15:57
@robcohen
robcohen force-pushed the fix/price-date-asof-and-harness branch from 84d9d44 to de9c06e Compare May 3, 2026 15:57
robcohen added a commit that referenced this pull request May 3, 2026
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]>
robcohen and others added 2 commits May 3, 2026 09:59
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]>
@robcohen
robcohen force-pushed the fix/price-date-asof-and-harness branch from de9c06e to daa011f Compare May 3, 2026 16:00
@robcohen
robcohen enabled auto-merge (squash) May 3, 2026 16:02
@codecov

codecov Bot commented May 3, 2026

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 94.62366% with 5 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger/src/cmd/price_cmd.rs 0.00% 5 Missing ⚠️

📢 Thoughts on this report? Let us know!

@github-actions

github-actions Bot commented May 3, 2026

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 31.8ms ± 0.4ms 21.5 MB
beancount 968ms ± 8.1ms 50.4 MB
Comparison 30.4x faster 2.3x less

vs main branch (2026-05-03)

Metric main this PR Change
Time 36.4ms 31.8ms -12.6% 🟢
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

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 --date into 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.rs includes 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 --clobber gate 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 existing price directive 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 --clobber problem 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.

@github-actions

github-actions Bot commented May 3, 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
robcohen merged commit de7427a into main May 3, 2026
49 checks passed
@robcohen
robcohen deleted the fix/price-date-asof-and-harness branch May 3, 2026 16:37
robcohen added a commit that referenced this pull request May 3, 2026
… 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]>
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.

2 participants