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
Stop Metabot's queries when canceled or after timeout (#84360)
Chris Trutera20aa3b15e3c
diff --git a/src/metabase/metabot/agent/core.clj b/src/metabase/metabot/agent/core.cljindex 572128fcbf5..f28b215ebe5 100644--- a/src/metabase/metabot/agent/core.clj+++ b/src/metabase/metabot/agent/core.clj@@ -25,6 +25,7 @@[metabase.metabot.self.schema :as self.schema][metabase.metabot.tools :as tools][metabase.util :as u]+ [metabase.util.async :as async.u][metabase.util.json :as json][metabase.util.log :as log][metabase.util.malli :as mu]@@ -495,7 +496,7 @@The system message and the tool declarations are rendered once for the whole turn. Both read settings or statusthat can change mid-turn, and a change would invalidate replayed thinking the same way an edited earlier messagedoes (see [[turn-input-parts]])."- [{:keys [messages state metabot profile-id context tracking-opts conversation-id]+ [{:keys [messages state metabot profile-id context tracking-opts conversation-id request-canceled-chan]external-memory-atom :memory-atom}](let [context (assign-context-ids context);; Resolve the profile once (its nlq availability redirect probes the index): reuse it for both the@@ -518,7 +519,8 @@(seed-charts context))memory (-> (memory/initialize messages seeded context)(assoc :conversation-id conversation-id- :tool-names (set (keys base-tools)))+ :tool-names (set (keys base-tools))+ :request-canceled-chan request-canceled-chan)(memory/add-client-ids (client-content-ids context)))memory-atom (doto (or external-memory-atom (atom nil)) (reset! memory))tools (update-vals (tools/wrap-tools-with-state base-tools memory-atom metabot profile-id)@@ -735,7 +737,9 @@[:eval-session-id {:optional true}[:maybe [:and [:string {:max ait/max-session-id-length}] [:re ait/safe-session-id-re]]]][:debug? {:optional true} [:maybe :boolean]]- [:memory-atom {:optional true} [:maybe [:fn #(instance? clojure.lang.Atom %)]]]]]+ [:memory-atom {:optional true} [:maybe [:fn #(instance? clojure.lang.Atom %)]]]+ ;; Receives a value when the request this turn serves is canceled, so a tool can cancel the query it runs.+ [:request-canceled-chan {:optional true} [:maybe [:fn async.u/promise-chan?]]]]](let [opts (m/update-existing-in opts [:context :capabilities] capabilities/enforce-permissions)profile-id (:profile-id opts)debug? (:debug? opts)diff --git a/src/metabase/metabot/api.clj b/src/metabase/metabot/api.cljindex e77b0c00520..7f5b81cd4ab 100644--- a/src/metabase/metabot/api.clj+++ b/src/metabase/metabot/api.clj@@ -230,15 +230,17 @@(transduce xf(streaming-writer-rf os canceled-chan canceled?)(agent/run-agent-loop- (cond-> {:messages messages- :state state- :metabot metabot- :conversation-id conversation-id- :profile-id (keyword profile-id)- :context enriched-context- :eval-session-id eval-session-id- :memory-atom memory-atom- :tracking-opts {:session-id conversation-id}}+ (cond-> {:messages messages+ :state state+ :metabot metabot+ :conversation-id conversation-id+ :profile-id (keyword profile-id)+ :context enriched-context+ :eval-session-id eval-session-id+ :memory-atom memory-atom+ :tracking-opts {:session-id conversation-id}+ ;; A query a tool is running stops when the client goes away.+ :request-canceled-chan canceled-chan}debug? (assoc :debug? true))))(catch org.eclipse.jetty.io.EofException _(vreset! canceled? true)diff --git a/src/metabase/metabot/query_execution.clj b/src/metabase/metabot/query_execution.cljindex 5ef1eb680aa..8c6ab699dba 100644--- a/src/metabase/metabot/query_execution.clj+++ b/src/metabase/metabot/query_execution.clj@@ -1,10 +1,15 @@(ns metabase.metabot.query-execution"Run a serialized MBQL query on behalf of an agent and return one bounded page of rows."(:require+ [clojure.core.async :as a][metabase.api.common :as api]+ [metabase.driver.settings :as driver.settings][metabase.query-processor.core :as qp]+ [metabase.query-processor.pipeline :as qp.pipeline][metabase.util :as u]- [metabase.util.i18n :refer [tru]]))+ [metabase.util.i18n :refer [tru]])+ (:import+ (java.util.concurrent ScheduledFuture ScheduledThreadPoolExecutor ThreadFactory TimeUnit)))(set! *warn-on-reflection* true)@@ -17,19 +22,91 @@The QP strips some of these itself; that is defense in depth, not this boundary's contract."[:lib/type :database :stages :parameters])+(defn- query-canceled+ "An agent error for a query that did not finish because the request it served was canceled."+ []+ (ex-info (tru "Query canceled: the request ended before the query finished.")+ {:agent-error? true+ :error :query-canceled}))++(defn- query-timed-out+ "An agent error for a query that was stopped at its time limit."+ [timeout-ms]+ (ex-info (tru "Query timed out: it did not finish within {0} seconds. A narrower query may finish in time."+ (quot timeout-ms 1000))+ {:agent-error? true+ :error :query-timed-out}))++(defonce ^:private time-limit-executor+ (delay+ (doto (ScheduledThreadPoolExecutor. 1+ (reify ThreadFactory+ (newThread [_ r]+ (doto (Thread. ^Runnable r "metabot-query-time-limit")+ (.setDaemon true)))))+ (.setRemoveOnCancelPolicy true))))++(defn- schedule-time-limit!+ "Call `stop!` after `timeout-ms`. Returns the task, which the caller cancels when the query ends."+ ^ScheduledFuture [timeout-ms stop!]+ (.schedule ^ScheduledThreadPoolExecutor @time-limit-executor ^Runnable stop! (long timeout-ms) TimeUnit/MILLISECONDS))++(defn- do-with-time-limit+ "Call `thunk`, canceling the query it runs on [[qp.pipeline/*canceled-chan*]] after `timeout-ms`.+ Sets `timed-out?` when the limit cancels it."+ [timeout-ms timed-out? thunk]+ ;; Rebinding `*query-timeout-ms*` would also stop the query, but a connection pool opened by this query would keep+ ;; the shorter limit as its leak timeout and kill the connections of every later query on that database.+ (let [canceled-chan qp.pipeline/*canceled-chan*+ task (schedule-time-limit! timeout-ms (fn []+ (reset! timed-out? true)+ (a/put! canceled-chan ::timed-out)))]+ (try+ (thunk)+ (finally+ (.cancel task false)))))+(defn- execute!"Run a serialized MBQL query through the QP with the standard agent userland preparation.Caps this call's rows at `row-limit` (within the backend's 2000/10000 userland ceilings) and records the run- under `context`."- [serialized-query row-limit context]- (let [result (qp/process-query- (-> (select-keys serialized-query query-passthrough-keys)- (assoc :middleware {:js-int-to-string? true})- qp/userland-query-with-default-constraints- (assoc :constraints {:max-results row-limit- :max-results-bare-rows row-limit}- :info {:executed-by api/*current-user-id*- :context context})))]+ under `context`, stopping it as [[execute-page!]] describes for `options`."+ [serialized-query row-limit context {:keys [request-canceled-chan timeout-ms]}]+ (let [query (-> (select-keys serialized-query query-passthrough-keys)+ (assoc :middleware {:js-int-to-string? true})+ qp/userland-query-with-default-constraints+ (assoc :constraints {:max-results row-limit+ :max-results-bare-rows row-limit}+ :info {:executed-by api/*current-user-id*+ :context context}))+ timeout-ms (some-> timeout-ms (min driver.settings/*query-timeout-ms*))+ timer (u/start-timer)+ timed-out? (atom false)+ run #(qp/process-query query)+ ;; Depending on how far it got, a stopped run comes back from the QP as a failure, as nothing,+ ;; as an exception, or as a completed result holding only the rows read before it stopped.+ ;; Each is reported as what stopped it, so the model never reads it as a broken query or a complete page.+ ;; The database query timeout can stop the run first when it is as short as the limit.+ ;; It stops a query no sooner than that, so a run that lasted as long as the limit was stopped by one of them.+ stopped #(cond+ (qp.pipeline/canceled?* request-canceled-chan)+ (query-canceled)++ (or @timed-out? (some-> timeout-ms (<= (u/since-ms timer))))+ (query-timed-out timeout-ms))+ result (try+ ;; Each query gets its own channel.+ ;; The QP closes it when the query ends and writes to it on a timeout.+ ;; On one channel for the whole turn, either would cancel every later query.+ ;; A query with a time limit needs its own channel even when no request can cancel it.+ (qp.pipeline/do-with-own-canceled-chan+ (or request-canceled-chan (when timeout-ms (a/promise-chan)))+ (if timeout-ms+ #(do-with-time-limit timeout-ms timed-out? run)+ run))+ (catch Throwable e+ (throw (or (stopped) e))))]+ (when-let [e (stopped)]+ (throw e))(when-not (= (:status result) :completed)(throw (ex-info (if-let [error (:error result)](tru "Query failed: {0}" error)@@ -47,18 +124,26 @@The `truncated?` flag is true only when more rows exist, so a result that fills the page exactly is complete.A run that doesn't complete throws an agent error whose message carries the QP's error text.Its ex-data is `{:agent-error? true :error :query-failed :query-error <QP error text or nil>}`, with a true- `:permissions-error?` when the QP refused the query because the current user may not run it."- [serialized-query row-limit context]- ;; Fetch one row past the limit so truncation is observed rather than inferred from a full page.- ;; Dropping the probe row keeps `(last rows)` a real page boundary.- (let [result (execute! serialized-query (inc row-limit) context)- all-rows (vec (get-in result [:data :rows]))- truncated? (> (count all-rows) row-limit)- rows (cond-> all-rows truncated? (subvec 0 row-limit))]- {:cols (get-in result [:data :cols])- :rows rows- :returned (count rows)- :truncated? truncated?}))+ `:permissions-error?` when the QP refused the query because the current user may not run it.++ Two options stop a run early, each with an agent error of its own:+ - `:request-canceled-chan`, a promise channel that receives a value when the request being served is canceled.+ The error is `:query-canceled`.+ - `:timeout-ms`, a time limit for the run. The database query timeout still applies when it is shorter.+ The error is `:query-timed-out`."+ ([serialized-query row-limit context]+ (execute-page! serialized-query row-limit context nil))+ ([serialized-query row-limit context options]+ ;; Fetch one row past the limit so truncation is observed rather than inferred from a full page.+ ;; Dropping the probe row keeps `(last rows)` a real page boundary.+ (let [result (execute! serialized-query (inc row-limit) context options)+ all-rows (vec (get-in result [:data :rows]))+ truncated? (> (count all-rows) row-limit)+ rows (cond-> all-rows truncated? (subvec 0 row-limit))]+ {:cols (get-in result [:data :cols])+ :rows rows+ :returned (count rows)+ :truncated? truncated?})))(defn response-cols"The agent-facing description of result `cols`: name, display name, and qualified type names."diff --git a/src/metabase/metabot/tools/run_query.clj b/src/metabase/metabot/tools/run_query.cljindex 8f7f24fb280..913c9d948ea 100644--- a/src/metabase/metabot/tools/run_query.clj+++ b/src/metabase/metabot/tools/run_query.clj@@ -439,13 +439,24 @@:checked-sql (when (or inline-sql? sql-card?)(check-read-only-select! query-id serialized sql-card? allow-non-sql?))}))))+(def ^:private query-timeout-ms+ "How long one query may run."+ ;; A query Metabot wrote can be far slower than expected, and nothing else ends it before the database query timeout.+ (u/minutes->ms 3))++(defn- run-options+ "What may stop a query this tool runs: the chat request being canceled, and the time limit."+ []+ {:request-canceled-chan (shared/request-canceled-chan)+ :timeout-ms query-timeout-ms})+(defn- execute-page!"Run `query` for one page of rows. With `checked-sql`, the driver runs only that SQL or other SQL that is itself aread-only SELECT: the QP compiles the query again, and a snippet or card it references may have changed since`checked-sql` was compiled from it."[query-id {:keys [query checked-sql sql-card?]} row-limit allow-non-sql?](if-not checked-sql- (query-execution/execute-page! query row-limit :metabot)+ (query-execution/execute-page! query row-limit :metabot (run-options))(let [execute qp.pipeline/*execute*;; The driver and SQL the driver step refused, if it refused any.refused (atom nil)]@@ -458,7 +469,7 @@(reset! refused [driver sql])(throw (ex-info "Not a read-only SELECT." {}))))(execute driver native-query respond))]- (query-execution/execute-page! query row-limit :metabot))+ (query-execution/execute-page! query row-limit :metabot (run-options)))(catch Exception e;; The QP reports an exception from the driver step as a failed run, which would reach the model as;; quoted database error text instead of as this tool's refusal.diff --git a/src/metabase/metabot/tools/shared.clj b/src/metabase/metabot/tools/shared.cljindex ec935d48a21..78694e86c68 100644--- a/src/metabase/metabot/tools/shared.clj+++ b/src/metabase/metabot/tools/shared.clj@@ -43,6 +43,11 @@[](:conversation-id (current-memory)))+(defn request-canceled-chan+ "The channel that receives a value when the current turn's request is canceled, or nil when the turn has none."+ []+ (:request-canceled-chan (current-memory)))+(defn current-queries-state"Returns the current queries state map from agent memory."[]diff --git a/test/metabase/metabot/query_execution_test.clj b/test/metabase/metabot/query_execution_test.cljindex cf3f8a77994..6ea0f05a91b 100644--- a/test/metabase/metabot/query_execution_test.clj+++ b/test/metabase/metabot/query_execution_test.clj@@ -1,6 +1,8 @@(ns metabase.metabot.query-execution-test(:require+ [clojure.core.async :as a][clojure.test :refer [deftest is testing]]+ [metabase.driver.settings :as driver.settings][metabase.lib-be.core :as lib-be][metabase.lib.core :as lib][metabase.lib.metadata :as lib.metadata]@@ -9,7 +11,10 @@;; Tests redefine `process-query` here, not in `metabase.query-processor.core`. The core var is a potemkin copy of;; this one, so once other tests have patched both, redefining the copy no longer takes effect.[metabase.query-processor :as qp]- [metabase.test :as mt]))+ [metabase.query-processor.pipeline :as qp.pipeline]+ [metabase.query-processor.reducible :as qp.reducible]+ [metabase.test :as mt]+ [metabase.util :as u]))(defn- venues-query[limit]@@ -55,3 +60,142 @@(testing "any other failure does not"(mt/with-dynamic-fn-redefs [qp/process-query (constantly {:status :failed, :error "Column FOO not found"})](is (=? {:error :query-failed, :permissions-error? false} (failure))))))))++(defn- received+ "The value `chan` delivers within 5 seconds, or nil."+ [chan]+ (first (a/alts!! [chan (a/timeout 5000)])))++(defn- waiting-execute+ "An [[qp.pipeline/*execute*]] that calls `before!`, then waits as a driver does until its channel says to stop,+ records what the channel delivered in `saw`, and responds with nothing."+ [before! saw]+ (fn [_driver _query _respond]+ (before!)+ (reset! saw (received qp.pipeline/*canceled-chan*))+ nil))++(deftest execute-page-request-cancellation-test+ (mt/with-current-user (mt/user->id :rasta)+ (let [query (venues-query 3)+ request-chan (a/promise-chan)+ seen! (fn [request-canceled-chan during-query]+ (let [seen (atom nil)]+ (mt/with-dynamic-fn-redefs [qp/process-query (fn [_query]+ (let [query-chan qp.pipeline/*canceled-chan*]+ (reset! seen (during-query query-chan))+ ;; As the QP does when a query ends.+ (some-> query-chan a/close!)+ {:status :completed+ :data {:cols [] :rows []}}))]+ ;; A canceled run throws; what the query saw is the point here.+ (try+ (query-execution/execute-page! query 3 :agent+ {:request-canceled-chan request-canceled-chan})+ (catch clojure.lang.ExceptionInfo _)))+ @seen))]+ (testing "without a request to follow, the QP is left to make its own channel"+ (is (false? (seen! nil some?))))+ (testing "a query runs on a channel of its own, and the QP closing that one leaves the request's open"+ (is (true? (seen! request-chan #(and (some? %) (not= request-chan %)))))+ (is (nil? (a/poll! request-chan)))))))++(deftest execute-page-canceled-run-test+ (mt/with-current-user (mt/user->id :rasta)+ (let [query (venues-query 3)+ failure #(try+ (query-execution/execute-page! query 3 :agent {:request-canceled-chan %})+ (catch clojure.lang.ExceptionInfo e+ (ex-data e)))]+ (testing "a request canceled while the driver runs the query reaches the driver, and the run reads as canceled"+ (let [request-chan (a/promise-chan)+ driver-saw (atom nil)]+ (binding [qp.pipeline/*execute* (waiting-execute #(a/>!! request-chan :canceled) driver-saw)]+ (is (=? {:error :query-canceled} (failure request-chan)))+ (is (some? @driver-saw)))))+ (testing "a request that is already canceled runs nothing"+ (let [ran? (atom false)]+ (binding [qp.pipeline/*execute* (fn [_driver _query _respond]+ (reset! ran? true)+ nil)]+ (is (=? {:error :query-canceled} (failure (doto (a/promise-chan) (a/>!! :canceled)))))+ (is (false? @ran?))))))))++(deftest execute-page-stopped-mid-stream-test+ (mt/with-current-user (mt/user->id :rasta)+ (let [query (venues-query 3)+ cols (for [column ["ID" "NAME" "CATEGORY_ID" "LATITUDE" "LONGITUDE" "PRICE"]]+ {:name column})+ run (fn [stop! options]+ ;; A driver streams rows until its channel says to stop.+ ;; The QP returns the rows read so far as a completed result, which must not read as a complete page.+ (binding [qp.pipeline/*execute* (fn [_driver _query respond]+ (let [rows (atom (for [id [1 2 3]] [id "Venue" 1 0.0 0.0 1]))]+ (respond {:cols cols}+ (qp.reducible/reducible-rows+ (fn []+ (when (= 3 (count @rows))+ (stop!)+ (received qp.pipeline/*canceled-chan*))+ (let [row (first @rows)]+ (swap! rows rest)+ row))))))]+ (try+ (query-execution/execute-page! query 3 :agent options)+ (catch clojure.lang.ExceptionInfo e+ (ex-data e)))))]+ (testing "a request canceled after the first row reads as canceled"+ (let [request-chan (a/promise-chan)]+ (is (=? {:error :query-canceled}+ (run #(a/>!! request-chan :canceled) {:request-canceled-chan request-chan})))))+ (testing "a time limit reached after the first row reads as timed out"+ (is (=? {:error :query-timed-out}+ (run (constantly nil) {:timeout-ms 200})))))))++(deftest execute-page-time-limit-test+ (mt/with-current-user (mt/user->id :rasta)+ (let [query (venues-query 3)+ driver-saw (atom nil)+ limit-ms (atom nil)+ ;; The query timeout the driver ran under, which a connection pool it opened would keep.+ driver-timeout (atom nil)+ failure (fn [run]+ (reset! driver-saw nil)+ (reset! limit-ms nil)+ (let [stop! (atom nil)+ before! (fn []+ (reset! driver-timeout driver.settings/*query-timeout-ms*)+ (some-> @stop! (apply [])))]+ ;; The limit fires once the driver is waiting, not on a clock started before+ ;; preprocessing, so on a slow runner it still stops the query in flight.+ (mt/with-dynamic-fn-redefs [query-execution/schedule-time-limit!+ (fn [timeout-ms stop-query!]+ (reset! limit-ms timeout-ms)+ (reset! stop! stop-query!)+ ((mt/original-fn #'query-execution/schedule-time-limit!)+ (u/hours->ms 1)+ (constantly nil)))]+ (binding [qp.pipeline/*execute* (waiting-execute before! driver-saw)]+ (try+ (run)+ (catch clojure.lang.ExceptionInfo e+ (ex-data e)))))))]+ (testing "a run that reaches its time limit is stopped, and reads as timed out"+ (is (=? {:error :query-timed-out}+ (failure #(query-execution/execute-page! query 3 :agent {:timeout-ms 60000}))))+ (is (= 60000 @limit-ms))+ (is (some? @driver-saw))+ (testing "without shortening the database query timeout, which a connection pool opened by the run would keep"+ (is (= driver.settings/*query-timeout-ms* @driver-timeout))))+ (testing "the database query timeout still applies when it is the shorter"+ (binding [driver.settings/*query-timeout-ms* 30000]+ (is (=? {:error :query-timed-out}+ (failure #(query-execution/execute-page! query 3 :agent {:timeout-ms 60000}))))+ (is (= 30000 @limit-ms))+ (is (some? @driver-saw))))+ (testing "a caller that sets no limit gets the database query timeout, reported as any failed query is"+ ;; The QP's own timer, which may stop the run before or after it reaches the driver.+ (binding [driver.settings/*query-timeout-ms* 200]+ (is (=? {:error :query-failed}+ (failure #(query-execution/execute-page! query 3 :agent))))+ (is (nil? @limit-ms)))))))diff --git a/test/metabase/metabot/tools/run_query_test.clj b/test/metabase/metabot/tools/run_query_test.cljindex 99581ae9550..52258a4662e 100644--- a/test/metabase/metabot/tools/run_query_test.clj+++ b/test/metabase/metabot/tools/run_query_test.clj@@ -1,7 +1,9 @@(ns metabase.metabot.tools.run-query-test(:require+ [clojure.core.async :as a][clojure.string :as str][clojure.test :refer :all]+ [metabase.driver.settings :as driver.settings][metabase.lib.core :as lib][metabase.lib.metadata :as lib.metadata][metabase.metabot.scope :as scope]@@ -874,3 +876,22 @@(call-sql-tool-in-conversation! {:state {:queries {}}:context {:user_is_viewing [{:type "question", :id card-id}]}}{:query_id (str card-id)})))))))))++(deftest run-query-follows-request-cancellation-test+ (testing "a turn whose request is canceled runs nothing, and tells the model so in place of a query failure"+ (mt/with-temporary-setting-values [metabot-query-execution-enabled? true]+ (is (=? {:output #"Query canceled.*"}+ (call-tool-in-conversation! {:state {:queries {"q1" (venues-count)}}+ :request-canceled-chan (doto (a/promise-chan) (a/>!! :canceled))}+ {:query_id "q1"}))))))++(deftest run-query-time-limit-test+ (testing "a query that runs past the tool's time limit is stopped, and the model is told it timed out"+ ;; The driver waits until its channel says to stop.+ ;; The database timeout is shorter, so the run reads as timed out only if the tool passed its own limit.+ (binding [qp.pipeline/*execute* (fn [_driver _query _respond]+ (a/alts!! [qp.pipeline/*canceled-chan* (a/timeout 5000)])+ nil)+ driver.settings/*query-timeout-ms* 200]+ (is (=? {:output #"Query timed out.*"}+ (run-tool! {"q1" (venues-count)} {:query_id "q1"}))))))