Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Derive exchange rates a provider lacks from its USD legs (#4438)

Artem Danilova6224c03ccbf
diff --git a/app/models/exchange_rate/importer.rb b/app/models/exchange_rate/importer.rb
index ef507477d4..8cba9afe0f 100644
--- a/app/models/exchange_rate/importer.rb
+++ b/app/models/exchange_rate/importer.rb
@@ -218,9 +218,14 @@ class ExchangeRate::Importer
end_date: end_date
)
- if provider_response.success?
+ if provider_response.success? && provider_response.data.present?
+ ExchangeRatePair.record_direct_quote(from: from, to: to, provider_name: current_provider_name)
Rails.logger.debug("Fetched #{provider_response.data.size} rates from #{exchange_rate_provider.class.name} for #{from}/#{to} between #{provider_fetch_start_date} and #{end_date}")
provider_response.data.index_by(&:date)
+ elsif (crossed = usd_cross_rates(provider_response.error)).any?
+ crossed.index_by(&:date)
+ elsif provider_response.success?
+ {} # No rates at all; import_provider_rates logs that.
else
message = "#{exchange_rate_provider.class.name} could not fetch exchange rate pair from: #{from} to: #{to} between: #{effective_start_date} and: #{Date.current}. Provider error: #{provider_response.error.message}"
Rails.logger.warn(message)
@@ -230,6 +235,12 @@ class ExchangeRate::Importer
end
end
+ # The provider has no such pair, but it may still quote both USD legs.
+ def usd_cross_rates(error)
+ ExchangeRate::UsdCross.new(exchange_rate_provider)
+ .rates(from: from, to: to, start_date: provider_fetch_start_date, end_date: end_date, error: error)
+ end
+
def backfill_inverse_rates_if_needed
existing_inverse_dates = ExchangeRate.where(from_currency: to, to_currency: from, date: clamped_start_date..end_date).pluck(:date).to_set
return if existing_inverse_dates.size >= expected_count
diff --git a/app/models/exchange_rate/provided.rb b/app/models/exchange_rate/provided.rb
index a89db20407..124ca518f2 100644
--- a/app/models/exchange_rate/provided.rb
+++ b/app/models/exchange_rate/provided.rb
@@ -76,9 +76,17 @@ module ExchangeRate::Provided
response = fx_provider.fetch_exchange_rate(from: from, to: to, date: date)
Rails.cache.write(FALLBACK_DOWN_KEY, true, expires_in: 1.minute) if fail_fast && !response.success? && response.error.failure_code == :unreachable
- return nil unless response.success? # Provider error
+ rate = if response.success?
+ ExchangeRatePair.record_direct_quote(from: from, to: to)
+ response.data
+ else
+ # The provider has no such pair, but it may still quote both USD legs.
+ ExchangeRate::UsdCross.new(fx_provider)
+ .rates(from: from, to: to, start_date: date - NEAREST_RATE_LOOKBACK_DAYS, end_date: date, error: response.error).last
+ end
+
+ return nil unless rate # Provider error, and no USD legs either
- rate = response.data
return rate unless cache
begin
diff --git a/app/models/exchange_rate/usd_cross.rb b/app/models/exchange_rate/usd_cross.rb
new file mode 100644
index 0000000000..05e8e41e36
--- /dev/null
+++ b/app/models/exchange_rate/usd_cross.rb
@@ -0,0 +1,93 @@
+# Derives a pair the provider does not quote from its two USD legs:
+# X→Y = X→USD × USD→Y. Providers quote nearly every currency against USD but
+# far fewer crosses between two others; Yahoo Finance has KZT/USD and USD/RUB
+# with full history, yet no KZT/RUB at all.
+class ExchangeRate::UsdCross
+ # Errors every provider names this way when the provider itself is failing,
+ # not the pair; the USD legs would only fail the same way. Others (a network
+ # error, an unknown pair) look alike, as Yahoo Finance reports both as Error.
+ PROVIDER_FAILURES = %w[RateLimitError AuthenticationError].freeze
+
+ # Avoid repeating unsuccessful USD-leg requests for the same pair and dates
+ # during a sync of many entries or holdings.
+ MISS_TTL = 1.hour
+
+ def initialize(provider)
+ @provider = provider
+ end
+
+ # Rate[] for dates with both USD legs. Callers can reuse a completed cross
+ # when a date has no matching quotes. `error` is why the direct pair failed.
+ # [] when either side is USD, the provider itself is failing or cannot derive
+ # a pair (see Provider::ExchangeRateConcept#usd_cross?), it has quoted
+ # this pair before (so the failure is an outage, and a derived rate would
+ # be cached in place of its own), or the legs yield no usable cross. The
+ # latter is cached for MISS_TTL unless the provider itself failed.
+ def rates(from:, to:, start_date:, end_date:, error: nil)
+ return [] if from == to || [ from, to ].include?("USD")
+ return [] if provider_failure?(error)
+ return [] if @provider.respond_to?(:usd_cross?) && [email protected]_cross?
+ return [] if Rails.cache.exist?(miss_key(from, to, start_date, end_date))
+ # A pair is derived until the provider has answered it once, so a transient failure before then keeps the rates derived at that point.
+ return [] if ExchangeRatePair.for_pair(from: from, to: to).quoted_directly?
+
+ to_usd = leg(from, "USD", start_date, end_date)
+ return miss(from, to, start_date, end_date) if to_usd.empty?
+
+ from_usd = leg("USD", to, start_date, end_date)
+ return miss(from, to, start_date, end_date) if from_usd.empty?
+
+ from_usd_by_date = from_usd.index_by(&:date)
+ crossed = to_usd.filter_map do |first|
+ second = from_usd_by_date[first.date]
+ next unless second
+
+ # Two tiny legs can multiply to under 5e-13, which rounds to a zero rate.
+ rate = (BigDecimal(first.rate.to_s) * BigDecimal(second.rate.to_s)).round(12)
+ next unless ExchangeRate.valid_rate?(rate)
+
+ Provider::ExchangeRateConcept::Rate.new(date: first.date, from: from, to: to, rate: rate)
+ end
+
+ return miss(from, to, start_date, end_date) if crossed.empty?
+
+ Rails.cache.delete(miss_key(from, to, start_date, end_date))
+ direct_error = error&.message
+ report("info", "Derived #{crossed.size} #{from}/#{to} rates from #{@provider.class.name} USD rates between #{start_date} and #{end_date}; direct pair: #{direct_error || "no rates"}",
+ from:, to:, start_date:, end_date:, direct_error:)
+ crossed
+ end
+
+ private
+ def leg(from, to, start_date, end_date)
+ response = @provider.fetch_exchange_rates(from: from, to: to, start_date: start_date, end_date: end_date)
+ return response.data.sort_by(&:date) if response.success?
+
+ @provider_failing ||= provider_failure?(response.error)
+ error = response.error.message
+ report("warn", "#{@provider.class.name} could not fetch the #{from}/#{to} leg between #{start_date} and #{end_date}: #{error}",
+ from:, to:, start_date:, end_date:, error:)
+ []
+ end
+
+ def provider_failure?(error)
+ error.class.name.to_s.demodulize.in?(PROVIDER_FAILURES)
+ end
+
+ def miss_key(from, to, start_date, end_date)
+ "usd_cross_miss:#{@provider.class.name}:#{from}:#{to}:#{start_date}:#{end_date}"
+ end
+
+ # A failed derivation says nothing about the pair if the provider is down.
+ def miss(from, to, start_date, end_date)
+ Rails.cache.write(miss_key(from, to, start_date, end_date), true, expires_in: MISS_TTL) unless @provider_failing
+ []
+ end
+
+ # Derived rates are stored like direct ones, so the debug log is the only
+ # record of which dates came from the USD legs.
+ def report(level, message, **metadata)
+ Rails.logger.public_send(level, message)
+ DebugLogEntry.capture(category: "exchange_rates", level: level, message: message, source: self.class.name, provider: @provider, metadata: metadata)
+ end
+end
diff --git a/app/models/exchange_rate_pair.rb b/app/models/exchange_rate_pair.rb
index 857602d728..5026fab276 100644
--- a/app/models/exchange_rate_pair.rb
+++ b/app/models/exchange_rate_pair.rb
@@ -5,11 +5,11 @@ class ExchangeRatePair < ApplicationRecord
pair = find_or_create_by!(from_currency: from, to_currency: to)
current_provider = provider_name || ExchangeRate.provider_name
- if pair.provider_name != current_provider && pair.first_provider_rate_on.present?
+ if pair.provider_name != current_provider && (pair.first_provider_rate_on.present? || pair.quoted_directly?)
ExchangeRatePair
.where(id: pair.id)
.where.not(provider_name: current_provider)
- .update_all(first_provider_rate_on: nil, provider_name: current_provider, updated_at: Time.current)
+ .update_all(first_provider_rate_on: nil, quoted_directly: false, provider_name: current_provider, updated_at: Time.current)
pair.reload
end
@@ -18,6 +18,21 @@ class ExchangeRatePair < ApplicationRecord
find_by!(from_currency: from, to_currency: to)
end
+ # Once the provider has answered the pair itself, a later failure is an
+ # outage rather than a pair it lacks, so it no longer derives from USD legs.
+ # A pair with a USD side is never derived, so its flag is never used.
+ def self.record_direct_quote(from:, to:, provider_name: nil)
+ return if from == "USD" || to == "USD"
+
+ current_provider = provider_name || ExchangeRate.provider_name
+ pair = for_pair(from: from, to: to, provider_name: current_provider)
+ return if pair.quoted_directly?
+
+ ExchangeRatePair
+ .where(id: pair.id)
+ .update_all(quoted_directly: true, provider_name: current_provider, updated_at: Time.current)
+ end
+
def self.record_first_provider_rate_on(from:, to:, date:, provider_name: nil)
return if date.blank?
diff --git a/app/models/provider/exchange_rate_concept.rb b/app/models/provider/exchange_rate_concept.rb
index 4c62708f6b..cb99b10392 100644
--- a/app/models/provider/exchange_rate_concept.rb
+++ b/app/models/provider/exchange_rate_concept.rb
@@ -71,6 +71,13 @@ module Provider::ExchangeRateConcept
raise NotImplementedError, "Subclasses must implement #fetch_exchange_rates"
end
+ # Whether a pair the provider lacks may be derived from its two USD legs (see
+ # ExchangeRate::UsdCross). Override with false in a provider for which that
+ # can never succeed, so the legs are not fetched for nothing.
+ def usd_cross?
+ true
+ end
+
# Maximum number of calendar days of historical FX data the provider can
# return. Returns nil when the provider has no known limit (unbounded).
# Callers should clamp start_date when non-nil to avoid requesting data
diff --git a/app/models/provider/frankfurter.rb b/app/models/provider/frankfurter.rb
index 294583b0b7..5b6dbaea2b 100644
--- a/app/models/provider/frankfurter.rb
+++ b/app/models/provider/frankfurter.rb
@@ -80,6 +80,13 @@ class Provider::Frankfurter < Provider
end
end
+ # The API converts every pair between two currencies it covers itself, so a
+ # pair it lacks has an unsupported currency or no data for the dates, and so
+ # does a USD leg.
+ def usd_cross?
+ false
+ end
+
def max_history_days
nil # Backed by central bank reference rates going back decades, no bounded window.
end
diff --git a/app/models/provider/moex_public.rb b/app/models/provider/moex_public.rb
index 2a69ccc39b..4f72b28af8 100644
--- a/app/models/provider/moex_public.rb
+++ b/app/models/provider/moex_public.rb
@@ -181,6 +181,11 @@ class Provider::MoexPublic < Provider
# Exchange Rates
# ================================
+ # Only X/RUB pairs are quoted, so no pair has both USD legs.
+ def usd_cross?
+ false
+ end
+
def fetch_exchange_rate(from:, to:, date:)
with_provider_response do
# Fetch a short lookback window, not just the exact day, so a weekend or
diff --git a/app/models/provider/yahoo_finance.rb b/app/models/provider/yahoo_finance.rb
index 84a00289d9..f3d3a7b10c 100644
--- a/app/models/provider/yahoo_finance.rb
+++ b/app/models/provider/yahoo_finance.rb
@@ -159,7 +159,13 @@ class Provider::YahooFinance < Provider
end_date: end_date
)
- raise Error, "Failed to fetch exchange rates: #{rates_response.error.message}" unless rates_response.success?
+ unless rates_response.success?
+ error = rates_response.error
+ # Kept as is, so callers can tell the provider failing from the pair missing.
+ raise error if error.is_a?(RateLimitError) || error.is_a?(AuthenticationError)
+
+ raise Error, "Failed to fetch exchange rates: #{error.message}"
+ end
rates = rates_response.data
if rates.length == 1
@@ -981,6 +987,9 @@ class Provider::YahooFinance < Provider
provider_key: "yahoo_finance",
metadata: { symbol: symbol, exception_class: e.class.name, exception_message: e.message }
)
+ # Not a missing pair: the inverse symbol would only be limited too.
+ raise RateLimitError.new("Yahoo Finance rate limit exceeded", details: e.response&.dig(:body)) if e.is_a?(Faraday::TooManyRequestsError)
+
nil
end
end
diff --git a/db/migrate/20261118120000_add_quoted_directly_to_exchange_rate_pairs.rb b/db/migrate/20261118120000_add_quoted_directly_to_exchange_rate_pairs.rb
new file mode 100644
index 0000000000..fc2f7dc693
--- /dev/null
+++ b/db/migrate/20261118120000_add_quoted_directly_to_exchange_rate_pairs.rb
@@ -0,0 +1,8 @@
+class AddQuotedDirectlyToExchangeRatePairs < ActiveRecord::Migration[8.1]
+ # Not backfilled from first_provider_rate_on: a recorded quote may be one the
+ # provider no longer gives, such as Yahoo's mis-scaled RUBGEL=X, which is
+ # rejected. Pairs it still quotes are flagged on their next successful fetch.
+ def change
+ add_column :exchange_rate_pairs, :quoted_directly, :boolean, default: false, null: false
+ end
+end
diff --git a/db/schema.rb b/db/schema.rb
index f45334ca0d..e0c1eaba9f 100644
--- a/db/schema.rb
+++ b/db/schema.rb
@@ -814,6 +814,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_23_220100) do
t.date "first_provider_rate_on"
t.string "from_currency", null: false
t.string "provider_name"
+ t.boolean "quoted_directly", default: false, null: false
t.string "to_currency", null: false
t.datetime "updated_at", null: false
t.index ["from_currency", "to_currency"], name: "index_exchange_rate_pairs_on_pair_unique", unique: true
diff --git a/test/models/account/market_data_importer_test.rb b/test/models/account/market_data_importer_test.rb
index a45a438d5e..93bcd77288 100644
--- a/test/models/account/market_data_importer_test.rb
+++ b/test/models/account/market_data_importer_test.rb
@@ -91,10 +91,11 @@ class Account::MarketDataImporterTest < ActiveSupport::TestCase
)
account.entries.create!(date: 10.days.ago.to_date, amount: 10, currency: "GBP", name: "Card payment", entryable: Transaction.new)
- [ %w[GBP CAD], %w[GBP USD], %w[CAD USD] ].each do |from, to|
+ # GBP/CAD comes back empty, so GBP/USD is fetched again as its first USD leg.
+ { %w[GBP CAD] => 1, %w[GBP USD] => 2, %w[CAD USD] => 1 }.each do |(from, to), calls|
@provider.expects(:fetch_exchange_rates)
.with(from: from, to: to, start_date: anything, end_date: anything)
- .once
+ .times(calls)
.returns(provider_success_response([]))
end
diff --git a/test/models/exchange_rate/importer_test.rb b/test/models/exchange_rate/importer_test.rb
index 8db771395e..2f2840fc6b 100644
--- a/test/models/exchange_rate/importer_test.rb
+++ b/test/models/exchange_rate/importer_test.rb
@@ -36,6 +36,26 @@ class ExchangeRate::ImporterTest < ActiveSupport::TestCase
assert_equal 1.3, db_rates[0].rate
assert_equal 1.4, db_rates[1].rate
assert_equal 1.5, db_rates[2].rate
+ assert_not ExchangeRatePair.find_by!(from_currency: "USD", to_currency: "EUR").quoted_directly?
+ end
+
+ test "records that the provider answered a pair with neither side USD" do
+ ExchangeRate.delete_all
+ ExchangeRatePair.delete_all
+
+ @provider.expects(:fetch_exchange_rates)
+ .with(from: "KZT", to: "RUB", start_date: get_provider_fetch_start_date(Date.current), end_date: Date.current)
+ .returns(provider_success_response([ OpenStruct.new(from: "KZT", to: "RUB", date: Date.current, rate: 0.16) ]))
+
+ ExchangeRate::Importer.new(
+ exchange_rate_provider: @provider,
+ from: "KZT",
+ to: "RUB",
+ start_date: Date.current,
+ end_date: Date.current
+ ).import_provider_rates
+
+ assert ExchangeRatePair.find_by!(from_currency: "KZT", to_currency: "RUB").quoted_directly?
end
test "syncs diff when some rates already exist" do
@@ -338,6 +358,96 @@ class ExchangeRate::ImporterTest < ActiveSupport::TestCase
assert_not ExchangeRate.exists?(from_currency: "XYZ", to_currency: "BTC")
end
+ test "imports a cross from same-day USD legs and carries the cross over a gap" do
+ ExchangeRate.delete_all
+ window = { start_date: get_provider_fetch_start_date(1.day.ago.to_date), end_date: Date.current }
+
+ @provider.expects(:fetch_exchange_rates).with(from: "KZT", to: "RUB", **window)
+ .returns(provider_error_response(StandardError.new("no KZT/RUB")))
+ @provider.expects(:fetch_exchange_rates).with(from: "KZT", to: "USD", **window)
+ .returns(provider_success_response([
+ OpenStruct.new(from: "KZT", to: "USD", date: 1.day.ago.to_date, rate: 0.002),
+ OpenStruct.new(from: "KZT", to: "USD", date: Date.current, rate: 0.0022)
+ ]))
+ @provider.expects(:fetch_exchange_rates).with(from: "USD", to: "RUB", **window)
+ .returns(provider_success_response([ OpenStruct.new(from: "USD", to: "RUB", date: 1.day.ago.to_date, rate: 80) ]))
+
+ ExchangeRate::Importer.new(
+ exchange_rate_provider: @provider,
+ from: "KZT",
+ to: "RUB",
+ start_date: 1.day.ago.to_date,
+ end_date: Date.current
+ ).import_provider_rates
+
+ rates = ExchangeRate.where(from_currency: "KZT", to_currency: "RUB").order(:date).pluck(:rate).map(&:to_f)
+ assert_equal [ 0.16, 0.16 ], rates
+ assert_equal 2, ExchangeRate.where(from_currency: "RUB", to_currency: "KZT").count
+ end
+
+ test "derives a pair from its USD legs when the provider answers it with no rates" do
+ ExchangeRate.delete_all
+ window = { start_date: get_provider_fetch_start_date(Date.current), end_date: Date.current }
+
+ @provider.expects(:fetch_exchange_rates).with(from: "KZT", to: "RUB", **window).returns(provider_success_response([]))
+ @provider.expects(:fetch_exchange_rates).with(from: "KZT", to: "USD", **window)
+ .returns(provider_success_response([ OpenStruct.new(from: "KZT", to: "USD", date: Date.current, rate: 0.002) ]))
+ @provider.expects(:fetch_exchange_rates).with(from: "USD", to: "RUB", **window)
+ .returns(provider_success_response([ OpenStruct.new(from: "USD", to: "RUB", date: Date.current, rate: 80) ]))
+
+ ExchangeRate::Importer.new(
+ exchange_rate_provider: @provider,
+ from: "KZT",
+ to: "RUB",
+ start_date: Date.current,
+ end_date: Date.current
+ ).import_provider_rates
+
+ assert_equal 0.16, ExchangeRate.find_by!(from_currency: "KZT", to_currency: "RUB", date: Date.current).rate.to_f
+ end
+
+ test "reports the direct failure when a USD leg fails too" do
+ ExchangeRate.delete_all
+ window = { start_date: get_provider_fetch_start_date(Date.current), end_date: Date.current }
+
+ @provider.expects(:fetch_exchange_rates).with(from: "KZT", to: "RUB", **window)
+ .returns(provider_error_response(StandardError.new("no KZT/RUB")))
+ @provider.expects(:fetch_exchange_rates).with(from: "KZT", to: "USD", **window)
+ .returns(provider_error_response(StandardError.new("no KZT/USD")))
+ Sentry.expects(:capture_exception).with do |error, options|
+ error.is_a?(ExchangeRate::Importer::MissingExchangeRateError) &&
+ error.message.include?("Provider error: no KZT/RUB") &&
+ options == { level: :warning }
+ end
+
+ ExchangeRate::Importer.new(
+ exchange_rate_provider: @provider,
+ from: "KZT",
+ to: "RUB",
+ start_date: Date.current,
+ end_date: Date.current
+ ).import_provider_rates
+
+ assert_equal 0, ExchangeRate.count
+ end
+
+ test "does not derive a pair the provider has quoted before from its USD legs" do
+ ExchangeRate.delete_all
+ ExchangeRatePair.record_direct_quote(from: "KZT", to: "RUB")
+
+ @provider.expects(:fetch_exchange_rates).once.returns(provider_error_response(StandardError.new("timeout")))
+
+ ExchangeRate::Importer.new(
+ exchange_rate_provider: @provider,
+ from: "KZT",
+ to: "RUB",
+ start_date: Date.current,
+ end_date: Date.current
+ ).import_provider_rates
+
+ assert_equal 0, ExchangeRate.count
+ end
+
test "handles rate limit error gracefully" do
ExchangeRate.delete_all
diff --git a/test/models/exchange_rate/usd_cross_test.rb b/test/models/exchange_rate/usd_cross_test.rb
new file mode 100644
index 0000000000..2e6668667c
--- /dev/null
+++ b/test/models/exchange_rate/usd_cross_test.rb
@@ -0,0 +1,187 @@
+require "test_helper"
+
+class ExchangeRate::UsdCrossTest < ActiveSupport::TestCase
+ include ProviderTestHelper
+
+ setup do
+ @provider = mock
+ @day1 = Date.new(2026, 10, 19)
+ @day2 = @day1 + 1
+ Rails.stubs(:cache).returns(ActiveSupport::Cache::MemoryStore.new)
+ end
+
+ test "multiplies only USD legs observed on the same date, in date order" do
+ day3 = @day2 + 1
+ @provider.expects(:fetch_exchange_rates).with(from: "KZT", to: "USD", start_date: @day1, end_date: day3)
+ .returns(provider_success_response([ rate(day3, "KZT", "USD", 0.003), rate(@day2, "KZT", "USD", 0.0022), rate(@day1, "KZT", "USD", 0.002) ]))
+ @provider.expects(:fetch_exchange_rates).with(from: "USD", to: "RUB", start_date: @day1, end_date: day3)
+ .returns(provider_success_response([ rate(day3, "USD", "RUB", 90), rate(@day1, "USD", "RUB", 80) ]))
+
+ rates = ExchangeRate::UsdCross.new(@provider)
+ .rates(from: "KZT", to: "RUB", start_date: @day1, end_date: day3, error: StandardError.new("no KZT/RUB"))
+
+ assert_equal [ @day1, day3 ], rates.map(&:date)
+ assert_equal [ 0.16, 0.27 ], rates.map { |r| r.rate.to_f }
+ assert_equal [ "KZT", "RUB" ], [ rates.first.from, rates.first.to ]
+
+ entry = DebugLogEntry.where(category: "exchange_rates", level: "info").recent.first
+ assert_equal "ExchangeRate::UsdCross", entry.source
+ assert_equal "no KZT/RUB", entry.metadata["direct_error"]
+ end
+
+ test "skips a product that rounds to a zero rate" do
+ @provider.stubs(:fetch_exchange_rates).with(from: "AAA", to: "USD", start_date: @day1, end_date: @day1)
+ .returns(provider_success_response([ rate(@day1, "AAA", "USD", 0.0000001) ]))
+ @provider.stubs(:fetch_exchange_rates).with(from: "USD", to: "BBB", start_date: @day1, end_date: @day1)
+ .returns(provider_success_response([ rate(@day1, "USD", "BBB", 0.000001) ]))
+
+ assert_empty ExchangeRate::UsdCross.new(@provider).rates(from: "AAA", to: "BBB", start_date: @day1, end_date: @day1)
+ end
+
+ test "is empty without asking the provider when it is rate limiting or rejecting requests" do
+ @provider.expects(:fetch_exchange_rates).never
+ cross = ExchangeRate::UsdCross.new(@provider)
+
+ [ Provider::TwelveData::RateLimitError.new("slow down"), Provider::YahooFinance::AuthenticationError.new("no crumb") ].each do |error|
+ assert_empty cross.rates(from: "KZT", to: "RUB", start_date: @day1, end_date: @day2, error: error)
+ end
+ end
+
+ test "skips days before the first USD rate" do
+ @provider.stubs(:fetch_exchange_rates).with(from: "KZT", to: "USD", start_date: @day1, end_date: @day2)
+ .returns(provider_success_response([ rate(@day1, "KZT", "USD", 0.002), rate(@day2, "KZT", "USD", 0.0022) ]))
+ @provider.stubs(:fetch_exchange_rates).with(from: "USD", to: "RUB", start_date: @day1, end_date: @day2)
+ .returns(provider_success_response([ rate(@day2, "USD", "RUB", 80) ]))
+
+ rates = ExchangeRate::UsdCross.new(@provider).rates(from: "KZT", to: "RUB", start_date: @day1, end_date: @day2)
+
+ assert_equal [ @day2 ], rates.map(&:date)
+ end
+
+ test "is empty without asking the provider when a side is USD" do
+ @provider.expects(:fetch_exchange_rates).never
+
+ assert_empty ExchangeRate::UsdCross.new(@provider).rates(from: "USD", to: "RUB", start_date: @day1, end_date: @day2)
+ assert_empty ExchangeRate::UsdCross.new(@provider).rates(from: "RUB", to: "USD", start_date: @day1, end_date: @day2)
+ end
+
+ test "is empty without asking a provider that cannot quote both USD legs" do
+ moex = Provider::MoexPublic.new
+ moex.expects(:fx_history).never
+
+ assert_empty ExchangeRate::UsdCross.new(moex).rates(from: "RUB", to: "KZT", start_date: @day1, end_date: @day2)
+ end
+
+ test "is empty without asking the provider for a pair it has quoted before" do
+ ExchangeRatePair.record_direct_quote(from: "KZT", to: "RUB")
+ @provider.expects(:fetch_exchange_rates).never
+
+ assert_empty ExchangeRate::UsdCross.new(@provider)
+ .rates(from: "KZT", to: "RUB", start_date: @day1, end_date: @day2, error: StandardError.new("timeout"))
+ end
+
+ test "is empty when the first leg fails, without fetching the second, and logs the leg" do
+ @provider.expects(:fetch_exchange_rates).once.returns(provider_error_response(StandardError.new("no pair")))
+
+ assert_difference -> { DebugLogEntry.where(category: "exchange_rates", level: "warn").count }, 1 do
+ assert_empty ExchangeRate::UsdCross.new(@provider).rates(from: "KZT", to: "RUB", start_date: @day1, end_date: @day2)
+ end
+
+ metadata = DebugLogEntry.where(category: "exchange_rates").recent.first.metadata
+ assert_equal({ "from" => "KZT", "to" => "USD", "error" => "no pair" }, metadata.slice("from", "to", "error"))
+ end
+
+ test "does not ask again for a pair whose first leg just failed, nor log it again" do
+ @provider.expects(:fetch_exchange_rates).once.returns(provider_error_response(StandardError.new("no pair")))
+ cross = ExchangeRate::UsdCross.new(@provider)
+
+ assert_empty cross.rates(from: "KZT", to: "RUB", start_date: @day1, end_date: @day2)
+
+ assert_no_difference -> { DebugLogEntry.where(category: "exchange_rates").count } do
+ assert_empty ExchangeRate::UsdCross.new(@provider).rates(from: "KZT", to: "RUB", start_date: @day1, end_date: @day2)
+ end
+ end
+
+ test "does not let a miss for other dates hide the pair" do
+ old_day = Date.new(2010, 1, 4)
+ @provider.stubs(:fetch_exchange_rates).with(from: "KZT", to: "USD", start_date: old_day, end_date: old_day)
+ .returns(provider_success_response([]))
+ @provider.stubs(:fetch_exchange_rates).with(from: "KZT", to: "USD", start_date: @day1, end_date: @day1)
+ .returns(provider_success_response([ rate(@day1, "KZT", "USD", 0.002) ]))
+ @provider.stubs(:fetch_exchange_rates).with(from: "USD", to: "RUB", start_date: @day1, end_date: @day1)
+ .returns(provider_success_response([ rate(@day1, "USD", "RUB", 80) ]))
+
+ assert_empty ExchangeRate::UsdCross.new(@provider).rates(from: "KZT", to: "RUB", start_date: old_day, end_date: old_day)
+ assert_equal 1, ExchangeRate::UsdCross.new(@provider).rates(from: "KZT", to: "RUB", start_date: @day1, end_date: @day1).size
+ end
+
+ test "remembers a pair whose second leg has no rates" do
+ @provider.expects(:fetch_exchange_rates).with(from: "KZT", to: "USD", start_date: @day1, end_date: @day2)
+ .returns(provider_success_response([ rate(@day1, "KZT", "USD", 0.002) ]))
+ @provider.expects(:fetch_exchange_rates).with(from: "USD", to: "RUB", start_date: @day1, end_date: @day2)
+ .returns(provider_error_response(StandardError.new("no pair")))
+
+ 2.times { assert_empty ExchangeRate::UsdCross.new(@provider).rates(from: "KZT", to: "RUB", start_date: @day1, end_date: @day2) }
+ end
+
+ test "asks again once the remembered miss expires, and a later success is derived" do
+ @provider.stubs(:fetch_exchange_rates).with(from: "KZT", to: "USD", start_date: @day1, end_date: @day2)
+ .returns(provider_error_response(StandardError.new("down"))).then
+ .returns(provider_success_response([ rate(@day1, "KZT", "USD", 0.002) ]))
+ @provider.expects(:fetch_exchange_rates).with(from: "USD", to: "RUB", start_date: @day1, end_date: @day2)
+ .returns(provider_success_response([ rate(@day1, "USD", "RUB", 80) ]))
+
+ assert_empty ExchangeRate::UsdCross.new(@provider).rates(from: "KZT", to: "RUB", start_date: @day1, end_date: @day2)
+
+ travel_to(ExchangeRate::UsdCross::MISS_TTL.from_now + 1.minute) do
+ rates = ExchangeRate::UsdCross.new(@provider).rates(from: "KZT", to: "RUB", start_date: @day1, end_date: @day2)
+ assert_equal [ 0.16 ], rates.map { |r| r.rate.to_f }
+ end
+ end
+
+ test "forgets a remembered miss when a lookup that began before it was recorded derives the pair" do
+ cache = ActiveSupport::Cache::MemoryStore.new
+ Rails.stubs(:cache).returns(cache)
+ key = "usd_cross_miss:#{@provider.class.name}:KZT:RUB:#{@day1}:#{@day1}"
+ cache.write(key, true)
+ cache.stubs(:exist?).with(key).returns(false)
+ @provider.stubs(:fetch_exchange_rates).with(from: "KZT", to: "USD", start_date: @day1, end_date: @day1)
+ .returns(provider_success_response([ rate(@day1, "KZT", "USD", 0.002) ]))
+ @provider.stubs(:fetch_exchange_rates).with(from: "USD", to: "RUB", start_date: @day1, end_date: @day1)
+ .returns(provider_success_response([ rate(@day1, "USD", "RUB", 80) ]))
+
+ assert_equal 1, ExchangeRate::UsdCross.new(@provider).rates(from: "KZT", to: "RUB", start_date: @day1, end_date: @day1).size
+ assert_not cache.read(key)
+ end
+
+ test "remembers a miss for its own provider and pair only" do
+ other = Provider::YahooFinance.new
+ @provider.expects(:fetch_exchange_rates).once.returns(provider_error_response(StandardError.new("no pair")))
+ other.expects(:fetch_exchange_rates).twice.returns(provider_error_response(StandardError.new("no pair")))
+
+ ExchangeRate::UsdCross.new(@provider).rates(from: "KZT", to: "RUB", start_date: @day1, end_date: @day2)
+ ExchangeRate::UsdCross.new(@provider).rates(from: "KZT", to: "RUB", start_date: @day1, end_date: @day2)
+ ExchangeRate::UsdCross.new(other).rates(from: "KZT", to: "RUB", start_date: @day1, end_date: @day2)
+ ExchangeRate::UsdCross.new(other).rates(from: "KZT", to: "PYG", start_date: @day1, end_date: @day2)
+ end
+
+ test "does not remember a leg that failed because the provider is rate limiting" do
+ @provider.expects(:fetch_exchange_rates).twice.returns(provider_error_response(Provider::TwelveData::RateLimitError.new("slow down")))
+
+ 2.times { assert_empty ExchangeRate::UsdCross.new(@provider).rates(from: "KZT", to: "RUB", start_date: @day1, end_date: @day2) }
+ end
+
+ test "remembers a miss when both USD legs have quotes but no shared dates" do
+ @provider.expects(:fetch_exchange_rates).with(from: "KZT", to: "USD", start_date: @day1, end_date: @day2).once
+ .returns(provider_success_response([ rate(@day1, "KZT", "USD", 0.002) ]))
+ @provider.expects(:fetch_exchange_rates).with(from: "USD", to: "RUB", start_date: @day1, end_date: @day2).once
+ .returns(provider_success_response([ rate(@day2, "USD", "RUB", 80) ]))
+
+ 2.times { assert_empty ExchangeRate::UsdCross.new(@provider).rates(from: "KZT", to: "RUB", start_date: @day1, end_date: @day2) }
+ end
+
+ private
+ def rate(date, from, to, value)
+ Provider::ExchangeRateConcept::Rate.new(date: date, from: from, to: to, rate: value)
+ end
+end
diff --git a/test/models/exchange_rate_pair_test.rb b/test/models/exchange_rate_pair_test.rb
index 4279ec49e6..2e36d56f54 100644
--- a/test/models/exchange_rate_pair_test.rb
+++ b/test/models/exchange_rate_pair_test.rb
@@ -40,6 +40,35 @@ class ExchangeRatePairTest < ActiveSupport::TestCase
end
end
+ test "record_direct_quote flags the pair for the current provider" do
+ ExchangeRatePair.delete_all
+
+ ExchangeRatePair.record_direct_quote(from: "KZT", to: "RUB", provider_name: "yahoo_finance")
+
+ pair = ExchangeRatePair.find_by!(from_currency: "KZT", to_currency: "RUB")
+ assert pair.quoted_directly?
+ assert_equal "yahoo_finance", pair.provider_name
+ end
+
+ test "record_direct_quote leaves a pair with a USD side alone, as it is never derived" do
+ ExchangeRatePair.delete_all
+
+ ExchangeRatePair.record_direct_quote(from: "USD", to: "EUR", provider_name: "yahoo_finance")
+ ExchangeRatePair.record_direct_quote(from: "EUR", to: "USD", provider_name: "yahoo_finance")
+
+ assert_equal 0, ExchangeRatePair.count
+ end
+
+ test "for_pair forgets a direct quote when the provider changes" do
+ ExchangeRatePair.delete_all
+ ExchangeRatePair.create!(from_currency: "KZT", to_currency: "RUB", quoted_directly: true, provider_name: "twelve_data")
+
+ refreshed = ExchangeRatePair.for_pair(from: "KZT", to: "RUB", provider_name: "yahoo_finance")
+
+ assert_not refreshed.quoted_directly?
+ assert_equal "yahoo_finance", refreshed.provider_name
+ end
+
test "for_pair resets clamp when the Twelve Data key is removed and Frankfurter takes over" do
ExchangeRatePair.delete_all
ExchangeRatePair.create!(
diff --git a/test/models/exchange_rate_test.rb b/test/models/exchange_rate_test.rb
index 988c44257d..5837111f32 100644
--- a/test/models/exchange_rate_test.rb
+++ b/test/models/exchange_rate_test.rb
@@ -86,6 +86,19 @@ class ExchangeRateTest < ActiveSupport::TestCase
end
end
+ test "keyless fallback records a direct quote under Frankfurter, so later lookups keep it" do
+ keyless_fallback(signed_in: false) do
+ ExchangeRatePair.where(from_currency: "SEK", to_currency: "NOK").delete_all
+ stub_request(:get, %r{/rate/SEK/NOK}).to_return(status: 200, body: { date: Date.current.to_s, base: "SEK", quote: "NOK", rate: 0.95 }.to_json)
+
+ ExchangeRate.find_or_fetch_rate(from: "SEK", to: "NOK", date: Date.current)
+ pair = ExchangeRatePair.for_pair(from: "SEK", to: "NOK")
+
+ assert_equal "frankfurter", pair.provider_name
+ assert pair.quoted_directly?
+ end
+ end
+
test "finds rate in DB" do
existing_rate = exchange_rates(:one)
@@ -134,6 +147,18 @@ class ExchangeRateTest < ActiveSupport::TestCase
assert_difference "ExchangeRate.count", 1 do
assert_equal 1.2, ExchangeRate.find_or_fetch_rate(from: "USD", to: "EUR", date: Date.current, cache: true).rate
end
+ assert_not ExchangeRatePair.exists?(from_currency: "USD", to_currency: "EUR")
+ end
+
+ test "records that the provider answered a pair with neither side USD" do
+ ExchangeRate.delete_all
+ ExchangeRatePair.delete_all
+ @provider.expects(:fetch_exchange_rate)
+ .returns(provider_success_response(OpenStruct.new(from: "KZT", to: "RUB", date: Date.current, rate: 0.16)))
+
+ ExchangeRate.find_or_fetch_rate(from: "KZT", to: "RUB", date: Date.current)
+
+ assert ExchangeRatePair.find_by!(from_currency: "KZT", to_currency: "RUB").quoted_directly?
end
test "returns nil on provider error" do
@@ -144,6 +169,80 @@ class ExchangeRateTest < ActiveSupport::TestCase
assert_nil ExchangeRate.find_or_fetch_rate(from: "USD", to: "EUR", date: Date.current, cache: true)
end
+ test "caches the latest cross on its shared observation date" do
+ ExchangeRate.delete_all
+ date = Date.current
+ common_date = date - 1
+ window = { start_date: date - ExchangeRate::Provided::NEAREST_RATE_LOOKBACK_DAYS, end_date: date }
+
+ @provider.expects(:fetch_exchange_rate).returns(provider_error_response(StandardError.new("no KZT/RUB")))
+ @provider.expects(:fetch_exchange_rates).with(from: "KZT", to: "USD", **window)
+ .returns(provider_success_response([
+ OpenStruct.new(from: "KZT", to: "USD", date: common_date, rate: 0.002),
+ OpenStruct.new(from: "KZT", to: "USD", date: date, rate: 0.0022)
+ ]))
+ @provider.expects(:fetch_exchange_rates).with(from: "USD", to: "RUB", **window)
+ .returns(provider_success_response([ OpenStruct.new(from: "USD", to: "RUB", date: common_date, rate: 80) ]))
+
+ assert_equal 0.16, ExchangeRate.find_or_fetch_rate(from: "KZT", to: "RUB", date: date).rate.to_f
+ assert_equal [ [ common_date, BigDecimal("0.16") ] ], ExchangeRate.where(from_currency: "KZT", to_currency: "RUB").pluck(:date, :rate)
+ end
+
+ test "does not ask Yahoo for the USD legs when its single lookup failed on authentication" do
+ ExchangeRate.delete_all
+ yahoo = Provider::YahooFinance.new
+ ExchangeRate.stubs(:provider).returns(yahoo)
+ auth = Provider::YahooFinance::AuthenticationError.new("no crumb")
+ yahoo.expects(:fetch_exchange_rates).once.returns(provider_error_response(auth))
+
+ assert_nil ExchangeRate.find_or_fetch_rate(from: "KZT", to: "RUB", date: Date.current)
+ end
+
+ test "asks for the USD legs once for a pair the provider lacks in every form" do
+ ExchangeRate.delete_all
+ Rails.stubs(:cache).returns(ActiveSupport::Cache::MemoryStore.new)
+ @provider.expects(:fetch_exchange_rate).twice.returns(provider_error_response(StandardError.new("no KZT/RUB")))
+ @provider.expects(:fetch_exchange_rates).once.returns(provider_error_response(StandardError.new("no KZT/USD")))
+
+ 2.times { assert_nil ExchangeRate.find_or_fetch_rate(from: "KZT", to: "RUB", date: Date.current) }
+ end
+
+ test "builds the provider once per lookup, so its throttle spaces the direct request and the legs" do
+ ExchangeRate.delete_all
+ ExchangeRate.unstub(:provider)
+ ExchangeRate.expects(:provider).once.returns(@provider)
+ @provider.expects(:fetch_exchange_rate).returns(provider_error_response(StandardError.new("no KZT/RUB")))
+ @provider.expects(:fetch_exchange_rates).once.returns(provider_error_response(StandardError.new("no KZT/USD")))
+
+ assert_nil ExchangeRate.find_or_fetch_rate(from: "KZT", to: "RUB", date: Date.current)
+ end
+
+ test "returns a derived rate without storing it when cache is false" do
+ ExchangeRate.delete_all
+ date = Date.current
+
+ @provider.expects(:fetch_exchange_rate).returns(provider_error_response(StandardError.new("no KZT/RUB")))
+ @provider.expects(:fetch_exchange_rates).with(from: "KZT", to: "USD", start_date: date - 5, end_date: date)
+ .returns(provider_success_response([ OpenStruct.new(from: "KZT", to: "USD", date: date, rate: 0.002) ]))
+ @provider.expects(:fetch_exchange_rates).with(from: "USD", to: "RUB", start_date: date - 5, end_date: date)
+ .returns(provider_success_response([ OpenStruct.new(from: "USD", to: "RUB", date: date, rate: 80) ]))
+
+ assert_no_difference "ExchangeRate.count" do
+ assert_equal 0.16, ExchangeRate.find_or_fetch_rate(from: "KZT", to: "RUB", date: date, cache: false).rate.to_f
+ end
+ end
+
+ test "does not derive and cache a pair the provider has quoted before when it fails" do
+ ExchangeRate.delete_all
+ ExchangeRatePair.record_direct_quote(from: "KZT", to: "RUB")
+
+ @provider.expects(:fetch_exchange_rate).returns(provider_error_response(StandardError.new("timeout")))
+ @provider.expects(:fetch_exchange_rates).never
+
+ assert_nil ExchangeRate.find_or_fetch_rate(from: "KZT", to: "RUB", date: Date.current)
+ assert_equal 0, ExchangeRate.count
+ end
+
test "reuses nearest cached rate within lookback window instead of calling provider" do
# Simulate a rate saved under Friday's date when Saturday is requested
friday = 1.day.ago.to_date
diff --git a/test/models/market_data_importer_test.rb b/test/models/market_data_importer_test.rb
index ed85e57597..bbacee8c0d 100644
--- a/test/models/market_data_importer_test.rb
+++ b/test/models/market_data_importer_test.rb
@@ -86,10 +86,11 @@ class MarketDataImporterTest < ActiveSupport::TestCase
account = family.accounts.create!(name: "Chequing", currency: "CAD", balance: 100, accountable: Depository.new)
account.entries.create!(date: 10.days.ago.to_date, amount: 10, currency: "GBP", name: "Card payment", entryable: Transaction.new)
- [ %w[GBP CAD], %w[GBP USD], %w[CAD USD] ].each do |from, to|
+ # GBP/CAD comes back empty, so GBP/USD is fetched again as its first USD leg.
+ { %w[GBP CAD] => 1, %w[GBP USD] => 2, %w[CAD USD] => 1 }.each do |(from, to), calls|
@provider.expects(:fetch_exchange_rates)
.with(from: from, to: to, start_date: anything, end_date: anything)
- .once
+ .times(calls)
.returns(provider_success_response([]))
end
diff --git a/test/models/provider/exchange_rate_concept_test.rb b/test/models/provider/exchange_rate_concept_test.rb
index 77ba8ffa6c..02519fe33f 100644
--- a/test/models/provider/exchange_rate_concept_test.rb
+++ b/test/models/provider/exchange_rate_concept_test.rb
@@ -79,6 +79,10 @@ class Provider::ExchangeRateConceptTest < ActiveSupport::TestCase
end
end
+ test "a provider may be asked for USD legs unless it says otherwise" do
+ assert StubProvider.new([ 1 ]).usd_cross?
+ 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
diff --git a/test/models/provider/frankfurter_test.rb b/test/models/provider/frankfurter_test.rb
index 79a522ea30..6b0e9221f5 100644
--- a/test/models/provider/frankfurter_test.rb
+++ b/test/models/provider/frankfurter_test.rb
@@ -54,6 +54,10 @@ class Provider::FrankfurterTest < ActiveSupport::TestCase
assert_equal "INR", response.data.to
end
+ test "usd_cross? is false, as Frankfurter converts any pair itself" do
+ assert_not @provider.usd_cross?
+ end
+
# ================================
# fetch_exchange_rate (GET /rate/{base}/{quote})
# ================================
diff --git a/test/models/provider/moex_public_test.rb b/test/models/provider/moex_public_test.rb
index e74ccc657e..fe82b4bab1 100644
--- a/test/models/provider/moex_public_test.rb
+++ b/test/models/provider/moex_public_test.rb
@@ -343,6 +343,10 @@ class Provider::MoexPublicTest < ActiveSupport::TestCase
assert_in_delta 12.4, cny.data.rate.to_f
end
+ test "usd_cross? is false, as only RUB pairs are quoted" do
+ assert_not @provider.usd_cross?
+ end
+
test "fetch_exchange_rates returns empty for a non-RUB-crossed pair" do
@provider.expects(:get_json).never
diff --git a/test/models/provider/yahoo_finance_test.rb b/test/models/provider/yahoo_finance_test.rb
index c6d2a3088b..457b9656d2 100644
--- a/test/models/provider/yahoo_finance_test.rb
+++ b/test/models/provider/yahoo_finance_test.rb
@@ -453,6 +453,29 @@ class Provider::YahooFinanceTest < ActiveSupport::TestCase
assert_equal date, rate.date
end
+ test "fetch_exchange_rate keeps a rate limit or authentication failure as its own error" do
+ date = Date.new(2026, 10, 22)
+
+ [ Provider::YahooFinance::RateLimitError.new("slow down"), Provider::YahooFinance::AuthenticationError.new("no crumb") ].each do |error|
+ @provider.stubs(:fetch_exchange_rates).returns(Provider::Response.new(success?: false, data: nil, error: error))
+
+ response = @provider.fetch_exchange_rate(from: "KZT", to: "RUB", date: date)
+
+ assert_not response.success?
+ assert_instance_of error.class, response.error
+ end
+ end
+
+ test "fetch_exchange_rate still wraps any other failure in a plain error" do
+ @provider.stubs(:fetch_exchange_rates)
+ .returns(Provider::Response.new(success?: false, data: nil, error: Provider::YahooFinance::Error.new("no chart")))
+
+ response = @provider.fetch_exchange_rate(from: "KZT", to: "RUB", date: Date.new(2026, 10, 22))
+
+ assert_instance_of Provider::YahooFinance::Error, response.error
+ assert_equal "Failed to fetch exchange rates: no chart", response.error.message
+ end
+
test "fetch_exchange_rate handles invalid currency codes" do
date = Date.parse("2024-01-15")
@@ -1103,6 +1126,18 @@ class Provider::YahooFinanceTest < ActiveSupport::TestCase
assert_nil result
end
+ test "fetch_exchange_rates reports a chart HTTP 429 as a rate limit, without trying the inverse symbol" do
+ @provider.stubs(:throttle_request)
+ @provider.expects(:fetch_authenticated_chart).once
+ .raises(Faraday::TooManyRequestsError.new("Too many requests", { body: "slow down" }))
+ DebugLogEntry.expects(:capture).with { |attributes| attributes[:metadata][:exception_class] == "Faraday::TooManyRequestsError" }
+
+ response = @provider.fetch_exchange_rates(from: "KZT", to: "USD", start_date: Date.new(2026, 10, 20), end_date: Date.new(2026, 10, 22))
+
+ assert_not response.success?
+ assert_instance_of Provider::YahooFinance::RateLimitError, response.error
+ end
+
# ================================
# Cookie/Crumb Authentication Tests
# ================================