Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

fix(reports): bust report caches when categories are merged or replaced (#3604)

Arnav Joshi275f2f994c35
diff --git a/app/models/category.rb b/app/models/category.rb
index f1c6bdd6a0..ec236b6a2b 100644
--- a/app/models/category.rb
+++ b/app/models/category.rb
@@ -31,6 +31,11 @@ class Category < ApplicationRecord
before_save :inherit_color_from_parent
+ # prepend: runs before dependent: :nullify's own before_destroy, so the
+ # reassignment (which touches entries to bust report caches) still sees the
+ # transactions; nullify then runs as the safety net.
+ before_destroy :reassign_transactions_to_nothing, prepend: true
+
scope :alphabetically, -> { order(:name) }
scope :recently_used, -> { where.not(last_used_at: nil).order(last_used_at: :desc) }
scope :alphabetically_by_hierarchy, -> {
@@ -347,7 +352,7 @@ class Category < ApplicationRecord
def replace_and_destroy!(replacement)
transaction do
- transactions.update_all category_id: replacement&.id
+ Transaction.reassign_category!(transactions, replacement&.id)
destroy!
end
end
@@ -407,6 +412,10 @@ class Category < ApplicationRecord
end
private
+ def reassign_transactions_to_nothing
+ Transaction.reassign_category!(transactions, nil)
+ end
+
def category_level_limit
if (subcategory? && parent&.subcategory?) || (parent? && subcategory?)
errors.add(:parent, "can't have more than 2 levels of subcategories")
diff --git a/app/models/category/merger.rb b/app/models/category/merger.rb
index 13176a14eb..6e238e148d 100644
--- a/app/models/category/merger.rb
+++ b/app/models/category/merger.rb
@@ -28,7 +28,7 @@ class Category::Merger
private
def merge_sources!
source_categories.each do |source|
- family.transactions.where(category_id: source.id).update_all(category_id: target_category.id)
+ Transaction.reassign_category!(family.transactions.where(category_id: source.id), target_category.id)
merge_budget_categories(source)
family.categories.where(parent_id: source.id).where.not(id: target_category.id).update_all(parent_id: target_category.id)
family.categories.find(source.id).destroy!
diff --git a/app/models/family.rb b/app/models/family.rb
index 2638b7191f..41aaddb408 100644
--- a/app/models/family.rb
+++ b/app/models/family.rb
@@ -515,7 +515,7 @@ class Family < ApplicationRecord
if duplicates.any?
duplicate_ids = duplicates.map(&:id)
categories.where(parent_id: duplicate_ids).update_all(parent_id: keeper.id)
- Transaction.where(category_id: duplicate_ids).update_all(category_id: keeper.id)
+ Transaction.reassign_category!(transactions.where(category_id: duplicate_ids), keeper.id)
BudgetCategory.where(category_id: duplicate_ids).update_all(category_id: keeper.id)
categories.where(id: duplicate_ids).delete_all
end
diff --git a/app/models/transaction.rb b/app/models/transaction.rb
index 2284fef6e1..9e4735fa9a 100644
--- a/app/models/transaction.rb
+++ b/app/models/transaction.rb
@@ -114,6 +114,10 @@ class Transaction < ApplicationRecord
# Providers that support pending transaction flags
PENDING_PROVIDERS = %w[simplefin plaid lunchflow enable_banking akahu up monobank mercury redbark financekit].freeze
+ # Slice size for the entry touch in reassign_category! — bounds the UPDATE
+ # statement size when a merge or category destroy hits many transactions.
+ REASSIGN_TOUCH_BATCH_SIZE = 5_000
+
# DataEnrichment sources that represent automatic category assignment
AUTO_CATEGORY_SOURCES = %w[ai bayes].freeze
@@ -219,6 +223,41 @@ class Transaction < ApplicationRecord
joins(entry: :account).where(accounts: { family_id: family.id })
end
+ # Bulk category reassignment that still busts entry-keyed report caches.
+ # update_all skips callbacks, so the `has_one :entry, touch: true` bump that
+ # every normal save relies on (Family#entries_cache_version) never happens.
+ # Expects a plain relation — `to_sql` on a scope carrying `select` or
+ # `includes` would emit the wrong subquery for the IN clause.
+ def self.reassign_category!(scope, category_id)
+ transaction do
+ # Lock inside the scope so a concurrent category edit is rechecked before
+ # its ID reaches the UPDATE, rather than overwriting the new category.
+ sql = <<~SQL
+ UPDATE #{quoted_table_name}
+ SET category_id = #{connection.quote(category_id)}
+ WHERE id IN (#{scope.reselect(:id).lock("FOR UPDATE OF transactions").to_sql})
+ RETURNING id
+ SQL
+
+ # exec_query is the uncached primitive (QueryCache only wraps select_all)
+ # and isn't in dirties_query_cache's list, so clear the cache explicitly.
+ updated_ids = connection.exec_query(sql, "Transaction Reassign Category").rows.flatten
+ connection.clear_query_cache
+
+ next 0 if updated_ids.empty?
+
+ # Touch exactly the rows the UPDATE reassigned (RETURNING), so a
+ # transaction entering the scope mid-merge can't be updated without its
+ # 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|
+ Entry.where(entryable_type: "Transaction", entryable_id: batch).touch_all
+ end
+
+ updated_ids.size
+ end
+ end
+
# Overarching grouping method for all transfer-type transactions
def transfer?
TRANSFER_KINDS.include?(kind)
diff --git a/test/models/category/merger_test.rb b/test/models/category/merger_test.rb
index 46e9803cce..1faa3a8b31 100644
--- a/test/models/category/merger_test.rb
+++ b/test/models/category/merger_test.rb
@@ -49,6 +49,27 @@ class Category::MergerTest < ActiveSupport::TestCase
assert_not Category.exists?(source.id)
end
+ test "merging categories invalidates entries_cache_version" do
+ target = create_category(@family, "Cache Merge Target")
+ source = create_category(@family, "Cache Merge Source")
+ transaction = create_transaction_for(@family, source)
+
+ before = @family.reload.entries_cache_version
+
+ travel 1.second do
+ merger = Category::Merger.new(
+ family: @family,
+ target_category: target,
+ source_categories: [ source ]
+ )
+
+ assert merger.merge!
+ end
+
+ assert_equal target.id, transaction.reload.category_id
+ assert_not_equal before, @family.reload.entries_cache_version
+ end
+
private
def create_category(family, name, parent: nil)
family.categories.create!(
diff --git a/test/models/category_test.rb b/test/models/category_test.rb
index 714b2572e9..7a4bfcf7c0 100644
--- a/test/models/category_test.rb
+++ b/test/models/category_test.rb
@@ -21,6 +21,38 @@ class CategoryTest < ActiveSupport::TestCase
assert_nil transactions.map { |t| t.reload.category }.uniq.first
end
+ test "replacing and destroying invalidates entries_cache_version" do
+ before = @family.entries_cache_version
+
+ travel 1.second do
+ categories(:food_and_drink).replace_and_destroy!(categories(:income))
+ end
+
+ assert_not_equal before, @family.entries_cache_version
+ end
+
+ test "replacing with nil invalidates entries_cache_version" do
+ before = @family.entries_cache_version
+
+ travel 1.second do
+ categories(:food_and_drink).replace_and_destroy!(nil)
+ end
+
+ assert_not_equal before, @family.entries_cache_version
+ end
+
+ test "destroy nullifies transaction categories and bumps entries_cache_version" do
+ transaction = transactions(:one)
+ before = @family.entries_cache_version
+
+ travel 1.second do
+ categories(:food_and_drink).destroy!
+ end
+
+ assert_nil transaction.reload.category_id
+ assert_not_equal before, @family.entries_cache_version
+ end
+
test "destroying parent category preserves subcategory transaction assignments" do
parent = @family.categories.create!(
name: "Parent With Child Transactions",
diff --git a/test/models/family_test.rb b/test/models/family_test.rb
index 06766f047b..ff18f971bb 100644
--- a/test/models/family_test.rb
+++ b/test/models/family_test.rb
@@ -138,9 +138,11 @@ class FamilyTest < ActiveSupport::TestCase
name: "Test 2"
)
+ txn2_entry_updated_at = txn2.entry.updated_at
+
# Should merge both categories into one, keeping the oldest
assert_difference "Category.count", -1 do
- result = family.investment_contributions_category
+ result = travel_to(1.minute.from_now) { family.investment_contributions_category }
assert_equal english_category.id, result.id
assert_equal "Investment Contributions", result.name
@@ -148,11 +150,62 @@ class FamilyTest < ActiveSupport::TestCase
assert_equal english_category.id, txn1.reload.category_id
assert_equal english_category.id, txn2.reload.category_id
+ # Reassignment must touch entries so entry-keyed caches bust
+ # (only txn2 is reassigned — txn1 already points at the keeper)
+ assert txn2.entry.reload.updated_at > txn2_entry_updated_at
+
# French category should be deleted
assert_nil Category.find_by(id: french_category.id)
end
end
+ test "investment_contributions_category merges duplicates across accounts" do
+ family = families(:dylan_family)
+ family.update!(locale: "en")
+ family.categories.where(name: [ "Investment Contributions", "Contributions aux investissements" ]).destroy_all
+
+ english_category = family.categories.create!(
+ name: "Investment Contributions",
+ color: "#0d9488",
+ lucide_icon: "trending-up"
+ )
+
+ french_category = family.categories.create!(
+ name: "Contributions aux investissements",
+ color: "#0d9488",
+ lucide_icon: "trending-up"
+ )
+
+ # Transactions on two different accounts of the same family: the
+ # transactions-through-accounts scope must reach both.
+ txn1 = Transaction.create!(category: english_category)
+ Entry.create!(
+ account: accounts(:depository),
+ entryable: txn1,
+ amount: 100,
+ currency: "USD",
+ date: Date.current,
+ name: "First account txn"
+ )
+
+ txn2 = Transaction.create!(category: french_category)
+ Entry.create!(
+ account: accounts(:credit_card),
+ entryable: txn2,
+ amount: 50,
+ currency: "USD",
+ date: Date.current,
+ name: "Second account txn"
+ )
+
+ result = family.investment_contributions_category
+
+ assert_equal english_category.id, result.id
+ assert_equal english_category.id, txn1.reload.category_id
+ assert_equal english_category.id, txn2.reload.category_id,
+ "transaction on the second account must also be reassigned to the keeper"
+ end
+
test "moniker helpers return expected singular and plural labels" do
family = families(:dylan_family)
diff --git a/test/models/transaction/reassign_category_concurrency_test.rb b/test/models/transaction/reassign_category_concurrency_test.rb
new file mode 100644
index 0000000000..db6548c7fd
--- /dev/null
+++ b/test/models/transaction/reassign_category_concurrency_test.rb
@@ -0,0 +1,145 @@
+require "test_helper"
+
+# Separate connections need committed records so the writer and reassignment
+# can observe each other without changing fixtures shared by other tests.
+class Transaction::ReassignCategoryConcurrencyTest < ActiveSupport::TestCase
+ self.use_transactional_tests = false
+
+ setup do
+ @family = Family.create!(name: "Category reassignment race", currency: "USD")
+ @categories = []
+ %w[Source Concurrent Replacement].each do |name|
+ @categories << Category.create!(
+ family: @family, name: name, color: "#0d9488", lucide_icon: "tag"
+ )
+ end
+ @source, @concurrent, @replacement = @categories
+ @account = Account.create!(
+ family: @family, name: "Checking", currency: "USD",
+ balance: 0, accountable: Depository.new
+ )
+ @entry = Entry.create!(
+ account: @account, name: "Concurrent category edit", date: Date.current,
+ amount: 10, currency: "USD", entryable: Transaction.new(category: @source)
+ )
+ @record = @entry.entryable
+ Entry.where(id: @entry.id).update_all(updated_at: 1.hour.ago)
+ @original_entry_timestamp = @entry.reload.updated_at
+ end
+
+ teardown do
+ Entry.where(id: @entry.id).delete_all if @entry
+ Transaction.where(id: @entry.entryable_id).delete_all if @entry
+ Category.where(family_id: @family.id).delete_all if @family
+ Account.where(id: @account.id).delete_all if @account
+ Depository.where(id: @account.accountable_id).delete_all if @account
+ Family.where(id: @family.id).delete_all if @family
+ end
+
+ %i[category family].each do |scope_type|
+ test "#{scope_type} reassignment preserves a category edit committed while waiting for its row lock" do
+ scope = if scope_type == :category
+ @source.transactions
+ else
+ @family.transactions.where(category_id: @source.id)
+ end
+
+ count = reassign_after_concurrent_edit(scope)
+
+ assert_equal 0, count
+ assert_equal @concurrent.id, @record.reload.category_id
+ assert_equal @original_entry_timestamp, @entry.reload.updated_at
+ end
+ end
+
+ private
+ def reassign_after_concurrent_edit(scope)
+ pool = ActiveRecord::Base.connection_pool
+ assert_operator pool.size, :>=, 3, "race regression needs writer, worker, and observer connections"
+ observer = Transaction.connection
+ writer = pool.checkout
+ worker = nil
+ worker_pid = nil
+
+ writer.transaction do
+ writer.execute("SET LOCAL statement_timeout = '30s'")
+ writer.execute("SET LOCAL lock_timeout = '30s'")
+ writer_pid = writer.select_value("SELECT pg_backend_pid()")
+ # Bypass Entryable's touch callback so only the reassignment can change
+ # the entry timestamp being checked below.
+ writer.execute(<<~SQL)
+ UPDATE transactions
+ SET category_id = #{writer.quote(@concurrent.id)}
+ WHERE id = #{writer.quote(@record.id)}
+ SQL
+
+ backend_pids = Queue.new
+ worker = Thread.new do
+ pool.with_connection do |connection|
+ connection.transaction do
+ connection.execute("SET LOCAL statement_timeout = '30s'")
+ connection.execute("SET LOCAL lock_timeout = '30s'")
+ backend_pids << connection.select_value("SELECT pg_backend_pid()")
+ Transaction.reassign_category!(scope, @replacement.id)
+ end
+ end
+ end
+ worker.report_on_exception = false
+ worker_pid = wait_for_worker_pid(worker, backend_pids)
+ wait_for_writer_lock(observer, worker, worker_pid, writer_pid)
+ end
+
+ assert worker.join(10), "reassignment worker did not finish after the writer committed"
+ worker.value
+ ensure
+ begin
+ # The transaction block has committed or rolled back the writer before
+ # waiting for the worker, including assertion and synchronization failures.
+ finish_worker(worker, observer, worker_pid)
+ ensure
+ pool.checkin(writer) if writer
+ end
+ end
+
+ def wait_for_worker_pid(worker, backend_pids)
+ deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + 10
+ loop do
+ return backend_pids.pop unless backend_pids.empty?
+ unless worker.alive?
+ worker.value # Propagate worker failures instead of reporting a timeout.
+ flunk "reassignment worker finished before reporting its backend PID"
+ end
+ flunk "reassignment worker did not report its backend PID" if Process.clock_gettime(Process::CLOCK_MONOTONIC) >= deadline
+ sleep 0.01
+ end
+ end
+
+ def wait_for_writer_lock(observer, worker, worker_pid, writer_pid)
+ deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + 10
+ loop do
+ blocked = observer.uncached do
+ observer.select_value("SELECT #{Integer(writer_pid)} = ANY(pg_blocking_pids(#{Integer(worker_pid)}))")
+ end
+ return if blocked
+ unless worker.alive?
+ worker.value
+ flunk "reassignment finished before waiting on the concurrent writer"
+ end
+ flunk "reassignment did not wait on the concurrent writer" if Process.clock_gettime(Process::CLOCK_MONOTONIC) >= deadline
+ sleep 0.01
+ end
+ end
+
+ def finish_worker(worker, observer, worker_pid)
+ return unless worker&.alive?
+ return if worker.join(5)
+
+ observer.uncached { observer.select_value("SELECT pg_cancel_backend(#{Integer(worker_pid)})") } if worker_pid
+ return if worker.join(5)
+
+ worker.kill
+ raise "reassignment worker could not be stopped" unless worker.join(5)
+ rescue ActiveRecord::QueryCanceled
+ # Cancellation above deliberately interrupts an unfinished SQL statement.
+ end
+end
diff --git a/test/models/transaction_test.rb b/test/models/transaction_test.rb
index f35c70766a..bf07722836 100644
--- a/test/models/transaction_test.rb
+++ b/test/models/transaction_test.rb
@@ -521,6 +521,26 @@ class TransactionTest < ActiveSupport::TestCase
assert_nil category.reload.last_used_at
end
+ test "reassign_category! updates category, touches entries, and returns the count" do
+ transaction = transactions(:one)
+ entry = entries(:transaction)
+ new_category = categories(:income)
+
+ before = entry.updated_at
+
+ count = travel_to(1.minute.from_now) do
+ Transaction.reassign_category!(Transaction.where(id: transaction.id), new_category.id)
+ end
+
+ assert_equal 1, count
+ assert_equal new_category.id, transaction.reload.category_id
+ assert entry.reload.updated_at > before
+ end
+
+ test "reassign_category! returns 0 for an empty scope" do
+ assert_equal 0, Transaction.reassign_category!(Transaction.none, categories(:income).id)
+ end
+
test "toggle_tag! adds a missing tag and removes a present one" do
transaction = transactions(:one)
transaction.update!(tag_ids: [ tags(:one).id ])