Skip to content

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

Fix metabot construct-query bugs: string-filter options + skill gaps (#76015)

Mihael Konjević665fed1d4f0a
diff --git a/resources/metabot/skills/construct-notebook-query-advanced.md b/resources/metabot/skills/construct-notebook-query-advanced.md
index 4fca8cad7c7..01fe3465411 100644
--- a/resources/metabot/skills/construct-notebook-query-advanced.md
+++ b/resources/metabot/skills/construct-notebook-query-advanced.md
@@ -104,7 +104,7 @@ Re-aggregate — average daily total by month:
]
```
-- Cross-stage refs use a **string name** in slot 3 (e.g. `["field", {}, "count"]`). The name is whatever the previous stage's aggregation/breakout/field produced (`count`, `sum`, or the source field's name).
+- Cross-stage refs use a **string name** in slot 3 (e.g. `["field", {}, "count"]`). The name is whatever the previous stage's aggregation/breakout/field produced (`count`, `sum`, or the source field's name). A `distinct` (count-of-distinct-values) aggregation produces a column named **`count`** — reference it as `["field", {}, "count"]`, not `"distinct"`.
- Within the **same stage**, refer to your own aggregation with `["aggregation", {}, <idx>]` (see Aggregation references above). In a **later** stage, use the cross-stage string-name form against the previous stage's output.
- Joins, expressions, filters, aggregation, breakout, order-by, limit are all valid in later stages.
@@ -162,14 +162,36 @@ A metric is a pre-defined aggregation attached to a base table. To use one:
```json
{"lib/type": "mbql.stage/mbql",
- "source-table": ["Analytics", "brex_enriched", "fct_cards"],
- "filters": [["!=", {}, ["field", {},
- ["Analytics", "brex_enriched", "fct_cards", "card_status"]], "inactive"]],
+ "source-table": ["Sample Database", "PUBLIC", "ORDERS"],
+ "filters": [[">", {}, ["field", {},
+ ["Sample Database", "PUBLIC", "ORDERS", "TOTAL"]], 0]],
"aggregation": [["metric", {}, "aB3cD4eF5gH6iJ7kL8mN9"]]}
```
Metrics are aggregations, **not sources** — never put a metric in `source-table` or `source-card`. The `metabase://metric/<id>` URIs are for reading metadata via `read_resource`, not for embedding in queries.
+### Breaking out a metric by a dimension on another table
+
+To group a metric by a field that lives on a **different** table, add an explicit `joins` entry and break out on the join-aliased field. Do **not** break out (or order) a metric by a field reached only through an implicit foreign-key reference — the query processor cannot resolve an implicit join against a metric aggregation and rejects the query with a 400. Source the metric's base table, reference the metric in `aggregation`, join the dimension table, and break out on the joined column:
+
+```json
+{"lib/type": "mbql.stage/mbql",
+ "source-table": ["Sample Database", "PUBLIC", "ORDERS"],
+ "aggregation": [["metric", {}, "aB3cD4eF5gH6iJ7kL8mN9"]],
+ "joins": [{"alias": "Products",
+ "strategy": "left-join",
+ "stages": [{"lib/type": "mbql.stage/mbql",
+ "source-table": ["Sample Database", "PUBLIC", "PRODUCTS"]}],
+ "conditions": [["=", {},
+ ["field", {}, ["Sample Database", "PUBLIC", "ORDERS", "PRODUCT_ID"]],
+ ["field", {"join-alias": "Products"},
+ ["Sample Database", "PUBLIC", "PRODUCTS", "ID"]]]}],
+ "breakout": [["field", {"join-alias": "Products"},
+ ["Sample Database", "PUBLIC", "PRODUCTS", "CATEGORY"]]]}
+```
+
+When the breakout dimension lives on the metric's **own** base table, no join is needed — just break out on a portable FK as in the example above.
+
## Using measures and segments
A measure or segment can be referenced two ways. **Prefer the opaque-id clause** — it preserves the measure/segment's identity in the rendered notebook (chip with the official name, click-through to the definition, lineage tooling sees the dependency, definition updates propagate).
diff --git a/src/metabase/agent_lib/representations/repair.clj b/src/metabase/agent_lib/representations/repair.clj
index 15033731199..552c84f86dc 100644
--- a/src/metabase/agent_lib/representations/repair.clj
+++ b/src/metabase/agent_lib/representations/repair.clj
@@ -489,6 +489,53 @@
node))
form))
+;;; ============================================================
+;;; Pass 1.89 -- merge a trailing options-map into position-1 on N-ary string-search filters
+;;; (`contains` / `does-not-contain` / `starts-with` / `ends-with`).
+;;;
+;;; These four string filters are N-ary in MBQL (`[op opts field val1 val2 …]`, at least two
+;;; string args) and carry their `case-sensitive` flag in the position-1 options map (see
+;;; `metabase.lib.schema.filter/string-filter-options`). Because they're variadic, the
+;;; fixed-arity [[merge-trailing-options*]] pass deliberately skips them -- there, a trailing
+;;; map could be a legitimate arg. LLMs nonetheless append the case-sensitivity options as a
+;;; trailing element, e.g.
+;;;
+;;; ["contains" {} <field> "@gmail.com" {"case-sensitive" false}]
+;;;
+;;; A string-search value is always a string, never a map, so a trailing map is unambiguously
+;;; misplaced options. We merge it into position-1 (trailing keys win) and drop it. Left
+;;; unrepaired, `lib.normalize` cannot normalise the clause and the query explodes downstream
+;;; with a missing-`lib/uuid` "Invalid output" error.
+;;;
+;;; Runs after [[ensure-clause-options*]] so position 1 is already a map. Idempotent: the
+;;; repaired clause's last element is a string arg, so the predicate fails on a second pass.
+;;; ============================================================
+
+(def ^:private string-search-filter-heads
+ "N-ary string-search filter heads whose options (e.g. `case-sensitive`) belong in the
+ position-1 options map. See `metabase.lib.schema.filter`."
+ #{"contains" "does-not-contain" "starts-with" "ends-with"})
+
+(defn- needs-string-filter-options-merge?
+ "True when `node` is an N-ary string-search filter whose last element is a misplaced trailing
+ options map (the args before it are string values, never maps). See the pass docstring above."
+ [node]
+ (and (clause-like? node)
+ (contains? string-search-filter-heads (nth node 0))
+ ;; head + opts + field + >=1 value + trailing options-map
+ (>= (count node) 5)
+ (map? (nth node 1))
+ (map? (peek node))))
+
+(defn- merge-string-filter-trailing-options*
+ [form]
+ (walk/postwalk
+ (fn [node]
+ (if (needs-string-filter-options-merge? node)
+ (merge-trailing-options node)
+ node))
+ form))
+
;;; ============================================================
;;; Pass 1.84 -- normalise alternative `case` / `if` argument shapes.
;;;
@@ -2513,6 +2560,7 @@
rewrite-temporal-bucket-aliases*
rewrite-direction-aliases*
merge-trailing-options*
+ merge-string-filter-trailing-options*
wrap-iso-date-bounds*
wrap-now-literals*
swap-between-bounds*
diff --git a/test/metabase/agent_lib/representations/repair_test.clj b/test/metabase/agent_lib/representations/repair_test.clj
index 8592b24b40b..02f44dba3d3 100644
--- a/test/metabase/agent_lib/representations/repair_test.clj
+++ b/test/metabase/agent_lib/representations/repair_test.clj
@@ -2874,3 +2874,75 @@
(is (not (contains? counts "or")))
(is (not (contains? counts "case")))
(is (not (contains? counts "coalesce")))))))
+
+;;; ============================================================
+;;; Pass 1.89 - merge trailing options-map into position-1 opts on N-ary string filters
+;;; ============================================================
+
+(deftest ^:parallel merge-string-filter-trailing-options-test
+ (testing (str "N-ary string-search filters carry case-sensitivity in their position-1 options,\n"
+ "but LLMs append it as a trailing map. These clauses are variadic, so the\n"
+ "fixed-arity merge-trailing-options pass skips them; this pass merges the trailing\n"
+ "map (a string-search value is never a map, so it is unambiguously misplaced opts).")
+ (testing "contains"
+ (is (= ["contains" {"case-sensitive" false}
+ ["field" {} ["S" "P" "T" "EMAIL"]] "@gmail.com"]
+ (repair/repair trivial-mp
+ ["contains" {}
+ ["field" {} ["S" "P" "T" "EMAIL"]] "@gmail.com"
+ {"case-sensitive" false}]))))
+ (testing "starts-with / ends-with / does-not-contain"
+ (doseq [head ["starts-with" "ends-with" "does-not-contain"]]
+ (is (= [head {"case-sensitive" false} ["field" {} ["S" "P" "T" "C"]] "x"]
+ (repair/repair trivial-mp
+ [head {} ["field" {} ["S" "P" "T" "C"]] "x"
+ {"case-sensitive" false}]))
+ head)))))
+
+(deftest ^:parallel merge-string-filter-trailing-options-multi-value-test
+ (testing "multiple string values + trailing options: only the trailing map is merged"
+ (is (= ["contains" {"case-sensitive" true} ["field" {} ["S" "P" "T" "C"]] "a" "b"]
+ (repair/repair trivial-mp
+ ["contains" {} ["field" {} ["S" "P" "T" "C"]] "a" "b"
+ {"case-sensitive" true}])))))
+
+(deftest ^:parallel merge-string-filter-trailing-options-keys-win-test
+ (testing "trailing keys win on conflict; existing position-1 keys are preserved"
+ (is (= ["contains" {"case-sensitive" false "lib/uuid" "u"} ["field" {} ["S" "P" "T" "C"]] "x"]
+ (repair/repair trivial-mp
+ ["contains" {"case-sensitive" true "lib/uuid" "u"}
+ ["field" {} ["S" "P" "T" "C"]] "x"
+ {"case-sensitive" false}])))))
+
+(deftest ^:parallel merge-string-filter-trailing-options-nested-in-and-test
+ (testing (str "a contains clause with trailing case-sensitivity options, nested inside `and`\n"
+ "inside the stage filters (the gmail-customers repro), is repaired via postwalk")
+ (let [q {"lib/type" "mbql/query"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "filters" [["and" {}
+ ["=" {} ["field" {} ["Sample" "PUBLIC" "ORDERS" "STATUS"]] "active"]
+ ["contains" {}
+ ["field" {} ["Sample" "PUBLIC" "ORDERS" "STATUS"]]
+ "@gmail.com" {"case-sensitive" false}]]]}]}
+ out (repair/repair trivial-mp q)
+ ;; and-clause is ["and" {} <=-cond> <contains-cond>]; the contains is at index 3
+ c (get-in out ["stages" 0 "filters" 0 3])]
+ (is (= ["contains" {"case-sensitive" false}
+ ["field" {} ["Sample" "PUBLIC" "ORDERS" "STATUS"]] "@gmail.com"]
+ c)))))
+
+(deftest ^:parallel merge-string-filter-trailing-options-no-op-test
+ (testing "well-formed string filters are unchanged"
+ (testing "options already in position 1"
+ (let [ok ["contains" {"case-sensitive" false} ["field" {} ["S" "P" "T" "C"]] "x"]]
+ (is (= ok (repair/repair trivial-mp ok)))))
+ (testing "plain contains with no trailing options map"
+ (let [ok ["contains" {} ["field" {} ["S" "P" "T" "C"]] "x"]]
+ (is (= ok (repair/repair trivial-mp ok)))))))
+
+(deftest ^:parallel merge-string-filter-trailing-options-idempotent-test
+ (testing "repair(repair(q)) = repair(q)"
+ (let [bug ["contains" {} ["field" {} ["S" "P" "T" "C"]] "x" {"case-sensitive" false}]
+ once (repair/repair trivial-mp bug)]
+ (is (= once (repair/repair trivial-mp once))))))