Skip to content

The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:

Persist disabling a collection from remote sync (GHY-4189) (#78493)

Eric Normand65f07f2d116b
diff --git a/enterprise/backend/src/metabase_enterprise/remote_sync/core.clj b/enterprise/backend/src/metabase_enterprise/remote_sync/core.clj
index aa84c79a93e..686a9bdb248 100644
--- a/enterprise/backend/src/metabase_enterprise/remote_sync/core.clj
+++ b/enterprise/backend/src/metabase_enterprise/remote_sync/core.clj
@@ -1,5 +1,6 @@
(ns metabase-enterprise.remote-sync.core
(:require
+ [java-time.api :as t]
[metabase-enterprise.remote-sync.guards :as guards]
[metabase-enterprise.remote-sync.settings :as settings]
[metabase-enterprise.remote-sync.source :as source]
@@ -87,6 +88,78 @@
(spec/batch-check-eligibility spec instances)
(into {} (map (fn [inst] [(:id inst) false])) instances)))
+(defn- subtree-where
+ "HoneySQL predicate matching `collections` and all of their descendants."
+ [collections]
+ (into [:or [:in :id (map :id collections)]]
+ (for [collection collections]
+ [:like :location (str (collections/location-path collection) "%")])))
+
+(defn- contents-rso-where
+ "HoneySQL predicate matching the RemoteSyncObject rows of `collection-ids` and of their contents."
+ [collection-ids]
+ [:or
+ [:and [:= :model_type "Collection"] [:in :model_id collection-ids]]
+ [:in :model_collection_id collection-ids]])
+
+(defn- record-removed-rsos!
+ "Records a pending removal on the RemoteSyncObject rows of the given collections and their contents, so
+ the next export deletes them from the remote. Rows still in 'create' (never pushed) are dropped outright
+ — the remote never received them, so there is nothing to delete there."
+ [collection-ids]
+ (let [rows (t2/select [:model/RemoteSyncObject :id :status] {:where (contents-rso-where collection-ids)})
+ {created true tracked false} (group-by #(= "create" (:status %)) rows)]
+ (when (seq created)
+ (t2/delete! :model/RemoteSyncObject :id [:in (map :id created)]))
+ (when (seq tracked)
+ (t2/update! :model/RemoteSyncObject :id [:in (map :id tracked)]
+ {:status "removed" :status_changed_at (t/offset-date-time)}))))
+
+(defn- restore-removed-rsos!
+ "Clears any pending 'removed' status on the given collections' and contents' RemoteSyncObject rows when the
+ collections are re-synced, so the next export does not delete them from the remote. This targets every
+ 'removed' row in the subtree regardless of what recorded it (typically [[record-removed-rsos!]] from an
+ earlier un-sync, but also e.g. an unpublished table's pending removal).
+
+ Restores to 'update' rather than 'synced': edits made while the collection was un-synced are not tracked,
+ so the entity must be re-serialized for the remote to be guaranteed to match local."
+ [collection-ids]
+ (when-let [ids (seq (t2/select-pks-set :model/RemoteSyncObject
+ {:where [:and
+ [:= :status "removed"]
+ (contents-rso-where collection-ids)]}))]
+ (t2/update! :model/RemoteSyncObject :id [:in ids]
+ {:status "update" :status_changed_at (t/offset-date-time)})))
+
+(defn- collection-content-specs
+ "Specs for entities tracked by living directly in a remote-synced collection (Card, Dashboard, Document,
+ Timeline) — eligibility keyed on the collection being remote-synced, so they carry a collection_id."
+ []
+ (filter #(= :remote-synced (get-in % [:eligibility :collection])) (vals spec/remote-sync-specs)))
+
+(defn- track-untracked-contents!
+ "Inserts a 'create' RemoteSyncObject row for every eligible content entity in `collection-ids` that has
+ none — e.g. a never-pushed card whose 'create' row was dropped when its collection was previously
+ un-synced. Without this a re-enabled collection's untracked contents would be omitted by the next
+ (incremental) export. The RemoteSyncObject table only records pending changes, so already-synced content
+ is legitimately absent; re-marking it 'create' re-serializes it harmlessly (a 'create' onto its own path
+ stays a no-op)."
+ [collection-ids]
+ (doseq [{:keys [model-key model-type archived-key] :as spec} (collection-content-specs)
+ :let [tracked (t2/select-fn-set :model_id :model/RemoteSyncObject :model_type model-type)
+ where (if archived-key
+ [:and [:in :collection_id collection-ids] [:= archived-key false]]
+ [:in :collection_id collection-ids])
+ entities (t2/select model-key {:where where})]
+ entity entities
+ :when (not (contains? tracked (:id entity)))]
+ (t2/insert! :model/RemoteSyncObject
+ (merge {:model_type model-type
+ :model_id (:id entity)
+ :status "create"
+ :status_changed_at (t/offset-date-time)}
+ (spec/build-sync-object-fields spec entity)))))
+
(mu/defn bulk-set-remote-sync :- :nil
"Sets remote sync to true/false on one or collections in a single transaction. Checks that the remote sync state
afterwards is consistent in terms of dependency rules. Collections are provided as a map of collection-id -> sync state."
@@ -108,26 +181,24 @@
:set {:is_remote_synced true}
:where [:and
[:= :is_remote_synced false]
- (into [:or [:in :id (map :id sync-on)]]
- (for [collection sync-on]
- [:like :location (str (collections/location-path collection) "%")]))]}))
+ (subtree-where sync-on)]})
+ (when-let [ids (seq (t2/select-pks-set :model/Collection {:where (subtree-where sync-on)}))]
+ ;; Re-syncing before a recorded removal was pushed must not leave the contents marked for deletion.
+ (restore-removed-rsos! ids)
+ ;; ...and contents that were dropped outright (never-pushed 'create' rows) must be re-tracked, so
+ ;; the next export pushes them rather than silently omitting them.
+ (track-untracked-contents! ids)))
(when (seq sync-off)
(let [affected-collection-ids
(t2/select-pks-set :model/Collection
{:where [:and
[:= :is_remote_synced true]
- (into [:or [:in :id (map :id sync-off)]]
- (for [collection sync-off]
- [:like :location (str (collections/location-path collection) "%")]))]})]
+ (subtree-where sync-off)]})]
(when (seq affected-collection-ids)
(t2/query {:update (t2/table-name :model/Collection)
:set {:is_remote_synced false}
:where [:in :id affected-collection-ids]})
- (t2/delete! :model/RemoteSyncObject
- :model_type "Collection"
- :model_id [:in affected-collection-ids])
- (t2/delete! :model/RemoteSyncObject
- :model_collection_id [:in affected-collection-ids]))))
+ (record-removed-rsos! affected-collection-ids))))
(doseq [collection sync-on]
(collections/check-non-remote-synced-dependencies collection))
(doseq [collection sync-off]
diff --git a/enterprise/backend/src/metabase_enterprise/remote_sync/events.clj b/enterprise/backend/src/metabase_enterprise/remote_sync/events.clj
index 770b79e7c7d..26bf8edbecf 100644
--- a/enterprise/backend/src/metabase_enterprise/remote_sync/events.clj
+++ b/enterprise/backend/src/metabase_enterprise/remote_sync/events.clj
@@ -119,35 +119,69 @@
;;; ----------------------------------------- Spec-based Event Handling ------------------------------------------------
+(defn- still-eligible?
+ "Re-checks `model-id`'s eligibility against current DB state. The eligibility that got us here was computed
+ from an event payload, which a concurrent change may have invalidated in the meantime."
+ [model-spec model-id]
+ (boolean (when-let [instance (t2/select-one (:model-key model-spec) :id model-id)]
+ (spec/check-eligibility model-spec instance))))
+
(defn- create-or-update-sync-object-from-spec!
"Creates or updates a RemoteSyncObject entry using a spec for field hydration.
- This is the spec-based version of create-or-update-remote-sync-object-entry!."
+ This is the spec-based version of create-or-update-remote-sync-object-entry!.
+
+ Row-locks the entry for the transaction, so this and a concurrent un-sync of the entity's collection
+ settle in a fixed order rather than losing one of the two writes: whichever locks first commits, and
+ the other then observes that result — the un-sync re-marking the row, or the eligibility re-check below
+ seeing the entity is gone from the synced set."
[model-spec model-id status]
- (let [model-type (:model-type model-spec)
- existing (t2/select-one :model/RemoteSyncObject :model_type model-type :model_id model-id)]
- (cond
- (not existing)
- (let [model-details (spec/hydrate-model-details model-spec model-id)
- fields (spec/build-sync-object-fields model-spec model-details)]
- (t2/insert! :model/RemoteSyncObject
- (merge {:model_type model-type
- :model_id model-id
- :status status
- :status_changed_at (t/offset-date-time)}
- fields)))
- (and (= "create" (:status existing)) (contains? #{"removed" "delete"} status))
- (t2/delete! :model/RemoteSyncObject (:id existing))
- (= "delete" (:status existing))
- (t2/update! :model/RemoteSyncObject (:id existing)
- {:status status
- :status_changed_at (t/offset-date-time)})
- (not= "create" (:status existing))
- (let [model-details (spec/hydrate-model-details model-spec model-id)
- fields (spec/build-sync-object-fields model-spec model-details)]
+ (t2/with-transaction [_conn]
+ (let [model-type (:model-type model-spec)
+ existing (t2/select-one :model/RemoteSyncObject
+ {:where [:and [:= :model_type model-type] [:= :model_id model-id]]
+ :for :update})]
+ (cond
+ ;; No row to lock, so a concurrent un-sync that hasn't inserted yet is invisible here (a phantom the
+ ;; row lock can't cover). Re-check eligibility so a stale tracked-status event does not start tracking
+ ;; an entity that has since left the synced set. This narrows, but cannot fully close, that window.
+ (and (not existing)
+ (not (contains? #{"removed" "delete"} status))
+ (not (still-eligible? model-spec model-id)))
+ nil
+
+ (not existing)
+ (let [model-details (spec/hydrate-model-details model-spec model-id)
+ fields (spec/build-sync-object-fields model-spec model-details)]
+ (t2/insert! :model/RemoteSyncObject
+ (merge {:model_type model-type
+ :model_id model-id
+ :status status
+ :status_changed_at (t/offset-date-time)}
+ fields)))
+
+ (and (= "create" (:status existing)) (contains? #{"removed" "delete"} status))
+ (t2/delete! :model/RemoteSyncObject (:id existing))
+
+ ;; A pending removal must not be resurrected by a tracked-status write whose eligibility check was
+ ;; overtaken by a concurrent un-sync: that check ran against the event payload, well before this
+ ;; write, so re-check against current state and let the removal stand when it no longer holds.
+ (and (contains? #{"removed" "delete"} (:status existing))
+ (not (contains? #{"removed" "delete"} status))
+ (not (still-eligible? model-spec model-id)))
+ nil
+
+ (= "delete" (:status existing))
(t2/update! :model/RemoteSyncObject (:id existing)
- (merge {:status (resolve-status model-type model-id status existing)
- :status_changed_at (t/offset-date-time)}
- fields))))))
+ {:status status
+ :status_changed_at (t/offset-date-time)})
+
+ (not= "create" (:status existing))
+ (let [model-details (spec/hydrate-model-details model-spec model-id)
+ fields (spec/build-sync-object-fields model-spec model-details)]
+ (t2/update! :model/RemoteSyncObject (:id existing)
+ (merge {:status (resolve-status model-type model-id status existing)
+ :status_changed_at (t/offset-date-time)}
+ fields)))))))
(defn- cascade-filter
"Derives the filter conditions for querying eligible children from a child spec."
diff --git a/enterprise/backend/test/metabase_enterprise/remote_sync/core_test.clj b/enterprise/backend/test/metabase_enterprise/remote_sync/core_test.clj
index a933cc27832..099f8aaf08b 100644
--- a/enterprise/backend/test/metabase_enterprise/remote_sync/core_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/remote_sync/core_test.clj
@@ -5,6 +5,8 @@
[java-time.api :as t]
[metabase-enterprise.remote-sync.core :as core]
[metabase-enterprise.remote-sync.guards :as guards]
+ [metabase-enterprise.remote-sync.models.remote-sync-object :as remote-sync.object]
+ [metabase-enterprise.remote-sync.test-helpers :as rs.test]
[metabase.collections.test-utils :refer [with-library-synced with-library-not-synced]]
[metabase.events.core :as events]
[metabase.test :as mt]
@@ -12,6 +14,9 @@
[toucan2.core :as t2]))
(use-fixtures :once (fixtures/initialize :db))
+;; Disabling a collection now marks its RemoteSyncObject rows rather than deleting them, so rows seeded by
+;; a test outlive it without this — leaking dirty state into every later test.
+(use-fixtures :each rs.test/clean-object)
;; bulk-set-remote-sync tests
@@ -267,53 +272,78 @@
;;; ------------------------------------------- RSO Cleanup Tests -------------------------------------------
-(deftest bulk-set-remote-sync-cleans-up-rsos-on-disable-test
- (testing "bulk-set-remote-sync deletes RemoteSyncObject entries for un-synced collections and their contents"
- (mt/with-temp [:model/Collection {coll-id :id} {:name "Test Collection" :location "/" :is_remote_synced true}
- :model/Card {card-id :id} {:name "Test Card" :collection_id coll-id
- :database_id (mt/id)
- :dataset_query (mt/mbql-query venues)}]
- (let [now (t/offset-date-time)]
+(deftest bulk-set-remote-sync-marks-rsos-removed-on-disable-test
+ (testing "bulk-set-remote-sync marks RemoteSyncObject entries for un-synced collections and their
+ contents as 'removed' — a pending deletion the next export pushes to the remote — instead of
+ silently dropping them, which left nothing to push (GHY-4189)"
+ (mt/with-temp [:model/Collection {coll-id :id} {:name "Test Collection" :location "/" :is_remote_synced true}]
+ (let [now (t/offset-date-time)
+ card-eid 90001]
+ ;; Both entities are already on the remote (status 'synced', with a stored file_path).
(t2/insert! :model/RemoteSyncObject
{:model_type "Collection" :model_id coll-id :model_name "Test Collection"
- :status "update" :status_changed_at now})
+ :status "synced" :status_changed_at now :file_path "collections/tc/tc.yaml"})
(t2/insert! :model/RemoteSyncObject
- {:model_type "Card" :model_id card-id :model_name "Test Card"
- :model_collection_id coll-id :status "update" :status_changed_at now})
- (is (= 2 (t2/count :model/RemoteSyncObject
- {:where [:or
- [:and [:= :model_type "Collection"] [:= :model_id coll-id]]
- [:= :model_collection_id coll-id]]})))
+ {:model_type "Card" :model_id card-eid :model_name "Test Card"
+ :model_collection_id coll-id :status "synced" :status_changed_at now
+ :file_path "collections/tc/cards/card.yaml"})
(mt/with-dynamic-fn-redefs [events/publish-event! (constantly nil)]
(core/bulk-set-remote-sync {coll-id false}))
- (is (= 0 (t2/count :model/RemoteSyncObject
- {:where [:or
- [:and [:= :model_type "Collection"] [:= :model_id coll-id]]
- [:= :model_collection_id coll-id]]})))))))
-
-(deftest bulk-set-remote-sync-cleans-up-descendant-rsos-test
- (testing "bulk-set-remote-sync deletes RSOs for descendant collections and their contents"
+ (is (= "removed" (t2/select-one-fn :status :model/RemoteSyncObject
+ :model_type "Collection" :model_id coll-id))
+ "the collection RSO is marked removed, not deleted")
+ (is (= "removed" (t2/select-one-fn :status :model/RemoteSyncObject
+ :model_type "Card" :model_id card-eid))
+ "the collection's contents are marked removed too")
+ (is (true? (remote-sync.object/dirty?))
+ "disabling leaves a pending change so a subsequent export pushes the removal")))))
+
+(deftest bulk-set-remote-sync-drops-never-pushed-rsos-on-disable-test
+ (testing "bulk-set-remote-sync drops RSOs still in 'create' (never pushed to the remote) rather than
+ marking them 'removed' — the remote never received them, so there is nothing to delete there"
+ (mt/with-temp [:model/Collection {coll-id :id} {:name "Test Collection" :location "/" :is_remote_synced true}]
+ (let [now (t/offset-date-time)
+ card-eid 90002]
+ (t2/insert! :model/RemoteSyncObject
+ {:model_type "Collection" :model_id coll-id :model_name "Test Collection"
+ :status "create" :status_changed_at now})
+ (t2/insert! :model/RemoteSyncObject
+ {:model_type "Card" :model_id card-eid :model_name "Test Card"
+ :model_collection_id coll-id :status "create" :status_changed_at now})
+ (mt/with-dynamic-fn-redefs [events/publish-event! (constantly nil)]
+ (core/bulk-set-remote-sync {coll-id false}))
+ (is (false? (t2/exists? :model/RemoteSyncObject :model_type "Collection" :model_id coll-id))
+ "a never-pushed collection RSO is dropped outright")
+ (is (false? (t2/exists? :model/RemoteSyncObject :model_type "Card" :model_id card-eid))
+ "a never-pushed content RSO is dropped outright")))))
+
+(deftest bulk-set-remote-sync-marks-descendant-rsos-removed-test
+ (testing "bulk-set-remote-sync marks RSOs for descendant collections and their contents as removed,
+ dropping only the never-pushed ('create') ones (GHY-4189)"
(mt/with-temp [:model/Collection {parent-id :id} {:name "Parent" :location "/" :is_remote_synced true}
:model/Collection {child-id :id} {:name "Child" :location (format "/%d/" parent-id)
- :is_remote_synced true}
- :model/Card {card-id :id} {:name "Child Card" :collection_id child-id
- :database_id (mt/id)
- :dataset_query (mt/mbql-query venues)}]
- (let [now (t/offset-date-time)]
+ :is_remote_synced true}]
+ (let [now (t/offset-date-time)
+ card-eid 90003]
(t2/insert! :model/RemoteSyncObject
{:model_type "Collection" :model_id parent-id :model_name "Parent"
- :status "update" :status_changed_at now})
+ :status "synced" :status_changed_at now :file_path "collections/parent/parent.yaml"})
(t2/insert! :model/RemoteSyncObject
{:model_type "Collection" :model_id child-id :model_name "Child"
- :status "update" :status_changed_at now})
+ :status "update" :status_changed_at now :file_path "collections/parent/child/child.yaml"})
(t2/insert! :model/RemoteSyncObject
- {:model_type "Card" :model_id card-id :model_name "Child Card"
+ {:model_type "Card" :model_id card-eid :model_name "Child Card"
:model_collection_id child-id :status "create" :status_changed_at now})
(mt/with-dynamic-fn-redefs [events/publish-event! (constantly nil)]
(core/bulk-set-remote-sync {parent-id false}))
- (is (false? (t2/exists? :model/RemoteSyncObject :model_type "Collection" :model_id parent-id)))
- (is (false? (t2/exists? :model/RemoteSyncObject :model_type "Collection" :model_id child-id)))
- (is (false? (t2/exists? :model/RemoteSyncObject :model_id card-id)))))))
+ (is (= "removed" (t2/select-one-fn :status :model/RemoteSyncObject
+ :model_type "Collection" :model_id parent-id))
+ "already-pushed parent collection is marked removed")
+ (is (= "removed" (t2/select-one-fn :status :model/RemoteSyncObject
+ :model_type "Collection" :model_id child-id))
+ "already-pushed descendant collection is marked removed")
+ (is (false? (t2/exists? :model/RemoteSyncObject :model_type "Card" :model_id card-eid))
+ "never-pushed content RSO is dropped")))))
;;; ------------------------------------------- batch-model-eligible? Tests -------------------------------------------
diff --git a/enterprise/backend/test/metabase_enterprise/remote_sync/events_test.clj b/enterprise/backend/test/metabase_enterprise/remote_sync/events_test.clj
index af6d91c3b5c..f566785c85c 100644
--- a/enterprise/backend/test/metabase_enterprise/remote_sync/events_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/remote_sync/events_test.clj
@@ -6,6 +6,7 @@
(:require
[clojure.test :refer :all]
[java-time.api :as t]
+ [metabase-enterprise.remote-sync.core :as remote-sync.core]
[metabase-enterprise.remote-sync.events :as remote-sync.events]
[metabase-enterprise.remote-sync.spec :as spec]
[metabase.collections.models.collection :as collection]
@@ -13,6 +14,7 @@
[metabase.events.core :as events]
[metabase.test :as mt]
[metabase.test.fixtures :as fixtures]
+ [metabase.test.util.thread-local :as tu.thread-local]
[metabase.util :as u]
[toucan2.core :as t2]))
@@ -1167,6 +1169,108 @@
:model_table_id (:id table)}
(first entries)))))))
+;;; ------------------------------------- Concurrent Un-Sync Race Tests -------------------------------------
+;;;
+;;; When a card-update event and a collection disable run concurrently, the handler must not resurrect the
+;;; pending 'removed' status the disable records. Two orderings, each guarded by a different mechanism:
+;;; - disable commits first -> the handler's write-time eligibility re-check keeps the removal
+;;; - handler locks first -> the disable blocks on the row lock and records the removal last
+;;; Both are exercised below by parking the handler at a chosen point and driving the disable around it.
+
+(defn- once-parking-select-one!
+ "Wraps `t2/select-one` to park the first call whose args match `park-pred` — signalling `reached`, then
+ blocking on `release` (10s cap) — so a test can freeze the handler at a precise point."
+ [park-pred reached release]
+ (let [orig t2/select-one
+ fired (atom false)]
+ (fn [& args]
+ (let [res (apply orig args)]
+ (when (and (park-pred args) (compare-and-set! fired false true))
+ (deliver reached true)
+ (deref release 10000 nil))
+ res))))
+
+(defn- rso-lookup-select?
+ "The handler's plain (non-locking) existing-entry read: `(t2/select-one :model/RemoteSyncObject :model_type … :model_id …)`."
+ [[model second-arg]]
+ (and (= model :model/RemoteSyncObject) (keyword? second-arg)))
+
+(defn- rso-locking-select?
+ "The `FOR UPDATE` read inside create-or-update: `(t2/select-one :model/RemoteSyncObject {:where … :for :update})`."
+ [[model second-arg]]
+ (and (= model :model/RemoteSyncObject) (map? second-arg) (= :update (:for second-arg))))
+
+(defn- do-with-unsync-race-fixture
+ "Sets up a remote-synced collection + card already on the remote (status 'synced', as after an export;
+ no content_hash, so the handler's no-op suppression stays out of the way) and calls `(f coll-id card)`.
+ Rows are committed because the event handler runs on another thread with its own connection."
+ [f]
+ (binding [tu.thread-local/*thread-local* false]
+ (mt/with-temp [:model/Collection {coll-id :id} {:name "Race-Sync" :location "/" :is_remote_synced true}
+ :model/Card card {:name "Race Card" :collection_id coll-id
+ :database_id (mt/id)
+ :dataset_query (mt/mbql-query venues)}]
+ (try
+ (t2/delete! :model/RemoteSyncObject)
+ (t2/insert! :model/RemoteSyncObject
+ [{:model_type "Collection" :model_id coll-id :model_name "Race-Sync"
+ :status "synced" :status_changed_at (t/offset-date-time)
+ :file_path "collections/rs/rs.yaml"}
+ {:model_type "Card" :model_id (:id card) :model_name "Race Card"
+ :model_collection_id coll-id :status "synced"
+ :status_changed_at (t/offset-date-time)
+ :file_path "collections/rs/cards/race.yaml"}])
+ (f coll-id card)
+ (finally
+ (t2/delete! :model/RemoteSyncObject))))))
+
+(defn- fire-card-update! [card]
+ (future (events/publish-event! :event/card-update
+ {:object card :previous-object card :user-id (mt/user->id :rasta)})))
+
+(defn- assert-removal-survived [coll-id card]
+ (is (= "removed" (t2/select-one-fn :status :model/RemoteSyncObject :model_type "Card" :model_id (:id card)))
+ "the card's pending removal survives the concurrent event")
+ (is (= "removed" (t2/select-one-fn :status :model/RemoteSyncObject :model_type "Collection" :model_id coll-id))
+ "the collection's pending removal is untouched"))
+
+(deftest disable-first-recheck-preserves-removal-test
+ (testing "disable commits between the handler's stale eligibility read and its write: the write-time
+ eligibility re-check must keep the pending removal (GHY-4189)"
+ (do-with-unsync-race-fixture
+ (fn [coll-id card]
+ (let [reached (promise)
+ release (promise)]
+ ;; Park at the handler's plain existing-entry read — before it takes any row lock. Nothing is
+ ;; locked while parked, so the disable runs to completion first (the disable-first ordering).
+ (with-redefs [t2/select-one (once-parking-select-one! rso-lookup-select? reached release)]
+ (let [handler (fire-card-update! card)]
+ (is (true? (deref reached 10000 false)) "handler parked after reading pre-disable state")
+ (remote-sync.core/bulk-set-remote-sync {coll-id false})
+ (deliver release true)
+ (deref handler 10000 nil))))
+ (assert-removal-survived coll-id card)))))
+
+(deftest handler-first-lock-preserves-removal-test
+ (testing "the handler holds the entry's row lock when the disable arrives: the disable blocks until the
+ handler commits, then records the removal last, so it survives (GHY-4189)"
+ (do-with-unsync-race-fixture
+ (fn [coll-id card]
+ (let [reached (promise)
+ release (promise)]
+ ;; Park at the FOR UPDATE read, i.e. while the handler holds the entry's row lock (the
+ ;; handler-first ordering).
+ (with-redefs [t2/select-one (once-parking-select-one! rso-locking-select? reached release)]
+ (let [handler (fire-card-update! card)]
+ (is (true? (deref reached 10000 false)) "handler parked holding the row lock")
+ (let [disable (future (remote-sync.core/bulk-set-remote-sync {coll-id false}))]
+ (is (= ::blocked (deref disable 300 ::blocked))
+ "the disable blocks on the row lock the handler holds")
+ (deliver release true)
+ (deref disable 10000 nil)
+ (deref handler 10000 nil)))))
+ (assert-removal-survived coll-id card)))))
+
(deftest field-update-no-rso-when-no-fus-row-test
(testing "field-update on an eligible field with NO FUS row creates no RSOs at all"
(mt/with-temp [:model/Collection coll {:is_remote_synced true :name "Remote-Sync" :type "library-data"}
diff --git a/enterprise/backend/test/metabase_enterprise/remote_sync/incremental_export_test.clj b/enterprise/backend/test/metabase_enterprise/remote_sync/incremental_export_test.clj
index 07a82920380..bf591cf16fe 100644
--- a/enterprise/backend/test/metabase_enterprise/remote_sync/incremental_export_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/remote_sync/incremental_export_test.clj
@@ -7,7 +7,9 @@
[clojure.string :as str]
[clojure.test :refer :all]
[java-time.api :as t]
+ [metabase-enterprise.remote-sync.core :as core]
[metabase-enterprise.remote-sync.impl :as impl]
+ [metabase-enterprise.remote-sync.models.remote-sync-object :as remote-sync.object]
[metabase-enterprise.remote-sync.source.protocol :as source.p]
[metabase-enterprise.remote-sync.test-helpers :as rs.test]
[metabase.test :as mt]
@@ -186,6 +188,98 @@
(is (some (fn [[_ c]] (re-find (re-pattern a-eid) c)) files-after) "card A preserved")
(is (nil? (rso "Card" card-b)) "deleted entity's RemoteSyncObject row removed"))))))
+(deftest disable-collection-pushes-removal-and-survives-pull-test
+ (testing "disabling a synced collection removes its files (and its contents') from the remote on the
+ next export, and a subsequent import does not re-enable it (GHY-4189)"
+ (with-exported-collection!
+ (fn [{:keys [mock coll-id card-a card-b]}]
+ (let [coll-eid (t2/select-one-fn :entity_id :model/Collection :id coll-id)
+ a-eid (t2/select-one-fn :entity_id :model/Card :id card-a)
+ b-eid (t2/select-one-fn :entity_id :model/Card :id card-b)]
+ (is (entity-exported? mock coll-eid) "precondition: the collection is on the remote")
+ ;; Production populates a content RSO's model_collection_id from the card's collection_id (see
+ ;; the tracking specs); the bare seed-synced-row! helper does not, so set it to match reality —
+ ;; it is how a collection's contents are located when the collection is un-synced.
+ (t2/update! :model/RemoteSyncObject :model_type "Card" :model_id [:in [card-a card-b]]
+ {:model_collection_id coll-id})
+ ;; Clear the initial-export task: a direct impl/export! never marks its task ended, so the
+ ;; bulk-set-remote-sync guard would otherwise (correctly) refuse to run alongside it.
+ (t2/delete! :model/RemoteSyncTask)
+ ;; USER ACTION: disable the collection from remote sync.
+ (core/bulk-set-remote-sync {coll-id false})
+ (is (true? (remote-sync.object/dirty?))
+ "disabling leaves a pending change to push (the removal)")
+ ;; USER ACTION: push. The removal must reach the remote.
+ (let [task (new-task!)
+ result (impl/export! (source.p/snapshot mock) task "disable collection")]
+ (is (= :success (:status result)))
+ (is (not (entity-exported? mock coll-eid)) "collection file removed from the remote")
+ (is (not (entity-exported? mock a-eid)) "card A removed from the remote")
+ (is (not (entity-exported? mock b-eid)) "card B removed from the remote"))
+ ;; USER ACTION: pull from the remote. Because the removal was pushed, the collection is no
+ ;; longer in the remote, so the import cannot re-enable it.
+ (let [task (new-task!)
+ result (impl/import! (source.p/snapshot mock) task)]
+ (is (= :success (:status result))
+ "the pull itself succeeds — otherwise the assertion below passes vacuously"))
+ (is (false? (t2/select-one-fn :is_remote_synced :model/Collection :id coll-id))
+ "a pull does not re-enable a collection that was disabled and pushed"))))))
+
+(deftest reenable-collection-before-export-keeps-contents-test
+ (testing "disable → re-enable before any export runs: the next export must not delete the collection's
+ contents from the remote (GHY-4189)"
+ (with-exported-collection!
+ (fn [{:keys [mock coll-id card-a card-b]}]
+ (let [coll-eid (t2/select-one-fn :entity_id :model/Collection :id coll-id)
+ a-eid (t2/select-one-fn :entity_id :model/Card :id card-a)
+ b-eid (t2/select-one-fn :entity_id :model/Card :id card-b)]
+ ;; Production populates a content RSO's model_collection_id from the card's collection_id (see
+ ;; the tracking specs); the bare seed-synced-row! helper does not, so set it to match reality.
+ (t2/update! :model/RemoteSyncObject :model_type "Card" :model_id [:in [card-a card-b]]
+ {:model_collection_id coll-id})
+ ;; Clear the initial-export task so the bulk-set-remote-sync guard lets us proceed.
+ (t2/delete! :model/RemoteSyncTask)
+ ;; USER ACTION: disable the collection, then re-enable it before any export runs.
+ (core/bulk-set-remote-sync {coll-id false})
+ (core/bulk-set-remote-sync {coll-id true})
+ ;; USER ACTION: push. Nothing was disabled at push time, so nothing may be deleted.
+ (let [task (new-task!)
+ result (impl/export! (source.p/snapshot mock) task "after re-enable")]
+ (is (= :success (:status result)))
+ (is (entity-exported? mock coll-eid) "collection file still on the remote")
+ (is (entity-exported? mock a-eid) "card A still on the remote")
+ (is (entity-exported? mock b-eid) "card B still on the remote")))))))
+
+(deftest reenable-retracks-never-pushed-content-test
+ (testing "a card created but never pushed, dropped when its collection was disabled, is re-tracked on
+ re-enable so the next export pushes it instead of silently losing it (GHY-4189)"
+ (with-exported-collection!
+ (fn [{:keys [mock coll-id card-a card-b]}]
+ ;; Mirror production: content RSOs carry model_collection_id, so the disable can find them.
+ (t2/update! :model/RemoteSyncObject :model_type "Card" :model_id [:in [card-a card-b]]
+ {:model_collection_id coll-id})
+ (mt/with-temp [:model/Card {card-c :id} {:name "Card C" :collection_id coll-id}]
+ ;; Card C is new and never pushed: a 'create' RSO with no file_path (as a card-create event
+ ;; produces). It exists locally in the synced collection but is not yet on the remote.
+ (t2/delete! :model/RemoteSyncObject :model_type "Card" :model_id card-c)
+ (t2/insert! :model/RemoteSyncObject
+ {:model_type "Card" :model_id card-c :model_name "Card C"
+ :model_collection_id coll-id :status "create"
+ :status_changed_at (t/offset-date-time)})
+ (let [c-eid (t2/select-one-fn :entity_id :model/Card :id card-c)]
+ (is (not (entity-exported? mock c-eid)) "precondition: card C has never been pushed")
+ ;; Clear the initial-export task so the bulk-set-remote-sync guard lets us proceed.
+ (t2/delete! :model/RemoteSyncTask)
+ ;; USER ACTION: disable then re-enable before card C is ever pushed. The disable drops card C's
+ ;; never-pushed 'create' row; re-enable must re-track it.
+ (core/bulk-set-remote-sync {coll-id false})
+ (core/bulk-set-remote-sync {coll-id true})
+ ;; USER ACTION: push. Card C must reach the remote, not be silently lost.
+ (let [result (impl/export! (source.p/snapshot mock) (new-task!) "after re-enable")]
+ (is (= :success (:status result)))
+ (is (entity-exported? mock c-eid)
+ "card C is pushed to the remote after the disable/re-enable cycle"))))))))
+
(deftest rename-without-stored-path-falls-back-test
(with-exported-collection!
(fn [{:keys [mock card-a]}]