The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
Metric Dimensions: Healthy remote sync, with unportable but stable IDs (#82751)
Braden Shepherdson27e4890c7a46
diff --git a/.clj-kondo/config.edn b/.clj-kondo/config.ednindex e56de7889ed..3d155df2f07 100644--- a/.clj-kondo/config.edn+++ b/.clj-kondo/config.edn@@ -624,6 +624,7 @@metabase-enterprise.cache.config-test/with-temp-persist-models hooks.common/with-seven-bindingsmetabase-enterprise.dependencies.api-test/with-dependents-test! hooks.common/with-two-bindingsmetabase-enterprise.metabot-v3.tools.dependencies-test/with-dependent-transforms! hooks.common/with-two-bindings+ metabase-enterprise.remote-sync.metric-dimension-api-test/with-synced-metric hooks.common/with-one-bindingmetabase-enterprise.semantic-search.db.connection/with-migrate-tx hooks.common/let-one-with-optional-valuemetabase-enterprise.serialization.api-test/with-serialization-test-data! hooks.common/with-three-bindingsmetabase-enterprise.serialization.test-util/with-temp-dpc hooks.toucan2.tools.with-temp/with-tempdiff --git a/enterprise/backend/src/metabase_enterprise/dependencies/api.clj b/enterprise/backend/src/metabase_enterprise/dependencies/api.cljindex b7d53c23371..c517ea5e38e 100644--- a/enterprise/backend/src/metabase_enterprise/dependencies/api.clj+++ b/enterprise/backend/src/metabase_enterprise/dependencies/api.clj@@ -205,9 +205,9 @@{:card [:id :name :description :type :display :database_id :query_type :collection_id :dashboard_id :document_id :result_metadata:created_at :creator_id :view_count;; :card_schema always has to be selected, and every column the Card schema upgrade- ;; reads has to come with it. The last three are not part of the response — `entity-keys`+ ;; reads has to come with it. The last four are not part of the response — `entity-keys`;; decides that — they are here only to make the upgrade runnable.- :card_schema :dataset_query :dimensions :dimension_mappings]+ :card_schema :entity_id :dataset_query :dimensions :dimension_mappings]:dashboard [:id :name :description :created_at :creator_id :collection_id :view_count]:document [:id :name :created_at :creator_id :collection_id :view_count]:table [:id :name :description :display_name :db_id :schemadiff --git a/enterprise/backend/src/metabase_enterprise/dependencies/events.clj b/enterprise/backend/src/metabase_enterprise/dependencies/events.cljindex d56f4e4a0fd..4e10be69122 100644--- a/enterprise/backend/src/metabase_enterprise/dependencies/events.clj+++ b/enterprise/backend/src/metabase_enterprise/dependencies/events.clj@@ -32,7 +32,6 @@(events/derive! ::card-deps :metabase/event)(events/derive! :event/card-create ::card-deps)(events/derive! :event/card-update ::card-deps)-(events/derive! :event/metric-dimensions-update ::card-deps)(methodical/defmethod events/publish-event! ::card-deps[_ {:keys [object]}]diff --git a/enterprise/backend/src/metabase_enterprise/sandbox/db.clj b/enterprise/backend/src/metabase_enterprise/sandbox/db.cljindex 03b8b1527bd..5e5318edc56 100644--- a/enterprise/backend/src/metabase_enterprise/sandbox/db.clj+++ b/enterprise/backend/src/metabase_enterprise/sandbox/db.clj@@ -203,7 +203,7 @@(t2/select :model/Card{:select [:c.id :c.dataset_query :c.database_id :c.card_schema;; required alongside :card_schema for the Card schema upgrade- :c.type :c.result_metadata :c.dimensions :c.dimension_mappings]+ :c.type :c.entity_id :c.result_metadata :c.dimensions :c.dimension_mappings]:from [[(t2/table-name :model/Card) :c]]:where [:exists ^:allow-subquery {:select [[[:inline 1]]]:from [[(t2/table-name :model/Sandbox) :s]]diff --git a/enterprise/backend/src/metabase_enterprise/stale/db.clj b/enterprise/backend/src/metabase_enterprise/stale/db.cljindex b738f39fac4..4402cba3b50 100644--- a/enterprise/backend/src/metabase_enterprise/stale/db.clj+++ b/enterprise/backend/src/metabase_enterprise/stale/db.clj@@ -38,6 +38,7 @@;; :type is read by `queries/model?` when labelling the row; the rest are here only;; because :dataset_query is schema-governed and the Card schema upgrade needs them.:type+ :entity_id:result_metadata:dimensions:dimension_mappingsdiff --git a/enterprise/backend/test/metabase_enterprise/audit_app/audit_test.clj b/enterprise/backend/test/metabase_enterprise/audit_app/audit_test.cljindex 6bd675254c7..1d452ebb7d3 100644--- a/enterprise/backend/test/metabase_enterprise/audit_app/audit_test.clj+++ b/enterprise/backend/test/metabase_enterprise/audit_app/audit_test.clj@@ -13,6 +13,7 @@[metabase.permissions-rest.data-permissions.graph :as data-perms.graph][metabase.permissions.models.permissions-group :as perms-group][metabase.plugins.core :as plugins]+ [metabase.queries.card-schema :as card-schema][metabase.sync.core :as sync.core][metabase.sync.sync :as sync][metabase.sync.task.sync-databases :as task.sync-databases]@@ -66,8 +67,7 @@(is (not= 0 (t2/count :model/Card {:where [:= :database_id audit/audit-db-id]}))"Cards should be created for Audit DB when the content is there."))(testing "Cards in the audit collection have non-empty :result_metadata after installation"- (let [audit-cards (t2/select [:model/Card :id :name :result_metadata :card_schema :type :database_id :dataset_query :dimensions :dimension_mappings]- :database_id audit/audit-db-id)+ (let [audit-cards (t2/select (card-schema/selection [:name]) :database_id audit/audit-db-id)audit-cards-no-metadata (filter (comp empty? :result_metadata) audit-cards)](is (seq audit-cards))(is (empty? audit-cards-no-metadata)diff --git a/enterprise/backend/test/metabase_enterprise/dependencies/events_test.clj b/enterprise/backend/test/metabase_enterprise/dependencies/events_test.cljindex 943682dc3a8..b9f5efadd08 100644--- a/enterprise/backend/test/metabase_enterprise/dependencies/events_test.clj+++ b/enterprise/backend/test/metabase_enterprise/dependencies/events_test.clj@@ -255,7 +255,7 @@(assert-stale :card card-id)))))))(deftest metric-dimensions-update-marks-stale-and-includes-mapped-table-test- (testing ":event/metric-dimensions-update marks the metric card stale and recomputes deps, including mapped-dimension tables"+ (testing "a metric dimension write marks the metric card stale and recomputes deps, including mapped-dimension tables"(run-with-dependencies-setup!(fn [mp](let [base (-> (lib/query mp (lib.metadata/table mp (mt/id :venues)))@@ -265,12 +265,18 @@;; uncurated, so the after-insert dimension auto-sync would seed dimensions from the query and;; overwrite mappings passed to with-temp. A plain update sticks — the after-update hook only;; re-syncs when `:dataset_query` changes.- (t2/update! :model/Card card-id- {:dimension_mappings [{:type :table- :dimension-id "550e8400-e29b-41d4-a716-446655440000"- :table-id (mt/id :categories)- :target [:field {} (mt/id :categories :name)]}]})- (events/publish-event! :event/metric-dimensions-update {:object {:id card-id}})+ ;; The dimension endpoints announce their writes as card updates; see+ ;; [[metabase.metrics.api/notify-dimensions-changed!]].+ (let [before (t2/select-one :model/Card :id card-id)]+ (t2/update! :model/Card card-id+ {:dimension_mappings [{:type :table+ :dimension-id "550e8400-e29b-41d4-a716-446655440000"+ :table-id (mt/id :categories)+ :target [:field {} (mt/id :categories :name)]}]})+ (events/publish-event! :event/card-update+ {:object (t2/select-one :model/Card :id card-id)+ :previous-object before+ :user-id api/*current-user-id*}))(assert-stale :card card-id)(deps.test/synchronously-run-backfill!)(is (t2/exists? :model/Dependency :from_entity_type :card :from_entity_id card-iddiff --git a/enterprise/backend/test/metabase_enterprise/dependencies/metadata_update_test.clj b/enterprise/backend/test/metabase_enterprise/dependencies/metadata_update_test.cljindex df360d407f0..a6a9f1e5ce3 100644--- a/enterprise/backend/test/metabase_enterprise/dependencies/metadata_update_test.clj+++ b/enterprise/backend/test/metabase_enterprise/dependencies/metadata_update_test.clj@@ -14,6 +14,7 @@[metabase.lib-be.core :as lib-be][metabase.lib.core :as lib][metabase.lib.metadata :as lib.metadata]+ [metabase.queries.card-schema :as card-schema][metabase.sync.core :as sync][metabase.test :as mt][metabase.test.data.one-off-dbs :as one-off-dbs]@@ -130,7 +131,7 @@:to_entity_id child-id}](is (= #{8}(t2/select-fn-set (comp count :result_metadata)- [:model/Card :id :result_metadata :card_schema :type :database_id :dataset_query :dimensions :dimension_mappings]+ (card-schema/selection [:database_id]):id [:in [parent-id child-id grandchild-id]])))(t2/update! :model/Card parent-id {:dataset_query (lib/query mp orders)})(mt/with-dynamic-fn-redefs [async/submit! (fn [f] (f))]@@ -140,7 +141,7 @@:user-id api/*current-user-id*}))(is (= #{9}(t2/select-fn-set (comp count :result_metadata)- [:model/Card :id :result_metadata :card_schema :type :database_id :dataset_query :dimensions :dimension_mappings]+ (card-schema/selection [:database_id]):id [:in [parent-id child-id grandchild-id]])))))))))(deftest ^:synchronized native-card-update-does-not-update-children-test@@ -165,7 +166,7 @@:user-id api/*current-user-id*}))(is (= nil(t2/select-one-fn :result_metadata- [:model/Card :id :result_metadata :card_schema :type :database_id :dataset_query :dimensions :dimension_mappings]+ (card-schema/selection [:database_id]):id child-id)))))))))(deftest ^:synchronized model-update-passes-down-new-values-test@@ -201,7 +202,7 @@:user-id api/*current-user-id*}))(is (= #{[child-id "new-name"] [grandchild-id "new-name"]}(t2/select-fn-set (juxt :id #(get-in % [:result_metadata 0 :display_name]))- [:model/Card :id :result_metadata :card_schema :type :database_id :dataset_query :dimensions :dimension_mappings]+ (card-schema/selection [:database_id]):id [:in [child-id grandchild-id]]))))))))))(deftest ^:synchronized model-update-respects-child-overrides-test@@ -244,7 +245,7 @@:user-id api/*current-user-id*}))(is (= #{[child-id "child-name"] [grandchild-id "grandchild-name"]}(t2/select-fn-set (juxt :id #(get-in % [:result_metadata 0 :display_name]))- [:model/Card :id :result_metadata :card_schema :type :database_id :dataset_query :dimensions :dimension_mappings]+ (card-schema/selection [:database_id]):id [:in [child-id grandchild-id]]))))))))))(deftest ^:synchronized model-update-stops-recursing-when-child-metadata-is-unchanged-test@@ -286,7 +287,7 @@:user-id api/*current-user-id*}))(is (= nil(t2/select-one-fn #(get-in % [:result_metadata 0 :display_name])- [:model/Card :id :result_metadata :card_schema :type :database_id :dataset_query :dimensions :dimension_mappings]+ (card-schema/selection [:database_id]):id grandchild-id))))))))))(defn- with-syncable-db! [thunk]diff --git a/enterprise/backend/test/metabase_enterprise/remote_sync/metric_dimension_api_test.clj b/enterprise/backend/test/metabase_enterprise/remote_sync/metric_dimension_api_test.cljnew file mode 100644index 00000000000..2f8bcfb5ba7--- /dev/null+++ b/enterprise/backend/test/metabase_enterprise/remote_sync/metric_dimension_api_test.clj@@ -0,0 +1,139 @@+(ns ^:synchronized metabase-enterprise.remote-sync.metric-dimension-api-test+ "The `/api/metric/:id/dimension/*` endpoints write a Card's `dimensions`/`dimension_mappings`+ directly, bypassing the regular card-update path. Since those columns are serialized, every one of+ those writes has to reach remote sync's dirty tracking, which listens only for the standard+ per-model event families."+ (:require+ [clojure.test :refer :all]+ [java-time.api :as t]+ [metabase-enterprise.remote-sync.source :as source]+ [metabase.lib.core :as lib]+ [metabase.lib.metadata :as lib.metadata]+ [metabase.metrics.core :as metrics]+ [metabase.test :as mt]+ [metabase.test.fixtures :as fixtures]+ [metabase.util :as u]+ [toucan2.core :as t2]))++(use-fixtures :once (fixtures/initialize :db :web-server :test-users))++(use-fixtures :each (fn [thunk]+ (mt/with-temporary-setting-values [remote-sync-type :read-write]+ (thunk))))++(defn- metric-query []+ (let [mp (mt/metadata-provider)]+ (-> (lib/query mp (lib.metadata/table mp (mt/id :venues)))+ (lib/aggregate (lib/count)))))++(defn- mark-synced!+ "Put the Card's RemoteSyncObject in the state a successful export leaves behind: `synced`, with the+ content hash of the row as it stands right now."+ [card-id]+ (t2/delete! :model/RemoteSyncObject :model_type "Card" :model_id card-id)+ (t2/insert! :model/RemoteSyncObject+ {:model_type "Card"+ :model_id card-id+ :model_name (t2/select-one-fn :name :model/Card card-id)+ :status "synced"+ :content_hash (source/row->content-hash {:model_type "Card" :model_id card-id})+ :status_changed_at (t/offset-date-time)}))++(defn- sync-status [card-id]+ (t2/select-one-fn :status :model/RemoteSyncObject :model_type "Card" :model_id card-id))++(defmacro ^:private with-synced-metric+ "Binds a seeded metric Card living in a remote-synced collection, with its RemoteSyncObject already+ marked `synced`."+ [[metric-binding] & body]+ `(mt/with-temp [:model/Collection collection# {:name "Remote-Synced" :location "/" :is_remote_synced true}+ :model/Card metric# {:name "Synced Metric"+ :type :metric+ :collection_id (:id collection#)+ :database_id (mt/id)+ :table_id (mt/id :venues)+ :dataset_query (metric-query)}]+ (metrics/sync-dimensions! :metadata/metric (:id metric#))+ (mark-synced! (:id metric#))+ (let [~metric-binding (t2/select-one :model/Card :id (:id metric#))]+ ~@body)))++(defn- dimension-id [metric column-name]+ (:id (u/seek #(= column-name (:name %)) (:dimensions metric))))++(deftest add-dimension-marks-card-dirty-test+ (testing "POST /api/metric/:id/dimension/add marks the metric dirty for remote sync"+ (with-synced-metric [metric]+ (let [addable (->> (mt/user-http-request :crowberto :get 200+ (str "metric/" (:id metric) "/dimension")+ :with-addable true)+ :addable first :dimensions first)]+ (is (some? addable) "there should be a joinable column available to add")+ (mt/user-http-request :crowberto :post 200 (str "metric/" (:id metric) "/dimension/add")+ {:dimensions [{:id (str (random-uuid))+ :mapping_target (:mapping_target addable)}]})+ (is (= "update" (sync-status (:id metric))))))))++(deftest remove-dimension-marks-card-dirty-test+ (testing "POST /api/metric/:id/dimension/remove marks the metric dirty for remote sync"+ (with-synced-metric [metric]+ (mt/user-http-request :crowberto :post 200 (str "metric/" (:id metric) "/dimension/remove")+ {:dimension_ids [(dimension-id metric "PRICE")]})+ (is (= "update" (sync-status (:id metric)))))))++(deftest set-default-dimension-marks-card-dirty-test+ (testing "POST /api/metric/:id/dimension/set-default marks the metric dirty for remote sync"+ (with-synced-metric [metric]+ (mt/user-http-request :crowberto :post 200 (str "metric/" (:id metric) "/dimension/set-default")+ {:dimension_id (dimension-id metric "PRICE")})+ (is (= "update" (sync-status (:id metric)))))))++(deftest reorder-dimensions-marks-card-dirty-test+ (testing "POST /api/metric/:id/dimension/reorder marks the metric dirty for remote sync"+ (with-synced-metric [metric]+ (let [ids (mapv :id (:dimensions metric))]+ (mt/user-http-request :crowberto :post 200 (str "metric/" (:id metric) "/dimension/reorder")+ {:dimension_ids (vec (reverse ids))})+ (is (= "update" (sync-status (:id metric))))))))++(deftest update-dimension-marks-card-dirty-test+ (testing "POST /api/metric/:id/dimension/:dimension-key marks the metric dirty for remote sync"+ (with-synced-metric [metric]+ (mt/user-http-request :crowberto :post 200+ (str "metric/" (:id metric) "/dimension/" (dimension-id metric "PRICE"))+ {:display_name "Cost"})+ (is (= "update" (sync-status (:id metric)))))))++(deftest no-op-dimension-write-leaves-card-synced-test+ (testing "a dimension write that does not change the metric's serialized content leaves it synced"+ (with-synced-metric [metric]+ (mt/user-http-request :crowberto :post 200 (str "metric/" (:id metric) "/dimension/reorder")+ {:dimension_ids (mapv :id (:dimensions metric))})+ (is (= "synced" (sync-status (:id metric)))))))++(deftest pre-curation-metric-content-hash-is-stable-test+ (testing "A metric that predates curated dimensions has no stored dimensions — the `card_schema`+ 23→24 upgrade synthesizes them on every read, and nothing persists that. Its exported+ content therefore has to be identical read to read, or every such metric would look+ permanently dirty after a customer upgrades."+ (mt/with-temp [:model/Collection collection {:name "Remote-Synced" :location "/" :is_remote_synced true}+ :model/Card metric {:name "Pre-curation Metric"+ :type :metric+ :collection_id (:id collection)+ :database_id (mt/id)+ :table_id (mt/id :venues)+ :dataset_query (metric-query)}]+ (t2/query-one {:update :report_card+ :set {:card_schema 23 :dimensions nil :dimension_mappings nil}+ :where [:= :id (:id metric)]})+ (let [content-hash #(source/row->content-hash {:model_type "Card" :model_id (:id metric)})]+ (is (= (content-hash) (content-hash) (content-hash))+ "the upgrade derives its dimension ids from the card's entity_id and each mapping target+ instead of generating them, so the content hash is the same every time it is taken")))))++(deftest reading-dimensions-leaves-card-synced-test+ (testing "GET /api/metric/:id/dimension does not dirty the metric — a read-triggered dimension+ refresh is not a user edit"+ (with-synced-metric [metric]+ (mt/user-http-request :crowberto :get 200 (str "metric/" (:id metric) "/dimension"))+ (is (= "synced" (sync-status (:id metric)))))))diff --git a/enterprise/backend/test/metabase_enterprise/serialization/v2/e2e_test.clj b/enterprise/backend/test/metabase_enterprise/serialization/v2/e2e_test.cljindex f11e3815a13..5c75f99b98b 100644--- a/enterprise/backend/test/metabase_enterprise/serialization/v2/e2e_test.clj+++ b/enterprise/backend/test/metabase_enterprise/serialization/v2/e2e_test.clj@@ -17,6 +17,7 @@[metabase.lib.core :as lib][metabase.lib.metadata :as lib.metadata][metabase.models.serialization :as serdes]+ [metabase.queries.card-schema :as card-schema][metabase.query-processor :as qp][metabase.query-processor.compile :as qp.compile][metabase.search.core :as search]@@ -1004,11 +1005,7 @@[:field %products.category {:join-alias "Products"}]]}]})}];; Populate the native source card's result_metadata the way the app does when a user runs and;; saves the query. This is the state serdes must preserve across the round-trip.- (let [source-cols (-> (qp/process-query (t2/select-one-fn :dataset_query- [:model/Card :id :dataset_query :card_schema- :type :database_id :result_metadata- :dimensions :dimension_mappings]- native-id))+ (let [source-cols (-> (qp/process-query (t2/select-one-fn :dataset_query (card-schema/selection) native-id))(get-in [:data :results_metadata :columns]))source-names (mapv :name source-cols)](t2/update! :model/Card native-id {:result_metadata source-cols})diff --git a/src/metabase/activity_feed/db.clj b/src/metabase/activity_feed/db.cljindex 88b34bd7ca0..f8b6429e11c 100644--- a/src/metabase/activity_feed/db.clj+++ b/src/metabase/activity_feed/db.clj@@ -18,7 +18,7 @@:id :name :collection_id :description :display:dataset_query :type :archived :card_schema;; required alongside :card_schema for the Card schema upgrade- :result_metadata :dimensions :dimension_mappings+ :entity_id :result_metadata :dimensions :dimension_mappings:collection.authority_level [:collection.name :collection_name][:dashboard.name :dashboard_name] :dashboard_id]{:where [:in :report_card.id ids]diff --git a/src/metabase/dashboards/db.clj b/src/metabase/dashboards/db.cljindex 01bca49d59c..6725388f55a 100644--- a/src/metabase/dashboards/db.clj+++ b/src/metabase/dashboards/db.clj@@ -173,7 +173,7 @@"The series Cards of the DashboardCards with `dashcard-ids`, each with its `:dashboardcard_id`, in series order."[dashcard-ids :- [:sequential ::lib.schema.id/dashcard]](t2/select [:model/Card :id :name :description :display :dataset_query :type :database_id- :visualization_settings :collection_id :card_schema :result_metadata+ :visualization_settings :collection_id :card_schema :entity_id :result_metadata:dimensions :dimension_mappings :series.dashboardcard_id]{:left-join [[:dashboardcard_series :series] [:= :report_card.id :series.card_id]]:where [:in :series.dashboardcard_id dashcard-ids]diff --git a/src/metabase/lib_metric/dimension.cljc b/src/metabase/lib_metric/dimension.cljcindex e63715919a8..2e2bf733927 100644--- a/src/metabase/lib_metric/dimension.cljc+++ b/src/metabase/lib_metric/dimension.cljc@@ -160,7 +160,10 @@(let [persisted-dim (find-persisted-by-target (:target mapping)persisted-mappingspersisted-dims-by-id)- dim-id (or (:id persisted-dim) (random-uuid-str))+ ;; A computed dimension arrives with an id already derived from its entity and target, and+ ;; so is stable across recomputation; the random fallback only covers callers that build+ ;; pairs by hand without one.+ dim-id (or (:id persisted-dim) (:id dimension) (random-uuid-str))merged-dim (-> dimension(assoc :id dim-id)(assoc :status :status/active)diff --git a/src/metabase/lib_metric/dimension/jvm.clj b/src/metabase/lib_metric/dimension/jvm.cljindex 1df7c545909..3bdfce1c7b8 100644--- a/src/metabase/lib_metric/dimension/jvm.clj+++ b/src/metabase/lib_metric/dimension/jvm.clj@@ -5,6 +5,7 @@(:require[metabase.lib-be.core :as lib-be][metabase.lib-metric.db :as lib-metric.db]+ [metabase.lib-metric.dimension :as lib-metric.dimension][metabase.lib-metric.metadata.provider :as lib-metric.provider][metabase.lib.core :as lib][metabase.lib.util :as lib.util]@@ -49,16 +50,52 @@(assoc-in [1 :source-field] (:lib/original-fk-field-id column)))ref)))+(defn- dimension-id+ "Id for a computed dimension, derived from the entity it belongs to and the column it maps to rather than+ generated.++ Un-curated metrics recompute their whole dimension set on every read (the `card_schema` 23->24 backfill) and+ persist nothing, so a generated id would hand the same metric a different dimension set — and therefore a+ different serialization — on every SELECT. Its remote-sync content hash would never settle, and anything that+ stored one of those ids would be pointing at nothing by the next read.++ `owner-key` scopes the id to its entity, so two metrics over the same column do not collide. That matters+ because ids are resolved entity-wide (`dimensions-for-table`) and instance-wide+ ([[metabase.lib-metric.dimension/dimension]]), not only against their own entity's `dimension_mappings`, and+ because the measure sync path persists these ids the first time it sees a column.++ Contrast [[group-id]], which is deliberately NOT scoped: a column group is the same group wherever it appears,+ and its id is already persisted unscoped on curated entities.++ `column-name` is in the seed because the target alone does not identify a column. [[field-id-ref]] rewrites a+ source-card column's ref to use the column's integer *field* id, and a model that joins one table twice — a+ self-join, or two joins to the same table — surfaces each of that table's fields twice with the same field id.+ The join alias that tells the two copies apart lives inside the *model's* query, not in the outer query's refs,+ so both targets reduce to the same [[metabase.lib-metric.dimension/field-ref->key]]. Without the name they+ would share an id, and since dimensions resolve by id, editing one would rewrite its twin. The deduplicated+ column name (`PRICE` vs `PRICE_2`) is what survives to tell them apart.++ This is a stable local seed, not a portable identity — `owner-key` and the target's field ids are both+ instance-local, so two instances derive different ids for the same logical dimension. Nothing depends on them+ agreeing: `dimensions` and `dimension_mappings` are serialized and imported as a unit."+ ^String [owner-key column-name target]+ (-> [owner-key column-name (lib-metric.dimension/field-ref->key target)]+ pr-str+ (.getBytes "UTF-8")+ UUID/nameUUIDFromBytes+ str))+(defn- column->computed-pair- "Convert a column to a dimension/mapping pair. IDs are nil until reconciliation.+ "Convert a column to a dimension/mapping pair. The dimension id is derived from `owner-key` and the mapping+ target; reconciliation replaces it with the persisted id when the column is already curated.The table-id is extracted from the column's metadata.When `group` is provided, it is attached to the dimension."- ([column]- (column->computed-pair column nil))- ([column group]+ ([owner-key column]+ (column->computed-pair owner-key column nil))+ ([owner-key column group](let [target (field-id-ref column)has-field-values (lib/infer-has-field-values column)]- {:dimension (cond-> {:id nil+ {:dimension (cond-> {:id (dimension-id owner-key (:name column) target):name (:name column):effective-type (or (:effective-type column)(:base-type column))}@@ -116,11 +153,15 @@(str (UUID/nameUUIDFromBytes (.getBytes (str type-str "/" display-name) "UTF-8"))))(defn compute-dimension-pairs- "Compute dimension/mapping pairs from visible columns. IDs not yet assigned.+ "Compute dimension/mapping pairs from visible columns.Only includes actual database fields, not expressions.Dimensions are annotated with their source group (main table vs connected tables).- Columns are enriched with `:has-field-values` from the database."- [metadata-providerable query]+ Columns are enriched with `:has-field-values` from the database.++ `owner-key` is an opaque salt identifying the entity these dimensions belong to; see [[dimension-id]], which+ derives each dimension's id from it. It only has to be stable for the entity's lifetime on this instance, and+ callers that discard the ids (comparing targets only) may pass anything."+ [metadata-providerable owner-key query](let [mp (lib/->metadata-provider metadata-providerable)query-with-mp (lib/query mp query)db-mp (db-provider-for-query mp query-with-mp)@@ -149,5 +190,5 @@group-cols (lib/columns-group-columns col-group)](->> group-cols(remove #(= :source/expressions (:lib/source %)))- (perf/mapv #(column->computed-pair % group-desc))))))+ (perf/mapv #(column->computed-pair owner-key % group-desc))))))col-groups)))diff --git a/src/metabase/metrics/api.clj b/src/metabase/metrics/api.cljindex 05ad5030c25..560fe3ece85 100644--- a/src/metabase/metrics/api.clj+++ b/src/metabase/metrics/api.clj@@ -347,15 +347,21 @@(defn- write-check-metric! [id](api/write-check (metrics.db/metric-card id)))-;; The module-local parent keeps the topic publishable in OSS, where no consumer namespace derives-;; it. (A direct :metabase/event derive would throw once an EE consumer makes it an ancestor.)-(events/derive! ::dimensions-event :metabase/event)-(events/derive! :event/metric-dimensions-update ::dimensions-event)-(defn- notify-dimensions-changed!- "Signal that a metric's dimension mappings changed so its dependency graph is recomputed."- [id]- (events/publish-event! :event/metric-dimensions-update {:object {:id id}}))+ "Announce a write to metric `id`'s curated dimensions, given the `before` Card that+ [[write-check-metric!]] already fetched.++ These endpoints write `:dimensions`/`:dimension_mappings`, which are serialized columns, so the write has to+ reach everything a Card update normally reaches — remote-sync dirty tracking above all, which listens only for+ the standard per-model event families and so never saw the bespoke topic this replaces. Audit logging and the+ dependency graph come along for the ride; a dimension edit is a card edit.++ Revisions are unaffected: `metabase.revisions.impl.card` excludes both columns from the snapshot, and+ `push-revision!` skips a revision whose serialization is unchanged."+ [id before]+ (events/publish-event! :event/card-update {:object (metrics.db/metric-card id)+ :previous-object before+ :user-id api/*current-user-id*}))(api.macros/defendpoint :get "/:id/dimension":- [:map@@ -388,9 +394,9 @@[:display_name {:optional true} ms/NonBlankString][:description {:optional true} [:maybe :string]][:mapping_target ::lib-metric.schema/dimension-mapping.target]]]]]]- (write-check-metric! id)- (u/prog1 (metrics/add-dimensions! :metadata/metric id dimensions)- (notify-dimensions-changed! id)))+ (let [before (write-check-metric! id)]+ (u/prog1 (metrics/add-dimensions! :metadata/metric id dimensions)+ (notify-dimensions-changed! id before))))(api.macros/defendpoint :post "/:id/dimension/remove":- [:sequential :map]@@ -398,9 +404,9 @@[{:keys [id]} :- [:map {:closed true} [:id ms/PositiveInt]]_query-params{:keys [dimension_ids]} :- [:map {:closed true} [:dimension_ids [:sequential ms/NonBlankString]]]]- (write-check-metric! id)- (u/prog1 (metrics/remove-dimensions! :metadata/metric id dimension_ids)- (notify-dimensions-changed! id)))+ (let [before (write-check-metric! id)]+ (u/prog1 (metrics/remove-dimensions! :metadata/metric id dimension_ids)+ (notify-dimensions-changed! id before))))(api.macros/defendpoint :post "/:id/dimension/set-default":- [:sequential :map]@@ -410,8 +416,9 @@[{:keys [id]} :- [:map {:closed true} [:id ms/PositiveInt]]_query-params{:keys [dimension_id]} :- [:map {:closed true} [:dimension_id [:maybe ms/NonBlankString]]]]- (write-check-metric! id)- (metrics/set-default-dimension! :metadata/metric id dimension_id))+ (let [before (write-check-metric! id)]+ (u/prog1 (metrics/set-default-dimension! :metadata/metric id dimension_id)+ (notify-dimensions-changed! id before))))(api.macros/defendpoint :post "/:id/dimension/reorder":- [:sequential :map]@@ -421,8 +428,9 @@[{:keys [id]} :- [:map {:closed true} [:id ms/PositiveInt]]_query-params{:keys [dimension_ids]} :- [:map {:closed true} [:dimension_ids [:sequential ms/NonBlankString]]]]- (write-check-metric! id)- (metrics/reorder-dimensions! :metadata/metric id dimension_ids))+ (let [before (write-check-metric! id)]+ (u/prog1 (metrics/reorder-dimensions! :metadata/metric id dimension_ids)+ (notify-dimensions-changed! id before))))(api.macros/defendpoint :post "/:id/dimension/:dimension-key":- :map@@ -439,8 +447,6 @@[:description {:optional true} [:maybe :string]][:default_temporal_unit {:optional true} ms/NonBlankString][:source {:optional true} [:maybe [:map {:closed true} [:field-id ms/PositiveInt]]]]]]- (write-check-metric! id)- (u/prog1 (metrics/update-dimension! :metadata/metric id dimension-key body)- ;; Only a source-column change alters the mapping (and thus the deps graph).- (when (:source body)- (notify-dimensions-changed! id))))+ (let [before (write-check-metric! id)]+ (u/prog1 (metrics/update-dimension! :metadata/metric id dimension-key body)+ (notify-dimensions-changed! id before))))diff --git a/src/metabase/metrics/core.clj b/src/metabase/metrics/core.cljindex 81db52112d0..de4e9ee4e57 100644--- a/src/metabase/metrics/core.clj+++ b/src/metabase/metrics/core.clj@@ -103,6 +103,18 @@[entity](some? (lib-metric/get-persisted-dimensions entity)))+(defn- dimension-owner-key+ "The salt that scopes an entity's computed dimension ids to that entity; see+ [[metabase.lib-metric.dimension.jvm/compute-dimension-pairs]].++ Metrics are Cards and use their `:entity-id`, which survives an export/import round trip. Measures have no+ `:entity-id` on their metadata (`:metabase.lib.schema.metadata/measure` is closed), so they fall back to their+ local id — enough, since these ids are never required to agree across instances."+ [entity]+ (case (:lib/type entity)+ :metadata/measure (str "measure/" (:id entity))+ (:entity-id entity)))+;;; ------------------------------------------------- Hydration -------------------------------------------------(defn- save-dimensions-if-changed!@@ -184,11 +196,14 @@A newly created post-curation metric gets its own-table and explicitly joined columns as dimensions.In contrast, this function preserves the pre-curation behaviour, and returns every implicitly joinable- column."- [query]+ column.++ `owner-key` seeds the computed dimension ids; pass the metric Card's `:entity_id`. See+ [[metabase.lib-metric.dimension.jvm/compute-dimension-pairs]]."+ [owner-key query](when (seq query)(let [mp (lib-metric/metadata-provider)- computed-pairs (lib-metric/compute-dimension-pairs mp query)+ computed-pairs (lib-metric/compute-dimension-pairs mp owner-key query){:keys [dimensions dimension-mappings]}(lib-metric/reconcile-dimensions-and-mappings computed-pairs nil nil)]{:dimensions (-> (mapv table-prefixed-dimension dimensions)@@ -265,7 +280,7 @@{:lib/type metadata-type :id #{id}}))](when-let [query (lib-metric/dimensionable-query entity)](let [mp (lib-metric/metadata-provider)- computed-pairs (lib-metric/compute-dimension-pairs mp query)+ computed-pairs (lib-metric/compute-dimension-pairs mp (dimension-owner-key entity) query)persisted-dims (lib-metric/get-persisted-dimensions entity)persisted-mappings (lib-metric/get-persisted-dimension-mappings entity)@@ -308,7 +323,7 @@(lib-metric/metadata-provider){:lib/type metadata-type :id #{id}}))](when-let [query (lib-metric/dimensionable-query entity)]- (let [computed-pairs (lib-metric/compute-dimension-pairs (lib-metric/metadata-provider) query)+ (let [computed-pairs (lib-metric/compute-dimension-pairs (lib-metric/metadata-provider) (dimension-owner-key entity) query)persisted-dims (lib-metric/get-persisted-dimensions entity)persisted-mappings (lib-metric/get-persisted-dimension-mappings entity)](case metadata-type@@ -364,7 +379,7 @@"All computed dimension pairs (main + connection groups) for an entity's query, or `[]`."[entity](if-let [query (lib-metric/dimensionable-query entity)]- (lib-metric/compute-dimension-pairs (lib-metric/metadata-provider) query)+ (lib-metric/compute-dimension-pairs (lib-metric/metadata-provider) (dimension-owner-key entity) query)[]))(defn- pair->field-iddiff --git a/src/metabase/metrics/transforms.clj b/src/metabase/metrics/transforms.cljindex 14b34865072..a4118d7173a 100644--- a/src/metabase/metrics/transforms.clj+++ b/src/metabase/metrics/transforms.clj@@ -34,6 +34,10 @@[:default-temporal-unit {:optional true} [:or :string :keyword]][:default {:optional true} [:maybe :boolean]]]](cond-> dim+ ;; `:lib/source` arrives as a keyword on a computed dimension and as a string once it has been through the+ ;; JSON column. Keywordizing it here, like every other enum below, is what keeps a metric's serialization the+ ;; same before and after the backfill is persisted.+ (:lib/source dim) (update :lib/source keyword)(:status dim) (update :status keyword)(:effective-type dim) (update :effective-type keyword)(:semantic-type dim) (update :semantic-type keyword)diff --git a/src/metabase/public_sharing_rest/db.clj b/src/metabase/public_sharing_rest/db.cljindex 7e917edfa6f..72266d04869 100644--- a/src/metabase/public_sharing_rest/db.clj+++ b/src/metabase/public_sharing_rest/db.clj@@ -15,7 +15,7 @@[card-id :- [:maybe ::lib.schema.id/card]& {:keys [enable-embedding?]} :- [:maybe [:map {:closed true} [:enable-embedding? {:optional true} [:maybe :boolean]]]]](t2/select-one [:model/Card :id :dataset_query :description :display :name :parameters :visualization_settings- :card_schema :type :result_metadata :dimensions :dimension_mappings]+ :card_schema :type :entity_id :result_metadata :dimensions :dimension_mappings]{:where [:and[:= :id card-id][:= :archived false]diff --git a/src/metabase/pulse/db.clj b/src/metabase/pulse/db.cljindex 61626f13627..2a3b4d5cd1a 100644--- a/src/metabase/pulse/db.clj+++ b/src/metabase/pulse/db.clj@@ -21,7 +21,7 @@;; `pulse`, so requiring it back would add a module cycle for one query. Keep in sync with;; `metabase.queries.card-schema/schema-upgrade-triggers`.(t2/select-one-fn :dataset_query- [:model/Card :id :dataset_query :card_schema :type+ [:model/Card :id :dataset_query :card_schema :type :entity_id:result_metadata :dimensions :dimension_mappings]card-id))diff --git a/src/metabase/queries/card_schema.clj b/src/metabase/queries/card_schema.cljindex 6b26d0b3e3e..c046e931650 100644--- a/src/metabase/queries/card_schema.clj+++ b/src/metabase/queries/card_schema.clj@@ -26,9 +26,12 @@representation, so selecting it alone must not demand the rest of the set.- `:type`, read by the upgrade to 24 to recognize a metric. It is never written by an upgrade, but leaving it outis worse than an error: the upgrade silently skips the card and still stamps it as current.+ - `:entity_id`, which the upgrade to 24 seeds the backfilled dimension ids from. Same failure mode as `:type`, and+ quieter still: without it the ids are derived from `nil`, so this SELECT's dimension set disagrees with every+ other one's and the card serializes differently depending on who read it.Keep this in sync with the columns read by the `upgrade-card-schema-to` implementations."- (conj schema-governed-columns :card_schema :type))+ (conj schema-governed-columns :card_schema :type :entity_id))(def ^:private schema-select-columns"The `[modelable & columns]` projection [[selection]] SELECTs with: `:id`, so callers can key the rows they getdiff --git a/src/metabase/queries/models/card.clj b/src/metabase/queries/models/card.cljindex d1565e4ac86..85ce1ad627c 100644--- a/src/metabase/queries/models/card.clj+++ b/src/metabase/queries/models/card.clj@@ -676,12 +676,20 @@;; Curated metric dimensions. New metrics seed their own-table columns only, with joined/FK;; columns available to add on demand. But metrics created before curated dimensions shipped implicitly;; exposed EVERY breakoutable column (own-table + implicitly-joined), and existing dashboard filters may-;; be mapped to those joined columns. The default dimension was also expressed as a breakout on the metric's-;; query, rather than the `:default` flag in the `:dimensions`.-;; This upgrade modernizes a metric card to have properly constructed `:dimensions`, preserving the legacy-;; behaviour of including all breakoutable columns, and setting the `:default` accordingly.+;; be mapped to those joined columns. This schema upgrade modernizes a pre-curation metric in one of two ways.+;;+;; `:dimensions` which were set before schema 24 do not have the correct `:default` set, and the representation differs+;; slightly from the current form. The `:default` is inferred from the single breakout on the metric's query, or left+;; unset if there's no breakout.+;;+;; When the metric's `:dimensions` have never been set, we backfill the complete implicitly-joined dimension set,+;; preserving the pre-curation behavior for those metrics.+;;+;; This runs on every read of an un-curated metric and persists nothing, so the dimension ids it hands out have to+;; be the same every time — hence the `:entity_id` seed and `:entity_id`'s place in+;; [[card-schema/schema-upgrade-triggers]]. See `metabase.lib-metric.dimension.jvm/dimension-id`.(defmethod upgrade-card-schema-to 24- [{:keys [dataset_query dimensions] :as card} _schema-version]+ [{:keys [dataset_query dimensions entity_id] :as card} _schema-version](cond(not= :metric (keyword (:type card))) card ; Ignore non-:metric cards(empty? dataset_query) card ; And those without real queries@@ -690,7 +698,7 @@;; We generate the legacy, "full" dimensions, selecting all breakoutable columns as a dimension.;; (In contrast, a newly created metric starts with only its *own* table's columns as dimensions.)(nil? dimensions)- (let [{:keys [dimensions dimension-mappings]} (metrics/compute-full-dimension-set dataset_query)]+ (let [{:keys [dimensions dimension-mappings]} (metrics/compute-full-dimension-set entity_id dataset_query)](assoc card :dimensions dimensions :dimension_mappings dimension-mappings));; Metric with legacy `:dimensions` already set.diff --git a/src/metabase/queries_rest/db.clj b/src/metabase/queries_rest/db.cljindex 53674aeb810..79905fcaeff 100644--- a/src/metabase/queries_rest/db.clj+++ b/src/metabase/queries_rest/db.clj@@ -164,7 +164,7 @@[card-ids :- [:set ::lib.schema.id/card]new-collection-id-or-nil :- [:maybe ms/PositiveInt]](t2/select [:model/Card :id :collection_id :collection_position :dataset_query :card_schema :type- :result_metadata :dimensions :dimension_mappings]+ :entity_id :result_metadata :dimensions :dimension_mappings]{:where [:and [:in :id card-ids][:or [:not= :collection_id new-collection-id-or-nil](when new-collection-id-or-nildiff --git a/src/metabase/query_processor/dashboard.clj b/src/metabase/query_processor/dashboard.cljindex bd594eed1b1..c24a564827d 100644--- a/src/metabase/query_processor/dashboard.clj+++ b/src/metabase/query_processor/dashboard.clj@@ -39,11 +39,13 @@(query-processor.db/dashcard-series-exists? card-id dashcard-id))))))(defn- current-dimension-mapping?- [provider query mapping]+ [provider card query mapping](let [target-key (lib-metric/field-ref->key (:target mapping))](boolean(some #(= target-key (lib-metric/field-ref->key (-> % :mapping :target)))- (lib-metric/compute-dimension-pairs provider query)))))+ ;; Only the computed targets are read here, never the ids, but pass the card's real owner key anyway+ ;; rather than teach a second call site that it may lie about one.+ (lib-metric/compute-dimension-pairs provider (:entity_id card) query)))))(defn- default-metric-dimension[provider query card]@@ -58,7 +60,7 @@(not= :status/orphaned (:status %)))dimensions)](when-let [mapping (u/seek #(= (:id dimension) (:dimension-id %)) mappings)]- (when (current-dimension-mapping? provider query mapping)+ (when (current-dimension-mapping? provider card query mapping)(when-let [database-provider (lib-metric/database-provider-for-table provider (:table-id mapping))](when (permissions.metric/can-use-dimension-mapping? database-provider (:database_id card) mapping)(let [field-id (lib-metric/dimension-target->field-id (:target mapping))]diff --git a/src/metabase/revisions/models/revision.clj b/src/metabase/revisions/models/revision.cljindex 65516ba3f8f..f064447b2c4 100644--- a/src/metabase/revisions/models/revision.clj+++ b/src/metabase/revisions/models/revision.clj@@ -223,19 +223,22 @@(let [entity-name (name entity)serialized-object (serialize-instance entity id (dissoc object :message))last-object (revisions.db/latest-revision-object entity-name id)- ;; For Card entities, ensure :card_schema is excluded from comparison- ;; Old revisions might have :card_schema added by after-select, but this field- ;; shouldn't trigger new revisions as it's a technical/internal field- last-object-for-comparison (cond-> last-object- (= entity :model/Card) (dissoc :card_schema))]+ ;; For Card entities, ensure :card_schema is excluded from comparison. It is a+ ;; technical/internal marker, so on its own it should not trigger a new revision. It has to come off+ ;; BOTH sides: `serialize-instance :model/Card` keeps it, so dropping it only from the last revision+ ;; made every Card compare as changed and recorded a revision on every push.+ ;; It stays in the object we store, because `revert-to-revision! :model/Card` reads it back.+ for-comparison (fn [m]+ (cond-> m+ (= entity :model/Card) (dissoc :card_schema)))];; make sure we still have a map after calling out serialization function(assert (map? serialized-object));; the last-object could have nested object, e.g: Dashboard can have multiple Card in it,;; even though we call `post-select` on the `object`, the nested object might not be transformed correctly;; E.g: Cards inside Dashboard will not be transformed;; so to be safe, we'll just compare them as string- (when-not (= (json/encode serialized-object)- (json/encode last-object-for-comparison))+ (when-not (= (json/encode (for-comparison serialized-object))+ (json/encode (for-comparison last-object)))(revisions.db/insert-revision! {:model entity-name:model_id id:user_id user-iddiff --git a/src/metabase/usage_metadata/db.clj b/src/metabase/usage_metadata/db.cljindex 587fc61bd4d..1b344e8bf56 100644--- a/src/metabase/usage_metadata/db.clj+++ b/src/metabase/usage_metadata/db.clj@@ -245,5 +245,6 @@(mu/defn unarchived-metric-cards"The id, Database id, query, and schema of the unarchived metric Cards."[]- (t2/select [:model/Card :id :database_id :dataset_query :card_schema :type :result_metadata :dimensions :dimension_mappings]+ (t2/select [:model/Card :id :database_id :dataset_query :card_schema :type :entity_id :result_metadata :dimensions+ :dimension_mappings]:type "metric" :archived false))diff --git a/src/metabase/warehouses_rest/db.clj b/src/metabase/warehouses_rest/db.cljindex a841f1a208d..7df660462f8 100644--- a/src/metabase/warehouses_rest/db.clj+++ b/src/metabase/warehouses_rest/db.clj@@ -52,7 +52,7 @@;; Rows are pushed through `mi/do-after-select :model/Card` by the caller, so `:dataset_query` and;; `:result_metadata` drag in the rest of [[metabase.queries.card-schema/schema-upgrade-triggers]].(t2/reducible-query {:select [:name :description :database_id :dataset_query :id :collection_id- :result_metadata :type :source_card_id :card_schema+ :result_metadata :type :source_card_id :card_schema :entity_id:dimensions :dimension_mappings[^:allow-subquery {:select [:status]:from [:moderation_review]diff --git a/test/metabase/lib_metric/dimension/jvm_test.clj b/test/metabase/lib_metric/dimension/jvm_test.cljindex ea380cbfba3..ed433e620d2 100644--- a/test/metabase/lib_metric/dimension/jvm_test.clj+++ b/test/metabase/lib_metric/dimension/jvm_test.clj@@ -38,7 +38,7 @@table (lib.metadata/table (mt/metadata-provider) (mt/id :venues))query (-> (lib/query (mt/metadata-provider) table)(lib/aggregate (lib/count)))- pairs (dimension.jvm/compute-dimension-pairs mp query)]+ pairs (dimension.jvm/compute-dimension-pairs mp "owner" query)](is (seq pairs) "should produce at least one dimension pair")(testing "each pair has :dimension and :mapping"(doseq [pair pairs]@@ -80,7 +80,7 @@card-meta (lib.metadata/card db-mp (:id model))query (-> (lib/query db-mp card-meta)(lib/aggregate (lib/count)))- pairs (dimension.jvm/compute-dimension-pairs mp query)]+ pairs (dimension.jvm/compute-dimension-pairs mp "owner" query)](is (seq pairs)"should resolve dimensions from the card's result_metadata")(is (= #{"ID" "NAME" "CATEGORY_ID"}@@ -93,8 +93,48 @@table (lib.metadata/table (mt/metadata-provider) (mt/id :venues))query (-> (lib/query (mt/metadata-provider) table)(lib/aggregate (lib/count)))- pairs (dimension.jvm/compute-dimension-pairs mp query)+ pairs (dimension.jvm/compute-dimension-pairs mp "owner" query)cat-dim (first (filter #(= "CATEGORY_ID" (get-in % [:dimension :name])) pairs))](is (some? cat-dim) "CATEGORY_ID dimension should exist")(is (some? (get-in cat-dim [:dimension :has-field-values]))"CATEGORY_ID should have :has-field-values"))))++(defn- self-joined-venues-query+ "An MBQL 5 query joining Venues to itself, so every Venues field is visible twice."+ []+ (let [mp (mt/metadata-provider)+ venues (lib.metadata/table mp (mt/id :venues))+ venues-id (lib.metadata/field mp (mt/id :venues :id))]+ (-> (lib/query mp venues)+ (lib/join (lib/join-clause venues+ [(lib/= venues-id+ (lib/with-join-alias venues-id "V2"))])))))++(deftest compute-dimension-pairs-self-joined-source-card-distinct-ids-test+ (testing "a model that joins the same table twice gets a distinct dimension id per column"+ ;; `dimension-id` derives the id from `[owner-key (field-ref->key target)]`, and `field-id-ref`+ ;; rewrites a source-card column's name-based ref to use the column's integer field id. A model+ ;; that self-joins a table surfaces each underlying field twice, and both copies carry the *same*+ ;; field id — the join alias that told them apart lives inside the model, not in the outer query's+ ;; refs. So both targets reduce to the same key and both dimensions get the same id.+ ;;+ ;; The visible symptom is that editing one dimension edits its twin: resolution is by id+ ;; (`dimensions-for-table`, `lib-metric.dimension/dimension`), so renaming PRICE also rewrites the+ ;; other columns to their second-copy values.+ (mt/with-temp [:model/Card model {:type :model+ :dataset_query (self-joined-venues-query)}]+ (let [mp (lib-metric.metadata.jvm/metadata-provider)+ db-mp (mt/metadata-provider)+ card-meta (lib.metadata/card db-mp (:id model))+ query (-> (lib/query db-mp card-meta)+ (lib/aggregate (lib/count)))+ pairs (dimension.jvm/compute-dimension-pairs mp "owner" query)+ field-ids (keep #(get-in % [:dimension :sources 0 :field-id]) pairs)]+ (testing "precondition: the self-join surfaces at least one field id twice"+ (is (seq (for [[field-id n] (frequencies field-ids)+ :when (> n 1)]+ field-id))+ "the model's self-join should put two columns with the same field id in the dimension set"))+ (is (= (count pairs)+ (count (into #{} (map #(get-in % [:dimension :id])) pairs)))+ "every dimension should have its own id")))))diff --git a/test/metabase/metrics/api_dimension_test.clj b/test/metabase/metrics/api_dimension_test.cljindex f58dc85e13f..c2f40d18161 100644--- a/test/metabase/metrics/api_dimension_test.clj+++ b/test/metabase/metrics/api_dimension_test.clj@@ -436,8 +436,9 @@(is (= "week" (:default_temporal_unit resp)))(is (= :week (:default-temporal-unit stored)))(is (= "week" (:default_temporal_unit fetched)))- (is (not-any? #{:event/metric-dimensions-update} @topics)- "changing presentation metadata does not invalidate the dependency graph")))))+ (is (some #{:event/card-update} @topics)+ (str "a presentation-only dimension edit still announces a Card update, so remote sync marks the "+ "metric dirty; re-running the dependency graph is the accepted cost"))))))(deftest update-dimension-default-temporal-unit-validation-test(testing "default_temporal_unit must be visible and compatible with the dimension type"@@ -717,9 +718,10 @@(defn- legacy-dimension-set"The `{:dimensions ... :dimension-mappings ...}` a metric on `query` would have had at `card_schema` 23:the same full set [[metrics/compute-full-dimension-set]] produces, but *without* the table-prefixed- `:display-name`s that schema 24 introduced."- [query]- (let [computed-pairs (lib-metric/compute-dimension-pairs (lib-metric/metadata-provider) query)+ `:display-name`s that schema 24 introduced. `owner-key` seeds the dimension ids; pass the metric's+ `:entity_id`, as the schema-24 upgrade does."+ [owner-key query]+ (let [computed-pairs (lib-metric/compute-dimension-pairs (lib-metric/metadata-provider) owner-key query){:keys [dimensions dimension-mappings]}(lib-metric/reconcile-dimensions-and-mappings computed-pairs nil nil)]{:dimensions (lib-metric/extract-persisted-dimensions dimensions)@@ -739,7 +741,7 @@:database_id (mt/id):table_id (mt/id :orders):dataset_query orders-q}]- (let [{:keys [dimensions dimension-mappings]} (legacy-dimension-set orders-q)]+ (let [{:keys [dimensions dimension-mappings]} (legacy-dimension-set (:entity_id metric) orders-q)];; Raw UPDATE so nothing bumps the schema back up or re-modernizes on the way in.(t2/query-one {:update :report_card:set {:card_schema 23diff --git a/test/metabase/metrics/core_test.clj b/test/metabase/metrics/core_test.cljindex 2efeb772b86..a9ccb9bd3a7 100644--- a/test/metabase/metrics/core_test.clj+++ b/test/metabase/metrics/core_test.clj@@ -1,11 +1,13 @@(ns metabase.metrics.core-test"Tests for metrics.core dimension sync functionality."(:require+ [clojure.set :as set][clojure.test :refer :all][medley.core :as m][metabase.lib.core :as lib][metabase.lib.metadata :as lib.metadata][metabase.metrics.core :as metrics]+ [metabase.models.serialization :as serdes][metabase.test :as mt][metabase.util.json :as json][toucan2.core :as t2]))@@ -116,6 +118,76 @@(is (some? (:dimension_mappings stored)))(is (= first-ids next-ids))))))+(defn- uncurate!+ "Return `card-id` to the state a metric created before curated dimensions shipped is in: no stored dimensions, and+ a `card_schema` old enough that the 23->24 backfill still runs on read."+ [card-id]+ (t2/query-one {:update :report_card+ :set {:card_schema 23+ :dimensions nil+ :dimension_mappings nil}+ :where [:= :id card-id]}))++(deftest metric-upgraded-dimension-ids-are-stable-without-a-write-test+ (testing "Backfilled dimension IDs are stable across reads even without persisting (UXW-4943)"+ (mt/with-temp [:model/Card metric {:name "Legacy Metric"+ :type :metric+ :database_id (mt/id)+ :table_id (mt/id :venues)+ :dataset_query (metric-query)}]+ (uncurate! (:id metric))+ (let [ids #(mapv :id (:dimensions (t2/select-one :model/Card :id (:id metric))))]+ (is (seq (ids))+ "the backfill produces dimensions")+ (is (= (ids) (ids))+ "two reads agree")+ (is (nil? (:dimensions (t2/query-one {:select [:dimensions]+ :from [:report_card]+ :where [:= :id (:id metric)]})))+ "and neither read persisted anything")))))++(deftest metric-dimension-ids-are-scoped-to-their-entity-test+ (testing "Two metrics with a dimension on the same column get different stable IDs (UXW-4943)"+ (mt/with-temp [:model/Card metric-a {:name "Legacy Metric A"+ :type :metric+ :database_id (mt/id)+ :table_id (mt/id :venues)+ :dataset_query (metric-query)}+ :model/Card metric-b {:name "Legacy Metric B"+ :type :metric+ :database_id (mt/id)+ :table_id (mt/id :venues)+ :dataset_query (metric-query)}]+ (uncurate! (:id metric-a))+ (uncurate! (:id metric-b))+ (let [ids #(into #{} (map :id) (:dimensions (t2/select-one :model/Card :id %)))+ a (ids (:id metric-a))+ b (ids (:id metric-b))]+ (is (seq a))+ (is (= (count a) (count b))+ "the same query produces the same number of dimensions")+ (is (empty? (set/intersection a b))+ "but no id is shared between the two metrics")))))++(deftest metric-upgraded-dimensions-serialize-identically-across-reads-test+ (testing "Pre-curation metrics serialize stably; no remote sync churn (UXW-4943)"+ (mt/with-temp [:model/Card metric {:name "Legacy Metric"+ :type :metric+ :database_id (mt/id)+ :table_id (mt/id :venues)+ :dataset_query (metric-query)}]+ (uncurate! (:id metric))+ (let [extract #(serdes/with-cache+ (serdes/extract-one "Card" {} (t2/select-one :model/Card :id (:id metric))))+ before (extract)]+ (is (seq (:dimensions before))+ "the backfilled dimensions are part of what a metric serializes to")+ (is (= before (extract))+ "two extractions of the same un-curated metric agree")+ (metrics/sync-dimensions! :metadata/metric (:id metric))+ (is (= before (extract))+ "and persisting the backfill leaves the serialization untouched")))))+(deftest metric-sync-dimensions-picks-no-default-test(testing "new metrics are seeded with a curated dimension list and no default dimension"(let [mp (mt/metadata-provider)diff --git a/test/metabase/metrics/permissions_test.clj b/test/metabase/metrics/permissions_test.cljindex 4bef766f082..7f7b53e15e4 100644--- a/test/metabase/metrics/permissions_test.clj+++ b/test/metabase/metrics/permissions_test.clj@@ -42,7 +42,7 @@(defn- persist-full-dimension-set)]+ (metrics/compute-full-dimension-set (:entity_id metric) (:dataset_query metric))](t2/update! :model/Card (:id metric){:dimensions dimensions, :dimension_mappings dimension-mappings})))diff --git a/test/metabase/queries/models/card_test.clj b/test/metabase/queries/models/card_test.cljindex 5a68c516621..93ad5ac18b1 100644--- a/test/metabase/queries/models/card_test.clj+++ b/test/metabase/queries/models/card_test.clj@@ -998,6 +998,7 @@column must project all of these — see [[metabase.queries.card-schema/schema-upgrade-triggers]]."{:id 1:type :question+ :entity_id "cardcardcardcardcard1":database_id 1:dataset_query {}:result_metadata nildiff --git a/test/metabase/revisions/models/revision_test.clj b/test/metabase/revisions/models/revision_test.cljindex c7f8a7d15a8..aa53dc4a0aa 100644--- a/test/metabase/revisions/models/revision_test.clj+++ b/test/metabase/revisions/models/revision_test.clj@@ -246,6 +246,40 @@(push-revision)(is (= 2 (count (revision/revisions :model/Dashboard dash-id))))))))))+(deftest do-not-record-card-revision-if-object-is-not-changed-test+ (testing "Check that we don't record a revision for a real :model/Card that hasn't changed"+ ;; The sibling test above exercises ::FakedCard, which has no `:card_schema`, so it never covered the+ ;; Card-specific branch in `push-revision!`. `serialize-instance :model/Card` keeps `:card_schema`, so+ ;; stripping it from only the previous revision made every Card compare as changed and recorded a+ ;; revision on every push — filling a metric's history with "created a revision with no change." and+ ;; evicting real edits once `max-revisions` was reached.+ (mt/with-model-cleanup [:model/Revision]+ (mt/with-temp [:model/Card {card-id :id} {:name "Tips Created by Day"}]+ (let [push-revision (fn [] (revision/push-revision!+ {:entity :model/Card+ :id card-id+ :user-id (mt/user->id :rasta)+ :object (t2/select-one :model/Card card-id)}))]+ (testing "first revision should be recorded"+ (push-revision)+ (is (= 1 (count (revision/revisions :model/Card card-id)))))+ (testing "pushing the same object again shouldn't record a new revision"+ (dorun (repeatedly 3 push-revision))+ (is (= 1 (count (revision/revisions :model/Card card-id)))))+ (testing "a real change should record a new revision"+ (t2/update! :model/Card :id card-id {:name "Spots Created by Day"})+ (push-revision)+ (is (= 2 (count (revision/revisions :model/Card card-id)))))+ (testing "`:card_schema` is still stored in the snapshot, because revert reads it back"+ ;; Excluding it from `serialize-instance` would also equalize the comparison, but then+ ;; `revert-to-revision! :model/Card` would fall back to `starting-card-schema-version` and+ ;; silently downgrade the card on every revert.+ (let [card (t2/select-one :model/Card card-id)]+ (is (= (:card_schema card)+ (:card_schema (revision/serialize-instance :model/Card card-id card))))+ (is (> (:card_schema card) queries/starting-card-schema-version)+ "sanity check: the card is past the legacy schema version, so a downgrade would be visible"))))))))+;;; # REVISIONS+DETAILS(deftest add-revision-details-testdiff --git a/test/metabase/warehouses_rest/api_test.clj b/test/metabase/warehouses_rest/api_test.cljindex f2d1c053f08..7e5d8544496 100644--- a/test/metabase/warehouses_rest/api_test.clj+++ b/test/metabase/warehouses_rest/api_test.clj@@ -144,7 +144,7 @@(merge{:id (format "card__%d" (u/the-id card)):db_id (:database_id card)- :entity_id nil+ :entity_id (:entity_id card):display_name (:name card):schema "Everything else":moderated_status nil@@ -2395,7 +2395,7 @@(testing "Should be able to get saved questions in a specific collection"(is (= [{:id (format "card__%d" (:id card-1)):db_id (mt/id)- :entity_id nil+ :entity_id (:entity_id card-1):metrics nil:moderated_status nil:display_name "Card 1"@@ -2421,7 +2421,7 @@(is (contains? (set response){:id (format "card__%d" (:id card-2)):db_id (mt/id)- :entity_id nil+ :entity_id (:entity_id card-2):display_name "Card 2":metrics nil:moderated_status nil@@ -2489,7 +2489,7 @@(is (contains? (set response){:id (format "card__%d" (:id card-2)):db_id (mt/id)- :entity_id nil+ :entity_id (:entity_id card-2):display_name "Card 2":metrics nil:moderated_status nil