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
Put real IDs in the Agent API's query recovery hints (#85518)
Paolo Rascunàcb7dcd54e611
diff --git a/src/metabase/metabot/tools/recoverable/pipeline.clj b/src/metabase/metabot/tools/recoverable/pipeline.cljindex bd0c136a47e..4925c580884 100644--- a/src/metabase/metabot/tools/recoverable/pipeline.clj+++ b/src/metabase/metabot/tools/recoverable/pipeline.clj@@ -62,18 +62,28 @@(def ^:private id-keys"For each code whose recovery steps name a table or a database, a map from the payload key to thefunction that reads that id from the `ex-data`."+ ;; Repair and resolve throw these errors. The permission sweep query-checks the tables of+ ;; `:table-id` and `:source-table` before repair and resolve run.{:unknown-table {:database-id readable-database-id}:ambiguous-table {:database-id readable-database-id}:unknown-field {:table-id :table-id}:ambiguous-fk {:table-id :source-table}})+(defn error-ids+ "The `:table-id` or `:database-id` that the recovery steps for `error` name, read from the `ex-data` `data`.++ For example, `(error-ids :ambiguous-fk {:source-table 5})` is `{:table-id 5}`, and a code whose steps+ name no id gives `{}`. A table id is the raw `ex-data` value, so check it with `pos-int?`."+ [error data]+ (update-vals (id-keys error) #(% data)))+(defn payload"The [[::payload]] for the pipeline exception `e`, whose `:error` code is `error`.A database id is kept only when [[readable-database-id]] returns it."[error e](let [{:keys [entity-type entity-id source-card source-card-type] :as data} (ex-data e)- {:keys [table-id database-id]} (update-vals (id-keys error) #(% data))]+ {:keys [table-id database-id]} (error-ids error data)](cond-> {:message (or (ex-message e) "")}entity-type (assoc :entity-type entity-type)(some? entity-id) (assoc :entity-id entity-id)diff --git a/src/metabase/metabot/tools/recovery_hints.clj b/src/metabase/metabot/tools/recovery_hints.cljindex ef1ef2fa5b8..dcb97c9712a 100644--- a/src/metabase/metabot/tools/recovery_hints.clj+++ b/src/metabase/metabot/tools/recovery_hints.clj@@ -10,9 +10,16 @@Keep every sentence inside v1's own vocabulary — `read_resource`, `metabase://` URIs,portable FKs and `portable_entity_id`. An error key with no entry here yields no sentence,which is the intended failure mode: a missing hint reads as terse, a wrong one sends the- agent at a tool it does not have."+ agent at a tool it does not have.++ The hints for an unknown or ambiguous table, an unknown column and an ambiguous foreign key name+ the real id when the `ex-data` carries one. For example, such a hint names+ `metabase://database/1/tables` instead of `metabase://database/<numeric id>/tables`. A database id+ appears only when the current user can read that database."(:require- [metabase.agent-lib.representations :as repr]))+ [clojure.string :as str]+ [metabase.agent-lib.representations :as repr]+ [metabase.metabot.tools.recoverable.pipeline :as recoverable.pipeline]))(set! *warn-on-reflection* true)@@ -50,8 +57,11 @@(when (seq paths)(format "Invalid at %s. Fix the named paths." paths))))-(defn recovery-hint- "The v1 recovery sentence for an agent error's `ex-data`, or nil when it has none."+(defn- placeholder-hint+ "The v1 recovery sentence for an agent error's `ex-data`, or nil.++ Some hints keep a `<numeric id>` placeholder. [[recovery-hint]] fills it only when+ [[recoverable.pipeline/error-ids]] reads a `pos-int?` id for the code from `data`."[{:keys [error entity-type entity-id humanized] :as data}](case error:invalid-representations-query@@ -110,3 +120,24 @@"`source-table:` takes a portable FK `[<db-name>, <schema>, <table>]`; `source-card:` takes an entity_id string."nil))++(defn- hint-id+ "The id that the hint for `data` names, or nil when its code names none or the id is not a `pos-int?`."+ [{:keys [error] :as data}]+ (let [{:keys [table-id database-id]} (recoverable.pipeline/error-ids error data)]+ (some #(when (pos-int? %) %) [table-id database-id])))++(defn- with-id+ "`hint` with its `<numeric id>` replaced by `id`, or unchanged when either is nil."+ [hint id]+ (cond-> hint+ (and hint id) (str/replace "<numeric id>" (str id))))++(defn recovery-hint+ "The v1 recovery sentence for an agent error's `ex-data`, or nil when it has none.++ For example, `{:error :unknown-field :table-id 5}` gives a sentence that names+ `metabase://table/5/fields`, and `{:error :unknown-field}` one that names+ `metabase://table/<numeric id>/fields`."+ [data]+ (with-id (placeholder-hint data) (hint-id data)))diff --git a/test/metabase/agent_api/api_test.clj b/test/metabase/agent_api/api_test.cljindex d7dd637275c..42baa210955 100644--- a/test/metabase/agent_api/api_test.clj+++ b/test/metabase/agent_api/api_test.clj@@ -376,6 +376,112 @@(is (=? {:error (name error) :message expected}(mt/user-http-request :rasta :post 400 "agent/v2/construct-query" {:query query})))))))+(defn- recovery-uri+ "The `metabase://` URI that a recovery hint tells the agent to read, e.g.+ \"Call `read_resource` with `metabase://table/5/fields` to ...\" → \"metabase://table/5/fields\"."+ [message]+ (second (re-find #"`(metabase://[^`]+)`" message)))++(defn- check-read-resource+ "Check that `user` can read `uri` with `POST /v1/read-resource`.++ The endpoint returns 200 with a per-item `:error` for a URI it cannot read, so check the item too."+ [user uri]+ (let [{:keys [resources]} (mt/user-http-request user :post 200 "agent/v1/read-resource" {:uris [uri]})+ resource (first resources)]+ (is (= uri (:uri resource)))+ (is (some? (:content resource)))+ (is (nil? (:error resource)))))++(defn- unknown-table-query+ "A count query on `[db \"PUBLIC\" table]`, by default on the misspelled `ORDRS` table of the test database."+ ([] (unknown-table-query (db-name) "ORDRS"))+ ([db table]+ {:lib/type "mbql/query"+ :stages [{:lib/type "mbql.stage/mbql"+ :source-table [db "PUBLIC" table]+ :aggregation [["count" {}]]}]}))++(deftest construct-query-recovery-hints-name-the-real-ids-test+ (let [tables-uri (str "metabase://database/" (mt/id) "/tables")+ orders-uri (str "metabase://table/" (mt/id :orders) "/fields")+ check-error (fn [endpoint query error uri]+ (let [response (mt/user-http-request :crowberto :post 400 endpoint {:query query})]+ (is (= error (:error response)))+ (is (= uri (recovery-uri (:message response))))))]+ (doseq [endpoint ["agent/v2/construct-query" "agent/v2/query"]]+ (testing endpoint+ (testing "an unknown table names the query's database"+ (check-error endpoint (unknown-table-query) "unknown-table" tables-uri)+ (check-read-resource :crowberto tables-uri))+ (testing "an ambiguous table names the query's database"+ ;; The app DB's unique keys forbid a duplicate table, so both tables exist only in the metadata provider.+ (let [mp (lib.tu/mock-metadata-provider+ (mt/metadata-provider)+ {:tables [{:id 99999901 :db-id (mt/id) :schema "PUBLIC" :name "SHIPMENTS"}+ {:id 99999902 :db-id (mt/id) :schema "PUBLIC" :name "SHIPMENTS"}]})]+ (mt/with-dynamic-fn-redefs [lib-be/application-database-metadata-provider (constantly mp)]+ (check-error endpoint (unknown-table-query (db-name) "SHIPMENTS") "ambiguous-table" tables-uri))))+ (testing "an unknown column names its table"+ (check-error endpoint+ (orders-query :aggregation [["count" {}]]+ :breakout [["field" {} [(db-name) "PUBLIC" "ORDERS" "CREATD_AT"]]])+ "unknown-field"+ orders-uri)+ (check-read-resource :crowberto orders-uri))+ (testing "an unknown column on another table names that table"+ (let [products-uri (str "metabase://table/" (mt/id :products) "/fields")]+ (check-error endpoint+ (orders-query :aggregation [["count" {}]]+ :breakout [["field" {} [(db-name) "PUBLIC" "PRODUCTS" "CATEGRY"]]])+ "unknown-field"+ products-uri)+ (check-read-resource :crowberto products-uri)))+ (testing "an ambiguous foreign key names the source table"+ (mt/with-temp-vals-in-db :model/Field (mt/id :orders :user_id) {:fk_target_field_id (mt/id :products :id)}+ (check-error endpoint+ (orders-query :aggregation [["count" {}]]+ :breakout [["field" {} [(db-name) "PUBLIC" "PRODUCTS" "CATEGORY"]]])+ "ambiguous-fk"+ orders-uri)))))))++(deftest construct-query-recovery-hint-names-the-database-only-when-readable-test+ (testing "the pipeline finds the database by name before any permission check, so a user who cannot read it+ gets the placeholder instead of its id"+ (mt/with-no-data-perms-for-all-users!+ (let [response (mt/user-http-request :rasta :post 400 "agent/v2/construct-query" {:query (unknown-table-query)})]+ (is (= "unknown-table" (:error response)))+ (is (= "metabase://database/<numeric id>/tables" (recovery-uri (:message response)))))))+ (testing "a user who can read the database gets its id, and can read the URI"+ (mt/with-full-data-perms-for-all-users!+ (let [response (mt/user-http-request :rasta :post 400 "agent/v2/construct-query" {:query (unknown-table-query)})+ uri (recovery-uri (:message response))]+ (is (= (str "metabase://database/" (mt/id) "/tables") uri))+ (check-read-resource :rasta uri)))))++(deftest construct-query-recovery-hint-skips-a-routing-destination-test+ (testing "`read_resource` never opens a routing destination, so even an admin gets the placeholder"+ (mt/with-temp [:model/Database {router-id :id} {}+ :model/Database {destination :name} {:router_database_id router-id}]+ (let [response (mt/user-http-request :crowberto :post 400 "agent/v2/construct-query"+ {:query (unknown-table-query destination "ORDERS")})]+ (is (= "unknown-table" (:error response)))+ (is (= "metabase://database/<numeric id>/tables" (recovery-uri (:message response))))))))++(deftest construct-query-unknown-field-on-an-unqueryable-table-test+ (testing "a misspelled column on a table the user cannot query gets a 403 that does not name the table"+ (mt/with-no-data-perms-for-all-users!+ (perms/set-table-permission! (perms/all-users-group) (mt/id :orders) :perms/view-data :unrestricted)+ (perms/set-table-permission! (perms/all-users-group) (mt/id :orders) :perms/create-queries :query-builder)+ (testing "the user can query ORDERS, so a 403 below comes from PRODUCTS"+ (mt/user-http-request :rasta :post 200 "agent/v2/construct-query"+ {:query (orders-query :aggregation [["count" {}]])}))+ (let [query (orders-query+ :aggregation [["count" {}]]+ :breakout [["field" {} [(db-name) "PUBLIC" "PRODUCTS" "CATEGRY"]]])+ response (mt/user-http-request :rasta :post 403 "agent/v2/construct-query" {:query query})]+ (is (not (str/includes? (pr-str response) (str "metabase://table/" (mt/id :products)))))))))+(deftest construct-query-permission-checks-test(testing "Rejects a first-stage source-table the current user cannot query"(mt/with-no-data-perms-for-all-users!diff --git a/test/metabase/metabot/tools/recoverable/pipeline_test.clj b/test/metabase/metabot/tools/recoverable/pipeline_test.cljindex 39653a67581..0c6a267da8a 100644--- a/test/metabase/metabot/tools/recoverable/pipeline_test.clj+++ b/test/metabase/metabot/tools/recoverable/pipeline_test.clj@@ -282,6 +282,18 @@(is (= :metabase.metabot.tools.recoverable.pipeline/unknown-table code))(is (= "metabase://database/<numeric id>/tables" (recovery-uri text))))))))+(deftest both-surfaces-name-the-same-ids-test+ (testing "for every pipeline code, the Agent API hint names an id exactly when Metabot's payload carries it"+ (mt/with-current-user (mt/user->id :crowberto)+ (let [data {:table-id 424242 :source-table 424242 :database-id (mt/id)}]+ (doseq [code (pipeline-codes)+ :let [{:keys [table-id database-id]} (pipeline/payload code (ex-info "" (assoc data :error code)))+ hint (v1-hints/recovery-hint (assoc data :error code))]+ :when hint]+ (testing code+ (is (= (some? table-id) (str/includes? hint "metabase://table/424242/")))+ (is (= (some? database-id) (str/includes? hint (str "metabase://database/" (mt/id) "/"))))))))))+(deftest ^:parallel structural-paths-payload-test(doseq [[paths expected-class] [["stages[0].filters: invalid type" :recoverable][nil :unrecoverable]diff --git a/test/metabase/metabot/tools/recovery_hints_test.clj b/test/metabase/metabot/tools/recovery_hints_test.cljindex f14ee6eab5b..13d7cf3a355 100644--- a/test/metabase/metabot/tools/recovery_hints_test.clj+++ b/test/metabase/metabot/tools/recovery_hints_test.clj@@ -1,7 +1,9 @@(ns metabase.metabot.tools.recovery-hints-test(:require+ [clojure.string :as str][clojure.test :refer [deftest is testing]]- [metabase.metabot.tools.recovery-hints :as recovery-hints]))+ [metabase.metabot.tools.recovery-hints :as recovery-hints]+ [metabase.test :as mt]))(set! *warn-on-reflection* true)@@ -21,3 +23,71 @@(deftest ^:parallel ambiguous-database-name-hint-test(is (= "Ask the user to rename one of the databases."(recovery-hints/recovery-hint {:error :ambiguous-database-name}))))++(def ^:private list-tables-hint+ (str "Call `read_resource` with `metabase://database/<numeric id>/tables` to list available tables and schemas, "+ "then retry with an exact portable FK from the response."))++(def ^:private ambiguous-table-hint+ (str "Call `read_resource` with `metabase://database/<numeric id>/tables` to list available tables "+ "and retry with a more specific portable FK."))++(def ^:private list-fields-hint+ "Call `read_resource` with `metabase://table/<numeric id>/fields` to list this table's columns.")++(def ^:private list-fk-columns-hint+ (str "Call `read_resource` with `metabase://table/<numeric id>/fields` for the source table "+ "to list the available foreign-key columns."))++(defn- with-id+ "`hint` with its `<numeric id>` replaced by `id`."+ [hint id]+ (str/replace hint "<numeric id>" (str id)))++(deftest ^:parallel table-hints-name-the-table-id-test+ (testing "an unknown column names the table that its field path names"+ (is (= (with-id list-fields-hint 42)+ (recovery-hints/recovery-hint {:error :unknown-field :table-id 42}))))+ (testing "an ambiguous foreign key names the source table"+ (is (= (with-id list-fk-columns-hint 42)+ (recovery-hints/recovery-hint {:error :ambiguous-fk :source-table 42})))))++(deftest ^:parallel ambiguous-fk-card-source-keeps-the-card-hint-test+ (let [hint (recovery-hints/recovery-hint {:error :ambiguous-fk+ :source-card 7+ :source-card-type "model"+ :source-table 42})]+ (is (= (str "Call `read_resource` with `metabase://model/7/fields` to list the foreign-key columns "+ "this model returns.")+ hint))))++(deftest ^:parallel hints-keep-the-placeholder-without-an-id-test+ (doseq [[data expected] [[{:error :unknown-table} list-tables-hint]+ [{:error :ambiguous-table} ambiguous-table-hint]+ [{:error :unknown-field} list-fields-hint]+ [{:error :ambiguous-fk} list-fk-columns-hint]+ [{:error :unknown-table :database-id 0} list-tables-hint]+ [{:error :ambiguous-table :database-id 0} ambiguous-table-hint]+ [{:error :unknown-field :table-id 0} list-fields-hint]+ [{:error :ambiguous-fk :source-table 0} list-fk-columns-hint]]]+ (testing (pr-str data)+ (is (= expected (recovery-hints/recovery-hint data))))))++(deftest ^:parallel other-codes-ignore-table-ids-test+ (testing "a numeric table id that does not resolve keeps the database placeholder"+ (is (str/includes? (recovery-hints/recovery-hint {:error :unknown-table-id :table-id 42})+ "`metabase://database/<numeric id>/tables`")))+ (testing "a numeric field id keeps the table placeholder"+ (is (= list-fields-hint+ (recovery-hints/recovery-hint {:error :unknown-field-id :field-id 42 :table-id 42}))))+ (testing "an ambiguous foreign key through a join has no hint"+ (is (nil? (recovery-hints/recovery-hint {:error :ambiguous-fk-via-join :source-table 42})))))++(deftest database-hints-name-a-readable-database-test+ (mt/with-current-user (mt/user->id :crowberto)+ (testing "an unknown table names the query's database"+ (is (= (with-id list-tables-hint (mt/id))+ (recovery-hints/recovery-hint {:error :unknown-table :database-id (mt/id)}))))+ (testing "an ambiguous table names the query's database"+ (is (= (with-id ambiguous-table-hint (mt/id))+ (recovery-hints/recovery-hint {:error :ambiguous-table :database-id (mt/id)}))))))