Repository navigation
fix(price): error on unmapped fetch instead of silent default-source dispatch (closes #966) - #971
Merged
Merged
Conversation
robcohen
force-pushed
the
fix/price-explicit-source-required
branch
2 times, most recently
from
May 2, 2026 00:55
7d91295 to
5e0b0fb
Compare
…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
force-pushed
the
fix/price-explicit-source-required
branch
from
May 2, 2026 03:15
5e0b0fb to
ce3480a
Compare
Contributor
There was a problem hiding this comment.
Pull request overview
This PR changes rledger price <SYMBOL> default behavior to error when no explicit source declaration exists, preventing silent bad-data fetches caused by dispatching ambiguous symbols (e.g., BAM) to the configured default_source (issue #966).
Changes:
- Add
[price] use_default_source = true|false(default false) to control whether unmapped symbols fall back todefault_source. - Make
PriceSourceRegistry::resolve_mappingreturn aResultand error on unmapped symbols unless opted in. - Document the new default behavior and configuration opt-in.
Reviewed changes
Copilot reviewed 3 out of 3 changed files in this pull request and generated 3 comments.
| File | Description |
|---|---|
docs/commands/price.md |
Documents the new “explicit source required by default” behavior and the use_default_source opt-in. |
crates/rustledger/src/config.rs |
Adds PriceConfig.use_default_source and a helper effective_use_default_source(). |
crates/rustledger/src/cmd/price/mod.rs |
Threads the flag into PriceSourceRegistry and makes unmapped resolution error by default; updates unit tests for the new Result signature. |
💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.
Codecov Report❌ Patch coverage is
📢 Thoughts on this report? Let us know! |
Contributor
📊 Benchmark Results
vs main branch (2026-05-02)
What do these numbers mean?
|
Contributor
|
| 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
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]>
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]>
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]>
robcohen
enabled auto-merge (squash)
May 2, 2026 03:44
This was referenced May 3, 2026
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]>
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Summary
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 comment, 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:
If none are set, `resolve_mapping` returns an error whose message lists exactly those three remediation paths plus the new opt-in flag.
Changes
The CLI `--source` flag bypasses `resolve_mapping` entirely (it routes through `fetch_with_source`), so users who just want a quick one-off fetch still have a single-flag escape hatch: `rledger price --source yahoo BAM`.
Tests
rledger price <SYMBOL>returns wrong source data on ticker collisions #966 regression. Asserts the error names the symbol and mentions all four remediation paths.Test plan
Closes #966.
🤖 Generated with Claude Code