Skip to content

feat(price): bean-price audit bundle (refs #967, #972 follow-up) - #982

Merged
robcohen merged 4 commits into
mainfrom
feat/bean-price-audit-bundle
May 3, 2026
Merged

robcohen merged 4 commits into
mainfrom
feat/bean-price-audit-bundle

Conversation

@robcohen

@robcohen robcohen commented May 3, 2026

Copy link
Copy Markdown
Member

Summary

Bundles the cheap items from issue #967's bean-price compatibility audit plus the #972 zero-skip follow-up the original reporter expected. New behavior is opt-in or follows back-compat defaults; nothing existing changes shape.

Refs #967, addresses #972 follow-up.

What's in this PR

--dry-run / -n on rledger price (audit item 1)

Print the resolved fetch plan and exit; no network. Matches bean-price --dry-run.

$ rledger price -f ledger.beancount -n
AAPL /USD @ today yahoo(AAPL)
GBP  /EUR @ today ecbrates(GBP-EUR), ecb(GBP)
SAP  /EUR @ today yahoo(SAP.DE)

Honors --source / --source-cmd bypasses, walks fallback chains, preserves per-source tickers from #963/#970, picks up --date.

--clobber / -C on rledger price (audit item 2)

Skip fetching when the input file already has a price directive for (symbol, quote_currency, date). Default behavior matches bean-price (skip existing). --clobber re-fetches.

$ rledger price -f ledger.beancount -b -v
AAPL: skipped (existing price for 2026-05-03 USD; pass --clobber to refetch)
2026-05-03 price MSFT 1.00 USD
$ rledger price -f ledger.beancount -b --clobber
2026-05-03 price AAPL 1.00 USD
2026-05-03 price MSFT 1.00 USD

--include-zero-amounts on rledger extract (#972 follow-up)

The original reporter expected zero-amount rows to be preserved when migrating from GnuCash. The default still drops them (back-compat); the new flag flips it for one run.

$ rledger extract /path/to/bug.csv --auto --include-zero-amounts

API: CsvConfigBuilder::skip_zero_amounts(false).

Documentation (audit items 3, 4, 5, 6)

docs/commands/price.md:

Test plan

  • cargo test -p rustledger --lib (255 passing)
  • cargo test -p rustledger-importer (130+ passing, including new test_csv_import_zero_amount_preserved_when_opted_in)
  • cargo clippy --all-features --all-targets -- -D warnings clean
  • cargo fmt --all -- --check clean
  • Bean-price compat harness passes (pre-push hook ran it)
  • Manual rledger price -f X -n against a fixture with USD, EUR, and a fallback chain — output correct
  • Manual rledger price -f X --clobber and without — skip vs refetch behavior verified
  • Manual rledger extract /tmp/bug.csv --auto --include-zero-amounts — preserves the 0.00 row that bug.csv (issue [Bug]: extract fails to parse amounts of $0.00 #972 reproduction) emits

What's NOT in this PR (per #967 audit)

Bundles the cheap items from #967's bean-price compatibility audit plus
the #972 zero-skip follow-up. New behavior is opt-in or follows
back-compat defaults; nothing existing changes shape.

#967 deliverables:

- Item 5 (precedence re-doc): refresh `docs/commands/price.md`'s
  source-selection precedence to match the post-#970/#971 code. Promote
  `--source` and `--source-cmd` to the top as full bypasses, add the
  `Simple(symbol)` synthesis rung for `quote_currency:`-only and
  `--undeclared` discovery, point at #966's strict default.

- Item 6 (logging format decision): documented as an intentional
  divergence in a new "Differences from bean-price" table, alongside
  items 3 (cache) and 4 (--date) which are documented divergences
  rather than fixes.

- Item 1 (--dry-run / -n): print the resolved
  `(symbol, /currency, @ date, source(ticker)[, source(ticker)…])`
  plan and exit without any network. Matches `bean-price --dry-run`.
  Honors --source / --source-cmd bypasses; walks fallback chains
  (preserves per-source tickers from #963/#970).

- Item 2 (--clobber / -C): skip fetching when a `price` directive
  already exists in the input file for `(symbol, currency, date)`.
  Default behavior matches `bean-price` (skip); `--clobber` re-fetches.

- Items 3, 4: investigations documented as known divergences (cache
  granularity, --date semantics for active filter). Code-level
  alignment is a separate effort.

#972 follow-up:

- New `CsvConfig.skip_zero_amounts` (default true, back-compat) and
  `CsvConfigBuilder::skip_zero_amounts(bool)`. The reporter expected
  zero-amount rows to be preserved when migrating from GnuCash.

- New CLI flag `rledger extract --include-zero-amounts` flips the
  default for that one run, applies to both --auto and explicit-config
  paths.

Tests:

- New `test_csv_import_zero_amount_preserved_when_opted_in`.
- All existing tests still pass; the original `_skips_row` test still
  asserts the back-compat default.

Verified end-to-end against fixtures: --dry-run dumps the plan
correctly with -s override, with -d, and with fallback chains;
--clobber skips/refetches as expected based on existing price
directives; --include-zero-amounts preserves a 0.00 row.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Copilot AI review requested due to automatic review settings May 3, 2026 14:58
@robcohen
robcohen requested a review from a team as a code owner May 3, 2026 14:58
@codecov

codecov Bot commented May 3, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 55.68627% with 113 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger/src/cmd/price_cmd.rs 43.95% 102 Missing ⚠️
crates/rustledger/src/cmd/extract_cmd/mod.rs 27.27% 8 Missing ⚠️
crates/rustledger-importer/src/csv_importer.rs 94.73% 3 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 32.9ms ± 3ms 22 MB
beancount 933.1ms ± 10.6ms 50.2 MB
Comparison 28.4x faster 2.3x less

vs main branch (2026-05-03)

Metric main this PR Change
Time 36.4ms 32.9ms -9.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

Three issues from a deep re-read:

1. dry-run dump said `default(SYMBOL)` for Simple mappings rather than
   the actual configured default source name (e.g. `yahoo`). Defeats the
   purpose of --dry-run, which is to show what will run. describe_attempts
   now takes a default_source parameter and uses it.

2. --dry-run ignored --clobber: the printed plan included symbols that a
   real run would skip due to existing price directives. The plan now
   takes existing_prices into account and annotates skipped symbols with
   `[skip: existing price]`. With --clobber the annotation is suppressed.

3. No unit tests for the new flag plumbing. Added:
   - describe_attempts_simple_mapping_uses_configured_default
   - describe_attempts_walks_fallback_chain_with_per_source_tickers
   - describe_attempts_unmapped_returns_empty
   - test_price_args_clobber_flag (--clobber and short -C)
   - test_price_args_clobber_requires_file (rejects --clobber without -f)
   - test_price_args_dry_run_flag (--dry-run and short -n)

Also: cleaned up the source-cmd dump label from `source-cmd:<full cmd>(...)`
to a fixed `source-cmd(...)` since the full command can contain spaces and
parens that mangle the output.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>

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 PR continues the bean-price compatibility work in rledger price while also addressing the CSV zero-amount extraction follow-up from #972. It adds new CLI behavior for price planning/refetch control, exposes an importer-level zero-row toggle for migration workflows, and updates the price command documentation to explain the new behavior and known divergences.

Changes:

  • Add --dry-run and --clobber support to rledger price, including fetch-plan rendering and existing-price detection.
  • Add --include-zero-amounts to rledger extract and CsvConfigBuilder::skip_zero_amounts(false) to preserve zero-value CSV rows when requested.
  • Refresh docs/commands/price.md with updated precedence rules, new option docs/examples, and a divergences table.

Reviewed changes

Copilot reviewed 5 out of 5 changed files in this pull request and generated 9 comments.

Show a summary per file
File Description
docs/commands/price.md Documents new price flags, precedence behavior, examples, and bean-price differences.
crates/rustledger/src/cmd/price_cmd.rs Implements dry-run output, existing-price skip/clobber logic, and supporting fetch-plan helpers.
crates/rustledger/src/cmd/extract_cmd/mod.rs Adds the extract CLI flag for preserving zero-amount rows and wires it into some CSV config paths.
crates/rustledger-importer/src/csv_importer.rs Makes zero-row skipping configurable during CSV row parsing and adds a regression test.
crates/rustledger-importer/src/config.rs Adds skip_zero_amounts to CSV importer configuration defaults and builder API.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread docs/commands/price.md Resolved
Comment thread crates/rustledger/src/cmd/price_cmd.rs Resolved
Comment thread crates/rustledger/src/cmd/price_cmd.rs Resolved
Comment thread docs/commands/price.md Resolved
Comment thread crates/rustledger/src/cmd/price_cmd.rs Resolved
Comment thread crates/rustledger/src/cmd/price_cmd.rs Resolved
Comment thread crates/rustledger/src/cmd/price_cmd.rs Resolved
@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 and others added 2 commits May 3, 2026 09:45
Seven of nine inline comments addressed; the other two were already fixed
in the earlier self-review (commit 52538e0):

- (price.md L115) `--mapping <SYMBOL>:<TICKER>[:<SOURCE>]` doc was wrong:
  the parser only does a single split_once(':'). Documented the limitation
  in the precedence section.

- (price.md L357) Toned down the "Most behavior matches Python bean-price
  1:1 (verified via the differential test harness)" claim. The harness
  covers commodity discovery; source resolution / fallback chains are
  exercised via unit tests in price_cmd.rs, not the harness.

- (extract_cmd/mod.rs L139) `--include-zero-amounts` was only wired into
  the --auto and raw CLI paths; --importer / --config builds went through
  build_config_from_entry which kept skip_zero_amounts=true. Apply the
  flag uniformly with a post-build override.

- (csv_importer.rs L211) parse_amount returned Ok(0) when both debit and
  credit columns failed to parse non-blank input. With --include-zero-
  amounts that turned malformed rows into real 0.00 transactions instead
  of surfacing a warning. Now distinguishes blank cells (normal) from
  parse failures (now Err with a clear message).

- (price_cmd.rs L545) Dry-run reported `<unmapped>` for CLI-only symbols
  even when [price] use_default_source = true would route them to the
  default source at runtime. dump_fetch_plan now takes use_default_source
  and synthesizes default_source(symbol) when it's set.

- (price_cmd.rs L322) Documented the `--clobber` date-mismatch limitation
  inline: the existing-prices check uses the requested date; some sources
  return a different effective date for "latest" (ECB on weekends), so
  duplicates may still be emitted. Tracked as a follow-up.

- (price_cmd.rs L632) Same date-mismatch concern in run_with_external_command
  — same root cause, same documented limitation.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
… PR #982)

Tightening the fix from 918c6d0. The earlier `any_parse_failure && amount
== ZERO` guard still let through a malformed-debit + valid-credit case as
+credit alone, silently masking the error. Now bail on any non-blank
parse failure regardless of the running total.

Added test_csv_import_malformed_debit_or_credit_warns covering both:
- Bad debit + valid credit → row rejected with parse warning
- Both cells blank → no warning, row skipped (back-compat)

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@robcohen
robcohen enabled auto-merge (squash) May 3, 2026 15:49
@robcohen
robcohen merged commit 0baaa90 into main May 3, 2026
30 checks passed
@robcohen
robcohen deleted the feat/bean-price-audit-bundle branch May 3, 2026 15:54
robcohen added a commit that referenced this pull request May 3, 2026
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]>
robcohen added a commit that referenced this pull request May 3, 2026
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]>
robcohen added a commit that referenced this pull request May 3, 2026
#983)

* feat(price): --date as-of for active filter + extend compat harness

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]>

* test(price): self-review on PR #983 — boundary date assertions

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]>

---------

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