Log swallowed Brex import failures to the debug log (#5479)

## Summary

Provider kit follow-up: `BrexItem::Importer` rescued its per-call
failures and only wrote them to `Rails.logger`, so a partly failed Brex
import left nothing in `/settings/debug`. AGENTS.md asks for
`DebugLogEntry.capture` for support-relevant failures and partial
responses.

Part of #5003.

Stacked on #5478. Fork pre-flight: jaysbeekay/sure#925 (same branch,
same commit). Fork issue: jaysbeekay/sure#816.

## What changed

- One private helper, `capture_import_failure`, is called at each fetch
and import rescue that swallows an error: the accounts fetch (bad
format, `BrexError`, parse, unexpected), one account's import, and one
account's transactions (bad format, `BrexError`, parse, unexpected, and
the per-account rescue around it).
`mark_requires_update_if_credentials_error` still only logs a failure of
its own status update.
- Each entry records `provider_key: "brex"` and the family. A
transactions failure also records the Brex account's link; an
account-import failure records only the account id, since that account
may not be linked yet.
- Its metadata holds `brex_item_id`, `account_id`, `error_class`,
`error_message` and `trace_id`, with blanks dropped.
- Credential errors are re-raised without a capture here. The kit syncer
already logs them (`provider_sync_error`), so capturing here too would
record each one twice. The snapshot-store failure re-raises and is left
to the syncer for the same reason.
- Return values are unchanged.

## Verification

- Fail-first: a failed accounts fetch and a failed transactions fetch
each add one entry with the exact metadata; before the change they added
none. A failed account import carries its account id in the metadata.
Each of the other seven capture sites has its own test: the accounts
fetch's non-Hash response, parse error and unexpected error, the same
three for a transactions fetch, and the per-account transactions rescue.
- Guards:
  - a 401 during a sync adds exactly one entry, the syncer's;
  - a clean import adds none.
- Mutations, each caught: removing either capture, capturing before the
credential re-raise, dropping `trace_id`, dropping the account link, and
dropping `account_id`.
- `bin/rails test` (full, at e3ab39fc0): 16620 runs, 0 failures (8
`ReleaseNotesWorkflowTest` environment errors). rubocop clean. Non-test
diff +31 / -0; +179 / -1 with tests.

## Migration notes

No migration.

<!-- This is an auto-generated description by cubic. -->
---
## Summary by cubic
Logs swallowed Brex import failures so a partly failed import now leaves
entries in `/settings/debug` for support to see.

- Calls a new private helper, `capture_import_failure`, at every rescue
that swallows an error: accounts fetch, per-account import, and
per-account transactions.
- Each entry records the `"brex"` provider key, the family, and the Brex
account link when there is one; metadata holds `brex_item_id`,
`account_id`, `error_class`, `error_message`, and `trace_id`, with
blanks dropped.
- Credential errors and snapshot-store failures are still re-raised
without a capture because the kit syncer already logs them once each.
- Tests pin each of the seven capture sites to exactly one entry, and a
403 on transactions must yield exactly one entry, from the syncer, so a
capture placed above the credential re-raise can't log the failure
twice.
- Return values are unchanged.

<sup>Written for commit 2db7e1872f.
Summary will update on new commits.</sup>

<a
href="https://cubic.dev/pr/we-promise/sure/pull/5479?utm_source=github"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/review-in-cubic-light.svg"><img
alt="View guided diff"
src="https://www.cubic.dev/buttons/review-in-cubic-light.svg"></picture></a>
<a
href="https://www.cubic.dev/action/auto-fix/pr/we-promise/sure/5479?returnTo=https%3A%2F%2Fgithub.com%2Fwe-promise%2Fsure%2Fpull%2F5479&source=description"
target="_blank" rel="noopener noreferrer"
data-no-image-dialog="true"><picture><source
media="(prefers-color-scheme: dark)"
srcset="https://www.cubic.dev/buttons/turn-on-auto-fix-dark.svg"><source
media="(prefers-color-scheme: light)"
srcset="https://www.cubic.dev/buttons/turn-on-auto-fix-light.svg"><img
alt="Turn on auto-fix"
src="https://www.cubic.dev/buttons/turn-on-auto-fix-light.svg"></picture></a>

