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
BOT-2544 The Documents chart tool accepts a metric as `source-card` and reports success, but the chart does not load (#86113)
Voytek Pituła915b8f5e9222
diff --git a/resources/metabot/prompts/system/document-generate-content.selmer b/resources/metabot/prompts/system/document-generate-content.selmerindex 2121cb68fa3..a48172c4116 100644--- a/resources/metabot/prompts/system/document-generate-content.selmer+++ b/resources/metabot/prompts/system/document-generate-content.selmer@@ -4,18 +4,19 @@ The user is requesting a new chart to be created.You have been provided with a series of tool results that will create a new chart definition.# Your Approach-First, identify if the user is requesting a chart based on an existing model or if they want a custom native SQL base chart-If the user does not specify, first try to build it with an existing model and if that is not possible, fall back to native SQL+First, identify if the user is requesting a chart based on an existing model or metric, or if they want a custom native SQL base chart+If the user does not specify, first try to build it with an existing model or metric and if that is not possible, fall back to native SQLRegardless of the query type, determine the best visualization settings for the chart based on the user request.-## If using an existing model:-IF using an existing model, identify the relevant model using the `list_available_data_sources` tool-THEN use the `document_construct_model_chart` tool (IF a relevant model is found) to generate the chart.-OR use the `document_schema_collect` tool (IF a relevant model is NOT found) as a first step to generating a SQL chart.+## If using an existing model or metric:+IF using an existing model or metric, identify the relevant one using the `list_available_data_sources` tool+THEN use the `document_construct_model_chart` tool (IF a relevant model or metric is found) to generate the chart.+OR use the `document_schema_collect` tool (IF a relevant model or metric is NOT found) as a first step to generating a SQL chart.-`document_construct_model_chart` queries the model as its `source-card`: load the `construct-notebook-query-core`-and `construct-notebook-query-advanced` skills before writing its `query`.+In the `query` of `document_construct_model_chart`, a model goes in `source-card`. A metric goes in `aggregation`, on+the source its `<metric>` tag names. Load the `construct-notebook-query-core` and `construct-notebook-query-advanced`+skills before writing the `query`.## IF using custom SQL:IF writing custom SQL, FIRST use the `document_schema_collect` to get the schema information for thediff --git a/src/metabase/mcp/v2/recovery_hints.clj b/src/metabase/mcp/v2/recovery_hints.cljindex 548e4a1c6ee..f546e46c9d8 100644--- a/src/metabase/mcp/v2/recovery_hints.clj+++ b/src/metabase/mcp/v2/recovery_hints.clj@@ -39,7 +39,7 @@(message/msg ["`source-table:` accepts a numeric table id; `source-card:` accepts a saved-card numeric id."]))))(defn- usable-sources-hint- "Return the usable source IDs from an `:incompatible-metric` error as MCP guidance."+ "Return the usable source IDs from an `:incompatible-metric` or `:metric-as-source-card` error as MCP guidance."[usable-sources](when (seq usable-sources)(apply message/msg@@ -59,11 +59,16 @@(defn recovery-hint"The v2 recovery message for an agent error's `ex-data`, or nil when it has none."- [{:keys [error entity-type entity-id usable-sources source-card source-card-type]}]+ [{:keys [error entity-type entity-id metric-ids usable-sources source-card source-card-type]}](case error:incompatible-metric(usable-sources-hint usable-sources)+ :metric-as-source-card+ (when-let [sources-hint (usable-sources-hint usable-sources)]+ (message/msg ["%s Then reference the metric by its numeric ID: `aggregation: [[\"metric\", {}, %s]]`."]+ sources-hint (first metric-ids)))+:uri-in-source-table(uri-hint entity-type entity-id)diff --git a/src/metabase/metabot/tools/construct.clj b/src/metabase/metabot/tools/construct.cljindex 7b1164d9782..59c52d66296 100644--- a/src/metabase/metabot/tools/construct.clj+++ b/src/metabase/metabot/tools/construct.clj@@ -1007,6 +1007,34 @@(not-any? not-runnable-problem errors)(str ". This usually means a field reference is missing its type or names a column that does not exist, or an aggregation or window function such as `offset` is in `expressions:` instead of `aggregation:` or `order-by:`")))))))+(defn- first-stage-metric-ids+ "Return the IDs of the metrics that the first stage's aggregations reference."+ [query]+ (into #{}+ (match/match-many (lib/aggregations query 0)+ [:metric _ (id :guard pos-int?)]+ id)))++(defn- metric-source-card+ "Return `{metric-id required-source}`, as [[incompatible-metrics]] does, for the metric that the first stage of+ `query` reads as its `source-card`, when that stage does not aggregate the same metric.++ The query processor expands a metric `source-card` only when the query references a metric. Otherwise the stage+ reads the metric's aggregated result, so a `count` gives 1 and a base column is not there. This check is stricter:+ the stage must aggregate this metric.++ A stage that passes this check still goes to [[incompatible-metrics]]. That check accepts the stage for a metric on+ a table, and refuses it for a metric on a model or a saved question, because the stage's `source-card` is not that+ card."+ [mp query]+ ;; Not `lib.util/source-card-id`: it validates the query, and this check runs before the gate that explains an+ ;; invalid query.+ (when-let [card-id (get-in query [:stages 0 :source-card])]+ (let [card (lib.metadata/card mp card-id)]+ (when (and (= :metric (:type card))+ (not (contains? (first-stage-metric-ids query) card-id)))+ {card-id (tools.u/metric-required-source mp card)}))))+(defn- incompatible-metrics"Return the required sources of incompatible metrics in the first stage, sorted by metric ID.@@ -1017,10 +1045,7 @@Only source mismatches in the first stage's aggregations are checked. Metrics in later stages, joins, or otherclauses still reach the query processor, as do other errors such as archived metrics."[mp query]- (let [referenced (into #{}- (match/match-many (lib/aggregations query 0)- [:metric _ (id :guard pos-int?)]- id))]+ (let [referenced (first-stage-metric-ids query)](when (seq referenced)(let [stage-card-id (lib.util/source-card-id query)_ (lib.metadata/bulk-metadata mp :metadata/card (cond-> referenced@@ -1042,11 +1067,12 @@[metric-id required]))))referenced))))))-(defn- incompatible-metric-explanation- "Describe each incompatible metric and the source it requires.+(defn- metric-source-descriptions+ "Describe each metric and the source it requires.- Return `{:message ... :usable-sources {metric-id {:source-table id} | {:source-card id}}}`.- `required-by-metric-id` comes from [[incompatible-metrics]]; `mp` supplies the database name for portable FKs.+ Return `{:descriptions [string ...] :usable-sources {metric-id {:source-table id} | {:source-card id}}}`, with the+ descriptions in the order of `required-by-metric-id`. `required-by-metric-id` maps a metric ID to its+ [[metabase.metabot.tools.util/metric-required-source]]; `mp` supplies the database name for portable FKs.Include names and sources only when the current user may access them. `:usable-sources` identifies those samesources by numeric ID."[mp required-by-metric-id]@@ -1083,11 +1109,7 @@:else" (defined on a source you do not have access to)"))))]- {:message (str "These metrics cannot be used on this stage's source: "- (str/join ", " (map describe metric-ids))- ". "- "Either change the stage's source-table:/source-card: to the one shown for each metric, "- "or drop the metric and express the aggregation directly.")+ {:descriptions (mapv describe metric-ids):usable-sources (into {}(keep (fn [[metric-id r]](cond@@ -1098,6 +1120,47 @@[metric-id {:source-card (:card-id r)}])))required-by-metric-id)}))+(defn- incompatible-metric-explanation+ "Describe each incompatible metric and the source it requires.++ Return `{:message ... :usable-sources ...}`, as [[metric-source-descriptions]] does.+ `required-by-metric-id` comes from [[incompatible-metrics]]."+ [mp required-by-metric-id]+ (let [{:keys [descriptions usable-sources]} (metric-source-descriptions mp required-by-metric-id)]+ {:message (str "These metrics cannot be used on this stage's source: "+ (str/join ", " descriptions)+ ". "+ "Either change the stage's source-table:/source-card: to the one shown for each metric, "+ "or drop the metric and express the aggregation directly.")+ :usable-sources usable-sources}))++(defn- metric-source-card-explanation+ "Describe the metric that a stage reads as its `source-card`, and the source to use instead.++ Return `{:message ... :usable-sources ...}`, as [[metric-source-descriptions]] does.+ `required-by-metric-id` comes from [[metric-source-card]]."+ [mp required-by-metric-id]+ (let [{:keys [descriptions usable-sources]} (metric-source-descriptions mp required-by-metric-id)]+ {:message (str "The metric " (first descriptions) " is in `source-card:`. A metric is an aggregation, "+ "not a source: a stage on a metric reads its result, not its rows. "+ (if (seq usable-sources)+ (str "Build the stage on the source shown for the metric, and put the metric in the "+ "stage's `aggregation:`.")+ "Drop the metric, and express its aggregation directly on a table or model."))+ :usable-sources usable-sources}))++(defn- metric-source-error+ "Return the agent error for the metrics in `required-by-metric-id`, with the message and usable sources that+ `explanation` gives for them. `data` carries the `:error` code."+ [mp data explanation required-by-metric-id]+ (let [{:keys [message usable-sources]} (explanation mp required-by-metric-id)]+ (ex-info message+ (assoc data+ :agent-error? true+ :metric-ids (vec (keys required-by-metric-id))+ :usable-sources usable-sources+ :status-code 400))))+(defn- execute-representations-query*"Execute a notebook query in the canonical portable MBQL 5 representations format.@@ -1120,7 +1183,8 @@5. Sanity-check the post-repair shape against the portable repair schema.6. Resolve portable FKs to numeric IDs and normalize through `lib.schema/query` against themetadata-provider.- 6.5. Backstop-gate the resolved query: mirror the FE `canRun` schema validation+ 6.5. Backstop-gate the resolved query: reject a metric in the first stage's `source-card:` unless that stage+ aggregates the metric ([[metric-source-card]]), mirror the FE `canRun` schema validation([[query-not-runnable-explanation]]), check that implicit field references use a foreign key to their table([[assert-source-fields-reach-their-tables!]]), run the FE expression editor's owndiagnostics over every custom column / aggregation / filter@@ -1176,6 +1240,10 @@_validated (repr/validate-query repaired)pmbql-query (repr.resolve/resolve-query mp repaired permission-aware-content-store)_curated (check-curated-query-sources! mp pmbql-query)+ ;; Before the other gates: a metric source changes which columns the stage has, so their errors would+ ;; send the agent to fix the wrong thing.+ _metric-src (when-let [bad (metric-source-card mp pmbql-query)]+ (throw (metric-source-error mp {:error :metric-as-source-card} metric-source-card-explanation bad)))_runnable (when-let [why (query-not-runnable-explanation pmbql-query repaired)](throw (ex-info (format "The constructed query is not runnable - it would fail the query builder's validation, so it cannot be visualized or saved. Failing paths: %s."why)@@ -1192,13 +1260,7 @@_buckets-ok (repr.repair/assert-temporal-buckets-on-temporal-columns! pmbql-query);; Check sources after schema validation so an incompatible metric produces a retryable error before execution._metrics-ok (when-let [bad (incompatible-metrics mp pmbql-query)]- (let [{:keys [message usable-sources]} (incompatible-metric-explanation mp bad)]- (throw (ex-info message- {:agent-error? true- :error :incompatible-metric- :metric-ids (vec (keys bad))- :usable-sources usable-sources- :status-code 400}))))+ (throw (metric-source-error mp {:error :incompatible-metric} incompatible-metric-explanation bad)))exported-repr (repr.resolve/export-query mp pmbql-query permission-aware-content-store)_validated' (try(repr/validate-query exported-repr)diff --git a/src/metabase/metabot/tools/recoverable/pipeline.clj b/src/metabase/metabot/tools/recoverable/pipeline.cljindex 69e446891f7..9354081faad 100644--- a/src/metabase/metabot/tools/recoverable/pipeline.clj+++ b/src/metabase/metabot/tools/recoverable/pipeline.clj@@ -364,6 +364,14 @@;; No step: the message names the source each metric needs, or says it has none.[])+(defpipeline-error metric-as-source-card!+ "A metric was the stage's `source-card:`, and the stage did not aggregate it."+ ;; The message names the source the metric needs, or says to drop the metric when it has none. The step gives+ ;; the reference form for the first case.+ [{:uses #{}+ :text (str "When you build the stage on the metric's source, reference the metric by its `portable_entity_id`: "+ "`aggregation: [[\"metric\", {}, \"<portable_entity_id>\"]]`.")}])+;;; Query shape(defpipeline-error missing-source-in-first-stage!diff --git a/test/metabase/mcp/v2/recovery_hints_test.clj b/test/metabase/mcp/v2/recovery_hints_test.cljindex 212812c22a0..6c609005226 100644--- a/test/metabase/mcp/v2/recovery_hints_test.clj+++ b/test/metabase/mcp/v2/recovery_hints_test.clj@@ -23,3 +23,16 @@(is (= (str "Use a numeric table id in `source-table:` (from \"browse_data\" ""action \"list_tables\"), which needs no database name at all.")(some-> (recovery-hints/recovery-hint {:error :ambiguous-database-name}) message/render))))++(deftest ^:parallel metric-as-source-card-hint-test+ (testing "names the numeric source and the numeric metric reference"+ (is (= (str "Use numeric IDs here: metric 7 needs `\"source-table\": 3`. "+ "Then reference the metric by its numeric ID: `aggregation: [[\"metric\", {}, 7]]`.")+ (some-> (recovery-hints/recovery-hint {:error :metric-as-source-card+ :metric-ids [7]+ :usable-sources {7 {:source-table 3}}})+ message/render))))+ (testing "gives no hint when the metric has no usable source"+ (is (nil? (recovery-hints/recovery-hint {:error :metric-as-source-card+ :metric-ids [7]+ :usable-sources {}})))))diff --git a/test/metabase/metabot/tools/construct_representations_test.clj b/test/metabase/metabot/tools/construct_representations_test.cljindex 94f9413660e..1cc340a005a 100644--- a/test/metabase/metabot/tools/construct_representations_test.clj+++ b/test/metabase/metabot/tools/construct_representations_test.clj@@ -2453,6 +2453,12 @@(ex-data e)))(is (str/includes? (ex-message e) question-eid)"the message names the source card to build the stage on")))+ (testing "sourcing the metric itself is rejected, also when the stage aggregates the metric"+ (let [e (is (thrown? clojure.lang.ExceptionInfo+ (construct/execute-representations-query+ (metric-query-data {"source-card" metric-eid} metric-eid))))]+ (is (=? {:error :incompatible-metric} (ex-data e)))+ (is (str/includes? (ex-message e) question-eid))))(testing "sourcing the card it was defined on is accepted"(let [result (construct/execute-representations-query(metric-query-data {"source-card" question-eid} metric-eid))]@@ -2764,6 +2770,67 @@(get-in [:structured-output :query]))](is (= [[18760]] (mt/rows (qp/process-query query))))))))))+(deftest metric-as-source-card-test+ (testing "a metric in `source-card:` on a stage that does not aggregate it"+ (mt/with-temp [:model/Card {metric-id :id, metric-eid :entity_id}+ {:name "Big order count"+ :type :metric+ :dataset_query (-> (table-query :orders)+ (lib/filter (lib/> (field-col :orders :total) 100))+ (lib/aggregate (lib/count)))}]+ (mt/with-current-user (mt/user->id :crowberto)+ (let [on-metric (fn [stage]+ (query-data {"lib/type" "mbql/query"+ "stages" [(merge {"lib/type" "mbql.stage/mbql"+ "source-card" metric-eid}+ stage)]}))+ rows (fn [query-data]+ (-> (construct/execute-representations-query query-data)+ (get-in [:structured-output :query])+ qp/process-query+ mt/rows))]+ (testing "reads the metric's result in the query processor, so a count is wrong"+ ;; Not `card-query`: Lib builds a metric's query on the metric's own source.+ (is (= [[1]] (mt/rows (qp/process-query {:database (mt/id)+ :type :query+ :query {:source-table (str "card__" metric-id)+ :aggregation [[:count]]}})))))+ (testing "is refused with an error that names the source to use"+ (doseq [stage [{"aggregation" [["count" {}]]}+ {"aggregation" [["sum" {} ["field" {} "TOTAL"]]]+ "breakout" [["field" {"temporal-unit" "month"} "CREATED_AT"]]}+ {"breakout" [["field" {"temporal-unit" "month"} "CREATED_AT"]]}]]+ (testing (pr-str stage)+ (is (=? {:class :recoverable+ :code :metabase.metabot.tools.recoverable.pipeline/metric-as-source-card+ :text (str "The metric \"Big order count\" (needs source-table: "+ (json/encode (orders-source-table-fk)) ") is in `source-card:`. A metric is "+ "an aggregation, not a source: a stage on a metric reads its result, not its "+ "rows. Build the stage on the source shown for the metric, and put the metric "+ "in the stage's `aggregation:`.\n"+ "When you build the stage on the metric's source, reference the metric by its "+ "`portable_entity_id`: "+ "`aggregation: [[\"metric\", {}, \"<portable_entity_id>\"]]`.")}+ (test-util/tool-failure construct/construct-notebook-query-tool {:query (on-metric stage)}))))))+ (testing "gives the MCP surface the numeric source"+ (let [e (is (thrown? clojure.lang.ExceptionInfo+ (construct/execute-representations-query (on-metric {"aggregation" [["count" {}]]}))))]+ (is (=? {:error :metric-as-source-card+ :metric-ids [metric-id]+ :usable-sources {metric-id {:source-table (mt/id :orders)}}}+ (ex-data e)))))+ (testing "says to drop the metric when it has no usable source"+ (is (= {:message (str "The metric \"Big order count\" (has no usable source) is in "+ "`source-card:`. A metric is an aggregation, not a source: a stage on a "+ "metric reads its result, not its rows. Drop the metric, and express its "+ "aggregation directly on a table or model.")+ :usable-sources {}}+ (#'construct/metric-source-card-explanation (mt/metadata-provider) {metric-id nil}))))+ (testing "is accepted when the stage aggregates that metric, which the query processor expands"+ (is (= [[5755]] (rows (on-metric {"aggregation" [["metric" {} metric-eid]]})))))+ (testing "and the query the error asks for gives the same result"+ (is (= [[5755]] (rows (metric-query-data {"source-table" (orders-source-table-fk)} metric-eid))))))))))+(deftest metric-source-check-follows-a-source-card-that-changed-table-test(testing "After C1 moves from ORDERS to PRODUCTS, the check follows it as the query processor does"(mt/with-temp [:model/Card {c1-id :id}diff --git a/test/metabase/metabot/tools/curated_content_test.clj b/test/metabase/metabot/tools/curated_content_test.cljindex 1fc48b90a23..ed9dbc5a401 100644--- a/test/metabase/metabot/tools/curated_content_test.clj+++ b/test/metabase/metabot/tools/curated_content_test.clj@@ -398,8 +398,12 @@:name "plain metric":dataset_query (count-metric-query (orders-query))}:model/Metabot metabot {:name "curated metabot" :use_verified_content true}]+ ;; The stage aggregates the metric: construct_notebook_query rejects a metric `source-card` that the stage+ ;; does not aggregate, with `:metric-as-source-card`.(let [q {:lib/type "mbql/query"- :stages [{:lib/type "mbql.stage/mbql" :source-card metric-eid}]}+ :stages [{:lib/type "mbql.stage/mbql"+ :source-card metric-eid+ :aggregation [["metric" {} metric-eid]]}]}construct (fn [metabot profile-id](as-metabot metabot profile-id #(construct/execute-representations-query q)))rejected? (fn []diff --git a/test/metabase/metabot/tools/document_test.clj b/test/metabase/metabot/tools/document_test.cljindex 15495d82228..43a6a5b808d 100644--- a/test/metabase/metabot/tools/document_test.clj+++ b/test/metabase/metabot/tools/document_test.clj@@ -332,6 +332,25 @@:stages [{:source-card (:id model)}]}(:dataset_query structured)))))))))+(deftest document-construct-model-chart-metric-as-source-card-test+ (testing "a metric in `source-card` is a failed call that names the source to use, not a chart"+ (let [mp (mt/metadata-provider)]+ (mt/with-current-user (mt/user->id :crowberto)+ (mt/with-temp [:model/Card metric {:type :metric+ :name "Order count"+ :dataset_query (-> (lib/query mp (lib.metadata/table mp (mt/id :orders)))+ (lib/aggregate (lib/count)))}]+ (let [result (invoke-document-tool "document_construct_model_chart"+ (assoc model-chart-args+ :query {:lib/type "mbql/query"+ :stages [{:lib/type "mbql.stage/mbql"+ :source-card (:entity_id metric)+ :aggregation [["count" {}]]+ :breakout [["field" {} "PRODUCT_ID"]]}]}))]+ (is (= {:class :recoverable :code ::recoverable.pipeline/metric-as-source-card} (:error result)))+ (is (str/starts-with? (:output result) "The metric \"Order count\" (needs source-table: "))+ (is (nil? (:structured-output result)))))))))+(deftest document-construct-model-chart-new-chart-types-test(testing "the tool schema accepts newly added chart types";; Stubbed one layer below the tool: `construct_notebook_query` is a record now, and the