The personal finance app for everyone (by everyone)
Ruby
fix(simplefin): stop repair_stale_linkages from hijacking a live linkage on a same-name twin (#3116)
GFR5a2bf02b13d3
diff --git a/app/models/simplefin_item.rb b/app/models/simplefin_item.rbindex ee09a86294..eefde6aae6 100644--- a/app/models/simplefin_item.rb+++ b/app/models/simplefin_item.rb@@ -7,6 +7,12 @@ class SimplefinItem < ApplicationRecord# Virtual attribute for the setup token form fieldattr_accessor :setup_token+ # Transient, in-memory only. Set by SimplefinItem::Importer#perform_account_discovery+ # to the set of account_ids returned by the current sync's unbounded discovery call.+ # Used by #repair_stale_linkages to verify a "stale" linked account is actually absent+ # upstream, rather than trusting a name match alone. Never persisted.+ attr_accessor :upstream_account_ids+# Encrypt sensitive credentials and raw payloads if ActiveRecord encryption is configuredif encryption_ready?encrypts :access_url, deterministic: true@@ -138,15 +144,38 @@ class SimplefinItem < ApplicationRecordreturn if unlinked_with_data.empty?+ # Without a current picture of what the provider actually returned this sync, a+ # name match alone cannot distinguish a genuinely stale account (re-added institution,+ # new account_id) from two distinct upstream accounts that merely share a display name.+ # Refuse to act rather than risk hijacking a live linkage. See GH issue #2852.+ if upstream_account_ids.nil?+ Rails.logger.warn "SimplefinItem#repair_stale_linkages - upstream_account_ids unavailable, skipping repair to avoid hijacking a live linkage"+ DebugLogEntry.capture(+ category: "provider_sync_warning",+ level: "warn",+ message: "Skipped stale-linkage repair: upstream_account_ids unavailable",+ source: self.class.name,+ provider_key: "simplefin",+ family: family,+ metadata: { simplefin_item_id: id, unlinked_with_data_count: unlinked_with_data.count }+ )+ return+ end+# For each unlinked account with data, try to find a matching linked accountunlinked_with_data.each do |new_sfa|- # Find linked SimplefinAccount with same name (case-insensitive).+ # Find linked SimplefinAccount with same name (case-insensitive) that is ALSO+ # actually absent from the current upstream response. A name match alone is not+ # enough: two distinct upstream accounts can legitimately share a display name.stale_matches = linked.select do |old_sfa|- old_sfa.name.to_s.downcase.strip == new_sfa.name.to_s.downcase.strip+ old_sfa.name.to_s.downcase.strip == new_sfa.name.to_s.downcase.strip &&+ old_sfa.account_id.present? &&+ upstream_account_ids.exclude?(old_sfa.account_id.to_s)endif stale_matches.size > 1- Rails.logger.warn "SimplefinItem#repair_stale_linkages - Multiple linked accounts match '#{new_sfa.name}': #{stale_matches.map(&:id).join(', ')}. Using first match."+ Rails.logger.warn "SimplefinItem#repair_stale_linkages - Multiple stale linked accounts match '#{new_sfa.name}': #{stale_matches.map(&:id).join(', ')}. Ambiguous, skipping repair."+ nextendstale_match = stale_matches.firstdiff --git a/app/models/simplefin_item/importer.rb b/app/models/simplefin_item/importer.rbindex f58af403df..945b3615fd 100644--- a/app/models/simplefin_item/importer.rb+++ b/app/models/simplefin_item/importer.rb@@ -565,6 +565,11 @@ class SimplefinItem::Importer## Returns nothing; side-effects are snapshot + account upserts.def perform_account_discovery+ # Clear any upstream_account_ids left over from a prior discovery on this same+ # SimplefinItem instance (e.g. reused across import runs). If this discovery finds+ # zero accounts, we must not let repair_stale_linkages act on stale IDs from before.+ simplefin_item.upstream_account_ids = nil+Rails.logger.info "SimplefinItem::Importer - perform_account_discovery START (no date params - transactions may be empty)"discovery_data = fetch_accounts_data(start_date: nil)discovered_count = discovery_data&.dig(:accounts)&.size.to_i@@ -603,6 +608,11 @@ class SimplefinItem::Importer# SimplefinAccount records would appear in the setup UI as duplicates.upstream_account_ids = discovery_data[:accounts].map { |a| a[:id].to_s }.compactprune_orphaned_simplefin_accounts(upstream_account_ids)++ # Expose to SimplefinItem#repair_stale_linkages, which runs later in the same sync+ # (via SimplefinItem::Syncer -> #process_accounts) and needs to know which linked+ # accounts are actually absent upstream before treating them as stale. See GH #2852.+ simplefin_item.upstream_account_ids = upstream_account_idsendenddiff --git a/test/models/simplefin_account/transactions/processor_investment_test.rb b/test/models/simplefin_account/transactions/processor_investment_test.rbindex 587c3fc015..7cbacb74a5 100644--- a/test/models/simplefin_account/transactions/processor_investment_test.rb+++ b/test/models/simplefin_account/transactions/processor_investment_test.rb@@ -199,6 +199,10 @@ class SimplefinAccount::Transactions::ProcessorInvestmentTest < ActiveSupport::T# Before repair: @simplefin_account is linked (but stale), new_simplefin_account is unlinkedassert_equal @simplefin_account.id, @account.reload.simplefin_account_id+ # Simulate what SimplefinItem::Importer sets during discovery: the old account_id is+ # genuinely absent upstream, so the repair is allowed to proceed.+ @simplefin_item.upstream_account_ids = [ new_simplefin_account.account_id ]+# Process accounts - should repair the stale linkage@simplefin_item.process_accounts@@ -261,6 +265,10 @@ class SimplefinAccount::Transactions::ProcessorInvestmentTest < ActiveSupport::T])+ # Simulate what SimplefinItem::Importer sets during discovery: the old account_id is+ # genuinely absent upstream, so the repair is allowed to proceed.+ @simplefin_item.upstream_account_ids = [ new_simplefin_account.account_id ]+@simplefin_item.process_accounts# Should transfer linkage to new account (repair by name match)diff --git a/test/models/simplefin_item/importer_orphan_prune_test.rb b/test/models/simplefin_item/importer_orphan_prune_test.rbindex 626e2d1bf2..e500481286 100644--- a/test/models/simplefin_item/importer_orphan_prune_test.rb+++ b/test/models/simplefin_item/importer_orphan_prune_test.rb@@ -171,4 +171,27 @@ class SimplefinItem::ImporterOrphanPruneTest < ActiveSupport::TestCasestats = @sync.reload.sync_statsassert_equal 2, stats["accounts_pruned"], "should track both pruned accounts"end++ test "clears upstream_account_ids when a later discovery on the same item finds zero accounts" do+ # First discovery: provider returns one account, so upstream_account_ids gets set.+ mock_provider = mock()+ mock_provider.expects(:get_accounts).at_least_once.returns({+ accounts: [ { id: "ACT-business", name: "Business", balance: "100.00", currency: "USD", type: "checking" } ]+ })+ SimplefinItem::Importer.new(@item, simplefin_provider: mock_provider, sync: @sync)+ .send(:perform_account_discovery)++ assert_equal [ "ACT-business" ], @item.upstream_account_ids++ # Second discovery on the same SimplefinItem instance (e.g. a later sync run) finds+ # nothing upstream (both the plain and pending=true attempts return zero accounts).+ # It must NOT leave the stale IDs from the first discovery in place, or+ # repair_stale_linkages could later act on obsolete provider state (see GH #2852).+ empty_provider = mock()+ empty_provider.expects(:get_accounts).at_least_once.returns({ accounts: [] })+ SimplefinItem::Importer.new(@item, simplefin_provider: empty_provider, sync: @sync)+ .send(:perform_account_discovery)++ assert_nil @item.upstream_account_ids, "stale upstream_account_ids from a prior discovery must be cleared"+ endenddiff --git a/test/models/simplefin_item/repair_stale_linkages_test.rb b/test/models/simplefin_item/repair_stale_linkages_test.rbnew file mode 100644index 0000000000..1b3f774896--- /dev/null+++ b/test/models/simplefin_item/repair_stale_linkages_test.rb@@ -0,0 +1,192 @@+require "test_helper"++class SimplefinItem::RepairStaleLinkagesTest < 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)+ end++ test "does not hijack a linked account when an unlinked account merely shares its name (GH #2852)" do+ linked_sfa = SimplefinAccount.create!(+ simplefin_item: @item,+ account_id: "ACT-linked",+ name: "CHECKING (0001)",+ currency: "USD",+ current_balance: 100,+ account_type: "checking"+ )+ account = Account.create!(+ family: @family,+ name: "Checking",+ currency: "USD",+ balance: 100,+ accountable: Depository.create!(subtype: :checking)+ )+ AccountProvider.create!(account: account, provider: linked_sfa)++ unlinked_sfa = SimplefinAccount.create!(+ simplefin_item: @item,+ account_id: "ACT-unlinked-twin",+ name: "CHECKING (0001)",+ currency: "USD",+ current_balance: 999,+ account_type: "checking",+ raw_transactions_payload: [ { id: "txn-1", posted: 1_700_000_000, amount: "-10.00", description: "Coffee" } ]+ )++ # Both accounts are still present upstream (this is the reported failure mode:+ # two genuinely distinct accounts that happen to share a display name).+ @item.upstream_account_ids = [ linked_sfa.account_id, unlinked_sfa.account_id ]++ @item.send(:repair_stale_linkages, [ linked_sfa, unlinked_sfa ])++ linked_sfa.reload+ unlinked_sfa.reload++ assert_equal account, linked_sfa.current_account, "the correctly-linked account must keep its linkage"+ assert_nil unlinked_sfa.current_account, "the distinct twin must remain unlinked"+ assert_empty linked_sfa.raw_transactions_payload.to_a, "linked account's transactions must not be overwritten by its twin's"+ end++ test "still repairs a genuinely stale linkage when the old account_id is absent upstream" do+ stale_sfa = SimplefinAccount.create!(+ simplefin_item: @item,+ account_id: "ACT-old-id",+ name: "Business",+ currency: "USD",+ current_balance: 100,+ account_type: "checking",+ raw_transactions_payload: [ { id: "old-txn", posted: 1_699_000_000, amount: "-5.00", description: "Old" } ]+ )+ account = Account.create!(+ family: @family,+ name: "Business Checking",+ currency: "USD",+ balance: 100,+ accountable: Depository.create!(subtype: :checking)+ )+ AccountProvider.create!(account: account, provider: stale_sfa)++ new_sfa = SimplefinAccount.create!(+ simplefin_item: @item,+ account_id: "ACT-new-id",+ name: "Business",+ currency: "USD",+ current_balance: 288.41,+ account_type: "checking",+ raw_transactions_payload: [ { id: "new-txn", posted: 1_700_000_000, amount: "-10.00", description: "New" } ]+ )++ # Only the new account_id comes back upstream; the old one is genuinely gone+ # (e.g. the user deleted and re-added the institution in SimpleFIN).+ @item.upstream_account_ids = [ new_sfa.account_id ]++ @item.send(:repair_stale_linkages, [ stale_sfa, new_sfa ])++ new_sfa.reload+ stale_sfa.reload++ assert_equal account, new_sfa.current_account, "linkage should transfer to the new SimplefinAccount"+ assert_nil stale_sfa.current_account, "the old SimplefinAccount should be left orphaned"+ assert_equal 2, new_sfa.raw_transactions_payload.to_a.size, "transactions from both should be merged"+ end++ test "skips repair when upstream_account_ids is unavailable" do+ linked_sfa = SimplefinAccount.create!(+ simplefin_item: @item,+ account_id: "ACT-linked",+ name: "Business",+ currency: "USD",+ current_balance: 100,+ account_type: "checking"+ )+ account = Account.create!(+ family: @family,+ name: "Business Checking",+ currency: "USD",+ balance: 100,+ accountable: Depository.create!(subtype: :checking)+ )+ AccountProvider.create!(account: account, provider: linked_sfa)++ unlinked_sfa = SimplefinAccount.create!(+ simplefin_item: @item,+ account_id: "ACT-unlinked",+ name: "Business",+ currency: "USD",+ current_balance: 999,+ account_type: "checking",+ raw_transactions_payload: [ { id: "txn-1", posted: 1_700_000_000, amount: "-10.00", description: "Coffee" } ]+ )++ assert_nil @item.upstream_account_ids++ assert_difference "DebugLogEntry.count", 1 do+ @item.send(:repair_stale_linkages, [ linked_sfa, unlinked_sfa ])+ end++ assert_equal account, linked_sfa.reload.current_account+ assert_nil unlinked_sfa.reload.current_account++ entry = DebugLogEntry.last+ assert_equal "provider_sync_warning", entry.category+ assert_equal "simplefin", entry.provider_key+ assert_equal @family, entry.family+ end++ test "does not act on an ambiguous multi-way name match" do+ linked_sfa = SimplefinAccount.create!(+ simplefin_item: @item,+ account_id: "ACT-linked",+ name: "Checking",+ currency: "USD",+ current_balance: 100,+ account_type: "checking"+ )+ account = Account.create!(+ family: @family,+ name: "Checking",+ currency: "USD",+ balance: 100,+ accountable: Depository.create!(subtype: :checking)+ )+ AccountProvider.create!(account: account, provider: linked_sfa)++ other_linked_sfa = SimplefinAccount.create!(+ simplefin_item: @item,+ account_id: "ACT-other-linked",+ name: "Checking",+ currency: "USD",+ current_balance: 50,+ account_type: "checking"+ )+ other_account = Account.create!(+ family: @family,+ name: "Other Checking",+ currency: "USD",+ balance: 50,+ accountable: Depository.create!(subtype: :checking)+ )+ AccountProvider.create!(account: other_account, provider: other_linked_sfa)++ unlinked_sfa = SimplefinAccount.create!(+ simplefin_item: @item,+ account_id: "ACT-unlinked",+ name: "Checking",+ currency: "USD",+ current_balance: 999,+ account_type: "checking",+ raw_transactions_payload: [ { id: "txn-1", posted: 1_700_000_000, amount: "-10.00", description: "Coffee" } ]+ )++ # Neither linked account_id is present upstream, so both are candidates -> ambiguous.+ @item.upstream_account_ids = [ unlinked_sfa.account_id ]++ @item.send(:repair_stale_linkages, [ linked_sfa, other_linked_sfa, unlinked_sfa ])++ assert_equal account, linked_sfa.reload.current_account+ assert_equal other_account, other_linked_sfa.reload.current_account+ assert_nil unlinked_sfa.reload.current_account+ end+end