The personal finance app for everyone (by everyone)
Ruby
Keep SimpleFIN entries when the bridge re-issues ids (#4318)
jaysbeekaye529f1113601
diff --git a/app/models/simplefin_account/transaction_id_rotation.rb b/app/models/simplefin_account/transaction_id_rotation.rbnew file mode 100644index 0000000000..34b4da1f40--- /dev/null+++ b/app/models/simplefin_account/transaction_id_rotation.rb@@ -0,0 +1,111 @@+# Recognises transactions the SimpleFIN bridge re-issued under new ids (#3436).+#+# Some bridges rotate transaction ids for transactions they already served, on a+# live account and on every reconnect. The stored payload is keyed by id, so the+# new row lands beside the old one and both become entries. Deleting either one+# does not hold, because each sync rebuilds entries from the stored payload.+#+# Stored and incoming rows are grouped by content. Within a group, stored rows+# whose id is still served keep it. The rest pair by position with the incoming+# rows whose id is not stored yet: each pair is one transaction under a new id, so+# its entry moves to the new id and the stored row gives way to the incoming one.+# Pairing by position keeps multiplicity: three identical charges map onto three,+# never one. Content-level deduplication would collapse them (#2013, #2720).+#+# Stored rows left unpaired in a group that did receive rows are dropped from the+# payload too. Their twin was served under an id that is already stored, which is+# the duplicate state this defect left behind; the entry stays, but a user who+# deletes it is no longer overruled by the next sync. A group with no incoming+# rows is never touched, so a short or partial response cannot evict history.+#+# Same pairing approach as the Enable Banking importer's rotated-id handling+# (#4159), without its window replacement.+class SimplefinAccount::TransactionIdRotation+ def initialize(stored_rows, incoming_rows)+ @stored_rows = stored_rows.to_a+ @incoming_rows = incoming_rows.to_a+ end++ # The stored rows to keep, with superseded rows removed.+ def retained_rows+ superseded, _rekeys = pairing+ stored_rows.reject { |row| superseded.include?(row) }+ end++ # Moves each rotated entry to its new id. Run it in the transaction that saves+ # the payload: an entry whose id the payload no longer mentions is duplicated+ # again by the next sync.+ def rekey_entries!(account)+ return if account.nil?++ entries = account.entries.where(source: "simplefin")+ _superseded, rekeys = pairing++ rekeys.each do |old_id, new_id|+ next if entries.exists?(external_id: "simplefin_#{new_id}")++ # One conditional UPDATE, so a concurrent sync cannot re-key the same entry twice.+ entries.where(external_id: "simplefin_#{old_id}").update_all(external_id: "simplefin_#{new_id}", updated_at: Time.current)+ end+ end++ private+ attr_reader :stored_rows, :incoming_rows++ # [stored rows superseded (an identity set), [old_id, new_id] pairs to re-key]+ def pairing+ @pairing ||= pair+ end++ def pair+ superseded = Set.new.compare_by_identity+ rekeys = []++ stored_ids = stored_rows.filter_map { |row| row_id(row) }.to_set+ incoming_ids = incoming_rows.filter_map { |row| row_id(row) }.to_set+ incoming_by_content = with_ids(incoming_rows).group_by { |row| content_key(row) }++ with_ids(stored_rows).group_by { |row| content_key(row) }.each do |key, old_rows|+ new_rows = incoming_by_content[key] or next++ unserved = old_rows.reject { |row| incoming_ids.include?(row_id(row)) }+ unstored = new_rows.reject { |row| stored_ids.include?(row_id(row)) }++ unserved.each_with_index do |old_row, index|+ superseded << old_row+ rekeys << [ row_id(old_row), row_id(unstored[index]) ] if unstored[index]+ end+ end++ [ superseded, rekeys ]+ end++ # SimplefinEntry::Processor cannot import a row without an id, so only rows+ # with one can be paired.+ def with_ids(rows)+ rows.select { |row| row_id(row) }+ end++ def row_id(row)+ row.with_indifferent_access[:id].presence&.to_s+ end++ def content_key(row)+ t = row.with_indifferent_access+ [+ epoch(t[:posted]),+ epoch(t[:transacted_at]),+ t[:amount].to_d,+ t[:description].to_s,+ t[:payee].to_s,+ SimplefinEntry::Processor.pending?(t)+ ]+ end++ # Bridges send epoch seconds or ISO strings (see Simplefin::DateUtils).+ # String#to_i would read every ISO date in a year as that year, so two+ # charges months apart would share a content group.+ def epoch(value)+ Simplefin::DateUtils.parse_provider_time(value)&.to_i+ end+enddiff --git a/app/models/simplefin_item.rb b/app/models/simplefin_item.rbindex fb29092ae3..bb1200eae5 100644--- a/app/models/simplefin_item.rb+++ b/app/models/simplefin_item.rb@@ -184,38 +184,50 @@ class SimplefinItem < ApplicationRecord# Transfer the linkage from old to newbegin- # Merge transactions from old to new before transferring- old_transactions = stale_match.raw_transactions_payload.to_a- new_transactions = new_sfa.raw_transactions_payload.to_a- if old_transactions.any?- Rails.logger.info "SimplefinItem#repair_stale_linkages - Merging #{old_transactions.count} transactions from old SimplefinAccount"- merged = merge_transactions(old_transactions, new_transactions)- new_sfa.update!(raw_transactions_payload: merged)+ # One transaction: re-keyed entries must not outlive a failed transfer, or+ # the stale account's payload re-creates their old ids on the next pass.+ SimplefinAccount.transaction do+ # Merge transactions from old to new before transferring. Both payloads+ # are read as stored, under a row lock: an overlapping sync may have+ # saved either since they were loaded, and pairing the loaded copies+ # would re-key entries against ids the stored payload no longer holds.+ stored = SimplefinAccount.where(id: [ stale_match.id, new_sfa.id ]).lock.order(:id).pluck(:id, :raw_transactions_payload).to_h+ old_transactions = stored.fetch(stale_match.id, stale_match.raw_transactions_payload).to_a+ new_transactions = stored.fetch(new_sfa.id, new_sfa.raw_transactions_payload).to_a+ if old_transactions.any?+ Rails.logger.info "SimplefinItem#repair_stale_linkages - Merging #{old_transactions.count} transactions from old SimplefinAccount"+ # A reconnect re-issues transaction ids too. Rows that came back under a+ # new id give way to the new row, and their entries move to the new id.+ id_rotation = SimplefinAccount::TransactionIdRotation.new(old_transactions, new_transactions)+ id_rotation.rekey_entries!(account)+ merged = merge_transactions(id_rotation.retained_rows, new_transactions)+ new_sfa.update!(raw_transactions_payload: merged)+ end++ # Check if linked via legacy FK (use to_s for UUID comparison safety)+ if account.simplefin_account_id.to_s == stale_match.id.to_s+ account.simplefin_account_id = new_sfa.id+ account.save!+ end++ # Check if linked via AccountProvider+ if stale_match.account_provider.present?+ Rails.logger.info "SimplefinItem#repair_stale_linkages - Transferring AccountProvider linkage from SimplefinAccount #{stale_match.id} to #{new_sfa.id}"+ stale_match.account_provider.update!(provider: new_sfa)+ end++ # If the new one doesn't have an AccountProvider yet, create one+ new_sfa.ensure_account_provider!++ Rails.logger.info "SimplefinItem#repair_stale_linkages - Successfully transferred linkage for Account '#{account.name}' to SimplefinAccount id=#{new_sfa.id}"++ # Clear transactions from stale SimplefinAccount and leave it orphaned+ # We don't destroy it because has_one :account, dependent: :nullify would nullify the FK we just set+ # IMPORTANT: Use update_all to bypass AR associations - stale_match.update! would+ # trigger autosave on the preloaded account association, reverting the FK we just set!+ SimplefinAccount.where(id: stale_match.id).update_all(raw_transactions_payload: [], raw_holdings_payload: [])+ Rails.logger.info "SimplefinItem#repair_stale_linkages - Cleared data from stale SimplefinAccount id=#{stale_match.id} (leaving orphaned)"end-- # Check if linked via legacy FK (use to_s for UUID comparison safety)- if account.simplefin_account_id.to_s == stale_match.id.to_s- account.simplefin_account_id = new_sfa.id- account.save!- end-- # Check if linked via AccountProvider- if stale_match.account_provider.present?- Rails.logger.info "SimplefinItem#repair_stale_linkages - Transferring AccountProvider linkage from SimplefinAccount #{stale_match.id} to #{new_sfa.id}"- stale_match.account_provider.update!(provider: new_sfa)- end-- # If the new one doesn't have an AccountProvider yet, create one- new_sfa.ensure_account_provider!-- Rails.logger.info "SimplefinItem#repair_stale_linkages - Successfully transferred linkage for Account '#{account.name}' to SimplefinAccount id=#{new_sfa.id}"-- # Clear transactions from stale SimplefinAccount and leave it orphaned- # We don't destroy it because has_one :account, dependent: :nullify would nullify the FK we just set- # IMPORTANT: Use update_all to bypass AR associations - stale_match.update! would- # trigger autosave on the preloaded account association, reverting the FK we just set!- SimplefinAccount.where(id: stale_match.id).update_all(raw_transactions_payload: [], raw_holdings_payload: [])- Rails.logger.info "SimplefinItem#repair_stale_linkages - Cleared data from stale SimplefinAccount id=#{stale_match.id} (leaving orphaned)"rescue => eRails.logger.error "SimplefinItem#repair_stale_linkages - Failed to transfer linkage: #{e.class} - #{e.message}"Rails.logger.error e.backtrace.first(5).join("\n") if e.backtracediff --git a/app/models/simplefin_item/importer.rb b/app/models/simplefin_item/importer.rbindex aacfa4c74a..7c249829c6 100644--- a/app/models/simplefin_item/importer.rb+++ b/app/models/simplefin_item/importer.rb@@ -793,6 +793,77 @@ class SimplefinItem::Importernilend+ # The rotation for `stored` against `transactions`, and the payload they merge+ # into (see import_account). A method so the save can run it again against+ # the payload as stored.+ def merged_transaction_payload(stored, transactions, account_id)+ # Stored rows the bridge re-issued under a new id give way to the new row,+ # or the id-keyed merge below keeps both and each becomes an entry.+ id_rotation = SimplefinAccount::TransactionIdRotation.new(stored, transactions)+ existing_transactions = id_rotation.retained_rows++ Rails.logger.info "SimplefinItem::Importer#import_account - Merging transactions for account_id=#{account_id}: #{existing_transactions.count} existing + #{transactions.count} new"++ # Build a map of key => best_tx+ best_by_key = {}++ comparator = lambda do |a, b|+ ax = a.with_indifferent_access+ bx = b.with_indifferent_access++ # Key dates+ a_posted = ax[:posted].to_i+ b_posted = bx[:posted].to_i+ a_trans = ax[:transacted_at].to_i+ b_trans = bx[:transacted_at].to_i++ a_pending = !!ax[:pending]+ b_pending = !!bx[:pending]++ # 1) Prefer real posted date over 0/blank+ a_has_posted = a_posted > 0+ b_has_posted = b_posted > 0+ return a if a_has_posted && !b_has_posted+ return b if b_has_posted && !a_has_posted++ # 2) Prefer later posted date+ if a_posted != b_posted+ return a_posted > b_posted ? a : b+ end++ # 3) Prefer non-pending over pending+ if a_pending != b_pending+ return a_pending ? b : a+ end++ # 4) Prefer later transacted_at+ if a_trans != b_trans+ return a_trans > b_trans ? a : b+ end++ # 5) Stable: keep 'a'+ a+ end++ build_key = lambda do |tx|+ t = tx.with_indifferent_access+ t[:id] || t[:fitid] || [ t[:posted], t[:amount], t[:description] ]+ end++ (existing_transactions + transactions).each do |tx|+ key = build_key.call(tx)+ if (cur = best_by_key[key])+ best_by_key[key] = comparator.call(cur, tx)+ else+ best_by_key[key] = tx+ end+ end++ merged_transactions = best_by_key.values++ [ id_rotation, merged_transactions ]+ end+def import_account(account_data)account_id = account_data[:id].to_s@@ -848,67 +919,10 @@ class SimplefinItem::Importer# Merge transactions from chunked/regular imports (accumulate history).# Prefer non-pending records with a real posted timestamp over earlier# pending placeholders that sometimes come back with posted: 0.+ id_rotation = nilif transactions.is_a?(Array) && transactions.any?- existing_transactions = simplefin_account.raw_transactions_payload.to_a-- Rails.logger.info "SimplefinItem::Importer#import_account - Merging transactions for account_id=#{account_id}: #{existing_transactions.count} existing + #{transactions.count} new"-- # Build a map of key => best_tx- best_by_key = {}-- comparator = lambda do |a, b|- ax = a.with_indifferent_access- bx = b.with_indifferent_access-- # Key dates- a_posted = ax[:posted].to_i- b_posted = bx[:posted].to_i- a_trans = ax[:transacted_at].to_i- b_trans = bx[:transacted_at].to_i-- a_pending = !!ax[:pending]- b_pending = !!bx[:pending]-- # 1) Prefer real posted date over 0/blank- a_has_posted = a_posted > 0- b_has_posted = b_posted > 0- return a if a_has_posted && !b_has_posted- return b if b_has_posted && !a_has_posted-- # 2) Prefer later posted date- if a_posted != b_posted- return a_posted > b_posted ? a : b- end-- # 3) Prefer non-pending over pending- if a_pending != b_pending- return a_pending ? b : a- end-- # 4) Prefer later transacted_at- if a_trans != b_trans- return a_trans > b_trans ? a : b- end-- # 5) Stable: keep 'a'- a- end-- build_key = lambda do |tx|- t = tx.with_indifferent_access- t[:id] || t[:fitid] || [ t[:posted], t[:amount], t[:description] ]- end-- (existing_transactions + transactions).each do |tx|- key = build_key.call(tx)- if (cur = best_by_key[key])- best_by_key[key] = comparator.call(cur, tx)- else- best_by_key[key] = tx- end- end-- merged_transactions = best_by_key.values+ stored_snapshot = simplefin_account.raw_transactions_payload.to_a+ id_rotation, merged_transactions = merged_transaction_payload(stored_snapshot, transactions, account_id)attrs[:raw_transactions_payload] = merged_transactionsRails.logger.info "SimplefinItem::Importer#import_account - Merged result for account_id=#{account_id}: #{merged_transactions.count} total transactions"@@ -956,7 +970,29 @@ class SimplefinItem::Importerendbegin- simplefin_account.save!+ # Entries move to their new ids only if the payload naming those ids saves.+ SimplefinAccount.transaction do+ # Another sync of this account may have saved since the payload was read+ # (syncs can overlap once the first is over five minutes old). The row+ # lock serialises the two; pairing again against what is stored keeps+ # the re-keys and the payload on one snapshot, or the stale payload+ # would put an id back beside the entry the other sync re-keyed.+ if id_rotation && simplefin_account.persisted?+ stored_now = SimplefinAccount.where(id: simplefin_account.id).lock.pick(:raw_transactions_payload).to_a+ if stored_now != stored_snapshot+ id_rotation, simplefin_account.raw_transactions_payload = merged_transaction_payload(stored_now, transactions, account_id)+ end++ # That sync's repair_stale_linkages may also have moved the linkage to+ # this account. The associations were loaded before the lock, so they+ # are read again: re-keying through a stale (empty) linkage would skip+ # the entry and save the new id beside it.+ %i[account account_provider linked_account].each { |name| simplefin_account.association(name).reset }+ end++ id_rotation&.rekey_entries!(simplefin_account.current_account)+ simplefin_account.save!+ end# Log final state after save for debuggingif is_investmentdiff --git a/test/models/simplefin_item/importer_rotated_ids_test.rb b/test/models/simplefin_item/importer_rotated_ids_test.rbnew file mode 100644index 0000000000..9a1d654e30--- /dev/null+++ b/test/models/simplefin_item/importer_rotated_ids_test.rb@@ -0,0 +1,362 @@+require "test_helper"++# The SimpleFIN bridge sometimes re-issues the ids of transactions it already+# served (#3436). A stored row the bridge no longer returns, re-delivered in the+# same response under a new id with identical content, is the same transaction:+# its entry moves to the new id and the payload keeps one row for it.+class SimplefinItem::ImporterRotatedIdsTest < ActiveSupport::TestCase+ setup do+ @family = families(:dylan_family)+ @item = SimplefinItem.create!(family: @family, name: "SF Conn", access_url: "https://example.com/access")+ @sync = Sync.create!(syncable: @item)+ @importer = SimplefinItem::Importer.new(@item, simplefin_provider: mock(), sync: @sync)++ @account = Account.create!(+ family: @family,+ name: "Checking",+ currency: "USD",+ balance: 0,+ accountable: Depository.create!(subtype: :checking)+ )+ @sfa = SimplefinAccount.create!(+ simplefin_item: @item,+ account_id: "ACT-1",+ name: "Checking",+ currency: "USD",+ current_balance: 0,+ account_type: "checking"+ )+ AccountProvider.create!(account: @account, provider: @sfa)++ @posted = 5.days.ago.beginning_of_day.to_i+ end++ def row(id, amount: "-10.25", description: "Amazon", payee: "Amazon", posted: @posted, transacted_at: @posted, **rest)+ { id: id, posted: posted, amount: amount, description: description, payee: payee, memo: "", transacted_at: transacted_at }.merge(rest).compact+ end++ # Stores rows as an earlier sync would have, and builds their entries.+ def store(*rows)+ @sfa.update!(raw_transactions_payload: rows)+ process+ end++ def import(*rows, sfa: @sfa)+ @importer.send(:import_account, { id: sfa.account_id, name: sfa.name, currency: "USD", balance: "0", transactions: rows })+ sfa.reload+ end++ def process+ SimplefinAccount::Transactions::Processor.new(@sfa.reload).process+ end++ def payload_ids(sfa = @sfa)+ sfa.reload.raw_transactions_payload.map { |t| t.with_indifferent_access[:id] }+ end++ def external_ids+ @account.entries.where(source: "simplefin").pluck(:external_id).sort+ end++ def entry_for(id)+ @account.entries.find_by!(source: "simplefin", external_id: "simplefin_#{id}")+ end++ test "P1 rotated id re-keys the existing entry instead of adding one" do+ store(row("T1"))+ entry = entry_for("T1")+ category = @family.categories.create!(name: "Shopping #{SecureRandom.hex(3)}")+ entry.transaction.update!(category: category)++ assert_no_difference -> { Entry.count } do+ import(row("T2"))+ process+ end++ entry.reload+ assert_equal "simplefin_T2", entry.external_id+ assert_equal category.id, entry.transaction.category_id+ assert_equal [ "T2" ], payload_ids+ end++ test "P3 repeated identical charges keep their count across a rotation" do+ store(row("T1"), row("T2"), row("T3"))+ assert_equal 3, external_ids.size++ assert_no_difference -> { Entry.count } do+ import(row("U1"), row("U2"), row("U3"))+ process+ end++ assert_equal %w[simplefin_U1 simplefin_U2 simplefin_U3], external_ids+ assert_equal %w[U1 U2 U3], payload_ids.sort+ end++ test "P4 a duplicate from before the fix stays deleted" do+ # The state the defect left behind: both ids stored, both with entries.+ store(row("T1"), row("T2"))++ import(row("T2"))+ assert_equal [ "T2" ], payload_ids++ entry_for("T1").destroy!+ assert_no_difference -> { Entry.count } do+ process+ end+ assert_equal [ "simplefin_T2" ], external_ids+ end++ test "P5 re-keyed entry keeps its recorded pending claim and pending date" do+ store(row("T1"))+ entry = entry_for("T1")+ pending_date = entry.date - 3.days+ entry.update_column(:date, pending_date)+ entry.transaction.update_column(:extra, entry.transaction.extra.merge("auto_claimed_pending_ids" => [ "simplefin_P0" ]))++ assert_no_difference -> { Entry.count } do+ import(row("T2"))+ process+ end++ entry.reload+ assert_equal "simplefin_T2", entry.external_id+ assert_equal [ "simplefin_P0" ], entry.transaction.extra["auto_claimed_pending_ids"]+ assert_equal pending_date, entry.date+ end++ test "N1 identical twins served together stay two entries" do+ import(row("T1"), row("T2"))+ process++ assert_equal %w[simplefin_T1 simplefin_T2], external_ids+ end++ test "N2 a stored twin that is still served keeps its id" do+ store(row("T1"))+ entry = entry_for("T1")++ # The new twin comes first, so pairing by position alone would hand it T1's entry.+ import(row("T2"), row("T1"))+ process++ assert_equal "simplefin_T1", entry.reload.external_id+ assert_equal %w[simplefin_T1 simplefin_T2], external_ids+ assert_equal %w[T1 T2], payload_ids.sort+ end++ test "N2 a partial rotation pairs the old id only with the new one" do+ store(row("T1"), row("T2"))+ entry = entry_for("T1")++ # T2 kept its id and comes first; only T1 was re-issued, as U1.+ assert_no_difference -> { Entry.count } do+ import(row("T2"), row("U1"))+ process+ end++ assert_equal "simplefin_U1", entry.reload.external_id+ assert_equal %w[simplefin_T2 simplefin_U1], external_ids+ end++ test "N3 pending and posted rows never pair" do+ store(row("P1", pending: true))+ entry = entry_for("P1")++ # Same dates, amount and text: only the pending flag differs.+ import(row("T9"))++ assert_equal "simplefin_P1", entry.reload.external_id+ assert_equal %w[P1 T9], payload_ids.sort+ end++ test "N3 an inferred-pending row does not pair with its posted version" do+ store(row("P1", posted: 0))+ entry = entry_for("P1")++ import(row("T9"))++ assert_equal "simplefin_P1", entry.reload.external_id+ assert_equal %w[P1 T9], payload_ids.sort+ end++ # Rows that differ in any field of the content key are different transactions.+ def assert_no_pairing(**changes)+ store(row("T1"))+ entry = entry_for("T1")++ import(row("T9", **changes))++ assert_equal "simplefin_T1", entry.reload.external_id+ assert_equal %w[T1 T9], payload_ids.sort+ end++ test "N3 rows with a different payee never pair" do+ assert_no_pairing(payee: "Amazon Marketplace")+ end++ test "N3 rows with a different transacted_at never pair" do+ assert_no_pairing(transacted_at: @posted - 3600)+ end++ test "N3 rows with a different posted date never pair" do+ assert_no_pairing(posted: @posted - 86_400)+ end++ test "N3 rows with a different amount never pair" do+ assert_no_pairing(amount: "-10.26")+ end++ test "N3 rows with a different description never pair" do+ assert_no_pairing(description: "Amazon Mktp")+ end++ # The bridge may send dates as ISO strings, which Simplefin::DateUtils accepts.+ # Compared as String#to_i, every date in a year reads as that year.+ test "N3 ISO dates a day apart never pair" do+ day = Time.at(@posted).utc+ other = day.yday == 1 ? day + 1.day : day - 1.day+ store(row("T1", posted: day.iso8601, transacted_at: day.iso8601))++ import(row("T2", posted: other.iso8601, transacted_at: other.iso8601))++ assert_equal %w[T1 T2], payload_ids.sort+ assert_equal "simplefin_T1", entry_for("T1").external_id+ end++ test "the same instant pairs whether it is sent as epoch seconds or an ISO string" do+ store(row("T1"))+ entry = entry_for("T1")+ iso = Time.at(@posted).utc.iso8601++ import(row("T2", posted: iso, transacted_at: iso))++ assert_equal "simplefin_T2", entry.reload.external_id+ assert_equal [ "T2" ], payload_ids+ end++ # Two syncs can overlap once the first is over five minutes old (Sync::VISIBLE_FOR).+ # Here a second rotation (T2 -> T3) arrives in a sync that read the payload+ # before the first sync's T1 -> T2 committed. Pairing against what it read+ # would re-key nothing and save T3 beside the committed T2: a duplicate.+ test "a sync that read the payload before another committed pairs against what is stored" do+ store(row("T1"))+ entry = entry_for("T1")+ @importer.stubs(:update_inactive_state).with do |sfa, _|+ # The overlapping sync commits between this one's read and its save.+ Entry.where(id: entry.id).update_all(external_id: "simplefin_T2")+ SimplefinAccount.where(id: sfa.id).update_all(raw_transactions_payload: [ row("T2") ])+ true+ end++ import(row("T3"))+ process++ assert_equal [ "simplefin_T3" ], external_ids+ assert_equal [ "T3" ], payload_ids+ end++ # The overlapping sync can also move the linkage: its repair_stale_linkages+ # links this SimpleFIN account to the account holding the entries. Re-keying+ # with the linkage this sync loaded before the lock (none) would skip the+ # entry and save the new id beside it.+ test "a sync re-keys through the linkage as stored, not as loaded" do+ store(row("T1"))+ entry = entry_for("T1")+ new_sfa = SimplefinAccount.create!(+ simplefin_item: @item, account_id: "ACT-new", name: "Checking", currency: "USD",+ current_balance: 0, account_type: "checking"+ )+ @importer.stubs(:update_inactive_state).with do |sfa, _|+ assert_nil sfa.current_account, "the linkage must be loaded, and empty, before the other sync commits"+ # The other sync's repair: the linkage and the stale payload move over.+ AccountProvider.where(provider: @sfa).update_all(provider_id: new_sfa.id)+ SimplefinAccount.where(id: new_sfa.id).update_all(raw_transactions_payload: [ row("T1") ])+ SimplefinAccount.where(id: @sfa.id).update_all(raw_transactions_payload: [])+ true+ end++ import(row("T2"), sfa: new_sfa)+ SimplefinAccount::Transactions::Processor.new(new_sfa.reload).process++ assert_equal "simplefin_T2", entry.reload.external_id+ assert_equal [ "simplefin_T2" ], external_ids+ end++ test "N4 a fetch that omits older rows never evicts them" do+ old = 120.days.ago.beginning_of_day.to_i+ store(row("OLD1", posted: old, transacted_at: old), row("OLD2", posted: old, transacted_at: old, amount: "-3.00"))++ # Discovery passes start_date: nil, but the bridge still returns recent rows only.+ import(row("R1"))+ process++ assert_equal %w[OLD1 OLD2 R1], payload_ids.sort+ assert_equal %w[simplefin_OLD1 simplefin_OLD2 simplefin_R1], external_ids+ end++ test "N5 a new id that already has an entry is not re-keyed onto" do+ store(row("T1"), row("T2"))+ @sfa.update_column(:raw_transactions_payload, [ row("T1") ])+ entry = entry_for("T1")++ import(row("T2"))++ assert_equal "simplefin_T1", entry.reload.external_id+ assert_equal [ "T2" ], payload_ids+ end++ test "N6 a failed payload save rolls back the re-key" do+ store(row("T1"))+ entry = entry_for("T1")+ SimplefinAccount.any_instance.stubs(:save!).raises(ActiveRecord::RecordInvalid)++ import(row("T2"))++ assert_equal "simplefin_T1", entry.reload.external_id+ end++ test "N7 an unlinked account has its payload re-pointed without touching entries" do+ unlinked = SimplefinAccount.create!(+ simplefin_item: @item, account_id: "ACT-2", name: "Savings", currency: "USD",+ current_balance: 0, account_type: "savings", raw_transactions_payload: [ row("T1") ]+ )++ assert_no_difference -> { Entry.count } do+ import(row("T2"), sfa: unlinked)+ end++ assert_equal [ "T2" ], payload_ids(unlinked)+ end++ test "N8 a row without an id never pairs" do+ store(row("T1"))+ entry = entry_for("T1")++ import(row(nil, fitid: "F1"))++ assert_equal "simplefin_T1", entry.reload.external_id+ assert_includes payload_ids, "T1"+ end++ test "an unchanged id is re-imported onto its own entry" do+ store(row("T1"))+ entry = entry_for("T1")++ assert_no_difference -> { Entry.count } do+ import(row("T1"))+ process+ end++ assert_equal "simplefin_T1", entry.reload.external_id+ assert_equal [ "T1" ], payload_ids+ end++ test "an empty transactions array leaves payload and entries alone" do+ store(row("T1"))++ import++ assert_equal [ "T1" ], payload_ids+ assert_equal [ "simplefin_T1" ], external_ids+ end+enddiff --git a/test/models/simplefin_item/repair_stale_linkages_test.rb b/test/models/simplefin_item/repair_stale_linkages_test.rbindex 1b3f774896..3b07f5474f 100644--- a/test/models/simplefin_item/repair_stale_linkages_test.rb+++ b/test/models/simplefin_item/repair_stale_linkages_test.rb@@ -189,4 +189,79 @@ class SimplefinItem::RepairStaleLinkagesTest < ActiveSupport::TestCaseassert_equal other_account, other_linked_sfa.reload.current_accountassert_nil unlinked_sfa.reload.current_accountend++ # A reconnect issues new account ids and new transaction ids for the same+ # transactions (#3436). The stale account's rows must not survive beside their+ # re-issued twins, or every transaction in the window is imported twice.+ # `retain_old_row` adds a stale row the new account was not served, so it+ # survives the merge and a merged payload differs from the new account's own.+ def reconnect_fixture(retain_old_row: false)+ posted = 5.days.ago.beginning_of_day.to_i+ tx = ->(id) { { id: id, posted: posted, transacted_at: posted, amount: "-10.25", description: "Amazon", payee: "Amazon", memo: "" } }+ stale_payload = [ tx.("T1") ]+ stale_payload << tx.("OLD9").merge(posted: posted - 86_400, transacted_at: posted - 86_400) if retain_old_row++ stale_sfa = SimplefinAccount.create!(+ simplefin_item: @item, account_id: "ACT-old", name: "Card", currency: "USD",+ current_balance: 0, account_type: "credit", raw_transactions_payload: stale_payload+ )+ account = Account.create!(+ family: @family, name: "Card", currency: "USD", balance: 0,+ accountable: Depository.create!(subtype: :checking)+ )+ AccountProvider.create!(account: account, provider: stale_sfa)+ SimplefinAccount::Transactions::Processor.new(stale_sfa).process++ new_sfa = SimplefinAccount.create!(+ simplefin_item: @item, account_id: "ACT-new", name: "Card", currency: "USD",+ current_balance: 0, account_type: "credit", raw_transactions_payload: [ tx.("T2") ]+ )+ @item.upstream_account_ids = [ new_sfa.account_id ]++ [ stale_sfa, new_sfa, account, account.entries.find_by!(external_id: "simplefin_T1") ]+ end++ test "P2 reconnect re-keys entries carried over from the stale account" do+ stale_sfa, new_sfa, account, entry = reconnect_fixture++ @item.send(:repair_stale_linkages, [ stale_sfa, new_sfa ])++ new_sfa.reload+ assert_equal account, new_sfa.current_account+ assert_equal [ "T2" ], new_sfa.raw_transactions_payload.map { |t| t["id"] }+ assert_equal "simplefin_T2", entry.reload.external_id++ assert_no_difference -> { Entry.count } do+ SimplefinAccount::Transactions::Processor.new(new_sfa).process+ end+ end++ test "a failed linkage transfer rolls back the re-key and the merged payload" do+ stale_sfa, new_sfa, account, entry = reconnect_fixture(retain_old_row: true)+ AccountProvider.any_instance.stubs(:update!).raises(ActiveRecord::RecordInvalid)++ @item.send(:repair_stale_linkages, [ stale_sfa, new_sfa ])++ # The linkage stays on the stale account, so its entry must keep the stale id+ # or the stale payload's next pass re-creates simplefin_T1 beside it.+ assert_equal account, stale_sfa.reload.current_account+ assert_equal "simplefin_T1", entry.reload.external_id+ assert_equal [ "T2" ], new_sfa.reload.raw_transactions_payload.map { |t| t["id"] }+ end++ # A repair reads both payloads as stored when its transaction starts, not as+ # loaded: an overlapping sync may have changed them since.+ test "a repair pairs against the payloads as stored, not as loaded" do+ stale_sfa, new_sfa, account, entry = reconnect_fixture+ # Since these were loaded, the new account was served T3 in place of T2.+ posted = 5.days.ago.beginning_of_day.to_i+ t3 = { id: "T3", posted: posted, transacted_at: posted, amount: "-10.25", description: "Amazon", payee: "Amazon", memo: "" }+ SimplefinAccount.where(id: new_sfa.id).update_all(raw_transactions_payload: [ t3 ])++ @item.send(:repair_stale_linkages, [ stale_sfa, new_sfa ])++ assert_equal "simplefin_T3", entry.reload.external_id+ assert_equal [ "T3" ], new_sfa.reload.raw_transactions_payload.map { |t| t["id"] }+ assert_equal account, new_sfa.current_account+ endend