The personal finance app for everyone (by everyone)
Ruby
Reconstruct a bill's history whenever a detection is activated (#4371)
jaysbeekayc8467fce18c3
diff --git a/app/controllers/recurring_transactions_controller.rb b/app/controllers/recurring_transactions_controller.rbindex 4f768529aa..bde75c6246 100644--- a/app/controllers/recurring_transactions_controller.rb+++ b/app/controllers/recurring_transactions_controller.rb@@ -36,24 +36,12 @@ class RecurringTransactionsController < ApplicationController# real, active bill; dismissing tombstones it as `ended`, which the# Identifier treats as "never suggest this again".def confirm- first_confirmation = @recurring_transaction.suggested?- @recurring_transaction.update!(status: "active")-# A just-confirmed bill shows its lived history rather than starting- # blank. Guarded so a replayed POST does not re-run the backfill; the- # matcher pass inside is family-wide on purpose (exact-tier, idempotent,- # and scoping it would need a parallel Matcher entry point). Taken under- # the family lock so it cannot interleave with a running pipeline; when- # the lock is held the backfill is skipped and the confirm still succeeds.- if first_confirmation- RecurringTransaction::Pipeline.with_family_lock(Current.family.id) do- RecurringTransaction::HistoryBackfiller.new(- Current.family,- months: RecurringTransaction::Pipeline::FIRST_RUN_BACKFILL_MONTHS,- series_scope: Current.family.recurring_transactions.where(id: @recurring_transaction.id)- ).run!- end- end+ # blank: the status change reconstructs it (RecurringTransaction#+ # reconstruct_history_on_activation), queued when a pipeline holds the+ # family lock. Only the change from suggested does, so a replayed POST+ # reconstructs nothing twice.+ @recurring_transaction.update!(status: "active")flash[:notice] = t(@recurring_transaction.typed_income? ? "recurring_transactions.confirmed_income" : "recurring_transactions.confirmed")redirect_back_or_to recurring_transactions_pathdiff --git a/app/jobs/backfill_recurring_history_job.rb b/app/jobs/backfill_recurring_history_job.rbnew file mode 100644index 0000000000..8707178352--- /dev/null+++ b/app/jobs/backfill_recurring_history_job.rb@@ -0,0 +1,21 @@+# Reconstructs one bill's past payments when activating it could not: the+# activation found a pipeline holding the family lock. Skipping instead left+# the bill with no history for good, because the live matcher only ever looks+# at open occurrences from the current cycle on.+class BackfillRecurringHistoryJob < ApplicationJob+ queue_as :default++ class FamilyLockHeld < StandardError; end++ retry_on FamilyLockHeld, wait: :polynomially_longer, attempts: 10++ def perform(series_id)+ series = RecurringTransaction.find_by(id: series_id)++ # Dismissed, paused or deleted while this waited: the user has said what+ # they think of the bill, and a backfill would write payments onto it.+ return unless series&.active?++ raise FamilyLockHeld unless series.reconstruct_history!+ end+enddiff --git a/app/models/recurring_transaction.rb b/app/models/recurring_transaction.rbindex 95c4f4b2a3..f8ad7130af 100644--- a/app/models/recurring_transaction.rb+++ b/app/models/recurring_transaction.rb@@ -74,6 +74,11 @@ class RecurringTransaction < ApplicationRecordattr_accessor :rules_rewrittenafter_commit :generate_occurrences, on: :create+ # Ahead of regeneration: activation changes status, so both run, and with+ # load_defaults 7.1+ these run in the order defined. An exception in one+ # stops the rest, so a failed regeneration must not cost the bill its+ # history; reconstruct_history! generates the upcoming rows itself.+ after_commit :reconstruct_history_on_activation, on: :update, if: :activated_from_suggestion?after_commit :regenerate_future_occurrences, on: :update, if: :schedule_shape_changed?before_save :preserve_detected_name, if: -> { name_changed? && name_was.present? && matcher_hints.to_h["detected_name"].blank? }after_commit :pin_amount_on_dates_already_due, on: :update, if: :saved_change_to_amount?@@ -190,6 +195,55 @@ class RecurringTransaction < ApplicationRecordOccurrenceGenerator.new(self).generate!end+ # Links what a bill already paid before it was a bill. Every route that+ # confirms a detection -- the review strip, the pause toggle, the API and+ # the assistant's update_bill -- lands here through the status change.+ # Generation is scoped to this series; the matcher pass inside stays+ # family-wide on purpose (exact-tier, idempotent, and scoping it would need+ # a parallel Matcher entry point). Returns false only when another pipeline+ # holds the family lock.+ def reconstruct_history!+ return true if family.recurring_transactions_disabled?++ Pipeline.with_family_lock(family_id) do+ series_scope = family.recurring_transactions.where(id: id)++ # The current cycle and the upcoming occurrences first, as Pipeline#run!+ # does, so the history pass can match an early payment to the occurrence+ # it was paid ahead of. Idempotent, and it no longer relies on the+ # activation's regeneration having run. Freshly loaded, like the+ # backfiller's, so a pause that committed since this record was read+ # is respected.+ series_scope.find_each { |series| OccurrenceGenerator.new(series).generate! }+ HistoryBackfiller.new(+ family,+ months: Pipeline::FIRST_RUN_BACKFILL_MONTHS,+ series_scope: series_scope+ ).run!+ end+ end++ # Read from the saved change rather than the current status: update_bill+ # assigns every field and saves once, so by now the series reads active+ # whichever route it took.+ def activated_from_suggestion?+ saved_change_to_status?(from: "suggested", to: "active")+ end++ # Skipping under a held lock used to leave the bill without history for+ # good, since the live matcher never looks behind the current cycle.+ #+ # The activation has committed by now, so a failure here must not fail the+ # caller's own write (a toggle, an API update, the assistant's update_bill).+ # It is reported and handed to the job, which retries; the backfill is+ # re-runnable by construction.+ def reconstruct_history_on_activation+ BackfillRecurringHistoryJob.perform_later(id) unless reconstruct_history!+ rescue StandardError => e+ Rails.error.report(e, handled: true, context: { recurring_transaction_id: id })+ BackfillRecurringHistoryJob.perform_later(id)+ end+# Regenerating rebuilds only scheduled, allocation-free, not-yet-due rows;# anything closed or carrying payments is untouched.def regenerate_future_occurrencesdiff --git a/test/controllers/api/v1/recurring_transactions_controller_test.rb b/test/controllers/api/v1/recurring_transactions_controller_test.rbindex daa2c679f9..dfeb93f9b3 100644--- a/test/controllers/api/v1/recurring_transactions_controller_test.rb+++ b/test/controllers/api/v1/recurring_transactions_controller_test.rb@@ -330,6 +330,28 @@ class Api::V1::RecurringTransactionsControllerTest < ActionDispatch::Integrationassert_equal 16, response_data["expected_day_of_month"]end+ # The API writes "active" onto any writable series, a detected one included.+ test "should link a detected bill's past payments when activating it" do+ paid_on = Date.current.beginning_of_month + 8.days - 2.months+ suggestion = @family.recurring_transactions.create!(+ account: @account, name: "CITY WATER", amount: 80, currency: "USD",+ expected_day_of_month: 9, last_occurrence_date: paid_on,+ next_expected_date: paid_on + 2.months, status: "suggested", manual: false+ )+ entry = @account.entries.create!(+ date: paid_on, amount: 80, currency: "USD", name: "CITY WATER", entryable: Transaction.new+ )++ assert_difference -> { suggestion.recurring_occurrences.paid.where(due_on: paid_on).count }, 1 do+ patch api_v1_recurring_transaction_url(suggestion),+ params: { recurring_transaction: { status: "active" } },+ headers: api_headers(@api_key)+ end++ assert_response :success+ assert RecurringAllocation.where(entry_id: entry.id, state: "confirmed").exists?+ end+test "should update payment url and normalize a bare host" dopatch api_v1_recurring_transaction_url(@recurring_transaction),params: { recurring_transaction: { payment_url: "pay.example.com/bill" } },diff --git a/test/controllers/recurring_transactions_controller_test.rb b/test/controllers/recurring_transactions_controller_test.rbindex 81775aeac1..d2ab1be984 100644--- a/test/controllers/recurring_transactions_controller_test.rb+++ b/test/controllers/recurring_transactions_controller_test.rb@@ -1,6 +1,9 @@require "test_helper"class RecurringTransactionsControllerTest < ActionDispatch::IntegrationTest+ include FamilyLockTestHelper+ include ActiveJob::TestHelper+setup dosign_in @user = users(:family_admin)# The declare/edit/suggestion paths sit behind the Bills preview gate.@@ -993,6 +996,122 @@ class RecurringTransactionsControllerTest < ActionDispatch::IntegrationTest"confirming must close history a real entry anchors"end+ test "confirming while a pipeline holds the family lock queues the history instead of dropping it" do+ paid_on, suggestion, entry = suggested_bill_with_past_payment++ with_family_lock_held_elsewhere(@family.id) do+ assert_enqueued_with(job: BackfillRecurringHistoryJob, args: [ suggestion.id ]) do+ post confirm_recurring_transaction_url(suggestion)+ end+ end++ assert suggestion.reload.active?+ assert_equal 0, suggestion.recurring_occurrences.paid.where(due_on: paid_on).count,+ "nothing may run under another session's lock"++ perform_enqueued_jobs(only: BackfillRecurringHistoryJob)++ assert_equal 1, suggestion.recurring_occurrences.paid.where(due_on: paid_on).count+ assert RecurringAllocation.where(entry_id: entry.id, state: "confirmed").exists?+ end++ # The backfill prunes unpaid past rows of whatever it is scoped to, so it+ # must stay scoped to the bill being confirmed.+ test "confirming a detected bill leaves other bills' past rows alone" do+ _, suggestion, = suggested_bill_with_past_payment+ other_row = @recurring_transaction.recurring_occurrences.create!(+ family: @family, original_due_on: 3.months.ago.to_date, due_on: 3.months.ago.to_date, currency: "USD"+ )++ post confirm_recurring_transaction_url(suggestion)++ assert suggestion.reload.active?+ assert RecurringOccurrence.exists?(other_row.id), "another bill's history is not this confirm's to prune"+ end++ test "confirming an already-active bill queues nothing" do+ assert @recurring_transaction.active?++ assert_no_enqueued_jobs(only: BackfillRecurringHistoryJob) do+ with_family_lock_held_elsewhere(@family.id) { post confirm_recurring_transaction_url(@recurring_transaction) }+ end+ end++ # toggle_status reaches a detected bill too: the action only asks whether the+ # series is active, and a suggestion is not.+ test "toggling a detected bill on links its past payments" do+ paid_on, suggestion, entry = suggested_bill_with_past_payment++ assert_difference -> { suggestion.recurring_occurrences.paid.where(due_on: paid_on).count }, 1 do+ post toggle_status_recurring_transaction_url(suggestion)+ end+ assert suggestion.reload.active?+ assert RecurringAllocation.where(entry_id: entry.id, state: "confirmed").exists?+ end++ # The status change has committed by the time the reconstruction runs, so a+ # failure in it must not turn the user's own action into an error: it is+ # reported and handed to the job, which retries.+ test "toggling a detected bill on succeeds when reconstructing its history fails" do+ _, suggestion, = suggested_bill_with_past_payment+ RecurringTransaction::HistoryBackfiller.any_instance.stubs(:run!).raises(ActiveRecord::Deadlocked)+ Rails.error.expects(:report).with(instance_of(ActiveRecord::Deadlocked), has_entry(handled: true))++ assert_enqueued_with(job: BackfillRecurringHistoryJob, args: [ suggestion.id ]) do+ post toggle_status_recurring_transaction_url(suggestion)+ end++ assert_redirected_to recurring_transactions_url+ assert suggestion.reload.active?+ end++ # Activation changes status, a schedule-shaping column, so regeneration runs+ # in the same after_commit chain. A raise there stops the callbacks after+ # it, so the history reconstruction must not sit behind it.+ test "toggling a detected bill on still links its past payments when regenerating its future fails" do+ paid_on, suggestion, entry = suggested_bill_with_past_payment+ RecurringTransaction::OccurrenceGenerator.any_instance.stubs(:regenerate_future!).raises(RuntimeError, "regeneration failed")++ assert_raises(RuntimeError) { post toggle_status_recurring_transaction_url(suggestion) }++ assert suggestion.reload.active?+ assert_equal 1, suggestion.recurring_occurrences.paid.where(due_on: paid_on).count+ assert RecurringAllocation.where(entry_id: entry.id, state: "confirmed").exists?+ end++ # The history pass matches against every open occurrence, so the upcoming+ # one must exist by then: a payment made a couple of days early belongs to+ # it, not to the unpaid cycle before.+ test "toggling a detected bill on links an early payment to the upcoming occurrence" do+ travel_to Date.new(2026, 10, 14) do+ suggestion = @family.recurring_transactions.create!(+ name: "CITY POWER", account: accounts(:depository), amount: 95, currency: "USD",+ expected_day_of_month: 16, last_occurrence_date: Date.new(2026, 9, 16),+ next_expected_date: Date.new(2026, 10, 16), status: "suggested", manual: false+ )+ entry = accounts(:depository).entries.create!(+ date: Date.new(2026, 10, 14), amount: 95, currency: "USD", name: "CITY POWER",+ entryable: Transaction.new+ )++ post toggle_status_recurring_transaction_url(suggestion)++ upcoming = suggestion.recurring_occurrences.find_by!(due_on: Date.new(2026, 10, 16))+ assert RecurringAllocation.where(recurring_occurrence: upcoming, entry_id: entry.id).exists?,+ "the early payment belongs to the occurrence it was paid ahead of"+ end+ end++ test "resuming a paused bill does not reconstruct its history" do+ paid_on, suggestion, = suggested_bill_with_past_payment+ suggestion.update_columns(status: "inactive")++ assert_no_difference -> { suggestion.recurring_occurrences.where(due_on: paid_on).count } do+ post toggle_status_recurring_transaction_url(suggestion)+ end+ assert suggestion.reload.active?+ end+test "confirming twice does not double anything" dosuggestion = @family.recurring_transactions.create!(name: "CITY GAS", account: accounts(:depository), amount: 55, currency: "USD",@@ -1372,4 +1491,21 @@ class RecurringTransactionsControllerTest < ActionDispatch::IntegrationTestentryable: Transaction.new(**transaction_attrs))end++ # A detected bill with a payment two cycles back: before the current cycle+ # whatever day the suite runs, so only a history pass can link it.+ def suggested_bill_with_past_payment+ paid_on = Date.current.beginning_of_month + 8.days - 2.months+ suggestion = @family.recurring_transactions.create!(+ name: "CITY WATER", account: accounts(:depository), amount: 80, currency: "USD",+ expected_day_of_month: 9, last_occurrence_date: paid_on,+ next_expected_date: paid_on + 2.months, status: "suggested", manual: false+ )+ entry = accounts(:depository).entries.create!(+ date: paid_on, amount: 80, currency: "USD", name: "CITY WATER",+ entryable: Transaction.new+ )++ [ paid_on, suggestion, entry ]+ endenddiff --git a/test/jobs/backfill_recurring_history_job_test.rb b/test/jobs/backfill_recurring_history_job_test.rbnew file mode 100644index 0000000000..664aa92940--- /dev/null+++ b/test/jobs/backfill_recurring_history_job_test.rb@@ -0,0 +1,116 @@+require "test_helper"++# The deferred half of reconstructing a bill's history: activating a detected+# bill queues this when a pipeline holds the family lock, rather than skipping+# the backfill.+class BackfillRecurringHistoryJobTest < ActiveJob::TestCase+ include FamilyLockTestHelper+ setup do+ @family = families(:dylan_family)+ @account = accounts(:depository)+ @paid_on = Date.current.beginning_of_month + 8.days - 2.months++ @series = @family.recurring_transactions.create!(+ name: "CITY WATER", account: @account, amount: 80, currency: "USD",+ expected_day_of_month: 9, last_occurrence_date: @paid_on,+ next_expected_date: @paid_on + 2.months, status: "suggested", manual: false+ )+ @entry = @account.entries.create!(+ date: @paid_on, amount: 80, currency: "USD", name: "CITY WATER",+ entryable: Transaction.new+ )+ end++ test "links the past payment of a bill that is still active" do+ activate_without_callbacks(@series)++ assert_difference -> { paid_past_occurrences }, 1 do+ BackfillRecurringHistoryJob.perform_now(@series.id)+ end+ assert RecurringAllocation.where(entry_id: @entry.id, state: "confirmed").exists?+ end++ test "does nothing for a bill dismissed before the job ran" do+ occurrence = open_occurrence_on_payment_date+ @series.update_columns(status: "ended")++ BackfillRecurringHistoryJob.perform_now(@series.id)++ assert_not RecurringAllocation.where(entry_id: @entry.id).exists?,+ "the payment must not be written onto a bill the user set aside"+ assert occurrence.reload.scheduled?+ end++ test "does nothing for a bill paused before the job ran" do+ occurrence = open_occurrence_on_payment_date+ @series.update_columns(status: "inactive")++ BackfillRecurringHistoryJob.perform_now(@series.id)++ assert_not RecurringAllocation.where(entry_id: @entry.id).exists?,+ "the payment must not be written onto a bill the user set aside"+ assert occurrence.reload.scheduled?+ end++ test "does nothing for a bill deleted before the job ran" do+ id = @series.id+ @series.destroy!++ assert_nothing_raised { BackfillRecurringHistoryJob.perform_now(id) }+ assert_not RecurringAllocation.where(entry_id: @entry.id).exists?+ end++ test "does nothing for a family that has turned bills off" do+ activate_without_callbacks(@series)+ @family.update!(recurring_transactions_disabled: true)++ assert_no_enqueued_jobs(only: BackfillRecurringHistoryJob) do+ BackfillRecurringHistoryJob.perform_now(@series.id)+ end+ assert_equal 0, paid_past_occurrences+ end++ # The job's status check reads a record that a pause can overtake. The+ # pause's own regeneration clears the upcoming rows, so the rebuild must+ # read the status afresh rather than put them back on a paused bill.+ test "a bill paused after the job loaded it gains no occurrences" do+ activate_without_callbacks(@series)+ loaded = RecurringTransaction.find(@series.id)+ RecurringTransaction.where(id: @series.id).update_all(status: "inactive")++ assert_no_difference -> { @series.recurring_occurrences.count } do+ loaded.reconstruct_history!+ end+ end++ test "tries again later while a pipeline still holds the family lock" do+ activate_without_callbacks(@series)++ with_family_lock_held_elsewhere(@family.id) do+ assert_enqueued_with(job: BackfillRecurringHistoryJob, args: [ @series.id ]) do+ BackfillRecurringHistoryJob.perform_now(@series.id)+ end+ end++ assert_equal 0, paid_past_occurrences, "nothing may run while the lock is held"+ end++ private+ # Puts the series in the state the job finds after a contended confirm:+ # active, with the callback's own backfill not having run.+ def activate_without_callbacks(series)+ series.update_columns(status: "active")+ end++ # An open row the bill already had on the payment date: a backfill run+ # against it links the entry, which is what the status guard must stop.+ def open_occurrence_on_payment_date+ @series.recurring_occurrences.create!(+ family: @family, original_due_on: @paid_on, due_on: @paid_on, currency: "USD"+ )+ end++ def paid_past_occurrences+ @series.recurring_occurrences.paid.where(due_on: @paid_on).count+ end+enddiff --git a/test/models/assistant/function/update_bill_test.rb b/test/models/assistant/function/update_bill_test.rbindex cf5226c9db..4603a62099 100644--- a/test/models/assistant/function/update_bill_test.rb+++ b/test/models/assistant/function/update_bill_test.rb@@ -178,6 +178,35 @@ class Assistant::Function::UpdateBillTest < ActiveSupport::TestCaseassert_match(/not a kind/, call_tool(series.id, "bill_type" => "loan")[:error])end+ # The tool applies every field in memory and saves once, so whatever reacts+ # to the activation must read the saved change, not the status after save.+ test "activating a detected bill links its past payments" do+ paid_on = Date.current.beginning_of_month + 8.days - 2.months+ series = create_series(name: "CITY WATER", amount: 80, status: "suggested", manual: false,+ anchor_date: nil, expected_day_of_month: 9, last_occurrence_date: paid_on)+ entry = accounts(:depository).entries.create!(+ date: paid_on, amount: 80, currency: "USD", name: "CITY WATER", entryable: Transaction.new+ )++ assert_difference -> { series.recurring_occurrences.paid.where(due_on: paid_on).count }, 1 do+ assert call_tool(series.id, "status" => "active")[:updated]+ end+ assert RecurringAllocation.where(entry_id: entry.id, state: "confirmed").exists?+ end++ test "resuming a paused bill does not reconstruct its history" do+ paid_on = Date.current.beginning_of_month + 8.days - 2.months+ series = create_series(name: "CITY WATER", amount: 80, status: "inactive", manual: false,+ anchor_date: nil, expected_day_of_month: 9, last_occurrence_date: paid_on)+ accounts(:depository).entries.create!(+ date: paid_on, amount: 80, currency: "USD", name: "CITY WATER", entryable: Transaction.new+ )++ assert_no_difference -> { series.recurring_occurrences.where(due_on: paid_on).count } do+ assert call_tool(series.id, "status" => "active")[:updated]+ end+ end+privatedef call_tool(bill_id, params)diff --git a/test/models/recurring_transaction/pipeline_test.rb b/test/models/recurring_transaction/pipeline_test.rbindex 695c5ad1ff..b45ab8aa15 100644--- a/test/models/recurring_transaction/pipeline_test.rb+++ b/test/models/recurring_transaction/pipeline_test.rb@@ -1,6 +1,7 @@require "test_helper"class RecurringTransaction::PipelineTest < ActiveSupport::TestCase+ include FamilyLockTestHelperPipeline = RecurringTransaction::Pipelinedef setup@@ -114,22 +115,9 @@ class RecurringTransaction::PipelineTest < ActiveSupport::TestCaseendtest "run_with_lock! refuses to stack on a held family lock" do- key = Pipeline.advisory_lock_key(@family.id)- # Transactional tests hand every checkout the same shared fixture- # connection, and a session can always re-take its own advisory lock, so- # holding the lock needs a genuinely separate PG session.- config = ActiveRecord::Base.connection_pool.db_config.configuration_hash- other = PG.connect({- dbname: config[:database], host: config[:host], port: config[:port],- user: config[:username], password: config[:password]- }.compact)- other.exec("SELECT pg_advisory_lock(#{key})")-- result = Pipeline.new(@family).run_with_lock!+ result = with_family_lock_held_elsewhere(@family.id) { Pipeline.new(@family).run_with_lock! }assert_nil result, "a held lock reports nil rather than running"- ensure- other&.closeendtest "run! preloads recurrence rules for occurrence generation instead of querying per series" dodiff --git a/test/support/family_lock_test_helper.rb b/test/support/family_lock_test_helper.rbnew file mode 100644index 0000000000..97bb656ce9--- /dev/null+++ b/test/support/family_lock_test_helper.rb@@ -0,0 +1,17 @@+module FamilyLockTestHelper+ # Holds the recurring pipeline's advisory lock for a family from a separate+ # PG session. Transactional tests share one session, and a session can+ # always re-take its own advisory lock, so this needs a genuinely separate one.+ def with_family_lock_held_elsewhere(family_id)+ key = RecurringTransaction::Pipeline.advisory_lock_key(family_id)+ config = ActiveRecord::Base.connection_pool.db_config.configuration_hash+ other = PG.connect({+ dbname: config[:database], host: config[:host], port: config[:port],+ user: config[:username], password: config[:password]+ }.compact)+ other.exec("SELECT pg_advisory_lock(#{key})")+ yield+ ensure+ other&.close+ end+enddiff --git a/test/test_helper.rb b/test/test_helper.rbindex d60dc5ad85..0e592be2c7 100644--- a/test/test_helper.rb+++ b/test/test_helper.rb@@ -28,6 +28,7 @@ require "tempfile"require "uri"require Rails.root.join("test/support/sql_query_capture").to_srequire Rails.root.join("test/support/rake_task_test_helper").to_s+require Rails.root.join("test/support/family_lock_test_helper").to_sVCR.configure do |config|config.cassette_library_dir = "test/vcr_cassettes"