Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Retire bill suggestions whose transactions became transfer legs (#5120)

David Gil06b7519d0427
diff --git a/app/jobs/identify_recurring_transactions_job.rb b/app/jobs/identify_recurring_transactions_job.rb
index 61d2117268..11bef80b0e 100644
--- a/app/jobs/identify_recurring_transactions_job.rb
+++ b/app/jobs/identify_recurring_transactions_job.rb
@@ -19,10 +19,14 @@ class IdentifyRecurringTransactionsJob < ApplicationJob
# Check if there are still incomplete syncs - if so, skip and let the last sync trigger it
return if family_has_incomplete_syncs?(family)
- # Use advisory lock as final safety net against concurrent execution
- RecurringTransaction::Pipeline.with_family_lock(family_id) do
+ # Use advisory lock as final safety net against concurrent execution. A
+ # run already holding it may have read the data before the change that
+ # scheduled this one (a transfer confirmed mid-run), so retry rather than
+ # drop it.
+ acquired = RecurringTransaction::Pipeline.with_family_lock(family_id) do
RecurringTransaction::Pipeline.new(family).run!
end
+ retry_job(wait: DEBOUNCE_DELAY) unless acquired
end
def self.schedule_for(family)
diff --git a/app/models/recurring_transaction.rb b/app/models/recurring_transaction.rb
index d6cc556409..d91889a794 100644
--- a/app/models/recurring_transaction.rb
+++ b/app/models/recurring_transaction.rb
@@ -870,6 +870,18 @@ class RecurringTransaction < ApplicationRecord
last_occurrence_date < staleness_threshold_date
end
+ # True when this series matches transactions and every one of them is now a
+ # transfer leg. Detection skips transfer kinds (see Identifier), so a
+ # suggestion built from charges later confirmed as a transfer has nothing
+ # left that would detect it today. One ordinary match keeps it: detection
+ # still sees that charge and may refresh the series from it.
+ def matches_only_transfer_legs?
+ entryable_ids = matching_transactions.map(&:entryable_id)
+
+ entryable_ids.any? &&
+ Transaction.where(id: entryable_ids).where.not(kind: Transaction::TRANSFER_KINDS).none?
+ end
+
# A cadence the user typed is intent; the dates charges land on are
# observation. Detection keeps refreshing the latter but must not move a
# schedule someone set by hand. `manual` cannot carry this: it is set at
diff --git a/app/models/recurring_transaction/cleaner.rb b/app/models/recurring_transaction/cleaner.rb
index 5a0da14323..dda0538d56 100644
--- a/app/models/recurring_transaction/cleaner.rb
+++ b/app/models/recurring_transaction/cleaner.rb
@@ -38,6 +38,39 @@ class RecurringTransaction
stale_count
end
+ # Delete detected suggestions whose transactions have all since been
+ # confirmed as transfer legs: they were offered while the legs were still
+ # ordinary charges, and detection never revisits a suggestion it no longer
+ # finds. Deleting rather than tombstoning as `ended` keeps them revivable:
+ # nothing rebuilds the row while the transfers stand, and if the transfers
+ # are later unlinked the legs are ordinary again and detection offers the
+ # bill afresh. An `ended` row would block that, as it does for a user's
+ # dismissal. Confirmed bills, manual series and recurring transfers
+ # (destination_account_id present, matched by their pair) are never
+ # touched, nor is any series in `claimed_ids`: the ones detection just
+ # attributed this run's ordinary charges to, which may sit at an amount
+ # `matching_transactions` does not look at.
+ def retire_transfer_suggestions(claimed_ids: [])
+ retired_count = 0
+
+ retirement_candidates(claimed_ids).find_each do |recurring_transaction|
+ next unless recurring_transaction.matches_only_transfer_legs?
+
+ # Re-check under a row lock: the user may have confirmed or dismissed
+ # the suggestion, an import may have marked it manual, or one of its
+ # transfers may have been unlinked since the check.
+ retired = recurring_transaction.with_lock do
+ recurring_transaction.suggested? &&
+ !recurring_transaction.manual? &&
+ recurring_transaction.matches_only_transfer_legs? &&
+ recurring_transaction.destroy!
+ end
+ retired_count += 1 if retired
+ end
+
+ retired_count
+ end
+
# Remove inactive recurring transactions that have been inactive for 6+ months
# Manual recurring transactions are never automatically deleted
def remove_old_inactive_transactions
@@ -49,5 +82,14 @@ class RecurringTransaction
.where("updated_at < ?", six_months_ago)
.destroy_all
end
+
+ private
+
+ def retirement_candidates(claimed_ids)
+ family.recurring_transactions
+ .suggested
+ .where(manual: false, destination_account_id: nil)
+ .where.not(id: claimed_ids)
+ end
end
end
diff --git a/app/models/recurring_transaction/identifier.rb b/app/models/recurring_transaction/identifier.rb
index bcf3d8d774..08ae533b1b 100644
--- a/app/models/recurring_transaction/identifier.rb
+++ b/app/models/recurring_transaction/identifier.rb
@@ -4,10 +4,13 @@ class RecurringTransaction
# them, lands unclaimed patterns as `suggested`, and offers candidate patterns
# to the add-bill pickers.
class Identifier
- attr_reader :family
+ # Ids of the series the last identify_recurring_patterns run attributed
+ # ordinary charges to, by claiming or creating them.
+ attr_reader :family, :claimed_series_ids
def initialize(family)
@family = family
+ @claimed_series_ids = []
end
# Amounts within this percentage of a cluster's running mean belong to the
@@ -104,6 +107,7 @@ class RecurringTransaction
# Identify and create/update recurring transactions for the family
def identify_recurring_patterns
+ claimed_series_ids.clear
three_months_ago = 3.months.ago.to_date
recurring_patterns = collect_patterns(min_occurrences: 3)
@@ -133,6 +137,7 @@ class RecurringTransaction
begin
created = create_suggested_series(pattern, scoped: candidates.any?)
+ claimed_series_ids << created.id
(existing_by_identity[identity] ||= []) << created
rescue ActiveRecord::RecordNotUnique
# Race: another process created the same identity between load and
@@ -365,6 +370,7 @@ class RecurringTransaction
# PriceChangeDetector), and so is the due day once the user has pinned
# the schedule.
def update_claimed_series(recurring, pattern)
+ claimed_series_ids << recurring.id
# A detected day shift lands before the date math, so the persisted
# next_expected_date agrees with the regenerated occurrences instead
# of keeping the old day for a cycle.
diff --git a/app/models/recurring_transaction/pipeline.rb b/app/models/recurring_transaction/pipeline.rb
index 644f4ec3b9..5130a246e8 100644
--- a/app/models/recurring_transaction/pipeline.rb
+++ b/app/models/recurring_transaction/pipeline.rb
@@ -1,11 +1,12 @@
class RecurringTransaction
- # The full detection pipeline -- identify patterns, materialize occurrence
- # windows, repair provider-replaced entries, match payments, detect price
- # changes -- in one place for its three callers: the post-sync job, the
- # Settings "Identify Patterns" button, and the Bills page's detection action.
+ # The full detection pipeline -- identify patterns, retire suggestions that
+ # became transfers, materialize occurrence windows, repair provider-replaced
+ # entries, match payments, detect price changes -- in one place for its
+ # three callers: the post-sync job, the Settings "Identify Patterns" button,
+ # and the Bills page's detection action.
#
# `run!` returns the identified pattern count. `backfill: true` additionally
- # reconstructs recent history after the five stages; user-triggered detection
+ # reconstructs recent history after the six stages; user-triggered detection
# asks for it, background syncs never do. `run_with_lock!` returns the count,
# or nil when another run already holds the family lock.
class Pipeline
@@ -18,7 +19,9 @@ class RecurringTransaction
end
def run!(backfill: false)
- patterns_count = Identifier.new(family).identify_recurring_patterns
+ identifier = Identifier.new(family)
+ patterns_count = identifier.identify_recurring_patterns
+ Cleaner.new(family).retire_transfer_suggestions(claimed_ids: identifier.claimed_series_ids)
# Schedule.for reads recurrence_rules for every series; preload them so
# occurrence generation doesn't issue one query per series (N+1).
diff --git a/app/models/transfer.rb b/app/models/transfer.rb
index 05ff46d566..b16bc0a402 100644
--- a/app/models/transfer.rb
+++ b/app/models/transfer.rb
@@ -203,6 +203,14 @@ class Transfer < ApplicationRecord
inflow_transaction.update!(kind: "funds_movement")
outflow_transaction.update!(outflow_attrs)
end
+
+ # The legs just stopped being ordinary transactions, so a bill suggestion
+ # detected from them can now be retired. A family that never syncs would
+ # otherwise keep it until someone reruns detection by hand. Scheduling
+ # waits for every enclosing transaction: the debounce timestamp lives in
+ # the cache, and a rolled-back confirmation must not supersede a queued run.
+ family = to_account.family
+ ActiveRecord.after_all_transactions_commit { RecurringTransaction.identify_patterns_for(family) }
end
def date
diff --git a/test/jobs/identify_recurring_transactions_job_test.rb b/test/jobs/identify_recurring_transactions_job_test.rb
index 22a07ef669..e5f31ef1c5 100644
--- a/test/jobs/identify_recurring_transactions_job_test.rb
+++ b/test/jobs/identify_recurring_transactions_job_test.rb
@@ -37,6 +37,15 @@ class IdentifyRecurringTransactionsJobTest < ActiveJob::TestCase
IdentifyRecurringTransactionsJob.new.perform(@family.id, @scheduled_at)
end
+ test "retries later when another pipeline run holds the family lock" do
+ Sync.for_family(@family).incomplete.find_each(&:destroy)
+ RecurringTransaction::Pipeline.stubs(:with_family_lock).returns(false)
+
+ assert_enqueued_with(job: IdentifyRecurringTransactionsJob, args: [ @family.id, @scheduled_at ]) do
+ IdentifyRecurringTransactionsJob.perform_now(@family.id, @scheduled_at)
+ end
+ end
+
test "skips when family is missing" do
RecurringTransaction::Identifier.any_instance.expects(:identify_recurring_patterns).never
diff --git a/test/models/recurring_transaction/pipeline_test.rb b/test/models/recurring_transaction/pipeline_test.rb
index b45ab8aa15..fa3b4ca9f1 100644
--- a/test/models/recurring_transaction/pipeline_test.rb
+++ b/test/models/recurring_transaction/pipeline_test.rb
@@ -30,6 +30,53 @@ class RecurringTransaction::PipelineTest < ActiveSupport::TestCase
end
end
+ test "run! removes suggestions detected from charges later confirmed as transfer legs" do
+ travel_to Date.new(2026, 8, 10) do
+ savings = accounts(:connected)
+ transfers = 3.times.map do |i|
+ date = Date.new(2026, 8, 5) << i
+ outflow = create_entry(amount: 500, date: date, name: "Move to savings")
+ inflow = savings.entries.create!(date: date, amount: -500, currency: "USD",
+ name: "Move from checking", entryable: Transaction.new)
+ Transfer.create!(outflow_transaction: outflow.entryable, inflow_transaction: inflow.entryable, status: "pending")
+ end
+
+ Pipeline.new(@family).run!
+ detected = @family.recurring_transactions.where(name: [ "Move to savings", "Move from checking" ])
+ assert_equal 2, detected.suggested.count, "both legs are detected while they are ordinary transactions"
+
+ transfers.each(&:confirm!)
+ Pipeline.new(@family).run!
+
+ assert_empty detected.reload
+ end
+ end
+
+ test "run! keeps a suggestion detection refreshed from ordinary charges at a new amount" do
+ travel_to Date.new(2026, 8, 10) do
+ suggestion = @family.recurring_transactions.create!(
+ account: @account, name: "Move to savings", amount: 500, currency: "USD",
+ expected_day_of_month: 5, last_occurrence_date: Date.new(2026, 5, 5),
+ next_expected_date: Date.new(2026, 6, 5), status: "suggested", occurrence_count: 3
+ )
+ savings = accounts(:connected)
+ # Older 500 charges were later confirmed as transfer legs...
+ 3.times do |i|
+ date = Date.new(2026, 5, 5) << i
+ outflow = create_entry(amount: 500, date: date, name: "Move to savings")
+ inflow = savings.entries.create!(date: date, amount: -500, currency: "USD",
+ name: "Move from checking", entryable: Transaction.new)
+ Transfer.create!(outflow_transaction: outflow.entryable, inflow_transaction: inflow.entryable, status: "pending").confirm!
+ end
+ # ...while the bill itself kept charging, now at 520.
+ 3.times { |i| create_entry(amount: 520, date: Date.new(2026, 8, 5) << i, name: "Move to savings") }
+
+ Pipeline.new(@family).run!
+
+ assert suggestion.reload.suggested?, "detection claimed it from ordinary charges this run"
+ end
+ end
+
test "run! with backfill reconstructs history and is idempotent" do
travel_to Date.new(2026, 8, 10) do
series = create_series(name: "CITY WATER", amount: 80, day_offset: -1)
diff --git a/test/models/recurring_transaction_test.rb b/test/models/recurring_transaction_test.rb
index a474bb7336..3a83d9fae9 100644
--- a/test/models/recurring_transaction_test.rb
+++ b/test/models/recurring_transaction_test.rb
@@ -1605,6 +1605,134 @@ class RecurringTransactionTest < ActiveSupport::TestCase
assert_equal "inactive", rt.reload.status
end
+ test "Cleaner removes a suggestion once every transaction it matches is a confirmed transfer leg" do
+ travel_to Date.new(2026, 8, 10) do
+ suggestion = transfer_shaped_suggestion
+ transfers = 3.times.map { |i| pending_transfer_leg_pair(Date.new(2026, 8, 5) << i) }
+
+ cleaner = RecurringTransaction::Cleaner.new(@family)
+ assert_equal 0, cleaner.retire_transfer_suggestions,
+ "a pending auto-match leaves the legs as ordinary transactions"
+ assert suggestion.reload.suggested?
+
+ transfers.each(&:confirm!)
+
+ assert_equal 1, cleaner.retire_transfer_suggestions
+ assert_not RecurringTransaction.exists?(suggestion.id),
+ "deleted, not tombstoned: no dismissal by the user stands behind it"
+ end
+ end
+
+ test "Cleaner keeps a suggestion that turned manual between its scan and the row lock" do
+ travel_to Date.new(2026, 8, 10) do
+ suggestion = transfer_shaped_suggestion
+ 3.times.map { |i| pending_transfer_leg_pair(Date.new(2026, 8, 5) << i) }.each(&:confirm!)
+ cleaner = RecurringTransaction::Cleaner.new(@family)
+ # The scan loaded the row while it was still detected; an import replay
+ # then marked it manual. Only the reload under the lock can see that.
+ scanned = RecurringTransaction.find(suggestion.id)
+ scan = stub
+ scan.stubs(:find_each).yields(scanned)
+ cleaner.stubs(:retirement_candidates).returns(scan)
+ RecurringTransaction.where(id: suggestion.id).update_all(manual: true)
+ assert_not scanned.manual?
+
+ assert_equal 0, cleaner.retire_transfer_suggestions
+ assert RecurringTransaction.exists?(suggestion.id)
+ end
+ end
+
+ test "Cleaner's retirement leaves the bill detectable again once the transfers are unlinked" do
+ travel_to Date.new(2026, 8, 10) do
+ transfer_shaped_suggestion
+ transfers = 3.times.map { |i| pending_transfer_leg_pair(Date.new(2026, 8, 5) << i) }
+ transfers.each(&:confirm!)
+ RecurringTransaction::Cleaner.new(@family).retire_transfer_suggestions
+
+ transfers.each(&:reject!)
+ # A fresh family, as the next detection job loads: this one has the
+ # retired row cached in its association.
+ RecurringTransaction.identify_patterns_for!(Family.find(@family.id))
+
+ revived = RecurringTransaction.find_by(family: @family, name: "Move to savings")
+ assert revived&.suggested?, "the legs are standard again, so detection offers the bill again"
+ end
+ end
+
+ test "Cleaner keeps a suggestion detection attributes to this run's charges" do
+ travel_to Date.new(2026, 8, 10) do
+ suggestion = transfer_shaped_suggestion
+ 3.times { |i| pending_transfer_leg_pair(Date.new(2026, 8, 5) << i).confirm! }
+
+ assert_equal 0, RecurringTransaction::Cleaner.new(@family).retire_transfer_suggestions(claimed_ids: [ suggestion.id ])
+ assert suggestion.reload.suggested?
+ end
+ end
+
+ test "Cleaner keeps a suggestion whose transfer was unlinked before it took the lock" do
+ travel_to Date.new(2026, 8, 10) do
+ suggestion = transfer_shaped_suggestion
+ transfers = 3.times.map { |i| pending_transfer_leg_pair(Date.new(2026, 8, 5) << i) }
+ transfers.each(&:confirm!)
+ # The unlink commits after the unlocked check and before the row lock.
+ RecurringTransaction.any_instance.stubs(:lock!).with do
+ transfers.each { |transfer| transfer.reload.destroy! if Transfer.exists?(transfer.id) }
+ end.returns(suggestion)
+
+ assert_equal 0, RecurringTransaction::Cleaner.new(@family).retire_transfer_suggestions
+ assert suggestion.reload.suggested?
+ end
+ end
+
+ test "Cleaner keeps a suggestion while it still matches an ordinary transaction" do
+ travel_to Date.new(2026, 8, 10) do
+ suggestion = transfer_shaped_suggestion
+ 2.times { |i| pending_transfer_leg_pair(Date.new(2026, 8, 5) << i).confirm! }
+ @account.entries.create!(date: Date.new(2026, 6, 5), amount: 500, currency: "USD",
+ name: "Move to savings", entryable: Transaction.new)
+
+ assert_equal 0, RecurringTransaction::Cleaner.new(@family).retire_transfer_suggestions
+ assert suggestion.reload.suggested?
+ end
+ end
+
+ test "Cleaner leaves a suggestion the user confirmed while it was checking" do
+ travel_to Date.new(2026, 8, 10) do
+ suggestion = transfer_shaped_suggestion
+ # The confirmation lands between loading the batch and ending the row.
+ RecurringTransaction.any_instance.stubs(:matches_only_transfer_legs?).with do
+ RecurringTransaction.where(id: suggestion.id).update_all(status: "active")
+ end.returns(true)
+
+ assert_equal 0, RecurringTransaction::Cleaner.new(@family).retire_transfer_suggestions
+ assert suggestion.reload.active?
+ end
+ end
+
+ test "Cleaner keeps a suggestion that matches nothing" do
+ travel_to Date.new(2026, 8, 10) do
+ suggestion = transfer_shaped_suggestion
+
+ assert_equal 0, RecurringTransaction::Cleaner.new(@family).retire_transfer_suggestions
+ assert suggestion.reload.suggested?
+ end
+ end
+
+ test "Cleaner never retires confirmed, manual or transfer series whose matches are transfer legs" do
+ travel_to Date.new(2026, 8, 10) do
+ active = transfer_shaped_suggestion(status: "active")
+ manual = transfer_shaped_suggestion(manual: true, dedup_scope: "manual")
+ transfer_series = transfer_shaped_suggestion(destination_account: accounts(:connected))
+ 3.times { |i| pending_transfer_leg_pair(Date.new(2026, 8, 5) << i).confirm! }
+ assert_not_empty transfer_series.matching_transactions, "guard sanity: the transfer series sees the pairs"
+
+ assert_equal 0, RecurringTransaction::Cleaner.new(@family).retire_transfer_suggestions
+ assert active.reload.active?
+ assert manual.reload.suggested?
+ assert transfer_series.reload.suggested?
+ end
+ end
+
test "matching_transactions finds the transfer pair regardless of occurrence name" do
rt = @family.recurring_transactions.create!(
account: @account, destination_account: accounts(:credit_card),
@@ -1969,6 +2097,27 @@ class RecurringTransactionTest < ActiveSupport::TestCase
end
private
+ # A detected bill on the outflow side of what later turns out to be a
+ # monthly move between two of the family's own accounts.
+ def transfer_shaped_suggestion(status: "suggested", manual: false, destination_account: nil, dedup_scope: "")
+ @family.recurring_transactions.create!(
+ account: @account, destination_account: destination_account, name: "Move to savings",
+ amount: 500, currency: "USD", expected_day_of_month: 5, dedup_scope: dedup_scope,
+ last_occurrence_date: Date.new(2026, 8, 5), next_expected_date: Date.new(2026, 9, 5),
+ status: status, manual: manual, occurrence_count: 3
+ )
+ end
+
+ # Two ordinary transactions linked by an auto-match the user has yet to
+ # confirm, the state they are in when detection first sees them.
+ def pending_transfer_leg_pair(date)
+ outflow = @account.entries.create!(date: date, amount: 500, currency: "USD",
+ name: "Move to savings", entryable: Transaction.new)
+ inflow = accounts(:connected).entries.create!(date: date, amount: -500, currency: "USD",
+ name: "Move from checking", entryable: Transaction.new)
+ Transfer.create!(outflow_transaction: outflow.entryable, inflow_transaction: inflow.entryable, status: "pending")
+ end
+
def create_rent(amount, name: "Rent", **attributes)
@family.recurring_transactions.create!(
name: name, account: @account, amount: amount, currency: "USD",
diff --git a/test/models/transfer_test.rb b/test/models/transfer_test.rb
index 55e69a3437..200b732006 100644
--- a/test/models/transfer_test.rb
+++ b/test/models/transfer_test.rb
@@ -2,6 +2,7 @@ require "test_helper"
class TransferTest < ActiveSupport::TestCase
include EntriesTestHelper
+ include ActiveJob::TestHelper
setup do
@outflow = transactions(:transfer_out)
@@ -179,6 +180,24 @@ class TransferTest < ActiveSupport::TestCase
assert_equal "funds_movement", transfer.inflow_transaction.reload.kind
end
+ test "confirm! schedules recurring detection so suggestions built from the legs are retired" do
+ transfer = create_pending_transfer(from: accounts(:depository), to: accounts(:credit_card))
+
+ assert_enqueued_with(job: IdentifyRecurringTransactionsJob, args: ->(args) { args.first == transfer.to_account.family_id }) do
+ transfer.confirm!
+ end
+ end
+
+ test "confirm! schedules recurring detection only once the enclosing transaction commits" do
+ transfer = create_pending_transfer(from: accounts(:depository), to: accounts(:credit_card))
+ IdentifyRecurringTransactionsJob.expects(:schedule_for).never
+
+ Transfer.transaction do
+ transfer.confirm!
+ raise ActiveRecord::Rollback
+ end
+ end
+
test "confirm! assigns the investment contributions category to an uncategorized outflow" do
transfer = create_pending_transfer(from: accounts(:depository), to: accounts(:investment))