The personal finance app for everyone (by everyone)
Ruby
fix: stop a missing exchange rate from failing a whole account, and make the error legible (#3493)
Yaroslav Shparukf96c6bb7642d
diff --git a/app/models/balance/sync_cache.rb b/app/models/balance/sync_cache.rbindex 6209753c24..3ec9e40309 100644--- a/app/models/balance/sync_cache.rb+++ b/app/models/balance/sync_cache.rb@@ -1,6 +1,24 @@class Balance::SyncCachedef initialize(account)@account = account+ @unconvertible_entry_count = 0+ @unconvertible_holding_count = 0+ end++ # How many entries were left out of the balance calculation because no exchange rate was+ # available to convert them into the account's currency. Populated once `converted_entries`+ # has run; zero on a healthy sync.+ def unconvertible_entry_count+ entries_by_date+ @unconvertible_entry_count+ end++ # How many holdings were counted at a 1:1 rate for the same reason, overstating or+ # understating the holdings total by the FX gap. Populated once `holdings_value_by_date`+ # has run; zero on a healthy sync.+ def unconvertible_holding_count+ holdings_value_by_date+ @unconvertible_holding_countenddef get_valuation(date)@@ -23,35 +41,103 @@ class Balance::SyncCacheenddef holdings_value_by_date- @holdings_value_by_date ||= account.holdings.each_with_object(Hash.new(0)) do |h, totals|- begin- converted = Money.new(h.amount, h.currency).exchange_to(account.currency, date: h.date).amount- rescue Money::ConversionError- converted = h.amount # fallback to 1:1 conversion rate if exchange rate unavailable+ @holdings_value_by_date ||= begin+ missing_rate_pairs = []++ totals = account.holdings.each_with_object(Hash.new(0)) do |h, acc|+ begin+ converted = Money.new(h.amount, h.currency).exchange_to(account.currency, date: h.date).amount+ rescue Money::ConversionError => error+ # Fall back to a 1:1 rate, which misstates the holding by the FX gap. Excluding it+ # instead would be worse here: `BaseCalculator#derive_cash_balance_on_date_from_total`+ # derives cash as `total_balance - holdings_value`, so a dropped holding reappears+ # as phantom cash. Report it rather than silently accepting the wrong number.+ converted = h.amount+ @unconvertible_holding_count += 1+ missing_rate_pairs |= [ [ error.from_currency, error.to_currency ] ]+ end+ acc[h.date] += convertedend- totals[h.date] += converted++ if @unconvertible_holding_count.positive?+ report_missing_rates(+ message: "Valued #{@unconvertible_holding_count} #{"holding".pluralize(@unconvertible_holding_count)} at a 1:1 rate: no exchange rate available",+ counts: { unconvertible_holding_count: @unconvertible_holding_count },+ missing_rate_pairs: missing_rate_pairs+ )+ end++ totalsendenddef converted_entries- @converted_entries ||= account.entries.excluding_pending.excluding_split_parents.includes(:entryable).order(:date).to_a.map do |e|- custom_rate = e.entryable.exchange_rate if e.entryable.respond_to?(:exchange_rate)-- # Use Money#exchange_to with custom rate if available, standard lookup otherwise.- # Mutate the entry in place rather than dup'ing — these instances are scoped to- # this sync-cache only and never persisted, so avoiding the dup eliminates a- # large amount of ActiveModel::Attribute allocations during sync.- # to_a materializes independent instances; no AR identity map is active during sync,- # so callers holding a reference to the same association will never see these mutations.- new_amount = e.amount_money.exchange_to(- account.currency,- date: e.date,- custom_rate: custom_rate- ).amount-- e.amount = new_amount- e.currency = account.currency- e+ @converted_entries ||= begin+ missing_rate_pairs = []++ converted = account.entries.excluding_pending.excluding_split_parents.includes(:entryable).order(:date).to_a.filter_map do |e|+ custom_rate = e.entryable.exchange_rate if e.entryable.respond_to?(:exchange_rate)++ # Use Money#exchange_to with custom rate if available, standard lookup otherwise.+ # Mutate the entry in place rather than dup'ing — these instances are scoped to+ # this sync-cache only and never persisted, so avoiding the dup eliminates a+ # large amount of ActiveModel::Attribute allocations during sync.+ # to_a materializes independent instances; no AR identity map is active during sync,+ # so callers holding a reference to the same association will never see these mutations.+ begin+ new_amount = e.amount_money.exchange_to(+ account.currency,+ date: e.date,+ custom_rate: custom_rate+ ).amount+ rescue Money::ConversionError => error+ # Drop the entry instead of converting it at a made-up rate. A 1:1 fallback here+ # would silently misstate the balance by the size of the FX gap (see #1143), and+ # raising would abandon the whole account's balances over a single entry.+ @unconvertible_entry_count += 1+ missing_rate_pairs |= [ [ error.from_currency, error.to_currency ] ]+ next+ end++ e.amount = new_amount+ e.currency = account.currency+ e+ end++ if @unconvertible_entry_count.positive?+ report_missing_rates(+ message: "Excluded #{@unconvertible_entry_count} #{"entry".pluralize(@unconvertible_entry_count)} from balance calculation: no exchange rate available",+ counts: { unconvertible_entry_count: @unconvertible_entry_count },+ missing_rate_pairs: missing_rate_pairs+ )+ end++ convertedendend++ def report_missing_rates(message:, counts:, missing_rate_pairs:)+ DebugLogEntry.capture(+ category: "sync",+ level: "warn",+ source: "Balance::SyncCache",+ message: message,+ account: account,+ family: account.family,+ provider_key: exchange_rate_provider_key,+ metadata: {+ account_currency: account.currency,+ missing_rate_pairs: missing_rate_pairs.map { |from, to| "#{from}->#{to}" }+ }.merge(counts)+ )+ end++ # Which FX backend was configured when the rate came up missing, so support can filter+ # these entries by provider. Read from the setting rather than `ExchangeRate.provider`,+ # which raises on an unrecognized configuration — diagnostics must never fail the sync.+ def exchange_rate_provider_key+ ENV["EXCHANGE_RATE_PROVIDER"].presence || Setting.exchange_rate_provider+ rescue StandardError+ nil+ endenddiff --git a/lib/money.rb b/lib/money.rbindex 4f58877613..3d0384a499 100644--- a/lib/money.rb+++ b/lib/money.rb@@ -10,9 +10,7 @@ class Money@to_currency = to_currency@date = date- error_message = message || "Couldn't find exchange rate from #{from_currency} to #{to_currency} on #{date}"-- super(error_message)+ super("Couldn't find exchange rate from #{from_currency} to #{to_currency} on #{date}")endenddiff --git a/test/lib/money_test.rb b/test/lib/money_test.rbindex 1ee6b9745c..21f603adce 100644--- a/test/lib/money_test.rb+++ b/test/lib/money_test.rb@@ -202,6 +202,25 @@ class MoneyTest < ActiveSupport::TestCaseendend+ test "conversion error names the currency pair and date it failed on" do+ error = Money::ConversionError.new(from_currency: "EUR", to_currency: "UAH", date: Date.new(2026, 9, 10))++ assert_equal "Couldn't find exchange rate from EUR to UAH on 2026-09-10", error.message+ assert_equal "EUR", error.from_currency+ assert_equal "UAH", error.to_currency+ assert_equal Date.new(2026, 9, 10), error.date+ end++ test "conversion error raised by exchange_to carries a descriptive message" do+ ExchangeRate.expects(:find_or_fetch_rate).returns(nil)++ error = assert_raises(Money::ConversionError) do+ Money.new(1000, :usd).exchange_to(:jpy, date: Date.new(2026, 9, 10))+ end++ assert_equal "Couldn't find exchange rate from USD to JPY on 2026-09-10", error.message+ end+test "uses custom rate when provided" doExchangeRate.expects(:find_or_fetch_rate).neverdiff --git a/test/models/balance/sync_cache_test.rb b/test/models/balance/sync_cache_test.rbindex d657ed9ada..94600b1037 100644--- a/test/models/balance/sync_cache_test.rb+++ b/test/models/balance/sync_cache_test.rb@@ -181,6 +181,75 @@ class Balance::SyncCacheTest < ActiveSupport::TestCaseassert_in_delta 120.0, amounts[2], 0.01 # 100 EUR * 1.2end+ test "excludes an entry with no available exchange rate instead of failing the whole account" do+ convertible = @account.entries.create!(+ date: Date.current,+ name: "USD Transaction",+ amount: 75,+ currency: "USD",+ entryable: Transaction.new(extra: {})+ )+ _unconvertible = @account.entries.create!(+ date: Date.current,+ name: "EUR Transaction",+ amount: 100,+ currency: "EUR",+ entryable: Transaction.new(extra: {})+ )++ sync_cache = Balance::SyncCache.new(@account)+ converted_entries = sync_cache.send(:converted_entries)++ assert_equal [ convertible.name ], converted_entries.map(&:name)+ assert_equal 1, sync_cache.unconvertible_entry_count+ end++ test "records a debug log entry naming the missing currency pairs" do+ @account.entries.create!(+ date: Date.current,+ name: "EUR Transaction",+ amount: 100,+ currency: "EUR",+ entryable: Transaction.new(extra: {})+ )+ @account.entries.create!(+ date: Date.current,+ name: "GBP Transaction",+ amount: 50,+ currency: "GBP",+ entryable: Transaction.new(extra: {})+ )++ assert_difference "DebugLogEntry.count", 1 do+ Balance::SyncCache.new(@account).send(:converted_entries)+ end++ log = DebugLogEntry.order(:created_at).last+ assert_equal "Balance::SyncCache", log.source+ assert_equal "warn", log.level+ assert_equal @account, log.account+ assert_equal Setting.exchange_rate_provider, log.provider_key+ assert_equal 2, log.metadata["unconvertible_entry_count"]+ assert_equal [ "EUR->USD", "GBP->USD" ], log.metadata["missing_rate_pairs"].sort+ end++ test "records no debug log entry when every entry converts" do+ @account.entries.create!(+ date: Date.current,+ name: "USD Transaction",+ amount: 75,+ currency: "USD",+ entryable: Transaction.new(extra: {})+ )++ assert_no_difference "DebugLogEntry.count" do+ sync_cache = Balance::SyncCache.new(@account)+ sync_cache.send(:converted_entries)++ assert_equal 0, sync_cache.unconvertible_entry_count+ end+ end+# get_holdings_valuetest "returns 0 for date with no holdings" do@@ -225,6 +294,41 @@ class Balance::SyncCacheTest < ActiveSupport::TestCaseassert_equal 100, Balance::SyncCache.new(@account).get_holdings_value(Date.current)end+ test "reports a holding valued at 1:1 rather than accepting the wrong number silently" do+ security = Security.create!(ticker: "TST", name: "Test")+ @account.holdings.create!(security: security, date: Date.current, qty: 1, price: 100, amount: 100, currency: "EUR")++ sync_cache = Balance::SyncCache.new(@account)++ assert_difference "DebugLogEntry.count", 1 do+ sync_cache.get_holdings_value(Date.current)+ end++ assert_equal 1, sync_cache.unconvertible_holding_count++ log = DebugLogEntry.order(:created_at).last+ assert_equal "Balance::SyncCache", log.source+ assert_equal "warn", log.level+ assert_equal @account, log.account+ assert_equal 1, log.metadata["unconvertible_holding_count"]+ assert_equal [ "EUR->USD" ], log.metadata["missing_rate_pairs"]+ end++ test "records no holding diagnostic when every holding converts" do+ ExchangeRate.create!(from_currency: "EUR", to_currency: "USD", date: Date.current, rate: 1.5)++ security = Security.create!(ticker: "TST", name: "Test")+ @account.holdings.create!(security: security, date: Date.current, qty: 1, price: 100, amount: 100, currency: "EUR")++ sync_cache = Balance::SyncCache.new(@account)++ assert_no_difference "DebugLogEntry.count" do+ assert_equal 150.0, sync_cache.get_holdings_value(Date.current)+ end++ assert_equal 0, sync_cache.unconvertible_holding_count+ end+test "prioritizes custom rate over fetched rate" do# Create fetched rateExchangeRate.create!(