Skip to content

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

Uxw 4977 show collection that couldnt be synced (#79652)

Nick Fitzpatrick3e9460c53ed0
diff --git a/e2e/test/scenarios/admin/remote-sync.cy.spec.ts b/e2e/test/scenarios/admin/remote-sync.cy.spec.ts
index 7ff2c340512..ebbaba1e938 100644
--- a/e2e/test/scenarios/admin/remote-sync.cy.spec.ts
+++ b/e2e/test/scenarios/admin/remote-sync.cy.spec.ts
@@ -1,7 +1,10 @@
import { WRITABLE_DB_ID } from "e2e/support/cypress_data";
import { SAMPLE_DATABASE } from "e2e/support/cypress_sample_database";
import { ORDERS_DASHBOARD_ID } from "e2e/support/cypress_sample_instance_data";
-import type { Collection } from "metabase-types/api";
+import type {
+ Collection,
+ RemoteSyncDependencyErrorResponse,
+} from "metabase-types/api";
const { PRODUCTS_ID } = SAMPLE_DATABASE;
@@ -11,6 +14,13 @@ const LOCAL_GIT_URL = "file://" + H.LOCAL_GIT_PATH + "/.git";
const REMOTE_QUESTION_NAME = "Remote Sync Test Question";
+const BLOCKED_COLLECTION_NAME = "Blocked Collection";
+const SECOND_BLOCKED_COLLECTION_NAME = "Also Blocked Collection";
+const SOURCE_COLLECTION_NAME = "Dependency Source";
+const SOURCE_QUESTION_NAME = "Dependency Source Question";
+const DEPENDENT_QUESTION_NAME = "Dependent Question";
+const SECOND_DEPENDENT_QUESTION_NAME = "Second Dependent Question";
+
describe("Remote Sync", () => {
beforeEach(() => {
H.restore("postgres-writable");
@@ -601,6 +611,89 @@ describe("Remote Sync", () => {
ensureSyncedCollectionIsVisible();
});
+
+ describe("unsynced dependency modal", () => {
+ beforeEach(() => {
+ H.configureGit("read-write");
+ cy.intercept("PUT", "/api/ee/remote-sync/settings").as("saveSettings");
+ });
+
+ it("reports every blocked collection, re-opens after a dismissal, syncs them all, and stays hidden for unrelated errors", () => {
+ createDependencyFixture().then(({ source, blocked, alsoBlocked }) => {
+ cy.visit("/admin/settings/remote-sync");
+
+ cy.button("Save changes").should("be.disabled");
+
+ cy.findByLabelText(`Sync ${BLOCKED_COLLECTION_NAME}`).click({
+ force: true,
+ });
+ cy.findByLabelText(`Sync ${SECOND_BLOCKED_COLLECTION_NAME}`).click({
+ force: true,
+ });
+
+ cy.log("Both collections are refused in a single pass");
+ saveAndExpectRefusal().then((interception) => {
+ const body: RemoteSyncDependencyErrorResponse =
+ interception.response?.body;
+ expect(
+ body.errors.collections.map((failure) => failure.collection.name),
+ ).to.have.members([
+ BLOCKED_COLLECTION_NAME,
+ SECOND_BLOCKED_COLLECTION_NAME,
+ ]);
+ });
+
+ H.modal().within(() => {
+ // Every remedy here is a collection we can switch on, so the modal asks rather than refuses.
+ cy.findByText("Sync collections with dependencies?").should(
+ "be.visible",
+ );
+ // Both failures resolve to the same remedy, so it is offered once.
+ cy.findAllByText(SOURCE_COLLECTION_NAME).should("have.length", 1);
+ cy.button("Cancel").click();
+ });
+ H.modal().should("not.exist");
+
+ cy.log("Saving the same selection again brings it back");
+ saveAndExpectRefusal();
+
+ H.modal().within(() => {
+ cy.button("Sync required collections").click();
+ });
+
+ cy.wait("@saveSettings").then(({ request, response }) => {
+ expect(response?.statusCode).to.eq(200);
+ expect(request.body.collections).to.deep.equal({
+ [blocked.id]: true,
+ [alsoBlocked.id]: true,
+ [source.id]: true,
+ });
+ });
+
+ H.modal().should("not.exist");
+
+ cy.reload();
+ [
+ BLOCKED_COLLECTION_NAME,
+ SECOND_BLOCKED_COLLECTION_NAME,
+ SOURCE_COLLECTION_NAME,
+ ].forEach((name) => {
+ cy.findByLabelText(`Sync ${name}`).should("be.checked");
+ });
+
+ // The dependents error carries no error_code, so the modal must ignore it.
+ cy.log("Un-syncing the source is a plain error, not the modal");
+ cy.findByLabelText(`Sync ${SOURCE_COLLECTION_NAME}`).click({
+ force: true,
+ });
+ cy.button("Save changes").should("be.enabled").click();
+
+ cy.wait("@saveSettings").its("response.statusCode").should("eq", 400);
+ H.undoToast().should("contain.text", "Used by remote synced content");
+ H.modal().should("not.exist");
+ });
+ });
+ });
});
describe("read-only mode", () => {
@@ -1019,3 +1112,62 @@ const ensureSyncedCollectionIsVisible = () => {
cy.findByRole("treeitem", { name: /Synced Collection/ }).should("exist");
});
};
+
+const createCollection = (name: string) =>
+ cy
+ .request<Collection>("POST", "/api/collection", { name })
+ .then(({ body }) => cy.wrap(body));
+
+// Saves, clears the toast and yields the refusal for inspection.
+const saveAndExpectRefusal = () => {
+ cy.findByRole("button", { name: "Save changes", timeout: 6000 })
+ .should("be.enabled")
+ .click(); // action button text
+ return cy.wait("@saveSettings").then((interception) => {
+ expect(interception.response?.statusCode).to.eq(400);
+ H.undoToast()
+ .should("contain.text", "Uses content that is not remote synced")
+ .icon("close")
+ .click();
+ return cy.wrap(interception, { log: false });
+ });
+};
+
+const createDependentQuestion = (
+ name: string,
+ sourceQuestionId: number,
+ collectionId: Collection["id"],
+) =>
+ H.createQuestion({
+ name,
+ query: { "source-table": `card__${sourceQuestionId}` },
+ collection_id: collectionId,
+ });
+
+// Two collections that each depend on a question in a third, so syncing either alone is refused.
+const createDependencyFixture = () =>
+ createCollection(SOURCE_COLLECTION_NAME).then((source) =>
+ createCollection(BLOCKED_COLLECTION_NAME).then((blocked) =>
+ createCollection(SECOND_BLOCKED_COLLECTION_NAME).then((alsoBlocked) =>
+ H.createQuestion({
+ name: SOURCE_QUESTION_NAME,
+ query: { "source-table": PRODUCTS_ID },
+ collection_id: source.id,
+ })
+ .then(({ body: sourceQuestion }) =>
+ createDependentQuestion(
+ DEPENDENT_QUESTION_NAME,
+ sourceQuestion.id,
+ blocked.id,
+ ).then(() =>
+ createDependentQuestion(
+ SECOND_DEPENDENT_QUESTION_NAME,
+ sourceQuestion.id,
+ alsoBlocked.id,
+ ),
+ ),
+ )
+ .then(() => ({ source, blocked, alsoBlocked })),
+ ),
+ ),
+ );
diff --git a/enterprise/backend/src/metabase_enterprise/remote_sync/api.clj b/enterprise/backend/src/metabase_enterprise/remote_sync/api.clj
index af362173d57..935d148f627 100644
--- a/enterprise/backend/src/metabase_enterprise/remote_sync/api.clj
+++ b/enterprise/backend/src/metabase_enterprise/remote_sync/api.clj
@@ -292,8 +292,10 @@
(remote-sync.core/bulk-set-remote-sync collections)
(catch Exception e
(throw (ex-info (or (ex-message e) "Invalid collection settings")
- {:error (ex-message e)
- :status-code 400} e)))))
+ (assoc (ex-data e)
+ :error (ex-message e)
+ :status-code 400)
+ e)))))
(events/publish-event! :event/remote-sync-settings-update
{:details {:remote-sync-type remote-sync-type}
:user-id api/*current-user-id*})
diff --git a/enterprise/backend/src/metabase_enterprise/remote_sync/core.clj b/enterprise/backend/src/metabase_enterprise/remote_sync/core.clj
index 686a9bdb248..e9fdf679760 100644
--- a/enterprise/backend/src/metabase_enterprise/remote_sync/core.clj
+++ b/enterprise/backend/src/metabase_enterprise/remote_sync/core.clj
@@ -10,6 +10,8 @@
[metabase.collections.core :as collections]
[metabase.events.core :as events]
[metabase.premium-features.core :refer [defenterprise]]
+ [metabase.util :as u]
+ [metabase.util.i18n :refer [tru]]
[metabase.util.malli :as mu]
[potemkin :as p]
[toucan2.core :as t2]))
@@ -160,6 +162,183 @@
:status_changed_at (t/offset-date-time)}
(spec/build-sync-object-fields spec entity)))))
+(defn- collections-by-id
+ "`{id collection}` for `ids`, carrying the fields the failure descriptions need. Nil and duplicate ids
+ are tolerated so callers can pass raw `:collection_id`s straight from the entities they described."
+ [ids]
+ (when-let [ids (not-empty (disj (set ids) nil))]
+ (t2/select-pk->fn identity [:model/Collection :id :name :location :personal_owner_id] :id [:in ids])))
+
+(defn- top-level-ancestor-id
+ "Id of the outermost collection containing `collection`."
+ [{:keys [id location]}]
+ (or (first (collections/location-path->ids location)) id))
+
+(def ^:private model-name->collection-item-model
+ "Toucan model name -> the model string the collections API uses for the same entity, so clients can
+ reuse their existing icon, label and link handling."
+ {"Card" "card"
+ "Collection" "collection"
+ "Dashboard" "dashboard"
+ "Document" "document"
+ "NativeQuerySnippet" "snippet"
+ "Timeline" "timeline"})
+
+(defn- dependency-item-model
+ "The model string clients should use for `model-name`. Anything outside
+ [[model-name->collection-item-model]] degrades to the lowercased Toucan name — the convention the rest
+ of the remote-sync API already uses for entities the collections API has no item model for — so this
+ never puts a `nil` model on the wire."
+ [model-name]
+ (get model-name->collection-item-model model-name (u/lower-case-en model-name)))
+
+(defn- entity-names
+ "`{[model-name id] name}` for `entities`. A separate select rather than widening the eligibility select,
+ which is shared with the dependents path and sees models that have no `:name`."
+ [entities]
+ (into {}
+ (for [[model-name group] (group-by :model entities)
+ row (t2/select [(keyword "model" model-name) :id :name] :id [:in (map :id group)])]
+ [[model-name (:id row)] (:name row)])))
+
+(defn- card-item-models
+ "`{card-id model}` for the Cards in `entities` — only their `type` separates questions from models and
+ metrics, and the eligibility select doesn't carry it."
+ [entities]
+ (when-let [ids (seq (keep #(when (= "Card" (:model %)) (:id %)) entities))]
+ (into {}
+ (map (fn [{:keys [id type]}]
+ [id (case (keyword type)
+ :model "dataset"
+ :metric "metric"
+ "card")]))
+ ;; :card_schema is required alongside :type — selecting it runs Card's schema upgrades.
+ (t2/select [:model/Card :id :type :card_schema] :id [:in ids]))))
+
+(defn- describe-entities
+ "`[{:model :id :name}]` for `entities`, which are `{:model \"Card\" :id 412}` maps, in the order given."
+ [entities]
+ (let [names (entity-names entities)
+ card-models (card-item-models entities)]
+ (mapv (fn [{:keys [model id]}]
+ {:model (if (= "Card" model)
+ (get card-models id "card")
+ (dependency-item-model model))
+ :id id
+ :name (get names [model id])})
+ entities)))
+
+(defn- sync-remedy
+ "What an admin would have to sync for `dep` to be covered: a specific top-level collection, or the
+ Library for models whose eligibility keys on it (snippets) rather than on their own collection.
+ `:none` when the dependency lives outside any collection."
+ [{:keys [model instance]} collections top-levels]
+ (let [top (some->> (:collection_id instance)
+ (get collections)
+ top-level-ancestor-id
+ (get top-levels))]
+ (cond
+ (= :library-synced (get-in (spec/spec-for-model-key (keyword "model" model)) [:eligibility :type]))
+ {:type :library}
+
+ top
+ {:type :collection
+ :collection {:id (:id top)
+ :name (:name top)
+ :personal (some? (:personal_owner_id top))}}
+
+ :else
+ {:type :none})))
+
+(defn- dependency-collection
+ "Where the dependency lives, as a map to merge into its description. An explicit `nil` says the root
+ collection — a real place, not a missing value — while an absent key says we could not resolve the
+ collection at all, so clients don't read one as the other."
+ [{:keys [collection_id]} collections]
+ (if collection_id
+ (when-let [collection (get collections collection_id)]
+ {:collection (select-keys collection [:id :name])})
+ {:collection nil}))
+
+(defn- describe-dependencies
+ "Renders [[collections/ineligible-dependencies]] for the API: what each dependency is, the collection it
+ lives in, and the collection (or the Library) that would have to be synced to cover it."
+ [deps]
+ (let [collections (collections-by-id (map (comp :collection_id :instance) deps))
+ top-levels (collections-by-id (map top-level-ancestor-id (vals collections)))]
+ (mapv (fn [described {:keys [instance] :as dep}]
+ (merge described
+ {:remedy (sync-remedy dep collections top-levels)}
+ (dependency-collection instance collections)))
+ (describe-entities deps)
+ deps)))
+
+(defn- describe-dependents
+ "Renders [[collections/remote-synced-dependents]] for the API. Each dependent arrives as a path map like
+ `{\"DashboardCard\" 12 \"Dashboard\" 3}`; every entry an admin can actually open is reported, and the
+ nested models (DashboardCard, DashboardCardSeries, Action) fall away — they have no name of their own,
+ and the parent that does is in the same path."
+ [dependents]
+ (describe-entities
+ (vec (distinct (for [dependent dependents
+ [model-name id] dependent
+ :when (contains? model-name->collection-item-model model-name)]
+ {:model model-name :id id})))))
+
+(defn- unsynced-dependency-failures
+ "For each collection being synced on, the dependencies that syncing it would leave outside remote sync.
+ Unlike [[collections/check-non-remote-synced-dependencies]] this reports every offending collection
+ rather than throwing on the first, so an admin sees the whole picture in one pass. Realized eagerly:
+ eligibility only reads correctly against the pending updates, so nothing may be left for
+ [[describe-dependency-failure]] to force after the transaction rolls back."
+ [collections-to-sync]
+ (vec
+ (for [collection collections-to-sync
+ :let [deps (collections/ineligible-dependencies collection)]
+ :when (seq deps)]
+ {:collection collection :dependencies deps})))
+
+(defn- remote-synced-dependent-failure
+ "The first collection being synced off that remote-synced content still depends on, if any. Stops at the
+ first, unlike [[unsynced-dependency-failures]]: every [[collections/remote-synced-dependents]] call
+ traverses every remote-synced root, and the admin's remedy is the same however many collections are at
+ fault — leave them synced."
+ [collections-to-unsync]
+ (first
+ (for [collection collections-to-unsync
+ :let [dependents (collections/remote-synced-dependents collection)]
+ :when (seq dependents)]
+ {:collection collection :dependents (vec dependents)})))
+
+(defn- describe-dependency-failure
+ [{:keys [collection dependencies]}]
+ {:collection (select-keys collection [:id :name])
+ :dependencies (describe-dependencies dependencies)})
+
+(defn- describe-dependent-failure
+ [{:keys [collection dependents]}]
+ {:collection (select-keys collection [:id :name])
+ :dependents (describe-dependents dependents)})
+
+(defn- rejection
+ "Turns the marker [[bulk-set-remote-sync]] throws out of its transaction into the 400 the API returns.
+ Describing a failure takes several more selects, and they run here — after the rollback — rather than
+ under the row locks the transaction was holding. Returns nil for anything else, which propagates as-is."
+ [e]
+ (let [{::keys [unsynced-dependencies remote-synced-dependents]} (ex-data e)]
+ (cond
+ unsynced-dependencies
+ (ex-info (ex-message e)
+ {:status-code 400
+ :error_code "unsynced-dependencies"
+ :errors {:collections (mapv describe-dependency-failure unsynced-dependencies)}})
+
+ remote-synced-dependents
+ (ex-info (ex-message e)
+ {:status-code 400
+ :error_code "remote-synced-dependents"
+ :errors {:collections [(describe-dependent-failure remote-synced-dependents)]}}))))
+
(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."
@@ -175,34 +354,39 @@
(t2/select :model/Collection :id [:in sync-on])))
(update :sync-off #(when-let [sync-off (seq %)]
(t2/select :model/Collection :id [:in sync-off]))))]
- (t2/with-transaction [_]
- (when (seq sync-on)
- (t2/query {:update (t2/table-name :model/Collection)
- :set {:is_remote_synced true}
- :where [:and
- [:= :is_remote_synced false]
- (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]
- (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]})
- (record-removed-rsos! affected-collection-ids))))
- (doseq [collection sync-on]
- (collections/check-non-remote-synced-dependencies collection))
- (doseq [collection sync-off]
- (collections/check-remote-synced-dependents collection)))
+ (try
+ (t2/with-transaction [_]
+ (when (seq sync-on)
+ (t2/query {:update (t2/table-name :model/Collection)
+ :set {:is_remote_synced true}
+ :where [:and
+ [:= :is_remote_synced false]
+ (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]
+ (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]})
+ (record-removed-rsos! affected-collection-ids))))
+ (when-let [failures (not-empty (unsynced-dependency-failures sync-on))]
+ (throw (ex-info (tru "Uses content that is not remote synced.")
+ {::unsynced-dependencies failures})))
+ (when-let [failure (remote-synced-dependent-failure sync-off)]
+ (throw (ex-info (tru "Used by remote synced content.")
+ {::remote-synced-dependents failure}))))
+ (catch clojure.lang.ExceptionInfo e
+ (throw (or (rejection e) e))))
(doseq [collection sync-on
;; only publish event when this changed
:when (not (:is_remote_synced collection))]
diff --git a/enterprise/backend/test/metabase_enterprise/remote_sync/api_test.clj b/enterprise/backend/test/metabase_enterprise/remote_sync/api_test.clj
index 27952cf7210..664b2823c8d 100644
--- a/enterprise/backend/test/metabase_enterprise/remote_sync/api_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/remote_sync/api_test.clj
@@ -1186,7 +1186,22 @@
impl/finish-remote-config! (constantly nil)]
(let [response (mt/user-http-request :crowberto :put 400 "ee/remote-sync/settings"
{:collections {remote-synced-coll-id true}})]
- (is (= "Uses content that is not remote synced." (:error response)))))))))
+ (is (= "Uses content that is not remote synced." (:error response)))
+ (testing "the structured failure survives the endpoint's rewrap, keyed by error_code"
+ (is (=? {:error_code "unsynced-dependencies"
+ :errors {:collections [{:collection {:id remote-synced-coll-id :name "Remote Synced"}
+ :dependencies [{:model "card"
+ :id source-card-id
+ :name "Source Card"
+ :collection {:id regular-coll-id :name "Regular"}
+ :remedy {:type "collection"
+ :collection {:id regular-coll-id
+ :name "Regular"
+ :personal false}}}]}]}}
+ response)))
+ (testing "the body is the ex-data itself, not a stacktrace dump"
+ (is (nil? (:trace response)))
+ (is (nil? (:via response))))))))))
(deftest settings-collections-errors-on-remote-synced-dependents-test
(testing "PUT /api/ee/remote-sync/settings with collections errors when disabling a collection that has remote-synced dependents"
@@ -1205,7 +1220,16 @@
impl/finish-remote-config! (constantly nil)]
(let [response (mt/user-http-request :crowberto :put 400 "ee/remote-sync/settings"
{:collections {coll1-id false}})]
- (is (= "Used by remote synced content." (:error response)))))))))
+ (is (= "Used by remote synced content." (:error response)))
+ (testing "the structured failure survives the endpoint's rewrap, keyed by error_code"
+ (is (=? {:error_code "remote-synced-dependents"
+ :errors {:collections [{:collection {:id coll1-id :name "Collection 1"}
+ :dependents [{:model "card"
+ :name "Dependent Card"}]}]}}
+ response)))
+ (testing "the body is the ex-data itself, not a stacktrace dump"
+ (is (nil? (:trace response)))
+ (is (nil? (:via response))))))))))
(deftest settings-collections-empty-is-no-op-test
(testing "PUT /api/ee/remote-sync/settings with empty collections is a no-op"
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 099f8aaf08b..2345b5d9a21 100644
--- a/enterprise/backend/test/metabase_enterprise/remote_sync/core_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/remote_sync/core_test.clj
@@ -85,6 +85,174 @@
#"Uses content that is not remote synced"
(core/bulk-set-remote-sync {remote-synced-coll-id true}))))))
+(deftest bulk-set-remote-sync-dependency-failure-names-both-collections-test
+ (testing "the failure names the collection we tried to sync and the collection that must be synced too"
+ (mt/with-temp [:model/Collection {synced-id :id} {:name "Synced" :location "/" :is_remote_synced false}
+ :model/Collection {regular-id :id} {:name "Regular" :location "/" :is_remote_synced false}
+ :model/Card {source-card-id :id} {:name "Source Card"
+ :collection_id regular-id
+ :database_id (mt/id)
+ :dataset_query (mt/mbql-query venues)}
+ :model/Card _ {:name "Dependent Card"
+ :collection_id synced-id
+ :database_id (mt/id)
+ :dataset_query (mt/mbql-query nil {:source-table (str "card__" source-card-id)})}]
+ (let [ex (is (thrown? clojure.lang.ExceptionInfo
+ (core/bulk-set-remote-sync {synced-id true})))]
+ (is (=? {:status-code 400
+ :errors {:collections [{:collection {:id synced-id :name "Synced"}
+ :dependencies [{:model "card"
+ :id source-card-id
+ :name "Source Card"
+ :collection {:id regular-id :name "Regular"}
+ :remedy {:type :collection
+ :collection {:id regular-id
+ :name "Regular"
+ :personal false}}}]}]}}
+ (ex-data ex)))))))
+
+(deftest bulk-set-remote-sync-dependency-model-follows-card-type-test
+ (testing "a Card dependency reports the collection-item model its type implies, not the Toucan name"
+ (doseq [[card-type expected] {:model "dataset"
+ :metric "metric"}]
+ (testing (str "a " card-type " reports as " expected)
+ (mt/with-temp [:model/Collection {synced-id :id} {:name "Synced" :location "/" :is_remote_synced false}
+ :model/Collection {regular-id :id} {:name "Regular" :location "/" :is_remote_synced false}
+ :model/Card {source-card-id :id} {:name "Source"
+ :type card-type
+ :collection_id regular-id
+ :database_id (mt/id)
+ :dataset_query (mt/mbql-query venues)}
+ :model/Card _ {:name "Dependent Card"
+ :collection_id synced-id
+ :database_id (mt/id)
+ :dataset_query (mt/mbql-query nil {:source-table (str "card__" source-card-id)})}]
+ (let [ex (is (thrown? clojure.lang.ExceptionInfo
+ (core/bulk-set-remote-sync {synced-id true})))]
+ (is (=? {:errors {:collections [{:dependencies [{:model expected
+ :id source-card-id}]}]}}
+ (ex-data ex)))))))))
+
+(deftest bulk-set-remote-sync-dependency-remedy-is-top-level-ancestor-test
+ (testing "the remedy names the top-level collection settings can toggle, not the dependency's sub-collection"
+ (mt/with-temp [:model/Collection {synced-id :id} {:name "Synced" :location "/" :is_remote_synced false}
+ :model/Collection {root-id :id} {:name "Root Regular" :location "/" :is_remote_synced false}
+ :model/Collection {child-id :id} {:name "Nested"
+ :location (format "/%d/" root-id)
+ :is_remote_synced false}
+ :model/Card {source-card-id :id} {:name "Source Card"
+ :collection_id child-id
+ :database_id (mt/id)
+ :dataset_query (mt/mbql-query venues)}
+ :model/Card _ {:name "Dependent Card"
+ :collection_id synced-id
+ :database_id (mt/id)
+ :dataset_query (mt/mbql-query nil {:source-table (str "card__" source-card-id)})}]
+ (let [ex (is (thrown? clojure.lang.ExceptionInfo
+ (core/bulk-set-remote-sync {synced-id true})))]
+ (is (=? {:errors {:collections [{:dependencies [{:id source-card-id
+ :collection {:id child-id :name "Nested"}
+ :remedy {:type :collection
+ :collection {:id root-id :name "Root Regular"}}}]}]}}
+ (ex-data ex)))))))
+
+(deftest bulk-set-remote-sync-root-dependency-collection-is-explicit-nil-test
+ (testing "a dependency in the root collection reports `:collection nil` — the root is a place, not a missing value"
+ (mt/with-temp [:model/Collection {synced-id :id} {:name "Synced" :location "/" :is_remote_synced false}
+ :model/Card {source-card-id :id} {:name "Root Card"
+ :collection_id nil
+ :database_id (mt/id)
+ :dataset_query (mt/mbql-query venues)}
+ :model/Card _ {:name "Dependent Card"
+ :collection_id synced-id
+ :database_id (mt/id)
+ :dataset_query (mt/mbql-query nil {:source-table (str "card__" source-card-id)})}]
+ (let [ex (is (thrown? clojure.lang.ExceptionInfo
+ (core/bulk-set-remote-sync {synced-id true})))
+ [dep] (get-in (ex-data ex) [:errors :collections 0 :dependencies])]
+ (is (= source-card-id (:id dep)))
+ (is (= {:type :none} (:remedy dep)))
+ (testing "the key is present and nil, so clients can tell root from unresolvable"
+ (is (contains? dep :collection))
+ (is (nil? (:collection dep))))))))
+
+(deftest bulk-set-remote-sync-snippet-dependency-remedy-is-library-test
+ (testing "a snippet dependency asks for Library sync — its eligibility keys on the Library, not its collection"
+ (with-library-not-synced
+ (mt/with-temp [:model/Collection {synced-id :id} {:name "Synced" :location "/" :is_remote_synced false}
+ :model/NativeQuerySnippet {snippet-id :id} {:name "active_users" :content "1 = 1"}
+ :model/Card _ {:name "Snippet Card"
+ :collection_id synced-id
+ :database_id (mt/id)
+ :dataset_query (mt/native-query
+ {:query "SELECT 1 WHERE {{snippet: active_users}}"
+ :template-tags {"snippet: active_users"
+ {:snippet-id snippet-id
+ :snippet-name "active_users"
+ :type :snippet
+ :name "snippet: active_users"
+ :display-name "Snippet: Active Users"
+ :id (str (random-uuid))}}})}]
+ (let [ex (is (thrown? clojure.lang.ExceptionInfo
+ (core/bulk-set-remote-sync {synced-id true})))]
+ (is (=? {:errors {:collections [{:dependencies [{:model "snippet"
+ :id snippet-id
+ :name "active_users"
+ :remedy {:type :library}}]}]}}
+ (ex-data ex))))))))
+
+(deftest bulk-set-remote-sync-reports-every-failing-collection-test
+ (testing "every collection with unsynced dependencies is reported, not just the first to fail"
+ (mt/with-temp [:model/Collection {synced-a-id :id} {:name "Synced A" :location "/" :is_remote_synced false}
+ :model/Collection {synced-b-id :id} {:name "Synced B" :location "/" :is_remote_synced false}
+ :model/Collection {regular-id :id} {:name "Regular" :location "/" :is_remote_synced false}
+ :model/Card {source-card-id :id} {:name "Source Card"
+ :collection_id regular-id
+ :database_id (mt/id)
+ :dataset_query (mt/mbql-query venues)}
+ :model/Card _ {:name "Dependent A"
+ :collection_id synced-a-id
+ :database_id (mt/id)
+ :dataset_query (mt/mbql-query nil {:source-table (str "card__" source-card-id)})}
+ :model/Card _ {:name "Dependent B"
+ :collection_id synced-b-id
+ :database_id (mt/id)
+ :dataset_query (mt/mbql-query nil {:source-table (str "card__" source-card-id)})}]
+ (let [ex (is (thrown? clojure.lang.ExceptionInfo
+ (core/bulk-set-remote-sync {synced-a-id true synced-b-id true})))]
+ (is (= #{"Synced A" "Synced B"}
+ (into #{} (map (comp :name :collection)) (get-in (ex-data ex) [:errors :collections]))))))))
+
+(deftest bulk-set-remote-sync-dependent-failure-is-structured-test
+ (testing "disabling a collection something still depends on fails with a structured payload, not a bare message"
+ (mt/with-temp [:model/Collection {coll1-id :id} {:name "Collection 1" :location "/" :is_remote_synced true}
+ :model/Collection {coll2-id :id} {:name "Collection 2" :location "/" :is_remote_synced true}
+ :model/Card {source-card-id :id} {:name "Source Card"
+ :collection_id coll1-id
+ :database_id (mt/id)
+ :dataset_query (mt/mbql-query venues)}
+ :model/Card {dependent-card-id :id} {:name "Dependent Card"
+ :collection_id coll2-id
+ :database_id (mt/id)
+ :dataset_query (mt/mbql-query nil {:source-table (str "card__" source-card-id)})}]
+ (let [ex (is (thrown? clojure.lang.ExceptionInfo
+ (core/bulk-set-remote-sync {coll1-id false})))]
+ (is (=? {:status-code 400
+ :error_code "remote-synced-dependents"
+ :errors {:collections [{:collection {:id coll1-id :name "Collection 1"}}]}}
+ (ex-data ex)))
+ (testing "the dependents are named, and nested models resolve to something an admin can open"
+ (is (contains? (into #{}
+ (get-in (ex-data ex) [:errors :collections 0 :dependents]))
+ {:model "card" :id dependent-card-id :name "Dependent Card"})))))))
+
+(deftest dependency-item-model-never-nil-test
+ (testing "a model with no collections-API name degrades to its lowercased Toucan name, never nil"
+ (is (= "dashboard" (#'core/dependency-item-model "Dashboard")))
+ (is (= "snippet" (#'core/dependency-item-model "NativeQuerySnippet")))
+ (is (= "pulse" (#'core/dependency-item-model "Pulse")))
+ (is (= "exploration" (#'core/dependency-item-model "Exploration")))))
+
(deftest bulk-set-remote-sync-throws-on-remote-synced-dependents-test
(testing "bulk-set-remote-sync throws when disabling a collection that has remote-synced dependents"
(mt/with-temp [:model/Collection {coll1-id :id} {:name "Collection 1" :location "/" :is_remote_synced true}
diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/RemoteSyncDependencyModal.module.css b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/RemoteSyncDependencyModal.module.css
new file mode 100644
index 00000000000..0271d58c3b7
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/RemoteSyncDependencyModal.module.css
@@ -0,0 +1,7 @@
+.collectionRow {
+ border-bottom: 1px solid var(--mb-color-border);
+
+ &:last-child {
+ border-bottom: none;
+ }
+}
diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/RemoteSyncDependencyModal.tsx b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/RemoteSyncDependencyModal.tsx
new file mode 100644
index 00000000000..3451ba2d05a
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/RemoteSyncDependencyModal.tsx
@@ -0,0 +1,122 @@
+import { useFormikContext } from "formik";
+import { useState } from "react";
+import { t } from "ttag";
+
+import { Button, Card, Group, Icon, Modal, Stack, Text } from "metabase/ui";
+import type { RemoteSyncDependencyFailure } from "metabase-types/api";
+
+import { COLLECTIONS_KEY } from "../../constants";
+import type { RemoteSyncSettingsFormState } from "../../types";
+import {
+ canSyncRequiredCollections,
+ getBlockedMessage,
+ getRequiredCollectionRows,
+ getRequiredCollections,
+} from "../../utils";
+
+import S from "./RemoteSyncDependencyModal.module.css";
+
+interface RemoteSyncDependencyModalProps {
+ /** Why the last save was refused, one entry per collection. */
+ failures?: RemoteSyncDependencyFailure[];
+}
+
+export const RemoteSyncDependencyModal = ({
+ failures,
+}: RemoteSyncDependencyModalProps) => {
+ const { values, setValues, submitForm } =
+ useFormikContext<RemoteSyncSettingsFormState>();
+ // RTK returns a new error object per request, so identity separates fresh from dismissed.
+ const [dismissedFailures, setDismissedFailures] =
+ useState<RemoteSyncDependencyFailure[]>();
+
+ if (!failures?.length || failures === dismissedFailures) {
+ return null;
+ }
+
+ // Rows are for display and can include Our analytics; only real remedies are safe to switch on.
+ const requiredCollections = getRequiredCollections(failures);
+ const requiredCollectionRows = getRequiredCollectionRows(failures);
+ const canSync = canSyncRequiredCollections(failures);
+
+ const handleDismiss = () => setDismissedFailures(failures);
+
+ const handleSyncAndSave = async () => {
+ await setValues({
+ ...values,
+ [COLLECTIONS_KEY]: {
+ ...values[COLLECTIONS_KEY],
+ ...Object.fromEntries(requiredCollections.map(({ id }) => [id, true])),
+ },
+ });
+ await submitForm();
+ };
+
+ return (
+ <Modal
+ opened
+ onClose={handleDismiss}
+ padding="xl"
+ title={
+ canSync
+ ? t`Sync collections with dependencies?`
+ : t`Couldn’t sync selected collection`
+ }
+ >
+ <Stack gap="lg" pt="md">
+ <Text>{getBlockedMessage(failures)}</Text>
+
+ {requiredCollectionRows.length > 0 && (
+ <Card withBorder p={0} shadow="none">
+ <Stack gap={0}>
+ {requiredCollectionRows.map((collection) => (
+ <Group
+ key={collection.id}
+ gap="sm"
+ className={S.collectionRow}
+ py="sm"
+ px="md"
+ justify="space-between"
+ bg={collection.syncable ? undefined : "background-secondary"}
+ >
+ <Group>
+ <Icon
+ name={collection.personal ? "person" : "collection"}
+ c="text-secondary"
+ />
+ <Text fw="medium">{collection.name}</Text>
+ </Group>
+ {collection.syncable ? (
+ <Group gap="sm">
+ <Icon name="warning_triangle_filled" c="warning" />
+ <Text c="feedback-warning-strong">{t`Sync to continue`}</Text>
+ </Group>
+ ) : (
+ <Text c="text-secondary">{t`Can't be synced`}</Text>
+ )}
+ </Group>
+ ))}
+ </Stack>
+ </Card>
+ )}
+
+ <Group justify={canSync ? "space-between" : "end"} gap="sm">
+ <>
+ {canSync && (
+ <Button onClick={handleSyncAndSave}>
+ {t`Sync required collections`}
+ </Button>
+ )}
+ <Button
+ variant="filled"
+ onClick={handleDismiss}
+ style={{ justifySelf: "end" }}
+ >
+ {canSync ? t`Cancel` : t`Back`}
+ </Button>
+ </>
+ </Group>
+ </Stack>
+ </Modal>
+ );
+};
diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/RemoteSyncDependencyModal.unit.spec.tsx b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/RemoteSyncDependencyModal.unit.spec.tsx
new file mode 100644
index 00000000000..10a5f4ebfd1
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/RemoteSyncDependencyModal.unit.spec.tsx
@@ -0,0 +1,301 @@
+import userEvent from "@testing-library/user-event";
+import fetchMock from "fetch-mock";
+
+import { findRequests } from "__support__/server-mocks";
+import { screen, waitFor, within } from "__support__/ui";
+import type {
+ RemoteSyncDependencyErrorResponse,
+ RemoteSyncIneligibleDependency,
+} from "metabase-types/api";
+import { createMockCollectionItemFromCollection } from "metabase-types/api/mocks";
+
+import { setup } from "./RemoteSyncSettingsForm.setup.spec";
+
+const BLOCKED_COLLECTION = { id: 20, name: "Marketing" };
+const REQUIRED_COLLECTION = { id: 30, name: "Finance" };
+
+const SYNCABLE_DEPENDENCY: RemoteSyncIneligibleDependency = {
+ model: "card",
+ id: 416,
+ name: "Seats over time",
+ collection: REQUIRED_COLLECTION,
+ remedy: {
+ type: "collection",
+ collection: { ...REQUIRED_COLLECTION, personal: false },
+ },
+};
+
+const PERSONAL_DEPENDENCY: RemoteSyncIneligibleDependency = {
+ model: "card",
+ id: 417,
+ name: "Draft",
+ collection: REQUIRED_COLLECTION,
+ remedy: {
+ type: "collection",
+ collection: { id: 5, name: "Nick's stuff", personal: true },
+ },
+};
+
+// `collection: null` is the root collection
+const ROOT_DEPENDENCY: RemoteSyncIneligibleDependency = {
+ model: "card",
+ id: 512,
+ name: "Orphaned",
+ collection: null,
+ remedy: { type: "none" },
+};
+
+// The backend sends no id for the Library, so there is nothing to switch on.
+const SNIPPET_DEPENDENCY: RemoteSyncIneligibleDependency = {
+ model: "snippet",
+ id: 3,
+ name: "active_users",
+ remedy: { type: "library" },
+};
+
+const createRefusal = (
+ ...dependencies: RemoteSyncIneligibleDependency[]
+): RemoteSyncDependencyErrorResponse => ({
+ error: "Uses content that is not remote synced.",
+ error_code: "unsynced-dependencies",
+ errors: {
+ collections: [{ collection: BLOCKED_COLLECTION, dependencies }],
+ },
+});
+
+// First save is refused with `body`; any retry succeeds, so the second PUT shows what the modal sent.
+const setupRefusedSave = async ({
+ body = createRefusal(SYNCABLE_DEPENDENCY),
+}: { body?: RemoteSyncDependencyErrorResponse } = {}) => {
+ setup({
+ remoteSyncType: "read-write",
+ remoteSyncUrl: "https://github.com/test/repo.git",
+ remoteSyncEnabled: true,
+ rootCollectionItems: [
+ createMockCollectionItemFromCollection({
+ ...BLOCKED_COLLECTION,
+ is_remote_synced: false,
+ can_write: true,
+ }),
+ createMockCollectionItemFromCollection({
+ ...REQUIRED_COLLECTION,
+ is_remote_synced: false,
+ can_write: true,
+ }),
+ ],
+ });
+
+ let putCount = 0;
+ fetchMock.removeRoute("remote-sync-settings");
+ fetchMock.put(
+ "path:/api/ee/remote-sync/settings",
+ () => {
+ putCount += 1;
+ return putCount === 1 ? { status: 400, body } : { success: true };
+ },
+ { name: "remote-sync-settings" },
+ );
+
+ await waitFor(() => {
+ expect(screen.getByLabelText("Read-write")).toBeChecked();
+ });
+
+ await userEvent.click(
+ screen.getByLabelText(`Sync ${BLOCKED_COLLECTION.name}`),
+ );
+ await userEvent.click(screen.getByRole("button", { name: /Save changes/i }));
+};
+
+// The modal asks a question when it can act, and reports a failure when it can't.
+const expectFixOffered = (modal: HTMLElement) => {
+ expect(
+ within(modal).getByText("Sync collections with dependencies?"),
+ ).toBeInTheDocument();
+ expect(
+ within(modal).getByRole("button", { name: "Sync required collections" }),
+ ).toBeInTheDocument();
+ expect(
+ within(modal).getByRole("button", { name: "Cancel" }),
+ ).toBeInTheDocument();
+};
+
+const expectNoFixOffered = (modal: HTMLElement) => {
+ expect(
+ within(modal).getByText(/Couldn.t sync selected collection/),
+ ).toBeInTheDocument();
+ expect(
+ within(modal).queryByRole("button", { name: "Sync required collections" }),
+ ).not.toBeInTheDocument();
+ expect(
+ within(modal).getByRole("button", { name: "Back" }),
+ ).toBeInTheDocument();
+};
+
+const getSettingsPuts = async () => {
+ const puts = await findRequests("PUT");
+ return puts.filter((request) =>
+ request.url.includes("/api/ee/remote-sync/settings"),
+ );
+};
+
+describe("RemoteSyncDependencyModal", () => {
+ it("opens when a save is refused, naming the collection that must be synced too", async () => {
+ await setupRefusedSave();
+
+ const modal = await screen.findByRole("dialog");
+ expectFixOffered(modal);
+ expect(
+ within(modal).getByText(/rely on data saved elsewhere/),
+ ).toBeInTheDocument();
+ expect(
+ within(modal).getByText(REQUIRED_COLLECTION.name),
+ ).toBeInTheDocument();
+ });
+
+ it("stays closed until a save is refused", async () => {
+ setup({
+ remoteSyncType: "read-write",
+ remoteSyncEnabled: true,
+ remoteSyncUrl: "https://github.com/test/repo.git",
+ });
+
+ await waitFor(() => {
+ expect(screen.getByLabelText("Read-write")).toBeChecked();
+ });
+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
+ });
+
+ it("switches the required collections on and saves them in one action", async () => {
+ await setupRefusedSave();
+
+ const modal = await screen.findByRole("dialog");
+ await userEvent.click(
+ within(modal).getByRole("button", { name: "Sync required collections" }),
+ );
+
+ await waitFor(async () => {
+ expect(await getSettingsPuts()).toHaveLength(2);
+ });
+
+ // The retry carries the collection the admin picked *and* the one the modal added — proof the
+ // save reads the flipped form state rather than the values that were refused.
+ const [, retry] = await getSettingsPuts();
+ expect(retry.body).toHaveProperty("collections", {
+ [BLOCKED_COLLECTION.id]: true,
+ [REQUIRED_COLLECTION.id]: true,
+ });
+ });
+
+ it("closes once the retry succeeds", async () => {
+ await setupRefusedSave();
+
+ const modal = await screen.findByRole("dialog");
+ await userEvent.click(
+ within(modal).getByRole("button", { name: "Sync required collections" }),
+ );
+
+ await waitFor(() => {
+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
+ });
+ });
+
+ it("stays closed after the admin dismisses it", async () => {
+ await setupRefusedSave();
+
+ const modal = await screen.findByRole("dialog");
+ await userEvent.click(
+ within(modal).getByRole("button", { name: "Cancel" }),
+ );
+
+ await waitFor(() => {
+ expect(screen.queryByRole("dialog")).not.toBeInTheDocument();
+ });
+ expect(await getSettingsPuts()).toHaveLength(1);
+ });
+
+ it("offers no fix when the blocking content sits in a personal collection", async () => {
+ await setupRefusedSave({ body: createRefusal(PERSONAL_DEPENDENCY) });
+
+ const modal = await screen.findByRole("dialog");
+ expect(
+ within(modal).getByText(/saved in a personal collection/),
+ ).toBeInTheDocument();
+ expectNoFixOffered(modal);
+ });
+
+ it("offers no fix when the blocking content sits in the root collection", async () => {
+ await setupRefusedSave({ body: createRefusal(ROOT_DEPENDENCY) });
+
+ const modal = await screen.findByRole("dialog");
+ expect(
+ within(modal).getByText(/can.t be synced where it currently lives/),
+ ).toBeInTheDocument();
+ expectNoFixOffered(modal);
+ });
+
+ it("lists Our analytics as unsyncable, rather than leaving the list empty", async () => {
+ await setupRefusedSave({
+ body: createRefusal(SYNCABLE_DEPENDENCY, ROOT_DEPENDENCY),
+ });
+
+ const modal = await screen.findByRole("dialog");
+ expect(within(modal).getByText("Our analytics")).toBeInTheDocument();
+ // The syncable remedy is still listed, but nothing here is actionable while the root one stands.
+ expect(
+ within(modal).getByText(REQUIRED_COLLECTION.name),
+ ).toBeInTheDocument();
+ expect(within(modal).getByText("Can't be synced")).toBeInTheDocument();
+ });
+
+ it("offers no fix when the dependency is a snippet, since the Library has no id to switch on", async () => {
+ await setupRefusedSave({ body: createRefusal(SNIPPET_DEPENDENCY) });
+
+ const modal = await screen.findByRole("dialog");
+ expect(
+ within(modal).getByText(/sync with the Library/),
+ ).toBeInTheDocument();
+ expectNoFixOffered(modal);
+ });
+
+ it("keeps the admin's selection after a refused save, so it can be retried", async () => {
+ await setupRefusedSave();
+
+ const modal = await screen.findByRole("dialog");
+ await userEvent.click(
+ within(modal).getByRole("button", { name: "Cancel" }),
+ );
+
+ // A refused save rolls back, so the collection list refetch it triggers must not reset the form.
+ await waitFor(async () => {
+ expect(await findRequests("GET")).toEqual(
+ expect.arrayContaining([
+ expect.objectContaining({
+ url: expect.stringContaining("/api/collection/root/items"),
+ }),
+ ]),
+ );
+ });
+
+ expect(
+ screen.getByLabelText(`Sync ${BLOCKED_COLLECTION.name}`),
+ ).toBeChecked();
+ // Enabled means still dirty; the button relabels to "Failed" after a rejected submit.
+ expect(screen.getByTestId("remote-sync-submit-button")).toBeEnabled();
+ });
+
+ // Switching Finance on would leave the other dependency behind, so the save is refused again.
+ it.each([
+ ["personal", PERSONAL_DEPENDENCY],
+ ["root", ROOT_DEPENDENCY],
+ ["snippet", SNIPPET_DEPENDENCY],
+ ])(
+ "offers no fix when a syncable dependency is joined by a %s one",
+ async (_label, dependency) => {
+ await setupRefusedSave({
+ body: createRefusal(SYNCABLE_DEPENDENCY, dependency),
+ });
+
+ expectNoFixOffered(await screen.findByRole("dialog"));
+ },
+ );
+});
diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/RemoteSyncSettingsForm.tsx b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/RemoteSyncSettingsForm.tsx
index aa0806e6694..f8b4c9d3f19 100644
--- a/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/RemoteSyncSettingsForm.tsx
+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/components/RemoteSyncAdminSettings/RemoteSyncSettingsForm.tsx
@@ -33,6 +33,7 @@ import { CollectionsToSyncSection } from "./CollectionsToSyncSection";
import { GitSettingsSection } from "./GitSettingsSection";
import { ReadOnlyBranchSection } from "./ReadOnlyBranchSection";
import { RemoteSyncConflictModal } from "./RemoteSyncConflictModal";
+import { RemoteSyncDependencyModal } from "./RemoteSyncDependencyModal";
import {
RemoteSyncSettingsSection,
RemoteSyncSettingsVariantProvider,
@@ -58,16 +59,22 @@ export const RemoteSyncSettingsForm = ({
});
const { initialValues, libraryCollection } =
useRemoteSyncInitialValues(variant);
- const { handleSubmit, branchChangeModal, isUpdating, isCreatingLibrary } =
- useRemoteSyncSubmit({
- initialValues,
- libraryCollection,
- onSaveSuccess,
- variant,
- });
+ const {
+ handleSubmit,
+ branchChangeModal,
+ isUpdating,
+ isCreatingLibrary,
+ unsyncedDependenciesError,
+ } = useRemoteSyncSubmit({
+ initialValues,
+ libraryCollection,
+ onSaveSuccess,
+ variant,
+ });
const { handleDisable, disableModal, isDisabling } = useDisableRemoteSync();
const dirtyEntities = dirtyData?.dirty ?? [];
+ const dependencyFailures = unsyncedDependenciesError?.errors.collections;
const isModalVariant = variant === "settings-modal";
const isSaving = isUpdating || isDisabling;
const canDisable =
@@ -151,6 +158,11 @@ export const RemoteSyncSettingsForm = ({
</Flex>
</Flex>
</Stack>
+
+ {/* Inside the form so its fix-and-save can write through formik; Mantine portals it out. */}
+ {!isModalVariant && (
+ <RemoteSyncDependencyModal failures={dependencyFailures} />
+ )}
</Form>
);
}}
diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/hooks/use-remote-sync-submit.ts b/enterprise/frontend/src/metabase-enterprise/remote_sync/hooks/use-remote-sync-submit.ts
index 2b41d915ec5..04daae54779 100644
--- a/enterprise/frontend/src/metabase-enterprise/remote_sync/hooks/use-remote-sync-submit.ts
+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/hooks/use-remote-sync-submit.ts
@@ -1,4 +1,4 @@
-import { useCallback, useRef } from "react";
+import { useCallback, useMemo, useRef } from "react";
import { t } from "ttag";
import { getErrorMessage } from "metabase/api/utils";
@@ -11,6 +11,7 @@ import type {
LibraryCollection,
RemoteSyncConfigurationSettings,
} from "metabase-types/api";
+import { isRemoteSyncDependencyError } from "metabase-types/guards";
import {
trackBranchSwitched,
@@ -47,8 +48,10 @@ export const useRemoteSyncSubmit = ({
}: UseRemoteSyncSubmitProps) => {
const isModalVariant = variant === "settings-modal";
const { data: settingValues } = useGetSettingsQuery();
- const [updateRemoteSyncSettings, { isLoading: isUpdating }] =
- useUpdateRemoteSyncSettingsMutation();
+ const [
+ updateRemoteSyncSettings,
+ { isLoading: isUpdating, error: updateError },
+ ] = useUpdateRemoteSyncSettingsMutation();
const [createLibrary, { isLoading: isCreatingLibrary }] =
useCreateLibraryMutation();
const [sendToast] = useToast();
@@ -137,7 +140,9 @@ export const useRemoteSyncSubmit = ({
message: getErrorMessage(error, t`Settings could not be saved`),
icon: "warning",
});
- throw error;
+ throw isRemoteSyncDependencyError(error)
+ ? { ...error, data: { ...error.data, errors: undefined } }
+ : error;
}
};
@@ -178,5 +183,17 @@ export const useRemoteSyncSubmit = ({
],
);
- return { handleSubmit, branchChangeModal, isUpdating, isCreatingLibrary };
+ const unsyncedDependenciesError = useMemo(
+ () =>
+ isRemoteSyncDependencyError(updateError) ? updateError.data : undefined,
+ [updateError],
+ );
+
+ return {
+ handleSubmit,
+ branchChangeModal,
+ isUpdating,
+ isCreatingLibrary,
+ unsyncedDependenciesError,
+ };
};
diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/hooks/use-remote-sync-submit.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/remote_sync/hooks/use-remote-sync-submit.unit.spec.ts
new file mode 100644
index 00000000000..a1900d42277
--- /dev/null
+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/hooks/use-remote-sync-submit.unit.spec.ts
@@ -0,0 +1,73 @@
+import fetchMock from "fetch-mock";
+
+import { setupPropertiesEndpoints } from "__support__/server-mocks";
+import { renderHookWithProviders, waitFor } from "__support__/ui";
+import type { RemoteSyncDependencyErrorResponse } from "metabase-types/api";
+import { createMockSettings } from "metabase-types/api/mocks";
+
+import { COLLECTIONS_KEY, TYPE_KEY, URL_KEY } from "../constants";
+
+import { useRemoteSyncSubmit } from "./use-remote-sync-submit";
+
+const UNSYNCED_DEPENDENCIES_BODY: RemoteSyncDependencyErrorResponse = {
+ error: "Uses content that is not remote synced.",
+ error_code: "unsynced-dependencies",
+ errors: {
+ collections: [
+ {
+ collection: { id: 14, name: "New Collection" },
+ dependencies: [
+ {
+ model: "card",
+ id: 416,
+ name: "Subscription seats over time",
+ collection: { id: 7, name: "Regular" },
+ remedy: {
+ type: "collection",
+ collection: { id: 7, name: "Regular", personal: false },
+ },
+ },
+ ],
+ },
+ ],
+ },
+};
+
+const setup = () => {
+ setupPropertiesEndpoints(createMockSettings());
+ fetchMock.put("path:/api/ee/remote-sync/settings", {
+ status: 400,
+ body: UNSYNCED_DEPENDENCIES_BODY,
+ });
+
+ return renderHookWithProviders(
+ () =>
+ useRemoteSyncSubmit({
+ initialValues: { [COLLECTIONS_KEY]: {} },
+ variant: "admin",
+ }),
+ {},
+ );
+};
+
+describe("useRemoteSyncSubmit", () => {
+ it("surfaces the unsynced-dependencies payload from a rejected save", async () => {
+ const { result } = setup();
+
+ expect(result.current.unsyncedDependenciesError).toBeUndefined();
+
+ await result.current
+ .handleSubmit({
+ [TYPE_KEY]: "read-write",
+ [URL_KEY]: "https://github.com/test/repo.git",
+ [COLLECTIONS_KEY]: { 14: true },
+ })
+ .catch(() => undefined);
+
+ await waitFor(() => {
+ expect(result.current.unsyncedDependenciesError).toEqual(
+ UNSYNCED_DEPENDENCIES_BODY,
+ );
+ });
+ });
+});
diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/utils.ts b/enterprise/frontend/src/metabase-enterprise/remote_sync/utils.ts
index 8dd987bc35f..5627ad18bd0 100644
--- a/enterprise/frontend/src/metabase-enterprise/remote_sync/utils.ts
+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/utils.ts
@@ -4,7 +4,9 @@ import type { ColorName } from "metabase/ui/colors/types";
import type {
Collection,
IconName,
+ RemoteSyncDependencyFailure,
RemoteSyncEntityStatus,
+ RemoteSyncRemedyCollection,
SettingDefinition,
} from "metabase-types/api";
@@ -166,6 +168,155 @@ export const parseSyncError = (exportError: SyncError | null): ParsedError => {
};
};
+// Deduped because remedies point at top-level collections, so dependencies collapse onto the same one.
+export const getRequiredCollections = (
+ failures: RemoteSyncDependencyFailure[],
+): RemoteSyncRemedyCollection[] => {
+ const collections = failures
+ .flatMap((failure) => failure.dependencies)
+ .flatMap((dependency) =>
+ dependency.remedy.type === "collection"
+ ? [dependency.remedy.collection]
+ : [],
+ );
+
+ const byId = new Map<number, RemoteSyncRemedyCollection>(
+ collections.map((collection) => [collection.id, collection]),
+ );
+
+ return [...byId.values()];
+};
+
+export const ROOT_COLLECTION_ROW_ID = "root";
+
+export type RequiredCollectionRow = {
+ id: number | typeof ROOT_COLLECTION_ROW_ID;
+ name: string;
+ personal: boolean;
+ syncable: boolean;
+};
+
+const getUnsyncableRows = (
+ failures: RemoteSyncDependencyFailure[],
+): RequiredCollectionRow[] => {
+ const rows = failures
+ .flatMap((failure) => failure.dependencies)
+ .filter((dependency) => dependency.remedy.type === "none")
+ .flatMap((dependency): RequiredCollectionRow[] => {
+ const { collection } = dependency;
+
+ // Absent means the backend couldn't resolve one, so there is nothing honest to name.
+ if (collection === undefined) {
+ return [];
+ }
+ return collection === null
+ ? [
+ {
+ id: ROOT_COLLECTION_ROW_ID,
+ name: t`Our analytics`,
+ personal: false,
+ syncable: false,
+ },
+ ]
+ : [{ ...collection, personal: false, syncable: false }];
+ });
+
+ return [...new Map(rows.map((row) => [row.id, row])).values()];
+};
+
+export const getRequiredCollectionRows = (
+ failures: RemoteSyncDependencyFailure[],
+): RequiredCollectionRow[] => [
+ ...getRequiredCollections(failures).map(({ id, name, personal }) => ({
+ id,
+ name,
+ personal,
+ syncable: !personal,
+ })),
+ ...getUnsyncableRows(failures),
+];
+
+// `every`, not `some`: one dependency we can't toggle makes this a partial fix, which is refused again.
+export const canSyncRequiredCollections = (
+ failures: RemoteSyncDependencyFailure[],
+): boolean =>
+ getRequiredCollections(failures).length > 0 &&
+ failures.every((failure) =>
+ failure.dependencies.every(
+ (dependency) =>
+ dependency.remedy.type === "collection" &&
+ !dependency.remedy.collection.personal,
+ ),
+ );
+
+export type BlockedReason =
+ | "personal-content"
+ | "unsyncable-content"
+ | "library"
+ | "linked-collections";
+
+// Ordered so content that can't be synced at all outranks content that can.
+export const getBlockedReason = (
+ failures: RemoteSyncDependencyFailure[],
+): BlockedReason => {
+ if (isBlockedByPersonalContent(failures)) {
+ return "personal-content";
+ }
+ if (requiresContentMove(failures)) {
+ return "unsyncable-content";
+ }
+ if (requiresLibrarySync(failures)) {
+ return "library";
+ }
+ return "linked-collections";
+};
+
+// `personal` sits on the remedy — the top-level ancestor — not the collection the dependency is in.
+const isBlockedByPersonalContent = (
+ failures: RemoteSyncDependencyFailure[],
+): boolean =>
+ failures.some((failure) =>
+ failure.dependencies.some(
+ (dependency) =>
+ dependency.remedy.type === "collection" &&
+ dependency.remedy.collection.personal,
+ ),
+ );
+
+const requiresLibrarySync = (
+ failures: RemoteSyncDependencyFailure[],
+): boolean =>
+ failures.some((failure) =>
+ failure.dependencies.some(
+ (dependency) => dependency.remedy.type === "library",
+ ),
+ );
+
+// A `none` remedy leaves nothing to switch on, so the content has to move instead.
+const requiresContentMove = (
+ failures: RemoteSyncDependencyFailure[],
+): boolean =>
+ failures.some((failure) =>
+ failure.dependencies.some(
+ (dependency) => dependency.remedy.type === "none",
+ ),
+ );
+
+export const getBlockedMessage = (
+ failures: RemoteSyncDependencyFailure[],
+): string => {
+ switch (getBlockedReason(failures)) {
+ case "personal-content":
+ return t`Dashboards or questions in this collection rely on content saved in a personal collection, which can’t be synced. Move that content to a shared collection to continue.`;
+ case "unsyncable-content":
+ return t`Dashboards or questions in this collection rely on content that can’t be synced where it currently lives. Move that content into a collection you’re syncing to continue.`;
+ case "library":
+ return t`Dashboards or questions in this collection rely on snippets, which sync with the Library. Sync the Library as well to continue.`;
+ case "linked-collections":
+ return t`Dashboards or questions in this collection rely on data saved elsewhere. To continue, sync those linked collections as well.`;
+ }
+};
+
export const buildCollectionMap = (
collectionTree: Collection[],
): Map<number, Collection> => {
diff --git a/enterprise/frontend/src/metabase-enterprise/remote_sync/utils.unit.spec.ts b/enterprise/frontend/src/metabase-enterprise/remote_sync/utils.unit.spec.ts
index f3de1146eab..3415a6d1a6c 100644
--- a/enterprise/frontend/src/metabase-enterprise/remote_sync/utils.unit.spec.ts
+++ b/enterprise/frontend/src/metabase-enterprise/remote_sync/utils.unit.spec.ts
@@ -1,8 +1,16 @@
+import type {
+ RemoteSyncDependencyFailure,
+ RemoteSyncIneligibleDependency,
+} from "metabase-types/api";
import { createMockCollection } from "metabase-types/api/mocks";
import {
buildCollectionMap,
+ canSyncRequiredCollections,
+ getBlockedReason,
getCollectionPathSegments,
+ getRequiredCollectionRows,
+ getRequiredCollections,
isTableChildModel,
} from "./utils";
@@ -218,4 +226,272 @@ describe("remote_sync utils", () => {
expect(isTableChildModel("dashboard")).toBe(false);
});
});
+
+ describe("unsynced dependency failures", () => {
+ // Two blocked collections whose dependencies resolve to the same remedy collection, plus a
+ // snippet (Library remedy) and a dependency with no actionable remedy.
+ const FAILURES: RemoteSyncDependencyFailure[] = [
+ {
+ collection: { id: 14, name: "Marketing" },
+ dependencies: [
+ {
+ model: "card",
+ id: 416,
+ name: "Seats over time",
+ collection: { id: 7, name: "Finance" },
+ remedy: {
+ type: "collection",
+ collection: { id: 7, name: "Finance", personal: false },
+ },
+ },
+ {
+ model: "snippet",
+ id: 3,
+ name: "active_users",
+ remedy: { type: "library" },
+ },
+ ],
+ },
+ {
+ collection: { id: 22, name: "Ops" },
+ dependencies: [
+ {
+ model: "dashboard",
+ id: 91,
+ name: "Weekly review",
+ collection: { id: 9, name: "Nested" },
+ // Same top-level remedy as the card above, reached from a different collection.
+ remedy: {
+ type: "collection",
+ collection: { id: 7, name: "Finance", personal: false },
+ },
+ },
+ {
+ model: "card",
+ id: 512,
+ name: "Orphaned",
+ remedy: { type: "none" },
+ },
+ ],
+ },
+ ];
+
+ describe("getRequiredCollections", () => {
+ it("flattens remedies across every failure and dedupes by id", () => {
+ expect(getRequiredCollections(FAILURES)).toEqual([
+ { id: 7, name: "Finance", personal: false },
+ ]);
+ });
+
+ it("ignores library and non-actionable remedies", () => {
+ const libraryOnly = [
+ {
+ collection: { id: 14, name: "Marketing" },
+ dependencies: [
+ {
+ model: "snippet" as const,
+ id: 3,
+ name: "active_users",
+ remedy: { type: "library" as const },
+ },
+ ],
+ },
+ ];
+
+ expect(getRequiredCollections(libraryOnly)).toEqual([]);
+ });
+
+ it("keeps personal collections so callers can flag them as unsyncable", () => {
+ const personal = [
+ {
+ collection: { id: 14, name: "Marketing" },
+ dependencies: [
+ {
+ model: "card" as const,
+ id: 1,
+ name: "Draft",
+ remedy: {
+ type: "collection" as const,
+ collection: { id: 5, name: "Nick's stuff", personal: true },
+ },
+ },
+ ],
+ },
+ ];
+
+ expect(getRequiredCollections(personal)).toEqual([
+ { id: 5, name: "Nick's stuff", personal: true },
+ ]);
+ });
+ });
+
+ const SYNCABLE_DEPENDENCY: RemoteSyncIneligibleDependency = {
+ model: "card",
+ id: 1,
+ name: "Seats over time",
+ remedy: {
+ type: "collection",
+ collection: { id: 7, name: "Finance", personal: false },
+ },
+ };
+ const PERSONAL_DEPENDENCY: RemoteSyncIneligibleDependency = {
+ model: "card",
+ id: 2,
+ name: "Draft",
+ remedy: {
+ type: "collection",
+ collection: { id: 5, name: "Personal", personal: true },
+ },
+ };
+ const ROOT_DEPENDENCY: RemoteSyncIneligibleDependency = {
+ model: "card",
+ id: 3,
+ name: "Orphaned",
+ collection: null,
+ remedy: { type: "none" },
+ };
+
+ // No remedy, but it does live somewhere — the backend couldn't resolve a syncable ancestor.
+ const UNRESOLVED_DEPENDENCY: RemoteSyncIneligibleDependency = {
+ model: "card",
+ id: 6,
+ name: "Stranded",
+ collection: { id: 9, name: "Dangling" },
+ remedy: { type: "none" },
+ };
+ const SNIPPET_DEPENDENCY: RemoteSyncIneligibleDependency = {
+ model: "snippet",
+ id: 4,
+ name: "active_users",
+ remedy: { type: "library" },
+ };
+
+ const failureWith = (
+ ...dependencies: RemoteSyncIneligibleDependency[]
+ ): RemoteSyncDependencyFailure[] => [
+ { collection: { id: 31, name: "Drafts" }, dependencies },
+ ];
+
+ describe("getBlockedReason", () => {
+ it("is linked-collections when every remedy is a collection the admin can sync", () => {
+ expect(getBlockedReason(failureWith(SYNCABLE_DEPENDENCY))).toBe(
+ "linked-collections",
+ );
+ });
+
+ it("is library when a dependency needs the Library", () => {
+ expect(
+ getBlockedReason(
+ failureWith(SYNCABLE_DEPENDENCY, SNIPPET_DEPENDENCY),
+ ),
+ ).toBe("library");
+ });
+
+ it("ranks root content above the Library, since it can't be synced at all", () => {
+ expect(
+ getBlockedReason(failureWith(SNIPPET_DEPENDENCY, ROOT_DEPENDENCY)),
+ ).toBe("unsyncable-content");
+ });
+
+ it("ranks personal content above every other reason", () => {
+ expect(
+ getBlockedReason(
+ failureWith(
+ SNIPPET_DEPENDENCY,
+ ROOT_DEPENDENCY,
+ PERSONAL_DEPENDENCY,
+ ),
+ ),
+ ).toBe("personal-content");
+ });
+ });
+
+ describe("getRequiredCollectionRows", () => {
+ it("marks a syncable remedy as actionable", () => {
+ expect(
+ getRequiredCollectionRows(failureWith(SYNCABLE_DEPENDENCY)),
+ ).toEqual([
+ { id: 7, name: "Finance", personal: false, syncable: true },
+ ]);
+ });
+
+ it("keeps a personal remedy in the list but not as actionable", () => {
+ expect(
+ getRequiredCollectionRows(failureWith(PERSONAL_DEPENDENCY)),
+ ).toEqual([
+ { id: 5, name: "Personal", personal: true, syncable: false },
+ ]);
+ });
+
+ it("names the collection a stranded dependency actually lives in", () => {
+ expect(
+ getRequiredCollectionRows(failureWith(UNRESOLVED_DEPENDENCY)),
+ ).toEqual([
+ { id: 9, name: "Dangling", personal: false, syncable: false },
+ ]);
+ });
+
+ it("adds Our analytics for a root dependency, which carries no remedy of its own", () => {
+ expect(getRequiredCollectionRows(failureWith(ROOT_DEPENDENCY))).toEqual(
+ [
+ {
+ id: "root",
+ name: "Our analytics",
+ personal: false,
+ syncable: false,
+ },
+ ],
+ );
+ });
+
+ it("lists the syncable remedy alongside Our analytics", () => {
+ expect(
+ getRequiredCollectionRows(
+ failureWith(SYNCABLE_DEPENDENCY, ROOT_DEPENDENCY),
+ ),
+ ).toEqual([
+ { id: 7, name: "Finance", personal: false, syncable: true },
+ {
+ id: "root",
+ name: "Our analytics",
+ personal: false,
+ syncable: false,
+ },
+ ]);
+ });
+
+ it("is empty when only the Library is implicated", () => {
+ expect(
+ getRequiredCollectionRows(failureWith(SNIPPET_DEPENDENCY)),
+ ).toEqual([]);
+ });
+ });
+
+ describe("canSyncRequiredCollections", () => {
+ it("is true when every dependency points at a collection we can switch on", () => {
+ expect(
+ canSyncRequiredCollections(failureWith(SYNCABLE_DEPENDENCY)),
+ ).toBe(true);
+ });
+
+ it.each([
+ ["personal", PERSONAL_DEPENDENCY],
+ ["root", ROOT_DEPENDENCY],
+ ["library", SNIPPET_DEPENDENCY],
+ ])(
+ "is false when a %s dependency rides along, since a half fix is refused again",
+ (_label, dependency) => {
+ expect(
+ canSyncRequiredCollections(
+ failureWith(SYNCABLE_DEPENDENCY, dependency),
+ ),
+ ).toBe(false);
+ },
+ );
+
+ it("is false when there is nothing to switch on", () => {
+ expect(canSyncRequiredCollections([])).toBe(false);
+ });
+ });
+ });
});
diff --git a/frontend/src/metabase-types/api/remote-sync.ts b/frontend/src/metabase-types/api/remote-sync.ts
index 26f2122804b..036d0837a79 100644
--- a/frontend/src/metabase-types/api/remote-sync.ts
+++ b/frontend/src/metabase-types/api/remote-sync.ts
@@ -1,3 +1,4 @@
+import type { CollectionItemModel } from "./collection";
import type { EnterpriseSettings } from "./settings";
import type { UserId } from "./user";
import type { CardDisplayType } from "./visualization";
@@ -135,6 +136,49 @@ export type UpdateRemoteSyncConfigurationResponse = {
task_id?: number;
};
+export type RemoteSyncDependencyModel = Extract<
+ CollectionItemModel,
+ "card" | "dataset" | "metric" | "dashboard" | "document" | "snippet"
+>;
+
+export type RemoteSyncCollectionRef = {
+ id: number;
+ name: string;
+};
+
+export type RemoteSyncRemedyCollection = RemoteSyncCollectionRef & {
+ personal: boolean;
+};
+
+export type RemoteSyncDependencyRemedy =
+ | { type: "collection"; collection: RemoteSyncRemedyCollection }
+ | { type: "library" }
+ | { type: "none" };
+
+export type RemoteSyncIneligibleDependency = {
+ model: RemoteSyncDependencyModel;
+ id: number;
+ name: string;
+ /** `null` is the root collection; absent means the backend couldn't resolve one. */
+ collection?: RemoteSyncCollectionRef | null;
+ remedy: RemoteSyncDependencyRemedy;
+};
+
+export type RemoteSyncDependencyFailure = {
+ collection: RemoteSyncCollectionRef;
+ dependencies: RemoteSyncIneligibleDependency[];
+};
+
+export const UNSYNCED_DEPENDENCIES_ERROR_CODE = "unsynced-dependencies";
+
+export type RemoteSyncDependencyErrorResponse = {
+ error_code: typeof UNSYNCED_DEPENDENCIES_ERROR_CODE;
+ error: string;
+ errors: {
+ collections: RemoteSyncDependencyFailure[];
+ };
+};
+
export type RemoteSyncTaskStatus =
| "running"
| "successful"
diff --git a/frontend/src/metabase-types/guards/index.ts b/frontend/src/metabase-types/guards/index.ts
index fd5dc4159a5..08cf1fb10c7 100644
--- a/frontend/src/metabase-types/guards/index.ts
+++ b/frontend/src/metabase-types/guards/index.ts
@@ -3,5 +3,6 @@ export * from "./click-behavior";
export * from "./common";
export * from "./dom";
export * from "./parameters";
+export * from "./remote-sync";
export * from "./settings";
export * from "./visualization";
diff --git a/frontend/src/metabase-types/guards/remote-sync.ts b/frontend/src/metabase-types/guards/remote-sync.ts
new file mode 100644
index 00000000000..713eaf45c70
--- /dev/null
+++ b/frontend/src/metabase-types/guards/remote-sync.ts
@@ -0,0 +1,29 @@
+import {
+ type RemoteSyncDependencyErrorResponse,
+ UNSYNCED_DEPENDENCIES_ERROR_CODE,
+} from "metabase-types/api";
+
+import { isObject } from "./common";
+
+/**
+ * Narrows a rejected `updateRemoteSyncSettings` request to the dependency failure the backend
+ * returns when the requested collections reference content that would stay unsynced. Any other
+ * failure (bad credentials, read-only mode, …) comes back without this payload.
+ */
+export const isRemoteSyncDependencyError = (
+ error: unknown,
+): error is { data: RemoteSyncDependencyErrorResponse } =>
+ isObject(error) &&
+ isObject(error.data) &&
+ error.data.error_code === UNSYNCED_DEPENDENCIES_ERROR_CODE;
+
+/**
+ * True for any rejected request carrying a structured `errors` payload. The backend uses that key for
+ * several remote-sync failures — unsynced dependencies, remote-synced dependents — and the form layer
+ * would adopt any of them as field-level validation errors, so they all have to be stripped before the
+ * rejection reaches it.
+ */
+export const hasRemoteSyncErrorsPayload = (
+ error: unknown,
+): error is { data: { errors: unknown } } =>
+ isObject(error) && isObject(error.data) && isObject(error.data.errors);
diff --git a/src/metabase/collections/core.clj b/src/metabase/collections/core.clj
index 199002d2c5d..7f03af64f1f 100644
--- a/src/metabase/collections/core.clj
+++ b/src/metabase/collections/core.clj
@@ -21,16 +21,19 @@
check-remote-synced-dependents
create-library-collection!
descendant-ids
+ ineligible-dependencies
library-collection
library-collection-type
library-data-collection-type
library-metrics-collection-type
location-path
+ location-path->ids
moving-from-remote-synced?
moving-into-remote-synced?
non-remote-synced-dependencies
remote-synced-collection
remote-synced-collection?
+ remote-synced-dependents
shared-tenant-collection?
transforms-ns]
[metabase.collections.util
diff --git a/src/metabase/collections/models/collection.clj b/src/metabase/collections/models/collection.clj
index fda83b0021c..72b7be4480a 100644
--- a/src/metabase/collections/models/collection.clj
+++ b/src/metabase/collections/models/collection.clj
@@ -1363,6 +1363,38 @@
(let [direct-dependents (get all-remote-synced-descendants [(name (t2/model model)) id] [])]
(filter-eligible-dependents direct-dependents)))))
+(defn ineligible-dependencies
+ "Finds dependencies of a model that are not eligible for remote sync, along with the context needed to
+ explain why. Uses spec-based eligibility rules which account for special cases like snippets
+ (eligible when Library is synced, not by collection).
+
+ Takes model (the model to check dependencies for).
+
+ Returns a vector of maps, one per ineligible dependency:
+
+ {:model \"Card\", :id 412, :instance <row>}
+
+ `:instance` carries whatever [[select-for-eligibility-check]] loaded for it, notably `:collection_id`.
+ It falls out of the traversal that [[non-remote-synced-dependencies]] already runs, so reporting it
+ costs no extra queries."
+ [{:keys [id] :as model}]
+ (if (t2/exists? :model/Collection :id (if (= (t2/model model) :model/Collection) (:id model) (:collection_id model)))
+ (let [descendants (u/group-by first second (keys (traverse-descendants [(name (t2/model model)) id] true)))]
+ (into []
+ (for [m (collectable-models)
+ :let [model-name (name m)
+ descendant-ids (set (get descendants model-name))]
+ :when (seq descendant-ids)
+ :let [instances (select-for-eligibility-check m descendant-ids)
+ by-id (into {} (map (juxt :id identity)) instances)
+ eligibility-map (remote-sync/batch-model-eligible? m instances)]
+ [inst-id eligible?] eligibility-map
+ :when (not eligible?)]
+ {:model model-name
+ :id inst-id
+ :instance (get by-id inst-id)})))
+ []))
+
(defn non-remote-synced-dependencies
"Finds dependencies of a model that are not eligible for remote sync.
Uses spec-based eligibility rules which account for special cases like
@@ -1370,21 +1402,10 @@
Takes model (the model to check dependencies for).
- Returns a set of model IDs for dependencies of the given model that are not eligible for remote sync."
- [{:keys [id] :as model}]
- (if (t2/select-one :model/Collection :id (if (= (t2/model model) :model/Collection) (:id model) (:collection_id model)))
- (let [descendants (u/group-by first second (keys (traverse-descendants [(name (t2/model model)) id] true)))]
- (apply set/union
- (for [m (collectable-models)
- :let [key (name m)
- descendant-ids (set (get descendants key))]
- :when (seq descendant-ids)]
- (let [instances (select-for-eligibility-check m descendant-ids)
- eligibility-map (remote-sync/batch-model-eligible? m instances)]
- (into #{}
- (keep (fn [[inst-id eligible?]] (when-not eligible? inst-id)))
- eligibility-map)))))
- #{}))
+ Returns a set of model IDs for dependencies of the given model that are not eligible for remote sync.
+ See [[ineligible-dependencies]] for the same set with the containing collection attached."
+ [model]
+ (into #{} (map :id) (ineligible-dependencies model)))
(defn check-non-remote-synced-dependencies
"Checks if a model has non-remote-synced-dependencies and throws if it does.