Skip to content

fix(price): preserve per-spec tickers in fallback chains (closes #963) - #970

Merged
robcohen merged 4 commits into
mainfrom
fix/price-fallback-per-spec-ticker
May 2, 2026
Merged

robcohen merged 4 commits into
mainfrom
fix/price-fallback-per-spec-ticker

Conversation

@robcohen

@robcohen robcohen commented May 2, 2026

Copy link
Copy Markdown
Member

Summary

Issue #963 reports that
```beancount
1970-01-01 commodity GBP
price: "EUR:ecbrates/GBP-EUR,EUR:ecb/GBP"
```
fails with:
```
Error fetching GBP: Failed to fetch ECB rate for GBP-EUR; note: unknown sources skipped: ecbrates
```

Root cause: the discovery layer (PR #951) built a fallback chain that collapsed every source onto the FIRST spec's ticker. Once `ecbrates` was skipped (it's not a built-in source), `ecb` got queried with ticker `GBP-EUR` instead of `GBP` — ECB rejected the bogus ticker shape.

This fix preserves per-spec tickers all the way through the pipeline.

Changes

  • New `FallbackEntry` enum (`config.rs`). Either a bare source name (inherits parent ticker) or `{source = "...", ticker = "..."}`. `#[serde(untagged)]` keeps the legacy `source = ["a", "b"]` config form parsing unchanged, and lets you mix both shapes in the same list.
  • `SourceRef::Fallback(Vec)` → `SourceRef::Fallback(Vec)`. `discovery.rs::build_mapping` now emits `FallbackEntry::Detailed` per spec, carrying that spec's ticker.
  • `PriceSourceRegistry::resolve_mapping` returns `Vec<(String, String)>` — (source, ticker) pairs — instead of `(Vec, String)`. `fetch_price` iterates pairs so each fallback attempt uses its own source's ticker.

Tests

New regression tests:

  • `config::tests::test_parse_commodity_mapping_fallback_with_per_source_tickers`
  • `config::tests::test_parse_commodity_mapping_fallback_mixed_entry_shapes`
  • `cmd::price::tests::test_resolve_mapping_fallback_uses_per_source_tickers` (the [Bug]: price download fallbacks ignored #963 regression)
  • `cmd::price::tests::test_resolve_mapping_fallback_mixed_entries_inherit_parent_ticker`

Existing `test_resolve_mapping_*` tests updated for the new return type. 237 rustledger lib tests pass.

Bean-price compat note

The reporter's follow-up comment on #963 confirmed bean-price treats the comma-syntax as invalid; chained `price:` is a deliberate rustledger extension. PR #965 already documented the broader `--undeclared` divergence; #967 tracks the audit. This PR makes the extension actually work as advertised when sources expect different ticker shapes.

Test plan

  • `cargo test -p rustledger --lib` (237 passed)
  • `cargo clippy -p rustledger --all-features -- -D warnings`
  • `cargo fmt --all -- --check`
  • CI green

Closes #963.

🤖 Generated with Claude Code

Issue #963 reports that
`price: "EUR:ecbrates/GBP-EUR,EUR:ecb/GBP"` fails:

```
Error fetching GBP: Failed to fetch ECB rate for GBP-EUR; \
note: unknown sources skipped: ecbrates
```

Root cause: the discovery layer (PR #951) collapsed every source in a
fallback chain onto the FIRST spec's ticker. So once `ecbrates` got
skipped (we don't ship that source), `ecb` was queried with ticker
`GBP-EUR` instead of `GBP`. ECB rejected the bogus ticker shape.

The fix preserves per-spec tickers all the way through the pipeline.

## Changes

- New `FallbackEntry` enum in `crates/rustledger/src/config.rs`. Either
  a bare source name (inherits parent ticker) or
  `{source = "...", ticker = "..."}`. `#[serde(untagged)]` so both
  shapes coexist in the same `source = [...]` list, and the legacy
  `source = ["a", "b"]` config form still parses unchanged.
- `SourceRef::Fallback(Vec<String>)` -> `SourceRef::Fallback(Vec<FallbackEntry>)`.
  The metadata-driven path in `discovery.rs::build_mapping` now emits
  `FallbackEntry::Detailed` per spec, carrying that spec's ticker.
- `PriceSourceRegistry::resolve_mapping` returns `Vec<(String, String)>`
  -- (source, ticker) pairs -- instead of `(Vec<String>, String)`.
  `fetch_price` iterates pairs so each fallback attempt uses its
  source's own ticker.

## Tests

New regression tests:

- `config::tests::test_parse_commodity_mapping_fallback_with_per_source_tickers`
  -- toml schema accepts the object form.
- `config::tests::test_parse_commodity_mapping_fallback_mixed_entry_shapes`
  -- mixed bare-string and object entries in the same list.
- `cmd::price::tests::test_resolve_mapping_fallback_uses_per_source_tickers`
  -- the #963 regression: each fallback source gets its own ticker.
- `cmd::price::tests::test_resolve_mapping_fallback_mixed_entries_inherit_parent_ticker`
  -- bare-name entries inherit the parent ticker correctly.

Existing `test_resolve_mapping_*` tests updated for the new return
type. 237 rustledger tests pass.

## Note on bean-price compat

The reporter's follow-up comment on #963 confirmed bean-price treats
the comma-syntax `"a,b"` as invalid; chained `price:` is a deliberate
rustledger extension. PR #965 already documented the broader
`--undeclared` divergence and #967 tracks the audit. This PR just
makes the extension actually work as advertised when the user mixes
sources with different ticker shapes.

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

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 price-source fallback chains so each fallback entry uses its own ticker (instead of incorrectly reusing the first entry’s ticker), addressing issue #963 in the metadata-driven price discovery/execution pipeline.

Changes:

  • Introduces FallbackEntry to represent fallback chains with either bare source names or {source, ticker} entries.
  • Updates discovery mapping generation to preserve per-spec tickers in fallback chains.
  • Updates mapping resolution/execution to iterate (source, ticker) attempts and adds regression tests/docs.

Reviewed changes

Copilot reviewed 4 out of 4 changed files in this pull request and generated 1 comment.

File Description
docs/commands/price.md Documents per-spec tickers in fallback chains and adds config example for per-source tickers.
crates/rustledger/src/config.rs Adds FallbackEntry and updates SourceRef::Fallback to support per-entry tickers; adds parsing tests.
crates/rustledger/src/cmd/price/mod.rs Resolves mappings into ordered (source, ticker) attempts and uses them during fetch; adds regression tests.
crates/rustledger/src/cmd/price/discovery.rs Builds fallback mappings that preserve each spec’s ticker (fix for #963).

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

Comment thread crates/rustledger/src/config.rs Resolved
@codecov

codecov Bot commented May 2, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 86.36364% with 21 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger/src/cmd/price/discovery.rs 0.00% 14 Missing ⚠️
crates/rustledger/src/config.rs 93.65% 4 Missing ⚠️
crates/rustledger/src/cmd/price/mod.rs 96.10% 3 Missing ⚠️

📢 Thoughts on this report? Let us know!

@github-actions

github-actions Bot commented May 2, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 33.1ms ± 0.4ms 21.5 MB
beancount 816.3ms ± 10.5ms 50.3 MB
Comparison 24.7x faster 2.3x less

vs main branch (2026-05-01)

Metric main this PR Change
Time 32.8ms 33.1ms +0.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

@github-actions

github-actions Bot commented May 2, 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

…oc_markdown

CI runs `cargo clippy --all-features --all-targets -- -D warnings` —
my local check used `-p rustledger` which didn't surface this. Same
test name in CI's lint pass was the only diff vs main.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
robcohen added a commit that referenced this pull request May 2, 2026
…dispatch (closes #966)

Issue #966: `rledger price BAM` was sending the symbol to Yahoo (the
default source) and returning a stock price for an unrelated ticker
that happened to share the symbol. The discovery-side fix in #965
addressed the `-f` flow but explicit fetches still produced silent
bad data.

Per the reporter's follow-up, this PR makes the default behavior
**refuse** to fetch when no explicit source declaration exists,
covering all three paths the user has to opt in:

- CLI `--source <name>`
- A `[price.mapping.X]` block in config
- A `price:` metadata annotation on the commodity directive

If none of those are set, `resolve_mapping` returns an error whose
message lists exactly those three remediation paths plus the new opt-in
flag.

## Changes

- New `PriceConfig.use_default_source: Option<bool>` (defaults to false)
  with helper `effective_use_default_source()`.
- `PriceSourceRegistry` now captures the flag at construction.
- `resolve_mapping` returns `Result<Vec<(String, String)>>`. When the
  commodity has no mapping AND the flag is false, returns an error
  with the directive remediation message.
- `fetch_price` propagates the error.

The CLI `--source` flag bypasses `resolve_mapping` entirely
(it uses `fetch_with_source`), so users who just want a quick fetch
still have a one-flag escape hatch: `rledger price --source yahoo BAM`.

## Tests

- `test_resolve_mapping_no_mapping_errors_by_default` -- the #966
  regression, asserting the error message names the symbol and all
  four remediation paths (`--source`, config block, metadata, opt-in
  flag).
- `test_resolve_mapping_no_mapping_uses_default_when_opted_in` --
  setting `use_default_source = true` restores the previous behavior.
- All existing `test_resolve_mapping_*` tests updated for the new
  Result signature. 238 rustledger lib tests pass.

## Note

Built on top of #970 (per-spec tickers in fallback chains). After
#970 merges this PR rebases trivially onto main.

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

Copilot review on PR #970 caught that the inline `Detailed` variant of
`FallbackEntry` was missing `#[serde(deny_unknown_fields)]`. A typo
like `{ source = "ecb", tickre = "GBP" }` would silently deserialize
as `Detailed { source = "ecb", ticker = None }` and then fall back to
the parent ticker — exactly the silent-misconfig failure mode #952
fixed for `DetailedMapping`.

Fix: extract the variant into a named `FallbackDetail` struct with
`#[serde(deny_unknown_fields)]`. Update call sites in
`discovery.rs::build_mapping` and the test code.

New test `test_parse_commodity_mapping_fallback_rejects_unknown_field_in_entry`
asserts that a typo causes a load error. Caveat in the test docs:
`SourceRef`/`CommodityMapping` are `serde(untagged)` so the inner
"unknown field `tickre`" gets wrapped into the generic
"data did not match any variant" by the time the caller sees it; the
test only asserts load failure, which is what matters.

238 lib tests pass; clippy --all-features --all-targets clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
robcohen added a commit that referenced this pull request May 2, 2026
…dispatch (closes #966)

Issue #966: `rledger price BAM` was sending the symbol to Yahoo (the
default source) and returning a stock price for an unrelated ticker
that happened to share the symbol. The discovery-side fix in #965
addressed the `-f` flow but explicit fetches still produced silent
bad data.

Per the reporter's follow-up, this PR makes the default behavior
**refuse** to fetch when no explicit source declaration exists,
covering all three paths the user has to opt in:

- CLI `--source <name>`
- A `[price.mapping.X]` block in config
- A `price:` metadata annotation on the commodity directive

If none of those are set, `resolve_mapping` returns an error whose
message lists exactly those three remediation paths plus the new opt-in
flag.

## Changes

- New `PriceConfig.use_default_source: Option<bool>` (defaults to false)
  with helper `effective_use_default_source()`.
- `PriceSourceRegistry` now captures the flag at construction.
- `resolve_mapping` returns `Result<Vec<(String, String)>>`. When the
  commodity has no mapping AND the flag is false, returns an error
  with the directive remediation message.
- `fetch_price` propagates the error.

The CLI `--source` flag bypasses `resolve_mapping` entirely
(it uses `fetch_with_source`), so users who just want a quick fetch
still have a one-flag escape hatch: `rledger price --source yahoo BAM`.

## Tests

- `test_resolve_mapping_no_mapping_errors_by_default` -- the #966
  regression, asserting the error message names the symbol and all
  four remediation paths (`--source`, config block, metadata, opt-in
  flag).
- `test_resolve_mapping_no_mapping_uses_default_when_opted_in` --
  setting `use_default_source = true` restores the previous behavior.
- All existing `test_resolve_mapping_*` tests updated for the new
  Result signature. 238 rustledger lib tests pass.

## Note

Built on top of #970 (per-spec tickers in fallback chains). After
#970 merges this PR rebases trivially onto main.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@robcohen
robcohen enabled auto-merge (squash) May 2, 2026 01:02
@robcohen
robcohen merged commit 14bf99b into main May 2, 2026
31 checks passed
@robcohen
robcohen deleted the fix/price-fallback-per-spec-ticker branch May 2, 2026 01:08
robcohen added a commit that referenced this pull request May 2, 2026
…dispatch (closes #966)

Issue #966: `rledger price BAM` was sending the symbol to Yahoo (the
default source) and returning a stock price for an unrelated ticker
that happened to share the symbol. The discovery-side fix in #965
addressed the `-f` flow but explicit fetches still produced silent
bad data.

Per the reporter's follow-up, this PR makes the default behavior
**refuse** to fetch when no explicit source declaration exists,
covering all three paths the user has to opt in:

- CLI `--source <name>`
- A `[price.mapping.X]` block in config
- A `price:` metadata annotation on the commodity directive

If none of those are set, `resolve_mapping` returns an error whose
message lists exactly those three remediation paths plus the new opt-in
flag.

## Changes

- New `PriceConfig.use_default_source: Option<bool>` (defaults to false)
  with helper `effective_use_default_source()`.
- `PriceSourceRegistry` now captures the flag at construction.
- `resolve_mapping` returns `Result<Vec<(String, String)>>`. When the
  commodity has no mapping AND the flag is false, returns an error
  with the directive remediation message.
- `fetch_price` propagates the error.

The CLI `--source` flag bypasses `resolve_mapping` entirely
(it uses `fetch_with_source`), so users who just want a quick fetch
still have a one-flag escape hatch: `rledger price --source yahoo BAM`.

## Tests

- `test_resolve_mapping_no_mapping_errors_by_default` -- the #966
  regression, asserting the error message names the symbol and all
  four remediation paths (`--source`, config block, metadata, opt-in
  flag).
- `test_resolve_mapping_no_mapping_uses_default_when_opted_in` --
  setting `use_default_source = true` restores the previous behavior.
- All existing `test_resolve_mapping_*` tests updated for the new
  Result signature. 238 rustledger lib tests pass.

## Note

Built on top of #970 (per-spec tickers in fallback chains). After
#970 merges this PR rebases trivially onto main.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
robcohen added a commit that referenced this pull request May 2, 2026
…dispatch (closes #966) (#971)

* fix(price): error on unmapped fetch instead of silent default-source dispatch (closes #966)

Issue #966: `rledger price BAM` was sending the symbol to Yahoo (the
default source) and returning a stock price for an unrelated ticker
that happened to share the symbol. The discovery-side fix in #965
addressed the `-f` flow but explicit fetches still produced silent
bad data.

Per the reporter's follow-up, this PR makes the default behavior
**refuse** to fetch when no explicit source declaration exists,
covering all three paths the user has to opt in:

- CLI `--source <name>`
- A `[price.mapping.X]` block in config
- A `price:` metadata annotation on the commodity directive

If none of those are set, `resolve_mapping` returns an error whose
message lists exactly those three remediation paths plus the new opt-in
flag.

## Changes

- New `PriceConfig.use_default_source: Option<bool>` (defaults to false)
  with helper `effective_use_default_source()`.
- `PriceSourceRegistry` now captures the flag at construction.
- `resolve_mapping` returns `Result<Vec<(String, String)>>`. When the
  commodity has no mapping AND the flag is false, returns an error
  with the directive remediation message.
- `fetch_price` propagates the error.

The CLI `--source` flag bypasses `resolve_mapping` entirely
(it uses `fetch_with_source`), so users who just want a quick fetch
still have a one-flag escape hatch: `rledger price --source yahoo BAM`.

## Tests

- `test_resolve_mapping_no_mapping_errors_by_default` -- the #966
  regression, asserting the error message names the symbol and all
  four remediation paths (`--source`, config block, metadata, opt-in
  flag).
- `test_resolve_mapping_no_mapping_uses_default_when_opted_in` --
  setting `use_default_source = true` restores the previous behavior.
- All existing `test_resolve_mapping_*` tests updated for the new
  Result signature. 238 rustledger lib tests pass.

## Note

Built on top of #970 (per-spec tickers in fallback chains). After
#970 merges this PR rebases trivially onto main.

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

* fix(price): address Copilot review on PR #971 — three real issues

Copilot review on PR #971 surfaced three substantive bugs:

1. **Doc/code contradiction** (`docs/commands/price.md:130`,
   `cmd/price/mod.rs:318`). The new strict default would error on:
   - `quote_currency:`-only commodities (no `price:`, just a quote
     hint), which discovery is supposed to opt into.
   - `--undeclared` ticker-shape commodities, which the flag is
     supposed to enable for default-source dispatch.

   Both produce `DiscoveredCommodity { mapping: None, .. }`, and my
   prior change made the empty mapping trip the explicit-source-required
   guard. **Real regression** for both flows.

2. **`PriceConfig::merge` missed the new field** (`config.rs:105`).
   Setting `[price] use_default_source = true` in a project/user
   config wouldn't override a base value, because the merge function
   didn't apply the field's `Option` override logic.

## Fixes

- `discover_symbols` no longer injects CLI symbols into its output.
  CLI symbols are now handled in `price_cmd.rs::run` so the two paths
  can have different downstream behavior:
  - **File-discovered** (with or without `info.mapping`): a Simple
    mapping pointing at the default source is synthesized when no
    explicit `price:` source was given. This restores the
    `quote_currency:`-only and `--undeclared` flows.
  - **CLI-only symbols** (in `args.symbols` but not in `discovered`):
    NOT auto-mapped, so they hit `resolve_mapping`'s
    explicit-source-required error path — preserves #966.
- `PriceConfig::merge` now propagates `use_default_source` like the
  other `Option` fields.
- `discovery.rs::cli_symbols_always_included_with_default_info` test
  removed; replaced with `discover_returns_empty_for_empty_ledger`
  to lock in the new contract.
- `config.rs::test_merge_price_config_use_default_source` added —
  asserts both `None → Some(true)` and `Some(true) → Some(false)`
  layered overrides take effect.
- `effective_use_default_source()` covered in the existing
  `test_price_config_effective_defaults`.

251 lib tests pass; clippy --all-features --all-targets clean;
fmt clean.

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

* fix(price): self-review fixes — preserve config mappings, dedup CLI args

Self-review of #971 surfaced two real bugs and a doc/coverage gap:

1. **Synthesis overwrote config-level mappings.** When a commodity had
   `[price.mapping.X]` in config AND `quote_currency:`-only metadata
   in the file, the synthesized `Simple(symbol)` was overwriting the
   user's deliberate config block — quietly dispatching to the
   default source instead of the configured one. Fix: switch to
   `entry().or_insert_with(...)` so synthesis fires only when the
   config doesn't already cover the symbol.

2. **Duplicate CLI args produced duplicate fetches.**
   `rledger price AAPL AAPL` (no `-f`) ended up with `["AAPL", "AAPL"]`
   in `symbols_to_fetch`. The old code dedupped via `HashMap` because
   CLI symbols were injected through `or_default()`; my new
   set-difference loop lost that property. Fix: `dedup()` after
   `sort()`.

3. **Doc gap.** The "explicit source declaration required" section
   listed three opt-in paths but missed two — `quote_currency:`-only
   metadata and `--undeclared` heuristic — both of which now opt
   into default-source dispatch via the synthesis path.

## Refactor

Extracted the combined-mapping construction from `run()` into a
`build_combined_mapping()` function. The four-way precedence is now
in one place with a focused doc comment, and the bugs above can be
unit-tested directly. Four new tests:

- `build_combined_mapping_preserves_config_for_quote_currency_only_commodity`
  — the bug-1 regression. Config `[price.mapping.BTC] source = coinbase`
  + file `commodity BTC: quote_currency: "USD"` (no `price:`) must
  end with the coinbase mapping intact, not overwritten by `Simple("BTC")`.
- `build_combined_mapping_synthesizes_simple_for_unmapped_discovered_symbol`
  — confirms synthesis still fires when there's no config entry.
- `build_combined_mapping_discovered_metadata_overrides_config` —
  pins existing #948/#951 precedence: explicit `price:` metadata
  wins over a config block.
- `build_combined_mapping_cli_mapping_wins_over_discovery` — pins
  CLI `--mapping` as highest precedence.

255 lib tests pass; clippy --all-features --all-targets clean;
fmt clean.

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

* fix(price): doc + error-message polish from second self-review

Two doc/UX refinements from the second self-review of #971:

1. **Doc on `price: ""` opt-out** (`docs/commands/price.md`). Old text
   said CLI fetches were "always fetched regardless of opt-out".
   That was true pre-#971 (silent default-source dispatch) but is no
   longer the case — CLI symbols now hit the explicit-source-required
   guard. Reworded to match: the opt-out only affects discovery; CLI
   symbols still need their own source declaration.

2. **`resolve_mapping` error message** lists every remediation path.
   Previously omitted `--mapping`, `quote_currency:`, and `-f`. With
   the synthesis fix, all five metadata/discovery paths plus the
   three CLI flags are valid opt-ins. The new error message
   enumerates them as a bullet list so users can pick whichever fits
   their workflow.

Test `test_resolve_mapping_no_mapping_errors_by_default` extended
with all seven needles (`--source`, `--mapping`, `[price.mapping.X]`,
`price:`, `quote_currency:`, `-f`, `use_default_source`) so the
error stays directive as the codebase evolves.

255 lib tests pass; clippy --all-features --all-targets clean;
fmt clean.

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
robcohen added a commit that referenced this pull request May 3, 2026
…nd fixture

Self-review fixes for PR #978:

1. Scope correction. Rename "symbol-set" -> "commodity discovery". The
   harness uses --source-cmd, which bypasses rledger's source-resolution
   layer — so it cannot validate source-precedence (audit item 5),
   per-spec ticker preservation (#970), or fallback chains. Module
   docstring now states this explicitly. Validating those needs an HTTP
   mock or a future --dry-run flag on rledger.

2. Switch rledger output extraction to --beancount format. Stable,
   documented format (`<date> price <SYM> <amt> <CCY>`); decouples
   the parser from whatever the stub source happens to print.

3. #![cfg(unix)]. The set_mode(0o755) call needs unix::fs::PermissionsExt;
   without the gate, Windows builds would fail to compile.

4. Tighten extract_bean_price_jobs: require uppercase ticker shape +
   uppercase currency. Previously a stray log line beginning with an
   identifier could be wrongly interpreted as a job.

5. New CI sanity test bean_price_must_be_on_path_in_dev_shell. Without
   it, removing beanprice from the flake would silently turn every
   compat test into a no-op (skip path) and we wouldn't notice. Gated
   on IN_NIX_SHELL or CI env vars to avoid false failures locally.

6. New fixture FIXTURE_MIXED_CURRENCIES (USD AAPL + EUR SAP). On its
   first run it found a real bug — see #979: parse_simple_format
   hardcodes "USD" when --source-cmd output omits a currency. The
   stub now echoes the requested --currency back as a workaround so
   the harness can land independently; #979 tracks the underlying fix.

7. Drop noise docstrings on private helpers; consolidate via
   assert_same_commodities helper.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
robcohen added a commit that referenced this pull request May 3, 2026
…967) (#978)

* feat(test): bean-price compat harness — symbol-set differential (refs #967)

Lands the keystone deliverable from issue #967's audit: a Rust integration
test that runs both `rledger price` and `bean-price -n` against a fixture
beancount file and asserts they discover the same set of (symbol,
quote_currency) pairs to fetch.

How it works:
- Fixture is written to a temp file with two declared commodities carrying
  `price: "USD:yahoo/SYMBOL"` metadata.
- `bean-price -n` (dry-run) is parsed from its tabular output.
- `rledger price -f <fixture> --source-cmd <stub>` is run with a no-op stub
  that returns "1.00" for any symbol — no network, no fetching.
- Both symbol-sets are compared; mismatch fails the test with a useful
  diff in the assertion message.

The harness skips (with a notice) when `bean-price` is not on PATH so
contributors running `cargo test` outside `nix develop` aren't blocked.
CI uses the dev shell (where #976 added beanprice), so this runs there.

Note on the stub source: written into a `TempDir` with a plain file (not
`NamedTempFile`) — the latter holds an open write handle and Linux refuses
to exec it (ETXTBSY).

Once landed, every per-candidate audit item from #967 (#967 items 1-6) can
add its own fixture + assertion against this harness.

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

* test(price): tighten compat harness — scope clarity, robustness, second fixture

Self-review fixes for PR #978:

1. Scope correction. Rename "symbol-set" -> "commodity discovery". The
   harness uses --source-cmd, which bypasses rledger's source-resolution
   layer — so it cannot validate source-precedence (audit item 5),
   per-spec ticker preservation (#970), or fallback chains. Module
   docstring now states this explicitly. Validating those needs an HTTP
   mock or a future --dry-run flag on rledger.

2. Switch rledger output extraction to --beancount format. Stable,
   documented format (`<date> price <SYM> <amt> <CCY>`); decouples
   the parser from whatever the stub source happens to print.

3. #![cfg(unix)]. The set_mode(0o755) call needs unix::fs::PermissionsExt;
   without the gate, Windows builds would fail to compile.

4. Tighten extract_bean_price_jobs: require uppercase ticker shape +
   uppercase currency. Previously a stray log line beginning with an
   identifier could be wrongly interpreted as a job.

5. New CI sanity test bean_price_must_be_on_path_in_dev_shell. Without
   it, removing beanprice from the flake would silently turn every
   compat test into a no-op (skip path) and we wouldn't notice. Gated
   on IN_NIX_SHELL or CI env vars to avoid false failures locally.

6. New fixture FIXTURE_MIXED_CURRENCIES (USD AAPL + EUR SAP). On its
   first run it found a real bug — see #979: parse_simple_format
   hardcodes "USD" when --source-cmd output omits a currency. The
   stub now echoes the requested --currency back as a workaround so
   the harness can land independently; #979 tracks the underlying fix.

7. Drop noise docstrings on private helpers; consolidate via
   assert_same_commodities helper.

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

* test(price): shell-quote --source-cmd path (Copilot review on PR #978)

rledger parses --source-cmd through shell_words::split, so a temp directory
containing whitespace would cause the path to be word-split into separate
tokens and the exec to fail before discovery could be compared.

Quote the path with shell_words::quote before passing.

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

* test(price): fix CI failure — only assert bean-price PATH inside nix shell

The bean_price_must_be_on_path_in_dev_shell sanity test was gated on
\`IN_NIX_SHELL OR CI\`, but CI doesn't currently run inside \`nix develop\`
— so on CI the gate fired but bean-price wasn't on PATH, causing the
test to fail.

Drop the CI env-var trigger; only assert when actually inside the dev
shell. Local devs running tests via \`nix develop\` still get the
flake-regression guard; making CI also run under nix is a separate
workflow change.

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

* ci: run bean-price compat harness inside nix develop

The harness in crates/rustledger/tests/bean_price_compat.rs depends on
bean-price being on PATH, which is only true inside the nix dev shell
(added to the flake in #976). The main Test matrix uses dtolnay/rust-toolchain
+ cargo nextest directly, with no nix involved, so the harness silently
skipped there.

Add a dedicated bean-price-compat job that uses cachix/install-nix-action
and runs `cargo test -p rustledger --test bean_price_compat` inside
`nix develop`. Wire it into the build aggregator's required-results list.

This ensures CI actually executes the differential tests against bean-price
so a flake regression (or a real divergence between rledger and bean-price
discovery) breaks the PR loudly instead of silently.

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

* Revert "ci: run bean-price compat harness inside nix develop"

This reverts commit 919fee1.

* ci: enforce bean-price compat harness in pre-push hook (local only)

Reverts the CI workflow approach (commit 919fee1, reverted in adad0b28)
in favor of a local pre-push hook gated on relevant file changes.

Why local instead of CI: running the harness in CI requires nix shell
(for bean-price), which adds noticeable runtime to every PR. The harness
mostly catches regressions in the price command's discovery layer or in
the flake's beanprice packaging — both areas are touched rarely. Running
the check pre-push when those specific files change concentrates the
cost on the contributor making the relevant change.

The hook fires when any of these change:
- crates/rustledger/src/cmd/price/**, price_cmd.rs (discovery / source layer)
- crates/rustledger/tests/bean_price_compat.rs (the harness itself)
- flake.nix, flake.lock (could drop or break beanprice)

Uses `nix develop --command cargo test ...` so bean-price is reliably on
PATH; if nix isn't installed, the push fails loudly with a clear error
rather than silently skipping.

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

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
robcohen added a commit that referenced this pull request May 3, 2026
* feat(price): bean-price audit bundle (refs #967, closes #972 follow-up)

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

* fix(price): self-review on PR #982 — better dry-run output + tests

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

* fix(price): address Copilot review on PR #982

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

* fix(importer): bail on any debit/credit parse failure (self-review on 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]>

---------

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

[Bug]: price download fallbacks ignored

2 participants