Skip to content

feat(price): metadata-driven, active-commodity discovery (closes #948) - #951

Merged
robcohen merged 2 commits into
mainfrom
feat/active-commodities-price-discovery
Apr 29, 2026
Merged

robcohen merged 2 commits into
mainfrom
feat/active-commodities-price-discovery

Conversation

@robcohen

Copy link
Copy Markdown
Member

Summary

Issue #948 asks for bean-price-style symbol discovery: read the ledger, fetch prices for the commodities you actually hold, and use per-commodity price: metadata to drive source/ticker selection. Today's -f flag picks every commodity that looks ticker-shaped, so users with holdings named Vanguard_VTI get nothing while users who closed a position years ago keep paying for refetches.

This PR closes the gap in one shot.

Changes

1. price: metadata drives source/ticker selection

Format mirrors bean-price: "<quote-currency>:<source>/<ticker>", comma-chained for fallback.

```beancount
2024-01-01 commodity AAPL
price: "USD:yahoo/AAPL"

2024-01-01 commodity Vanguard_VTI
price: "USD:yahoo/VTI,USD:google/NYSEARCA:VTI"

2024-01-01 commodity AUD
price: "EUR:ecb/AUD-EUR"
```

Parsed entries become a CommodityMapping::Detailed with SourceRef::Single or SourceRef::Fallback, so the rest of the price pipeline picks them up unchanged.

2. quote_currency: metadata for per-commodity quote currency

Sets the quote currency for one symbol, overriding --currency. price: metadata's first entry wins over a separate quote_currency: if both are set (matches Python beancount).

3. Active-only filtering by default

A commodity is fetched only if at least one open balance-sheet account (Assets / Liabilities, read from options.name_assets / name_liabilities so non-English ledgers work) ends with a non-zero balance in it. The previous behavior is reachable via the new --all-commodities flag.

Why "balance-sheet" not "any account": Equity:Opening-Balances retains inverse balances of every commodity that ever moved through the ledger, so a naive "non-zero anywhere" check would mark every long-closed position as still active. Restricting to Assets/Liabilities is what makes the check correct. A regression test guards this.

Precedence for source/ticker resolution

High to low:

  1. CLI `--mapping`
  2. CLI `--source`
  3. Discovered `price:` metadata (new)
  4. Config `[price.mapping]`
  5. Default source from `[price.default_source]`

Backward compat

  • Commodities with no metadata still pass the ticker-shape heuristic, so existing `-f` users keep working.
  • CLI-positional symbols are always included regardless of file discovery.
  • The activity filter is opt-out (`--all-commodities`) for users who want today's behavior.

Implementation

New module `crates/rustledger/src/cmd/price/discovery.rs` keeps `price_cmd.rs` readable. Public API:

```rust
pub struct DiscoveredCommodity { mapping, quote_currency }
pub fn discover_symbols(directives, options, cli_symbols, include_inactive)
```

Takes a directive slice rather than the `Ledger` type so it works with both `LoadResult` (raw load) and `Ledger` (post-processing) without coupling.

Tests

8 new unit tests in `discovery.rs`:

  • `parses_single_price_spec` / `parses_chained_price_specs` / `parse_price_skips_malformed_entries`
  • `ticker_heuristic_rejects_long_or_lowercase`
  • `active_filter_keeps_held_commodities` (AAPL held → active, BTC fully sold → inactive, EUR cash → active)
  • `closed_account_balance_does_not_count_as_active` (the Equity-Opening regression)
  • `discover_picks_up_metadata_driven_commodity` (non-ticker name with `price:` is picked up)
  • `discover_skips_inactive_by_default` + opt-in via `include_inactive`
  • `cli_symbols_always_included_with_default_info`

2 new CLI parsing tests in `price_cmd.rs` for the `--all-commodities` flag.

Verification

  • `cargo test -p rustledger`: all green (224 + 27 + 43 + 7 + 65 + 17)
  • `cargo clippy --all-features --all-targets -- -D warnings`: clean
  • `cargo fmt --check`: clean

Test plan

  • CI: Clippy, Test, Doctests, Format, Compatibility
  • Manual: `rledger price -f main.beancount` returns only currently-held commodities
  • Manual: add a `commodity` directive with `price: "EUR:ecb/AUD-EUR"` and confirm it gets fetched from ECB in EUR (not the global default source)
  • Manual: `--all-commodities` brings back all declared commodities

Closes #948

🤖 Generated with Claude Code

Issue #948 asks for `bean-price`-style symbol discovery: read the ledger,
fetch prices for the commodities you actually hold, and use per-commodity
`price:` metadata to drive source/ticker selection.

Three changes in one PR:

1. `price:` metadata on commodity directives drives source/ticker.
   Format: `"<quote>:<source>/<ticker>"`, comma-chained for fallback.
2. `quote_currency:` metadata sets a per-commodity quote currency.
3. Active-only filtering by default. A commodity is fetched only if at
   least one open Assets/Liabilities account ends with non-zero balance
   in it. Restricting to balance-sheet accounts (vs any account) is the
   correct definition: Equity:Opening retains inverse balances of every
   commodity ever held, so including Equity would mark closed positions
   as still active. The `--all-commodities` flag opts out of the filter.

Backward compat: commodities without metadata still pass the
ticker-shape heuristic; CLI symbols pass through unchanged.

New module: `crates/rustledger/src/cmd/price/discovery.rs`. 8 new unit
tests, 2 new CLI parsing tests. Docs updated in `docs/commands/price.md`.

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

codecov Bot commented Apr 29, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 81.38889% with 67 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger/src/cmd/price_cmd.rs 13.11% 53 Missing ⚠️
crates/rustledger/src/cmd/price/discovery.rs 95.31% 14 Missing ⚠️

📢 Thoughts on this report? Let us know!

@github-actions

github-actions Bot commented Apr 29, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 33.7ms ± 4.5ms 21.3 MB
beancount 909ms ± 5.4ms 50.1 MB
Comparison 27x faster 2.4x less

vs main branch (2026-04-28)

Metric main this PR Change
Time 35.9ms 33.7ms -6.1% 🟢
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

Adds bean-price-style commodity discovery to rledger price so it fetches prices for commodities you actually hold and can use per-commodity metadata to control source/ticker/quote currency (closing #948).

Changes:

  • Introduces metadata-driven discovery via price: and quote_currency: on commodity directives, including fallback source chains.
  • Adds active-only filtering by default (opt-out via --all-commodities) and wires discovered per-commodity quote currency into fetching + caching.
  • Updates CLI/docs and adds unit tests for discovery + CLI parsing.

Reviewed changes

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

File Description
docs/commands/price.md Documents metadata-driven symbol discovery, active-only filtering, and new --all-commodities flag.
crates/rustledger/src/cmd/price_cmd.rs Integrates discovery into the price command, merges mappings with new precedence, applies per-symbol quote currency, adds CLI flag tests.
crates/rustledger/src/cmd/price/mod.rs Exposes the new discovery module.
crates/rustledger/src/cmd/price/discovery.rs New module implementing symbol discovery, metadata parsing, and activity filtering with unit tests.

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

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
Comment thread docs/commands/price.md Resolved
@github-actions

github-actions Bot commented Apr 29, 2026 •

Copy link
Copy Markdown
Contributor

⚠️ Compatibility Test Results

Metric Result
Check Compatibility 99%
BQL Compatibility 85%
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

Four issues raised by Copilot review:

1. **Interpolated postings were silently dropped from the activity check.**
   `Loader::new().load(...)` returns the unprocessed `LoadResult`, where
   auto-balanced postings (units missing in source, filled in by booking)
   have `units == None`. The active-commodity filter only sees postings
   with `posting.amount() == Some(_)`, so a transaction like

       2024-02-01 * "Buy AAPL"
         Assets:Brokerage             ; interpolated
         Equity:Opening   -100 AAPL

   would mark AAPL as inactive (the asset side has no explicit amount,
   the equity side is filtered out as non-balance-sheet).

   Switched to `rustledger_loader::load(file, &LoadOptions { run_plugins:
   false, validate: false, ..default() })`, which runs the booking pass
   so every posting has explicit units. Plugins/validation are skipped
   here because price discovery shouldn't be blocked on plugin failures
   in an otherwise-loadable file.

2. **`--source-cmd` ignored per-commodity quote currency.** The external
   command path built `PriceRequest` with `args.currency` directly,
   bypassing the per-symbol `effective_currency` resolution that the
   network path already uses. Threaded the discovery map through and
   applied the same lookup so quote_currency / price: metadata work
   uniformly across all source types.

3. **Misleading mapping-precedence comment.** Said "highest precedence
   first" but the code starts with config (lowest) and inserts CLI
   (highest) last. Reworded to "in increasing precedence" and called
   out the high-to-low effective order explicitly.

4. **Doc inaccuracy on activity scope.** `docs/commands/price.md` said
   activity is "any open account", but the implementation restricts to
   Assets/Liabilities (with the rationale that Equity:Opening retains
   inverse balances of every commodity ever held). Refreshed the prose
   to match the actual behavior and rationale.

New regression test `active_filter_handles_explicit_amounts_on_balance_sheet_side`
locks in the post-booking shape that #1 relies on.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@robcohen
robcohen merged commit 16de343 into main Apr 29, 2026
30 checks passed
@robcohen
robcohen deleted the feat/active-commodities-price-discovery branch April 29, 2026 00:58
robcohen added a commit that referenced this pull request Apr 30, 2026
…) (#953)

* fix(price): config quote_currency, dotted ticker discovery (closes #952)

Issue #952 surfaced three distinct gaps in the price command after #951
landed metadata-driven discovery. This PR addresses two of them; the
third (Yahoo returning a TRY/GBP cross-rate when EUR was requested)
needs a reproducer from the user and is being followed up separately.

1. **`[price.mapping.X] quote_currency` was silently ignored.**
   The user wrote `[price.mapping.AUD] currency = "EUR"` and got USD
   prices because:
   - Our `CommodityMapping::Detailed` had no `currency`/`quote_currency`
     field at all, so the value was dropped at deserialization.
   - The struct didn't enforce `deny_unknown_fields`, so the typo passed
     silently.

   Fix is two-fold:
   - Pull `Detailed` out of the inline `untagged` enum variant into its
     own `DetailedMapping` struct so it can carry
     `#[serde(deny_unknown_fields)]`. Future typos error at config load
     with a clear "unknown field" diagnostic.
   - Add a `quote_currency: Option<String>` field. Per-symbol quote
     currency from config now resolves with the same precedence as the
     ledger-side `quote_currency:` metadata added in #948.

   New `resolve_quote_currency` helper centralizes the
   high-to-low precedence lookup (discovered metadata, then config
   mapping, then global `--currency`) so the network and `--source-cmd`
   paths apply it identically.

2. **Exchange-suffixed tickers (`VECP.AS`, `BRK.B`, `7203.T`) were
   silently skipped.** The `looks_like_ticker` heuristic in
   `discovery.rs` rejected `.` even though beancount's commodity grammar
   permits it. Added `.` to the allowed character set, and extended the
   existing test.

Tests:
- `test_parse_commodity_mapping_with_quote_currency` — config field
  round-trips through TOML deserialization.
- `test_parse_commodity_mapping_rejects_unknown_field` — the
  `currency = "EUR"` typo now errors instead of being dropped.
- 4 new `resolve_quote_currency` unit tests covering each level of the
  precedence chain.
- Existing `ticker_heuristic_rejects_long_or_lowercase` extended with
  `VECP.AS`, `BRK.B`, `7203.T`.

Docs:
- `docs/commands/price.md` config example shows
  `quote_currency = "EUR"`. New "Quote currency resolution" section
  enumerates the three-step precedence and notes that unknown keys now
  error.

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

* test(price): tighten review feedback on #953

Self-review found five small improvements:

1. `test_parse_commodity_mapping_rejects_unknown_field` now asserts the
   error message references the bad block (AUD) or mentions the
   unknown-field reason, not just `is_err()`.

2. New `test_resolve_quote_currency_detailed_without_quote_currency_uses_default`
   covers the most common shape: a `[price.mapping.X]` block with
   `source = "..."` and no `quote_currency` falls through to the global
   default.

3. Code comment at the `--source-cmd` callsite explains why it passes
   `&price_config.mapping` instead of the merged `combined_mapping`
   (CLI `--mapping` only creates `Simple` entries with no quote_currency,
   so merging wouldn't add anything for currency resolution).

4. Code comment in `looks_like_ticker` documents the deliberate
   permissiveness about leading characters (`7203.T` legitimately starts
   with a digit) so a future maintainer doesn't tighten it and break
   valid tickers.

5. PR description amended to reflect actual test count (separate edit).

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

* fix(price): resolve quote_currency from raw config, not merged map (Copilot #953)

Copilot review on PR #953 caught a real precedence bug. With the
network path passing `&combined_mapping` to `resolve_quote_currency`,
a CLI override like `--mapping AUD:NEW-TICKER` overwrites the
config-file `Detailed` entry with `Simple` in the merged map and
silently drops the config's `quote_currency`. The user's intended
override was the ticker only, but the merge took the currency with it.

Fix: resolve quote currency against `&price_config.mapping` (the raw
config map) on both the network and `--source-cmd` paths. Source/ticker
lookup still uses the merged map further down — only currency
resolution stays config-only, matching the documented precedence
"config quote_currency wins over global default".

Updated the call-site comments in both paths to record the contract:
"use the raw config map so a CLI Simple override can't wipe out a
Detailed.quote_currency".

New regression test
`test_resolve_quote_currency_uses_raw_config_not_merged_mapping`
locks in the helper-level invariant.

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 2, 2026
#970)

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

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

* fix(price): backtick `FallbackEntry` in test doc to satisfy clippy::doc_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]>

* fix(price): deny unknown fields on FallbackDetail to surface typos (Copilot #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]>

---------

Co-authored-by: Claude Opus 4.7 (1M context) <[email protected]>
robcohen added a commit that referenced this pull request May 2, 2026
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]>
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]>
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.

[Feature]: Get Symbols from active commodities

2 participants