The personal finance app for everyone (by everyone)
Ruby
Prevent lost updates to loan variable-rate schedules (#4445)
Orange🍊0d92d43563fb
diff --git a/app/controllers/concerns/accountable_resource.rb b/app/controllers/concerns/accountable_resource.rbindex ac9d1b5f61..677a86afa4 100644--- a/app/controllers/concerns/accountable_resource.rb+++ b/app/controllers/concerns/accountable_resource.rb@@ -100,38 +100,42 @@ module AccountableResource# account's cached balance; before this, a validation failing on the# attributes (a half-filled loan rate change, say) returned 422 with the# balance half of the rejected form already committed.- saved = Account.transaction do- # Handle balance update if the value actually changed- if account_params[:balance].present? && account_params[:balance].to_d != @account.balance- result = @account.set_current_balance(account_params[:balance].to_d)- unless result.success?- @account.assign_attributes(update_params)- @error_message = result.error+ saved = with_account_update_lock do+ # Loan updates already hold a row-lock transaction. Use a savepoint so+ # Rollback undoes these writes without being swallowed by that outer scope.+ Account.transaction(requires_new: true) do+ # Handle balance update if the value actually changed+ if account_params[:balance].present? && account_params[:balance].to_d != @account.balance+ result = @account.set_current_balance(account_params[:balance].to_d)+ unless result.success?+ @account.assign_attributes(update_params)+ @error_message = result.error+ raise ActiveRecord::Rollback+ end+ end++ # Update remaining account attributes. Note: currency is intentionally allowed+ # here so all account types (depositories, credit cards, loans, etc.) can+ # have their currency changed via this shared update path.+ # One save: lock_saved_attributes! below locks what this save changed,+ # and a second save would leave it nothing to lock.+ @account.assign_attributes(update_params)+ @account.cost_basis_method = cost_basis_method if cost_basis_method && @account.supports_trades?+ unless @account.save+ @error_message = @account.errors.full_messages.join(", ")raise ActiveRecord::Rollbackend- end- # Update remaining account attributes. Note: currency is intentionally allowed- # here so all account types (depositories, credit cards, loans, etc.) can- # have their currency changed via this shared update path.- # One save: lock_saved_attributes! below locks what this save changed,- # and a second save would leave it nothing to lock.- @account.assign_attributes(update_params)- @account.cost_basis_method = cost_basis_method if cost_basis_method && @account.supports_trades?- unless @account.save- @error_message = @account.errors.full_messages.join(", ")+ # Inside the transaction, as `create` does: the locks are saved with+ # `update!`, and a raise there after the commit left the balance and the+ # attributes above in place behind a failed request.+ @account.lock_saved_attributes!++ true+ rescue ActiveRecord::RecordInvalid => e+ @error_message = e.record.errors.full_messages.join(", ").presence || e.messageraise ActiveRecord::Rollbackend-- # Inside the transaction, as `create` does: the locks are saved with- # `update!`, and a raise there after the commit left the balance and the- # attributes above in place behind a failed request.- @account.lock_saved_attributes!-- true- rescue ActiveRecord::RecordInvalid => e- @error_message = e.record.errors.full_messages.join(", ").presence || e.message- raise ActiveRecord::Rollbackendunless saved@@ -160,6 +164,12 @@ module AccountableResourceendprivate+ # Hook for subclasses to serialize persistence. The default takes no lock;+ # loans override it, leaving rendering and redirects outside the lock.+ def with_account_update_lock+ yield+ end+# Whether `update` saved the account, for controllers that save more after it.def account_updated?@account_updated.present?diff --git a/app/controllers/loans_controller.rb b/app/controllers/loans_controller.rbindex 8d3a4be985..517257dff2 100644--- a/app/controllers/loans_controller.rb+++ b/app/controllers/loans_controller.rb@@ -4,7 +4,26 @@ class LoansController < ApplicationControllerpermitted_accountable_attributes(:id, :subtype, :rate_type, :interest_rate, :term_months, :initial_balance, :start_date,:down_payment, :insurance_rate, :insurance_rate_type, :day_count_convention,- :principal_only_transfers,+ :principal_only_transfers, :rate_schedule_snapshot,{ rate_changes: [ :effective_date, :rate ] })++ def update+ attributes = account_params[:accountable_attributes]+ if attributes&.key?(:rate_changes) && attributes[:rate_schedule_snapshot].blank?+ @error_message = t("loans.edit.stale_rate_schedule")+ render :edit, status: :unprocessable_entity+ else+ super+ end+ end++ private+ def with_account_update_lock+ @account.accountable.with_schedule_lock do+ # The account row is locked too, but the request loaded it before the lock.+ @account.reload+ yield+ end+ endenddiff --git a/app/models/loan.rb b/app/models/loan.rbindex f39f212245..df795165ee 100644--- a/app/models/loan.rb+++ b/app/models/loan.rb@@ -136,7 +136,11 @@ class Loan < ApplicationRecord# place the column is parsed: RateResolver and the form rows read these# pairs rather than the raw JSON, so every reader agrees on what a row means.def variable_rates- (variable_rate_schedule || {})+ parse_rate_schedule(variable_rate_schedule)+ end++ private def parse_rate_schedule(schedule)+ (schedule || {}).map { |date, rate| [ Date.iso8601(date.to_s), BigDecimal(rate.to_s) ] }.sort_by(&:first)end@@ -149,6 +153,50 @@ class Loan < ApplicationRecordRateResolver.for(self).accrual_rate_for(as_of)end+ # Account updates can save their nested loan, and loan saves touch the account.+ # Always lock the account first so both paths acquire rows in the same order.+ # A bare save of a persisted loan takes the reverse order (Loan, then Account+ # through Accountable's `touch: true`), so write existing loans through this+ # helper or two writers can deadlock.+ # Nested provider writes share the locks without reloading assigned values.+ def with_schedule_lock+ return yield if new_record? || @schedule_lock_held++ self.class.transaction do+ association(:account).scope.lock.pick(:id)+ with_lock do+ @schedule_lock_held = true+ begin+ yield+ ensure+ @schedule_lock_held = false+ end+ end+ end+ end++ # Provider updates may have been assembled from an older Loan instance.+ # Apply only their dated changes to the schedule read under the row lock.+ def enrich_attributes(attrs, **options)+ key = attrs.keys.find { |name| name.to_s == "variable_rate_schedule" }+ baseline = (variable_rate_schedule || {}).stringify_keys+ with_schedule_lock do+ updates = key ? attrs.merge(key => merge_rate_schedule(attrs[key], baseline: baseline)) : attrs+ super(updates, **options)+ end+ end++ # Keep the rendered schedule so a form can delete its own rows without+ # deleting dates a provider added after the form was opened.+ def rate_schedule_snapshot+ (variable_rate_schedule_in_database || {}).to_json+ end++ def rate_schedule_snapshot=(snapshot)+ @rate_schedule_snapshot = snapshot+ @rate_schedule_reconciliation = nil+ end+# What a provider should write when it reports this variable loan's rate on# `as_of`, or nil when there is nothing to write. Writes nothing itself, so# the provider's own writer keeps locks, provenance and refusal handling.@@ -200,6 +248,9 @@ class Loan < ApplicationRecordvalidate :rate_changes_must_be_parseablevalidate :rate_changes_must_not_precede_origination+ validate :rate_schedule_snapshot_must_be_valid+ before_validation :merge_submitted_rate_changes+ after_save :clear_rate_submission# Assembles variable_rate_schedule from the form's rows.#@@ -247,9 +298,77 @@ class Loan < ApplicationRecordend@invalid_rate_changes = invalid+ @submitted_rate_changes = parsed+ @rate_schedule_reconciliation = nilself.variable_rate_schedule = parsedend+ # Assigns the reconciled schedule once per submission. Later validations+ # leave the attribute alone, so a value assigned after the first one stays.+ private def merge_submitted_rate_changes+ reconciliation = rate_schedule_reconciliation+ return if reconciliation.nil? || reconciliation[:applied]++ self.variable_rate_schedule = reconciliation[:schedule]+ reconciliation[:applied] = true+ end++ # The submitted rows applied to the schedule read from the database, or that+ # schedule unchanged when the snapshot is malformed. Computed once per+ # submission without assigning attributes, so the form can render it before+ # validations run. Nil when there is no snapshot to reconcile against.+ private def rate_schedule_reconciliation+ return unless @submitted_rate_changes && @rate_schedule_snapshot++ @rate_schedule_reconciliation ||= begin+ baseline = JSON.parse(@rate_schedule_snapshot)+ raise JSON::ParserError unless baseline.is_a?(Hash)++ schedule = merge_rate_schedule(+ @submitted_rate_changes, baseline: baseline,+ current: variable_rate_schedule_in_database+ )+ { valid: true, schedule: schedule, applied: false }+ rescue JSON::ParserError, TypeError+ { valid: false, schedule: variable_rate_schedule_in_database || {}, applied: false }+ end+ end++ private def rate_schedule_snapshot_must_be_valid+ errors.add(:base, :invalid_rate_schedule_snapshot) if rate_schedule_reconciliation&.dig(:valid) == false+ end++ # Applies a submitter's edits to the schedule as it is now, given the+ # baseline the submitter saw. A submitted row equal to its baseline rate is+ # unchanged and does not overwrite the current value. A baseline date left+ # out of the submission deletes only the rate the submitter saw: if someone+ # else has changed that date since, their rate is kept. Any other submitted+ # row wins.+ private def merge_rate_schedule(submitted, baseline:, current: variable_rate_schedule)+ baseline = (baseline || {}).stringify_keys+ submitted = (submitted || {}).stringify_keys+ current = (current || {}).stringify_keys+ changed = submitted.reject { |date, rate| baseline.key?(date) && same_rate?(baseline[date], rate) }+ removed = (baseline.keys - submitted.keys).select do |date|+ current.key?(date) && same_rate?(current[date], baseline[date])+ end+ current.except(*removed).merge(changed)+ end++ # Compares rates by value, so "6", "6.0" and "0.6e1" are the same rate.+ # Values that do not parse as numbers compare as text.+ private def same_rate?(left, right)+ left_rate = BigDecimal(left.to_s, exception: false)+ right_rate = BigDecimal(right.to_s, exception: false)+ left_rate && right_rate ? left_rate == right_rate : left.to_s == right.to_s+ end++ private def clear_rate_submission+ @rate_schedule_snapshot = nil+ @submitted_rate_changes = nil+ @rate_schedule_reconciliation = nil+ end+# The form reaches this record through Account's nested attributes, which# validate it only when it has changes. Resubmitting the stored rows plus a# typo'd one leaves `variable_rate_schedule` equal to its stored value, so@@ -261,7 +380,8 @@ class Loan < ApplicationRecord# loan that has recorded rate changes and no start date; every other loan# answers from its own attributes.def changed_for_autosave?- super || invalid_rate_changes.present? || rate_changes_precede_origination?+ super || invalid_rate_changes.present? || rate_changes_precede_origination? ||+ (@rate_schedule_snapshot.present? && !@submitted_rate_changes.nil?)end# Form rows, in a shape the form can render without parsing anything.@@ -274,7 +394,12 @@ class Loan < ApplicationRecord## Invalid rows come back too, so a rejected save redisplays what was typed.def rate_change_rows- variable_rates.map { |date, rate| { effective_date: date.iso8601, rate: rate.to_s("F") } } ++ # A balance failure can render before validations run, so rows come from+ # the pending reconciliation until it is assigned. Reading them assigns+ # nothing and adds no errors; validation owns both.+ reconciliation = rate_schedule_reconciliation+ schedule = reconciliation && !reconciliation[:applied] ? reconciliation[:schedule] : variable_rate_schedule+ parse_rate_schedule(schedule).map { |date, rate| { effective_date: date.iso8601, rate: rate.to_s("F") } } +Array(invalid_rate_changes)end@@ -358,6 +483,7 @@ class Loan < ApplicationRecorddef reload(*)@amortization_schedule = nil@insurance = nil+ clear_rate_submissionsuperenddiff --git a/app/models/plaid_account/liabilities/loan_term_writer.rb b/app/models/plaid_account/liabilities/loan_term_writer.rbindex 6ab9f3c2cd..cbb5517864 100644--- a/app/models/plaid_account/liabilities/loan_term_writer.rb+++ b/app/models/plaid_account/liabilities/loan_term_writer.rb@@ -35,14 +35,20 @@ module PlaidAccount::Liabilities::LoanTermWriter# loan is applied before its rate is judged, then the rate. They land# together or not at all, as the single save did.#+ # Both run under the loan's schedule lock, which reloads the loan, so+ # the rate is judged against the schedule a concurrent form or provider+ # write left rather than the one this sync loaded.+ ## Enrichable logs the DataEnrichment before it saves, and a refused save# does not roll that row back. This transaction does, so provenance never# says Plaid supplied a value the loan rejected. `requires_new`, so the# rollback holds even when a caller has a transaction open.refusal = nil- loan.transaction(requires_new: true) do- refusal = enrich(loan, terms) || (rate.nil? ? nil : enrich(loan, rate_update(loan, rate)))- raise ActiveRecord::Rollback if refusal+ loan.with_schedule_lock do+ loan.transaction(requires_new: true) do+ refusal = enrich(loan, terms) || (rate.nil? ? nil : enrich(loan, rate_update(loan, rate)))+ raise ActiveRecord::Rollback if refusal+ endendreturn if refusal.nil?diff --git a/app/models/redbark_account/loan_details_processor.rb b/app/models/redbark_account/loan_details_processor.rbindex 6ef72c5713..11348e7ae7 100644--- a/app/models/redbark_account/loan_details_processor.rb+++ b/app/models/redbark_account/loan_details_processor.rb@@ -28,8 +28,10 @@ class RedbarkAccount::LoanDetailsProcessorreturn if details.blank?return unless details_fetched_this_sync?- apply_loan_terms- apply_rate+ loan.with_schedule_lock do+ apply_loan_terms+ apply_rate+ endendprivate@@ -244,14 +246,7 @@ class RedbarkAccount::LoanDetailsProcessordef write(attrs)return if attrs.blank?- # Enrichable rolls back its own savepoint when the save is refused, so no- # DataEnrichment row says Redbark supplied a value the loan rejected.- # That savepoint is the guarantee. This block can join a caller's- # transaction, and a Rollback raised in a joined block undoes nothing.- ActiveRecord::Base.transaction do- loan.enrich_attributes(attrs, source: SOURCE)- raise ActiveRecord::Rollback if loan.errors.any?- end+ loan.enrich_attributes(attrs, source: SOURCE)return if loan.errors.empty?capture(diff --git a/app/views/loans/_form.html.erb b/app/views/loans/_form.html.erbindex 4f6a0a7204..1f0c36af50 100644--- a/app/views/loans/_form.html.erb+++ b/app/views/loans/_form.html.erb@@ -2,6 +2,7 @@<%= render "accounts/form", account: account, url: url do |form| %><%= form.fields_for :accountable do |loan_form| %>+ <%= loan_form.hidden_field :rate_schedule_snapshot %><%# What kind of loan it is sits with the account's own fields, straightafter the balance, above the divider and the loan's terms. %><div>diff --git a/config/locales/models/loan/ca.yml b/config/locales/models/loan/ca.ymlindex 6ea1cd63b7..3dc34adc24 100644--- a/config/locales/models/loan/ca.yml+++ b/config/locales/models/loan/ca.yml@@ -5,4 +5,5 @@ ca:models:loan:invalid_rate_change: Les files de canvi de tipus necessiten una data d'efecte i un tipus d'interès.+ invalid_rate_schedule_snapshot: No s'han pogut comparar els canvis de tipus amb el calendari desat. Torneu a carregar el préstec i apliqueu de nou els canvis.rate_change_before_origination: Un canvi de tipus no pot tenir efecte abans de la data de formalització del préstec.diff --git a/config/locales/models/loan/de.yml b/config/locales/models/loan/de.ymlindex e4528e389a..8bff3be92b 100644--- a/config/locales/models/loan/de.yml+++ b/config/locales/models/loan/de.yml@@ -5,4 +5,5 @@ de:models:loan:invalid_rate_change: Jede Zinsänderung braucht einen Stichtag und einen Zinssatz.+ invalid_rate_schedule_snapshot: Die Zinsänderungen konnten nicht mit dem gespeicherten Zinsplan abgeglichen werden. Lade den Kredit neu und übernimm deine Änderungen erneut.rate_change_before_origination: Eine Zinsänderung kann nicht vor dem Beginn des Kredits wirksam werden.diff --git a/config/locales/models/loan/en.yml b/config/locales/models/loan/en.ymlindex 0ab2f5360f..825d87a015 100644--- a/config/locales/models/loan/en.yml+++ b/config/locales/models/loan/en.yml@@ -5,4 +5,5 @@ en:models:loan:invalid_rate_change: Rate change rows need both an effective date and a rate.+ invalid_rate_schedule_snapshot: The rate changes could not be compared with the saved schedule. Reload the loan and reapply your changes.rate_change_before_origination: A rate change cannot take effect before the loan originated.diff --git a/config/locales/models/loan/fr.yml b/config/locales/models/loan/fr.ymlindex 9e4229ba3f..4219cfcc8b 100644--- a/config/locales/models/loan/fr.yml+++ b/config/locales/models/loan/fr.yml@@ -5,4 +5,5 @@ fr:models:loan:invalid_rate_change: Chaque ligne de changement de taux doit comporter une date d'effet et un taux.+ invalid_rate_schedule_snapshot: Les changements de taux n'ont pas pu être comparés au calendrier enregistré. Rechargez le prêt et appliquez de nouveau vos modifications.rate_change_before_origination: Un changement de taux ne peut pas prendre effet avant le déblocage du prêt.diff --git a/config/locales/models/loan/id.yml b/config/locales/models/loan/id.ymlindex b501a531b3..4d40a86ec7 100644--- a/config/locales/models/loan/id.yml+++ b/config/locales/models/loan/id.yml@@ -5,4 +5,5 @@ id:models:loan:invalid_rate_change: Baris perubahan suku bunga memerlukan tanggal berlaku dan suku bunga.+ invalid_rate_schedule_snapshot: Perubahan suku bunga tidak dapat dibandingkan dengan jadwal yang tersimpan. Muat ulang pinjaman dan terapkan kembali perubahan Anda.rate_change_before_origination: Perubahan suku bunga tidak dapat berlaku sebelum pinjaman dimulai.diff --git a/config/locales/models/loan/nl.yml b/config/locales/models/loan/nl.ymlindex bcda59d14a..99cce18732 100644--- a/config/locales/models/loan/nl.yml+++ b/config/locales/models/loan/nl.yml@@ -5,4 +5,5 @@ nl:models:loan:invalid_rate_change: "Rijen met rentewijzigingen hebben zowel een ingangsdatum als een rentepercentage nodig."+ invalid_rate_schedule_snapshot: "De rentewijzigingen konden niet worden vergeleken met het opgeslagen renteschema. Laad de lening opnieuw en breng je wijzigingen opnieuw aan."rate_change_before_origination: "Een rentewijziging kan niet ingaan vóór de startdatum van de lening."diff --git a/config/locales/models/loan/ru.yml b/config/locales/models/loan/ru.ymlindex f3d20d4bb7..0e51e6d70a 100644--- a/config/locales/models/loan/ru.yml+++ b/config/locales/models/loan/ru.yml@@ -5,4 +5,5 @@ ru:models:loan:invalid_rate_change: Для каждого изменения ставки нужно указать дату вступления в силу и ставку.+ invalid_rate_schedule_snapshot: Не удалось сопоставить изменения ставки с сохранённым графиком. Перезагрузите кредит и внесите изменения заново.rate_change_before_origination: Изменение ставки не может вступить в силу раньше даты выдачи кредита.diff --git a/config/locales/models/loan/tr.yml b/config/locales/models/loan/tr.ymlindex d5e96da477..a2d38e2f05 100644--- a/config/locales/models/loan/tr.yml+++ b/config/locales/models/loan/tr.yml@@ -5,4 +5,5 @@ tr:models:loan:invalid_rate_change: Faiz oranı değişikliği satırlarında hem geçerlilik tarihi hem de oran bulunmalıdır.+ invalid_rate_schedule_snapshot: Faiz oranı değişiklikleri kayıtlı takvimle karşılaştırılamadı. Krediyi yeniden yükleyin ve değişikliklerinizi tekrar uygulayın.rate_change_before_origination: Faiz oranı değişikliği, kredinin kullandırım tarihinden önce geçerli olamaz.diff --git a/config/locales/models/loan/uk.yml b/config/locales/models/loan/uk.ymlindex 064a04f4c8..345d0e6e2a 100644--- a/config/locales/models/loan/uk.yml+++ b/config/locales/models/loan/uk.yml@@ -5,4 +5,5 @@ uk:models:loan:invalid_rate_change: Для кожної зміни ставки потрібні дата набрання чинності та ставка.+ invalid_rate_schedule_snapshot: Не вдалося зіставити зміни ставки зі збереженим графіком. Перезавантажте позику та внесіть зміни повторно.rate_change_before_origination: Зміна ставки не може набрати чинності раніше за дату видачі позики.diff --git a/config/locales/models/loan/zh-CN.yml b/config/locales/models/loan/zh-CN.ymlindex d527117aa8..2502dbd738 100644--- a/config/locales/models/loan/zh-CN.yml+++ b/config/locales/models/loan/zh-CN.yml@@ -5,4 +5,5 @@ zh-CN:models:loan:invalid_rate_change: 利率变更行需要同时填写生效日期和利率。+ invalid_rate_schedule_snapshot: 无法将利率变更与已保存的利率表进行比对。请重新加载贷款后再次应用你的修改。rate_change_before_origination: 利率变更不能在贷款发放日之前生效。diff --git a/config/locales/views/loans/en.yml b/config/locales/views/loans/en.ymlindex 6b9fb46e20..ecfaf6f4e4 100644--- a/config/locales/views/loans/en.yml+++ b/config/locales/views/loans/en.yml@@ -3,6 +3,7 @@ en:loans:edit:edit: Edit %{account}+ stale_rate_schedule: This form is out of date. Reload the loan and reapply your changes. Nothing has been saved.form:interest_rate: Interest rateinterest_rate_placeholder: '5.25'diff --git a/config/locales/views/loans/zh-CN.yml b/config/locales/views/loans/zh-CN.ymlindex 8d0e8c0a7f..a8a8e4e6cf 100644--- a/config/locales/views/loans/zh-CN.yml+++ b/config/locales/views/loans/zh-CN.yml@@ -3,6 +3,7 @@ zh-CN:loans:edit:edit: 编辑%{account}+ stale_rate_schedule: 此表单已过期。请重新加载贷款页面后再次编辑,本次修改未保存。form:interest_rate: 利率interest_rate_placeholder: '5.25'diff --git a/test/controllers/loans_controller_locking_test.rb b/test/controllers/loans_controller_locking_test.rbnew file mode 100644index 0000000000..33f38e27de--- /dev/null+++ b/test/controllers/loans_controller_locking_test.rb@@ -0,0 +1,201 @@+require "test_helper"++class LoansControllerLockingTest < ActionDispatch::IntegrationTest+ self.use_transactional_tests = false++ setup do+ @user = users(:family_admin).dup+ @user.email = "loan-locking-#{SecureRandom.uuid}@example.com"+ @user.password = user_password_test+ @user.save!+ sign_in @user+ @account = @user.family.accounts.create!(+ name: "Loan rendering", balance: 100_000, currency: "USD",+ accountable: Loan.new(rate_type: "variable", interest_rate: 6, start_date: Date.new(2024, 1, 1),+ variable_rate_schedule: { "2026-01-01" => "7" })+ )+ end++ teardown do+ @account&.destroy!+ @plaid_account&.destroy!+ @user&.destroy!+ end++ test "a balance edit compares with the account committed before the lock" do+ snapshot = @account.loan.rate_schedule_snapshot++ with_concurrent_account_update(balance: 90_000, currency: "EUR", notes: "Provider notes",+ locked_attributes: { "notes" => Time.current.iso8601 }) do+ patch loan_path(@account), params: { account: {+ name: "Edited loan", balance: 100_000, accountable_attributes: {+ rate_schedule_snapshot: snapshot,+ rate_changes: [ { effective_date: "2026-03-01", rate: "9" } ]+ }+ } }+ end++ assert_redirected_to account_path(@account)+ assert_equal 100_000, @account.reload.balance+ assert_equal "Edited loan", @account.name+ assert_equal "Provider notes", @account.notes+ assert @account.locked?("notes")+ assert_equal "EUR", @account.currency+ assert_equal [ "EUR" ], @account.entries.distinct.pluck(:currency)+ assert_equal({ "2026-02-01" => "8", "2026-03-01" => "9.0" }, @account.loan.variable_rate_schedule)+ end++ test "a balance already committed before the lock does not create another valuation" do+ assert_no_difference "Entry.count" do+ with_concurrent_account_update(balance: 90_000) do+ patch loan_path(@account), params: { account: { name: "Edited loan", balance: 90_000 } }+ end+ end++ assert_redirected_to account_path(@account)+ assert_equal 90_000, @account.reload.balance+ assert_equal "Edited loan", @account.name+ end++ test "a failed balance edit preserves the concurrent account and schedule on retry" do+ snapshot = @account.loan.rate_schedule_snapshot+ assert_no_difference "Entry.count" do+ with_concurrent_account_update(balance: 90_000, notes: "Provider notes") do+ patch loan_path(@account), params: { account: {+ name: "Rejected name", balance: 100_000, accountable_attributes: {+ rate_schedule_snapshot: snapshot,+ rate_changes: [ { effective_date: "", rate: "9" } ]+ }+ } }+ end+ end++ assert_response :unprocessable_entity+ assert_equal 90_000, @account.reload.balance+ assert_equal "Loan rendering", @account.name+ assert_equal "Provider notes", @account.notes+ expected = { "2026-01-01" => "7", "2026-02-01" => "8" }+ assert_equal expected, @account.loan.variable_rate_schedule+ snapshot = css_select("input[name='account[accountable_attributes][rate_schedule_snapshot]']").first["value"]+ assert_equal expected, JSON.parse(snapshot)++ patch loan_path(@account), params: { account: { balance: 90_000, accountable_attributes: {+ rate_schedule_snapshot: snapshot,+ rate_changes: expected.map { |date, rate| { effective_date: date, rate: rate } }+ } } }++ assert_redirected_to account_path(@account)+ assert_equal 90_000, @account.reload.balance+ assert_equal expected, @account.loan.variable_rate_schedule+ end++ test "a linked loan rolls back a rejected balance edit and saves its anchor on retry" do+ @plaid_account = PlaidAccount.create!(+ plaid_item: plaid_items(:one), plaid_id: SecureRandom.uuid, name: "Linked loan", currency: "USD",+ current_balance: 100_000, plaid_type: "loan", plaid_subtype: "mortgage"+ )+ @account.account_providers.create!(provider: @plaid_account)+ assert @account.reload.linked?+ snapshot = @account.loan.rate_schedule_snapshot++ assert_no_difference "Entry.count" do+ with_concurrent_account_update(balance: 90_000, currency: "EUR") do+ patch loan_path(@account), params: { account: { balance: 100_000, accountable_attributes: {+ rate_schedule_snapshot: snapshot, rate_changes: [ { effective_date: "", rate: "9" } ]+ } } }+ end+ end++ assert_response :unprocessable_entity+ assert_equal 90_000, @account.reload.balance+ assert_empty @account.valuations.current_anchor+ snapshot = css_select("input[name='account[accountable_attributes][rate_schedule_snapshot]']").first["value"]++ patch loan_path(@account), params: { account: { name: "Linked edit", balance: 100_000, accountable_attributes: {+ rate_schedule_snapshot: snapshot,+ rate_changes: [ { effective_date: "2026-01-01", rate: "7" }, { effective_date: "2026-02-01", rate: "8" } ]+ } } }++ assert_redirected_to account_path(@account)+ assert_equal 100_000, @account.reload.balance+ assert_equal "Linked edit", @account.name+ assert_equal 1, @account.valuations.current_anchor.count+ anchor = @account.valuations.current_anchor.first.entry+ assert_equal 100_000, anchor.amount+ assert_equal "EUR", anchor.currency+ assert_equal({ "2026-01-01" => "7", "2026-02-01" => "8" }, @account.loan.variable_rate_schedule)+ end++ test "all rejected update forms render after account and loan locks are released" do+ submissions = [+ { rate_changes: [] },+ { rate_schedule_snapshot: "[]", rate_changes: [] },+ { rate_schedule_snapshot: @account.loan.rate_schedule_snapshot, rate_changes: [ { effective_date: "", rate: "9" } ] }+ ]+ submissions.each do |attributes|+ rendered = 0+ subscriber = lambda do |event|+ next unless event.payload[:identifier].to_s.end_with?("/loans/edit.html.erb")++ Thread.new do+ ActiveRecord::Base.connection_pool.with_connection do |connection|+ connection.transaction do+ Account.where(id: @account.id).lock("FOR UPDATE NOWAIT").pick(:id)+ Loan.where(id: @account.accountable_id).lock("FOR UPDATE NOWAIT").pick(:id)+ end+ end+ end.value+ rendered += 1+ end++ ActiveSupport::Notifications.subscribed(subscriber, "render_template.action_view") do+ patch loan_path(@account), params: { account: { accountable_attributes: attributes } }+ end++ assert_response :unprocessable_entity+ assert_equal 1, rendered+ end+ end++ private+ # Commits a provider-style update from another connection just before the+ # request takes its account row lock, after it has loaded the account and+ # loan it will update. The hook is a notification subscription scoped to+ # the block, so it cannot outlive the test.+ def with_concurrent_account_update(attributes)+ account_id = @account.id+ request_thread = Thread.current+ loaded_before_lock = []+ fired = 0+ failure = nil++ hook = Object.new+ hook.define_singleton_method(:start) do |_name, _id, payload|+ next unless Thread.current == request_thread && fired.zero?+ next unless payload[:sql].match?(/FROM "accounts".*FOR UPDATE/m)++ fired += 1+ Thread.new do+ ActiveRecord::Base.connection_pool.with_connection do+ account = Account.find(account_id)+ account.update!(attributes)+ account.loan.enrich_attributes(+ { variable_rate_schedule: { "2026-01-01" => "7", "2026-02-01" => "8" } }, source: "redbark"+ )+ end+ rescue StandardError => e+ failure = e+ end.join+ end+ hook.define_singleton_method(:finish) do |_name, _id, payload|+ loaded_before_lock << payload[:name] if Thread.current == request_thread && fired.zero?+ end++ ActiveSupport::Notifications.subscribed(hook, "sql.active_record") { yield }++ raise failure if failure+ assert_equal 1, fired, "the concurrent update should run once, before the request locks the account"+ assert_includes loaded_before_lock, "Account Load"+ assert_includes loaded_before_lock, "Loan Load"+ end+enddiff --git a/test/controllers/loans_controller_test.rb b/test/controllers/loans_controller_test.rbindex caf2337d25..bcfeb772b4 100644--- a/test/controllers/loans_controller_test.rb+++ b/test/controllers/loans_controller_test.rb@@ -8,6 +8,186 @@ class LoansControllerTest < ActionDispatch::IntegrationTest@account = accounts(:loan)end+ test "old forms without a schedule snapshot cannot overwrite provider rows or account fields" do+ @account.loan.update!(rate_type: "variable", start_date: Date.new(2024, 1, 1),+ variable_rate_schedule: { "2026-01-01" => "6" })+ @account.loan.enrich_attributes(+ { variable_rate_schedule: { "2026-01-01" => "6", "2026-02-01" => "7" } }, source: "redbark"+ )+ original_name = @account.name+ original_balance = @account.balance+ [ nil, "" ].each do |snapshot|+ attrs = { rate_changes: [ { effective_date: "2026-01-01", rate: "6" } ] }+ attrs[:rate_schedule_snapshot] = snapshot unless snapshot.nil?++ assert_no_difference [ "Entry.count", "DataEnrichment.count" ] do+ patch loan_path(@account), params: { account: {+ name: "Outdated edit", balance: original_balance - 1000, accountable_attributes: attrs+ } }+ end++ assert_response :unprocessable_entity+ assert_match I18n.t("loans.edit.stale_rate_schedule"), response.body+ assert_select "input[name='account[accountable_attributes][rate_changes][][effective_date]'][value='2026-02-01']", count: 1+ assert_equal original_name, @account.reload.name+ assert_equal original_balance, @account.balance+ assert_equal({ "2026-01-01" => "6", "2026-02-01" => "7" }, @account.loan.variable_rate_schedule)+ end+ end++ test "an old form cannot clear the schedule without a snapshot" do+ @account.loan.update!(rate_type: "variable", start_date: Date.new(2024, 1, 1),+ variable_rate_schedule: { "2026-01-01" => "6" })++ patch loan_path(@account), params: { account: { accountable_attributes: { rate_changes: [ "" ] } } }++ assert_response :unprocessable_entity+ assert_equal({ "2026-01-01" => "6" }, @account.loan.reload.variable_rate_schedule)+ end++ test "a stale form preserves provider dates while deleting and adding its own rows" do+ @account.loan.update!(rate_type: "variable", start_date: Date.new(2024, 1, 1),+ variable_rate_schedule: { "2026-01-01" => "6" })+ get edit_loan_path(@account)+ assert_response :success+ snapshot = css_select("input[name='account[accountable_attributes][rate_schedule_snapshot]']").first["value"]++ @account.loan.enrich_attributes(+ { variable_rate_schedule: { "2026-01-01" => "6", "2026-02-01" => "7" } }, source: "redbark"+ )+ patch loan_path(@account), params: { account: { accountable_attributes: {+ rate_schedule_snapshot: snapshot,+ rate_changes: [ { effective_date: "2026-03-01", rate: "8" } ]+ } } }++ assert_response :redirect+ assert_equal({ "2026-02-01" => "7", "2026-03-01" => "8.0" }, @account.loan.reload.variable_rate_schedule)+ end++ {+ "deleting" => [ [ "" ], { "2026-01-01" => "7" } ],+ "moving" => [ [ "", { effective_date: "2026-01-15", rate: "6" } ], { "2026-01-01" => "7", "2026-01-15" => "6.0" } ]+ }.each do |action, (rate_changes, expected)|+ test "a stale form #{action} a rendered row keeps the provider's correction of it" do+ @account.loan.update!(rate_type: "variable", start_date: Date.new(2024, 1, 1),+ variable_rate_schedule: { "2026-01-01" => "6" })+ get edit_loan_path(@account)+ assert_response :success+ snapshot = css_select("input[name='account[accountable_attributes][rate_schedule_snapshot]']").first["value"]++ @account.loan.enrich_attributes({ variable_rate_schedule: { "2026-01-01" => "7" } }, source: "redbark")+ patch loan_path(@account), params: { account: { accountable_attributes: {+ rate_schedule_snapshot: snapshot, rate_changes: rate_changes+ } } }++ assert_response :redirect+ assert_equal expected, @account.loan.reload.variable_rate_schedule+ end+ end++ test "an invalid schedule snapshot is rejected even with no changed rate rows" do+ @account.loan.update!(rate_type: "variable", variable_rate_schedule: {})+ patch loan_path(@account), params: { account: { accountable_attributes: {+ rate_schedule_snapshot: "[]", rate_changes: []+ } } }++ assert_response :unprocessable_entity+ assert_match I18n.t("activerecord.errors.models.loan.invalid_rate_schedule_snapshot"), response.body+ assert_empty @account.loan.reload.variable_rate_schedule+ end++ test "malformed snapshots redisplay persisted provider rows and cannot delete them on retry" do+ @account.loan.update!(rate_type: "variable", start_date: Date.new(2024, 1, 1),+ variable_rate_schedule: { "2026-01-01" => "6", "2026-02-01" => "7" })+ [ "{broken", "[]", "null", "5" ].each do |invalid_snapshot|+ patch loan_path(@account), params: { account: { accountable_attributes: {+ rate_schedule_snapshot: invalid_snapshot, rate_changes: [ { effective_date: "2026-01-01", rate: "6" } ]+ } } }++ assert_response :unprocessable_entity+ assert_match I18n.t("activerecord.errors.models.loan.invalid_rate_schedule_snapshot"), response.body+ assert_no_match I18n.t("activerecord.errors.models.loan.invalid_rate_change"), response.body+ assert_select "input[name='account[accountable_attributes][rate_changes][][effective_date]'][value='2026-02-01']", count: 1+ snapshot = css_select("input[name='account[accountable_attributes][rate_schedule_snapshot]']").first["value"]+ rows = css_select("[data-rate-change-row]").filter_map do |row|+ date = row.at_css("input[name$='[effective_date]']")["value"]+ rate = row.at_css("input[name$='[rate]']")["value"]+ { effective_date: date, rate: rate } if date.present?+ end++ patch loan_path(@account), params: { account: { accountable_attributes: {+ rate_schedule_snapshot: snapshot, rate_changes: rows+ } } }+ assert_response :redirect+ assert_equal({ "2026-01-01" => "6", "2026-02-01" => "7" }, @account.loan.reload.variable_rate_schedule)+ end+ end++ test "an unchanged form row does not overwrite a provider correction on the same date" do+ @account.loan.update!(rate_type: "variable", start_date: Date.new(2024, 1, 1),+ variable_rate_schedule: { "2026-01-01" => "0.6e1" })+ snapshot = @account.loan.rate_schedule_snapshot+ @account.loan.enrich_attributes({ variable_rate_schedule: { "2026-01-01" => "7" } }, source: "redbark")++ patch loan_path(@account), params: { account: { name: "Reviewed", accountable_attributes: {+ rate_schedule_snapshot: snapshot, rate_changes: [ { effective_date: "2026-01-01", rate: "6.0" } ]+ } } }++ assert_response :redirect+ assert_equal({ "2026-01-01" => "7" }, @account.loan.reload.variable_rate_schedule)+ end++ test "rows shown after a validation error can be removed on resubmission" do+ @account.loan.update!(rate_type: "variable", start_date: Date.new(2024, 1, 1), variable_rate_schedule: {})+ snapshot = @account.loan.rate_schedule_snapshot+ @account.loan.enrich_attributes({ variable_rate_schedule: { "2026-01-01" => "7" } }, source: "redbark")++ patch loan_path(@account), params: { account: { accountable_attributes: {+ rate_schedule_snapshot: snapshot, rate_changes: [ { effective_date: "", rate: "8" } ]+ } } }+ assert_response :unprocessable_entity+ snapshot = css_select("input[name='account[accountable_attributes][rate_schedule_snapshot]']").first["value"]+ assert_equal({ "2026-01-01" => "7" }, JSON.parse(snapshot))++ patch loan_path(@account), params: { account: { accountable_attributes: {+ rate_schedule_snapshot: snapshot, rate_changes: []+ } } }+ assert_response :redirect+ assert_empty @account.loan.reload.variable_rate_schedule+ end++ test "a failed balance update preserves provider rows through the rendered form and retry" do+ @account.loan.update!(rate_type: "variable", start_date: Date.new(2024, 1, 1),+ variable_rate_schedule: { "2026-01-01" => "6" })+ snapshot = @account.loan.rate_schedule_snapshot+ @account.loan.enrich_attributes(+ { variable_rate_schedule: { "2026-01-01" => "6", "2026-02-01" => "7" } }, source: "redbark"+ )+ failure = Account::CurrentBalanceManager::Result.new(success?: false, changes_made?: false, error: "Balance update failed")+ Account.any_instance.stubs(:set_current_balance).returns(failure)++ patch loan_path(@account), params: { account: { balance: @account.balance - 1000, accountable_attributes: {+ rate_schedule_snapshot: snapshot,+ rate_changes: [ { effective_date: "2026-03-01", rate: "8" }, { effective_date: "", rate: "9" } ]+ } } }+ assert_response :unprocessable_entity+ assert_select "input[name='account[accountable_attributes][rate_changes][][effective_date]'][value='2026-02-01']", count: 1+ assert_select "input[name='account[accountable_attributes][rate_changes][][rate]'][value='9']", count: 1+ snapshot = css_select("input[name='account[accountable_attributes][rate_schedule_snapshot]']").first["value"]+ rows = css_select("[data-rate-change-row]").filter_map do |row|+ date = row.at_css("input[name$='[effective_date]']")["value"]+ rate = row.at_css("input[name$='[rate]']")["value"]+ { effective_date: date, rate: rate } if date.present?+ end+ Account.any_instance.unstub(:set_current_balance)++ patch loan_path(@account), params: { account: { balance: @account.balance - 1000, accountable_attributes: {+ rate_schedule_snapshot: snapshot, rate_changes: rows+ } } }+ assert_response :redirect+ assert_equal({ "2026-02-01" => "7", "2026-03-01" => "8.0" }, @account.loan.reload.variable_rate_schedule)+ end+# The overview only shows what the loan actually records: a leverage figure# needs a down payment, and an insurance card needs a premium. A loan with# neither must not grow cards reading zero, which would say the borrower has@@ -392,6 +572,7 @@ class LoansControllerTest < ActionDispatch::IntegrationTestid: @account.loan.id,rate_type: "variable",start_date: "2024-03-15",+ rate_schedule_snapshot: @account.loan.rate_schedule_snapshot,rate_changes: [{ effective_date: "2026-04-01", rate: "7.25" },{ effective_date: "2026-10-01", rate: "6.5" },@@ -471,6 +652,7 @@ class LoansControllerTest < ActionDispatch::IntegrationTestpatch loan_path(@account), params: {account: { accountable_attributes: {id: @account.loan.id, rate_type: "variable",+ rate_schedule_snapshot: @account.loan.rate_schedule_snapshot,rate_changes: [ { effective_date: "", rate: "9" } ]} }}@@ -495,7 +677,8 @@ class LoansControllerTest < ActionDispatch::IntegrationTest# as "" and strong parameters drop, so the writer receives an empty array.patch loan_path(@account), params: {account: { accountable_attributes: {- id: @account.loan.id, rate_type: "variable", rate_changes: [ "" ]+ id: @account.loan.id, rate_type: "variable", rate_schedule_snapshot: @account.loan.rate_schedule_snapshot,+ rate_changes: [ "" ]} }}@@ -590,6 +773,7 @@ class LoansControllerTest < ActionDispatch::IntegrationTestpatch loan_path(@account), params: { account: { accountable_attributes: {id: @account.loan.id, rate_type: "variable",+ rate_schedule_snapshot: @account.loan.rate_schedule_snapshot,rate_changes: [ "", { effective_date: "2026-04-01", rate: "7.25" }, { effective_date: "", rate: "9" } ]} } }@@ -618,6 +802,7 @@ class LoansControllerTest < ActionDispatch::IntegrationTest# inputs are enabled: the sentinel and the row it rendered.patch loan_path(@account), params: { account: { accountable_attributes: {id: @account.loan.id, rate_type: "variable",+ rate_schedule_snapshot: @account.loan.rate_schedule_snapshot,rate_changes: [ "", { effective_date: "2026-04-01", rate: "7.25" } ]} } }@@ -873,6 +1058,7 @@ class LoansControllerTest < ActionDispatch::IntegrationTestbalance: balance_before - 10_000,accountable_attributes: {id: @account.loan.id, rate_type: "variable",+ rate_schedule_snapshot: @account.loan.rate_schedule_snapshot,rate_changes: [ "", { effective_date: "2026-04-01", rate: "7.25" }, { effective_date: "", rate: "9" } ]}} }diff --git a/test/models/loan/schedule_lock_test.rb b/test/models/loan/schedule_lock_test.rbnew file mode 100644index 0000000000..e7a7a6ecf5--- /dev/null+++ b/test/models/loan/schedule_lock_test.rb@@ -0,0 +1,419 @@+require "test_helper"+require "timeout"+require "ostruct"++class Loan::ScheduleLockTest < ActiveSupport::TestCase+ self.use_transactional_tests = false++ setup do+ @loan = Loan.create!(rate_type: "variable", interest_rate: 5, start_date: Date.new(2024, 1, 1))+ end++ teardown do+ @loan.destroy!+ end++ test "provider schedules assembled from stale instances retain both dates" do+ stale = Loan.find(@loan.id)+ @loan.enrich_attributes({ variable_rate_schedule: { "2026-01-01" => "6" } }, source: "redbark")+ stale.enrich_attributes({ variable_rate_schedule: { "2026-02-01" => "7" } }, source: "plaid")++ assert_equal({ "2026-01-01" => "6", "2026-02-01" => "7" }, @loan.reload.variable_rate_schedule)+ end++ test "the last provider update for the same date wins" do+ stale = Loan.find(@loan.id)+ @loan.enrich_attributes({ variable_rate_schedule: { "2026-01-01" => "6" } }, source: "redbark")+ stale.enrich_attributes({ variable_rate_schedule: { "2026-01-01" => "7" } }, source: "plaid")++ assert_equal({ "2026-01-01" => "7" }, @loan.reload.variable_rate_schedule)+ end++ test "the outer lock refreshes the rate before deciding that a provider reading is unchanged" do+ @loan.update!(interest_rate: 6)+ stale = Loan.find(@loan.id)+ as_of = Date.new(2026, 2, 1)+ assert_equal BigDecimal("6"), stale.current_variable_rate(as_of)+ @loan.enrich_attributes({ variable_rate_schedule: { "2026-01-01" => "7" } }, source: "redbark")++ stale.with_schedule_lock do+ unless stale.current_variable_rate(as_of) == BigDecimal("6")+ stale.enrich_attributes(+ { variable_rate_schedule: stale.variable_rate_schedule.merge(as_of.iso8601 => "6") }, source: "plaid"+ )+ end+ end++ assert_equal({ "2026-01-01" => "7", "2026-02-01" => "6" }, @loan.reload.variable_rate_schedule)+ end++ test "provider schedule updates respect user attribute locks" do+ stale = Loan.find(@loan.id)+ @loan.lock_attr!(:variable_rate_schedule)+ stale.enrich_attributes({ variable_rate_schedule: { "2026-01-01" => "6" } }, source: "redbark")++ assert_empty @loan.reload.variable_rate_schedule+ assert_empty @loan.data_enrichments+ end++ test "a form snapshot preserves new provider dates and allows deleting rendered dates" do+ @loan.update!(variable_rate_schedule: { "2026-01-01" => "6" })+ snapshot = @loan.rate_schedule_snapshot+ @loan.enrich_attributes({ variable_rate_schedule: { "2026-01-01" => "6", "2026-02-01" => "7" } }, source: "redbark")++ @loan.with_schedule_lock do+ @loan.update!(rate_schedule_snapshot: snapshot, rate_changes: [ { effective_date: "2026-03-01", rate: "8" } ])+ end++ assert_equal({ "2026-02-01" => "7", "2026-03-01" => "8.0" }, @loan.reload.variable_rate_schedule)+ end++ test "a form deleting a rendered date keeps a provider correction made after rendering" do+ @loan.update!(variable_rate_schedule: { "2026-01-01" => "6" })+ snapshot = @loan.rate_schedule_snapshot+ Loan.find(@loan.id).enrich_attributes({ variable_rate_schedule: { "2026-01-01" => "7" } }, source: "redbark")++ @loan.with_schedule_lock do+ @loan.update!(rate_schedule_snapshot: snapshot, rate_changes: [])+ end++ assert_equal({ "2026-01-01" => "7" }, @loan.reload.variable_rate_schedule)+ end++ test "a form moving a rendered date keeps a provider correction made after rendering" do+ @loan.update!(variable_rate_schedule: { "2026-01-01" => "6" })+ snapshot = @loan.rate_schedule_snapshot+ Loan.find(@loan.id).enrich_attributes({ variable_rate_schedule: { "2026-01-01" => "7" } }, source: "redbark")++ @loan.with_schedule_lock do+ @loan.update!(rate_schedule_snapshot: snapshot, rate_changes: [ { effective_date: "2026-01-15", rate: "6" } ])+ end++ assert_equal({ "2026-01-01" => "7", "2026-01-15" => "6.0" }, @loan.reload.variable_rate_schedule)+ end++ test "a form deletes a rendered date whose stored rate was rewritten in another format" do+ @loan.update!(variable_rate_schedule: { "2026-01-01" => "0.6e1" })+ snapshot = @loan.rate_schedule_snapshot+ Loan.find(@loan.id).update!(variable_rate_schedule: { "2026-01-01" => "6.0" })++ @loan.with_schedule_lock do+ @loan.update!(rate_schedule_snapshot: snapshot, rate_changes: [])+ end++ assert_empty @loan.reload.variable_rate_schedule+ end++ test "a stale provider schedule that omits a date keeps a correction made since it loaded" do+ @loan.update!(variable_rate_schedule: { "2026-01-01" => "6" })+ stale = Loan.find(@loan.id)+ @loan.enrich_attributes({ variable_rate_schedule: { "2026-01-01" => "7" } }, source: "redbark")+ stale.enrich_attributes({ variable_rate_schedule: { "2026-02-01" => "8" } }, source: "plaid")++ assert_equal({ "2026-01-01" => "7", "2026-02-01" => "8" }, @loan.reload.variable_rate_schedule)+ end++ test "an invalid form snapshot refuses the save" do+ assert_not @loan.update(rate_schedule_snapshot: "[]", rate_changes: [])+ assert_equal [ { error: :invalid_rate_schedule_snapshot } ], @loan.errors.details[:base]+ end++ test "a committed loan retries after a real rollback by explicitly reloading the same instance" do+ assert_equal 0, Loan.connection.open_transactions+ loan = @loan+ loan.update!(variable_rate_schedule: { "2026-01-01" => "7" })+ snapshot = loan.rate_schedule_snapshot+ rows = [ { effective_date: "2026-03-01", rate: "9" } ]++ Loan.transaction do+ loan.update!(rate_schedule_snapshot: snapshot, rate_changes: rows)+ assert_not loan.changed_for_autosave?+ assert_equal({ "2026-03-01" => "9.0" }, Loan.find(loan.id).variable_rate_schedule)+ raise ActiveRecord::Rollback+ end++ assert_equal 0, Loan.connection.open_transactions+ assert_equal({ "2026-01-01" => "7" }, Loan.find(loan.id).variable_rate_schedule)+ assert loan.has_changes_to_save?+ error = assert_raises(RuntimeError) { loan.with_schedule_lock { flunk "Dirty retries must not acquire the lock" } }+ assert_includes error.message, "unpersisted changes"++ loan_id = loan.id+ Thread.new do+ ActiveRecord::Base.connection_pool.with_connection do+ Loan.find(loan_id).enrich_attributes(+ { variable_rate_schedule: { "2026-01-01" => "7", "2026-02-01" => "8" } }, source: "redbark"+ )+ end+ end.value++ assert_same loan, loan.reload+ assert_not loan.has_changes_to_save?+ loan.with_schedule_lock do+ loan.assign_attributes(rate_schedule_snapshot: snapshot, rate_changes: rows)+ 2.times do+ assert loan.valid?+ assert_equal [ "2026-02-01", "2026-03-01" ], loan.rate_change_rows.pluck(:effective_date)+ end+ loan.save!+ end++ assert_equal({ "2026-02-01" => "8", "2026-03-01" => "9.0" }, Loan.find(loan.id).variable_rate_schedule)+ assert_not loan.changed_for_autosave?+ end++ test "concurrent connections serialize provider schedule writes" do+ held = Queue.new+ release = Queue.new+ second_pid = Queue.new+ id = @loan.id++ first = Thread.new do+ ActiveRecord::Base.connection_pool.with_connection do |connection|+ Thread.current[:schedule_lock_backend_pid] = connection.select_value("SELECT pg_backend_pid()").to_i+ loan = Loan.find(id)+ loan.with_schedule_lock do+ loan.enrich_attributes({ variable_rate_schedule: { "2026-01-01" => "6" } }, source: "redbark")+ held << true+ Timeout.timeout(10) { release.pop }+ end+ end+ end+ Timeout.timeout(10) { held.pop }++ second = Thread.new do+ ActiveRecord::Base.connection_pool.with_connection do |connection|+ Thread.current[:schedule_lock_backend_pid] = connection.select_value("SELECT pg_backend_pid()").to_i+ stale = Loan.find(id)+ second_pid << connection.select_value("SELECT pg_backend_pid()").to_i+ stale.enrich_attributes({ variable_rate_schedule: { "2026-02-01" => "7" } }, source: "plaid")+ end+ end+ pid = Timeout.timeout(10) { second_pid.pop }+ wait_for_lock(pid)+ release << true+ [ first, second ].each(&:value)++ assert_equal({ "2026-01-01" => "6", "2026-02-01" => "7" }, @loan.reload.variable_rate_schedule)+ ensure+ release << true+ stop_workers(first, second)+ end++ test "account-first provider updates and schedule writes use the same lock order" do+ account = families(:empty).accounts.create!(name: "Loan", currency: "USD", balance: 0, accountable: @loan)+ held = Queue.new+ release = Queue.new+ second_pid = Queue.new+ id = @loan.id++ first = Thread.new do+ ActiveRecord::Base.connection_pool.with_connection do |connection|+ Thread.current[:schedule_lock_backend_pid] = connection.select_value("SELECT pg_backend_pid()").to_i+ Account.transaction do+ provider_account = Account.find(account.id)+ provider_account.update!(name: "Provider name")+ held << true+ Timeout.timeout(10) { release.pop }+ provider_account.accountable.enrich_attributes({ subtype: "mortgage" }, source: "plaid")+ end+ end+ end+ Timeout.timeout(10) { held.pop }+ second = Thread.new do+ ActiveRecord::Base.connection_pool.with_connection do |connection|+ Thread.current[:schedule_lock_backend_pid] = connection.select_value("SELECT pg_backend_pid()").to_i+ loan = Loan.find(id)+ second_pid << connection.select_value("SELECT pg_backend_pid()").to_i+ loan.with_schedule_lock do+ loan.enrich_attributes({ variable_rate_schedule: { "2026-01-01" => "6" } }, source: "redbark")+ end+ end+ end+ pid = Timeout.timeout(10) { second_pid.pop }+ wait_for_lock(pid)+ release << true+ [ first, second ].each(&:value)++ assert_equal "mortgage", @loan.reload.subtype+ assert_equal({ "2026-01-01" => "6" }, @loan.variable_rate_schedule)+ ensure+ release << true+ stop_workers(first, second)+ account&.destroy!+ end++ # The writer reads the loan before taking the lock; the lock must refresh it+ # before the rate is judged. A variable loan whose rate a concurrent write+ # already moved to the reported figure records no row, and a fixed one takes+ # the reported rate without losing the schedule written beside it.+ {+ PlaidAccount::Liabilities::MortgageProcessor => { interest_rate: BigDecimal("5"), rate_type: "variable" },+ PlaidAccount::Liabilities::StudentLoanProcessor => { interest_rate: BigDecimal("7"), rate_type: "fixed" }+ }.each do |processor_class, expected|+ test "#{processor_class.name} shares the schedule writer lock order" do+ account = families(:empty).accounts.create!(name: "Loan", currency: "USD", balance: 0, accountable: @loan)+ held = Queue.new+ release = Queue.new+ second_pid = Queue.new+ plaid_item = plaid_items(:one)++ first = Thread.new do+ ActiveRecord::Base.connection_pool.with_connection do |connection|+ Thread.current[:schedule_lock_backend_pid] = connection.select_value("SELECT pg_backend_pid()").to_i+ Account.transaction do+ writer_account = Account.find(account.id)+ writer_account.update!(name: "Updated")+ held << true+ Timeout.timeout(10) { release.pop }+ writer_account.loan.enrich_attributes({ variable_rate_schedule: { "2026-01-01" => "7" } }, source: "redbark")+ end+ end+ end+ Timeout.timeout(10) { held.pop }+ second = Thread.new do+ ActiveRecord::Base.connection_pool.with_connection do |connection|+ Thread.current[:schedule_lock_backend_pid] = connection.select_value("SELECT pg_backend_pid()").to_i+ provider = OpenStruct.new(+ current_account: Account.find(account.id),+ plaid_item: plaid_item,+ raw_liabilities_payload: {+ "mortgage" => { "interest_rate" => { "type" => "variable", "percentage" => 7 } },+ "student" => { "interest_rate_percentage" => 7 }+ }+ )+ second_pid << connection.select_value("SELECT pg_backend_pid()").to_i+ processor_class.new(provider, as_of: Date.new(2026, 3, 1)).process+ end+ end+ pid = Timeout.timeout(10) { second_pid.pop }+ wait_for_lock(pid)+ release << true+ [ first, second ].each(&:value)++ @loan.reload+ assert_equal expected[:interest_rate], @loan.interest_rate+ assert_equal expected[:rate_type], @loan.rate_type+ assert_equal({ "2026-01-01" => "7" }, @loan.variable_rate_schedule)+ ensure+ release << true+ stop_workers(first, second)+ account&.destroy!+ end+ end++ test "worker cleanup cancels an active PostgreSQL query and releases its row lock" do+ held = Queue.new+ id = @loan.id+ worker = Thread.new do+ ActiveRecord::Base.connection_pool.with_connection do |connection|+ Thread.current[:schedule_lock_backend_pid] = connection.select_value("SELECT pg_backend_pid()").to_i+ connection.transaction do+ Loan.where(id: id).lock.pick(:id)+ held << connection.select_value("SELECT pg_backend_pid()").to_i+ connection.select_value("SELECT pg_sleep(30)")+ end+ end+ end+ worker.report_on_exception = false+ pid = Timeout.timeout(10) { held.pop }+ Timeout.timeout(10) do+ ActiveRecord::Base.uncached do+ sleep 0.01 until ActiveRecord::Base.connection.select_value("SELECT wait_event = 'PgSleep' FROM pg_stat_activity WHERE pid = #{pid}")+ end+ end++ stop_workers(worker, wait: 0)++ assert_not worker.alive?+ assert_equal id, Loan.where(id: id).lock("FOR UPDATE NOWAIT").pick(:id)+ ensure+ stop_workers(worker, wait: 0)+ end++ test "worker cleanup terminates a blocked Ruby worker and releases its transaction" do+ held = Queue.new+ id = @loan.id+ worker = Thread.new do+ ActiveRecord::Base.connection_pool.with_connection do |connection|+ Thread.current[:schedule_lock_backend_pid] = connection.select_value("SELECT pg_backend_pid()").to_i+ Loan.find(id).with_lock do+ held << true+ Queue.new.pop+ end+ end+ end+ worker.report_on_exception = false+ Timeout.timeout(10) { held.pop }++ stop_workers(worker, wait: 0)++ assert_not worker.alive?+ assert_equal id, Loan.where(id: id).lock("FOR UPDATE NOWAIT").pick(:id)+ ensure+ stop_workers(worker, wait: 0)+ end++ test "worker cleanup continues after backend termination fails" do+ stuck_worker = mock("stuck worker")+ finished_worker = mock("finished worker")+ expects(:join_worker).with(stuck_worker, 1).times(4).returns(false)+ expects(:cancel_worker_query).with(stuck_worker).raises(ActiveRecord::StatementInvalid)+ stuck_worker.expects(:kill)+ expects(:cancel_worker_query).with(stuck_worker, terminate: true).raises(ActiveRecord::StatementInvalid)+ expects(:join_worker).with(finished_worker, 1).returns(true)++ error = assert_raises(RuntimeError) { stop_workers(stuck_worker, finished_worker) }+ assert_equal "Concurrent test worker did not stop", error.message+ end++ private+ def stop_workers(*workers, wait: 1)+ stuck = []+ workers.compact.each do |worker|+ next if join_worker(worker, wait)++ begin+ cancel_worker_query(worker)+ rescue ActiveRecord::StatementInvalid+ # Still terminate the Ruby worker if cancellation itself fails.+ end+ next if join_worker(worker, 1)++ worker.kill+ next if join_worker(worker, 1)++ begin+ cancel_worker_query(worker, terminate: true)+ rescue ActiveRecord::StatementInvalid+ # Finish checking every worker even if backend termination fails.+ end+ stuck << worker unless join_worker(worker, 1)+ end+ raise "Concurrent test worker did not stop" if stuck.any?+ end++ def cancel_worker_query(worker, terminate: false)+ pid = worker[:schedule_lock_backend_pid]+ return unless pid++ function = terminate ? "pg_terminate_backend" : "pg_cancel_backend"+ ActiveRecord::Base.uncached do+ ActiveRecord::Base.connection.select_value("SELECT #{function}(#{pid.to_i})")+ end+ end++ def join_worker(worker, wait)+ worker.join(wait)+ rescue StandardError+ !worker.alive?+ end++ def wait_for_lock(pid)+ Timeout.timeout(10) do+ ActiveRecord::Base.uncached do+ sleep 0.01 until ActiveRecord::Base.connection.select_value("SELECT cardinality(pg_blocking_pids(#{pid}))").positive?+ end+ end+ end+enddiff --git a/test/models/loan/variable_rate_schedule_test.rb b/test/models/loan/variable_rate_schedule_test.rbindex 7276ac8cfe..d97e88de44 100644--- a/test/models/loan/variable_rate_schedule_test.rb+++ b/test/models/loan/variable_rate_schedule_test.rb@@ -7,6 +7,142 @@ class Loan::VariableRateScheduleTest < ActiveSupport::TestCase@family = families(:dylan_family)end+ test "repeated form reads do not duplicate snapshot validation errors" do+ message = I18n.t("activerecord.errors.models.loan.invalid_rate_schedule_snapshot")+ [ "{broken", "[]", "null", "5" ].each do |snapshot|+ account = build_loan(rate_type: "variable").account+ account.assign_attributes(accountable_attributes: { rate_schedule_snapshot: snapshot, rate_changes: [] })+ loan = account.loan++ 2.times do+ assert_not account.valid?+ assert_equal [ message ], loan.errors[:base]+ assert_equal 1, account.errors[:"accountable.base"].size+ errors_before_render = loan.errors.objects.dup++ 2.times { assert_empty loan.rate_change_rows }++ assert_equal errors_before_render, loan.errors.objects+ assert_equal 1, account.errors[:"accountable.base"].size+ end+ end+ end++ test "reading invalid snapshot rows before validation does not add errors or allow a later save" do+ loan = build_loan(rate_type: "variable", start_date: Date.new(2024, 1, 1),+ variable_rate_schedule: { "2026-01-01" => "7" })+ loan.assign_attributes(rate_schedule_snapshot: "[]", rate_changes: [])++ 2.times do+ assert_equal [ { effective_date: "2026-01-01", rate: "7.0" } ], loan.rate_change_rows+ assert_empty loan.errors+ end+ 2.times do+ assert_not loan.valid?+ assert_equal 1, loan.errors[:base].size+ end+ assert_not loan.save+ assert_equal({ "2026-01-01" => "7" }, loan.reload.variable_rate_schedule)+ assert loan.valid?+ assert_not loan.changed_for_autosave?+ end++ test "invalid rows and an invalid snapshot each report their own error once" do+ loan = build_loan(rate_type: "variable")+ loan.assign_attributes(rate_schedule_snapshot: "[]", rate_changes: [ { effective_date: "", rate: "9" } ])+ expected = {+ I18n.t("activerecord.errors.models.loan.invalid_rate_change") => 1,+ I18n.t("activerecord.errors.models.loan.invalid_rate_schedule_snapshot") => 1+ }++ 2.times do+ assert_not loan.valid?+ 2.times { loan.rate_change_rows }+ assert_equal expected, loan.errors[:base].tally+ end+ end++ test "reading form rows shows the reconciled schedule without assigning it" do+ loan = build_loan(rate_type: "variable", start_date: Date.new(2024, 1, 1),+ variable_rate_schedule: { "2026-01-01" => "7" })+ snapshot = loan.rate_schedule_snapshot+ Loan.find(loan.id).enrich_attributes(+ { variable_rate_schedule: { "2026-01-01" => "7", "2026-02-01" => "8" } }, source: "redbark"+ )+ loan.reload+ loan.assign_attributes(rate_schedule_snapshot: snapshot, rate_changes: [+ { effective_date: "2026-01-01", rate: "7" }, { effective_date: "2026-03-01", rate: "9" }+ ])+ changes = loan.changes.deep_dup+ schedule = loan.variable_rate_schedule.deep_dup+ reconciled = [+ { effective_date: "2026-01-01", rate: "7.0" },+ { effective_date: "2026-02-01", rate: "8.0" },+ { effective_date: "2026-03-01", rate: "9.0" }+ ]++ 2.times { assert_equal reconciled, loan.rate_change_rows }++ assert_equal changes, loan.changes+ assert_equal schedule, loan.variable_rate_schedule+ assert_not_includes loan.variable_rate_schedule.keys, "2026-02-01"+ assert loan.valid?+ assert_equal({ "2026-01-01" => "7", "2026-02-01" => "8", "2026-03-01" => "9.0" }, loan.variable_rate_schedule)+ assert_equal reconciled, loan.rate_change_rows+ end++ test "reconciliation is reused until the snapshot or submitted rows change" do+ loan = build_loan(rate_type: "variable", start_date: Date.new(2024, 1, 1))+ loan.assign_attributes(rate_schedule_snapshot: "{}", rate_changes: [ { effective_date: "2026-01-01", rate: "7" } ])+ rows = loan.rate_change_rows++ assert loan.valid?+ schedule = loan.variable_rate_schedule+ assert_equal rows, loan.rate_change_rows+ assert loan.valid?+ assert_same schedule, loan.variable_rate_schedule++ loan.rate_changes = [ { effective_date: "2026-02-01", rate: "8" } ]+ assert_equal [ { effective_date: "2026-02-01", rate: "8.0" } ], loan.rate_change_rows+ loan.rate_schedule_snapshot = "[]"+ assert_empty loan.rate_change_rows+ assert_not loan.valid?+ loan.rate_schedule_snapshot = "{}"+ assert loan.valid?+ assert_equal [ { effective_date: "2026-02-01", rate: "8.0" } ], loan.rate_change_rows+ assert loan.save+ assert_not loan.changed_for_autosave?+ assert_equal({ "2026-02-01" => "8.0" }, loan.reload.variable_rate_schedule)+ assert loan.valid?+ end++ test "provider locking clears both valid and invalid form caches on the same loan instance" do+ [ true, false ].each do |invalid_snapshot|+ loan = build_loan(rate_type: "variable", start_date: Date.new(2024, 1, 1),+ variable_rate_schedule: { "2026-01-01" => "7" })+ snapshot = invalid_snapshot ? "[]" : loan.rate_schedule_snapshot+ loan.assign_attributes(rate_schedule_snapshot: snapshot,+ rate_changes: [ { effective_date: "2026-01-01", rate: "7" } ])+ loan.rate_change_rows+ assert_equal !invalid_snapshot, loan.valid?+ assert_not loan.has_changes_to_save?+ Loan.find(loan.id).enrich_attributes(+ { variable_rate_schedule: { "2026-01-01" => "7", "2026-02-01" => "8" } }, source: "redbark"+ )++ assert loan.enrich_attributes(+ { variable_rate_schedule: { "2026-01-01" => "7", "2026-03-01" => "9" } }, source: "plaid"+ )++ assert loan.valid?+ assert_empty loan.errors+ assert_equal [ "2026-01-01", "2026-02-01", "2026-03-01" ], loan.rate_change_rows.pluck(:effective_date)+ assert_equal({ "2026-01-01" => "7", "2026-02-01" => "8", "2026-03-01" => "9" },+ Loan.find(loan.id).variable_rate_schedule)+ assert_not loan.changed_for_autosave?+ end+ end+test "a fixed loan is unaffected by this feature" dofixed = build_loan(rate_type: "fixed")diff --git a/test/models/plaid_account/liabilities/mortgage_processor_test.rb b/test/models/plaid_account/liabilities/mortgage_processor_test.rbindex c7285a1a06..beb33a398e 100644--- a/test/models/plaid_account/liabilities/mortgage_processor_test.rb+++ b/test/models/plaid_account/liabilities/mortgage_processor_test.rb@@ -55,6 +55,22 @@ class PlaidAccount::Liabilities::MortgageProcessorTest < ActiveSupport::TestCaseassert_not_empty loan.amortization_schedule.paymentsend+ # The processor's loan is cached on the account and can predate another+ # writer's change. LoanTermWriter's schedule lock reloads it before the rate+ # is judged. The payload has no rate type, so no terms save takes the lock+ # first and only that wrapper stands between the stale copy and a second row+ # for a rate already in force.+ test "a rate another writer recorded after the loan was loaded is not dated again" do+ loan = loan_with(interest_rate: 6, rate_type: "variable", start_date: ORIGINATED)+ Loan.find(loan.id).update!(variable_rate_schedule: { "2026-02-01" => "7" })+ payload(percentage: 7)++ PlaidAccount::Liabilities::MortgageProcessor.new(@plaid_account, as_of: Date.new(2026, 3, 1)).process++ assert_equal({ "2026-02-01" => 7.0 }, rates(loan.reload),+ "the rate was judged against a loan loaded before the other write")+ end+test "does nothing when mortgage data absent" do@plaid_account.update!(raw_liabilities_payload: {})diff --git a/test/models/redbark_account/loan_details_processor_test.rb b/test/models/redbark_account/loan_details_processor_test.rbindex 66622d8572..bbe17df3cb 100644--- a/test/models/redbark_account/loan_details_processor_test.rb+++ b/test/models/redbark_account/loan_details_processor_test.rb@@ -80,6 +80,21 @@ class RedbarkAccount::LoanDetailsProcessorTest < ActiveSupport::TestCaseassert_empty schedule, "a rate that had not moved was recorded as a change"end+ # The processor's loan can be loaded before another writer records the same+ # rate. The schedule lock reloads it, so the decision sees that rate in force;+ # deciding on the stale copy would add a second row for a rate already held.+ test "a rate another writer recorded after the loan was loaded is not recorded again" do+ # The processor reads the loan through this cached association.+ @redbark_account.current_account.accountable+ Loan.find(@loan.id).enrich_attributes({ variable_rate_schedule: { "2026-03-01" => "7" } }, source: "redbark")+ detail lendingRate: "0.07"++ process++ assert_equal({ "2026-03-01" => BigDecimal("7") }, rates,+ "the rate was decided on a loan loaded before the concurrent write")+ end+# Rows 4 and 10: a fixed loan's rate does not move, so a bank disagreeing is# something to surface rather than something to write.test "a different rate on a fixed loan writes nothing and is logged" do