Skip to content

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

Normalize row charts before sending to metabot in chart configs (#76102)

appleby951e37d922a3
diff --git a/frontend/src/metabase/query_builder/containers/use-register-query-builder-metabot-context.tsx b/frontend/src/metabase/query_builder/containers/use-register-query-builder-metabot-context.tsx
index 2f3bd482296..582f3c0b218 100644
--- a/frontend/src/metabase/query_builder/containers/use-register-query-builder-metabot-context.tsx
+++ b/frontend/src/metabase/query_builder/containers/use-register-query-builder-metabot-context.tsx
@@ -4,6 +4,10 @@ import { match } from "ts-pattern";
import { useRegisterMetabotContextProvider } from "metabase/metabot";
import { useUserMetabotPermissions } from "metabase/metabot/hooks";
import { CHART_ANALYSIS_RENDER_FORMATS } from "metabase/metabot/utils/chart-analysis";
+import {
+ extractRemappings,
+ getVisualizationTransformed,
+} from "metabase/visualizations";
import {
getChartImagePngDataUri,
getChartSelector,
@@ -11,6 +15,7 @@ import {
getVisualizationSvgDataUri,
} from "metabase/visualizations/lib/image-exports";
import type { ComputedVisualizationSettings } from "metabase/visualizations/types";
+import { transformSeries as transformCartesianSeries } from "metabase/visualizations/visualizations/CartesianChart/chart-definition-legacy";
import * as Lib from "metabase-lib";
import type Question from "metabase-lib/v1/Question";
import type {
@@ -24,7 +29,7 @@ import type {
import {
getFirstQueryResult,
getQuestion,
- getTransformedSeries,
+ getRawSeries,
getVisibleTimelineEvents,
getVisualizationSettings,
} from "../selectors";
@@ -92,15 +97,30 @@ const getMetrics = (visualizationSettings: ComputedVisualizationSettings) => {
return [];
};
+// Turns the raw query result series into the per-series shape Metabot consumes.
+//
+// For most charts that means `getVisualizationTransformed`. Row charts are the exception: their `transformSeries`
+// (RowChart.tsx) overrides `cols` to `[dimension, metric]` but leaves the original un-pivoted `rows` in place. The
+// resulting misaligned cols/rows makes the reduce below read a text dimension's values as the numeric metric and send
+// those strings to Metabot as `y_values`, crashing the analysis (BOT-1598). So for row charts we call
+// `transformCartesianSeries` instead. It pivots `rows` and `cols` together yielding a correctly aligned breakout
+// series whose `y_values` are guaranteed to be the metric.
+function transformSeries(rawSeries: RawSeries): RawSeries {
+ const remappedSeries = extractRemappings(rawSeries);
+ return rawSeries[0]?.card.display === "row"
+ ? transformCartesianSeries(remappedSeries)
+ : (getVisualizationTransformed(remappedSeries).series as RawSeries);
+}
+
export function processSeriesData(
- transformedSeriesData: RawSeries,
+ seriesData: RawSeries,
visualizationSettings: ComputedVisualizationSettings | undefined,
) {
if (!visualizationSettings) {
return {};
}
- return transformedSeriesData
+ return transformSeries(seriesData)
.filter((series) => !!series.data.cols && !!series.data.rows)
.reduce(
(acc, series, index) => {
@@ -271,7 +291,7 @@ export const useRegisterQueryBuilderMetabotContext = () => {
useRegisterMetabotContextProvider(
async (state) => {
const question = getQuestion(state);
- const series = getTransformedSeries(state);
+ const series = getRawSeries(state);
const visualizationSettings = getVisualizationSettings(state);
const timelineEvents = getVisibleTimelineEvents(state);
const queryResult = getFirstQueryResult(state);
diff --git a/frontend/src/metabase/query_builder/containers/use-register-query-builder-metabot-context.unit.spec.tsx b/frontend/src/metabase/query_builder/containers/use-register-query-builder-metabot-context.unit.spec.tsx
index 14a8688ce5d..36b73c46769 100644
--- a/frontend/src/metabase/query_builder/containers/use-register-query-builder-metabot-context.unit.spec.tsx
+++ b/frontend/src/metabase/query_builder/containers/use-register-query-builder-metabot-context.unit.spec.tsx
@@ -3,6 +3,7 @@ import _ from "underscore";
import { setupUserMetabotPermissionsEndpoint } from "__support__/server-mocks";
import { mockSettings } from "__support__/settings";
import { renderHookWithProviders } from "__support__/ui";
+import registerVisualizations from "metabase/visualizations/register";
import type { ComputedVisualizationSettings } from "metabase/visualizations/types";
import Question from "metabase-lib/v1/Question";
import type {
@@ -25,6 +26,8 @@ import {
useRegisterQueryBuilderMetabotContext,
} from "./use-register-query-builder-metabot-context";
+registerVisualizations();
+
const MOCK_PNG = "data:image/png;base64,test-base64";
const MOCK_SVG = "data:image/svg+xml;base64,test-base64";
@@ -181,9 +184,9 @@ describe("registerQueryBuilderMetabotContextFn", () => {
const chartConfig = getChartConfig(result)!;
expect(chartConfig.series).toEqual({
- "Count by name": {
+ Count: {
chart_type: "line",
- display_name: "Count by name",
+ display_name: "Count",
stacked: false,
x: { name: "name", type: "string" },
x_values: ["a", "b", "c"],
@@ -199,6 +202,113 @@ describe("registerQueryBuilderMetabotContextFn", () => {
]);
});
+ it("should re-project a breakout row chart so y_values are the numeric metric (BOT-1598)", async () => {
+ // Two text dimensions + a count metric, the same shape as the query in BOT-1598.
+ const card = createMockCard({
+ name: "Count by category and series",
+ display: "row",
+ visualization_settings: createMockVisualizationSettings({
+ "graph.dimensions": ["cat", "series"],
+ "graph.metrics": ["count"],
+ }),
+ });
+ const rawRowSeries: RawSeries = [
+ createMockSingleSeries(card, {
+ data: {
+ cols: [
+ createMockColumn({
+ name: "cat",
+ display_name: "Category",
+ base_type: "type/Text",
+ }),
+ createMockColumn({
+ name: "series",
+ display_name: "Series",
+ base_type: "type/Text",
+ }),
+ createMockColumn({
+ name: "count",
+ display_name: "Count",
+ base_type: "type/Integer",
+ source: "aggregation",
+ }),
+ ],
+ rows: [
+ ["A", "X", 1],
+ ["B", "X", 2],
+ ["A", "Y", 3],
+ ["B", "Y", 4],
+ ],
+ },
+ }),
+ ];
+ const data = createMockData({
+ question: new Question(card),
+ series: rawRowSeries,
+ visualizationSettings: createMockVisualizationSettings({
+ "graph.dimensions": ["cat", "series"],
+ "graph.metrics": ["count"],
+ }),
+ });
+ const result = await registerQueryBuilderMetabotContextFn(data);
+
+ const series = getChartConfig(result)!.series!;
+ const entries = Object.values(series);
+ expect(entries).toHaveLength(2);
+
+ entries.forEach((seriesConfig) => {
+ expect(seriesConfig.chart_type).toBe("row");
+ expect(seriesConfig.x).toEqual({ name: "cat", type: "string" });
+ expect(seriesConfig.y).toEqual({ name: "count", type: "number" });
+ expect(seriesConfig.x_values).toEqual(["A", "B"]);
+ expect(seriesConfig.y_values).toHaveLength(
+ seriesConfig.x_values?.length ?? 0,
+ );
+ // The metric must reach y_values as numbers, never the text breakout column (BOT-1598).
+ expect(
+ (seriesConfig.y_values ?? []).every(
+ (value) => typeof value === "number",
+ ),
+ ).toBe(true);
+ });
+
+ const allYValues = entries.flatMap(
+ (seriesConfig) => seriesConfig.y_values ?? [],
+ );
+ expect([...allYValues].sort()).toEqual([1, 2, 3, 4]);
+ });
+
+ it("should produce valid series results for a single-dimension row chart", async () => {
+ const card = createMockCard({
+ name: "Count by name",
+ display: "row",
+ visualization_settings: createMockVisualizationSettings({
+ "graph.dimensions": ["name"],
+ "graph.metrics": ["count"],
+ }),
+ });
+ const data = createMockData({
+ question: new Question(card),
+ visualizationSettings: createMockVisualizationSettings({
+ "graph.dimensions": ["name"],
+ "graph.metrics": ["count"],
+ }),
+ });
+ const result = await registerQueryBuilderMetabotContextFn(data);
+
+ const series = getChartConfig(result)!.series!;
+ const entries = Object.values(series);
+ expect(entries).toHaveLength(1);
+ expect(entries[0]).toMatchObject({
+ chart_type: "row",
+ stacked: false,
+ x: { name: "name", type: "string" },
+ x_values: ["a", "b", "c"],
+ y: { name: "count", type: "number" },
+ y_values: [1, 2, 3],
+ });
+ });
+
it("should produce valid series results for pie charts", async () => {
const card = createMockCard({
name: "Count by name",
diff --git a/src/metabase/metabot/tools/analyze_chart.clj b/src/metabase/metabot/tools/analyze_chart.clj
index d406a1c3fef..43f63ee1182 100644
--- a/src/metabase/metabot/tools/analyze_chart.clj
+++ b/src/metabase/metabot/tools/analyze_chart.clj
@@ -49,6 +49,29 @@ Do not use headers (##). Do not list statistics. Do not analyze series separatel
(some-> (get (shared/current-chart-configs-state) chart-config-id)
stringify-series-keys))
+(defn- non-numeric-y-value?
+ "True when `y-values` contains a non-nil value that is not a number.
+ nil y-values are allowed; they are treated as missing data points downstream."
+ [y-values]
+ (boolean (some (fn [v] (and (some? v) (not (number? v)))) y-values)))
+
+(defn- validate-chart-config!
+ "Throw an informative exception when `chart-config` is too malformed to analyze."
+ [{:keys [series] :as _chart-config}]
+ (when (empty? series)
+ (throw (ex-info "This chart has no series data to analyze."
+ {:type ::malformed-chart-config})))
+ (doseq [[series-name {:keys [y_values]}] series]
+ (when (empty? y_values)
+ (throw (ex-info (format "Series \"%s\" has no data points to analyze." series-name)
+ {:type ::malformed-chart-config, :series series-name})))
+ (when (non-numeric-y-value? y_values)
+ ;; compute-chart-stats assumes each series has numeric y-values.
+ (throw (ex-info (format (str "Series \"%s\" has non-numeric y-values. Chart analysis "
+ "requires a numeric y-axis metric.")
+ series-name)
+ {:type ::malformed-chart-config, :series series-name})))))
+
(mu/defn ^{:tool-name "analyze_chart"
:prompt "analyze_chart"
:scope scope/agent-viz-read}
@@ -63,17 +86,19 @@ Do not use headers (##). Do not list statistics. Do not analyze series separatel
[:deep {:optional true :default true} [:maybe :boolean]]]]
(try
(if-let [chart-config (resolve-chart-config-from-memory chart_config_id)]
- ;; Wrap TMD operations in resource context to ensure off-heap memory is released
- (resource/stack-resource-context
- (let [{:keys [timeline_events title display_type]} chart-config
- opts {:deep? (if (nil? deep) true (boolean deep))}
- stats (interestingness/compute-chart-stats chart-config opts)
- context {:title title
- :display-type display_type
- :stats stats
- :timeline-events timeline_events}
- representation (interestingness/generate-representation context)]
- {:output (str representation "\n\n---\n\n" interpretation-guidance)}))
+ (do
+ (validate-chart-config! chart-config)
+ ;; Wrap TMD operations in resource context to ensure off-heap memory is released
+ (resource/stack-resource-context
+ (let [{:keys [timeline_events title display_type]} chart-config
+ opts {:deep? (if (nil? deep) true (boolean deep))}
+ stats (interestingness/compute-chart-stats chart-config opts)
+ context {:title title
+ :display-type display_type
+ :stats stats
+ :timeline-events timeline_events}
+ representation (interestingness/generate-representation context)]
+ {:output (str representation "\n\n---\n\n" interpretation-guidance)})))
{:output (str "Chart config not found: " chart_config_id
". Available chart configs can be found in the viewing context.")})
(catch Exception e
diff --git a/test/metabase/metabot/tools/analyze_chart_test.clj b/test/metabase/metabot/tools/analyze_chart_test.clj
new file mode 100644
index 00000000000..325b3aa2fe8
--- /dev/null
+++ b/test/metabase/metabot/tools/analyze_chart_test.clj
@@ -0,0 +1,65 @@
+(ns metabase.metabot.tools.analyze-chart-test
+ (:require
+ [clojure.string :as str]
+ [clojure.test :refer :all]
+ [metabase.metabot.tools.analyze-chart :as analyze-chart]
+ [metabase.metabot.tools.shared :as shared]))
+
+(set! *warn-on-reflection* true)
+
+(defn- analyze
+ "Run `analyze-chart-tool` for `chart-config-id` with `chart-configs` seeded into agent memory."
+ [chart-config-id chart-configs]
+ (binding [shared/*memory-atom* (atom {:state {:chart-configs chart-configs}})]
+ (analyze-chart/analyze-chart-tool {:chart_config_id chart-config-id :deep false})))
+
+(defn- numeric-series-config
+ "A well-formed single-series row chart config."
+ []
+ {"c1" {:display_type "row"
+ :title "Orders by category"
+ :series {"Count" {:x {:name "category" :type "string"}
+ :y {:name "count" :type "number"}
+ :x_values ["A" "B" "C" "D"]
+ :y_values [42 53 51 54]
+ :display_name "Count"}}}})
+
+(deftest ^:parallel analyze-chart-tool-chart-not-found-test
+ (testing "an unknown chart_config_id returns a not-found message"
+ (is (= {:output (str "Chart config not found: c1. "
+ "Available chart configs can be found in the viewing context.")}
+ (analyze "c1" {})))))
+
+(deftest ^:parallel analyze-chart-tool-valid-chart-test
+ (testing "a well-formed chart config produces a chart analysis"
+ (let [output (:output (analyze "c1" (numeric-series-config)))]
+ (is (str/includes? output "Chart Analysis"))
+ (is (str/includes? output "Categorical")))))
+
+(deftest ^:parallel analyze-chart-tool-empty-series-test
+ (testing "a chart config with no series is rejected"
+ (is (= {:output "Failed to analyze chart: This chart has no series data to analyze."}
+ (analyze "c1" {"c1" {:display_type "row" :title "Empty" :series {}}})))))
+
+(deftest ^:parallel analyze-chart-tool-empty-y-values-test
+ (testing "a series with no data points is rejected"
+ (is (= {:output "Failed to analyze chart: Series \"Count\" has no data points to analyze."}
+ (analyze "c1" {"c1" {:display_type "row"
+ :title "No points"
+ :series {"Count" {:x {:name "category" :type "string"}
+ :y {:name "count" :type "number"}
+ :x_values []
+ :y_values []
+ :display_name "Count"}}}})))))
+
+(deftest ^:parallel analyze-chart-tool-non-numeric-y-values-test
+ (testing "a series with non-numeric y-values is rejected"
+ (is (= {:output (str "Failed to analyze chart: Series \"Count\" has non-numeric y-values. "
+ "Chart analysis requires a numeric y-axis metric.")}
+ (analyze "c1" {"c1" {:display_type "row"
+ :title "Survey responses"
+ :series {"Count" {:x {:name "frequency" :type "string"}
+ :y {:name "count" :type "number"}
+ :x_values ["Never" "Rarely" "Often"]
+ :y_values ["One" "Two" "Three"]
+ :display_name "Count"}}}})))))