Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Fix cache invalidation on currency change and account deletion (#4200) (#4235)

MD YASIN ALAM9884e617b26f
diff --git a/app/models/family.rb b/app/models/family.rb
index 564d24e9ae..fa2685ff0d 100644
--- a/app/models/family.rb
+++ b/app/models/family.rb
@@ -656,9 +656,10 @@ class Family < ApplicationRecord
[
id,
+ currency,
key,
data_invalidation_key,
- accounts.maximum(:updated_at)
+ accounts_status_version
].compact.join("_")
end
@@ -692,7 +693,8 @@ class Family < ApplicationRecord
# nothing on entries, but changes which entries `uncategorized_transactions`
# considers accessible).
def accounts_status_version
- "#{accounts.count}-#{accounts.maximum(:updated_at)&.to_f}"
+ count, max_at = accounts.pick(Arel.sql("count(*)"), Arel.sql('max("accounts"."updated_at")'))
+ "#{count}-#{max_at&.to_f}"
end
# Used for invalidating caches that render merchant name/logo for recurring
diff --git a/app/models/income_statement.rb b/app/models/income_statement.rb
index d038ac2228..bdf8120db2 100644
--- a/app/models/income_statement.rb
+++ b/app/models/income_statement.rb
@@ -305,14 +305,14 @@ class IncomeStatement
def family_stats(interval: "month")
@family_stats ||= {}
@family_stats[interval] ||= Rails.cache.fetch([
- "income_statement", "family_stats", family.id, user&.id, interval, included_account_ids_hash, family.entries_cache_version
+ "income_statement", "family_stats", family.id, user&.id, interval, included_account_ids_hash, *cache_freshness_key
]) { FamilyStats.new(family, interval:, account_ids: included_account_ids).call }
end
def category_stats(interval: "month")
@category_stats ||= {}
@category_stats[interval] ||= Rails.cache.fetch([
- "income_statement", "category_stats", family.id, user&.id, interval, included_account_ids_hash, family.entries_cache_version
+ "income_statement", "category_stats", family.id, user&.id, interval, included_account_ids_hash, *cache_freshness_key
]) { CategoryStats.new(family, interval:, account_ids: included_account_ids).call }
end
@@ -333,8 +333,10 @@ class IncomeStatement
# Rates and target currency can change without touching entries or accounts.
def cache_freshness_key
@cache_freshness_key ||= [
- family.entries_cache_version, family.accounts.maximum(:updated_at)&.to_i,
- family.currency, ExchangeRate.maximum(:updated_at)&.to_i
+ family.entries_cache_version,
+ family.accounts_status_version,
+ family.currency,
+ ExchangeRate.maximum(:updated_at)&.to_i
]
end
diff --git a/app/models/investment_statement.rb b/app/models/investment_statement.rb
index 31046e5b03..29d05bfaee 100644
--- a/app/models/investment_statement.rb
+++ b/app/models/investment_statement.rb
@@ -387,7 +387,7 @@ class InvestmentStatement
account_ids_hash = Digest::MD5.hexdigest(account_ids.sort.join(","))
Rails.cache.fetch([
- "investment_statement", "totals_query/v2", family.id, user&.id,
+ "investment_statement", "totals_query/v2", family.id, user&.id, family.currency,
account_ids_hash, date_range.begin, date_range.end, family.entries_cache_version
]) { Totals.new(family, account_ids: account_ids, date_range: date_range).call }
end
diff --git a/app/models/transaction/search.rb b/app/models/transaction/search.rb
index 1e5603f981..209362fea6 100644
--- a/app/models/transaction/search.rb
+++ b/app/models/transaction/search.rb
@@ -116,6 +116,7 @@ class Transaction::Search
def cache_key_base
[
family.id,
+ family.currency,
Digest::SHA256.hexdigest(attributes.sort.to_h.to_json), # cached by filters
family.entries_cache_version,
Digest::SHA256.hexdigest(family.tax_advantaged_account_ids.sort.to_json), # stable across processes
diff --git a/test/models/balance_sheet/net_worth_breakdown_series_builder_test.rb b/test/models/balance_sheet/net_worth_breakdown_series_builder_test.rb
index efe513025f..7e74c5e90f 100644
--- a/test/models/balance_sheet/net_worth_breakdown_series_builder_test.rb
+++ b/test/models/balance_sheet/net_worth_breakdown_series_builder_test.rb
@@ -99,6 +99,37 @@ class BalanceSheet::NetWorthBreakdownSeriesBuilderTest < ActiveSupport::TestCase
assert_includes builder.send(:cache_key, period), BalanceSheet::NetWorthBreakdownSeriesBuilder::CACHE_VERSION
end
+ test "cache key changes when the family currency changes" do
+ period = Period.last_30_days
+ before = builder.send(:cache_key, period)
+ @family.update!(currency: "EUR")
+ after = BalanceSheet::NetWorthBreakdownSeriesBuilder.new(@family.reload).send(:cache_key, period)
+
+ assert_not_equal before, after
+ end
+
+ test "cache key changes through the account deletion lifecycle and does not revert" do
+ period = Period.last_30_days
+
+ # Ensure @liability_account has the newest updated_at timestamp so deleting
+ # @asset_account causes accounts.maximum(:updated_at) to revert to the same timestamp.
+ @liability_account.touch
+ k0 = builder.send(:cache_key, period)
+
+ # Mark older account for deletion (K1)
+ @asset_account.mark_for_deletion!
+ k1 = BalanceSheet::NetWorthBreakdownSeriesBuilder.new(@family.reload).send(:cache_key, period)
+
+ # Destroy the account completely (K2, simulating DestroyJob)
+ @asset_account.destroy!
+ k2 = BalanceSheet::NetWorthBreakdownSeriesBuilder.new(@family.reload).send(:cache_key, period)
+
+ assert_not_equal k0, k1
+ assert_not_equal k1, k2
+ # Regression assertion for #4200: ensure key does not revert to pre-deletion state (k0)
+ assert_not_equal k0, k2
+ end
+
private
def builder
BalanceSheet::NetWorthBreakdownSeriesBuilder.new(@family)
diff --git a/test/models/balance_sheet/net_worth_series_builder_test.rb b/test/models/balance_sheet/net_worth_series_builder_test.rb
new file mode 100644
index 0000000000..2f53df7441
--- /dev/null
+++ b/test/models/balance_sheet/net_worth_series_builder_test.rb
@@ -0,0 +1,47 @@
+require "test_helper"
+
+class BalanceSheet::NetWorthSeriesBuilderTest < ActiveSupport::TestCase
+ include BalanceTestHelper
+
+ setup do
+ @family = families(:dylan_family)
+ @asset_account = accounts(:depository)
+ @liability_account = accounts(:credit_card)
+ end
+
+ test "net worth series cache key changes when the family currency changes" do
+ period = Period.last_30_days
+ before = builder.send(:cache_key, period)
+ @family.update!(currency: "EUR")
+ after = BalanceSheet::NetWorthSeriesBuilder.new(@family.reload).send(:cache_key, period)
+
+ assert_not_equal before, after
+ end
+
+ test "net worth series cache key changes through the account deletion lifecycle and does not revert" do
+ period = Period.last_30_days
+
+ # Ensure @liability_account has the newest updated_at timestamp so deleting
+ # @asset_account causes accounts.maximum(:updated_at) to revert to the same timestamp.
+ @liability_account.touch
+ k0 = builder.send(:cache_key, period)
+
+ # Mark older account for deletion (K1)
+ @asset_account.mark_for_deletion!
+ k1 = BalanceSheet::NetWorthSeriesBuilder.new(@family.reload).send(:cache_key, period)
+
+ # Destroy the account completely (K2, simulating DestroyJob)
+ @asset_account.destroy!
+ k2 = BalanceSheet::NetWorthSeriesBuilder.new(@family.reload).send(:cache_key, period)
+
+ assert_not_equal k0, k1
+ assert_not_equal k1, k2
+ # Regression assertion for #4200: ensure key does not revert to pre-deletion state (k0)
+ assert_not_equal k0, k2
+ end
+
+ private
+ def builder
+ BalanceSheet::NetWorthSeriesBuilder.new(@family)
+ end
+end
diff --git a/test/models/family_test.rb b/test/models/family_test.rb
index 057797cd5b..26cfff8105 100644
--- a/test/models/family_test.rb
+++ b/test/models/family_test.rb
@@ -2,6 +2,7 @@ require "test_helper"
class FamilyTest < ActiveSupport::TestCase
include SyncableInterfaceTest
+ include SqlQueryCapture
def setup
@syncable = families(:dylan_family)
@@ -240,6 +241,53 @@ class FamilyTest < ActiveSupport::TestCase
assert_not_equal before_destroy, family.reload.entries_cache_version
end
+ test "build_cache_key changes when family currency changes" do
+ family = families(:empty)
+ before = family.build_cache_key("test_key")
+ family.update!(currency: "EUR")
+ after = family.reload.build_cache_key("test_key")
+
+ assert_not_equal before, after
+ end
+
+ test "build_cache_key changes through the account deletion lifecycle and does not revert" do
+ family = families(:dylan_family)
+ newer_account = accounts(:credit_card)
+ older_account = accounts(:depository)
+
+ newer_account.touch
+ k0 = family.build_cache_key("test_key")
+
+ older_account.mark_for_deletion!
+ k1 = family.reload.build_cache_key("test_key")
+
+ older_account.destroy!
+ k2 = family.reload.build_cache_key("test_key")
+
+ assert_not_equal k0, k1
+ assert_not_equal k1, k2
+ # Regression assertion for #4200: ensure key does not revert to pre-deletion state (k0)
+ assert_not_equal k0, k2
+ end
+
+ test "build_cache_key remains unchanged when nothing relevant has changed" do
+ family = families(:dylan_family)
+ key1 = family.build_cache_key("test_key", invalidate_on_data_updates: true)
+ key2 = family.reload.build_cache_key("test_key", invalidate_on_data_updates: true)
+
+ assert_equal key1, key2
+ end
+
+ test "accounts_status_version fetches count and max updated_at in a single query" do
+ family = families(:dylan_family)
+ queries = capture_sql_queries do
+ family.accounts_status_version
+ end
+
+ account_queries = queries.grep(/FROM "accounts"/i)
+ assert_equal 1, account_queries.size, "accounts_status_version should execute only one query"
+ end
+
test "default currency comes from country ISO data" do
assert_equal "CAD", Family.default_currency_for_country("CA")
assert_equal "EUR", Family.default_currency_for_country("DE")
diff --git a/test/models/income_statement_test.rb b/test/models/income_statement_test.rb
index b1f7d71f9b..42155e1200 100644
--- a/test/models/income_statement_test.rb
+++ b/test/models/income_statement_test.rb
@@ -32,6 +32,98 @@ class IncomeStatementTest < ActiveSupport::TestCase
IncomeStatement.new(@family).daily_expense_series(period: period)
end
+ test "a new statement invalidates family_stats when the family currency changes" do
+ statement = IncomeStatement.new(@family)
+
+ Rails.stubs(:cache).returns(ActiveSupport::Cache::MemoryStore.new)
+ IncomeStatement::FamilyStats.expects(:new).twice.returns(stub(call: []))
+
+ statement.send(:family_stats)
+ @family.update!(currency: "EUR")
+ IncomeStatement.new(@family).send(:family_stats)
+ end
+
+ test "a new statement invalidates category_stats when the family currency changes" do
+ statement = IncomeStatement.new(@family)
+
+ Rails.stubs(:cache).returns(ActiveSupport::Cache::MemoryStore.new)
+ IncomeStatement::CategoryStats.expects(:new).twice.returns(stub(call: []))
+
+ statement.send(:category_stats)
+ @family.update!(currency: "EUR")
+ IncomeStatement.new(@family).send(:category_stats)
+ end
+
+ test "family_stats and category_stats are served from cache when nothing has changed" do
+ Rails.stubs(:cache).returns(ActiveSupport::Cache::MemoryStore.new)
+ IncomeStatement::FamilyStats.expects(:new).once.returns(stub(call: []))
+ IncomeStatement::CategoryStats.expects(:new).once.returns(stub(call: []))
+
+ statement1 = IncomeStatement.new(@family)
+ statement1.send(:family_stats)
+ statement1.send(:category_stats)
+
+ statement2 = IncomeStatement.new(@family.reload)
+ statement2.send(:family_stats)
+ statement2.send(:category_stats)
+ end
+
+ test "cache freshness key changes through account deletion lifecycle and does not revert" do
+ empty_account = @family.accounts.create!(
+ name: "Empty Account",
+ currency: @family.currency,
+ balance: 0,
+ accountable: Depository.new
+ )
+
+ @checking_account.touch
+ k0 = IncomeStatement.new(@family.reload).send(:cache_freshness_key)
+
+ empty_account.mark_for_deletion!
+ k1 = IncomeStatement.new(@family.reload).send(:cache_freshness_key)
+
+ empty_account.destroy!
+ k2 = IncomeStatement.new(@family.reload).send(:cache_freshness_key)
+
+ assert_not_equal k0, k1
+ assert_not_equal k1, k2
+ # Regression assertion for #4200: ensure key does not revert to pre-deletion state (k0)
+ assert_not_equal k0, k2
+ end
+
+ test "family_stats and category_stats caches invalidate across empty account deletion lifecycle without reverting" do
+ Rails.stubs(:cache).returns(ActiveSupport::Cache::MemoryStore.new)
+
+ travel_to Time.current do
+ @family.accounts.update_all(updated_at: 2.days.ago)
+ empty_account = @family.accounts.create!(
+ name: "Empty Account",
+ balance: 0,
+ currency: @family.currency,
+ accountable: Depository.new
+ )
+ empty_account.update_columns(updated_at: 2.days.ago)
+
+ # K0 (Initial) -> K1 (Pending Deletion) -> K2 (Destroyed): all 3 states must miss cache and recompute
+ IncomeStatement::FamilyStats.expects(:new).times(3).returns(stub(call: []))
+ IncomeStatement::CategoryStats.expects(:new).times(3).returns(stub(call: []))
+
+ # 1. Initial state (K0)
+ IncomeStatement.new(@family.reload).send(:family_stats)
+ IncomeStatement.new(@family.reload).send(:category_stats)
+
+ # 2. Marked for deletion (K1)
+ empty_account.update!(status: "pending_deletion")
+ IncomeStatement.new(@family.reload).send(:family_stats)
+ IncomeStatement.new(@family.reload).send(:category_stats)
+
+ # 3. Destroyed (K2) - must not revert back to K0's cached value
+ empty_account.destroy!
+ IncomeStatement.new(@family.reload).send(:family_stats)
+ IncomeStatement.new(@family.reload).send(:category_stats)
+ end
+ end
+
test "a new statement invalidates daily series when exchange rates change" do
statement = IncomeStatement.new(@family)
period = Period.last_30_days
diff --git a/test/models/investment_statement_test.rb b/test/models/investment_statement_test.rb
index 2f1182965e..cd4b30c1c6 100644
--- a/test/models/investment_statement_test.rb
+++ b/test/models/investment_statement_test.rb
@@ -723,6 +723,21 @@ class InvestmentStatementTest < ActiveSupport::TestCase
"the investment_accounts lookup backing current_holdings should only run once, even for the empty case"
end
+ test "totals cache invalidates when family currency changes" do
+ create_investment_account(balance: 500)
+ period = Period.last_30_days
+
+ Rails.stubs(:cache).returns(ActiveSupport::Cache::MemoryStore.new)
+ dummy_result = { contributions: 0, withdrawals: 0, dividends: 0, interest: 0, trades_count: 0 }
+ InvestmentStatement::Totals.expects(:new).twice.returns(stub(call: dummy_result))
+
+ statement = InvestmentStatement.new(@family)
+ statement.totals(period: period)
+
+ @family.update!(currency: "EUR")
+ InvestmentStatement.new(@family.reload).totals(period: period)
+ end
+
private
def create_investment_account(balance:, cash_balance: 0, currency: "USD")
@family.accounts.create!(
diff --git a/test/models/market_data_importer_test.rb b/test/models/market_data_importer_test.rb
index 93e70344cf..0ee171093c 100644
--- a/test/models/market_data_importer_test.rb
+++ b/test/models/market_data_importer_test.rb
@@ -4,11 +4,11 @@ require "ostruct"
class MarketDataImporterTest < ActiveSupport::TestCase
include ProviderTestHelper
- SNAPSHOT_START_DATE = MarketDataImporter::SNAPSHOT_DAYS.days.ago.to_date
SECURITY_PRICE_BUFFER = Security::Price::Importer::PROVISIONAL_LOOKBACK_DAYS.days
EXCHANGE_RATE_BUFFER = 5.days
setup do
+ travel_to Time.current
Security::Price.delete_all
ExchangeRate.delete_all
Trade.delete_all
@@ -32,15 +32,15 @@ class MarketDataImporterTest < ActiveSupport::TestCase
# Seed stale rate so only the next missing day is fetched
ExchangeRate.create!(from_currency: "CAD",
to_currency: "USD",
- date: SNAPSHOT_START_DATE,
+ date: snapshot_start_date,
rate: 2.0)
ExchangeRate.create!(from_currency: "USD",
to_currency: "CAD",
- date: SNAPSHOT_START_DATE,
+ date: snapshot_start_date,
rate: 0.5)
- expected_start_date = (SNAPSHOT_START_DATE + 1.day) - EXCHANGE_RATE_BUFFER
+ expected_start_date = (snapshot_start_date + 1.day) - EXCHANGE_RATE_BUFFER
end_date = Date.current.in_time_zone("America/New_York").to_date
# Only the forward pair (CAD→USD) should be fetched; inverse (USD→CAD) is computed automatically
@@ -50,7 +50,7 @@ class MarketDataImporterTest < ActiveSupport::TestCase
start_date: expected_start_date,
end_date: end_date)
.returns(provider_success_response([
- OpenStruct.new(from: "CAD", to: "USD", date: SNAPSHOT_START_DATE, rate: 1.5)
+ OpenStruct.new(from: "CAD", to: "USD", date: snapshot_start_date, rate: 1.5)
]))
before = ExchangeRate.count
@@ -103,7 +103,7 @@ class MarketDataImporterTest < ActiveSupport::TestCase
account.entries.create!(name: "Buy AAPL", date: 40.days.ago.to_date, amount: 100, currency: "USD", entryable: trade)
account.holdings.create!(security: security, date: Date.current, qty: 1, price: 100, amount: 100, currency: "USD")
- expected_start_date = SNAPSHOT_START_DATE - SECURITY_PRICE_BUFFER
+ expected_start_date = snapshot_start_date - SECURITY_PRICE_BUFFER
end_date = Date.current.in_time_zone("America/New_York").to_date
@provider.expects(:fetch_security_prices)
@@ -113,7 +113,7 @@ class MarketDataImporterTest < ActiveSupport::TestCase
end_date: end_date)
.returns(provider_success_response([
OpenStruct.new(security: security,
- date: SNAPSHOT_START_DATE,
+ date: snapshot_start_date,
price: 100,
currency: "USD")
]))
@@ -127,7 +127,7 @@ class MarketDataImporterTest < ActiveSupport::TestCase
MarketDataImporter.new(mode: :snapshot).import_security_prices
- assert_equal 1, Security::Price.where(security: security, date: SNAPSHOT_START_DATE).count
+ assert_equal 1, Security::Price.where(security: security, date: snapshot_start_date).count
end
test "fetches no prices for online securities without holdings or trades" do
@@ -239,4 +239,9 @@ class MarketDataImporterTest < ActiveSupport::TestCase
MarketDataImporter.new(mode: :full).import_security_prices
end
+
+ private
+ def snapshot_start_date
+ MarketDataImporter::SNAPSHOT_DAYS.days.ago.to_date
+ end
end
diff --git a/test/models/transaction/search_test.rb b/test/models/transaction/search_test.rb
index c16416faba..ee759e6580 100644
--- a/test/models/transaction/search_test.rb
+++ b/test/models/transaction/search_test.rb
@@ -453,6 +453,45 @@ class Transaction::SearchTest < ActiveSupport::TestCase
assert_equal Money.new(0, "USD"), totals.income_money
end
+ test "totals cache invalidates when family currency changes" do
+ create_transaction(
+ account: @checking_account,
+ amount: 100,
+ category: categories(:food_and_drink),
+ kind: "standard"
+ )
+
+ search_usd = Transaction::Search.new(@family, filters: {})
+ before_key = search_usd.cache_key_base
+ totals_usd = search_usd.totals
+
+ assert_equal Money.new(100, "USD"), totals_usd.expense_money
+
+ @family.update!(currency: "EUR")
+ search_eur = Transaction::Search.new(@family.reload, filters: {})
+ after_key = search_eur.cache_key_base
+ totals_eur = search_eur.totals
+
+ assert_not_equal before_key, after_key
+ assert_equal "EUR", totals_eur.expense_money.currency.iso_code
+ end
+
+ test "totals is served from cache when nothing has changed" do
+ cache = ActiveSupport::Cache::MemoryStore.new
+ Rails.stubs(:cache).returns(cache)
+
+ search1 = Transaction::Search.new(@family)
+ key1 = search1.cache_key_base
+ result1 = search1.totals
+
+ search2 = Transaction::Search.new(@family.reload)
+ key2 = search2.cache_key_base
+
+ assert_equal key1, key2
+ assert_not_nil cache.read("transaction_search_totals/v3/#{key2}")
+ assert_equal result1, search2.totals
+ end
+
test "category filter includes subcategories" do
# Create a transaction with the parent category
parent_entry = create_transaction(
diff --git a/test/system/accounts_sync_ui_test.rb b/test/system/accounts_sync_ui_test.rb
index bf66b2530c..83025f9190 100644
--- a/test/system/accounts_sync_ui_test.rb
+++ b/test/system/accounts_sync_ui_test.rb
@@ -6,10 +6,16 @@ class AccountsSyncUiTest < ApplicationSystemTestCase
# These tests control sync state explicitly; login must not start a new
# sync when fixtures were loaded before midnight.
@user.family.update!(auto_sync_on_login: false)
- Sync.for_family(@user.family).incomplete.destroy_all
+ Sync.incomplete.for_family(@user.family).destroy_all
# Exercise the previous-day fixture boundary without waiting for midnight.
@user.family.syncs.update_all(created_at: 1.day.ago)
sign_in @user
+ # Guard against background syncs enqueued during the login flow even when auto_sync_on_login is false
+ Sync.incomplete.for_family(@user.family).destroy_all
+ end
+
+ teardown do
+ Sync.incomplete.destroy_all
end
test "idle state shows a plain refresh trigger with no cancel control" do