The personal finance app for everyone (by everyone)
Ruby
Make a category change end the AI's and Bayes' claim on it (#4814)
Yong Cong Sin080c3581fa83
diff --git a/app/models/concerns/enrichable.rb b/app/models/concerns/enrichable.rbindex 00fbe6da61..da7aa07045 100644--- a/app/models/concerns/enrichable.rb+++ b/app/models/concerns/enrichable.rb@@ -173,14 +173,25 @@ module Enrichableremoved_count = 0ActiveRecord::Base.transaction do+ # The record first, then its enrichments, in the order a save followed by+ # log_enrichment (or a category change ending a claim) locks them, so the+ # two cannot deadlock. It also reads the values as they stand under lock.+ # A record deleted since it was loaded took its enrichments with it.+ begin+ lock!+ rescue ActiveRecord::RecordNotFound+ return 0+ end+ai_enrichments = data_enrichments.where(source: "ai")# Only unlock attributes where current value still matches what AI set- # If user changed the value, they took ownership - don't unlock+ # If user changed the value, they took ownership - don't unlock, even+ # once they change it back (the change marked the record superseded)attrs_to_unlock = ai_enrichments.select do |enrichment|attr_name = enrichment.attribute_namecurrent_value = respond_to?(attr_name) ? send(attr_name) : self[attr_name]- current_value.to_s == enrichment.value.to_s+ current_value.to_s == enrichment.value.to_s && enrichment.metadata&.dig("superseded") != trueend.map(&:attribute_name).uniq# Batch unlock in a single updatediff --git a/app/models/family/auto_categorizer.rb b/app/models/family/auto_categorizer.rbindex 4bd67e0cc7..73d321e173 100644--- a/app/models/family/auto_categorizer.rb+++ b/app/models/family/auto_categorizer.rb@@ -267,12 +267,7 @@ class Family::AutoCategorizerenddef cached_transaction_ids- protected_transactions- .joins(:data_enrichments)- .where(data_enrichments: { attribute_name: "category_id", source: "ai" })- .where(Arel.sql("data_enrichments.value = to_jsonb(transactions.category_id::text)"))- .distinct- .pluck(:id)+ protected_transactions.where(Transaction.category_from_sql("ai")).pluck(:id)enddef protected_transaction_idsdiff --git a/app/models/transaction.rb b/app/models/transaction.rbindex c0ceb7d522..c0a8db18bf 100644--- a/app/models/transaction.rb+++ b/app/models/transaction.rb@@ -28,6 +28,7 @@ class Transaction < ApplicationRecordaccepts_nested_attributes_for :taggings, allow_destroy: trueafter_save :clear_merchant_unlinked_association, if: :merchant_id_previously_changed?+ after_save :supersede_automatic_category_claims, if: :saved_change_to_category_id?# Accessors for exchange_rate stored in extra jsonb fielddef exchange_rate@@ -122,6 +123,10 @@ class Transaction < ApplicationRecord# DataEnrichment sources that represent automatic category assignmentAUTO_CATEGORY_SOURCES = %w[ai bayes].freeze+ # Excludes enrichments (aliased de) whose value a later change superseded;+ # see #supersede_automatic_category_claims.+ UNSUPERSEDED_ENRICHMENT_SQL = "de.metadata->>'superseded' IS DISTINCT FROM 'true'".freeze+# Stored flag values that do not mark a transaction pending: the strings# ActiveModel::Type::Boolean casts to false, plus "" (which it casts to nil).# Any other present value is pending, as #pending? decides.@@ -229,8 +234,9 @@ class Transaction < ApplicationRecord# Transactions whose attribute (category_id, merchant_id; internal callers# only) is still the value an automatic source set: that source's- # enrichment holds the current value. since: only enrichments written- # after it; metadata: only those whose metadata contains it.+ # enrichment holds the current value and no change has superseded it since.+ # since: only enrichments written after it; metadata: only those whose+ # metadata contains it.def self.enriched_from_sql(attribute, *sources, since: nil, metadata: nil)sql = +<<~SQL.squishEXISTS (@@ -240,12 +246,23 @@ class Transaction < ApplicationRecordAND de.attribute_name = :attributeAND de.source IN (:sources)AND de.value = to_jsonb(transactions.#{attribute}::text)+ AND #{UNSUPERSEDED_ENRICHMENT_SQL}SQLsql << " AND de.updated_at > :since" if sincesql << " AND de.metadata @> CAST(:metadata AS jsonb)" if metadatasanitize_sql_array([ "#{sql})", { attribute: attribute, sources: sources.flatten.map(&:to_s), since: since, metadata: metadata&.to_json } ])end+ # Marks the AI's and Bayes' category enrichments of the given transactions+ # superseded: their category changed, so it is no longer the value they+ # recorded as theirs, even where it later equals it again. Callers hold the+ # transactions' row locks, so the enrichments are locked after them, as a+ # save followed by Enrichable#log_enrichment locks them.+ def self.supersede_automatic_category_claims!(transaction_ids)+ DataEnrichment.where(enrichable_type: name, enrichable_id: transaction_ids, attribute_name: "category_id", source: AUTO_CATEGORY_SOURCES)+ .update_all(Arel.sql(%(metadata = COALESCE(metadata, '{}'::jsonb) || '{"superseded": true}'::jsonb)))+ end+# Family-scoped query for Enrichable#clear_ai_cachedef self.family_scope(family)joins(entry: :account).where(accounts: { family_id: family.id })@@ -279,6 +296,9 @@ class Transaction < ApplicationRecord# entry being touched. Locks are taken transactions-first, matching a# normal save; sliced to bound the entries UPDATE on large merges.updated_ids.each_slice(REASSIGN_TOUCH_BATCH_SIZE) do |batch|+ # The UPDATE skips the after_save that ends the automatic+ # categorizers' claims, so end them here for the rows reassigned.+ supersede_automatic_category_claims!(batch)Entry.where(entryable_type: "Transaction", entryable_id: batch).touch_allend@@ -708,4 +728,14 @@ class Transaction < ApplicationRecordFamilyMerchantAssociation.where(family: family, merchant: merchant).delete_allend++ # The AI's or Bayes' category counts as theirs while it is still the value+ # they recorded, which a category changed away and back again would+ # satisfy too. Any change marks their records superseded; the records stay+ # as history (the "AI history" filter). A change the source makes itself+ # rewrites its record's metadata right after the save+ # (Enrichable#log_enrichment), so only someone else's change ends a claim.+ def supersede_automatic_category_claims+ self.class.supersede_automatic_category_claims!([ id ])+ endenddiff --git a/app/models/transaction/search.rb b/app/models/transaction/search.rbindex a6db0e74b5..e8f690dc27 100644--- a/app/models/transaction/search.rb+++ b/app/models/transaction/search.rb@@ -145,6 +145,8 @@ class Transaction::Searchend# Automatic-categorization provenance filter values (used by the view)AI_STATUSES = %w[current history].freeze+ # An automatic category enrichment that is still the transaction's category.+ CURRENT_AUTO_CATEGORY_SQL = "de.value = to_jsonb(transactions.category_id::text) AND #{Transaction::UNSUPERSEDED_ENRICHMENT_SQL}".freezeATTACHMENT_STATUSES = %w[with without].freeze@@ -317,11 +319,11 @@ class Transaction::Searchcase wanted.sortwhen [ "current" ]- query.where(auto_enrichment_exists_sql("de.value = to_jsonb(transactions.category_id::text)"), sources: Transaction::AUTO_CATEGORY_SOURCES)+ query.where(auto_enrichment_exists_sql(CURRENT_AUTO_CATEGORY_SQL), sources: Transaction::AUTO_CATEGORY_SOURCES)when [ "history" ]query.where(auto_enrichment_exists_sql, sources: Transaction::AUTO_CATEGORY_SOURCES)- .where.not(auto_enrichment_exists_sql("de.value = to_jsonb(transactions.category_id::text)"), sources: Transaction::AUTO_CATEGORY_SOURCES)+ .where.not(auto_enrichment_exists_sql(CURRENT_AUTO_CATEGORY_SQL), sources: Transaction::AUTO_CATEGORY_SOURCES)elsequery.where(auto_enrichment_exists_sql, sources: Transaction::AUTO_CATEGORY_SOURCES)enddiff --git a/test/models/transaction_test.rb b/test/models/transaction_test.rbindex dcf2345c1b..bd25cc9d93 100644--- a/test/models/transaction_test.rb+++ b/test/models/transaction_test.rb@@ -571,6 +571,111 @@ class TransactionTest < ActiveSupport::TestCaseassert_empty scope.category_from("ai", metadata: { confidence: 0.5 }).pluck(:id)end++ test "a category changed away from the AI's and back again is no longer the AI's" do+ transaction = transactions(:one)+ transaction.enrich_attribute(:category_id, categories(:income).id, source: "ai")+ assert Transaction.where(id: transaction.id).category_from("ai").exists?, "precondition: the AI's category"++ transaction.update!(category: categories(:food_and_drink))+ transaction.update!(category: categories(:income))++ assert_not Transaction.where(id: transaction.id).category_from("ai").exists?+ end++ test "an automatic categorizer's own change keeps its claim" do+ transaction = transactions(:one)+ transaction.enrich_attribute(:category_id, categories(:income).id, source: "ai")+ transaction.enrich_attribute(:category_id, categories(:food_and_drink).id, source: "bayes", metadata: { locked_by_bayes: true })++ assert Transaction.where(id: transaction.id).category_from("bayes", metadata: { locked_by_bayes: true }).exists?+ end++ test "an automatic categorizer setting its category again reclaims it" do+ transaction = transactions(:one)+ transaction.enrich_attribute(:category_id, categories(:income).id, source: "ai")+ transaction.update!(category: categories(:food_and_drink))+ transaction.enrich_attribute(:category_id, categories(:income).id, source: "ai")++ assert Transaction.where(id: transaction.id).category_from("ai").exists?+ end++ test "a category changed away from the AI's and back again stays in the AI history" do+ transaction = transactions(:one)+ transaction.enrich_attribute(:category_id, categories(:income).id, source: "ai")+ transaction.update!(category: categories(:food_and_drink))+ transaction.update!(category: categories(:income))+ family = transaction.entry.account.family++ assert_includes Transaction::Search.new(family, filters: { ai_status: [ "history" ] }).transactions_scope.ids, transaction.id+ assert_not_includes Transaction::Search.new(family, filters: { ai_status: [ "current" ] }).transactions_scope.ids, transaction.id+ end++ test "clearing the AI cache keeps a lock on a category the user changed away from and back" do+ transaction = transactions(:one)+ transaction.enrich_attribute(:category_id, categories(:income).id, source: "ai")+ transaction.lock_attr!(:category_id)+ transaction.update!(category: categories(:food_and_drink))+ transaction.update!(category: categories(:income))++ transaction.reload.clear_ai_cache++ assert transaction.reload.locked?(:category_id)+ end++ test "a category merge ends a claim the AI recorded on the category merged into" do+ transaction = transactions(:one)+ transaction.enrich_attribute(:category_id, categories(:income).id, source: "ai")+ # A claim recorded before category changes ended claims: the category moved on without it.+ transaction.update_column(:category_id, categories(:food_and_drink).id)++ Transaction.reassign_category!(Transaction.where(id: transaction.id), categories(:income).id)++ assert_equal categories(:income), transaction.reload.category+ assert_not Transaction.where(id: transaction.id).category_from("ai").exists?+ end++ test "clearing the AI cache locks the transaction before its enrichments" do+ transaction = transactions(:one)+ transaction.enrich_attribute(:category_id, categories(:income).id, source: "ai")+ transaction.update!(category: categories(:food_and_drink))+ statements = []+ subscriber = ActiveSupport::Notifications.subscribe("sql.active_record") { |*, payload| statements << payload[:sql] }++ begin+ transaction.reload.clear_ai_cache+ ensure+ ActiveSupport::Notifications.unsubscribe(subscriber)+ end+ lock_at = statements.index { |sql| sql.match?(/FROM "transactions".*FOR UPDATE/m) }+ delete_at = statements.index { |sql| sql.match?(/DELETE FROM "data_enrichments"/) }+ assert lock_at, "locks the transaction"+ assert delete_at, "deletes the AI's enrichments"+ assert_operator lock_at, :<, delete_at+ end++ test "clearing the AI cache of a transaction deleted since it was loaded clears nothing" do+ transaction = transactions(:one)+ transaction.enrich_attribute(:category_id, categories(:income).id, source: "ai")+ stale = Transaction.find(transaction.id)+ Transaction.where(id: transaction.id).delete_all++ assert_equal 0, stale.clear_ai_cache+ end++ test "clearing Bayes' locks keeps a lock on a category the user changed away from and back" do+ transaction = transactions(:one)+ transaction.enrich_attribute(:category_id, categories(:income).id, source: "bayes", metadata: { locked_by_bayes: true })+ transaction.lock_attr!(:category_id)++ transaction.update!(category: categories(:food_and_drink))+ transaction.update!(category: categories(:income))+ transaction.lock_attr!(:category_id)+ transaction.entry.account.family.clear_bayes_locks!++ assert transaction.reload.locked?(:category_id)+ end+private# Whether each SQL form of "is this transaction pending?" says it is.def sql_pending_answers(transaction)