The personal finance app for everyone (by everyone)
Ruby
feat(jobs): reap imports and exports stuck by lost background jobs (#2681)
Guillem Arias Fauste9d4b4bc27c32
diff --git a/app/jobs/family_data_export_job.rb b/app/jobs/family_data_export_job.rbindex 1b62bd66c0..78bb1cff3f 100644--- a/app/jobs/family_data_export_job.rb+++ b/app/jobs/family_data_export_job.rb@@ -2,6 +2,12 @@ class FamilyDataExportJob < ApplicationJobqueue_as :defaultdef perform(family_export)+ # Terminal statuses own the record: a redelivered job must not restart a+ # completed export, and one the reaper already failed stays failed.+ # A processing export is allowed through — graceful worker shutdowns+ # re-enqueue in-flight jobs, and that redelivery is what completes it.+ return if family_export.completed? || family_export.failed?+family_export.update!(status: :processing)exporter = Family::DataExporter.new(family_export.family)diff --git a/app/jobs/sync_cleaner_job.rb b/app/jobs/sync_cleaner_job.rbindex f5e425516e..ea9799a95f 100644--- a/app/jobs/sync_cleaner_job.rb+++ b/app/jobs/sync_cleaner_job.rb@@ -1,7 +1,67 @@class SyncCleanerJob < ApplicationJobqueue_as :scheduled+ # Provider account rows flip activities_fetch_pending while a fetch-job chain+ # runs; the chain's state lives only in job args, so a lost link strands the+ # flag (and its "fetching" UI badge) forever.+ ACTIVITY_FLAG_STUCK_AFTER = 6.hours+ ACTIVITY_FLAG_MODELS = %w[SnaptradeAccount QuestradeAccount IndexaCapitalAccount].freeze++ # Sweeps records whose background job died without finalizing them. A hard+ # worker kill (OOM, SIGKILL during deploy) loses in-flight Sidekiq jobs+ # permanently, leaving records wedged in non-terminal statuses. Each sweep is+ # isolated so one failing model doesn't block the others.def perform- Sync.clean+ sweep("syncs") { Sync.clean }+ sweep("imports") { Import.clean }+ sweep("import_sessions") { ImportSession.clean }+ sweep("family_exports") { FamilyExport.clean }+ sweep("pdf_imports") { PdfImport.clean }+ sweep("provider_activity_flags") { clear_stuck_activity_fetch_flags }end++ private+ def sweep(label)+ yield+ rescue => e+ Rails.logger.error("SyncCleanerJob sweep #{label} failed: #{e.class}: #{e.message}")+ Sentry.capture_exception(e) do |scope|+ scope.set_tags(sweep: label)+ end+ end++ def clear_stuck_activity_fetch_flags+ ACTIVITY_FLAG_MODELS.each do |model_name|+ model = model_name.constantize+ scope = model.where(activities_fetch_pending: true)+ .where("updated_at < ?", ACTIVITY_FLAG_STUCK_AFTER.ago)+ scope = scope.includes(:account) if model.reflect_on_association(:account)+ scope.find_each do |record|+ # Read before the lock — see Import.reap_stuck!.+ account = record.respond_to?(:account) ? record.account : nil++ # Row-lock + re-check so a fetch chain finishing right now isn't+ # clobbered mid-write (same guard as the reapers, see #2680).+ record.with_lock do+ next unless record.activities_fetch_pending? && record.updated_at < ACTIVITY_FLAG_STUCK_AFTER.ago++ record.update!(activities_fetch_pending: false)++ DebugLogEntry.capture(+ category: "background_jobs",+ level: "warn",+ message: "Cleared #{model_name} activities_fetch_pending flag stuck for over #{ACTIVITY_FLAG_STUCK_AFTER.inspect}",+ source: self.class.name,+ account: account,+ metadata: { record_type: model_name, record_id: record.id }+ )+ end+ rescue => e+ # One bad record must not abort the sweep for the rest of this+ # model or the models still to come.+ Rails.logger.error("SyncCleanerJob activity-flag sweep failed for #{model_name} #{record.id}: #{e.class}: #{e.message}")+ Sentry.capture_exception(e) { |scope| scope.set_tags(record_type: model_name, record_id: record.id) } if defined?(Sentry)+ end+ end+ endenddiff --git a/app/models/category_import.rb b/app/models/category_import.rbindex 1bf4564bb4..0ca853df74 100644--- a/app/models/category_import.rb+++ b/app/models/category_import.rb@@ -28,6 +28,12 @@ class CategoryImport < Importendend+ # Categories hang off the family, not the import — see+ # Import#committed_by_named_records?.+ def data_committed?+ committed_by_named_records?(family.categories)+ end+def column_keys%i[name category_color category_parent category_icon]enddiff --git a/app/models/family_export.rb b/app/models/family_export.rbindex 0ac61aeefd..b3af1cf929 100644--- a/app/models/family_export.rb+++ b/app/models/family_export.rb@@ -1,4 +1,9 @@class FamilyExport < ApplicationRecord+ # See Import::STUCK_AFTER — same dead-worker failure mode. Exports build in+ # minutes, so a shorter window; a wedged pending/processing export otherwise+ # spins in the UI forever (the exports index polls while any is in flight).+ STUCK_AFTER = 2.hours+belongs_to :familyhas_one_attached :export_file, dependent: :purge_later@@ -34,6 +39,38 @@ class FamilyExport < ApplicationRecordtrueend+ def self.clean+ where(status: [ :pending, :processing ])+ .where("updated_at < ?", STUCK_AFTER.ago)+ .includes(:family)+ .find_each do |export|+ # Read before the lock — see Import.reap_stuck!.+ family = export.family++ # Row-lock + staleness re-check before mutating, as Sync#perform+ # does since #2680 — the export job may have finished in between.+ export.with_lock do+ next unless %w[pending processing].include?(export.status) && export.updated_at < STUCK_AFTER.ago++ previous_status = export.status+ export.update!(status: :failed)++ DebugLogEntry.capture(+ category: "background_jobs",+ level: "warn",+ message: "Reaped FamilyExport stuck in #{previous_status} for over #{STUCK_AFTER.inspect}",+ source: name,+ family: family,+ metadata: { record_type: name, record_id: export.id, previous_status: previous_status, new_status: "failed" }+ )+ end+ rescue => e+ # One bad record must not abort the sweep for the rest.+ Rails.logger.error("FamilyExport.clean failed for #{export.id}: #{e.class}: #{e.message}")+ Sentry.capture_exception(e) { |scope| scope.set_tags(record_type: name, record_id: export.id) } if defined?(Sentry)+ end+ end+def filename"sure_export_#{created_at.strftime('%Y%m%d_%H%M%S')}.zip"enddiff --git a/app/models/import.rb b/app/models/import.rbindex 17e10dbaa0..6d92a01e8b 100644--- a/app/models/import.rb+++ b/app/models/import.rb@@ -9,6 +9,10 @@ class Import < ApplicationRecord# hour of silence dwarfs any legitimate run.PRESUMED_LOST_AFTER = 1.hour+ # The automated counterpart to the manual escape hatch above: SyncCleanerJob+ # reaps records stuck past this longer window (see Import.clean).+ STUCK_AFTER = 6.hours+# User-facing (shown as the import's error in the UI), so resolved through# i18n at call time rather than frozen at boot.def self.lost_error_message@@ -18,6 +22,15 @@ class Import < ApplicationRecord)end+ # User-facing (shown as the import's error in the UI). Resolved at reap+ # time; the sweep runs from cron so this snapshots the default locale.+ def self.interrupted_error_message+ I18n.t(+ "imports.errors.interrupted",+ default: "The background worker was interrupted before this finished. Imported data was rolled back — you can safely try again."+ )+ end+# Shared CSV upload/content limit for web and API imports, including preflight.MAX_CSV_SIZE = 10.megabytesMAX_PDF_SIZE = 25.megabytes@@ -98,6 +111,71 @@ class Import < ApplicationRecordhas_many :entries, dependent: :destroyclass << self+ # Reaps imports whose job died mid-flight. import! runs in a single DB+ # transaction, so which side of its commit the worker died on is+ # observable: no rows attached → the data rolled back, failing the record+ # re-enables the "Try again" path; rows attached → the job died between+ # the commit and the status write, so the truthful terminal state is+ # complete (re-enabling retry there would double-import types without row+ # dedup, e.g. TradeImport). Reverts that died the same way go to+ # revert_failed so the revert can be retried. PdfImports are excluded+ # (their statuses double as processing claims, see PdfImport.clean), and+ # so are session-owned chunks — ImportSession.clean reconciles those+ # within the session flow.+ def clean+ where(status: [ :importing, :reverting ])+ .where.not(type: "PdfImport")+ .where(import_session_id: nil)+ .where("updated_at < ?", STUCK_AFTER.ago)+ .includes(:family)+ .find_each do |import|+ reap_stuck!(import)+ rescue => e+ # One bad record must not abort the sweep for every other stuck+ # import this hour.+ Rails.logger.error("Import.clean failed for #{import.type} #{import.id}: #{e.class}: #{e.message}")+ Sentry.capture_exception(e) { |scope| scope.set_tags(record_type: import.type, record_id: import.id) } if defined?(Sentry)+ end+ end++ def reap_stuck!(import)+ needs_sync = false+ # Read before the lock: with_lock reloads the row and drops the+ # association cache, which would turn the sweep's preload into an N+1.+ family = import.family++ # Same guard Sync#perform gained in #2680: between the sweep query+ # and this row the owning job may have finished (or another sweep+ # won), so re-check staleness under a row lock before mutating.+ import.with_lock do+ next unless import.reapable_since?(STUCK_AFTER.ago)++ previous_status = import.status+ if previous_status == "reverting"+ import.update!(status: :revert_failed, error: interrupted_error_message)+ elsif import.data_committed?+ import.update!(status: :complete, error: nil)+ needs_sync = true+ else+ import.update!(status: :failed, error: interrupted_error_message)+ end++ DebugLogEntry.capture(+ category: "background_jobs",+ level: "warn",+ message: "Reaped #{import.type} stuck in #{previous_status} for over #{STUCK_AFTER.inspect} (→ #{import.status})",+ source: name,+ family: family,+ metadata: { record_type: import.type, record_id: import.id, previous_status: previous_status, new_status: import.status }+ )+ end++ # Outside the row-lock transaction: Rails doesn't defer enqueues to+ # after-commit by default, so enqueuing inside the lock could hand+ # Sidekiq a job before the status write is visible.+ family.sync_later if needs_sync+ end+def parse_csv_str(csv_str, col_sep: ",")CSV.parse((csv_str || "").strip,@@ -163,7 +241,38 @@ class Import < ApplicationRecordImportJob.perform_later(self)end+ # Whether import! already committed rows for this import. Distinguishes a+ # job that died mid-import (single transaction → rolled back, nothing+ # attached) from one that died after the data landed but before the status+ # write. Covers entry-producing imports and account-producing ones+ # (AccountImport creates accounts, not entries).+ def data_committed?+ entries.exists? || accounts.exists?+ end++ # Reaper guard: still wedged in a job-owned status and untouched since the+ # sweep's cutoff. Called under the record's row lock (fresh read).+ def reapable_since?(cutoff)+ %w[importing reverting].include?(status) && updated_at < cutoff+ end+def publish+ # A redelivered or stray ImportJob must not re-import data that already+ # committed (types without row dedup would double-apply), and must not+ # race a revert that owns the record. A failed import is deliberately NOT+ # blocked: its transaction rolled back, so a re-run is a safe retry.+ if complete? || reverting? || revert_failed?+ DebugLogEntry.capture(+ category: "background_jobs",+ level: "warn",+ message: "Import publish skipped: job redelivered while record was #{status}",+ source: self.class.name,+ family: family,+ metadata: { record_type: type, record_id: id, status: status }+ )+ return+ end+raise MaxRowCountExceededError if row_count_exceeded?import!@@ -422,6 +531,20 @@ class Import < ApplicationRecordendprivate+ # Commit signal for import types whose records hang off the family rather+ # than the import itself (Category/Merchant/Rule imports create no entries+ # or accounts, so the base data_committed? can't see them). import! runs as+ # a single find-or-create-by-name transaction, so once every named row has+ # a matching family record the data committed — or every name already+ # existed, leaving the family in the same end state. Either way the+ # truthful terminal status is complete, not a retryable failed. Rows with+ # blank names carry no stable key, so a file with only blank names yields+ # no signal and stays retryable (the conservative side of the reaper).+ def committed_by_named_records?(scope)+ names = rows.pluck(:name).filter_map { |value| value.to_s.strip.presence }.uniq+ names.any? && (names - scope.where(name: names).pluck(:name)).empty?+ end+def row_count_exceeded?rows_count > max_row_countenddiff --git a/app/models/import_session.rb b/app/models/import_session.rbindex 8ce8c1fd9f..c6b6677817 100644--- a/app/models/import_session.rb+++ b/app/models/import_session.rb@@ -29,6 +29,77 @@ class ImportSession < ApplicationRecordallow_nil: truevalidate :payloads_are_json_objects+ # See Import::STUCK_AFTER — same dead-worker failure mode, same sweep.+ # A session wedged in importing is otherwise unrecoverable: publish_later+ # refuses to re-publish while importing. Before failing it, chunks whose+ # import! committed but never got their complete-status write are+ # reconciled — otherwise the re-publish would run those chunks again+ # (process_chunk! only skips complete ones) and double-import their rows.+ # Failing the session then re-enables re-publish, which resumes safely at+ # the first genuinely incomplete chunk.+ def self.clean+ where(status: :importing)+ .where("updated_at < ?", Import::STUCK_AFTER.ago)+ .includes(:family)+ .find_each do |session|+ # Read before the lock — see Import.reap_stuck!.+ family = session.family++ # Row-lock + staleness re-check before mutating, as Sync#perform+ # does since #2680 — the owning job may have finished in between.+ session.with_lock do+ next unless session.importing? && session.updated_at < Import::STUCK_AFTER.ago++ session.reconcile_committed_chunks!+ session.update!(+ status: :failed,+ error_details: {+ "code" => "import_interrupted",+ "message" => Import.interrupted_error_message+ }+ )++ DebugLogEntry.capture(+ category: "background_jobs",+ level: "warn",+ message: "Reaped ImportSession stuck in importing for over #{Import::STUCK_AFTER.inspect}",+ source: name,+ family: family,+ metadata: { record_type: name, record_id: session.id, previous_status: "importing", new_status: "failed" }+ )+ end+ rescue => e+ # One bad record must not abort the sweep for the rest.+ Rails.logger.error("ImportSession.clean failed for #{session.id}: #{e.class}: #{e.message}")+ Sentry.capture_exception(e) { |scope| scope.set_tags(record_type: name, record_id: session.id) } if defined?(Sentry)+ end+ end++ # Chunks caught by a worker kill between import!'s commit and the+ # complete-status write have their rows attached but still read importing.+ # Mark them complete so a re-publish skips them instead of importing the+ # same rows twice (SureImport's split path would duplicate child entries).+ # The chunk's summary was lost with the job; aggregate_chunk_summaries+ # tolerates the empty hash.+ def reconcile_committed_chunks!+ # Plain each: the association carries a default order (find_each would+ # log a scoped-order warning) and sessions cap out at a handful of chunks.+ imports.where(status: :importing).each do |chunk|+ next unless chunk.data_committed?++ chunk.update!(status: :complete, error: nil, error_details: {})++ DebugLogEntry.capture(+ category: "background_jobs",+ level: "warn",+ message: "Reconciled ImportSession chunk whose data committed before the worker died",+ source: self.class.name,+ family: family,+ metadata: { record_type: chunk.type, record_id: chunk.id, import_session_id: id }+ )+ end+ end+def self.create_or_find_for!(family:, import_type:, client_session_id:, expected_chunks:)import_type = import_type.presence || "SureImport"expected_chunks = normalize_positive_integer(expected_chunks)diff --git a/app/models/merchant_import.rb b/app/models/merchant_import.rbindex 58eb681de8..6696a60677 100644--- a/app/models/merchant_import.rb+++ b/app/models/merchant_import.rb@@ -15,6 +15,12 @@ class MerchantImport < Importendend+ # Merchants hang off the family, not the import — see+ # Import#committed_by_named_records?.+ def data_committed?+ committed_by_named_records?(family.merchants)+ end+def column_keys%i[name merchant_color merchant_website]enddiff --git a/app/models/pdf_import.rb b/app/models/pdf_import.rbindex ce2413216f..120c74c8e2 100644--- a/app/models/pdf_import.rb+++ b/app/models/pdf_import.rb@@ -5,6 +5,61 @@ class PdfImport < Importvalidate :account_statement_matches_importclass << self+ # PdfImport's importing status doubles as a processing claim: the AI+ # extraction claim from process_with_ai_later (no rows yet) or a regular+ # publish (rows being written). A lost job leaves the claim held forever —+ # ProcessPdfJob's own reclaim only runs when the job is redelivered.+ # Which claim died is observable from the data: no rows attached → the AI+ # claim, reclaim to pending so the user can re-trigger; rows attached →+ # the publish died after import!'s commit, so finalize as complete+ # (pending would let the user publish the same extracted rows again —+ # PdfImport#import! always builds new transactions). Stuck reverts go to+ # revert_failed like every other import, keeping the retry path exposed.+ def clean+ where(status: [ :importing, :reverting ])+ .where("updated_at < ?", Import::STUCK_AFTER.ago)+ .includes(:family)+ .find_each do |pdf_import|+ reap_stuck!(pdf_import)+ rescue => e+ # One bad record must not abort the sweep for the rest.+ Rails.logger.error("PdfImport.clean failed for #{pdf_import.id}: #{e.class}: #{e.message}")+ Sentry.capture_exception(e) { |scope| scope.set_tags(record_type: name, record_id: pdf_import.id) } if defined?(Sentry)+ end+ end++ def reap_stuck!(pdf_import)+ needs_sync = false+ # Read before the lock — see Import.reap_stuck!.+ family = pdf_import.family++ pdf_import.with_lock do+ next unless pdf_import.reapable_since?(Import::STUCK_AFTER.ago)++ previous_status = pdf_import.status+ if previous_status == "reverting"+ pdf_import.update!(status: :revert_failed, error: Import.interrupted_error_message)+ elsif pdf_import.data_committed?+ pdf_import.update!(status: :complete, error: nil)+ needs_sync = true+ else+ pdf_import.update!(status: :pending)+ end++ DebugLogEntry.capture(+ category: "background_jobs",+ level: "warn",+ message: "Reclaimed PdfImport stuck in #{previous_status} for over #{Import::STUCK_AFTER.inspect} (→ #{pdf_import.status})",+ source: name,+ family: family,+ metadata: { record_type: name, record_id: pdf_import.id, previous_status: previous_status, new_status: pdf_import.status }+ )+ end++ # Outside the row lock — see Import.reap_stuck!.+ family.sync_later if needs_sync+ end+def create_from_upload!(family:, file:, user:)statement = AccountStatement.create_from_prepared_upload!(family: family,diff --git a/app/models/rule_import.rb b/app/models/rule_import.rbindex 31cf4025af..dd946fb660 100644--- a/app/models/rule_import.rb+++ b/app/models/rule_import.rb@@ -7,6 +7,13 @@ class RuleImport < Importendend+ # Rules hang off the family, not the import — see+ # Import#committed_by_named_records?. Nameless rows build unconditionally and+ # carry no stable key, so a file of only nameless rows has no commit signal.+ def data_committed?+ committed_by_named_records?(family.rules)+ end+def column_keys%i[name resource_type active effective_date conditions actions]enddiff --git a/config/locales/views/imports/en.yml b/config/locales/views/imports/en.ymlindex d5e5ce852c..2a90caf487 100644--- a/config/locales/views/imports/en.yml+++ b/config/locales/views/imports/en.yml@@ -434,6 +434,7 @@ en:back_to_imports: Back to importserrors:custom_column_requires_inflow: "Custom column imports require an inflow column to be selected"+ interrupted: "The background worker was interrupted before this finished. Imported data was rolled back — you can safely try again."presumed_lost: "Marked as failed after the background job was presumed lost. The imported data was rolled back — you can safely try again."document_types:bank_statement: Bank Statementdiff --git a/config/schedule.yml b/config/schedule.ymlindex 720966f040..eecea69858 100644--- a/config/schedule.yml+++ b/config/schedule.yml@@ -11,7 +11,7 @@ clean_syncs:cron: "0 * * * *" # every hourclass: "SyncCleanerJob"queue: "scheduled"- description: "Cleans up stale syncs"+ description: "Cleans up stale syncs and reaps imports, exports, and provider fetch flags stuck by lost jobs"run_security_health_checks:cron: "0 2 * * 1-5" # 2:00 AM EST / 3:00 AM EDT (NY time) Monday through Fridaydiff --git a/db/schema.rb b/db/schema.rbindex d2e0872dc8..863db26c59 100644--- a/db/schema.rb+++ b/db/schema.rb@@ -576,9 +576,6 @@ ActiveRecord::Schema[7.2].define(version: 2026_07_19_000002) dot.jsonb "raw_transactions_payload"t.datetime "created_at", null: falset.datetime "updated_at", null: false- t.string "product"- t.decimal "credit_limit", precision: 19, scale: 4- t.jsonb "identification_hashes", default: []t.boolean "treat_balance_as_available_credit", default: false, null: falset.index ["account_id"], name: "index_enable_banking_accounts_on_account_id"t.index ["enable_banking_item_id"], name: "index_enable_banking_accounts_on_enable_banking_item_id"diff --git a/test/jobs/family_data_export_job_test.rb b/test/jobs/family_data_export_job_test.rbindex 6aae26e813..79ed56f09a 100644--- a/test/jobs/family_data_export_job_test.rb+++ b/test/jobs/family_data_export_job_test.rb@@ -18,6 +18,18 @@ class FamilyDataExportJobTest < ActiveJob::TestCaseassert @export.export_file.attached?end+ test "does not restart an export in a terminal status" do+ @export.update_columns(status: "failed")++ Family::DataExporter.any_instance.expects(:generate_export).never++ perform_enqueued_jobs do+ FamilyDataExportJob.perform_later(@export)+ end++ assert_equal "failed", @export.reload.status+ end+test "marks export as failed on error" do# Mock the exporter to raise an errorFamily::DataExporter.any_instance.stubs(:generate_export).raises(StandardError, "Export failed")diff --git a/test/jobs/sync_cleaner_job_test.rb b/test/jobs/sync_cleaner_job_test.rbnew file mode 100644index 0000000000..898ed0b355--- /dev/null+++ b/test/jobs/sync_cleaner_job_test.rb@@ -0,0 +1,96 @@+require "test_helper"++class SyncCleanerJobTest < ActiveSupport::TestCase+ test "reaps records stuck by lost jobs and spares fresh ones" do+ stuck_import = imports(:transaction)+ stuck_import.update_columns(status: "importing", updated_at: 7.hours.ago)++ stuck_revert = imports(:trade)+ stuck_revert.update_columns(status: "reverting", updated_at: 7.hours.ago)++ stuck_pdf = imports(:pdf)+ stuck_pdf.update_columns(status: "importing", updated_at: 7.hours.ago)++ stuck_export = FamilyExport.create!(family: families(:dylan_family))+ stuck_export.update_columns(status: "processing", updated_at: 3.hours.ago)++ stuck_session = families(:dylan_family).import_sessions.create!(status: :importing)+ stuck_session.update_columns(updated_at: 7.hours.ago)++ fresh_import = imports(:account)+ fresh_import.update_columns(status: "importing", updated_at: 1.hour.ago)++ fresh_export = FamilyExport.create!(family: families(:dylan_family))+ fresh_export.update_columns(status: "processing", updated_at: 30.minutes.ago)++ SyncCleanerJob.perform_now++ assert_equal "failed", stuck_import.reload.status+ assert_equal Import.interrupted_error_message, stuck_import.error++ assert_equal "revert_failed", stuck_revert.reload.status++ # PdfImport's importing status is a processing claim — reclaimed, not failed+ assert_equal "pending", stuck_pdf.reload.status++ assert_equal "failed", stuck_export.reload.status+ assert_equal "failed", stuck_session.reload.status+ assert_equal "import_interrupted", stuck_session.error_details["code"]++ assert_equal "importing", fresh_import.reload.status+ assert_equal "processing", fresh_export.reload.status+ end++ test "clears provider activity fetch flags stuck by lost job chains" do+ stuck = snaptrade_accounts(:fidelity_401k)+ stuck.update_columns(activities_fetch_pending: true, updated_at: 7.hours.ago)++ SyncCleanerJob.perform_now++ assert_not stuck.reload.activities_fetch_pending+ end++ test "a failing sweep does not block the others" do+ Sync.expects(:clean).raises(StandardError.new("boom"))++ stuck_export = FamilyExport.create!(family: families(:dylan_family))+ stuck_export.update_columns(status: "processing", updated_at: 3.hours.ago)++ assert_nothing_raised do+ SyncCleanerJob.perform_now+ end++ assert_equal "failed", stuck_export.reload.status+ end++ test "reaped records are captured as debug log entries" do+ stuck_import = imports(:transaction)+ stuck_import.update_columns(status: "importing", updated_at: 7.hours.ago)++ assert_difference "DebugLogEntry.count", 1 do+ SyncCleanerJob.perform_now+ end++ entry = DebugLogEntry.order(:created_at).last+ assert_equal "background_jobs", entry.category+ assert_equal stuck_import.family, entry.family+ assert_equal stuck_import.id, entry.metadata["record_id"]+ end++ test "activity-flag sweep isolates a failing model so later models still run" do+ snaptrade = snaptrade_accounts(:fidelity_401k)+ snaptrade.update_columns(activities_fetch_pending: true, updated_at: 7.hours.ago)++ questrade = questrade_accounts(:one)+ questrade.update_columns(activities_fetch_pending: true, updated_at: 7.hours.ago)++ # SnaptradeAccount is swept before QuestradeAccount; a failing update! on a+ # Snaptrade record must not skip the models that follow it.+ SnaptradeAccount.any_instance.stubs(:update!).raises(ActiveRecord::RecordInvalid.new(SnaptradeAccount.new))++ assert_nothing_raised { SyncCleanerJob.perform_now }++ assert snaptrade.reload.activities_fetch_pending # rolled back, still stuck+ assert_not questrade.reload.activities_fetch_pending # still cleared+ end+enddiff --git a/test/models/family_export_test.rb b/test/models/family_export_test.rbindex bad6fd2b5d..19faec3f23 100644--- a/test/models/family_export_test.rb+++ b/test/models/family_export_test.rb@@ -142,4 +142,15 @@ class FamilyExportTest < ActiveSupport::TestCaseassert_equal new_export.id, ordered_exports.first.idassert_equal old_export.id, ordered_exports.last.idend++ test "clean isolates a record whose update! fails so the sweep does not abort" do+ @export.update_columns(status: "processing", updated_at: 3.hours.ago)++ # A validation/DB error on one stuck record must not abort the sweep for+ # the rest (mirrors Import.clean's per-record rescue).+ FamilyExport.any_instance.stubs(:update!).raises(ActiveRecord::RecordInvalid.new(FamilyExport.new))++ assert_nothing_raised { FamilyExport.clean }+ assert_equal "processing", @export.reload.status+ endenddiff --git a/test/models/import_session_test.rb b/test/models/import_session_test.rbindex d1b80df4b0..2707a1aaf1 100644--- a/test/models/import_session_test.rb+++ b/test/models/import_session_test.rb@@ -725,6 +725,46 @@ class ImportSessionTest < ActiveSupport::TestCaseassert_includes mapping.errors[:target], "must belong to your family"end+ test "clean reconciles committed chunks before failing a stuck session" do+ session = @family.import_sessions.create!(status: "importing")+ session.update_columns(updated_at: 7.hours.ago)++ checksum = Digest::SHA256.hexdigest("chunk")+ committed_chunk = TransactionImport.create!(family: @family, import_session: session, sequence: 1, checksum: checksum, status: "importing")+ entries(:transaction).update_columns(import_id: committed_chunk.id)+ rolled_back_chunk = TransactionImport.create!(family: @family, import_session: session, sequence: 2, checksum: checksum, status: "importing")++ ImportSession.clean++ session.reload+ assert_equal "failed", session.status+ assert_equal "import_interrupted", session.error_details["code"]+ # The chunk whose import! committed must be skipped by a re-publish...+ assert_equal "complete", committed_chunk.reload.status+ # ...while the one that rolled back stays re-runnable.+ assert_equal "importing", rolled_back_chunk.reload.status+ end++ test "clean leaves fresh importing sessions alone" do+ session = @family.import_sessions.create!(status: "importing")++ ImportSession.clean++ assert_equal "importing", session.reload.status+ end++ test "clean isolates a session whose update! fails so the sweep does not abort" do+ session = @family.import_sessions.create!(status: "importing")+ session.update_columns(updated_at: 7.hours.ago)++ # A validation/DB error on one stuck session must not abort the sweep for+ # the rest (mirrors Import.clean's per-record rescue).+ ImportSession.any_instance.stubs(:update!).raises(ActiveRecord::RecordInvalid.new(ImportSession.new))++ assert_nothing_raised { ImportSession.clean }+ assert_equal "importing", session.reload.status+ end+privatedef entity_records[diff --git a/test/models/import_test.rb b/test/models/import_test.rbindex c7736cf57c..8c58201851 100644--- a/test/models/import_test.rb+++ b/test/models/import_test.rb@@ -1,6 +1,102 @@require "test_helper"class ImportTest < ActiveSupport::TestCase+ test "publish skips imports in terminal statuses" do+ import = imports(:transaction)+ import.update_columns(status: "complete")++ import.expects(:import!).never++ import.publish++ assert_equal "complete", import.reload.status+ end++ test "publish skips imports that are reverting" do+ import = imports(:transaction)+ import.update_columns(status: "reverting")++ import.expects(:import!).never++ import.publish++ assert_equal "reverting", import.reload.status+ end++ test "clean fails stuck imports but leaves PdfImports to their own reclaim" do+ stuck_csv = imports(:transaction)+ stuck_csv.update_columns(status: "importing", updated_at: 7.hours.ago)++ stuck_pdf = imports(:pdf)+ stuck_pdf.update_columns(status: "importing", updated_at: 7.hours.ago)++ Import.clean++ assert_equal "failed", stuck_csv.reload.status+ assert_equal "importing", stuck_pdf.reload.status+ end++ test "clean leaves session-owned chunks to ImportSession.clean" do+ family = families(:dylan_family)+ session = family.import_sessions.create!(status: "importing")+ chunk = TransactionImport.create!(+ family: family,+ import_session: session,+ sequence: 1,+ checksum: Digest::SHA256.hexdigest("chunk"),+ status: "importing"+ )+ chunk.update_columns(updated_at: 7.hours.ago)++ Import.clean++ assert_equal "importing", chunk.reload.status+ end++ test "clean completes a stuck import whose data already committed" do+ stuck = imports(:transaction)+ stuck.update_columns(status: "importing", updated_at: 7.hours.ago)+ entries(:transaction).update_columns(import_id: stuck.id)++ Import.clean++ stuck.reload+ assert_equal "complete", stuck.status+ assert_nil stuck.error+ end++ test "clean moves a stuck revert to revert_failed" do+ stuck = imports(:transaction)+ stuck.update_columns(status: "reverting", updated_at: 7.hours.ago)++ Import.clean++ assert_equal "revert_failed", stuck.reload.status+ end++ test "PdfImport clean reclaims the AI claim but completes a committed publish" do+ ai_claim = imports(:pdf)+ ai_claim.update_columns(status: "importing", updated_at: 7.hours.ago)++ published = imports(:pdf_processed)+ published.update_columns(status: "importing", updated_at: 7.hours.ago)+ entries(:transaction).update_columns(import_id: published.id)++ PdfImport.clean++ assert_equal "pending", ai_claim.reload.status+ assert_equal "complete", published.reload.status+ end++ test "PdfImport clean moves a stuck revert to revert_failed" do+ stuck = imports(:pdf)+ stuck.update_columns(status: "reverting", updated_at: 7.hours.ago)++ PdfImport.clean++ assert_equal "revert_failed", stuck.reload.status+ end+test "force_fail! refuses records that have not been idle long enough" doimport = imports(:transaction)import.update_columns(status: "importing", updated_at: 5.minutes.ago)@@ -39,4 +135,68 @@ class ImportTest < ActiveSupport::TestCaseassert pdf.force_fail!assert_equal "pending", pdf.reload.statusend++ # Category/Merchant/Rule imports attach nothing to the import (their records+ # hang off the family), so reap_stuck! leans on the type-specific+ # data_committed? override to tell a committed run from a rolled-back one.+ test "clean completes a stuck CategoryImport whose categories committed" do+ family = families(:dylan_family)+ stuck = CategoryImport.create!(family: family, status: "importing")+ stuck.rows.create!(source_row_number: 1, name: categories(:income).name, currency: "USD")+ stuck.update_columns(updated_at: 7.hours.ago)++ Import.clean++ stuck.reload+ assert_equal "complete", stuck.status+ assert_nil stuck.error+ end++ test "clean fails a stuck CategoryImport whose categories never committed" do+ family = families(:dylan_family)+ stuck = CategoryImport.create!(family: family, status: "importing")+ stuck.rows.create!(source_row_number: 1, name: "Never Committed Category", currency: "USD")+ stuck.update_columns(updated_at: 7.hours.ago)++ Import.clean++ assert_equal "failed", stuck.reload.status+ end++ test "clean completes a stuck MerchantImport whose merchants committed" do+ family = families(:dylan_family)+ stuck = MerchantImport.create!(family: family, status: "importing")+ stuck.rows.create!(source_row_number: 1, name: merchants(:netflix).name, currency: "USD")+ stuck.update_columns(updated_at: 7.hours.ago)++ Import.clean++ assert_equal "complete", stuck.reload.status+ end++ test "clean completes a stuck RuleImport whose named rules committed" do+ family = families(:dylan_family)+ # Skip Rule's own validations — the reaper only asks whether a rule with+ # this name exists in the family, which is the state a committed import+ # leaves behind.+ family.rules.new(resource_type: "transaction", name: "Committed rule").save!(validate: false)+ stuck = RuleImport.create!(family: family, status: "importing")+ stuck.rows.create!(source_row_number: 1, name: "Committed rule", resource_type: "transaction", conditions: "[]", actions: "[]", currency: "USD")+ stuck.update_columns(updated_at: 7.hours.ago)++ Import.clean++ assert_equal "complete", stuck.reload.status+ end++ test "clean fails a stuck RuleImport of only nameless rows (no commit signal)" do+ family = families(:dylan_family)+ stuck = RuleImport.create!(family: family, status: "importing")+ stuck.rows.create!(source_row_number: 1, name: "", resource_type: "transaction", conditions: "[]", actions: "[]", currency: "USD")+ stuck.update_columns(updated_at: 7.hours.ago)++ Import.clean++ assert_equal "failed", stuck.reload.status+ endend