<!-- End of auto-generated description by cubic. -->
This commit is contained in:
jaysbeekay
2026-12-01 17:16:03 -08:00
committed by Juan José Mata
parent b24b466379
commit 52a50e24f0
3 changed files with 179 additions and 1 deletions
+31
View File
@@ -36,6 +36,7 @@ class BrexItem::Importer
unless accounts_data.is_a?(Hash)
Rails.logger.error "BrexItem::Importer - Invalid accounts_data format: expected Hash, got #{accounts_data.class}"
capture_import_failure("Invalid accounts response format")
return nil
end
@@ -45,13 +46,16 @@ class BrexItem::Importer
Rails.logger.error "BrexItem::Importer - Brex API error: #{e.message} trace_id=#{e.trace_id}"
# A rejected token fails the sync instead of completing it with nothing imported
raise if credentials_error?(e)
capture_import_failure("Failed to fetch accounts", error: e)
nil
rescue JSON::ParserError => e
Rails.logger.error "BrexItem::Importer - Failed to parse Brex API response: #{e.message}"
capture_import_failure("Failed to parse accounts response", error: e)
nil
rescue => e
Rails.logger.error "BrexItem::Importer - Unexpected error fetching accounts: #{e.class} - #{e.message}"
Rails.logger.error Array(e.backtrace).join("\n")
capture_import_failure("Unexpected error fetching accounts", error: e)
nil
end
@@ -93,6 +97,7 @@ class BrexItem::Importer
rescue => e
accounts_failed += 1
Rails.logger.error "BrexItem::Importer - Failed to import account #{account_id.presence || 'unknown'}: #{e.message}"
capture_import_failure("Failed to import account", error: e, account_id: account_id.presence)
end
{
@@ -129,6 +134,7 @@ class BrexItem::Importer
transactions_failed += 1
Rails.logger.error "BrexItem::Importer - Failed to fetch/store transactions for account #{brex_account.account_id}: #{e.message}"
capture_import_failure("Failed to import transactions", error: e, brex_account: brex_account)
end
{
@@ -149,6 +155,7 @@ class BrexItem::Importer
unless transactions_data.is_a?(Hash)
Rails.logger.error "BrexItem::Importer - Invalid transactions_data format for account #{brex_account.account_id}"
capture_import_failure("Invalid transactions response format", brex_account: brex_account)
return { success: false, transactions_count: 0, error: "Invalid response format" }
end
@@ -161,13 +168,16 @@ class BrexItem::Importer
Rails.logger.error "BrexItem::Importer - Brex API error for account #{brex_account.account_id}: #{e.message} trace_id=#{e.trace_id}"
# Also when the token can list accounts but not read their transactions
raise if credentials_error?(e)
capture_import_failure("Failed to fetch transactions", error: e, brex_account: brex_account)
{ success: false, transactions_count: 0, error: e.message }
rescue JSON::ParserError => e
Rails.logger.error "BrexItem::Importer - Failed to parse transaction response for account #{brex_account.account_id}: #{e.message}"
capture_import_failure("Failed to parse transactions response", error: e, brex_account: brex_account)
{ success: false, transactions_count: 0, error: "Failed to parse response" }
rescue => e
Rails.logger.error "BrexItem::Importer - Unexpected error fetching transactions for account #{brex_account.account_id}: #{e.class} - #{e.message}"
Rails.logger.error Array(e.backtrace).join("\n")
capture_import_failure("Unexpected error fetching transactions", error: e, brex_account: brex_account)
{ success: false, transactions_count: 0, error: "Unexpected error: #{e.message}" }
end
@@ -241,6 +251,27 @@ class BrexItem::Importer
Rails.logger.error "BrexItem::Importer - Failed to update item status: #{update_error.message}"
end
# Failures the import swallows, for the debug log. Credential errors are
# re-raised instead, and the syncer logs those.
def capture_import_failure(message, error: nil, brex_account: nil, account_id: brex_account&.account_id)
DebugLogEntry.capture(
category: "provider_sync_error",
level: "error",
message: message,
source: self.class.name,
provider_key: "brex",
family: brex_item.family,
account_provider: brex_account&.account_provider,
metadata: {
brex_item_id: brex_item.id,
account_id: account_id,
error_class: error&.class&.name,
error_message: error&.message,
trace_id: error.try(:trace_id)
}.compact
)
end
def failed_result(error)
{
success: false,
+144
View File
@@ -295,6 +295,150 @@ class BrexItem::ImporterTest < ActiveSupport::TestCase
assert_equal BigDecimal("987.65"), unlinked_account.current_balance
end
test "a failed accounts fetch records a debug log entry for support" do
provider = mock("brex_provider")
provider.expects(:get_accounts).raises(
Provider::Brex::BrexError.new("Brex API server error", :server_error, http_status: 500, trace_id: "trace_456")
)
result = nil
assert_difference -> { DebugLogEntry.count }, 1 do
result = BrexItem::Importer.new(@brex_item, brex_provider: provider).import
end
assert_not result[:success]
entry = DebugLogEntry.recent.first
assert_equal [ "brex", "BrexItem::Importer", "error" ], [ entry.provider_key, entry.source, entry.level ]
assert_equal @family, entry.family
assert_nil entry.account_provider
assert_equal(
{ "brex_item_id" => @brex_item.id, "error_class" => "Provider::Brex::BrexError",
"error_message" => "Brex API server error", "trace_id" => "trace_456" },
entry.metadata
)
end
test "a failed transactions fetch records a debug log entry for the account" do
provider = mock("brex_provider")
provider.expects(:get_accounts).returns(accounts: [ cash_account_payload ])
provider.expects(:get_cash_transactions).raises(
Provider::Brex::BrexError.new("Rate limit exceeded", :rate_limited, http_status: 429, trace_id: "trace_789")
)
result = nil
assert_difference -> { DebugLogEntry.count }, 1 do
result = BrexItem::Importer.new(@brex_item, brex_provider: provider).import
end
assert_equal 1, result[:transactions_failed]
entry = DebugLogEntry.recent.first
assert_equal [ "brex", "BrexItem::Importer" ], [ entry.provider_key, entry.source ]
assert_equal @family, entry.family
assert_equal @brex_account.account_provider, entry.account_provider
assert_equal(
{ "brex_item_id" => @brex_item.id, "account_id" => "cash_1", "error_class" => "Provider::Brex::BrexError",
"error_message" => "Rate limit exceeded", "trace_id" => "trace_789" },
entry.metadata
)
end
test "a failed account import records the account id in the metadata" do
provider = mock("brex_provider")
provider.expects(:get_accounts).returns(accounts: [ cash_account_payload ])
provider.stubs(:get_cash_transactions).returns(transactions: [])
BrexAccount.any_instance.stubs(:upsert_brex_snapshot!).raises(StandardError, "snapshot write failed")
assert_difference -> { DebugLogEntry.count }, 1 do
BrexItem::Importer.new(@brex_item, brex_provider: provider).import
end
entry = DebugLogEntry.recent.first
assert_equal "Failed to import account", entry.message
assert_equal(
{ "brex_item_id" => @brex_item.id, "account_id" => "cash_1", "error_class" => "StandardError",
"error_message" => "snapshot write failed" },
entry.metadata
)
end
{
"an accounts response that is not a Hash" => [ -> { [] }, "Invalid accounts response format", nil ],
"an accounts response that cannot be parsed" => [ -> { raise JSON::ParserError, "unexpected token" }, "Failed to parse accounts response", "JSON::ParserError" ],
"an unexpected accounts fetch error" => [ -> { raise ArgumentError, "boom" }, "Unexpected error fetching accounts", "ArgumentError" ]
}.each do |name, (response, message, error_class)|
test "#{name} records a debug log entry" do
provider = Object.new
provider.define_singleton_method(:get_accounts) { response.call }
assert_difference -> { DebugLogEntry.where(message: message).count }, 1 do
assert_not BrexItem::Importer.new(@brex_item, brex_provider: provider).import[:success]
end
assert_equal({ "error_class" => error_class }.compact, DebugLogEntry.find_by!(message: message).metadata.slice("error_class"))
end
end
{
"a transactions response that is not a Hash" => [ -> { [] }, "Invalid transactions response format", nil ],
"a transactions response that cannot be parsed" => [ -> { raise JSON::ParserError, "unexpected token" }, "Failed to parse transactions response", "JSON::ParserError" ],
"an unexpected transactions fetch error" => [ -> { raise ArgumentError, "boom" }, "Unexpected error fetching transactions", "ArgumentError" ]
}.each do |name, (response, message, error_class)|
test "#{name} records a debug log entry for the account" do
accounts = { accounts: [ cash_account_payload ] }
provider = Object.new
provider.define_singleton_method(:get_accounts) { accounts }
provider.define_singleton_method(:get_cash_transactions) { |*, **| response.call }
result = nil
assert_difference -> { DebugLogEntry.where(message: message).count }, 1 do
result = BrexItem::Importer.new(@brex_item, brex_provider: provider).import
end
assert_equal 1, result[:transactions_failed]
entry = DebugLogEntry.find_by!(message: message)
assert_equal @brex_account.account_provider, entry.account_provider
assert_equal [ "cash_1", error_class ], entry.metadata.values_at("account_id", "error_class")
end
end
test "a transactions failure outside the fetch records a debug log entry for the account" do
provider = mock("brex_provider")
provider.expects(:get_accounts).returns(accounts: [ cash_account_payload ])
BrexItem::Importer.any_instance.stubs(:fetch_and_store_transactions).raises(ArgumentError, "boom")
result = nil
assert_difference -> { DebugLogEntry.where(message: "Failed to import transactions").count }, 1 do
result = BrexItem::Importer.new(@brex_item, brex_provider: provider).import
end
assert_equal 1, result[:transactions_failed]
entry = DebugLogEntry.find_by!(message: "Failed to import transactions")
assert_equal @brex_account.account_provider, entry.account_provider
assert_equal [ "cash_1", "ArgumentError" ], entry.metadata.values_at("account_id", "error_class")
end
test "a credential failure is logged once, by the syncer, not by the importer" do
Provider::Brex.any_instance.stubs(:get_accounts).raises(
Provider::Brex::BrexError.new("Invalid Brex API token", :unauthorized, http_status: 401, trace_id: "trace_401")
)
Sentry.stubs(:capture_exception)
assert_difference -> { DebugLogEntry.count }, 1 do
Sync.create!(syncable: @brex_item).perform
end
assert_equal "BrexItem::Syncer", DebugLogEntry.recent.first.source
end
test "a clean import records no debug log entry" do
provider = mock("brex_provider")
provider.expects(:get_accounts).returns(accounts: [ cash_account_payload ])
provider.expects(:get_cash_transactions).returns(transactions: [])
assert_no_difference -> { DebugLogEntry.count } do
assert BrexItem::Importer.new(@brex_item, brex_provider: provider).import[:success]
end
end
private
def cash_account_payload
+4 -1
View File
@@ -167,11 +167,14 @@ class BrexItem::SyncerTest < ActiveSupport::TestCase
.raises(Provider::Brex::BrexError.new("Access forbidden", :access_forbidden, http_status: 403))
sync = Sync.create!(syncable: @brex_item)
sync.perform
assert_difference -> { DebugLogEntry.count }, 1 do
sync.perform
end
assert sync.reload.failed?, "expected the sync to fail, was #{sync.status}"
assert_equal I18n.t("brex_items.syncer.credentials_invalid"), sync.error
assert @brex_item.reload.requires_update?
assert_equal "BrexItem::Syncer", DebugLogEntry.where(provider_key: "brex").recent.first.source
end
private