Skip to content

fix(price): strict metadata-only discovery, add --undeclared/--inactive (closes #962) - #965

Merged
robcohen merged 5 commits into
mainfrom
fix/price-discovery-strict-metadata
May 1, 2026
Merged

robcohen merged 5 commits into
mainfrom
fix/price-discovery-strict-metadata

Conversation

@robcohen

@robcohen robcohen commented May 1, 2026

Copy link
Copy Markdown
Member

Summary

rledger price -f file.beancount was downloading prices for any ticker-shaped commodity name even without price: metadata. Issue #962 flagged this for currency code BAM (no Yahoo ticker correspondence) and custom symbol UKW (collides with an unrelated stock).

This PR makes discovery strict by default — matching bean-price — and adds two granular flags that map 1:1 to the upstream CLI.

Verification against upstream

beanprice/price.py::find_currencies_declared (master):

source_str = entry.meta.get(\"price\", None)
if source_str is not None:
    if source_str == \"\":
        # Skip — empty price: opts out
        continue
    # parse \"<quote>:<source>/<ticker>\" and include
else:
    # No price: metadata → ignore the commodity entirely

No name heuristic exists upstream.

Changes

  • Default: only commodities with price: or quote_currency: metadata are discovered. Fixes the BAM/UKW false positives.
  • price: \"\" is honored as an explicit opt-out (matches bean-price's "Skipping ignored currency (with empty price)" log).
  • --all-commodities is replaced by two flags:
    • --inactive ↔ bean-price --inactive (include zero-balance commodities)
    • --undeclared ↔ bean-price --undeclared (re-enable the ticker-shape heuristic for commodities without metadata)
  • The two flags compose: --inactive --undeclared is the legacy "fetch everything that looks fetchable" behavior.

Migration

Users who relied on -f picking up ticker-shaped commodity names without metadata can either:

  1. Pass --undeclared (and --inactive if needed) to restore the previous behavior, or
  2. Annotate the affected commodities with price: metadata, which is the recommended path going forward.

Tests

New unit tests in discovery.rs:

  • discover_skips_no_metadata_commodity_by_default — the BAM regression
  • discover_honors_empty_price_opt_out — price: \"\" always skips
  • discover_picks_up_quote_currency_only_commodity — quote_currency: alone opts in

New CLI tests in price_cmd.rs cover the new flag combinations.

Test plan

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

🤖 Generated with Claude Code

…ve (closes #962)

`rledger price -f file.beancount` was downloading prices for any
ticker-shaped commodity name even without `price:` metadata. Issue #962
flagged this against `bean-price`, where the equivalent flow walks
Commodity directives and fetches *only* commodities with explicit
`price:` metadata.

Verified against upstream `beanprice/price.py::find_currencies_declared`:

```python
source_str = entry.meta.get("price", None)
if source_str is not None:
    if source_str == "":
        # Skip — empty price: opts out
        continue
    # parse "<quote>:<source>/<ticker>" and include
else:
    # No price: metadata → ignore the commodity entirely
```

Changes:

- Default discovery now requires `price:` or `quote_currency:` metadata.
  Currency codes like `BAM` and custom commodities like `UKW` no longer
  collide with stock tickers.
- `price: ""` (empty string) is honored as an explicit opt-out, even
  with `--undeclared`. Matches `bean-price`'s "Skipping ignored currency
  (with empty price)" behavior.
- `--all-commodities` is replaced with two granular flags that match
  `bean-price`:
  - `--inactive`: include commodities with zero balance.
  - `--undeclared`: re-enable the ticker-shape heuristic for commodities
    without metadata (legacy behavior). Pair with `--inactive` for the
    pre-#962 "fetch everything" behavior.

Tests added in `discovery.rs`:

- `discover_skips_no_metadata_commodity_by_default` — the BAM regression.
- `discover_honors_empty_price_opt_out` — `price: ""` always skips.
- `discover_picks_up_quote_currency_only_commodity` — `quote_currency:`
  alone is a valid opt-in.

CLI tests in `price_cmd.rs` cover the new flag combinations.

Docs: `docs/commands/price.md` rewrites the "Discovering Symbols" section
to reflect strict-by-default semantics, the new flags, and the
`price: ""` opt-out.

This is a behavioral break for users who relied on `-f` discovering
ticker-shaped names without metadata. Migration: pass `--undeclared` to
restore the previous behavior, or annotate the affected commodities
with `price:` metadata.

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

Aligns rledger price -f commodity discovery with Python bean-price by making discovery metadata-driven by default, preventing accidental downloads for ticker-shaped currency codes (e.g., BAM, UKW) unless explicitly opted in.

Changes:

  • Make -f/--file discovery strict by default: only commodities with price: or quote_currency: metadata are discovered (and price: "" explicitly opts out).
  • Replace --all-commodities with --inactive (include zero-balance commodities) and --undeclared (re-enable ticker-shaped heuristic without metadata).
  • Add/adjust unit + CLI argument parsing tests to cover the new discovery behavior and flag combinations.

Reviewed changes

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

File Description
docs/commands/price.md Updates CLI docs and discovery semantics, documents --inactive/--undeclared and price: "" opt-out.
crates/rustledger/src/cmd/price_cmd.rs Replaces --all-commodities with --inactive/--undeclared, updates discovery call and CLI tests.
crates/rustledger/src/cmd/price/discovery.rs Implements strict-by-default discovery, adds explicit price: "" opt-out, and adds targeted regression 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 docs/commands/price.md Resolved
@github-actions

github-actions Bot commented May 1, 2026 •

Copy link
Copy Markdown
Contributor

📊 Benchmark Results

Tool Time Memory
rustledger 32.9ms ± 0.2ms 21.8 MB
beancount 785.9ms ± 2.9ms 50.4 MB
Comparison 23.9x faster 2.3x less

vs main branch (2026-05-01)

Metric main this PR Change
Time 32.8ms 32.9ms +0.3% ✅
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

@codecov

codecov Bot commented May 1, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 87.50000% with 27 lines in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
crates/rustledger/src/cmd/price_cmd.rs 54.00% 23 Missing ⚠️
crates/rustledger/src/cmd/price/discovery.rs 97.59% 4 Missing ⚠️

📢 Thoughts on this report? Let us know!

@github-actions

github-actions Bot commented May 1, 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 April 30, 2026 21:38
…ut trim, refactor

Self-review of #965 surfaced six fixable issues:

1. The PR description and docs both claimed `--undeclared` is a 1:1
   match for `bean-price --undeclared`. It isn't: bean-price walks
   transactions (at-cost ∪ converted ∪ priced) with no name filter,
   while ours walks `commodity` directives with a ticker-shape filter.
   Different inputs, different outputs. The strict subset is
   intentional (avoids routing currency codes like `EUR` to stock
   sources by default), so this PR documents the divergence honestly
   instead of changing behavior. Closer alignment is tracked as a
   follow-up under the bean-price audit issue.

2. Whitespace-only `price: "   "` now triggers the explicit opt-out,
   same as `price: ""`. Previously fell through to strict-skip with the
   same effective result, but inconsistent with the explicit-opt-out
   intent.

3. Stale doc comment on `DiscoveredCommodity::mapping` — `None` no
   longer means "name heuristic only"; it can also mean
   `quote_currency:`-only or CLI-supplied. Updated.

4. Refactored discovery loop to use a `DiscoveryDecision` enum
   (`OptOut | Discovered | Inherit`). This eliminates the previous
   double-read of `price:` metadata (once for the opt-out check, once
   in `build_discovery_info`) and reads the cleaner branch structure
   off the match arms.

5. Renamed
   `active_filter_handles_explicit_amounts_on_balance_sheet_side_signature_passthrough`
   to `discover_inactive_undeclared_combined_matches_legacy_all_commodities`
   — the previous name implied it was about active-filter behavior, but
   the test is about combined flag interaction.

6. `--inactive` and `--undeclared` now use clap `requires = "file"` so
   they error fast when used without `-f`, instead of silently being
   no-ops.

Plus a new test `discover_honors_whitespace_only_price_opt_out` for #2.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
Three Copilot review comments addressed:

1. **Restored `--all-commodities` as a deprecated, hidden alias** for
   `--inactive --undeclared`. Existing 0.14.1 scripts and CI
   invocations no longer break. Emits a deprecation warning to
   stderr the first time it's used; the flag is hidden from
   `--help` output. Will be removed in a future release.

2. **Clarified `price: ""` opt-out wording** in
   `docs/commands/price.md`. The opt-out only suppresses discovery
   from `-f / --file`; an explicit CLI symbol like
   `rledger price BAM` is still fetched (CLI args are explicit user
   intent and override per-commodity discovery rules). The previous
   "never fetched" wording was misleading.

3. **Warn on malformed `price:` metadata.** A non-empty `price:`
   value that produces no parseable specs (e.g. typo, wrong format)
   used to be silently skipped by the strict default. Now we emit a
   warning to stderr matching `bean-price`'s "Ignoring currency
   with invalid 'price' source" log, and surface the warning even
   when the commodity is included via `quote_currency:`. The
   commodity itself is still skipped under the strict default
   (matches bean-price); the user sees the typo loudly.

Refactor: `classify_commodity_meta` now returns a `Classification`
struct carrying both the discovery decision and a `malformed_price`
flag, so the caller can log warnings per-symbol with the symbol name
in scope.

Tests added:

- `classify_flags_malformed_price_metadata` — `price: "BOGUS_FORMAT"`
  flag set, decision = Inherit (skipped under strict default).
- `classify_flags_malformed_price_even_when_quote_currency_present` —
  malformed `price:` paired with valid `quote_currency:` still flags
  the malformed warning, and the commodity is still discovered.
- `classify_does_not_flag_empty_price_as_malformed` — `price: ""`
  is an opt-out, not malformed (no false-positive warning).
- `test_price_args_all_commodities_deprecated_alias_still_parses` —
  the deprecated flag is accepted by clap.

Co-Authored-By: Claude Opus 4.7 (1M context) <[email protected]>
@robcohen
robcohen enabled auto-merge (squash) May 1, 2026 04:56
@robcohen
robcohen merged commit e98e8ea into main May 1, 2026
30 checks passed
@robcohen
robcohen deleted the fix/price-discovery-strict-metadata branch May 1, 2026 12:17
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)

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