Skip to content

armgit / sure

Public Imported from GitHub
0

The personal finance app for everyone (by everyone)

Ruby

Invalidate entry caches when categories change (#4124)

Arnav Joshia759029f9951
diff --git a/app/models/concerns/enrichable.rb b/app/models/concerns/enrichable.rb
index e409ad41b7..8253c092de 100644
--- a/app/models/concerns/enrichable.rb
+++ b/app/models/concerns/enrichable.rb
@@ -176,9 +176,8 @@ module Enrichable
# Delete AI enrichment records
removed_count = ai_enrichments.delete_all
- # Views and totals filtered on provenance are cached under
- # Family#entries_cache_version, which only moves when an entry's
- # timestamp changes. delete_all skips callbacks, so touch the record
+ # Views and totals filtered on provenance use Family#entries_cache_version.
+ # delete_all changes neither entries nor categories, so touch the record
# like a normal save would; `has_one :entry, touch: true` carries it to
# the entry. This stays inside the transaction so the cache invalidation
# commits or rolls back with the deletion.
diff --git a/app/models/family.rb b/app/models/family.rb
index 41aaddb408..6d37e1bcde 100644
--- a/app/models/family.rb
+++ b/app/models/family.rb
@@ -640,16 +640,20 @@ class Family < ApplicationRecord
# Used for invalidating entry related aggregation queries
def entries_cache_version
- "#{entries.count}-#{entries.maximum(:updated_at)&.to_f || 0}"
+ "#{entries.count}-#{entries.maximum(:updated_at)&.to_f || 0}-#{categories_version}"
end
- # Used for invalidating caches keyed on entries (e.g. the transactions
- # index's uncategorized count). Unlike #entries_cache_version, includes
- # .count so a hard-deleted entry busts the cache even when it didn't hold
- # the current max updated_at, and uses full-precision timestamps so two
- # updates within the same second still produce distinct versions.
+ # Used for caches keyed on entries (e.g. the transactions index's
+ # uncategorized count). Counts capture deletions, and full-precision
+ # timestamps distinguish updates within the same second.
def entries_version
- "#{entries.count}-#{entries.maximum(:updated_at)&.to_f}"
+ "#{entries.count}-#{entries.maximum(:updated_at)&.to_f}-#{categories_version}"
+ end
+
+ # Category deletion can nullify a late assignment without touching its
+ # entry; category metadata also affects cached entry results.
+ def categories_version
+ "#{categories.count}-#{categories.maximum(:updated_at)&.to_f || 0}"
end
# Used for invalidating caches keyed on recurring transactions (e.g. the
diff --git a/app/models/transaction.rb b/app/models/transaction.rb
index 9e4735fa9a..1667320ee0 100644
--- a/app/models/transaction.rb
+++ b/app/models/transaction.rb
@@ -226,8 +226,8 @@ class Transaction < ApplicationRecord
# 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.
+ # Expects a relation without eager loading so reselect(:id) produces
+ # a single-column 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
@@ -239,8 +239,8 @@ class Transaction < ApplicationRecord
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.
+ # Execute the write without read-query memoization and clear cached
+ # reads before selecting the affected entries.
updated_ids = connection.exec_query(sql, "Transaction Reassign Category").rows.flatten
connection.clear_query_cache
diff --git a/test/models/category/cache_invalidation_concurrency_test.rb b/test/models/category/cache_invalidation_concurrency_test.rb
new file mode 100644
index 0000000000..f3f01d0d75
--- /dev/null
+++ b/test/models/category/cache_invalidation_concurrency_test.rb
@@ -0,0 +1,127 @@
+require "test_helper"
+
+# A committed isolated family lets a normal assignment race with category
+# deletion on a second connection without changing shared fixtures.
+class Category::CacheInvalidationConcurrencyTest < ActiveSupport::TestCase
+ self.use_transactional_tests = false
+
+ setup do
+ @family = Family.create!(name: "Late category assignment", currency: "USD")
+ @source = @family.categories.create!(
+ name: "Empty source", color: "#0d9488", lucide_icon: "tag", updated_at: 2.hours.ago
+ )
+ @other = @family.categories.create!(
+ name: "Initial category", color: "#0d9488", lucide_icon: "tag", updated_at: 1.hour.ago
+ )
+ @account = Account.create!(
+ family: @family, name: "Checking", currency: "USD",
+ balance: 0, accountable: Depository.new
+ )
+ @entry = Entry.create!(
+ account: @account, name: "Late source assignment", date: Date.current,
+ amount: 10, currency: "USD", entryable: Transaction.new(category: @other)
+ )
+ @record = @entry.entryable
+ Entry.where(id: @entry.id).update_all(updated_at: 1.day.ago)
+ 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
+
+ test "totals refresh when deletion nullifies an assignment committed after the reassignment callback" do
+ previous_cache = Rails.cache
+ Rails.cache = ActiveSupport::Cache::MemoryStore.new
+ ready = Queue.new
+ resume = Queue.new
+ pool = ActiveRecord::Base.connection_pool
+ assert_operator pool.size, :>=, 2
+ observer = Transaction.connection
+ worker = nil
+ worker_pid = nil
+ original_reassignment = @source.method(:reassign_transactions_to_nothing)
+
+ # Pause this category instance at the boundary between the actual callback
+ # and dependent nullification; the original callback still runs unchanged.
+ @source.define_singleton_method(:reassign_transactions_to_nothing) do
+ count = original_reassignment.call
+ ready << count
+ resume.pop
+ count
+ end
+
+ 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'")
+ worker_pid = connection.select_value("SELECT pg_backend_pid()")
+ @source.destroy!
+ end
+ end
+ end
+ worker.report_on_exception = false
+ assert_equal 0, wait_for_callback(worker, ready)
+
+ @record.update!(category: @source)
+ timestamp_before_delete = @entry.reload.updated_at
+ category_timestamp = @family.categories.maximum(:updated_at)
+ filters = { categories: [ Category::UNCATEGORIZED_FILTER_VALUE ], active_accounts_only: false }
+ before_version = observer.uncached { @family.entries_cache_version }
+ assert_equal 0, observer.uncached { Transaction::Search.new(@family, filters: filters).totals.count }
+
+ resume << true
+ assert worker.join(10), "deletion worker did not finish"
+ worker.value
+
+ observer.uncached do
+ assert_not Category.exists?(@source.id)
+ assert_nil @record.reload.category_id
+ assert_equal timestamp_before_delete, @entry.reload.updated_at
+ assert_equal category_timestamp, @family.categories.maximum(:updated_at)
+ search = Transaction::Search.new(@family, filters: filters)
+ assert_equal 1, search.transactions_scope.count
+ assert_equal 1, search.totals.count
+ assert_not_equal before_version, @family.entries_cache_version
+ end
+ ensure
+ begin
+ finish_worker(worker, observer, worker_pid, resume)
+ ensure
+ Rails.cache = previous_cache
+ end
+ end
+
+ private
+ def wait_for_callback(worker, ready)
+ deadline = Process.clock_gettime(Process::CLOCK_MONOTONIC) + 10
+ loop do
+ return ready.pop unless ready.empty?
+ unless worker.alive?
+ worker.value
+ flunk "deletion worker finished before its reassignment callback"
+ end
+ flunk "deletion worker did not reach its reassignment callback" if Process.clock_gettime(Process::CLOCK_MONOTONIC) >= deadline
+ sleep 0.01
+ end
+ end
+
+ def finish_worker(worker, observer, worker_pid, resume)
+ return unless worker&.alive?
+ resume << true
+ return if worker.join(10)
+
+ observer.uncached { observer.select_value("SELECT pg_cancel_backend(#{Integer(worker_pid)})") } if worker_pid
+ return if worker.join(5)
+
+ worker.kill
+ raise "deletion worker could not be stopped" unless worker.join(5)
+ rescue ActiveRecord::QueryCanceled
+ # Cancellation deliberately interrupts an unfinished SQL statement.
+ end
+end
diff --git a/test/models/family/category_cache_version_test.rb b/test/models/family/category_cache_version_test.rb
new file mode 100644
index 0000000000..acbac3ea2e
--- /dev/null
+++ b/test/models/family/category_cache_version_test.rb
@@ -0,0 +1,73 @@
+require "test_helper"
+
+class Family::CategoryCacheVersionTest < ActiveSupport::TestCase
+ test "entry cache versions change when a category below the maximum timestamp is deleted" do
+ family = families(:dylan_family)
+ older = family.categories.create!(
+ name: "Older cache category", color: "#0d9488", lucide_icon: "tag",
+ updated_at: 2.days.ago
+ )
+ newest = family.categories.create!(
+ name: "Newest cache category", color: "#0d9488", lucide_icon: "tag",
+ updated_at: 1.hour.from_now
+ )
+ family.categories.load
+ before = entry_versions(family)
+ entry_timestamp = family.entries.maximum(:updated_at)
+
+ older.destroy!
+
+ assert_equal newest.reload.updated_at, family.categories.maximum(:updated_at)
+ assert_equal entry_timestamp, family.entries.maximum(:updated_at)
+ assert_versions_changed before, family
+ end
+
+ test "entry cache versions change for category metadata updates within one second" do
+ family = families(:dylan_family)
+ first_time = Time.utc(2030, 1, 1, 12, 0, 0, 123_456)
+ category = travel_to(first_time, with_usec: true) do
+ family.categories.create!(
+ name: "Category metadata cache", color: "#0d9488", lucide_icon: "tag"
+ )
+ end
+ before = entry_versions(family)
+ original_timestamp = category.updated_at
+ entry_timestamp = family.entries.maximum(:updated_at)
+
+ travel_to(first_time + 0.0001, with_usec: true) do
+ category.update!(color: "#4da568")
+ end
+
+ assert_equal original_timestamp.to_i, category.reload.updated_at.to_i
+ assert_equal entry_timestamp, family.entries.maximum(:updated_at)
+ assert_versions_changed before, family
+ end
+
+ test "another family's category changes do not change entry cache versions" do
+ family = families(:dylan_family)
+ unrelated_family = families(:empty)
+ before = entry_versions(family)
+ category = unrelated_family.categories.create!(
+ name: "Unrelated cache category", color: "#0d9488", lucide_icon: "tag"
+ )
+ assert_equal before, entry_versions(family)
+
+ travel 1.second do
+ category.update!(color: "#4da568")
+ end
+ assert_equal before, entry_versions(family)
+
+ category.destroy!
+ assert_equal before, entry_versions(family)
+ end
+
+ private
+ def entry_versions(family)
+ [ family.entries_cache_version, family.entries_version ]
+ end
+
+ def assert_versions_changed(before, family)
+ after = entry_versions(family)
+ before.zip(after).each { |previous, current| assert_not_equal previous, current }
+ end
+end