The personal finance app for everyone (by everyone)
Ruby
Reject zero and invalid exchange rates for every provider (#3790)
GFR9d59fc5ccfa9
diff --git a/app/models/exchange_rate.rb b/app/models/exchange_rate.rbindex cca0c41c6a..c7751807c2 100644--- a/app/models/exchange_rate.rb+++ b/app/models/exchange_rate.rb@@ -3,4 +3,23 @@ class ExchangeRate < ApplicationRecordvalidates :from_currency, :to_currency, :date, :rate, presence: truevalidates :date, uniqueness: { scope: %i[from_currency to_currency] }+ validate :rate_must_convert_amounts, if: -> { rate.present? }++ # A rate multiplies an amount into another currency, so only a finite,+ # positive number is usable. A zero turns every converted balance into zero+ # (we-promise/sure#1187); negative, NaN or infinite rates are just as wrong.+ #+ # The chk_exchange_rates_rate_positive database constraint enforces the same+ # rule for writes that skip validations, such as the importer's upsert_all.+ def self.valid_rate?(value)+ number = value.is_a?(Numeric) ? value : BigDecimal(value.to_s)+ number.finite? && number.positive?+ rescue ArgumentError, TypeError+ false+ end++ private+ def rate_must_convert_amounts+ errors.add(:rate, :greater_than, count: 0) unless self.class.valid_rate?(rate)+ endenddiff --git a/app/models/exchange_rate/importer.rb b/app/models/exchange_rate/importer.rbindex bd1533b57b..04fa84761e 100644--- a/app/models/exchange_rate/importer.rb+++ b/app/models/exchange_rate/importer.rb@@ -83,11 +83,14 @@ class ExchangeRate::Importerinverse_rates = gapfilled_rates.filter_map do |row|next if row[:rate].to_f <= 0+ inverse = inverse_rate(row[:rate])+ next unless inverse+{from_currency: row[:to_currency],to_currency: row[:from_currency],date: row[:date],- rate: (BigDecimal("1") / BigDecimal(row[:rate].to_s)).round(12)+ rate: inverse}end@@ -235,17 +238,28 @@ class ExchangeRate::Importernext if existing_inverse_dates.include?(rate.date)next if rate.rate.to_f <= 0+ inverse = inverse_rate(rate.rate)+ next unless inverse+{from_currency: to,to_currency: from,date: rate.date,- rate: (BigDecimal("1") / BigDecimal(rate.rate.to_s)).round(12)+ rate: inverse}endupsert_rows(inverse_rows) if inverse_rows.any?end+ # Inverses are stored to 12 decimal places, so a forward rate above 1e12+ # rounds its inverse to zero. That pair is skipped rather than stored as the+ # zero rate ExchangeRate.valid_rate? rejects.+ def inverse_rate(rate)+ inverse = (BigDecimal("1") / BigDecimal(rate.to_s)).round(12)+ inverse if ExchangeRate.valid_rate?(inverse)+ end+def all_rates_exist?db_count == expected_countenddiff --git a/app/models/provider/exchange_rate_concept.rb b/app/models/provider/exchange_rate_concept.rbindex dc120ba6a4..4c62708f6b 100644--- a/app/models/provider/exchange_rate_concept.rb+++ b/app/models/provider/exchange_rate_concept.rb@@ -3,6 +3,66 @@ module Provider::ExchangeRateConceptRate = Data.define(:date, :from, :to, :rate)+ # Prepended to every provider that includes this concept, so each one, and+ # any added later, only hands callers rates that can convert an amount (see+ # ExchangeRate.valid_rate?). Providers occasionally answer with a zero rate;+ # stored, it turned every balance in that currency into zero+ # (we-promise/sure#1187).+ module RateValidation+ # An unusable rate is reported as a failed lookup, which callers already+ # handle, instead of a successful one they would store and convert with.+ def fetch_exchange_rate(from:, to:, date:)+ response = super+ return response unless response.success?+ return response if ExchangeRate.valid_rate?(response.data&.rate)++ report_invalid_exchange_rates(from:, to:, rates: [ response.data ])++ Provider::Response.new(+ success?: false,+ data: nil,+ error: self.class::Error.new("#{self.class.name} returned an invalid exchange rate for #{from}/#{to} on #{date}: #{response.data&.rate.inspect}")+ )+ end++ # Unusable rows are dropped, so the importer treats their dates as gaps and+ # carries the previous valid rate forward.+ def fetch_exchange_rates(from:, to:, start_date:, end_date:)+ response = super+ return response unless response.success?++ valid_rates, invalid_rates = Array(response.data).partition { |rate| ExchangeRate.valid_rate?(rate&.rate) }+ return response if invalid_rates.empty?++ report_invalid_exchange_rates(from:, to:, rates: invalid_rates)++ Provider::Response.new(success?: true, data: valid_rates, error: nil)+ end++ private+ def report_invalid_exchange_rates(from:, to:, rates:)+ message = "#{self.class.name} returned #{rates.size} invalid exchange rate(s) for #{from}/#{to}"+ Rails.logger.warn(message)++ DebugLogEntry.capture(+ category: "exchange_rates",+ level: "warn",+ message: message,+ source: self.class.name,+ provider: self,+ metadata: {+ from: from,+ to: to,+ rates: rates.map { |rate| { date: rate&.date&.to_s, rate: rate&.rate.inspect } }+ }+ )+ end+ end++ included do+ prepend RateValidation+ end+def fetch_exchange_rate(from:, to:, date:)raise NotImplementedError, "Subclasses must implement #fetch_exchange_rate"enddiff --git a/db/migrate/20261006210000_add_positive_rate_check_to_exchange_rates.rb b/db/migrate/20261006210000_add_positive_rate_check_to_exchange_rates.rbnew file mode 100644index 0000000000..21ef2e0ba6--- /dev/null+++ b/db/migrate/20261006210000_add_positive_rate_check_to_exchange_rates.rb@@ -0,0 +1,40 @@+# An exchange rate multiplies an amount into another currency, so a zero,+# negative or NaN rate misstates every balance converted with it: a stored zero+# CHF->CNY rate showed CHF accounts as worth nothing (we-promise/sure#1187).+#+# Such rows are provider glitches, not history worth keeping. Deleting them+# leaves gaps that the next sync refetches (ExchangeRate::Importer only skips a+# pair when every date in the range is present), and lookups fall back to the+# nearest earlier rate in the meantime.+#+# NaN is excluded explicitly because PostgreSQL sorts it above every number, so+# `rate > 0` alone accepts it. Infinity only exists for numeric on PostgreSQL+# 14+, and `rate > 0` accepts it too, so it's excluded via a text comparison+# instead of a numeric 'Infinity' literal: casting to numeric requires 14+,+# but casting to text is safe everywhere, since a rate can only render as the+# string "Infinity" on servers that support storing it in the first place.+#+# The constraint is added NOT VALID so this migration only holds the+# ACCESS EXCLUSIVE lock briefly: new and updated rows are checked right away,+# while the full-table scan that validates existing rows runs in the next+# migration (ValidatePositiveRateCheckOnExchangeRates), in its own transaction+# and under a lighter SHARE UPDATE EXCLUSIVE lock that doesn't block reads or+# writes.+class AddPositiveRateCheckToExchangeRates < ActiveRecord::Migration[8.1]+ def up+ execute <<~SQL+ DELETE FROM exchange_rates+ WHERE NOT (rate > 0 AND rate <> 'NaN'::numeric AND rate::text <> 'Infinity')+ SQL++ add_check_constraint :exchange_rates,+ "rate > 0 AND rate <> 'NaN'::numeric AND rate::text <> 'Infinity'",+ name: "chk_exchange_rates_rate_positive",+ validate: false+ end++ # The deleted rows were unusable and are not restored.+ def down+ remove_check_constraint :exchange_rates, name: "chk_exchange_rates_rate_positive"+ end+enddiff --git a/db/migrate/20261006210001_validate_positive_rate_check_on_exchange_rates.rb b/db/migrate/20261006210001_validate_positive_rate_check_on_exchange_rates.rbnew file mode 100644index 0000000000..720c8cf0b6--- /dev/null+++ b/db/migrate/20261006210001_validate_positive_rate_check_on_exchange_rates.rb@@ -0,0 +1,14 @@+# Validates the check constraint AddPositiveRateCheckToExchangeRates added as+# NOT VALID. Kept in its own migration so the full-table scan runs in a separate+# transaction, after the ACCESS EXCLUSIVE lock from adding the constraint has+# been released; VALIDATE CONSTRAINT itself only takes SHARE UPDATE EXCLUSIVE.+class ValidatePositiveRateCheckOnExchangeRates < ActiveRecord::Migration[8.1]+ def up+ validate_check_constraint :exchange_rates, name: "chk_exchange_rates_rate_positive"+ end++ # A validated constraint can't be marked NOT VALID again; rolling back the+ # previous migration removes it entirely.+ def down+ end+enddiff --git a/db/schema.rb b/db/schema.rbindex 33698038d8..7648d7e2b9 100644--- a/db/schema.rb+++ b/db/schema.rb@@ -834,6 +834,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_10_11_151000) dot.index ["from_currency", "to_currency", "date"], name: "index_exchange_rates_on_base_converted_date_unique", unique: truet.index ["from_currency"], name: "index_exchange_rates_on_from_currency"t.index ["to_currency"], name: "index_exchange_rates_on_to_currency"+ t.check_constraint "rate > 0::numeric AND rate <> 'NaN'::numeric AND rate::text <> 'Infinity'::text", name: "chk_exchange_rates_rate_positive"endcreate_table "families", id: :uuid, default: -> { "gen_random_uuid()" }, force: :cascade do |t|diff --git a/docs/llm-guides/providers.md b/docs/llm-guides/providers.mdindex 7f72cd64f8..02e57d83ab 100644--- a/docs/llm-guides/providers.md+++ b/docs/llm-guides/providers.md@@ -99,6 +99,16 @@ Pending inclusion is provider- and layer-specific:budgeting, and keep the pending lookback wide enough that live holds stay in thepayload instead of being pruned as stale.+## Exchange rate providers++Exchange rate providers include+[`Provider::ExchangeRateConcept`](../../app/models/provider/exchange_rate_concept.rb),+which validates their responses: a rate that `ExchangeRate.valid_rate?` rejects+(zero, negative, NaN, infinite or missing) turns a single lookup into a failed+response and is dropped from a series, with a `DebugLogEntry` in the+`exchange_rates` category. Providers do not need their own check. A database+constraint on `exchange_rates.rate` rejects anything that still gets through.+## Transaction namingWhere a provider supplies both a cleaned merchant name and the bank's owndiff --git a/test/models/coinspot_account/processor_test.rb b/test/models/coinspot_account/processor_test.rbindex b0479f4b20..6e04d39650 100644--- a/test/models/coinspot_account/processor_test.rb+++ b/test/models/coinspot_account/processor_test.rb@@ -233,9 +233,9 @@ class CoinspotAccount::ProcessorTest < ActiveSupport::TestCaseassert_not_includes record.to_json, "bc1qsecretdestinationaddress"end- # ExchangeRate validates presence but not numericality, so a zero or negative- # rate is storable -- multiplying by one writes a zeroed valuation instead of- # failing.+ # ExchangeRate no longer stores a zero or negative rate, but the converter+ # still guards against one: multiplying by it would write a zeroed valuation+ # instead of failing.test "refuses to convert with a non-positive exchange rate" do@family.update!(currency: "USD")ExchangeRate.stubs(:find_or_fetch_rate).returns(diff --git a/test/models/exchange_rate/importer_test.rb b/test/models/exchange_rate/importer_test.rbindex 9de97e51ef..e227b9b478 100644--- a/test/models/exchange_rate/importer_test.rb+++ b/test/models/exchange_rate/importer_test.rb@@ -253,6 +253,27 @@ class ExchangeRate::ImporterTest < ActiveSupport::TestCaseassert_equal 0, ExchangeRate.where(from_currency: "USD", to_currency: "EUR").countend+ test "skips inverse rates that would round to zero" do+ ExchangeRate.delete_all++ provider_response = provider_success_response([+ OpenStruct.new(from: "BTC", to: "XYZ", date: Date.current, rate: 2e13)+ ])++ @provider.expects(:fetch_exchange_rates).returns(provider_response)++ ExchangeRate::Importer.new(+ exchange_rate_provider: @provider,+ from: "BTC",+ to: "XYZ",+ start_date: Date.current,+ end_date: Date.current+ ).import_provider_rates++ assert_equal 2e13, ExchangeRate.find_by!(from_currency: "BTC", to_currency: "XYZ", date: Date.current).rate+ assert_not ExchangeRate.exists?(from_currency: "XYZ", to_currency: "BTC")+ end+test "handles rate limit error gracefully" doExchangeRate.delete_alldiff --git a/test/models/exchange_rate_test.rb b/test/models/exchange_rate_test.rbindex 53e037dd6a..3c3ac66a28 100644--- a/test/models/exchange_rate_test.rb+++ b/test/models/exchange_rate_test.rb@@ -95,4 +95,34 @@ class ExchangeRateTest < ActiveSupport::TestCaseresult = ExchangeRate.find_or_fetch_rate(from: "USD", to: "JPY", date: Date.current)assert_equal 155.0, result.rateend++ test "rejects rates that cannot convert an amount" do+ [ 0, -1.2, Float::NAN, Float::INFINITY ].each do |value|+ rate = ExchangeRate.new(from_currency: "CHF", to_currency: "CNY", date: Date.current, rate: value)++ assert_not rate.valid?, "expected a rate of #{value.inspect} to be rejected"+ assert rate.errors.of_kind?(:rate, :greater_than)+ end+ end++ # The importer writes with upsert_all, which skips model validations.+ test "database rejects a zero rate written without validations" do+ assert_raises ActiveRecord::CheckViolation do+ ExchangeRate.upsert_all(+ [ { from_currency: "CHF", to_currency: "CNY", date: Date.current, rate: 0 } ],+ unique_by: %i[from_currency to_currency date]+ )+ end+ end++ # Infinity only exists for numeric on PostgreSQL 14+ and satisfies `rate > 0`,+ # so the constraint excludes it with a text comparison instead.+ test "database rejects an infinite rate written without validations" do+ assert_raises ActiveRecord::CheckViolation do+ ExchangeRate.upsert_all(+ [ { from_currency: "CHF", to_currency: "CNY", date: Date.current, rate: Float::INFINITY } ],+ unique_by: %i[from_currency to_currency date]+ )+ end+ endenddiff --git a/test/models/family/auto_transfer_matchable_test.rb b/test/models/family/auto_transfer_matchable_test.rbindex 301e3df7ae..44b54b8fb3 100644--- a/test/models/family/auto_transfer_matchable_test.rb+++ b/test/models/family/auto_transfer_matchable_test.rb@@ -251,16 +251,6 @@ class Family::AutoTransferMatchableTest < ActiveSupport::TestCaseassert Transfer.exists?(inflow_transaction_id: inflow.entryable_id, outflow_transaction_id: outflow.entryable_id)end- test "a zero direct rate does not mask a usable family currency cross rate" do- load_family_currency_rates- ExchangeRate.create!(from_currency: "GBP", to_currency: "CAD", date: 1.day.ago.to_date, rate: 0)-- outflow = create_transaction(date: 1.day.ago.to_date, account: @depository, amount: 400, currency: "GBP")- inflow = create_transaction(date: Date.current, account: @credit_card, amount: -680, currency: "CAD")-- assert_includes candidate_pairs, [ inflow.entryable_id, outflow.entryable_id ]- end-test "an exact same-currency match is not displaced by a closer cross-currency candidate" doload_family_currency_rateslink_account!(@depository)diff --git a/test/models/holding_test.rb b/test/models/holding_test.rbindex 43eee1e681..f4260fc226 100644--- a/test/models/holding_test.rb+++ b/test/models/holding_test.rb@@ -99,9 +99,11 @@ class HoldingTest < ActiveSupport::TestCaseassert_nil @amzn.avg_costend+ # `exchange_rates` no longer stores a 0, but a rate written to the trade's+ # `extra` directly still can, and the cost must not trust it either.test "a foreign purchase whose stored rate cannot convert makes the average cost unknown" do- ExchangeRate.create!(from_currency: "CAD", to_currency: "USD", date: 1.day.ago.to_date, rate: 0)- create_trade(@amzn.security, account: @account, qty: 10, price: 212.00, date: 1.day.ago.to_date, currency: "CAD")+ entry = create_trade(@amzn.security, account: @account, qty: 10, price: 212.00, date: 1.day.ago.to_date, currency: "CAD")+ entry.entryable.update_column(:extra, (entry.entryable.extra || {}).merge("exchange_rate" => 0))assert_nil @amzn.avg_costenddiff --git a/test/models/provider/exchange_rate_concept_test.rb b/test/models/provider/exchange_rate_concept_test.rbnew file mode 100644index 0000000000..77ba8ffa6c--- /dev/null+++ b/test/models/provider/exchange_rate_concept_test.rb@@ -0,0 +1,93 @@+require "test_helper"++class Provider::ExchangeRateConceptTest < ActiveSupport::TestCase+ # Answers with whatever rates it is given, like a provider whose API+ # occasionally publishes a zero or missing rate, or fails when given an error.+ class StubProvider < Provider+ include Provider::ExchangeRateConcept++ def initialize(rates, error: nil)+ @rates = rates+ @error = error+ end++ def fetch_exchange_rate(from:, to:, date:)+ with_provider_response do+ raise @error if @error++ Rate.new(date:, from:, to:, rate: @rates.first)+ end+ end++ def fetch_exchange_rates(from:, to:, start_date:, end_date:)+ with_provider_response do+ raise @error if @error++ @rates.each_with_index.map { |rate, index| Rate.new(date: start_date + index, from:, to:, rate:) }+ end+ end+ end++ test "rejects a single rate that cannot convert an amount" do+ [ 0, "0.0", -1.5, nil, Float::NAN, Float::INFINITY ].each do |value|+ response = StubProvider.new([ value ]).fetch_exchange_rate(from: "CHF", to: "CNY", date: Date.current)++ assert_not response.success?, "expected a rate of #{value.inspect} to fail the lookup"+ assert_nil response.data+ assert_kind_of Provider::Error, response.error+ end+ end++ test "passes a valid single rate through unchanged" do+ response = StubProvider.new([ "8.0723" ]).fetch_exchange_rate(from: "CHF", to: "CNY", date: Date.current)++ assert response.success?+ assert_equal "8.0723", response.data.rate+ end++ test "drops invalid rates from a series and keeps the valid ones" do+ start_date = 3.days.ago.to_date++ response = StubProvider.new([ 8.07, 0, nil, 8.08 ])+ .fetch_exchange_rates(from: "CHF", to: "CNY", start_date: start_date, end_date: Date.current)++ assert response.success?+ assert_equal [ start_date, start_date + 3 ], response.data.map(&:date)+ assert_equal [ 8.07, 8.08 ], response.data.map(&:rate)+ end++ test "records invalid rates in the debug log" do+ assert_difference -> { DebugLogEntry.where(category: "exchange_rates", level: "warn").count }, 1 do+ StubProvider.new([ 8.07, 0 ]).fetch_exchange_rates(from: "CHF", to: "CNY", start_date: 1.day.ago.to_date, end_date: Date.current)+ end++ entry = DebugLogEntry.where(category: "exchange_rates").recent.first+ assert_equal "CHF", entry.metadata["from"]+ assert_equal "CNY", entry.metadata["to"]+ assert_equal [ Date.current.to_s ], entry.metadata["rates"].map { |rate| rate["date"] }+ end++ test "passes failed lookups through unchanged" do+ provider = StubProvider.new([], error: StandardError.new("timeout"))++ [+ provider.fetch_exchange_rate(from: "CHF", to: "CNY", date: Date.current),+ provider.fetch_exchange_rates(from: "CHF", to: "CNY", start_date: Date.current, end_date: Date.current)+ ].each do |response|+ assert_not response.success?+ assert_equal "timeout", response.error.message+ end+ end++ # A provider added to the registry is covered without extra work, as long as+ # it includes the concept.+ test "every registered exchange rate provider validates its rates" do+ Provider::Registry.for_concept(:exchange_rates).provider_keys.each do |key|+ provider_class = "Provider::#{key.to_s.camelize}".constantize++ assert provider_class < Provider::ExchangeRateConcept, "#{provider_class} does not include Provider::ExchangeRateConcept"+ assert provider_class.ancestors.index(Provider::ExchangeRateConcept::RateValidation) < provider_class.ancestors.index(provider_class),+ "#{provider_class} bypasses Provider::ExchangeRateConcept::RateValidation"+ end+ end+enddiff --git a/test/models/provider/twelve_data_test.rb b/test/models/provider/twelve_data_test.rbindex e5c67d6ab0..b36dc64906 100644--- a/test/models/provider/twelve_data_test.rb+++ b/test/models/provider/twelve_data_test.rb@@ -48,6 +48,22 @@ class Provider::TwelveDataTest < ActiveSupport::TestCaseassert_instance_of Provider::TwelveData::RateLimitError, result.errorend+ # we-promise/sure#1187: the exchange_rate endpoint occasionally answers with+ # a zero rate, which used to be stored and zeroed converted balances.+ test "treats a zero rate from the single exchange rate endpoint as a failed lookup" do+ mock_response = mock+ mock_response.stubs(:body).returns({ "symbol" => "CHF/CNY", "rate" => 0.0, "timestamp" => Time.current.to_i }.to_json)++ @provider.stubs(:throttle_request)+ @provider.stubs(:client).returns(mock_client = mock)+ mock_client.stubs(:get).returns(mock_response)++ result = @provider.fetch_exchange_rate(from: "CHF", to: "CNY", date: Date.current)++ assert_not result.success?+ assert_instance_of Provider::TwelveData::Error, result.error+ end+test "does not fall through to cross API when rate limited" dorate_limit_body = {"code" => 429,diff --git a/test/models/trade_test.rb b/test/models/trade_test.rbindex 3089accd0f..cdffb1a812 100644--- a/test/models/trade_test.rb+++ b/test/models/trade_test.rb@@ -58,23 +58,23 @@ class TradeTest < ActiveSupport::TestCaseassert_nil sell.realized_gain_loss, "a neighbouring day's rate is not this day's"end- # `ExchangeRate` validates presence only -- no positivity at the model, and- # `rate` is a plain `decimal, null: false` at the column -- so a provider or- # an import can leave a 0 or a negative behind. Multiplying by one is not a+ # `exchange_rates` no longer stores a 0 or a negative, but the conversion+ # still guards against being handed one. Multiplying by one is not a# conversion: at 0 the 300 EUR of proceeds become nothing and the disposal# reports a 200 USD total loss the user never took, and at -1.5 the proceeds# go negative and the loss is 650. Neither is distinguishable on the page# from a real one, and both are tax-relevant.#- # A rate that cannot convert is the missing-rate case, whatever is stored in- # the row, so it takes the same exit as an absent one.- test "a disposal whose stored rate cannot convert has no figure" do- [ 0, -1.5 ].each do |stored|+ # A rate that cannot convert is the missing-rate case, whatever supplied it,+ # so it takes the same exit as an absent one.+ test "a disposal whose rate cannot convert has no figure" do+ [ 0, -1.5 ].each do |rate|# Each case needs the same EUR->USD date, which is unique per pair.ExchangeRate.where(from_currency: "EUR", to_currency: "USD").delete_all- sell = cross_currency_disposal(rate: stored)+ sell = cross_currency_disposal(rate: 1.5)+ sell.preloaded_exchange_rates = { [ "EUR", "USD", sell.entry.date ] => rate }- assert_nil sell.realized_gain_loss, "a rate of #{stored} converts nothing"+ assert_nil sell.realized_gain_loss, "a rate of #{rate} converts nothing"endend