Skip to content

Open-source live-chat, email support, omni-channel desk. An alternative to Intercom, Zendesk, Salesforce Service Cloud etc. 🔥💬

fix: preserve automation labels on unrelated conversation saves (#15807)

Shivam Mishra00960a09d1a1
diff --git a/app/jobs/migration/conversation_batch_cache_label_job.rb b/app/jobs/migration/conversation_batch_cache_label_job.rb
index 511ee56502e..0a36e0cc35a 100644
--- a/app/jobs/migration/conversation_batch_cache_label_job.rb
+++ b/app/jobs/migration/conversation_batch_cache_label_job.rb
@@ -1,14 +1,23 @@
class Migration::ConversationBatchCacheLabelJob < ApplicationJob
queue_as :async_database_migration
- # To cache the label, we simply access it from the object and save it. Anytime the object is
- # saved in the future, ActsAsTaggable will automatically recompute it. This process is done
- # initially when the user has not performed any action.
+ # This job fills cached_label_list for conversations that were labelled before the column existed.
+ #
+ # It used to read label_list and call save!. That worked because acts-as-taggable-on wrote
+ # the label cache on every save once the list had been read.
# Reference: https://github.com/mbleigh/acts-as-taggable-on/wiki/Caching
+ #
+ # Labelable::Persistence now skips that write when the list was only read, because it let
+ # a stale record overwrite labels saved elsewhere. With that guard, read-then-save leaves
+ # the cache empty. So this job builds the cache from the taggings and writes it directly.
+ #
+ # The row lock stops a label edit from committing between the read and the write.
+ # Without it, the job could overwrite a newer cache with the list it read earlier.
def perform(conversation_batch)
conversation_batch.each do |conversation|
- conversation.label_list
- conversation.save!
+ conversation.with_lock do
+ conversation.update!(cached_label_list: conversation.labels.pluck(:name).join("#{ActsAsTaggableOn.delimiter} "))
+ end
end
end
end
diff --git a/app/models/concerns/labelable.rb b/app/models/concerns/labelable.rb
index bf877892157..cdd1b172ac8 100644
--- a/app/models/concerns/labelable.rb
+++ b/app/models/concerns/labelable.rb
@@ -3,6 +3,7 @@ module Labelable
included do
acts_as_taggable_on :labels
+ include Labelable::Persistence
end
def update_labels(labels = nil)
diff --git a/app/models/concerns/labelable/persistence.rb b/app/models/concerns/labelable/persistence.rb
new file mode 100644
index 00000000000..723722b5e19
--- /dev/null
+++ b/app/models/concerns/labelable/persistence.rb
@@ -0,0 +1,96 @@
+module Labelable::Persistence
+ extend ActiveSupport::Concern
+
+ # This concern overrides five acts-as-taggable-on methods through Labelable:
+ #
+ # Conversation / Contact
+ # -> Labelable
+ # -> acts-as-taggable-on: reads and writes labels
+ # -> Persistence: decides whether a loaded list should be written
+ #
+ # The gem writes a label list on save once it has been read, even if the worker
+ # only meant to update another field. Each worker has its own copy of the list:
+ #
+ # Message worker Automation worker
+ # Reads labels: []
+ # Adds "runner" to the database
+ # Saves first-reply time
+ # Gem also writes its old []
+ # -> "runner" disappears
+ #
+ # No label edit was tracked on the message worker's copy, so this deletion can
+ # happen without a removal activity. SLA and priority can remain unchanged.
+ #
+ # We remember the original list and compare it with the list being saved:
+ #
+ # Original [] -> current [] -> skip label and cache writes
+ # Original [] -> current ["runner"] -> let the gem persist the change
+ #
+ # The gem still performs the database writes. This comparison also notices
+ # label_list.add/remove edits, which mutate the list without calling its setter.
+ # It prevents unrelated saves from overwriting labels; it does not coordinate
+ # two workers that both intentionally edit labels.
+ #
+ # Gotcha: this assumes nobody reuses a record instance after one of its saves
+ # rolled back. The remembered list follows the database on a rollback, so an
+ # instance that edits labels again after a rollback can have that edit skipped.
+ # The same applies to a dup, which inherits the source record's remembered list.
+ # No current caller does either. Load a fresh record instead of reusing one.
+ #
+ # TODO: remove this concern once Chatwoot runs Rails 8 and acts-as-taggable-on
+ # ships a release with upstream commit cbd83ad, which does this in the gem.
+ # The author declined to backport it to 13.x, and gem master needs Rails 8.
+ included do
+ after_commit :forget_tag_lists_before_transaction
+ after_rollback :restore_tag_lists_before_transaction
+ end
+
+ def tag_list_cache_on(context)
+ super.tap do |list|
+ @original_tag_lists ||= {}
+ @original_tag_lists[context.to_s] ||= list.dup
+ end
+ end
+
+ # set_tag_list_on replaces the list without reading it, so load the original first.
+ def set_tag_list_on(context, new_list)
+ tag_list_cache_on(context)
+ super
+ end
+
+ # Both the tagging and cache callbacks ask this before writing.
+ def tag_list_cache_set_on(context)
+ super && tag_list_cache_on(context) != @original_tag_lists.fetch(context.to_s)
+ end
+
+ # The saved list becomes the new baseline right away, so a second edit in the same
+ # transaction is compared with what was just written. The baseline from before the
+ # transaction is kept until it ends. If the transaction rolls back, the database still
+ # has the old list, so that baseline comes back and a retry persists the edit again.
+ def save_tags
+ super.tap do
+ next unless @original_tag_lists
+
+ @tag_lists_before_transaction ||= @original_tag_lists.dup
+ @original_tag_lists.each_key { |context| @original_tag_lists[context] = tag_list_cache_on(context).dup }
+ end
+ end
+
+ # Reloading discards the old copy, so discard our remembered list too.
+ def reload(*)
+ @original_tag_lists = nil
+ @tag_lists_before_transaction = nil
+ super
+ end
+
+ private
+
+ def forget_tag_lists_before_transaction
+ @tag_lists_before_transaction = nil
+ end
+
+ def restore_tag_lists_before_transaction
+ @original_tag_lists = @tag_lists_before_transaction if @tag_lists_before_transaction
+ @tag_lists_before_transaction = nil
+ end
+end
diff --git a/spec/models/concerns/labelable/persistence_spec.rb b/spec/models/concerns/labelable/persistence_spec.rb
new file mode 100644
index 00000000000..1babe4021fb
--- /dev/null
+++ b/spec/models/concerns/labelable/persistence_spec.rb
@@ -0,0 +1,138 @@
+require 'rails_helper'
+
+RSpec.describe Labelable::Persistence do
+ %i[conversation contact].each do |factory|
+ context "with a #{factory}" do
+ let(:record) { create(factory) }
+ let(:other_instance) { record.class.find(record.id) }
+
+ it 'preserves labels added by another instance after the list was read' do
+ expect(record.label_list).to be_empty
+ other_instance.update_labels(['runner'])
+
+ record.update!(custom_attributes: { 'note' => 'Unrelated edit' })
+
+ expect(record.saved_change_to_label_list?).to be(false)
+ expect(record.reload.labels.pluck(:name)).to eq(['runner'])
+ end
+
+ it 'does not restore labels removed by another instance' do
+ record.update_labels(['runner'])
+ record.label_list
+ other_instance.update_labels([])
+
+ record.update!(custom_attributes: { 'note' => 'Unrelated edit' })
+
+ expect(record.reload.labels).to be_empty
+ end
+
+ it 'preserves concurrent additions after a previous label save on the same instance' do
+ record.update_labels(['runner'])
+ other_instance.add_labels(['lead'])
+
+ record.update!(custom_attributes: { 'note' => 'Unrelated edit' })
+
+ expect(record.reload.labels.pluck(:name)).to contain_exactly('runner', 'lead')
+ end
+
+ it 'persists explicit label additions and removals' do
+ record.update_labels(['runner'])
+ expect(record.saved_change_to_label_list?).to be(true)
+ expect(record.reload.labels.pluck(:name)).to eq(['runner'])
+
+ record.update_labels([])
+ expect(record.saved_change_to_label_list?).to be(true)
+ expect(record.reload.labels).to be_empty
+ end
+
+ it 'persists in-place additions and removals across successive saves' do
+ record.label_list.add('runner')
+ record.save!
+ expect(other_instance.labels.pluck(:name)).to eq(['runner'])
+
+ record.label_list.remove('runner')
+ record.label_list.add('lead')
+ record.save!
+ expect(other_instance.reload.labels.pluck(:name)).to eq(['lead'])
+ end
+
+ it 'uses the reloaded list as the baseline for subsequent edits' do
+ record.update_labels(['runner'])
+ other_instance.update_labels(['lead'])
+
+ record.reload
+ record.label_list.remove('lead')
+ record.label_list.add('runner')
+ record.save!
+
+ expect(other_instance.reload.labels.pluck(:name)).to eq(['runner'])
+ end
+
+ it 'retains pending label edits after validation fails' do
+ record.label_list.add('runner')
+ record.account = nil
+ expect(record.save).to be(false)
+
+ record.account = other_instance.account
+ record.save!
+
+ expect(other_instance.reload.labels.pluck(:name)).to eq(['runner'])
+ end
+
+ it 'persists a label edit retried after its transaction rolled back' do
+ record.class.transaction(requires_new: true) do
+ record.update_labels(['runner'])
+ raise ActiveRecord::Rollback
+ end
+ expect(other_instance.labels).to be_empty
+
+ record.save!
+
+ expect(other_instance.reload.labels.pluck(:name)).to eq(['runner'])
+ end
+
+ it 'persists a second label edit saved in the same transaction' do
+ record.class.transaction(requires_new: true) do
+ record.update_labels(['runner'])
+ record.update_labels([])
+ end
+
+ expect(other_instance.reload.labels).to be_empty
+ end
+
+ it 'persists a list set through set_tag_list_on without a prior read' do
+ other_instance.set_tag_list_on(:labels, ['runner'])
+ other_instance.save!
+
+ expect(record.reload.labels.pluck(:name)).to eq(['runner'])
+ end
+ end
+ end
+
+ context 'with a conversation label cache' do
+ let(:conversation) { create(:conversation) }
+
+ [nil, ''].each do |cached_labels|
+ it "preserves a newer cache when the original cache was #{cached_labels.inspect}" do
+ conversation.update!(cached_label_list: cached_labels)
+ stale_instance = Conversation.find(conversation.id)
+ expect(stale_instance.label_list).to be_empty
+ conversation.update_labels(['runner'])
+
+ stale_instance.update!(first_reply_created_at: Time.current, waiting_since: nil)
+
+ expect(conversation.reload.cached_label_list).to eq('runner')
+ expect(conversation.labels.pluck(:name)).to eq(['runner'])
+ end
+ end
+
+ it 'updates the cache when labels are intentionally changed' do
+ conversation.label_list.add('runner')
+ conversation.save!
+ expect(conversation.reload.cached_label_list).to eq('runner')
+
+ conversation.update_labels([])
+ expect(conversation.reload.cached_label_list).to eq('')
+ end
+ end
+end