Skip to content

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

67.3 KB
Raw Blame
(ns metabase-enterprise.remote-sync.spec
  "Centralized specifications for remote-syncable models.

   Each spec defines everything needed for a model to participate in remote sync:
   - Event handling (what events to listen to, how to determine status)
   - Eligibility checking (when should this model be tracked)
   - Dirty tracking (how to create/update RemoteSyncObject entries)
   - Identity resolution (for import/export matching)
   - Path construction (for serialization paths)

   To add a new syncable model, add a spec entry to `remote-sync-specs` and
   optionally implement custom multimethods if the default behavior doesn't fit."
  (:require
   [clojure.set :as set]
   [clojure.string :as str]
   [metabase-enterprise.remote-sync.db :as remote-sync.db]
   [metabase-enterprise.remote-sync.settings :as rs-settings]
   [metabase-enterprise.transforms-python.core :as transforms-python]
   [metabase.collections.core :as collections]
   [metabase.collections.models.collection :as collection]
   [metabase.models.serialization :as serdes]
   [metabase.settings.core :as setting]
   [metabase.util :as u]))

(set! *warn-on-reflection* true)

;;; ------------------------------------------------- Spec Definitions -------------------------------------------------

(def remote-sync-specs
  "Map of model keyword to its remote-sync specification.

   Each spec contains:
   - :model-type     - String name for RemoteSyncObject model_type column
   - :model-key      - Toucan2 model keyword (e.g., :model/Card)
   - :identity       - Identity strategy: :entity-id, :hybrid, or :user-settings (a Table's or Field's user
                       settings, keyed by the Table or Field id and loaded and tracked by their own import code)
   - :path-keys      - For :hybrid identity: vector of path components [:database :schema :table]
   - :source-model   - Optional model whose instances the events carry and eligibility is checked on, when it is not
                       :model-key (e.g., :model/Field for FieldUserSettings)
   - :row-key        - Optional column of `model-key` holding the tracked id; the model is only tracked for an id
                       with such a row (e.g., :field_id for FieldUserSettings)
   - :parent-model   - The parent model key (e.g., :model/TableUserSettings for FieldUserSettings, Segment, Measure)
   - :parent-fk      - For child models that cascade from their parent: the FK pointing to it (e.g., :table_id)
   - :cascade-filter  - Optional map of additional filter conditions for cascade queries.
                       Only needed when the filter differs from {archived-key false}.
   - :delete-after   - Optional vector of model keys that must be deleted AFTER this model.
                       Used to handle FK constraints during import cleanup. For example, if Card
                       has :delete-after [:model/Collection], Card will be deleted before Collection.
   - :events         - Event configuration map:
                       :prefix - Event keyword prefix (e.g., :event/card)
                       :types  - Vector of event types to handle [:create :update :delete]
   - :eligibility    - Eligibility configuration:
                       :type       - :collection, :published-table, :parent-table, :parent, :setting,
                                     :library-synced, or :always (:parent follows :parent-fk to a :parent-model
                                     instance)
                       :collection - For :collection type: :remote-synced, :transforms-namespace, :snippets-namespace, or :any
                       :setting    - For :setting type: setting keyword to check
                       (Note: :library-synced type uses the library-is-remote-synced? setting to determine eligibility)
   - :archived-key   - Key to check for archived status (nil if model has no archived concept)
   - :tracking       - RemoteSyncObject field configuration:
                       :select-fields  - Fields to select for hydration
                       :hydrate-query? - When true, hydrate via the model's
                                         `metabase-enterprise.remote-sync.db` tracking-join query instead of
                                         :select-fields (Field, Segment, Measure)
                       :field-mappings - Map of RemoteSyncObject column -> source field or [field transform-fn]
   - :conditions     - Optional map of conditions for filtering syncable entities.
                       Only entities matching these conditions are eligible for sync
                       (export, import cleanup, removal). Example: {:built_in_type nil}
                       to exclude built-in items from sync.
   - :export-conditions  - Optional. Overrides :conditions for export queries. Falls back to :conditions.
   - :removal-conditions - Optional. Overrides :conditions for removal/cleanup. Falls back to :conditions.
   - :removal        - Removal/cleanup configuration:
                       :statuses   - Set of statuses to check for removal (e.g., #{\"removed\" \"delete\"})
                       :scope-key  - Optional key for scoping deletions (e.g., :collection_id, :id).
                                     If nil, deletions are global (by entity_id only).
                       :all-on-setting-disable - Optional setting keyword; the model syncs all or nothing with
                                     this setting, so an import that drops it is checked for unsynced local work
   - :resources?     - Optional. True when the model's YAML files carry resource files (see
                       `metabase.models.serialization/resource-paths`), whose changes only a full import or export
                       handles.
   - :export-scope   - Export scope for query-export-roots:
                       :root-collections - Query root-level remote-synced + namespace collections (Collection)
                       :root-only        - Query root instances with collection_id = nil (Transform)
                       :all              - Query all instances (TransformTag, PythonLibrary, NativeQuerySnippet, Glossary)
                       nil/:derived      - No root query; derived from other models via serdes/descendants
   - :enabled?       - true, or setting keyword (e.g., :remote-sync-transforms, :library-synced).
                       When :library-synced, uses the library-is-remote-synced? setting."
  {:model/Card
   {:model-type     "Card"
    :model-key      :model/Card
    :identity       :entity-id
    :delete-after   [:model/Collection]  ; has collection_id FK
    :events         {:prefix :event/card
                     :types  [:create :update :delete :public-link-created :public-link-deleted]}
    :eligibility    {:type       :collection
                     :collection :remote-synced}
    :archived-key   :archived
    :tracking       {:select-fields  [:name :collection_id :display]
                     :field-mappings {:model_name          :name
                                      :model_collection_id :collection_id
                                      :model_display       [:display #(some-> % name)]}}
    :removal        {:statuses  #{"removed"}
                     :scope-key :collection_id}
    :enabled?       true}

   :model/Action
   {:model-type     "Action"
    :model-key      :model/Action
    :identity       :entity-id
    :delete-after   [:model/Collection]  ; has collection_id FK
    :events         {:prefix :event/action
                     :types  [:create :update :delete]}
    ;; actions without a model are Library content: synced with it from the data actions root and namespace
    :eligibility    {:type                      :collection
                     :collection                :remote-synced
                     :library-synced-conditions {:model_id nil}}
    :archived-key   :archived
    :tracking       {:select-fields  [:name :collection_id]
                     :field-mappings {:model_name          :name
                                      :model_collection_id :collection_id}}
    :removal        {:statuses  #{"removed"}
                     :scope-key :collection_id}
    :enabled?       true}

   :model/Dashboard
   {:model-type     "Dashboard"
    :model-key      :model/Dashboard
    :identity       :entity-id
    :delete-after   [:model/Collection]  ; has collection_id FK
    :events         {:prefix :event/dashboard
                     :types  [:create :update :delete :public-link-created :public-link-deleted]}
    :eligibility    {:type       :collection
                     :collection :remote-synced}
    :archived-key   :archived
    :tracking       {:select-fields  [:name :collection_id]
                     :field-mappings {:model_name          :name
                                      :model_collection_id :collection_id}}
    :removal        {:statuses  #{"removed"}
                     :scope-key :collection_id}
    :enabled?       true}

   :model/Document
   {:model-type     "Document"
    :model-key      :model/Document
    :identity       :entity-id
    :delete-after   [:model/Collection]  ; has collection_id FK
    :events         {:prefix :event/document
                     :types  [:create :update :delete]}
    :eligibility    {:type       :collection
                     :collection :remote-synced}
    :archived-key   :archived
    :tracking       {:select-fields  [:name :collection_id]
                     :field-mappings {:model_name          :name
                                      :model_collection_id :collection_id}}
    :conditions     {:exploration_id nil}  ; exclude exploration Summary docs from sync
    :removal        {:statuses  #{"removed"}
                     :scope-key :collection_id}
    :enabled?       true}

   :model/NativeQuerySnippet
   {:model-type     "NativeQuerySnippet"
    :model-key      :model/NativeQuerySnippet
    :identity       :entity-id
    :delete-after   [:model/Collection]  ; has collection_id FK
    :events         {:prefix :event/snippet
                     :types  [:create :update :delete]}
    :eligibility    {:type :library-synced}  ; sync all snippets when Library is remote-synced
    :archived-key   :archived
    :tracking       {:select-fields  [:name :collection_id]
                     :field-mappings {:model_name          :name
                                      :model_collection_id :collection_id}}
    :removal        {:statuses #{"removed" "delete"}}  ; no scope-key = global deletion
    :export-scope   :all  ; export all snippets
    :enabled?       :library-synced}

   :model/Glossary
   {:model-type     "Glossary"
    :model-key      :model/Glossary
    :identity       :entity-id
    :events         {:prefix :event/glossary
                     :types  [:create :update :delete]}
    :eligibility    {:type :library-synced}  ; sync every glossary entry when Library is remote-synced
    :archived-key   nil
    :tracking       {:select-fields  [:term]
                     :field-mappings {:model_name :term}}
    :removal        {:statuses #{"removed" "delete"}}  ; no scope-key = global deletion
    :export-scope   :all  ; export all glossary entries
    :enabled?       :library-synced
    ;; files exported before `entity_id` existed are keyed by term; resolve those paths through load-find-local
    :natural-key-paths? true}

   :model/Timeline
   {:model-type     "Timeline"
    :model-key      :model/Timeline
    :identity       :entity-id
    :delete-after   [:model/Collection]  ; has collection_id FK
    :events         {:prefix :event/timeline
                     :types  [:create :update :delete]}
    :eligibility    {:type       :collection
                     :collection :remote-synced}
    :archived-key   :archived
    :tracking       {:select-fields  [:name :collection_id]
                     :field-mappings {:model_name          :name
                                      :model_collection_id :collection_id}}
    :removal        {:statuses  #{"removed"}
                     :scope-key :collection_id}
    :enabled?       true}

   :model/Collection
   {:model-type     "Collection"
    :model-key      :model/Collection
    :identity       :entity-id
    :events         {:prefix :event/collection
                     :types  [:create :update]}  ; no delete event for collections
    :eligibility    {:type       :collection
                     :collection :any}  ; remote-synced OR transforms-namespace
    :archived-key   :archived
    :tracking       {:select-fields  [:name :id]
                     :field-mappings {:model_name          :name
                                      :model_collection_id :id}}  ; collection_id is self
    :removal        {:statuses  #{"removed" "delete"}  ; delete is set when collection is archived
                     :scope-key :id}  ; collections are scoped by their own id
    :export-scope   :root-collections  ; query for root-level remote-synced + transforms-namespace collections
    :enabled?       true}

   :model/TableUserSettings
   {:model-type     "TableUserSettings"
    :model-key      :model/TableUserSettings
    :source-model   :model/Table
    :identity       :user-settings
    :row-key        :table_id
    :events         {:prefix :event/table
                     :types  [:create :update :delete :publish :unpublish]}
    :eligibility    {:type :published-table}
    :archived-key   :archived_at
    :tracking       {:hydrate-query? true
                     :field-mappings {:model_name          :name
                                      :model_collection_id :collection_id
                                      :model_table_id      :table_id
                                      :model_table_name    :table_name}}
    :removal        {:statuses #{"removed"}}
    :enabled?       true}

   :model/FieldUserSettings
   {:model-type     "FieldUserSettings"
    :model-key      :model/FieldUserSettings
    :source-model   :model/Field
    :identity       :user-settings
    :row-key        :field_id
    :parent-model   :model/TableUserSettings
    :parent-fk      :table_id
    :events         {:prefix :event/field
                     :types  [:create :update :delete]}
    :eligibility    {:type :parent-table}
    :archived-key   nil
    :tracking       {:hydrate-query? true
                     :field-mappings {:model_name          :name
                                      :model_collection_id :collection_id
                                      :model_table_id      :table_id
                                      :model_table_name    :table_name}}
    :removal        {:statuses #{"removed"}}
    :enabled?       true}

   :model/Dimension
   {:model-type     "Dimension"
    :model-key      :model/Dimension
    :source-model   :model/Field
    :identity       :user-settings
    :row-key        :field_id
    :parent-model   :model/TableUserSettings
    :parent-fk      :table_id
    :events         {:prefix :event/field
                     :types  [:create :update :delete]}
    :eligibility    {:type :parent-table}
    :archived-key   nil
    :tracking       {:hydrate-query? true
                     :field-mappings {:model_name          :name
                                      :model_collection_id :collection_id
                                      :model_table_id      :table_id
                                      :model_table_name    :table_name}}
    :removal        {:statuses #{"removed"}}
    :enabled?       true}

   :model/Segment
   {:model-type     "Segment"
    :model-key      :model/Segment
    :identity       :hybrid  ; entity_id but needs table context for path
    :path-keys      [:database :schema :table]
    :parent-model   :model/TableUserSettings
    :events         {:prefix :event/segment
                     :types  [:create :update :delete]}
    :eligibility    {:type :parent-table}
    :archived-key   :archived
    :tracking       {:hydrate-query? true
                     :field-mappings {:model_name          :name
                                      :model_collection_id :collection_id
                                      :model_table_id      :table_id
                                      :model_table_name    :table_name}}
    :removal        {:statuses #{"removed" "delete"}}  ; Segment has both
    :enabled?       true}

   :model/Measure
   {:model-type     "Measure"
    :model-key      :model/Measure
    :identity       :hybrid  ; entity_id but needs table context for path
    :path-keys      [:database :schema :table]
    :parent-model   :model/TableUserSettings
    :events         {:prefix :event/measure
                     :types  [:create :update :delete]}
    :eligibility    {:type :parent-table}
    :archived-key   :archived
    :tracking       {:hydrate-query? true
                     :field-mappings {:model_name          :name
                                      :model_collection_id :collection_id
                                      :model_table_id      :table_id
                                      :model_table_name    :table_name}}
    :removal        {:statuses #{"removed" "delete"}}
    :enabled?       true}

   :model/Transform
   {:model-type     "Transform"
    :model-key      :model/Transform
    :identity       :entity-id
    :delete-after   [:model/Collection]  ; has collection_id FK
    :events         {:prefix :event/transform
                     :types  [:create :update :delete]}
    :eligibility    {:type    :setting
                     :setting :remote-sync-transforms}
    :archived-key   :archived
    :tracking       {:select-fields  [:name :collection_id]
                     :field-mappings {:model_name          :name
                                      :model_collection_id :collection_id}}
    :removal        {:statuses #{"removed" "delete"}  ; no scope-key = global deletion
                     :all-on-setting-disable :remote-sync-transforms}
    :export-scope   :root-only  ; query for root transforms (collection_id = nil)
    :enabled?       :remote-sync-transforms}

   :model/TransformTag
   {:model-type     "TransformTag"
    :model-key      :model/TransformTag
    :identity       :entity-id
    :events         {:prefix :event/transform-tag
                     :types  [:create :update :delete]}
    :eligibility    {:type    :setting
                     :setting :remote-sync-transforms}
    :archived-key   nil  ; no archived field
    :tracking       {:select-fields  [:name]
                     :field-mappings {:model_name :name}}
    :conditions     {:built_in_type nil}  ; exclude built-in tags from sync
    :removal        {:statuses #{"removed" "delete"}  ; no scope-key = global deletion
                     :all-on-setting-disable :remote-sync-transforms}
    :export-scope   :all  ; query for all instances
    :enabled?       :remote-sync-transforms}

   :model/TransformTest
   {:model-type     "TransformTest"
    :model-key      :model/TransformTest
    :identity       :entity-id
    :delete-after   [:model/Transform]  ; has transform_id FK
    :parent-model   :model/Transform
    :parent-fk      :transform_id
    :events         {:prefix :event/transform-test
                     :types  [:create :update :delete]}
    :eligibility    {:type    :setting
                     :setting :remote-sync-transforms}
    :archived-key   nil  ; no archived field
    :tracking       {:select-fields  [:name]
                     :field-mappings {:model_name :name}}
    :removal        {:statuses #{"removed" "delete"}  ; no scope-key = global deletion
                     :all-on-setting-disable :remote-sync-transforms}
    :export-scope   :all  ; query for all instances
    :enabled?       :remote-sync-transforms}

   :model/PythonLibrary
   {:model-type     "PythonLibrary"
    :model-key      :model/PythonLibrary
    :identity       :entity-id
    :events         {:prefix :event/python-library
                     :types  [:create :update]}  ; no delete - upsert only
    :eligibility    {:type    :setting
                     :setting :remote-sync-transforms}
    :archived-key   nil  ; no archived field
    :tracking       {:select-fields  [:path]
                     :field-mappings {:model_name :path}}
    :conditions         {:is_default false}  ; exclude the default common.py from sync
    :removal-conditions {:entity_id [:not= transforms-python/builtin-entity-id]}  ; protect built-in common.py from deletion
    :removal        {:statuses               #{"removed" "delete"}  ; no scope-key = global deletion
                     :all-on-setting-disable :remote-sync-transforms}
    :export-scope   :all  ; query for all instances
    :enabled?       :remote-sync-transforms}

   :model/DataApp
   {:model-type     "DataApp"
    :model-key      :model/DataApp
    :identity       :entity-id
    :events         {:prefix :event/data-app
                     :types  [:create :update :delete]}
    :eligibility    {:type :always}
    :archived-key   nil
    :tracking       {:select-fields  [:name]
                     :field-mappings {:model_name :name}}
    :removal        {:statuses #{"removed" "delete"}}
    :resources?     true
    :export-scope   :all
    :enabled?       true}})

;;; ------------------------------------------------- Helper Functions -------------------------------------------------

(defn spec-enabled?
  "Returns true if the spec is currently enabled based on its :enabled? value."
  [{:keys [enabled?]}]
  (cond
    (true? enabled?)            true
    (= enabled? :library-synced) (rs-settings/library-is-remote-synced?)
    (keyword? enabled?)         (boolean (setting/get-value-of-type :boolean enabled?))
    :else                       false))

(defn export-conditions
  "Returns conditions to apply when querying entities for export.
   Uses :export-conditions if present, else falls back to :conditions."
  [spec]
  (or (:export-conditions spec) (:conditions spec)))

(defn removal-conditions
  "Returns conditions to apply when removing unsynced entities.
   Uses :removal-conditions if present, else falls back to :conditions."
  [spec]
  (or (:removal-conditions spec) (:conditions spec)))

(defn enabled-specs
  "Returns a map of model-key -> spec for all currently enabled specs."
  []
  (into {}
        (filter (fn [[_ spec]] (spec-enabled? spec)))
        remote-sync-specs))

(defn spec-for-model-type
  "Returns the spec for a given model type string (e.g., \"Card\")."
  [model-type-str]
  (some (fn [[_ spec]]
          (when (= (:model-type spec) model-type-str)
            spec))
        remote-sync-specs))

(defn spec-for-model-key
  "Returns the spec for a given model key (e.g., :model/Card)."
  [model-key]
  (get remote-sync-specs model-key))

(defn children-specs
  "Returns child specs for a given parent model key, derived from :parent-model references."
  [parent-model-key]
  (into []
        (comp (map val)
              (filter #(and (= (:parent-model %) parent-model-key)
                            (:parent-fk %))))
        remote-sync-specs))

(defn specs-by-identity-type
  "Returns a map of model-key -> spec filtered by identity type."
  [identity-type]
  (into {}
        (filter (fn [[_ spec]] (= (:identity spec) identity-type)))
        (enabled-specs)))

(defn specs-for-deletion
  "Returns specs with :entity-id identity type, topologically sorted for safe deletion.
   Uses :delete-after declarations to ensure models are deleted before their dependencies.
   If model A has :delete-after [:model/B], then A will be deleted before B."
  []
  (let [entity-id-specs (specs-by-identity-type :entity-id)
        ;; Build dependency graph: model -> set of models that must be deleted after it
        ;; (i.e., the models listed in this model's :delete-after)
        delete-after-map (reduce-kv
                          (fn [m model-key spec]
                            (assoc m model-key (set (get spec :delete-after))))
                          {}
                          entity-id-specs)
        ;; Invert to get: model -> set of models that must be deleted before it
        ;; If A has :delete-after [B], then B must wait for A to be deleted first
        must-wait-for (reduce-kv
                       (fn [m model-key deps]
                         (reduce (fn [m' dep]
                                   (update m' dep (fnil conj #{}) model-key))
                                 m
                                 deps))
                       {}
                       delete-after-map)
        ;; Simple topological sort - repeatedly take models with no remaining dependencies
        sorted (loop [remaining (set (keys entity-id-specs))
                      result []]
                 (if (empty? remaining)
                   result
                   (let [;; Find models whose dependencies are all already processed
                         ready (filter (fn [k]
                                         (every? #(not (remaining %))
                                                 (get must-wait-for k)))
                                       remaining)]
                     (if (empty? ready)
                       ;; Cycle detected or no progress - just append remaining
                       (into result remaining)
                       (recur (apply disj remaining ready)
                              (into result ready))))))]
    (mapv (fn [k] [k (entity-id-specs k)]) sorted)))

(defn excluded-model-types
  "Returns a set of model type strings that should be excluded from dirty detection
   based on current settings. Models with a setting-based or library-synced :enabled?
   that is currently false will be excluded."
  []
  (->> remote-sync-specs
       (filter (fn [[_ spec]]
                 (let [enabled? (:enabled? spec)]
                   (and (keyword? enabled?)
                        (not (spec-enabled? spec))))))
       (map (fn [[_ spec]] (:model-type spec)))
       set))

(defn all-model-types
  "Returns a set of all model type strings."
  []
  (into #{} (map :model-type (vals remote-sync-specs))))

;;; ---------------------------------------- Import Conflict Detection -----------------------------------------------

(defn optional-feature-specs
  "Returns specs for optional features, grouped by their enabling setting keyword.
   Optional features are those with a keyword `:enabled?` value (not `true`).
   Returns map of {setting-keyword {model-key spec}}."
  []
  (-> remote-sync-specs
      (->> (filter (fn [[_ spec]] (keyword? (:enabled? spec))))
           (group-by (fn [[_ spec]] (:enabled? spec))))
      (update-vals #(into {} %))))

(defn- setting->category
  "Converts a setting keyword to a human-readable conflict category name."
  [setting-kw]
  (case setting-kw
    :remote-sync-transforms "Transforms"
    :library-synced         "Snippets"
    (str/capitalize (name setting-kw))))

(defn- setting->content-label
  "Describes the content a feature setting governs, for conflict messages. The Library groups several models
   under one category, so name them rather than the category."
  [setting-kw]
  (case setting-kw
    :library-synced "Library content (snippets, data actions, glossary)"
    (setting->category setting-kw)))

(defn- setting->namespace
  "Converts a setting keyword to the corresponding collection namespace keyword, or nil."
  [setting-kw]
  (case setting-kw
    :remote-sync-transforms :transforms
    :library-synced         :snippets
    nil))

(defn models-for-setting
  "Returns set of model-type strings for specs with the given `:enabled?` setting."
  [setting-kw]
  (->> remote-sync-specs
       (filter (fn [[_ spec]] (= (:enabled? spec) setting-kw)))
       (map (fn [[_ spec]] (:model-type spec)))
       (into #{})))

(def transform-models
  "Models that indicate transforms content in a snapshot.
   Derived from specs with `:enabled? :remote-sync-transforms`.
   Excludes TransformTag since built-in tags are always present and don't indicate
   user transform content. Non-built-in TransformTags are checked separately."
  (disj (models-for-setting :remote-sync-transforms) "TransformTag"))

(defn models-in-import
  "Returns set of model-type strings present in the import.
   Takes an ingest-list (sequence of serdes paths from serialization/ingest-list)."
  [ingest-list]
  (->> ingest-list
       (map (fn [path] (:model (last path))))
       (into #{})))

(defn check-entity-id-conflicts
  "Checks if imported entity_ids exist locally but are NOT in RemoteSyncObject.
   Returns map of {model-type #{conflicting-entity-ids}}.

   Excludes the Library collection entity_id since that's handled by the library-conflict check."
  [imported-entity-ids-by-model]
  (into {}
        (for [[model-type entity-ids] imported-entity-ids-by-model
              :when (seq entity-ids)
              :let [spec (spec-for-model-type model-type)
                    model-key (:model-key spec)]
              :when (and spec model-key (#{:entity-id :hybrid} (:identity spec)))
              :let [local-entity-ids (remote-sync.db/existing-entity-ids model-key entity-ids)
                    tracked-entity-ids (when (seq local-entity-ids)
                                         (let [pks (remote-sync.db/ids-by-entity-ids model-key local-entity-ids)]
                                           (into #{}
                                                 (map (fn [rso]
                                                        (:entity_id (remote-sync.db/instance model-key (:model_id rso)))))
                                                 (remote-sync.db/rsos-of-models model-type pks))))
                    conflicting-entity-ids (set/difference local-entity-ids (or tracked-entity-ids #{}))
                    conflicting-entity-ids (if (= model-type "Collection")
                                             (disj conflicting-entity-ids collection/library-entity-id)
                                             conflicting-entity-ids)]
              :when (seq conflicting-entity-ids)]
          [model-type conflicting-entity-ids])))

(defn- has-unsynced-entities-for-feature?
  "Returns true if any model in the feature group has local entities not tracked in RemoteSyncObject.
   Excludes entities filtered by removal-conditions (e.g., built-in TransformTags and the built-in common.py
   PythonLibrary every instance gets from a migration) from the count since they are system-created and not
   user data. Namespace collections are not checked here because they are organizational containers, not
   user data that would be lost on import."
  [specs-for-feature]
  (some (fn [[_ spec]]
          (let [model-key (:model-key spec)
                model-type (:model-type spec)
                conditions (removal-conditions spec)
                local-count (remote-sync.db/count-where model-key conditions)
                synced-count (remote-sync.db/rso-count-of-type model-type)]
            (and (pos? local-count)
                 (> local-count synced-count))))
        specs-for-feature))

(defn check-feature-conflicts
  "Checks if import contains models that conflict with existing local entities that are NOT already remote synced.
   Derives conflict categories from specs with keyword `:enabled?` values (optional features).
   Only triggers conflict when local has unsynced entities AND import has matching entities.
   If local entities are already synced, dirty tracking handles conflicts instead.

   `import-namespace-collections` is a set of namespace strings (e.g., #{\"transforms\" \"snippets\"})
   found in Collection entities in the import."
  [models-present import-namespace-collections]
  (let [feature-groups (optional-feature-specs)]
    (into []
          (for [[setting-kw specs-for-feature] feature-groups
                :let [feature-model-types (into #{} (map (fn [[_ s]] (:model-type s))) specs-for-feature)
                      feature-namespace (setting->namespace setting-kw)]
                :when (or (some feature-model-types models-present)
                          (and feature-namespace
                               (contains? import-namespace-collections (name feature-namespace))))
                :when (has-unsynced-entities-for-feature? specs-for-feature)
                :let [category (setting->category setting-kw)
                      label    (setting->content-label setting-kw)]]
            {:type     (keyword (str (u/lower-case-en category) "-conflict"))
             :category category
             :message  (format "Import contains %s but local instance has unsynced %s" label label)}))))

(defn check-namespace-collection-conflicts
  "Checks if import contains namespace collections (transforms/snippets) that conflict with local
   unsynced namespace collections. Only flags a conflict when the local collections were NOT created
   by the sync system (i.e., have no matching entity_id in the import).

   `import-namespace-collections` is a set of namespace strings found in the import.
   `import-ns-collection-entity-ids` is a map of namespace string -> set of entity_ids from the import."
  [import-namespace-collections import-ns-collection-entity-ids]
  (let [ns-configs [{:ns-name "transforms"   :setting-kw :remote-sync-transforms :category "Transforms"}
                    {:ns-name "snippets"     :setting-kw :library-synced         :category "Snippets"}
                    {:ns-name "data-actions" :setting-kw :library-synced         :category "Snippets"}]]
    (into []
          (for [{:keys [ns-name setting-kw category]} ns-configs
                :when (contains? import-namespace-collections ns-name)
                :let [setting-enabled? (cond
                                         (= setting-kw :library-synced) (rs-settings/library-is-remote-synced?)
                                         (keyword? setting-kw) (boolean (setting/get-value-of-type :boolean setting-kw))
                                         :else false)]
                :when (not setting-enabled?)
                :let [local-ns-colls (remote-sync.db/collections-in-namespace ns-name)
                      import-eids (get import-ns-collection-entity-ids ns-name #{})
                      ;; Only consider local collections that are NOT in the import (truly local-only)
                      ;; and NOT tracked in RemoteSyncObject
                      unsynced-local (remove
                                      (fn [coll]
                                        (or (contains? import-eids (:entity_id coll))
                                            (remote-sync.db/rso-exists? "Collection" (:id coll))))
                                      local-ns-colls)]
                :when (seq unsynced-local)]
            {:type     (keyword (str (u/lower-case-en category) "-conflict"))
             :category category
             :message  (format "Import contains %s but local instance has unsynced %s namespace collections"
                               category category)}))))

(defn- library-synced-root-conditions
  "The conditions selecting `spec`'s Library content outside of any Collection, when the Library is synced."
  [spec]
  (when-let [conditions (get-in spec [:eligibility :library-synced-conditions])]
    (when (rs-settings/library-is-remote-synced?)
      (assoc conditions :collection_id nil))))

(defn removal-opts
  "The `metabase-enterprise.remote-sync.db` removal-opts (`:scope-key`, `:synced-collection-ids`, `:entity-ids`,
  `:removal-conditions`) for removing the entity-id `spec`'s rows not in the import, scoped to
  `synced-collection-ids` when the spec has a `:scope-key`, minus the imported `entity-ids`."
  [spec synced-collection-ids entity-ids]
  {:scope-key              (get-in spec [:removal :scope-key])
   :synced-collection-ids  synced-collection-ids
   :unscoped-conditions    (library-synced-root-conditions spec)
   :entity-ids             entity-ids
   :removal-conditions     (removal-conditions spec)})

(defn check-deletion-conflicts
  "Detects local entities of all-or-nothing models (specs with :all-on-setting-disable) that an import
   would wholesale-delete because they are absent from it, but which hold unsaved local work — i.e. they
   have no RemoteSyncObject in 'synced' status. Already-synced entities are excluded: their removal is a
   normal reconcile against the remote source of truth, not data loss.

   Takes imported-data from [[extract-imported-entities]]. Returns a vector of conflict maps
   ({:type :category :message}), one per affected model type (categories repeat across the transform models;
   callers dedupe via the conflict summary)."
  [{:keys [by-entity-id]}]
  (into []
        (for [[model-key spec] (specs-for-deletion)
              :let [setting-kw (get-in spec [:removal :all-on-setting-disable])]
              :when setting-kw
              :let [model-type   (:model-type spec)
                    imported-ids (get by-entity-id model-type #{})
                    ;; These models are unscoped (no :scope-key), so the removal-opts just carry the
                    ;; not-in-import + removal-condition restrictions; unsynced-instance-count adds the anti-join.
                    n-unsynced   (remote-sync.db/unsynced-instance-count
                                  model-key model-type (removal-opts spec nil imported-ids))]
              :when (pos? n-unsynced)
              :let [category (setting->category setting-kw)]]
          {:type    (keyword (str (u/lower-case-en category) "-conflict"))
           :category category
           :message  (format "Import would delete %d unsynced local %s %s"
                             n-unsynced category (if (= 1 n-unsynced) "entity" "entities"))})))

;;; ------------------------------------------------ Eligibility Checking ----------------------------------------------

(defn transforms-namespace-collection?
  "Check if this is a transforms-namespace collection."
  [object]
  (= (keyword (:namespace object)) :transforms))

(defn snippets-namespace-collection?
  "Check if this is a snippets-namespace collection."
  [object]
  (= (keyword (:namespace object)) :snippets))

(defn data-actions-namespace-collection?
  "Check if this is a data-actions-namespace collection."
  [object]
  (= (keyword (:namespace object)) collections/data-actions-ns))

(defn library-namespace-collection?
  "Check if this is a collection of a namespace synced with the Library: snippets or data actions."
  [object]
  (or (snippets-namespace-collection? object)
      (data-actions-namespace-collection? object)))

(defn data-apps-namespace-collection?
  "Check if this is a data-apps-namespace collection: a data app's resource collection, synced with the app."
  [object]
  (= (keyword (:namespace object)) collections/data-apps-ns))

(defn library-collection?
  "Check if this is the Library collection."
  [collection]
  (= (:type collection) "library"))

(defn should-sync-collection?
  "Check if a collection should be synced - either remote-synced, transforms-namespace with setting enabled,
   snippets-namespace with Library synced, or data-apps-namespace, a data app's collection, synced with the app."
  [collection]
  (or (collections/remote-synced-collection? collection)
      (and (rs-settings/remote-sync-transforms)
           (transforms-namespace-collection? collection))
      (and (rs-settings/library-is-remote-synced?)
           (library-namespace-collection? collection))
      (data-apps-namespace-collection? collection)))

(defn all-syncable-collection-ids
  "Returns a vector of all collection IDs that are eligible for remote sync.
   This includes:
   - Collections with is_remote_synced=true
   - Transforms-namespace collections (when remote-sync-transforms setting is enabled)
   - Snippets- and data-actions-namespace collections (when Library is remote-synced)
   - Data-apps-namespace collections (data apps are synced globally)

   Used by import cleanup to determine which collections to scope deletions to."
  []
  (into []
        cat
        [(remote-sync.db/remote-synced-collection-ids)
         (when (rs-settings/remote-sync-transforms)
           (remote-sync.db/collection-ids-in-namespace (name collections/transforms-ns)))
         (when (rs-settings/library-is-remote-synced?)
           (remote-sync.db/collection-ids-in-namespace "snippets"))
         (when (rs-settings/library-is-remote-synced?)
           (remote-sync.db/collection-ids-in-namespace (name collections/data-actions-ns)))
         (remote-sync.db/collection-ids-in-namespace (name collections/data-apps-ns))]))

(def ^:private max-conflict-names
  "Cap on how many entity names a collection deletion conflict carries, so the payload stays bounded when
   a whole collection's worth of content would be swept. The :count field always holds the true total."
  100)

(defn check-content-deletion-conflicts
  "Detects unsynced local content an import would delete because it is absent from the import, but which
   holds unsaved local work — it has no RemoteSyncObject in 'synced' status, so its removal is data loss
   (unlike an already-synced entity's, which is a normal reconcile against the remote source of truth).

   Covers the entity-id content models [[check-deletion-conflicts]] does not (that one handles only the
   all-or-nothing, setting-gated transform family): Cards/metrics, Dashboards, Documents, Timelines, and
   NativeQuerySnippets. Collection is excluded — it is structural, its deletion cascades, and its contents
   are already covered here. The count matches what an import would actually delete.

   Takes imported-data from [[extract-imported-entities]]. Returns a vector of conflict maps
   ({:type :category :model :count :names :message}), one per affected model type."
  [{:keys [by-entity-id]}]
  (let [synced-collection-ids (all-syncable-collection-ids)]
    (into []
          (for [[model-key spec] (specs-for-deletion)
                :when (and (not (get-in spec [:removal :all-on-setting-disable]))
                           (not= :model/Collection model-key)
                           (or (seq synced-collection-ids)
                               (nil? (get-in spec [:removal :scope-key]))
                               (library-synced-root-conditions spec)))
                :let [model-type   (:model-type spec)
                      imported-ids (get by-entity-id model-type #{})
                      ;; Same base restriction remove-unsynced! deletes by, plus an anti-join keeping only the
                      ;; unsynced rows the import would delete. Done in SQL so we never materialize a whole
                      ;; collection's worth of rows just to count/sample them.
                      opts         (removal-opts spec synced-collection-ids imported-ids)
                      n            (remote-sync.db/unsynced-instance-count model-key model-type opts)
                      name-col     (get-in spec [:tracking :field-mappings :model_name])]
                :when (pos? n)]
            {:type     (keyword (str (u/lower-case-en model-type) "-deletion-conflict"))
             :category model-type
             :model    model-type
             :count    n
             ;; A bounded sample of names for the UI; :count above is the true total.
             :names    (remote-sync.db/unsynced-instance-names model-key model-type name-col opts
                                                               max-conflict-names)
             :message  (format "Import would delete %d unsynced local %s %s"
                               n model-type (if (= 1 n) "entity" "entities"))}))))

(defn- object-matches-conditions?
  "True if `object` satisfies every column-value pair in `conditions` (or if no conditions are set).
   A key MISSING from `object` does not match, even against a nil condition value — eligibility needs
   positive evidence the condition holds (e.g. the Document spec's `{:exploration_id nil}` must
   see an explicit nil, not an absent key), so a partial payload can't sneak conditioned rows into
   sync scope.
   NOTE: only handles scalar values — non-scalar `:conditions` (e.g. `[:not= ...]`) are not supported here.
   Such forms belong in `:export-conditions`/`:removal-conditions`, which feed query-builders, not this helper."
  [conditions object]
  (or (empty? conditions)
      (every? (fn [[k v]]
                (= (find object k) [k v]))
              conditions)))

(defmulti ^:private check-eligibility-by-type
  "Type-specific eligibility check, dispatched on `(get-in spec [:eligibility :type])`.
   Callers should use `check-eligibility` instead — it also enforces the spec's `:conditions`."
  {:arglists '([spec object])}
  (fn [spec _object] (get-in spec [:eligibility :type])))

(defn check-eligibility
  "Determines if a model instance should be tracked for remote sync.
   Applies the spec's `:conditions` filter and then delegates to the eligibility-type method."
  [spec object]
  (boolean
   (and (object-matches-conditions? (:conditions spec) object)
        (check-eligibility-by-type spec object))))

(defn library-synced-object?
  "Whether `object` matches the spec's `:library-synced-conditions`, which make it Library content."
  [spec object]
  (when-let [conditions (get-in spec [:eligibility :library-synced-conditions])]
    (object-matches-conditions? conditions object)))

(defn library-content?
  "Whether `object` matches the spec's `:library-synced-conditions` and is in the data actions root or namespace,
  which makes it Library content."
  [spec {collection-id :collection_id :as object}]
  (boolean
   (and (library-synced-object? spec object)
        (or (nil? collection-id)
            (= collections/data-actions-ns
               (some-> (remote-sync.db/collection-namespace collection-id) keyword))))))

(defmethod check-eligibility-by-type :collection
  [{:keys [eligibility] :as spec} object]
  (let [collection-type (:collection eligibility)
        collection-id   (:collection_id object)
        ;; what sits in a data app's collection is synced with the app, an action without a model included: the
        ;; app's copies belong to no model, and are the app's rather than the Library's
        in-data-app?    (and (some? collection-id)
                             (data-apps-namespace-collection? {:namespace (remote-sync.db/collection-namespace collection-id)}))]
    (if (and (library-synced-object? spec object) (not in-data-app?))
      (and (rs-settings/library-is-remote-synced?)
           (library-content? spec object))
      (case collection-type
        :remote-synced
        (or (collections/remote-synced-collection? collection-id)
            in-data-app?)

        :transforms-namespace
        (and (rs-settings/remote-sync-transforms)
             (transforms-namespace-collection? object))

        :snippets-namespace
        (and (rs-settings/library-is-remote-synced?)
             (snippets-namespace-collection? object))

        :any
        (or (collections/remote-synced-collection? (or collection-id object))
            (and (rs-settings/remote-sync-transforms)
                 (transforms-namespace-collection? object))
            (and (rs-settings/library-is-remote-synced?)
                 (library-namespace-collection? object))
            (data-apps-namespace-collection? object))

        false))))

(defn- published-in-remote-synced-collection?
  "Whether `table` is published in a remote-synced Collection."
  [{:keys [is_published collection_id]}]
  (and is_published
       (collections/remote-synced-collection? collection_id)))

(defmethod check-eligibility-by-type :published-table
  [_ table]
  (published-in-remote-synced-collection? table))

(defmethod check-eligibility-by-type :parent-table
  [_ {:keys [table_id]}]
  (when table_id
    (some-> (remote-sync.db/instance :model/Table table_id) published-in-remote-synced-collection?)))

(defn source-model
  "The model whose instances the spec's events carry and its eligibility is checked on."
  [spec]
  (or (:source-model spec) (:model-key spec)))

(defn row-exists?
  "Whether the spec's model has a row for `id`, which always holds for a spec without a `:row-key`."
  [{:keys [model-key row-key]} id]
  (or (nil? row-key)
      (remote-sync.db/row-exists? model-key row-key id)))

(defmethod check-eligibility-by-type :setting
  [{:keys [eligibility]} _object]
  (setting/get-value-of-type :boolean (:setting eligibility)))

(defmethod check-eligibility-by-type :library-synced
  [_spec _object]
  (rs-settings/library-is-remote-synced?))

(defmethod check-eligibility-by-type :always
  [_ _]
  true)

(defmethod check-eligibility-by-type :default
  [_ _]
  false)

(defmulti batch-check-eligibility
  "Batch version of check-eligibility. Returns a map of instance-id -> eligible? boolean."
  {:arglists '([spec instances])}
  (fn [spec _instances] (get-in spec [:eligibility :type])))

(defmethod batch-check-eligibility :library-synced
  [{:keys [conditions]} instances]
  (let [library-on? (rs-settings/library-is-remote-synced?)]
    (into {} (map (fn [inst]
                    [(:id inst) (boolean (and library-on?
                                              (object-matches-conditions? conditions inst)))]))
          instances)))

(defmethod batch-check-eligibility :default
  [spec instances]
  (into {} (map (fn [inst] [(:id inst) (check-eligibility spec inst)])) instances))

;;; -------------------------------------------- Editability Checking ------------------------------------------------

(defn model-editable?
  "Determines if a model instance is editable based on remote sync configuration.

   Returns false if:
   - Remote sync is enabled AND
   - The model has a spec in remote-sync-specs AND
   - The instance is eligible for sync (via check-eligibility) AND
   - remote-sync-type is :read-only

   For models with global eligibility (e.g., :library-synced, :setting), the instance
   argument can be nil or an empty map since eligibility doesn't depend on instance data."
  [model-key instance]
  (if-let [spec (and (rs-settings/remote-sync-enabled) (spec-for-model-key model-key))]
    (or (= (rs-settings/remote-sync-type) :read-write)
        (not (check-eligibility spec instance)))
    true))

(defn batch-model-editable?
  "Batch version of model-editable?. Returns a map of instance-id -> editable? boolean."
  [model-key instances]
  (if-let [spec (and (rs-settings/remote-sync-enabled) (spec-for-model-key model-key))]
    (if (= (rs-settings/remote-sync-type) :read-write)
      (into {} (map (fn [inst] [(:id inst) true])) instances)
      (let [eligibility-map (batch-check-eligibility spec instances)]
        (into {} (map (fn [[id eligible?]] [id (not eligible?)])) eligibility-map)))
    (into {} (map (fn [inst] [(:id inst) true])) instances)))

;;; ---------------------------------------------------- Hydration -----------------------------------------------------

(defn hydrate-model-details
  "Returns a map with the fields (always including :id) needed to populate a RemoteSyncObject for `spec`."
  [{:keys [model-key tracking]} model-id]
  (if (:hydrate-query? tracking)
    ;; Use the tracking-join query for models needing a Table join (Field, Segment, Measure)
    (remote-sync.db/tracking-details-by-id model-key model-id)
    ;; Simple select using select-fields
    (when-let [fields (:select-fields tracking)]
      (remote-sync.db/instance-with-columns model-key (into [:id] fields) model-id))))

(defn build-sync-object-fields
  "Builds the fields map for RemoteSyncObject from hydrated model details.
   Applies any transform functions defined in field-mappings."
  [{:keys [tracking]} model-details]
  (when model-details
    (into {}
          (for [[sync-field source-spec] (:field-mappings tracking)]
            (let [value (cond
                          ;; Simple keyword - just get the field
                          (keyword? source-spec)
                          (get model-details source-spec)

                          ;; Vector with transform function [field transform-fn]
                          (vector? source-spec)
                          (let [[field transform-fn] source-spec]
                            (transform-fn (get model-details field)))

                          :else
                          source-spec)]
              [sync-field value])))))

;;; ------------------------------------------------ Identity Resolution -----------------------------------------------

(defmulti extract-identity
  "Extracts the identity for a model instance based on the spec's identity strategy.
   Used for matching during import/export."
  {:arglists '([spec instance])}
  (fn [spec _instance] (:identity spec)))

(defmethod extract-identity :entity-id
  [_ instance]
  {:entity-id (:entity_id instance)})

(defmethod extract-identity :path
  [{:keys [path-keys]} instance]
  ;; Path-based identity uses the path-keys to build a unique identifier
  (select-keys instance path-keys))

(defmethod extract-identity :hybrid
  [{:keys [path-keys]} instance]
  ;; Hybrid uses both entity_id and path context
  {:entity-id (:entity_id instance)
   :path      (select-keys instance path-keys)})

;;; ----------------------------------------- Serdes Path Identity Extraction ------------------------------------------

(def ^:private serdes-path-identity-hierarchy
  "Hierarchy for extract-identity-from-serdes-path dispatch. Both :entity-id and :hybrid models
   extract identity the same way (entity_id from last path element)."
  (-> (make-hierarchy)
      (derive :entity-id ::entity-id-extractor)
      (derive :hybrid ::entity-id-extractor)))

(defmulti extract-identity-from-serdes-path
  "Extracts identity data from a serdes path based on the spec's identity strategy. For entity-id
   and hybrid models, returns the entity_id string from the last path element. For path-based models
   like Table and Field, returns a map with database, schema, and table/field names that can be used
   to look up the entity. A spec with `:natural-key-paths?` may also be keyed on a natural key (files
   exported before the model had an entity_id); its paths are resolved through `serdes/load-find-local`, and
   through the entity's natural key when `ingest-one` (path -> ingested entity, or nil) is given."
  {:arglists '([spec serdes-path ingest-one])}
  (fn [spec _path _ingest-one] (:identity spec))
  :hierarchy #'serdes-path-identity-hierarchy)

(defn- natural-key-entity-id
  "The entity_id of the local row whose natural-key column (the spec's tracked name column) equals `ingested`'s,
  or nil."
  [{:keys [model-key] :as spec} ingested]
  (let [column (get-in spec [:tracking :field-mappings :model_name])]
    (when-some [value (get ingested column)]
      (remote-sync.db/entity-id-where model-key column value))))

(defmethod extract-identity-from-serdes-path ::entity-id-extractor
  [{:keys [natural-key-paths?] :as spec} serdes-path ingest-one]
  (let [id (:id (last serdes-path))]
    (if natural-key-paths?
      ;; The path id may be a natural key (a glossary term, before `entity_id` existed) naming whichever local row
      ;; the loader matches it to, so use that row's entity_id. Before the load there may be no row with that id
      ;; yet; the loader then matches the entity on its natural key, so resolve the same way when the entity can
      ;; be read. Failing both, the raw id is kept, since it matches no local row (harmless to the removal
      ;; anti-join) and still counts as an imported entity.
      (or (:entity_id (serdes/load-find-local serdes-path))
          (when ingest-one (natural-key-entity-id spec (ingest-one serdes-path)))
          id)
      id)))

(defmethod extract-identity-from-serdes-path :user-settings
  [_ serdes-path _ingest-one]
  serdes-path)

(defmethod extract-identity-from-serdes-path :default
  [_ _ _]
  nil)

(defn extract-imported-entities
  "Processes serdes paths from an import and extracts entity identities grouped by how they should be looked up.
   Returns a map with :by-entity-id containing entity_ids grouped by model type, and :by-path containing
   the serdes paths of the user settings models, which are only counted.

   `ingest-one` (path -> ingested entity) is for the pre-load conflict check: a `:natural-key-paths?` path whose
   id matches no local row yet resolves to the row the loader will match on the entity's natural key."
  ([seen-paths]
   (extract-imported-entities seen-paths nil))
  ([seen-paths ingest-one]
   (reduce
    (fn [acc path]
      (let [model-type (-> path last :model)]
        (if-let [spec (spec-for-model-type model-type)]
          (let [identity-type (:identity spec)
                identity-data (extract-identity-from-serdes-path spec path ingest-one)]
            (if identity-data
              (case identity-type
                (:entity-id :hybrid)
                (update-in acc [:by-entity-id model-type] (fnil conj #{}) identity-data)

                :user-settings
                (update-in acc [:by-path (:model-key spec)] (fnil conj []) identity-data)

                acc)
              acc))
          acc)))
    {:by-entity-id {}
     :by-path {}}
    seen-paths)))

;;; -------------------------------------------- Event Helper Functions ------------------------------------------------

(defn determine-status
  "Determines the sync status based on event type and archived state."
  [{:keys [archived-key]} topic object]
  (let [archived? (and archived-key (get object archived-key))]
    (if archived?
      "delete"
      (let [topic-name (name topic)]
        (cond
          (str/ends-with? topic-name "-create") "create"
          (str/ends-with? topic-name "-update") "update"
          (str/ends-with? topic-name "-delete") "delete"
          :else "update")))))

(defn event-keywords
  "Returns a map of event keywords for a spec: {:parent :create :update :delete}."
  [{:keys [model-type events]}]
  (let [{:keys [prefix types]} events
        ns-str (namespace prefix)
        base   (name prefix)]
    (merge
     {:parent (keyword "metabase-enterprise.remote-sync.events"
                       (str (u/->kebab-case-en model-type) "-change-event"))}
     (into {}
           (for [event-type types]
             [event-type (keyword ns-str (str base "-" (name event-type)))])))))

;;; ---------------------------------------------- Spec Field Accessors ------------------------------------------------

(defn fields-for-sync
  "Returns the fields to select for a model during sync operations.
   Falls back to default if not specified in spec."
  [model-type-str]
  (if-let [spec (spec-for-model-type model-type-str)]
    (or (get-in spec [:tracking :select-fields])
        [:id :name :collection_id])
    [:id :name :collection_id]))

;;; ----------------------------------------- Sync Object Query Functions --------------------------------------------

(defmulti query-entities-for-sync
  "Queries entities for sync based on identity type.
   Returns a sequence of maps ready for RemoteSyncObject insertion.

   Parameters:
   - spec: The model spec
   - data: For :entity-id/:hybrid - a collection of entity_ids
   - timestamp: The sync timestamp"
  {:arglists '([spec data timestamp])}
  (fn [spec _data _timestamp] (:identity spec)))

(defmethod query-entities-for-sync :entity-id
  [{:keys [model-type model-key tracking]} entity-ids timestamp]
  (when (seq entity-ids)
    (let [;; Get select fields from spec, with :id always included
          select-fields (into [:id] (or (:select-fields tracking) [:name :collection_id]))
          entities (remote-sync.db/instances-with-columns-by-entity-ids model-key select-fields entity-ids)]
      (map (fn [entity]
             (let [;; Apply field mappings
                   field-mappings (:field-mappings tracking)
                   mapped-fields (into {}
                                       (for [[sync-field source-spec] field-mappings]
                                         (let [value (cond
                                                       (keyword? source-spec)
                                                       (get entity source-spec)
                                                       (vector? source-spec)
                                                       (let [[field transform-fn] source-spec]
                                                         (transform-fn (get entity field)))
                                                       :else source-spec)]
                                           [sync-field value])))]
               (merge {:model_type        model-type
                       :model_id          (:id entity)
                       :status            "synced"
                       :status_changed_at timestamp}
                      mapped-fields)))
           entities))))

(defmethod query-entities-for-sync :hybrid
  ;; Hybrid models like Segment need a join query for table info
  [{:keys [model-type model-key tracking]} entity-ids timestamp]
  (when (seq entity-ids)
    (when (:hydrate-query? tracking)
      (->> (remote-sync.db/tracking-details-by-entity-ids model-key entity-ids)
           (map (fn [entity]
                  (let [field-mappings (:field-mappings tracking)
                        mapped-fields (into {}
                                            (for [[sync-field source-spec] field-mappings]
                                              [sync-field (get entity source-spec)]))]
                    (merge {:model_type        model-type
                            :model_id          (:id entity)
                            :status            "synced"
                            :status_changed_at timestamp}
                           mapped-fields))))))))

(defmethod query-entities-for-sync :default
  [_ _ _]
  nil)

(defn sync-all-entities!
  "Builds RemoteSyncObject entries for all imported entities based on their specs. Iterates over enabled
   specs and queries the database to hydrate the fields needed for each sync object. Returns a sequence
   of maps ready for insertion into the RemoteSyncObject table."
  [timestamp {:keys [by-entity-id]}]
  (into []
        (for [[_model-key spec] (enabled-specs)
              :let [data (get by-entity-id (:model-type spec))]
              :when (seq data)
              entity (query-entities-for-sync spec data timestamp)]
          entity)))

;;; -------------------------------------------- Export Extraction ------------------------------------------------

(defmulti query-export-roots
  "Queries for root-level export targets based on eligibility configuration.
   Returns a sequence of [model-type id] tuples for initial targets, or nil if
   this model type's targets are derived from other models (e.g., via serdes/descendants)."
  {:arglists '([spec])}
  (fn [spec] (get-in spec [:eligibility :type])))

(defn- library-synced-root-export-roots
  "The `[model-type id]` export roots of `spec`'s unarchived Library content outside of any Collection, when the
  Library is synced; that in data actions Collections is exported with them."
  [{:keys [model-key model-type archived-key eligibility]}]
  (when-let [conditions (:library-synced-conditions eligibility)]
    (when (rs-settings/library-is-remote-synced?)
      (into #{}
            (map (fn [id] [model-type id]))
            (remote-sync.db/ids-where model-key (cond-> (assoc conditions :collection_id nil)
                                                  archived-key (assoc archived-key false)))))))

(defmethod query-export-roots :collection
  [{:keys [export-scope] :as spec}]
  (case (or export-scope :derived)
    :root-collections
    ;; Excludes archived collections - their files are handled by the removal logic
    (let [collection-keys (fn [ids] (into #{} (map (fn [id] ["Collection" id])) ids))]
      (concat
       (collection-keys (remote-sync.db/unarchived-remote-synced-root-collection-ids))
       (when (rs-settings/remote-sync-transforms)
         (collection-keys (remote-sync.db/unarchived-root-collection-ids-in-namespace (name collections/transforms-ns))))
       (when (rs-settings/library-is-remote-synced?)
         (collection-keys (remote-sync.db/unarchived-root-collection-ids-in-namespace "snippets")))
       (when (rs-settings/library-is-remote-synced?)
         (collection-keys (remote-sync.db/unarchived-root-collection-ids-in-namespace
                           (name collections/data-actions-ns))))
       (collection-keys (remote-sync.db/unarchived-root-collection-ids-in-namespace (name collections/data-apps-ns)))))
    :derived
    (library-synced-root-export-roots spec)))

(defmethod query-export-roots :setting
  [{:keys [export-scope model-key model-type] :as spec}]
  (when (spec-enabled? spec)
    (let [conditions (export-conditions spec)
          model-keys (fn [ids] (into #{} (map (fn [id] [model-type id])) ids))]
      (case export-scope
        :root-only
        (model-keys (remote-sync.db/ids-where model-key (assoc conditions :collection_id nil)))
        :all
        (model-keys (remote-sync.db/ids-where model-key conditions))
        nil))))

(defmethod query-export-roots :published-table [_] nil)
(defmethod query-export-roots :parent-table [_] nil)

(defmethod query-export-roots :library-synced
  [{:keys [export-scope model-key model-type archived-key] :as spec}]
  (when (spec-enabled? spec)
    (case export-scope
      :all
      (into #{}
            (map (fn [id] [model-type id]))
            (remote-sync.db/ids-where model-key (when archived-key {archived-key false})))
      nil)))

(defmethod query-export-roots :always
  [{:keys [export-scope model-key model-type] :as spec}]
  (case export-scope
    :all
    (into #{}
          (map (fn [id] [model-type id]))
          (remote-sync.db/ids-where model-key (export-conditions spec)))
    nil))

(defmethod query-export-roots :default [_] nil)

(def git-sync-extract-opts
  "Serdes extraction opts for git sync."
  {:include-field-values     false
   :include-database-secrets false
   :continue-on-error        false
   :skip-archived            true})

(def ^:private models-traversed-but-not-stored
  "Models git sync walks through but never writes."
  #{"Table" "Field"})

(defn exportable-entities
  "What a full export would serialize: a map of {model-name [id ...]} — the export roots plus their transitive
  `serdes/descendants`/`required` closure — or `{}` when there is no remote-syncable content."
  []
  (let [root-targets (into []
                           (mapcat query-export-roots)
                           (vals (enabled-specs)))
        targets (-> #{}
                    (into (keys (u/traverse root-targets #(serdes/descendants (first %) (second %) git-sync-extract-opts))))
                    (into (keys (u/traverse root-targets #(serdes/required (first %) (second %))))))]
    (apply dissoc (u/group-by first second targets) models-traversed-but-not-stored)))

(defn exportable-entity-count
  "Number of entities `targets` (a map as returned by [[exportable-entities]]) names. An upper bound on what
  [[extract-entities-for-export]] yields, suitable for progress reporting."
  [targets]
  (transduce (map count) + 0 (vals targets)))

(defn extract-entities-for-export
  "Extracts all entities for remote-sync export based on enabled specs.

   Returns an eduction of serialized entities ready for storage. Every traversal re-runs the extraction, so
   callers must reduce it once.

   `targets` defaults to [[exportable-entities]]; pass it explicitly when the same map is needed for
   [[exportable-entity-count]] so the dependency walk runs once.

   Only extracts models that:
   1. Have a spec in remote-sync-specs
   2. Are currently enabled (based on :enabled? field)
   3. Are in one of the provided collections (or descendants)"
  ([]
   (extract-entities-for-export (exportable-entities)))
  ([targets]
   (eduction (map (fn [[model ids]]
                    (serdes/extract-all model (merge git-sync-extract-opts
                                                     {:filter-column (serdes/primary-key model)
                                                      :filter-ids    (vec ids)}))))
             cat
             targets)))

(defn extract-entities-for-rows
  "Serializes the entities named by `rows`, grouped by model type. Each row is a map with a
   `:model_type` (the serdes model name) and a `:model_id` (the local DB primary key). Returns a lazy
   sequence of serialized entities."
  [rows]
  (let [by-model (u/group-by :model_type :model_id conj #{} rows)]
    (eduction (map (fn [[model ids]]
                     (serdes/extract-all model (merge git-sync-extract-opts
                                                      {:filter-column (serdes/primary-key model)
                                                       :filter-ids    (vec ids)}))))
              cat
              by-model)))