Skip to content

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

GDGT-3331: record the status of a subscription run after all of its channels (#84656)

Bartosz Rybacki9506a20b2f27
diff --git a/src/metabase/notification/send.clj b/src/metabase/notification/send.clj
index 1f8739210ec..8c679839175 100644
--- a/src/metabase/notification/send.clj
+++ b/src/metabase/notification/send.clj
@@ -288,9 +288,7 @@
;; observed here so a send that throws is counted too
(analytics/observe! :metabase-notification/send-duration-ms {:payload-type payload_type} (duration-ms-fn))
(when-let [total-time (since-trigger-ms notification-info)]
- (analytics/observe! :metabase-notification/total-duration-ms {:payload-type payload_type} total-time))
- (when-let [run-id (task-history/current-run-id)]
- (task-history/complete-task-run! run-id))))
+ (analytics/observe! :metabase-notification/total-duration-ms {:payload-type payload_type} total-time))))
nil)))
(defn- cron->next-execution-times
@@ -371,7 +369,7 @@
(defprotocol NotificationQueueProtocol
"Protocol for notification queue implementations."
- (put-notification! [this notification] "Add a notification to the queue. If a notification with the same id is already in the queue, replace it.")
+ (put-notification! [this notification] "Add a notification to the queue. If a notification with the same id is already in the queue, replace it and return the replaced one.")
(take-notification-with-timeout! [this timeout-ms] "Take the next notification from the queue, returning nil if timeout is reached.")
(queue-size [this] "Get the current size of the queue."))
@@ -389,9 +387,10 @@
(try
(when-not (.containsKey id->notification id)
(.offer items-list item))
- (.put id->notification id notification)
- ;; Signal that a notification is available
- (.signal not-empty-cond)
+ (let [replaced (.put id->notification id notification)]
+ ;; Signal that a notification is available
+ (.signal not-empty-cond)
+ replaced)
(finally
(.unlock queue-lock)))))
@@ -447,6 +446,26 @@
[]
(BlockingQueue. (ArrayBlockingQueue. default-blocking-queue-size)))
+(defn- queue-notification!
+ "Put `notification` in `queue`, with the log context and the current task run in its metadata."
+ [queue notification]
+ (let [tagged (-> notification
+ log/with-context-meta
+ task-history/track-run-work!)
+ replaced (try
+ (put-notification! queue tagged)
+ (catch Throwable e
+ ;; `tagged` is not in the queue, so it will never run
+ (task-history/end-run-work! tagged)
+ (throw e)))]
+ ;; the replaced map will never run. Release it outside the queue lock, because the last piece of work of a run
+ ;; writes the run status. A failure there belongs to the run of the replaced map, not to this send, which is queued.
+ (when replaced
+ (try
+ (task-history/end-run-work! replaced)
+ (catch Throwable e
+ (log/warn e "Could not end the task run work of a replaced notification"))))))
+
(defn- create-notification-dispatcher
"Create a thread pool for sending notifications.
There can only be one notification with the same id in the queue.
@@ -490,9 +509,7 @@
(if-not (.get shutdown-flag)
(do
(ensure-enough-workers!)
- (put-notification! queue (-> notification
- log/with-context-meta
- task-history/with-run-id-meta))
+ (queue-notification! queue notification)
::ok)
(do
(log/infof "Rejecting notification with id %d as the workers are being shutdown" (:id notification))
diff --git a/src/metabase/task_history/core.clj b/src/metabase/task_history/core.clj
index 18d22164d74..04e28a73316 100644
--- a/src/metabase/task_history/core.clj
+++ b/src/metabase/task_history/core.clj
@@ -11,8 +11,8 @@
[metabase.task-history.models.task-history
with-task-history]
[metabase.task-history.models.task-run
- complete-task-run!
current-run-id
+ end-run-work!
+ track-run-work!
with-restored-run-id
- with-run-id-meta
with-task-run])
diff --git a/src/metabase/task_history/models/task_run.clj b/src/metabase/task_history/models/task_run.clj
index 50c72f9a96e..b5e4c2ce030 100644
--- a/src/metabase/task_history/models/task_run.clj
+++ b/src/metabase/task_history/models/task_run.clj
@@ -7,6 +7,7 @@
[metabase.permissions.core :as perms]
[metabase.premium-features.core :as premium-features]
[metabase.task-history.db :as task-history.db]
+ [metabase.util.log :as log]
[metabase.util.malli :as mu]
[metabase.util.malli.registry :as mr]
[metabase.util.malli.schema :as ms]
@@ -64,26 +65,40 @@
:status mi/transform-keyword})
#_{:clj-kondo/ignore [:metabase/discourage-dynamic-vars]}
-(def ^:dynamic *run-id*
- "The ID of the current task run. Set by [[with-task-run]]."
+(def ^:dynamic *run*
+ "The current task run, set by [[with-task-run]] and [[with-restored-run-id]]: its `:id`, and `:auto-complete?`, true
+ when [[with-task-run]] completes the run after its body."
nil)
(defn current-run-id
- "Returns the current task run ID, or nil if not inside a [[with-task-run]] block."
+ "Returns the current task run ID, or nil when neither [[with-task-run]] nor [[with-restored-run-id]] set a run."
[]
- *run-id*)
-
-(defn with-run-id-meta
- "Given a map, returns the map with `*run-id*` attached to metadata.
- Used for propagation of run context across threads (e.g., async notification dispatch)."
- [m]
- (vary-meta m assoc ::run-id *run-id*))
-
-(defmacro with-restored-run-id
- "Given a map presumably containing metadata from [[with-run-id-meta]], restores `*run-id*` and executes body."
- [m & body]
- `(binding [*run-id* (::run-id (meta ~m))]
- ~@body))
+ (:id *run*))
+
+(defonce ^:private run-id->pending-work
+ ;; The number of pieces of work of each run with `:auto-complete false` that have not ended yet: the body of
+ ;; [[with-task-run]], and each map tagged with [[track-run-work!]]. A run is in this map only while it has such work.
+ ;; The queue that holds the work is in this process too, so the count does not need to be in the app DB.
+ (atom {}))
+
+(defn- add-pending-work!
+ [run-id]
+ (swap! run-id->pending-work update run-id (fnil inc 0)))
+
+(defn- end-pending-work!
+ "Count one piece of work of the run `run-id` as ended. Returns `:last` when it was the last one, `:more` when the run
+ has other work that has not ended, and `:unknown` when the run has no count."
+ [run-id]
+ (let [[before after] (swap-vals! run-id->pending-work
+ (fn [counts]
+ (let [n (dec (get counts run-id 0))]
+ (if (pos? n)
+ (assoc counts run-id n)
+ (dissoc counts run-id)))))]
+ (cond
+ (not (contains? before run-id)) :unknown
+ (contains? after run-id) :more
+ :else :last)))
(mr/def ::TaskRunInfo
[:map {:closed true}
@@ -106,9 +121,9 @@
:status :started
:process_uuid config/local-process-uuid}))
-(mu/defn complete-task-run!
- "Mark a task run as complete, deriving status from child tasks.
- Must be called manually for async flows, or automatically via [[with-task-run]].
+(mu/defn- complete-task-run!
+ "Mark a task run as complete, deriving status from child tasks. [[with-task-run]] calls it after its body; for
+ `:auto-complete false` runs, [[task-run-work-done!]] calls it after the last piece of work.
Idempotent - only completes if status is still :started."
[run-id :- ms/PositiveInt]
(let [task-statuses (task-history.db/task-statuses-for-run run-id)
@@ -117,6 +132,73 @@
:failed)]
(task-history.db/finish-started-task-run! run-id status (t/instant))))
+(mu/defn- task-run-work-done!
+ "Call when one piece of work of the `:auto-complete false` run `run-id` ends: [[with-task-run]] after its body, and
+ [[end-run-work!]] for a map from [[track-run-work!]]. The run stays started while it has work that has not
+ ended, and the call for its last piece of work completes it with [[complete-task-run!]]. At that point every task of
+ the run has ended."
+ [run-id :- ms/PositiveInt]
+ (case (end-pending-work! run-id)
+ :more nil
+ :last (complete-task-run! run-id)
+ :unknown (do
+ (log/warnf "Task run %d: a piece of work ended that was not counted, or that ended twice" run-id)
+ (complete-task-run! run-id))))
+
+(defn track-run-work!
+ "Returns the map `m` with the current run attached to its metadata, so that the run can be restored on another thread
+ with [[with-restored-run-id]] (e.g., async notification dispatch).
+
+ When the current run has `:auto-complete false`, the map is also one more piece of work of that run: the run stays
+ started until [[end-run-work!]] is called for the map, exactly once. [[with-restored-run-id]] calls it after the
+ work."
+ [m]
+ (let [{:keys [id auto-complete?]} *run*
+ pending-work? (boolean (and id (not auto-complete?)))]
+ (when pending-work?
+ (add-pending-work! id))
+ (vary-meta m assoc ::run-id id ::pending-work? pending-work?)))
+
+(defn end-run-work!
+ "Call once for the map `m` from [[track-run-work!]]: after its work ran, or when it will never run, for example
+ because a newer map replaced it in a queue. Does nothing when `m` is not a piece of work of its run."
+ [m]
+ (let [{::keys [run-id pending-work?]} (meta m)]
+ (when pending-work?
+ (task-run-work-done! run-id))))
+
+(defmacro with-restored-run-id
+ "Given a map presumably containing metadata from [[track-run-work!]], restores the current run and executes body,
+ then calls [[end-run-work!]] for the map. The restored run counts the work that the body tags with
+ [[track-run-work!]] only when the run counted the map itself."
+ [m & body]
+ `(let [m# ~m
+ {run-id# ::run-id
+ pending-work?# ::pending-work?} (meta m#)]
+ (binding [*run* (when run-id#
+ {:id run-id# :auto-complete? (not pending-work?#)})]
+ (try
+ ~@body
+ (finally
+ (end-run-work! m#))))))
+
+(defn do-with-task-run
+ "Implementation of [[with-task-run]]."
+ [run-info thunk]
+ (if (or *run* (nil? run-info))
+ (thunk)
+ (let [auto-complete (boolean (get run-info :auto-complete true))
+ run-id (create-task-run! run-info)]
+ (when-not auto-complete
+ (add-pending-work! run-id))
+ (binding [*run* {:id run-id :auto-complete? auto-complete}]
+ (try
+ (thunk)
+ (finally
+ (if auto-complete
+ (complete-task-run! run-id)
+ (task-run-work-done! run-id))))))))
+
(defmacro with-task-run
"Wrap a root flow to group all tasks under a single run.
`run-info` should contain :run_type, :entity_type, :entity_id.
@@ -124,20 +206,9 @@
If `run-info` is nil or already inside a task run, just executes body without
creating a new task run (prevents nesting).
- For async flows (e.g., async notifications), use :auto-complete false and
- call [[complete-task-run!]] manually when all async work is done."
+ After the body, it completes the run with [[complete-task-run!]]. For async flows (e.g., async notifications), use
+ :auto-complete false: then the body is one piece of work of the run, and each map that carries the run to another
+ thread with [[track-run-work!]] is one more. The run completes after the last of them ends."
{:style/indent 1}
[run-info & body]
- `(if (or *run-id* (nil? ~run-info))
- (do ~@body)
- (let [info# ~run-info
- auto-complete# (get info# :auto-complete true)
- run-id# (create-task-run! info#)]
- (binding [*run-id* run-id#]
- (if auto-complete#
- (try
- ~@body
- (finally
- (complete-task-run! run-id#)))
- ;; Async: caller is responsible for calling complete-task-run!
- (do ~@body))))))
+ `(do-with-task-run ~run-info (fn [] ~@body)))
diff --git a/test/metabase/notification/send_test.clj b/test/metabase/notification/send_test.clj
index c23965ffc5a..74985efb640 100644
--- a/test/metabase/notification/send_test.clj
+++ b/test/metabase/notification/send_test.clj
@@ -14,6 +14,8 @@
[metabase.notification.send :as notification.send]
[metabase.notification.settings :as notification.settings]
[metabase.notification.test-util :as notification.tu]
+ [metabase.task-history.core :as task-history]
+ [metabase.task-history.models.task-run :as task-run]
[metabase.test :as mt]
[metabase.test.fixtures :as fixtures]
[metabase.test.util :as tu]
@@ -726,6 +728,64 @@
(for [_ (range 2)]
(take-notification! queue)))))))
+(defn- with-async-run!
+ "Run `thunk` in a new task run with `:auto-complete false` that has one successful task, and return the run id."
+ [thunk]
+ (task-history/with-task-run {:run_type :subscription
+ :entity_type :dashboard
+ :entity_id 1
+ :auto-complete false}
+ (task-history/with-task-history {:task "job"}
+ :done)
+ (thunk)
+ (task-history/current-run-id)))
+
+(deftest queue-notification-releases-replaced-work-test
+ (testing "a queued notification that a newer one replaces no longer keeps its run started (GDGT-3331)"
+ (mt/with-model-cleanup [:model/TaskRun :model/TaskHistory]
+ (let [queue (#'notification.send/create-dedup-priority-queue)
+ run-id (with-async-run! (fn []
+ (#'notification.send/queue-notification! queue {:id 1 :payload_type :notification/testing :test-value "A"})
+ (#'notification.send/queue-notification! queue {:id 1 :payload_type :notification/testing :test-value "B"})))
+ run-status #(t2/select-one-fn :status :model/TaskRun :id run-id)]
+ (is (= :started (run-status)) "B is still in the queue")
+ (let [b (take-notification! queue)]
+ (is (= "B" (:test-value b)))
+ (task-history/with-restored-run-id b
+ :sent))
+ (is (= :success (run-status)) "B was the last piece of work")))))
+
+(deftest queue-notification-release-failure-test
+ (testing "when the run of a replaced notification cannot be completed, the new notification stays queued and counted (GDGT-3331)"
+ (mt/with-model-cleanup [:model/TaskRun :model/TaskHistory]
+ (let [queue (#'notification.send/create-dedup-priority-queue)
+ run-x (with-async-run! #(#'notification.send/queue-notification!
+ queue {:id 1 :payload_type :notification/testing :test-value "A"}))
+ complete! (mt/original-fn #'task-run/complete-task-run!)
+ run-y (mt/with-dynamic-fn-redefs [task-run/complete-task-run! (fn [run-id]
+ (if (= run-id run-x)
+ (throw (ex-info "app DB is down" {}))
+ (complete! run-id)))]
+ (with-async-run! #(#'notification.send/queue-notification!
+ queue {:id 1 :payload_type :notification/testing :test-value "B"})))
+ run-status #(t2/select-one-fn :status :model/TaskRun :id %)]
+ (is (= :started (run-status run-y)) "B, of run Y, is still in the queue")
+ (is (= "B" (:test-value (take-notification! queue))))
+ (is (= :started (run-status run-x)) "run X could not be completed; the reaper marks it abandoned later")))))
+
+(deftest queue-notification-put-failure-test
+ (testing "a notification that cannot be queued does not keep its run started (GDGT-3331)"
+ (mt/with-model-cleanup [:model/TaskRun :model/TaskHistory]
+ (let [queue (reify notification.send/NotificationQueueProtocol
+ (put-notification! [_ _] (throw (ex-info "queue is full" {})))
+ (take-notification-with-timeout! [_ _] nil)
+ (queue-size [_] 0))
+ run-id (with-async-run! #(is (thrown-with-msg? clojure.lang.ExceptionInfo #"queue is full"
+ (#'notification.send/queue-notification!
+ queue {:id 1 :payload_type :notification/testing}))))]
+ (is (= :success (t2/select-one-fn :status :model/TaskRun :id run-id))
+ "the body was the only piece of work left")))))
+
(deftest notification-dedup-priority-test
(let [queue (#'notification.send/create-dedup-priority-queue)]
(testing "put and take operations work correctly"
@@ -734,8 +794,10 @@
(take-notification! queue))))
(testing "notifications with same ID are replaced in queue"
(let [queue (#'notification.send/create-dedup-priority-queue)]
- (#'notification.send/put-notification! queue {:id 1 :payload_type :notification/testing :test-value "A"})
- (#'notification.send/put-notification! queue {:id 1 :payload_type :notification/testing :test-value "B"})
+ (is (nil? (#'notification.send/put-notification! queue {:id 1 :payload_type :notification/testing :test-value "A"})))
+ (is (= {:id 1 :payload_type :notification/testing :test-value "A"}
+ (#'notification.send/put-notification! queue {:id 1 :payload_type :notification/testing :test-value "B"}))
+ "put returns the notification that it replaced")
(is (= {:id 1 :payload_type :notification/testing :test-value "B"}
(take-notification! queue)))))
(testing "multiple notifications are processed in order"
diff --git a/test/metabase/notification/task/send_test.clj b/test/metabase/notification/task/send_test.clj
index a254a6b245c..f37b3210057 100644
--- a/test/metabase/notification/task/send_test.clj
+++ b/test/metabase/notification/task/send_test.clj
@@ -4,6 +4,8 @@
[metabase.channel.core :as channel]
[metabase.driver :as driver]
[metabase.notification.models :as models.notification]
+ [metabase.notification.payload.execute :as notification.execute]
+ [metabase.notification.send :as notification.send]
[metabase.notification.task.send :as task.notification]
[metabase.notification.task.send-trigger :as notification.task.send-trigger]
[metabase.notification.test-util :as notification.tu]
@@ -53,6 +55,81 @@
(u/poll {:thunk #(latest-task-history-entry "notification-trigger")
:done? (fn [task] (= [(:id noti)] (get-in task [:task_details :notification_ids])))}))))))))))))
+(deftest send-notification-job-completes-run-test
+ (testing "the job records the run of a scheduled alert as success after its `notification-trigger` row ends (GDGT-3331)"
+ ;; with the testing setup the send runs on the job's thread, so it ends while the `notification-trigger` row is
+ ;; still started, and only the job's own call can set the final status
+ (mt/with-model-cleanup [:model/TaskRun :model/TaskHistory]
+ (notification.tu/with-notification-testing-setup!
+ (notification.tu/with-card-notification
+ [notification {:subscriptions [{:type :notification-subscription/cron
+ :cron_schedule every-second}]
+ :handlers [{:channel_type :channel/email
+ :recipients [{:type :notification-recipient/user
+ :user_id (mt/user->id :crowberto)}]}]}]
+ (with-redefs [channel/render-notification (fn [& _] [{:stub-message true}])
+ channel/send! (constantly nil)]
+ (#'task.notification/send-notification* (-> notification :subscriptions first :id)))
+ (let [run (t2/select-one :model/TaskRun :notification_id (:id notification))]
+ (is (= :success (:status run)))
+ (is (some? (:ended_at run)))
+ (is (= #{"notification-trigger" "notification-send"}
+ (t2/select-fn-set :task :model/TaskHistory :run_id (:id run) :task [:not= "channel-send"])))))))))
+
+(deftest send-notification-job-async-run-status-test
+ (testing "a worker thread sends a scheduled alert, and the run gets the status of all of its channels (GDGT-3331)"
+ ;; no `mt/with-temp`: it keeps its rows in a transaction that the worker thread cannot see
+ (mt/with-model-cleanup [:model/Card :model/TaskRun :model/TaskHistory]
+ (notification.tu/with-notification-cleanup!
+ (doseq [[slack-fails? expected] [[false :success] [true :failed]]]
+ (testing (if slack-fails? "Slack fails" "both channels deliver")
+ (let [card (t2/insert-returning-instance! :model/Card {:name "Async alert card"
+ :display :table
+ :dataset_query (mt/native-query {:query "SELECT 1"})
+ :visualization_settings {}
+ :creator_id (mt/user->id :crowberto)})
+ notification (models.notification/create-notification!
+ {:payload_type :notification/card
+ :payload {:card_id (:id card)}
+ :creator_id (mt/user->id :crowberto)}
+ ;; a schedule that never fires, so the scheduler does not start a second run
+ [{:type :notification-subscription/cron
+ :cron_schedule "0 0 0 1 1 ? 2099"}]
+ [{:channel_type :channel/email
+ :recipients [{:type :notification-recipient/user
+ :user_id (mt/user->id :crowberto)}]}
+ {:channel_type :channel/slack
+ :recipients [{:type :notification-recipient/raw-value
+ :details {:value "#general"}}]}])
+ release (promise)]
+ ;; `with-redefs`, not `mt/with-dynamic-fn-redefs`: the worker thread does not get the test's bindings
+ (with-redefs [;; no card query: the query processor saves its `query` row later, on another thread, and
+ ;; other tests insert the same query
+ notification.execute/execute-card (fn [_creator-id card-id]
+ {:type :card
+ :card (t2/select-one :model/Card card-id)
+ :result {:status :completed :row_count 1 :data {:rows [[1]]}}})
+ channel/render-notification (fn [& _]
+ ;; the worker waits until the test checked the run
+ (deref release 5000 nil)
+ [{:stub-message true}])
+ channel/send! (fn [channel _]
+ (when (and slack-fails? (= :channel/slack (:type channel)))
+ (throw (ex-info "Slack is down" {}))))
+ notification.send/should-skip-retry? (constantly true)]
+ (#'task.notification/send-notification* (t2/select-one-pk :model/NotificationSubscription
+ :notification_id (:id notification)))
+ (let [run-id (t2/select-one-pk :model/TaskRun :notification_id (:id notification))
+ run-status #(t2/select-one-fn :status :model/TaskRun run-id)]
+ (is (= :started (run-status))
+ "the job has ended, and the run stays started while the worker sends")
+ (deliver release true)
+ (is (= expected (u/poll {:thunk run-status
+ :done? #{:success :failed}
+ :timeout-ms 5000
+ :interval-ms 50})))
+ (is (= 2 (t2/count :model/TaskHistory :run_id run-id :task "channel-send"))))))))))))
+
(deftest init-send-notification-triggers-test
(mt/with-model-cleanup [:model/Notification]
(mt/with-temp-scheduler!
diff --git a/test/metabase/pulse/task/send_pulses_test.clj b/test/metabase/pulse/task/send_pulses_test.clj
index 4c42ebbd04c..976a5d909e6 100644
--- a/test/metabase/pulse/task/send_pulses_test.clj
+++ b/test/metabase/pulse/task/send_pulses_test.clj
@@ -4,7 +4,9 @@
[clojure.test :refer :all]
[clojurewerkz.quartzite.triggers :as triggers]
[java-time.api :as t]
+ [metabase.channel.core :as channel]
[metabase.driver :as driver]
+ [metabase.notification.send :as notification.send]
[metabase.notification.test-util :as notification.tu]
[metabase.pulse.db :as pulse.db]
[metabase.pulse.models.pulse-channel-test :as pulse-channel-test]
@@ -159,6 +161,62 @@
(t2/delete! :model/TaskHistory :run_id [:in (conj (task-runs) -1)])
(t2/delete! :model/TaskRun :entity_type :dashboard :entity_id dash-id)))))))))
+(defn- scheduled-send-run!
+ "Send the scheduled subscription of a new Dashboard to an email and a Slack channel through the job's `send-pulse!`,
+ and return the task run and its `notification-send` statuses. `render!` replaces `channel/render-notification`. The
+ job queues each channel send for a worker; here each send runs on the job's thread instead, so the run sees the
+ sends end before the `send-pulse` row does."
+ [render!]
+ (notification.tu/with-notification-testing-setup!
+ (mt/with-temp [:model/Dashboard {dash-id :id} {}
+ :model/Pulse {pulse-id :id} {:dashboard_id dash-id}
+ :model/PulseChannel {email-id :id} (merge {:pulse_id pulse-id
+ :channel_type :email
+ :details {:emails ["[email protected]"]}}
+ daily-at-1am)
+ :model/PulseChannel {slack-id :id} (merge {:pulse_id pulse-id
+ :channel_type :slack
+ :details {:channel "#general"}}
+ daily-at-1am)]
+ (with-redefs [notification.send/send-notification-async! #'notification.send/send-notification-sync!
+ channel/render-notification render!
+ channel/send! (constantly nil)]
+ (#'task.send-pulses/send-pulse! pulse-id #{email-id slack-id}))
+ (let [run (t2/select-one :model/TaskRun :entity_type :dashboard :entity_id dash-id)]
+ {:run (:status run)
+ :sends (frequencies (t2/select-fn-vec :status :model/TaskHistory :run_id (:id run) :task "notification-send"))
+ :ended? (some? (:ended_at run))}))))
+
+(deftest scheduled-send-run-status-test
+ (mt/with-model-cleanup [:model/TaskRun :model/TaskHistory]
+ (testing "a scheduled send to two channels records the run as success when both deliver (GDGT-3331)"
+ (is (= {:run :success :sends {:success 2} :ended? true}
+ (scheduled-send-run! (fn [& _] [{:stub-message true}])))))
+ (testing "a scheduled send to two channels records the run as failed when the second channel fails after the first delivered (GDGT-3331)"
+ ;; the channels come in the pulse's channel order, which the test does not fix, so fail the second render
+ (let [renders (atom 0)]
+ (is (= {:run :failed :sends {:success 1 :failed 1} :ended? true}
+ (scheduled-send-run! (fn [& _]
+ (if (= 1 (swap! renders inc))
+ [{:stub-message true}]
+ (throw (ex-info "second channel failed" {})))))))))))
+
+(deftest send-pulse-job-failure-fails-run-test
+ (testing "when the job's send fails before it queues any channel send, the job records the run as failed (GDGT-3331)"
+ (mt/with-model-cleanup [:model/TaskRun :model/TaskHistory]
+ (mt/with-temp [:model/Dashboard {dash-id :id} {}
+ :model/Pulse {pulse-id :id} {:dashboard_id dash-id}
+ :model/PulseChannel {pc-id :id} (merge {:pulse_id pulse-id
+ :channel_type :slack
+ :details {:channel "#general"}}
+ daily-at-1am)]
+ (mt/with-dynamic-fn-redefs [pulse.send/send-pulse! (fn [& _] (throw (ex-info "send failed" {})))]
+ (#'task.send-pulses/send-pulse! pulse-id #{pc-id}))
+ (let [run (t2/select-one :model/TaskRun :entity_type :dashboard :entity_id dash-id)]
+ (is (= :failed (:status run)))
+ (is (some? (:ended_at run)))
+ (is (= [:failed] (t2/select-fn-vec :status :model/TaskHistory :run_id (:id run) :task "send-pulse"))))))))
+
(deftest dashboard-archived?-test
(mt/with-temp [:model/Dashboard {live-id :id} {}
:model/Dashboard {archived-id :id} {:archived true}]
diff --git a/test/metabase/task_history/models/task_run_test.clj b/test/metabase/task_history/models/task_run_test.clj
index cfc6b3cc429..6c55c819b5c 100644
--- a/test/metabase/task_history/models/task_run_test.clj
+++ b/test/metabase/task_history/models/task_run_test.clj
@@ -2,6 +2,7 @@
"Tests for TaskRun model and with-task-run macro."
(:require
[clojure.test :refer :all]
+ [metabase.channel.core :as channel]
[metabase.models.interface :as mi]
[metabase.notification.send :as notification.send]
[metabase.notification.test-util :as notification.tu]
@@ -68,23 +69,52 @@
(deftest with-task-run-auto-complete-false-test
(mt/with-model-cleanup [:model/TaskRun :model/TaskHistory]
- (testing "with-task-run does NOT auto-complete when :auto-complete false"
- (let [run-id (atom nil)]
- (task-history/with-task-run {:run_type :subscription
- :entity_type :dashboard
- :entity_id 1
- :auto-complete false}
- (reset! run-id (task-history/current-run-id))
- (task-history/with-task-history {:task "test-task"}
+ (testing "with :auto-complete false and no work for other threads, with-task-run completes the run after its body"
+ (let [run-id (task-history/with-task-run {:run_type :subscription
+ :entity_type :dashboard
+ :entity_id 1
+ :auto-complete false}
+ (task-history/with-task-history {:task "test-task"}
+ :done)
+ (task-history/current-run-id))
+ run (t2/select-one :model/TaskRun :id run-id)]
+ (is (= :success (:status run)))
+ (is (some? (:ended_at run)))))
+ (testing "work on another thread that fails makes the run failed when it ends"
+ (let [[run-id send] (task-history/with-task-run {:run_type :subscription
+ :entity_type :dashboard
+ :entity_id 1
+ :auto-complete false}
+ [(task-history/current-run-id)
+ (task-history/track-run-work! {:send 1})])]
+ (is (= :started (t2/select-one-fn :status :model/TaskRun :id run-id)))
+ (task-history/with-restored-run-id send
+ (try
+ (task-history/with-task-history {:task "send"}
+ (throw (Exception. "fail")))
+ (catch Exception _)))
+ (is (= :failed (t2/select-one-fn :status :model/TaskRun :id run-id)))))))
+
+(deftest task-run-pending-work-test
+ (testing "an :auto-complete false run stays started until its body and all work tagged with its run id have ended (GDGT-3331)"
+ (mt/with-model-cleanup [:model/TaskRun :model/TaskHistory]
+ (let [[run-id send-1 send-2] (task-history/with-task-run {:run_type :subscription
+ :entity_type :dashboard
+ :entity_id 1
+ :auto-complete false}
+ [(task-history/current-run-id)
+ (task-history/track-run-work! {:send 1})
+ (task-history/track-run-work! {:send 2})])
+ run-status #(t2/select-one-fn :status :model/TaskRun :id run-id)]
+ (is (= :started (run-status)) "the body has ended, two sends have not")
+ ;; as the queue does when a newer notification replaces `send-1`
+ (task-history/end-run-work! send-1)
+ (is (= :started (run-status)) "one send has not ended")
+ ;; as the notification worker does
+ (task-history/with-restored-run-id send-2
+ (task-history/with-task-history {:task "send"}
:done))
- (let [run (t2/select-one :model/TaskRun :id @run-id)]
- (is (= :started (:status run)) "status remains :started")
- (is (nil? (:ended_at run)) "ended_at is nil"))
- ;; Manual completion
- (task-history/complete-task-run! @run-id)
- (let [run (t2/select-one :model/TaskRun :id @run-id)]
- (is (= :success (:status run)))
- (is (some? (:ended_at run))))))))
+ (is (= :success (run-status)) "the last send sets the run status")))))
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | Nesting prevention tests |
@@ -126,7 +156,7 @@
(mt/with-dynamic-fn-redefs [task-run/current-run-id (constantly run-id)]
(task-history/with-task-history {:task "t1"} :ok)
(task-history/with-task-history {:task "t2"} :ok))
- (task-history/complete-task-run! run-id)
+ (#'task-run/complete-task-run! run-id)
(is (= :success (:status (t2/select-one :model/TaskRun :id run-id))))))
(testing "complete-task-run! derives :failed when any child failed"
(let [run-id (task-run/create-task-run! {:run_type :sync
@@ -138,7 +168,7 @@
(task-history/with-task-history {:task "t2"}
(throw (Exception. "fail")))
(catch Exception _)))
- (task-history/complete-task-run! run-id)
+ (#'task-run/complete-task-run! run-id)
(is (= :failed (:status (t2/select-one :model/TaskRun :id run-id))))))))
(deftest complete-task-run-idempotent-test
@@ -150,7 +180,7 @@
(mt/with-dynamic-fn-redefs [task-run/current-run-id (constantly run-id)]
(task-history/with-task-history {:task "t1"} :ok))
;; First completion
- (task-history/complete-task-run! run-id)
+ (#'task-run/complete-task-run! run-id)
(let [first-ended-at (:ended_at (t2/select-one :model/TaskRun :id run-id))]
(is (= :success (:status (t2/select-one :model/TaskRun :id run-id))))
;; Add a failing task and try to complete again
@@ -160,7 +190,7 @@
(throw (Exception. "fail")))
(catch Exception _)))
;; Second completion should be no-op
- (task-history/complete-task-run! run-id)
+ (#'task-run/complete-task-run! run-id)
(let [run (t2/select-one :model/TaskRun :id run-id)]
(is (= :success (:status run)) "status unchanged")
(is (= first-ended-at (:ended_at run)) "ended_at unchanged")))))))
@@ -171,19 +201,35 @@
(deftest run-id-meta-propagation-test
(mt/with-model-cleanup [:model/TaskRun]
- (testing "with-run-id-meta and with-restored-run-id propagate run-id via metadata"
- (let [captured-run-id (atom nil)]
+ (testing "track-run-work! and with-restored-run-id propagate run-id via metadata"
+ (let [restored-run (atom nil)]
(task-history/with-task-run {:run_type :sync
:entity_type :database
:entity_id 1}
- (let [data (task-history/with-run-id-meta {:some "data"})
+ (let [data (task-history/track-run-work! {:some "data"})
original-run-id (task-history/current-run-id)]
- ;; Simulate async - outside the with-task-run
(is (some? original-run-id) "run-id is set")
- ;; Restore from metadata in a new context
+ (is (true? (:auto-complete? task-run/*run*)) "with-task-run completes this run itself")
(task-history/with-restored-run-id data
- (reset! captured-run-id (task-history/current-run-id)))
- (is (= original-run-id @captured-run-id) "run-id restored from metadata")))))))
+ (reset! restored-run task-run/*run*))
+ (is (= {:id original-run-id :auto-complete? true} @restored-run)
+ "the restored run has the id from the metadata, and it completes itself, as the original run does")
+ (is (= :started (t2/select-one-fn :status :model/TaskRun :id original-run-id))
+ "the map was not counted, so the restore does not complete the run (GDGT-3331)")))))))
+
+(deftest restored-run-counts-like-its-run-test
+ (testing "work queued on a worker for a run that completes itself is not counted, so it cannot complete that run early (GDGT-3331)"
+ (mt/with-model-cleanup [:model/TaskRun :model/TaskHistory]
+ (task-history/with-task-run {:run_type :subscription
+ :entity_type :dashboard
+ :entity_id 1}
+ (let [run-id (task-history/current-run-id)
+ queued (task-history/track-run-work! {:send 1})]
+ ;; as a worker that sends `queued`, and queues one more notification while it sends
+ (task-history/with-restored-run-id queued
+ (task-history/end-run-work! (task-history/track-run-work! {:send 2})))
+ (is (= :started (t2/select-one-fn :status :model/TaskRun :id run-id))
+ "with-task-run completes the run after its body"))))))
(deftest run-id-meta-nil-propagation-test
(testing "with-restored-run-id handles nil metadata gracefully"
@@ -304,6 +350,33 @@
(is (= :dashboard (:entity_type run)))
(is (#{:success :failed} (:status run)) "task run completed"))))))))
+(deftest pulse-send-run-fails-when-a-later-channel-fails-test
+ (testing "a test send to two channels records the run as failed when the second channel fails after the first delivered (GDGT-3331)"
+ (mt/with-model-cleanup [:model/TaskRun :model/TaskHistory]
+ (notification.tu/with-notification-testing-setup!
+ (mt/with-temp [:model/Dashboard {dash-id :id} {:name "Test Dashboard"}
+ :model/Pulse {pulse-id :id} {:name "Test Pulse"
+ :dashboard_id dash-id}
+ :model/PulseChannel _ {:pulse_id pulse-id
+ :channel_type "email"
+ :details {:emails ["[email protected]"]}}
+ :model/PulseChannel _ {:pulse_id pulse-id
+ :channel_type "slack"
+ :details {:channel "#general"}}]
+ ;; the channels come in the pulse's channel order, which the test does not fix, so fail the second render
+ (let [renders (atom 0)]
+ (with-redefs [channel/render-notification (fn [& _]
+ (if (= 1 (swap! renders inc))
+ [{:stub-message true}]
+ (throw (ex-info "second channel failed" {}))))
+ channel/send! (constantly nil)]
+ (is (thrown? clojure.lang.ExceptionInfo
+ (pulse.send/send-pulse! (t2/select-one :model/Pulse pulse-id))))))
+ (let [run (t2/select-one :model/TaskRun :entity_type :dashboard :entity_id dash-id)]
+ (is (= {:success 1 :failed 1}
+ (frequencies (t2/select-fn-vec :status :model/TaskHistory :run_id (:id run) :task "notification-send"))))
+ (is (= :failed (:status run)))))))))
+
;;; +----------------------------------------------------------------------------------------------------------------+
;;; | Notification integration tests |
;;; +----------------------------------------------------------------------------------------------------------------+