Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

perf(transfers): narrow auto-transfer candidate search (#2080)

ghost2fb7962d6ee6
diff --git a/app/models/family/auto_transfer_matchable.rb b/app/models/family/auto_transfer_matchable.rb
index a53cca8466..e88b7141da 100644
--- a/app/models/family/auto_transfer_matchable.rb
+++ b/app/models/family/auto_transfer_matchable.rb
@@ -1,59 +1,40 @@
module Family::AutoTransferMatchable
- def transfer_match_candidates(date_window: 4, exchange_rate_tolerance: 0.1)
- Entry.select([
- "inflow_candidates.entryable_id as inflow_transaction_id",
- "outflow_candidates.entryable_id as outflow_transaction_id",
- "ABS(inflow_candidates.date - outflow_candidates.date) as date_diff"
- ]).from("entries inflow_candidates")
- .joins("
- JOIN entries outflow_candidates ON (
- inflow_candidates.amount < 0 AND
- outflow_candidates.amount > 0 AND
- inflow_candidates.account_id <> outflow_candidates.account_id AND
- inflow_candidates.date BETWEEN outflow_candidates.date - #{date_window.to_i} AND outflow_candidates.date + #{date_window.to_i}
- )
- ").joins("
- LEFT JOIN transfers existing_transfers ON (
- existing_transfers.inflow_transaction_id = inflow_candidates.entryable_id OR
- existing_transfers.outflow_transaction_id = outflow_candidates.entryable_id
- )
- ")
- .joins("LEFT JOIN rejected_transfers ON (
- rejected_transfers.inflow_transaction_id = inflow_candidates.entryable_id AND
- rejected_transfers.outflow_transaction_id = outflow_candidates.entryable_id
- )")
- .joins("LEFT JOIN exchange_rates ON (
- exchange_rates.date = outflow_candidates.date AND
- exchange_rates.from_currency = outflow_candidates.currency AND
- exchange_rates.to_currency = inflow_candidates.currency
- )")
- .joins("JOIN accounts inflow_accounts ON inflow_accounts.id = inflow_candidates.account_id")
- .joins("JOIN accounts outflow_accounts ON outflow_accounts.id = outflow_candidates.account_id")
- .where("inflow_accounts.family_id = ? AND outflow_accounts.family_id = ?", self.id, self.id)
- .where("inflow_accounts.status IN ('draft', 'active')")
- .where("outflow_accounts.status IN ('draft', 'active')")
- .where("inflow_candidates.entryable_type = 'Transaction' AND outflow_candidates.entryable_type = 'Transaction'")
- .where("
- (
- inflow_candidates.currency = outflow_candidates.currency AND
- inflow_candidates.amount = -outflow_candidates.amount
- ) OR (
- inflow_candidates.currency <> outflow_candidates.currency AND
- ABS(inflow_candidates.amount / NULLIF(outflow_candidates.amount * exchange_rates.rate, 0)) BETWEEN #{1 - exchange_rate_tolerance} AND #{1 + exchange_rate_tolerance}
- )
- ")
- .where(existing_transfers: { id: nil })
- .order("date_diff ASC") # Closest matches first
+ def transfer_match_candidates(
+ date_window: 4,
+ exchange_rate_tolerance: 0.1,
+ inflow_transaction_id: nil,
+ outflow_transaction_id: nil,
+ include_rejected: true
+ )
+ date_window = coerce_transfer_match_date_window!(date_window)
+ exchange_rate_tolerance = coerce_transfer_match_exchange_rate_tolerance!(exchange_rate_tolerance)
+
+ Entry.find_by_sql([
+ transfer_match_candidates_sql,
+ {
+ date_window:,
+ family_id: id,
+ inflow_transaction_id:,
+ outflow_transaction_id:,
+ include_rejected:,
+ lower_exchange_rate_bound: 1 - exchange_rate_tolerance,
+ upper_exchange_rate_bound: 1 + exchange_rate_tolerance
+ }
+ ])
end
def auto_match_transfers!
# Exclude already matched transfers
- candidates_scope = transfer_match_candidates.where(rejected_transfers: { id: nil })
+ candidates_scope = transfer_match_candidates(include_rejected: false)
+ transaction_ids = candidates_scope.flat_map do |match|
+ [ match.inflow_transaction_id, match.outflow_transaction_id ]
+ end.uniq
+ transactions_by_id = Transaction.includes(entry: :account).where(id: transaction_ids).index_by(&:id)
# Track which transactions we've already matched to avoid duplicates
used_transaction_ids = Set.new
-
- candidates = []
+ investment_category = nil
+ investment_category_loaded = false
Transfer.transaction do
candidates_scope.each do |match|
@@ -69,20 +50,24 @@ module Family::AutoTransferMatchable
# Another concurrent job created the transfer; safe to ignore
end
- inflow_transaction = Transaction.find(match.inflow_transaction_id)
- outflow_transaction = Transaction.find(match.outflow_transaction_id)
+ inflow_transaction = transactions_by_id.fetch(match.inflow_transaction_id)
+ outflow_transaction = transactions_by_id.fetch(match.outflow_transaction_id)
+ destination_account = inflow_transaction.entry.account
+ transfer_kind = Transfer.kind_for_account(destination_account)
# The kind is determined by the DESTINATION account (inflow), matching Transfer::Creator logic
inflow_transaction.update!(kind: "funds_movement")
- outflow_transaction.update!(kind: Transfer.kind_for_account(inflow_transaction.entry.account))
+ outflow_transaction.update!(kind: transfer_kind)
# Assign Investment Contributions category for transfers to investment accounts
- destination_account = Transaction.find(match.inflow_transaction_id).entry.account
- if Transfer.kind_for_account(destination_account) == "investment_contribution"
- outflow_txn = Transaction.find(match.outflow_transaction_id)
+ if transfer_kind == "investment_contribution"
+ outflow_txn = outflow_transaction
if outflow_txn.category_id.blank?
- category = destination_account.family.investment_contributions_category
- outflow_txn.update!(category: category) if category.present?
+ unless investment_category_loaded
+ investment_category = investment_contributions_category
+ investment_category_loaded = true
+ end
+ outflow_txn.update!(category: investment_category) if investment_category.present?
end
end
@@ -91,4 +76,110 @@ module Family::AutoTransferMatchable
end
end
end
+
+ private
+ def coerce_transfer_match_date_window!(value)
+ Integer(value)
+ rescue ArgumentError, TypeError
+ raise ArgumentError, "date_window must be an integer"
+ end
+
+ def coerce_transfer_match_exchange_rate_tolerance!(value)
+ tolerance = begin
+ Float(value)
+ rescue ArgumentError, TypeError
+ raise ArgumentError, "exchange_rate_tolerance must be numeric"
+ end
+
+ raise ArgumentError, "exchange_rate_tolerance must be numeric" unless tolerance.finite?
+ raise ArgumentError, "exchange_rate_tolerance must be non-negative" if tolerance.negative?
+
+ tolerance
+ end
+
+ def transfer_match_candidates_sql
+ <<~SQL.squish
+ SELECT transfer_match_candidates.*
+ FROM (
+ SELECT
+ inflow_candidates.entryable_id AS inflow_transaction_id,
+ outflow_candidates.entryable_id AS outflow_transaction_id,
+ ABS(inflow_candidates.date - outflow_candidates.date) AS date_diff,
+ rejected_transfers.id AS rejected_transfer_id
+ FROM entries inflow_candidates
+ JOIN accounts inflow_accounts ON inflow_accounts.id = inflow_candidates.account_id
+ JOIN entries outflow_candidates ON (
+ outflow_candidates.entryable_type = 'Transaction' AND
+ outflow_candidates.amount > 0 AND
+ outflow_candidates.account_id <> inflow_candidates.account_id AND
+ outflow_candidates.date BETWEEN inflow_candidates.date - :date_window AND inflow_candidates.date + :date_window AND
+ outflow_candidates.currency = inflow_candidates.currency AND
+ outflow_candidates.amount = -inflow_candidates.amount
+ )
+ JOIN accounts outflow_accounts ON outflow_accounts.id = outflow_candidates.account_id
+ LEFT JOIN transfers existing_transfers ON (
+ existing_transfers.inflow_transaction_id = inflow_candidates.entryable_id OR
+ existing_transfers.outflow_transaction_id = outflow_candidates.entryable_id
+ )
+ LEFT JOIN rejected_transfers ON (
+ rejected_transfers.inflow_transaction_id = inflow_candidates.entryable_id AND
+ rejected_transfers.outflow_transaction_id = outflow_candidates.entryable_id
+ )
+ WHERE
+ inflow_candidates.entryable_type = 'Transaction' AND
+ inflow_candidates.amount < 0 AND
+ inflow_accounts.family_id = :family_id AND
+ outflow_accounts.family_id = :family_id AND
+ inflow_accounts.status IN ('draft', 'active') AND
+ outflow_accounts.status IN ('draft', 'active') AND
+ existing_transfers.id IS NULL AND
+ (: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
+ (:include_rejected = TRUE OR rejected_transfers.id IS NULL)
+ UNION ALL
+ SELECT
+ inflow_candidates.entryable_id AS inflow_transaction_id,
+ outflow_candidates.entryable_id AS outflow_transaction_id,
+ ABS(inflow_candidates.date - outflow_candidates.date) AS date_diff,
+ rejected_transfers.id AS rejected_transfer_id
+ FROM entries inflow_candidates
+ JOIN accounts inflow_accounts ON inflow_accounts.id = inflow_candidates.account_id
+ JOIN entries outflow_candidates ON (
+ outflow_candidates.entryable_type = 'Transaction' AND
+ outflow_candidates.amount > 0 AND
+ outflow_candidates.account_id <> inflow_candidates.account_id AND
+ outflow_candidates.date BETWEEN inflow_candidates.date - :date_window AND inflow_candidates.date + :date_window AND
+ outflow_candidates.currency <> inflow_candidates.currency
+ )
+ JOIN accounts outflow_accounts ON outflow_accounts.id = outflow_candidates.account_id
+ JOIN exchange_rates ON (
+ exchange_rates.date = outflow_candidates.date AND
+ exchange_rates.from_currency = outflow_candidates.currency AND
+ exchange_rates.to_currency = inflow_candidates.currency
+ )
+ LEFT JOIN transfers existing_transfers ON (
+ existing_transfers.inflow_transaction_id = inflow_candidates.entryable_id OR
+ existing_transfers.outflow_transaction_id = outflow_candidates.entryable_id
+ )
+ LEFT JOIN rejected_transfers ON (
+ rejected_transfers.inflow_transaction_id = inflow_candidates.entryable_id AND
+ rejected_transfers.outflow_transaction_id = outflow_candidates.entryable_id
+ )
+ WHERE
+ inflow_candidates.entryable_type = 'Transaction' AND
+ inflow_candidates.amount < 0 AND
+ inflow_accounts.family_id = :family_id AND
+ outflow_accounts.family_id = :family_id AND
+ inflow_accounts.status IN ('draft', 'active') AND
+ outflow_accounts.status IN ('draft', 'active') AND
+ existing_transfers.id IS NULL AND
+ ABS(inflow_candidates.amount / NULLIF(outflow_candidates.amount * exchange_rates.rate, 0))
+ BETWEEN :lower_exchange_rate_bound AND :upper_exchange_rate_bound AND
+ (: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
+ (:include_rejected = TRUE OR rejected_transfers.id IS NULL)
+ ) transfer_match_candidates
+ ORDER BY transfer_match_candidates.date_diff ASC
+ SQL
+ end
end
diff --git a/app/models/transaction/transferable.rb b/app/models/transaction/transferable.rb
index 0980876105..7f96e4491a 100644
--- a/app/models/transaction/transferable.rb
+++ b/app/models/transaction/transferable.rb
@@ -16,9 +16,9 @@ module Transaction::Transferable
def transfer_match_candidates(date_window: 30)
candidates_scope = if self.entry.amount.negative?
- family_matches_scope(date_window: date_window).where("inflow_candidates.entryable_id = ?", self.id)
+ family_matches_scope(date_window: date_window, inflow_transaction_id: self.id)
else
- family_matches_scope(date_window: date_window).where("outflow_candidates.entryable_id = ?", self.id)
+ family_matches_scope(date_window: date_window, outflow_transaction_id: self.id)
end
candidates_scope.map do |match|
@@ -30,7 +30,7 @@ module Transaction::Transferable
end
private
- def family_matches_scope(date_window:)
- self.entry.account.family.transfer_match_candidates(date_window: date_window)
+ def family_matches_scope(date_window:, **filters)
+ self.entry.account.family.transfer_match_candidates(date_window: date_window, **filters)
end
end
diff --git a/db/migrate/20260531153000_add_transfer_match_lookup_index_to_entries.rb b/db/migrate/20260531153000_add_transfer_match_lookup_index_to_entries.rb
new file mode 100644
index 0000000000..f287e5af18
--- /dev/null
+++ b/db/migrate/20260531153000_add_transfer_match_lookup_index_to_entries.rb
@@ -0,0 +1,11 @@
+class AddTransferMatchLookupIndexToEntries < ActiveRecord::Migration[7.2]
+ disable_ddl_transaction!
+
+ def change
+ add_index :entries,
+ [ :currency, :amount, :date, :account_id ],
+ name: "index_entries_on_transfer_match_lookup",
+ where: "entryable_type = 'Transaction'",
+ algorithm: :concurrently
+ end
+end
diff --git a/db/schema.rb b/db/schema.rb
index 994d950e0b..fb44f8a0d4 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[7.2].define(version: 2026_05_25_121841) do
+ActiveRecord::Schema[7.2].define(version: 2026_05_31_153000) do
# These are extensions that must be enabled in order to support this database
enable_extension "pgcrypto"
enable_extension "plpgsql"
@@ -595,6 +595,7 @@ ActiveRecord::Schema[7.2].define(version: 2026_05_25_121841) do
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"
+ t.index ["currency", "amount", "date", "account_id"], name: "index_entries_on_transfer_match_lookup", where: "((entryable_type)::text = 'Transaction'::text)"
t.index ["user_modified"], name: "index_entries_on_user_modified_true", where: "(user_modified = true)"
end
diff --git a/test/models/family/auto_transfer_matchable_test.rb b/test/models/family/auto_transfer_matchable_test.rb
index 3a8e09df3e..40ffa20dad 100644
--- a/test/models/family/auto_transfer_matchable_test.rb
+++ b/test/models/family/auto_transfer_matchable_test.rb
@@ -109,6 +109,19 @@ class Family::AutoTransferMatchableTest < ActiveSupport::TestCase
end
end
+ test "transfer candidate options require valid numeric input" do
+ assert_raises(ArgumentError) { @family.transfer_match_candidates(date_window: "soon") }
+ assert_raises(ArgumentError) { @family.transfer_match_candidates(date_window: nil) }
+ assert_raises(ArgumentError) { @family.transfer_match_candidates(exchange_rate_tolerance: "wide") }
+ assert_raises(ArgumentError) { @family.transfer_match_candidates(exchange_rate_tolerance: Float::INFINITY) }
+ error = assert_raises(ArgumentError) { @family.transfer_match_candidates(exchange_rate_tolerance: -0.1) }
+ assert_equal "exchange_rate_tolerance must be non-negative", error.message
+
+ assert_nothing_raised do
+ @family.transfer_match_candidates(date_window: "4", exchange_rate_tolerance: "0.1")
+ end
+ end
+
test "auto-matched cash to investment assigns investment contribution category" do
investment = accounts(:investment)
outflow_entry = create_transaction(date: Date.current, account: @depository, amount: 500)
@@ -122,6 +135,22 @@ class Family::AutoTransferMatchableTest < ActiveSupport::TestCase
assert_equal category, outflow_entry.entryable.category
end
+ test "auto-matched investment transfers reuse contribution category lookup" do
+ investment = accounts(:investment)
+ category = @family.investment_contributions_category
+
+ create_transaction(date: Date.current, account: @depository, amount: 500)
+ create_transaction(date: Date.current, account: investment, amount: -500)
+ create_transaction(date: Date.current, account: @depository, amount: 700)
+ create_transaction(date: Date.current, account: investment, amount: -700)
+
+ @family.expects(:investment_contributions_category).once.returns(category)
+
+ assert_difference -> { Transfer.count }, 2 do
+ @family.auto_match_transfers!
+ end
+ end
+
test "does not match multi-currency transfer with missing exchange rate" do
create_transaction(date: Date.current, account: @depository, amount: 500)
create_transaction(date: Date.current, account: @credit_card, amount: -700, currency: "GBP")
@@ -131,6 +160,52 @@ class Family::AutoTransferMatchableTest < ActiveSupport::TestCase
end
end
+ test "same-currency matching ignores amount-mismatched busy-window entries" do
+ noise_transaction_ids = []
+
+ 25.times do |index|
+ noise_outflow = create_transaction(date: Date.current, account: @depository, amount: 13_001 + index)
+ noise_inflow = create_transaction(date: Date.current, account: @credit_card, amount: -(27_001 + index))
+
+ noise_transaction_ids << noise_outflow.entryable_id
+ noise_transaction_ids << noise_inflow.entryable_id
+ end
+
+ outflow = create_transaction(date: Date.current, account: @depository, amount: 500)
+ inflow = create_transaction(date: Date.current, account: @credit_card, amount: -500)
+
+ candidate_pairs = @family.transfer_match_candidates.map do |candidate|
+ [ candidate.inflow_transaction_id, candidate.outflow_transaction_id ]
+ end
+
+ assert_includes candidate_pairs, [ inflow.entryable_id, outflow.entryable_id ]
+
+ noise_pairs = candidate_pairs.select do |inflow_transaction_id, outflow_transaction_id|
+ noise_transaction_ids.include?(inflow_transaction_id) || noise_transaction_ids.include?(outflow_transaction_id)
+ end
+
+ assert_empty noise_pairs
+ end
+
+ test "single transaction transfer candidates filter optimized relation aliases" do
+ outflow = create_transaction(date: Date.current, account: @depository, amount: 500)
+ inflow = create_transaction(date: Date.current, account: @credit_card, amount: -500)
+
+ outflow_candidates = outflow.transaction.transfer_match_candidates
+ inflow_candidates = inflow.transaction.transfer_match_candidates
+
+ assert_equal [ inflow.entryable_id ], outflow_candidates.map(&:inflow_transaction_id)
+ assert_equal [ outflow.entryable_id ], inflow_candidates.map(&:outflow_transaction_id)
+ end
+
+ test "transfer candidate query separates exact and exchange-rate matching paths" do
+ sql = @family.send(:transfer_match_candidates_sql)
+
+ assert_includes sql, "UNION ALL"
+ assert_includes sql, "outflow_candidates.amount = -inflow_candidates.amount"
+ assert_includes sql, "JOIN exchange_rates"
+ end
+
# Regression tests for loan transfer kind assignment bug
# The kind should be determined by the DESTINATION account (inflow), not the source (outflow)
test "loan payment (cash to loan) assigns loan_payment kind to outflow" do