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
Zombie transform reaper (#75194)
Nicola Momettoc6a4c1bb0e61
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.ednindex 5e317d954c7..48694371c6a 100644--- a/.clj-kondo/config/modules/config.edn+++ b/.clj-kondo/config/modules/config.edn@@ -1895,6 +1895,14 @@:model/Segment:model/Transform}}+ run-tracking+ {:team "Gadget"+ :api #{metabase.run-tracking.core}+ :uses #{analytics-interface+ app-db+ task+ util}}+sample-data{:team "UX West":api #{metabase.sample-data.core@@ -2220,13 +2228,13 @@metabase.task-history.coremetabase.task-history.init}:uses #{api- app-dbconfigmodelspermissionspremium-featuresquery-processorrequest+ run-trackingtasktracingutil}@@ -2325,6 +2333,7 @@query-processorremote-syncrevisions+ run-trackingsearchsettingstaskdiff --git a/enterprise/backend/src/metabase_enterprise/transforms_python/execute.clj b/enterprise/backend/src/metabase_enterprise/transforms_python/execute.cljindex ec655a40c9a..e31f563ec2f 100644--- a/enterprise/backend/src/metabase_enterprise/transforms_python/execute.clj+++ b/enterprise/backend/src/metabase_enterprise/transforms_python/execute.clj@@ -97,7 +97,7 @@"Execute a Python transform by calling the python runner.Blocks until the transform returns."- [transform {:keys [run-method start-promise user-id]}]+ [transform {:keys [run-method on-start user-id]}](try(let [message-log (base/empty-message-log){:keys [target owner_user_id creator_id] transform-id :id} transform@@ -106,7 +106,7 @@user-id(or owner_user_id creator_id)){run-id :id} (transforms.u/try-start-unless-already-running transform-id run-method run-user-id)]- (some-> start-promise (deliver [:started run-id]))+ (when on-start (on-start run-id))(with-open [_ (open-python-message-update-future! run-id message-log)](driver.conn/with-write-connection(let [target-type (keyword (:type target))]diff --git a/enterprise/backend/test/metabase_enterprise/transforms_python/job_test.clj b/enterprise/backend/test/metabase_enterprise/transforms_python/job_test.cljindex d090709a415..087693c1866 100644--- a/enterprise/backend/test/metabase_enterprise/transforms_python/job_test.clj+++ b/enterprise/backend/test/metabase_enterprise/transforms_python/job_test.clj@@ -62,7 +62,7 @@(mt/with-dynamic-fn-redefs [log/log* (fn [_ level _ message](swap! logged-messages conj {:level level :message message}))transform-run/running-run-for-transform-id (constantly nil)]- (#'jobs/run-transform! run-id :scheduled nil python-transform)+ (#'jobs/run-transform! run-id :scheduled nil (promise) python-transform)(is (= 1 (count @logged-messages))"Should log exactly one warning")(is (= :warn (:level (first @logged-messages)))diff --git a/mage/test/mage/modules_test.clj b/mage/test/mage/modules_test.cljindex cf96f044bb4..9eb18658006 100644--- a/mage/test/mage/modules_test.clj+++ b/mage/test/mage/modules_test.clj@@ -350,7 +350,8 @@;; 2026-03-10 Bumped to 40 for lib-metric + metrics (Metrics Explorer #68961);; Added premium-features to driver-affecting-overrides (#69561);; 2026-04-07 Bumped to 41 due to agent-lib addition (Metabot MBQL improvements #71524)- max-allowed-count 41]+ ;; 2026-06-04 Bumped to 42 due to run-tracking addition (Zombie transform reaper #75194)+ max-allowed-count 42](is (<= (count modules-triggering-drivers) max-allowed-count)(format "Too many modules trigger driver tests! Expected <= %d, got %d.Modules triggering driver tests: %sdiff --git a/resources/migrations/063/20260603_transform_run_heartbeat.yaml b/resources/migrations/063/20260603_transform_run_heartbeat.yamlnew file mode 100644index 00000000000..6899a51763e--- /dev/null+++ b/resources/migrations/063/20260603_transform_run_heartbeat.yaml@@ -0,0 +1,101 @@+## Add heartbeat tracking to transform_run and transform_job_run for dead-process orphan detection++databaseChangeLog:++ - changeSet:+ id: v63.2026-06-03T00:00:00+ author: bronsa+ comment: Add last_heartbeat column to transform_run for heartbeat-based orphan detection+ preConditions:+ - onFail: MARK_RAN+ - not:+ - columnExists:+ tableName: transform_run+ columnName: last_heartbeat+ changes:+ - addColumn:+ tableName: transform_run+ columns:+ - column:+ name: last_heartbeat+ type: ${timestamp_type}+ defaultValueComputed: current_timestamp+ remarks: Heartbeat timestamp stamped periodically while the run executes; a stale value means the owning process died+ constraints:+ nullable: false+ rollback:+ - dropColumn:+ tableName: transform_run+ columnName: last_heartbeat++ - changeSet:+ id: v63.2026-06-12T00:00:00+ author: bronsa+ comment: Add last_heartbeat column to transform_job_run for heartbeat-based orphan detection+ preConditions:+ - onFail: MARK_RAN+ - not:+ - columnExists:+ tableName: transform_job_run+ columnName: last_heartbeat+ changes:+ - addColumn:+ tableName: transform_job_run+ columns:+ - column:+ name: last_heartbeat+ type: ${timestamp_type}+ defaultValueComputed: current_timestamp+ remarks: Heartbeat timestamp stamped periodically while the run executes; a stale value means the owning process died+ constraints:+ nullable: false+ rollback:+ - dropColumn:+ tableName: transform_job_run+ columnName: last_heartbeat++ - changeSet:+ id: v63.2026-06-12T00:00:01+ author: bronsa+ comment: Index transform_job_run on (is_active, last_heartbeat) so the every-minute reaper scan is O(active rows)+ preConditions:+ - onFail: MARK_RAN+ - not:+ - indexExists:+ tableName: transform_job_run+ indexName: idx_transform_job_run_active_runs+ changes:+ - createIndex:+ tableName: transform_job_run+ indexName: idx_transform_job_run_active_runs+ columns:+ - column:+ name: is_active+ - column:+ name: last_heartbeat+ rollback:+ - dropIndex:+ tableName: transform_job_run+ indexName: idx_transform_job_run_active_runs++ - changeSet:+ id: v63.2026-06-12T00:00:02+ author: bronsa+ comment: Index task_run on status so the task-run reaper's locking scan only touches started rows+ preConditions:+ - onFail: MARK_RAN+ - not:+ - indexExists:+ tableName: task_run+ indexName: idx_task_run_status+ changes:+ - createIndex:+ tableName: task_run+ indexName: idx_task_run_status+ columns:+ - column:+ name: status+ rollback:+ - dropIndex:+ tableName: task_run+ indexName: idx_task_run_statusdiff --git a/src/metabase/run_tracking/core.clj b/src/metabase/run_tracking/core.cljnew file mode 100644index 00000000000..6c46c5650fc--- /dev/null+++ b/src/metabase/run_tracking/core.clj@@ -0,0 +1,22 @@+(ns metabase.run-tracking.core+ "Shared primitives for run-tracking heartbeats and orphan reaping."+ (:require+ [metabase.run-tracking.ops]+ [metabase.run-tracking.task]+ [potemkin :as p]))++(comment metabase.run-tracking.ops/keep-me+ metabase.run-tracking.task/keep-me)++(p/import-vars+ [metabase.run-tracking.ops+ cutoff+ detection-latency-ms+ heartbeat-and-reconcile!+ heartbeat-ids!+ reap-orphaned!+ reap-rows!+ unit->ms]+ [metabase.run-tracking.task+ schedule-reaper!+ start-heartbeat!])diff --git a/src/metabase/run_tracking/ops.clj b/src/metabase/run_tracking/ops.cljnew file mode 100644index 00000000000..7a285b602c1--- /dev/null+++ b/src/metabase/run_tracking/ops.clj@@ -0,0 +1,89 @@+(ns metabase.run-tracking.ops+ "Data operations for run-tracking heartbeats and orphan reaping."+ (:require+ [metabase.analytics-interface.core :as analytics]+ [metabase.app-db.core :as mdb]+ [metabase.util.honey-sql-2 :as h2x]+ [toucan2.core :as t2])+ (:import+ (java.time OffsetDateTime)))++(set! *warn-on-reflection* true)++(defn cutoff+ "Honeysql form for `(now - age unit)` in the app-db dialect."+ [age unit]+ (h2x/add-interval-honeysql-form (mdb/db-type) :%now (- age) unit))++(defn unit->ms+ "Convert `age` of `unit` (`:second`, `:minute`, or `:hour`) to milliseconds."+ [age unit]+ (* age (case unit+ :second 1000+ :minute 60000+ :hour 3600000)))++(defn detection-latency-ms+ "Milliseconds elapsed past `(reference-ts + timeout-ms)` at `detected-at-ms` (epoch millis).+ Clamped at zero."+ [^OffsetDateTime reference-ts timeout-ms detected-at-ms]+ (max 0 (- detected-at-ms (inst-ms (.toInstant reference-ts)) timeout-ms)))++(defn heartbeat-ids!+ "Stamp `heartbeat-column = now` on the `active` rows of `model` in `ids`; no-op on empty `ids`.+ `active` is a HoneySQL predicate, e.g. `[:= :is_active true]`."+ [model active heartbeat-column ids]+ (when (seq ids)+ (t2/query {:update (t2/table-name model)+ :set {heartbeat-column :%now}+ :where [:and active [:in :id ids]]})))++(defn heartbeat-and-reconcile!+ "Per-node tick for the runs this process owns: call `(heartbeat! ids)`, then `(on-gone id)` for+ each id whose row no longer matches `active` (a HoneySQL predicate, e.g. `[:= :is_active true]`).++ `on-gone` runs on the shared heartbeat thread and must not block: a slow callback delays+ heartbeats for every run on this node, leaving them to be reaped as stale."+ [{:keys [model active ids heartbeat! on-gone]}]+ (when-let [ids (seq ids)]+ (heartbeat! ids)+ (let [active-ids (t2/select-fn-set :id model {:where [:and [:in :id ids] active]})]+ (doseq [id ids+ :when (not (contains? active-ids id))]+ (on-gone id)))))++(defn reap-rows!+ "Atomically move the `active` rows of `model` matching the `stale` honeysql predicate into+ `terminal`, returning the pre-update rows. `SELECT … FOR UPDATE` + `UPDATE` in one transaction,+ so the returned rows are exactly those transitioned.+ `active` is a HoneySQL predicate, e.g. `[:= :is_active true]`."+ [{:keys [model active stale terminal]}]+ (t2/with-transaction [_conn]+ (when-let [rows (not-empty (t2/select model {:where [:and active stale] :for :update}))]+ (t2/query {:update (t2/table-name model)+ :set terminal+ :where [:and active [:in :id (mapv :id rows)]]})+ rows)))++(defn reap-orphaned!+ "Like [[reap-rows!]] — reap the `active` rows of `model` matching the `stale` predicate into+ `terminal` — but also emit timeout analytics. Returns the reaped rows.++ `:metrics` (optional) holds the analytics inputs:+ - `:total-metric` (+ `:tags`) — counter incremented by the number of rows reaped.+ - `:latency-metric` (+ `:latency-column`, `:timeout-ms`) — per row, observes how long past+ `(row's :latency-column + :timeout-ms)` the reap was detected (see [[detection-latency-ms]])."+ [{:keys [model active terminal stale]+ {:keys [total-metric latency-metric tags latency-column timeout-ms]} :metrics}]+ (let [detected-at-ms (System/currentTimeMillis)+ reaped (reap-rows! {:model model :active active :terminal terminal :stale stale})]+ (when (seq reaped)+ (when total-metric+ (analytics/inc! total-metric tags (count reaped)))+ (when latency-metric+ (doseq [row reaped+ :let [ts (get row latency-column)]+ :when ts]+ (analytics/observe! latency-metric tags+ (detection-latency-ms ts timeout-ms detected-at-ms)))))+ reaped))diff --git a/src/metabase/run_tracking/task.clj b/src/metabase/run_tracking/task.cljnew file mode 100644index 00000000000..5c129b27970--- /dev/null+++ b/src/metabase/run_tracking/task.clj@@ -0,0 +1,62 @@+(ns metabase.run-tracking.task+ "Quartz job and scheduler primitives for run-tracking reapers."+ (:require+ [clojurewerkz.quartzite.jobs :as jobs]+ [clojurewerkz.quartzite.schedule.calendar-interval :as calendar-interval]+ [clojurewerkz.quartzite.triggers :as triggers]+ [metabase.task.core :as task]+ [metabase.util :as u]+ [metabase.util.jvm :as u.jvm]+ [metabase.util.log :as log])+ (:import+ (org.quartz JobExecutionContext)))++(set! *warn-on-reflection* true)++;; One Quartz job class serves every reaper; each clustered job resolves its reap-fn by job key.+;; `task/init!` methods run on every node before its scheduler starts, so the registry is always+;; populated before a trigger can fire locally.+(defonce ^:private reapers (atom {}))++(task/defjob ^{:doc "Reap orphaned (stale-heartbeat) runs for a registered run model."+ org.quartz.DisallowConcurrentExecution true}+ RunTrackingReaper [ctx]+ (let [job-key (.. ^JobExecutionContext ctx getJobDetail getKey getName)+ {:keys [reap-fn label]} (@reapers job-key)]+ (when-let [reaped (and reap-fn (not-empty (reap-fn)))]+ (log/infof "Reaped %d orphaned %s(s) with stale heartbeats." (count reaped) label))))++(defn schedule-reaper!+ "Register and schedule the clustered orphan-reaper job `job-key`: every `interval-minutes` (default 1)+ it calls `reap-fn` (which returns the reaped rows) and logs a summary naming the rows `label`.+ No-op if `job-key` is already scheduled. Call from a `task/init!` method."+ [{:keys [job-key reap-fn label interval-minutes] :or {interval-minutes 1}}]+ (swap! reapers assoc job-key {:reap-fn reap-fn :label label})+ (when-not (task/job-exists? job-key)+ (let [job (jobs/build+ (jobs/of-type RunTrackingReaper)+ (jobs/with-identity (jobs/key job-key)))+ trigger (triggers/build+ (triggers/with-identity (triggers/key job-key))+ (triggers/start-now)+ (triggers/with-schedule+ (calendar-interval/schedule+ (calendar-interval/with-interval-in-minutes interval-minutes)+ (calendar-interval/with-misfire-handling-instruction-do-nothing))))]+ (task/schedule-task! job trigger))))++(defn start-heartbeat!+ "Call `heartbeat-fn` now and then every `interval-minutes`, on a dedicated daemon (virtual) thread.+ Returns a future; cancel it to stop the heartbeat. Call from a `task/init!` method."+ [heartbeat-fn interval-minutes]+ (u.jvm/in-virtual-thread*+ (try+ (loop []+ (try+ (heartbeat-fn)+ (catch InterruptedException e (throw e))+ (catch Throwable t+ (log/error t "Error sending run-tracking heartbeat")))+ (Thread/sleep (long (u/minutes->ms interval-minutes)))+ (recur))+ (catch InterruptedException _ nil))))diff --git a/src/metabase/task_history/task/task_run_heartbeat.clj b/src/metabase/task_history/task/task_run_heartbeat.cljindex ad0c4c3e8dc..c345ee262e9 100644--- a/src/metabase/task_history/task/task_run_heartbeat.clj+++ b/src/metabase/task_history/task/task_run_heartbeat.clj@@ -4,15 +4,11 @@2. Mark orphaned task runs (no heartbeat for threshold hours) as :abandoned3. Mark orphaned tasks (in :started status with no heartbeat) as :unknown"(:require- [clojurewerkz.quartzite.jobs :as jobs]- [clojurewerkz.quartzite.schedule.cron :as cron]- [clojurewerkz.quartzite.triggers :as triggers]- [metabase.app-db.core :as mdb][metabase.config.core :as config][metabase.models.interface :as mi]+ [metabase.run-tracking.core :as rt][metabase.task.core :as task][metabase.tracing.core :as tracing]- [metabase.util.honey-sql-2 :as h2x][metabase.util.log :as log][toucan2.core :as t2]))@@ -44,22 +40,14 @@2. started_at is older than max run duration (stuck run)Returns the set of run IDs that were marked as orphaned."[]- (let [heartbeat-cutoff (h2x/add-interval-honeysql-form (mdb/db-type) :%now (- orphan-threshold-hours) :hour)- duration-cutoff (h2x/add-interval-honeysql-form (mdb/db-type) :%now (- max-run-duration-hours) :hour)- where-clause {:where [:and- [:= :status "started"]- [:or- [:< :updated_at heartbeat-cutoff]- [:< :started_at duration-cutoff]]]}- orphaned-run-ids (tracing/with-span :tasks "task.heartbeat.mark-orphaned-runs"- {:db/statement (tracing/best-effort-sanitize-sql (assoc where-clause :select [:id] :from [:task_run]))}- (t2/select-fn-set :id :model/TaskRun where-clause))]- (when (seq orphaned-run-ids)- (t2/update! :model/TaskRun {:id [:in orphaned-run-ids]}- {:status :abandoned- :ended_at (mi/now)})- (log/infof "Marked %d abandoned task runs" (count orphaned-run-ids)))- orphaned-run-ids))+ (let [orphaned (tracing/with-span :tasks "task.heartbeat.mark-orphaned-runs" {}+ (rt/reap-rows! {:model :model/TaskRun+ :active [:= :status "started"]+ :terminal {:status "abandoned" :ended_at (mi/now)}+ :stale [:or+ [:< :updated_at (rt/cutoff orphan-threshold-hours :hour)]+ [:< :started_at (rt/cutoff max-run-duration-hours :hour)]]}))]+ (into #{} (map :id) orphaned)))(defn mark-orphaned-tasks!"Mark tasks as :unknown if they belong to the given orphaned runs."@@ -75,30 +63,18 @@(log/infof "Marked %d orphaned tasks as :unknown" orphaned))orphaned))))-(defn- task-run-heartbeat!- "Send heartbeat for running tasks and mark orphaned runs/tasks."+(defn- reap-orphans!+ "Mark orphaned task runs as :abandoned and their tasks as :unknown; return the reaped run ids."[]- (log/debug "Running task run heartbeat")- (send-heartbeat!)(let [orphaned-run-ids (mark-orphaned-runs!)]- (mark-orphaned-tasks! orphaned-run-ids)))--(task/defjob- ^{:doc "Send heartbeat for running task runs and mark orphaned runs as :unknown"}- TaskRunHeartbeat [_]- (task-run-heartbeat!))--(def ^:private job-key "metabase.task.task-run-heartbeat.job")-(def ^:private trigger-key "metabase.task.task-run-heartbeat.trigger")+ (mark-orphaned-tasks! orphaned-run-ids)+ orphaned-run-ids))(defmethod task/init! ::TaskRunHeartbeat [_]- (let [job (jobs/build- (jobs/of-type TaskRunHeartbeat)- (jobs/with-identity (jobs/key job-key)))- trigger (triggers/build- (triggers/with-identity (triggers/key trigger-key))- (triggers/start-now)- (triggers/with-schedule- ;; run every 10 minutes- (cron/cron-schedule "0 */10 * * * ? *")))]- (task/schedule-task! job trigger)))+ (rt/start-heartbeat! send-heartbeat! 10))++(defmethod task/init! ::TaskRunReaper [_]+ (rt/schedule-reaper! {:job-key "metabase.task.task-run-reaper.job"+ :label "task run"+ :reap-fn reap-orphans!+ :interval-minutes 10}))diff --git a/src/metabase/transforms/canceling.clj b/src/metabase/transforms/canceling.cljindex 271c955997e..60bbeed6e81 100644--- a/src/metabase/transforms/canceling.clj+++ b/src/metabase/transforms/canceling.clj@@ -6,6 +6,7 @@[clojurewerkz.quartzite.triggers :as triggers][metabase.analytics-interface.core :as analytics][metabase.events.core :as events]+ [metabase.run-tracking.core :as rt][metabase.task.core :as task][metabase.tracing.core :as tracing][metabase.transforms.models.transform-run :as transform-run]@@ -47,13 +48,40 @@(a/put! cancel-chan :cancel!)true))+(defn heartbeat-and-reconcile-runs!+ "Per-node tick: heartbeat the runs this process is executing (those registered in `connections`),+ then signal cancel for any that another path (timeout sweeper, reaper, force-cancel) already+ terminated, so the local work stops promptly. Each node reconciles its own runs — only the+ owning node holds a run's `cancel-chan`."+ []+ (rt/heartbeat-and-reconcile! {:model :model/TransformRun+ :active [:= :is_active true]+ :ids (keys @connections)+ :heartbeat! transform-run/heartbeat-runs!+ :on-gone chan-signal-cancel!}))+(defn chan-start-timeout-vthread!- "Starts a thread that will signal a timeout after a given number of minutes."+ "Starts a vthread that will signal a timeout after a given number of minutes."[run-id timeout-minutes](u.jvm/in-virtual-thread*- (Thread/sleep (long (* timeout-minutes 60 1000))) ;; 4 hours- (chan-signal-cancel! run-id)- (transform-run/timeout-run! run-id)))+ (try+ (Thread/sleep (long (* timeout-minutes 60 1000)))+ (chan-signal-cancel! run-id)+ (transform-run/timeout-run! run-id)+ (catch InterruptedException _ nil))))++(defmacro with-cancelation+ "Run `body` with cancellation wired up for `run-id`, tearing it down on exit (normal or throw)+ Returns the value of `body`."+ [[run-id cancel-chan timeout-minutes] & body]+ `(let [run-id# ~run-id]+ (chan-start-run! run-id# ~cancel-chan)+ (let [timeout-handle# (chan-start-timeout-vthread! run-id# ~timeout-minutes)]+ (try+ ~@body+ (finally+ (some-> timeout-handle# future-cancel)+ (chan-end-run! run-id#))))))(defn- request-latency-ms"Milliseconds elapsed since `request-time`, or nil when `request-time` is nil.@@ -145,6 +173,16 @@(log/info "Scheduling cancel transforms task.")(start-job!))+(def ^:private transform-heartbeat-stale-minutes 5)++(defmethod task/init! ::TransformRunHeartbeat [_]+ (rt/start-heartbeat! heartbeat-and-reconcile-runs! 1))++(defmethod task/init! ::TransformRunReaper [_]+ (rt/schedule-reaper! {:job-key "metabase.transforms.reaper"+ :label "transform run"+ :reap-fn #(transform-run/reap-orphaned-runs! transform-heartbeat-stale-minutes)}))+(defmethod task/init! ::CancelRuns [_](log/info "Scheduling the cancelation background task.");; does not use the Quartz schedulerdiff --git a/src/metabase/transforms/crud.clj b/src/metabase/transforms/crud.cljindex 1b70402c41b..a7cd2dc383c 100644--- a/src/metabase/transforms/crud.clj+++ b/src/metabase/transforms/crud.clj@@ -104,7 +104,7 @@(comp (transforms-base.u/->date-field-filter-xf [:last_run :start_time] last-run-start-time)(transforms-base.u/->status-filter-xf [:last_run :status] last-run-statuses)(transforms-base.u/->tag-filter-xf [:tag_ids] tag-ids)- (map #(update % :last_run transforms-base.u/localize-run-timestamps))+ (map #(update % :last_run transforms-base.u/present-run))(map transforms.u/add-source-readable)))))))(defn get-transform@@ -114,7 +114,7 @@target-table (transforms-base.u/target-table (transforms-base.i/target-db-id transform) target :active true)](-> transform(t2/hydrate :last_run :transform_tag_ids :creator :owner :can_read :can_write :can_execute)- (u/update-some :last_run transforms-base.u/localize-run-timestamps)+ (u/update-some :last_run transforms-base.u/present-run)(assoc :table target-table)transforms.u/add-source-readable)))diff --git a/src/metabase/transforms/execute.clj b/src/metabase/transforms/execute.cljindex af31023932f..fea4e5c78e4 100644--- a/src/metabase/transforms/execute.clj+++ b/src/metabase/transforms/execute.clj@@ -29,11 +29,24 @@(defn execute!"Run `transform` and sync its target table.- This is executing synchronously, but supports being kicked off in the background- by delivering the `start-promise` just before the start when the beginning of the execution has been booked- in the database."+ Executes synchronously, but the start is observable: once the run row is booked in the database,+ `:on-start` is called with the transform run id and `:start-promise` (if any) is delivered+ `[:started run-id]`. A throw before that point delivers the throwable to the promise instead, so+ callers awaiting the start never hang."([transform](execute! transform nil))- ([transform opts]- #_{:clj-kondo/ignore [:discouraged-var]}- (transforms.i/execute! (resolve-target transform) opts)))+ ([transform {:keys [start-promise on-start] :as opts}]+ (let [opts (merge opts+ {:on-start (fn [run-id]+ (when start-promise+ (deliver start-promise [:started run-id]))+ (when on-start+ (on-start run-id)))})]+ (try+ #_{:clj-kondo/ignore [:discouraged-var]}+ (transforms.i/execute! (resolve-target transform) opts)+ (catch Throwable t+ ;; so a caller awaiting the start isn't left hanging on a pre-start failure;+ ;; a no-op when the run had already started and the promise was delivered+ (when start-promise (deliver start-promise t))+ (throw t))))))diff --git a/src/metabase/transforms/interface.clj b/src/metabase/transforms/interface.cljindex 7e195385386..f50719293ff 100644--- a/src/metabase/transforms/interface.clj+++ b/src/metabase/transforms/interface.clj@@ -18,9 +18,9 @@For base execution without database tracking, use [[metabase.transforms-base.interface/execute-base!]] instead.Options:- - `:start-promise`- Will have a `transform_run.run_id` value delivered once the execution is registered with the database.- Callers can await this promise to identify the transform_run record, which enables progress / status monitoring.+ - `:on-start`+ Called with the `transform_run` id once the execution is registered with the database, which+ enables progress / status monitoring.- `:run-method`Expected to be either `:cron` (for scheduled runs) or `:manual` (for ad-hoc or test runs)diff --git a/src/metabase/transforms/jobs.clj b/src/metabase/transforms/jobs.cljindex 8ab8a4fa9d5..e96997e1d1b 100644--- a/src/metabase/transforms/jobs.clj+++ b/src/metabase/transforms/jobs.clj@@ -2,17 +2,16 @@(:require[clojure.set :as set][clojure.string :as str]- [clojurewerkz.quartzite.jobs :as jobs]- [clojurewerkz.quartzite.schedule.calendar-interval :as calendar-interval]- [clojurewerkz.quartzite.triggers :as triggers][flatland.ordered.set :as ordered-set][metabase.channel.urls :as urls][metabase.events.core :as events][metabase.revisions.core :as revisions]+ [metabase.run-tracking.core :as rt][metabase.task.core :as task][metabase.tracing.core :as tracing][metabase.transforms-base.ordering :as transforms-base.ordering][metabase.transforms-base.util :as transforms-base.u]+ [metabase.transforms.canceling :as canceling][metabase.transforms.execute :as transforms.execute][metabase.transforms.freshness :as freshness][metabase.transforms.instrumentation :as transforms.instrumentation]@@ -25,13 +24,19 @@[metabase.util :as u][metabase.util.i18n :as i18n][metabase.util.log :as log]- [toucan2.core :as t2])- (:import- (java.util.concurrent ArrayBlockingQueue BlockingQueue ExecutorService Executors ThreadFactory)- (org.apache.commons.lang3.concurrent BasicThreadFactory$Builder)))+ [toucan2.core :as t2]))(set! *warn-on-reflection* true)+(def ^:private transform-job-heartbeat-stale-minutes+ "A job run whose coordinator hasn't heartbeat in this many minutes is presumed dead and reaped."+ 5)++(def ^:private transform-worker-grace-ms+ "Slack beyond the transform run timeout before the coordinator interrupts a worker that ignored its+ own timeout."+ (* transform-job-heartbeat-stale-minutes 60 1000))+(defn- next-transform [ordering transforms-by-id complete](-> (transforms-base.ordering/available-transforms ordering #{} complete)first@@ -82,13 +87,16 @@{:order (map transforms-by-id complete):deps dependencies}))))))-(defn- block-until-not-already-running [transform-id]- (when-let [active-run (transform-run/running-run-for-transform-id transform-id)]- (log/warn "Transform" (pr-str transform-id) "already running, waiting for run" (:id active-run))- (while (transform-run/running-run-for-transform-id transform-id)- (Thread/sleep 2000))))+(defn- wait-for-transform-slot!+ "Poll until no active run exists for `transform-id`, up to `timeout-ms`."+ [transform-id timer timeout-ms]+ (loop []+ (cond+ (not (transform-run/running-run-for-transform-id transform-id)) true+ (>= (u/since-ms timer) timeout-ms) false+ :else (do (Thread/sleep 2000) (recur)))))-(defn- run-transform! [run-id run-method user-id {transform-id :id :as transform}]+(defn- run-transform! [run-id run-method user-id started-run-id {transform-id :id :as transform}](cond(not (transforms.u/check-feature-enabled transform))(log/warnf "Skip running transform %d due to lacking premium features" transform-id)@@ -99,58 +107,58 @@:else(tracing/with-span :tasks "task.transform.execute" {:transform/id transform-id:transform/name (:name transform)}- (block-until-not-already-running transform-id)- (let [try-exec- (fn []- (try- (log/info "Executing job transform" (pr-str transform-id))- (transforms.execute/execute! transform {:run-method run-method- :user-id user-id})- (catch Exception e- (if (= :already-running (:error (ex-data e)))- :already-running- (throw e)))))]+ (let [timer (u/start-timer)+ timeout-ms (u/minutes->ms (transforms.settings/transform-timeout))]+ (when (transform-run/running-run-for-transform-id transform-id)+ (log/warn "Transform" (pr-str transform-id) "already running, waiting for slot"))(loop []- (when (= :already-running (try-exec))- (when (transform-run/running-run-for-transform-id transform-id)- (log/warn "Transform" (pr-str transform-id) "already running, waiting")- (loop []- (Thread/sleep 2000)- (when (transform-run/running-run-for-transform-id transform-id)- (recur))))- (recur))))+ (if-not (wait-for-transform-slot! transform-id timer timeout-ms)+ (throw (ex-info (format "Transform %s skipped: another active run held the slot for over %d minute(s)"+ (pr-str transform-id) (transforms.settings/transform-timeout))+ {:transform-id transform-id :error :already-running-timeout}))+ (let [result (try+ (log/info "Executing job transform" (pr-str transform-id))+ (transforms.execute/execute! transform {:run-method run-method+ :user-id user-id+ ;; lets the coordinator cancel exactly the run+ ;; this worker started (see [[cancel-worker!]])+ :on-start #(deliver started-run-id %)})+ :ok+ (catch Exception e+ ;; Raced with another starter that won the is_active slot; wait again.+ (if (= :already-running (:error (ex-data e)))+ :already-running+ (throw e))))]+ (when (= :already-running result)+ (recur))))))(transforms.job-run/add-run-activity! run-id))))-(defn- named-thread-factory ^ThreadFactory [pattern]- (.build (doto (BasicThreadFactory$Builder.)- (.namingPattern pattern)- (.daemon true))))+(defn- lane-for+ "Lane a transform runs in: `:py` for python transforms (single-slot), `:sql` otherwise."+ [t]+ (if (transforms-base.u/python-transform? t) :py :sql))++(defn- busy?+ "True while any transform is still in flight in either lane."+ [{:keys [in-flight]}]+ (some seq (vals in-flight)))(defn- submit-transform!- [^ExecutorService executor- ^BlockingQueue completions- run-id run-method user-id transform]- (let [task (bound-fn []- (let [tid (:id transform)]- (try- (run-transform! run-id run-method user-id transform)- (.put completions {::status :succeeded ::transform transform})- (catch Throwable t- (log/errorf t "Transform %s in run %s failed" (pr-str tid) (pr-str run-id))- ;; Record the failure with as much debugging context as we can; the coordinator- ;; preserves these fields onto :failures. We catch Throwable (not just- ;; Exception) so a non-Exception Error — e.g. OutOfMemoryError — is still- ;; reported as a transform failure and lets the coordinator unwind cleanly,- ;; rather than vanishing into the worker's FutureTask. `::fatal` flags that case- ;; so consumers can distinguish it. (We don't rethrow: under `.submit` the- ;; FutureTask would just swallow it, so a rethrow would be a silent no-op.)- (.put completions {::status :failed- ::transform transform- ::message (or (ex-message t) (str t))- ::ex-data (ex-data t)- ::throwable t- ::fatal (not (instance? Exception t))})))))]- (.submit executor ^Runnable task)))+ "Run `transform` on its own thread; returns a future yielding a `::status` completion map.+ `started-run-id` is a promise the worker delivers its transform run id to once `execute!` has+ created it — at most once, since the `:already-running` retry only re-enters after a failed+ start — so [[cancel-worker!]] can target exactly that run."+ [run-id run-method user-id started-run-id transform]+ (future+ (try+ (run-transform! run-id run-method user-id started-run-id transform)+ {::status :succeeded ::transform transform}+ (catch Throwable t+ (log/errorf t "Transform %s in run %s failed" (pr-str (:id transform)) (pr-str run-id))+ {::status :failed+ ::transform transform+ ::message (or (ex-message t) (str t))+ ::throwable t}))))(defn- transform-target-key"A coarse identity for a transform's output table, used to keep two transforms that write the@@ -160,134 +168,207 @@(when-let [{:keys [database schema name]} (:target transform)][database schema name]))+(defn- dispatch-ready!+ "Submit every transform whose deps have all succeeded and whose lane has a free slot, recording the+ transitive cascade of dep-failures along the way. Returns the updated state."+ [st {:keys [plan deps lanes run-id run-method user-id]}]+ (reduce+ (fn [{:keys [succeeded failed in-flight-targets] :as st} t]+ (let [id (:id t)+ dep-ids (get deps id)+ lane-key (lane-for t)+ in-flight-now (get-in st [:in-flight lane-key])+ tkey (transform-target-key t)]+ (cond+ (or (succeeded id) (failed id) (in-flight-now id))+ st++ (some failed dep-ids)+ (-> st+ (update :failed conj id)+ (update :failures conj+ {::transform t+ ::message (i18n/trs "Failed to run because one or more of the transforms it depends on failed.")}))++ ;; Defer if another in-flight transform is already writing this target table.+ ;; `transform-ordering` builds DAG edges from table *reads*, not co-*writes*, so two+ ;; transforms sharing a target are independent in the DAG and would otherwise dispatch+ ;; concurrently — producing nondeterministic DDL. Retried on a later pass once the in-flight+ ;; writer completes (something is always in-flight while a target is held).+ (and tkey (contains? in-flight-targets tkey))+ st++ (and (every? succeeded dep-ids)+ (< (count in-flight-now) (lanes lane-key)))+ (let [started-run-id (promise)+ fut (submit-transform! run-id run-method user-id started-run-id t)]+ (cond-> (assoc-in st [:in-flight lane-key id]+ {:future fut+ :timer (u/start-timer)+ :tkey tkey+ :transform t+ :started-run-id started-run-id})+ tkey (update :in-flight-targets conj tkey)))++ :else st)))+ st+ plan))++(defn- cancel-worker!+ "Stop an in-flight worker: signal cooperative cancelation for the run it started, then interrupt+ its thread."+ [{:keys [started-run-id] fut :future}]+ (when-let [run-id (deref started-run-id 0 nil)]+ (canceling/chan-signal-cancel! run-id))+ (future-cancel fut))++(defn- sweep-workers!+ "Fold finished workers into the state; cancel, interrupt, and fail workers that have outrun+ `timeout-ms` — the hard backstop for a worker that ignored its own (query/cancel) timeout."+ [st timeout-ms]+ (reduce-kv+ (fn [st lane-key workers]+ (reduce-kv+ (fn [st id {:keys [timer tkey transform] fut :future :as worker}]+ (let [freed (cond-> (update-in st [:in-flight lane-key] dissoc id)+ tkey (update :in-flight-targets disj tkey))]+ (cond+ (future-done? fut)+ (let [{::keys [status] :as completion} @fut]+ (if (= status :succeeded)+ (update freed :succeeded conj id)+ ;; preserve the worker's failure context (::message / ::throwable)+ (-> freed+ (update :failed conj id)+ (update :failures conj (dissoc completion ::status)))))++ (>= (u/since-ms timer) timeout-ms)+ (do (log/warnf "Transform %s exceeded its deadline; canceling its worker" (pr-str id))+ (cancel-worker! worker)+ (-> freed+ (update :failed conj id)+ (update :failures conj+ {::transform transform+ ::message (i18n/trs "Transform did not complete within the timeout and was interrupted.")})))++ :else st)))+ st+ workers))+ st+ (:in-flight st)))++(defn- cancel-in-flight!+ "Best-effort cancel + interrupt of every in-flight worker."+ [st]+ (doseq [workers (vals (:in-flight st))+ [id worker] workers]+ (try+ (cancel-worker! worker)+ (catch Throwable t+ (log/warnf t "Error canceling in-flight worker for transform %s" (pr-str id))))))++(defonce ^:private active-runs+ ;; job-run-id -> promise, delivered once the run is found terminated externally (e.g. reaped)+ (atom {}))++(defn- heartbeat-and-reconcile-runs!+ "Stamp a heartbeat on every job run this process is coordinating, then deliver the `gone` promise+ of any that another path (reaper, force-fail) already terminated, so its coordinator aborts."+ []+ (rt/heartbeat-and-reconcile! {:model :model/TransformJobRun+ :active [:= :is_active true]+ :ids (keys @active-runs)+ :heartbeat! transforms.job-run/heartbeat-runs!+ :on-gone (fn [run-id]+ (some-> (get @active-runs run-id) (deliver true)))}))++(defn- run-coordinator-loop!+ "Dispatch ready transforms; then each round sweep the in-flight workers and refill freed slots —+ until nothing is in flight. On an abnormal exit (exception or interrupt) the in-flight workers are+ canceled before rethrowing, so they don't keep writing under a run that is about to be failed."+ [init-state {:keys [run-gone? timeout-ms] :as ctx}]+ (let [last-st (volatile! init-state)+ step! (fn [st] (vreset! last-st st) st)]+ (try+ (loop [st (step! (dispatch-ready! init-state ctx))]+ (cond+ (not (busy? st))+ st++ (run-gone?)+ (do (cancel-in-flight! st)+ (assoc st :aborted? true))++ :else+ (let [st (-> st+ (sweep-workers! timeout-ms)+ (dispatch-ready! ctx)+ step!)]+ (Thread/sleep 250)+ (recur st))))+ (catch Throwable t+ (cancel-in-flight! @last-st)+ (throw t)))))+(defn- app-db-now[](:now (t2/query-one {:select [[[:raw "current_timestamp"] :now]]})))(defn run-transforms!- "Run a series of transforms and their dependencies.+ "Run `transform-ids-to-run` and their dependencies, honoring the DAG.- SQL transforms are dispatched concurrently up to `transform-run-job-sql-concurrency`, respecting- the DAG: a transform is only started once all of its dependencies have succeeded.+ Each transform runs on its own thread; SQL transforms run concurrently up to+ `transform-run-job-sql-concurrency`, python transforms one at a time (the python-runner service has+ a single worker). A failed dependency fails its dependents transitively; a worker that overruns the+ transform timeout (plus grace) is interrupted and failed.- Python transforms run in a separate single-slot lane regardless of the SQL pool size, because- the python-runner service has only one worker; oversubscribing it would just queue requests- against their own per-call timeouts.+ Transforms pulled into the plan only as dependencies (not directly requested) are skipped while+ still fresh, unless `skip-fresh-deps?` is false.- If a dependency failed, dependents are recorded as failures (transitively) without being- executed.-- Updates the transform-job-run specified by run-id after every completion.- Returns a map with :status and a collection of :failures if failed."+ Returns `{::status :succeeded}`, `{::status :failed ::failures [...]}`, or `{::status :aborted}`+ when the job run was terminated externally (e.g. reaped) while this coordinator was still running."[run-id transform-ids-to-run {:keys [run-method start-promise user-id skip-fresh-deps?]:or {skip-fresh-deps? true}}]- (let [{plan :order deps :deps} (get-plan transform-ids-to-run)- requested (set transform-ids-to-run)- closure (into #{} (map :id) plan)- ;; Only deps pulled into the plan (not directly requested) are freshness-gated. Seeding them- ;; as :succeeded lets their dependents dispatch while they themselves are never submitted.- skip (or (when skip-fresh-deps?- (freshness/fresh-dep-ids (app-db-now) (set/difference closure requested)))- #{})- n (max 1 (transforms.settings/transform-run-job-sql-concurrency))- sql-executor (Executors/newFixedThreadPool n (named-thread-factory "transforms-sql-worker-%d"))- py-executor (Executors/newSingleThreadExecutor (named-thread-factory "transforms-python-worker-%d"))- lanes {:sql {:executor sql-executor :capacity n}- :py {:executor py-executor :capacity 1}}- lane-for (fn [t] (if (transforms-base.u/python-transform? t) :py :sql))- completions (ArrayBlockingQueue. (max 2 (inc n)))- state (volatile! {:succeeded skip- :failed #{}- :failures []- :in-flight {:sql #{} :py #{}}- ;; target tables currently being written by an in-flight transform- :in-flight-targets #{}})- busy? (fn [{:keys [in-flight]}] (some seq (vals in-flight)))- ;; Plan is topo-sorted, so a single pass propagates the full cascade of dep-failures.- dispatch! (fn [st]- (reduce- (fn [{:keys [succeeded failed in-flight-targets] :as st} t]- (let [id (:id t)- dep-ids (get deps id)- lane-key (lane-for t)- {:keys [^ExecutorService executor capacity]} (get lanes lane-key)- in-flight-now (get-in st [:in-flight lane-key])- tkey (transform-target-key t)]- (cond- (or (succeeded id) (failed id) (in-flight-now id))- st-- (some failed dep-ids)- (-> st- (update :failed conj id)- (update :failures conj- {::transform t- ::message (i18n/trs "Failed to run because one or more of the transforms it depends on failed.")}))-- ;; Defer if another in-flight transform is already writing this target- ;; table. `transform-ordering` builds DAG edges from table *reads*, not- ;; co-*writes*, so two transforms sharing a target are independent in- ;; the DAG and would otherwise dispatch concurrently — producing- ;; nondeterministic DDL. This shouldn't happen in a well-formed config;- ;; the guard just stops a misconfiguration from racing. Retried on a- ;; later pass once the in-flight writer completes (something is always- ;; in-flight while a target is held, so the loop won't exit early).- (and tkey (contains? in-flight-targets tkey))- st-- (and (every? succeeded dep-ids)- (< (count in-flight-now) capacity))- (try- (submit-transform! executor completions run-id run-method user-id t)- (cond-> (update-in st [:in-flight lane-key] conj id)- tkey (update :in-flight-targets conj tkey))- (catch java.util.concurrent.RejectedExecutionException e- ;; The pool was shut down out from under us (abnormal-exit window).- ;; Record the failure so the run reflects the partial dispatch- ;; rather than silently dropping this transform.- (-> st- (update :failed conj id)- (update :failures conj- {::transform t- ::message (or (ex-message e) (str e))}))))-- :else st)))- st- plan))]- (when (seq skip)- (log/infof "Skipping %d fresh pulled-in dependency transform(s): %s" (count skip) (pr-str skip)))- (when start-promise (deliver start-promise :started))- (try- (vreset! state (dispatch! @state))- (while (busy? @state)- (let [completion (.take completions)- {::keys [transform status]} completion- id (:id transform)- lane-key (lane-for transform)- tkey (transform-target-key transform)]- (vswap! state- (fn [st]- (let [st' (cond-> (update-in st [:in-flight lane-key] disj id)- tkey (update :in-flight-targets disj tkey))]- (case status- :succeeded (update st' :succeeded conj id)- ;; Preserve the full failure context the worker attached (::message plus- ;; ::ex-data / ::throwable / ::fatal) so downstream consumers — notifications- ;; and logs — can surface it. dispatch!'s dep-failure path produces a subset- ;; of the same shape, and consumers only read ::transform / ::message.- :failed (-> st'- (update :failed conj id)- (update :failures conj (dissoc completion ::status)))))))- (vreset! state (dispatch! @state))))- (finally- ;; shutdownNow (not shutdown): on the happy path the in-flight set is already drained, so- ;; this is equivalent to shutdown; on an abnormal exit (e.g. an interrupted take) it also- ;; interrupts any workers still running against a run that has already been failed.- (.shutdownNow sql-executor)- (.shutdownNow py-executor)))- (if (seq (:failures @state))- {::status :failed ::failures (:failures @state)}- {::status :succeeded})))+ (let [gone (promise)+ _ (swap! active-runs assoc run-id gone)+ final-state+ (try+ (let [{plan :order deps :deps} (get-plan transform-ids-to-run)+ requested (set transform-ids-to-run)+ closure (into #{} (map :id) plan)+ ;; Only deps pulled into the plan (not directly requested) are freshness-gated. Seeding them+ ;; as :succeeded lets their dependents dispatch while they themselves are never submitted.+ skip (or (when skip-fresh-deps?+ (freshness/fresh-dep-ids (app-db-now) (set/difference closure requested)))+ #{})+ init-state {:succeeded skip+ :failed #{}+ :failures []+ ;; per lane: transform-id -> {:future :timer :tkey :transform}+ :in-flight {:sql {} :py {}}+ ;; target tables currently being written by an in-flight transform+ :in-flight-targets #{}}+ ctx {:plan plan+ :deps deps+ :run-id run-id+ :run-gone? #(realized? gone)+ :run-method run-method+ :user-id user-id+ ;; lane -> max concurrent workers+ :lanes {:sql (max 1 (transforms.settings/transform-run-job-sql-concurrency))+ :py 1}+ :timeout-ms (+ (u/minutes->ms (transforms.settings/transform-timeout))+ transform-worker-grace-ms)}]+ (when (seq skip)+ (log/infof "Skipping %d fresh pulled-in dependency transform(s): %s" (count skip) (pr-str skip)))+ (when start-promise (deliver start-promise :started))+ (run-coordinator-loop! init-state ctx))+ (finally+ (swap! active-runs dissoc run-id)))]+ (cond+ (:aborted? final-state) {::status :aborted}+ (seq (:failures final-state)) {::status :failed ::failures (:failures final-state)}+ :else {::status :succeeded})))(defn- job-transform-ids [job-id](let [tag-ids (t2/select-fn-set :tag_id :model/TransformJobTransformTag :job_id job-id)]@@ -400,6 +481,10 @@(let [result (run-transforms! run-id transforms opts)](case (::status result):succeeded (transforms.job-run/succeed-started-run! run-id)+ ;; terminated externally (e.g. reaped): the row is already terminal and the+ ;; terminator already notified, so just log+ :aborted (log/warnf "Transform job run %s for job %s was terminated externally; coordinator aborted."+ (pr-str run-id) (pr-str job-id)):failed (try(transforms.job-run/fail-started-run! run-id {:message (compile-transform-failure-messages (::failures result))})(when (= :cron run-method)@@ -418,37 +503,15 @@(throw t)))))run-id)))))-(def ^:private job-key "metabase.transforms.jobs.timeout-job")--(defn- timeout-old-runs!- "Time out stale transform job runs."+(defn- reap-orphaned-runs!+ "Reap job runs whose coordinator process died (stale heartbeat)."[]- (let [timed-out (transforms.job-run/timeout-old-runs!- (transforms.settings/transform-timeout) :minute)]- (when (seq timed-out)- (log/infof "Timed out %d transform job run(s)." (count timed-out)))- timed-out))--(task/defjob ^{:doc "Times out transform jobs when necessary."- org.quartz.DisallowConcurrentExecution true}- TimeoutOldRuns [_ctx]- (tracing/with-span :tasks "task.transform.timeout-check" {:transform.timeout/type "job"}- (timeout-old-runs!)))--(defn- start-job! []- (when (not (task/job-exists? job-key))- (let [job (jobs/build- (jobs/of-type TimeoutOldRuns)- (jobs/with-identity (jobs/key job-key)))- trigger (triggers/build- (triggers/with-identity (triggers/key job-key))- (triggers/start-now)- (triggers/with-schedule- (calendar-interval/schedule- (calendar-interval/with-interval-in-minutes 10)- (calendar-interval/with-misfire-handling-instruction-do-nothing))))]- (task/schedule-task! job trigger))))--(defmethod task/init! ::TimeoutJob [_]- (log/info "Scheduling transform job timeout.")- (start-job!))+ (transforms.job-run/reap-orphaned-runs! transform-job-heartbeat-stale-minutes))++(defmethod task/init! ::TransformJobRunHeartbeat [_]+ (rt/start-heartbeat! heartbeat-and-reconcile-runs! 1))++(defmethod task/init! ::TransformJobRunReaper [_]+ (rt/schedule-reaper! {:job-key "metabase.transforms.jobs.reaper-job"+ :label "transform job run"+ :reap-fn #'reap-orphaned-runs!}))diff --git a/src/metabase/transforms/models/job_run.clj b/src/metabase/transforms/models/job_run.cljindex b1c40e57249..71ed3b2da76 100644--- a/src/metabase/transforms/models/job_run.clj+++ b/src/metabase/transforms/models/job_run.clj@@ -1,15 +1,10 @@(ns metabase.transforms.models.job-run(:require- [metabase.analytics-interface.core :as analytics]- [metabase.app-db.core :as mdb][metabase.models.interface :as mi]- [metabase.transforms.models.timeout-util :as timeout-util]- [metabase.util.honey-sql-2 :as h2x]+ [metabase.run-tracking.core :as rt][methodical.core :as methodical][toucan2.core :as t2]- [toucan2.realize :as t2.realize])- (:import- (java.time Instant)))+ [toucan2.realize :as t2.realize]))(set! *warn-on-reflection* true)@@ -80,25 +75,25 @@{:status :failed:is_active nil})))-(defn timeout-old-runs!- "Time out all active job runs older than the specified age. Returns the rows that- were timed out so callers can take follow-up action (e.g. sending notifications).- See [[metabase.transforms.models.timeout-util/timeout-rows!]] for atomicity rationale."- [age unit]- (let [cutoff (h2x/add-interval-honeysql-form (mdb/db-type) :%now (- age) unit)- timeout-dur (timeout-util/unit->duration age unit)- detected-at (Instant/now)- timed-out (timeout-util/timeout-rows! :model/TransformJobRun :updated_at cutoff)]- (when (seq timed-out)- (analytics/inc! :metabase-transforms/timeouts-total- {:type "job"}- (count timed-out))- (doseq [run timed-out]- (when-let [updated-at (:updated_at run)]- (analytics/observe! :metabase-transforms/timeout-detection-latency-ms- {:type "job"}- (timeout-util/detection-latency-ms updated-at timeout-dur detected-at)))))- timed-out))+(defn heartbeat-runs!+ "Stamp `last_heartbeat = now` on the given still-active job-run-ids."+ [run-ids]+ (rt/heartbeat-ids! :model/TransformJobRun [:= :is_active true] :last_heartbeat run-ids))++(defn reap-orphaned-runs!+ "Time out active job runs whose `last_heartbeat` is older than `stale-minutes` (their coordinator+ process is presumed dead). Returns the rows that were timed out so callers can notify."+ [stale-minutes]+ (rt/reap-orphaned!+ {:model :model/TransformJobRun+ :active [:= :is_active true]+ :stale [:< :last_heartbeat (rt/cutoff stale-minutes :minute)]+ :terminal {:status "timeout" :end_time :%now :is_active nil :message "Timed out: no heartbeat"}+ :metrics {:total-metric :metabase-transforms/timeouts-total+ :latency-metric :metabase-transforms/timeout-detection-latency-ms+ :tags {:type "job"}+ :latency-column :last_heartbeat+ :timeout-ms (rt/unit->ms stale-minutes :minute)}}))(defn running-run-for-job-id"Return a single active job run or nil."diff --git a/src/metabase/transforms/models/timeout_util.clj b/src/metabase/transforms/models/timeout_util.cljdeleted file mode 100644index 2812e5898a2..00000000000--- a/src/metabase/transforms/models/timeout_util.clj+++ /dev/null@@ -1,45 +0,0 @@-(ns metabase.transforms.models.timeout-util- "Helpers shared by the transform-run and job-run timeout sweepers."- (:require- [toucan2.core :as t2])- (:import- (java.time Duration Instant OffsetDateTime)- (java.time.temporal ChronoUnit)))--(set! *warn-on-reflection* true)--(defn unit->duration- "Convert `age` of `unit` (`:second`, `:minute`, or `:hour`) to an exact `java.time.Duration`."- ^Duration [age unit]- (Duration/of age (case unit- :minute ChronoUnit/MINUTES- :second ChronoUnit/SECONDS- :hour ChronoUnit/HOURS)))--(defn detection-latency-ms- "Milliseconds elapsed past `(reference-ts + timeout-duration)` at the time of detection. Clamped at zero."- [^OffsetDateTime reference-ts ^Duration timeout-duration ^Instant detected-at]- (max 0 (.toMillis (.minus (Duration/between (.toInstant reference-ts) detected-at)- timeout-duration))))--(defn timeout-rows!- "Atomically time out active rows of `model` whose `age-column` predates `cutoff`; returns the pre-update rows,- or `nil` if none were stale.- Runs SELECT FOR UPDATE + UPDATE in one transaction so the rows callers report on match those the UPDATE- transitions — without the lock, a concurrent `:is_active` flip between SELECT and UPDATE would leave callers- counting a timeout that didn't happen. `UPDATE … RETURNING *` would be simpler but isn't portable to H2/MySQL."- [model age-column cutoff]- (t2/with-transaction [_conn]- (when-let [stale (not-empty (t2/select model- {:where [:and- [:= :is_active true]- [:< age-column cutoff]]- :for :update}))]- (t2/update! model- :id [:in (mapv :id stale)]- :is_active true- {:status :timeout- :end_time :%now- :is_active nil- :message "Timed out by metabase"})- stale)))diff --git a/src/metabase/transforms/models/transform.clj b/src/metabase/transforms/models/transform.cljindex 70d272a3f2d..c6dadd8f5db 100644--- a/src/metabase/transforms/models/transform.clj+++ b/src/metabase/transforms/models/transform.clj@@ -232,7 +232,7 @@last-runs (m/index-by :transform_id (transform-run/latest-runs transform-ids))](for [{transform-id :id :as transform} transforms](let [{:keys [status checkpoint_hi_value] :as last-run} (get last-runs transform-id)- transform (assoc transform :last_run last-run)]+ transform (assoc transform :last_run (dissoc last-run :last_heartbeat))](if (and (= status :succeeded) checkpoint_hi_value);; ensure consistency of last_checkpoint_value with last_run(if (:last_checkpoint_value transform)diff --git a/src/metabase/transforms/models/transform_run.clj b/src/metabase/transforms/models/transform_run.cljindex 055d4a20cca..c91394ff095 100644--- a/src/metabase/transforms/models/transform_run.clj+++ b/src/metabase/transforms/models/transform_run.clj@@ -8,7 +8,7 @@[metabase.models.interface :as mi][metabase.premium-features.core :as premium-features][metabase.query-processor.parameters.dates :as params.dates]- [metabase.transforms.models.timeout-util :as timeout-util]+ [metabase.run-tracking.core :as rt][metabase.transforms.models.transform-run-cancelation :as cancel][metabase.util :as u][metabase.util.date-2 :as u.date]@@ -19,7 +19,7 @@[toucan2.core :as t2][toucan2.realize :as t2.realize])(:import- (java.time Instant OffsetDateTime ZoneOffset)))+ (java.time OffsetDateTime ZoneOffset)))(set! *warn-on-reflection* true)@@ -154,31 +154,46 @@(when-let [run (t2/select-one :model/TransformRun :id run-id)](publish-timeout-event! run))))))+(defn- reap-transform-runs!+ "Reap active transform runs by `stale-column` into a timeout carrying `message`, publishing a timeout+ event per run. See [[metabase.run-tracking.core/reap-orphaned!]]."+ [stale-column age unit message]+ (let [end-time (OffsetDateTime/now ZoneOffset/UTC)+ reaped (rt/reap-orphaned!+ {:model :model/TransformRun+ :active [:= :is_active true]+ :stale [:< stale-column (rt/cutoff age unit)]+ :terminal {:status "timeout" :end_time :%now :is_active nil :message message}+ :metrics {:total-metric :metabase-transforms/timeouts-total+ :latency-metric :metabase-transforms/timeout-detection-latency-ms+ :tags {:type "transform"}+ :latency-column stale-column+ :timeout-ms (rt/unit->ms age unit)}})]+ (doseq [run reaped]+ (publish-timeout-event! (assoc run+ :status :timeout+ :is_active nil+ :end_time end-time+ :message message)))+ (cancel/delete-old-canceling-runs!)+ reaped))+(defn timeout-old-runs!- "Time out all active runs older than the specified age. Returns the rows that were timed out.- See [[metabase.transforms.models.timeout-util/timeout-rows!]] for atomicity rationale."+ "Time out all active runs whose `start_time` is older than the specified age. Returns the rows that were+ timed out."[age unit]- (let [cutoff (h2x/add-interval-honeysql-form (mdb/db-type) :%now (- age) unit)- timeout-dur (timeout-util/unit->duration age unit)- detected-at (Instant/now)- end-time (OffsetDateTime/ofInstant detected-at ZoneOffset/UTC)- timed-out (timeout-util/timeout-rows! :model/TransformRun :start_time cutoff)]- (when (seq timed-out)- (analytics/inc! :metabase-transforms/timeouts-total- {:type "transform"}- (count timed-out))- (doseq [run timed-out]- (when-let [start (:start_time run)]- (analytics/observe! :metabase-transforms/timeout-detection-latency-ms- {:type "transform"}- (timeout-util/detection-latency-ms start timeout-dur detected-at)))- (publish-timeout-event! (assoc run- :status :timeout- :is_active nil- :end_time end-time- :message "Timed out by metabase"))))- (cancel/delete-old-canceling-runs!)- timed-out))+ (reap-transform-runs! :start_time age unit "Timed out by metabase"))++(defn heartbeat-runs!+ "Stamp `last_heartbeat = now` on the given still-active `run-ids`."+ [run-ids]+ (rt/heartbeat-ids! :model/TransformRun [:= :is_active true] :last_heartbeat run-ids))++(defn reap-orphaned-runs!+ "Time out active runs whose `last_heartbeat` is older than `stale-minutes` (their owning process is+ presumed dead). Returns the rows that were timed out."+ [stale-minutes]+ (reap-transform-runs! :last_heartbeat stale-minutes :minute "Timed out: no heartbeat"))(defn cancel-old-canceling-runs!"Atomically force-cancels active runs whose cancelation requests are older than `age` `unit`. Returns thediff --git a/src/metabase/transforms/query_impl.clj b/src/metabase/transforms/query_impl.cljindex ccc1de45c5e..bc56ba21bc8 100644--- a/src/metabase/transforms/query_impl.clj+++ b/src/metabase/transforms/query_impl.clj@@ -32,7 +32,7 @@(defn- run-mbql-transform!([transform] (run-mbql-transform! transform nil))([{:keys [id source target owner_user_id creator_id] :as transform}- {:keys [run-method start-promise user-id]}]+ {:keys [run-method on-start user-id]}];; `:target` is already workspace-rewritten — `resolve-transform-target` runs in;; `metabase.transforms.execute/execute!` before dispatch.(try@@ -43,7 +43,7 @@user-id(or owner_user_id creator_id)){run-id :id} (transforms.u/try-start-unless-already-running id run-method run-user-id)]- (when start-promise (deliver start-promise [:started run-id]))+ (when on-start (on-start run-id))(driver.conn/with-write-connection(log/info "Executing transform" id "with target" (pr-str target)"using" (driver.conn/connection-telemetry-info))@@ -80,10 +80,6 @@(if (= :already-running (:error (ex-data t)))(log/warnf "Transform %d is already running" id)(log/error t "Error executing transform"))- (when start-promise- ;; if the start-promise has been delivered, this is a no-op,- ;; but we assume nobody would catch the exception anyway- (deliver start-promise t))(throw t)))))#_{:clj-kondo/ignore [:discouraged-var]}diff --git a/src/metabase/transforms/util.clj b/src/metabase/transforms/util.cljindex bbc49f65278..762632c7ce1 100644--- a/src/metabase/transforms/util.clj+++ b/src/metabase/transforms/util.clj@@ -138,64 +138,61 @@- `:ex-message-fn` change how caught exceptions are presented to the user in run logs, by default the same as clojure.core/ex-message"[run-id transform driver {:keys [db-id conn-spec output-schema]} run-transform! & {:keys [ex-message-fn] :or {ex-message-fn ex-message}}];; local run is responsible for status, using canceling lifecycle- (try- (when (and (not (str/blank? output-schema))- (not (driver/schema-exists? driver db-id output-schema)))- (driver/create-schema-if-needed! driver conn-spec output-schema))- (let [source-range-params (transforms-base.u/get-source-range-params transform)- transform-timeout (transforms.settings/transform-timeout)- transform-timeout-ms (u/minutes->ms transform-timeout)- full-incremental? (transforms-base.u/full-incremental-run? transform)- ;; Efficiency metrics (rows-available / rows-processed) are only meaningful when this run's- ;; rows-affected count can be trusted. On drivers that declare- ;; `:transforms/accurate-rows-affected` false, a full-rebuild (CTAS) run reports a bogus- ;; count, so we skip emitting efficiency metrics for those runs entirely. The INSERT path's- ;; count is accurate even on those drivers.- reliable-row-count? (or (driver.u/supports? driver :transforms/accurate-rows-affected- {:lib/type :metadata/database :id db-id})- (not full-incremental?))]- (transforms-base.u/save-run-checkpoint-range! run-id source-range-params)- (when-let [{:keys [rows-available] :as srp} source-range-params]- (tracing/add-span-attrs! :tasks- (cond-> (transforms-base.u/checkpoint-span-attrs srp)- (and reliable-row-count? rows-available)- (assoc :transform/rows-available rows-available))))- (canceling/chan-start-timeout-vthread! run-id transform-timeout)- (let [cancel-chan (a/promise-chan)- ret (driver.conn/with-transform-connection- ;; Route through the `:transform` JDBC pool, whose `unreturnedConnectionTimeout` will be set- ;; from the `*query-timeout-ms*` binding below at pool-creation time. This keeps the default- ;; pool's leak-detector at `MB_DB_QUERY_TIMEOUT_MINUTES` for all non-transform traffic.- (binding [qp.pipeline/*canceled-chan* cancel-chan- driver.settings/*query-timeout-ms* transform-timeout-ms- ;; Match the query timeout so a single slow socket read (or a driver that waits for- ;; the full server-side query) does not get killed before the transform's own deadline.- driver.settings/*network-timeout-ms* (max driver.settings/*network-timeout-ms* transform-timeout-ms)]- (canceling/chan-start-run! run-id cancel-chan)- (run-transform! cancel-chan source-range-params)))]- (transforms-base.u/save-watermark! (:id transform) source-range-params)- (transform-run/succeed-started-run! run-id)- ;; Narrow try/catch so an emission throw doesn't trigger the outer catch's- ;; fail-started-run! after succeed-started-run! has already fired.- (when reliable-row-count?- (try- (when-some [rows-available (:rows-available source-range-params)]- (when-some [rp (:rows-affected (:result ret))]- (tracing/add-span-attrs! :tasks {:transform/rows-processed rp})- (transforms.instrumentation/record-incremental-rows!- rows-available- rp- full-incremental?)))- (catch Throwable t- (log/warnf t "Failed to emit incremental-rows metric for transform %s" (:id transform)))))- ret))- (catch Throwable t- (if (:timeout (ex-data t))- (transform-run/timeout-run! run-id {:message (ex-message-fn t)})- (transform-run/fail-started-run! run-id {:message (ex-message-fn t)}))- (throw t))- (finally- (canceling/chan-end-run! run-id))))+ (let [cancel-chan (a/promise-chan)+ transform-timeout (transforms.settings/transform-timeout)+ transform-timeout-ms (u/minutes->ms transform-timeout)]+ (canceling/with-cancelation [run-id cancel-chan transform-timeout]+ (try+ (let [source-range-params (transforms-base.u/get-source-range-params transform)+ full-incremental? (transforms-base.u/full-incremental-run? transform)+ ;; Efficiency metrics (rows-available / rows-processed) are only meaningful when this run's+ ;; rows-affected count can be trusted. On drivers that declare+ ;; `:transforms/accurate-rows-affected` false, a full-rebuild (CTAS) run reports a bogus+ ;; count, so we skip emitting efficiency metrics for those runs entirely. The INSERT path's+ ;; count is accurate even on those drivers.+ reliable-row-count? (or (driver.u/supports? driver :transforms/accurate-rows-affected+ {:lib/type :metadata/database :id db-id})+ (not full-incremental?))]+ (when (and (not (str/blank? output-schema))+ (not (driver/schema-exists? driver db-id output-schema)))+ (driver/create-schema-if-needed! driver conn-spec output-schema))+ (transforms-base.u/save-run-checkpoint-range! run-id source-range-params)+ (when-let [{:keys [rows-available] :as srp} source-range-params]+ (tracing/add-span-attrs! :tasks+ (cond-> (transforms-base.u/checkpoint-span-attrs srp)+ (and reliable-row-count? rows-available)+ (assoc :transform/rows-available rows-available))))+ (let [ret (driver.conn/with-transform-connection+ ;; Route through the `:transform` JDBC pool, whose `unreturnedConnectionTimeout` will be set+ ;; from the `*query-timeout-ms*` binding below at pool-creation time. This keeps the default+ ;; pool's leak-detector at `MB_DB_QUERY_TIMEOUT_MINUTES` for all non-transform traffic.+ (binding [qp.pipeline/*canceled-chan* cancel-chan+ driver.settings/*query-timeout-ms* transform-timeout-ms+ ;; Match the query timeout so a single slow socket read (or a driver that waits for+ ;; the full server-side query) does not get killed before the transform's own deadline.+ driver.settings/*network-timeout-ms* (max driver.settings/*network-timeout-ms* transform-timeout-ms)]+ (run-transform! cancel-chan source-range-params)))]+ (transforms-base.u/save-watermark! (:id transform) source-range-params)+ (transform-run/succeed-started-run! run-id)+ ;; Narrow try/catch so an emission throw doesn't trigger the outer catch's+ ;; fail-started-run! after succeed-started-run! has already fired.+ (when reliable-row-count?+ (try+ (when-some [rows-available (:rows-available source-range-params)]+ (when-some [rp (:rows-affected (:result ret))]+ (tracing/add-span-attrs! :tasks {:transform/rows-processed rp})+ (transforms.instrumentation/record-incremental-rows!+ rows-available+ rp+ full-incremental?)))+ (catch Throwable t+ (log/warnf t "Failed to emit incremental-rows metric for transform %s" (:id transform)))))+ ret))+ (catch Throwable t+ (if (:timeout (ex-data t))+ (transform-run/timeout-run! run-id {:message (ex-message-fn t)})+ (transform-run/fail-started-run! run-id {:message (ex-message-fn t)}))+ (throw t))))))(defn is-temp-transform-table?"Return true when `table` matches the transform temporary table naming pattern and transforms are enabled."diff --git a/src/metabase/transforms_base/util.clj b/src/metabase/transforms_base/util.cljindex 700bb367e7c..4d8b3533a42 100644--- a/src/metabase/transforms_base/util.clj+++ b/src/metabase/transforms_base/util.clj@@ -753,6 +753,13 @@(u/update-some :start_time utc-timestamp-string)(u/update-some :end_time utc-timestamp-string)))+(defn present-run+ "Prepare a transform run for an API response: localize its timestamps and drop internal-only fields."+ [run]+ (-> run+ localize-run-timestamps+ (dissoc :last_heartbeat)))+;;; ------------------------------------------------- Filter Transforms -------------------------------------------------(defn- matching-timestamp?diff --git a/src/metabase/transforms_rest/api/transform.clj b/src/metabase/transforms_rest/api/transform.cljindex 06e2af9cb67..c3458eb9902 100644--- a/src/metabase/transforms_rest/api/transform.clj+++ b/src/metabase/transforms_rest/api/transform.clj@@ -219,7 +219,7 @@(-> (transforms.core/paged-runs (assoc query-params:offset (request/offset):limit (request/limit)))- (update :data #(map transforms-base.u/localize-run-timestamps %))))+ (update :data #(map transforms-base.u/present-run %))))(api.macros/defendpoint :get "/run/:run-id" :- TransformRunResponse"Get a transform run by ID."@@ -228,7 +228,7 @@(api/check-data-analyst)(let [run (api/check-404 (t2/select-one :model/TransformRun :id run-id))](-> (t2/hydrate run [:transform :collection :transform_tag_ids])- transforms-base.u/localize-run-timestamps)))+ transforms-base.u/present-run)))(api.macros/defendpoint :put "/:id" :- TransformResponse"Update a transform."diff --git a/src/metabase/transforms_rest/api/transform_job.clj b/src/metabase/transforms_rest/api/transform_job.cljindex ba3a97b7f91..330d2dfd0d5 100644--- a/src/metabase/transforms_rest/api/transform_job.clj+++ b/src/metabase/transforms_rest/api/transform_job.clj@@ -203,7 +203,8 @@(when (and schedule was-active will-be-active)(transforms.core/update-job! job-id schedule))(-> (t2/select-one :model/TransformJob :id job-id)- (t2/hydrate :tag_ids :last_run)))))+ (t2/hydrate :tag_ids :last_run)+ (update :last_run transforms-base.u/present-run)))))(api.macros/defendpoint :delete "/:job-id" :- nil"Delete a transform job."@@ -242,7 +243,8 @@[:job-id ms/PositiveInt]]](log/info "Getting transform job" job-id)(-> (api/read-check (t2/select-one :model/TransformJob :id job-id))- (t2/hydrate :tag_ids :last_run)))+ (t2/hydrate :tag_ids :last_run)+ (update :last_run transforms-base.u/present-run)))(defn- add-next-run[{id :id :as job}]@@ -279,8 +281,8 @@(transforms-base.u/->date-field-filter-xf [:next_run :start_time] next-run-start-time)(transforms-base.u/->status-filter-xf [:last_run :status] last-run-statuses)(transforms-base.u/->tag-filter-xf [:tag_ids] tag-ids)- (map #(update % :last_run transforms-base.u/localize-run-timestamps))- (map #(update % :next_run transforms-base.u/localize-run-timestamps)))+ (map #(update % :last_run transforms-base.u/present-run))+ (map #(update % :next_run transforms-base.u/present-run)))(t2/hydrate jobs :tag_ids :last_run))))(def ^{:arglists '([request respond raise])} routesdiff --git a/test/metabase/run_tracking/core_test.clj b/test/metabase/run_tracking/core_test.cljnew file mode 100644index 00000000000..f7e3374bda0--- /dev/null+++ b/test/metabase/run_tracking/core_test.clj@@ -0,0 +1,120 @@+(ns metabase.run-tracking.core-test+ "Tests for the shared heartbeat + orphan-reaping primitives in [[metabase.run-tracking.core]]."+ (:require+ [clojure.test :refer :all]+ [metabase.run-tracking.core :as rt]+ [metabase.test :as mt]+ [metabase.test.fixtures :as fixtures]+ [toucan2.core :as t2])+ (:import+ (java.time OffsetDateTime ZoneOffset)))++(set! *warn-on-reflection* true)++(use-fixtures :once (fixtures/initialize :db :test-users))++(defn- minutes-ago ^OffsetDateTime [^long n]+ (.minusMinutes (OffsetDateTime/now ZoneOffset/UTC) n))++;;; --------------------------------------------- pure helpers ---------------------------------------------++(deftest ^:parallel unit->ms-test+ (testing "converts each supported unit to milliseconds"+ (is (= 30000 (rt/unit->ms 30 :second)))+ (is (= 300000 (rt/unit->ms 5 :minute)))+ (is (= 7200000 (rt/unit->ms 2 :hour))))+ (testing "unknown unit throws"+ (is (thrown? IllegalArgumentException (rt/unit->ms 1 :day)))))++(deftest ^:parallel detection-latency-ms-test+ (let [^OffsetDateTime reference-ts (OffsetDateTime/of 2026 1 1 0 0 0 0 ZoneOffset/UTC)+ timeout-ms (rt/unit->ms 10 :minute)+ deadline-ms (+ (inst-ms (.toInstant reference-ts)) timeout-ms)]+ (testing "zero at the deadline"+ (is (zero? (rt/detection-latency-ms reference-ts timeout-ms deadline-ms))))+ (testing "clamped to zero before the deadline"+ (is (zero? (rt/detection-latency-ms reference-ts timeout-ms (- deadline-ms 5000)))))+ (testing "milliseconds past the deadline"+ (is (= 7500+ (rt/detection-latency-ms reference-ts timeout-ms (+ deadline-ms 7500)))))))++;;; --------------------------------------------- reap-rows! -----------------------------------------------++(deftest reap-rows!-is-active-test+ (testing "is_active-based active guard: reaps and returns only the stale active row"+ (mt/with-premium-features #{:transforms-basic}+ ;; one active run per transform is allowed (unique index), so use a distinct transform per active run+ (mt/with-temp [:model/Transform {t1 :id} {}+ :model/Transform {t2 :id} {}+ :model/TransformRun {stale :id} {:transform_id t1 :status :started :is_active true+ :run_method :manual :start_time (minutes-ago 10)+ :last_heartbeat (minutes-ago 10)}+ :model/TransformRun {fresh :id} {:transform_id t2 :status :started :is_active true+ :run_method :manual :start_time (minutes-ago 10)+ :last_heartbeat (minutes-ago 1)}]+ (let [reaped (rt/reap-rows! {:model :model/TransformRun :active [:= :is_active true]+ :stale [:< :last_heartbeat (rt/cutoff 5 :minute)]+ :terminal {:status "timeout" :is_active nil :end_time :%now+ :message "reaped"}})]+ (is (= [stale] (mapv :id reaped)))+ (is (= :timeout (t2/select-one-fn :status :model/TransformRun :id stale)))+ (is (nil? (t2/select-one-fn :is_active :model/TransformRun :id stale)))+ (is (= "reaped" (t2/select-one-fn :message :model/TransformRun :id stale)))+ (is (= :started (t2/select-one-fn :status :model/TransformRun :id fresh))))+ (testing "second sweep is empty — the row is no longer active"+ (is (empty? (rt/reap-rows! {:model :model/TransformRun :active [:= :is_active true]+ :stale [:< :last_heartbeat (rt/cutoff 5 :minute)]+ :terminal {:status "timeout" :is_active nil :end_time :%now}}))))))))++(deftest reap-rows!-or-stale-test+ (testing "an :or stale predicate reaps on either branch (fresh heartbeat, old start_time)"+ (mt/with-premium-features #{:transforms-basic}+ (mt/with-temp [:model/Transform {tid :id} {}+ :model/TransformRun {old-start :id} {:transform_id tid :status :started :is_active true+ :run_method :manual :start_time (minutes-ago 120)+ :last_heartbeat (minutes-ago 1)}]+ (let [reaped (rt/reap-rows! {:model :model/TransformRun :active [:= :is_active true]+ :stale [:or [:< :last_heartbeat (rt/cutoff 5 :minute)]+ [:< :start_time (rt/cutoff 60 :minute)]]+ :terminal {:status "timeout" :is_active nil :end_time :%now}})]+ (is (= [old-start] (mapv :id reaped)))+ (is (= :timeout (t2/select-one-fn :status :model/TransformRun :id old-start))))))))++(deftest reap-rows!-status-active-test+ (testing "status-based active guard (TaskRun): guards on :status :started, transitions to :abandoned"+ (mt/with-temp [:model/TaskRun {stale :id} {:run_type :sync :entity_type :database :entity_id 1+ :status :started :started_at (minutes-ago 120)+ :updated_at (minutes-ago 120) :process_uuid "test"}+ :model/TaskRun {fresh :id} {:run_type :sync :entity_type :database :entity_id 1+ :status :started :started_at (minutes-ago 1)+ :updated_at (minutes-ago 1) :process_uuid "test"}]+ (let [reaped (rt/reap-rows! {:model :model/TaskRun :active [:= :status "started"]+ :stale [:< :updated_at (rt/cutoff 60 :minute)]+ :terminal {:status "abandoned"}})]+ (is (= [stale] (mapv :id reaped)))+ (is (= :abandoned (t2/select-one-fn :status :model/TaskRun :id stale)))+ (is (= :started (t2/select-one-fn :status :model/TaskRun :id fresh)))))))++;;; --------------------------------------------- heartbeat-ids! -------------------------------------------++(deftest heartbeat-ids!-test+ (mt/with-premium-features #{:transforms-basic}+ (mt/with-temp [:model/Transform {t1 :id} {}+ :model/Transform {t2 :id} {}+ :model/TransformRun {beat :id} {:transform_id t1 :status :started :is_active true+ :run_method :manual :start_time (minutes-ago 10)+ :last_heartbeat (minutes-ago 10)}+ :model/TransformRun {skip :id} {:transform_id t2 :status :started :is_active true+ :run_method :manual :start_time (minutes-ago 10)+ :last_heartbeat (minutes-ago 10)}+ ;; inactive run can share a transform with an active one (unique index is on active rows)+ :model/TransformRun {done :id} {:transform_id t1 :status :succeeded :is_active nil+ :run_method :manual :start_time (minutes-ago 10)+ :last_heartbeat (minutes-ago 10)}]+ (rt/heartbeat-ids! :model/TransformRun [:= :is_active true] :last_heartbeat [beat done])+ (let [recent? (fn [id] (.isAfter ^OffsetDateTime (t2/select-one-fn :last_heartbeat :model/TransformRun :id id)+ (minutes-ago 1)))]+ (is (recent? beat) "a passed, still-active id is stamped")+ (is (not (recent? skip)) "an id not in the list is left to go stale")+ (is (not (recent? done)) "an inactive id is not stamped (active guard)")+ (is (nil? (rt/heartbeat-ids! :model/TransformRun [:= :is_active true] :last_heartbeat [])) "empty id list is a no-op")))))diff --git a/test/metabase/transforms/heartbeat_test.clj b/test/metabase/transforms/heartbeat_test.cljnew file mode 100644index 00000000000..ef76ce2d143--- /dev/null+++ b/test/metabase/transforms/heartbeat_test.clj@@ -0,0 +1,177 @@+(ns metabase.transforms.heartbeat-test+ "Tests for transform-run and job-run heartbeats and orphan reaping."+ (:require+ [clojure.core.async :as a]+ [clojure.test :refer :all]+ [metabase.test :as mt]+ [metabase.test.fixtures :as fixtures]+ [metabase.transforms.canceling :as canceling]+ [metabase.transforms.models.job-run :as job-run]+ [metabase.transforms.models.transform-run :as transform-run]+ [toucan2.core :as t2])+ (:import+ (java.time OffsetDateTime ZoneOffset)))++(set! *warn-on-reflection* true)++(use-fixtures :once (fixtures/initialize :db :test-users))++(defn- minutes-ago ^OffsetDateTime [^long n]+ (.minusMinutes (OffsetDateTime/now ZoneOffset/UTC) n))++(defn- heartbeat ^OffsetDateTime [run-id]+ (t2/select-one-fn :last_heartbeat :model/TransformRun :id run-id))++(defn- recently-beaten? [run-id]+ (.isAfter (heartbeat run-id) (minutes-ago 1)))++(defn- job-heartbeat ^OffsetDateTime [run-id]+ (t2/select-one-fn :last_heartbeat :model/TransformJobRun :id run-id))++(defn- job-recently-beaten? [run-id]+ (.isAfter (job-heartbeat run-id) (minutes-ago 1)))++(deftest heartbeat-runs!-test+ (mt/with-premium-features #{:transforms-basic}+ ;; only one active run per transform is allowed (unique index): distinct transform per active run+ (mt/with-temp [:model/Transform {t1 :id} {}+ :model/Transform {t2 :id} {}+ :model/TransformRun {beat-id :id} {:transform_id t1+ :status :started+ :is_active true+ :run_method :manual+ :start_time (minutes-ago 10)+ :last_heartbeat (minutes-ago 10)}+ :model/TransformRun {other-id :id} {:transform_id t2+ :status :started+ :is_active true+ :run_method :manual+ :start_time (minutes-ago 10)+ :last_heartbeat (minutes-ago 10)}+ :model/TransformRun {done-id :id} {:transform_id t1+ :status :succeeded+ :is_active nil+ :run_method :manual+ :start_time (minutes-ago 10)+ :last_heartbeat (minutes-ago 10)}]+ (transform-run/heartbeat-runs! [beat-id done-id])+ (testing "only the passed run that is still active gets a fresh heartbeat"+ (is (recently-beaten? beat-id))+ (is (not (recently-beaten? other-id)) "a run not in the id list is left to go stale"))+ (testing "an inactive run is not stamped even when passed (is_active guard)"+ (is (not (recently-beaten? done-id))))+ (testing "empty id list is a no-op"+ (is (nil? (transform-run/heartbeat-runs! [])))))))++(deftest heartbeat-and-reconcile-runs!-beats-connections-test+ (testing "the per-node tick beats exactly the runs registered in the cancel/heartbeat registry"+ (mt/with-premium-features #{:transforms-basic}+ (mt/with-temp [:model/Transform {t1 :id} {}+ :model/Transform {t2 :id} {}+ :model/TransformRun {registered-id :id} {:transform_id t1+ :status :started+ :is_active true+ :run_method :manual+ :start_time (minutes-ago 10)+ :last_heartbeat (minutes-ago 10)}+ :model/TransformRun {unregistered-id :id} {:transform_id t2+ :status :started+ :is_active true+ :run_method :manual+ :start_time (minutes-ago 10)+ :last_heartbeat (minutes-ago 10)}]+ (canceling/chan-start-run! registered-id (a/promise-chan))+ (try+ (canceling/heartbeat-and-reconcile-runs!)+ (is (recently-beaten? registered-id) "the registered (executing) run is heartbeated")+ (is (not (recently-beaten? unregistered-id)) "a run not being executed here is left to go stale")+ (finally+ (canceling/chan-end-run! registered-id)))))))++(deftest reap-orphaned-runs!-test+ (mt/with-premium-features #{:transforms-basic :audit-app}+ (mt/with-prometheus-system! [_ _system]+ (mt/with-temp [:model/Transform {t1 :id} {}+ :model/Transform {t2 :id} {}+ :model/TransformRun {stale-id :id} {:transform_id t1+ :status :started+ :is_active true+ :run_method :manual+ :start_time (minutes-ago 10)+ :last_heartbeat (minutes-ago 10)}+ :model/TransformRun {fresh-id :id} {:transform_id t2+ :status :started+ :is_active true+ :run_method :manual+ :start_time (minutes-ago 10)+ :last_heartbeat (minutes-ago 1)}]+ (testing "reaps only the run whose heartbeat is older than the threshold"+ (let [reaped (transform-run/reap-orphaned-runs! 5)]+ (is (= [stale-id] (mapv :id reaped)))+ (is (= :timeout (t2/select-one-fn :status :model/TransformRun :id stale-id)))+ (is (= :started (t2/select-one-fn :status :model/TransformRun :id fresh-id)))+ (testing "reaped row carries the distinguishing message"+ (is (= "Timed out: no heartbeat"+ (t2/select-one-fn :message :model/TransformRun :id stale-id))))))+ (testing "a second sweep finds nothing (row already inactive)"+ (is (empty? (transform-run/reap-orphaned-runs! 5))))))))++(deftest start-run!-stamps-initial-heartbeat-test+ (testing "a freshly started run has an initial heartbeat"+ (mt/with-premium-features #{:transforms-basic}+ (mt/with-temp [:model/Transform {transform-id :id} {}]+ (let [{run-id :id} (transform-run/start-run! transform-id {:run_method "manual"})]+ (is (some? (heartbeat run-id)) "last_heartbeat is populated by the column default"))))))++;;; ------------------------------------------- Job-run heartbeat -------------------------------------------++(deftest job-heartbeat-runs!-test+ (mt/with-premium-features #{:transforms-basic}+ (mt/with-temp [:model/TransformJob {job-id :id} {:name "hb-job" :schedule "0 0 * * * ? *"}+ :model/TransformJobRun {beat-id :id} {:job_id job-id+ :status :started+ :is_active true+ :run_method :manual+ :last_heartbeat (minutes-ago 10)}+ :model/TransformJobRun {other-id :id} {:job_id job-id+ :status :started+ :is_active true+ :run_method :manual+ :last_heartbeat (minutes-ago 10)}+ :model/TransformJobRun {done-id :id} {:job_id job-id+ :status :succeeded+ :is_active nil+ :run_method :manual+ :last_heartbeat (minutes-ago 10)}]+ (job-run/heartbeat-runs! [beat-id done-id])+ (testing "only the passed run that is still active gets a fresh heartbeat"+ (is (job-recently-beaten? beat-id))+ (is (not (job-recently-beaten? other-id)) "a run not in the id list is left to go stale"))+ (testing "an inactive run is not stamped even when passed (is_active guard)"+ (is (not (job-recently-beaten? done-id))))+ (testing "empty id list is a no-op"+ (is (nil? (job-run/heartbeat-runs! [])))))))++(deftest job-reap-orphaned-runs!-test+ (mt/with-premium-features #{:transforms-basic}+ (mt/with-prometheus-system! [_ _system]+ (mt/with-temp [:model/TransformJob {job-id :id} {:name "hb-job" :schedule "0 0 * * * ? *"}+ :model/TransformJobRun {stale-id :id} {:job_id job-id+ :status :started+ :is_active true+ :run_method :manual+ :last_heartbeat (minutes-ago 10)}+ :model/TransformJobRun {fresh-id :id} {:job_id job-id+ :status :started+ :is_active true+ :run_method :manual+ :last_heartbeat (minutes-ago 1)}]+ (testing "reaps only the job run whose heartbeat is older than the threshold"+ (let [reaped (job-run/reap-orphaned-runs! 5)]+ (is (= [stale-id] (mapv :id reaped)))+ (is (= :timeout (t2/select-one-fn :status :model/TransformJobRun :id stale-id)))+ (is (= :started (t2/select-one-fn :status :model/TransformJobRun :id fresh-id)))+ (is (= "Timed out: no heartbeat"+ (t2/select-one-fn :message :model/TransformJobRun :id stale-id)))))+ (testing "a second sweep finds nothing (row already inactive)"+ (is (empty? (job-run/reap-orphaned-runs! 5))))))))diff --git a/test/metabase/transforms/jobs_test.clj b/test/metabase/transforms/jobs_test.cljindex 42692015e64..3795c6f6311 100644--- a/test/metabase/transforms/jobs_test.clj+++ b/test/metabase/transforms/jobs_test.clj@@ -142,7 +142,7 @@transforms.execute/execute! (fn [_ _](reset! run-called? true))transforms.job-run/add-run-activity! (constantly nil)]- (#'jobs/run-transform! run-id :scheduled nil query-transform)+ (#'jobs/run-transform! run-id :scheduled nil (promise) query-transform)(is (empty? (filter (comp #{:warn} :level) @logged-messages))"Should not log warnings when feature is enabled")(is @run-called?@@ -157,7 +157,7 @@(mt/with-dynamic-fn-redefs [log/log* (fn [_ level _ message](swap! logged-messages conj {:level level :message message}))transform-run/running-run-for-transform-id (constantly nil)]- (#'jobs/run-transform! run-id :scheduled nil query-transform)+ (#'jobs/run-transform! run-id :scheduled nil (promise) query-transform)(is (= 1 (count @logged-messages))"Should log exactly one warning")(is (= :warn (:level (first @logged-messages)))@@ -179,7 +179,7 @@transforms.execute/execute! (fn [_ _](reset! run-called? true))transforms.job-run/add-run-activity! (constantly nil)]- (#'jobs/run-transform! run-id :scheduled nil query-transform)+ (#'jobs/run-transform! run-id :scheduled nil (promise) query-transform)(is (empty? (filter (comp #{:warn} :level) @logged-messages))"Should not log warnings when feature is enabled")(is @run-called?@@ -209,7 +209,7 @@transform-run/running-run-for-transform-id (constantly nil)transforms.execute/execute! (fn [_ _] (reset! run-called? true))transforms.job-run/add-run-activity! (constantly nil)]- (#'jobs/run-transform! 200 :scheduled nil transform)+ (#'jobs/run-transform! 200 :scheduled nil (promise) transform)(is (false? @run-called?)"execute! must not be called when the meter is locked")(is (some #(re-matches #".*Skip running transform 7 due to locked meter.*"@@ -224,7 +224,7 @@(mt/with-dynamic-fn-redefs [transform-run/running-run-for-transform-id (constantly nil)transforms.execute/execute! (fn [_ _] (reset! run-called? true))transforms.job-run/add-run-activity! (constantly nil)]- (#'jobs/run-transform! 201 :scheduled nil transform)+ (#'jobs/run-transform! 201 :scheduled nil (promise) transform)(is (true? @run-called?)))))))(testing "non-metered transform (transform-metered-as → nil) is never blocked by lock state";; Override the outer mock with one that returns nil for every source-type.@@ -236,7 +236,7 @@(mt/with-dynamic-fn-redefs [transform-run/running-run-for-transform-id (constantly nil)transforms.execute/execute! (fn [_ _] (reset! run-called? true))transforms.job-run/add-run-activity! (constantly nil)]- (#'jobs/run-transform! 202 :scheduled nil transform)+ (#'jobs/run-transform! 202 :scheduled nil (promise) transform)(is (true? @run-called?)"Non-metered transforms are not gated by lock state"))))))))@@ -286,52 +286,25 @@:message string?}(t2/select-one :model/TransformJobRun :id @run-id-atom))))))))))))))-(deftest job-run-boom-manual-no-email-test+(deftest reap-orphaned-runs-test(mt/with-premium-features #{:transforms-basic}- (mt/test-drivers (mt/normal-drivers-with-feature :transforms/table)- (mt/dataset transforms-dataset/transforms-test- (mt/with-model-cleanup [:model/Notification- :model/TransformJobRun]- (mt/with-fake-inbox- (notification.seed/seed-notification!)- (let [mp (mt/metadata-provider)- table (t2/select-one :model/Table (mt/id :transforms_products))- ;; generate sql for different dbs- sql (-> (lib/query mp (lib.metadata/table mp (mt/id :transforms_products)))- (lib/with-fields [(lib.metadata/field mp (mt/id :transforms_products :name))])- (lib/limit 10)- qp.compile/compile- :query)]- (with-transform-cleanup! [target0 {:type "table"- :schema (:schema table)- :name "t0"}]- (mt/with-temp [:model/TransformTag tag {:name "test-tag"}- :model/TransformJob job {:name "test-job"- :schedule "0 0 * * * ? *"}- :model/TransformJobTransformTag _ {:job_id (:id job)- :tag_id (:id tag)- :position 0}- ;; independent transform- :model/Transform t0 {:name "transform0"- :source {:type :query- :query (lib/native-query mp sql)}- :creator_id (mt/user->id :crowberto)- :target target0}- :model/TransformTransformTag _tag0 {:transform_id (:id t0)- :tag_id (:id tag)- :position 0}]- (let [run-id-atom (atom nil)]- (mt/with-dynamic-fn-redefs [jobs/run-transforms! (fn [run-id & _]- (reset! run-id-atom run-id)- (throw (ex-info "Uncaught error" {})))]- (try- (jobs/run-job! (:id job) {:run-method :manual})- (catch clojure.lang.ExceptionInfo _))- (is (some? @run-id-atom))- (is (=? {:status :failed- :message string?}- (t2/select-one :model/TransformJobRun :id @run-id-atom)))- (is (zero? (count @mt/inbox))))))))))))))+ (mt/with-model-cleanup [:model/TransformJobRun]+ (mt/with-temp [:model/TransformJob job {:name "stalled-cron-job"+ :schedule "0 0 * * * ? *"}]+ (let [run (t2/insert-returning-instance! :model/TransformJobRun+ {:job_id (:id job)+ :run_method :cron+ :status :started+ :is_active true})]+ ;; push last_heartbeat past the heartbeat-staleness threshold so the reaper fires+ (t2/update! :model/TransformJobRun+ :id (:id run)+ {:last_heartbeat #t "2000-01-01T00:00:00Z"})+ (#'jobs/reap-orphaned-runs!)+ (is (=? {:status :timeout+ :is_active nil+ :message "Timed out: no heartbeat"}+ (t2/select-one :model/TransformJobRun :id (:id run)))))))))(deftest job-run-with-tranform-run-failure-test(mt/with-premium-features #{:transforms-basic}@@ -515,7 +488,7 @@;; only pulled-in deps are offered for gating(is (= #{1} (set dep-ids)))#{1})- jobs/run-transform! (fn [_ _ _ t] (swap! ran conj (:id t)))]+ jobs/run-transform! (fn [_ _ _ _ t] (swap! ran conj (:id t)))](is (= {::jobs/status :succeeded}(jobs/run-transforms! 0 #{2 3} {:run-method :cron})))(is (= #{2 3} @ran) "transform 1 (fresh dep) was skipped; 2 and 3 ran")))@@ -523,7 +496,7 @@(reset! ran #{})(with-redefs [jobs/get-plan (fn [_] {:order plan :deps deps})freshness/fresh-dep-ids (fn [& _] (throw (ex-info "must not gate when disabled" {})))- jobs/run-transform! (fn [_ _ _ t] (swap! ran conj (:id t)))]+ jobs/run-transform! (fn [_ _ _ _ t] (swap! ran conj (:id t)))](is (= {::jobs/status :succeeded}(jobs/run-transforms! 0 #{2 3} {:run-method :manual :skip-fresh-deps? false})))(is (= #{1 2 3} @ran) "with skipping disabled, the dep runs too"))))@@ -531,7 +504,7 @@(let [ran (atom #{})](with-redefs [jobs/get-plan (fn [_] {:order [{:id 1}] :deps {1 #{}}})freshness/fresh-dep-ids (fn [_now _dep-ids] #{1})- jobs/run-transform! (fn [_ _ _ t] (swap! ran conj (:id t)))]+ jobs/run-transform! (fn [_ _ _ _ t] (swap! ran conj (:id t)))](is (= {::jobs/status :succeeded}(jobs/run-transforms! 0 #{} {:run-method :cron})))(is (= #{} @ran)))))))@@ -616,7 +589,7 @@barrier (CyclicBarrier. 4)](mt/with-temporary-setting-values [transforms.settings/transform-run-job-sql-concurrency 4](with-redefs [jobs/get-plan (fn [_] {:order plan :deps deps})- jobs/run-transform! (fn [_ _ _ _]+ jobs/run-transform! (fn [_ _ _ _ _](.await barrier 5 TimeUnit/SECONDS))](is (= {::jobs/status :succeeded}(jobs/run-transforms! 0 #{1 2 3 4} {:run-method :manual}))@@ -627,7 +600,7 @@order (atom [])](mt/with-temporary-setting-values [transforms.settings/transform-run-job-sql-concurrency 4](with-redefs [jobs/get-plan (fn [_] {:order plan :deps deps})- jobs/run-transform! (fn [_ _ _ transform]+ jobs/run-transform! (fn [_ _ _ _ transform](when (= 1 (:id transform))(Thread/sleep 100))(swap! order conj (:id transform)))]@@ -638,7 +611,7 @@deps {1 #{} 2 #{1} 3 #{2}}](mt/with-temporary-setting-values [transforms.settings/transform-run-job-sql-concurrency 4](with-redefs [jobs/get-plan (fn [_] {:order plan :deps deps})- jobs/run-transform! (fn [_ _ _ transform]+ jobs/run-transform! (fn [_ _ _ _ transform](when (= 1 (:id transform))(throw (ex-info "boom" {}))))](let [result (jobs/run-transforms! 0 #{1 2 3} {:run-method :manual})]@@ -655,7 +628,7 @@max-live (atom 0)](mt/with-temporary-setting-values [transforms.settings/transform-run-job-sql-concurrency 2](with-redefs [jobs/get-plan (fn [_] {:order plan :deps deps})- jobs/run-transform! (fn [_ _ _ _]+ jobs/run-transform! (fn [_ _ _ _ _](let [n (swap! live inc)](swap! max-live max n))(.await partner-up 5 TimeUnit/SECONDS)@@ -670,7 +643,7 @@max-live (atom 0)](mt/with-temporary-setting-values [transforms.settings/transform-run-job-sql-concurrency 4](with-redefs [jobs/get-plan (fn [_] {:order plan :deps deps})- jobs/run-transform! (fn [_ _ _ _]+ jobs/run-transform! (fn [_ _ _ _ _](let [n (swap! live inc)](swap! max-live max n));; A short sleep gives any (hypothetical) parallel@@ -690,7 +663,7 @@max-py (atom 0)](mt/with-temporary-setting-values [transforms.settings/transform-run-job-sql-concurrency 3](with-redefs [jobs/get-plan (fn [_] {:order plan :deps deps})- jobs/run-transform! (fn [_ _ _ transform]+ jobs/run-transform! (fn [_ _ _ _ transform](if (= :python (-> transform :source :type))(do (let [n (swap! py-live inc)](swap! max-py max n))diff --git a/test/metabase/transforms/models/timeout_util_test.clj b/test/metabase/transforms/models/timeout_util_test.cljdeleted file mode 100644index 57b6afe66dc..00000000000--- a/test/metabase/transforms/models/timeout_util_test.clj+++ /dev/null@@ -1,28 +0,0 @@-(ns metabase.transforms.models.timeout-util-test- (:require- [clojure.test :refer :all]- [metabase.transforms.models.timeout-util :as timeout-util])- (:import- (java.time Duration OffsetDateTime ZoneOffset)))--(set! *warn-on-reflection* true)--(deftest ^:parallel unit->duration-test- (testing "produces an exact Duration for each supported unit"- (is (= (Duration/ofSeconds 30) (timeout-util/unit->duration 30 :second)))- (is (= (Duration/ofMinutes 5) (timeout-util/unit->duration 5 :minute)))- (is (= (Duration/ofHours 2) (timeout-util/unit->duration 2 :hour))))- (testing "unknown unit throws"- (is (thrown? IllegalArgumentException (timeout-util/unit->duration 1 :day)))))--(deftest ^:parallel detection-latency-ms-test- (let [^OffsetDateTime reference-ts (OffsetDateTime/of 2026 1 1 0 0 0 0 ZoneOffset/UTC)- timeout-dur (Duration/ofMinutes 10)- deadline (.plus (.toInstant reference-ts) timeout-dur)]- (testing "zero at the deadline"- (is (zero? (timeout-util/detection-latency-ms reference-ts timeout-dur deadline))))- (testing "clamped to zero before the deadline"- (is (zero? (timeout-util/detection-latency-ms reference-ts timeout-dur (.minusMillis deadline 5000)))))- (testing "milliseconds past the deadline"- (is (= 7500- (timeout-util/detection-latency-ms reference-ts timeout-dur (.plusMillis deadline 7500)))))))diff --git a/test/metabase/transforms/timeout_test.clj b/test/metabase/transforms/timeout_test.cljindex 357caa92463..428de6039f3 100644--- a/test/metabase/transforms/timeout_test.clj+++ b/test/metabase/transforms/timeout_test.clj@@ -1,7 +1,5 @@(ns metabase.transforms.timeout-test- "Tests for observability of the transform timeout sweepers- ([[metabase.transforms.models.transform-run/timeout-old-runs!]] and- [[metabase.transforms.models.job-run/timeout-old-runs!]])."+ "Tests for observability of the transform-run timeout sweeper and the job-run reaper."(:require[clojure.test :refer :all][metabase.analytics-interface.core :as analytics]@@ -29,16 +27,18 @@(prometheus/clear! :metabase-transforms/timeout-detection-latency-ms)(mt/with-temp [:model/Transform {old-transform-id :id} {}:model/Transform {fresh-transform-id :id} {}- :model/TransformRun {old-run-id :id} {:transform_id old-transform-id- :status :started- :is_active true- :run_method :manual- :start_time (minutes-ago 30)}- :model/TransformRun {fresh-run-id :id} {:transform_id fresh-transform-id- :status :started- :is_active true- :run_method :manual- :start_time (minutes-ago 1)}]+ :model/TransformRun {old-run-id :id} {:transform_id old-transform-id+ :status :started+ :is_active true+ :run_method :manual+ :start_time (minutes-ago 30)+ :last_heartbeat (minutes-ago 30)}+ :model/TransformRun {fresh-run-id :id} {:transform_id fresh-transform-id+ :status :started+ :is_active true+ :run_method :manual+ :start_time (minutes-ago 1)+ :last_heartbeat (minutes-ago 1)}](let [timed-out (transform-run/timeout-old-runs! 5 :minute)](testing "only the stale run is timed out"(is (= 1 (count timed-out)))@@ -68,11 +68,12 @@(mt/with-dynamic-fn-redefs [analytics/inc! (fn [metric & _] (swap! inc-calls conj metric))analytics/observe! (fn [metric & _] (swap! observe-calls conj metric))](mt/with-temp [:model/Transform {transform-id :id} {}- :model/TransformRun _ {:transform_id transform-id- :status :started- :is_active true- :run_method :manual- :start_time (minutes-ago 1)}]+ :model/TransformRun _ {:transform_id transform-id+ :status :started+ :is_active true+ :run_method :manual+ :start_time (minutes-ago 1)+ :last_heartbeat (minutes-ago 1)}](is (empty? (transform-run/timeout-old-runs! 5 :minute)))(is (not-any? #{:metabase-transforms/timeouts-total} @inc-calls)"sweeper did not increment :metabase-transforms/timeouts-total")@@ -81,11 +82,12 @@(testing "single-run timeout-run! bumps counter and publishes audit event"(prometheus/clear! :metabase-transforms/timeouts-total)(mt/with-temp [:model/Transform {transform-id :id} {}- :model/TransformRun {run-id :id} {:transform_id transform-id- :status :started- :is_active true- :run_method :manual- :start_time (minutes-ago 1)}]+ :model/TransformRun {run-id :id} {:transform_id transform-id+ :status :started+ :is_active true+ :run_method :manual+ :start_time (minutes-ago 1)+ :last_heartbeat (minutes-ago 1)}](transform-run/timeout-run! run-id)(is (= :timeout (t2/select-one-fn :status :model/TransformRun :id run-id)))(is (== 1 (mt/metric-value system@@ -95,22 +97,23 @@(is (some? entry))(is (= run-id (:model_id entry)))(is (= "timeout" (some-> entry :details :status))))))- (testing "job-run sweeper bumps {type=job} counter and observes histogram per timed-out job run"+ (testing "job-run reaper bumps {type=job} counter and observes histogram per reaped job run"(prometheus/clear! :metabase-transforms/timeouts-total)(prometheus/clear! :metabase-transforms/timeout-detection-latency-ms)(mt/with-temp [:model/TransformJob {job-id :id} {:name "timeout-test-job":schedule "0 0 * * * ? *"}- :model/TransformJobRun {old-run-id :id} {:job_id job-id- :status :started- :is_active true- :run_method :manual- :updated_at (minutes-ago 30)}- :model/TransformJobRun {fresh-run-id :id} {:job_id job-id- :status :started- :is_active true- :run_method :manual- :updated_at (minutes-ago 1)}]- (let [timed-out (transforms.job-run/timeout-old-runs! 5 :minute)]+ :model/TransformJobRun {old-run-id :id} {:job_id job-id+ :status :started+ :is_active true+ :run_method :manual+ :updated_at (minutes-ago 30)+ :last_heartbeat (minutes-ago 30)}+ :model/TransformJobRun {fresh-run-id :id} {:job_id job-id+ :status :started+ :is_active true+ :run_method :manual+ :last_heartbeat (minutes-ago 1)}]+ (let [timed-out (transforms.job-run/reap-orphaned-runs! 5)](is (= 1 (count timed-out)))(is (= :timeout (t2/select-one-fn :status :model/TransformJobRun :id old-run-id)))(is (= :started (t2/select-one-fn :status :model/TransformJobRun :id fresh-run-id))))