Skip to content

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

Send Metabot's structured queries to the frontend as MBQL 5 (#84647)

Mihael Konjević7a78715aaf55
diff --git a/frontend/src/metabase/metabot/components/MetabotChat/MetabotAgentDataSourcePills.tsx b/frontend/src/metabase/metabot/components/MetabotChat/MetabotAgentDataSourcePills.tsx
index f54c39bb0b6..224d79bca5a 100644
--- a/frontend/src/metabase/metabot/components/MetabotChat/MetabotAgentDataSourcePills.tsx
+++ b/frontend/src/metabase/metabot/components/MetabotChat/MetabotAgentDataSourcePills.tsx
@@ -41,7 +41,6 @@ import type {
MetabotCodeEdit,
MetabotCodeEditorBufferContext,
MetabotSourceFeedback,
- NativeDatasetQuery,
TemplateTags,
} from "metabase-types/api";
@@ -79,33 +78,31 @@ type SourceFeedbackTarget = Pick<
"source_id" | "source_type"
>;
-const isNativeDatasetQuery = (
- datasetQuery: DatasetQuery,
-): datasetQuery is NativeDatasetQuery =>
- "type" in datasetQuery && datasetQuery.type === "native";
-
const decodeQuery = (datasetQuery: DatasetQuery | undefined): DecodedQuery => {
try {
if (!datasetQuery) {
return { kind: "none" };
}
- if (isNativeDatasetQuery(datasetQuery)) {
- const sql = datasetQuery.native.query;
- const databaseId = datasetQuery.database;
- if (typeof sql === "string" && typeof databaseId === "number") {
- return {
- kind: "native",
- databaseId,
- sql,
- templateTags: datasetQuery.native["template-tags"],
- };
- }
- return { kind: "none" };
- }
-
const question = Question.create({ dataset_query: datasetQuery });
const query = question.query();
+ const isNativeOnly =
+ Lib.queryDisplayInfo(query).isNative && Lib.stageCount(query) === 1;
+
+ if (isNativeOnly) {
+ const databaseId = Lib.databaseID(query);
+ if (databaseId == null) {
+ return { kind: "none" };
+ }
+ const templateTags = Lib.templateTags(query);
+ return {
+ kind: "native",
+ databaseId,
+ sql: Lib.rawNativeQuery(query),
+ templateTags:
+ Object.keys(templateTags).length > 0 ? templateTags : undefined,
+ };
+ }
return {
kind: "mbql",
diff --git a/frontend/src/metabase/metabot/components/MetabotChat/MetabotAgentDataSourcePills.unit.spec.tsx b/frontend/src/metabase/metabot/components/MetabotChat/MetabotAgentDataSourcePills.unit.spec.tsx
index 5297dec5029..ec08847ae99 100644
--- a/frontend/src/metabase/metabot/components/MetabotChat/MetabotAgentDataSourcePills.unit.spec.tsx
+++ b/frontend/src/metabase/metabot/components/MetabotChat/MetabotAgentDataSourcePills.unit.spec.tsx
@@ -3,6 +3,9 @@ import fetchMock from "fetch-mock";
import { renderWithProviders, screen, waitFor, within } from "__support__/ui";
import type { GeneratedCard } from "metabase/api/ai-streaming/schemas";
+import { checkNotNull } from "metabase/utils/types";
+import * as Lib from "metabase-lib";
+import { SAMPLE_PROVIDER } from "metabase-lib/test-helpers";
import type {
DatasetQuery,
MetabotCodeEdit,
@@ -16,6 +19,11 @@ import {
createMockDatabase,
createMockTable,
} from "metabase-types/api/mocks";
+import {
+ ORDERS_ID,
+ PRODUCTS_ID,
+ SAMPLE_DB_ID,
+} from "metabase-types/api/mocks/presets";
import {
CodeEditTablePills,
@@ -33,7 +41,7 @@ const ORDERS_TABLE = createMockTable({
display_name: "Orders",
});
const PRODUCTS_TABLE = createMockTable({
- id: 3,
+ id: PRODUCTS_ID,
db_id: 1,
name: "PRODUCTS",
display_name: "Products",
@@ -82,6 +90,22 @@ const createNativeCard = (
},
});
+const createNativeQueryWithJoin = () => {
+ const query = Lib.appendStage(
+ Lib.createTestNativeQuery(SAMPLE_PROVIDER, {
+ query: "SELECT * FROM ORDERS",
+ }),
+ );
+ const products = checkNotNull(Lib.tableOrCardMetadata(query, PRODUCTS_ID));
+ const condition = Lib.joinConditionClause(
+ "=",
+ Lib.expressionClause(1),
+ Lib.expressionClause(1),
+ );
+ const [strategy] = Lib.availableJoinStrategies(query, -1);
+ return Lib.join(query, -1, Lib.joinClause(products, [condition], strategy));
+};
+
const setupTableEndpoints = (...tables: (typeof ORDERS_TABLE)[]) => {
tables.forEach((table) => {
fetchMock.get(`path:/api/table/${table.id}`, table);
@@ -278,6 +302,75 @@ describe("MetabotAgentDataSourcePills", () => {
).toHaveLength(1);
});
+ it("parses MBQL 5 native SQL queries and requests extracted sources", async () => {
+ const sql = "SELECT * FROM ORDERS";
+ setupNativeEndpoints();
+
+ renderWithProviders(
+ <GeneratedCardTablePills
+ messageId="message-5"
+ value={createGeneratedCard(
+ Lib.createTestJsNativeQuery(SAMPLE_PROVIDER, { query: sql }),
+ )}
+ />,
+ );
+
+ expect(
+ await screen.findByRole("link", { name: "Orders" }),
+ ).toBeInTheDocument();
+ expect(
+ fetchMock.callHistory.calls(EXTRACT_SOURCES_ENDPOINT, {
+ body: {
+ database_id: SAMPLE_DB_ID,
+ sql,
+ },
+ }),
+ ).toHaveLength(1);
+ });
+
+ it("parses MBQL 5 source tables", async () => {
+ setupTableEndpoints(ORDERS_TABLE);
+
+ renderWithProviders(
+ <GeneratedCardTablePills
+ messageId="message-4"
+ value={createGeneratedCard(
+ Lib.createTestJsQuery(SAMPLE_PROVIDER, {
+ stages: [{ source: { type: "table", id: ORDERS_ID } }],
+ }),
+ )}
+ />,
+ );
+
+ expect(
+ await screen.findByRole("link", { name: "Orders" }),
+ ).toBeInTheDocument();
+ });
+
+ it.each([
+ { format: "legacy", toDatasetQuery: Lib.toLegacyQuery },
+ { format: "MBQL 5", toDatasetQuery: Lib.toJsQuery },
+ ])(
+ "lists a table joined after a native stage as a source ($format)",
+ async ({ toDatasetQuery }) => {
+ setupTableEndpoints(PRODUCTS_TABLE);
+ fetchMock.post(FIELD_TABLE_IDS_ENDPOINT, { table_ids: [] });
+
+ renderWithProviders(
+ <GeneratedCardTablePills
+ messageId="message-6"
+ value={createGeneratedCard(
+ toDatasetQuery(createNativeQueryWithJoin()),
+ )}
+ />,
+ );
+
+ expect(
+ await screen.findByRole("link", { name: "Products" }),
+ ).toBeInTheDocument();
+ },
+ );
+
it("renders extracted native query model sources", async () => {
const sql = "SELECT * FROM {{#4-revenue_model}}";
const templateTags: TemplateTags = {
diff --git a/src/metabase/agent_lib/representations/repair.clj b/src/metabase/agent_lib/representations/repair.clj
index b776682f996..589783fefcd 100644
--- a/src/metabase/agent_lib/representations/repair.clj
+++ b/src/metabase/agent_lib/representations/repair.clj
@@ -951,11 +951,13 @@
;;; ["between", {}, ["field", {}, <col>], ["absolute-datetime", {}, "2025-01-01", "day"], ["now", {}]]
;;; => ["between", {}, ["field", {}, <col>], "2025-01-01", ["now", {}]]
;;;
-;;; Why: the frontend opens a Metabot question from a `/question#` hash holding *legacy* MBQL
-;;; (`metabase.metabot.agent.links/->legacy-mbql`). JSON turns the unit into a string, and the legacy
-;;; schema cannot decode it back for `absolute-datetime` / `during`, so the clause never survives the
-;;; hop -- the last paragraph below says what that costs, which depends on where the clause sits. A
-;;; `temporal-unit` on a ref decodes fine (`legacy-json-round-trip-temporal-filters-test`).
+;;; `metabase.metabot.agent.links/->frontend-query` converts a structured query that does not
+;;; normalize to valid MBQL 5 to legacy MBQL. If that conversion fails too, as it does for a query
+;;; stripped of its `:lib/*` keys whose aggregation ref no longer resolves, the raw MBQL 5 query goes
+;;; out instead. In legacy MBQL, JSON turns the unit into a string, and the legacy schema cannot
+;;; decode it for `absolute-datetime` / `during`, so the frontend drops the clause (BOT-1972). A
+;;; `temporal-unit` on a ref decodes correctly (`legacy-json-round-trip-temporal-filters-test`). The
+;;; query builder also writes the hoisted form.
;;;
;;; Only inside a stage's `filters` and `expressions`, at every nesting level of the two -- a
;;; comparison inside a `case` included -- and in every stage of the query, a join's inner stages
@@ -986,8 +988,8 @@
;;; `date-field-with-day-bucketing?`, so the literal-side form becomes a negated range
;;; (`d < x OR d >= x+1`, dropping NULL rows) while the hoisted one stays an `!=` and gets the
;;; `IS NULL` disjunct `sql.qp` adds to every other `!=` (`correct-null-behaviour`). Hoisting is the
-;;; only option here, not just the better one: every `!=` shape that survives the JSON hop compiles
-;;; to `<> ... OR ... IS NULL`, and the one shape that does not is the broken one above. Pinned by
+;;; only option here, not just the better one: the `/question#` link carries the literal-side form
+;;; intact as MBQL 5, and the query engine then runs it as that negated range. Pinned by
;;; `optimize-date-not-equals-null-semantics-test`. The divergence is about *which rows*; inside a
;;; `case` under `expressions` that becomes a difference in a computed value rather than in the
;;; filter.
@@ -1039,15 +1041,10 @@
;;; Runs after Pass 2.9, which creates new `filters`. Idempotent: the output matches neither
;;; predicate.
;;;
-;;; None of the survivors above is merely unrewritten -- each is broken. The legacy unit enums have no
-;;; `:decode/normalize`, so after the JSON hop the clause never normalizes back. What that costs
-;;; depends on where it sits. In `filters`, `expressions` and join `conditions:` the dev and CI
-;;; question page 400s, while a production JAR -- where `normalize-or-throw`'s `mu/defn` output check
-;;; is compiled out -- lets `lib/query`'s `clean-stage-schema-errors` delete the clause, and the
-;;; question silently answers something else. In `aggregation:` the legacy schema is permissive
-;;; enough that even dev never throws: the `count-where` above is deleted in both, silently. Pass 6's
-;;; [[unencodable-temporal-clause-error!]] catches every one and raises a retryable `:agent-error?`,
-;;; except the unparseable literal, which resolve names more precisely.
+;;; The survivors above reach the question intact, since the `/question#` link carries MBQL 5, but the
+;;; query engine runs some of them wrong. Pass 6's [[unencodable-temporal-clause-error!]], whose
+;;; docstring has two examples, catches every one and raises a retryable `:agent-error?`, except the
+;;; unparseable literal, which resolve names more precisely.
;;; ============================================================
(def ^:private date-truncation-units
@@ -1302,11 +1299,13 @@
;;; ["temporal-extract", {}, <col>, "week-of-year-iso"] => ["get-week", {}, <col>, "iso"]
;;; ["temporal-extract", {}, <col>, "day-of-week", "us"] => ["get-day-of-week", {}, <col>]
;;;
-;;; Same hazard as Pass 2.95: the unit lands in the legacy `::TemporalExtractUnit` enum, which has
-;;; no decoder, so the question page 400s. A `get-*` clause carries no unit. The week-mode units keep
-;;; their meaning through the trailing argument `get-week` / `get-day-of-week` already take. The
-;;; clause's own optional mode slot (third example) is dropped: SQL compilation reads only the unit
-;;; (`:temporal-extract` in `metabase.driver.sql.query-processor`), so it never mattered.
+;;; The unit lands in the legacy `::TemporalExtractUnit` enum, which has no decoder, so a question
+;;; that opens from legacy MBQL 400s. The `/question#` link carries a structured query as MBQL 5,
+;;; where the clause survives, so this matters only when a query falls back to legacy MBQL. A
+;;; `get-*` clause carries no unit. The week-mode units keep their meaning through the trailing
+;;; argument `get-week` / `get-day-of-week` already take. The clause's own optional mode slot (third
+;;; example) is dropped: SQL compilation reads only the unit (`:temporal-extract` in
+;;; `metabase.driver.sql.query-processor`), so it never mattered.
;;;
;;; An exact synonym wherever the clause appears, so not scoped to `filters`. Idempotent: the new
;;; head is not `temporal-extract`.
@@ -2996,7 +2995,7 @@
:error :numeric-field-id
:clause &match})))))
-;;; ----- E7: a temporal clause the `/question#` hash cannot carry ---------------------
+;;; ----- E7: a temporal clause Pass 2.95 could not rewrite ----------------------------
(defn- deferred-to-invalid-temporal-literal?
"True for an `absolute-datetime` whose literal cannot parse.
@@ -3011,9 +3010,8 @@
Deferring the whole query instead would be a worse trade -- `validate-temporal-literals` does not
inspect every position, since a bare literal on a comparison head is checked only when an operand
is *known* temporal, so an unparseable literal in a position it does not inspect would silence E7
- with nothing to replace it, reopening the silent-deletion hole
- Pass 2.95 and this detector exist to close. The model fixes what E7 named and sees the literal
- complaint on the next turn."
+ with nothing to replace it, and the clause would reach the query engine. The model fixes what E7
+ named and sees the literal complaint on the next turn."
[node]
(let [literal (nth node 2)]
(and (string? literal)
@@ -3027,23 +3025,22 @@
All three hold a temporal unit in a slot the legacy schema types with `::DateUnit` /
`::DateTimeUnit` (`metabase.legacy-mbql.schema`, via `::ValueTypeInfo` for `value`), and neither
- enum carries a `:decode/normalize`. Once the `/question#` hash has JSON-encoded the query the unit
- is a string and the clause never normalizes back. In `filters`, `expressions` and join
- `conditions:` that is a 400 on the dev and CI question page, and in a production JAR -- where
- `normalize-or-throw`'s `mu/defn` output check is compiled out -- `lib/query`'s
- `clean-stage-schema-errors` deletes the clause outright and the question silently answers something
- else. In `aggregation:` the legacy schema is permissive enough that nothing throws even in dev: the
- clause is deleted silently in both. Pass 2.95 rewrites every shape it can rewrite without changing
- the answer, so anything still standing here is broken either way.
+ enum carries a `:decode/normalize`: after a JSON hop as legacy MBQL the unit is a string and the
+ clause never normalizes back. The `/question#` link carries a structured query as MBQL 5, where the
+ clause survives the hop, but the query engine runs some of these clauses wrong by comparing the
+ column with the start of the literal's period. On the Sample Database, `count-where` with
+ `[\">\" CREATED_AT [\"absolute-datetime\" \"2026-01-01\" \"month\"]]` counts 18016 orders, though
+ 17811 are after January 2026, and
+ `[\"=\" [\"absolute-datetime\" \"2026-03-01\" \"month\"] CREATED_AT]` counts none of the 256 orders
+ from March 2026. Pass 2.95 rewrites every shape it can rewrite without changing the answer, and
+ this detector has the model rewrite the rest.
`relative-datetime` and `datetime-diff` units do carry `:decode/normalize`, so they survive the hop
and are not listed. `temporal-extract`'s `::TemporalExtractUnit` has no decoder either, but Pass
1.867 has already rewritten every one to a `get-*` clause by the time this runs -- narrow that pass
and this detector needs the head. `time` is excluded on purpose: it 400s in dev, but `->mbql5`
salvages the raw clause in prod (unit correctly keywordized, filter intact), so flagging it would
- reject a query that works for customers. This detector exists only because `::DateUnit`,
- `::TimeUnit`, `::DateTimeUnit` and `::TemporalExtractUnit` lack decoders -- if they ever gain them,
- delete it rather than inherit a false-positive machine.
+ reject a query that works for customers.
Throws `:agent-error?` ex-info on the first offender."
[form]
@@ -3064,7 +3061,7 @@
(some? (get (nth node 1) "unit")))
false))
(throw (ex-info
- (tru "`{0}` does not survive the round trip through the question link the frontend opens: the question either fails to load, or silently loses the clause and answers something else. Put the unit on the column instead - a `temporal-unit` option on the `field` / `expression` reference, compared to the first day of the period as a plain date string like \"2025-01-01\" - or write the range out as `>=` its first day and `<` the first day after it, both plain date strings (not `between`, which drops everything after midnight on its last day). Use the range for `year` on an `expression` reference, which the query engine reads as a number, and inside `aggregation:` (`count-where`, `sum-where`, `share`) and join `conditions:`, where moving the unit onto the column would change the answer."
+ (tru "Move the temporal unit in `{0}` off the literal. Put it on the column - a `temporal-unit` option on the `field` / `expression` reference, compared to the first day of the period as a plain date string like \"2025-01-01\" - or write the range out as `>=` its first day and `<` the first day after it, both plain date strings (not `between`, which drops everything after midnight on its last day). Use the range for `year` on an `expression` reference, which the query engine reads as a number, and inside `aggregation:` (`count-where`, `sum-where`, `share`) and join `conditions:`, where moving the unit onto the column would change the answer."
(pr-str node))
{:agent-error? true
:error :unencodable-temporal-clause
@@ -3137,16 +3134,17 @@
1.75. strip stray surrounding double-quotes from the string segments of `field` clauses'
portable-FK vector targets, e.g. `\"col\"` → `col` (cross-stage string targets are left
to the resolution-aware cross-stage matching in pass 5);
- 1.867. rewrite `temporal-extract` to the equivalent `get-*` clause, so its unit no longer sits
- where legacy normalization cannot decode it (examples in the pass header);
+ 1.867. rewrite `temporal-extract` to the equivalent `get-*` clause, which survives a fallback
+ to legacy MBQL (examples in the pass header);
1.87. rewrite a known-misspelled `\"lib/type\"` marker to its canonical value (e.g. the
join slip `\"mbql.join/join\"` → `\"mbql/join\"`);
1.88. merge a trailing extra options-map back into position-1 options on fixed-arity
tuple clauses (e.g. `[\"time-interval\" {} <expr> -1 \"month\" {\"include-current\" true}]`);
2. fill in missing `\"lib/type\"` markers on the query, joins, and stages;
2.95. inside a stage's `filters` and `expressions` only, hoist a temporal bucket off an
- `absolute-datetime` literal and onto the ref it is compared to, for the same reason
- (examples in the pass header; runs after Pass 2.9, which creates new `filters`);
+ `absolute-datetime` literal and onto the ref it is compared to: the hoisted form survives a
+ fallback to legacy MBQL, and the query engine runs it right where it runs the literal-side
+ form wrong (examples in the pass header; runs after Pass 2.9, which creates new `filters`);
3. rewrite inline aggregation expressions in `order-by` to aggregation references when
they match an aggregation in the same stage's `aggregation:` list (synthesising the
referenced aggregation's `lib/uuid` if needed);
diff --git a/src/metabase/metabot/agent/links.clj b/src/metabase/metabot/agent/links.clj
index 1830daff10c..6b0f1260340 100644
--- a/src/metabase/metabot/agent/links.clj
+++ b/src/metabase/metabot/agent/links.clj
@@ -9,7 +9,8 @@
[metabase.metabot.db :as metabot.db]
[metabase.system.core :as system]
[metabase.util.json :as json]
- [metabase.util.log :as log]))
+ [metabase.util.log :as log]
+ [metabase.util.malli.registry :as mr]))
(set! *warn-on-reflection* true)
@@ -28,11 +29,11 @@
;;; Query/Chart URL Generation
(defn ->legacy-mbql
- "Normalize a MBQL 5 query to legacy MBQL. Frontend /question# URLs require legacy
- MBQL format; non-MBQL 5 values pass through unchanged. A MBQL 5 query that fails
- conversion is also returned unchanged rather than raising."
+ "Convert an MBQL 5 query to legacy MBQL.
+
+ Non-MBQL 5 values and queries that fail conversion are returned unchanged.
+ Use [[->frontend-query]] for frontend links and chart data."
[query]
- ;; builds the legacy-MBQL /question# hash; the FE also accepts MBQL 5, so this could migrate
#_{:clj-kondo/ignore [:discouraged-var]}
(if (and (map? query)
;; `:stages` alone (no `:lib/type`) also counts: a query round-tripped through
@@ -53,10 +54,33 @@
query))
query))
+(defn ->frontend-query
+ "Prepare a query for frontend links and chart data.
+
+ Structured MBQL 5 queries stay in MBQL 5 so temporal filters survive JSON serialization (BOT-1972),
+ and they keep their `:parameters`.
+ Native-only queries use legacy MBQL because the embedding SDK opens its SQL editor only when
+ `dataset_query.type` is `\"native\"`.
+
+ A query with `:stages` but no `:lib/type` stays in MBQL 5 if it normalizes to a valid query.
+ All other values go through [[->legacy-mbql]]."
+ [query]
+ (or (when (and (map? query) (or (:lib/type query) (:stages query)))
+ (try
+ (let [normalized (lib/normalize :metabase.lib.schema/query query)]
+ (when (and (not (lib/native-only-query? normalized))
+ (or (:lib/type query) (mr/validate :metabase.lib.schema/query normalized)))
+ (cond-> (lib/prepare-for-serialization normalized)
+ (:parameters normalized) (assoc :parameters (:parameters normalized)))))
+ (catch Exception e
+ (log/warn e "Failed to normalize MBQL 5 query for the frontend")
+ nil)))
+ (->legacy-mbql query)))
+
(defn- query->url-hash
"Convert an MBQL query to a base64-encoded URL hash for /question# URLs."
[query]
- (-> {:dataset_query (->legacy-mbql query)
+ (-> {:dataset_query (->frontend-query query)
:type "question"
:visualization_settings {}}
json/encode
@@ -64,12 +88,14 @@
codecs/bytes->b64-str))
(defn pseudo-card->link
- "Convert map with relevant card keys into a link. Relevant keys are e.g. dataset_query, display, displayIsLocked.
+ "Convert a map of card properties into a link.
+
+ Relevant keys include `dataset_query`, `display` and `displayIsLocked`.
`:visualization_settings` defaults to `{}` so the frontend always gets a populated map to read chart settings from.
- A MBQL 5 `:dataset_query` is normalized to legacy MBQL (/question# URLs are legacy-only)."
+ `:dataset_query` goes through [[->frontend-query]]."
[pc]
(let [pc (cond-> (merge {:visualization_settings {}} pc)
- (:dataset_query pc) (update :dataset_query ->legacy-mbql))]
+ (:dataset_query pc) (update :dataset_query ->frontend-query))]
(str "/question#"
(-> pc
json/encode
diff --git a/src/metabase/metabot/agent/streaming.clj b/src/metabase/metabot/agent/streaming.clj
index bb5d4be5acb..e01c49408c7 100644
--- a/src/metabase/metabot/agent/streaming.clj
+++ b/src/metabase/metabot/agent/streaming.clj
@@ -168,9 +168,10 @@
:data {:title title}})
(defn viz-part
- "Return the `generated_entity` card data part that surfaces a query/chart result
- to the frontend. Embeds the (legacy) `query` so the FE runs and renders the card
- in the conversation. The caller must supply a distinct `entity-id` (card id) and
+ "Return a `generated_entity` card data part for the frontend.
+
+ The frontend runs and renders `query` in the conversation.
+ The caller must supply a distinct `entity-id` (card ID) and
`query-id`, plus a `title`; `display` and `description` are included when present."
[{:keys [entity-id query-id query display title description]}]
(generated-entity-part
diff --git a/src/metabase/metabot/tools/charts.clj b/src/metabase/metabot/tools/charts.clj
index f09d9ccd7cd..4a4db6ec191 100644
--- a/src/metabase/metabot/tools/charts.clj
+++ b/src/metabase/metabot/tools/charts.clj
@@ -55,7 +55,7 @@
:data-parts [(streaming/viz-part
{:entity-id (:chart-id result)
:query-id (:query-id result)
- :query (links/->legacy-mbql (:query result))
+ :query (links/->frontend-query (:query result))
:display (:chart-type result)
:title title
:description description})]})
@@ -101,7 +101,7 @@
:data-parts [(streaming/viz-part
{:entity-id (or (:chart_id new-chart-data) chart_id)
:query-id (or (:query_id new-chart-data) (str (random-uuid)))
- :query (links/->legacy-mbql query)
+ :query (links/->frontend-query query)
:display new-viz
:title title
:description description})]})
diff --git a/src/metabase/metabot/tools/construct.clj b/src/metabase/metabot/tools/construct.clj
index 79be4a926ec..ef697e7e5c7 100644
--- a/src/metabase/metabot/tools/construct.clj
+++ b/src/metabase/metabot/tools/construct.clj
@@ -970,7 +970,7 @@
:data-parts [(streaming/viz-part
{:entity-id (:chart-id chart)
:query-id (:query-id structured)
- :query (links/->legacy-mbql (:query structured))
+ :query (links/->frontend-query (:query structured))
:display chart-type
:title title
:description description})]})))))
diff --git a/src/metabase/metabot/tools/sql.clj b/src/metabase/metabot/tools/sql.clj
index 1ad260622cb..c20a1eeaf72 100644
--- a/src/metabase/metabot/tools/sql.clj
+++ b/src/metabase/metabot/tools/sql.clj
@@ -104,7 +104,7 @@
:instructions instr
:data-parts [(streaming/viz-part {:entity-id (str (random-uuid))
:query-id query-id
- :query (links/->legacy-mbql query)
+ :query (links/->frontend-query query)
:title title})]})
(let [instr (instructions/sql-validation-error-instructions dialect error-message)]
{:output (format-validation-error-output instr)
@@ -182,7 +182,7 @@
(code-edit-part buffer-id query-content)
(streaming/viz-part {:entity-id (str (random-uuid))
:query-id query-id
- :query (links/->legacy-mbql query)
+ :query (links/->frontend-query query)
:title title}))]})
(let [instr (instructions/sql-validation-error-instructions dialect error-message)]
{:output (format-validation-error-output instr)
@@ -228,7 +228,7 @@
(code-edit-part buffer-id query-content)
(streaming/viz-part {:entity-id (str (random-uuid))
:query-id query-id
- :query (links/->legacy-mbql query)
+ :query (links/->frontend-query query)
:title title}))]})
(let [instr (instructions/sql-validation-error-instructions dialect error-message)]
{:output (format-validation-error-output instr)
diff --git a/test/metabase/metabot/agent/links_test.clj b/test/metabase/metabot/agent/links_test.clj
index 3029490d85a..3f406a25bd6 100644
--- a/test/metabase/metabot/agent/links_test.clj
+++ b/test/metabase/metabot/agent/links_test.clj
@@ -7,6 +7,8 @@
[metabase.lib.test-metadata :as meta]
[metabase.lib.test-util :as lib.tu]
[metabase.metabot.agent.links :as links]
+ [metabase.metabot.tools.charts :as charts]
+ [metabase.metabot.tools.shared :as shared]
[metabase.test :as mt]
[metabase.util :as u]
[metabase.util.json :as json]))
@@ -84,8 +86,88 @@
(is (not (contains? stripped :lib/type)))
(is (= stripped (links/->legacy-mbql stripped))))))
+(deftest ^:parallel pseudo-card->link-keeps-mbql5-temporal-filters-test
+ (testing "temporal filters survive JSON serialization in the /question# hash (BOT-1972)"
+ (let [date (meta/field-metadata :checkins :date)
+ query (lib/query meta/metadata-provider (meta/table-metadata :checkins))
+ year (fn [y] (lib/between date
+ (lib/absolute-datetime (str y "-01-01") :day)
+ (lib/absolute-datetime (str y "-12-31") :day)))]
+ (doseq [[desc filter-clause] {"between with absolute-datetime bounds"
+ (lib/between date
+ (lib/absolute-datetime "2025-01-01" :day)
+ (lib/absolute-datetime "2026-12-31" :day))
+ "during"
+ [:during {:lib/uuid (str (random-uuid))} (lib/ref date) "2026-07-01" :month]
+ "or combines between filters for each year"
+ (lib/or (year 2025) (year 2026))
+ "and combines an equality with a during filter"
+ (lib/and (lib/= (meta/field-metadata :checkins :user-id) 5)
+ [:during {:lib/uuid (str (random-uuid))} (lib/ref date) "2026-07-01" :month])}
+ [query-desc ->sent strip] [["MBQL 5 query" identity identity]
+ ["MBQL 5 query stripped of its :lib/* keys" strip-lib-keys strip-lib-keys]]]
+ (testing (str desc ", " query-desc)
+ (let [query (lib/filter query filter-clause)
+ dataset-query (:dataset_query (decode-question-url (links/pseudo-card->link {:dataset_query (->sent query)})))]
+ (is (= "mbql/query" (:lib/type dataset-query)))
+ (testing "the frontend keeps the filter when it normalizes the hash"
+ (is (= (strip (lib/filters query))
+ (strip (-> dataset-query lib/normalize :stages first :filters)))))))))))
+
+(deftest ^:parallel ->frontend-query-stripped-query-with-aggregation-ref-goes-out-raw-test
+ (testing "a query without :lib/* keys goes out as the raw MBQL 5 query when normalization invalidates its aggregation ref"
+ ;; Normalization assigns a new UUID to the aggregation, so the aggregation ref no longer resolves,
+ ;; and ->legacy-mbql cannot convert the query either.
+ (let [q (-> (lib.tu/venues-query) (lib/aggregate (lib/count)))
+ stripped (strip-lib-keys (lib/order-by q (lib/aggregation-ref q 0) :desc))]
+ (is (= stripped (links/->frontend-query stripped))))))
+
+(deftest ^:parallel ->frontend-query-sends-native-queries-as-legacy-test
+ (let [native (lib/native-query meta/metadata-provider "SELECT * FROM CHECKINS")
+ structured (-> (lib/query meta/metadata-provider (meta/table-metadata :checkins))
+ (lib/filter (lib/between (meta/field-metadata :checkins :date)
+ (lib/absolute-datetime "2025-01-01" :day)
+ (lib/absolute-datetime "2025-12-31" :day))))]
+ (testing "the SDK receives a native query as legacy MBQL and opens it in its SQL editor"
+ (doseq [[desc sent] {"MBQL 5" native
+ "MBQL 5 stripped of its :lib/* keys" (strip-lib-keys native)
+ "MBQL 5 after a JSON round trip" (-> native lib/prepare-for-serialization json/encode json/decode+kw)}]
+ (testing desc
+ (is (= (lib/->legacy-MBQL native)
+ (links/->frontend-query sent))))))
+ (testing "a structured query with a date filter stays MBQL 5"
+ (let [sent (links/->frontend-query structured)]
+ (is (= :mbql/query (:lib/type sent)))
+ (is (= (lib/filters structured) (-> sent :stages first :filters)))))))
+
+(deftest ^:parallel ->frontend-query-keeps-parameters-test
+ (testing "a structured query keeps its :parameters in the /question# link and in the chart data part"
+ (let [parameters [{:id "checkins-month"
+ :type :date/month-year
+ :target [:dimension [:field (meta/id :checkins :date) nil]]
+ :value "2014-07"}]
+ query (assoc (lib/query meta/metadata-provider (meta/table-metadata :checkins))
+ :parameters parameters)
+ expected (json/decode+kw (json/encode parameters))]
+ (testing "in the link"
+ (is (= expected
+ (-> (links/pseudo-card->link {:dataset_query query})
+ decode-question-url
+ :dataset_query
+ :parameters))))
+ (testing "in the chart data part"
+ (is (= expected
+ (-> (binding [shared/*memory-atom* (atom {:state {:queries {"q-1" query}}})]
+ (charts/create-chart-tool {:data_source {:query_id "q-1"}
+ :viz_settings {:chart_type "bar"}
+ :title "Check-ins in July"
+ :description "Check-ins during July 2014."}))
+ (get-in [:data-parts 0 :data :query :query :parameters])
+ json/encode
+ json/decode+kw)))))))
+
(deftest ^:parallel resolve-chart-link-lib-type-less-query-test
- (testing "chart link whose query lost :lib/type resolves to a renderable legacy /question# URL"
+ (testing "a chart link resolves to an MBQL 5 /question# URL even when the query has no :lib/type"
(let [chart-id "chart-fe-1"
fe-query (strip-lib-keys (lib.tu/venues-query))
charts-state {chart-id {:chart_id chart-id
@@ -94,10 +176,11 @@
result (links/resolve-metabase-uri (str "metabase://chart/" chart-id) {} charts-state)
decoded (decode-question-url result)]
(is (str/starts-with? result "/question#"))
- (testing "decoded dataset_query is legacy MBQL — raw pMBQL :stages would crash the FE"
- (is (= "query" (get-in decoded [:dataset_query :type])))
- (is (not (contains? (:dataset_query decoded) :stages)))
- (is (map? (get-in decoded [:dataset_query :query])))))))
+ (testing "the decoded dataset_query is normalized MBQL 5"
+ (is (= "mbql/query" (get-in decoded [:dataset_query :lib/type])))
+ (is (some? (get-in decoded [:dataset_query :database])))
+ (is (= (:stages (strip-lib-keys fe-query))
+ (:stages (strip-lib-keys (:dataset_query decoded)))))))))
;;; resolve-metabase-uri tests
diff --git a/test/metabase/metabot/tools/charts_test.clj b/test/metabase/metabot/tools/charts_test.clj
index b3721882b38..4fa1904185c 100644
--- a/test/metabase/metabot/tools/charts_test.clj
+++ b/test/metabase/metabot/tools/charts_test.clj
@@ -4,14 +4,18 @@
branches on a capability."
(:require
[clojure.test :refer :all]
+ [metabase.lib.core :as lib]
+ [metabase.lib.metadata :as lib.metadata]
+ [metabase.lib.test-metadata :as meta]
[metabase.metabot.tools.charts :as charts]
[metabase.metabot.tools.charts.create :as create-chart-tools]
[metabase.metabot.tools.charts.edit :as edit-chart-tools]
[metabase.metabot.tools.shared :as shared]
- [metabase.test :as mt]))
+ [metabase.test :as mt]
+ [metabase.util.json :as json]))
;; create-chart only needs the query present in queries-state; the link builder
-;; json-encodes it and `->legacy-mbql` passes a non-MBQL 5 value through unchanged,
+;; json-encodes it and `->frontend-query` passes a non-MBQL 5 value through unchanged,
;; so a stub query is enough to exercise the emission branch without a database.
(def ^:private stub-query
{:database 1 :type "query" :query {:source-table 1}})
@@ -45,6 +49,34 @@
(testing "keeps the query in structured-output so chart memory stores it for later edits"
(is (= stub-query (get-in result [:structured-output :query])))))))
+(deftest chart-tools-keep-mbql5-temporal-filter-test
+ (testing "the generated_entity part carries a during filter through JSON intact (BOT-1972)"
+ (let [date (meta/field-metadata :checkins :date)
+ query (-> (lib/query meta/metadata-provider (meta/table-metadata :checkins))
+ (lib/filter [:during {:lib/uuid (str (random-uuid))} (lib/ref date) "2026-07-01" :month]))
+ state {:queries {"q-1" query}
+ :charts {"c-1" {:chart_id "c-1"
+ :query_id "q-1"
+ :queries [query]
+ :visualization_settings {:chart_type :bar}}}}]
+ (doseq [[tool-name run-tool] [["create_chart"
+ #(charts/create-chart-tool {:data_source {:query_id "q-1"}
+ :viz_settings {:chart_type "bar"}
+ :title "Check-ins in July"
+ :description "Check-ins during July 2026."})]
+ ["edit_chart"
+ #(charts/edit-chart-tool {:chart_id "c-1"
+ :new_viz_settings {:chart_type "line"}
+ :title "Check-ins in July"
+ :description "Check-ins during July 2026."})]]]
+ (testing tool-name
+ (let [result (binding [shared/*memory-atom* (atom {:state state})]
+ (run-tool))
+ sent (-> result (get-in [:data-parts 0 :data :query :query]) json/encode (json/decode true))]
+ (is (= "mbql/query" (:lib/type sent)))
+ (is (= (lib/filters query)
+ (-> sent lib/normalize :stages first :filters)))))))))
+
(deftest create-chart-new-chart-types-test
(testing "the tool schema accepts newly added chart types"
(doseq [chart-type ["treemap" "boxplot"]]
@@ -52,6 +84,28 @@
(is (= (keyword chart-type) (get-in result [:structured-output :chart-type])))
(is (= chart-type (get-in result [:data-parts 0 :data :display])))))))
+(deftest create-chart-query-keeps-date-filter-through-dataset-api-test
+ (testing "POST /api/dataset, where the chart in the conversation sends its query, applies its date filter (BOT-1972)"
+ (let [mp (mt/metadata-provider)
+ date (lib.metadata/field mp (mt/id :checkins :date))]
+ (doseq [[filter-desc filter-clause]
+ {"during"
+ [:during {:lib/uuid (str (random-uuid))} (lib/ref date) "2014-07-01" :month]
+ "between with absolute-datetime bounds"
+ (lib/between date (lib/absolute-datetime "2014-07-01" :day) (lib/absolute-datetime "2014-07-31" :day))}]
+ (testing filter-desc
+ (let [query (-> (lib/query mp (lib.metadata/table mp (mt/id :checkins)))
+ (lib/filter filter-clause)
+ (lib/aggregate (lib/count)))
+ result (binding [shared/*memory-atom* (atom {:state {:queries {"q-1" query}}})]
+ (charts/create-chart-tool {:data_source {:query_id "q-1"}
+ :viz_settings {:chart_type "scalar"}
+ :title "Check-ins in July 2014"
+ :description "Check-ins during July 2014."}))
+ body (-> result (get-in [:data-parts 0 :data :query :query]) json/encode json/decode)]
+ (is (= (mt/first-row (mt/process-query query))
+ (mt/first-row (mt/user-http-request :crowberto :post 202 "dataset" body))))))))))
+
(deftest edit-chart-query-fallback-test
(testing "edit_chart resolves the query from queries-state when chart memory has no query"
(let [memory (atom {:state {:queries {"q-1" stub-query}
diff --git a/test/metabase/metabot/tools/sql_test.clj b/test/metabase/metabot/tools/sql_test.clj
index 8eb4f602cfa..cb4b6a84ef8 100644
--- a/test/metabase/metabot/tools/sql_test.clj
+++ b/test/metabase/metabot/tools/sql_test.clj
@@ -213,36 +213,40 @@
(is (str/starts-with? instructions "The SQL query has a syntax error"))
(is (str/starts-with? output "<result>\nSQL query construction failed.\n</result>\n<instructions>\nThe SQL query has a syntax error")))))))))
-(deftest edit-sql-query-viz-part-test
- (testing "edit_sql_query emits a generated_entity card unless an open code-editor buffer wins"
+(deftest edit-and-replace-sql-query-viz-part-test
+ (testing "edit_sql_query and replace_sql_query emit a generated_entity card unless a code-editor buffer is open"
(mt/test-drivers #{:h2}
(mt/with-current-user (mt/user->id :crowberto)
(mt/with-temp [:model/Database {:as db} {:engine :h2}]
(mt/with-db db
(let [mp (mt/metadata-provider)
query-id "test-inline-q"
- query (-> (lib/native-query mp "SELECT * FROM t") lib/->legacy-MBQL)
- run (fn [context]
- (let [memory (atom {:state {:queries {query-id query}}
- :context context})]
- (binding [shared/*memory-atom* memory]
- (agent-sql/edit-sql-query-tool
- {:query_id query-id
- :checklist "- [x] checked"
- :edits [{:old_string "SELECT *" :new_string "SELECT id"}]
- :title "Results"}))))]
- (testing "no code-editor buffer -> a single generated_entity (native) part"
- (let [parts (:data-parts (run {}))
- entity (:data (first parts))]
- (is (= 1 (count parts)))
- (is (= "generated_entity" (:data-type (first parts))))
- (is (= "card" (:type entity)))
- (is (= :native (get-in entity [:query :query :type])))))
- (testing "an open code-editor buffer wins"
- (let [parts (:data-parts (run {:user_is_viewing [{:type "code_editor"
- :buffers [{:id "buf-1" :source {:language "sql" :database_id nil} :cursor {:line 0 :column 0}}]}]}))]
- (is (= 1 (count parts)))
- (is (= "code_edit" (:data-type (first parts)))))))))))))
+ query (-> (lib/native-query mp "SELECT * FROM t") lib/->legacy-MBQL)]
+ (doseq [[tool-name tool args] [["edit_sql_query" agent-sql/edit-sql-query-tool
+ {:edits [{:old_string "SELECT *" :new_string "SELECT id"}]}]
+ ["replace_sql_query" agent-sql/replace-sql-query-tool
+ {:new_query "SELECT id FROM t"}]]
+ :let [run (fn [context]
+ (let [memory (atom {:state {:queries {query-id query}}
+ :context context})]
+ (binding [shared/*memory-atom* memory]
+ (tool (assoc args
+ :query_id query-id
+ :checklist "- [x] checked"
+ :title "Results")))))]]
+ (testing tool-name
+ (testing "a single generated_entity part carries a legacy native query when no code-editor buffer is open"
+ (let [parts (:data-parts (run {}))
+ entity (:data (first parts))]
+ (is (= 1 (count parts)))
+ (is (= "generated_entity" (:data-type (first parts))))
+ (is (= "card" (:type entity)))
+ (is (= :native (get-in entity [:query :query :type])))))
+ (testing "an open code-editor buffer receives a code_edit part"
+ (let [parts (:data-parts (run {:user_is_viewing [{:type "code_editor"
+ :buffers [{:id "buf-1" :source {:language "sql" :database_id nil} :cursor {:line 0 :column 0}}]}]}))]
+ (is (= 1 (count parts)))
+ (is (= "code_edit" (:data-type (first parts)))))))))))))))
(def ^:private no-native-permission-output
"You do not have permission to write SQL queries against this database. Native query permissions are required.")
diff --git a/test/metabase/metabot/tools_test.clj b/test/metabase/metabot/tools_test.clj
index 47f61c75a4c..843a366b7c0 100644
--- a/test/metabase/metabot/tools_test.clj
+++ b/test/metabase/metabot/tools_test.clj
@@ -4,6 +4,8 @@
[clojure.test :refer :all]
[metabase.api-scope.core :as api-scope]
[metabase.channel.settings :as channel.settings]
+ [metabase.lib.core :as lib]
+ [metabase.lib.test-metadata :as meta]
[metabase.metabot.agent.profiles :as profiles]
[metabase.metabot.scope :as scope]
[metabase.metabot.test-util :as test-util]
@@ -15,6 +17,7 @@
[metabase.notification.models :as models.notification]
[metabase.search.entity-retrieval.core :as entity-retrieval]
[metabase.test :as mt]
+ [metabase.util.json :as json]
[toucan2.core :as t2]))
(deftest all-tools-test
@@ -198,6 +201,27 @@
(is (= "Total order count."
(get-in result [:data-parts 0 :data :description]))))))))
+(deftest construct-notebook-query-keeps-mbql5-temporal-filter-test
+ (testing "the generated_entity part carries a between filter of absolute-datetime bounds through JSON intact (BOT-1972)"
+ (let [query (-> (lib/query meta/metadata-provider (meta/table-metadata :checkins))
+ (lib/filter (lib/between (meta/field-metadata :checkins :date)
+ (lib/absolute-datetime "2026-07-01" :day)
+ (lib/absolute-datetime "2026-07-31" :day))))]
+ (mt/with-dynamic-fn-redefs [construct/execute-representations-query
+ (fn [_ & _]
+ {:structured-output {:query-id "q-1"
+ :query query
+ :result-columns []}})]
+ (let [result (binding [shared/*profile-id* :nlq]
+ (test-util/call-tool agent-tools/construct-notebook-query-tool
+ {:query {:lib/type "mbql/query" :stages []}
+ :title "Check-ins in July"
+ :description "Check-ins during July 2026."}))
+ sent (-> result (get-in [:data-parts 0 :data :query :query]) json/encode (json/decode true))]
+ (is (= "mbql/query" (:lib/type sent)))
+ (is (= (lib/filters query)
+ (-> sent lib/normalize :stages first :filters))))))))
+
(deftest construct-notebook-query-tool-show-chart-test
(let [construct! (fn [tool-names show-chart-arg]
(let [chart-created? (atom false)]