The personal finance app for everyone (by everyone)
Ruby
Fix Plaid transaction sync pagination recovery (#5654)
Darrell538c892b77f0
diff --git a/app/models/plaid_item/importer.rb b/app/models/plaid_item/importer.rbindex b64b9d852b..ad68246055 100644--- a/app/models/plaid_item/importer.rb+++ b/app/models/plaid_item/importer.rb@@ -51,6 +51,9 @@ class PlaidItem::Importerdef fetch_and_import_accounts_datasnapshot = PlaidItem::AccountsSnapshot.new(plaid_item, plaid_provider: plaid_provider)returned_ids = snapshot.accounts.map(&:account_id)+ # Fetch before opening the import transaction so retry diagnostics survive+ # exhausted retries or a later account import failure.+ transactions_cursor = snapshot.transactions_cursorPlaidItem.transaction dosnapshot.accounts.each do |raw_account|@@ -65,7 +68,7 @@ class PlaidItem::Importerclear_liabilities_of_omitted_accounts(snapshot)# Once we know all data has been imported, save the cursor to avoid re-fetching the same data next time- plaid_item.update!(next_cursor: snapshot.transactions_cursor)+ plaid_item.update!(next_cursor: transactions_cursor)endenddiff --git a/app/models/provider/plaid.rb b/app/models/provider/plaid.rbindex 09d88e18e1..f9487f46d2 100644--- a/app/models/provider/plaid.rb+++ b/app/models/provider/plaid.rb@@ -3,6 +3,7 @@ class Provider::PlaidSUPPORTED_PLAID_PRODUCTS = %w[transactions investments liabilities].freezeMAX_HISTORY_DAYS = Rails.env.development? ? 90 : 730+ MAX_TRANSACTION_SYNC_RETRIES = 3def initialize(config, region: :us)@client = Plaid::PlaidApi.new(@@ -92,31 +93,52 @@ class Provider::Plaidenddef get_transactions(access_token, next_cursor: nil)- cursor = next_cursor- added = []- modified = []- removed = []- has_more = true-- while has_more- request = Plaid::TransactionsSyncRequest.new(- access_token: access_token,- cursor: cursor,- options: {- include_original_description: true- }- )+ retries = 0- response = client.transactions_sync(request)+ begin+ cursor = next_cursor+ added = []+ modified = []+ removed = []+ has_more = true- added += response.added- modified += response.modified- removed += response.removed- has_more = response.has_more- cursor = response.next_cursor- end+ while has_more+ request = Plaid::TransactionsSyncRequest.new(+ access_token: access_token,+ cursor: cursor,+ count: 500,+ options: {+ include_original_description: true+ }+ )++ response = client.transactions_sync(request)++ added += response.added+ modified += response.modified+ removed += response.removed+ has_more = response.has_more+ cursor = response.next_cursor+ end++ TransactionSyncResponse.new(added:, modified:, removed:, cursor:)+ rescue Plaid::ApiError => error+ error_code = plaid_error_code(error)+ raise unless error_code == "TRANSACTIONS_SYNC_MUTATION_DURING_PAGINATION" && retries < MAX_TRANSACTION_SYNC_RETRIES++ retries += 1+ DebugLogEntry.capture(+ category: "provider_sync",+ level: "info",+ message: "Restarting Plaid transaction pagination after data changed",+ source: self.class.name,+ provider_key: "plaid",+ metadata: { error_code: error_code, retry_count: retries }+ )- TransactionSyncResponse.new(added:, modified:, removed:, cursor:)+ # A changed page invalidates the whole update, including accumulated rows.+ retry+ endenddef refresh_transactions(access_token)@@ -152,6 +174,13 @@ class Provider::Plaidendprivate+ def plaid_error_code(error)+ body = JSON.parse(error.response_body.to_s)+ body["error_code"] if body.is_a?(Hash)+ rescue JSON::ParserError+ nil+ end+TransactionSyncResponse = Struct.new :added, :modified, :removed, :cursor, keyword_init: trueInvestmentsResponse = Struct.new :holdings, :transactions, :securities, keyword_init: truediff --git a/test/models/plaid_item/importer_retry_diagnostics_test.rb b/test/models/plaid_item/importer_retry_diagnostics_test.rbnew file mode 100644index 0000000000..3debbdda4b--- /dev/null+++ b/test/models/plaid_item/importer_retry_diagnostics_test.rb@@ -0,0 +1,90 @@+require "test_helper"+require "ostruct"++class PlaidItem::ImporterRetryDiagnosticsTest < ActiveSupport::TestCase+ # These assertions must observe a real import rollback, not a transaction+ # joined to the fixture transaction that rolls back only after the test.+ self.use_transactional_tests = false++ setup do+ @existing_log_ids = retry_logs.pluck(:id)+ @item = PlaidItem.create!(+ family: families(:dylan_family), name: "Retry diagnostics bank", plaid_id: "retry-item",+ access_token: "synthetic-token", next_cursor: "saved-cursor",+ billed_products: [ "transactions" ], available_products: []+ )+ @account = @item.plaid_accounts.create!(+ plaid_id: "retry-account", name: "Retry account", plaid_type: "depository",+ currency: "USD", current_balance: 1000+ )+ @provider = Provider::Plaid.new(Plaid::Configuration.new)+ @importer = PlaidItem::Importer.new(@item, plaid_provider: @provider)+ @importer.stubs(:fetch_and_import_item_data)++ raw_account = Plaid::AccountBase.new(+ account_id: @account.plaid_id, name: "Retry account", type: "depository",+ subtype: "checking", balances: Plaid::AccountBalance.new(current: 1234, iso_currency_code: "USD")+ )+ @provider.client.expects(:accounts_get).returns(OpenStruct.new(accounts: [ raw_account ]))+ end++ teardown do+ retry_logs.where.not(id: @existing_log_ids).delete_all+ if @item+ PlaidAccount.where(plaid_item_id: @item.id).delete_all+ PlaidItem.where(id: @item.id).delete_all+ end+ end++ test "retry diagnostics persist when transaction pagination exhausts its retries" do+ pages = sequence("transaction pages")+ error = mutation_error+ 4.times do+ expect_page("saved-cursor", pages).returns(transaction_page("page-2", has_more: true))+ expect_page("page-2", pages).raises(error)+ end+ PlaidAccount::Importer.any_instance.expects(:import).never++ assert_difference -> { retry_logs.count }, 3 do+ assert_same error, assert_raises(Plaid::ApiError) { @importer.import }+ end++ assert_equal [ 1, 2, 3 ], retry_logs.order(:created_at).where.not(id: @existing_log_ids).map { |log| log.metadata.fetch("retry_count") }+ assert_equal "saved-cursor", @item.reload.next_cursor+ assert_equal 1000, @account.reload.current_balance+ end++ test "retry diagnostics survive a later import rollback without advancing the cursor" do+ pages = sequence("transaction pages")+ expect_page("saved-cursor", pages).raises(mutation_error)+ expect_page("saved-cursor", pages).returns(transaction_page("complete"))+ error = StandardError.new("Synthetic cursor persistence failure")+ @item.expects(:update!).with(next_cursor: "complete").raises(error)++ assert_difference -> { retry_logs.count }, 1 do+ assert_same error, assert_raises(StandardError) { @importer.import }+ end++ assert_equal "saved-cursor", @item.reload.next_cursor+ assert_equal 1000, @account.reload.current_balance+ log = retry_logs.where.not(id: @existing_log_ids).sole+ assert_equal({ "error_code" => "TRANSACTIONS_SYNC_MUTATION_DURING_PAGINATION", "retry_count" => 1 }, log.metadata)+ end++ private+ def retry_logs+ DebugLogEntry.where(source: "Provider::Plaid", message: "Restarting Plaid transaction pagination after data changed")+ end++ def expect_page(cursor, pages)+ @provider.client.expects(:transactions_sync).with { |request| request.cursor == cursor }.in_sequence(pages)+ end++ def transaction_page(cursor, has_more: false)+ OpenStruct.new(added: [], modified: [], removed: [], next_cursor: cursor, has_more: has_more)+ end++ def mutation_error+ Plaid::ApiError.new(code: 400, response_body: { error_code: "TRANSACTIONS_SYNC_MUTATION_DURING_PAGINATION" }.to_json)+ end+enddiff --git a/test/models/provider/plaid_test.rb b/test/models/provider/plaid_test.rbindex 39d015bd87..f8eced3571 100644--- a/test/models/provider/plaid_test.rb+++ b/test/models/provider/plaid_test.rb@@ -149,6 +149,109 @@ class Provider::PlaidTest < ActiveSupport::TestCaseendend+ test "collects all transaction pages with the maximum page size" do+ pages = sequence("transaction pages")+ expect_transaction_page("saved-cursor", pages).returns(transaction_page("page-2", has_more: true, prefix: "first"))+ expect_transaction_page("page-2", pages).returns(transaction_page("complete", prefix: "second"))+ DebugLogEntry.expects(:capture).never++ result = @plaid.get_transactions("access-token", next_cursor: "saved-cursor")++ assert_equal [ "first-added", "second-added" ], result.added+ assert_equal [ "first-modified", "second-modified" ], result.modified+ assert_equal [ "first-removed", "second-removed" ], result.removed+ assert_equal "complete", result.cursor+ end++ test "restarts the entire transaction update and discards partial results" do+ pages = sequence("transaction pages")+ expect_transaction_page("saved-cursor", pages).returns(transaction_page("page-2", has_more: true, prefix: "discarded"))+ expect_transaction_page("page-2", pages).raises(transaction_mutation_error)+ expect_transaction_page("saved-cursor", pages).returns(transaction_page("retry-page-2", has_more: true, prefix: "retry-first"))+ expect_transaction_page("retry-page-2", pages).returns(transaction_page("complete", prefix: "retry-second"))+ expect_transaction_restart(1)++ result = @plaid.get_transactions("access-token", next_cursor: "saved-cursor")++ assert_equal [ "retry-first-added", "retry-second-added" ], result.added+ assert_equal [ "retry-first-modified", "retry-second-modified" ], result.modified+ assert_equal [ "retry-first-removed", "retry-second-removed" ], result.removed+ assert_equal "complete", result.cursor+ end++ test "restarts an initial transaction sync without a cursor" do+ pages = sequence("transaction pages")+ expect_transaction_page(nil, pages).returns(transaction_page("page-2", has_more: true, prefix: "discarded"))+ expect_transaction_page("page-2", pages).raises(transaction_mutation_error)+ expect_transaction_page(nil, pages).returns(transaction_page("complete"))+ expect_transaction_restart(1)++ result = @plaid.get_transactions("access-token")++ assert_equal [ "kept-added" ], result.added+ assert_equal [ "kept-modified" ], result.modified+ assert_equal [ "kept-removed" ], result.removed+ assert_equal "complete", result.cursor+ end++ test "allows three transaction pagination restarts" do+ pages = sequence("transaction pages")+ 3.times do |index|+ expect_transaction_page("saved-cursor", pages).returns(transaction_page("page-2", has_more: true, prefix: "discarded"))+ expect_transaction_page("page-2", pages).raises(transaction_mutation_error)+ expect_transaction_restart(index + 1)+ end+ expect_transaction_page("saved-cursor", pages).returns(transaction_page("complete"))++ result = @plaid.get_transactions("access-token", next_cursor: "saved-cursor")++ assert_equal [ "kept-added" ], result.added+ assert_equal [ "kept-modified" ], result.modified+ assert_equal [ "kept-removed" ], result.removed+ assert_equal "complete", result.cursor+ end++ test "raises the Plaid error after exhausting transaction pagination restarts" do+ pages = sequence("transaction pages")+ error = transaction_mutation_error+ 4.times do |index|+ expect_transaction_page("saved-cursor", pages).returns(transaction_page("page-2", has_more: true))+ expect_transaction_page("page-2", pages).raises(error)+ expect_transaction_restart(index + 1) if index < 3+ end++ raised = assert_raises(Plaid::ApiError) do+ @plaid.get_transactions("access-token", next_cursor: "saved-cursor")+ end++ assert_same error, raised+ end++ {+ "unrelated Plaid error" => '{"error_code":"ITEM_LOGIN_REQUIRED"}',+ "item limit error" => '{"error_code":"TRANSACTIONS_SYNC_ITEM_LIMIT_EXCEEDED"}',+ "malformed error body" => "not json",+ "missing error body" => nil,+ "missing error code" => "{}",+ "array error body" => "[]",+ "null error body" => "null",+ "string error body" => '"unexpected"'+ }.each do |description, body|+ test "does not restart transaction pagination for #{description}" do+ pages = sequence("transaction pages")+ error = Plaid::ApiError.new(code: 400, response_body: body)+ expect_transaction_page("saved-cursor", pages).returns(transaction_page("page-2", has_more: true))+ expect_transaction_page("page-2", pages).raises(error)+ DebugLogEntry.expects(:capture).never++ raised = assert_raises(Plaid::ApiError) do+ @plaid.get_transactions("access-token", next_cursor: "saved-cursor")+ end++ assert_same error, raised+ end+ end+test "requests a transaction refresh" do@plaid.client.expects(:transactions_refresh).with do |request|request.access_token == "access-token"@@ -250,6 +353,41 @@ class Provider::PlaidTest < ActiveSupport::TestCaseendprivate+ def expect_transaction_page(cursor, pages)+ @plaid.client.expects(:transactions_sync).with do |request|+ request.access_token == "access-token" && request.cursor == cursor &&+ request.count == 500 && request.options == { include_original_description: true }+ end.in_sequence(pages)+ end++ def transaction_page(cursor, has_more: false, prefix: "kept")+ OpenStruct.new(+ added: [ "#{prefix}-added" ],+ modified: [ "#{prefix}-modified" ],+ removed: [ "#{prefix}-removed" ],+ has_more: has_more,+ next_cursor: cursor+ )+ end++ def transaction_mutation_error+ Plaid::ApiError.new(+ code: 400,+ response_body: { error_code: "TRANSACTIONS_SYNC_MUTATION_DURING_PAGINATION" }.to_json+ )+ end++ def expect_transaction_restart(retry_count)+ DebugLogEntry.expects(:capture).with(+ category: "provider_sync",+ level: "info",+ message: "Restarting Plaid transaction pagination after data changed",+ source: "Provider::PlaidSandbox",+ provider_key: "plaid",+ metadata: { error_code: "TRANSACTIONS_SYNC_MUTATION_DURING_PAGINATION", retry_count: retry_count }+ )+ end+# Pins the webhook verification contract that the jwt gem bump (2.10.3 -># 3.3.0) rides on: JWKS built from the key Plaid publishes for the token's# kid, ES256 decode with expiration skipped in favor of the iat age check,