The personal finance app for everyone (by everyone)
Ruby
Speed up Reports, transactions and account pages (#5377)
jezmorea5e59786ab5
diff --git a/app/controllers/reports_controller.rb b/app/controllers/reports_controller.rbindex 54658f72af..52f1921e56 100644--- a/app/controllers/reports_controller.rb+++ b/app/controllers/reports_controller.rb@@ -637,10 +637,11 @@ class ReportsController < ApplicationControllerdef build_gains_by_tax_treatment(investment_statement)currency = Current.family.currency- # Eager-load account and accountable to avoid N+1 when accessing tax_treatment- current_holdings = investment_statement.current_holdings- .includes(account: :accountable)- .to_a+ # The card's holdings, average costs already read in one query (the trends+ # below would otherwise run them per holding), plus each account's+ # accountable for its tax treatment.+ current_holdings = investment_statement.holdings_with_avg_costs+ ActiveRecord::Associations::Preloader.new(records: current_holdings, associations: { account: :accountable }).call# Group holdings by tax treatment (from account)holdings_by_treatment = current_holdings.group_by { |h| h.account.tax_treatment || :taxable }@@ -651,18 +652,9 @@ class ReportsController < ApplicationController.includes(:security, entry: { account: :accountable }).to_a- # Preload holdings for all accounts that have sell trades to avoid N+1 in realized_gain_loss- account_ids = sell_trades.map { |t| t.entry.account_id }.uniq- holdings_by_account = Holding- .where(account_id: account_ids)- .where("date <= ?", @period.date_range.end)- .order(date: :desc)- .group_by(&:account_id)-- # Inject preloaded holdings into trades for realized_gain_loss calculation- sell_trades.each do |trade|- trade.instance_variable_set(:@preloaded_holdings, holdings_by_account[trade.entry.account_id] || [])- end+ # Each sale's basis position in one query, before the rates: the rate+ # preload keys on the currency that position is carried in.+ Trade.preload_basis_holdings(sell_trades)# What each fifo sale took from which lot, read once for the whole set.lot_disposals = HoldingLotDisposal.readable_by_sale(sell_trades)@@ -707,7 +699,7 @@ class ReportsController < ApplicationControllerforeign_trade_currencies = (sell_trades.map(&:currency) +sell_trades.map { |t| t.entry.account.currency } +- holdings_by_account.values.flatten.map(&:currency)+ sell_trades.map(&:preloaded_basis_currency)).compact.uniq.reject { |c| c == currency }rates_by_trade_date = sell_trades.map { |t| t.entry.date }.uniq.each_with_object({}) do |date, memo|memo[date] = ExchangeRate.rates_for(foreign_trade_currencies, to: currency, date: date)diff --git a/app/models/family/auto_transfer_matchable.rb b/app/models/family/auto_transfer_matchable.rbindex 575cdf87c9..454b858eff 100644--- a/app/models/family/auto_transfer_matchable.rb+++ b/app/models/family/auto_transfer_matchable.rb@@ -51,6 +51,7 @@ module Family::AutoTransferMatchable)date_window = coerce_transfer_match_date_window!(date_window)exchange_rate_tolerance = coerce_transfer_match_exchange_rate_tolerance!(exchange_rate_tolerance)+ window_start, window_end = transfer_match_window(transaction_ids, date_window) if transaction_ids.present?Entry.find_by_sql([transfer_match_candidates_sql,@@ -64,6 +65,8 @@ module Family::AutoTransferMatchablefilter_transaction_ids: !transaction_ids.nil?,# IN () is invalid SQL, so an empty list binds a NULL that matches nothing.transaction_ids: transaction_ids.presence || [ nil ],+ window_start:,+ window_end:,include_rejected:,restrict_cross_currency_to_linked_accounts:,require_common_writer:,@@ -257,6 +260,17 @@ module Family::AutoTransferMatchable)end+ # Both legs of any pair that touches one of `transaction_ids` lie within+ # `date_window` days of that transaction, so within the ids' date span+ # widened by the window. The id filter spans both legs and only applies+ # once pairs are formed; this range narrows each leg before the join and+ # drops no pair the id filter would keep. nil when none of the ids exist.+ def transfer_match_window(transaction_ids, date_window)+ first, last = Entry.where(entryable_type: "Transaction", entryable_id: transaction_ids)+ .pick(Arel.sql("MIN(entries.date)"), Arel.sql("MAX(entries.date)"))+ [ first - date_window, last + date_window ] if first+ end+def coerce_transfer_match_date_window!(value)Integer(value)rescue ArgumentError, TypeError@@ -412,6 +426,10 @@ module Family::AutoTransferMatchable(:inflow_transaction_id IS NULL OR inflow_candidates.entryable_id = :inflow_transaction_id) AND(:outflow_transaction_id IS NULL OR outflow_candidates.entryable_id = :outflow_transaction_id) AND(:filter_transaction_ids = FALSE OR inflow_candidates.entryable_id IN (:transaction_ids) OR outflow_candidates.entryable_id IN (:transaction_ids)) AND+ (:window_start IS NULL OR (+ inflow_candidates.date BETWEEN :window_start AND :window_end AND+ outflow_candidates.date BETWEEN :window_start AND :window_end+ )) AND(:include_rejected = TRUE OR rejected_transfers.id IS NULL) AND#{provider_exclusion_condition} AND#{common_writer_condition_sql}@@ -499,6 +517,10 @@ module Family::AutoTransferMatchable(:inflow_transaction_id IS NULL OR inflow_candidates.entryable_id = :inflow_transaction_id) AND(:outflow_transaction_id IS NULL OR outflow_candidates.entryable_id = :outflow_transaction_id) AND(:filter_transaction_ids = FALSE OR inflow_candidates.entryable_id IN (:transaction_ids) OR outflow_candidates.entryable_id IN (:transaction_ids)) AND+ (:window_start IS NULL OR (+ inflow_candidates.date BETWEEN :window_start AND :window_end AND+ outflow_candidates.date BETWEEN :window_start AND :window_end+ )) AND(:include_rejected = TRUE OR rejected_transfers.id IS NULL) AND(:restrict_cross_currency_to_linked_accounts = FALSE ORdiff --git a/app/models/investment_flow_statement.rb b/app/models/investment_flow_statement.rbindex 964897dfb2..ce90b9ac87 100644--- a/app/models/investment_flow_statement.rb+++ b/app/models/investment_flow_statement.rb@@ -21,10 +21,14 @@ class InvestmentFlowStatement# Get contribution/withdrawal totals for a perioddef period_totals(period: Period.current_month)- base = family.transactions+ # From Transaction rather than family.transactions: `visible` joins the+ # entry and its account itself, and the association's own copies of those+ # joins left the date filter on one copy only, so Postgres matched every+ # candidate transaction against every transaction entry of the family.+ base = Transaction.visible.excluding_pending- .where(entries: { date: period.date_range })+ .where(entries: { account_id: family.accounts.select(:id), date: period.date_range }).where(investment_activity_label: %w[Contribution Withdrawal])scope = base.where(kind: %w[standard investment_contribution])diff --git a/app/models/trade.rb b/app/models/trade.rbindex d5b6e7a33f..5f7b4155f0 100644--- a/app/models/trade.rb+++ b/app/models/trade.rb@@ -180,6 +180,48 @@ class Trade < ApplicationRecordtrades.each { |trade| trade.preloaded_exchange_rates = rates }end+ # Set by callers that list many sales: the holdings this sale's basis is read+ # from. Authoritative once set, so an empty list means there is no position+ # to measure against, not that one should be looked up.+ def preloaded_holdings=(value)+ @preloaded_holdings = value+ remove_instance_variable(:@realized_gain_loss) if defined?(@realized_gain_loss)+ end++ # Each disposal's basis position, for a whole set in one query: per trade,+ # its security's latest holding on or before the trade date. Loading the+ # accounts' holdings instead reads a row per security per day of their whole+ # history, which on a long-lived brokerage account is hundreds of thousands.+ # A same-day tie (another currency, as a security remap can leave) resolves+ # as basis_holding does: the account's currency, then the lower id.+ def self.preload_basis_holdings(trades)+ return if trades.empty?++ wanted = [ trades.map { |t| t.entry.id }, trades.map { |t| t.entry.account_id },+ trades.map(&:security_id), trades.map { |t| t.entry.date } ]+ holdings = Holding.find_by_sql([ <<~SQL.squish, *wanted ])+ SELECT basis.*, wanted.entry_id AS basis_for_entry_id+ FROM unnest(ARRAY[?]::uuid[], ARRAY[?]::uuid[], ARRAY[?]::uuid[], ARRAY[?]::date[])+ AS wanted(entry_id, account_id, security_id, date)+ CROSS JOIN LATERAL (+ SELECT holdings.* FROM holdings+ JOIN accounts ON accounts.id = holdings.account_id+ WHERE holdings.account_id = wanted.account_id+ AND holdings.security_id = wanted.security_id+ AND holdings.date <= wanted.date+ ORDER BY holdings.date DESC, (holdings.currency = accounts.currency) DESC, holdings.id+ LIMIT 1+ ) AS basis+ SQL++ # A sale is measured against its holding's average cost, which for a+ # position without a stored basis is two or more queries each.+ Holding.preload_avg_costs(holdings)++ by_entry = holdings.index_by { |holding| holding["basis_for_entry_id"] }+ trades.each { |trade| trade.preloaded_holdings = Array(by_entry[trade.entry.id]) }+ end+# The currency this disposal's basis is carried in, where it can be answered# without a query. `Holding#avg_cost` is Money in the HOLDING's own currency,# which is not always the account's, and that is what the proceeds are@@ -273,20 +315,25 @@ class Trade < ApplicationRecord## Uses preloaded holdings when the caller set them, and treats a# defined-but-empty preload as authoritative rather than falling back to a- # query. `select` + `max_by` rather than `find`, so the answer does not- # depend on the order the caller's array happens to be in.+ # query. The answer never depends on the order the caller's array happens+ # to be in: two snapshots on the latest date (another currency, as a+ # security remap can leave) resolve to the account's currency, then the+ # lower id, the same rule as Trade.preload_basis_holdings.# Not memoised: `realized_gain_loss` already is, and a memo here would hold# a holding selected before a caller set `@preloaded_holdings`.def basis_holdingif defined?(@preloaded_holdings)- (@preloaded_holdings || [])- .select { |h| h.security_id == security_id && h.date <= entry.date }- .max_by(&:date)+ candidates = (@preloaded_holdings || []).select { |h| h.security_id == security_id && h.date <= entry.date }+ latest = candidates.map(&:date).max+ tied = candidates.select { |h| h.date == latest }+ tied.one? ? tied.first : tied.min_by { |h| [ h.currency == entry.account.currency ? 0 : 1, h.id ] }elseentry.account.holdings.where(security_id: security_id).where("date <= ?", entry.date).order(date: :desc)+ .order(Arel.sql(Holding.sanitize_sql_array([ "holdings.currency = ? DESC", entry.account.currency ])))+ .order(:id).firstendenddiff --git a/db/migrate/20261120050000_add_entryable_index_to_entries.rb b/db/migrate/20261120050000_add_entryable_index_to_entries.rbnew file mode 100644index 0000000000..3930ecac43--- /dev/null+++ b/db/migrate/20261120050000_add_entryable_index_to_entries.rb@@ -0,0 +1,10 @@+class AddEntryableIndexToEntries < ActiveRecord::Migration[8.1]+ disable_ddl_transaction!++ # Every lookup of an entry from its transaction, trade or valuation filters on+ # both columns, and the entryable_type index alone has a handful of values,+ # so each one scanned that type's entries across every family.+ def change+ add_index :entries, [ :entryable_type, :entryable_id ], algorithm: :concurrently, if_not_exists: true+ end+enddiff --git a/db/schema.rb b/db/schema.rbindex 0b51adc2d3..a2072288c3 100644--- a/db/schema.rb+++ b/db/schema.rb@@ -10,7 +10,7 @@## It's strongly recommended that you check this file into your version control system.-ActiveRecord::Schema[8.1].define(version: 2026_11_19_120000) do+ActiveRecord::Schema[8.1].define(version: 2026_11_20_050000) do# These are extensions that must be enabled in order to support this databaseenable_extension "pg_catalog.plpgsql"enable_extension "pgcrypto"@@ -724,6 +724,7 @@ ActiveRecord::Schema[8.1].define(version: 2026_11_19_120000) dot.index ["currency", "amount", "date", "account_id"], name: "index_entries_on_transfer_match_lookup", where: "(((entryable_type)::text = 'Transaction'::text) AND (excluded = false))"t.index ["date"], name: "index_entries_on_date"t.index ["entryable_type"], name: "index_entries_on_entryable_type"+ t.index ["entryable_type", "entryable_id"], name: "index_entries_on_entryable_type_and_entryable_id"t.index ["import_id"], name: "index_entries_on_import_id"t.index ["import_locked"], name: "index_entries_on_import_locked_true", where: "(import_locked = true)"t.index ["parent_entry_id"], name: "index_entries_on_parent_entry_id"diff --git a/test/models/family/auto_transfer_matchable_test.rb b/test/models/family/auto_transfer_matchable_test.rbindex 33d86a3b9d..18da376ff0 100644--- a/test/models/family/auto_transfer_matchable_test.rb+++ b/test/models/family/auto_transfer_matchable_test.rb@@ -22,6 +22,23 @@ class Family::AutoTransferMatchableTest < ActiveSupport::TestCaseendend+ # Candidates for a page of transactions are searched within the page's date+ # span widened by the match window, so a counterpart at the far edge of the+ # window, outside the page's own dates, must still be found -- on either side.+ test "candidates for given transactions reach a counterpart at the edge of the window" do+ outflow = create_transaction(date: Date.new(2026, 3, 10), account: @depository, amount: 432.10)+ early_inflow = create_transaction(date: Date.new(2026, 3, 6), account: @credit_card, amount: -432.10)+ late_inflow = create_transaction(date: Date.new(2026, 3, 14), account: @other_asset, amount: -432.10)+ beyond = create_transaction(date: Date.new(2026, 3, 15), account: @loan, amount: -432.10)++ pairs = @family.transfer_match_candidates(date_window: 4, transaction_ids: [ outflow.entryable_id ])+ .map { |candidate| [ candidate.inflow_transaction_id, candidate.outflow_transaction_id ] }++ assert_includes pairs, [ early_inflow.entryable_id, outflow.entryable_id ]+ assert_includes pairs, [ late_inflow.entryable_id, outflow.entryable_id ]+ assert_not_includes pairs, [ beyond.entryable_id, outflow.entryable_id ], "five days apart is outside a four-day window"+ end+test "auto-matched transfers wait for confirmation before changing transaction kinds" dooutflow_entry = create_transaction(date: Date.current, account: @depository, amount: 500)inflow_entry = create_transaction(date: Date.current, account: accounts(:investment), amount: -500)diff --git a/test/models/trade_test.rb b/test/models/trade_test.rbindex c74613ea6d..29963288c5 100644--- a/test/models/trade_test.rb+++ b/test/models/trade_test.rb@@ -112,11 +112,10 @@ class TradeTest < ActiveSupport::TestCasecreate_trade(security, account: account, qty: -2, date: date, price: 150, currency: "EUR").entryableend- # The ivar directly, as ReportsController does on this branch -- there is- # no public writer for it upstream yet. Outside the capture on purpose: the- # cost being counted is the rates', not the holdings'.+ # Outside the capture on purpose: the cost being counted is the rates', not+ # the holdings'.holdings = account.holdings.to_a- trades.each { |trade| trade.instance_variable_set(:@preloaded_holdings, holdings) }+ trades.each { |trade| trade.preloaded_holdings = holdings }queries = capture_sql_queries doTrade.preload_exchange_rates(trades)@@ -146,7 +145,7 @@ class TradeTest < ActiveSupport::TestCaseendholdings = account.holdings.to_a- trades.each { |trade| trade.instance_variable_set(:@preloaded_holdings, holdings) }+ trades.each { |trade| trade.preloaded_holdings = holdings }queries = capture_sql_queries doTrade.preload_exchange_rates(trades)@@ -160,6 +159,91 @@ class TradeTest < ActiveSupport::TestCaseassert_equal [ BigDecimal(40) ] * 4, trades.map { |t| t.realized_gain_loss.value.amount }end+ # A sale is measured against its security's latest position on or before the+ # sale: one row. Preloading used to read every holding of the sale's account+ # instead, a row per security per day of its history.+ test "preloading reads each disposal's basis position in one query" do+ account, security = cross_currency_account+ other = Security.create!(ticker: "OTH#{SecureRandom.hex(3)}", name: "Other")++ (0..9).each do |offset|+ date = Date.new(2026, 3, 1) + offset+ account.holdings.create!(security: security, date: date, qty: 5, price: 150,+ amount: BigDecimal(750), currency: "USD", cost_basis: 100 + offset)+ account.holdings.create!(security: other, date: date, qty: 5, price: 10,+ amount: BigDecimal(50), currency: "USD", cost_basis: 8)+ end+ early = create_trade(security, account: account, qty: -2, date: Date.new(2026, 3, 3), price: 150, currency: "USD").entryable+ late = create_trade(security, account: account, qty: -2, date: Date.new(2026, 3, 20), price: 150, currency: "USD").entryable+ unheld = create_trade(Security.create!(ticker: "NEW#{SecureRandom.hex(3)}", name: "Never held"),+ account: account, qty: -1, date: Date.new(2026, 3, 5), price: 10, currency: "USD").entryable+ trades = Trade.where(id: [ early, late, unheld ].map(&:id)).includes(:entry).to_a++ queries = capture_sql_queries { Trade.preload_basis_holdings(trades) }.grep(/holdings/)++ assert_equal 1, queries.size, "three disposals cost one holdings query, not one each"+ by_id = trades.index_by(&:id)+ # The position on the sale's own date, and for a sale after the last+ # snapshot the last one: never a later day's, nor another security's.+ assert_equal BigDecimal(2 * 150 - 2 * 102), by_id[early.id].realized_gain_loss.value.amount+ assert_equal BigDecimal(2 * 150 - 2 * 109), by_id[late.id].realized_gain_loss.value.amount+ assert_no_queries_matching(/holdings/) { by_id[unheld.id].realized_gain_loss }+ end++ # A basis holding without a stored cost basis falls back to averaging its+ # buys, which on its own is several queries per sale.+ test "preloading reads the basis positions' average costs in the same pass" do+ account, security = cross_currency_account+ create_trade(security, account: account, qty: 10, date: Date.new(2026, 3, 1), price: 100, currency: "USD")+ (1..5).each do |day|+ account.holdings.create!(security: security, date: Date.new(2026, 3, day), qty: 10, price: 150,+ amount: BigDecimal(1500), currency: "USD")+ end+ sales = [ 3, 5 ].map do |day|+ create_trade(security, account: account, qty: -2, date: Date.new(2026, 3, day), price: 150, currency: "USD").entryable+ end+ trades = Trade.where(id: sales.map(&:id)).includes(:entry).to_a+ Trade.preload_basis_holdings(trades)+ trades.each { |trade| trade.preloaded_lot_disposals = nil }++ queries = capture_sql_queries { trades.each(&:realized_gain_loss) }++ assert_empty queries.grep(/SUM\(/), "no sale averages its buys on its own"+ assert_equal [ BigDecimal(100) ] * 2, trades.map { |t| t.realized_gain_loss.value.amount }+ end++ test "a preloaded disposal measures the same as one that looks its position up" do+ account, security = cross_currency_account+ account.holdings.create!(security: security, date: Date.new(2026, 3, 10), qty: 5, price: 150,+ amount: BigDecimal(750), currency: "USD", cost_basis: 100)+ sale = create_trade(security, account: account, qty: -2, date: Date.new(2026, 3, 12), price: 150, currency: "USD").entryable++ looked_up = Trade.find(sale.id).realized_gain_loss.value+ preloaded = Trade.find(sale.id).tap { |trade| Trade.preload_basis_holdings([ trade ]) }.realized_gain_loss.value++ assert_equal looked_up, preloaded+ end++ # Two snapshots on the same day differ only by currency (a security remap can+ # leave that). Every path settles on the same one, whatever the row order.+ test "a same-day tie resolves to the account's currency on every path" do+ account, security = cross_currency_account+ date = Date.new(2026, 3, 10)+ usd = account.holdings.create!(security: security, date: date, qty: 5, price: 150,+ amount: BigDecimal(750), currency: "USD", cost_basis: 100)+ eur = account.holdings.create!(security: security, date: date, qty: 5, price: 140,+ amount: BigDecimal(700), currency: "EUR", cost_basis: 90)+ sale = create_trade(security, account: account, qty: -2, date: Date.new(2026, 3, 12), price: 150, currency: "USD").entryable++ looked_up = Trade.find(sale.id).send(:basis_holding)+ preloaded = Trade.find(sale.id).tap { |trade| Trade.preload_basis_holdings([ trade ]) }.send(:basis_holding)+ given = [ [ eur, usd ], [ usd, eur ] ].map do |order|+ Trade.find(sale.id).tap { |trade| trade.preloaded_holdings = order }.send(:basis_holding)+ end++ assert_equal [ usd.id ] * 4, [ looked_up, preloaded, *given ].map(&:id)+ end+test "build_name generates buy trade name" doname = Trade.build_name("buy", 10, "AAPL")assert_equal "Buy 10.0 shares of AAPL", name@@ -275,6 +359,10 @@ class TradeTest < ActiveSupport::TestCaseendprivate+ def assert_no_queries_matching(pattern, &block)+ assert_empty capture_sql_queries(&block).grep(pattern)+ end+# A position whose cost basis is known, which is what makes a fabricated# gain possible: without one, realized_gain_loss returns nil for any reason.def position_with_known_cost_basis