The personal finance app for everyone (by everyone)
Ruby
Add comprehensive debug logging to AI cache reset job (#3046)
Juan José Matada483746e255
diff --git a/app/controllers/rules_controller.rb b/app/controllers/rules_controller.rbindex ae9e1ee1f0..c81fb2a4e2 100644--- a/app/controllers/rules_controller.rb+++ b/app/controllers/rules_controller.rb@@ -129,11 +129,56 @@ class RulesController < ApplicationControllerenddef clear_ai_cache- ClearAiCacheJob.perform_later(Current.family)+ enqueue_ai_cache_resetredirect_to rules_path, notice: t("rules.clear_ai_cache.success")endprivate+ # The reset itself happens in a background job, so an enqueue that never+ # lands looks exactly like a job that ran and found nothing. Logging the+ # request separately from the job's own "started" entry tells those apart.+ def enqueue_ai_cache_reset+ perform_ai_cache_reset_later++ DebugLogEntry.capture(+ category: ClearAiCacheJob::DEBUG_CATEGORY,+ level: "info",+ message: "AI cache reset requested from the rules page",+ source: self.class.name,+ family: Current.family,+ user: Current.user+ )+ end++ # Split out so the rescue below covers only the enqueue it reports on.+ # Anything that runs after the job is safely queued — the request log above,+ # the redirect — is then structurally incapable of being recorded as an+ # enqueue failure and retried, without that resting on the internals of+ # whatever those later steps happen to call.+ def perform_ai_cache_reset_later+ attempted_job = nil+ enqueued = ClearAiCacheJob.perform_later(Current.family) { |job| attempted_job = job }++ # perform_later turns an ActiveJob::EnqueueError — or an enqueue aborted by+ # a callback — into a false return rather than raising it, so the return+ # value is the only signal that the reset never reached the queue. The+ # yielded job carries the underlying error when there was one.+ return if enqueued++ raise attempted_job&.enqueue_error || ActiveJob::EnqueueError.new("ClearAiCacheJob was not enqueued")+ rescue => e+ DebugLogEntry.capture(+ category: ClearAiCacheJob::DEBUG_CATEGORY,+ level: "error",+ message: "AI cache reset could not be enqueued: #{e.class}: #{e.message}",+ source: self.class.name,+ family: Current.family,+ user: Current.user,+ metadata: { error_class: e.class.name, error_message: e.message }+ )+ raise+ end+def set_rule@rule = Current.family.rules.find(params[:id])enddiff --git a/app/jobs/clear_ai_cache_job.rb b/app/jobs/clear_ai_cache_job.rbindex 478acba648..48a5afc8f4 100644--- a/app/jobs/clear_ai_cache_job.rb+++ b/app/jobs/clear_ai_cache_job.rb@@ -1,28 +1,108 @@class ClearAiCacheJob < ApplicationJobqueue_as :low_priority+ # The reset runs in the background with no UI of its own, so /settings/debug is+ # the only place an operator can see whether it ran. Its own category keeps a+ # single run filterable there.+ DEBUG_CATEGORY = "ai_cache_reset"++ # Both models carry AI-sourced enrichments: categories and merchants land on+ # Transaction, entry-level attributes on Entry. Keyed by the label used in the+ # debug log so the entries read the way an operator thinks about them.+ CLEARABLE_MODELS = { "transactions" => "Transaction", "entries" => "Entry" }.freeze++ # A family-wide problem would otherwise write one debug entry per record. The+ # full tally still lands in the completion entry's metadata.+ MAX_LOGGED_RECORD_ERRORS = 5+def perform(family)if family.nil?- Rails.logger.warn("ClearAiCacheJob called with nil family, skipping")+ capture("warn", "AI cache reset skipped: job received no family")returnend- Rails.logger.info("Clearing AI cache for family #{family.id}")+ capture("info", "AI cache reset started", family: family)- # Clear AI enrichment data for transactions- begin- count = Transaction.clear_ai_cache(family)- Rails.logger.info("Cleared AI cache for #{count} transactions")- rescue => e- Rails.logger.error("Failed to clear AI cache for transactions: #{e.message}")- end+ removed = {}+ failures = {}+ skipped = {}- # Clear AI enrichment data for entries- begin- count = Entry.clear_ai_cache(family)- Rails.logger.info("Cleared AI cache for #{count} entries")+ CLEARABLE_MODELS.each do |label, model_name|+ removed[label], scope_skipped = clear_scope(family, label, model_name.constantize)+ skipped[label] = scope_skipped if scope_skipped.positive?rescue => e- Rails.logger.error("Failed to clear AI cache for entries: #{e.message}")+ removed[label] = 0+ failures[label] = "#{e.class}: #{e.message}"+ capture(+ "error",+ "AI cache reset failed while clearing #{label}: #{e.class}: #{e.message}",+ family: family,+ metadata: { scope: label, error_class: e.class.name, error_message: e.message }+ )end++ capture(+ "info",+ completion_message(removed, failures, skipped),+ family: family,+ metadata: {+ entries_removed: removed.values.sum,+ removed_by_scope: removed,+ failed_scopes: failures,+ skipped_records: skipped+ }+ )end++ private+ # Per-record failures are warned about (up to a cap) and counted rather than+ # raised, so one unclearable transaction can't wipe out the whole family's+ # reset — or the count of what it did clear. Returns [removed, skipped].+ def clear_scope(family, label, model)+ logged_errors = 0+ skipped = 0++ removed = model.clear_ai_cache(family) do |record, error|+ skipped += 1++ next if logged_errors >= MAX_LOGGED_RECORD_ERRORS++ logged_errors += 1+ capture(+ "warn",+ "AI cache reset could not clear #{label.singularize} #{record.id}: #{error.class}: #{error.message}",+ family: family,+ metadata: { scope: label, record_id: record.id, error_class: error.class.name, error_message: error.message }+ )+ end++ [ removed, skipped ]+ end++ def completion_message(removed, failures, skipped)+ total = removed.values.sum+ breakdown = removed.map { |label, count| "#{label}: #{count}" }.join(", ")++ message = failures.any? ? "AI cache reset completed with errors" : "AI cache reset completed"+ message += ": removed #{total} AI cache #{'entry'.pluralize(total)} (#{breakdown})"+ message += ". Failed to clear: #{failures.keys.join(', ')}" if failures.any?++ if skipped.any?+ skipped_total = skipped.values.sum+ message += ". Skipped #{skipped_total} #{'record'.pluralize(skipped_total)} that could not be cleared"+ end++ message+ end++ def capture(level, message, family: nil, metadata: {})+ DebugLogEntry.capture(+ category: DEBUG_CATEGORY,+ level: level,+ message: message,+ source: self.class.name,+ family: family,+ metadata: metadata+ )+ endenddiff --git a/app/models/concerns/enrichable.rb b/app/models/concerns/enrichable.rbindex 8b01698e2e..9a5bf05d29 100644--- a/app/models/concerns/enrichable.rb+++ b/app/models/concerns/enrichable.rb@@ -30,11 +30,21 @@ module Enrichablenoneend- def clear_ai_cache(family)+ # Clears AI-sourced enrichments for every record of this type in the family.+ # Returns the number of cache entries actually removed, not the number of+ # records visited, so callers can report a figure that means something.+ #+ # A single bad record would otherwise abort the sweep and throw away the+ # tally of everything already cleared, so callers may pass a block to handle+ # per-record failures and keep going.+ def clear_ai_cache(family, &on_record_error)count = 0family_scope(family).find_each do |record|- record.clear_ai_cache- count += 1+ count += record.clear_ai_cache+ rescue => e+ raise unless on_record_error++ on_record_error.call(record, e)endcountend@@ -142,7 +152,10 @@ module Enrichableendend+ # Returns the number of AI cache entries removed from this record.def clear_ai_cache+ removed_count = 0+ActiveRecord::Base.transaction doai_enrichments = data_enrichments.where(source: "ai")@@ -161,8 +174,10 @@ module Enrichableend# Delete AI enrichment records- ai_enrichments.delete_all+ removed_count = ai_enrichments.delete_allend++ removed_countendprivatediff --git a/test/controllers/rules_controller_test.rb b/test/controllers/rules_controller_test.rbindex cdbc491342..aaf5c9e00e 100644--- a/test/controllers/rules_controller_test.rb+++ b/test/controllers/rules_controller_test.rb@@ -242,4 +242,57 @@ class RulesControllerTest < ActionDispatch::IntegrationTestassert_redirected_to rules_urlend++ test "clear_ai_cache enqueues job and records the request in the debug log" do+ assert_enqueued_with(job: ClearAiCacheJob, args: [ @user.family ]) do+ post clear_ai_cache_rules_url+ end++ assert_redirected_to rules_url++ entry = DebugLogEntry.where(category: ClearAiCacheJob::DEBUG_CATEGORY, level: "info").sole+ assert_equal "AI cache reset requested from the rules page", entry.message+ assert_equal @user, entry.user+ assert_equal @user.family, entry.family+ end++ test "clear_ai_cache records an error when the job cannot be enqueued" do+ ClearAiCacheJob.expects(:perform_later).with(@user.family).raises(StandardError, "queue is down")++ assert_raises(StandardError) { post clear_ai_cache_rules_url }++ entry = DebugLogEntry.where(category: ClearAiCacheJob::DEBUG_CATEGORY, level: "error").sole+ assert_match "AI cache reset could not be enqueued", entry.message+ assert_equal "StandardError", entry.metadata["error_class"]+ end++ # perform_later swallows ActiveJob::EnqueueError into a false return instead of+ # raising it, which would otherwise log the reset as requested and redirect+ # with a success notice while nothing was queued.+ test "clear_ai_cache records an error when the job is silently not enqueued" do+ ClearAiCacheJob.stubs(:perform_later).with(@user.family).returns(false)++ assert_raises(ActiveJob::EnqueueError) { post clear_ai_cache_rules_url }++ entry = DebugLogEntry.where(category: ClearAiCacheJob::DEBUG_CATEGORY, level: "error").sole+ assert_match "AI cache reset could not be enqueued", entry.message+ assert_equal "ActiveJob::EnqueueError", entry.metadata["error_class"]+ assert_empty DebugLogEntry.where(category: ClearAiCacheJob::DEBUG_CATEGORY, level: "info")+ end++ # When the adapter reports the failure, the yielded job carries the underlying+ # cause — the detail an operator actually needs. The fallback above can only+ # say that nothing was queued.+ test "clear_ai_cache surfaces the queue adapter's error when the job carries one" do+ failed_job = ClearAiCacheJob.new(@user.family)+ failed_job.enqueue_error = ActiveJob::EnqueueError.new("connection refused")+ ClearAiCacheJob.stubs(:perform_later).with(@user.family).yields(failed_job).returns(false)++ error = assert_raises(ActiveJob::EnqueueError) { post clear_ai_cache_rules_url }+ assert_equal "connection refused", error.message++ entry = DebugLogEntry.where(category: ClearAiCacheJob::DEBUG_CATEGORY, level: "error").sole+ assert_match "connection refused", entry.message+ assert_equal "connection refused", entry.metadata["error_message"]+ endenddiff --git a/test/jobs/clear_ai_cache_job_test.rb b/test/jobs/clear_ai_cache_job_test.rbnew file mode 100644index 0000000000..61b0d9586a--- /dev/null+++ b/test/jobs/clear_ai_cache_job_test.rb@@ -0,0 +1,87 @@+require "test_helper"++class ClearAiCacheJobTest < ActiveSupport::TestCase+ setup do+ @family = families(:dylan_family)+ @transaction = transactions(:one)+ @entry = entries(:transaction)+ end++ test "logs start and completion with the number of AI cache entries removed" do+ create_ai_enrichment(@transaction, "category_id")+ create_ai_enrichment(@transaction, "merchant_id")+ create_ai_enrichment(@entry, "name")+ DataEnrichment.create!(enrichable: @transaction, attribute_name: "notes", source: "rule", value: "keep me")++ ClearAiCacheJob.perform_now(@family)++ assert_equal 0, DataEnrichment.where(enrichable: @transaction, source: "ai").count+ assert_equal 1, DataEnrichment.where(enrichable: @transaction, source: "rule").count++ assert_equal @family, start_entry.family++ assert_match "removed 3 AI cache entries", completion_entry.message+ assert_equal 3, completion_entry.metadata["entries_removed"]+ assert_equal({ "transactions" => 2, "entries" => 1 }, completion_entry.metadata["removed_by_scope"])+ assert_equal @family, completion_entry.family+ end++ test "logs an error and still reports the surviving scope when one scope fails" do+ create_ai_enrichment(@entry, "name")+ Transaction.stubs(:clear_ai_cache).raises(ActiveRecord::StatementInvalid, "boom")++ ClearAiCacheJob.perform_now(@family)++ errors = log_entries("error")+ assert_equal 1, errors.size+ assert_match "AI cache reset failed while clearing transactions", errors.first.message+ assert_equal "transactions", errors.first.metadata["scope"]++ assert_match "completed with errors", completion_entry.message+ assert_match "removed 1 AI cache entry", completion_entry.message+ assert_equal({ "transactions" => 0, "entries" => 1 }, completion_entry.metadata["removed_by_scope"])+ end++ test "warns about records it cannot clear instead of losing the whole run" do+ transaction_count = Transaction.family_scope(@family).count+ assert transaction_count.positive?, "fixture setup should leave the family some transactions"++ Transaction.any_instance.stubs(:clear_ai_cache).raises(StandardError, "record is wedged")++ ClearAiCacheJob.perform_now(@family)++ warnings = log_entries("warn")+ assert_equal [ transaction_count, ClearAiCacheJob::MAX_LOGGED_RECORD_ERRORS ].min, warnings.size+ assert_match "AI cache reset could not clear transaction", warnings.first.message++ assert_match "Skipped #{transaction_count} record", completion_entry.message+ assert_equal({ "transactions" => transaction_count }, completion_entry.metadata["skipped_records"])+ assert_equal 0, completion_entry.metadata["entries_removed"]+ end++ test "warns instead of failing silently when no family is given" do+ ClearAiCacheJob.perform_now(nil)++ warnings = log_entries("warn")+ assert_equal 1, warnings.size+ assert_equal "AI cache reset skipped: job received no family", warnings.first.message+ assert_empty log_entries("info")+ end++ private+ def create_ai_enrichment(record, attribute_name)+ DataEnrichment.create!(enrichable: record, attribute_name: attribute_name, source: "ai", value: "ai value")+ end++ def log_entries(level)+ DebugLogEntry.where(category: ClearAiCacheJob::DEBUG_CATEGORY, level: level).order(:created_at).to_a+ end++ def start_entry+ log_entries("info").find { |entry| entry.message.start_with?("AI cache reset started") }+ end++ def completion_entry+ log_entries("info").find { |entry| entry.message.start_with?("AI cache reset completed") }+ end+end