Skip to content

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

GHY-4251: Bound dependency backfill memory and stop its crash loop (#79392)

Eric Normand43915d73538f
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.edn
index ae563dabfa7..f5cc9cde6e4 100644
--- a/.clj-kondo/config/modules/config.edn
+++ b/.clj-kondo/config/modules/config.edn
@@ -2234,7 +2234,8 @@
lib
settings
sql-parsing
- util}}
+ util}
+ :model-imports #{:model/Table}}
sso
{:team "UX West"
diff --git a/enterprise/backend/src/metabase_enterprise/dependencies/findings.clj b/enterprise/backend/src/metabase_enterprise/dependencies/findings.clj
index 6de5f909caa..0fafbe5b4e8 100644
--- a/enterprise/backend/src/metabase_enterprise/dependencies/findings.clj
+++ b/enterprise/backend/src/metabase_enterprise/dependencies/findings.clj
@@ -164,11 +164,14 @@
termination even when the dependency graph has cycles."
[type :- AnalyzableEntityType
batch-size :- pos-int?]
- (let [instances (deps.analysis-finding/instances-for-analysis type batch-size)]
- (lib-be/with-metadata-provider-cache
+ ;; The cache spans the select too: reading an entity attaches a `MetadataProvider` to its query
+ ;; (see `metabase.lib-be.models.transforms/transform-query`), so selecting outside the cache gives every entity in
+ ;; the batch a private one.
+ (lib-be/with-metadata-provider-cache
+ (let [instances (deps.analysis-finding/instances-for-analysis type batch-size)]
(doseq [instance instances]
(try (upsert-analysis! instance)
(catch Exception e
(log/errorf "Analyzing entity %s %s failed: %s"
- (t2/model instance) (:id instance) (ex-message e))))))
- (count instances)))
+ (t2/model instance) (:id instance) (ex-message e)))))
+ (count instances))))
diff --git a/enterprise/backend/src/metabase_enterprise/dependencies/models/dependency_status.clj b/enterprise/backend/src/metabase_enterprise/dependencies/models/dependency_status.clj
index 46dfea30e68..b2848ea4fb5 100644
--- a/enterprise/backend/src/metabase_enterprise/dependencies/models/dependency_status.clj
+++ b/enterprise/backend/src/metabase_enterprise/dependencies/models/dependency_status.clj
@@ -110,19 +110,24 @@
(defn record-failure!
"Record a failed dependency calculation attempt for an entity.
Increments fail_count and sets next_retry_at based on exponential backoff.
- If max retries exceeded, marks the entity as terminal."
+ If max retries exceeded, marks the entity as terminal.
+ Creates the entry if it doesn't exist, since entities with no row yet are exactly the ones
+ [[instances-for-dependency-calculation]] picks up first.
+ Uses [[app-db/update-or-insert!]] for cross-database atomicity."
[entity-type entity-id max-retries delay-minutes]
- (when-let [status (t2/select-one :model/DependencyStatus
- :entity_type entity-type
- :entity_id entity-id)]
- (let [new-fail-count (inc (:fail_count status 0))]
- (if (> new-fail-count max-retries)
- (t2/update! :model/DependencyStatus (:id status)
- {:fail_count new-fail-count
- :terminal true
- :next_retry_at nil})
- (let [retry-minutes (* new-fail-count delay-minutes)]
- (t2/update! :model/DependencyStatus (:id status)
- {:fail_count new-fail-count
- :next_retry_at (when (pos? retry-minutes)
- (t/plus (t/offset-date-time) (t/minutes retry-minutes)))}))))))
+ (app-db/update-or-insert!
+ :model/DependencyStatus
+ {:entity_type entity-type :entity_id entity-id}
+ (fn [existing]
+ ;; An inserted row takes the column defaults for `stale` (false) and `dependency_analysis_version` (0). 0 is
+ ;; below `current-dependency-analysis-version`, which is what keeps the entity eligible for the retry once
+ ;; `next_retry_at` has elapsed.
+ (let [new-fail-count (inc (:fail_count existing 0))]
+ (if (> new-fail-count max-retries)
+ {:fail_count new-fail-count
+ :terminal true
+ :next_retry_at nil}
+ (let [retry-minutes (* new-fail-count delay-minutes)]
+ {:fail_count new-fail-count
+ :next_retry_at (when (pos? retry-minutes)
+ (t/plus (t/offset-date-time) (t/minutes retry-minutes)))}))))))
diff --git a/enterprise/backend/src/metabase_enterprise/dependencies/task/backfill.clj b/enterprise/backend/src/metabase_enterprise/dependencies/task/backfill.clj
index 2fc70278a8e..60838ba00bf 100644
--- a/enterprise/backend/src/metabase_enterprise/dependencies/task/backfill.clj
+++ b/enterprise/backend/src/metabase_enterprise/dependencies/task/backfill.clj
@@ -18,6 +18,7 @@
[metabase-enterprise.dependencies.settings :as deps.settings]
[metabase-enterprise.dependencies.task-util :as deps.task-util]
[metabase.events.core :as events]
+ [metabase.lib-be.core :as lib-be]
[metabase.premium-features.core :as premium-features]
[metabase.task.core :as task]
[metabase.transforms.core :as transforms]
@@ -92,37 +93,40 @@
(defn- backfill-entity-batch!
[entity-type batch-size]
- (let [type-name (name entity-type)
- instances (processable-instances entity-type batch-size)]
- (when (seq instances)
- (log/infof "Processing a batch of %s %s(s)..." (count instances) type-name))
- (reduce (fn [total entity]
- (+ total
- (try
- (compute-deps-for-entity! entity-type entity)
- 1
- (catch Exception e
- (let [id (:id entity)]
- (try
- (deps.dependency-status/record-failure!
- entity-type id max-retries
- (deps.settings/dependency-backfill-delay-minutes))
- (let [{:keys [fail_count terminal]} (t2/select-one :model/DependencyStatus
- :entity_type entity-type
- :entity_id id)]
- (if terminal
- (log/errorf "Entity %s %s failed %d times, marking as terminally broken: %s"
- type-name id fail_count (ex-message e))
- (log/warnf "Entity %s %s failed, failure count: %d. %s"
- type-name id fail_count (ex-message e))))
- (catch Exception record-ex
- (log/errorf "Entity %s %s failed during dependency calculation: %s"
- type-name id (ex-message e))
- (log/errorf "Additionally, failed to record the failure for %s %s: %s"
- type-name id (ex-message record-ex)))))
- 0))))
- 0
- instances)))
+ (lib-be/with-metadata-provider-cache
+ (let [type-name (name entity-type)
+ instances (processable-instances entity-type batch-size)]
+ (when (seq instances)
+ (log/infof "Processing a batch of %s %s(s)..." (count instances) type-name))
+ (reduce (fn [total entity]
+ (+ total
+ (try
+ (compute-deps-for-entity! entity-type entity)
+ 1
+ (catch Throwable e ;; catch OOMs
+ (let [id (:id entity)]
+ (try
+ (deps.dependency-status/record-failure!
+ entity-type id max-retries
+ (deps.settings/dependency-backfill-delay-minutes))
+ (let [{:keys [fail_count terminal]} (t2/select-one :model/DependencyStatus
+ :entity_type entity-type
+ :entity_id id)]
+ (if terminal
+ (log/errorf "Entity %s %s failed %d times, marking as terminally broken: %s"
+ type-name id fail_count (ex-message e))
+ (log/warnf "Entity %s %s failed, failure count: %d. %s"
+ type-name id fail_count (ex-message e))))
+ (catch Exception record-ex
+ (log/errorf "Entity %s %s failed during dependency calculation: %s"
+ type-name id (ex-message e))
+ (log/errorf "Additionally, failed to record the failure for %s %s: %s"
+ type-name id (ex-message record-ex)))))
+ (when-not (instance? Exception e) ;; re-throw Errors
+ (throw e))
+ 0))))
+ 0
+ instances))))
(defn- backfill-dependencies!
"Job to backfill dependencies for all entities.
@@ -140,11 +144,44 @@
entity-types)
(< 1))))
-(defn- has-pending-retries? []
- (deps.dependency-status/has-pending-retries?))
+(defn- has-pending-retries?
+ "Whether any entity is in retry backoff that this instance can actually act on.
+
+ Fails open on an indeterminate token status. `has-feature?` cannot tell a network failure from being unlicensed, and
+ both inputs to the job's reschedule decision consult the licence, so reading a blip as `false` would stop the job
+ for good — nothing re-fires when the check recovers, because the token never changed. Only a definitive `false`
+ counts as unlicensed here — which is the common case, since no token at all answers `false`. A token that cannot be
+ validated answers `nil` and keeps the job alive. Doing the work still fails closed — see
+ [[backfill-dependencies!]]."
+ []
+ (and (not (false? (premium-features/canonically-has-feature? :dependencies)))
+ (deps.dependency-status/has-pending-retries?)))
(declare schedule-run!)
+(defn- next-run-delay []
+ (deps.task-util/job-delay
+ (deps.settings/dependency-backfill-delay-minutes)
+ (deps.settings/dependency-backfill-variance-minutes)))
+
+(defn- run-and-reschedule!
+ "Process a batch, then schedule the next run if there is more to do.
+
+ Reschedules on the way out of a failure too, then rethrows. This job is one-shot self-rescheduling with no cron
+ backstop, so anything escaping the batch would otherwise end the chain until a content-change event or a restart —
+ survivable for an `OutOfMemoryError` that takes the process with it, not for a `StackOverflowError` from
+ pathological SQL that leaves a live process behind."
+ [scheduler]
+ (try
+ (let [full-batch-selected? (backfill-dependencies!)
+ retries? (has-pending-retries?)]
+ (if (or full-batch-selected? retries?)
+ (schedule-run! scheduler (next-run-delay))
+ (log/info "No more entities to backfill for, stopping.")))
+ (catch Throwable e
+ (schedule-run! scheduler (next-run-delay))
+ (throw e))))
+
(defn- log-job-start
[^JobExecutionContext ctx]
(let [scheduler (.getScheduler ctx)
@@ -159,20 +196,14 @@
BackfillDependencies [ctx]
(let [ctx ^JobExecutionContext ctx]
(log-job-start ctx)
- (let [full-batch-selected? (backfill-dependencies!)
- retries? (has-pending-retries?)]
- (if (or full-batch-selected?
- retries?)
- (let [delay-in-seconds (deps.task-util/job-delay
- (deps.settings/dependency-backfill-delay-minutes)
- (deps.settings/dependency-backfill-variance-minutes))]
- (schedule-run! (.getScheduler ctx) delay-in-seconds))
- (log/info "No more entities to backfill for, stopping.")))))
+ (run-and-reschedule! (.getScheduler ctx))))
(def ^:private job-key "metabase.task.dependency-backfill.job")
(def ^:private trigger-key "metabase.task.dependency-backfill.trigger")
-(defn- schedule-run! [scheduler delay-in-seconds]
+(defn- schedule-run!
+ "Schedule a run of the backfill job `delay-in-seconds` from now."
+ [scheduler delay-in-seconds]
(let [start-at (-> (t/instant)
(t/+ (t/duration delay-in-seconds :seconds))
java.util.Date/from)
@@ -185,19 +216,24 @@
(task/schedule-task! scheduler job trigger)))
(defn trigger-backfill-job!
- "Trigger the BackfillDependencies job to run after a brief delay.
- The 1-second delay ensures the calling transaction has committed before
- the job checks for stale entities."
+ "Trigger the BackfillDependencies job to run after a brief delay, unless the batch size disables it.
+
+ The 1-second delay ensures the calling transaction has committed before the job checks for stale entities. Entity
+ changes fire this, so leaving it ungated is what made a disabled job wake roughly once a second; the job's own
+ periodic schedule is left alone so it still resumes if the batch size becomes positive.
+
+ Disable with MB_DEPENDENCY_BACKFILL_BATCH_SIZE=0"
[]
- (schedule-run! (task/scheduler) 1))
+ (when (pos? (deps.settings/dependency-backfill-batch-size))
+ (schedule-run! (task/scheduler) 1)))
(defmethod task/init! ::DependencyBackfill [_]
- (if (pos? (deps.settings/dependency-backfill-batch-size))
- (schedule-run!
- (task/scheduler)
- (deps.task-util/job-initial-delay
- (deps.settings/dependency-backfill-variance-minutes)))
- (log/info "Not starting dependency backfill job because the batch size is not positive")))
+ (when-not (pos? (deps.settings/dependency-backfill-batch-size))
+ (log/info "Dependency backfill batch size is not positive; the job will run but process nothing"))
+ (schedule-run!
+ (task/scheduler)
+ (deps.task-util/job-initial-delay
+ (deps.settings/dependency-backfill-variance-minutes))))
(events/derive! ::backfill :metabase/event)
(events/derive! :event/serdes-load ::backfill)
diff --git a/enterprise/backend/src/metabase_enterprise/dependencies/task/entity_check.clj b/enterprise/backend/src/metabase_enterprise/dependencies/task/entity_check.clj
index 1faa7beafe5..7cb7a386573 100644
--- a/enterprise/backend/src/metabase_enterprise/dependencies/task/entity_check.clj
+++ b/enterprise/backend/src/metabase_enterprise/dependencies/task/entity_check.clj
@@ -7,9 +7,11 @@
[metabase-enterprise.dependencies.models.analysis-finding :as deps.analysis-finding]
[metabase-enterprise.dependencies.settings :as deps.settings]
[metabase-enterprise.dependencies.task-util :as deps.task-util]
+ [metabase.events.core :as events]
[metabase.premium-features.core :as premium-features]
[metabase.task.core :as task]
- [metabase.util.log :as log]))
+ [metabase.util.log :as log]
+ [methodical.core :as methodical]))
(set! *warn-on-reflection* true)
@@ -49,21 +51,41 @@
(declare schedule-run!)
+(defn- reschedule-after-run!
+ "Schedule the next periodic run of the entity check job, unless the `:dependencies` feature is absent.
+
+ Unlike the backfill job this one has no terminal state — it is a periodic checker, so while licensed it always queues
+ another run rather than stopping once the stale set is drained. Without the feature there is nothing the next run
+ could do, since [[check-entities!]] is gated on it, so rescheduling would just wake the instance forever. The job
+ restarts from the token event above, from the content-change handlers, or on the next restart.
+
+ Scheduling deliberately fails open on an indeterminate token status: `has-feature?` cannot tell a network failure
+ from being unlicensed, and nothing re-fires when the check later succeeds, so reading a blip as `false` would end
+ the chain for good. Only a definitive `false` stops it — which is the common unlicensed case, since no token at all
+ answers `false`. A token that cannot be validated answers `nil` and keeps the job scheduled: if there is a token, we
+ keep trying. Doing the work still fails closed — see [[check-entities!]]."
+ [scheduler]
+ (if (false? (premium-features/canonically-has-feature? :dependencies))
+ (log/debug "Not rescheduling job Dependency Entity Check: the dependencies feature is not enabled")
+ (schedule-run! scheduler
+ (deps.task-util/job-delay
+ (deps.settings/dependency-entity-check-delay-minutes)
+ (deps.settings/dependency-entity-check-variance-minutes)))))
+
(task/defjob
^{:doc "Check all entities for validity"
org.quartz.DisallowConcurrentExecution true}
DependencyEntityCheck [ctx]
(log/info "Executing DependencyEntityCheck job...")
(check-entities!)
- (let [delay-in-seconds (deps.task-util/job-delay
- (deps.settings/dependency-entity-check-delay-minutes)
- (deps.settings/dependency-entity-check-variance-minutes))]
- (schedule-run! (.getScheduler ctx) delay-in-seconds)))
+ (reschedule-after-run! (.getScheduler ctx)))
(def ^:private job-key "metabase.dependencies.task.entity-check.job")
(def ^:private trigger-key "metabase.dependencies.task.entity-check.trigger")
-(defn- schedule-run! [scheduler delay-in-seconds]
+(defn- schedule-run!
+ "Schedule a run of the entity check job `delay-in-seconds` from now."
+ [scheduler delay-in-seconds]
(let [start-at (-> (t/instant)
(t/+ (t/duration delay-in-seconds :seconds))
java.util.Date/from)
@@ -76,16 +98,32 @@
(task/schedule-task! scheduler job trigger)))
(defmethod task/init! ::DependencyEntityCheck [_]
- (if (pos? (deps.settings/dependency-entity-check-batch-size))
- (schedule-run!
- (task/scheduler)
- (deps.task-util/job-initial-delay
- (deps.settings/dependency-entity-check-variance-minutes)))
- (log/info "Not starting dependency entity check job because the batch size is not positive")))
+ (when-not (pos? (deps.settings/dependency-entity-check-batch-size))
+ (log/info "Dependency entity check batch size is not positive; the job will run but process nothing"))
+ (schedule-run!
+ (task/scheduler)
+ (deps.task-util/job-initial-delay
+ (deps.settings/dependency-entity-check-variance-minutes))))
(defn trigger-entity-check-job!
- "Trigger the DependencyEntityCheck job to run after a brief delay.
- The 1-second delay ensures the calling transaction has committed before
- the job checks for stale entities."
+ "Trigger the DependencyEntityCheck job to run after a brief delay, unless the batch size disables it.
+
+ The 1-second delay ensures the calling transaction has committed before the job checks for stale entities. Entity
+ changes fire this, so leaving it ungated is what made a disabled job wake roughly once a second; the job's own
+ periodic schedule is left alone so it still resumes if the batch size becomes positive.
+
+ Disable with MB_DEPENDENCY_ENTITY_CHECK_BATCH_SIZE=0"
[]
- (schedule-run! (task/scheduler) 1))
+ (when (pos? (deps.settings/dependency-entity-check-batch-size))
+ (schedule-run! (task/scheduler) 1)))
+
+;;; Mirrors the backfill job's wiring: enabling the feature has to restart the job, because
+;;; [[reschedule-after-run!]] stops the periodic chain while it is disabled and the content-change handlers that
+;;; would otherwise revive it are themselves gated on the feature.
+(events/derive! ::entity-check :metabase/event)
+(events/derive! :event/set-premium-embedding-token ::entity-check)
+
+(methodical/defmethod events/publish-event! ::entity-check
+ [_ _]
+ (when (premium-features/has-feature? :dependencies)
+ (trigger-entity-check-job!)))
diff --git a/enterprise/backend/test/metabase_enterprise/dependencies/core_test.clj b/enterprise/backend/test/metabase_enterprise/dependencies/core_test.clj
index e48e2c075f4..275b10a7b9e 100644
--- a/enterprise/backend/test/metabase_enterprise/dependencies/core_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/dependencies/core_test.clj
@@ -7,8 +7,8 @@
[metabase.graph.core :as graph]
[metabase.lib.core :as lib]
[metabase.lib.metadata :as lib.metadata]
- [metabase.lib.test-metadata :as meta]
[metabase.lib.test-util :as lib.tu]
+ [metabase.test :as mt]
[metabase.util.malli :as mu]))
(defn- only-missing-column-errors
@@ -36,9 +36,9 @@
"A `MetadataProvider` with a chain of MBQL cards and transforms for testing."
[]
(let [mp (deps.tu/default-metadata-provider)
- query1 (-> (lib/query mp (meta/table-metadata :orders))
- (lib/expression "Tax Rate" (lib// (meta/field-metadata :orders :tax)
- (meta/field-metadata :orders :subtotal))))
+ query1 (-> (lib/query mp (lib.metadata/table (mt/metadata-provider) (mt/id :orders)))
+ (lib/expression "Tax Rate" (lib// (lib.metadata/field (mt/metadata-provider) (mt/id :orders :tax))
+ (lib.metadata/field (mt/metadata-provider) (mt/id :orders :subtotal)))))
mp (lib.tu/metadata-provider-with-card-from-query mp 101 query1)
card1 (lib.metadata/card mp 101)
card1-query (lib/query mp card1)
@@ -55,7 +55,7 @@
:source {:query tf1-query}
:target {:schema "Transformed"
:name "output_tf30"}}
- tf1-output (-> (meta/table-metadata :orders)
+ tf1-output (-> (lib.metadata/table (mt/metadata-provider) (mt/id :orders))
(assoc :id 1234567
:schema "Transformed"
:name "output_tf30"
@@ -86,7 +86,7 @@
:source {:query (lib/->legacy-MBQL tf2-query)}
:target {:schema "Transformed"
:name "output_tf31"}}
- tf2-output (-> (meta/table-metadata :orders)
+ tf2-output (-> (lib.metadata/table (mt/metadata-provider) (mt/id :orders))
(assoc :id 1234568
:schema "Transformed"
:name "output_tf31"
@@ -159,10 +159,10 @@
(testing "a column that no longer exists will cause errors when referenced"
(let [card' (-> mbql-base
(assoc :dataset-query
- (-> (lib/query provider (meta/table-metadata :orders))
+ (-> (lib/query provider (lib.metadata/table (mt/metadata-provider) (mt/id :orders)))
;; ridiculous
- (lib/expression "Sales Taxes" (lib// (meta/field-metadata :orders :tax)
- (meta/field-metadata :orders :subtotal)))))
+ (lib/expression "Sales Taxes" (lib// (lib.metadata/field (mt/metadata-provider) (mt/id :orders :tax))
+ (lib.metadata/field (mt/metadata-provider) (mt/id :orders :subtotal))))))
(dissoc :result-metadata))
errors (dependencies/errors-from-proposed-edits {:card [card']}
:base-provider provider
@@ -180,7 +180,7 @@
(is (= #{downstream-card-id transformed-card-id} (set (keys (:card errors)))))))
(testing "changing something unrelated will cause no errors"
(let [card' (-> mbql-base
- (update :dataset-query lib/filter (lib/> (meta/field-metadata :orders :quantity)
+ (update :dataset-query lib/filter (lib/> (lib.metadata/field (mt/metadata-provider) (mt/id :orders :quantity))
100))
(dissoc :result-metadata))]
(is (= {} (dependencies/errors-from-proposed-edits {:card [card']}
@@ -238,7 +238,7 @@
;; Graph where card 101 -> card 999 (broken card depends on the base card)
graph (graph/in-memory {[:card 101] #{[:card 999]}})
card' (-> mbql-base
- (update :dataset-query lib/filter (lib/> (meta/field-metadata :orders :quantity) 100))
+ (update :dataset-query lib/filter (lib/> (lib.metadata/field (mt/metadata-provider) (mt/id :orders :quantity)) 100))
(dissoc :result-metadata))
errors (dependencies/errors-from-proposed-edits {:card [card']}
:base-provider provider
@@ -256,7 +256,7 @@
graph (graph/in-memory {[:card 101] #{[:dashboard 999]}
[:dashboard 999] #{[:dashboard 999]}})
card' (-> mbql-base
- (update :dataset-query lib/filter (lib/> (meta/field-metadata :orders :quantity) 100))
+ (update :dataset-query lib/filter (lib/> (lib.metadata/field (mt/metadata-provider) (mt/id :orders :quantity)) 100))
(dissoc :result-metadata))
fut (future (dependencies/errors-from-proposed-edits {:card [card']}
:base-provider provider
diff --git a/enterprise/backend/test/metabase_enterprise/dependencies/findings_test.clj b/enterprise/backend/test/metabase_enterprise/dependencies/findings_test.clj
index f6915e9caa5..b04afc82e61 100644
--- a/enterprise/backend/test/metabase_enterprise/dependencies/findings_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/dependencies/findings_test.clj
@@ -357,3 +357,31 @@
(is (false? (t2/select-one-fn :stale :model/AnalysisFinding
:analyzed_entity_type :card :analyzed_entity_id cid))
"phase 2: re-analysis cleared stale again"))))))))
+
+(deftest ^:sequential analyze-batch-shares-one-metadata-provider-test
+ (testing "Every entity in an analysis batch must share one MetadataProvider per database. Reading an entity attaches
+ a provider to its query, so selecting the batch outside the cache gives each entity a private one. Nothing
+ reads through those providers today -- upsert-analysis! builds its own from the database id and passes it
+ explicitly -- so this is a latent trap rather than a live leak: the moment an entity is analyzed through its
+ own query, a batch of 500 retains 500 providers' worth of fetched metadata. upsert-analysis! already throws
+ when no cache is bound, so the cache is meant to cover this work; only the select sat outside it."
+ (backfill-all-entity-analyses!)
+ (let [providers (atom [])
+ native-card (fn [sql] {:database (mt/id) :type :native :native {:query sql}})]
+ (mt/with-premium-features #{:dependencies}
+ (mt/with-temp [:model/Card {card1-id :id} {:dataset_query (native-card "select id from orders")}
+ :model/Card {card2-id :id} {:dataset_query (native-card "select id from products")}]
+ (let [wanted #{card1-id card2-id}
+ upsert-analysis! deps.findings/upsert-analysis!]
+ (with-redefs [deps.findings/upsert-analysis!
+ (fn [instance]
+ (when (wanted (:id instance))
+ (swap! providers conj (:lib/metadata (:dataset_query instance))))
+ (upsert-analysis! instance))]
+ (deps.findings/analyze-batch! :card 500)))
+ (testing "both cards were selected, so the assertion below is meaningful"
+ (is (= 2 (count @providers))))
+ (testing "and they carry the same provider instance"
+ ;; Identity, not equality: providers compare equal when they wrap the same database id, so `=` would be
+ ;; satisfied by two separate caches and would not detect the regression.
+ (is (every? #(identical? (first @providers) %) @providers))))))))
diff --git a/enterprise/backend/test/metabase_enterprise/dependencies/native_validation_test.clj b/enterprise/backend/test/metabase_enterprise/dependencies/native_validation_test.clj
index f7f9386fd8d..d7e5415cc0d 100644
--- a/enterprise/backend/test/metabase_enterprise/dependencies/native_validation_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/dependencies/native_validation_test.clj
@@ -62,25 +62,25 @@
(deftest ^:parallel basic-deps-test
(let [mp (deps.tu/default-metadata-provider)
driver (:engine (lib.metadata/database mp))]
- (is (= #{{:table (meta/id :products)}} ; how is a driver supposed to work out the ID of the table??
+ (is (= #{{:table (mt/id :products)}} ; how is a driver supposed to work out the ID of the table??
(->> (lib.metadata/card mp 4)
:dataset-query
(lib-be/normalize-query mp)
(deps.native-validation/native-query-deps driver))))
- (is (= #{{:table (meta/id :products)}
+ (is (= #{{:table (mt/id :products)}
{:card 1}}
(->> (lib.metadata/card mp 5)
:dataset-query
(lib-be/normalize-query mp)
(deps.native-validation/native-query-deps driver))))
- (is (= #{{:table (meta/id :products)}
+ (is (= #{{:table (mt/id :products)}
{:card 1}
{:snippet 1}}
(->> (lib.metadata/card mp 6)
:dataset-query
(lib-be/normalize-query mp)
(deps.native-validation/native-query-deps driver))))
- (is (= #{{:table (meta/id :products)}
+ (is (= #{{:table (mt/id :products)}
{:card 1}
{:snippet 1}
{:snippet 2}}
@@ -88,8 +88,8 @@
:dataset-query
(lib-be/normalize-query mp)
(deps.native-validation/native-query-deps driver))))
- (is (= #{{:table (meta/id :products)}
- {:table (meta/id :orders)}
+ (is (= #{{:table (mt/id :products)}
+ {:table (mt/id :orders)}
{:card 1}
{:card 2}}
(->> (lib.metadata/card mp 9)
@@ -119,7 +119,7 @@
(is (= (normalize-error-names driver
#{(merge (lib/missing-column-error "bad")
{:source-entity-type :table
- :source-entity-id (meta/id :products)})})
+ :source-entity-id (mt/id :products)})})
(deps.native-validation/validate-native-query
driver
(fake-query mp "select bad from products"))))))))
@@ -142,21 +142,21 @@
(testing "Invalid query - selecting non-existent column from subquery"
(validates? mp driver 11 #{(merge (lib/missing-column-error "CATEGORY")
{:source-entity-type :table
- :source-entity-id (meta/id :people)})})
+ :source-entity-id (mt/id :people)})})
(validates? mp driver 12 #{(merge (lib/missing-column-error "CATEGORY")
{:source-entity-type :table
- :source-entity-id (meta/id :people)})}))
+ :source-entity-id (mt/id :people)})}))
(testing "Nested subqueries"
(validates? mp driver 13 empty?)
(validates? mp driver 14 #{(merge (lib/missing-column-error "CATEGORY")
{:source-entity-type :table
- :source-entity-id (meta/id :people)})}))
+ :source-entity-id (mt/id :people)})}))
(testing "SELECT * from subquery expands to subquery columns"
(validates? mp driver 15 empty?)
(validates? mp driver 16 empty?)
(validates? mp driver 17 #{(merge (lib/missing-column-error "EMAIL")
{:source-entity-type :table
- :source-entity-id (meta/id :people)})})))))
+ :source-entity-id (mt/id :people)})})))))
(deftest ^:parallel validate-card-reference-after-expansion-test
(testing "Validation of queries after card references have been expanded"
@@ -208,12 +208,12 @@
(validates? mp driver 27
#{(merge (lib/missing-column-error "BAD")
{:source-entity-type :table
- :source-entity-id (meta/id :products)})}))
+ :source-entity-id (mt/id :products)})}))
(testing "Mixed table+card, missing column + unknown alias"
(validates? mp driver 28
#{(merge (lib/missing-column-error "BAD")
{:source-entity-type :table
- :source-entity-id (meta/id :products)})
+ :source-entity-id (mt/id :products)})
(lib/missing-table-alias-error "xix")})))))
(defn- check-result-metadata [driver mp query expected]
@@ -234,17 +234,17 @@
(check-result-metadata
driver mp
"select * from orders"
- (add-desired-column-alias (lib.metadata/fields mp (meta/id :orders)))))
+ (add-desired-column-alias (lib.metadata/fields mp (mt/id :orders)))))
(testing "Selecting a table wildcard"
(check-result-metadata
driver mp
"select orders.* from orders"
- (add-desired-column-alias (lib.metadata/fields mp (meta/id :orders)))))
+ (add-desired-column-alias (lib.metadata/fields mp (mt/id :orders)))))
(testing "Selecting a single col"
(check-result-metadata
driver mp
"select total from orders"
- (add-desired-column-alias [(lib.metadata/field mp (meta/id :orders :total))])))
+ (add-desired-column-alias [(lib.metadata/field mp (mt/id :orders :total))])))
(testing "Selecting a nonexistent col"
(check-result-metadata
driver mp
@@ -329,7 +329,7 @@
#{{:type :missing-column
:name "bad"
:source-entity-type :table
- :source-entity-id (meta/id :products)}})
+ :source-entity-id (mt/id :products)}})
(deps.native-validation/validate-native-query
driver
(fake-query mp "select bad from products")))))
@@ -345,7 +345,7 @@
#{{:type :missing-column
:name "bad"
:source-entity-type :table
- :source-entity-id (meta/id :products)}})
+ :source-entity-id (mt/id :products)}})
(deps.native-validation/validate-native-query
driver
(fake-query mp "select products.bad from products join orders on products.id = orders.product_id")))))
@@ -354,7 +354,7 @@
#{{:type :missing-column
:name "bad"
:source-entity-type :table
- :source-entity-id (meta/id :products)}})
+ :source-entity-id (mt/id :products)}})
(deps.native-validation/validate-native-query
driver
(fake-query mp "select p.bad from products p join orders o on p.id = o.product_id")))))
@@ -372,7 +372,7 @@
#{{:type :missing-column
:name "bad"
:source-entity-type :table
- :source-entity-id (meta/id :products)}})
+ :source-entity-id (mt/id :products)}})
(deps.native-validation/validate-native-query
driver
(fake-query mp "WITH cte AS (SELECT id, title FROM products) SELECT bad FROM cte")))))))
diff --git a/enterprise/backend/test/metabase_enterprise/dependencies/task/backfill_test.clj b/enterprise/backend/test/metabase_enterprise/dependencies/task/backfill_test.clj
index 25fa25ea724..46be1cf7ff7 100644
--- a/enterprise/backend/test/metabase_enterprise/dependencies/task/backfill_test.clj
+++ b/enterprise/backend/test/metabase_enterprise/dependencies/task/backfill_test.clj
@@ -10,6 +10,7 @@
[metabase-enterprise.dependencies.task.backfill :as dependencies.backfill]
[metabase-enterprise.dependencies.test-util :as deps.test]
[metabase.events.core :as events]
+ [metabase.premium-features.core :as premium-features]
[metabase.task.core :as task]
[metabase.test :as mt]
[metabase.test.fixtures :as fixtures]
@@ -470,3 +471,137 @@
(assert-processed :card card-id)
(is (false? (deps.dependency-status/has-stale-or-outdated?))
"Expected no pending work once the card has been processed")))))
+
+(deftest ^:sequential batch-size-zero-suppresses-event-triggers-but-stays-warm-test
+ (testing "A non-positive batch size stops the job doing work, but leaves it on its slow periodic schedule so it
+ resumes if the setting ever becomes positive. What it must not do is keep firing the 1-second event-driven
+ trigger, which is what made a disabled job wake roughly once a second on a busy instance -- entity changes
+ fire it, and it never consulted the batch size."
+ (let [scheduled (atom [])
+ scheduled-by (fn [thunk]
+ (reset! scheduled [])
+ (thunk)
+ (count @scheduled))]
+ (with-redefs [task/schedule-task! (fn [& args] (swap! scheduled conj args) nil)]
+ (with-redefs [env/env (assoc env/env :mb-dependency-backfill-batch-size "0")]
+ (testing "the 1-second event-driven trigger is suppressed"
+ (is (zero? (scheduled-by dependencies.backfill/trigger-backfill-job!))))
+ (testing "but task/init! still puts the job on its periodic schedule"
+ (is (= 1 (scheduled-by #(task/init! ::dependencies.backfill/DependencyBackfill)))))
+ (testing "and a run keeps the chain going rather than stopping"
+ (mt/with-premium-features #{:dependencies}
+ (is (= 1 (scheduled-by #(#'dependencies.backfill/run-and-reschedule! nil)))))))
+ (testing "a positive batch size schedules from the event trigger too"
+ (with-redefs [env/env (assoc env/env :mb-dependency-backfill-batch-size "5")]
+ (is (= 1 (scheduled-by dependencies.backfill/trigger-backfill-job!)))))))))
+
+(deftest ^:sequential backfill-batch-shares-one-metadata-provider-test
+ (testing "GHY-4251: every entity in a batch must share one MetadataProvider per database. Reading an entity attaches
+ a provider to its query, so without a batch-scoped cache each entity gets a private one; native dep
+ calculation then fills each with that database's table metadata and the batch retains one copy per entity,
+ which is what exhausted the heap on instances with large warehouses."
+ (backfill-all-existing-entities!)
+ (let [providers (atom [])
+ calculate-deps deps.calculation/calculate-deps
+ native-card (fn [sql] {:database (mt/id) :type :native :native {:query sql}})]
+ (mt/with-premium-features #{}
+ (mt/with-temp [:model/Card {card1-id :id} {:dataset_query (native-card "select id from orders")}
+ :model/Card {card2-id :id} {:dataset_query (native-card "select id from products")}]
+ (mark-stale! :card card1-id)
+ (mark-stale! :card card2-id)
+ (with-redefs [deps.calculation/calculate-deps
+ (fn [entity-type entity]
+ (when-let [mp (:lib/metadata (:dataset_query entity))]
+ (swap! providers conj mp))
+ (calculate-deps entity-type entity))]
+ (backfill-dependencies-single-trigger!))
+ (testing "both cards were analyzed, so the assertion below is meaningful"
+ (is (<= 2 (count @providers))))
+ (testing "and they were analyzed through the same provider instance"
+ ;; Identity, not equality: providers compare equal when they wrap the same database id, so `=` would be
+ ;; satisfied by two separate caches and would not detect the regression.
+ (is (= 1 (count (into #{} (map #(System/identityHashCode %)) @providers))))))))))
+
+(deftest ^:sequential backfill-records-failure-for-fatal-error-test
+ (testing "GHY-4251: a fatal Error must record the entity's failure before propagating. Only Exception was caught,
+ so an OutOfMemoryError escaped without recording anything and the next run selected the identical batch --
+ a crash loop that never made progress. Recording first means the entity backs off and eventually goes
+ terminal, so the batch drains even if one entity always kills the process."
+ (backfill-all-existing-entities!)
+ (mt/with-premium-features #{}
+ (mt/with-temp [:model/Card {card-id :id} {:dataset_query (mt/mbql-query orders)}]
+ (mark-stale! :card card-id)
+ (with-redefs [deps.calculation/calculate-deps (fn [& _] (throw (Error. "simulated fatal error")))]
+ (testing "the Error propagates instead of being swallowed, failing the job"
+ (is (thrown-with-msg? Error #"simulated fatal error"
+ (backfill-dependencies-single-trigger!)))))
+ (testing "and the failure was recorded first, so the next run backs off instead of replaying the batch"
+ (let [{:keys [fail_count next_retry_at terminal]}
+ (t2/select-one :model/DependencyStatus :entity_type :card :entity_id card-id)]
+ (is (= 1 fail_count))
+ (is (some? next_retry_at))
+ (is (false? terminal))))))))
+
+(deftest ^:sequential pending-retries-licence-states-test
+ (testing "A pending retry keeps the backfill job scheduled, but only when the licence permits acting on it. A retry
+ marker is cleared by processing the entity -- on success via upsert-status!, or by going terminal past
+ max-retries -- and both are gated on the feature, so without it the job could never resolve the condition
+ keeping it awake and rescheduled hourly forever.
+
+ The licence is resolved with canonically-has-feature? rather than has-feature?, which collapses 'no licence'
+ and 'could not check' into the same false. Both inputs to the job's reschedule decision consult the licence,
+ so a transient token failure would take the job down permanently -- nothing re-fires when the check
+ recovers, because the token never changed."
+ (backfill-all-existing-entities!)
+ (mt/with-temp [:model/Card {card-id :id} {:dataset_query (mt/mbql-query orders)}]
+ (mark-stale! :card card-id)
+ (backfill-dependencies-single-trigger!)
+ (deps.dependency-status/record-failure! :card card-id 5 60)
+ (is (t2/exists? :model/DependencyStatus
+ :entity_type :card :entity_id card-id
+ :terminal false :next_retry_at [:not= nil])
+ "test setup: the card must be in retry backoff")
+ (let [actionable? (fn [licence]
+ (with-redefs [premium-features/canonically-has-feature? (constantly licence)]
+ (#'dependencies.backfill/has-pending-retries?)))]
+ (testing "licensed: the pending retry keeps the job scheduled"
+ (is (true? (actionable? true))))
+ (testing "indeterminate: treated as actionable, so a blip cannot end the chain"
+ (is (true? (actionable? nil))))
+ (testing "definitively unlicensed: not actionable"
+ (is (false? (actionable? false))))))))
+
+(deftest ^:sequential backfill-records-failure-for-never-processed-entity-test
+ (testing "An entity with no dependency_status row yet must still get a failure recorded when it fails. Such entities
+ are explicitly selected for processing (instances-for-dependency-calculation matches a null status row), so
+ on a first backfill every entity is in this state -- exactly the population most likely to fail on a large
+ instance. record-failure! only updated an existing row, so nothing was recorded and the next run selected
+ the identical batch: the crash loop, unbroken for the entities most likely to cause it."
+ (backfill-all-existing-entities!)
+ (mt/with-premium-features #{}
+ (mt/with-temp [:model/Card {card-id :id} {:dataset_query (mt/mbql-query orders)}]
+ (is (not (t2/exists? :model/DependencyStatus :entity_type :card :entity_id card-id))
+ "test setup: the card must have no status row, which is what makes it eligible")
+ (with-redefs [deps.calculation/calculate-deps (fn [& _] (throw (ex-info "boom" {})))]
+ (backfill-dependencies-single-trigger!))
+ (testing "the failure is recorded, so the entity backs off instead of being reselected unchanged"
+ (let [{:keys [fail_count next_retry_at]}
+ (t2/select-one :model/DependencyStatus :entity_type :card :entity_id card-id)]
+ (is (= 1 fail_count))
+ (is (some? next_retry_at))))))))
+
+(deftest ^:sequential fatal-error-still-reschedules-test
+ (testing "A failure must not leave the job unscheduled. The job is one-shot self-rescheduling with no cron
+ backstop, so an Error propagating out of the batch skipped schedule-run! entirely and the chain ended
+ until a content-change event or a restart. A real OutOfMemoryError usually takes the process with it and
+ task/init! recovers on boot, but survivable Errors -- StackOverflowError from deeply nested SQL, an
+ AssertionError, a LinkageError -- leave a live process with a dead job."
+ (let [scheduled (atom [])]
+ (with-redefs [task/schedule-task! (fn [& args] (swap! scheduled conj args) nil)
+ dependencies.backfill/backfill-dependencies!
+ (fn [& _] (throw (Error. "simulated fatal error")))]
+ (testing "the Error still propagates"
+ (is (thrown-with-msg? Error #"simulated fatal error"
+ (#'dependencies.backfill/run-and-reschedule! nil))))
+ (testing "and the next run was scheduled anyway"
+ (is (= 1 (count @scheduled))))))))
diff --git a/enterprise/backend/test/metabase_enterprise/dependencies/task/entity_check_test.clj b/enterprise/backend/test/metabase_enterprise/dependencies/task/entity_check_test.clj
new file mode 100644
index 00000000000..65ffa1b7e91
--- /dev/null
+++ b/enterprise/backend/test/metabase_enterprise/dependencies/task/entity_check_test.clj
@@ -0,0 +1,78 @@
+(ns metabase-enterprise.dependencies.task.entity-check-test
+ (:require
+ [clojure.test :refer [deftest is testing]]
+ [environ.core :as env]
+ [metabase-enterprise.dependencies.task.entity-check :as dependencies.entity-check]
+ [metabase.events.core :as events]
+ [metabase.premium-features.core :as premium-features]
+ [metabase.task.core :as task]
+ [metabase.test :as mt])
+ (:import
+ (org.quartz JobDetail)))
+
+(set! *warn-on-reflection* true)
+
+(deftest ^:sequential batch-size-zero-suppresses-event-triggers-but-stays-warm-test
+ (testing "A non-positive batch size stops the job doing work, but leaves it on its slow periodic schedule so it
+ resumes if the setting ever becomes positive. What it must not do is keep firing the 1-second event-driven
+ trigger: entity changes fire it, and it never consulted the batch size, so a disabled job woke roughly once
+ a second on a busy instance."
+ (let [scheduled (atom [])
+ scheduled-by (fn [thunk]
+ (reset! scheduled [])
+ (thunk)
+ (count @scheduled))]
+ (with-redefs [task/schedule-task! (fn [& args] (swap! scheduled conj args) nil)]
+ (with-redefs [env/env (assoc env/env :mb-dependency-entity-check-batch-size "0")]
+ (testing "the 1-second event-driven trigger is suppressed"
+ (is (zero? (scheduled-by dependencies.entity-check/trigger-entity-check-job!))))
+ (testing "but task/init! still puts the job on its periodic schedule"
+ (is (= 1 (scheduled-by #(task/init! ::dependencies.entity-check/DependencyEntityCheck)))))
+ (testing "and a run keeps the periodic chain going"
+ (with-redefs [premium-features/canonically-has-feature? (constantly true)]
+ (is (= 1 (scheduled-by #(#'dependencies.entity-check/reschedule-after-run! nil)))))))
+ (testing "a positive batch size schedules from the event trigger too"
+ (with-redefs [env/env (assoc env/env :mb-dependency-entity-check-batch-size "5")]
+ (is (= 1 (scheduled-by dependencies.entity-check/trigger-entity-check-job!)))))))))
+
+(deftest ^:sequential post-run-reschedule-licence-states-test
+ (testing "The entity check job is a periodic checker with no terminal state, so it always queues another run. That
+ is right while licensed, but check-entities! is gated on :dependencies, so without the feature the job
+ rescheduled itself every 30-90 minutes forever to do nothing at all.
+
+ Scheduling resolves the licence with canonically-has-feature?, not has-feature?, so it can distinguish
+ 'definitively unlicensed' from 'could not tell'. has-feature? collapses both to false, and since nothing
+ re-fires when a failed token check later succeeds, reading a blip as unlicensed would end the chain for
+ good. Only a definitive false stops it."
+ (let [scheduled (atom [])
+ scheduled-by (fn [licence]
+ (reset! scheduled [])
+ (with-redefs [premium-features/canonically-has-feature? (constantly licence)]
+ (#'dependencies.entity-check/reschedule-after-run! nil))
+ (count @scheduled))]
+ (with-redefs [task/schedule-task! (fn [& args] (swap! scheduled conj args) nil)]
+ (testing "licensed: keeps itself scheduled"
+ (is (= 1 (scheduled-by true))))
+ (testing "indeterminate: keeps the chain alive rather than ending it on a transient failure"
+ (is (= 1 (scheduled-by nil))))
+ (testing "definitively unlicensed: stops"
+ (is (zero? (scheduled-by false))))))))
+
+(def ^:private entity-check-job-name "metabase.dependencies.task.entity-check.job")
+
+(defn- scheduled-job-names
+ "Job names from captured [[task/schedule-task!]] calls. Needed because several jobs listen for the same events, so a
+ bare call count cannot tell us which job got scheduled."
+ [calls]
+ (into #{} (map (fn [args] (.getName (.getKey ^JobDetail (nth args 1))))) calls))
+
+(deftest ^:sequential token-event-restarts-the-job-test
+ (testing "Setting a premium token must restart the entity check job. The backfill job derives
+ :event/set-premium-embedding-token for this; entity check had no event wiring at all, so its only restarts
+ came from content-change handlers. Enabling the feature on an idle instance left the periodic checker dead
+ until the next process restart."
+ (let [scheduled (atom [])]
+ (with-redefs [task/schedule-task! (fn [& args] (swap! scheduled conj args) nil)]
+ (mt/with-premium-features #{:dependencies}
+ (events/publish-event! :event/set-premium-embedding-token {})
+ (is (contains? (scheduled-job-names @scheduled) entity-check-job-name)))))))
diff --git a/enterprise/backend/test/metabase_enterprise/dependencies/test_util.clj b/enterprise/backend/test/metabase_enterprise/dependencies/test_util.clj
index 42950daa0b1..b122e09b05c 100644
--- a/enterprise/backend/test/metabase_enterprise/dependencies/test_util.clj
+++ b/enterprise/backend/test/metabase_enterprise/dependencies/test_util.clj
@@ -5,7 +5,6 @@
[metabase.lib.convert :as lib.convert]
[metabase.lib.core :as lib]
[metabase.lib.metadata :as lib.metadata]
- [metabase.lib.test-metadata :as meta]
[metabase.lib.test-util.metadata-providers.mock :as providers.mock]
[metabase.test :as mt]))
@@ -43,9 +42,14 @@
:template-tags template-tags
:lib/type :metadata/native-query-snippet})
-(defn mock-metadata-provider [{:keys [cards snippets]}]
+(defn mock-metadata-provider
+ "Cards and snippets from an in-memory mock, Tables from the application database.
+
+ The Tables have to be real rows: resolving a table name parsed out of native SQL is a lookup against the appdb, so a
+ purely in-memory base would have no rows to find."
+ [{:keys [cards snippets]}]
(lib/composed-metadata-provider
- meta/metadata-provider
+ (mt/metadata-provider)
(providers.mock/mock-metadata-provider
{:cards cards
:native-query-snippets snippets})))
@@ -72,10 +76,10 @@
initial-mock-mp (mock-metadata-provider {:snippets snippets})
initial-card-a (mock-card initial-mock-mp
{:id 1
- :query (lib/query initial-mock-mp (meta/table-metadata :products))})
+ :query (lib/query initial-mock-mp (lib.metadata/table initial-mock-mp (mt/id :products)))})
initial-card-b (mock-card initial-mock-mp
{:id 2
- :query (lib/query initial-mock-mp (meta/table-metadata :orders))})]
+ :query (lib/query initial-mock-mp (lib.metadata/table initial-mock-mp (mt/id :orders)))})]
(mock-metadata-provider
{:cards (into [initial-card-a
initial-card-b]
@@ -160,7 +164,7 @@
:query "SELECT CATEGORY FROM {{#31}}"}
;; Card 33: MBQL card with subset of products columns (simulates MBQL intermediary)
{:id 33
- :query (lib/query initial-mock-mp (meta/table-metadata :products))
+ :query (lib/query initial-mock-mp (lib.metadata/table initial-mock-mp (mt/id :products)))
:details {:result-metadata
(vec (filter #(#{"ID" "TITLE"} (:name %))
(:result-metadata initial-card-a)))}}
diff --git a/src/metabase/sql_tools/common.clj b/src/metabase/sql_tools/common.clj
index 67dbd1ca1a4..93969eb03d0 100644
--- a/src/metabase/sql_tools/common.clj
+++ b/src/metabase/sql_tools/common.clj
@@ -7,8 +7,10 @@
[metabase.lib.core :as lib]
[metabase.lib.metadata :as lib.metadata]
[metabase.sql-tools.interface :as sql-tools]
+ [metabase.util :as u]
[metabase.util.humanization :as u.humanization]
- [metabase.util.malli :as mu]))
+ [metabase.util.malli :as mu]
+ [toucan2.core :as t2]))
(defn normalize-name
"Normalize a name by per driver rules."
@@ -21,6 +23,35 @@
{:table (normalize-name driver table)
:schema (some->> schema (normalize-name driver))})
+(mu/defn table-ids-by-name :- [:set pos-int?]
+ "Ids of the active, non-hidden Tables in `database-id` whose name case-insensitively matches one of `table-names`.
+
+ Resolving a name parsed out of native SQL is a lookup, so it goes straight to the appdb; the metadata for the ids is
+ then fetched through the `MetadataProvider` as usual. Case-insensitive because the spelling sync recorded need not
+ match the spelling in a query: `normalize-name` lower-cases while some warehouses (Snowflake) report upper-case.
+
+ This is a prefilter, not the decision — [[find-table-or-transform]] still matches precisely — so it must return a
+ superset of what that accepts. That holds while the appdb's `lower()` agrees with `u/lower-case-en` and a driver's
+ `normalize-unquoted-name` is a pure case fold; both have tests."
+ [database-id :- pos-int?
+ table-names :- [:sequential :string]]
+ (if-let [names (not-empty (into #{} (map u/lower-case-en) table-names))]
+ ;; `set` because `select-pks-set` answers `nil`, not `#{}`, when nothing matches — which is the common case of a
+ ;; query naming a table that does not exist.
+ (set (t2/select-pks-set :model/Table
+ {:where [:and
+ [:= :db_id database-id]
+ ;; `lower()` cannot use an index on the name column, but it still beats fetching every
+ ;; row for the Database.
+ [:in [:lower :name] names]
+ ;; Mirrors the Table filter the MetadataProvider applies to an unfiltered fetch; an
+ ;; `:id` lookup does not apply it, so it has to happen here.
+ [:= :active true]
+ [:or
+ [:= :visibility_type nil]
+ [:not-in :visibility_type [:inline ["hidden" "technical" "cruft"]]]]]}))
+ #{}))
+
(defn find-table-or-transform
"Given a table and schema that has been parsed out of a native query, finds either a matching table or a matching transform.
It will return either {:table table-id} or {:transform transform-id}, or nil if neither is found."
diff --git a/src/metabase/sql_tools/macaw/core.clj b/src/metabase/sql_tools/macaw/core.clj
index e586270acd5..85c784173d8 100644
--- a/src/metabase/sql_tools/macaw/core.clj
+++ b/src/metabase/sql_tools/macaw/core.clj
@@ -96,18 +96,20 @@
(mu/defn- referenced-tables
[driver :- :keyword
query :- :metabase.lib.schema/native-only-query]
- (let [db-tables (lib.metadata/tables query)
+ (let [specs (-> query
+ lib/raw-native-query
+ (parsed-query driver)
+ (macaw/query->components {:strip-contexts? true})
+ :tables
+ (->> (map :component))
+ (->> (map split-compound-table-spec))
+ (->> (mapv #(sql-tools.common/normalize-table-spec driver %))))
+ table-ids (sql-tools.common/table-ids-by-name (lib/database-id query) (keep :table specs))
+ db-tables (lib.metadata/bulk-metadata query :metadata/table table-ids)
db-transforms (lib.metadata/transforms query)]
- (-> query
- lib/raw-native-query
- (parsed-query driver)
- (macaw/query->components {:strip-contexts? true})
- :tables
- (->> (map :component))
- (->> (map split-compound-table-spec))
- (->> (into #{}
- (keep #(->> (sql-tools.common/normalize-table-spec driver %)
- (sql-tools.common/find-table-or-transform driver db-tables db-transforms))))))))
+ (into #{}
+ (keep #(sql-tools.common/find-table-or-transform driver db-tables db-transforms %))
+ specs)))
(defmethod sql-tools/referenced-tables-impl :macaw
[_parser driver query]
diff --git a/src/metabase/sql_tools/sqlglot/core.clj b/src/metabase/sql_tools/sqlglot/core.clj
index 945507111a3..2ffe91bb9d1 100644
--- a/src/metabase/sql_tools/sqlglot/core.clj
+++ b/src/metabase/sql_tools/sqlglot/core.clj
@@ -51,19 +51,20 @@
(defn- referenced-tables
[driver query]
(try
- (let [db-tables (lib.metadata/tables query)
- db-transforms (lib.metadata/transforms query)
- sql (lib/raw-native-query query)
+ (let [sql (lib/raw-native-query query)
default-schema (sql.normalize/default-schema driver)
- query-tables (sql-parsing/referenced-tables (driver->dialect driver) sql)]
+ query-tables (sql-parsing/referenced-tables (driver->dialect driver) sql)
+ specs (map (fn [[_catalog table-schema table]]
+ (sql-tools.common/normalize-table-spec
+ driver {:table table
+ :schema (or table-schema default-schema)}))
+ query-tables)
+ table-ids (sql-tools.common/table-ids-by-name (lib/database-id query) (keep :table specs))
+ db-tables (lib.metadata/bulk-metadata query :metadata/table table-ids)
+ db-transforms (lib.metadata/transforms query)]
(into #{}
- (keep (fn [[_catalog table-schema table]]
- (sql-tools.common/find-table-or-transform
- driver db-tables db-transforms
- (sql-tools.common/normalize-table-spec
- driver {:table table
- :schema (or table-schema default-schema)}))))
- query-tables))
+ (keep #(sql-tools.common/find-table-or-transform driver db-tables db-transforms %))
+ specs))
(catch Exception e
;; Return empty sequence on parse error to follow the Macaw implementation behavior.
(if (sql-parsing/parse-error? e)
diff --git a/test/metabase/driver/sql/normalize_test.clj b/test/metabase/driver/sql/normalize_test.clj
new file mode 100644
index 00000000000..5b5b27e9456
--- /dev/null
+++ b/test/metabase/driver/sql/normalize_test.clj
@@ -0,0 +1,33 @@
+(ns metabase.driver.sql.normalize-test
+ (:require
+ [clojure.test :refer [deftest is testing]]
+ ;; loaded for its `normalize-unquoted-name` implementation, which is one of the two this asserts over
+ [metabase.driver.h2]
+ [metabase.driver.sql.normalize :as sql.normalize]
+ [metabase.util :as u]))
+
+(def ^:private sample-names
+ ["orders" "PRODUCTS" "MixedCase" "École" "snake_case_1" "x"])
+
+(deftest normalize-unquoted-name-is-a-pure-case-fold-test
+ (testing "Every implementation must only change a name's case.
+
+ `metabase.lib-be.metadata.jvm/tables-by-name` narrows a table lookup with SQL `lower(name)` and then lets
+ `metabase.sql-tools.common/find-table-or-transform` decide using this multimethod. That is only sound while
+ the narrowed set is a superset of what the precise match accepts, which holds exactly when normalization is
+ a pure case fold: anything else -- trimming, stripping characters, substituting them -- makes the prefilter
+ drop rows that would have matched, and a dependency silently disappears.
+
+ Each implementation is invoked directly rather than through driver dispatch, so this needs no driver to be
+ registered or initialised and covers every impl loaded in the run."
+ (let [impls (methods sql.normalize/normalize-unquoted-name)]
+ (testing "the implementations under test were actually loaded, so this cannot pass by covering nothing"
+ (is (<= 2 (count impls)))
+ (is (= #{:sql :h2} (set (keys impls)))
+ "a new implementation appeared: confirm it is a pure case fold, then extend this assertion"))
+ (doseq [[dispatch-value impl] impls
+ name* sample-names]
+ (testing (format "%s with %s" dispatch-value (pr-str name*))
+ (is (= (u/lower-case-en name*)
+ (u/lower-case-en (impl dispatch-value name*)))
+ "normalization changed more than the name's case, so tables-by-name will silently drop matches"))))))
diff --git a/test/metabase/sql_tools/common_test.clj b/test/metabase/sql_tools/common_test.clj
new file mode 100644
index 00000000000..b4e9d980ef7
--- /dev/null
+++ b/test/metabase/sql_tools/common_test.clj
@@ -0,0 +1,50 @@
+(ns metabase.sql-tools.common-test
+ (:require
+ [clojure.test :refer [deftest is testing]]
+ [metabase.sql-tools.common :as sql-tools.common]
+ [metabase.test :as mt]
+ [metabase.util :as u]
+ [toucan2.core :as t2]))
+
+(deftest table-ids-by-name-case-folding-test
+ (testing "table-ids-by-name must fold case the same way the application database's lower() does.
+
+ It is a prefilter, not the decision: it narrows with SQL `lower(name)` against names lowered by
+ u/lower-case-en, and find-table-or-transform then matches precisely using the driver's normalize-name. That
+ is only correct while the prefilter returns a superset of what the precise match accepts, so if the appdb's
+ lower() and Java's disagree about a name the prefilter drops a row that would have matched and the
+ dependency silently disappears. This therefore has to run on every supported appdb -- H2 in the backend
+ workflow, Postgres and MariaDB in app-db.yml -- which it does simply by existing.
+
+ Scope: ASCII case variants (the real case, since warehouses like Snowflake report upper-case while
+ normalize-name lower-cases) and accented Latin. Deliberately not covered: locale-dependent folds such as
+ U+0130 LATIN CAPITAL LETTER I WITH DOT ABOVE, where lower() legitimately differs between engines and
+ locales. That stays a documented limit of the prefilter rather than an assertion."
+ (mt/with-temp [:model/Database {db-id :id} {:name "case-folding-probe" :engine :h2 :details {}}]
+ (let [names ["orders" "PRODUCTS" "MixedCase" "École"]
+ name->id (into {}
+ (for [n names]
+ [n (t2/insert-returning-pk! :model/Table
+ {:db_id db-id
+ :name n
+ :display_name n
+ :schema "public"
+ :active true
+ :visibility_type nil})]))]
+ (doseq [stored names
+ spelling [stored (u/lower-case-en stored) (u/upper-case-en stored)]]
+ (testing (format "stored %s, queried as %s" (pr-str stored) (pr-str spelling))
+ (is (contains? (sql-tools.common/table-ids-by-name db-id [spelling])
+ (name->id stored))
+ "the appdb's lower() disagrees with u/lower-case-en, so the prefilter drops a matching row")))
+ (testing "inactive and hidden Tables are excluded, matching what an unfiltered provider fetch returns"
+ (t2/insert! :model/Table
+ [{:db_id db-id :name "gone" :display_name "gone"
+ :schema "public" :active false :visibility_type nil}
+ {:db_id db-id :name "shy" :display_name "shy"
+ :schema "public" :active true :visibility_type "hidden"}])
+ (is (= #{} (sql-tools.common/table-ids-by-name db-id ["gone" "shy"]))))
+ (testing "a name that matches nothing returns empty rather than everything"
+ (is (= #{} (sql-tools.common/table-ids-by-name db-id ["no_such_table"]))))
+ (testing "no names requested returns empty rather than the whole catalog"
+ (is (= #{} (sql-tools.common/table-ids-by-name db-id []))))))))
diff --git a/test/metabase/sql_tools/core_test.clj b/test/metabase/sql_tools/core_test.clj
index d780c9e15e7..19393a99457 100644
--- a/test/metabase/sql_tools/core_test.clj
+++ b/test/metabase/sql_tools/core_test.clj
@@ -61,6 +61,25 @@
{:table (mt/id :products)}}
(sql-tools/referenced-tables driver/*driver* query))))))))
+(deftest referenced-tables-fetches-only-named-tables-test
+ (testing "GHY-4251: referenced-tables looks up only the Tables the SQL names, never the Database's whole catalog.
+ Fetching the catalog per entity made dependency analysis scale with warehouse size instead of query size,
+ OOM-killing instances with ~20k synced tables."
+ (sql-tools.tu/test-parser-backends
+ (mt/test-driver :h2
+ (let [catalog-fetches (atom 0)
+ all-tables lib.metadata/tables]
+ (with-redefs [lib.metadata/tables (fn [mp] (swap! catalog-fetches inc) (all-tables mp))]
+ (testing "the referenced table still resolves"
+ ;; H2 stores table names upper-cased while the query spells them lower-case, so this also covers the
+ ;; case-folding that makes an exact name match unusable (the same mismatch Snowflake has).
+ (is (= #{{:table (mt/id :orders)}}
+ (sql-tools/referenced-tables driver/*driver*
+ (lib/native-query (mt/metadata-provider)
+ "select id from orders")))))
+ (testing "and it did so without fetching the catalog"
+ (is (zero? @catalog-fetches)))))))))
+
;;; ------------------------------------------------ replace-names -------------------------------------------------
(deftest ^:parallel replace-names-table-test