Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

perf: memoize Family#balance_sheet/investment_statement, cache transactions-index side queries (#3058)

GFR3e79de5b640a
diff --git a/app/controllers/transactions_controller.rb b/app/controllers/transactions_controller.rb
index 0a7a53b679..c21d03a9b4 100644
--- a/app/controllers/transactions_controller.rb
+++ b/app/controllers/transactions_controller.rb
@@ -73,16 +73,21 @@ class TransactionsController < ApplicationController
Set.new
end
- @uncategorized_count = Current.accessible_entries.uncategorized_transactions.count
+ @uncategorized_count = Rails.cache.fetch(uncategorized_count_cache_key) do
+ Current.accessible_entries.uncategorized_transactions.count
+ end
# Load projected recurring transactions for next 10 days
- @projected_recurring = Current.family.recurring_transactions
- .accessible_by(Current.user)
- .active
- .where("next_expected_date <= ? AND next_expected_date >= ?",
- 10.days.from_now.to_date,
- Date.current)
- .includes(:merchant)
+ @projected_recurring = Rails.cache.fetch(projected_recurring_cache_key, expires_in: 1.day) do
+ Current.family.recurring_transactions
+ .accessible_by(Current.user)
+ .active
+ .where("next_expected_date <= ? AND next_expected_date >= ?",
+ 10.days.from_now.to_date,
+ Date.current)
+ .includes(:merchant)
+ .to_a
+ end
@breadcrumbs = [ [ t("breadcrumbs.home"), root_path ], [ t("breadcrumbs.transactions"), nil ] ]
end
@@ -446,6 +451,32 @@ class TransactionsController < ApplicationController
end
private
+ # Scoped by user (not just family) because Current.accessible_entries is
+ # user-scoped for family sharing (see Current#accessible_entries).
+ #
+ # Includes Family#accounts_status_version because `uncategorized_transactions`
+ # filters on account status (draft/active), and toggling an account's
+ # active status (AccountsController#toggle_active) doesn't touch `entries`
+ # or `AccountShare`, so it wouldn't otherwise bust this cache.
+ def uncategorized_count_cache_key
+ "transactions_uncategorized_count/v3/#{Current.family.id}/#{Current.user.id}/" \
+ "#{Current.family.entries_version}/#{Current.family.accounts_status_version}/#{Current.account_share_version}"
+ end
+
+ # Scoped additionally by Date.current since the "next 10 days" window is
+ # date-dependent and would otherwise return a stale window on a cache hit
+ # from an earlier day.
+ #
+ # Includes Family#recurring_transaction_merchants_version because the
+ # cached records are preloaded with :merchant and rendered with its
+ # name/logo, but editing a FamilyMerchant or a shared ProviderMerchant
+ # doesn't touch `recurring_transactions`.
+ def projected_recurring_cache_key
+ "transactions_projected_recurring/v5/#{Current.family.id}/#{Current.user.id}/#{Date.current}/" \
+ "#{Current.family.recurring_transactions_version}/#{Current.family.accounts_status_version}/" \
+ "#{Current.family.recurring_transaction_merchants_version}/#{Current.account_share_version}"
+ end
+
# The "Mark as Recurring" block is only ever rendered under these same
# conditions (see transactions/show.html.erb), so skip the extra query
# entirely when it won't be used — this runs on every show/failed-update
diff --git a/app/models/current.rb b/app/models/current.rb
index af9f14b770..c7bdd29cc6 100644
--- a/app/models/current.rb
+++ b/app/models/current.rb
@@ -32,4 +32,15 @@ class Current < ActiveSupport::CurrentAttributes
return family&.entries unless user
family.entries.joins(:account).merge(Account.accessible_by(user))
end
+
+ # Used for invalidating caches whose results depend on the current user's
+ # account-share access (e.g. the transactions index's uncategorized count
+ # and projected recurring list, which are scoped to accessible accounts).
+ # Changes whenever an AccountShare granting/revoking the user's access is
+ # created, updated, or destroyed.
+ def account_share_version
+ return "0-" unless user
+ shares = AccountShare.where(user: user)
+ "#{shares.count}-#{shares.maximum(:updated_at)&.to_f}"
+ end
end
diff --git a/app/models/family.rb b/app/models/family.rb
index 31b1b3671c..5964431d9a 100644
--- a/app/models/family.rb
+++ b/app/models/family.rb
@@ -340,9 +340,10 @@ class Family < ApplicationRecord
AutoMerchantDetector.new(self, transaction_ids: transaction_ids).auto_detect
end
- # Memoized per user: the layout renders the sidebar for desktop and mobile
- # (each with three tab panels), so one request asks for the balance sheet
- # many times; rebuilding it repeats the account/sync/exchange-rate queries.
+ # Memoized per user: the layout renders the account sidebar on every page
+ # (mobile + desktop, each with 3 tabs), so a single request can ask for the
+ # balance sheet many times. Rebuilding it repeats the account/sync/exchange-
+ # rate queries it depends on.
def balance_sheet(user: Current.user)
@balance_sheets ||= {}
@balance_sheets[user&.id] ||= BalanceSheet.new(self, user: user)
@@ -419,8 +420,10 @@ class Family < ApplicationRecord
end
end
+ # Memoized per user for the same reason as #balance_sheet above.
def investment_statement(user: Current.user)
- InvestmentStatement.new(self, user: user)
+ @investment_statements ||= {}
+ @investment_statements[user&.id] ||= InvestmentStatement.new(self, user: user)
end
def eu?
@@ -496,6 +499,48 @@ class Family < ApplicationRecord
end
end
+ # Used for invalidating caches keyed on entries (e.g. the transactions
+ # index's uncategorized count). Unlike #entries_cache_version, includes
+ # .count so a hard-deleted entry busts the cache even when it didn't hold
+ # the current max updated_at, and uses full-precision timestamps so two
+ # updates within the same second still produce distinct versions.
+ def entries_version
+ "#{entries.count}-#{entries.maximum(:updated_at)&.to_f}"
+ end
+
+ # Used for invalidating caches keyed on recurring transactions (e.g. the
+ # transactions index's projected recurring list). See #entries_version for
+ # why .count is included alongside the timestamp.
+ def recurring_transactions_version
+ "#{recurring_transactions.count}-#{recurring_transactions.maximum(:updated_at)&.to_f}"
+ end
+
+ # Used for invalidating caches whose results depend on which accounts are
+ # active/draft vs. disabled (e.g. AccountsController#toggle_active changes
+ # nothing on entries, but changes which entries `uncategorized_transactions`
+ # considers accessible).
+ def accounts_status_version
+ "#{accounts.count}-#{accounts.maximum(:updated_at)&.to_f}"
+ end
+
+ # Used for invalidating caches that render merchant name/logo for recurring
+ # transactions (e.g. the transactions index's projected recurring list).
+ # Recurring detection copies `transaction.merchant_id` (see
+ # RecurringTransaction::Identifier), which can point at either a
+ # family-owned FamilyMerchant or a shared ProviderMerchant -- editing either
+ # (e.g. a manual rename, or ProviderMerchant::Enhancer updating a shared
+ # provider merchant's name/logo) doesn't touch `recurring_transactions`.
+ # Scoped to only the merchants actually referenced by this family's
+ # recurring transactions, rather than all family merchants, so unrelated
+ # merchant edits don't bust the cache unnecessarily.
+ def recurring_transaction_merchants_version
+ merchant_ids = recurring_transactions.where.not(merchant_id: nil).distinct.pluck(:merchant_id)
+ return "0-" if merchant_ids.empty?
+
+ scope = Merchant.where(id: merchant_ids)
+ "#{scope.count}-#{scope.maximum(:updated_at)&.to_f}"
+ end
+
def self_hoster?
Rails.application.config.app_mode.self_hosted?
end
diff --git a/app/models/investment_statement.rb b/app/models/investment_statement.rb
index 8ef4209766..66c8d58144 100644
--- a/app/models/investment_statement.rb
+++ b/app/models/investment_statement.rb
@@ -64,20 +64,30 @@ class InvestmentStatement
# All current holdings across investment accounts. Holdings are returned in
# their native currency; callers that aggregate across accounts must convert
# to family currency via convert_to_family_currency.
+ #
+ # Memoized: top_holdings, allocation, unrealized_gains, unrealized_gains_trend,
+ # and day_change each call this, so an unmemoized version ran the same
+ # DISTINCT ON query up to 5x per dashboard/report request.
def current_holdings
- return Holding.none unless investment_accounts.any?
-
- # Get the latest holding for each security per account
- Holding
- .where(account_id: investment_account_ids)
- .where.not(qty: 0)
- .where(
- id: Holding
- .where(account_id: investment_account_ids)
- .select("DISTINCT ON (holdings.account_id, holdings.security_id) holdings.id")
- .order(Arel.sql("holdings.account_id, holdings.security_id, holdings.date DESC"))
- )
- .includes(:security, :account)
+ @current_holdings ||= begin
+ account_ids = investment_account_ids
+
+ if account_ids.any?
+ # Get the latest holding for each security per account
+ Holding
+ .where(account_id: account_ids)
+ .where.not(qty: 0)
+ .where(
+ id: Holding
+ .where(account_id: account_ids)
+ .select("DISTINCT ON (holdings.account_id, holdings.security_id) holdings.id")
+ .order(Arel.sql("holdings.account_id, holdings.security_id, holdings.date DESC"))
+ )
+ .includes(:security, :account)
+ else
+ Holding.none
+ end
+ end
end
# Top holdings by family-currency value
diff --git a/test/controllers/transactions_controller_test.rb b/test/controllers/transactions_controller_test.rb
index 4fed721ff2..045a54b109 100644
--- a/test/controllers/transactions_controller_test.rb
+++ b/test/controllers/transactions_controller_test.rb
@@ -1000,6 +1000,266 @@ end
"Expected transfer counterparty accounts to be preloaded"
end
+ test "index caches uncategorized_count and projected_recurring across requests" do
+ # Test environment uses null_store; swap in a memory store so the cache
+ # actually persists between the two requests below.
+ original_cache = Rails.cache
+ Rails.cache = ActiveSupport::Cache::MemoryStore.new
+
+ get transactions_url
+ assert_response :success
+
+ queries = capture_sql_queries { get transactions_url }
+ assert_response :success
+
+ # uncategorized_transactions is a scope (joins/wheres), so its name never
+ # appears in the generated SQL -- match the COUNT query it produces instead.
+ assert_empty queries.select { |q| q =~ /SELECT COUNT/i && q =~ /category_id.*IS NULL/i },
+ "second request with unchanged data should reuse the cached uncategorized count"
+ # Building the cache key itself still runs small COUNT/MAX queries against
+ # recurring_transactions (Family#recurring_transactions_version and
+ # #recurring_transaction_merchants_version), so match the projection query
+ # the cached block itself would run instead of the whole table name.
+ assert_empty queries.grep(/next_expected_date/i),
+ "second request with unchanged data should reuse the cached projected recurring lookup"
+ ensure
+ Rails.cache = original_cache
+ end
+
+ test "index uncategorized_count cache reflects new transactions immediately" do
+ original_cache = Rails.cache
+ Rails.cache = ActiveSupport::Cache::MemoryStore.new
+
+ get transactions_url
+ initial_count = rendered_uncategorized_count
+
+ account = @user.family.accounts.visible.first
+ account.entries.create!(
+ name: "New uncategorized transaction",
+ amount: 42,
+ currency: "USD",
+ date: Date.current,
+ entryable: Transaction.new
+ )
+
+ get transactions_url
+ updated_count = rendered_uncategorized_count
+
+ assert_equal initial_count + 1, updated_count,
+ "a new uncategorized transaction must be reflected without a stale cache read"
+ ensure
+ Rails.cache = original_cache
+ end
+
+ test "index uncategorized_count cache reflects categorizing a transaction immediately" do
+ original_cache = Rails.cache
+ Rails.cache = ActiveSupport::Cache::MemoryStore.new
+
+ entry = @user.family.accounts.visible.first.entries.create!(
+ name: "Needs a category",
+ amount: 42,
+ currency: "USD",
+ date: Date.current,
+ entryable: Transaction.new
+ )
+
+ get transactions_url
+ initial_count = rendered_uncategorized_count
+
+ entry.entryable.update!(category: categories(:food_and_drink))
+
+ get transactions_url
+ updated_count = rendered_uncategorized_count
+
+ assert_equal initial_count - 1, updated_count,
+ "categorizing a transaction must be reflected without a stale cache read"
+ ensure
+ Rails.cache = original_cache
+ end
+
+ test "index uncategorized_count cache is invalidated when account-share access is revoked" do
+ original_cache = Rails.cache
+ Rails.cache = ActiveSupport::Cache::MemoryStore.new
+
+ member = users(:family_member)
+ share = account_shares(:depository_shared_with_member)
+ share.account.entries.create!(
+ name: "Uncategorized on shared account",
+ amount: 42,
+ currency: "USD",
+ date: Date.current,
+ entryable: Transaction.new
+ )
+
+ sign_in member
+ get transactions_url
+ count_with_access = rendered_uncategorized_count
+ assert_operator count_with_access, :>, 0,
+ "the member should see the shared account's uncategorized transaction before revocation"
+
+ share.destroy!
+
+ get transactions_url
+ count_after_revocation = rendered_uncategorized_count
+
+ assert_operator count_after_revocation, :<, count_with_access,
+ "revoking account-share access must not leave a stale cached count that still includes the now-inaccessible account"
+ ensure
+ Rails.cache = original_cache
+ end
+
+ test "index projected_recurring cache is invalidated when account-share access is revoked" do
+ original_cache = Rails.cache
+ Rails.cache = ActiveSupport::Cache::MemoryStore.new
+
+ member = users(:family_member)
+ share = account_shares(:depository_shared_with_member)
+ recurring = recurring_transactions(:netflix_subscription)
+ assert_equal share.account_id, recurring.account_id,
+ "fixture assumption: the shared depository account has the netflix recurring charge"
+
+ merchant_name_pattern = /#{Regexp.escape(recurring.merchant.name)}/
+
+ sign_in member
+ get transactions_url
+ assert_match merchant_name_pattern, response.body,
+ "the member should see the shared account's recurring transaction before revocation"
+
+ share.destroy!
+
+ get transactions_url
+ assert_no_match merchant_name_pattern, response.body,
+ "revoking account-share access must not leave a stale cached projected-recurring list"
+ ensure
+ Rails.cache = original_cache
+ end
+
+ test "index projected_recurring cache reflects a merchant rename immediately" do
+ original_cache = Rails.cache
+ Rails.cache = ActiveSupport::Cache::MemoryStore.new
+
+ recurring = recurring_transactions(:netflix_subscription)
+ merchant = recurring.merchant
+
+ get transactions_url
+ assert_match(/#{Regexp.escape(merchant.name)}/, response.body,
+ "the recurring transaction should render with the merchant's original name")
+
+ merchant.update!(name: "Netflix Renamed")
+
+ get transactions_url
+ assert_match(/Netflix Renamed/, response.body,
+ "renaming the merchant must not leave a stale cached projected-recurring list")
+ ensure
+ Rails.cache = original_cache
+ end
+
+ test "index projected_recurring cache reflects a provider merchant update immediately" do
+ original_cache = Rails.cache
+ Rails.cache = ActiveSupport::Cache::MemoryStore.new
+
+ # Recurring detection copies transaction.merchant_id, which can point at a
+ # shared ProviderMerchant (not just a family-owned FamilyMerchant) -- e.g.
+ # ProviderMerchant::Enhancer updates these after the recurring row exists.
+ provider_merchant = ProviderMerchant.create!(name: "Provider Merchant Original", source: "enable_banking")
+ recurring = recurring_transactions(:netflix_subscription)
+ recurring.update!(merchant: provider_merchant, name: nil)
+
+ get transactions_url
+ assert_match(/Provider Merchant Original/, response.body,
+ "the recurring transaction should render with the provider merchant's original name")
+
+ provider_merchant.update!(name: "Provider Merchant Renamed")
+
+ get transactions_url
+ assert_match(/Provider Merchant Renamed/, response.body,
+ "updating the provider merchant must not leave a stale cached projected-recurring list")
+ ensure
+ Rails.cache = original_cache
+ end
+
+ test "index uncategorized_count cache reflects deleting an uncategorized transaction immediately" do
+ original_cache = Rails.cache
+ Rails.cache = ActiveSupport::Cache::MemoryStore.new
+
+ entry = @user.family.accounts.visible.first.entries.create!(
+ name: "Deleted while uncategorized",
+ amount: 42,
+ currency: "USD",
+ date: Date.current,
+ entryable: Transaction.new
+ )
+
+ get transactions_url
+ initial_count = rendered_uncategorized_count
+
+ entry.destroy!
+
+ get transactions_url
+ updated_count = rendered_uncategorized_count
+
+ assert_equal initial_count - 1, updated_count,
+ "deleting an uncategorized transaction must not leave a stale cached count"
+ ensure
+ Rails.cache = original_cache
+ end
+
+ test "index uncategorized_count cache reflects disabling an account immediately" do
+ original_cache = Rails.cache
+ Rails.cache = ActiveSupport::Cache::MemoryStore.new
+
+ account = @user.family.accounts.visible.first
+ account.entries.create!(
+ name: "Uncategorized on account about to be disabled",
+ amount: 42,
+ currency: "USD",
+ date: Date.current,
+ entryable: Transaction.new
+ )
+
+ get transactions_url
+ initial_count = rendered_uncategorized_count
+ assert_operator initial_count, :>, 0
+
+ account.disable!
+
+ get transactions_url
+ updated_count = rendered_uncategorized_count
+
+ assert_operator updated_count, :<, initial_count,
+ "disabling an account must not leave a stale cached count that still includes its transactions"
+ ensure
+ Rails.cache = original_cache
+ end
+
+ test "index uncategorized_count cache is scoped per user, not just per family" do
+ original_cache = Rails.cache
+ Rails.cache = ActiveSupport::Cache::MemoryStore.new
+
+ # family_member has no share on this account (see test/fixtures/account_shares.yml),
+ # so only the admin can see its uncategorized transaction.
+ accounts(:other_asset).entries.create!(
+ name: "Admin-only uncategorized transaction",
+ amount: 42,
+ currency: "USD",
+ date: Date.current,
+ entryable: Transaction.new
+ )
+
+ get transactions_url
+ admin_count = rendered_uncategorized_count
+ assert_operator admin_count, :>, 0
+
+ sign_in users(:family_member)
+ get transactions_url
+ member_count = rendered_uncategorized_count
+
+ assert_not_equal admin_count, member_count,
+ "a member without access to the admin-only account must not reuse the admin's cached uncategorized count"
+ ensure
+ Rails.cache = original_cache
+ end
+
private
def rendered_entry_ids
css_select("turbo-frame[id^='entry_']").map { |node| node["id"].delete_prefix("entry_") }
@@ -1009,6 +1269,13 @@ end
sql.to_s.squish.gsub(/[`"]/, "").downcase
end
+ # The "Categorize (N)" menu item only renders when @uncategorized_count
+ # is positive, so an absent match means the count is 0.
+ def rendered_uncategorized_count
+ match = response.body.match(/Categorize \((\d+)\)/)
+ match ? match[1].to_i : 0
+ end
+
# Per-row lazy loads use `column = ?`. Do not treat `IN (...)` as lazy
# loads — ActiveRecord nested preloads also use single-value IN when only
# one associated record is needed (e.g. one counterparty account).
diff --git a/test/models/family_test.rb b/test/models/family_test.rb
index 481a13f3e8..53ffadd0ed 100644
--- a/test/models/family_test.rb
+++ b/test/models/family_test.rb
@@ -428,6 +428,34 @@ class FamilyTest < ActiveSupport::TestCase
assert family.save
end
+ test "balance_sheet memoizes per user for the same family instance" do
+ family = families(:dylan_family)
+ admin = users(:family_admin)
+ member = users(:family_member)
+
+ first_call_for_admin = family.balance_sheet(user: admin)
+
+ assert_same first_call_for_admin, family.balance_sheet(user: admin),
+ "repeated calls for the same user must reuse the same BalanceSheet instance"
+
+ refute_same first_call_for_admin, family.balance_sheet(user: member),
+ "different users must not share a memoized BalanceSheet (family sharing scoping)"
+ end
+
+ test "investment_statement memoizes per user for the same family instance" do
+ family = families(:dylan_family)
+ admin = users(:family_admin)
+ member = users(:family_member)
+
+ first_call_for_admin = family.investment_statement(user: admin)
+
+ assert_same first_call_for_admin, family.investment_statement(user: admin),
+ "repeated calls for the same user must reuse the same InvestmentStatement instance"
+
+ refute_same first_call_for_admin, family.investment_statement(user: member),
+ "different users must not share a memoized InvestmentStatement (family sharing scoping)"
+ end
+
private
def set_preview_features(user, enabled)
user.update!(preferences: (user.preferences || {}).merge("preview_features_enabled" => enabled))
diff --git a/test/models/investment_statement_test.rb b/test/models/investment_statement_test.rb
index 18d4ef51fc..232eecc7ab 100644
--- a/test/models/investment_statement_test.rb
+++ b/test/models/investment_statement_test.rb
@@ -268,6 +268,38 @@ class InvestmentStatementTest < ActiveSupport::TestCase
assert_no_match(/JOIN accounts/, aggregate_queries.first)
end
+ test "current_holdings memoizes so repeated dashboard-style calls issue a single query" do
+ account = create_investment_account(balance: 2100, currency: "USD")
+ security = Security.create!(ticker: "AAPL", name: "Apple")
+
+ Holding.create!(
+ account: account, security: security, date: Date.current,
+ qty: 10, price: 210, amount: 2100, currency: "USD"
+ )
+
+ queries = capture_sql_queries do
+ @statement.current_holdings
+ @statement.top_holdings(limit: 5)
+ @statement.allocation
+ @statement.day_change
+ end
+
+ holdings_queries = queries.grep(/DISTINCT ON \(holdings\.account_id, holdings\.security_id\)/)
+ assert_equal 1, holdings_queries.size,
+ "current_holdings should only run its DISTINCT ON query once per instance, not once per caller"
+ end
+
+ test "current_holdings memoizes the empty (no investment accounts) case too" do
+ queries = capture_sql_queries do
+ @statement.current_holdings
+ @statement.current_holdings
+ end
+
+ account_queries = queries.grep(/FROM "accounts"/)
+ assert_equal 1, account_queries.size,
+ "the investment_accounts lookup backing current_holdings should only run once, even for the empty case"
+ end
+
private
def create_investment_account(balance:, cash_balance: 0, currency: "USD")
@family.accounts.create!(