Address PR review feedback

- Preserve user locks: Only unlock attributes where current value still matches
  what AI set. If user changed the value, they took ownership.
- Add nil guard clause for family parameter in ClearAiCacheJob
- Add partial failure handling so one model's failure doesn't block the other
This commit is contained in:
eureka928
2026-01-26 10:14:06 +01:00
parent ed8185cf2b
commit 029d09685e
2 changed files with 29 additions and 10 deletions

View File

@@ -2,14 +2,27 @@ class ClearAiCacheJob < ApplicationJob
queue_as :low_priority
def perform(family)
if family.nil?
Rails.logger.warn("ClearAiCacheJob called with nil family, skipping")
return
end
Rails.logger.info("Clearing AI cache for family #{family.id}")
# Clear AI enrichment data for transactions
Transaction.clear_ai_cache(family)
Rails.logger.info("Cleared AI cache for transactions")
begin
Transaction.clear_ai_cache(family)
Rails.logger.info("Cleared AI cache for transactions")
rescue => e
Rails.logger.error("Failed to clear AI cache for transactions: #{e.message}")
end
# Clear AI enrichment data for entries
Entry.clear_ai_cache(family)
Rails.logger.info("Cleared AI cache for entries")
begin
Entry.clear_ai_cache(family)
Rails.logger.info("Cleared AI cache for entries")
rescue => e
Rails.logger.error("Failed to clear AI cache for entries: #{e.message}")
end
end
end

View File

@@ -150,17 +150,23 @@ module Enrichable
def clear_ai_cache
ActiveRecord::Base.transaction do
# Find attributes that were locked by AI enrichment
ai_enriched_attrs = data_enrichments.where(source: "ai").pluck(:attribute_name).uniq
ai_enrichments = data_enrichments.where(source: "ai")
# Batch unlock all AI-enriched attributes in a single update
if ai_enriched_attrs.any?
new_locked_attrs = locked_attributes.except(*ai_enriched_attrs)
# Only unlock attributes where current value still matches what AI set
# If user changed the value, they took ownership - don't unlock
attrs_to_unlock = ai_enrichments.select do |enrichment|
current_value = send(enrichment.attribute_name) rescue self[enrichment.attribute_name]
current_value.to_s == enrichment.value.to_s
end.map(&:attribute_name).uniq
# Batch unlock in a single update
if attrs_to_unlock.any?
new_locked_attrs = locked_attributes.except(*attrs_to_unlock)
update_column(:locked_attributes, new_locked_attrs) if new_locked_attrs != locked_attributes
end
# Delete AI enrichment records
data_enrichments.where(source: "ai").delete_all
ai_enrichments.delete_all
end
end