The personal finance app for everyone (by everyone)
Ruby
Record failed DestroyJob deletions and retry deadlocks (#4469)
GFRc3f5c6d66a87
diff --git a/app/jobs/destroy_job.rb b/app/jobs/destroy_job.rbindex 8d9483536a..3460f60df0 100644--- a/app/jobs/destroy_job.rb+++ b/app/jobs/destroy_job.rb@@ -6,9 +6,85 @@ class DestroyJob < ApplicationJob# misleading.) Deferring is correct here: destroy after the enclosing# transaction commits, never against an uncommitted/rolled-back record.+ # A deadlock (say, with a sync writing to the same account) is transient, so+ # it is retried with growing waits (about 3s, 18s, 83s, 258s) so a long sync+ # can finish first. Once the attempts run out it is handled like any other+ # failure.+ retry_on ActiveRecord::Deadlocked, wait: :polynomially_longer, attempts: 5 do |job, error|+ job.send(:handle_failure, job.arguments.first, error)+ end+def perform(model)- model.destroy+ # destroy returns false instead of raising when a callback aborts it.+ model.destroy || raise(ActiveRecord::RecordNotDestroyed.new("#{model.class.name} #{model.try(:id)} was not destroyed", model))+ rescue ActiveRecord::Deadlocked => e+ # Once the row is gone (a deadlock in an after-commit step) a retry could not+ # load the record and would be discarded, so report it now.+ model.destroyed? ? handle_failure(model, e) : raiserescue => e- model.update!(scheduled_for_deletion: false) if model.respond_to?(:scheduled_for_deletion) # Let's the user try again by resetting the state+ handle_failure(model, e)end++ private+ def handle_failure(model, error)+ report_failure(model, error)+ ensure+ restore(model) unless model.destroyed?+ end++ # Lets the user try again by resetting the state. update_column skips+ # validations, as in DestroyableLater. Anything raised here (a validation+ # that depends on the flag, or a partial unique index the flag gates) would+ # send the job into Sidekiq's retries, failing and reporting each time.+ def restore(model)+ if model.is_a?(Account)+ # Account#destroy has usually restored it already; this call then+ # finds it disabled and does nothing.+ model.restore_after_failed_destroy+ elsif model.respond_to?(:scheduled_for_deletion)+ model.update_column(:scheduled_for_deletion, false)+ end+ rescue ActiveRecord::ActiveRecordError => e+ report_failure(model, e)+ end++ # Apart from deadlocks, a failed destroy ends the job instead of retrying,+ # so this is the only trace of why the record is still there.+ def report_failure(model, error)+ Rails.logger.error("DestroyJob failed for #{model.class.name} #{model.try(:id)}: #{error.class}: #{error.message}")+ Sentry.capture_exception(error) { |scope| scope.set_tags(record_type: model.class.name, record_id: model.try(:id)) } if defined?(Sentry)++ DebugLogEntry.capture(+ category: "background_jobs",+ level: "error",+ message: "Failed to delete #{model.class.name} #{model.try(:id)}: #{error.class}",+ source: self.class.name,+ **log_context(model),+ metadata: {+ record_type: model.class.name,+ record_id: model.try(:id),+ error_class: error.class.name,+ error_message: error.message.to_s.truncate(500),+ # Why a callback aborted the destroy, for RecordNotDestroyed.+ record_errors: error.try(:record).try(:errors)&.full_messages.presence,+ backtrace: error.backtrace&.first(5)+ }+ )+ end++ # An error raised after the delete committed (an after_commit callback)+ # leaves no row to link, and the account_id foreign key would reject it.+ def log_context(model)+ case model+ when Account+ model.destroyed? ? { family_id: model.family_id } : { account: model }+ when Family+ model.destroyed? ? {} : { family: model }+ else+ family = model.try(:family)+ context = family.is_a?(Family) ? { family: family } : {}+ context[:provider_key] = model.class.name.delete_suffix("Item").underscore if model.class.name.end_with?("Item")+ context+ end+ endenddiff --git a/app/models/account.rb b/app/models/account.rbindex 5b8d1dbe3f..120a9393b1 100644--- a/app/models/account.rb+++ b/app/models/account.rb@@ -717,18 +717,40 @@ class Account < ApplicationRecord# Override destroy to handle error recovery for accountsdef destroysuper+ rescue ActiveRecord::Deadlocked+ # DestroyJob retries a deadlock, so the account stays pending_deletion (and+ # out of the user's reach) until it gives up and restores it.+ raiserescue => e- # If destruction fails, leave the account disabled so it stays visible and- # can be deleted again. DestroyJob's scheduled_for_deletion reset is for- # provider items; accounts track deletion in `status`.- if may_restore_after_failed_deletion?- restore_after_failed_deletion!- elsif may_disable?- disable!- end+ # An error after the delete committed leaves a frozen record to restore.+ restore_after_failed_destroy unless destroyed?raise eend+ # Leaves the account disabled so it stays visible and can be deleted again.+ # DestroyJob's scheduled_for_deletion reset is for provider items; accounts+ # track deletion in `status`.+ #+ # Mirrors the restore_after_failed_deletion and disable events, but written+ # directly: an unrelated validation (an owner who has since left the family,+ # say) must not leave the account hidden in pending_deletion or replace the+ # destroy error with its own. Only while the row still holds the status this+ # record saw, so a newer write (another worker's restore the user has since+ # re-enabled, say) is not overwritten.+ def restore_after_failed_destroy+ return unless may_restore_after_failed_deletion? || may_disable?++ restored = {+ status: "disabled",+ disabled_at: (disabled_at_in_database if pending_deletion?) || Time.current,+ updated_at: Time.current+ }+ return unless Account.where(id: id, status: status_in_database).update_all(restored) == 1++ assign_attributes(restored)+ clear_attribute_changes(restored.keys)+ end+def current_holdingsif (provider_snapshot_date = latest_provider_holdings_snapshot_date)holdingsdiff --git a/test/jobs/destroy_job_test.rb b/test/jobs/destroy_job_test.rbindex 2122ff0cdd..f60212a69d 100644--- a/test/jobs/destroy_job_test.rb+++ b/test/jobs/destroy_job_test.rb@@ -4,7 +4,7 @@ require "ostruct"class DestroyJobTest < ActiveJob::TestCasetest "destroys the model" domodel = mock- model.expects(:destroy).once+ model.expects(:destroy).once.returns(true)DestroyJob.perform_now(model)end@@ -12,7 +12,7 @@ class DestroyJobTest < ActiveJob::TestCasetest "resets scheduled_for_deletion when the destroy fails" domodel = OpenStruct.new(scheduled_for_deletion: true)model.stubs(:destroy).raises(ActiveRecord::RecordNotDestroyed.new("nope"))- model.expects(:update!).with(scheduled_for_deletion: false).once+ model.expects(:update_column).with(:scheduled_for_deletion, false).onceDestroyJob.perform_now(model)end@@ -48,6 +48,256 @@ class DestroyJobTest < ActiveJob::TestCaseendend+ test "a failed account destroy is recorded in the debug log" do+ account = accounts(:depository)+ account.mark_for_deletion!+ account.stubs(:cleanup_transfers).raises(StandardError, "destroy failed")++ assert_difference -> { DebugLogEntry.count }, 1 do+ DestroyJob.perform_now(account)+ end++ entry = DebugLogEntry.recent.first+ assert_equal "background_jobs", entry.category+ assert_equal "error", entry.level+ assert_equal "DestroyJob", entry.source+ assert_equal account, entry.account+ assert_equal account.family, entry.family+ assert_equal "Account", entry.metadata["record_type"]+ assert_equal account.id, entry.metadata["record_id"]+ assert_equal "StandardError", entry.metadata["error_class"]+ assert_equal "destroy failed", entry.metadata["error_message"]+ assert entry.metadata["backtrace"].present?+ end++ test "a failed destroy is also sent to the Rails log and Sentry" do+ item = plaid_items(:one)+ item.stubs(:destroy).raises(StandardError, "destroy failed")+ Rails.logger.expects(:error).with(regexp_matches(/DestroyJob failed for PlaidItem #{item.id}: StandardError: destroy failed/)).once+ Sentry.expects(:capture_exception).with(instance_of(StandardError)).once++ DestroyJob.perform_now(item)+ end++ # QuestradeItem only requires a refresh token while not scheduled for+ # deletion, so a reset that re-ran validations would raise RecordInvalid out+ # of the rescue and leave the job retrying with the flag still set.+ test "resets the flag without re-running validations that depend on it" do+ item = questrade_items(:one)+ item.update_columns(scheduled_for_deletion: true, refresh_token: nil)+ item.stubs(:destroy).raises(StandardError, "destroy failed")++ assert_nothing_raised { DestroyJob.perform_now(item) }++ assert_not item.reload.scheduled_for_deletion?+ end++ test "a failed provider item destroy is recorded in the debug log with its family" do+ item = plaid_items(:one)+ item.update_column(:scheduled_for_deletion, true)+ item.stubs(:destroy).raises(StandardError, "destroy failed")++ assert_difference -> { DebugLogEntry.where(family: item.family, source: "DestroyJob").count }, 1 do+ DestroyJob.perform_now(item)+ end++ entry = DebugLogEntry.recent.first+ assert_nil entry.account+ assert_equal "plaid", entry.provider_key+ assert_equal "PlaidItem", entry.metadata["record_type"]+ assert_equal item.id, entry.metadata["record_id"]+ assert_not item.reload.scheduled_for_deletion?+ end++ test "a failed family destroy is recorded against that family" do+ family = families(:dylan_family)+ family.stubs(:destroy).raises(StandardError, "destroy failed")++ assert_difference -> { DebugLogEntry.where(family: family, source: "DestroyJob").count }, 1 do+ DestroyJob.perform_now(family)+ end+ end++ test "a failed destroy of a record without a family is still recorded" do+ model = OpenStruct.new(scheduled_for_deletion: true)+ model.stubs(:destroy).raises(ActiveRecord::RecordNotDestroyed.new("nope"))+ model.stubs(:update_column)++ assert_difference -> { DebugLogEntry.where(family_id: nil, source: "DestroyJob").count }, 1 do+ DestroyJob.perform_now(model)+ end+ end++ test "a successful destroy writes no debug log entry" do+ account = accounts(:depository)+ account.mark_for_deletion!++ assert_no_difference -> { DebugLogEntry.count } do+ DestroyJob.perform_now(account)+ end+ end++ test "a destroy that a callback aborts is recorded and resets the flag" do+ item = plaid_items(:one)+ item.update_column(:scheduled_for_deletion, true)+ item.stubs(:destroy).returns(false)++ assert_difference -> { DebugLogEntry.where(source: "DestroyJob").count }, 1 do+ DestroyJob.perform_now(item)+ end++ assert_equal "ActiveRecord::RecordNotDestroyed", DebugLogEntry.recent.first.metadata["error_class"]+ assert_not item.reload.scheduled_for_deletion?+ end++ test "a deadlock is retried instead of failing the deletion" do+ item = plaid_items(:one)+ item.update_column(:scheduled_for_deletion, true)+ item.stubs(:destroy).raises(ActiveRecord::Deadlocked, "deadlock detected")++ assert_no_difference -> { DebugLogEntry.count } do+ assert_enqueued_with(job: DestroyJob, args: [ item ]) do+ DestroyJob.perform_now(item)+ end+ end++ assert item.reload.scheduled_for_deletion?+ end++ test "an account whose destroy deadlocks once is deleted on the retry" do+ account = accounts(:depository)+ account.mark_for_deletion!+ Account.any_instance.stubs(:cleanup_transfers).raises(ActiveRecord::Deadlocked, "deadlock detected").then.returns(nil)++ assert_difference "Account.count", -1 do+ perform_enqueued_jobs { DestroyJob.perform_later(account) }+ end+ end++ test "a deadlock that outlasts the retries is recorded and resets the flag" do+ item = plaid_items(:one)+ item.update_column(:scheduled_for_deletion, true)+ PlaidItem.any_instance.stubs(:destroy).raises(ActiveRecord::Deadlocked, "deadlock detected")++ assert_difference -> { DebugLogEntry.where(source: "DestroyJob").count }, 1 do+ perform_enqueued_jobs { DestroyJob.perform_later(item) }+ end++ assert_equal "ActiveRecord::Deadlocked", DebugLogEntry.recent.first.metadata["error_class"]+ assert_not item.reload.scheduled_for_deletion?+ end++ test "an account stays pending_deletion while a deadlock is retried" do+ account = accounts(:depository)+ account.mark_for_deletion!+ account.stubs(:cleanup_transfers).raises(ActiveRecord::Deadlocked, "deadlock detected")++ assert_enqueued_with(job: DestroyJob, args: [ account ]) do+ DestroyJob.perform_now(account)+ end++ assert_equal "pending_deletion", account.reload.status+ end++ test "an account whose deadlock outlasts the retries is recorded and left disabled" do+ account = accounts(:depository)+ account.mark_for_deletion!+ Account.any_instance.stubs(:cleanup_transfers).raises(ActiveRecord::Deadlocked, "deadlock detected")++ assert_difference -> { DebugLogEntry.where(source: "DestroyJob").count }, 1 do+ perform_enqueued_jobs { DestroyJob.perform_later(account) }+ end++ assert_equal "ActiveRecord::Deadlocked", DebugLogEntry.recent.first.metadata["error_class"]+ assert_equal "disabled", account.reload.status+ end++ test "an account whose destroy a callback aborts is recorded with the reason and left disabled" do+ account = accounts(:depository)+ account.mark_for_deletion!+ account.define_singleton_method(:cleanup_transfers) do+ errors.add(:base, "Still in use")+ throw :abort+ end++ DestroyJob.perform_now(account)++ entry = DebugLogEntry.recent.first+ assert_equal "ActiveRecord::RecordNotDestroyed", entry.metadata["error_class"]+ assert_equal [ "Still in use" ], entry.metadata["record_errors"]+ assert_equal "disabled", account.reload.status+ end++ test "an account whose owner left the family is still left disabled after a failed destroy" do+ account = accounts(:depository)+ account.mark_for_deletion!+ account.owner.update_column(:family_id, families(:empty).id)+ account.stubs(:cleanup_transfers).raises(StandardError, "destroy failed")++ assert_difference "DebugLogEntry.count", 1 do+ DestroyJob.perform_now(account)+ end++ assert_equal "disabled", account.reload.status+ assert_equal "StandardError", DebugLogEntry.order(:created_at).last.metadata["error_class"]+ end++ test "an error after the account delete committed is recorded as itself" do+ account = accounts(:depository)+ account.mark_for_deletion!+ account.stubs(:move_account_statements_to_inbox).raises(StandardError, "inbox move failed")++ assert_difference -> { DebugLogEntry.where(source: "DestroyJob").count }, 1 do+ DestroyJob.perform_now(account)+ end++ entry = DebugLogEntry.recent.first+ assert_equal "StandardError", entry.metadata["error_class"]+ assert_equal account.family, entry.family+ assert_nil entry.account_id+ assert_not Account.exists?(account.id)+ end++ test "a reset that the database rejects is recorded and does not raise out of the job" do+ item = plaid_items(:one)+ item.update_column(:scheduled_for_deletion, true)+ item.stubs(:destroy).raises(StandardError, "destroy failed")+ item.stubs(:update_column).raises(ActiveRecord::RecordNotUnique, "duplicate key")++ assert_difference -> { DebugLogEntry.where(source: "DestroyJob").count }, 2 do+ assert_nothing_raised { DestroyJob.perform_now(item) }+ end++ assert_equal %w[StandardError ActiveRecord::RecordNotUnique].sort,+ DebugLogEntry.where(source: "DestroyJob").map { |entry| entry.metadata["error_class"] }.sort+ end++ test "the flag is reset even when recording the failure raises" do+ item = plaid_items(:one)+ item.update_column(:scheduled_for_deletion, true)+ item.stubs(:destroy).raises(StandardError, "destroy failed")+ DebugLogEntry.stubs(:capture).raises(StandardError, "log write failed")++ assert_raises(StandardError) { DestroyJob.perform_now(item) }++ assert_not item.reload.scheduled_for_deletion?+ end++ test "a deadlock after the account delete committed is recorded instead of retried" do+ account = accounts(:depository)+ account.mark_for_deletion!+ account.stubs(:move_account_statements_to_inbox).raises(ActiveRecord::Deadlocked, "deadlock detected")++ assert_no_enqueued_jobs(only: DestroyJob) do+ assert_difference -> { DebugLogEntry.where(source: "DestroyJob").count }, 1 do+ DestroyJob.perform_now(account)+ end+ end++ assert_equal "ActiveRecord::Deadlocked", DebugLogEntry.recent.first.metadata["error_class"]+ assert_not Account.exists?(account.id)+ end+test "inherits the deferred-enqueue policy from ApplicationJob" doaccount = accounts(:depository)enqueued_mid_transaction = nildiff --git a/test/models/account_test.rb b/test/models/account_test.rbindex 4b8ffeaf3b..70d75f17be 100644--- a/test/models/account_test.rb+++ b/test/models/account_test.rb@@ -48,6 +48,16 @@ class AccountTest < ActiveSupport::TestCaseassert_equal "disabled", @account.reload.statusend+ test "the failed-destroy restore leaves a status written since the record was loaded" do+ @account.mark_for_deletion!+ Account.where(id: @account.id).update_all(status: "active")++ @account.restore_after_failed_destroy++ assert @account.pending_deletion?+ assert_equal "active", @account.reload.status+ end+test "disable from active is unchanged" doassert @account.active?