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
Heal and prevent effective_type drift without coercion (GHY-3388) (#72591)
Eric Normand254087339f37
diff --git a/frontend/src/metabase/metadata/utils/field.ts b/frontend/src/metabase/metadata/utils/field.tsindex 7cc7737d956..4552fea7860 100644--- a/frontend/src/metabase/metadata/utils/field.ts+++ b/frontend/src/metabase/metadata/utils/field.ts@@ -30,7 +30,17 @@ export function areFieldsComparable(field1: Field, field2: Field): boolean {}export function canCoerceFieldType(field: Field): boolean {- return !isTypeFK(field.semantic_type) && is_coerceable(field.base_type);+ // GHY-3388: also surface the cast UI when the field is in a state the user+ // needs to fix from the UI — either coercion_strategy is already set (so they+ // can clear or change it) or effective_type has drifted away from base_type+ // (so they can repair via toggle on/off, which clears the coercion and resets+ // effective_type=base_type via PUT /api/field/:id).+ return (+ field.coercion_strategy != null ||+ (field.effective_type != null &&+ field.effective_type !== field.base_type) ||+ (!isTypeFK(field.semantic_type) && is_coerceable(field.base_type))+ );}export function getRawTableFieldId(field: Field): FieldId {diff --git a/frontend/src/metabase/metadata/utils/field.unit.spec.ts b/frontend/src/metabase/metadata/utils/field.unit.spec.tsindex 0c517b443d1..edfe62ecbec 100644--- a/frontend/src/metabase/metadata/utils/field.unit.spec.ts+++ b/frontend/src/metabase/metadata/utils/field.unit.spec.ts@@ -61,6 +61,66 @@ describe("canCoerceFieldType", () => {canCoerceFieldType(createMockField({ base_type: "type/Boolean" })),).toBe(false);});++ // GHY-3388: surface the cast UI when the field is in a state the user needs+ // to fix from the UI — even when no forward coercions exist for base_type.+ it("should return true when coercion_strategy is set, even if base_type is not coerceable", () => {+ expect(+ canCoerceFieldType(+ createMockField({+ base_type: "type/Number",+ effective_type: "type/Number",+ coercion_strategy: "Coercion/String->Number",+ }),+ ),+ ).toBe(true);+ });++ it("should return true when effective_type drifted from base_type without a coercion (the GHY-3388 broken state)", () => {+ expect(+ canCoerceFieldType(+ createMockField({+ base_type: "type/Number",+ effective_type: "type/Text",+ coercion_strategy: null,+ }),+ ),+ ).toBe(true);+ });++ it("should return true for an FK field that has a stale coercion (so the user can clear it)", () => {+ const field = createOrdersProductIdField();+ expect(+ canCoerceFieldType({+ ...field,+ coercion_strategy: "Coercion/UNIXSeconds->DateTime",+ }),+ ).toBe(true);+ });++ it("should return false when effective_type is missing (separate concern, GHY-3367)", () => {+ expect(+ canCoerceFieldType(+ createMockField({+ base_type: "type/Number",+ effective_type: undefined,+ coercion_strategy: null,+ }),+ ),+ ).toBe(false);+ });++ it("should return false when effective_type matches base_type and no coercion", () => {+ expect(+ canCoerceFieldType(+ createMockField({+ base_type: "type/Boolean",+ effective_type: "type/Boolean",+ coercion_strategy: null,+ }),+ ),+ ).toBe(false);+ });});describe("getRawTableFieldId", () => {diff --git a/modules/drivers/snowflake/test/metabase/driver/snowflake_test.clj b/modules/drivers/snowflake/test/metabase/driver/snowflake_test.cljindex 846bb98c595..10f2e0575f0 100644--- a/modules/drivers/snowflake/test/metabase/driver/snowflake_test.clj+++ b/modules/drivers/snowflake/test/metabase/driver/snowflake_test.clj@@ -48,6 +48,7 @@[metabase.util.log :as log][metabase.util.log.capture :as log.capture][metabase.util.random :as u.random]+ [metabase.warehouse-schema.models.field-user-settings :as field-user-settings][metabase.warehouses.models.database :as database][ring.util.codec :as codec][toucan2.core :as t2]))@@ -480,6 +481,185 @@[(format "DROP TABLE IF EXISTS \"%s\".\"PUBLIC\".\"%s\";" db-name table-name)]{:transaction? false})))))))))+;; Five related repro phases (v1-v5) share Snowflake connection setup and table-name lifecycle.+;; Splitting would multiply CI Snowflake setup cost. Kondo's warning is acknowledged.+^{:clj-kondo/ignore [:metabase/i-like-making-cams-eyes-bleed-with-horrifically-long-tests]}+(deftest ^:sequential ^:synchronized create-or-replace-table-updates-effective-type-test+ (mt/test-driver :snowflake+ (testing "GHY-3388: when a column's database type changes via CREATE OR REPLACE TABLE+ (e.g. TEXT -> NUMBER via TRY_TO_NUMBER), sync should update effective_type to match+ the new base_type and clear stale coercion_strategy/semantic_type. Reproduces the+ in-place update path (repro v1 from the Linear issue) where Metabase's Field row is+ preserved across the schema change."+ (let [db-name (#'driver.snowflake/db-name (mt/db))+ table-name (str "ghy_3388_" (u.random/random-name))+ run-sql! (fn [stmts]+ (sql-jdbc.execute/do-with-connection-with-options+ :snowflake+ (mt/db)+ nil+ (fn [^java.sql.Connection conn]+ (doseq [stmt stmts]+ (jdbc/execute! {:connection conn} [stmt] {:transaction? false})))))+ qualified (format "\"%s\".\"PUBLIC\".\"%s\"" db-name table-name)]+ (try+ ;; step 1: create the table with a TEXT column and insert rows. Quote identifiers so they+ ;; are preserved lowercase (Snowflake upper-cases unquoted identifiers).+ (run-sql! [(format "CREATE OR REPLACE TRANSIENT TABLE %s (\"id\" INTEGER, \"text_column\" TEXT);" qualified)+ (format "INSERT INTO %s (\"id\", \"text_column\") VALUES (1, '100'), (2, '200'), (3, '300');" qualified)])+ ;; step 2: sync — Metabase creates Table + Field rows for our new table+ (sync/sync-database! (mt/db))+ (let [original-table (t2/select-one :model/Table :db_id (mt/id) :name table-name)+ _ (is (some? original-table) "table should be synced")+ original-field (t2/select-one :model/Field :table_id (:id original-table) :name "text_column")]+ (testing "sanity check: text_column is text"+ (is (=? {:base_type :type/Text+ :effective_type :type/Text}+ original-field)))+ ;; step 3: CREATE OR REPLACE the table, converting text_column to a number via TRY_TO_NUMBER+ (run-sql! [(format (str "CREATE OR REPLACE TABLE %s AS "+ "SELECT \"id\", TRY_TO_NUMBER(\"text_column\") AS \"text_column\" FROM %s;")+ qualified qualified)])+ ;; step 4: sync again+ (sync/sync-database! (mt/db))+ (let [new-field (t2/select-one :model/Field :id (:id original-field))]+ (testing "after sync, base_type and effective_type both reflect the new numeric column,+ and stale coercion/semantic type are cleared"+ ;; TRY_TO_NUMBER with no precision returns NUMBER(38,0) -> :type/BigInteger+ (is (=? {:base_type :type/BigInteger+ :effective_type :type/BigInteger+ :coercion_strategy nil+ :semantic_type nil}+ new-field))))+ ;; ----- repro v2 (clean state baseline): drop the table, wipe Metabase metadata for it,+ ;; recreate fresh as TEXT, sync, then CREATE OR REPLACE to numeric and sync again. The+ ;; field should end up with effective_type matching base_type. (In the Linear repro the+ ;; user observes the cast feature does not appear here — i.e. effective_type vs base_type+ ;; should be consistent and not stuck as text.)+ (run-sql! [(format "DROP TABLE IF EXISTS %s;" qualified)])+ (t2/delete! :model/Field :table_id (:id original-table))+ (t2/delete! :model/Table :id (:id original-table)))+ (run-sql! [(format "CREATE OR REPLACE TRANSIENT TABLE %s (\"id\" INTEGER, \"text_column\" TEXT);" qualified)+ (format "INSERT INTO %s (\"id\", \"text_column\") VALUES (1, '100'), (2, '200'), (3, '300');" qualified)])+ (sync/sync-database! (mt/db))+ (run-sql! [(format (str "CREATE OR REPLACE TABLE %s AS "+ "SELECT \"id\", TRY_TO_NUMBER(\"text_column\", 38, 2) AS \"text_column\" FROM %s;")+ qualified qualified)])+ (sync/sync-database! (mt/db))+ (let [fresh-table (t2/select-one :model/Table :db_id (mt/id) :name table-name)+ fresh-field (t2/select-one :model/Field :table_id (:id fresh-table) :name "text_column")]+ (testing "after fresh-state CREATE OR REPLACE to numeric, base_type and effective_type+ both reflect the new numeric column"+ ;; TRY_TO_NUMBER(x, 38, 2) returns NUMBER(38,2) -> :type/Number on Snowflake+ (is (=? {:base_type :type/Number+ :effective_type :type/Number+ :coercion_strategy nil+ :semantic_type nil}+ fresh-field)))+ ;; ----- repro v3: simulate the user setting a coercion strategy on the TEXT column+ ;; (via the UI cast-toggle) before the underlying type changes. When the DB column+ ;; becomes numeric natively, sync should clear the now-meaningless coercion strategy+ ;; and reset effective_type to match the new base_type. If sync leaves the coercion+ ;; sticky, effective_type will diverge from base_type — the observable GHY-3388 symptom.+ (run-sql! [(format "DROP TABLE IF EXISTS %s;" qualified)])+ (t2/delete! :model/Field :table_id (:id fresh-table))+ (t2/delete! :model/Table :id (:id fresh-table)))+ (run-sql! [(format "CREATE OR REPLACE TRANSIENT TABLE %s (\"id\" INTEGER, \"text_column\" TEXT);" qualified)+ (format "INSERT INTO %s (\"id\", \"text_column\") VALUES (1, '100'), (2, '200'), (3, '300');" qualified)])+ (sync/sync-database! (mt/db))+ (let [pre-coerce-table (t2/select-one :model/Table :db_id (mt/id) :name table-name)+ pre-coerce-field (t2/select-one :model/Field :table_id (:id pre-coerce-table) :name "text_column")]+ ;; user enables coercion: this TEXT column is really an integer+ (t2/update! :model/Field (:id pre-coerce-field)+ {:coercion_strategy :Coercion/String->Integer+ :effective_type :type/Integer})+ (run-sql! [(format (str "CREATE OR REPLACE TABLE %s AS "+ "SELECT \"id\", TRY_TO_NUMBER(\"text_column\") AS \"text_column\" FROM %s;")+ qualified qualified)])+ (sync/sync-database! (mt/db))+ (let [after-field (t2/select-one :model/Field :id (:id pre-coerce-field))]+ (testing "after the underlying TEXT column becomes a native number, the previously+ user-set coercion strategy should be cleared and effective_type should+ match the new base_type"+ (is (=? {:base_type :type/BigInteger+ :effective_type :type/BigInteger+ :coercion_strategy nil+ :semantic_type nil}+ after-field)))))+ ;; ----- repro v4: set coercion the way the PUT /api/field/:id endpoint does:+ ;; via upsert-user-settings, which writes to metabase_field_user_settings. That+ ;; row is overlaid back onto the field on every t2/update! via the+ ;; sync-user-settings before-update hook (merge non-nil user-settings over+ ;; field changes). v3 wrote only to metabase_field and so bypassed this+ ;; overlay; v4 exercises the real UI cast-toggle path.+ (run-sql! [(format "DROP TABLE IF EXISTS %s;" qualified)])+ (when-let [stale-table (t2/select-one :model/Table :db_id (mt/id) :name table-name)]+ (t2/delete! :model/Field :table_id (:id stale-table))+ (t2/delete! :model/Table :id (:id stale-table)))+ (run-sql! [(format "CREATE OR REPLACE TRANSIENT TABLE %s (\"id\" INTEGER, \"text_column\" TEXT);" qualified)+ (format "INSERT INTO %s (\"id\", \"text_column\") VALUES (1, '100'), (2, '200'), (3, '300');" qualified)])+ (sync/sync-database! (mt/db))+ (let [v4-table (t2/select-one :model/Table :db_id (mt/id) :name table-name)+ v4-field (t2/select-one :model/Field :table_id (:id v4-table) :name "text_column")]+ (field-user-settings/upsert-user-settings v4-field+ {:coercion_strategy :Coercion/String->Integer+ :effective_type :type/Integer})+ (t2/update! :model/Field (:id v4-field)+ {:coercion_strategy :Coercion/String->Integer+ :effective_type :type/Integer})+ (run-sql! [(format (str "CREATE OR REPLACE TABLE %s AS "+ "SELECT \"id\", TRY_TO_NUMBER(\"text_column\") AS \"text_column\" FROM %s;")+ qualified qualified)])+ (sync/sync-database! (mt/db))+ (let [after-field (t2/select-one :model/Field :id (:id v4-field))+ after-user-settings (t2/select-one :model/FieldUserSettings :field_id (:id v4-field))]+ (testing "after CREATE OR REPLACE to numeric, the user-set coercion stored in+ metabase_field_user_settings (via upsert-user-settings) should be+ cleared so it doesn't overlay back on top of the synced field"+ (is (=? {:base_type :type/BigInteger+ :effective_type :type/BigInteger+ :coercion_strategy nil+ :semantic_type nil}+ after-field))+ (is (=? {:effective_type :type/BigInteger+ :coercion_strategy nil+ :semantic_type nil}+ after-user-settings)))))+ ;; ----- repro v5: same as v1 (in-place CREATE OR REPLACE TEXT -> NUMBER) but trigger+ ;; sync via sync/sync-table! — the function the per-table "Sync table now" UI button+ ;; calls. Goes through sync-table-metadata! -> sync-fields-for-table! instead of+ ;; sync-db-metadata! -> sync-fields!. Both reach the same sync-and-update! core, but+ ;; the OP's repro instructions said "Now sync the table" (singular), so this rules+ ;; out a code-path-specific bug at the entry point.+ (run-sql! [(format "DROP TABLE IF EXISTS %s;" qualified)])+ (when-let [stale-table (t2/select-one :model/Table :db_id (mt/id) :name table-name)]+ (t2/delete! :model/Field :table_id (:id stale-table))+ (t2/delete! :model/Table :id (:id stale-table)))+ (run-sql! [(format "CREATE OR REPLACE TRANSIENT TABLE %s (\"id\" INTEGER, \"text_column\" TEXT);" qualified)+ (format "INSERT INTO %s (\"id\", \"text_column\") VALUES (1, '100'), (2, '200'), (3, '300');" qualified)])+ (sync/sync-database! (mt/db))+ (let [v5-table (t2/select-one :model/Table :db_id (mt/id) :name table-name)+ v5-field (t2/select-one :model/Field :table_id (:id v5-table) :name "text_column")]+ (run-sql! [(format (str "CREATE OR REPLACE TABLE %s AS "+ "SELECT \"id\", TRY_TO_NUMBER(\"text_column\") AS \"text_column\" FROM %s;")+ qualified qualified)])+ (sync/sync-table! v5-table)+ (let [after-field (t2/select-one :model/Field :id (:id v5-field))]+ (testing "sync-table! (the per-table UI button) should also reset effective_type+ when the underlying column type changes"+ (is (=? {:base_type :type/BigInteger+ :effective_type :type/BigInteger+ :coercion_strategy nil+ :semantic_type nil}+ after-field)))))+ (finally+ (let [t (t2/select-one :model/Table :db_id (mt/id) :name table-name)]+ (when t+ (u/ignore-exceptions (t2/delete! :model/Field :table_id (:id t)))+ (u/ignore-exceptions (t2/delete! :model/Table :id (:id t)))))+ (u/ignore-exceptions+ (run-sql! [(format "DROP TABLE IF EXISTS %s;" qualified)]))))))))+(deftest ^:sequential describe-table-test(mt/test-driver :snowflake(testing "make sure describe-table uses the NAME FROM DETAILS too"diff --git a/resources/migrations/062/20260508_ghy_3388_heal_effective_type.yaml b/resources/migrations/062/20260508_ghy_3388_heal_effective_type.yamlnew file mode 100644index 00000000000..9015a773115--- /dev/null+++ b/resources/migrations/062/20260508_ghy_3388_heal_effective_type.yaml@@ -0,0 +1,54 @@+## GHY-3388 — Heal effective_type drift without coercion.+##+## A cloud customer (pagaleve) had many metabase_field rows in an internally+## inconsistent state: base_type=:type/Number with effective_type=:type/Text and+## coercion_strategy=NULL. With no coercion to justify the divergence, this state+## is illegal under the codebase's existing rules but nothing was enforcing them.+## The bug isn't reproducible on current code, so this is historical drift from+## older Metabase versions that needs healing.+##+## Two changesets — split because the lint requires multiple SQL changes in one+## changeset to target different dbms values, and these two heals both need to+## run on every dialect:+## 1. metabase_field — restrict to active rows so dead state isn't resurrected.+## 2. metabase_field_user_settings — companion update so the user-settings+## overlay (sync-user-settings before-update merge) doesn't re-introduce the+## drift on the next field update.+##+## Rollback is empty — the drift these UPDATEs heal carries no recoverable+## information (effective_type was either equal to base_type or in an illegal+## state with no coercion to interpret it), so there's nothing to restore.++databaseChangeLog:+ - changeSet:+ id: v62.ghy3388-field-heal+ author: ericnormand+ comment: GHY-3388 heal metabase_field where coercion_strategy is NULL and effective_type drifted+ changes:+ - sql:+ sql: >-+ UPDATE metabase_field+ SET effective_type = base_type+ WHERE active = TRUE+ AND coercion_strategy IS NULL+ AND effective_type IS NOT NULL+ AND effective_type <> base_type;+ rollback: []++ - changeSet:+ id: v62.ghy3388-user-settings-heal+ author: ericnormand+ comment: GHY-3388 heal metabase_field_user_settings overlay so it doesn't reintroduce drift+ changes:+ - sql:+ sql: >-+ UPDATE metabase_field_user_settings+ SET effective_type = (+ SELECT base_type FROM metabase_field WHERE metabase_field.id = metabase_field_user_settings.field_id+ )+ WHERE coercion_strategy IS NULL+ AND effective_type IS NOT NULL+ AND effective_type <> (+ SELECT base_type FROM metabase_field WHERE metabase_field.id = metabase_field_user_settings.field_id+ );+ rollback: []diff --git a/src/metabase/sync/sync_metadata/fields/sync_metadata.clj b/src/metabase/sync/sync_metadata/fields/sync_metadata.cljindex 0f377516062..560eba2c4ab 100644--- a/src/metabase/sync/sync_metadata/fields/sync_metadata.clj+++ b/src/metabase/sync/sync_metadata/fields/sync_metadata.clj@@ -42,6 +42,8 @@metabase-field :- common/TableMetadataFieldWithID](let [{old-database-type :database-typeold-base-type :base-type+ old-effective-type :effective-type+ old-coercion-strategy :coercion-strategyold-field-comment :field-commentold-semantic-type :semantic-typeold-database-position :database-position@@ -137,6 +139,22 @@:semantic_type nil};; we must override user-set values(->> (schema.field-user-settings/upsert-user-settings metabase-field))))+ ;; GHY-3388 self-heal: a Field with no coercion_strategy must have effective_type=base_type.+ ;; We've observed customer instances where these drifted apart (likely from older Metabase+ ;; versions). When base_type didn't change at this sync but the row is in the broken state,+ ;; repair it. Wipe user-settings's stale effective_type too so sync-user-settings's merge-back+ ;; doesn't re-introduce drift on the next field update.+ (when (and (not new-base-type?)+ (nil? old-coercion-strategy)+ (some? old-effective-type)+ (not= old-effective-type new-base-type))+ (log/warnf "Healing %s: effective_type %s ≠ base_type %s with no coercion_strategy. Resetting effective_type to match base_type."+ (common/field-metadata-name-for-logging table metabase-field)+ old-effective-type+ new-base-type)+ (let [et {:effective_type new-base-type}]+ (schema.field-user-settings/upsert-user-settings metabase-field et)+ et))(when new-semantic-type?(log/infof "Semantic type of %s has changed from '%s' to '%s'."(common/field-metadata-name-for-logging table metabase-field)@@ -170,7 +188,7 @@;; this guard avoids spamming logs with pk changes when people first upgrade to support database_is_pk(when (or ;; if we have any value for the old database_is_pk we have upgraded already, and can log regardless(some? old-pk)- ;; otherwise, log only if logical pk status has changed+ ;; otherwise, log only if logical pk status has changed(not= new-pk (= old-semantic-type :type/PK)))(log/infof "Database pk of %s has changed from '%s' to '%s'"(common/field-metadata-name-for-logging table metabase-field)diff --git a/src/metabase/warehouse_schema/models/field.clj b/src/metabase/warehouse_schema/models/field.cljindex ef7c55193e6..9a1fb99edec 100644--- a/src/metabase/warehouse_schema/models/field.clj+++ b/src/metabase/warehouse_schema/models/field.clj@@ -126,10 +126,37 @@[field](dissoc field :is_defective_duplicate :unique_field_helper))+(defn- enforce-effective-type-invariant+ "GHY-3388 invariant: a Field row with no coercion_strategy must have effective_type=base_type.+ When effective_type is set but diverges from base_type without a coercion to justify it, this+ normalizes effective_type to match base_type (and logs a warning so the silent fix is visible).+ Does not touch rows where coercion_strategy is set (legitimate divergence), where effective_type+ is nil (separate concern, GHY-3367 territory), or where either type is not a valid descendant of+ :type/* (so the transform's invalid-type validation still fires)."+ [field]+ (let [coercion (:coercion_strategy field)+ effective-raw (:effective_type field)+ base-raw (:base_type field)+ effective (some-> effective-raw keyword)+ base (some-> base-raw keyword)]+ (if (and (nil? coercion)+ effective+ base+ (isa? effective :type/*)+ (isa? base :type/*)+ (not= effective base))+ (do (log/warnf "Field %s: effective_type %s ≠ base_type %s with no coercion_strategy. Normalizing effective_type to match base_type."+ (or (:id field) (:name field) "<new>")+ effective+ base)+ (assoc field :effective_type base-raw))+ field)))+(t2/define-before-insert :model/Field[field](let [defaults {:display_name (humanization/name->human-readable-name (:name field))}]- (merge defaults field)))+ (-> (merge defaults field)+ enforce-effective-type-invariant)))(def field-user-settings"Set of user-settable values for a Field"@@ -151,7 +178,10 @@(defn- sync-user-settings [field];; we transparently prevent updates that would override user-set values(let [user-settings (t2/select-one :model/FieldUserSettings (:id field))- updated-field (merge field (u/select-keys-when user-settings :non-nil field-user-settings))]+ updated-field (-> (merge field (u/select-keys-when user-settings :non-nil field-user-settings))+ ;; GHY-3388 invariant: enforce coercion_strategy=nil ⇒ effective_type=base_type+ ;; AFTER the user-settings merge, since the overlay can introduce stale effective_type+ enforce-effective-type-invariant)](t2.protocols/with-current field updated-field)))(t2/define-before-update :model/Fielddiff --git a/test/metabase/app_db/schema_migrations_test.clj b/test/metabase/app_db/schema_migrations_test.cljindex 07d2e00a4db..933e42d796b 100644--- a/test/metabase/app_db/schema_migrations_test.clj+++ b/test/metabase/app_db/schema_migrations_test.clj@@ -2930,3 +2930,95 @@:access_granted false:created_at :%now:updated_at :%now}))))))))++(deftest heal-effective-type-drift-without-coercion-test+ (testing "GHY-3388: heal metabase_field rows where coercion_strategy is NULL and effective_type+ drifted away from base_type. The migration must repair such rows in both metabase_field+ and metabase_field_user_settings, leaving legitimate states (real coercion, already+ consistent, null effective_type, inactive rows) alone."+ (impl/test-migrations ["v62.ghy3388-field-heal" "v62.ghy3388-user-settings-heal"] [migrate!]+ (let [db-id (first (t2/insert-returning-pks!+ (t2/table-name :model/Database)+ {:name "test-db"+ :engine "h2"+ :details "{}"+ :created_at :%now+ :updated_at :%now}))+ table-id (first (t2/insert-returning-pks!+ (t2/table-name :model/Table)+ {:name "test_table"+ :db_id db-id+ :active true+ :created_at :%now+ :updated_at :%now}))+ insert-field! (fn [m]+ (first (t2/insert-returning-pks!+ (t2/table-name :model/Field)+ (merge {:table_id table-id+ :name "f"+ :display_name "f"+ :position 0+ :database_position 0+ :active true+ :preview_display true+ :database_type "x"+ :created_at :%now+ :updated_at :%now}+ m))))+ broken-id (insert-field! {:name "broken"+ :base_type "type/Number"+ :effective_type "type/Text"+ :coercion_strategy nil})+ already-ok-id (insert-field! {:name "already_ok"+ :base_type "type/Number"+ :effective_type "type/Number"+ :coercion_strategy nil})+ with-coercion-id (insert-field! {:name "with_coercion"+ :base_type "type/Text"+ :effective_type "type/Number"+ :coercion_strategy "Coercion/String->Number"})+ null-effective-id (insert-field! {:name "null_effective"+ :base_type "type/Number"+ :effective_type nil+ :coercion_strategy nil})+ inactive-broken-id (insert-field! {:name "inactive_broken"+ :base_type "type/Number"+ :effective_type "type/Text"+ :coercion_strategy nil+ :active false})]+ ;; mirror the broken row in metabase_field_user_settings+ (t2/insert! :metabase_field_user_settings+ {:field_id broken-id+ :effective_type "type/Text"+ :coercion_strategy nil+ :created_at :%now+ :updated_at :%now})+ (t2/insert! :metabase_field_user_settings+ {:field_id with-coercion-id+ :effective_type "type/Number"+ :coercion_strategy "Coercion/String->Number"+ :created_at :%now+ :updated_at :%now})+ (migrate!)+ (testing "broken active row is healed"+ (is (= "type/Number"+ (t2/select-one-fn :effective_type (t2/table-name :model/Field) :id broken-id))))+ (testing "row that was already consistent is untouched"+ (is (= "type/Number"+ (t2/select-one-fn :effective_type (t2/table-name :model/Field) :id already-ok-id))))+ (testing "row with a real coercion is untouched"+ (is (= "type/Number"+ (t2/select-one-fn :effective_type (t2/table-name :model/Field) :id with-coercion-id)))+ (is (= "Coercion/String->Number"+ (t2/select-one-fn :coercion_strategy (t2/table-name :model/Field) :id with-coercion-id))))+ (testing "row with NULL effective_type is left alone (separate concern, GHY-3367 territory)"+ (is (nil? (t2/select-one-fn :effective_type (t2/table-name :model/Field) :id null-effective-id))))+ (testing "inactive rows are skipped (avoid resurrecting dead state)"+ (is (= "type/Text"+ (t2/select-one-fn :effective_type (t2/table-name :model/Field) :id inactive-broken-id))))+ (testing "user-settings overlay is healed in lockstep"+ (is (= "type/Number"+ (t2/select-one-fn :effective_type :metabase_field_user_settings :field_id broken-id))))+ (testing "user-settings with a real coercion is untouched"+ (is (= "type/Number"+ (t2/select-one-fn :effective_type :metabase_field_user_settings :field_id with-coercion-id))))))))diff --git a/test/metabase/sync/sync_metadata/fields/sync_metadata_test.clj b/test/metabase/sync/sync_metadata/fields/sync_metadata_test.cljindex ee0b24ca637..2c0eec530f3 100644--- a/test/metabase/sync/sync_metadata/fields/sync_metadata_test.clj+++ b/test/metabase/sync/sync_metadata/fields/sync_metadata_test.clj@@ -364,3 +364,136 @@(is (not= (:fingerprint original-field) (:fingerprint new-field))))))(finally(t2/delete! :model/Database (mt/id))))))))++(deftest create-or-replace-table-updates-effective-type-test+ (testing "GHY-3388: when a column's database type changes in place (e.g. TEXT -> numeric via+ Snowflake's CREATE OR REPLACE TABLE AS SELECT TRY_TO_NUMBER(...)), sync should update+ effective_type to match the new base_type and clear any stale coercion_strategy/semantic_type.+ Reproduces the in-place update path (repro v1 from the Linear issue), where the field row+ is preserved and only updated — as opposed to being dropped and re-created (repro v2)."+ (mt/with-temp-test-data [["my_table"+ [{:field-name "text_column"+ :base-type :type/Text}]+ [["100"] ["200"] ["300"]]]]+ (try+ (sync/sync-database! (mt/db))+ (let [original-field (t2/select-one :model/Field (mt/id :my_table :text_column))]+ (testing "sanity check: original column is text"+ (is (=? {:base_type :type/Text+ :effective_type :type/Text}+ original-field)))+ ;; Mimic Snowflake's CREATE OR REPLACE TABLE AS SELECT TRY_TO_NUMBER(text_column) —+ ;; the column is converted to a numeric type in place, preserving the field's identity+ ;; in Metabase's app DB (same name, same position). Snowflake's CREATE OR REPLACE does+ ;; not translate to H2, so we use ALTER COLUMN to achieve the same "in-place update" effect.+ (sql-jdbc.execute/do-with-connection-with-options+ :h2+ (mt/db)+ {}+ (fn [conn]+ (doseq [sql ["DROP TABLE \"MY_TABLE\";"+ "CREATE TABLE \"MY_TABLE\" (\"TEXT_COLUMN\" DECIMAL(38,2));"+ "INSERT INTO \"MY_TABLE\"(text_column) VALUES(100.00),(200.00),(300.00);"]]+ (next.jdbc/execute! conn [sql]))))+ (sync/sync-database! (mt/db))+ (let [new-field (t2/select-one :model/Field (mt/id :my_table :text_column))]+ (testing "after sync, base_type and effective_type both reflect the new numeric column+ and stale coercion/semantic type are cleared"+ (is (=? {:id (:id original-field)+ :base_type :type/Decimal+ :effective_type :type/Decimal+ :coercion_strategy nil+ :semantic_type nil}+ new-field))))++ (sql-jdbc.execute/do-with-connection-with-options+ :h2+ (mt/db)+ {}+ (fn [conn]+ (doseq [sql ["DROP TABLE \"MY_TABLE\";"]]+ (next.jdbc/execute! conn [sql]))))++ (t2/delete! :model/Table (:table_id original-field))+ (t2/delete! :model/Field :table_id (:table_id original-field))++ (sql-jdbc.execute/do-with-connection-with-options+ :h2+ (mt/db)+ {}+ (fn [conn]+ (doseq [sql ["CREATE TABLE \"MY_TABLE\" (\"TEXT_COLUMN\" TEXT);"+ "INSERT INTO \"MY_TABLE\"(text_column) VALUES('100'),('200'),('300');"]]+ (next.jdbc/execute! conn [sql]))))+ (sync/sync-database! (mt/db))+ (sql-jdbc.execute/do-with-connection-with-options+ :h2+ (mt/db)+ {}+ (fn [conn]+ (doseq [sql ["DROP TABLE \"MY_TABLE\";"+ "CREATE TABLE \"MY_TABLE\" (\"TEXT_COLUMN\" DECIMAL(38,2));"+ "INSERT INTO \"MY_TABLE\"(text_column) VALUES(100.00),(200.00),(300.00);"]]+ (next.jdbc/execute! conn [sql]))))+ (sync/sync-database! (mt/db))++ (let [new-field (t2/select-one :model/Field :name "TEXT_COLUMN")]+ (testing "after sync, base_type and effective_type both reflect the new numeric column+ and stale coercion/semantic type are cleared"+ (is (=? {:base_type :type/Decimal+ :effective_type :type/Decimal+ :coercion_strategy nil+ :semantic_type nil}+ new-field)))))+ (finally+ (t2/delete! :model/Database (mt/id)))))))++(deftest sync-self-heals-effective-type-drift-test+ (testing "GHY-3388: when a field is in the broken state (effective_type ≠ base_type with no+ coercion_strategy) AND base_type does not change at this sync, sync should still+ heal effective_type to match base_type. This catches drifted state from older+ Metabase versions that the customer's instance carries forward."+ (testing "broken row gets healed even when base_type does not change"+ (is (= [["FieldUserSettings" 1 {:effective_type :type/Number}]+ ["Field" 1 {:effective_type :type/Number}]]+ (updates-that-will-be-performed!+ (merge default-metadata+ {:base-type :type/Number})+ (merge default-metadata+ {:id 1+ :base-type :type/Number+ :effective-type :type/Text+ :coercion-strategy nil})))))+ (testing "row with a real coercion_strategy is left alone — effective_type ≠ base_type is legitimate"+ (is (= []+ (updates-that-will-be-performed!+ (merge default-metadata+ {:base-type :type/Text})+ (merge default-metadata+ {:id 1+ :base-type :type/Text+ :effective-type :type/Number+ :coercion-strategy :Coercion/String->Number})))))+ (testing "row that is already consistent is not updated"+ (is (= []+ (updates-that-will-be-performed!+ (merge default-metadata+ {:base-type :type/Number})+ (merge default-metadata+ {:id 1+ :base-type :type/Number+ :effective-type :type/Number+ :coercion-strategy nil})))))+ (testing "when base_type also changes, the existing reset path runs (not the heal path) —+ both produce the same effective_type but the base_type-change path also clears+ fingerprint and semantic_type for re-analysis"+ (let [updates (updates-that-will-be-performed!+ (merge default-metadata+ {:base-type :type/Number})+ (merge default-metadata+ {:id 1+ :base-type :type/Text+ :effective-type :type/Text+ :coercion-strategy nil}))]+ (is (some #(contains? (last %) :fingerprint_version) updates)+ "base_type-change reset still includes fingerprint reset")))))diff --git a/test/metabase/test/data/impl/get_or_create.clj b/test/metabase/test/data/impl/get_or_create.cljindex a97d40cf717..f45584fb600 100644--- a/test/metabase/test/data/impl/get_or_create.clj+++ b/test/metabase/test/data/impl/get_or_create.clj@@ -101,10 +101,22 @@(throw (Exception. (format "Field '%s' not loaded from definition:\n%s"field-name(u/pprint-to-str field-definition))))))]- (doseq [property [:visibility-type :semantic-type :effective-type :coercion-strategy]]+ (doseq [property [:visibility-type :semantic-type]](when-let [v (get field-definition property)](log/debugf "SET %s %s.%s -> %s" property table-name field-name v)- (t2/update! :model/Field (:id @field) {(keyword (str/replace (name property) #"-" "_")) (u/qualified-name v)}))))))))+ (t2/update! :model/Field (:id @field) {(keyword (str/replace (name property) #"-" "_")) (u/qualified-name v)})))+ ;; effective-type and coercion-strategy must be set atomically — the GHY-3388 model+ ;; invariant requires effective_type=base_type when coercion_strategy is nil, so a+ ;; sequence that sets effective_type alone first would be reverted before+ ;; coercion_strategy lands.+ (let [eff-type (:effective-type field-definition)+ coerce (:coercion-strategy field-definition)+ upd (cond-> {}+ eff-type (assoc :effective_type (u/qualified-name eff-type))+ coerce (assoc :coercion_strategy (u/qualified-name coerce)))]+ (when (seq upd)+ (log/debugf "SET effective-type/coercion-strategy %s.%s -> %s" table-name field-name upd)+ (t2/update! :model/Field (:id @field) upd))))))))(def ^:private create-database-timeout-ms"Max amount of time to wait for driver text extensions to create a DB and load test data."diff --git a/test/metabase/warehouse_schema/models/field_test.clj b/test/metabase/warehouse_schema/models/field_test.cljindex b6caea0a42d..15fcd08b11d 100644--- a/test/metabase/warehouse_schema/models/field_test.clj+++ b/test/metabase/warehouse_schema/models/field_test.clj@@ -9,6 +9,7 @@[metabase.test :as mt][metabase.util :as u][metabase.warehouse-schema.models.field :as field]+ [metabase.warehouse-schema.models.field-user-settings :as field-user-settings][toucan2.core :as t2]))(deftest unknown-types-test@@ -153,3 +154,208 @@(data-perms/set-table-permission! pg table-id :perms/create-queries :query-builder)(mt/with-test-user :rasta(is (true? (mi/can-query? (t2/select-one :model/Field field-id))))))))++;;; ---------------------------------- effective_type invariant guard tests -----------------------------------+;;; GHY-3388: a Field with coercion_strategy=nil and effective_type ≠ base_type is internally+;;; inconsistent — there's no coercion to justify the divergence. The model guard normalizes+;;; effective_type to base_type on insert and update so this state cannot be written by any+;;; caller (sync, API, serdes import, manual writes).++(deftest effective-type-guard-on-insert-test+ (testing "GHY-3388: inserting a field with effective_type ≠ base_type and no coercion_strategy+ gets normalized: effective_type is forced to match base_type"+ (mt/with-temp [:model/Database {db-id :id} {}+ :model/Table {table-id :id} {:db_id db-id}]+ (let [field-id (first (t2/insert-returning-pks!+ :model/Field+ {:table_id table-id+ :name "broken_on_insert"+ :display_name "broken_on_insert"+ :database_type "NUMBER"+ :base_type :type/Number+ :effective_type :type/Text+ :coercion_strategy nil+ :position 0+ :database_position 0}))]+ (is (=? {:base_type :type/Number+ :effective_type :type/Number}+ (t2/select-one :model/Field :id field-id)))))))++(deftest effective-type-guard-on-update-test+ (testing "GHY-3388: updating a field to set effective_type ≠ base_type with no coercion_strategy+ gets normalized; effective_type is forced to match base_type"+ (mt/with-temp [:model/Database {db-id :id} {}+ :model/Table {table-id :id} {:db_id db-id}+ :model/Field {field-id :id} {:table_id table-id+ :name "broken_on_update"+ :base_type :type/Number+ :effective_type :type/Number}]+ (t2/update! :model/Field field-id {:effective_type :type/Text+ :coercion_strategy nil})+ (is (=? {:base_type :type/Number+ :effective_type :type/Number}+ (t2/select-one :model/Field :id field-id))))))++(deftest effective-type-guard-preserves-legitimate-coercion-test+ (testing "GHY-3388: a field with a real coercion_strategy keeps its custom effective_type — the+ guard only fires when coercion_strategy is nil"+ (mt/with-temp [:model/Database {db-id :id} {}+ :model/Table {table-id :id} {:db_id db-id}+ :model/Field {field-id :id} {:table_id table-id+ :name "with_coercion"+ :base_type :type/Text+ :effective_type :type/Text}]+ (t2/update! :model/Field field-id {:effective_type :type/Number+ :coercion_strategy :Coercion/String->Number})+ (is (=? {:base_type :type/Text+ :effective_type :type/Number+ :coercion_strategy :Coercion/String->Number}+ (t2/select-one :model/Field :id field-id))))))++(deftest effective-type-guard-clearing-coercion-resets-effective-type-test+ (testing "GHY-3388: clearing coercion_strategy without explicitly setting effective_type to+ match base_type still results in a consistent row — the guard normalizes effective_type"+ (mt/with-temp [:model/Database {db-id :id} {}+ :model/Table {table-id :id} {:db_id db-id}+ :model/Field {field-id :id} {:table_id table-id+ :name "clearing_coercion"+ :base_type :type/Text+ :effective_type :type/Number+ :coercion_strategy :Coercion/String->Number}]+ ;; user clears the coercion but doesn't reset effective_type — guard catches this+ (t2/update! :model/Field field-id {:coercion_strategy nil})+ (is (=? {:base_type :type/Text+ :effective_type :type/Text+ :coercion_strategy nil}+ (t2/select-one :model/Field :id field-id))))))++(defn- assert-coercion-effective-type-invariant!+ "Reads the field row and asserts the GHY-3388 invariant:+ coercion_strategy is nil ⇒ effective_type = base_type."+ [field-id label]+ (let [{:keys [base_type effective_type coercion_strategy]} (t2/select-one :model/Field :id field-id)]+ (when (nil? coercion_strategy)+ (is (= base_type effective_type)+ (format "GHY-3388 invariant violated after %s: base_type=%s effective_type=%s coercion_strategy=nil"+ label (pr-str base_type) (pr-str effective_type))))))++(deftest effective-type-invariant-battery-test+ (testing "GHY-3388 INVARIANT: for any field row, if coercion_strategy is nil then effective_type+ must equal base_type. This battery exercises every write path that could violate the+ invariant and asserts it holds afterward. Adding a new path that writes :effective_type+ or :coercion_strategy on :model/Field should add a case here."+ (doseq [[label op]+ [["t2/insert! with broken state (effective_type ≠ base_type, coercion_strategy nil)"+ (fn [table-id]+ (first (t2/insert-returning-pks!+ :model/Field+ {:table_id table-id+ :name "ins_broken"+ :display_name "ins_broken"+ :database_type "NUMBER"+ :base_type :type/Number+ :effective_type :type/Text+ :coercion_strategy nil+ :position 0+ :database_position 0})))]++ ["t2/insert! with effective_type only set (no coercion)"+ (fn [table-id]+ (first (t2/insert-returning-pks!+ :model/Field+ {:table_id table-id+ :name "ins_eff_only"+ :display_name "ins_eff_only"+ :database_type "NUMBER"+ :base_type :type/Number+ :effective_type :type/Integer+ :position 0+ :database_position 0})))]++ ["t2/update! sets effective_type to differ from base_type without coercion"+ (fn [table-id]+ (let [id (first (t2/insert-returning-pks!+ :model/Field+ {:table_id table-id+ :name "upd_eff"+ :display_name "upd_eff"+ :database_type "NUMBER"+ :base_type :type/Number+ :effective_type :type/Number+ :position 0+ :database_position 0}))]+ (t2/update! :model/Field id {:effective_type :type/Text})+ id))]++ ["t2/update! clears coercion_strategy but leaves effective_type stale"+ (fn [table-id]+ (let [id (first (t2/insert-returning-pks!+ :model/Field+ {:table_id table-id+ :name "upd_clear_coerce"+ :display_name "upd_clear_coerce"+ :database_type "TEXT"+ :base_type :type/Text+ :effective_type :type/Number+ :coercion_strategy :Coercion/String->Number+ :position 0+ :database_position 0}))]+ (t2/update! :model/Field id {:coercion_strategy nil})+ id))]++ ["t2/update! changes base_type but leaves effective_type stale"+ (fn [table-id]+ (let [id (first (t2/insert-returning-pks!+ :model/Field+ {:table_id table-id+ :name "upd_base"+ :display_name "upd_base"+ :database_type "TEXT"+ :base_type :type/Text+ :effective_type :type/Text+ :position 0+ :database_position 0}))]+ (t2/update! :model/Field id {:base_type :type/Number})+ id))]++ ["t2/update! sets both effective_type AND coercion_strategy=nil to mismatched values"+ (fn [table-id]+ (let [id (first (t2/insert-returning-pks!+ :model/Field+ {:table_id table-id+ :name "upd_both"+ :display_name "upd_both"+ :database_type "NUMBER"+ :base_type :type/Number+ :effective_type :type/Number+ :position 0+ :database_position 0}))]+ (t2/update! :model/Field id {:effective_type :type/Text+ :coercion_strategy nil})+ id))]++ ["upsert-user-settings writes broken effective_type then any field update fires the merge-back overlay"+ (fn [table-id]+ (let [id (first (t2/insert-returning-pks!+ :model/Field+ {:table_id table-id+ :name "upsert_then_upd"+ :display_name "upsert_then_upd"+ :database_type "NUMBER"+ :base_type :type/Number+ :effective_type :type/Number+ :position 0+ :database_position 0}))]+ ;; write a stale, no-coercion overlay into user-settings+ (field-user-settings/upsert-user-settings+ {:id id}+ {:effective_type :type/Text :coercion_strategy nil})+ ;; trigger before-update (which runs sync-user-settings overlay merge)+ (t2/update! :model/Field id {:display_name "trigger merge"})+ id))]]]++ (testing label+ (mt/with-temp [:model/Database {db-id :id} {}+ :model/Table {table-id :id} {:db_id db-id}]+ (let [field-id (op table-id)]+ (assert-coercion-effective-type-invariant! field-id label)))))))