Files
sure/app/models/family_export.rb
Guillem Arias Fauste 9d4b4bc27c feat(jobs): reap imports and exports stuck by lost background jobs (#2681)
* feat(jobs): reap imports and exports stuck by lost background jobs

A hard-killed worker (OOM, SIGKILL during deploy) loses its in-flight
Sidekiq job permanently. Sync is the only model with a stale sweep;
everything else wedges in a non-terminal status forever:

- Import stuck "importing"/"reverting" (e.g. #2274)
- ImportSession stuck "importing" — unrecoverable, publish_later
  refuses to re-publish while importing
- FamilyExport stuck "pending"/"processing" — exports index polls
  every 3s indefinitely
- PdfImport's AI-processing claim held forever (ProcessPdfJob's
  reclaim only runs if the job is redelivered)
- Provider activities_fetch_pending flags stranded when a
  self-rescheduling fetch chain loses a link

SyncCleanerJob (existing hourly cron) now sweeps all of them, each
isolated so one failure doesn't block the rest, and records every
reaped record as a DebugLogEntry with the family attached.

Idempotency guards so a stray or redelivered job cannot corrupt a
record the reaper (or a user retry) has since moved on:

- Import#publish skips complete/reverting/revert_failed imports —
  a redelivered ImportJob after completion double-applies data for
  import types without row dedup. Failed imports deliberately stay
  publishable: their transaction rolled back, so a re-run is a retry.
- FamilyDataExportJob refuses terminal exports but still allows
  processing ones through, since graceful-shutdown redelivery is what
  completes them.

Reaper thresholds (6h imports, 2h exports) key off updated_at and
dwarf legitimate runtimes, so live jobs are not swept in practice.

* fix(jobs): make the reapers race-safe and commit-aware

Review feedback on #2681 (jjmata, Codex, CodeRabbit):

- Every sweep now mutates under record.with_lock with a staleness
  re-check, mirroring the guard Sync#perform gained in #2680 — a job
  finishing between the sweep query and the write can no longer be
  clobbered mid-flight
- Import.clean distinguishes which side of import!'s single transaction
  the worker died on: rows attached means the data committed and only
  the status write was lost, so the record is finalized as complete
  (marking it failed invited a re-publish that double-imports types
  without row dedup, e.g. TradeImport); no rows means a clean rollback
  and the failed/try-again path stays
- PdfImport.clean applies the same split: no rows → the AI-extraction
  claim died, reclaim to pending; rows → the publish died post-commit,
  finalize complete instead of letting the same extracted rows be
  published twice. Stuck PdfImport reverts (previously unswept by
  either clean) now go to revert_failed like every other import
- ImportSession.clean reconciles chunks whose import! committed but
  never got the complete-status write before failing the session, so
  re-publish skips them instead of duplicating their rows via
  SureImport's split path
- Import#publish redelivery skip is captured via DebugLogEntry instead
  of Rails.logger so support can see it in /settings/debug
- The interrupted-error copy is i18n-backed (imports.errors.interrupted)

* fix(jobs): round-2 review feedback on the reapers

- Import.clean excludes session-owned chunks (import_session_id: nil) —
  SyncCleanerJob runs it before ImportSession.clean, so it could
  finalize or fail a SureImport chunk outside the session flow that
  owns its lifecycle. Regression test added (CodeRabbit major)
- family.sync_later moved outside the row-lock transaction in both
  reap paths — Rails doesn't defer enqueues to after-commit by default,
  so Sidekiq could pick the job up before the status write was visible
- Per-record rescue in Import.clean / PdfImport.clean so one bad record
  doesn't abort the rest of the hourly sweep
- ImportSession.clean uses the importing? enum predicate;
  reconcile_committed_chunks! iterates with each (default-ordered
  association made find_each warn, and chunk counts are tiny)

* fix(jobs): address round-3 reaper review (isolation + commit signal)

Per-record rescue isolation for the three sweeps that lacked it —
FamilyExport.clean, ImportSession.clean, and SyncCleanerJob's
activity-flag loop — mirroring Import.clean/PdfImport.clean. One bad
record (validation error, DB blip) no longer aborts the rest of that
sweep for the hour; the activity-flag guard is per-record so a failure
also stops skipping the models that follow.

data_committed? now covers Category/Rule/Merchant imports, whose
records hang off the family rather than the import (no entries or
accounts), via the new Import#committed_by_named_records? helper. A
committed one is reaped to complete instead of a retryable failed;
nameless RuleImport rows carry no stable key, so a nameless-only file
has no commit signal and stays retryable.

* fix(schema): drop duplicate enable_banking_accounts columns from merge

The merge of main into this branch re-appended product, credit_limit,
and identification_hashes after updated_at, so schema.rb declared each
twice and db:schema:load raised "you can't define an already defined
column 'product'". Removed the duplicate declarations (kept the new
treat_balance_as_available_credit column); the test database loads
again.
2026-07-25 05:04:30 +02:00

82 lines
2.7 KiB
Ruby

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 :family
has_one_attached :export_file, dependent: :purge_later
enum :status, {
pending: "pending",
processing: "processing",
completed: "completed",
failed: "failed"
}, default: :pending, validate: true
scope :ordered, -> { order(created_at: :desc) }
# See Import::PRESUMED_LOST_AFTER — same dead-worker failure mode. Exports
# build in minutes; a pending/processing export idle for an hour is lost.
PRESUMED_LOST_AFTER = 1.hour
def presumed_lost?
(pending? || processing?) && updated_at < PRESUMED_LOST_AFTER.ago
end
# Escape hatch for exports whose background job died mid-flight; the
# with_lock re-check means a job finishing between render and click wins.
# Export generation is in-memory, so nothing is left behind — the user
# simply creates a new export.
def force_fail!
with_lock do
return false unless presumed_lost?
update!(status: :failed)
end
true
end
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"
end
def downloadable?
completed? && export_file.attached?
end
end