Skip to content

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

[BOT-1367] Representations based notebook query tooling (#73052)

Oleksandr Solovyovaf995a8deacf
diff --git a/.clj-kondo/config/modules/config.edn b/.clj-kondo/config/modules/config.edn
index 5fbd9803eab..83266562c9c 100644
--- a/.clj-kondo/config/modules/config.edn
+++ b/.clj-kondo/config/modules/config.edn
@@ -158,8 +158,7 @@
{:team "Metabot"
:api #{metabase.agent-api.api
metabase.agent-api.init}
- :uses #{agent-lib
- api
+ :uses #{api
auth-identity
dashboards
events
@@ -175,12 +174,16 @@
:model-imports #{:model/Card
:model/Dashboard
:model/DashboardCard
+ :model/Table
:model/User}}
agent-lib
{:team "Metabot"
- :api #{metabase.agent-lib.core}
+ :api #{metabase.agent-lib.representations
+ metabase.agent-lib.representations.repair
+ metabase.agent-lib.representations.resolve}
:uses #{lib
+ models
util}}
analytics
@@ -1279,8 +1282,10 @@
:model/Database
:model/Field
:model/Glossary
+ :model/Measure
:model/ModerationReview
:model/QueryTable
+ :model/Segment
:model/Table
:model/Transform
:model/User}}
@@ -1341,6 +1346,7 @@
metabase.models.resolution
metabase.models.serialization
metabase.models.serialization.resolve
+ metabase.models.serialization.resolve.mp
metabase.models.util.spec-update
metabase.models.visualization-settings}
:uses #{api
@@ -1356,6 +1362,7 @@
:model/DashboardTab
:model/Database
:model/Field
+ :model/Measure
:model/NativeQuerySnippet
:model/Segment
:model/Table
diff --git a/docs/api.json b/docs/api.json
index 641d6d7f0c2..f193ed85126 100644
--- a/docs/api.json
+++ b/docs/api.json
@@ -3490,38 +3490,20 @@
"required" : [ "name", "base_type", "display_name" ]
},
"metabase.agent-api.api.construct-query-request" : {
- "description" : "Request body for /v2/construct-query. Same as program-request, with an optional prompt\n capturing the user's original intent when a caller has one.",
+ "description" : "Request body for /v2/construct-query and the fresh-query branch of /v2/query.\n A single `:query` key whose value is a JSON object matching\n [[metabase.lib.schema/external-query]] — the canonical portable MBQL 5 wire format. The\n query is fully self-describing: the database is derived from the first stage's\n `source-table:` or `source-card:`, all field references are portable FKs\n (`[<db-name>, <schema>, <table-name>, <column-name>]`), and there is no auxiliary\n `source_entity` / `referenced_entities` envelope. See\n `resources/metabot/prompts/tools/construct_notebook_query.md` for the full format reference\n (including operators, joins, expressions, multi-stage queries, and FK conventions).\n\n Closed map: any extra top-level keys (notably the legacy `source_entity` /\n `referenced_entities` envelope from before the repr migration) are rejected with a 400 so\n callers don't silently send fields the server ignores.",
"type" : "object",
"properties" : {
- "operations" : {
- "type" : "array",
- "items" : {
- "$ref" : "#/components/schemas/metabase.agent-lib.schema.top-level-op"
- }
- },
- "prompt" : {
- "type" : "string",
- "minLength" : 1,
- "maxLength" : 10000,
- "description" : "The user's exact original message, when available. Pass it as-is without summarizing or rewriting."
- },
- "source" : {
- "$ref" : "#/components/schemas/metabase.agent-lib.schema.source"
+ "query" : {
+ "$ref" : "#/components/schemas/metabase.lib.schema.external-query"
}
},
- "required" : [ "source", "operations" ],
+ "required" : [ "query" ],
"additionalProperties" : false
},
"metabase.agent-api.api.construct-query-response" : {
- "description" : "Response containing a base64-encoded MBQL query and, when supplied, the original prompt for use with /v1/execute.",
+ "description" : "Response containing a base64-encoded MBQL query for use with /v1/execute.",
"type" : "object",
"properties" : {
- "prompt" : {
- "type" : "string",
- "minLength" : 1,
- "maxLength" : 10000,
- "description" : "The user's exact original message, when available. Pass it as-is without summarizing or rewriting."
- },
"query" : {
"type" : "string",
"minLength" : 1
@@ -3968,12 +3950,8 @@
},
"required" : [ "id", "type", "name" ]
},
- "metabase.agent-api.api.program-request" : {
- "description" : "Request body for /v2/query.\n An agent-lib structured program with `:source` and `:operations`. The top-level\n `:source` must reference a database entity (`table`, `card`, `dataset`, or\n `metric`); `context` and nested `program` sources are rejected at the HTTP\n boundary by [[evaluate-program-for-execution]] because they require an\n in-process evaluation context.",
- "$ref" : "#/components/schemas/metabase.agent-lib.schema.program"
- },
"metabase.agent-api.api.query-request" : {
- "description" : "Request body for /v2/query. Accepts either a structured program or a continuation_token.",
+ "description" : "Request body for /v2/query. Accepts either a fresh-query payload (`{:query <external-query>}`,\n same shape as /v2/construct-query) or a `:continuation_token` from a prior response.\n\n Both branches are closed maps: extra top-level keys (e.g. the legacy\n `source_entity` / `referenced_entities` envelope, or sending `:query` and\n `:continuation_token` simultaneously) are rejected with a 400.",
"oneOf" : [ {
"type" : "object",
"properties" : {
@@ -3982,9 +3960,10 @@
"minLength" : 1
}
},
- "required" : [ "continuation_token" ]
+ "required" : [ "continuation_token" ],
+ "additionalProperties" : false
}, {
- "$ref" : "#/components/schemas/metabase.agent-api.api.program-request"
+ "$ref" : "#/components/schemas/metabase.agent-api.api.construct-query-request"
} ]
},
"metabase.agent-api.api.query-response" : {
@@ -4402,302 +4381,6 @@
},
"required" : [ "id", "type", "name", "display_name", "database_id", "database_engine", "fields" ]
},
- "metabase.agent-lib.schema.aggregation-ref-form" : {
- "type" : "array",
- "prefixItems" : [ {
- "const" : "aggregation-ref"
- }, {
- "type" : "integer",
- "minimum" : 0
- } ]
- },
- "metabase.agent-lib.schema.expression-ref-form" : {
- "type" : "array",
- "prefixItems" : [ {
- "const" : "expression-ref"
- }, {
- "$ref" : "#/components/schemas/metabase.agent-lib.schema.non-blank-string"
- } ]
- },
- "metabase.agent-lib.schema.form" : {
- "anyOf" : [ {
- "$ref" : "#/components/schemas/metabase.agent-lib.schema.source-ref"
- }, {
- "$ref" : "#/components/schemas/metabase.agent-lib.schema.query-aware-ref"
- }, {
- "$ref" : "#/components/schemas/metabase.agent-lib.schema.nested-operator-form"
- } ]
- },
- "metabase.agent-lib.schema.map-literal" : {
- "type" : "object",
- "additionalProperties" : {
- "$ref" : "#/components/schemas/metabase.agent-lib.schema.node"
- }
- },
- "metabase.agent-lib.schema.nested-operator-form" : {
- "type" : "array",
- "items" : {
- "$ref" : "#/components/schemas/metabase.agent-lib.schema.node"
- },
- "minItems" : 1
- },
- "metabase.agent-lib.schema.node" : {
- "anyOf" : [ {
- "$ref" : "#/components/schemas/metabase.agent-lib.schema.scalar"
- }, {
- "$ref" : "#/components/schemas/metabase.agent-lib.schema.program-literal"
- }, {
- "$ref" : "#/components/schemas/metabase.agent-lib.schema.map-literal"
- }, {
- "$ref" : "#/components/schemas/metabase.agent-lib.schema.form"
- }, {
- "$ref" : "#/components/schemas/metabase.agent-lib.schema.vector-literal"
- } ]
- },
- "metabase.agent-lib.schema.non-blank-string" : {
- "type" : "string"
- },
- "metabase.agent-lib.schema.page" : {
- "type" : "object",
- "properties" : {
- "items" : {
- "description" : "value must be an integer greater than zero.",
- "type" : "integer",
- "minimum" : 1
- },
- "page" : {
- "description" : "value must be an integer greater than zero.",
- "type" : "integer",
- "minimum" : 1
- }
- },
- "required" : [ "page", "items" ],
- "additionalProperties" : false
- },
- "metabase.agent-lib.schema.program" : {
- "type" : "object",
- "properties" : {
- "operations" : {
- "type" : "array",
- "items" : {
- "$ref" : "#/components/schemas/metabase.agent-lib.schema.top-level-op"
- }
- },
- "source" : {
- "$ref" : "#/components/schemas/metabase.agent-lib.schema.source"
- }
- },
- "required" : [ "source", "operations" ],
- "additionalProperties" : false
- },
- "metabase.agent-lib.schema.program-literal" : {
- "type" : "object",
- "properties" : {
- "program" : {
- "$ref" : "#/components/schemas/metabase.agent-lib.schema.program"
- },
- "type" : {
- "const" : "program"
- }
- },
- "required" : [ "type", "program" ],
- "additionalProperties" : false
- },
- "metabase.agent-lib.schema.query-aware-ref" : {
- "anyOf" : [ {
- "$ref" : "#/components/schemas/metabase.agent-lib.schema.expression-ref-form"
- }, {
- "$ref" : "#/components/schemas/metabase.agent-lib.schema.aggregation-ref-form"
- } ]
- },
- "metabase.agent-lib.schema.scalar" : {
- "anyOf" : [ {
- "type" : "null"
- }, {
- "type" : "string"
- }, {
- "type" : "number"
- }, {
- "type" : "boolean"
- } ]
- },
- "metabase.agent-lib.schema.source" : {
- "anyOf" : [ {
- "type" : "object",
- "properties" : {
- "ref" : {
- "const" : "source"
- },
- "type" : {
- "const" : "context"
- }
- },
- "required" : [ "type", "ref" ],
- "additionalProperties" : false
- }, {
- "type" : "object",
- "properties" : {
- "id" : {
- "description" : "value must be an integer greater than zero.",
- "type" : "integer",
- "minimum" : 1
- },
- "type" : {
- "type" : "string",
- "enum" : [ "table", "card", "dataset", "metric" ]
- }
- },
- "required" : [ "type", "id" ],
- "additionalProperties" : false
- }, {
- "$ref" : "#/components/schemas/metabase.agent-lib.schema.program-literal"
- } ]
- },
- "metabase.agent-lib.schema.source-ref" : {
- "anyOf" : [ {
- "type" : "array",
- "prefixItems" : [ {
- "const" : "field"
- }, {
- "description" : "value must be an integer greater than zero.",
- "type" : "integer",
- "minimum" : 1
- } ]
- }, {
- "type" : "array",
- "prefixItems" : [ {
- "const" : "table"
- }, {
- "description" : "value must be an integer greater than zero.",
- "type" : "integer",
- "minimum" : 1
- } ]
- }, {
- "type" : "array",
- "prefixItems" : [ {
- "const" : "card"
- }, {
- "description" : "value must be an integer greater than zero.",
- "type" : "integer",
- "minimum" : 1
- } ]
- }, {
- "type" : "array",
- "prefixItems" : [ {
- "const" : "metric"
- }, {
- "description" : "value must be an integer greater than zero.",
- "type" : "integer",
- "minimum" : 1
- } ]
- } ]
- },
- "metabase.agent-lib.schema.top-level-op" : {
- "anyOf" : [ {
- "type" : "array",
- "prefixItems" : [ {
- "const" : "filter"
- }, {
- "$ref" : "#/components/schemas/metabase.agent-lib.schema.form"
- } ]
- }, {
- "type" : "array",
- "prefixItems" : [ {
- "const" : "aggregate"
- }, {
- "$ref" : "#/components/schemas/metabase.agent-lib.schema.form"
- } ]
- }, {
- "type" : "array",
- "prefixItems" : [ {
- "const" : "breakout"
- }, {
- "$ref" : "#/components/schemas/metabase.agent-lib.schema.form"
- } ]
- }, {
- "type" : "array",
- "prefixItems" : [ {
- "const" : "with-fields"
- }, {
- "type" : "array",
- "items" : {
- "$ref" : "#/components/schemas/metabase.agent-lib.schema.form"
- }
- } ]
- }, {
- "type" : "array",
- "prefixItems" : [ {
- "const" : "limit"
- }, {
- "description" : "value must be an integer greater than zero.",
- "type" : "integer",
- "minimum" : 1
- } ]
- }, {
- "type" : "array",
- "prefixItems" : [ {
- "const" : "expression"
- }, {
- "$ref" : "#/components/schemas/metabase.agent-lib.schema.non-blank-string"
- }, {
- "$ref" : "#/components/schemas/metabase.agent-lib.schema.form"
- } ]
- }, {
- "type" : "array",
- "prefixItems" : [ {
- "const" : "join"
- }, {
- "$ref" : "#/components/schemas/metabase.agent-lib.schema.form"
- } ]
- }, {
- "anyOf" : [ {
- "type" : "array",
- "prefixItems" : [ {
- "const" : "order-by"
- }, {
- "$ref" : "#/components/schemas/metabase.agent-lib.schema.form"
- } ]
- }, {
- "type" : "array",
- "prefixItems" : [ {
- "const" : "order-by"
- }, {
- "$ref" : "#/components/schemas/metabase.agent-lib.schema.form"
- }, {
- "type" : "string",
- "enum" : [ "asc", "desc" ]
- } ]
- } ]
- }, {
- "type" : "array",
- "prefixItems" : [ {
- "const" : "append-stage"
- } ]
- }, {
- "type" : "array",
- "prefixItems" : [ {
- "const" : "drop-stage"
- } ]
- }, {
- "type" : "array",
- "prefixItems" : [ {
- "const" : "drop-empty-stages"
- } ]
- }, {
- "type" : "array",
- "prefixItems" : [ {
- "const" : "with-page"
- }, {
- "$ref" : "#/components/schemas/metabase.agent-lib.schema.page"
- } ]
- } ]
- },
- "metabase.agent-lib.schema.vector-literal" : {
- "type" : "array",
- "items" : {
- "$ref" : "#/components/schemas/metabase.agent-lib.schema.node"
- }
- },
"metabase.analyze.query-results.ResultsMetadata" : {
"description" : "value must be an array of valid results column metadata maps.",
"oneOf" : [ {
@@ -6592,7 +6275,8 @@
"lib/uuid" : {
"type" : "string",
"minLength" : 36,
- "maxLength" : 36
+ "maxLength" : 36,
+ "$ref" : "#/components/schemas/metabase.lib.schema.common.uuid"
},
"name" : {
"oneOf" : [ {
@@ -8885,6 +8569,10 @@
"metabase.lib.schema.expression.window..offset.n" : {
"type" : "integer"
},
+ "metabase.lib.schema.external-query" : {
+ "description" : "Schema for \"External MBQL\" 5 query.",
+ "$ref" : "#/components/schemas/metabase.lib.schema.query"
+ },
"metabase.lib.schema.fields" : {
"allOf" : [ {
"type" : "array",
@@ -8982,6 +8670,13 @@
"description" : "The ID used to signify that a database is 'virtual' rather than physical.\n\n A fake integer ID is used so as to minimize the number of changes that need to be made on the frontend -- by using\n something that would otherwise be a legal ID, *nothing* need change there, and the frontend can query against this\n 'database' none the wiser. (This integer ID is negative which means it will never conflict with a *real* database\n ID.)\n\n This ID acts as a sort of flag. The relevant places in the middleware can check whether the DB we're querying is\n this 'virtual' database and take the appropriate actions.",
"const" : -1337
},
+ "metabase.lib.schema.id.schema" : {
+ "anyOf" : [ {
+ "type" : "null"
+ }, {
+ "type" : "string"
+ } ]
+ },
"metabase.lib.schema.id.segment" : {
"description" : "Valid legacy Segment ID",
"type" : "integer",
@@ -15380,7 +15075,7 @@
"post" : {
"operationId" : "post-api-agent-v2-construct-query",
"summary" : "POST /api/agent/v2/construct-query",
- "description" : "Construct an MBQL query from a structured agent-lib program.\n\n The body is the program itself: a JSON object with `source` (identifying the\n table/card/dataset/metric to query), `operations` (an array of operator\n tuples), and `prompt` (the user's original request). Returns a base64-encoded\n MBQL query that can be executed via /v1/execute. See the agent_api reference\n for the full program syntax.",
+ "description" : "Construct an MBQL query from a portable MBQL 5 representations JSON payload.\n\n The body is `{\"query\": <external-query>}` where `<external-query>` is a JSON object\n matching `::lib.schema/external-query` — see the `construct_notebook_query` tool\n documentation for the format reference. Returns a base64-encoded MBQL query that can be\n executed via /v1/execute or paginated via /v2/query.",
"parameters" : [ ],
"responses" : {
"2XX" : {
@@ -15416,7 +15111,7 @@
"post" : {
"operationId" : "post-api-agent-v2-query",
"summary" : "POST /api/agent/v2/query",
- "description" : "Execute a structured program and stream the results, with continuation-token pagination.\n\n Accepts either a program (same shape as /v2/construct-query) or a\n `continuation_token` from a previous response. Returns results with column\n metadata and an optional `continuation_token` for fetching the next page.",
+ "description" : "Execute a portable MBQL 5 representations JSON query and stream the results, with\n continuation-token pagination.\n\n Accepts either a JSON body (same shape as /v2/construct-query) or a `continuation_token`\n from a previous response. Returns results with column metadata and an optional\n `continuation_token` for fetching the next page.",
"parameters" : [ ],
"responses" : {
"2XX" : {
diff --git a/resources/metabase/agent_api/construct_query.md b/resources/metabase/agent_api/construct_query.md
deleted file mode 100644
index 2f9ad96b21d..00000000000
--- a/resources/metabase/agent_api/construct_query.md
+++ /dev/null
@@ -1,144 +0,0 @@
-# Construct Query Reference
-
-Construct a Metabase MBQL query from a structured program. The body is the program itself — no envelope — shaped:
-
-```
-{"source": {...}, "operations": [...]}
-```
-
-The `prompt` field is optional for Agent API callers. MCP clients should include it whenever they have the user's message; pass the original message as-is and do not summarize, rewrite, or infer a different prompt.
-
-In MCP, this returns `{"query_handle": "<uuid>"}` — pass `query_handle` to `execute_query` or `visualize_query`. The HTTP Agent API response contains `{"query": "<base64>"}` and echoes `prompt` only when supplied.
-
-IMPORTANT: field IDs must come from entity-detail endpoints (`/v1/table/{id}`, `/v1/metric/{id}`). Do not invent IDs. The backend repairs minor mistakes (aliases, casing, over-wrapping) before validation, but the canonical names below always work.
-
-## Workflow
-
-1. Use `search` and the entity-detail tools (`get_table`, `get_metric`) to find the table/metric/model and its fields.
-2. Call `construct_query` with the program. Include the user's original `prompt` whenever available. In MCP, you get back `{"query_handle": "<uuid>"}`.
-3. Pass `query_handle` to the follow-up `execute_query` or `visualize_query` call.
-
-Never embed IDs you did not read from a metadata endpoint — invented IDs will fail at execution.
-
-## Source
-
-One of `{"type": T, "id": N}`:
-
-- `table` — a database table
-- `card` — a saved question
-- `dataset` — a model (model card id)
-- `metric` — a metric (supplies its own aggregation and time dimension; extra aggregates usually unnecessary)
-
-## Top-level operations (applied in order)
-
-Each operation is `["op", arg, ...]`:
-
-- `["filter", clause]` — add a filter
-- `["aggregate", agg-clause]` — add an aggregation
-- `["breakout", ref-or-bucketed]` — add a grouping dimension
-- `["expression", "Name", expr]` — define a named computed column (reference later with `expression-ref`)
-- `["with-fields", [refs...]]` — restrict returned columns
-- `["order-by", ref]` or `["order-by", ref, "asc"|"desc"]` — sort
-- `["limit", N]` — cap rows
-- `["join", join-clause]` — join another entity
-- `["append-stage"]` — start a new query stage (needed to filter on aggregated values)
-- `["with-page", {"page": N, "items": M}]` — paginate
-
-## References (used as arguments inside operations)
-
-- `["field", N]` — database field by id. Do NOT put options in a third slot (no `["field", id, {...}]`); wrap instead
-- `["expression-ref", "Name"]` — a named expression defined earlier
-- `["aggregation-ref", N]` — the Nth `aggregate` defined earlier (0-based). REQUIRED when sorting by an aggregated value
-- `["measure", N]` — a pre-defined measure on the source entity
-- `["with-temporal-bucket", ref, unit]` — temporal bucketing. `unit` is one of: `minute` `hour` `day` `week` `month` `quarter` `year`. Also `day-of-week`, `hour-of-day`, etc. (extraction aliases)
-- `["with-binning", ref, {"strategy": "num-bins"|"bin-width"|"default", ...}]` — numeric binning. E.g. `{"strategy": "num-bins", "num-bins": 10}`
-
-## Filter operators
-
-`=`, `!=`, `<`, `<=`, `>`, `>=`, `between`, `in`, `not-in`, `is-null`, `not-null`, `is-empty`, `not-empty`, `contains`, `does-not-contain`, `starts-with`, `ends-with`, `time-interval`, `and`, `or`, `not`, `segment`.
-
-Examples: `["=", ["field", 101], "active"]`, `["between", ["field", 305], "2024-01-01", "2024-12-31"]`, `["in", ["field", 302], [10, 20, 30]]`, `["time-interval", ["field", 305], -7, "day"]`.
-
-## Aggregation operators
-
-`count`, `sum`, `avg`, `min`, `max`, `distinct`, `median`, `stddev`, `var`, `percentile`, `count-where`, `sum-where`, `distinct-where`, `share`, `cum-count`, `cum-sum`.
-
-Examples: `["count"]`, `["sum", ["field", 302]]`, `["count-where", ["=", ["field", 101], "completed"]]`.
-
-## Temporal helpers (for use in `expression` or as grouping)
-
-`get-year`, `get-quarter`, `get-month`, `get-week`, `get-day`, `get-day-of-week`, `get-hour`, `get-minute`, `datetime-add`, `datetime-diff`, `datetime-subtract`, `now`, `today`, `relative-datetime`, `absolute-datetime`, `with-temporal-bucket`, `convert-timezone`.
-
-## Examples
-
-Top 5 customers by revenue:
-
-```
-{"source": {"type": "table", "id": 42},
- "operations": [["aggregate", ["sum", ["field", 302]]],
- ["breakout", ["field", 101]],
- ["order-by", ["aggregation-ref", 0], "desc"],
- ["limit", 5]]}
-```
-
-Monthly revenue from a metric (metric supplies the aggregation):
-
-```
-{"source": {"type": "metric", "id": 10},
- "operations": [["breakout", ["with-temporal-bucket", ["field", 305], "month"]],
- ["order-by", ["with-temporal-bucket", ["field", 305], "month"], "asc"]]}
-```
-
-Filter on an aggregated value (requires `append-stage`):
-
-```
-{"source": {"type": "table", "id": 42},
- "operations": [["aggregate", ["sum", ["field", 302]]],
- ["breakout", ["field", 101]],
- ["append-stage"],
- ["filter", [">", ["aggregation-ref", 0], 1000]]]}
-```
-
-Named expression referenced later:
-
-```
-{"source": {"type": "table", "id": 42},
- "operations": [["expression", "Discount", ["-", ["field", 302], ["field", 303]]],
- ["aggregate", ["sum", ["expression-ref", "Discount"]]]]}
-```
-
-Previous-period comparison with `offset` (stay in the SAME stage — do NOT add `append-stage`):
-
-```
-{"source": {"type": "table", "id": 42},
- "operations": [["aggregate", ["sum", ["field", 302]]],
- ["aggregate", ["offset", ["sum", ["field", 302]], -1]],
- ["breakout", ["with-temporal-bucket", ["field", 305], "month"]]]}
-```
-
-## Rules & common pitfalls
-
-Stage boundaries (most common source of errors):
-
-- Filtering on an aggregated value REQUIRES `append-stage` between the aggregate/breakout and the filter (see the "filter on aggregated value" example). Without it, `aggregation-ref` resolution fails in the same stage.
-- Defining an `expression` that uses `aggregation-ref` also REQUIRES `append-stage` first.
-- EXCEPTION: `offset` (previous-period comparison) stays in the same stage as its base aggregation and breakout — do NOT add `append-stage` for it.
-
-Refs & shapes:
-
-- Aggregation helpers take field refs, not bare IDs: `["sum", ["field", 201]]`, never `["sum", 201]`.
-- To sort by an aggregated value, use `["aggregation-ref", N]` — not the original expression.
-- Do NOT put options in a third slot of `field` (no `["field", id, {...}]`). Wrap instead: `["with-temporal-bucket", ["field", id], "month"]` or `["with-binning", ["field", id], {...}]`.
-- `case` takes `[[condition, value], ...]` branches and an optional bare fallback as the THIRD arg — do not wrap it as `{"default": ...}`. Omit the third arg when there is no fallback.
-- JSON objects appear only where a helper explicitly calls for one (e.g. `with-page`, `with-binning`). Everywhere else, use operator tuples.
-
-Joins & related tables:
-
-- If the source table's detail response already surfaces a related table's fields, use those field refs directly — no explicit join needed.
-- Reach for `join` + `with-join-conditions` only for custom aliases, self-joins, explicit joined-field selection, or when direct related-field refs are unavailable.
-- If an explicit join returns a permission error, the underlying table is not accessible — surface the error, do not retry with implicit refs.
-
-Metrics & dates:
-
-- A `metric` source already provides its own aggregation and time dimension. Add only the additional breakouts/filters you need.
-- When the user asks for an exact year (e.g. 2024), use `["=", ["field", year_field], 2024]` or a `between` with explicit dates — not relative filters like `time-interval`.
diff --git a/resources/metabot/prompts/llm_representations.selmer b/resources/metabot/prompts/llm_shape.selmer
similarity index 79%
rename from resources/metabot/prompts/llm_representations.selmer
rename to resources/metabot/prompts/llm_shape.selmer
index 71b93086ce0..7b224dd7d48 100644
--- a/resources/metabot/prompts/llm_representations.selmer
+++ b/resources/metabot/prompts/llm_shape.selmer
@@ -1,19 +1,21 @@
{% if is_measure %}
-<measure measure_id="{{measure_id}}" name="{{measure_name}}" display_name="{{measure_display_name}}">{% if measure_description %}
-{{measure_description}}{% endif %}{% if measure_definition_description %}
-Definition: {{measure_definition_description}}{% endif %}{% if measure_definition %}
-<definition>{{measure_definition}}</definition>{% endif %}
+<measure measure_id="{{measure_id}}" name="{{measure_name}}" display_name="{{measure_display_name}}"{% if measure_portable_entity_id %} portable_entity_id="{{measure_portable_entity_id}}"{% endif %}>{% if measure_description %}
+{{measure_description}}{% endif %}{% if measure_definition %}
+<definition>
+{{measure_definition|safe}}
+</definition>{% endif %}
</measure>
{% endif %}
{% if is_segment %}
-<segment segment_id="{{segment_id}}" name="{{segment_name}}" display_name="{{segment_display_name}}">{% if segment_description %}
-{{segment_description}}{% endif %}{% if segment_definition_description %}
-Definition: {{segment_definition_description}}{% endif %}{% if segment_definition %}
-<definition>{{segment_definition}}</definition>{% endif %}
+<segment id="{{segment_id}}" name="{{segment_name}}" display_name="{{segment_display_name}}"{% if segment_portable_entity_id %} portable_entity_id="{{segment_portable_entity_id}}"{% endif %}>{% if segment_description %}
+{{segment_description}}{% endif %}{% if segment_definition %}
+<definition>
+{{segment_definition|safe}}
+</definition>{% endif %}
</segment>
{% endif %}
{% if is_field %}
-<field id="{{field_id}}" name="{{field_name_quoted|safe}}" display_name="{{field_display_name}}" type="{{field_base_type}}" database_type="{{field_database_type}}">{% if field_description %}
+<field id="{{field_id}}" name="{{field_name_quoted|safe}}" display_name="{{field_display_name}}" type="{{field_base_type}}" database_type="{{field_database_type}}"{% if field_fk_target_fqn %} fk_target_fully_qualified_name="{{field_fk_target_fqn}}"{% endif %}>{% if field_description %}
## Description
{{field_description}}{% endif %}</field>
{% endif %}
@@ -22,11 +24,11 @@ Definition: {{segment_definition_description}}{% endif %}{% if segment_definitio
<description>{{collection_description}}</description>{% endif %}</collection>
{% endif %}
{% if is_related_table %}
-<related-table{% if related_table_id %} id="{{related_table_id}}"{% endif %} name="{{related_table_name}}"{% if related_table_related_by %} related_by="{{related_table_related_by}}"{% endif %} fully_qualified_name="{{related_table_fqn}}">{% if related_table_fields_xml %}
+<related-table{% if related_table_id %} id="{{related_table_id}}"{% endif %} name="{{related_table_name}}"{% if related_table_related_by %} related_by="{{related_table_related_by}}"{% endif %}{% if related_table_database_name %} database_name="{{related_table_database_name}}"{% endif %} fully_qualified_name="{{related_table_fqn}}">{% if related_table_fields_xml %}
{{related_table_fields_xml|safe}}{% endif %}</related-table>
{% endif %}
{% if is_metric %}
-<metric id="{{metric_id}}", name="{{metric_name}}" is_verified="{{metric_verified}}">
+<metric id="{{metric_id}}", name="{{metric_name}}" is_verified="{{metric_verified}}"{% if metric_database_name %} database_name="{{metric_database_name}}"{% endif %}{% if metric_base_table_fqn %} base_table_fully_qualified_name="{{metric_base_table_fqn}}"{% endif %}{% if metric_portable_entity_id %} portable_entity_id="{{metric_portable_entity_id}}"{% endif %}>
{% if metric_collection_xml %}
The metric is stored in the following collection:
{{metric_collection_xml|safe}}
@@ -49,7 +51,7 @@ This will help avoid errors due to unexpected data types or formats.
</metric>
{% endif %}
{% if is_table %}
-<table id="{{table_id}}", name="{{table_name}}" database_id="{{table_database_id}}" database_engine="{{table_database_engine}}" fully_qualified_name="{{table_fqn}}">
+<table id="{{table_id}}", name="{{table_name}}" database_id="{{table_database_id}}"{% if table_database_name %} database_name="{{table_database_name}}"{% endif %} database_engine="{{table_database_engine}}" fully_qualified_name="{{table_fqn}}">
### Description
{{table_description}}
@@ -93,10 +95,19 @@ This will help avoid errors due to unexpected data types or formats.
</table>
{% endif %}
{% if is_model %}
-<metabase-model id="{{model_id}}" name="{{model_name}}" is_verified="{{model_verified}}" database_id="{{model_database_id}}" database_engine="{{model_database_engine}}" fully_qualified_name="{{model_fqn}}">
+<metabase-model id="{{model_id}}" name="{{model_name}}" is_verified="{{model_verified}}" database_id="{{model_database_id}}"{% if model_database_name %} database_name="{{model_database_name}}"{% endif %} database_engine="{{model_database_engine}}" fully_qualified_name="{{model_fqn}}"{% if model_portable_entity_id %} portable_entity_id="{{model_portable_entity_id}}"{% endif %}>
### Description
{{model_description}}
+{% if model_query_json %}
+
+### Saved query
+The model's saved query, in the same canonical portable representations JSON format the
+`construct_notebook_query` tool consumes:
+<query>
+{{model_query_json|safe}}
+</query>
+{% endif %}
{% if model_fields_xml %}
### Fields
@@ -175,7 +186,7 @@ Chart link: metabase://chart/{{chart_id}}
</chart>
{% endif %}
{% if is_question %}
-<metabase_question id="{{question_id}}" is_verified="{{question_verified}}"{% if question_display_type %} display_type="{{question_display_type}}"{% endif %}>
+<metabase_question id="{{question_id}}" is_verified="{{question_verified}}"{% if question_display_type %} display_type="{{question_display_type}}"{% endif %}{% if question_portable_entity_id %} portable_entity_id="{{question_portable_entity_id}}"{% endif %}>
<name>{{question_name}}</name>
{% if question_description %}
<description>{{question_description}}</description>
@@ -184,17 +195,17 @@ Chart link: metabase://chart/{{chart_id}}
The question is stored in the following collection:
{{question_collection_xml|safe}}
{% endif %}
+{% if question_query_json %}
+The question's saved query, in the same canonical portable representations JSON format the
+`construct_notebook_query` tool consumes:
+<query>
+{{question_query_json|safe}}
+</query>
+{% endif %}
{% if question_visualization_xml %}
The question is visualized as follows:
{{question_visualization_xml|safe}}
{% endif %}
-{% if question_fields_xml %}
-
-### Fields
-
-The following fields are returned by this question.
-{{question_fields_xml|safe}}
-{% endif %}
</metabase_question>
{% endif %}
{% if is_text_card %}
@@ -262,7 +273,7 @@ or jargon that may be relevant to the user's questions.
</user>
{% endif %}
{% if is_search_result %}
-<{{search_tag_name}} id="{{search_id}}" name="{{search_name}}"{% if search_has_verified %} is_verified="{{search_verified}}"{% endif %}{% if search_database_id %} database_id="{{search_database_id}}"{% endif %}{% if search_database_engine %} database_engine="{{search_database_engine}}"{% endif %}{% if search_fqn %} fully_qualified_name="{{search_fqn}}"{% endif %}>
+<{{search_tag_name}} id="{{search_id}}" name="{{search_name}}"{% if search_has_verified %} is_verified="{{search_verified}}"{% endif %}{% if search_database_id %} database_id="{{search_database_id}}"{% endif %}{% if search_database_name %} database_name="{{search_database_name}}"{% endif %}{% if search_database_engine %} database_engine="{{search_database_engine}}"{% endif %}{% if search_fqn %} fully_qualified_name="{{search_fqn}}"{% endif %}{% if search_base_table_fqn %} base_table_fully_qualified_name="{{search_base_table_fqn}}"{% endif %}{% if search_portable_entity_id %} portable_entity_id="{{search_portable_entity_id}}"{% endif %}>
{% if search_description %}
{{search_description}}
{% endif %}
diff --git a/resources/metabot/prompts/tools/construct_notebook_query.md b/resources/metabot/prompts/tools/construct_notebook_query.md
index 5eb1ea98f79..9ee4e07d5c5 100644
--- a/resources/metabot/prompts/tools/construct_notebook_query.md
+++ b/resources/metabot/prompts/tools/construct_notebook_query.md
@@ -1,180 +1,388 @@
-Use this tool to construct a notebook query directly from the structured MBQL tuple AST. MBQL (Metabase Query Language) is Metabase's structured, JSON-friendly query AST — this tool builds a query directly in that AST instead of writing SQL.
+# Construct Query Reference
-Return a payload with:
-- `source_entity`: `{"type":"table"|"model"|"question"|"metric","id":123}`
-- `referenced_entities`: optional additional context entities in the same shape
-- `program`: structured MBQL program
-- `visualization`: optional chart choice like `{"chart_type":"bar"}`
+Construct a Metabase MBQL 5 query as a JSON object describing the query shape. Metabase validates, repairs, and resolves it.
-The program must use the structured source/context pattern:
+Return:
+- `query`: a JSON **object** (never a quoted string). The target database is inferred from the first stage's `source-table` (or `source-card`) — use the **exact** database name reported by `entity_details` / metadata tools.
+- `visualization`: optional `{"chart_type": "bar"}` (sibling of `query`, never embedded inside it).
+
+## Minimal example — count of orders by month
```json
-{
- "source": { "type": "context", "ref": "source" },
- "operations": [
- ["filter", ["between", ["field", 2058], "2024-01-01", "2024-12-31"]],
- ["aggregate", ["sum", ["field", 2056]]],
- ["breakout", ["with-temporal-bucket", ["field", 2058], "month"]]
- ]
-}
+{"lib/type": "mbql/query",
+ "stages": [{"lib/type": "mbql.stage/mbql",
+ "source-table": ["Sample Database", "PUBLIC", "ORDERS"],
+ "aggregation": [["count", {}]],
+ "breakout": [["field", {"temporal-unit": "month"},
+ ["Sample Database", "PUBLIC", "ORDERS", "CREATED_AT"]]]}]}
```
-Rules:
-- Use real numeric ids only — the integer ids returned by the table/metric detail endpoints.
-- Use `["field", id]`, `["table", id]`, `["card", id]`, `["metric", id]`, and `["measure", id]` as needed.
-- `program` must be a JSON object, not a quoted JSON string.
-- Each item in `operations` must contain exactly one top-level transform.
- - Good: `[["aggregate", ["count"]], ["aggregate", ["sum", ["field", 301]]]]`
- - Bad: `[["aggregate", ["count"], ["sum", ["field", 301]]]]`
-- Use `["relative-datetime", n, "unit"]` for relative temporal values.
-- `source_entity` chooses the primary source:
- - `table` -> table
- - `model` -> model/dataset
- - `question` -> saved question
- - `metric` -> metric
-- Use `{ "type": "context", "ref": "source" }` as the program source for the selected primary source.
-- Use nested `{ "type": "program", "program": { ... } }` only when you truly need a derived query as a source or join target.
-
-Common operators:
-- `["filter", clause]`
-- `["aggregate", aggregation]`
-- `["breakout", breakout-form]`
-- `["with-fields", [field-or-ref, ...]]`
-- `["limit", 10]`
-- `["expression", "Name", expr]`
-- `["join", join-clause]`
-- `["order-by", orderable]`
-- `["order-by", orderable, "desc"]`
-- `["append-stage"]`
-- `["drop-stage"]`
-- `["drop-empty-stages"]`
-- `["with-page", {"page": 2, "items": 25}]`
-
-Do not put visualization inside `program.operations`.
-- Good: top-level `"visualization": {"chart_type": "pie"}`
-- Bad: `["visualization", {"chart_type": "pie"}]`
-
-Breakout and ordering rules:
-- Do not breakout on the same underlying field twice in one stage.
- - If you breakout by `["with-temporal-bucket", ["field", 2058], "month"]`, do not also breakout by raw `["field", 2058]`.
-- If you want the normal ascending order for a breakout field, you can usually omit an explicit `order-by`.
- - Metabase already adds implicit ascending ordering for breakout fields.
- - Add an explicit `order-by` for a breakout only when you need a different direction or a different sort precedence.
-
-Measures and segments:
-- Prefer `["measure", id]` when a model/table exposes an official measure that matches the requested aggregation.
-- Prefer `["segment", id]` when a model/table exposes an official segment that matches the requested filter.
-
-Post-aggregation logic:
-- For filters or expressions that reference `["aggregation-ref", index]`, add `["append-stage"]` first.
-- Example:
+Every clause is `["op", {}, ...args]` with a mandatory `{}` options map at position 1; every field reference uses a 4-segment portable FK in the last slot. These are the two most-violated rules.
+
+## Universal clause shape
+
+Every operation is `["<operator>", {options}, ...args]`. The options map is **always present**, even when empty.
+
+- Good: `["count", {}]`, `["field", {}, ["DB", "SCH", "TBL", "COL"]]`, `["sum", {}, <expr>]`
+- Bad: `["count"]`, `["field", ["DB", "SCH", "TBL", "COL"]]`
+
+The pipeline repairs missing `{}` slots, but write them — your output should match what later inspection will show.
+
+## Top-level query and stage shape
+
+Top level:
+- `"lib/type": "mbql/query"` — required marker.
+- `"stages": [...]` — at least one stage.
+
+Stage (`"lib/type": "mbql.stage/mbql"` — required marker):
+- `source-table` **or** `source-card` — exactly one, **first stage only**. Later stages take the previous stage's output implicitly.
+- Optional: `filters`, `aggregation`, `breakout`, `expressions`, `fields`, `joins`, `order-by`, `limit`, `page`.
+
+There is no top-level `database:` field in the LLM contract — the database is derived from the source.
+
+## Field references
```json
-{
- "source": { "type": "context", "ref": "source" },
- "operations": [
- ["aggregate", ["sum", ["field", 301]]],
- ["breakout", ["field", 401]],
- ["append-stage"],
- ["filter", [">", ["aggregation-ref", 0], 1000]]
- ]
-}
+["field", {}, ["<db-name>", "<schema-or-null>", "<table-name>", "<field-name>"]]
```
-Grouped ratio example:
+The third slot is the **portable field FK** — a 4+ element string array. Schemaless databases (MongoDB, etc.) use `null` in the schema slot: `["Mongo", null, "orders", "created_at"]`. JSON-unfolded fields append extra segments: `["DB", "SCH", "TBL", "PARENT", "CHILD"]`.
+
+Inside later stages, refer to a column produced by the previous stage by **string name** instead of a portable FK: `["field", {}, "count"]`, `["field", {}, "PRODUCT_ID"]`.
+
+Field options (all optional):
+- `temporal-unit` — bucket a date/time field, e.g. `"month"`, `"day"`, `"hour"`. Full list in §Operator catalogs.
+- `join-alias` — required on every field reference that lives inside an explicit join.
+- `source-field` — portable FK of the FK column on the source table; only needed when the implicit-join auto-fill is ambiguous.
+- `source-field-name` — name of the FK column when it comes from a previous stage's output (rare; not auto-filled).
+- `source-field-join-alias` — explicit-join alias the FK column belongs to (usually auto-filled).
+- `binning` — bucket a numeric field.
+
+`base-type` is auto-filled on cross-stage refs — don't write it.
+
+## Per-clause examples
+
+Filter (comparison + boolean combination):
```json
-{
- "source": { "type": "context", "ref": "source" },
- "operations": [
- ["aggregate", ["sum", ["field", 301]]],
- ["aggregate", ["sum", ["field", 302]]],
- ["breakout", ["field", 401]],
- ["append-stage"],
- ["expression", "Ratio", ["/", ["aggregation-ref", 0], ["aggregation-ref", 1]]],
- ["order-by", ["desc", ["expression-ref", "Ratio"]]],
- ["limit", 10]
- ]
-}
+"filters": [["and", {},
+ [">", {}, ["field", {}, ["Sample Database", "PUBLIC", "ORDERS", "TOTAL"]], 100],
+ ["=", {}, ["field", {}, ["Sample Database", "PUBLIC", "ORDERS", "STATUS"]], "paid"]]]
```
-Joins:
-- If a surrounding/related table is already shown in context for the source table, first try using that table's field ids directly without an explicit join.
-- Add an explicit join when you need custom join behavior, a join alias, explicit joined-field selection, self-joins, or direct related-field refs do not work.
-- Direct related-field refs are the default for one-hop related tables.
-- If an explicit join returns a permission error, the underlying table is not accessible — surface the error instead of retrying with implicit refs (they hit the same permission check).
-- Example:
+Aggregation (on a field, plus `count`):
```json
-{
- "source": { "type": "context", "ref": "source" },
- "operations": [
- ["join", ["with-join-conditions",
- ["join-clause", ["table", 42]],
- [["=", ["field", 101], ["field", 202]]]
- ]],
- ["aggregate", ["sum", ["field", 301]]],
- ["breakout", ["field", 202]]
- ]
-}
+"aggregation": [["sum", {}, ["field", {}, ["Sample Database", "PUBLIC", "ORDERS", "TOTAL"]]],
+ ["count", {}]]
```
-Field projection rules:
-- `with-fields` accepts returned columns and refs such as `["field", id]`, `["expression-ref", "Name"]`, and `["aggregation-ref", 0]`.
-- Do not define `["expression", "Name", expr]` inside `with-fields`.
- - Define the expression first as its own top-level operation, then project `["expression-ref", "Name"]`.
-- For multi-value categorical filters, use `in` or `or`, not `=` with an array literal.
- - Good: `["filter", ["in", ["field", 2492], ["authorized", "pending"]]]`
- - Bad: `["filter", ["=", ["field", 2492], ["authorized", "pending"]]]`
-- For temporal extraction, use helpers such as `["get-month", ["field", 2058]]` and `["get-day-of-week", ["field", 2058]]`.
- - Use `["get-hour", ["field", 2058]]` and `["get-quarter", ["field", 2058]]` for hour-of-day or quarter-number extraction.
- - Do not invent helpers or bucket names like `month-of-year`, `quarter-of-year`, `hour-of-day`, or `dayofweek`.
-- When filtering extracted quarter values, use numeric quarter numbers `1`, `2`, `3`, `4`, not strings like `"Q1"`.
-- When you need the number of days or other units between two temporal values, use `["datetime-diff", left-temporal-expr, right-temporal-expr, "day"]`.
- - Do not subtract dates with `-` to compute date differences.
-
-Use `with-fields` for row-level queries and `breakout` only for grouped results.
-If the result should be visualized, set `visualization.chart_type` to something appropriate like `table`, `bar`, `line`, `area`, `pie`, or `scalar`.
-
-Aggregation operators:
-- `["count"]` — Count all rows
-- `["sum", ["field", id]]` — Sum
-- `["avg", ["field", id]]` — Average
-- `["min", ["field", id]]` — Minimum
-- `["max", ["field", id]]` — Maximum
-- `["distinct", ["field", id]]` — Count distinct values
-- `["count-where", clause]` — Count rows matching a condition
-- `["sum-where", ["field", id], clause]` — Sum for matching rows
-- `["median", ["field", id]]` — Median
-- `["percentile", ["field", id], 0.95]` — Percentile
-- `["measure", id]` — Use a pre-defined measure
-
-Filter operators:
-- `["=", field, value]`, `["!=", field, value]`
-- `["<", field, value]`, `["<=", field, value]`, `[">", field, value]`, `[">=", field, value]`
-- `["between", field, low, high]`
-- `["contains", field, "text"]`, `["does-not-contain", field, "text"]`
-- `["starts-with", field, "prefix"]`, `["ends-with", field, "suffix"]`
-- `["is-null", field]`, `["not-null", field]`, `["is-empty", field]`, `["not-empty", field]`
-- `["in", field, [v1, v2, ...]]`, `["not-in", field, [v1, v2, ...]]`
-- `["time-interval", field, n, "unit"]` — Relative time window
-- `["and", clause1, clause2]`, `["or", clause1, clause2]`, `["not", clause]`
-- `["segment", id]` — Pre-defined segment
-
-Expression operators:
-- Arithmetic: `["+", a, b]`, `["-", a, b]`, `["*", a, b]`, `["/", a, b]`
-- Math: `["abs", x]`, `["ceil", x]`, `["floor", x]`, `["round", x]`, `["power", x, n]`, `["sqrt", x]`
-- String: `["concat", a, b]`, `["substring", s, start, len]`, `["replace", s, old, new]`, `["upper", s]`, `["lower", s]`, `["trim", s]`, `["length", s]`
-- Conditional: `["case", [[cond1, val1], [cond2, val2]], default]`
-- Coalesce: `["coalesce", a, b]`
-- Date extraction: `["get-year", field]`, `["get-month", field]`, `["get-day", field]`, `["get-quarter", field]`, `["get-hour", field]`, `["get-day-of-week", field]`
-- Date arithmetic: `["datetime-add", field, n, "unit"]`, `["datetime-diff", field1, field2, "unit"]`
-
-References:
-- `["field", id]` — Field by database ID
-- `["expression-ref", "Name"]` — Custom expression by name
-- `["aggregation-ref", 0]` — Aggregation result by 0-based index
-
-Temporal bucketing (for breakout):
-- `["with-temporal-bucket", ["field", id], "month"]`
-- Valid buckets: `year`, `quarter`, `month`, `week`, `day`, `hour`, `minute`, `second`, `day-of-week`
+Breakout with temporal bucket:
+
+```json
+"breakout": [["field", {"temporal-unit": "month"},
+ ["Sample Database", "PUBLIC", "ORDERS", "CREATED_AT"]]]
+```
+
+Order by — direction wraps a ref; works on field refs or aggregation refs:
+
+```json
+"order-by": [["desc", {}, ["field", {}, ["Sample Database", "PUBLIC", "ORDERS", "CREATED_AT"]]],
+ ["desc", {}, ["aggregation", {}, 0]]]
+```
+
+`"limit": 50` and `"fields": [<field-ref>, ...]` are the obvious scalar / list forms.
+
+### Aggregation references
+
+To refer to an aggregation already in the same stage's `aggregation` list — e.g. from `order-by`:
+1. **Inline** — repeat the clause itself. The inline form must match an entry in `aggregation` **exactly** (same op, same args). The tool rewrites it to a reference.
+2. **By 0-based index** (preferred when reused) — `["aggregation", {}, 0]` means "the first aggregation".
+
+Out-of-range indices surface a clear error listing every available aggregation with its index.
+
+## Expressions
+
+Define custom columns inside a stage using `expressions` and reference by name with `["expression", {}, "<Name>"]`. Object form (preferred); the name becomes the column's display name.
+
+```json
+"expressions": {
+ "Subtotal": ["+", {},
+ ["field", {}, ["Sample Database", "PUBLIC", "ORDERS", "TOTAL"]],
+ ["field", {}, ["Sample Database", "PUBLIC", "ORDERS", "TAX"]]]
+},
+"aggregation": [["sum", {}, ["expression", {}, "Subtotal"]]]
+```
+
+The sequential form `[["expression", {}, "Name", expr], ...]` is also accepted and auto-converted.
+
+## Joins (explicit)
+
+```json
+"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"]]]
+```
+
+- `alias` is a free-choice string; use it consistently in conditions, breakout, aggregation, order-by.
+- `strategy` is one of `"left-join"`, `"right-join"`, `"inner-join"`, `"full-join"`. Default `"left-join"`.
+- **Every** field reference on the joined side must carry `{"join-alias": "<same-alias>"}`.
+- Join `conditions` accept only `=`, `!=`, `<`, `<=`, `>`, `>=` — no `between`, `in`, `and`/`or` wrappers.
+
+## Implicit joins
+
+Reference a field on a related table directly — when the source has exactly one FK to that target, the tool auto-fills `source-field` and performs the implicit join:
+
+```json
+"source-table": ["Sample Database", "PUBLIC", "ORDERS"],
+"aggregation": [["count", {}]],
+"breakout": [["field", {}, ["Sample Database", "PUBLIC", "PRODUCTS", "CATEGORY"]]]
+```
+
+- **Multiple FKs** to the target → `:ambiguous-fk` lists them. Retry with explicit `{"source-field": ["DB", "SCH", "SRC", "FK_COL"]}` on the field.
+- **No FK path** → `:no-fk-path`. Switch to an explicit `joins` entry, or pick a field on the source table.
+- Inside an explicit `joins` block, joined-side field refs still need `{"join-alias": ...}` — implicit-join repair does not rewrite those.
+- If the FK column lives on a previous stage's output, write `{"source-field-name": "<col>"}` (not auto-filled).
+- If multiple explicit joins all expose the target FK, `:ambiguous-fk-via-join` lists them — set `{"source-field-join-alias": "<alias>"}` to pick one.
+
+**Tip:** discover FKs with `entity_details` / `read_resource metabase://table/<id>/fields`. FK columns are tagged `fk_target_fully_qualified_name="schema.table.field"` — always look for one before assuming a column lives on the current table.
+
+## Multi-stage queries
+
+Every stage after the first consumes the previous stage's output. Only the first stage has a `source-table`/`source-card`; later stages omit it.
+
+Post-aggregation filter — count orders per product, keep only those with > 10:
+
+```json
+"stages": [
+ {"lib/type": "mbql.stage/mbql",
+ "source-table": ["Sample Database", "PUBLIC", "ORDERS"],
+ "aggregation": [["count", {}]],
+ "breakout": [["field", {}, ["Sample Database", "PUBLIC", "ORDERS", "PRODUCT_ID"]]]},
+ {"lib/type": "mbql.stage/mbql",
+ "filters": [[">", {}, ["field", {}, "count"], 10]]}
+]
+```
+
+Re-aggregate — average daily total by month:
+
+```json
+"stages": [
+ {"lib/type": "mbql.stage/mbql",
+ "source-table": ["Sample Database", "PUBLIC", "ORDERS"],
+ "aggregation": [["sum", {}, ["field", {}, ["Sample Database", "PUBLIC", "ORDERS", "TOTAL"]]]],
+ "breakout": [["field", {"temporal-unit": "day"},
+ ["Sample Database", "PUBLIC", "ORDERS", "CREATED_AT"]]]},
+ {"lib/type": "mbql.stage/mbql",
+ "aggregation": [["avg", {}, ["field", {}, "sum"]]],
+ "breakout": [["field", {"temporal-unit": "month"}, ["field", {}, "CREATED_AT"]]]}
+]
+```
+
+- 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).
+- Within the **same stage**, refer to your own aggregation with `["aggregation", {}, <idx>]` (see §Aggregation references). 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.
+
+## Saved questions and models (`source-card`)
+
+Instead of `source-table`, use `source-card` to query an existing question or model. The value is the card's **portable entity id** — a 21-char opaque string reported by `entity_details` and search tools as `portable_entity_id`.
+
+1. Get the `portable_entity_id` from a tool response. `search` and `read_resource` (`metabase://question/<id>`, `metabase://model/<id>`) include it on the result tag — reuse what's already in context, no extra call needed.
+2. Copy it **verbatim** into `source-card`. The id is opaque — never guess, construct, or abbreviate.
+3. Reference the card's columns by output **name** (string in slot 3), not portable FK. If you don't know the names, call `read_resource metabase://question/<numeric-id>/fields` (or `.../model/...`).
+
+```json
+{"lib/type": "mbql.stage/mbql",
+ "source-card": "T4wA_GPFwGb6R4FxIDGTo",
+ "filters": [[">", {}, ["field", {}, "total"], 100]],
+ "limit": 50}
+```
+
+A stage has either `source-table` **or** `source-card`, never both. The card must live in the same database as the rest of the query (no cross-database queries). Falling back to native SQL like `SELECT * FROM {{#<id>-<slug>}}` is **not** acceptable — always use `source-card`.
+
+## Metrics
+
+A metric is a pre-defined aggregation attached to a base table. To use one:
+
+1. Put the metric's **base table** in `source-table`. Read it from the `base_table_fully_qualified_name` attribute on the `<metric>` tag (combine with `database_name` to form the portable FK). Never invent schema/table names.
+2. Reference the metric as `["metric", {}, "<portable_entity_id>"]` in `aggregation`.
+3. Filters/breakouts on the same stage use portable FKs on the metric's base table.
+
+```json
+{"lib/type": "mbql.stage/mbql",
+ "source-table": ["Analytics", "brex_enriched", "fct_cards"],
+ "filters": [["!=", {}, ["field", {},
+ ["Analytics", "brex_enriched", "fct_cards", "card_status"]], "inactive"]],
+ "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.
+
+## 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).
+
+### Preferred — opaque-id clause
+
+Each `<measure>` and `<segment>` block on a `<table>` carries a `portable_entity_id="…"` attribute (a 21-char NanoID). Copy it verbatim:
+
+```json
+"aggregation": [["measure", {}, "<portable_entity_id>"]]
+"filters": [["segment", {}, "<portable_entity_id>"]]
+```
+
+The stage's `source-table` must be the table the measure/segment belongs to (the same `<table>` block where you saw the `<measure>` / `<segment>` element).
+
+### Fallback — inline the `<definition>` body
+
+When you need to **compose on top of** a measure or segment (add an extra filter the segment doesn't include, breakout an aggregation the measure doesn't have, …), copy the JSON array inside `<definition>` directly into your stage's `aggregation: [...]` (measure) or `filters: [...]` (segment) and add your own clauses alongside. The definition is in the same portable form the tool expects.
+
+### Don't
+
+- Never invent a `portable_entity_id` — only use the value reported in a tool response.
+- The matching aggregation-only opaque-id clause is `["metric", {}, "<portable_entity_id>"]` (for metrics, which live independently of a table — see §Metrics above).
+
+## Rules and common mistakes
+
+Shape rules:
+- **Always include `{}` options in every clause**, even when empty. `["count"]` is wrong — it must be `["count", {}]`.
+- **The query is a JSON object**, not a string. Send it directly as the `"query"` field of the call.
+- **Use the exact database name** reported by `entity_details` (e.g. `"Sample Database"`, not `"Sample"`) as the first element of every portable FK. Near-misses surface `Unknown database` instead of silently picking one. Cross-database queries are not supported.
+- **Use portable FKs**, not numeric IDs. Schemaless databases use `null` in the schema slot. JSON-unfolded fields append path segments.
+- **Clause heads are lowercase, hyphenated**: `"count"`, `"sum-where"`, `"time-interval"`, `"get-day-of-week"`. Not underscores, not camelCase.
+- **Never invent a `source-card` entity_id.** It must be a 21-char string copied verbatim from `entity_details` / search — no patterns, no numeric ids, no `card__<id>`.
+- **`source-card` columns are referenced by output name** (string in slot 3), not portable FK.
+
+Anti-hallucination:
+- **Don't subtract dates** with `-`. Use `["datetime-diff", {}, <left>, <right>, "<unit>"]` for the integer count of units between two temporal values.
+- **For multi-value categorical filters, use `in` / `not-in`**, not `=` with a list literal. The tool rewrites the list form, but write canonical: `["in", {}, <field>, "a", "b"]`.
+- **Extracted quarter values are numbers `1, 2, 3, 4`**, never strings like `"Q1"`.
+- **Don't breakout on the same underlying field twice** in one stage. If you breakout by `{"temporal-unit": "month"}`, do not also breakout by the raw field.
+- **`visualization` is a sibling of `query`**, never embedded inside it.
+- **Ordering by an inline aggregation must match an `aggregation:` entry exactly** (same op, same args). If unsure, use `["aggregation", {}, <0-based-idx>]`.
+- **Never write `metabase://...` URIs as `source-table` or `source-card` values.** Those URIs are for `read_resource`, not for query sources.
+- **Never write `[aggregate, ...]`, `[filter, ...]`, `[order-by, ...]`, `[breakout, ...]`, `[limit, ...]` as clause heads** — those are stage *container keys*, not clauses. Place inner clauses directly inside the stage's `aggregation:` / `filters:` / etc. arrays.
+- Common typos (`count-if`, `variance`, `stddev-pop`, `count-distinct`, `dayofweek`, `hour-of-day`, `month-of-year`, `quarter-of-year`, `temporal-diff`, `relative-date`) are auto-corrected, but write the canonical name (`count-where`, `var`, `stddev`, `distinct`, `get-day-of-week`, `get-hour`, `get-month`, `get-quarter`, `datetime-diff`, `relative-datetime`) so the tool output matches what later inspection will show.
+
+## Operator catalogs
+
+> Source of truth: `src/metabase/lib/schema/{aggregation,filter,temporal_bucketing}.cljc` and `src/metabase/lib/schema/expression/*.cljc`. If something seems missing here, attempt it — the schema may have grown.
+
+### Aggregations
+
+- `["count", {}]` — count all rows. Optional 3rd slot `<expr>` counts non-NULL.
+- `["cum-count", {}]` — cumulative count. Optional 3rd slot `<expr>`.
+- `["sum", {}, <num-expr>]`
+- `["cum-sum", {}, <num-expr>]`
+- `["avg", {}, <num-expr>]`
+- `["min", {}, <orderable>]`
+- `["max", {}, <orderable>]`
+- `["median", {}, <num-expr>]`
+- `["percentile", {}, <num-expr>, <0..1>]`
+- `["distinct", {}, <expr>]` — count of distinct non-NULL values.
+- `["distinct-where", {}, <expr>, <bool-pred>]`
+- `["count-where", {}, <bool-pred>]`
+- `["sum-where", {}, <num-expr>, <bool-pred>]`
+- `["share", {}, <bool-pred>]` — fraction of rows where pred is true.
+- `["stddev", {}, <num-expr>]`
+- `["var", {}, <num-expr>]`
+- `["metric", {}, "<portable_entity_id>"]` — reference a defined metric. The metric's base table must be the stage's `source-table`.
+- `["measure", {}, "<portable_entity_id>"]` — reference a defined measure (preferred over inlining its definition). The measure's table must be the stage's `source-table`.
+
+### Order-by direction
+
+- `["asc", {}, <ref>]` / `["desc", {}, <ref>]` — wrap any field ref or aggregation ref.
+
+### Filters
+
+Boolean:
+- `["and", {}, <pred>, <pred>, ...]` — min 2 args.
+- `["or", {}, <pred>, <pred>, ...]` — min 2 args.
+- `["not", {}, <pred>]`
+
+Equality (variadic, ≥2 args):
+- `["=", {}, <a>, <b>, ...]`
+- `["!=", {}, <a>, <b>, ...]`
+- `["in", {}, <expr>, <v1>, <v2>, ...]`
+- `["not-in", {}, <expr>, <v1>, <v2>, ...]`
+
+Comparison:
+- `["<", {}, <a>, <b>]` / `["<=", {}, <a>, <b>]` / `[">", {}, <a>, <b>]` / `[">=", {}, <a>, <b>]`
+- `["between", {}, <expr>, <min>, <max>]`
+- `["inside", {}, <lat-expr>, <lon-expr>, <lat-max>, <lon-min>, <lat-min>, <lon-max>]` — lat/lon bounding box.
+
+Nullness / emptiness:
+- `["is-null", {}, <expr>]` / `["not-null", {}, <expr>]`
+- `["is-empty", {}, <expr>]` / `["not-empty", {}, <expr>]` — equivalent to is-null OR `= ""` for strings.
+
+String (accept `{"case-sensitive": false}` in opts):
+- `["starts-with", {}, <str>, <prefix>]`
+- `["ends-with", {}, <str>, <suffix>]`
+- `["contains", {}, <str>, <substring>]`
+- `["does-not-contain", {}, <str>, <substring>]`
+
+Temporal:
+- `["time-interval", {}, <temporal>, <n-or-:current/:last/:next>, "<unit>"]` — relative window. Opts may set `{"include-current": true}`.
+- `["during", {}, <temporal>, "<iso-date-or-datetime>", "<unit>"]` — value falls within the bucket containing the literal.
+- `["relative-time-interval", {}, <temporal>, <value>, "<bucket>", <offset-value>, "<offset-bucket>"]` — window offset from now.
+
+Named reference:
+- `["segment", {}, "<portable_entity_id>"]` — reference a defined segment (preferred over inlining its definition). The segment's table must be the stage's `source-table`.
+
+### Expressions
+
+Arithmetic:
+- `["+", {}, <a>, <b>, ...]` / `["-", {}, <a>, <b>, ...]` / `["*", {}, <a>, <b>, ...]` / `["/", {}, <a>, <b>, ...]`
+- `["abs", {}, <num>]` / `["power", {}, <num>, <exp>]` / `["sqrt", {}, <num>]`
+- `["exp", {}, <num>]` / `["log", {}, <num>]`
+- `["ceil", {}, <num>]` / `["floor", {}, <num>]` / `["round", {}, <num>]`
+- `["integer", {}, <num-or-str>]` / `["float", {}, <num-or-str>]`
+
+String:
+- `["concat", {}, <a>, <b>, ...]`
+- `["substring", {}, <str>, <start>, <length>]` — 1-based start; length is optional.
+- `["replace", {}, <str>, <old>, <new>]`
+- `["regex-match-first", {}, <str>, <regex>]`
+- `["split-part", {}, <str>, <sep>, <n>]`
+- `["length", {}, <str>]`
+- `["trim", {}, <str>]` / `["ltrim", {}, <str>]` / `["rtrim", {}, <str>]`
+- `["upper", {}, <str>]` / `["lower", {}, <str>]`
+- `["host", {}, <url>]` / `["domain", {}, <url>]` / `["subdomain", {}, <url>]` / `["path", {}, <url>]`
+- `["month-name", {}, <int>]` / `["quarter-name", {}, <int>]` / `["day-name", {}, <int>]`
+- `["text", {}, <expr>]` / `["collate", {}, <str>, <collation>]`
+
+Conditional:
+- `["case", {}, [[<pred1>, <expr1>], [<pred2>, <expr2>], ...], <default?>]` — alias: `if`.
+- `["coalesce", {}, <a>, <b>, ...]`
+
+Temporal:
+- `["datetime-add", {}, <temporal>, <n>, "<unit>"]`
+- `["datetime-subtract", {}, <temporal>, <n>, "<unit>"]`
+- `["datetime-diff", {}, <left>, <right>, "<unit>"]` — `<unit>` is one of `second, minute, hour, day, week, month, quarter, year`.
+- `["interval", {}, <n>, "<unit>"]`
+- `["get-year", {}, <temporal>]` / `["get-month", {}, <temporal>]` / `["get-day", {}, <temporal>]` / `["get-quarter", {}, <temporal>]`
+- `["get-hour", {}, <temporal>]` / `["get-minute", {}, <temporal>]` / `["get-second", {}, <temporal>]`
+- `["get-week", {}, <temporal>]` / `["get-day-of-week", {}, <temporal>]` — both accept optional 4th-slot mode `"iso"`, `"us"`, `"instance"`.
+- `["temporal-extract", {}, <temporal>, "<unit>"]` — extract one of the date/time extraction units listed below.
+- `["convert-timezone", {}, <temporal>, "<target-tz>"]` — optional 4th slot is source tz.
+- `["relative-datetime", {}, <n>, "<unit>"]` (or `["relative-datetime", {}, "current"]`)
+- `["absolute-datetime", {}, "<iso-string>", "<unit?>"]`
+- `["date", {}, <expr>]` / `["datetime", {}, <expr>]` / `["time", {}, <expr>]`
+- `["now", {}]` / `["today", {}]`
+
+### Temporal units (for `{"temporal-unit": ...}` on field refs and as `<unit>` args)
+
+- Date truncation: `day`, `week`, `month`, `quarter`, `year`
+- Date extraction (integer-returning): `day-of-week`, `day-of-month`, `day-of-year`, `week-of-year`, `month-of-year`, `quarter-of-year`, `year`, `year-of-era`
+- Time truncation: `millisecond`, `second`, `minute`, `hour`
+- Time extraction (integer-returning): `second-of-minute`, `minute-of-hour`, `hour-of-day`
+- Plus `default` — let the system pick based on the field's base type.
diff --git a/resources/openapi/openapi.json b/resources/openapi/openapi.json
index b074fb5407b..e5d94f117ae 100644
--- a/resources/openapi/openapi.json
+++ b/resources/openapi/openapi.json
@@ -43,6 +43,31 @@
},
"required" : [ "url", "created_at", "sync_started_at", "created_by_id", "db_id" ],
"type" : "object"
+ }, {
+ "properties" : {
+ "created_at" : {
+ "minimum" : 1,
+ "type" : "integer"
+ },
+ "created_by_id" : {
+ "minimum" : 1,
+ "type" : "integer"
+ },
+ "db_id" : {
+ "minimum" : 1,
+ "type" : "integer"
+ },
+ "sync_started_at" : {
+ "minimum" : 1,
+ "type" : "integer"
+ },
+ "url" : {
+ "minLength" : 1,
+ "type" : "string"
+ }
+ },
+ "required" : [ "url", "created_at", "sync_started_at", "created_by_id", "db_id" ],
+ "type" : "object"
}, {
"properties" : {
"created_at" : {
@@ -1142,827 +1167,437 @@
} ],
"description" : "All the various ways of referring to an action with the v2 APIs."
},
- "metabase-enterprise.agent-api.api.column-metadata" : {
- "description" : "Metadata for a single result column.",
+ "metabase-enterprise.data-studio.api.table.publish-table-selectors" : {
"properties" : {
- "base_type" : {
- "type" : "string"
+ "collection_id" : {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
},
- "display_name" : {
- "type" : "string"
+ "database_ids" : {
+ "items" : {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
+ },
+ "type" : "array"
},
- "effective_type" : {
- "oneOf" : [ {
+ "schema_ids" : {
+ "items" : {
"type" : "string"
+ },
+ "type" : "array"
+ },
+ "table_ids" : {
+ "items" : {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
+ },
+ "type" : "array"
+ }
+ },
+ "required" : [ "collection_id" ],
+ "type" : "object"
+ },
+ "metabase-enterprise.data-studio.api.table.publish-tables-response" : {
+ "description" : "Schema for /publish-tables endpoint response. Matches frontend PublishTablesResponse type.",
+ "properties" : {
+ "target_collection" : {
+ "oneOf" : [ {
+ "description" : "value must be an instance of :model/Collection"
}, {
"type" : "null"
} ]
- },
- "name" : {
- "type" : "string"
}
},
- "required" : [ "name", "base_type", "display_name" ],
+ "required" : [ "target_collection" ],
"type" : "object"
},
- "metabase-enterprise.agent-api.api.construct-query-metric-request" : {
- "allOf" : [ {
- "properties" : {
- "filters" : {
- "oneOf" : [ {
- "items" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.filter"
- },
- "type" : "array"
- }, {
- "type" : "null"
- } ]
+ "metabase-enterprise.data-studio.api.table.table-selectors" : {
+ "properties" : {
+ "database_ids" : {
+ "items" : {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
},
- "group_by" : {
- "oneOf" : [ {
- "items" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.group-by"
- },
- "type" : "array"
- }, {
- "type" : "null"
- } ]
+ "type" : "array"
+ },
+ "schema_ids" : {
+ "items" : {
+ "type" : "string"
},
- "metric_id" : {
+ "type" : "array"
+ },
+ "table_ids" : {
+ "items" : {
"description" : "value must be an integer greater than zero.",
"minimum" : 1,
"type" : "integer"
- }
- },
- "required" : [ "metric_id" ],
- "type" : "object"
- }, {
- "properties" : { },
- "type" : "object"
- } ],
- "description" : "Request schema for constructing a query from a metric.\n Only supports filters and group_by (aggregation is defined by the metric)."
- },
- "metabase-enterprise.agent-api.api.construct-query-request" : {
- "anyOf" : [ {
- "$ref" : "#/components/schemas/metabase-enterprise.agent-api.api.construct-query-table-request"
- }, {
- "$ref" : "#/components/schemas/metabase-enterprise.agent-api.api.construct-query-metric-request"
- } ],
- "description" : "Request schema for /v1/construct-query. Accepts either table_id or metric_id."
+ },
+ "type" : "array"
+ }
+ },
+ "type" : "object"
},
- "metabase-enterprise.agent-api.api.construct-query-response" : {
- "description" : "Response containing a base64-encoded MBQL query for use with /v1/execute.",
+ "metabase-enterprise.dependencies.api.base-entity" : {
"properties" : {
- "query" : {
- "minLength" : 1,
+ "data" : {
+ "properties" : { },
+ "type" : "object"
+ },
+ "dependents_count" : {
+ "oneOf" : [ {
+ "$ref" : "#/components/schemas/metabase-enterprise.dependencies.api.usages"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "dependents_errors" : {
+ "items" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.dependencies.models.analysis-finding-error.analysis-finding-error"
+ },
+ "type" : "array",
+ "uniqueItems" : true
+ },
+ "id" : {
+ "minimum" : 1,
+ "type" : "integer"
+ },
+ "type" : {
"type" : "string"
}
},
- "required" : [ "query" ],
+ "required" : [ "id", "type", "data", "dependents_count" ],
"type" : "object"
},
- "metabase-enterprise.agent-api.api.construct-query-table-request" : {
- "allOf" : [ {
- "properties" : {
- "aggregations" : {
- "oneOf" : [ {
- "items" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.aggregation"
- },
- "type" : "array"
- }, {
- "type" : "null"
- } ]
- },
- "fields" : {
- "oneOf" : [ {
- "items" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.field"
- },
- "type" : "array"
- }, {
- "type" : "null"
- } ]
- },
- "filters" : {
- "oneOf" : [ {
- "items" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.filter"
- },
- "type" : "array"
- }, {
- "type" : "null"
- } ]
- },
- "group_by" : {
- "oneOf" : [ {
- "items" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.group-by"
- },
- "type" : "array"
- }, {
- "type" : "null"
- } ]
- },
- "limit" : {
- "oneOf" : [ {
- "description" : "value must be an integer greater than zero.",
- "minimum" : 1,
- "type" : "integer"
- }, {
- "type" : "null"
- } ]
+ "metabase-enterprise.dependencies.api.broken-cards-response" : {
+ "properties" : {
+ "bad_cards" : {
+ "items" : {
+ "$ref" : "#/components/schemas/metabase.queries.schema.card"
},
- "order_by" : {
- "description" : "Order by regular fields only. To order by aggregation results, use sort_order on the aggregation.",
- "oneOf" : [ {
- "items" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.order-by"
- },
- "type" : "array"
- }, {
- "type" : "null"
- } ]
+ "type" : "array"
+ },
+ "bad_transforms" : {
+ "items" : {
+ "$ref" : "#/components/schemas/metabase.transforms.schema.transform"
},
- "table_id" : {
- "description" : "value must be an integer greater than zero.",
- "minimum" : 1,
- "type" : "integer"
- }
+ "type" : "array"
},
- "required" : [ "table_id" ],
- "type" : "object"
- }, {
- "properties" : { },
- "type" : "object"
- } ],
- "description" : "Request schema for constructing a query from a table.\n\n Query components:\n - filters: Filter conditions to apply\n - fields: Specific fields to select (omit for all fields)\n - aggregations: Aggregation functions (sum, count, avg, etc.). Use sort_order on the aggregation to order by it.\n - group_by: Fields to group by, with optional temporal granularity\n - order_by: Order by regular fields only. To order by an aggregation result, use sort_order on the aggregation instead.\n - limit: Maximum rows to return"
- },
- "metabase-enterprise.agent-api.api.entity-type" : {
- "description" : "The type of queryable entity.",
- "enum" : [ "table", "metric" ],
- "type" : "string"
- },
- "metabase-enterprise.agent-api.api.execute-query-request" : {
- "description" : "Request schema for /v1/execute. Accepts a base64-encoded MBQL query.",
- "properties" : {
- "query" : {
- "minLength" : 1,
- "type" : "string"
+ "success" : {
+ "type" : "boolean"
}
},
- "required" : [ "query" ],
+ "required" : [ "success" ],
"type" : "object"
},
- "metabase-enterprise.agent-api.api.execute-query-response" : {
- "description" : "Response from query execution. The HTTP status is always 202 because results are streamed —\n check the `status` field to determine success or failure.",
+ "metabase-enterprise.dependencies.api.broken-dependent-entity" : {
+ "description" : "Entity returned by /graph/broken endpoint - includes errors but no dependents_count.",
"properties" : {
"data" : {
- "properties" : {
- "cols" : {
- "items" : {
- "$ref" : "#/components/schemas/metabase-enterprise.agent-api.api.column-metadata"
- },
- "type" : "array"
- },
- "rows" : {
- "items" : {
- "items" : { },
- "type" : "array"
- },
- "type" : "array"
- }
- },
- "required" : [ "cols", "rows" ],
+ "properties" : { },
"type" : "object"
},
- "error" : {
- "type" : "string"
- },
- "row_count" : {
- "type" : "integer"
- },
- "running_time" : {
+ "id" : {
+ "minimum" : 1,
"type" : "integer"
},
- "status" : {
- "enum" : [ "completed", "failed" ],
+ "type" : {
"type" : "string"
}
},
- "required" : [ "status" ],
+ "required" : [ "id", "type", "data" ],
"type" : "object"
},
- "metabase-enterprise.agent-api.api.field" : {
- "description" : "A field from a table or metric. The field_id format is '<prefix><entity-id>-<field-index>' where prefix indicates the source (t=table, c=metric) and index is the position in the entity's fields.",
+ "metabase-enterprise.dependencies.api.card-body" : {
+ "description" : "Schema for an instance of a `:model/Card` (everything is optional to support updates).",
"properties" : {
- "database_type" : {
+ "collection_id" : {
"oneOf" : [ {
- "type" : "string"
+ "$ref" : "#/components/schemas/metabase.lib.schema.id.collection"
}, {
"type" : "null"
} ]
},
- "description" : {
+ "dashboard_id" : {
"oneOf" : [ {
- "type" : "string"
+ "$ref" : "#/components/schemas/metabase.lib.schema.id.dashboard"
}, {
"type" : "null"
} ]
},
- "field_id" : {
- "type" : "string"
- },
- "field_values" : {
+ "database_id" : {
"oneOf" : [ {
- "items" : { },
- "type" : "array"
+ "$ref" : "#/components/schemas/metabase.lib.schema.id.database"
}, {
"type" : "null"
} ]
},
- "name" : {
- "type" : "string"
- },
- "semantic_type" : {
+ "dataset_query" : {
"oneOf" : [ {
- "type" : "string"
+ "$ref" : "#/components/schemas/metabase.queries.schema.query"
}, {
"type" : "null"
} ]
},
- "type" : {
- "oneOf" : [ {
- "$ref" : "#/components/schemas/metabase-enterprise.agent-api.api.field-type"
- }, {
- "type" : "null"
- } ]
- }
- },
- "required" : [ "field_id", "name" ],
- "type" : "object"
- },
- "metabase-enterprise.agent-api.api.field-type" : {
- "description" : "A data type for a field derived from Metabase's type hierarchy.",
- "enum" : [ "boolean", "date", "datetime", "time", "number", "string" ],
- "type" : "string"
- },
- "metabase-enterprise.agent-api.api.field-values" : {
- "description" : "Statistics and sample values for a specific field.",
- "properties" : {
- "field_id" : {
+ "description" : {
"oneOf" : [ {
"type" : "string"
}, {
"type" : "null"
} ]
},
- "statistics" : {
- "oneOf" : [ {
- "$ref" : "#/components/schemas/metabase-enterprise.agent-api.api.statistics"
- }, {
- "type" : "null"
- } ]
- },
- "values" : {
- "oneOf" : [ {
- "items" : { },
- "type" : "array"
- }, {
- "type" : "null"
- } ]
- }
- },
- "type" : "object"
- },
- "metabase-enterprise.agent-api.api.measure" : {
- "description" : "A reusable aggregation expression associated with a table. Reference via measure_id in the aggregations array.",
- "properties" : {
- "description" : {
+ "document_id" : {
"oneOf" : [ {
- "type" : "string"
+ "$ref" : "#/components/schemas/metabase.documents.schema..document.id"
}, {
"type" : "null"
} ]
},
- "display_name" : {
+ "id" : {
"oneOf" : [ {
- "type" : "string"
+ "$ref" : "#/components/schemas/metabase.lib.schema.id.card"
}, {
"type" : "null"
} ]
},
- "id" : {
- "type" : "integer"
- },
"name" : {
- "type" : "string"
- }
- },
- "required" : [ "id", "name" ],
- "type" : "object"
- },
- "metabase-enterprise.agent-api.api.metric" : {
- "description" : "A metric with its queryable dimensions and segments. The default_time_dimension_field_id is the field_id of the recommended time dimension for temporal breakouts.",
- "properties" : {
- "default_time_dimension_field_id" : {
"oneOf" : [ {
"type" : "string"
}, {
"type" : "null"
} ]
},
- "description" : {
+ "parameter_mappings" : {
"oneOf" : [ {
- "type" : "string"
+ "$ref" : "#/components/schemas/metabase.parameters.schema.parameter-mappings"
}, {
"type" : "null"
} ]
},
- "id" : {
- "type" : "integer"
- },
- "name" : {
- "type" : "string"
- },
- "queryable_dimensions" : {
+ "parameters" : {
"oneOf" : [ {
- "items" : {
- "$ref" : "#/components/schemas/metabase-enterprise.agent-api.api.field"
- },
- "type" : "array"
+ "$ref" : "#/components/schemas/metabase.parameters.schema.parameters"
}, {
"type" : "null"
} ]
},
- "segments" : {
+ "result_metadata" : {
"oneOf" : [ {
- "items" : {
- "$ref" : "#/components/schemas/metabase-enterprise.agent-api.api.segment"
- },
- "type" : "array"
+ "$ref" : "#/components/schemas/metabase.analyze.query-results.ResultsMetadata"
}, {
"type" : "null"
} ]
},
"type" : {
- "const" : "metric"
- },
- "verified" : {
"oneOf" : [ {
- "type" : "boolean"
+ "$ref" : "#/components/schemas/metabase.lib.schema.metadata..card.type"
}, {
"type" : "null"
} ]
}
},
- "required" : [ "id", "type", "name" ],
"type" : "object"
},
- "metabase-enterprise.agent-api.api.metric-summary" : {
- "description" : "Summary of a metric associated with a table. Includes the field_id of the default time dimension for temporal breakouts.",
+ "metabase-enterprise.dependencies.api.card-entity" : {
"properties" : {
- "default_time_dimension_field_id" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
+ "data" : {
+ "properties" : {
+ "collection" : { },
+ "collection_id" : { },
+ "created_at" : { },
+ "creator" : { },
+ "creator_id" : { },
+ "dashboard" : { },
+ "dashboard_id" : { },
+ "database_id" : { },
+ "description" : { },
+ "display" : { },
+ "document" : { },
+ "document_id" : { },
+ "last-edit-info" : { },
+ "name" : { },
+ "query_type" : { },
+ "result_metadata" : { },
+ "type" : { },
+ "view_count" : { }
+ },
+ "type" : "object"
},
- "description" : {
+ "dependents_count" : {
"oneOf" : [ {
- "type" : "string"
+ "$ref" : "#/components/schemas/metabase-enterprise.dependencies.api.usages"
}, {
"type" : "null"
} ]
},
+ "dependents_errors" : {
+ "items" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.dependencies.models.analysis-finding-error.analysis-finding-error"
+ },
+ "type" : "array",
+ "uniqueItems" : true
+ },
"id" : {
+ "minimum" : 1,
"type" : "integer"
},
- "name" : {
- "type" : "string"
- },
"type" : {
- "const" : "metric"
+ "const" : "card"
}
},
- "required" : [ "id", "type", "name" ],
+ "required" : [ "id", "type", "data", "dependents_count" ],
"type" : "object"
},
- "metabase-enterprise.agent-api.api.related-table" : {
- "description" : "A table related to the queried entity via foreign key. The related_by field indicates the FK field name.",
+ "metabase-enterprise.dependencies.api.dashboard-entity" : {
"properties" : {
- "database_engine" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "database_id" : {
- "oneOf" : [ {
- "type" : "integer"
- }, {
- "type" : "null"
- } ]
- },
- "database_schema" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "description" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
+ "data" : {
+ "properties" : {
+ "collection" : { },
+ "collection_id" : { },
+ "created_at" : { },
+ "creator" : { },
+ "creator_id" : { },
+ "description" : { },
+ "last-edit-info" : { },
+ "moderation_reviews" : { },
+ "name" : { },
+ "view_count" : { }
+ },
+ "type" : "object"
},
- "display_name" : {
+ "dependents_count" : {
"oneOf" : [ {
- "type" : "string"
+ "$ref" : "#/components/schemas/metabase-enterprise.dependencies.api.usages"
}, {
"type" : "null"
} ]
},
- "fields" : {
- "oneOf" : [ {
- "items" : {
- "$ref" : "#/components/schemas/metabase-enterprise.agent-api.api.field"
- },
- "type" : "array"
- }, {
- "type" : "null"
- } ]
+ "dependents_errors" : {
+ "items" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.dependencies.models.analysis-finding-error.analysis-finding-error"
+ },
+ "type" : "array",
+ "uniqueItems" : true
},
"id" : {
+ "minimum" : 1,
"type" : "integer"
},
- "name" : {
- "type" : "string"
- },
- "related_by" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
"type" : {
- "const" : "table"
+ "const" : "dashboard"
}
},
- "required" : [ "id", "type", "name" ],
+ "required" : [ "id", "type", "data", "dependents_count" ],
"type" : "object"
},
- "metabase-enterprise.agent-api.api.search-response" : {
- "description" : "Search results containing tables and metrics matching the query.",
+ "metabase-enterprise.dependencies.api.document-entity" : {
"properties" : {
"data" : {
- "items" : {
- "$ref" : "#/components/schemas/metabase-enterprise.agent-api.api.search-result-item"
+ "properties" : {
+ "collection" : { },
+ "collection_id" : { },
+ "created_at" : { },
+ "creator" : { },
+ "description" : { },
+ "name" : { },
+ "view_count" : { }
},
- "type" : "array"
- },
- "total_count" : {
- "type" : "integer"
- }
- },
- "required" : [ "data", "total_count" ],
- "type" : "object"
- },
- "metabase-enterprise.agent-api.api.search-result-item" : {
- "description" : "A table or metric returned from search.",
- "properties" : {
- "created_at" : {
- "oneOf" : [ { }, {
- "type" : "null"
- } ]
- },
- "database_id" : {
- "oneOf" : [ {
- "type" : "integer"
- }, {
- "type" : "null"
- } ]
- },
- "database_schema" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "description" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "display_name" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "id" : {
- "type" : "integer"
- },
- "name" : {
- "type" : "string"
- },
- "type" : {
- "enum" : [ "table", "metric" ],
- "type" : "string"
- },
- "updated_at" : {
- "oneOf" : [ { }, {
- "type" : "null"
- } ]
- },
- "verified" : {
- "oneOf" : [ {
- "type" : "boolean"
- }, {
- "type" : "null"
- } ]
- }
- },
- "required" : [ "id", "type", "name" ],
- "type" : "object"
- },
- "metabase-enterprise.agent-api.api.segment" : {
- "description" : "A predefined filter condition that can be applied to queries via the segment_id in filters.",
- "properties" : {
- "description" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "display_name" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "id" : {
- "type" : "integer"
- },
- "name" : {
- "type" : "string"
- }
- },
- "required" : [ "id", "name" ],
- "type" : "object"
- },
- "metabase-enterprise.agent-api.api.statistics" : {
- "description" : "Statistical summary of a field's values computed during database sync. Includes counts, percentages, numeric summaries (min/max/avg/quartiles/sd), and date ranges.",
- "properties" : {
- "average_length" : {
- "oneOf" : [ {
- "type" : "number"
- }, {
- "type" : "null"
- } ]
- },
- "avg" : {
- "oneOf" : [ {
- "type" : "number"
- }, {
- "type" : "null"
- } ]
- },
- "distinct_count" : {
- "oneOf" : [ {
- "type" : "integer"
- }, {
- "type" : "null"
- } ]
- },
- "earliest" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "latest" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "max" : {
- "oneOf" : [ {
- "type" : "number"
- }, {
- "type" : "null"
- } ]
- },
- "min" : {
- "oneOf" : [ {
- "type" : "number"
- }, {
- "type" : "null"
- } ]
- },
- "percent_email" : {
- "oneOf" : [ {
- "type" : "number"
- }, {
- "type" : "null"
- } ]
- },
- "percent_json" : {
- "oneOf" : [ {
- "type" : "number"
- }, {
- "type" : "null"
- } ]
- },
- "percent_null" : {
- "oneOf" : [ {
- "type" : "number"
- }, {
- "type" : "null"
- } ]
- },
- "percent_state" : {
- "oneOf" : [ {
- "type" : "number"
- }, {
- "type" : "null"
- } ]
- },
- "percent_url" : {
- "oneOf" : [ {
- "type" : "number"
- }, {
- "type" : "null"
- } ]
- },
- "q1" : {
- "oneOf" : [ {
- "type" : "number"
- }, {
- "type" : "null"
- } ]
- },
- "q3" : {
- "oneOf" : [ {
- "type" : "number"
- }, {
- "type" : "null"
- } ]
- },
- "sd" : {
- "oneOf" : [ {
- "type" : "number"
- }, {
- "type" : "null"
- } ]
- }
- },
- "type" : "object"
- },
- "metabase-enterprise.agent-api.api.table" : {
- "description" : "Full details of a table including its fields, related tables, metrics, and segments.",
- "properties" : {
- "database_engine" : {
- "type" : "string"
- },
- "database_id" : {
- "type" : "integer"
- },
- "database_schema" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
+ "type" : "object"
},
- "description" : {
+ "dependents_count" : {
"oneOf" : [ {
- "type" : "string"
+ "$ref" : "#/components/schemas/metabase-enterprise.dependencies.api.usages"
}, {
"type" : "null"
} ]
},
- "display_name" : {
- "type" : "string"
- },
- "fields" : {
+ "dependents_errors" : {
"items" : {
- "$ref" : "#/components/schemas/metabase-enterprise.agent-api.api.field"
+ "$ref" : "#/components/schemas/metabase-enterprise.dependencies.models.analysis-finding-error.analysis-finding-error"
},
- "type" : "array"
+ "type" : "array",
+ "uniqueItems" : true
},
"id" : {
+ "minimum" : 1,
"type" : "integer"
},
- "measures" : {
- "oneOf" : [ {
- "items" : {
- "$ref" : "#/components/schemas/metabase-enterprise.agent-api.api.measure"
- },
- "type" : "array"
- }, {
- "type" : "null"
- } ]
- },
- "metrics" : {
- "oneOf" : [ {
- "items" : {
- "$ref" : "#/components/schemas/metabase-enterprise.agent-api.api.metric-summary"
- },
- "type" : "array"
- }, {
- "type" : "null"
- } ]
- },
- "name" : {
- "type" : "string"
- },
- "related_tables" : {
- "oneOf" : [ {
- "items" : {
- "$ref" : "#/components/schemas/metabase-enterprise.agent-api.api.related-table"
- },
- "type" : "array"
- }, {
- "type" : "null"
- } ]
- },
- "segments" : {
- "oneOf" : [ {
- "items" : {
- "$ref" : "#/components/schemas/metabase-enterprise.agent-api.api.segment"
- },
- "type" : "array"
- }, {
- "type" : "null"
- } ]
- },
"type" : {
- "$ref" : "#/components/schemas/metabase-enterprise.agent-api.api.entity-type"
+ "const" : "document"
}
},
- "required" : [ "id", "type", "name", "display_name", "database_id", "database_engine", "fields" ],
+ "required" : [ "id", "type", "data", "dependents_count" ],
"type" : "object"
},
- "metabase-enterprise.data-studio.api.table.publish-tables-response" : {
- "description" : "Schema for /publish-tables endpoint response. Matches frontend PublishTablesResponse type.",
- "properties" : {
- "target_collection" : {
- "oneOf" : [ {
- "description" : "value must be an instance of :model/Collection"
- }, {
- "type" : "null"
- } ]
- }
- },
- "required" : [ "target_collection" ],
- "type" : "object"
+ "metabase-enterprise.dependencies.api.entity" : {
+ "oneOf" : [ {
+ "$ref" : "#/components/schemas/metabase-enterprise.dependencies.api.table-entity"
+ }, {
+ "$ref" : "#/components/schemas/metabase-enterprise.dependencies.api.card-entity"
+ }, {
+ "$ref" : "#/components/schemas/metabase-enterprise.dependencies.api.snippet-entity"
+ }, {
+ "$ref" : "#/components/schemas/metabase-enterprise.dependencies.api.transform-entity"
+ }, {
+ "$ref" : "#/components/schemas/metabase-enterprise.dependencies.api.dashboard-entity"
+ }, {
+ "$ref" : "#/components/schemas/metabase-enterprise.dependencies.api.document-entity"
+ }, {
+ "$ref" : "#/components/schemas/metabase-enterprise.dependencies.api.sandbox-entity"
+ }, {
+ "$ref" : "#/components/schemas/metabase-enterprise.dependencies.api.segment-entity"
+ }, {
+ "$ref" : "#/components/schemas/metabase-enterprise.dependencies.api.measure-entity"
+ } ]
},
- "metabase-enterprise.data-studio.api.table.table-selectors" : {
+ "metabase-enterprise.dependencies.api.graph-response" : {
"properties" : {
- "database_ids" : {
- "items" : {
- "description" : "value must be an integer greater than zero.",
- "minimum" : 1,
- "type" : "integer"
- },
- "type" : "array"
- },
- "schema_ids" : {
+ "edges" : {
"items" : {
- "type" : "string"
+ "properties" : {
+ "from_entity_id" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.dependencies.dependency-types.entity-id"
+ },
+ "from_entity_type" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.dependencies.dependency-types.dependency-types"
+ },
+ "to_entity_id" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.dependencies.dependency-types.entity-id"
+ },
+ "to_entity_type" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.dependencies.dependency-types.dependency-types"
+ }
+ },
+ "required" : [ "from_entity_type", "from_entity_id", "to_entity_type", "to_entity_id" ],
+ "type" : "object"
},
"type" : "array"
},
- "table_ids" : {
+ "nodes" : {
"items" : {
- "description" : "value must be an integer greater than zero.",
- "minimum" : 1,
- "type" : "integer"
+ "$ref" : "#/components/schemas/metabase-enterprise.dependencies.api.entity"
},
"type" : "array"
}
},
+ "required" : [ "nodes", "edges" ],
"type" : "object"
},
- "metabase-enterprise.dependencies.api.base-entity" : {
+ "metabase-enterprise.dependencies.api.measure-entity" : {
"properties" : {
"data" : {
- "properties" : { },
+ "properties" : {
+ "created_at" : { },
+ "creator" : { },
+ "creator_id" : { },
+ "description" : { },
+ "name" : { },
+ "table" : { },
+ "table_id" : { }
+ },
"type" : "object"
},
"dependents_count" : {
@@ -1984,142 +1619,47 @@
"type" : "integer"
},
"type" : {
- "type" : "string"
+ "const" : "measure"
}
},
"required" : [ "id", "type", "data", "dependents_count" ],
"type" : "object"
},
- "metabase-enterprise.dependencies.api.broken-cards-response" : {
- "properties" : {
- "bad_cards" : {
- "items" : {
- "$ref" : "#/components/schemas/metabase.queries.schema.card"
- },
- "type" : "array"
- },
- "bad_transforms" : {
- "items" : {
- "$ref" : "#/components/schemas/metabase.transforms.schema.transform"
- },
- "type" : "array"
- },
- "success" : {
- "type" : "boolean"
- }
- },
- "required" : [ "success" ],
- "type" : "object"
- },
- "metabase-enterprise.dependencies.api.broken-dependent-entity" : {
- "description" : "Entity returned by /graph/broken endpoint - includes errors but no dependents_count.",
+ "metabase-enterprise.dependencies.api.sandbox-entity" : {
"properties" : {
"data" : {
- "properties" : { },
+ "properties" : {
+ "table" : { },
+ "table_id" : { }
+ },
"type" : "object"
},
- "id" : {
- "minimum" : 1,
- "type" : "integer"
- },
- "type" : {
- "type" : "string"
- }
- },
- "required" : [ "id", "type", "data" ],
- "type" : "object"
- },
- "metabase-enterprise.dependencies.api.card-body" : {
- "description" : "Schema for an instance of a `:model/Card` (everything is optional to support updates).",
- "properties" : {
- "collection_id" : {
- "oneOf" : [ {
- "$ref" : "#/components/schemas/metabase.lib.schema.id.collection"
- }, {
- "type" : "null"
- } ]
- },
- "dashboard_id" : {
- "oneOf" : [ {
- "$ref" : "#/components/schemas/metabase.lib.schema.id.dashboard"
- }, {
- "type" : "null"
- } ]
- },
- "database_id" : {
- "oneOf" : [ {
- "$ref" : "#/components/schemas/metabase.lib.schema.id.database"
- }, {
- "type" : "null"
- } ]
- },
- "dataset_query" : {
- "oneOf" : [ {
- "$ref" : "#/components/schemas/metabase.queries.schema.query"
- }, {
- "type" : "null"
- } ]
- },
- "description" : {
+ "dependents_count" : {
"oneOf" : [ {
- "type" : "string"
+ "$ref" : "#/components/schemas/metabase-enterprise.dependencies.api.usages"
}, {
"type" : "null"
} ]
},
- "document_id" : {
- "oneOf" : [ {
- "$ref" : "#/components/schemas/metabase.documents.schema..document.id"
- }, {
- "type" : "null"
- } ]
+ "dependents_errors" : {
+ "items" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.dependencies.models.analysis-finding-error.analysis-finding-error"
+ },
+ "type" : "array",
+ "uniqueItems" : true
},
"id" : {
- "oneOf" : [ {
- "$ref" : "#/components/schemas/metabase.lib.schema.id.card"
- }, {
- "type" : "null"
- } ]
- },
- "name" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "parameter_mappings" : {
- "oneOf" : [ {
- "$ref" : "#/components/schemas/metabase.parameters.schema.parameter-mappings"
- }, {
- "type" : "null"
- } ]
- },
- "parameters" : {
- "oneOf" : [ {
- "$ref" : "#/components/schemas/metabase.parameters.schema.parameters"
- }, {
- "type" : "null"
- } ]
- },
- "result_metadata" : {
- "oneOf" : [ {
- "$ref" : "#/components/schemas/metabase.analyze.query-results.ResultsMetadata"
- }, {
- "type" : "null"
- } ]
+ "minimum" : 1,
+ "type" : "integer"
},
"type" : {
- "oneOf" : [ {
- "$ref" : "#/components/schemas/metabase.lib.schema.metadata..card.type"
- }, {
- "type" : "null"
- } ]
+ "const" : "sandbox"
}
},
+ "required" : [ "id", "type", "data", "dependents_count" ],
"type" : "object"
},
- "metabase-enterprise.dependencies.api.card-entity" : {
+ "metabase-enterprise.dependencies.api.segment-entity" : {
"properties" : {
"data" : {
"properties" : {
@@ -2163,13 +1703,13 @@
"type" : "integer"
},
"type" : {
- "const" : "card"
+ "const" : "segment"
}
},
"required" : [ "id", "type", "data", "dependents_count" ],
"type" : "object"
},
- "metabase-enterprise.dependencies.api.dashboard-entity" : {
+ "metabase-enterprise.dependencies.api.snippet-entity" : {
"properties" : {
"data" : {
"properties" : {
@@ -2179,10 +1719,7 @@
"creator" : { },
"creator_id" : { },
"description" : { },
- "last-edit-info" : { },
- "moderation_reviews" : { },
- "name" : { },
- "view_count" : { }
+ "name" : { }
},
"type" : "object"
},
@@ -2205,276 +1742,21 @@
"type" : "integer"
},
"type" : {
- "const" : "dashboard"
+ "const" : "snippet"
}
},
"required" : [ "id", "type", "data", "dependents_count" ],
"type" : "object"
},
- "metabase-enterprise.dependencies.api.document-entity" : {
+ "metabase-enterprise.dependencies.api.table-entity" : {
"properties" : {
"data" : {
"properties" : {
- "collection" : { },
- "collection_id" : { },
- "created_at" : { },
- "creator" : { },
+ "db" : { },
+ "db_id" : { },
"description" : { },
- "name" : { },
- "view_count" : { }
- },
- "type" : "object"
- },
- "dependents_count" : {
- "oneOf" : [ {
- "$ref" : "#/components/schemas/metabase-enterprise.dependencies.api.usages"
- }, {
- "type" : "null"
- } ]
- },
- "dependents_errors" : {
- "items" : {
- "$ref" : "#/components/schemas/metabase-enterprise.dependencies.models.analysis-finding-error.analysis-finding-error"
- },
- "type" : "array",
- "uniqueItems" : true
- },
- "id" : {
- "minimum" : 1,
- "type" : "integer"
- },
- "type" : {
- "const" : "document"
- }
- },
- "required" : [ "id", "type", "data", "dependents_count" ],
- "type" : "object"
- },
- "metabase-enterprise.dependencies.api.entity" : {
- "oneOf" : [ {
- "$ref" : "#/components/schemas/metabase-enterprise.dependencies.api.table-entity"
- }, {
- "$ref" : "#/components/schemas/metabase-enterprise.dependencies.api.card-entity"
- }, {
- "$ref" : "#/components/schemas/metabase-enterprise.dependencies.api.snippet-entity"
- }, {
- "$ref" : "#/components/schemas/metabase-enterprise.dependencies.api.transform-entity"
- }, {
- "$ref" : "#/components/schemas/metabase-enterprise.dependencies.api.dashboard-entity"
- }, {
- "$ref" : "#/components/schemas/metabase-enterprise.dependencies.api.document-entity"
- }, {
- "$ref" : "#/components/schemas/metabase-enterprise.dependencies.api.sandbox-entity"
- }, {
- "$ref" : "#/components/schemas/metabase-enterprise.dependencies.api.segment-entity"
- }, {
- "$ref" : "#/components/schemas/metabase-enterprise.dependencies.api.measure-entity"
- } ]
- },
- "metabase-enterprise.dependencies.api.graph-response" : {
- "properties" : {
- "edges" : {
- "items" : {
- "properties" : {
- "from_entity_id" : {
- "$ref" : "#/components/schemas/metabase-enterprise.dependencies.dependency-types.entity-id"
- },
- "from_entity_type" : {
- "$ref" : "#/components/schemas/metabase-enterprise.dependencies.dependency-types.dependency-types"
- },
- "to_entity_id" : {
- "$ref" : "#/components/schemas/metabase-enterprise.dependencies.dependency-types.entity-id"
- },
- "to_entity_type" : {
- "$ref" : "#/components/schemas/metabase-enterprise.dependencies.dependency-types.dependency-types"
- }
- },
- "required" : [ "from_entity_type", "from_entity_id", "to_entity_type", "to_entity_id" ],
- "type" : "object"
- },
- "type" : "array"
- },
- "nodes" : {
- "items" : {
- "$ref" : "#/components/schemas/metabase-enterprise.dependencies.api.entity"
- },
- "type" : "array"
- }
- },
- "required" : [ "nodes", "edges" ],
- "type" : "object"
- },
- "metabase-enterprise.dependencies.api.measure-entity" : {
- "properties" : {
- "data" : {
- "properties" : {
- "created_at" : { },
- "creator" : { },
- "creator_id" : { },
- "description" : { },
- "name" : { },
- "table" : { },
- "table_id" : { }
- },
- "type" : "object"
- },
- "dependents_count" : {
- "oneOf" : [ {
- "$ref" : "#/components/schemas/metabase-enterprise.dependencies.api.usages"
- }, {
- "type" : "null"
- } ]
- },
- "dependents_errors" : {
- "items" : {
- "$ref" : "#/components/schemas/metabase-enterprise.dependencies.models.analysis-finding-error.analysis-finding-error"
- },
- "type" : "array",
- "uniqueItems" : true
- },
- "id" : {
- "minimum" : 1,
- "type" : "integer"
- },
- "type" : {
- "const" : "measure"
- }
- },
- "required" : [ "id", "type", "data", "dependents_count" ],
- "type" : "object"
- },
- "metabase-enterprise.dependencies.api.sandbox-entity" : {
- "properties" : {
- "data" : {
- "properties" : {
- "table" : { },
- "table_id" : { }
- },
- "type" : "object"
- },
- "dependents_count" : {
- "oneOf" : [ {
- "$ref" : "#/components/schemas/metabase-enterprise.dependencies.api.usages"
- }, {
- "type" : "null"
- } ]
- },
- "dependents_errors" : {
- "items" : {
- "$ref" : "#/components/schemas/metabase-enterprise.dependencies.models.analysis-finding-error.analysis-finding-error"
- },
- "type" : "array",
- "uniqueItems" : true
- },
- "id" : {
- "minimum" : 1,
- "type" : "integer"
- },
- "type" : {
- "const" : "sandbox"
- }
- },
- "required" : [ "id", "type", "data", "dependents_count" ],
- "type" : "object"
- },
- "metabase-enterprise.dependencies.api.segment-entity" : {
- "properties" : {
- "data" : {
- "properties" : {
- "collection" : { },
- "collection_id" : { },
- "created_at" : { },
- "creator" : { },
- "creator_id" : { },
- "dashboard" : { },
- "dashboard_id" : { },
- "database_id" : { },
- "description" : { },
- "display" : { },
- "document" : { },
- "document_id" : { },
- "last-edit-info" : { },
- "name" : { },
- "query_type" : { },
- "result_metadata" : { },
- "type" : { },
- "view_count" : { }
- },
- "type" : "object"
- },
- "dependents_count" : {
- "oneOf" : [ {
- "$ref" : "#/components/schemas/metabase-enterprise.dependencies.api.usages"
- }, {
- "type" : "null"
- } ]
- },
- "dependents_errors" : {
- "items" : {
- "$ref" : "#/components/schemas/metabase-enterprise.dependencies.models.analysis-finding-error.analysis-finding-error"
- },
- "type" : "array",
- "uniqueItems" : true
- },
- "id" : {
- "minimum" : 1,
- "type" : "integer"
- },
- "type" : {
- "const" : "segment"
- }
- },
- "required" : [ "id", "type", "data", "dependents_count" ],
- "type" : "object"
- },
- "metabase-enterprise.dependencies.api.snippet-entity" : {
- "properties" : {
- "data" : {
- "properties" : {
- "collection" : { },
- "collection_id" : { },
- "created_at" : { },
- "creator" : { },
- "creator_id" : { },
- "description" : { },
- "name" : { }
- },
- "type" : "object"
- },
- "dependents_count" : {
- "oneOf" : [ {
- "$ref" : "#/components/schemas/metabase-enterprise.dependencies.api.usages"
- }, {
- "type" : "null"
- } ]
- },
- "dependents_errors" : {
- "items" : {
- "$ref" : "#/components/schemas/metabase-enterprise.dependencies.models.analysis-finding-error.analysis-finding-error"
- },
- "type" : "array",
- "uniqueItems" : true
- },
- "id" : {
- "minimum" : 1,
- "type" : "integer"
- },
- "type" : {
- "const" : "snippet"
- }
- },
- "required" : [ "id", "type", "data", "dependents_count" ],
- "type" : "object"
- },
- "metabase-enterprise.dependencies.api.table-entity" : {
- "properties" : {
- "data" : {
- "properties" : {
- "db" : { },
- "db_id" : { },
- "description" : { },
- "display_name" : { },
- "fields" : { },
+ "display_name" : { },
+ "fields" : { },
"name" : { },
"owner" : { },
"owner_email" : { },
@@ -2645,145 +1927,84 @@
"required" : [ "id", "analyzed_entity_type", "analyzed_entity_id", "error_type" ],
"type" : "object"
},
- "metabase-enterprise.metabot-v3.client.schema.message" : {
+ "metabase-enterprise.permission-debug.impl.group-id" : {
+ "type" : "integer"
+ },
+ "metabase-enterprise.permission-debug.impl.perm-debug-info" : {
"properties" : {
- "content" : {
- "oneOf" : [ {
+ "data" : {
+ "properties" : { },
+ "type" : "object"
+ },
+ "decision" : {
+ "enum" : [ "allow", "denied", "limited" ],
+ "type" : "string"
+ },
+ "message" : {
+ "items" : {
"type" : "string"
- }, {
- "type" : "null"
- } ]
+ },
+ "type" : "array"
},
- "role" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.client.schema.role"
+ "model-id" : {
+ "type" : "string"
},
- "tool_call_id" : {
- "oneOf" : [ {
+ "model-type" : {
+ "enum" : [ "card", "invalid" ],
+ "type" : "string"
+ },
+ "segment" : {
+ "items" : {
+ "enum" : [ "sandboxed", "impersonated", "routed" ],
"type" : "string"
- }, {
- "type" : "null"
- } ]
+ },
+ "type" : "array",
+ "uniqueItems" : true
},
- "tool_calls" : {
- "oneOf" : [ {
- "items" : {
- "properties" : {
- "arguments" : {
- "type" : "string"
- },
- "id" : {
- "type" : "string"
- },
- "name" : {
- "type" : "string"
- }
- },
- "required" : [ "id", "name", "arguments" ],
- "type" : "object"
- },
- "type" : "array"
- }, {
- "type" : "null"
- } ]
+ "suggestions" : {
+ "additionalProperties" : {
+ "type" : "string"
+ },
+ "type" : "object"
}
},
- "required" : [ "role" ],
- "type" : "object"
- },
- "metabase-enterprise.metabot-v3.client.schema.messages" : {
- "items" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.client.schema.message"
- },
- "type" : "array"
- },
- "metabase-enterprise.metabot-v3.client.schema.role" : {
- "enum" : [ "system", "user", "assistant", "tool" ],
- "type" : "string"
- },
- "metabase-enterprise.metabot-v3.context.context" : {
- "additionalProperties" : { },
+ "required" : [ "model-type", "model-id", "decision", "segment", "message", "data", "suggestions" ],
"type" : "object"
},
- "metabase-enterprise.metabot-v3.tools.api.aggregation" : {
- "anyOf" : [ {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.count-aggregation"
- }, {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.field-aggregation"
- }, {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.measure-aggregation"
- } ],
- "description" : "Aggregation — count (field optional), field-based (field required), or measure-based."
- },
- "metabase-enterprise.metabot-v3.tools.api.answer-sources-arguments" : {
- "allOf" : [ {
- "properties" : {
- "with_metric_default_temporal_breakout" : {
- "default" : true,
- "type" : "boolean"
- },
- "with_metric_queryable_dimensions" : {
- "default" : true,
- "type" : "boolean"
- },
- "with_model_fields" : {
- "default" : true,
- "type" : "boolean"
+ "metabase-enterprise.replacement.schema.check-replace-source-response" : {
+ "properties" : {
+ "column_mappings" : {
+ "items" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.replacement.schema.column-mapping"
},
- "with_model_metrics" : {
- "default" : true,
- "type" : "boolean"
- }
- },
- "type" : "object"
- }, {
- "properties" : { },
- "type" : "object"
- } ]
- },
- "metabase-enterprise.metabot-v3.tools.api.answer-sources-result" : {
- "anyOf" : [ {
- "properties" : {
- "structured_output" : {
- "properties" : {
- "metrics" : {
- "items" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.full-metric"
- },
- "type" : "array"
- },
- "models" : {
- "items" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.table-result"
- },
- "type" : "array"
- }
- },
- "required" : [ "metrics", "models" ],
- "type" : "object"
- }
+ "type" : "array"
},
- "required" : [ "structured_output" ],
- "type" : "object"
- }, {
- "properties" : {
- "output" : {
- "type" : "string"
- }
+ "errors" : {
+ "items" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.replacement.schema.error-type"
+ },
+ "type" : "array"
},
- "required" : [ "output" ],
- "type" : "object"
- } ]
+ "success" : {
+ "type" : "boolean"
+ }
+ },
+ "required" : [ "success" ],
+ "type" : "object"
},
- "metabase-enterprise.metabot-v3.tools.api.basic-metric" : {
+ "metabase-enterprise.replacement.schema.column" : {
"properties" : {
- "default_time_dimension_field_id" : {
+ "base_type" : {
"oneOf" : [ {
"type" : "string"
}, {
"type" : "null"
} ]
},
- "description" : {
+ "display_name" : {
+ "type" : "string"
+ },
+ "effective_type" : {
"oneOf" : [ {
"type" : "string"
}, {
@@ -2791,783 +2012,788 @@
} ]
},
"id" : {
- "type" : "integer"
+ "oneOf" : [ {
+ "$ref" : "#/components/schemas/metabase.lib.schema.id.field"
+ }, {
+ "type" : "null"
+ } ]
},
"name" : {
"type" : "string"
},
- "type" : {
- "const" : "metric"
+ "semantic_type" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
}
},
- "required" : [ "id", "type", "name" ],
+ "required" : [ "id", "name", "display_name", "base_type", "effective_type", "semantic_type" ],
"type" : "object"
},
- "metabase-enterprise.metabot-v3.tools.api.basic-snippet" : {
+ "metabase-enterprise.replacement.schema.column-mapping" : {
"properties" : {
- "description" : {
+ "errors" : {
+ "items" : {
+ "$ref" : "#/components/schemas/metabase.source-swap.schema.column-error"
+ },
+ "type" : "array"
+ },
+ "source" : {
"oneOf" : [ {
- "type" : "string"
+ "$ref" : "#/components/schemas/metabase-enterprise.replacement.schema.column"
}, {
"type" : "null"
} ]
},
- "id" : {
- "type" : "integer"
- },
- "name" : {
- "type" : "string"
+ "target" : {
+ "oneOf" : [ {
+ "$ref" : "#/components/schemas/metabase-enterprise.replacement.schema.column"
+ }, {
+ "type" : "null"
+ } ]
}
},
- "required" : [ "id", "name" ],
"type" : "object"
},
- "metabase-enterprise.metabot-v3.tools.api.basic-transform" : {
+ "metabase-enterprise.replacement.schema.error-type" : {
+ "enum" : [ "cycle-detected", "database-mismatch", "incompatible-implicit-joins", "affects-gtap-policies" ],
+ "type" : "string"
+ },
+ "metabase-enterprise.replacement.schema.run" : {
"properties" : {
- "description" : {
+ "end_time" : {
"oneOf" : [ {
+ "format" : "date-time",
"type" : "string"
}, {
"type" : "null"
} ]
},
- "entity_id" : {
+ "id" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.replacement.schema.run-id"
+ },
+ "is_active" : {
+ "oneOf" : [ {
+ "type" : "boolean"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "message" : {
"oneOf" : [ {
"type" : "string"
}, {
"type" : "null"
} ]
},
- "id" : {
- "type" : "integer"
+ "progress" : {
+ "oneOf" : [ {
+ "type" : "number"
+ }, {
+ "type" : "null"
+ } ]
},
- "name" : {
- "type" : "string"
+ "source_entity_id" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.replacement.schema.source-entity-id"
},
- "source" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.transforms.transform-source"
+ "source_entity_type" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.replacement.schema.source-entity-type"
},
- "type" : {
- "enum" : [ "mbql", "native", "python" ],
+ "start_time" : {
+ "format" : "date-time",
"type" : "string"
- }
- },
- "required" : [ "id", "name", "type", "source" ],
- "type" : "object"
- },
- "metabase-enterprise.metabot-v3.tools.api.broken-question" : {
- "properties" : {
- "id" : {
- "type" : "integer"
},
- "name" : {
- "type" : "string"
- }
- },
- "required" : [ "id", "name" ],
- "type" : "object"
- },
- "metabase-enterprise.metabot-v3.tools.api.broken-transform" : {
- "properties" : {
- "id" : {
- "type" : "integer"
+ "status" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.replacement.schema.run-status"
},
- "name" : {
- "type" : "string"
+ "target_entity_id" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.replacement.schema.source-entity-id"
+ },
+ "target_entity_type" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.replacement.schema.source-entity-type"
+ },
+ "user_id" : {
+ "oneOf" : [ {
+ "$ref" : "#/components/schemas/metabase.lib.schema.id.user"
+ }, {
+ "type" : "null"
+ } ]
}
},
- "required" : [ "id", "name" ],
+ "required" : [ "id", "status", "is_active", "source_entity_type", "source_entity_id", "target_entity_type", "target_entity_id", "progress", "message", "user_id", "start_time", "end_time" ],
"type" : "object"
},
- "metabase-enterprise.metabot-v3.tools.api.bucket" : {
- "enum" : [ "millisecond", "second", "minute", "hour", "day", "week", "month", "quarter", "year", "second-of-minute", "minute-of-hour", "hour-of-day", "day-of-week", "day-of-month", "day-of-year", "week-of-year", "month-of-year", "quarter-of-year", "year-of-era" ],
+ "metabase-enterprise.replacement.schema.run-id" : {
+ "minimum" : 1,
+ "type" : "integer"
+ },
+ "metabase-enterprise.replacement.schema.run-status" : {
+ "enum" : [ "pending", "started", "succeeded", "failed", "canceled", "timeout" ],
"type" : "string"
},
- "metabase-enterprise.metabot-v3.tools.api.check-transform-dependencies-arguments" : {
- "allOf" : [ {
- "properties" : {
- "source" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.transforms.transform-source"
- },
- "transform_id" : {
- "type" : "integer"
- }
- },
- "required" : [ "transform_id", "source" ],
- "type" : "object"
+ "metabase-enterprise.replacement.schema.source-entity-id" : {
+ "anyOf" : [ {
+ "$ref" : "#/components/schemas/metabase.lib.schema.id.card"
}, {
- "properties" : { },
- "type" : "object"
+ "$ref" : "#/components/schemas/metabase.lib.schema.id.table"
} ]
},
- "metabase-enterprise.metabot-v3.tools.api.check-transform-dependencies-result" : {
- "anyOf" : [ {
- "properties" : {
- "structured_output" : {
- "properties" : {
- "bad_question_count" : {
- "type" : "integer"
- },
- "bad_questions" : {
- "items" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.broken-question"
- },
- "type" : "array"
- },
- "bad_transform_count" : {
- "type" : "integer"
- },
- "bad_transforms" : {
- "items" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.broken-transform"
- },
- "type" : "array"
- },
- "success" : {
- "type" : "boolean"
- }
- },
- "required" : [ "success", "bad_transform_count", "bad_transforms", "bad_question_count", "bad_questions" ],
- "type" : "object"
- }
- },
- "required" : [ "structured_output" ],
- "type" : "object"
- }, {
- "properties" : {
- "output" : {
+ "metabase-enterprise.replacement.schema.source-entity-type" : {
+ "enum" : [ "card", "table", "transform" ],
+ "type" : "string"
+ },
+ "metabase-enterprise.sandbox.schema.attribute-remappings" : {
+ "description" : "value must be a valid attribute remappings map (attribute name -> remapped name)",
+ "oneOf" : [ {
+ "additionalProperties" : {
+ "anyOf" : [ {
+ "minLength" : 1,
"type" : "string"
- }
+ }, {
+ "$ref" : "#/components/schemas/metabase.lib.schema.id.field"
+ }, {
+ "$ref" : "#/components/schemas/metabase.lib.schema.parameter.target"
+ } ]
},
- "required" : [ "output" ],
"type" : "object"
+ }, {
+ "type" : "null"
} ]
},
- "metabase-enterprise.metabot-v3.tools.api.column" : {
+ "metabase-enterprise.security-center.schema.advisory-id" : {
+ "minLength" : 1,
+ "type" : "string"
+ },
+ "metabase-enterprise.security-center.schema.affected-versions" : {
+ "items" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.security-center.schema.version-range"
+ },
+ "type" : "array"
+ },
+ "metabase-enterprise.security-center.schema.match-status" : {
+ "enum" : [ "unknown", "active", "resolved", "not_affected", "error" ],
+ "type" : "string"
+ },
+ "metabase-enterprise.security-center.schema.semver" : {
+ "pattern" : "^\\d+\\.\\d+\\.\\d+$",
+ "type" : "string"
+ },
+ "metabase-enterprise.security-center.schema.severity" : {
+ "enum" : [ "critical", "high", "medium", "low" ],
+ "type" : "string"
+ },
+ "metabase-enterprise.security-center.schema.version-range" : {
+ "description" : "A single affected version range with inclusive min and exclusive fixed.",
+ "properties" : {
+ "fixed" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.security-center.schema.semver"
+ },
+ "min" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.security-center.schema.semver"
+ }
+ },
+ "required" : [ "min", "fixed" ],
+ "type" : "object"
+ },
+ "metabase-enterprise.serialization.schema.export-metadata-response" : {
+ "properties" : {
+ "databases" : {
+ "items" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.serialization.schema.exported-database"
+ },
+ "type" : "array"
+ },
+ "fields" : {
+ "items" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.serialization.schema.exported-field"
+ },
+ "type" : "array"
+ },
+ "tables" : {
+ "items" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.serialization.schema.exported-table"
+ },
+ "type" : "array"
+ }
+ },
+ "type" : "object"
+ },
+ "metabase-enterprise.serialization.schema.exported-database" : {
"properties" : {
+ "engine" : {
+ "type" : "string"
+ },
+ "id" : {
+ "$ref" : "#/components/schemas/metabase.lib.schema.id.database"
+ },
+ "name" : {
+ "type" : "string"
+ }
+ },
+ "required" : [ "id", "name", "engine" ],
+ "type" : "object"
+ },
+ "metabase-enterprise.serialization.schema.exported-field" : {
+ "properties" : {
+ "base_type" : {
+ "type" : "string"
+ },
+ "coercion_strategy" : {
+ "type" : "string"
+ },
"database_type" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
+ "type" : "string"
},
"description" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
+ "type" : "string"
},
- "field_id" : {
+ "effective_type" : {
"type" : "string"
},
- "field_values" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.field-values"
+ "fk_target_field_id" : {
+ "$ref" : "#/components/schemas/metabase.lib.schema.id.field"
+ },
+ "id" : {
+ "$ref" : "#/components/schemas/metabase.lib.schema.id.field"
},
"name" : {
"type" : "string"
},
+ "nfc_path" : {
+ "items" : {
+ "type" : "string"
+ },
+ "type" : "array"
+ },
+ "parent_id" : {
+ "$ref" : "#/components/schemas/metabase.lib.schema.id.field"
+ },
"semantic_type" : {
+ "type" : "string"
+ },
+ "table_id" : {
+ "$ref" : "#/components/schemas/metabase.lib.schema.id.table"
+ }
+ },
+ "required" : [ "id", "table_id", "name", "base_type" ],
+ "type" : "object"
+ },
+ "metabase-enterprise.serialization.schema.exported-table" : {
+ "properties" : {
+ "db_id" : {
+ "$ref" : "#/components/schemas/metabase.lib.schema.id.database"
+ },
+ "description" : {
+ "type" : "string"
+ },
+ "id" : {
+ "$ref" : "#/components/schemas/metabase.lib.schema.id.table"
+ },
+ "name" : {
+ "type" : "string"
+ },
+ "schema" : {
+ "type" : "string"
+ }
+ },
+ "required" : [ "id", "db_id", "name" ],
+ "type" : "object"
+ },
+ "metabase-enterprise.support-access-grants.schema.create-grant-request" : {
+ "description" : "Schema for POST /api/ee/support-access-grants request body.",
+ "properties" : {
+ "grant_duration_minutes" : {
+ "maximum" : 10080,
+ "minimum" : 1,
+ "type" : "integer"
+ },
+ "notes" : {
"oneOf" : [ {
+ "maxLength" : 255,
+ "minLength" : 1,
"type" : "string"
}, {
"type" : "null"
} ]
},
- "type" : {
+ "ticket_number" : {
"oneOf" : [ {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.field-type"
+ "maxLength" : 100,
+ "minLength" : 1,
+ "type" : "string"
}, {
"type" : "null"
} ]
}
},
- "required" : [ "field_id", "name", "type" ],
+ "required" : [ "grant_duration_minutes" ],
"type" : "object"
},
- "metabase-enterprise.metabot-v3.tools.api.columns" : {
- "items" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.column"
- },
- "type" : "array"
- },
- "metabase-enterprise.metabot-v3.tools.api.count" : {
- "type" : "integer"
- },
- "metabase-enterprise.metabot-v3.tools.api.count-aggregation" : {
- "allOf" : [ {
- "properties" : {
- "bucket" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.bucket"
- },
- "function" : {
- "const" : "count"
- },
- "sort_order" : {
- "oneOf" : [ {
- "enum" : [ "asc", "desc" ],
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- }
- },
- "required" : [ "function" ],
- "type" : "object"
+ "metabase-enterprise.support-access-grants.schema.current-grant-response" : {
+ "description" : "Schema for GET /api/ee/support-access-grants/current response.",
+ "oneOf" : [ {
+ "$ref" : "#/components/schemas/metabase-enterprise.support-access-grants.schema.grant-response"
}, {
- "properties" : { },
- "type" : "object"
- } ],
- "description" : "Count aggregation — counts rows, no field_id needed.\n Use sort_order to order results by this aggregation ('asc' or 'desc')."
+ "type" : "null"
+ } ]
},
- "metabase-enterprise.metabot-v3.tools.api.create-dashboard-subscription-arguments" : {
- "allOf" : [ {
- "properties" : {
- "dashboard_id" : {
- "type" : "integer"
- },
- "email" : {
+ "metabase-enterprise.support-access-grants.schema.grant-response" : {
+ "description" : "Schema for a support access grant object in API responses.",
+ "properties" : {
+ "created_at" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.support-access-grants.schema.timestamp"
+ },
+ "grant_end_timestamp" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.support-access-grants.schema.timestamp"
+ },
+ "grant_start_timestamp" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.support-access-grants.schema.timestamp"
+ },
+ "id" : {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
+ },
+ "notes" : {
+ "oneOf" : [ {
"type" : "string"
- },
- "schedule" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.subscription-schedule"
- }
+ }, {
+ "type" : "null"
+ } ]
},
- "required" : [ "dashboard_id", "email", "schedule" ],
- "type" : "object"
- }, {
- "properties" : { },
- "type" : "object"
- } ]
- },
- "metabase-enterprise.metabot-v3.tools.api.disjunctive-numeric-filter" : {
- "allOf" : [ {
- "properties" : {
- "field_id" : {
+ "revoked_at" : {
+ "oneOf" : [ {
+ "$ref" : "#/components/schemas/metabase-enterprise.support-access-grants.schema.timestamp"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "revoked_by_user_id" : {
+ "oneOf" : [ {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "ticket_number" : {
+ "oneOf" : [ {
"type" : "string"
- },
- "operation" : {
- "enum" : [ "equals", "not-equals" ],
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "token" : {
+ "oneOf" : [ {
"type" : "string"
- },
- "values" : {
- "items" : {
- "anyOf" : [ {
- "type" : "integer"
- }, {
- "type" : "number"
- } ]
- },
- "type" : "array"
- }
+ }, {
+ "type" : "null"
+ } ]
},
- "required" : [ "field_id", "operation", "values" ],
- "type" : "object"
- }, {
- "properties" : { },
- "type" : "object"
- } ]
- },
- "metabase-enterprise.metabot-v3.tools.api.disjunctive-string-date-filter" : {
- "allOf" : [ {
- "properties" : {
- "field_id" : {
+ "updated_at" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.support-access-grants.schema.timestamp"
+ },
+ "user_email" : {
+ "oneOf" : [ {
"type" : "string"
- },
- "operation" : {
- "enum" : [ "equals", "not-equals", "string-contains", "string-not-contains", "string-starts-with", "string-ends-with" ],
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "user_id" : {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
+ },
+ "user_name" : {
+ "oneOf" : [ {
"type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ }
+ },
+ "required" : [ "id", "user_id", "user_name", "user_email", "ticket_number", "notes", "grant_start_timestamp", "grant_end_timestamp", "revoked_at", "revoked_by_user_id", "created_at", "updated_at" ],
+ "type" : "object"
+ },
+ "metabase-enterprise.support-access-grants.schema.list-grants-response" : {
+ "description" : "Schema for GET /api/ee/support-access-grants response (paginated list).",
+ "properties" : {
+ "data" : {
+ "items" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.support-access-grants.schema.grant-response"
},
- "values" : {
- "items" : {
- "type" : "string"
- },
- "type" : "array"
- }
+ "type" : "array"
},
- "required" : [ "field_id", "operation", "values" ],
- "type" : "object"
- }, {
- "properties" : { },
- "type" : "object"
- } ]
+ "limit" : {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
+ },
+ "offset" : {
+ "minimum" : 0,
+ "type" : "integer"
+ },
+ "total" : {
+ "minimum" : 0,
+ "type" : "integer"
+ }
+ },
+ "required" : [ "data", "total", "limit", "offset" ],
+ "type" : "object"
},
- "metabase-enterprise.metabot-v3.tools.api.disjunctive-temporal-extraction-filter" : {
- "allOf" : [ {
- "properties" : {
- "field_id" : {
- "type" : "string"
- },
- "operation" : {
- "enum" : [ "year-equals", "year-not-equals", "quarter-equals", "quarter-not-equals", "month-equals", "month-not-equals", "day-of-week-equals", "day-of-week-not-equals", "hour-equals", "hour-not-equals", "minute-equals", "minute-not-equals", "second-equals", "second-not-equals" ],
- "type" : "string"
- },
- "values" : {
- "items" : {
- "type" : "integer"
- },
- "type" : "array"
- }
+ "metabase-enterprise.support-access-grants.schema.timestamp" : {
+ "anyOf" : [ { }, { } ]
+ },
+ "metabase-enterprise.transforms-inspector.schema.alert-trigger" : {
+ "description" : "Definition for conditional alerts.\n FE evaluates condition against card results and shows alert if triggered.",
+ "properties" : {
+ "condition" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.transforms-inspector.schema.trigger-condition"
},
- "required" : [ "field_id", "operation", "values" ],
- "type" : "object"
- }, {
- "properties" : { },
- "type" : "object"
- } ]
+ "id" : {
+ "type" : "string"
+ },
+ "message" : {
+ "type" : "string"
+ },
+ "metadata" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.transforms-inspector.schema.trigger-metadata"
+ },
+ "severity" : {
+ "enum" : [ "info", "warning", "error" ],
+ "type" : "string"
+ }
+ },
+ "required" : [ "id", "condition", "severity", "message" ],
+ "type" : "object"
},
- "metabase-enterprise.metabot-v3.tools.api.disjunctive-temporal-filter" : {
- "allOf" : [ {
- "properties" : {
- "bucket" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.bucket"
- },
- "field_id" : {
- "type" : "string"
- },
- "operation" : {
- "enum" : [ "equals", "not-equals", "greater-than", "greater-than-or-equal", "less-than", "less-than-or-equal" ],
+ "metabase-enterprise.transforms-inspector.schema.card" : {
+ "description" : "A visualization card in the inspector output.\n\n Cards are generic - lens-specific data goes in :metadata.\n The :metadata map is opaque to the core but interpreted by\n lens-specific lib utilities on the frontend. ",
+ "properties" : {
+ "dataset_query" : {
+ "$ref" : "#/components/schemas/metabase.lib.schema.query"
+ },
+ "display" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.transforms-inspector.schema.display-type"
+ },
+ "id" : {
+ "type" : "string"
+ },
+ "metadata" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.transforms-inspector.schema.card-metadata"
+ },
+ "section_id" : {
+ "oneOf" : [ {
"type" : "string"
- },
- "values" : {
- "items" : {
- "anyOf" : [ {
- "type" : "string"
- }, {
- "type" : "integer"
- } ]
- },
- "type" : "array"
- }
+ }, {
+ "type" : "null"
+ } ]
},
- "required" : [ "field_id", "operation", "values" ],
- "type" : "object"
- }, {
- "properties" : { },
- "type" : "object"
- } ]
+ "title" : {
+ "type" : "string"
+ }
+ },
+ "required" : [ "id", "title", "display", "dataset_query" ],
+ "type" : "object"
},
- "metabase-enterprise.metabot-v3.tools.api.existence-filter" : {
- "allOf" : [ {
- "properties" : {
- "field_id" : {
+ "metabase-enterprise.transforms-inspector.schema.card-metadata" : {
+ "description" : "Common metadata for join-related cards and triggers.",
+ "properties" : {
+ "card_type" : {
+ "type" : "string"
+ },
+ "dedup_key" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.transforms-inspector.schema.dedup-key"
+ },
+ "depends_on_cards" : {
+ "items" : {
"type" : "string"
},
- "operation" : {
- "enum" : [ "is-null", "is-not-null", "string-is-empty", "string-is-not-empty", "is-true", "is-false" ],
- "type" : "string"
- }
+ "type" : "array",
+ "uniqueItems" : true
},
- "required" : [ "field_id", "operation" ],
- "type" : "object"
- }, {
- "properties" : { },
- "type" : "object"
- } ]
- },
- "metabase-enterprise.metabot-v3.tools.api.field" : {
- "allOf" : [ {
- "properties" : {
- "bucket" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.bucket"
- },
- "field_id" : {
- "type" : "string"
- }
+ "group_id" : {
+ "type" : "string"
},
- "required" : [ "field_id" ],
- "type" : "object"
- }, {
- "properties" : { },
- "type" : "object"
- } ]
+ "group_order" : {
+ "type" : "integer"
+ },
+ "group_role" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.transforms-inspector.schema.group-role"
+ },
+ "join_alias" : {
+ "type" : "string"
+ },
+ "join_step" : {
+ "type" : "integer"
+ },
+ "join_strategy" : {
+ "type" : "string"
+ }
+ },
+ "type" : "object"
},
- "metabase-enterprise.metabot-v3.tools.api.field-aggregation" : {
- "allOf" : [ {
- "properties" : {
- "bucket" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.bucket"
- },
- "field_id" : {
- "type" : "string"
- },
- "function" : {
- "enum" : [ "avg", "count-distinct", "max", "min", "sum" ],
- "type" : "string"
- },
- "sort_order" : {
- "oneOf" : [ {
- "enum" : [ "asc", "desc" ],
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- }
+ "metabase-enterprise.transforms-inspector.schema.complexity" : {
+ "description" : "Complexity estimate for a lens.",
+ "properties" : {
+ "level" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.transforms-inspector.schema.complexity-level"
},
- "required" : [ "field_id", "function" ],
- "type" : "object"
- }, {
- "properties" : { },
- "type" : "object"
- } ],
- "description" : "Aggregation using a field and function. field_id is required.\n Use sort_order to order results by this aggregation ('asc' or 'desc')."
+ "score" : {
+ "minimum" : 1,
+ "type" : "integer"
+ }
+ },
+ "required" : [ "level" ],
+ "type" : "object"
},
- "metabase-enterprise.metabot-v3.tools.api.field-type" : {
- "enum" : [ "boolean", "date", "datetime", "time", "number", "string" ],
+ "metabase-enterprise.transforms-inspector.schema.complexity-level" : {
+ "description" : "Estimated complexity/cost of generating a lens.",
+ "enum" : [ "fast", "slow", "very-slow" ],
"type" : "string"
},
- "metabase-enterprise.metabot-v3.tools.api.field-values" : {
- "anyOf" : [ {
- "items" : {
- "type" : "boolean"
+ "metabase-enterprise.transforms-inspector.schema.dedup-key" : {
+ "description" : "Key for deduplicating identical queries across lenses.\n Typically a vector like [:table_count table-id].",
+ "items" : { },
+ "type" : "array"
+ },
+ "metabase-enterprise.transforms-inspector.schema.discovery-response" : {
+ "description" : "Response from lens discovery.",
+ "properties" : {
+ "available_lenses" : {
+ "items" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.transforms-inspector.schema.lens-metadata"
+ },
+ "type" : "array"
},
- "type" : "array"
- }, {
- "items" : {
- "type" : "number"
+ "description" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
},
- "type" : "array"
- }, {
- "items" : {
+ "name" : {
"type" : "string"
},
- "type" : "array"
- } ]
- },
- "metabase-enterprise.metabot-v3.tools.api.field-values-arguments" : {
- "allOf" : [ {
- "properties" : {
- "entity_id" : {
- "type" : "integer"
- },
- "entity_type" : {
- "enum" : [ "table", "model", "metric" ],
- "type" : "string"
- },
- "field_id" : {
- "type" : "string"
+ "sources" : {
+ "items" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.transforms-inspector.schema.table"
},
- "limit" : {
- "oneOf" : [ {
- "type" : "integer"
- }, {
- "type" : "null"
- } ]
- }
+ "type" : "array"
},
- "required" : [ "entity_type", "entity_id", "field_id" ],
- "type" : "object"
- }, {
- "properties" : { },
- "type" : "object"
- } ]
- },
- "metabase-enterprise.metabot-v3.tools.api.field-values-result" : {
- "anyOf" : [ {
- "properties" : {
- "structured_output" : {
- "properties" : {
- "field_id" : {
- "type" : "string"
- },
- "statistics" : {
- "oneOf" : [ {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.statistics"
- }, {
- "type" : "null"
- } ]
- },
- "values" : {
- "oneOf" : [ {
- "items" : { },
- "type" : "array"
- }, {
- "type" : "null"
- } ]
- }
- },
- "required" : [ "field_id" ],
- "type" : "object"
- }
+ "status" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.transforms-inspector.schema.inspector-status"
},
- "required" : [ "structured_output" ],
- "type" : "object"
- }, {
- "properties" : {
- "output" : {
- "type" : "string"
- }
+ "target" : {
+ "oneOf" : [ {
+ "$ref" : "#/components/schemas/metabase-enterprise.transforms-inspector.schema.table"
+ }, {
+ "type" : "null"
+ } ]
},
- "required" : [ "output" ],
- "type" : "object"
- } ]
- },
- "metabase-enterprise.metabot-v3.tools.api.filter" : {
- "anyOf" : [ {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.segment-filter"
- }, {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.existence-filter"
- }, {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.temporal-extraction-filter"
- }, {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.disjunctive-temporal-extraction-filter"
- }, {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.temporal-filter"
- }, {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.disjunctive-temporal-filter"
- }, {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.string-filter"
- }, {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.disjunctive-string-date-filter"
- }, {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.numeric-filter"
- }, {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.disjunctive-numeric-filter"
- } ]
+ "visited_fields" : {
+ "oneOf" : [ {
+ "$ref" : "#/components/schemas/metabase-enterprise.transforms-inspector.schema.visited-fields"
+ }, {
+ "type" : "null"
+ } ]
+ }
+ },
+ "required" : [ "name", "status", "sources", "available_lenses" ],
+ "type" : "object"
},
- "metabase-enterprise.metabot-v3.tools.api.filter-records-arguments" : {
- "allOf" : [ {
- "properties" : {
- "data_source" : {
- "allOf" : [ {
- "anyOf" : [ {
- "properties" : {
- "query" : {
- "properties" : {
- "database" : {
- "type" : "integer"
- }
- },
- "required" : [ "database" ],
- "type" : "object"
- },
- "query_id" : {
- "type" : "string"
- }
- },
- "required" : [ "query" ],
- "type" : "object"
- }, {
- "properties" : {
- "report_id" : {
- "type" : "integer"
- }
- },
- "required" : [ "report_id" ],
- "type" : "object"
- }, {
- "properties" : {
- "table_id" : {
- "type" : "string"
- }
- },
- "required" : [ "table_id" ],
- "type" : "object"
- } ]
- }, {
- "properties" : { },
- "type" : "object"
- } ]
- },
- "filters" : {
- "items" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.filter"
- },
- "type" : "array"
- }
- },
- "required" : [ "data_source", "filters" ],
- "type" : "object"
- }, {
- "properties" : { },
- "type" : "object"
- } ]
+ "metabase-enterprise.transforms-inspector.schema.display-type" : {
+ "description" : "Valid display types for cards.",
+ "enum" : [ "bar", "row", "line", "area", "pie", "scalar", "gauge", "progress", "table", "hidden" ],
+ "type" : "string"
},
- "metabase-enterprise.metabot-v3.tools.api.filtering-result" : {
- "anyOf" : [ {
- "properties" : {
- "structured_output" : {
- "properties" : {
- "query" : {
- "$ref" : "#/components/schemas/metabase.legacy-mbql.schema.Query"
- },
- "query_id" : {
- "type" : "string"
- },
- "result_columns" : {
- "items" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.column"
- },
- "type" : "array"
- },
- "type" : {
- "const" : "query"
- }
- },
- "required" : [ "type", "query_id", "query", "result_columns" ],
- "type" : "object"
- }
- },
- "required" : [ "structured_output" ],
- "type" : "object"
- }, {
- "properties" : {
- "output" : {
+ "metabase-enterprise.transforms-inspector.schema.drill-lens" : {
+ "description" : "A drill-down lens available from the current lens.",
+ "properties" : {
+ "description" : {
+ "oneOf" : [ {
"type" : "string"
- }
+ }, {
+ "type" : "null"
+ } ]
},
- "required" : [ "output" ],
- "type" : "object"
- } ]
- },
- "metabase-enterprise.metabot-v3.tools.api.find-outliers-arguments" : {
- "allOf" : [ {
- "properties" : {
- "data_source" : {
- "allOf" : [ {
- "anyOf" : [ {
- "properties" : {
- "query" : {
- "properties" : {
- "database" : {
- "type" : "integer"
- }
- },
- "required" : [ "database" ],
- "type" : "object"
- },
- "query_id" : {
- "type" : "string"
- },
- "result_field_id" : {
- "type" : "string"
- }
- },
- "required" : [ "query", "result_field_id" ],
- "type" : "object"
- }, {
- "properties" : {
- "metric_id" : {
- "type" : "integer"
- }
- },
- "required" : [ "metric_id" ],
- "type" : "object"
- }, {
- "properties" : {
- "report_id" : {
- "type" : "integer"
- },
- "result_field_id" : {
- "type" : "string"
- }
- },
- "required" : [ "report_id", "result_field_id" ],
- "type" : "object"
- }, {
- "properties" : {
- "result_field_id" : {
- "type" : "string"
- },
- "table_id" : {
- "type" : "string"
- }
- },
- "required" : [ "table_id", "result_field_id" ],
- "type" : "object"
- } ]
- }, {
- "properties" : { },
- "type" : "object"
- } ]
- }
+ "display_name" : {
+ "type" : "string"
},
- "required" : [ "data_source" ],
- "type" : "object"
- }, {
- "properties" : { },
- "type" : "object"
- } ]
+ "id" : {
+ "type" : "string"
+ }
+ },
+ "required" : [ "id", "display_name" ],
+ "type" : "object"
},
- "metabase-enterprise.metabot-v3.tools.api.find-outliers-result" : {
- "anyOf" : [ {
- "properties" : {
- "structured_output" : {
- "items" : {
- "properties" : {
- "dimension" : { },
- "value" : {
- "anyOf" : [ {
- "type" : "integer"
- }, {
- "type" : "number"
- } ]
- }
- },
- "required" : [ "dimension", "value" ],
- "type" : "object"
- },
- "type" : "array"
- }
+ "metabase-enterprise.transforms-inspector.schema.drill-lens-trigger" : {
+ "description" : "Definition for conditional drill lens availability.\n FE evaluates condition and shows drill lens option if triggered.\n :params is passed to the drill lens when triggered.",
+ "properties" : {
+ "condition" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.transforms-inspector.schema.trigger-condition"
},
- "required" : [ "structured_output" ],
- "type" : "object"
- }, {
- "properties" : {
- "output" : {
- "type" : "string"
- }
+ "lens_id" : {
+ "type" : "string"
},
- "required" : [ "output" ],
- "type" : "object"
- } ]
+ "metadata" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.transforms-inspector.schema.trigger-metadata"
+ },
+ "params" : {
+ "additionalProperties" : { },
+ "type" : "object"
+ },
+ "reason" : {
+ "type" : "string"
+ }
+ },
+ "required" : [ "lens_id", "condition" ],
+ "type" : "object"
},
- "metabase-enterprise.metabot-v3.tools.api.full-metric" : {
+ "metabase-enterprise.transforms-inspector.schema.field" : {
+ "description" : "Field metadata for inspector.",
"properties" : {
- "default_time_dimension_field_id" : {
+ "base_type" : {
+ "$ref" : "#/components/schemas/metabase.lib.schema.common.base-type"
+ },
+ "display_name" : {
"oneOf" : [ {
"type" : "string"
}, {
"type" : "null"
} ]
},
- "description" : {
+ "id" : {
+ "minimum" : 1,
+ "type" : "integer"
+ },
+ "name" : {
+ "type" : "string"
+ },
+ "semantic_type" : {
"oneOf" : [ {
- "type" : "string"
+ "$ref" : "#/components/schemas/metabase.lib.schema.common.semantic-or-relation-type"
}, {
"type" : "null"
} ]
},
- "id" : {
+ "stats" : {
+ "oneOf" : [ {
+ "$ref" : "#/components/schemas/metabase-enterprise.transforms-inspector.schema.field-stats"
+ }, {
+ "type" : "null"
+ } ]
+ }
+ },
+ "required" : [ "id", "name", "base_type" ],
+ "type" : "object"
+ },
+ "metabase-enterprise.transforms-inspector.schema.field-stats" : {
+ "description" : "Statistics for a field from fingerprints.",
+ "properties" : {
+ "avg" : {
+ "type" : "number"
+ },
+ "distinct_count" : {
"type" : "integer"
},
- "name" : {
+ "earliest" : {
"type" : "string"
},
- "queryable_dimensions" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.columns"
+ "latest" : {
+ "type" : "string"
},
- "segments" : {
+ "max" : {
+ "type" : "number"
+ },
+ "min" : {
+ "type" : "number"
+ },
+ "nil_percent" : {
+ "type" : "number"
+ },
+ "q1" : {
+ "type" : "number"
+ },
+ "q3" : {
+ "type" : "number"
+ }
+ },
+ "type" : "object"
+ },
+ "metabase-enterprise.transforms-inspector.schema.group-role" : {
+ "description" : "Role of a card within a comparison group.",
+ "enum" : [ "input", "output" ],
+ "type" : "string"
+ },
+ "metabase-enterprise.transforms-inspector.schema.inspector-status" : {
+ "description" : "Status of the inspector result.",
+ "enum" : [ "not-run", "ready" ],
+ "type" : "string"
+ },
+ "metabase-enterprise.transforms-inspector.schema.layout-type" : {
+ "description" : "Layout hints for sections.\n - :flat - cards displayed in a grid\n - :comparison - cards grouped for side-by-side comparison",
+ "enum" : [ "flat", "comparison" ],
+ "type" : "string"
+ },
+ "metabase-enterprise.transforms-inspector.schema.lens" : {
+ "description" : "Full lens contents and drill lens/alert triggers.",
+ "properties" : {
+ "alert_triggers" : {
"items" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.segment"
+ "$ref" : "#/components/schemas/metabase-enterprise.transforms-inspector.schema.alert-trigger"
},
"type" : "array"
},
- "type" : {
- "const" : "metric"
+ "cards" : {
+ "items" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.transforms-inspector.schema.card"
+ },
+ "type" : "array"
},
- "verified" : {
- "type" : "boolean"
+ "complexity" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.transforms-inspector.schema.complexity"
+ },
+ "display_name" : {
+ "type" : "string"
+ },
+ "drill_lens_triggers" : {
+ "items" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.transforms-inspector.schema.drill-lens-trigger"
+ },
+ "type" : "array"
+ },
+ "drill_lenses" : {
+ "items" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.transforms-inspector.schema.drill-lens"
+ },
+ "type" : "array"
+ },
+ "id" : {
+ "type" : "string"
+ },
+ "sections" : {
+ "items" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.transforms-inspector.schema.section"
+ },
+ "type" : "array"
+ },
+ "summary" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.transforms-inspector.schema.lens-summary"
}
},
- "required" : [ "id", "type", "name" ],
+ "required" : [ "id", "display_name", "sections", "cards" ],
"type" : "object"
},
- "metabase-enterprise.metabot-v3.tools.api.full-snippet" : {
+ "metabase-enterprise.transforms-inspector.schema.lens-metadata" : {
"properties" : {
- "content" : {
- "type" : "string"
+ "complexity" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.transforms-inspector.schema.complexity"
},
"description" : {
"oneOf" : [ {
@@ -3576,30 +2802,46 @@
"type" : "null"
} ]
},
- "id" : {
- "type" : "integer"
+ "display_name" : {
+ "type" : "string"
},
- "name" : {
+ "id" : {
"type" : "string"
}
},
- "required" : [ "id", "name", "content" ],
+ "required" : [ "id", "display_name" ],
"type" : "object"
},
- "metabase-enterprise.metabot-v3.tools.api.full-transform" : {
+ "metabase-enterprise.transforms-inspector.schema.lens-summary" : {
+ "description" : "Summary section of a lens.",
"properties" : {
- "created_at" : {
- "description" : "value must be a valid date string",
- "type" : "string"
+ "alerts" : {
+ "items" : {
+ "properties" : { },
+ "type" : "object"
+ },
+ "type" : "array"
},
- "description" : {
+ "highlights" : {
+ "items" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.transforms-inspector.schema.summary-highlight"
+ },
+ "type" : "array"
+ },
+ "text" : {
"oneOf" : [ {
"type" : "string"
}, {
"type" : "null"
} ]
- },
- "entity_id" : {
+ }
+ },
+ "type" : "object"
+ },
+ "metabase-enterprise.transforms-inspector.schema.section" : {
+ "description" : "A section grouping cards in a lens.",
+ "properties" : {
+ "description" : {
"oneOf" : [ {
"type" : "string"
}, {
@@ -3607,708 +2849,875 @@
} ]
},
"id" : {
- "type" : "integer"
- },
- "name" : {
"type" : "string"
},
- "source" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.transforms.transform-source"
- },
- "target" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.transforms.transform-target"
- },
- "type" : {
- "enum" : [ "mbql", "native", "python" ],
- "type" : "string"
+ "layout" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.transforms-inspector.schema.layout-type"
},
- "updated_at" : {
- "description" : "value must be a valid date string",
+ "title" : {
"type" : "string"
}
},
- "required" : [ "id", "name", "type", "source", "created_at", "updated_at", "target" ],
+ "required" : [ "id", "title" ],
"type" : "object"
},
- "metabase-enterprise.metabot-v3.tools.api.generate-insights-arguments" : {
+ "metabase-enterprise.transforms-inspector.schema.summary-highlight" : {
+ "description" : "A highlight in the lens summary.",
"properties" : {
- "for" : {
- "anyOf" : [ {
- "properties" : {
- "metric_id" : {
- "type" : "integer"
- }
- },
- "required" : [ "metric_id" ],
- "type" : "object"
- }, {
- "properties" : {
- "table_id" : {
- "type" : "string"
- }
- },
- "required" : [ "table_id" ],
- "type" : "object"
- }, {
- "properties" : {
- "report_id" : {
- "type" : "integer"
- }
- },
- "required" : [ "report_id" ],
- "type" : "object"
- }, {
- "properties" : {
- "query" : {
- "properties" : { },
- "type" : "object"
- }
- },
- "required" : [ "query" ],
- "type" : "object"
+ "card_id" : {
+ "type" : "string"
+ },
+ "label" : {
+ "type" : "string"
+ },
+ "value" : {
+ "oneOf" : [ { }, {
+ "type" : "null"
} ]
}
},
- "required" : [ "for" ],
+ "required" : [ "label" ],
"type" : "object"
},
- "metabase-enterprise.metabot-v3.tools.api.get-current-user-result" : {
- "anyOf" : [ {
- "properties" : {
- "structured_output" : {
- "properties" : {
- "email_address" : {
- "type" : "string"
- },
- "glossary" : {
- "oneOf" : [ {
- "additionalProperties" : {
- "type" : "string"
- },
- "type" : "object"
- }, {
- "type" : "null"
- } ]
- },
- "id" : {
- "type" : "integer"
- },
- "name" : {
- "type" : "string"
- },
- "type" : {
- "const" : "user"
- }
- },
- "required" : [ "id", "type", "name", "email_address", "glossary" ],
- "type" : "object"
- }
+ "metabase-enterprise.transforms-inspector.schema.table" : {
+ "description" : "Table metadata.",
+ "properties" : {
+ "column_count" : {
+ "type" : "integer"
},
- "required" : [ "structured_output" ],
- "type" : "object"
- }, {
- "properties" : {
- "output" : {
+ "db_id" : {
+ "minimum" : 1,
+ "type" : "integer"
+ },
+ "fields" : {
+ "items" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.transforms-inspector.schema.field"
+ },
+ "type" : "array"
+ },
+ "schema" : {
+ "oneOf" : [ {
"type" : "string"
- }
+ }, {
+ "type" : "null"
+ } ]
},
- "required" : [ "output" ],
- "type" : "object"
- } ]
- },
- "metabase-enterprise.metabot-v3.tools.api.get-dashboard-details-arguments" : {
- "allOf" : [ {
- "properties" : {
- "dashboard_id" : {
- "type" : "integer"
- }
+ "table_id" : {
+ "minimum" : 1,
+ "type" : "integer"
},
- "required" : [ "dashboard_id" ],
- "type" : "object"
- }, {
- "properties" : { },
- "type" : "object"
- } ]
+ "table_name" : {
+ "type" : "string"
+ }
+ },
+ "required" : [ "table_id", "table_name", "db_id", "column_count", "fields" ],
+ "type" : "object"
},
- "metabase-enterprise.metabot-v3.tools.api.get-dashboard-details-result" : {
- "anyOf" : [ {
- "properties" : {
- "structured_output" : {
- "properties" : {
- "description" : {
- "type" : "string"
- },
- "id" : {
- "type" : "integer"
- },
- "name" : {
- "type" : "string"
- },
- "type" : {
- "const" : "dashboard"
- },
- "verified" : {
- "type" : "boolean"
- }
- },
- "required" : [ "id", "type", "name" ],
- "type" : "object"
- }
+ "metabase-enterprise.transforms-inspector.schema.trigger-condition" : {
+ "description" : "A named condition that triggers an alert or drill lens.\n Evaluated by multimethod in lib against card results.\n Only :name is required; other keys are condition-specific.",
+ "properties" : {
+ "name" : {
+ "type" : "string"
+ }
+ },
+ "required" : [ "name" ],
+ "type" : "object"
+ },
+ "metabase-enterprise.transforms-inspector.schema.trigger-metadata" : {
+ "description" : "Common metadata for join-related cards and triggers.",
+ "properties" : {
+ "join_alias" : {
+ "type" : "string"
},
- "required" : [ "structured_output" ],
- "type" : "object"
- }, {
- "properties" : {
- "output" : {
- "type" : "string"
- }
+ "join_step" : {
+ "type" : "integer"
},
- "required" : [ "output" ],
- "type" : "object"
- } ]
+ "join_strategy" : {
+ "type" : "string"
+ }
+ },
+ "type" : "object"
+ },
+ "metabase-enterprise.transforms-inspector.schema.visited-fields" : {
+ "description" : "Field IDs used in semantically important query clauses.\n Used for interestingness scoring and preselection.",
+ "properties" : {
+ "all" : {
+ "items" : {
+ "minimum" : 1,
+ "type" : "integer"
+ },
+ "type" : "array",
+ "uniqueItems" : true
+ }
+ },
+ "type" : "object"
},
- "metabase-enterprise.metabot-v3.tools.api.get-document-details-arguments" : {
+ "metabase.actions.schema..action.for-insert" : {
"allOf" : [ {
"properties" : {
- "document_id" : {
- "type" : "integer"
+ "archived" : {
+ "type" : "boolean"
+ },
+ "description" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "model_id" : {
+ "$ref" : "#/components/schemas/metabase.lib.schema.id.card"
+ },
+ "name" : {
+ "type" : "string"
+ },
+ "parameter_mappings" : {
+ "oneOf" : [ {
+ "$ref" : "#/components/schemas/metabase.parameters.schema.parameter-mappings"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "parameters" : {
+ "oneOf" : [ {
+ "$ref" : "#/components/schemas/metabase.parameters.schema.parameters"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "type" : {
+ "$ref" : "#/components/schemas/metabase.actions.schema.type"
+ },
+ "visualization_settings" : {
+ "oneOf" : [ {
+ "type" : "object"
+ }, {
+ "type" : "null"
+ } ]
}
},
- "required" : [ "document_id" ],
+ "required" : [ "name", "type", "model_id" ],
"type" : "object"
}, {
- "properties" : { },
- "type" : "object"
- } ]
+ "oneOf" : [ {
+ "$ref" : "#/components/schemas/metabase.actions.schema.http-action"
+ }, {
+ "$ref" : "#/components/schemas/metabase.actions.schema.implicit-action"
+ }, {
+ "$ref" : "#/components/schemas/metabase.actions.schema.query-action"
+ }, {
+ "properties" : { },
+ "type" : "object"
+ } ]
+ } ],
+ "description" : "Schema for inserting a new Action (REST API or internally)."
},
- "metabase-enterprise.metabot-v3.tools.api.get-document-details-result" : {
- "anyOf" : [ {
+ "metabase.actions.schema..action.for-update" : {
+ "allOf" : [ {
"properties" : {
- "structured_output" : {
- "properties" : {
- "document" : {
- "type" : "string"
- },
- "id" : {
- "type" : "integer"
- },
- "name" : {
- "type" : "string"
- }
- },
- "required" : [ "id", "name", "document" ],
- "type" : "object"
+ "archived" : {
+ "type" : "boolean"
+ },
+ "description" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "id" : {
+ "$ref" : "#/components/schemas/metabase.actions.schema.id"
+ },
+ "model_id" : {
+ "$ref" : "#/components/schemas/metabase.lib.schema.id.card"
+ },
+ "name" : {
+ "type" : "string"
+ },
+ "parameter_mappings" : {
+ "oneOf" : [ {
+ "$ref" : "#/components/schemas/metabase.parameters.schema.parameter-mappings"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "parameters" : {
+ "oneOf" : [ {
+ "$ref" : "#/components/schemas/metabase.parameters.schema.parameters"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "type" : {
+ "$ref" : "#/components/schemas/metabase.actions.schema.type"
+ },
+ "visualization_settings" : {
+ "oneOf" : [ {
+ "type" : "object"
+ }, {
+ "type" : "null"
+ } ]
}
},
- "required" : [ "structured_output" ],
"type" : "object"
}, {
- "properties" : {
- "output" : {
+ "oneOf" : [ {
+ "$ref" : "#/components/schemas/metabase.actions.schema.http-action"
+ }, {
+ "$ref" : "#/components/schemas/metabase.actions.schema.implicit-action"
+ }, {
+ "$ref" : "#/components/schemas/metabase.actions.schema.query-action"
+ }, {
+ "properties" : { },
+ "type" : "object"
+ } ]
+ } ],
+ "description" : "Schema for updating an Action (REST API or internally)."
+ },
+ "metabase.actions.schema..http-action.json-query" : {
+ "description" : "must be a valid json-query, something like '.item.title'",
+ "type" : "string"
+ },
+ "metabase.actions.schema..http-action.template" : {
+ "additionalProperties" : false,
+ "properties" : {
+ "body" : {
+ "oneOf" : [ {
"type" : "string"
- }
+ }, {
+ "type" : "null"
+ } ]
},
- "required" : [ "output" ],
- "type" : "object"
- } ]
+ "headers" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "method" : {
+ "enum" : [ "GET", "POST", "PUT", "DELETE", "PATCH" ],
+ "type" : "string"
+ },
+ "parameters" : {
+ "oneOf" : [ {
+ "$ref" : "#/components/schemas/metabase.parameters.schema.parameters"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "url" : {
+ "type" : "string"
+ }
+ },
+ "required" : [ "method", "url" ],
+ "type" : "object"
+ },
+ "metabase.actions.schema..implicit-action.kind" : {
+ "description" : "Unsupported implicit action kind",
+ "enum" : [ "row/create", "row/update", "row/delete", "bulk/create", "bulk/update", "bulk/delete" ],
+ "type" : "string"
},
- "metabase-enterprise.metabot-v3.tools.api.get-metric-details-arguments" : {
+ "metabase.actions.schema.action" : {
"allOf" : [ {
"properties" : {
- "metric_id" : {
- "type" : "integer"
- },
- "with_default_temporal_breakout" : {
- "default" : true,
+ "archived" : {
"type" : "boolean"
},
- "with_field_values" : {
- "default" : true,
- "type" : "boolean"
+ "created_at" : { },
+ "creator_id" : {
+ "oneOf" : [ {
+ "$ref" : "#/components/schemas/metabase.lib.schema.id.user"
+ }, {
+ "type" : "null"
+ } ]
},
- "with_queryable_dimensions" : {
- "default" : true,
- "type" : "boolean"
+ "description" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
},
- "with_segments" : {
- "default" : false,
- "type" : "boolean"
+ "id" : {
+ "$ref" : "#/components/schemas/metabase.actions.schema.id"
+ },
+ "made_public_by_id" : {
+ "oneOf" : [ {
+ "$ref" : "#/components/schemas/metabase.lib.schema.id.user"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "model_id" : {
+ "$ref" : "#/components/schemas/metabase.lib.schema.id.card"
+ },
+ "name" : {
+ "type" : "string"
+ },
+ "parameter_mappings" : {
+ "oneOf" : [ {
+ "$ref" : "#/components/schemas/metabase.parameters.schema.parameter-mappings"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "parameters" : {
+ "oneOf" : [ {
+ "$ref" : "#/components/schemas/metabase.parameters.schema.parameters"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "public_uuid" : {
+ "oneOf" : [ {
+ "description" : "value must be a valid UUID.",
+ "pattern" : "[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "type" : {
+ "$ref" : "#/components/schemas/metabase.actions.schema.type"
+ },
+ "updated_at" : { },
+ "visualization_settings" : {
+ "oneOf" : [ {
+ "type" : "object"
+ }, {
+ "type" : "null"
+ } ]
}
},
- "required" : [ "metric_id" ],
+ "required" : [ "id" ],
"type" : "object"
}, {
- "properties" : { },
- "type" : "object"
- } ]
+ "oneOf" : [ {
+ "$ref" : "#/components/schemas/metabase.actions.schema.http-action"
+ }, {
+ "$ref" : "#/components/schemas/metabase.actions.schema.implicit-action"
+ }, {
+ "$ref" : "#/components/schemas/metabase.actions.schema.query-action"
+ }, {
+ "properties" : { },
+ "type" : "object"
+ } ]
+ } ],
+ "description" : "An Action as it should appear when we `SELECT` it from the app DB."
},
- "metabase-enterprise.metabot-v3.tools.api.get-metric-details-result" : {
- "anyOf" : [ {
- "properties" : {
- "structured_output" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.full-metric"
- }
+ "metabase.actions.schema.http-action" : {
+ "properties" : {
+ "error_handle" : {
+ "oneOf" : [ {
+ "$ref" : "#/components/schemas/metabase.actions.schema..http-action.json-query"
+ }, {
+ "type" : "null"
+ } ]
},
- "required" : [ "structured_output" ],
- "type" : "object"
- }, {
- "properties" : {
- "output" : {
- "type" : "string"
- }
+ "response_handle" : {
+ "oneOf" : [ {
+ "$ref" : "#/components/schemas/metabase.actions.schema..http-action.json-query"
+ }, {
+ "type" : "null"
+ } ]
},
- "required" : [ "output" ],
- "type" : "object"
- } ]
+ "template" : {
+ "oneOf" : [ {
+ "$ref" : "#/components/schemas/metabase.actions.schema..http-action.template"
+ }, {
+ "type" : "null"
+ } ]
+ }
+ },
+ "type" : "object"
},
- "metabase-enterprise.metabot-v3.tools.api.get-query-details-arguments" : {
+ "metabase.actions.schema.id" : {
+ "description" : "Valid Action ID",
+ "minimum" : 1,
+ "type" : "integer"
+ },
+ "metabase.actions.schema.implicit-action" : {
"properties" : {
- "query" : {
- "properties" : { },
- "type" : "object"
+ "kind" : {
+ "oneOf" : [ {
+ "$ref" : "#/components/schemas/metabase.actions.schema..implicit-action.kind"
+ }, {
+ "type" : "null"
+ } ]
+ }
+ },
+ "type" : "object"
+ },
+ "metabase.actions.schema.query-action" : {
+ "properties" : {
+ "database_id" : {
+ "oneOf" : [ {
+ "$ref" : "#/components/schemas/metabase.lib.schema.id.database"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "dataset_query" : {
+ "oneOf" : [ {
+ "$ref" : "#/components/schemas/metabase.queries.schema.query"
+ }, {
+ "type" : "null"
+ } ]
}
},
- "required" : [ "query" ],
"type" : "object"
},
- "metabase-enterprise.metabot-v3.tools.api.get-query-details-result" : {
+ "metabase.actions.schema.type" : {
+ "description" : "Unsupported action type",
+ "enum" : [ "http", "implicit", "query" ],
+ "type" : "string"
+ },
+ "metabase.actions.types..scope.raw" : {
"anyOf" : [ {
"properties" : {
- "structured_output" : {
- "properties" : {
- "query" : {
- "properties" : { },
- "type" : "object"
- },
- "query_id" : {
- "type" : "string"
- },
- "result_columns" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.columns"
- },
- "type" : {
- "const" : "query"
- }
- },
- "required" : [ "type", "query_id", "query", "result_columns" ],
- "type" : "object"
+ "dashboard-id" : {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
}
},
- "required" : [ "structured_output" ],
+ "required" : [ "dashboard-id" ],
"type" : "object"
}, {
"properties" : {
- "output" : {
- "type" : "string"
+ "dashcard-id" : {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
}
},
- "required" : [ "output" ],
+ "required" : [ "dashcard-id" ],
"type" : "object"
- } ]
- },
- "metabase-enterprise.metabot-v3.tools.api.get-report-details-arguments" : {
- "allOf" : [ {
+ }, {
"properties" : {
- "report_id" : {
+ "card-id" : {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
"type" : "integer"
- },
- "with_field_values" : {
- "default" : true,
- "type" : "boolean"
- },
- "with_fields" : {
- "default" : true,
- "type" : "boolean"
}
},
- "required" : [ "report_id" ],
+ "required" : [ "card-id" ],
"type" : "object"
}, {
- "properties" : { },
- "type" : "object"
- } ]
- },
- "metabase-enterprise.metabot-v3.tools.api.get-report-details-result" : {
- "anyOf" : [ {
"properties" : {
- "structured_output" : {
- "properties" : {
- "description" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "id" : {
- "type" : "integer"
- },
- "name" : {
- "type" : "string"
- },
- "result_columns" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.columns"
- },
- "type" : {
- "const" : "question"
- },
- "verified" : {
- "type" : "boolean"
- }
- },
- "required" : [ "id", "type", "name", "result_columns" ],
- "type" : "object"
+ "model-id" : {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
}
},
- "required" : [ "structured_output" ],
+ "required" : [ "model-id" ],
"type" : "object"
}, {
"properties" : {
- "output" : {
- "type" : "string"
+ "table-id" : {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
}
},
- "required" : [ "output" ],
+ "required" : [ "table-id" ],
"type" : "object"
- } ]
- },
- "metabase-enterprise.metabot-v3.tools.api.get-snippet-details-arguments" : {
- "allOf" : [ {
+ }, {
"properties" : {
- "snippet_id" : {
+ "webhook-id" : {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
"type" : "integer"
}
},
- "required" : [ "snippet_id" ],
+ "required" : [ "webhook-id" ],
"type" : "object"
}, {
- "properties" : { },
+ "properties" : {
+ "unknown" : {
+ "enum" : [ "model-action" ],
+ "type" : "string"
+ }
+ },
+ "required" : [ "unknown" ],
"type" : "object"
} ]
},
- "metabase-enterprise.metabot-v3.tools.api.get-snippet-details-result" : {
- "description" : "Schema for SQL snippet detail results",
+ "metabase.agent-api.api.column-metadata" : {
+ "description" : "Metadata for a single result column.",
"properties" : {
- "structured_output" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.full-snippet"
+ "base_type" : {
+ "type" : "string"
+ },
+ "display_name" : {
+ "type" : "string"
+ },
+ "effective_type" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "name" : {
+ "type" : "string"
}
},
- "required" : [ "structured_output" ],
+ "required" : [ "name", "base_type", "display_name" ],
"type" : "object"
},
- "metabase-enterprise.metabot-v3.tools.api.get-snippets-result" : {
- "description" : "Schema for SQL snippet list results",
+ "metabase.agent-api.api.construct-query-request" : {
+ "additionalProperties" : false,
+ "description" : "Request body for /v2/construct-query and the fresh-query branch of /v2/query.\n A single `:query` key whose value is a JSON object matching\n [[metabase.lib.schema/external-query]] — the canonical portable MBQL 5 wire format. The\n query is fully self-describing: the database is derived from the first stage's\n `source-table:` or `source-card:`, all field references are portable FKs\n (`[<db-name>, <schema>, <table-name>, <column-name>]`), and there is no auxiliary\n `source_entity` / `referenced_entities` envelope. See\n `resources/metabot/prompts/tools/construct_notebook_query.md` for the full format reference\n (including operators, joins, expressions, multi-stage queries, and FK conventions).\n\n Closed map: any extra top-level keys (notably the legacy `source_entity` /\n `referenced_entities` envelope from before the repr migration) are rejected with a 400 so\n callers don't silently send fields the server ignores.",
"properties" : {
- "structured_output" : {
- "items" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.basic-snippet"
- },
- "type" : "array"
+ "query" : {
+ "$ref" : "#/components/schemas/metabase.lib.schema.external-query"
}
},
- "required" : [ "structured_output" ],
+ "required" : [ "query" ],
"type" : "object"
},
- "metabase-enterprise.metabot-v3.tools.api.get-table-details-arguments" : {
- "allOf" : [ {
- "properties" : {
- "model_id" : {
- "type" : "integer"
- },
- "table_id" : {
- "anyOf" : [ {
- "type" : "integer"
- }, {
- "type" : "string"
- } ]
- },
- "with_field_values" : {
- "default" : true,
- "type" : "boolean"
- },
- "with_fields" : {
- "default" : true,
- "type" : "boolean"
- },
- "with_measures" : {
- "default" : false,
- "type" : "boolean"
- },
- "with_metric_default_temporal_breakout" : {
- "default" : true,
- "type" : "boolean"
- },
- "with_metrics" : {
- "default" : true,
- "type" : "boolean"
- },
- "with_related_tables" : {
- "default" : true,
- "type" : "boolean"
- },
- "with_segments" : {
- "default" : false,
- "type" : "boolean"
- }
- },
- "type" : "object"
- }, {
- "properties" : { },
- "type" : "object"
- } ]
+ "metabase.agent-api.api.construct-query-response" : {
+ "description" : "Response containing a base64-encoded MBQL query for use with /v1/execute.",
+ "properties" : {
+ "query" : {
+ "minLength" : 1,
+ "type" : "string"
+ }
+ },
+ "required" : [ "query" ],
+ "type" : "object"
},
- "metabase-enterprise.metabot-v3.tools.api.get-table-details-result" : {
- "anyOf" : [ {
- "properties" : {
- "structured_output" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.table-result"
- }
+ "metabase.agent-api.api.create-dashboard-request" : {
+ "properties" : {
+ "collection_id" : {
+ "oneOf" : [ {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
+ }, {
+ "type" : "null"
+ } ]
},
- "required" : [ "structured_output" ],
- "type" : "object"
- }, {
- "properties" : {
- "output" : {
+ "description" : {
+ "oneOf" : [ {
"type" : "string"
- }
+ }, {
+ "type" : "null"
+ } ]
},
- "required" : [ "output" ],
- "type" : "object"
- } ]
+ "name" : {
+ "minLength" : 1,
+ "type" : "string"
+ },
+ "question_ids" : {
+ "oneOf" : [ {
+ "items" : {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
+ },
+ "type" : "array"
+ }, {
+ "type" : "null"
+ } ]
+ }
+ },
+ "required" : [ "name" ],
+ "type" : "object"
},
- "metabase-enterprise.metabot-v3.tools.api.get-tables-arguments" : {
- "allOf" : [ {
- "properties" : {
- "database_id" : {
+ "metabase.agent-api.api.create-dashboard-response" : {
+ "properties" : {
+ "collection_id" : {
+ "oneOf" : [ {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
"type" : "integer"
- }
+ }, {
+ "type" : "null"
+ } ]
},
- "required" : [ "database_id" ],
- "type" : "object"
- }, {
- "properties" : { },
- "type" : "object"
- } ]
- },
- "metabase-enterprise.metabot-v3.tools.api.get-tables-result" : {
- "anyOf" : [ {
- "properties" : {
- "structured_output" : {
- "properties" : {
- "database" : {
- "properties" : {
- "description" : {
- "type" : "string"
- },
- "engine" : {
- "type" : "string"
- },
- "id" : {
- "type" : "integer"
- },
- "name" : {
- "type" : "string"
- }
- },
- "required" : [ "id", "engine", "name", "description" ],
- "type" : "object"
- },
- "tables" : {
- "items" : {
- "properties" : {
- "columns" : {
- "items" : {
- "properties" : {
- "description" : {
- "type" : "string"
- },
- "id" : {
- "type" : "integer"
- },
- "name" : {
- "type" : "string"
- },
- "type" : {
- "type" : "string"
- }
- },
- "required" : [ "id", "name", "description", "type" ],
- "type" : "object"
- },
- "type" : "array"
- },
- "description" : {
- "type" : "string"
- },
- "id" : {
- "type" : "integer"
- },
- "name" : {
- "type" : "string"
- }
- },
- "required" : [ "id", "name", "description", "columns" ],
- "type" : "object"
- },
- "type" : "array"
- }
- },
- "required" : [ "database", "tables" ],
- "type" : "object"
- }
+ "dashcard_ids" : {
+ "items" : {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
+ },
+ "type" : "array"
},
- "required" : [ "structured_output" ],
- "type" : "object"
- }, {
- "properties" : {
- "output" : {
+ "description" : {
+ "oneOf" : [ {
"type" : "string"
- }
+ }, {
+ "type" : "null"
+ } ]
},
- "required" : [ "output" ],
- "type" : "object"
- } ]
+ "id" : {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
+ },
+ "name" : {
+ "minLength" : 1,
+ "type" : "string"
+ }
+ },
+ "required" : [ "id", "name", "collection_id", "description", "dashcard_ids" ],
+ "type" : "object"
},
- "metabase-enterprise.metabot-v3.tools.api.get-transform-details-arguments" : {
- "allOf" : [ {
- "properties" : {
- "transform_id" : {
+ "metabase.agent-api.api.create-question-request" : {
+ "properties" : {
+ "collection_id" : {
+ "oneOf" : [ {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
"type" : "integer"
- }
+ }, {
+ "type" : "null"
+ } ]
},
- "required" : [ "transform_id" ],
- "type" : "object"
- }, {
- "properties" : { },
- "type" : "object"
- } ]
- },
- "metabase-enterprise.metabot-v3.tools.api.get-transform-details-result" : {
- "anyOf" : [ {
- "properties" : {
- "structured_output" : {
- "items" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.full-transform"
- },
- "type" : "array"
- }
+ "description" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
},
- "required" : [ "structured_output" ],
- "type" : "object"
- }, {
- "properties" : {
- "output" : {
+ "display" : {
+ "oneOf" : [ {
"type" : "string"
- }
+ }, {
+ "type" : "null"
+ } ]
},
- "required" : [ "output" ],
- "type" : "object"
- } ]
+ "name" : {
+ "minLength" : 1,
+ "type" : "string"
+ },
+ "query" : {
+ "minLength" : 1,
+ "type" : "string"
+ },
+ "visualization_settings" : {
+ "oneOf" : [ {
+ "properties" : { },
+ "type" : "object"
+ }, {
+ "type" : "null"
+ } ]
+ }
+ },
+ "required" : [ "name", "query" ],
+ "type" : "object"
},
- "metabase-enterprise.metabot-v3.tools.api.get-transform-python-library-details-arguments" : {
- "allOf" : [ {
- "properties" : {
- "path" : {
+ "metabase.agent-api.api.create-question-response" : {
+ "properties" : {
+ "collection_id" : {
+ "oneOf" : [ {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "description" : {
+ "oneOf" : [ {
"type" : "string"
- }
+ }, {
+ "type" : "null"
+ } ]
},
- "required" : [ "path" ],
- "type" : "object"
- }, {
- "properties" : { },
- "type" : "object"
- } ]
+ "display" : {
+ "type" : "string"
+ },
+ "id" : {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
+ },
+ "name" : {
+ "minLength" : 1,
+ "type" : "string"
+ }
+ },
+ "required" : [ "id", "name", "display", "collection_id", "description" ],
+ "type" : "object"
},
- "metabase-enterprise.metabot-v3.tools.api.get-transform-python-library-details-result" : {
- "anyOf" : [ {
- "properties" : {
- "structured_output" : {
- "properties" : {
- "created_at" : {
- "description" : "value must be a valid date string",
- "type" : "string"
- },
- "path" : {
- "type" : "string"
- },
- "source" : {
- "type" : "string"
+ "metabase.agent-api.api.entity-type" : {
+ "description" : "The type of queryable entity.",
+ "enum" : [ "table", "metric" ],
+ "type" : "string"
+ },
+ "metabase.agent-api.api.execute-query-request" : {
+ "description" : "Request schema for /v1/execute. Accepts a base64-encoded MBQL query.",
+ "properties" : {
+ "query" : {
+ "minLength" : 1,
+ "type" : "string"
+ }
+ },
+ "required" : [ "query" ],
+ "type" : "object"
+ },
+ "metabase.agent-api.api.execute-query-response" : {
+ "description" : "Response from query execution. The HTTP status is always 202 because results are streamed —\n check the `status` field to determine success or failure.",
+ "properties" : {
+ "data" : {
+ "properties" : {
+ "cols" : {
+ "items" : {
+ "$ref" : "#/components/schemas/metabase.agent-api.api.column-metadata"
},
- "updated_at" : {
- "description" : "value must be a valid date string",
- "type" : "string"
- }
+ "type" : "array"
},
- "required" : [ "source", "path", "created_at", "updated_at" ],
- "type" : "object"
- }
+ "rows" : {
+ "items" : {
+ "items" : { },
+ "type" : "array"
+ },
+ "type" : "array"
+ }
+ },
+ "required" : [ "cols", "rows" ],
+ "type" : "object"
},
- "required" : [ "structured_output" ],
- "type" : "object"
- }, {
- "properties" : {
- "output" : {
- "type" : "string"
- }
+ "error" : {
+ "type" : "string"
},
- "required" : [ "output" ],
- "type" : "object"
- } ]
+ "row_count" : {
+ "type" : "integer"
+ },
+ "running_time" : {
+ "type" : "integer"
+ },
+ "status" : {
+ "enum" : [ "completed", "failed" ],
+ "type" : "string"
+ }
+ },
+ "required" : [ "status" ],
+ "type" : "object"
},
- "metabase-enterprise.metabot-v3.tools.api.get-transforms-result" : {
- "anyOf" : [ {
- "properties" : {
- "structured_output" : {
- "items" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.basic-transform"
- },
- "type" : "array"
- }
+ "metabase.agent-api.api.field" : {
+ "description" : "A field from a table or metric. field_id is the real database field ID (integer) for concrete fields,\n or a string alias for expression/aggregation columns.",
+ "properties" : {
+ "base_type" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
},
- "required" : [ "structured_output" ],
- "type" : "object"
- }, {
- "properties" : {
- "output" : {
+ "coercion_strategy" : {
+ "oneOf" : [ {
"type" : "string"
- }
+ }, {
+ "type" : "null"
+ } ]
},
- "required" : [ "output" ],
- "type" : "object"
- } ]
- },
- "metabase-enterprise.metabot-v3.tools.api.group-by" : {
- "allOf" : [ {
- "properties" : {
- "field_granularity" : {
- "oneOf" : [ {
- "enum" : [ "minute", "hour", "day", "week", "month", "quarter", "year", "day-of-week" ],
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "field_id" : {
+ "database_type" : {
+ "oneOf" : [ {
"type" : "string"
- }
+ }, {
+ "type" : "null"
+ } ]
},
- "required" : [ "field_id" ],
- "type" : "object"
+ "description" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "display_name" : {
+ "type" : "string"
+ },
+ "effective_type" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "field_id" : {
+ "$ref" : "#/components/schemas/metabase.agent-api.api.field-id"
+ },
+ "field_values" : {
+ "oneOf" : [ {
+ "items" : { },
+ "type" : "array"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "name" : {
+ "type" : "string"
+ },
+ "semantic_type" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "type" : {
+ "oneOf" : [ {
+ "$ref" : "#/components/schemas/metabase.agent-api.api.field-type"
+ }, {
+ "type" : "null"
+ } ]
+ }
+ },
+ "required" : [ "field_id", "name", "display_name" ],
+ "type" : "object"
+ },
+ "metabase.agent-api.api.field-id" : {
+ "anyOf" : [ {
+ "$ref" : "#/components/schemas/metabase.lib.schema.id.field"
}, {
- "properties" : { },
- "type" : "object"
- } ]
+ "type" : "string"
+ } ],
+ "description" : "Field id as accepted by agent_api endpoints — either a real app-DB field id (positive integer)\n or a string alias for expression/aggregation columns."
+ },
+ "metabase.agent-api.api.field-type" : {
+ "description" : "A data type for a field derived from Metabase's type hierarchy.",
+ "enum" : [ "boolean", "date", "datetime", "time", "number", "string" ],
+ "type" : "string"
},
- "metabase-enterprise.metabot-v3.tools.api.measure" : {
+ "metabase.agent-api.api.field-values" : {
+ "description" : "Statistics and sample values for a specific field.",
"properties" : {
- "definition" : {
+ "field_id" : {
"oneOf" : [ {
- "properties" : { },
- "type" : "object"
+ "$ref" : "#/components/schemas/metabase.agent-api.api.field-id"
}, {
"type" : "null"
} ]
},
+ "statistics" : {
+ "oneOf" : [ {
+ "$ref" : "#/components/schemas/metabase.agent-api.api.statistics"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "values" : {
+ "oneOf" : [ {
+ "items" : { },
+ "type" : "array"
+ }, {
+ "type" : "null"
+ } ]
+ }
+ },
+ "type" : "object"
+ },
+ "metabase.agent-api.api.measure" : {
+ "description" : "A reusable aggregation expression associated with a table. Reference via measure_id in the aggregations array.",
+ "properties" : {
"description" : {
"oneOf" : [ {
"type" : "string"
@@ -4333,402 +3742,247 @@
"required" : [ "id", "name" ],
"type" : "object"
},
- "metabase-enterprise.metabot-v3.tools.api.measure-aggregation" : {
- "allOf" : [ {
- "properties" : {
- "measure_id" : {
- "type" : "integer"
- },
- "sort_order" : {
- "oneOf" : [ {
- "enum" : [ "asc", "desc" ],
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- }
+ "metabase.agent-api.api.metric" : {
+ "description" : "A metric with its queryable dimensions and segments. The default_time_dimension_field_id is the field_id of the recommended time dimension for temporal breakouts.",
+ "properties" : {
+ "default_time_dimension_field_id" : {
+ "oneOf" : [ {
+ "$ref" : "#/components/schemas/metabase.agent-api.api.field-id"
+ }, {
+ "type" : "null"
+ } ]
},
- "required" : [ "measure_id" ],
- "type" : "object"
- }, {
- "properties" : { },
- "type" : "object"
- } ],
- "description" : "Aggregation using a pre-defined measure."
- },
- "metabase-enterprise.metabot-v3.tools.api.numeric-filter" : {
- "allOf" : [ {
- "properties" : {
- "field_id" : {
- "type" : "string"
- },
- "operation" : {
- "enum" : [ "equals", "not-equals", "greater-than", "greater-than-or-equal", "less-than", "less-than-or-equal" ],
+ "description" : {
+ "oneOf" : [ {
"type" : "string"
- },
- "value" : {
- "anyOf" : [ {
- "type" : "integer"
- }, {
- "type" : "number"
- } ]
- }
+ }, {
+ "type" : "null"
+ } ]
},
- "required" : [ "field_id", "operation", "value" ],
- "type" : "object"
- }, {
- "properties" : { },
- "type" : "object"
- } ]
- },
- "metabase-enterprise.metabot-v3.tools.api.order-by" : {
- "description" : "Order by item specifying a field and sort direction.",
- "properties" : {
- "direction" : {
- "enum" : [ "asc", "desc" ],
+ "id" : {
+ "type" : "integer"
+ },
+ "name" : {
"type" : "string"
},
- "field" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.field"
- }
- },
- "required" : [ "field", "direction" ],
- "type" : "object"
- },
- "metabase-enterprise.metabot-v3.tools.api.proportion" : {
- "type" : "number"
- },
- "metabase-enterprise.metabot-v3.tools.api.query-datasource-arguments" : {
- "allOf" : [ {
- "properties" : {
- "aggregations" : {
- "oneOf" : [ {
- "items" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.aggregation"
- },
- "type" : "array"
- }, {
- "type" : "null"
- } ]
- },
- "fields" : {
- "oneOf" : [ {
- "items" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.field"
- },
- "type" : "array"
- }, {
- "type" : "null"
- } ]
- },
- "filters" : {
- "oneOf" : [ {
- "items" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.filter"
- },
- "type" : "array"
- }, {
- "type" : "null"
- } ]
- },
- "group_by" : {
- "oneOf" : [ {
- "items" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.group-by"
- },
- "type" : "array"
- }, {
- "type" : "null"
- } ]
- },
- "limit" : {
- "oneOf" : [ {
- "type" : "integer"
- }, {
- "type" : "null"
- } ]
- },
- "model_id" : {
- "type" : "integer"
- },
- "order_by" : {
- "oneOf" : [ {
- "items" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.order-by"
- },
- "type" : "array"
- }, {
- "type" : "null"
- } ]
- },
- "table_id" : {
- "type" : "integer"
- }
+ "queryable_dimensions" : {
+ "oneOf" : [ {
+ "items" : {
+ "$ref" : "#/components/schemas/metabase.agent-api.api.field"
+ },
+ "type" : "array"
+ }, {
+ "type" : "null"
+ } ]
},
- "type" : "object"
- }, {
- "properties" : { },
- "type" : "object"
- } ]
+ "segments" : {
+ "oneOf" : [ {
+ "items" : {
+ "$ref" : "#/components/schemas/metabase.agent-api.api.segment"
+ },
+ "type" : "array"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "type" : {
+ "const" : "metric"
+ },
+ "verified" : {
+ "oneOf" : [ {
+ "type" : "boolean"
+ }, {
+ "type" : "null"
+ } ]
+ }
+ },
+ "required" : [ "id", "type", "name" ],
+ "type" : "object"
},
- "metabase-enterprise.metabot-v3.tools.api.query-metric-arguments" : {
- "allOf" : [ {
- "properties" : {
- "filters" : {
- "oneOf" : [ {
- "items" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.filter"
- },
- "type" : "array"
- }, {
- "type" : "null"
- } ]
- },
- "group_by" : {
- "oneOf" : [ {
- "items" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.group-by"
- },
- "type" : "array"
- }, {
- "type" : "null"
- } ]
- },
- "metric_id" : {
- "type" : "integer"
- }
+ "metabase.agent-api.api.metric-summary" : {
+ "description" : "Summary of a metric associated with a table. Includes the field_id of the default time dimension for temporal breakouts.",
+ "properties" : {
+ "default_time_dimension_field_id" : {
+ "oneOf" : [ {
+ "$ref" : "#/components/schemas/metabase.agent-api.api.field-id"
+ }, {
+ "type" : "null"
+ } ]
},
- "required" : [ "metric_id" ],
- "type" : "object"
- }, {
- "properties" : { },
- "type" : "object"
- } ]
+ "description" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "id" : {
+ "type" : "integer"
+ },
+ "name" : {
+ "type" : "string"
+ },
+ "type" : {
+ "const" : "metric"
+ }
+ },
+ "required" : [ "id", "type", "name" ],
+ "type" : "object"
},
- "metabase-enterprise.metabot-v3.tools.api.query-model-arguments" : {
- "allOf" : [ {
+ "metabase.agent-api.api.query-request" : {
+ "description" : "Request body for /v2/query. Accepts either a fresh-query payload (`{:query <external-query>}`,\n same shape as /v2/construct-query) or a `:continuation_token` from a prior response.\n\n Both branches are closed maps: extra top-level keys (e.g. the legacy\n `source_entity` / `referenced_entities` envelope, or sending `:query` and\n `:continuation_token` simultaneously) are rejected with a 400.",
+ "oneOf" : [ {
+ "additionalProperties" : false,
"properties" : {
- "aggregations" : {
- "oneOf" : [ {
- "items" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.aggregation"
- },
- "type" : "array"
- }, {
- "type" : "null"
- } ]
- },
- "fields" : {
- "oneOf" : [ {
- "items" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.field"
- },
- "type" : "array"
- }, {
- "type" : "null"
- } ]
- },
- "filters" : {
- "oneOf" : [ {
- "items" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.filter"
- },
- "type" : "array"
- }, {
- "type" : "null"
- } ]
- },
- "group_by" : {
- "oneOf" : [ {
- "items" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.group-by"
- },
- "type" : "array"
- }, {
- "type" : "null"
- } ]
- },
- "limit" : {
- "oneOf" : [ {
- "type" : "integer"
- }, {
- "type" : "null"
- } ]
- },
- "model_id" : {
- "type" : "integer"
- },
- "order_by" : {
- "oneOf" : [ {
- "items" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.order-by"
- },
- "type" : "array"
- }, {
- "type" : "null"
- } ]
+ "continuation_token" : {
+ "minLength" : 1,
+ "type" : "string"
}
},
- "required" : [ "model_id" ],
+ "required" : [ "continuation_token" ],
"type" : "object"
}, {
- "properties" : { },
- "type" : "object"
+ "$ref" : "#/components/schemas/metabase.agent-api.api.construct-query-request"
} ]
},
- "metabase-enterprise.metabot-v3.tools.api.search-arguments" : {
- "allOf" : [ {
- "properties" : {
- "created_at" : {
- "oneOf" : [ {
- "minLength" : 1,
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "database_id" : {
- "oneOf" : [ {
- "type" : "integer"
- }, {
- "type" : "null"
- } ]
- },
- "entity_types" : {
- "oneOf" : [ {
- "items" : {
- "enum" : [ "table", "model", "question", "dashboard", "metric", "database", "transform" ],
- "type" : "string"
- },
- "type" : "array"
- }, {
- "type" : "null"
- } ]
- },
- "last_edited_at" : {
- "oneOf" : [ {
- "minLength" : 1,
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "limit" : {
- "default" : 50,
- "type" : "integer"
- },
- "search_native_query" : {
- "default" : false,
- "oneOf" : [ {
- "type" : "boolean"
- }, {
- "type" : "null"
- } ]
- },
- "semantic_queries" : {
- "oneOf" : [ {
+ "metabase.agent-api.api.query-response" : {
+ "description" : "Response from query execution. The HTTP status is always 202 because results are streamed —\n check the `status` field to determine success or failure.",
+ "properties" : {
+ "continuation_token" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "data" : {
+ "properties" : {
+ "cols" : {
"items" : {
- "type" : "string"
+ "$ref" : "#/components/schemas/metabase.agent-api.api.column-metadata"
},
"type" : "array"
- }, {
- "type" : "null"
- } ]
- },
- "term_queries" : {
- "oneOf" : [ {
+ },
+ "rows" : {
"items" : {
- "type" : "string"
+ "items" : { },
+ "type" : "array"
},
"type" : "array"
- }, {
- "type" : "null"
- } ]
+ }
},
- "weights" : {
- "additionalProperties" : {
- "type" : "number"
- },
- "type" : "object"
- }
+ "required" : [ "cols", "rows" ],
+ "type" : "object"
},
- "type" : "object"
- }, {
- "properties" : { },
- "type" : "object"
- } ]
- },
- "metabase-enterprise.metabot-v3.tools.api.search-result" : {
- "anyOf" : [ {
- "properties" : {
- "structured_output" : {
- "properties" : {
- "data" : {
- "items" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.search-result-item"
- },
- "type" : "array"
- },
- "total_count" : {
- "type" : "integer"
- }
- },
- "required" : [ "data", "total_count" ],
- "type" : "object"
- }
+ "error" : {
+ "type" : "string"
},
- "required" : [ "structured_output" ],
- "type" : "object"
- }, {
- "properties" : {
- "output" : {
- "type" : "string"
- }
+ "row_count" : {
+ "type" : "integer"
},
- "required" : [ "output" ],
- "type" : "object"
- } ]
+ "running_time" : {
+ "type" : "integer"
+ },
+ "status" : {
+ "enum" : [ "completed", "failed" ],
+ "type" : "string"
+ }
+ },
+ "required" : [ "status" ],
+ "type" : "object"
},
- "metabase-enterprise.metabot-v3.tools.api.search-result-item" : {
- "description" : "Unified schema for search result items.",
+ "metabase.agent-api.api.related-table" : {
+ "description" : "A table related to the queried entity via foreign key. The related_by field indicates the FK field name.",
"properties" : {
- "collection" : {
+ "database_engine" : {
"oneOf" : [ {
- "properties" : {
- "authority_level" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "description" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "name" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- }
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "database_id" : {
+ "oneOf" : [ {
+ "type" : "integer"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "database_schema" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "description" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "display_name" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "fields" : {
+ "oneOf" : [ {
+ "items" : {
+ "$ref" : "#/components/schemas/metabase.agent-api.api.field"
},
- "type" : "object"
+ "type" : "array"
}, {
"type" : "null"
} ]
},
- "created_at" : {
+ "id" : {
+ "type" : "integer"
+ },
+ "name" : {
+ "type" : "string"
+ },
+ "related_by" : {
"oneOf" : [ {
"type" : "string"
}, {
"type" : "null"
} ]
},
+ "type" : {
+ "const" : "table"
+ }
+ },
+ "required" : [ "id", "type", "name" ],
+ "type" : "object"
+ },
+ "metabase.agent-api.api.search-response" : {
+ "description" : "Search results containing tables and metrics matching the query.",
+ "properties" : {
+ "data" : {
+ "items" : {
+ "$ref" : "#/components/schemas/metabase.agent-api.api.search-result-item"
+ },
+ "type" : "array"
+ },
+ "total_count" : {
+ "type" : "integer"
+ }
+ },
+ "required" : [ "data", "total_count" ],
+ "type" : "object"
+ },
+ "metabase.agent-api.api.search-result-item" : {
+ "description" : "A table or metric returned from search.",
+ "properties" : {
+ "created_at" : {
+ "oneOf" : [ { }, {
+ "type" : "null"
+ } ]
+ },
"database_id" : {
"oneOf" : [ {
"type" : "integer"
@@ -4764,13 +4018,11 @@
"type" : "string"
},
"type" : {
- "enum" : [ "table", "model", "dashboard", "question", "metric", "database", "transform" ],
+ "enum" : [ "table", "metric" ],
"type" : "string"
},
"updated_at" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
+ "oneOf" : [ { }, {
"type" : "null"
} ]
},
@@ -4785,16 +4037,9 @@
"required" : [ "id", "type", "name" ],
"type" : "object"
},
- "metabase-enterprise.metabot-v3.tools.api.segment" : {
+ "metabase.agent-api.api.segment" : {
+ "description" : "A predefined filter condition that can be applied to queries via the segment_id in filters.",
"properties" : {
- "definition" : {
- "oneOf" : [ {
- "properties" : { },
- "type" : "object"
- }, {
- "type" : "null"
- } ]
- },
"description" : {
"oneOf" : [ {
"type" : "string"
@@ -4819,22 +4064,8 @@
"required" : [ "id", "name" ],
"type" : "object"
},
- "metabase-enterprise.metabot-v3.tools.api.segment-filter" : {
- "allOf" : [ {
- "properties" : {
- "segment_id" : {
- "type" : "integer"
- }
- },
- "required" : [ "segment_id" ],
- "type" : "object"
- }, {
- "properties" : { },
- "type" : "object"
- } ],
- "description" : "Filter using a pre-defined segment."
- },
- "metabase-enterprise.metabot-v3.tools.api.statistics" : {
+ "metabase.agent-api.api.statistics" : {
+ "description" : "Statistical summary of a field's values computed during database sync. Includes counts, percentages, numeric summaries (min/max/avg/quartiles/sd), and date ranges.",
"properties" : {
"average_length" : {
"oneOf" : [ {
@@ -4852,7 +4083,7 @@
},
"distinct_count" : {
"oneOf" : [ {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.count"
+ "type" : "integer"
}, {
"type" : "null"
} ]
@@ -4887,35 +4118,35 @@
},
"percent_email" : {
"oneOf" : [ {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.proportion"
+ "type" : "number"
}, {
"type" : "null"
} ]
},
"percent_json" : {
"oneOf" : [ {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.proportion"
+ "type" : "number"
}, {
"type" : "null"
} ]
},
"percent_null" : {
"oneOf" : [ {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.proportion"
+ "type" : "number"
}, {
"type" : "null"
} ]
},
"percent_state" : {
"oneOf" : [ {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.proportion"
+ "type" : "number"
}, {
"type" : "null"
} ]
},
"percent_url" : {
"oneOf" : [ {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.proportion"
+ "type" : "number"
}, {
"type" : "null"
} ]
@@ -4940,96 +4171,12 @@
}, {
"type" : "null"
} ]
- },
- "values" : {
- "oneOf" : [ {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.field-values"
- }, {
- "type" : "null"
- } ]
}
},
"type" : "object"
},
- "metabase-enterprise.metabot-v3.tools.api.string-filter" : {
- "allOf" : [ {
- "properties" : {
- "field_id" : {
- "type" : "string"
- },
- "operation" : {
- "enum" : [ "equals", "not-equals", "string-contains", "string-not-contains", "string-starts-with", "string-ends-with" ],
- "type" : "string"
- },
- "value" : {
- "type" : "string"
- }
- },
- "required" : [ "field_id", "operation", "value" ],
- "type" : "object"
- }, {
- "properties" : { },
- "type" : "object"
- } ]
- },
- "metabase-enterprise.metabot-v3.tools.api.subscription-schedule" : {
- "allOf" : [ {
- "anyOf" : [ {
- "properties" : {
- "frequency" : {
- "const" : "hourly"
- }
- },
- "required" : [ "frequency" ],
- "type" : "object"
- }, {
- "properties" : {
- "frequency" : {
- "const" : "daily"
- },
- "hour" : {
- "type" : "integer"
- }
- },
- "required" : [ "frequency", "hour" ],
- "type" : "object"
- }, {
- "properties" : {
- "day_of_week" : {
- "enum" : [ "sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday" ],
- "type" : "string"
- },
- "frequency" : {
- "const" : "weekly"
- },
- "hour" : {
- "type" : "integer"
- }
- },
- "required" : [ "frequency", "hour", "day_of_week" ],
- "type" : "object"
- }, {
- "properties" : {
- "day_of_month" : {
- "enum" : [ "first-calendar-day", "middle-of-month", "last-calendar-day", "first-sunday", "first-monday", "first-tuesday", "first-wednesday", "first-thursday", "first-friday", "first-saturday", "last-sunday", "last-monday", "last-tuesday", "last-wednesday", "last-thursday", "last-friday", "last-saturday" ],
- "type" : "string"
- },
- "frequency" : {
- "const" : "monthly"
- },
- "hour" : {
- "type" : "integer"
- }
- },
- "required" : [ "frequency", "hour", "day_of_month" ],
- "type" : "object"
- } ]
- }, {
- "properties" : { },
- "type" : "object"
- } ]
- },
- "metabase-enterprise.metabot-v3.tools.api.table-result" : {
+ "metabase.agent-api.api.table" : {
+ "description" : "Full details of a table including its fields, related tables, metrics, and segments.",
"properties" : {
"database_engine" : {
"type" : "string"
@@ -5055,2627 +4202,1680 @@
"type" : "string"
},
"fields" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.columns"
- },
- "id" : {
- "type" : "integer"
- },
- "measures" : {
"items" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.measure"
+ "$ref" : "#/components/schemas/metabase.agent-api.api.field"
},
"type" : "array"
},
- "metrics" : {
- "items" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.basic-metric"
- },
- "type" : "array"
- },
- "name" : {
- "type" : "string"
+ "id" : {
+ "type" : "integer"
},
- "related_by" : {
+ "measures" : {
"oneOf" : [ {
- "type" : "string"
+ "items" : {
+ "$ref" : "#/components/schemas/metabase.agent-api.api.measure"
+ },
+ "type" : "array"
}, {
"type" : "null"
} ]
},
- "related_tables" : {
- "items" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.table-result"
- },
- "type" : "array"
+ "metrics" : {
+ "oneOf" : [ {
+ "items" : {
+ "$ref" : "#/components/schemas/metabase.agent-api.api.metric-summary"
+ },
+ "type" : "array"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "name" : {
+ "type" : "string"
+ },
+ "related_tables" : {
+ "oneOf" : [ {
+ "items" : {
+ "$ref" : "#/components/schemas/metabase.agent-api.api.related-table"
+ },
+ "type" : "array"
+ }, {
+ "type" : "null"
+ } ]
},
"segments" : {
- "items" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.segment"
- },
- "type" : "array"
+ "oneOf" : [ {
+ "items" : {
+ "$ref" : "#/components/schemas/metabase.agent-api.api.segment"
+ },
+ "type" : "array"
+ }, {
+ "type" : "null"
+ } ]
},
"type" : {
- "enum" : [ "model", "table" ],
- "type" : "string"
+ "$ref" : "#/components/schemas/metabase.agent-api.api.entity-type"
}
},
"required" : [ "id", "type", "name", "display_name", "database_id", "database_engine", "fields" ],
"type" : "object"
},
- "metabase-enterprise.metabot-v3.tools.api.temporal-extraction-filter" : {
- "allOf" : [ {
- "properties" : {
- "field_id" : {
- "type" : "string"
- },
- "operation" : {
- "enum" : [ "year-equals", "year-not-equals", "quarter-equals", "quarter-not-equals", "month-equals", "month-not-equals", "day-of-week-equals", "day-of-week-not-equals", "hour-equals", "hour-not-equals", "minute-equals", "minute-not-equals", "second-equals", "second-not-equals" ],
- "type" : "string"
- },
- "value" : {
- "type" : "integer"
- }
+ "metabase.analyze.query-results.ResultsMetadata" : {
+ "description" : "value must be an array of valid results column metadata maps.",
+ "oneOf" : [ {
+ "items" : {
+ "$ref" : "#/components/schemas/metabase.query-processor.schema..result-metadata.column"
},
- "required" : [ "field_id", "operation", "value" ],
- "type" : "object"
+ "type" : "array"
}, {
- "properties" : { },
- "type" : "object"
+ "type" : "null"
} ]
},
- "metabase-enterprise.metabot-v3.tools.api.temporal-filter" : {
+ "metabase.api-keys.schema..key.masked" : {
"allOf" : [ {
- "properties" : {
- "bucket" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.bucket"
- },
- "field_id" : {
- "type" : "string"
- },
- "operation" : {
- "enum" : [ "equals", "not-equals", "greater-than", "greater-than-or-equal", "less-than", "less-than-or-equal" ],
- "type" : "string"
- },
- "value" : {
- "anyOf" : [ {
- "type" : "string"
- }, {
- "type" : "integer"
- } ]
- }
- },
- "required" : [ "field_id", "operation", "value" ],
- "type" : "object"
+ "$ref" : "#/components/schemas/metabase.api-keys.schema..key.raw"
}, {
- "properties" : { },
- "type" : "object"
- } ]
+ "pattern" : "^mb_.*{4}\\*+$",
+ "type" : "string"
+ } ],
+ "description" : "Masked string like 'mb_1234**********'."
+ },
+ "metabase.api-keys.schema..key.raw" : {
+ "description" : "Unhashed string of the form 'mb_<base-64-bytes>'.",
+ "maxLength" : 254,
+ "minLength" : 12,
+ "type" : "string"
+ },
+ "metabase.api-keys.schema.id" : {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
+ },
+ "metabase.api-keys.schema.name" : {
+ "maxLength" : 254,
+ "minLength" : 1,
+ "type" : "string"
+ },
+ "metabase.api-keys.schema.prefix" : {
+ "description" : "Prefix string of an API Key, suitable for passing around unmasked. This must be unique.",
+ "maxLength" : 7,
+ "minLength" : 7,
+ "type" : "string"
},
- "metabase-enterprise.metabot-v3.tools.deftool.tool-request" : {
- "description" : "Base schema for all tool requests. Contains the conversation ID and optional profile ID.",
+ "metabase.cache.api..cache-strategy.base.ee" : {
"properties" : {
- "conversation_id" : {
- "description" : "value must be a valid UUID.",
- "pattern" : "[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",
+ "type" : {
+ "enum" : [ "nocache", "ttl", "duration", "schedule" ],
"type" : "string"
- },
- "profile_id" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
}
},
- "required" : [ "conversation_id" ],
+ "required" : [ "type" ],
"type" : "object"
},
- "metabase-enterprise.metabot-v3.tools.transforms.transform-source" : {
- "$ref" : "#/components/schemas/metabase.transforms.schema.transform-source"
- },
- "metabase-enterprise.metabot-v3.tools.transforms.transform-target" : {
- "$ref" : "#/components/schemas/metabase.transforms.schema.transform-target"
- },
- "metabase-enterprise.permission-debug.impl.group-id" : {
- "type" : "integer"
- },
- "metabase-enterprise.permission-debug.impl.perm-debug-info" : {
+ "metabase.cache.api..cache-strategy.base.oss" : {
"properties" : {
- "data" : {
- "properties" : { },
- "type" : "object"
- },
- "decision" : {
- "enum" : [ "allow", "denied", "limited" ],
- "type" : "string"
- },
- "message" : {
- "items" : {
- "type" : "string"
- },
- "type" : "array"
- },
- "model-id" : {
- "type" : "string"
- },
- "model-type" : {
- "enum" : [ "card", "invalid" ],
+ "type" : {
+ "enum" : [ "nocache", "ttl" ],
"type" : "string"
- },
- "segment" : {
- "items" : {
- "enum" : [ "sandboxed", "impersonated", "routed" ],
- "type" : "string"
- },
- "type" : "array",
- "uniqueItems" : true
- },
- "suggestions" : {
- "additionalProperties" : {
- "type" : "string"
- },
- "type" : "object"
}
},
- "required" : [ "model-type", "model-id", "decision", "segment", "message", "data", "suggestions" ],
+ "required" : [ "type" ],
"type" : "object"
},
- "metabase-enterprise.sandbox.schema.attribute-remappings" : {
- "description" : "value must be a valid attribute remappings map (attribute name -> remapped name)",
- "oneOf" : [ {
- "additionalProperties" : {
- "anyOf" : [ {
- "minLength" : 1,
- "type" : "string"
- }, {
- "$ref" : "#/components/schemas/metabase.lib.schema.id.field"
- }, {
- "$ref" : "#/components/schemas/metabase.lib.schema.parameter.target"
- } ]
- },
- "type" : "object"
+ "metabase.cache.api..cache-strategy.ee" : {
+ "allOf" : [ {
+ "$ref" : "#/components/schemas/metabase.cache.api..cache-strategy.base.ee"
}, {
- "type" : "null"
- } ]
+ "oneOf" : [ {
+ "$ref" : "#/components/schemas/metabase.cache.api..cache-strategy.nocache"
+ }, {
+ "$ref" : "#/components/schemas/metabase.cache.api..cache-strategy.ttl"
+ }, {
+ "$ref" : "#/components/schemas/metabase.cache.api..cache-strategy.ee.duration"
+ }, {
+ "$ref" : "#/components/schemas/metabase.cache.api..cache-strategy.ee.schedule"
+ } ]
+ } ],
+ "description" : "Schema for a caching strategy in EE when we have an premium token with `:cache-granular-controls`."
},
- "metabase-enterprise.support-access-grants.schema.create-grant-request" : {
- "description" : "Schema for POST /api/ee/support-access-grants request body.",
+ "metabase.cache.api..cache-strategy.ee.duration" : {
+ "additionalProperties" : false,
"properties" : {
- "grant_duration_minutes" : {
- "maximum" : 10080,
+ "duration" : {
+ "description" : "value must be an integer greater than zero.",
"minimum" : 1,
"type" : "integer"
},
- "notes" : {
+ "refresh_automatically" : {
"oneOf" : [ {
- "maxLength" : 255,
- "minLength" : 1,
- "type" : "string"
+ "type" : "boolean"
}, {
"type" : "null"
} ]
},
- "ticket_number" : {
+ "type" : {
+ "const" : "duration"
+ },
+ "unit" : {
+ "enum" : [ "hours", "minutes", "seconds", "days" ],
+ "type" : "string"
+ }
+ },
+ "required" : [ "type", "duration", "unit" ],
+ "type" : "object"
+ },
+ "metabase.cache.api..cache-strategy.ee.schedule" : {
+ "additionalProperties" : false,
+ "properties" : {
+ "refresh_automatically" : {
"oneOf" : [ {
- "maxLength" : 100,
- "minLength" : 1,
- "type" : "string"
+ "type" : "boolean"
}, {
"type" : "null"
} ]
+ },
+ "schedule" : {
+ "$ref" : "#/components/schemas/metabase.util.cron.CronScheduleString"
+ },
+ "type" : {
+ "const" : "schedule"
}
},
- "required" : [ "grant_duration_minutes" ],
+ "required" : [ "type", "schedule" ],
"type" : "object"
},
- "metabase-enterprise.support-access-grants.schema.current-grant-response" : {
- "description" : "Schema for GET /api/ee/support-access-grants/current response.",
- "oneOf" : [ {
- "$ref" : "#/components/schemas/metabase-enterprise.support-access-grants.schema.grant-response"
+ "metabase.cache.api..cache-strategy.nocache" : {
+ "properties" : {
+ "type" : {
+ "const" : "nocache"
+ }
+ },
+ "required" : [ "type" ],
+ "type" : "object"
+ },
+ "metabase.cache.api..cache-strategy.oss" : {
+ "allOf" : [ {
+ "$ref" : "#/components/schemas/metabase.cache.api..cache-strategy.base.oss"
}, {
- "type" : "null"
- } ]
+ "oneOf" : [ {
+ "$ref" : "#/components/schemas/metabase.cache.api..cache-strategy.nocache"
+ }, {
+ "$ref" : "#/components/schemas/metabase.cache.api..cache-strategy.ttl"
+ } ]
+ } ],
+ "description" : "Schema for a caching strategy (OSS)"
},
- "metabase-enterprise.support-access-grants.schema.grant-response" : {
- "description" : "Schema for a support access grant object in API responses.",
+ "metabase.cache.api..cache-strategy.ttl" : {
+ "additionalProperties" : false,
"properties" : {
- "created_at" : {
- "$ref" : "#/components/schemas/metabase-enterprise.support-access-grants.schema.timestamp"
- },
- "grant_end_timestamp" : {
- "$ref" : "#/components/schemas/metabase-enterprise.support-access-grants.schema.timestamp"
- },
- "grant_start_timestamp" : {
- "$ref" : "#/components/schemas/metabase-enterprise.support-access-grants.schema.timestamp"
+ "min_duration_ms" : {
+ "description" : "value must be an integer greater or equal to than zero.",
+ "minimum" : 0,
+ "type" : "integer"
},
- "id" : {
+ "multiplier" : {
"description" : "value must be an integer greater than zero.",
"minimum" : 1,
"type" : "integer"
},
- "notes" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "revoked_at" : {
- "oneOf" : [ {
- "$ref" : "#/components/schemas/metabase-enterprise.support-access-grants.schema.timestamp"
- }, {
- "type" : "null"
- } ]
- },
- "revoked_by_user_id" : {
- "oneOf" : [ {
- "description" : "value must be an integer greater than zero.",
- "minimum" : 1,
- "type" : "integer"
- }, {
- "type" : "null"
- } ]
- },
- "ticket_number" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "token" : {
+ "type" : {
+ "const" : "ttl"
+ }
+ },
+ "required" : [ "type", "multiplier", "min_duration_ms" ],
+ "type" : "object"
+ },
+ "metabase.cache.api.cache-config-item" : {
+ "properties" : {
+ "collection" : {
"oneOf" : [ {
- "type" : "string"
+ "properties" : {
+ "authority_level" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "id" : {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
+ },
+ "name" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "type" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ }
+ },
+ "required" : [ "id", "name" ],
+ "type" : "object"
}, {
"type" : "null"
} ]
},
- "updated_at" : {
- "$ref" : "#/components/schemas/metabase-enterprise.support-access-grants.schema.timestamp"
- },
- "user_email" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
+ "model" : {
+ "enum" : [ "root", "database", "dashboard", "question" ],
+ "type" : "string"
},
- "user_id" : {
- "description" : "value must be an integer greater than zero.",
- "minimum" : 1,
+ "model_id" : {
+ "description" : "value must be an integer greater or equal to than zero.",
+ "minimum" : 0,
"type" : "integer"
},
- "user_name" : {
+ "name" : {
"oneOf" : [ {
"type" : "string"
}, {
"type" : "null"
} ]
+ },
+ "strategy" : {
+ "properties" : {
+ "type" : {
+ "type" : "string"
+ }
+ },
+ "required" : [ "type" ],
+ "type" : "object"
}
},
- "required" : [ "id", "user_id", "user_name", "user_email", "ticket_number", "notes", "grant_start_timestamp", "grant_end_timestamp", "revoked_at", "revoked_by_user_id", "created_at", "updated_at" ],
+ "required" : [ "model", "model_id", "strategy" ],
"type" : "object"
},
- "metabase-enterprise.support-access-grants.schema.list-grants-response" : {
- "description" : "Schema for GET /api/ee/support-access-grants response (paginated list).",
+ "metabase.cache.api.cache-config-list-response" : {
"properties" : {
"data" : {
"items" : {
- "$ref" : "#/components/schemas/metabase-enterprise.support-access-grants.schema.grant-response"
+ "$ref" : "#/components/schemas/metabase.cache.api.cache-config-item"
},
"type" : "array"
},
"limit" : {
- "description" : "value must be an integer greater than zero.",
- "minimum" : 1,
- "type" : "integer"
+ "oneOf" : [ {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
+ }, {
+ "type" : "null"
+ } ]
},
"offset" : {
- "minimum" : 0,
- "type" : "integer"
+ "oneOf" : [ {
+ "description" : "value must be an integer greater or equal to than zero.",
+ "minimum" : 0,
+ "type" : "integer"
+ }, {
+ "type" : "null"
+ } ]
},
"total" : {
+ "description" : "value must be an integer greater or equal to than zero.",
"minimum" : 0,
"type" : "integer"
}
},
- "required" : [ "data", "total", "limit", "offset" ],
- "type" : "object"
- },
- "metabase-enterprise.support-access-grants.schema.timestamp" : {
- "anyOf" : [ { }, { } ]
- },
- "metabase-enterprise.workspaces.api.appdb-or-ref-id" : {
- "anyOf" : [ {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.appdb-id"
- }, {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.ref-id"
- } ]
- },
- "metabase-enterprise.workspaces.api.dependency-graph" : {
- "additionalProperties" : {
- "items" : {
- "type" : "string"
- },
- "type" : "array"
- },
- "description" : "Map of shorthand symbols to lists of dependencies. The latter are all strings, and refs need to be detected.",
+ "required" : [ "data" ],
"type" : "object"
},
- "metabase-enterprise.workspaces.api.graph-edge" : {
+ "metabase.cache.api.cache-config-store-response" : {
"properties" : {
- "from_entity_id" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.api.appdb-or-ref-id"
- },
- "from_entity_type" : {
- "type" : "string"
- },
- "to_entity_id" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.api.appdb-or-ref-id"
- },
- "to_entity_type" : {
- "type" : "string"
+ "id" : {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
}
},
- "required" : [ "from_entity_id", "from_entity_type", "to_entity_id", "to_entity_type" ],
+ "required" : [ "id" ],
"type" : "object"
},
- "metabase-enterprise.workspaces.api.graph-node" : {
+ "metabase.cache.api.cache-invalidate-response" : {
"properties" : {
- "data" : {
- "properties" : { },
- "type" : "object"
- },
- "dependents_count" : {
- "additionalProperties" : {
- "description" : "value must be an integer greater than zero.",
- "minimum" : 1,
- "type" : "integer"
+ "body" : {
+ "properties" : {
+ "count" : {
+ "type" : "integer"
+ },
+ "message" : {
+ "type" : "string"
+ }
},
+ "required" : [ "count", "message" ],
"type" : "object"
},
- "id" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.api.appdb-or-ref-id"
- },
- "type" : {
- "enum" : [ "input-table", "external-transform", "workspace-transform" ],
- "type" : "string"
+ "status" : {
+ "enum" : [ 200, 404 ],
+ "type" : "integer"
}
},
- "required" : [ "id", "type", "dependents_count", "data" ],
+ "required" : [ "status", "body" ],
"type" : "object"
},
- "metabase-enterprise.workspaces.api.graph-node-type" : {
- "enum" : [ "input-table", "external-transform", "workspace-transform" ],
- "type" : "string"
+ "metabase.cache.api.cache-strategy" : {
+ "oneOf" : [ {
+ "$ref" : "#/components/schemas/metabase.cache.api..cache-strategy.ee"
+ }, {
+ "$ref" : "#/components/schemas/metabase.cache.api..cache-strategy.oss"
+ } ]
},
- "metabase-enterprise.workspaces.api.input-table" : {
+ "metabase.channel.models.channel.Channel" : {
+ "description" : "Channel schema.",
"properties" : {
- "db_id" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.appdb-id"
+ "active" : {
+ "type" : "boolean"
},
- "schema" : {
+ "description" : {
"oneOf" : [ {
"type" : "string"
}, {
"type" : "null"
} ]
},
- "table" : {
+ "details" : {
+ "properties" : { },
+ "type" : "object"
+ },
+ "name" : {
"type" : "string"
},
- "table_id" : {
- "oneOf" : [ {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.appdb-id"
- }, {
- "type" : "null"
- } ]
+ "type" : {
+ "type" : "string"
}
},
- "required" : [ "db_id", "schema", "table", "table_id" ],
+ "required" : [ "name", "type", "details" ],
"type" : "object"
},
- "metabase-enterprise.workspaces.api.output-table" : {
- "properties" : {
- "db_id" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.appdb-id"
+ "metabase.channel.models.channel.ChannelTemplate" : {
+ "description" : "Channel Template schema.",
+ "oneOf" : [ {
+ "properties" : {
+ "channel_type" : { },
+ "details" : {
+ "$ref" : "#/components/schemas/metabase.channel.models.channel.ChannelTemplateEmailDetails"
+ }
},
- "global" : {
- "properties" : {
- "schema" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "table" : {
- "type" : "string"
- },
- "table_id" : {
- "oneOf" : [ {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.appdb-id"
- }, {
- "type" : "null"
- } ]
- },
- "transform_id" : {
- "oneOf" : [ {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.appdb-id"
- }, {
- "type" : "null"
- } ]
- }
+ "required" : [ "channel_type", "details" ],
+ "type" : "object"
+ }, { } ]
+ },
+ "metabase.channel.models.channel.ChannelTemplateEmailDetails" : {
+ "oneOf" : [ {
+ "properties" : {
+ "path" : {
+ "type" : "string"
},
- "required" : [ "transform_id", "schema", "table", "table_id" ],
- "type" : "object"
- },
- "isolated" : {
- "properties" : {
- "schema" : {
- "type" : "string"
- },
- "table" : {
- "type" : "string"
- },
- "table_id" : {
- "oneOf" : [ {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.appdb-id"
- }, {
- "type" : "null"
- } ]
- },
- "transform_id" : {
- "anyOf" : [ {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.ref-id"
- }, {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.appdb-id"
- } ]
- }
- },
- "required" : [ "transform_id", "schema", "table", "table_id" ],
- "type" : "object"
- }
- },
- "required" : [ "db_id", "global", "isolated" ],
- "type" : "object"
- },
- "metabase-enterprise.workspaces.api.status" : {
- "enum" : [ "archived", "ready", "broken", "pending", "uninitialized" ],
- "type" : "string"
- },
- "metabase-enterprise.workspaces.api.test-resources-request" : {
- "description" : "Request body for creating test resources.",
- "properties" : {
- "database_id" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.appdb-id"
- },
- "global" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.api.dependency-graph"
- },
- "workspace" : {
- "properties" : {
- "checkouts" : {
- "items" : {
- "type" : "string"
- },
- "type" : "array"
- },
- "definitions" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.api.dependency-graph"
- },
- "name" : {
- "type" : "string"
- }
- },
- "type" : "object"
- }
- },
- "type" : "object"
- },
- "metabase-enterprise.workspaces.api.test-resources-response" : {
- "description" : "Response from creating test resources.",
- "properties" : {
- "global-map" : {
- "additionalProperties" : {
- "type" : "integer"
+ "recipient-type" : {
+ "enum" : [ "cc", "bcc", "cc", "bcc" ]
},
- "type" : "object"
- },
- "workspace-id" : {
- "oneOf" : [ {
- "type" : "integer"
- }, {
- "type" : "null"
- } ]
- },
- "workspace-map" : {
- "additionalProperties" : {
+ "subject" : {
"type" : "string"
},
- "type" : "object"
- }
- },
- "required" : [ "workspace-id", "global-map", "workspace-map" ],
- "type" : "object"
- },
- "metabase-enterprise.workspaces.api.transform-source" : {
- "oneOf" : [ {
- "properties" : {
- "query" : {
- "$ref" : "#/components/schemas/metabase.queries.schema.query"
- },
"type" : {
- "const" : "query"
+ "enum" : [ "email/handlebars-resource", "email/handlebars-text", "email/handlebars-resource", "email/handlebars-text" ]
}
},
- "required" : [ "type", "query" ],
+ "required" : [ "type", "subject", "path" ],
"type" : "object"
}, {
- "additionalProperties" : false,
"properties" : {
"body" : {
"type" : "string"
},
- "source-database" : {
- "type" : "integer"
+ "recipient-type" : {
+ "enum" : [ "cc", "bcc", "cc", "bcc" ]
},
- "source-tables" : {
- "items" : {
- "properties" : {
- "alias" : {
- "minLength" : 1,
- "type" : "string"
- },
- "table_id" : {
- "type" : "integer"
- }
- },
- "required" : [ "alias", "table_id" ],
- "type" : "object"
- },
- "type" : "array"
+ "subject" : {
+ "type" : "string"
},
"type" : {
- "const" : "python"
+ "enum" : [ "email/handlebars-resource", "email/handlebars-text", "email/handlebars-resource", "email/handlebars-text" ]
}
},
- "required" : [ "source-tables", "type", "body" ],
+ "required" : [ "type", "subject", "body" ],
"type" : "object"
} ]
},
- "metabase-enterprise.workspaces.api.transform-target" : {
- "additionalProperties" : false,
+ "metabase.channel.models.channel.ChannelTemplateEmailDetailsUserProvided" : {
+ "description" : "Email template details schema for API-provided templates. Only handlebars-text is allowed;\n handlebars-resource is restricted to internal use only.",
"properties" : {
- "database" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.appdb-id"
- },
- "name" : {
- "minLength" : 1,
+ "body" : {
"type" : "string"
},
- "schema" : {
- "oneOf" : [ {
- "minLength" : 1,
- "type" : "string"
- }, {
- "type" : "null"
- } ]
+ "recipient-type" : {
+ "enum" : [ "cc", "bcc", "cc", "bcc" ]
},
- "type" : {
- "enum" : [ "table" ],
+ "subject" : {
"type" : "string"
- }
- },
- "required" : [ "type", "name" ],
- "type" : "object"
- },
- "metabase-enterprise.workspaces.types.ancestors-result" : {
- "description" : "Result of running stale ancestor transforms.",
- "properties" : {
- "failed" : {
- "items" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.ref-id"
- },
- "type" : "array"
- },
- "not_run" : {
- "items" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.ref-id"
- },
- "type" : "array"
},
- "succeeded" : {
- "items" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.ref-id"
- },
- "type" : "array"
+ "type" : {
+ "enum" : [ "email/handlebars-text", "email/handlebars-text" ]
}
},
- "required" : [ "succeeded", "failed", "not_run" ],
+ "required" : [ "type", "subject", "body" ],
"type" : "object"
},
- "metabase-enterprise.workspaces.types.appdb-id" : {
- "description" : "value must be an integer greater than zero.",
- "minimum" : 1,
- "type" : "integer"
+ "metabase.channel.models.channel.ChannelTemplateUserProvided" : {
+ "description" : "Channel Template schema for API-provided templates. Does not allow handlebars-resource.",
+ "oneOf" : [ {
+ "properties" : {
+ "channel_type" : { },
+ "details" : {
+ "$ref" : "#/components/schemas/metabase.channel.models.channel.ChannelTemplateEmailDetailsUserProvided"
+ }
+ },
+ "required" : [ "channel_type", "details" ],
+ "type" : "object"
+ }, { } ]
},
- "metabase-enterprise.workspaces.types.execution-result" : {
+ "metabase.collections-rest.api.DashboardQuestionCandidate" : {
"properties" : {
- "ancestors" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.ancestors-result"
- },
- "end_time" : {
- "oneOf" : [ { }, {
- "type" : "null"
- } ]
- },
- "message" : {
+ "description" : {
"oneOf" : [ {
"type" : "string"
}, {
"type" : "null"
} ]
},
- "start_time" : {
- "oneOf" : [ { }, {
- "type" : "null"
- } ]
+ "id" : {
+ "minimum" : 1,
+ "type" : "integer"
},
- "status" : {
- "enum" : [ "succeeded", "failed" ],
+ "name" : {
"type" : "string"
},
- "table" : {
+ "sole_dashboard_info" : {
"properties" : {
- "name" : {
- "type" : "string"
- },
- "schema" : {
+ "description" : {
"oneOf" : [ {
"type" : "string"
}, {
"type" : "null"
} ]
+ },
+ "id" : {
+ "minimum" : 1,
+ "type" : "integer"
+ },
+ "name" : {
+ "type" : "string"
}
},
- "required" : [ "name" ],
+ "required" : [ "id", "name", "description" ],
"type" : "object"
}
},
- "required" : [ "status", "table" ],
+ "required" : [ "id", "name", "description", "sole_dashboard_info" ],
"type" : "object"
},
- "metabase-enterprise.workspaces.types.flag" : {
- "anyOf" : [ {
- "const" : 1
- }, {
- "type" : "boolean"
- } ],
- "description" : "Boolean flag that accepts true, false, or 1 (for query param compatibility)."
- },
- "metabase-enterprise.workspaces.types.problem" : {
- "description" : "A problem detected during workspace validation.",
+ "metabase.collections-rest.api.DashboardQuestionCandidatesResponse" : {
"properties" : {
- "block_merge" : {
- "type" : "boolean"
- },
- "category" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.problem-category"
- },
"data" : {
- "properties" : { },
- "type" : "object"
- },
- "problem" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.problem-name"
+ "items" : {
+ "$ref" : "#/components/schemas/metabase.collections-rest.api.DashboardQuestionCandidate"
+ },
+ "type" : "array"
},
- "severity" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.severity"
+ "total" : {
+ "type" : "integer"
}
},
- "required" : [ "category", "problem", "severity", "block_merge", "data" ],
+ "required" : [ "data", "total" ],
"type" : "object"
},
- "metabase-enterprise.workspaces.types.problem-category" : {
- "enum" : [ "external", "external-downstream", "unused", "internal", "internal-downstream" ],
- "type" : "string"
+ "metabase.collections-rest.api.MoveDashboardQuestionCandidatesResponse" : {
+ "properties" : {
+ "moved" : {
+ "items" : {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
+ },
+ "type" : "array"
+ }
+ },
+ "required" : [ "moved" ],
+ "type" : "object"
},
- "metabase-enterprise.workspaces.types.problem-name" : {
- "enum" : [ "target-conflict", "not-run", "stale", "cycle", "failed", "removed-table", "removed-field" ],
+ "metabase.collections.schema.CardType" : {
+ "enum" : [ "model", "question", "metric" ],
"type" : "string"
},
- "metabase-enterprise.workspaces.types.query-result" : {
- "description" : "Result of a query preview (dry-run or ad-hoc query).\n Data is nested under :data to match /api/dataset response format.",
+ "metabase.collections.schema.Collection" : {
"properties" : {
- "ancestors" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.ancestors-result"
- },
- "data" : {
- "properties" : {
- "cols" : {
- "items" : {
- "properties" : { },
- "type" : "object"
- },
- "type" : "array"
- },
- "results_metadata" : {
- "properties" : {
- "columns" : {
- "items" : {
- "properties" : { },
- "type" : "object"
- },
- "type" : "array"
- }
- },
- "type" : "object"
- },
- "rows" : {
- "items" : { },
- "type" : "array"
- }
- },
- "type" : "object"
+ "archived" : {
+ "type" : "boolean"
},
- "message" : {
+ "authority_level" : {
"oneOf" : [ {
"type" : "string"
}, {
"type" : "null"
} ]
},
- "running_time" : {
+ "below" : {
+ "items" : {
+ "$ref" : "#/components/schemas/metabase.collections.schema.CollectionItemModel"
+ },
+ "type" : "array"
+ },
+ "can_delete" : {
+ "type" : "boolean"
+ },
+ "can_restore" : {
+ "type" : "boolean"
+ },
+ "can_write" : {
+ "type" : "boolean"
+ },
+ "children" : {
+ "items" : {
+ "$ref" : "#/components/schemas/metabase.collections.schema.Collection"
+ },
+ "type" : "array"
+ },
+ "description" : {
"oneOf" : [ {
- "type" : "integer"
+ "type" : "string"
}, {
"type" : "null"
} ]
},
- "started_at" : {
- "oneOf" : [ { }, {
- "type" : "null"
- } ]
+ "effective_ancestors" : {
+ "properties" : { },
+ "type" : "object"
},
- "status" : {
- "enum" : [ "succeeded", "failed" ],
+ "effective_location" : {
"type" : "string"
- }
- },
- "required" : [ "status" ],
- "type" : "object"
- },
- "metabase-enterprise.workspaces.types.ref-id" : {
- "minLength" : 1,
- "type" : "string"
- },
- "metabase-enterprise.workspaces.types.severity" : {
- "enum" : [ "error", "warning", "info" ],
- "type" : "string"
- },
- "metabase.actions.schema..action.for-insert" : {
- "allOf" : [ {
- "properties" : {
- "archived" : {
- "type" : "boolean"
- },
- "description" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "model_id" : {
- "$ref" : "#/components/schemas/metabase.lib.schema.id.card"
- },
- "name" : {
- "type" : "string"
- },
- "parameter_mappings" : {
- "oneOf" : [ {
- "$ref" : "#/components/schemas/metabase.parameters.schema.parameter-mappings"
- }, {
- "type" : "null"
- } ]
- },
- "parameters" : {
- "oneOf" : [ {
- "$ref" : "#/components/schemas/metabase.parameters.schema.parameters"
- }, {
- "type" : "null"
- } ]
- },
- "type" : {
- "$ref" : "#/components/schemas/metabase.actions.schema.type"
- },
- "visualization_settings" : {
- "oneOf" : [ {
- "type" : "object"
- }, {
- "type" : "null"
- } ]
- }
},
- "required" : [ "name", "type", "model_id" ],
- "type" : "object"
- }, {
- "oneOf" : [ {
- "$ref" : "#/components/schemas/metabase.actions.schema.http-action"
- }, {
- "$ref" : "#/components/schemas/metabase.actions.schema.implicit-action"
- }, {
- "$ref" : "#/components/schemas/metabase.actions.schema.query-action"
- }, {
- "properties" : { },
- "type" : "object"
- } ]
- } ],
- "description" : "Schema for inserting a new Action (REST API or internally)."
- },
- "metabase.actions.schema..action.for-update" : {
- "allOf" : [ {
- "properties" : {
- "archived" : {
- "type" : "boolean"
- },
- "description" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "id" : {
- "$ref" : "#/components/schemas/metabase.actions.schema.id"
- },
- "model_id" : {
- "$ref" : "#/components/schemas/metabase.lib.schema.id.card"
- },
- "name" : {
- "type" : "string"
- },
- "parameter_mappings" : {
- "oneOf" : [ {
- "$ref" : "#/components/schemas/metabase.parameters.schema.parameter-mappings"
- }, {
- "type" : "null"
- } ]
- },
- "parameters" : {
- "oneOf" : [ {
- "$ref" : "#/components/schemas/metabase.parameters.schema.parameters"
- }, {
- "type" : "null"
- } ]
- },
- "type" : {
- "$ref" : "#/components/schemas/metabase.actions.schema.type"
+ "entity_id" : {
+ "type" : "string"
+ },
+ "git_sync_enabled" : {
+ "type" : "boolean"
+ },
+ "here" : {
+ "items" : {
+ "$ref" : "#/components/schemas/metabase.collections.schema.CollectionItemModel"
},
- "visualization_settings" : {
- "oneOf" : [ {
- "type" : "object"
- }, {
- "type" : "null"
- } ]
- }
+ "type" : "array",
+ "uniqueItems" : true
},
- "type" : "object"
- }, {
- "oneOf" : [ {
- "$ref" : "#/components/schemas/metabase.actions.schema.http-action"
- }, {
- "$ref" : "#/components/schemas/metabase.actions.schema.implicit-action"
- }, {
- "$ref" : "#/components/schemas/metabase.actions.schema.query-action"
- }, {
- "properties" : { },
- "type" : "object"
- } ]
- } ],
- "description" : "Schema for updating an Action (REST API or internally)."
- },
- "metabase.actions.schema..http-action.json-query" : {
- "description" : "must be a valid json-query, something like '.item.title'",
- "type" : "string"
- },
- "metabase.actions.schema..http-action.template" : {
- "additionalProperties" : false,
- "properties" : {
- "body" : {
- "oneOf" : [ {
+ "id" : {
+ "anyOf" : [ {
"type" : "string"
}, {
- "type" : "null"
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
} ]
},
- "headers" : {
+ "is_personal" : {
+ "type" : "boolean"
+ },
+ "is_remote_synced" : {
+ "type" : "boolean"
+ },
+ "is_sample" : {
+ "type" : "boolean"
+ },
+ "location" : {
"oneOf" : [ {
"type" : "string"
}, {
"type" : "null"
} ]
},
- "method" : {
- "enum" : [ "GET", "POST", "PUT", "DELETE", "PATCH" ],
+ "name" : {
"type" : "string"
},
- "parameters" : {
+ "parent_id" : {
"oneOf" : [ {
- "$ref" : "#/components/schemas/metabase.parameters.schema.parameters"
+ "anyOf" : [ {
+ "type" : "string"
+ }, {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
+ } ]
}, {
"type" : "null"
} ]
},
- "url" : {
+ "personal_owner_id" : {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
+ },
+ "slug" : {
"type" : "string"
+ },
+ "type" : {
+ "$ref" : "#/components/schemas/metabase.collections.schema.CollectionType"
}
},
- "required" : [ "method", "url" ],
+ "required" : [ "id", "name", "description", "can_write", "can_restore", "can_delete", "archived", "location" ],
"type" : "object"
},
- "metabase.actions.schema..implicit-action.kind" : {
- "description" : "Unsupported implicit action kind",
- "enum" : [ "row/create", "row/update", "row/delete", "bulk/create", "bulk/update", "bulk/delete" ],
- "type" : "string"
- },
- "metabase.actions.schema.action" : {
- "allOf" : [ {
- "properties" : {
- "archived" : {
- "type" : "boolean"
- },
- "created_at" : { },
- "creator_id" : {
- "oneOf" : [ {
- "$ref" : "#/components/schemas/metabase.lib.schema.id.user"
+ "metabase.collections.schema.CollectionItem" : {
+ "properties" : {
+ "archived" : {
+ "type" : "boolean"
+ },
+ "authority_level" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "based_on_upload" : {
+ "oneOf" : [ {
+ "anyOf" : [ {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
}, {
- "type" : "null"
- } ]
- },
- "description" : {
- "oneOf" : [ {
"type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "id" : {
- "$ref" : "#/components/schemas/metabase.actions.schema.id"
- },
- "made_public_by_id" : {
- "oneOf" : [ {
- "$ref" : "#/components/schemas/metabase.lib.schema.id.user"
- }, {
- "type" : "null"
- } ]
- },
- "model_id" : {
- "$ref" : "#/components/schemas/metabase.lib.schema.id.card"
- },
- "name" : {
- "type" : "string"
- },
- "parameter_mappings" : {
- "oneOf" : [ {
- "$ref" : "#/components/schemas/metabase.parameters.schema.parameter-mappings"
- }, {
- "type" : "null"
} ]
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "below" : {
+ "items" : {
+ "$ref" : "#/components/schemas/metabase.collections.schema.CollectionItemModel"
},
- "parameters" : {
- "oneOf" : [ {
- "$ref" : "#/components/schemas/metabase.parameters.schema.parameters"
+ "type" : "array"
+ },
+ "can_delete" : {
+ "type" : "boolean"
+ },
+ "can_restore" : {
+ "type" : "boolean"
+ },
+ "can_write" : {
+ "type" : "boolean"
+ },
+ "collection" : {
+ "oneOf" : [ {
+ "$ref" : "#/components/schemas/metabase.collections.schema.Collection"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "collection_id" : {
+ "oneOf" : [ {
+ "anyOf" : [ {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
}, {
- "type" : "null"
- } ]
- },
- "public_uuid" : {
- "oneOf" : [ {
- "description" : "value must be a valid UUID.",
- "pattern" : "[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",
"type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "type" : {
- "$ref" : "#/components/schemas/metabase.actions.schema.type"
- },
- "updated_at" : { },
- "visualization_settings" : {
- "oneOf" : [ {
- "type" : "object"
- }, {
- "type" : "null"
} ]
- }
+ }, {
+ "type" : "null"
+ } ]
},
- "required" : [ "id" ],
- "type" : "object"
- }, {
- "oneOf" : [ {
- "$ref" : "#/components/schemas/metabase.actions.schema.http-action"
- }, {
- "$ref" : "#/components/schemas/metabase.actions.schema.implicit-action"
- }, {
- "$ref" : "#/components/schemas/metabase.actions.schema.query-action"
- }, {
- "properties" : { },
- "type" : "object"
- } ]
- } ],
- "description" : "An Action as it should appear when we `SELECT` it from the app DB."
- },
- "metabase.actions.schema.http-action" : {
- "properties" : {
- "error_handle" : {
+ "collection_position" : {
"oneOf" : [ {
- "$ref" : "#/components/schemas/metabase.actions.schema..http-action.json-query"
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
}, {
"type" : "null"
} ]
},
- "response_handle" : {
+ "collection_preview" : {
"oneOf" : [ {
- "$ref" : "#/components/schemas/metabase.actions.schema..http-action.json-query"
+ "type" : "boolean"
}, {
"type" : "null"
} ]
},
- "template" : {
+ "copy" : {
+ "type" : "boolean"
+ },
+ "dashboard_count" : {
"oneOf" : [ {
- "$ref" : "#/components/schemas/metabase.actions.schema..http-action.template"
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
}, {
"type" : "null"
} ]
- }
- },
- "type" : "object"
- },
- "metabase.actions.schema.id" : {
- "description" : "Valid Action ID",
- "minimum" : 1,
- "type" : "integer"
- },
- "metabase.actions.schema.implicit-action" : {
- "properties" : {
- "kind" : {
+ },
+ "database_id" : {
"oneOf" : [ {
- "$ref" : "#/components/schemas/metabase.actions.schema..implicit-action.kind"
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
}, {
"type" : "null"
} ]
- }
- },
- "type" : "object"
- },
- "metabase.actions.schema.query-action" : {
- "properties" : {
- "database_id" : {
+ },
+ "description" : {
"oneOf" : [ {
- "$ref" : "#/components/schemas/metabase.lib.schema.id.database"
+ "type" : "string"
}, {
"type" : "null"
} ]
},
- "dataset_query" : {
+ "display" : {
+ "type" : "string"
+ },
+ "effective_location" : {
+ "type" : "string"
+ },
+ "entity_id" : {
+ "type" : "string"
+ },
+ "fully_parameterized" : {
"oneOf" : [ {
- "$ref" : "#/components/schemas/metabase.queries.schema.query"
+ "type" : "boolean"
}, {
"type" : "null"
} ]
- }
- },
- "type" : "object"
- },
- "metabase.actions.schema.type" : {
- "description" : "Unsupported action type",
- "enum" : [ "http", "implicit", "query" ],
- "type" : "string"
- },
- "metabase.actions.types..scope.raw" : {
- "anyOf" : [ {
- "properties" : {
- "dashboard-id" : {
- "description" : "value must be an integer greater than zero.",
- "minimum" : 1,
- "type" : "integer"
- }
},
- "required" : [ "dashboard-id" ],
- "type" : "object"
- }, {
- "properties" : {
- "dashcard-id" : {
- "description" : "value must be an integer greater than zero.",
- "minimum" : 1,
- "type" : "integer"
- }
+ "here" : {
+ "items" : {
+ "$ref" : "#/components/schemas/metabase.collections.schema.CollectionItemModel"
+ },
+ "type" : "array",
+ "uniqueItems" : true
},
- "required" : [ "dashcard-id" ],
- "type" : "object"
- }, {
- "properties" : {
- "card-id" : {
- "description" : "value must be an integer greater than zero.",
- "minimum" : 1,
- "type" : "integer"
- }
+ "id" : {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
},
- "required" : [ "card-id" ],
- "type" : "object"
- }, {
- "properties" : {
- "model-id" : {
- "description" : "value must be an integer greater than zero.",
- "minimum" : 1,
- "type" : "integer"
- }
+ "last-edit-info" : {
+ "$ref" : "#/components/schemas/metabase.collections.schema.LastEditInfo"
},
- "required" : [ "model-id" ],
- "type" : "object"
- }, {
- "properties" : {
- "table-id" : {
- "description" : "value must be an integer greater than zero.",
- "minimum" : 1,
- "type" : "integer"
- }
+ "location" : {
+ "type" : "string"
},
- "required" : [ "table-id" ],
- "type" : "object"
- }, {
- "properties" : {
- "webhook-id" : {
+ "model" : {
+ "$ref" : "#/components/schemas/metabase.collections.schema.CollectionItemModel"
+ },
+ "moderated_status" : {
+ "type" : "string"
+ },
+ "name" : {
+ "type" : "string"
+ },
+ "personal_owner_id" : {
+ "oneOf" : [ {
"description" : "value must be an integer greater than zero.",
"minimum" : 1,
"type" : "integer"
- }
- },
- "required" : [ "webhook-id" ],
- "type" : "object"
- }, {
- "properties" : {
- "unknown" : {
- "enum" : [ "model-action" ],
- "type" : "string"
- }
- },
- "required" : [ "unknown" ],
- "type" : "object"
- } ]
- },
- "metabase.analyze.query-results.ResultsMetadata" : {
- "description" : "value must be an array of valid results column metadata maps.",
- "oneOf" : [ {
- "items" : {
- "$ref" : "#/components/schemas/metabase.query-processor.schema..result-metadata.column"
+ }, {
+ "type" : "null"
+ } ]
},
- "type" : "array"
- }, {
- "type" : "null"
- } ]
- },
- "metabase.api-keys.schema..key.masked" : {
- "allOf" : [ {
- "$ref" : "#/components/schemas/metabase.api-keys.schema..key.raw"
- }, {
- "pattern" : "^mb_.*{4}\\*+$",
- "type" : "string"
- } ],
- "description" : "Masked string like 'mb_1234**********'."
- },
- "metabase.api-keys.schema..key.raw" : {
- "description" : "Unhashed string of the form 'mb_<base-64-bytes>'.",
- "maxLength" : 254,
- "minLength" : 12,
- "type" : "string"
- },
- "metabase.api-keys.schema.id" : {
- "description" : "value must be an integer greater than zero.",
- "minimum" : 1,
- "type" : "integer"
- },
- "metabase.api-keys.schema.name" : {
- "maxLength" : 254,
- "minLength" : 1,
- "type" : "string"
- },
- "metabase.api-keys.schema.prefix" : {
- "description" : "Prefix string of an API Key, suitable for passing around unmasked. This must be unique.",
- "maxLength" : 7,
- "minLength" : 7,
- "type" : "string"
- },
- "metabase.cache.api..cache-strategy.base.ee" : {
- "properties" : {
"type" : {
- "enum" : [ "nocache", "ttl", "duration", "schedule" ],
- "type" : "string"
+ "anyOf" : [ {
+ "$ref" : "#/components/schemas/metabase.collections.schema.CollectionType"
+ }, {
+ "$ref" : "#/components/schemas/metabase.collections.schema.CardType"
+ } ]
}
},
- "required" : [ "type" ],
+ "required" : [ "id", "name", "description", "archived" ],
"type" : "object"
},
- "metabase.cache.api..cache-strategy.base.oss" : {
- "properties" : {
- "type" : {
- "enum" : [ "nocache", "ttl" ],
- "type" : "string"
- }
- },
- "required" : [ "type" ],
- "type" : "object"
+ "metabase.collections.schema.CollectionItemModel" : {
+ "enum" : [ "card", "dataset", "metric", "dashboard", "snippet", "collection", "indexed-entity", "indexed-entity", "document", "table" ],
+ "type" : "string"
},
- "metabase.cache.api..cache-strategy.ee" : {
- "allOf" : [ {
- "$ref" : "#/components/schemas/metabase.cache.api..cache-strategy.base.ee"
- }, {
- "oneOf" : [ {
- "$ref" : "#/components/schemas/metabase.cache.api..cache-strategy.nocache"
- }, {
- "$ref" : "#/components/schemas/metabase.cache.api..cache-strategy.ttl"
- }, {
- "$ref" : "#/components/schemas/metabase.cache.api..cache-strategy.ee.duration"
- }, {
- "$ref" : "#/components/schemas/metabase.cache.api..cache-strategy.ee.schedule"
- } ]
- } ],
- "description" : "Schema for a caching strategy in EE when we have an premium token with `:cache-granular-controls`."
+ "metabase.collections.schema.CollectionType" : {
+ "enum" : [ "instance-analytics", "trash", "remote-synced", "library", "library-models", "library-metrics" ],
+ "type" : "string"
},
- "metabase.cache.api..cache-strategy.ee.duration" : {
- "additionalProperties" : false,
+ "metabase.collections.schema.LastEditInfo" : {
"properties" : {
- "duration" : {
- "description" : "value must be an integer greater than zero.",
- "minimum" : 1,
- "type" : "integer"
- },
- "refresh_automatically" : {
+ "email" : {
"oneOf" : [ {
- "type" : "boolean"
+ "type" : "string"
}, {
"type" : "null"
} ]
},
- "type" : {
- "const" : "duration"
+ "first_name" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
},
- "unit" : {
- "enum" : [ "hours", "minutes", "seconds", "days" ],
- "type" : "string"
- }
- },
- "required" : [ "type", "duration", "unit" ],
- "type" : "object"
- },
- "metabase.cache.api..cache-strategy.ee.schedule" : {
- "additionalProperties" : false,
- "properties" : {
- "refresh_automatically" : {
+ "id" : {
"oneOf" : [ {
- "type" : "boolean"
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
}, {
"type" : "null"
} ]
},
- "schedule" : {
- "$ref" : "#/components/schemas/metabase.util.cron.CronScheduleString"
+ "last_name" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
},
- "type" : {
- "const" : "schedule"
- }
- },
- "required" : [ "type", "schedule" ],
- "type" : "object"
- },
- "metabase.cache.api..cache-strategy.nocache" : {
- "properties" : {
- "type" : {
- "const" : "nocache"
+ "timestamp" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
}
},
- "required" : [ "type" ],
+ "required" : [ "id", "email", "first_name", "last_name", "timestamp" ],
"type" : "object"
},
- "metabase.cache.api..cache-strategy.oss" : {
- "allOf" : [ {
- "$ref" : "#/components/schemas/metabase.cache.api..cache-strategy.base.oss"
- }, {
- "oneOf" : [ {
- "$ref" : "#/components/schemas/metabase.cache.api..cache-strategy.nocache"
- }, {
- "$ref" : "#/components/schemas/metabase.cache.api..cache-strategy.ttl"
- } ]
- } ],
- "description" : "Schema for a caching strategy (OSS)"
- },
- "metabase.cache.api..cache-strategy.ttl" : {
- "additionalProperties" : false,
+ "metabase.data-studio.api.table.bulk-table-info" : {
+ "description" : "Schema for table info in bulk operations. Matches frontend BulkTableInfo type.",
"properties" : {
- "min_duration_ms" : {
- "description" : "value must be an integer greater or equal to than zero.",
- "minimum" : 0,
+ "db_id" : {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
"type" : "integer"
},
- "multiplier" : {
+ "display_name" : {
+ "type" : "string"
+ },
+ "id" : {
"description" : "value must be an integer greater than zero.",
"minimum" : 1,
"type" : "integer"
},
- "type" : {
- "const" : "ttl"
+ "is_published" : {
+ "type" : "boolean"
+ },
+ "name" : {
+ "type" : "string"
+ },
+ "schema" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
}
},
- "required" : [ "type", "multiplier", "min_duration_ms" ],
+ "required" : [ "id", "db_id", "name", "display_name", "schema", "is_published" ],
"type" : "object"
},
- "metabase.cache.api.cache-strategy" : {
- "oneOf" : [ {
- "$ref" : "#/components/schemas/metabase.cache.api..cache-strategy.ee"
- }, {
- "$ref" : "#/components/schemas/metabase.cache.api..cache-strategy.oss"
- } ]
- },
- "metabase.channel.models.channel.Channel" : {
- "description" : "Channel schema.",
+ "metabase.data-studio.api.table.bulk-table-selection-info" : {
+ "description" : "Schema for /selection endpoint response. Matches frontend BulkTableSelectionInfo type.",
"properties" : {
- "active" : {
- "type" : "boolean"
+ "published_downstream_tables" : {
+ "items" : {
+ "$ref" : "#/components/schemas/metabase.data-studio.api.table.bulk-table-info"
+ },
+ "type" : "array"
},
- "description" : {
+ "selected_table" : {
"oneOf" : [ {
- "type" : "string"
+ "$ref" : "#/components/schemas/metabase.data-studio.api.table.bulk-table-info"
}, {
"type" : "null"
} ]
},
- "details" : {
- "properties" : { },
- "type" : "object"
- },
- "name" : {
- "type" : "string"
- },
- "type" : {
- "type" : "string"
+ "unpublished_upstream_tables" : {
+ "items" : {
+ "$ref" : "#/components/schemas/metabase.data-studio.api.table.bulk-table-info"
+ },
+ "type" : "array"
}
},
- "required" : [ "name", "type", "details" ],
+ "required" : [ "selected_table", "published_downstream_tables", "unpublished_upstream_tables" ],
"type" : "object"
},
- "metabase.channel.models.channel.ChannelTemplate" : {
- "description" : "Channel Template schema.",
- "oneOf" : [ {
- "properties" : {
- "channel_type" : { },
- "details" : {
- "$ref" : "#/components/schemas/metabase.channel.models.channel.ChannelTemplateEmailDetails"
- }
- },
- "required" : [ "channel_type", "details" ],
- "type" : "object"
- }, { } ]
+ "metabase.data-studio.api.table.data-authorities" : {
+ "enum" : [ "computed", "authoritative", "unconfigured", "ingested" ],
+ "type" : "string"
},
- "metabase.channel.models.channel.ChannelTemplateEmailDetails" : {
- "oneOf" : [ {
- "properties" : {
- "path" : {
- "type" : "string"
- },
- "recipient-type" : {
- "enum" : [ "cc", "bcc", "cc", "bcc" ]
- },
- "subject" : {
- "type" : "string"
- },
- "type" : {
- "enum" : [ "email/handlebars-resource", "email/handlebars-text", "email/handlebars-resource", "email/handlebars-text" ]
- }
- },
- "required" : [ "type", "subject", "path" ],
- "type" : "object"
- }, {
- "properties" : {
- "body" : {
- "type" : "string"
- },
- "recipient-type" : {
- "enum" : [ "cc", "bcc", "cc", "bcc" ]
+ "metabase.data-studio.api.table.data-layers" : {
+ "enum" : [ "final", "internal", "hidden" ],
+ "type" : "string"
+ },
+ "metabase.data-studio.api.table.data-sources" : {
+ "enum" : [ "source-data", "transform", "unknown", "ingested", "metabase-transform", "upload" ],
+ "type" : "string"
+ },
+ "metabase.data-studio.api.table.table-selectors" : {
+ "properties" : {
+ "database_ids" : {
+ "items" : {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
},
- "subject" : {
+ "type" : "array"
+ },
+ "schema_ids" : {
+ "items" : {
"type" : "string"
},
- "type" : {
- "enum" : [ "email/handlebars-resource", "email/handlebars-text", "email/handlebars-resource", "email/handlebars-text" ]
- }
+ "type" : "array"
},
- "required" : [ "type", "subject", "body" ],
- "type" : "object"
- } ]
+ "table_ids" : {
+ "items" : {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
+ },
+ "type" : "array"
+ }
+ },
+ "type" : "object"
},
- "metabase.channel.models.channel.ChannelTemplateEmailDetailsUserProvided" : {
- "description" : "Email template details schema for API-provided templates. Only handlebars-text is allowed;\n handlebars-resource is restricted to internal use only.",
+ "metabase.documents.schema..document.id" : {
+ "description" : "Valid Document ID",
+ "minimum" : 1,
+ "type" : "integer"
+ },
+ "metabase.documents.schema.document" : {
+ "description" : "Schema for an instance of a `:model/Document`.",
"properties" : {
- "body" : {
+ "id" : {
+ "$ref" : "#/components/schemas/metabase.documents.schema..document.id"
+ }
+ },
+ "required" : [ "id" ],
+ "type" : "object"
+ },
+ "metabase.driver.connection.connection-type" : {
+ "enum" : [ "default", "write-data" ],
+ "type" : "string"
+ },
+ "metabase.embedding-rest.api.theme.EmbeddingTheme" : {
+ "properties" : {
+ "created_at" : { },
+ "entity_id" : {
+ "minLength" : 1,
"type" : "string"
},
- "recipient-type" : {
- "enum" : [ "cc", "bcc", "cc", "bcc" ]
+ "id" : {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
},
- "subject" : {
+ "name" : {
+ "minLength" : 1,
"type" : "string"
},
- "type" : {
- "enum" : [ "email/handlebars-text", "email/handlebars-text" ]
- }
+ "settings" : {
+ "properties" : { },
+ "type" : "object"
+ },
+ "updated_at" : { }
},
- "required" : [ "type", "subject", "body" ],
+ "required" : [ "id", "entity_id", "name", "settings", "created_at", "updated_at" ],
"type" : "object"
},
- "metabase.channel.models.channel.ChannelTemplateUserProvided" : {
- "description" : "Channel Template schema for API-provided templates. Does not allow handlebars-resource.",
- "oneOf" : [ {
+ "metabase.frontend-errors.api.frontend-error-type" : {
+ "enum" : [ "component-crash", "chart-render-error" ],
+ "type" : "string"
+ },
+ "metabase.legacy-mbql.schema.-" : {
+ "allOf" : [ ],
+ "description" : "schema for a valid MBQL 4 :- clause"
+ },
+ "metabase.legacy-mbql.schema..NativeQuery.Common" : {
+ "allOf" : [ {
"properties" : {
- "channel_type" : { },
- "details" : {
- "$ref" : "#/components/schemas/metabase.channel.models.channel.ChannelTemplateEmailDetailsUserProvided"
+ "collection" : {
+ "oneOf" : [ {
+ "$ref" : "#/components/schemas/metabase.lib.schema.common.non-blank-string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "template-tags" : {
+ "$ref" : "#/components/schemas/metabase.legacy-mbql.schema.TemplateTagMap"
}
},
- "required" : [ "channel_type", "details" ],
"type" : "object"
- }, { } ]
+ }, {
+ "allOf" : [ ]
+ } ]
},
- "metabase.collections-rest.api.DashboardQuestionCandidate" : {
+ "metabase.legacy-mbql.schema..TemplateTag.Common" : {
+ "description" : "Things required by all template tag types.",
"properties" : {
- "description" : {
+ "display-name" : {
+ "$ref" : "#/components/schemas/metabase.lib.schema.common.non-blank-string"
+ },
+ "id" : {
+ "$ref" : "#/components/schemas/metabase.lib.schema.template-tag.id"
+ },
+ "name" : {
+ "$ref" : "#/components/schemas/metabase.lib.schema.common.non-blank-string"
+ },
+ "type" : {
+ "$ref" : "#/components/schemas/metabase.legacy-mbql.schema.TemplateTagType"
+ }
+ },
+ "required" : [ "type", "name", "display-name" ],
+ "type" : "object"
+ },
+ "metabase.legacy-mbql.schema..TemplateTag.FieldFilter" : {
+ "description" : "Things required by all template tag types.",
+ "properties" : {
+ "alias" : {
+ "type" : "string"
+ },
+ "default" : { },
+ "dimension" : {
+ "$ref" : "#/components/schemas/metabase.legacy-mbql.schema.field"
+ },
+ "display-name" : {
+ "$ref" : "#/components/schemas/metabase.lib.schema.common.non-blank-string"
+ },
+ "id" : {
+ "$ref" : "#/components/schemas/metabase.lib.schema.template-tag.id"
+ },
+ "name" : {
+ "$ref" : "#/components/schemas/metabase.lib.schema.common.non-blank-string"
+ },
+ "options" : {
+ "description" : "optional map to be appended to filter clause",
"oneOf" : [ {
- "type" : "string"
+ "$ref" : "#/components/schemas/metabase.legacy-mbql.schema..TemplateTag.FieldFilter.Options"
}, {
"type" : "null"
} ]
},
- "id" : {
- "minimum" : 1,
- "type" : "integer"
+ "required" : {
+ "type" : "boolean"
},
- "name" : {
- "type" : "string"
+ "type" : {
+ "const" : "dimension"
},
- "sole_dashboard_info" : {
- "properties" : {
- "description" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "id" : {
- "minimum" : 1,
- "type" : "integer"
- },
- "name" : {
- "type" : "string"
- }
- },
- "required" : [ "id", "name", "description" ],
- "type" : "object"
+ "widget-type" : {
+ "$ref" : "#/components/schemas/metabase.legacy-mbql.schema.WidgetType",
+ "default" : "category",
+ "description" : "which type of widget the frontend should show for this Field Filter; this also affects which parameter types\n are allowed to be specified for it."
}
},
- "required" : [ "id", "name", "description", "sole_dashboard_info" ],
+ "required" : [ "type", "name", "display-name", "dimension", "widget-type" ],
"type" : "object"
},
- "metabase.collections-rest.api.DashboardQuestionCandidatesResponse" : {
+ "metabase.legacy-mbql.schema..TemplateTag.FieldFilter.Options" : {
+ "additionalProperties" : { },
+ "type" : "object"
+ },
+ "metabase.legacy-mbql.schema..TemplateTag.RawValue" : {
+ "description" : "Things required by all template tag types.",
"properties" : {
- "data" : {
- "items" : {
- "$ref" : "#/components/schemas/metabase.collections-rest.api.DashboardQuestionCandidate"
- },
- "type" : "array"
+ "default" : { },
+ "display-name" : {
+ "$ref" : "#/components/schemas/metabase.lib.schema.common.non-blank-string"
},
- "total" : {
- "type" : "integer"
+ "id" : {
+ "$ref" : "#/components/schemas/metabase.lib.schema.template-tag.id"
+ },
+ "name" : {
+ "$ref" : "#/components/schemas/metabase.lib.schema.common.non-blank-string"
+ },
+ "required" : {
+ "type" : "boolean"
+ },
+ "type" : {
+ "enum" : [ "date", "number", "boolean", "text" ],
+ "type" : "string"
}
},
- "required" : [ "data", "total" ],
+ "required" : [ "type", "name", "display-name" ],
"type" : "object"
},
- "metabase.collections-rest.api.MoveDashboardQuestionCandidatesResponse" : {
+ "metabase.legacy-mbql.schema..TemplateTag.Snippet" : {
+ "description" : "Things required by all template tag types.",
"properties" : {
- "moved" : {
- "items" : {
- "description" : "value must be an integer greater than zero.",
- "minimum" : 1,
- "type" : "integer"
- },
- "type" : "array"
+ "database" : {
+ "$ref" : "#/components/schemas/metabase.lib.schema.id.database"
+ },
+ "display-name" : {
+ "$ref" : "#/components/schemas/metabase.lib.schema.common.non-blank-string"
+ },
+ "id" : {
+ "$ref" : "#/components/schemas/metabase.lib.schema.template-tag.id"
+ },
+ "name" : {
+ "$ref" : "#/components/schemas/metabase.lib.schema.common.non-blank-string"
+ },
+ "snippet-id" : {
+ "$ref" : "#/components/schemas/metabase.lib.schema.id.snippet"
+ },
+ "snippet-name" : {
+ "$ref" : "#/components/schemas/metabase.lib.schema.common.non-blank-string"
+ },
+ "type" : {
+ "const" : "snippet"
}
},
- "required" : [ "moved" ],
+ "required" : [ "type", "name", "display-name", "snippet-name", "snippet-id" ],
"type" : "object"
},
- "metabase.collections.schema.CardType" : {
- "enum" : [ "model", "question", "metric" ],
- "type" : "string"
+ "metabase.legacy-mbql.schema..TemplateTag.SourceFilter" : {
+ "description" : "Schema for a single source-filter applied to a table template tag.",
+ "properties" : {
+ "field-id" : {
+ "$ref" : "#/components/schemas/metabase.lib.schema.id.field"
+ },
+ "op" : {
+ "enum" : [ "<=", ">", ">=", "!=", "=", "<" ],
+ "type" : "string"
+ },
+ "value" : { }
+ },
+ "required" : [ "field-id", "op", "value" ],
+ "type" : "object"
},
- "metabase.collections.schema.Collection" : {
+ "metabase.legacy-mbql.schema..TemplateTag.SourceQuery" : {
+ "description" : "Things required by all template tag types.",
"properties" : {
- "archived" : {
- "type" : "boolean"
+ "card-id" : {
+ "$ref" : "#/components/schemas/metabase.lib.schema.id.card"
},
- "authority_level" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
+ "display-name" : {
+ "$ref" : "#/components/schemas/metabase.lib.schema.common.non-blank-string"
},
- "below" : {
- "items" : {
- "$ref" : "#/components/schemas/metabase.collections.schema.CollectionItemModel"
- },
- "type" : "array"
+ "id" : {
+ "$ref" : "#/components/schemas/metabase.lib.schema.template-tag.id"
},
- "can_delete" : {
- "type" : "boolean"
+ "name" : {
+ "$ref" : "#/components/schemas/metabase.lib.schema.common.non-blank-string"
},
- "can_restore" : {
- "type" : "boolean"
+ "type" : {
+ "const" : "card"
+ }
+ },
+ "required" : [ "type", "name", "display-name", "card-id" ],
+ "type" : "object"
+ },
+ "metabase.legacy-mbql.schema..TemplateTag.SourceTable" : {
+ "description" : "Things required by all template tag types.",
+ "properties" : {
+ "display-name" : {
+ "$ref" : "#/components/schemas/metabase.lib.schema.common.non-blank-string"
},
- "can_write" : {
+ "emit-alias" : {
"type" : "boolean"
},
- "children" : {
+ "id" : {
+ "$ref" : "#/components/schemas/metabase.lib.schema.template-tag.id"
+ },
+ "name" : {
+ "$ref" : "#/components/schemas/metabase.lib.schema.common.non-blank-string"
+ },
+ "source-filters" : {
"items" : {
- "$ref" : "#/components/schemas/metabase.collections.schema.Collection"
+ "$ref" : "#/components/schemas/metabase.legacy-mbql.schema..TemplateTag.SourceFilter"
},
"type" : "array"
},
- "description" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "effective_ancestors" : {
- "properties" : { },
- "type" : "object"
- },
- "effective_location" : {
- "type" : "string"
+ "table-id" : {
+ "$ref" : "#/components/schemas/metabase.lib.schema.id.table"
},
- "entity_id" : {
+ "type" : {
+ "const" : "table"
+ }
+ },
+ "required" : [ "type", "name", "display-name", "table-id" ],
+ "type" : "object"
+ },
+ "metabase.legacy-mbql.schema..TemplateTag.TemporalUnit" : {
+ "description" : "Things required by all template tag types.",
+ "properties" : {
+ "alias" : {
"type" : "string"
},
- "git_sync_enabled" : {
- "type" : "boolean"
+ "default" : { },
+ "dimension" : {
+ "$ref" : "#/components/schemas/metabase.legacy-mbql.schema.field"
},
- "here" : {
- "items" : {
- "$ref" : "#/components/schemas/metabase.collections.schema.CollectionItemModel"
- },
- "type" : "array",
- "uniqueItems" : true
+ "display-name" : {
+ "$ref" : "#/components/schemas/metabase.lib.schema.common.non-blank-string"
},
"id" : {
- "anyOf" : [ {
- "type" : "string"
- }, {
- "description" : "value must be an integer greater than zero.",
- "minimum" : 1,
- "type" : "integer"
- } ]
+ "$ref" : "#/components/schemas/metabase.lib.schema.template-tag.id"
},
- "is_personal" : {
- "type" : "boolean"
+ "name" : {
+ "$ref" : "#/components/schemas/metabase.lib.schema.common.non-blank-string"
},
- "is_remote_synced" : {
+ "required" : {
"type" : "boolean"
},
- "is_sample" : {
- "type" : "boolean"
+ "type" : {
+ "const" : "temporal-unit"
+ }
+ },
+ "required" : [ "type", "name", "display-name", "dimension" ],
+ "type" : "object"
+ },
+ "metabase.legacy-mbql.schema..TemplateTag.Value.Common" : {
+ "description" : "Things required by all template tag types.",
+ "properties" : {
+ "default" : { },
+ "display-name" : {
+ "$ref" : "#/components/schemas/metabase.lib.schema.common.non-blank-string"
},
- "location" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
+ "id" : {
+ "$ref" : "#/components/schemas/metabase.lib.schema.template-tag.id"
},
"name" : {
- "type" : "string"
+ "$ref" : "#/components/schemas/metabase.lib.schema.common.non-blank-string"
},
- "parent_id" : {
- "oneOf" : [ {
- "anyOf" : [ {
- "type" : "string"
- }, {
- "description" : "value must be an integer greater than zero.",
- "minimum" : 1,
- "type" : "integer"
- } ]
- }, {
- "type" : "null"
- } ]
+ "required" : {
+ "type" : "boolean"
},
- "personal_owner_id" : {
- "description" : "value must be an integer greater than zero.",
- "minimum" : 1,
- "type" : "integer"
+ "type" : {
+ "$ref" : "#/components/schemas/metabase.legacy-mbql.schema.TemplateTagType"
+ }
+ },
+ "required" : [ "type", "name", "display-name" ],
+ "type" : "object"
+ },
+ "metabase.legacy-mbql.schema..legacy-column-metadata.binning-info" : {
+ "properties" : {
+ "bin_width" : {
+ "$ref" : "#/components/schemas/metabase.lib.schema.binning.bin-width"
},
- "slug" : {
- "type" : "string"
+ "binning_strategy" : {
+ "$ref" : "#/components/schemas/metabase.lib.schema.binning.strategy"
},
- "type" : {
- "$ref" : "#/components/schemas/metabase.collections.schema.CollectionType"
+ "num_bins" : {
+ "$ref" : "#/components/schemas/metabase.lib.schema.binning.num-bins"
+ },
+ "strategy" : {
+ "$ref" : "#/components/schemas/metabase.lib.schema.binning.strategy"
}
},
- "required" : [ "id", "name", "description", "can_write", "can_restore", "can_delete", "archived", "location" ],
+ "required" : [ "strategy" ],
"type" : "object"
},
- "metabase.collections.schema.CollectionItem" : {
+ "metabase.legacy-mbql.schema..legacy-column-metadata.qualified-keys" : {
"properties" : {
- "archived" : {
- "type" : "boolean"
+ "lib/binning" : {
+ "oneOf" : [ {
+ "allOf" : [ {
+ "properties" : {
+ "strategy" : {
+ "$ref" : "#/components/schemas/metabase.lib.schema.binning.strategy"
+ }
+ },
+ "required" : [ "strategy" ],
+ "type" : "object"
+ }, {
+ "oneOf" : [ {
+ "properties" : {
+ "strategy" : {
+ "const" : "default"
+ }
+ },
+ "required" : [ "strategy" ],
+ "type" : "object"
+ }, {
+ "properties" : {
+ "bin-width" : {
+ "$ref" : "#/components/schemas/metabase.lib.schema.binning.bin-width"
+ },
+ "strategy" : {
+ "const" : "bin-width"
+ }
+ },
+ "required" : [ "strategy", "bin-width" ],
+ "type" : "object"
+ }, {
+ "properties" : {
+ "num-bins" : {
+ "$ref" : "#/components/schemas/metabase.lib.schema.binning.num-bins"
+ },
+ "strategy" : {
+ "const" : "num-bins"
+ }
+ },
+ "required" : [ "strategy", "num-bins" ],
+ "type" : "object"
+ } ]
+ } ],
+ "description" : "Schema for `:binning` options passed to a `:field` clause."
+ }, {
+ "type" : "null"
+ } ]
},
- "authority_level" : {
+ "lib/breakout?" : {
"oneOf" : [ {
- "type" : "string"
+ "type" : "boolean"
}, {
"type" : "null"
} ]
},
- "based_on_upload" : {
+ "lib/card-id" : {
"oneOf" : [ {
- "anyOf" : [ {
- "description" : "value must be an integer greater than zero.",
- "minimum" : 1,
- "type" : "integer"
- }, {
- "type" : "string"
- } ]
+ "description" : "Valid Card ID",
+ "minimum" : 1,
+ "type" : "integer"
}, {
"type" : "null"
} ]
},
- "below" : {
- "items" : {
- "$ref" : "#/components/schemas/metabase.collections.schema.CollectionItemModel"
- },
- "type" : "array"
- },
- "can_delete" : {
- "type" : "boolean"
- },
- "can_restore" : {
- "type" : "boolean"
- },
- "can_write" : {
- "type" : "boolean"
+ "lib/deduplicated-name" : {
+ "description" : "The simply-deduplicated name that was historically used in QP results metadata (originally calculated by\n the [[metabase.query-processor.middleware.annotate]] middleware, now calculated\n by [[metabase.lib.middleware.result-metadata]]). This just adds suffixes to column names e.g. `ID` and `ID` become\n `ID` and `ID_2`, respectively. Kept around because many old field refs use this column name.",
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
},
- "collection" : {
+ "lib/desired-column-alias" : {
"oneOf" : [ {
- "$ref" : "#/components/schemas/metabase.collections.schema.Collection"
+ "description" : "Name we should use as a column alias for a column in this stage of a query. The desired column alias in stage N\n becomes the source column alias in stage N+1. The right-hand side (RHS) in\n\n SELECT lhs AS rhs",
+ "type" : "string"
}, {
"type" : "null"
} ]
},
- "collection_id" : {
+ "lib/expression-name" : {
"oneOf" : [ {
- "anyOf" : [ {
- "description" : "value must be an integer greater than zero.",
- "minimum" : 1,
- "type" : "integer"
- }, {
- "type" : "string"
- } ]
+ "minLength" : 1,
+ "type" : "string"
}, {
"type" : "null"
} ]
},
- "collection_position" : {
+ "lib/external-remap" : {
"oneOf" : [ {
- "description" : "value must be an integer greater than zero.",
- "minimum" : 1,
- "type" : "integer"
+ "$ref" : "#/components/schemas/metabase.lib.schema.metadata..column.remapping.external"
}, {
"type" : "null"
} ]
},
- "collection_preview" : {
+ "lib/from-model?" : {
"oneOf" : [ {
"type" : "boolean"
}, {
"type" : "null"
} ]
},
- "copy" : {
- "type" : "boolean"
+ "lib/internal-remap" : {
+ "oneOf" : [ {
+ "$ref" : "#/components/schemas/metabase.lib.schema.metadata..column.remapping.internal"
+ }, {
+ "type" : "null"
+ } ]
},
- "dashboard_count" : {
+ "lib/join-alias" : {
"oneOf" : [ {
- "description" : "value must be an integer greater than zero.",
- "minimum" : 1,
- "type" : "integer"
+ "minLength" : 1,
+ "type" : "string"
}, {
"type" : "null"
} ]
},
- "database_id" : {
+ "lib/original-binning" : {
"oneOf" : [ {
- "description" : "value must be an integer greater than zero.",
- "minimum" : 1,
- "type" : "integer"
+ "allOf" : [ {
+ "properties" : {
+ "strategy" : {
+ "$ref" : "#/components/schemas/metabase.lib.schema.binning.strategy"
+ }
+ },
+ "required" : [ "strategy" ],
+ "type" : "object"
+ }, {
+ "oneOf" : [ {
+ "properties" : {
+ "strategy" : {
+ "const" : "default"
+ }
+ },
+ "required" : [ "strategy" ],
+ "type" : "object"
+ }, {
+ "properties" : {
+ "bin-width" : {
+ "$ref" : "#/components/schemas/metabase.lib.schema.binning.bin-width"
+ },
+ "strategy" : {
+ "const" : "bin-width"
+ }
+ },
+ "required" : [ "strategy", "bin-width" ],
+ "type" : "object"
+ }, {
+ "properties" : {
+ "num-bins" : {
+ "$ref" : "#/components/schemas/metabase.lib.schema.binning.num-bins"
+ },
+ "strategy" : {
+ "const" : "num-bins"
+ }
+ },
+ "required" : [ "strategy", "num-bins" ],
+ "type" : "object"
+ } ]
+ } ],
+ "description" : "Schema for `:binning` options passed to a `:field` clause."
}, {
"type" : "null"
} ]
},
- "description" : {
+ "lib/original-display-name" : {
"oneOf" : [ {
"type" : "string"
}, {
"type" : "null"
} ]
},
- "display" : {
- "type" : "string"
- },
- "effective_location" : {
- "type" : "string"
- },
- "entity_id" : {
- "type" : "string"
- },
- "fully_parameterized" : {
+ "lib/original-effective-type" : {
"oneOf" : [ {
- "type" : "boolean"
+ "type" : "string"
}, {
"type" : "null"
} ]
},
- "here" : {
- "items" : {
- "$ref" : "#/components/schemas/metabase.collections.schema.CollectionItemModel"
- },
- "type" : "array",
- "uniqueItems" : true
- },
- "id" : {
- "description" : "value must be an integer greater than zero.",
- "minimum" : 1,
- "type" : "integer"
- },
- "last-edit-info" : {
- "$ref" : "#/components/schemas/metabase.collections.schema.LastEditInfo"
- },
- "location" : {
- "type" : "string"
- },
- "model" : {
- "$ref" : "#/components/schemas/metabase.collections.schema.CollectionItemModel"
- },
- "moderated_status" : {
- "type" : "string"
- },
- "name" : {
- "type" : "string"
- },
- "personal_owner_id" : {
+ "lib/original-expression-name" : {
"oneOf" : [ {
- "description" : "value must be an integer greater than zero.",
- "minimum" : 1,
- "type" : "integer"
+ "minLength" : 1,
+ "type" : "string"
}, {
"type" : "null"
} ]
},
- "type" : {
- "anyOf" : [ {
- "$ref" : "#/components/schemas/metabase.collections.schema.CollectionType"
+ "lib/original-join-alias" : {
+ "oneOf" : [ {
+ "minLength" : 1,
+ "type" : "string"
}, {
- "$ref" : "#/components/schemas/metabase.collections.schema.CardType"
+ "type" : "null"
} ]
- }
- },
- "required" : [ "id", "name", "description", "archived" ],
- "type" : "object"
- },
- "metabase.collections.schema.CollectionItemModel" : {
- "enum" : [ "card", "dataset", "metric", "dashboard", "snippet", "collection", "indexed-entity", "indexed-entity", "document", "table" ],
- "type" : "string"
- },
- "metabase.collections.schema.CollectionType" : {
- "enum" : [ "instance-analytics", "trash", "remote-synced", "library", "library-models", "library-metrics" ],
- "type" : "string"
- },
- "metabase.collections.schema.LastEditInfo" : {
- "properties" : {
- "email" : {
+ },
+ "lib/original-name" : {
+ "description" : "The original name of the column as it appeared in the very first place it came from (i.e., the physical name of the\n column in the table it appears in). This should be the same as the `:lib/source-column-alias` for the very first\n usage of the column.\n Allowed to be blank because some databases like SQL Server allow blank column names.",
"oneOf" : [ {
"type" : "string"
}, {
"type" : "null"
} ]
},
- "first_name" : {
+ "lib/ref-display-name" : {
"oneOf" : [ {
"type" : "string"
}, {
"type" : "null"
} ]
},
- "id" : {
+ "lib/ref-name" : {
"oneOf" : [ {
- "description" : "value must be an integer greater than zero.",
- "minimum" : 1,
- "type" : "integer"
+ "type" : "string"
}, {
"type" : "null"
} ]
},
- "last_name" : {
+ "lib/simple-display-name" : {
"oneOf" : [ {
+ "minLength" : 1,
"type" : "string"
}, {
"type" : "null"
} ]
},
- "timestamp" : {
+ "lib/source" : {
+ "oneOf" : [ {
+ "$ref" : "#/components/schemas/metabase.lib.schema.metadata..column.source"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "lib/source-column-alias" : {
"oneOf" : [ {
+ "description" : "Name for a column as returned/projected by the previous stage of the query or source Table/source Card. The\n left-hand side (LHS) of\n\n SELECT lhs AS rhs",
"type" : "string"
}, {
"type" : "null"
} ]
- }
- },
- "required" : [ "id", "email", "first_name", "last_name", "timestamp" ],
- "type" : "object"
- },
- "metabase.data-studio.api.table.bulk-table-info" : {
- "description" : "Schema for table info in bulk operations. Matches frontend BulkTableInfo type.",
- "properties" : {
- "db_id" : {
- "description" : "value must be an integer greater than zero.",
- "minimum" : 1,
- "type" : "integer"
},
- "display_name" : {
- "type" : "string"
+ "lib/source-uuid" : {
+ "oneOf" : [ {
+ "$ref" : "#/components/schemas/metabase.lib.schema.common.uuid"
+ }, {
+ "type" : "null"
+ } ]
},
- "id" : {
- "description" : "value must be an integer greater than zero.",
- "minimum" : 1,
- "type" : "integer"
+ "lib/temporal-unit" : {
+ "oneOf" : [ {
+ "enum" : [ "day", "day-of-month", "day-of-week", "day-of-year", "default", "hour", "hour-of-day", "millisecond", "minute", "minute-of-hour", "month", "month-of-year", "quarter", "quarter-of-year", "second", "second-of-minute", "week", "week-of-year", "year", "year-of-era" ],
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
},
- "is_published" : {
- "type" : "boolean"
+ "lib/transformation-added-base-type" : {
+ "oneOf" : [ {
+ "type" : "boolean"
+ }, {
+ "type" : "null"
+ } ]
},
- "name" : {
- "type" : "string"
+ "lib/type" : {
+ "const" : "metadata/column",
+ "default" : "metadata/column"
},
- "schema" : {
+ "metabase.lib.metadata.result-metadata/field-ref" : {
"oneOf" : [ {
- "type" : "string"
+ "$ref" : "#/components/schemas/metabase.legacy-mbql.schema.Reference"
}, {
"type" : "null"
} ]
- }
- },
- "required" : [ "id", "db_id", "name", "display_name", "schema", "is_published" ],
- "type" : "object"
- },
- "metabase.data-studio.api.table.bulk-table-selection-info" : {
- "description" : "Schema for /selection endpoint response. Matches frontend BulkTableSelectionInfo type.",
- "properties" : {
- "published_downstream_tables" : {
- "items" : {
- "$ref" : "#/components/schemas/metabase.data-studio.api.table.bulk-table-info"
- },
- "type" : "array"
},
- "selected_table" : {
+ "metabase.lib.metadata.result-metadata/source" : {
"oneOf" : [ {
- "$ref" : "#/components/schemas/metabase.data-studio.api.table.bulk-table-info"
+ "$ref" : "#/components/schemas/metabase.lib.schema.metadata..column.legacy-source"
}, {
"type" : "null"
} ]
},
- "unpublished_upstream_tables" : {
- "items" : {
- "$ref" : "#/components/schemas/metabase.data-studio.api.table.bulk-table-info"
- },
- "type" : "array"
- }
- },
- "required" : [ "selected_table", "published_downstream_tables", "unpublished_upstream_tables" ],
- "type" : "object"
- },
- "metabase.data-studio.api.table.data-authorities" : {
- "enum" : [ "computed", "authoritative", "unconfigured", "ingested" ],
- "type" : "string"
- },
- "metabase.data-studio.api.table.data-layers" : {
- "enum" : [ "final", "internal", "hidden" ],
- "type" : "string"
- },
- "metabase.data-studio.api.table.data-sources" : {
- "enum" : [ "source-data", "transform", "unknown", "ingested", "metabase-transform", "upload" ],
- "type" : "string"
- },
- "metabase.data-studio.api.table.table-selectors" : {
- "properties" : {
- "database_ids" : {
- "items" : {
- "description" : "value must be an integer greater than zero.",
- "minimum" : 1,
- "type" : "integer"
- },
- "type" : "array"
+ "qp/implicit-field?" : {
+ "oneOf" : [ {
+ "type" : "boolean"
+ }, {
+ "type" : "null"
+ } ]
},
- "schema_ids" : {
- "items" : {
- "type" : "string"
- },
- "type" : "array"
+ "qp/native-sandbox-column.force-coercion-strategy" : {
+ "type" : "string"
},
- "table_ids" : {
- "items" : {
- "description" : "value must be an integer greater than zero.",
- "minimum" : 1,
- "type" : "integer"
- },
- "type" : "array"
- }
- },
- "type" : "object"
- },
- "metabase.documents.schema..document.id" : {
- "description" : "Valid Document ID",
- "minimum" : 1,
- "type" : "integer"
- },
- "metabase.documents.schema.document" : {
- "description" : "Schema for an instance of a `:model/Document`.",
- "properties" : {
- "id" : {
- "$ref" : "#/components/schemas/metabase.documents.schema..document.id"
+ "qp/native-sandbox-column.propagate-coercion?" : {
+ "type" : "boolean"
}
},
- "required" : [ "id" ],
"type" : "object"
},
- "metabase.driver.connection.connection-type" : {
- "enum" : [ "default", "write-data" ],
- "type" : "string"
- },
- "metabase.legacy-mbql.schema.-" : {
- "allOf" : [ ],
- "description" : "schema for a valid MBQL 4 :- clause"
+ "metabase.legacy-mbql.schema.Addable" : {
+ "anyOf" : [ {
+ "$ref" : "#/components/schemas/metabase.legacy-mbql.schema.NumericExpressionArg"
+ }, {
+ "$ref" : "#/components/schemas/metabase.legacy-mbql.schema.DateTimeExpressionArg"
+ }, {
+ "oneOf" : [ {
+ "$ref" : "#/components/schemas/metabase.legacy-mbql.schema.interval"
+ }, {
+ "$ref" : "#/components/schemas/metabase.legacy-mbql.schema.segment"
+ } ]
+ } ]
},
- "metabase.legacy-mbql.schema..NativeQuery.Common" : {
+ "metabase.legacy-mbql.schema.Aggregation" : {
"allOf" : [ {
- "properties" : {
- "collection" : {
- "oneOf" : [ {
- "$ref" : "#/components/schemas/metabase.lib.schema.common.non-blank-string"
- }, {
- "type" : "null"
- } ]
- },
- "template-tags" : {
- "$ref" : "#/components/schemas/metabase.legacy-mbql.schema.TemplateTagMap"
- }
- },
- "type" : "object"
+ "oneOf" : [ {
+ "$ref" : "#/components/schemas/metabase.legacy-mbql.schema.aggregation-options"
+ }, {
+ "$ref" : "#/components/schemas/metabase.legacy-mbql.schema.UnnamedAggregation"
+ } ]
}, {
- "allOf" : [ ]
- } ]
+ "description" : "Normalization should automatically unwrap :aggregation-options with an empty options map"
+ } ],
+ "description" : "Schema for anything that is a valid `:aggregation` clause."
},
- "metabase.legacy-mbql.schema..TemplateTag.Common" : {
- "description" : "Things required by all template tag types.",
+ "metabase.legacy-mbql.schema.AggregationOptionsOptions" : {
+ "description" : "Additional options for any aggregation clause when wrapping it in `:aggregation-options`.",
"properties" : {
"display-name" : {
"$ref" : "#/components/schemas/metabase.lib.schema.common.non-blank-string"
},
- "id" : {
- "$ref" : "#/components/schemas/metabase.lib.schema.template-tag.id"
- },
"name" : {
"$ref" : "#/components/schemas/metabase.lib.schema.common.non-blank-string"
- },
- "type" : {
- "$ref" : "#/components/schemas/metabase.legacy-mbql.schema.TemplateTagType"
}
},
- "required" : [ "type", "name", "display-name" ],
"type" : "object"
},
- "metabase.legacy-mbql.schema..TemplateTag.FieldFilter" : {
- "description" : "Things required by all template tag types.",
+ "metabase.legacy-mbql.schema.AggregationRefOptions" : {
"properties" : {
- "alias" : {
- "type" : "string"
- },
- "default" : { },
- "dimension" : {
- "$ref" : "#/components/schemas/metabase.legacy-mbql.schema.field"
- },
- "display-name" : {
- "$ref" : "#/components/schemas/metabase.lib.schema.common.non-blank-string"
- },
- "id" : {
- "$ref" : "#/components/schemas/metabase.lib.schema.template-tag.id"
- },
- "name" : {
- "$ref" : "#/components/schemas/metabase.lib.schema.common.non-blank-string"
- },
- "options" : {
- "description" : "optional map to be appended to filter clause",
+ "base-type" : {
"oneOf" : [ {
- "$ref" : "#/components/schemas/metabase.legacy-mbql.schema..TemplateTag.FieldFilter.Options"
+ "$ref" : "#/components/schemas/metabase.lib.schema.common.base-type"
}, {
"type" : "null"
} ]
},
- "required" : {
- "type" : "boolean"
- },
- "type" : {
- "const" : "dimension"
- },
- "widget-type" : {
- "$ref" : "#/components/schemas/metabase.legacy-mbql.schema.WidgetType",
- "default" : "category",
- "description" : "which type of widget the frontend should show for this Field Filter; this also affects which parameter types\n are allowed to be specified for it."
- }
- },
- "required" : [ "type", "name", "display-name", "dimension", "widget-type" ],
- "type" : "object"
- },
- "metabase.legacy-mbql.schema..TemplateTag.FieldFilter.Options" : {
- "additionalProperties" : { },
- "type" : "object"
- },
- "metabase.legacy-mbql.schema..TemplateTag.RawValue" : {
- "description" : "Things required by all template tag types.",
- "properties" : {
- "default" : { },
"display-name" : {
"$ref" : "#/components/schemas/metabase.lib.schema.common.non-blank-string"
},
- "id" : {
- "$ref" : "#/components/schemas/metabase.lib.schema.template-tag.id"
+ "effective-type" : {
+ "oneOf" : [ {
+ "$ref" : "#/components/schemas/metabase.lib.schema.common.base-type"
+ }, {
+ "type" : "null"
+ } ]
},
"name" : {
"$ref" : "#/components/schemas/metabase.lib.schema.common.non-blank-string"
- },
- "required" : {
- "type" : "boolean"
- },
- "type" : {
- "enum" : [ "date", "number", "boolean", "text" ],
- "type" : "string"
}
},
- "required" : [ "type", "name", "display-name" ],
"type" : "object"
},
- "metabase.legacy-mbql.schema..TemplateTag.Snippet" : {
- "description" : "Things required by all template tag types.",
- "properties" : {
- "database" : {
- "$ref" : "#/components/schemas/metabase.lib.schema.id.database"
- },
- "display-name" : {
- "$ref" : "#/components/schemas/metabase.lib.schema.common.non-blank-string"
- },
- "id" : {
- "$ref" : "#/components/schemas/metabase.lib.schema.template-tag.id"
- },
- "name" : {
- "$ref" : "#/components/schemas/metabase.lib.schema.common.non-blank-string"
- },
- "snippet-id" : {
- "$ref" : "#/components/schemas/metabase.lib.schema.id.snippet"
- },
- "snippet-name" : {
- "$ref" : "#/components/schemas/metabase.lib.schema.common.non-blank-string"
- },
- "type" : {
- "const" : "snippet"
- }
+ "metabase.legacy-mbql.schema.Aggregations" : {
+ "items" : {
+ "$ref" : "#/components/schemas/metabase.legacy-mbql.schema.Aggregation"
},
- "required" : [ "type", "name", "display-name", "snippet-name", "snippet-id" ],
- "type" : "object"
+ "minItems" : 1,
+ "type" : "array"
},
- "metabase.legacy-mbql.schema..TemplateTag.SourceQuery" : {
- "description" : "Things required by all template tag types.",
- "properties" : {
- "card-id" : {
- "$ref" : "#/components/schemas/metabase.lib.schema.id.card"
- },
- "display-name" : {
- "$ref" : "#/components/schemas/metabase.lib.schema.common.non-blank-string"
- },
- "id" : {
- "$ref" : "#/components/schemas/metabase.lib.schema.template-tag.id"
- },
- "name" : {
- "$ref" : "#/components/schemas/metabase.lib.schema.common.non-blank-string"
- },
- "type" : {
- "const" : "card"
- }
- },
- "required" : [ "type", "name", "display-name", "card-id" ],
- "type" : "object"
- },
- "metabase.legacy-mbql.schema..TemplateTag.SourceTable" : {
- "description" : "Things required by all template tag types.",
- "properties" : {
- "display-name" : {
- "$ref" : "#/components/schemas/metabase.lib.schema.common.non-blank-string"
- },
- "id" : {
- "$ref" : "#/components/schemas/metabase.lib.schema.template-tag.id"
- },
- "name" : {
- "$ref" : "#/components/schemas/metabase.lib.schema.common.non-blank-string"
- },
- "table-id" : {
- "$ref" : "#/components/schemas/metabase.lib.schema.id.table"
- },
- "type" : {
- "const" : "table"
- }
- },
- "required" : [ "type", "name", "display-name", "table-id" ],
- "type" : "object"
- },
- "metabase.legacy-mbql.schema..TemplateTag.TemporalUnit" : {
- "description" : "Things required by all template tag types.",
- "properties" : {
- "alias" : {
- "type" : "string"
- },
- "default" : { },
- "dimension" : {
- "$ref" : "#/components/schemas/metabase.legacy-mbql.schema.field"
- },
- "display-name" : {
- "$ref" : "#/components/schemas/metabase.lib.schema.common.non-blank-string"
- },
- "id" : {
- "$ref" : "#/components/schemas/metabase.lib.schema.template-tag.id"
- },
- "name" : {
- "$ref" : "#/components/schemas/metabase.lib.schema.common.non-blank-string"
- },
- "required" : {
- "type" : "boolean"
- },
- "type" : {
- "const" : "temporal-unit"
- }
- },
- "required" : [ "type", "name", "display-name", "dimension" ],
- "type" : "object"
- },
- "metabase.legacy-mbql.schema..TemplateTag.Value.Common" : {
- "description" : "Things required by all template tag types.",
- "properties" : {
- "default" : { },
- "display-name" : {
- "$ref" : "#/components/schemas/metabase.lib.schema.common.non-blank-string"
- },
- "id" : {
- "$ref" : "#/components/schemas/metabase.lib.schema.template-tag.id"
- },
- "name" : {
- "$ref" : "#/components/schemas/metabase.lib.schema.common.non-blank-string"
- },
- "required" : {
- "type" : "boolean"
- },
- "type" : {
- "$ref" : "#/components/schemas/metabase.legacy-mbql.schema.TemplateTagType"
- }
- },
- "required" : [ "type", "name", "display-name" ],
- "type" : "object"
- },
- "metabase.legacy-mbql.schema..legacy-column-metadata.binning-info" : {
- "properties" : {
- "bin_width" : {
- "$ref" : "#/components/schemas/metabase.lib.schema.binning.bin-width"
- },
- "binning_strategy" : {
- "$ref" : "#/components/schemas/metabase.lib.schema.binning.strategy"
- },
- "num_bins" : {
- "$ref" : "#/components/schemas/metabase.lib.schema.binning.num-bins"
- },
- "strategy" : {
- "$ref" : "#/components/schemas/metabase.lib.schema.binning.strategy"
- }
- },
- "required" : [ "strategy" ],
- "type" : "object"
- },
- "metabase.legacy-mbql.schema..legacy-column-metadata.qualified-keys" : {
- "properties" : {
- "lib/binning" : {
- "oneOf" : [ {
- "allOf" : [ {
- "properties" : {
- "strategy" : {
- "$ref" : "#/components/schemas/metabase.lib.schema.binning.strategy"
- }
- },
- "required" : [ "strategy" ],
- "type" : "object"
- }, {
- "oneOf" : [ {
- "properties" : {
- "strategy" : {
- "const" : "default"
- }
- },
- "required" : [ "strategy" ],
- "type" : "object"
- }, {
- "properties" : {
- "bin-width" : {
- "$ref" : "#/components/schemas/metabase.lib.schema.binning.bin-width"
- },
- "strategy" : {
- "const" : "bin-width"
- }
- },
- "required" : [ "strategy", "bin-width" ],
- "type" : "object"
- }, {
- "properties" : {
- "num-bins" : {
- "$ref" : "#/components/schemas/metabase.lib.schema.binning.num-bins"
- },
- "strategy" : {
- "const" : "num-bins"
- }
- },
- "required" : [ "strategy", "num-bins" ],
- "type" : "object"
- } ]
- } ],
- "description" : "Schema for `:binning` options passed to a `:field` clause."
- }, {
- "type" : "null"
- } ]
- },
- "lib/breakout?" : {
- "oneOf" : [ {
- "type" : "boolean"
- }, {
- "type" : "null"
- } ]
- },
- "lib/card-id" : {
- "oneOf" : [ {
- "description" : "Valid Card ID",
- "minimum" : 1,
- "type" : "integer"
- }, {
- "type" : "null"
- } ]
- },
- "lib/deduplicated-name" : {
- "description" : "The simply-deduplicated name that was historically used in QP results metadata (originally calculated by\n the [[metabase.query-processor.middleware.annotate]] middleware, now calculated\n by [[metabase.lib.middleware.result-metadata]]). This just adds suffixes to column names e.g. `ID` and `ID` become\n `ID` and `ID_2`, respectively. Kept around because many old field refs use this column name.",
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "lib/desired-column-alias" : {
- "oneOf" : [ {
- "description" : "Name we should use as a column alias for a column in this stage of a query. The desired column alias in stage N\n becomes the source column alias in stage N+1. The right-hand side (RHS) in\n\n SELECT lhs AS rhs",
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "lib/expression-name" : {
- "oneOf" : [ {
- "minLength" : 1,
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "lib/external-remap" : {
- "oneOf" : [ {
- "$ref" : "#/components/schemas/metabase.lib.schema.metadata..column.remapping.external"
- }, {
- "type" : "null"
- } ]
- },
- "lib/from-model?" : {
- "oneOf" : [ {
- "type" : "boolean"
- }, {
- "type" : "null"
- } ]
- },
- "lib/internal-remap" : {
- "oneOf" : [ {
- "$ref" : "#/components/schemas/metabase.lib.schema.metadata..column.remapping.internal"
- }, {
- "type" : "null"
- } ]
- },
- "lib/join-alias" : {
- "oneOf" : [ {
- "minLength" : 1,
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "lib/original-binning" : {
- "oneOf" : [ {
- "allOf" : [ {
- "properties" : {
- "strategy" : {
- "$ref" : "#/components/schemas/metabase.lib.schema.binning.strategy"
- }
- },
- "required" : [ "strategy" ],
- "type" : "object"
- }, {
- "oneOf" : [ {
- "properties" : {
- "strategy" : {
- "const" : "default"
- }
- },
- "required" : [ "strategy" ],
- "type" : "object"
- }, {
- "properties" : {
- "bin-width" : {
- "$ref" : "#/components/schemas/metabase.lib.schema.binning.bin-width"
- },
- "strategy" : {
- "const" : "bin-width"
- }
- },
- "required" : [ "strategy", "bin-width" ],
- "type" : "object"
- }, {
- "properties" : {
- "num-bins" : {
- "$ref" : "#/components/schemas/metabase.lib.schema.binning.num-bins"
- },
- "strategy" : {
- "const" : "num-bins"
- }
- },
- "required" : [ "strategy", "num-bins" ],
- "type" : "object"
- } ]
- } ],
- "description" : "Schema for `:binning` options passed to a `:field` clause."
- }, {
- "type" : "null"
- } ]
- },
- "lib/original-display-name" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "lib/original-effective-type" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "lib/original-expression-name" : {
- "oneOf" : [ {
- "minLength" : 1,
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "lib/original-join-alias" : {
- "oneOf" : [ {
- "minLength" : 1,
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "lib/original-name" : {
- "description" : "The original name of the column as it appeared in the very first place it came from (i.e., the physical name of the\n column in the table it appears in). This should be the same as the `:lib/source-column-alias` for the very first\n usage of the column.\n Allowed to be blank because some databases like SQL Server allow blank column names.",
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "lib/ref-display-name" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "lib/ref-name" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "lib/simple-display-name" : {
- "oneOf" : [ {
- "minLength" : 1,
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "lib/source" : {
- "oneOf" : [ {
- "$ref" : "#/components/schemas/metabase.lib.schema.metadata..column.source"
- }, {
- "type" : "null"
- } ]
- },
- "lib/source-column-alias" : {
- "oneOf" : [ {
- "description" : "Name for a column as returned/projected by the previous stage of the query or source Table/source Card. The\n left-hand side (LHS) of\n\n SELECT lhs AS rhs",
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "lib/source-uuid" : {
- "oneOf" : [ {
- "$ref" : "#/components/schemas/metabase.lib.schema.common.uuid"
- }, {
- "type" : "null"
- } ]
- },
- "lib/temporal-unit" : {
- "oneOf" : [ {
- "enum" : [ "day", "day-of-month", "day-of-week", "day-of-year", "default", "hour", "hour-of-day", "millisecond", "minute", "minute-of-hour", "month", "month-of-year", "quarter", "quarter-of-year", "second", "second-of-minute", "week", "week-of-year", "year", "year-of-era" ],
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "lib/transformation-added-base-type" : {
- "oneOf" : [ {
- "type" : "boolean"
- }, {
- "type" : "null"
- } ]
- },
- "lib/type" : {
- "const" : "metadata/column",
- "default" : "metadata/column"
- },
- "metabase.lib.metadata.result-metadata/field-ref" : {
- "oneOf" : [ {
- "$ref" : "#/components/schemas/metabase.legacy-mbql.schema.Reference"
- }, {
- "type" : "null"
- } ]
- },
- "metabase.lib.metadata.result-metadata/source" : {
- "oneOf" : [ {
- "$ref" : "#/components/schemas/metabase.lib.schema.metadata..column.legacy-source"
- }, {
- "type" : "null"
- } ]
- },
- "qp.pivot/pivot-grouping?" : {
- "oneOf" : [ {
- "type" : "boolean"
- }, {
- "type" : "null"
- } ]
- },
- "qp/implicit-field?" : {
- "oneOf" : [ {
- "type" : "boolean"
- }, {
- "type" : "null"
- } ]
- }
- },
- "type" : "object"
- },
- "metabase.legacy-mbql.schema.Addable" : {
- "anyOf" : [ {
- "$ref" : "#/components/schemas/metabase.legacy-mbql.schema.NumericExpressionArg"
- }, {
- "$ref" : "#/components/schemas/metabase.legacy-mbql.schema.DateTimeExpressionArg"
- }, {
- "oneOf" : [ {
- "$ref" : "#/components/schemas/metabase.legacy-mbql.schema.interval"
- }, {
- "$ref" : "#/components/schemas/metabase.legacy-mbql.schema.segment"
- } ]
- } ]
- },
- "metabase.legacy-mbql.schema.Aggregation" : {
- "allOf" : [ {
- "oneOf" : [ {
- "$ref" : "#/components/schemas/metabase.legacy-mbql.schema.aggregation-options"
- }, {
- "$ref" : "#/components/schemas/metabase.legacy-mbql.schema.UnnamedAggregation"
- } ]
- }, {
- "description" : "Normalization should automatically unwrap :aggregation-options with an empty options map"
- } ],
- "description" : "Schema for anything that is a valid `:aggregation` clause."
- },
- "metabase.legacy-mbql.schema.AggregationOptionsOptions" : {
- "description" : "Additional options for any aggregation clause when wrapping it in `:aggregation-options`.",
- "properties" : {
- "display-name" : {
- "$ref" : "#/components/schemas/metabase.lib.schema.common.non-blank-string"
- },
- "name" : {
- "$ref" : "#/components/schemas/metabase.lib.schema.common.non-blank-string"
- }
- },
- "type" : "object"
- },
- "metabase.legacy-mbql.schema.AggregationRefOptions" : {
- "properties" : {
- "base-type" : {
- "oneOf" : [ {
- "$ref" : "#/components/schemas/metabase.lib.schema.common.base-type"
- }, {
- "type" : "null"
- } ]
- },
- "display-name" : {
- "$ref" : "#/components/schemas/metabase.lib.schema.common.non-blank-string"
- },
- "effective-type" : {
- "oneOf" : [ {
- "$ref" : "#/components/schemas/metabase.lib.schema.common.base-type"
- }, {
- "type" : "null"
- } ]
- },
- "name" : {
- "$ref" : "#/components/schemas/metabase.lib.schema.common.non-blank-string"
- }
- },
- "type" : "object"
- },
- "metabase.legacy-mbql.schema.Aggregations" : {
- "items" : {
- "$ref" : "#/components/schemas/metabase.legacy-mbql.schema.Aggregation"
- },
- "minItems" : 1,
- "type" : "array"
- },
- "metabase.legacy-mbql.schema.AnyMBQLClause" : {
- "description" : "Schema for ANY valid MBQL clause"
+ "metabase.legacy-mbql.schema.AnyMBQLClause" : {
+ "description" : "Schema for ANY valid MBQL clause"
},
"metabase.legacy-mbql.schema.ArithmeticDateTimeUnit" : {
"enum" : [ "millisecond", "second", "minute", "hour", "day", "week", "month", "quarter", "year" ],
@@ -7951,6 +6151,7 @@
} ]
},
"lib/uuid" : {
+ "$ref" : "#/components/schemas/metabase.lib.schema.common.uuid",
"maxLength" : 36,
"minLength" : 36,
"type" : "string"
@@ -8092,13 +6293,6 @@
"original-temporal-unit" : {
"$ref" : "#/components/schemas/metabase.lib.schema.temporal-bucketing.unit"
},
- "qp.pivot/pivot-grouping?" : {
- "oneOf" : [ {
- "type" : "boolean"
- }, {
- "type" : "null"
- } ]
- },
"semantic-type" : {
"oneOf" : [ {
"$ref" : "#/components/schemas/metabase.lib.schema.common.semantic-or-relation-type"
@@ -8255,7 +6449,8 @@
"$ref" : "#/components/schemas/metabase.legacy-mbql.schema.Joins"
},
"limit" : {
- "$ref" : "#/components/schemas/metabase.lib.schema.common.int-greater-than-or-equal-to-zero"
+ "minimum" : 0,
+ "type" : "integer"
},
"order-by" : {
"$ref" : "#/components/schemas/metabase.legacy-mbql.schema.OrderBys"
@@ -9346,13 +7541,6 @@
"name" : {
"type" : "string"
},
- "qp.pivot/pivot-grouping?" : {
- "oneOf" : [ {
- "type" : "boolean"
- }, {
- "type" : "null"
- } ]
- },
"qp/implicit-field?" : {
"oneOf" : [ {
"type" : "boolean"
@@ -9360,6 +7548,12 @@
"type" : "null"
} ]
},
+ "qp/native-sandbox-column.force-coercion-strategy" : {
+ "type" : "string"
+ },
+ "qp/native-sandbox-column.propagate-coercion?" : {
+ "type" : "boolean"
+ },
"semantic_type" : {
"oneOf" : [ {
"$ref" : "#/components/schemas/metabase.lib.schema.common.semantic-or-relation-type"
@@ -9550,6 +7744,219 @@
"allOf" : [ ],
"description" : "schema for a valid MBQL 4 :value clause"
},
+ "metabase.lib-metric.schema..dimension-reference.options" : {
+ "description" : "Options map for dimension references.",
+ "properties" : {
+ "binning" : {
+ "oneOf" : [ {
+ "$ref" : "#/components/schemas/metabase.lib-metric.schema.binning"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "display-name" : {
+ "oneOf" : [ {
+ "$ref" : "#/components/schemas/metabase.lib.schema.common.non-blank-string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "effective-type" : {
+ "oneOf" : [ {
+ "$ref" : "#/components/schemas/metabase.lib.schema.common.base-type"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "semantic-type" : {
+ "oneOf" : [ {
+ "$ref" : "#/components/schemas/metabase.lib.schema.common.semantic-or-relation-type"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "temporal-unit" : {
+ "oneOf" : [ {
+ "$ref" : "#/components/schemas/metabase.lib.schema.temporal-bucketing.unit"
+ }, {
+ "type" : "null"
+ } ]
+ }
+ },
+ "type" : "object"
+ },
+ "metabase.lib-metric.schema.binning" : {
+ "allOf" : [ {
+ "properties" : {
+ "strategy" : {
+ "$ref" : "#/components/schemas/metabase.lib-metric.schema.binning-strategy"
+ }
+ },
+ "required" : [ "strategy" ],
+ "type" : "object"
+ }, {
+ "oneOf" : [ {
+ "properties" : {
+ "strategy" : {
+ "const" : "default"
+ }
+ },
+ "required" : [ "strategy" ],
+ "type" : "object"
+ }, {
+ "properties" : {
+ "bin-width" : {
+ "$ref" : "#/components/schemas/metabase.lib.schema.common.positive-number"
+ },
+ "strategy" : {
+ "const" : "bin-width"
+ }
+ },
+ "required" : [ "strategy", "bin-width" ],
+ "type" : "object"
+ }, {
+ "properties" : {
+ "num-bins" : {
+ "minimum" : 1,
+ "type" : "integer"
+ },
+ "strategy" : {
+ "const" : "num-bins"
+ }
+ },
+ "required" : [ "strategy", "num-bins" ],
+ "type" : "object"
+ } ]
+ } ],
+ "description" : "Schema for `:binning` options passed to a `:dimension` clause."
+ },
+ "metabase.lib-metric.schema.binning-strategy" : {
+ "enum" : [ "bin-width", "default", "num-bins" ],
+ "type" : "string"
+ },
+ "metabase.lib-metric.schema.dimension-id" : {
+ "$ref" : "#/components/schemas/metabase.lib.schema.common.uuid",
+ "description" : "UUID string identifying a dimension."
+ },
+ "metabase.lib-metric.schema.dimension-reference" : {
+ "description" : "Dimension reference clause [:dimension opts uuid].\n Handles normalization from JSON where the tag arrives as a string.",
+ "prefixItems" : [ {
+ "const" : "dimension"
+ }, {
+ "$ref" : "#/components/schemas/metabase.lib-metric.schema..dimension-reference.options"
+ }, {
+ "$ref" : "#/components/schemas/metabase.lib-metric.schema.dimension-id"
+ } ],
+ "type" : "array"
+ },
+ "metabase.lib-metric.schema.expression-leaf" : {
+ "anyOf" : [ {
+ "$ref" : "#/components/schemas/metabase.lib-metric.schema.metric-expression-ref"
+ }, {
+ "$ref" : "#/components/schemas/metabase.lib-metric.schema.measure-expression-ref"
+ } ],
+ "description" : "A leaf node in a metric math expression: either a metric or measure reference."
+ },
+ "metabase.lib-metric.schema.filter-clause" : {
+ "description" : "MBQL filter clause with normalization for API input.\n Handles string operators and dimension references."
+ },
+ "metabase.lib-metric.schema.instance-filter" : {
+ "description" : "A filter associated with a specific expression instance via lib/uuid.",
+ "properties" : {
+ "filter" : {
+ "$ref" : "#/components/schemas/metabase.lib-metric.schema.filter-clause"
+ },
+ "lib/uuid" : {
+ "$ref" : "#/components/schemas/metabase.lib.schema.common.non-blank-string"
+ }
+ },
+ "required" : [ "lib/uuid", "filter" ],
+ "type" : "object"
+ },
+ "metabase.lib-metric.schema.instance-filters" : {
+ "description" : "A sequence of per-instance filters.",
+ "items" : {
+ "$ref" : "#/components/schemas/metabase.lib-metric.schema.instance-filter"
+ },
+ "type" : "array"
+ },
+ "metabase.lib-metric.schema.measure-expression-ref" : {
+ "description" : "A measure reference in an expression: [:measure {:lib/uuid uuid} measure-id].",
+ "prefixItems" : [ {
+ "const" : "measure"
+ }, {
+ "properties" : {
+ "lib/uuid" : {
+ "$ref" : "#/components/schemas/metabase.lib.schema.common.non-blank-string"
+ }
+ },
+ "required" : [ "lib/uuid" ],
+ "type" : "object"
+ }, {
+ "minimum" : 1,
+ "type" : "integer"
+ } ],
+ "type" : "array"
+ },
+ "metabase.lib-metric.schema.metric-expression-ref" : {
+ "description" : "A metric reference in an expression: [:metric {:lib/uuid uuid} card-id].",
+ "prefixItems" : [ {
+ "const" : "metric"
+ }, {
+ "properties" : {
+ "lib/uuid" : {
+ "$ref" : "#/components/schemas/metabase.lib.schema.common.non-blank-string"
+ }
+ },
+ "required" : [ "lib/uuid" ],
+ "type" : "object"
+ }, {
+ "minimum" : 1,
+ "type" : "integer"
+ } ],
+ "type" : "array"
+ },
+ "metabase.lib-metric.schema.metric-math-expression" : {
+ "anyOf" : [ {
+ "$ref" : "#/components/schemas/metabase.lib-metric.schema.expression-leaf"
+ }, {
+ "type" : "number"
+ }, {
+ "type" : "array"
+ } ],
+ "description" : "A recursive metric math expression tree.\n Can be a leaf (metric/measure ref) or an arithmetic expression [op opts expr expr ...]\n with at least 2 operands.\n Note: uses :fn validator for arithmetic to avoid Malli's recursive seqex limitation."
+ },
+ "metabase.lib-metric.schema.typed-projection" : {
+ "description" : "A projection associated with a specific expression leaf instance via :lib/uuid.\n The :type and :id identify the source metric/measure for metadata resolution.\n The :lib/uuid disambiguates multiple references to the same metric/measure in an expression.",
+ "properties" : {
+ "id" : {
+ "minimum" : 1,
+ "type" : "integer"
+ },
+ "lib/uuid" : {
+ "$ref" : "#/components/schemas/metabase.lib.schema.common.non-blank-string"
+ },
+ "projection" : {
+ "items" : {
+ "$ref" : "#/components/schemas/metabase.lib-metric.schema.dimension-reference"
+ },
+ "type" : "array"
+ },
+ "type" : {
+ "enum" : [ "metric", "measure" ],
+ "type" : "string"
+ }
+ },
+ "required" : [ "type", "id", "lib/uuid", "projection" ],
+ "type" : "object"
+ },
+ "metabase.lib-metric.schema.typed-projections" : {
+ "description" : "A sequence of typed projections.",
+ "items" : {
+ "$ref" : "#/components/schemas/metabase.lib-metric.schema.typed-projection"
+ },
+ "type" : "array"
+ },
"metabase.lib.metadata.protocols.metadata-provider" : {
"description" : "Schema for something that satisfies the [[metabase.lib.metadata.protocols/MetadataProvider]] protocol."
},
@@ -9601,7 +8008,8 @@
"const" : "mbql.stage/mbql"
},
"limit" : {
- "$ref" : "#/components/schemas/metabase.lib.schema.common.int-greater-than-or-equal-to-zero"
+ "minimum" : 0,
+ "type" : "integer"
},
"order-by" : {
"$ref" : "#/components/schemas/metabase.lib.schema.order-by.order-bys"
@@ -9623,6 +8031,8 @@
"type" : "object"
}, {
"$ref" : "#/components/schemas/metabase.lib.schema..stage.valid-refs"
+ }, {
+ "$ref" : "#/components/schemas/metabase.lib.schema..stage.page-and-limit-are-mutually-exclusive"
}, {
"allOf" : [ ]
} ]
@@ -9676,6 +8086,9 @@
"allOf" : [ ]
} ]
},
+ "metabase.lib.schema..stage.page-and-limit-are-mutually-exclusive" : {
+ "description" : "If an MBQL query stage specifies `:page`, it should not also specify `:limit`"
+ },
"metabase.lib.schema..stage.type" : {
"enum" : [ "mbql.stage/native", "mbql.stage/mbql" ],
"type" : "string"
@@ -9773,18 +8186,9 @@
"$ref" : "#/components/schemas/metabase.lib.schema.util.distinct-mbql-clauses"
} ]
},
- "metabase.lib.schema.column-unique-key" : {
- "pattern" : "^column-unique-key-v\\d+\\$.+$",
- "type" : "string"
- },
"metabase.lib.schema.common.base-type" : {
"type" : "string"
},
- "metabase.lib.schema.common.int-greater-than-or-equal-to-zero" : {
- "description" : "Schema representing an integer than must also be greater than or equal to zero.",
- "minimum" : 0,
- "type" : "integer"
- },
"metabase.lib.schema.common.kebab-cased-map" : { },
"metabase.lib.schema.common.non-blank-string" : {
"minLength" : 1,
@@ -9856,12 +8260,14 @@
"description" : "Additional constraints added to a query limiting the maximum number of rows that can be returned. Mostly useful\n because native queries don't support the MBQL `:limit` clause. For MBQL queries, if `:limit` is set, it will\n override these values.",
"properties" : {
"max-results" : {
- "$ref" : "#/components/schemas/metabase.lib.schema.common.int-greater-than-or-equal-to-zero",
- "description" : "Maximum number of results to allow for a query with aggregations. If `max-results-bare-rows` is unset, this\n applies to all queries"
+ "description" : "Maximum number of results to allow for a query with aggregations. If `max-results-bare-rows` is unset, this\n applies to all queries",
+ "minimum" : 0,
+ "type" : "integer"
},
"max-results-bare-rows" : {
- "$ref" : "#/components/schemas/metabase.lib.schema.common.int-greater-than-or-equal-to-zero",
- "description" : "Maximum number of results to allow for a query with no aggregations. If set, this should be LOWER than\n `:max-results`."
+ "description" : "Maximum number of results to allow for a query with no aggregations. If set, this should be LOWER than\n `:max-results`.",
+ "minimum" : 0,
+ "type" : "integer"
}
},
"type" : "object"
@@ -10042,6 +8448,10 @@
"metabase.lib.schema.expression.window..offset.n" : {
"type" : "integer"
},
+ "metabase.lib.schema.external-query" : {
+ "$ref" : "#/components/schemas/metabase.lib.schema.query",
+ "description" : "Schema for \"External MBQL\" 5 query."
+ },
"metabase.lib.schema.fields" : {
"allOf" : [ {
"items" : {
@@ -10139,6 +8549,13 @@
"const" : -1337,
"description" : "The ID used to signify that a database is 'virtual' rather than physical.\n\n A fake integer ID is used so as to minimize the number of changes that need to be made on the frontend -- by using\n something that would otherwise be a legal ID, *nothing* need change there, and the frontend can query against this\n 'database' none the wiser. (This integer ID is negative which means it will never conflict with a *real* database\n ID.)\n\n This ID acts as a sort of flag. The relevant places in the middleware can check whether the DB we're querying is\n this 'virtual' database and take the appropriate actions."
},
+ "metabase.lib.schema.id.schema" : {
+ "anyOf" : [ {
+ "type" : "null"
+ }, {
+ "type" : "string"
+ } ]
+ },
"metabase.lib.schema.id.segment" : {
"description" : "Valid legacy Segment ID",
"minimum" : 1,
@@ -10166,7 +8583,7 @@
},
"metabase.lib.schema.info.context" : {
"description" : "Schema for `info.context`; used for informational purposes to record how a query was executed.",
- "enum" : [ "action", "ad-hoc", "agent", "cache-refresh", "collection", "map-tiles", "pulse", "dashboard-subscription", "dashboard", "question", "csv-download", "xlsx-download", "json-download", "public-dashboard", "public-question", "public-csv-download", "public-xlsx-download", "public-json-download", "embedded-dashboard", "embedded-question", "embedded-csv-download", "embedded-xlsx-download", "embedded-json-download", "table-grid", "transform-inspector" ],
+ "enum" : [ "action", "ad-hoc", "agent", "cache-refresh", "collection", "map-tiles", "pulse", "dashboard-subscription", "dashboard", "question", "csv-download", "xlsx-download", "json-download", "public-dashboard", "public-question", "public-csv-download", "public-xlsx-download", "public-json-download", "embedded-dashboard", "embedded-question", "embedded-csv-download", "embedded-xlsx-download", "embedded-json-download", "table-grid", "table-rows-sample", "transform-inspector", "slackbot" ],
"type" : "string"
},
"metabase.lib.schema.info.hash" : {
@@ -11120,13 +9537,6 @@
"type" : "null"
} ]
},
- "qp.pivot/pivot-grouping?" : {
- "oneOf" : [ {
- "type" : "boolean"
- }, {
- "type" : "null"
- } ]
- },
"qp/implicit-field?" : {
"oneOf" : [ {
"type" : "boolean"
@@ -11134,6 +9544,12 @@
"type" : "null"
} ]
},
+ "qp/native-sandbox-column.force-coercion-strategy" : {
+ "type" : "string"
+ },
+ "qp/native-sandbox-column.propagate-coercion?" : {
+ "type" : "boolean"
+ },
"selected?" : {
"type" : "boolean"
},
@@ -11209,6 +9625,13 @@
"type" : "null"
} ]
},
+ "excess-kurtosis" : {
+ "oneOf" : [ {
+ "type" : "number"
+ }, {
+ "type" : "null"
+ } ]
+ },
"max" : {
"oneOf" : [ {
"type" : "number"
@@ -11223,6 +9646,13 @@
"type" : "null"
} ]
},
+ "mode-fraction" : {
+ "oneOf" : [ {
+ "$ref" : "#/components/schemas/metabase.lib.schema.metadata.fingerprint.percent"
+ }, {
+ "type" : "null"
+ } ]
+ },
"q1" : {
"oneOf" : [ {
"type" : "number"
@@ -11243,6 +9673,27 @@
}, {
"type" : "null"
} ]
+ },
+ "skewness" : {
+ "oneOf" : [ {
+ "type" : "number"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "top-3-fraction" : {
+ "oneOf" : [ {
+ "$ref" : "#/components/schemas/metabase.lib.schema.metadata.fingerprint.percent"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "zero-fraction" : {
+ "oneOf" : [ {
+ "$ref" : "#/components/schemas/metabase.lib.schema.metadata.fingerprint.percent"
+ }, {
+ "type" : "null"
+ } ]
}
},
"type" : "object"
@@ -11257,12 +9708,53 @@
"type" : "null"
} ]
},
+ "hour-distribution" : {
+ "oneOf" : [ {
+ "items" : {
+ "$ref" : "#/components/schemas/metabase.lib.schema.metadata.fingerprint.percent"
+ },
+ "type" : "array"
+ }, {
+ "type" : "null"
+ } ]
+ },
"latest" : {
"oneOf" : [ {
"type" : "string"
}, {
"type" : "null"
} ]
+ },
+ "mode-fraction" : {
+ "oneOf" : [ {
+ "$ref" : "#/components/schemas/metabase.lib.schema.metadata.fingerprint.percent"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "skewness" : {
+ "oneOf" : [ {
+ "type" : "number"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "top-3-fraction" : {
+ "oneOf" : [ {
+ "$ref" : "#/components/schemas/metabase.lib.schema.metadata.fingerprint.percent"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "weekday-distribution" : {
+ "oneOf" : [ {
+ "items" : {
+ "$ref" : "#/components/schemas/metabase.lib.schema.metadata.fingerprint.percent"
+ },
+ "type" : "array"
+ }, {
+ "type" : "null"
+ } ]
}
},
"type" : "object"
@@ -11277,6 +9769,34 @@
"type" : "null"
} ]
},
+ "max-length" : {
+ "oneOf" : [ {
+ "type" : "number"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "min-length" : {
+ "oneOf" : [ {
+ "type" : "number"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "mode-fraction" : {
+ "oneOf" : [ {
+ "$ref" : "#/components/schemas/metabase.lib.schema.metadata.fingerprint.percent"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "percent-blank" : {
+ "oneOf" : [ {
+ "$ref" : "#/components/schemas/metabase.lib.schema.metadata.fingerprint.percent"
+ }, {
+ "type" : "null"
+ } ]
+ },
"percent-email" : {
"oneOf" : [ {
"$ref" : "#/components/schemas/metabase.lib.schema.metadata.fingerprint.percent"
@@ -11304,6 +9824,13 @@
}, {
"type" : "null"
} ]
+ },
+ "top-3-fraction" : {
+ "oneOf" : [ {
+ "$ref" : "#/components/schemas/metabase.lib.schema.metadata.fingerprint.percent"
+ }, {
+ "type" : "null"
+ } ]
}
},
"type" : "object"
@@ -11631,13 +10158,6 @@
"type" : "null"
} ]
},
- "qp.pivot/pivot-grouping?" : {
- "oneOf" : [ {
- "type" : "boolean"
- }, {
- "type" : "null"
- } ]
- },
"qp/implicit-field?" : {
"oneOf" : [ {
"type" : "boolean"
@@ -11645,6 +10165,12 @@
"type" : "null"
} ]
},
+ "qp/native-sandbox-column.force-coercion-strategy" : {
+ "type" : "string"
+ },
+ "qp/native-sandbox-column.propagate-coercion?" : {
+ "type" : "boolean"
+ },
"selected?" : {
"type" : "boolean"
},
@@ -12117,13 +10643,6 @@
"original-temporal-unit" : {
"$ref" : "#/components/schemas/metabase.lib.schema.temporal-bucketing.unit"
},
- "qp.pivot/pivot-grouping?" : {
- "oneOf" : [ {
- "type" : "boolean"
- }, {
- "type" : "null"
- } ]
- },
"semantic-type" : {
"oneOf" : [ {
"$ref" : "#/components/schemas/metabase.lib.schema.common.semantic-or-relation-type"
@@ -12210,13 +10729,6 @@
"original-temporal-unit" : {
"$ref" : "#/components/schemas/metabase.lib.schema.temporal-bucketing.unit"
},
- "qp.pivot/pivot-grouping?" : {
- "oneOf" : [ {
- "type" : "boolean"
- }, {
- "type" : "null"
- } ]
- },
"semantic-type" : {
"oneOf" : [ {
"$ref" : "#/components/schemas/metabase.lib.schema.common.semantic-or-relation-type"
@@ -12493,6 +11005,21 @@
"$ref" : "#/components/schemas/metabase.lib.schema.template-tag.disallow-dimension"
} ]
},
+ "metabase.lib.schema.template-tag.source-filter" : {
+ "description" : "Schema for a single source-filter applied to a table template tag.",
+ "properties" : {
+ "field-id" : {
+ "$ref" : "#/components/schemas/metabase.lib.schema.id.field"
+ },
+ "op" : {
+ "enum" : [ "<=", ">", ">=", "!=", "=", "<" ],
+ "type" : "string"
+ },
+ "value" : { }
+ },
+ "required" : [ "field-id", "op", "value" ],
+ "type" : "object"
+ },
"metabase.lib.schema.template-tag.source-query" : {
"allOf" : [ {
"properties" : {
@@ -12524,12 +11051,21 @@
"display-name" : {
"$ref" : "#/components/schemas/metabase.lib.schema.common.non-blank-string"
},
+ "emit-alias" : {
+ "type" : "boolean"
+ },
"id" : {
"$ref" : "#/components/schemas/metabase.lib.schema.template-tag.id"
},
"name" : {
"$ref" : "#/components/schemas/metabase.lib.schema.template-tag.name"
},
+ "source-filters" : {
+ "items" : {
+ "$ref" : "#/components/schemas/metabase.lib.schema.template-tag.source-filter"
+ },
+ "type" : "array"
+ },
"table-id" : {
"$ref" : "#/components/schemas/metabase.lib.schema.id.table"
},
@@ -13322,6 +11858,18 @@
"enum" : [ "days", "hours", "minutes", "seconds", "milliseconds", "microseconds", "nanoseconds" ],
"type" : "string"
},
+ "metabase.measures.api.RemappedValueResponse" : {
+ "anyOf" : [ {
+ "prefixItems" : [ { } ],
+ "type" : "array"
+ }, {
+ "prefixItems" : [ { }, {
+ "type" : "string"
+ } ],
+ "type" : "array"
+ } ],
+ "description" : "Response schema for dimension remapping endpoint.\n Returns [value] if no remapping, or [value, display-name] if remapped."
+ },
"metabase.measures.api.measure" : {
"description" : "Schema for a Measure entity as returned from the API.",
"properties" : {
@@ -13353,6 +11901,28 @@
"type" : "null"
} ]
},
+ "dimension_mappings" : {
+ "oneOf" : [ {
+ "items" : {
+ "properties" : { },
+ "type" : "object"
+ },
+ "type" : "array"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "dimensions" : {
+ "oneOf" : [ {
+ "items" : {
+ "properties" : { },
+ "type" : "object"
+ },
+ "type" : "array"
+ }, {
+ "type" : "null"
+ } ]
+ },
"entity_id" : {
"oneOf" : [ {
"type" : "string"
@@ -13369,6 +11939,13 @@
"minLength" : 1,
"type" : "string"
},
+ "result_column_name" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
"table_id" : {
"description" : "value must be an integer greater than zero.",
"minimum" : 1,
@@ -13379,6 +11956,361 @@
"required" : [ "id", "name", "table_id", "definition", "archived", "creator_id", "created_at", "updated_at" ],
"type" : "object"
},
+ "metabase.metabot.context.context" : {
+ "allOf" : [ {
+ "additionalProperties" : { },
+ "type" : "object"
+ }, {
+ "properties" : {
+ "user_is_viewing" : {
+ "items" : {
+ "anyOf" : [ {
+ "properties" : {
+ "chart_configs" : {
+ "items" : {
+ "properties" : {
+ "query" : {
+ "anyOf" : [ {
+ "$ref" : "#/components/schemas/metabase.lib.schema.query"
+ }, {
+ "$ref" : "#/components/schemas/metabase.legacy-mbql.schema.Query"
+ } ]
+ }
+ },
+ "type" : "object"
+ },
+ "type" : "array"
+ },
+ "query" : {
+ "anyOf" : [ {
+ "$ref" : "#/components/schemas/metabase.lib.schema.query"
+ }, {
+ "$ref" : "#/components/schemas/metabase.legacy-mbql.schema.Query"
+ } ]
+ },
+ "type" : {
+ "enum" : [ "model", "question", "metric", "adhoc" ],
+ "type" : "string"
+ }
+ },
+ "required" : [ "type" ],
+ "type" : "object"
+ }, {
+ "properties" : {
+ "query" : {
+ "anyOf" : [ {
+ "$ref" : "#/components/schemas/metabase.lib.schema.query"
+ }, {
+ "$ref" : "#/components/schemas/metabase.legacy-mbql.schema.Query"
+ } ]
+ },
+ "type" : {
+ "enum" : [ "dashboard", "model", "transform", "code_editor", "document", "question", "metric", "adhoc" ],
+ "type" : "string"
+ }
+ },
+ "required" : [ "type" ],
+ "type" : "object"
+ } ]
+ },
+ "type" : "array"
+ }
+ },
+ "type" : "object"
+ } ]
+ },
+ "metabase.metabot.schema.message" : {
+ "properties" : {
+ "content" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "role" : {
+ "$ref" : "#/components/schemas/metabase.metabot.schema.role"
+ },
+ "tool_call_id" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "tool_calls" : {
+ "oneOf" : [ {
+ "items" : {
+ "properties" : {
+ "arguments" : {
+ "type" : "string"
+ },
+ "id" : {
+ "type" : "string"
+ },
+ "name" : {
+ "type" : "string"
+ }
+ },
+ "required" : [ "id", "name", "arguments" ],
+ "type" : "object"
+ },
+ "type" : "array"
+ }, {
+ "type" : "null"
+ } ]
+ }
+ },
+ "required" : [ "role" ],
+ "type" : "object"
+ },
+ "metabase.metabot.schema.messages" : {
+ "items" : {
+ "$ref" : "#/components/schemas/metabase.metabot.schema.message"
+ },
+ "type" : "array"
+ },
+ "metabase.metabot.schema.role" : {
+ "enum" : [ "system", "user", "assistant", "tool" ],
+ "type" : "string"
+ },
+ "metabase.metrics.api.BreakoutValuesResponse" : {
+ "properties" : {
+ "col" : {
+ "properties" : { },
+ "type" : "object"
+ },
+ "values" : {
+ "items" : { },
+ "type" : "array"
+ }
+ },
+ "required" : [ "values", "col" ],
+ "type" : "object"
+ },
+ "metabase.metrics.api.DatasetRequest" : {
+ "description" : "Schema for POST /dataset request body.",
+ "properties" : {
+ "definition" : {
+ "$ref" : "#/components/schemas/metabase.metrics.api.Definition"
+ }
+ },
+ "required" : [ "definition" ],
+ "type" : "object"
+ },
+ "metabase.metrics.api.DatasetResponse" : {
+ "description" : "Schema for POST /dataset response.",
+ "properties" : {
+ "data" : {
+ "properties" : {
+ "cols" : {
+ "items" : { },
+ "type" : "array"
+ },
+ "rows" : {
+ "items" : { },
+ "type" : "array"
+ }
+ },
+ "required" : [ "cols", "rows" ],
+ "type" : "object"
+ },
+ "row_count" : {
+ "description" : "value must be an integer greater or equal to than zero.",
+ "minimum" : 0,
+ "type" : "integer"
+ },
+ "status" : {
+ "enum" : [ "completed", "completed" ]
+ }
+ },
+ "required" : [ "status", "data", "row_count" ],
+ "type" : "object"
+ },
+ "metabase.metrics.api.Definition" : {
+ "description" : "Schema for the definition object within a dataset request.\n Uses expression-based contract for metric math support.",
+ "properties" : {
+ "expression" : {
+ "$ref" : "#/components/schemas/metabase.lib-metric.schema.metric-math-expression"
+ },
+ "filters" : {
+ "oneOf" : [ {
+ "$ref" : "#/components/schemas/metabase.lib-metric.schema.instance-filters"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "projections" : {
+ "oneOf" : [ {
+ "$ref" : "#/components/schemas/metabase.lib-metric.schema.typed-projections"
+ }, {
+ "type" : "null"
+ } ]
+ }
+ },
+ "required" : [ "expression" ],
+ "type" : "object"
+ },
+ "metabase.metrics.api.Metric" : {
+ "description" : "Schema for a Metric in list responses (without hydrated dimensions).",
+ "properties" : {
+ "collection" : {
+ "oneOf" : [ {
+ "properties" : {
+ "id" : {
+ "oneOf" : [ {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "name" : {
+ "type" : "string"
+ }
+ },
+ "required" : [ "id", "name" ],
+ "type" : "object"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "collection_id" : {
+ "oneOf" : [ {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "description" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "id" : {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
+ },
+ "name" : {
+ "type" : "string"
+ }
+ },
+ "required" : [ "id", "name", "description", "collection_id" ],
+ "type" : "object"
+ },
+ "metabase.metrics.api.MetricWithDimensions" : {
+ "description" : "Schema for a Metric in list responses (without hydrated dimensions).",
+ "properties" : {
+ "collection" : {
+ "oneOf" : [ {
+ "properties" : {
+ "id" : {
+ "oneOf" : [ {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "name" : {
+ "type" : "string"
+ }
+ },
+ "required" : [ "id", "name" ],
+ "type" : "object"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "collection_id" : {
+ "oneOf" : [ {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "database_id" : {
+ "oneOf" : [ {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "dataset_query" : {
+ "properties" : { },
+ "type" : "object"
+ },
+ "description" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "dimension_mappings" : {
+ "oneOf" : [ {
+ "items" : {
+ "properties" : { },
+ "type" : "object"
+ },
+ "type" : "array"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "dimensions" : {
+ "oneOf" : [ {
+ "items" : {
+ "properties" : { },
+ "type" : "object"
+ },
+ "type" : "array"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "id" : {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
+ },
+ "name" : {
+ "type" : "string"
+ },
+ "result_column_name" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ }
+ },
+ "required" : [ "id", "name", "description", "collection_id" ],
+ "type" : "object"
+ },
+ "metabase.metrics.api.RemappedValueResponse" : {
+ "anyOf" : [ {
+ "prefixItems" : [ { } ],
+ "type" : "array"
+ }, {
+ "prefixItems" : [ { }, {
+ "type" : "string"
+ } ],
+ "type" : "array"
+ } ],
+ "description" : "Response schema for dimension remapping endpoint.\n Returns [value] if no remapping, or [value, display-name] if remapped."
+ },
"metabase.notification.api.notification.NotificationApiInput" : {
"description" : "Notification schema for API input. Like FullyHydratedNotification but restricts templates\n to user-provided types only (no handlebars-resource).",
"oneOf" : [ {
@@ -14574,6 +13506,13 @@
"details" : {
"additionalProperties" : false,
"properties" : {
+ "channel_id" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
"value" : { }
},
"required" : [ "value" ],
@@ -15040,19 +13979,6 @@
"$ref" : "#/components/schemas/metabase.legacy-mbql.schema.legacy-column-metadata",
"description" : "A single result metadata column as returned by the Query Processor."
},
- "metabase.query-processor.schema.any-query" : {
- "description" : "Schema for a map that is in the general shape of either a legacy MBQL or MBQL 5 query. Query may not be normalized\n yet!\n\n This schema is not very strict because we need to handle different types of queries (legacy MBQL, pMBQL,\n super-legacy MBQL, internal audit app queries, etc.) and it might not be normalized yet.",
- "properties" : {
- "database" : {
- "anyOf" : [ {
- "$ref" : "#/components/schemas/metabase.lib.schema.id.database"
- }, {
- "$ref" : "#/components/schemas/metabase.lib.schema.id.saved-questions-virtual-database"
- } ]
- }
- },
- "type" : "object"
- },
"metabase.query-processor.schema.export-format" : {
"description" : "Schema for valid export formats for downloading query results.",
"enum" : [ "csv", "api", "xlsx", "json" ],
@@ -15109,6 +14035,10 @@
"required" : [ "status", "row_count" ],
"type" : "object"
},
+ "metabase.source-swap.schema.column-error" : {
+ "enum" : [ "column-type-mismatch", "missing-primary-key", "missing-foreign-key", "foreign-key-mismatch" ],
+ "type" : "string"
+ },
"metabase.sync.schedules.ExpandedSchedulesMap" : {
"description" : "value must be a valid map of schedule maps for a DB.",
"properties" : {
@@ -15420,511 +14350,7 @@
} ]
}
},
- "required" : [ "alias" ],
- "type" : "object"
- },
- "metabase.transforms-inspector.schema.alert-trigger" : {
- "description" : "Definition for conditional alerts.\n FE evaluates condition against card results and shows alert if triggered.",
- "properties" : {
- "condition" : {
- "$ref" : "#/components/schemas/metabase.transforms-inspector.schema.trigger-condition"
- },
- "id" : {
- "type" : "string"
- },
- "message" : {
- "type" : "string"
- },
- "metadata" : {
- "$ref" : "#/components/schemas/metabase.transforms-inspector.schema.trigger-metadata"
- },
- "severity" : {
- "enum" : [ "info", "warning", "error" ],
- "type" : "string"
- }
- },
- "required" : [ "id", "condition", "severity", "message" ],
- "type" : "object"
- },
- "metabase.transforms-inspector.schema.card" : {
- "description" : "A visualization card in the inspector output.\n\n Cards are generic - lens-specific data goes in :metadata.\n The :metadata map is opaque to the core but interpreted by\n lens-specific lib utilities on the frontend. ",
- "properties" : {
- "dataset_query" : {
- "$ref" : "#/components/schemas/metabase.lib.schema.query"
- },
- "display" : {
- "$ref" : "#/components/schemas/metabase.transforms-inspector.schema.display-type"
- },
- "id" : {
- "type" : "string"
- },
- "metadata" : {
- "$ref" : "#/components/schemas/metabase.transforms-inspector.schema.card-metadata"
- },
- "section_id" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "title" : {
- "type" : "string"
- }
- },
- "required" : [ "id", "title", "display", "dataset_query" ],
- "type" : "object"
- },
- "metabase.transforms-inspector.schema.card-metadata" : {
- "description" : "Common metadata for join-related cards and triggers.",
- "properties" : {
- "card_type" : {
- "type" : "string"
- },
- "dedup_key" : {
- "$ref" : "#/components/schemas/metabase.transforms-inspector.schema.dedup-key"
- },
- "depends_on_cards" : {
- "items" : {
- "type" : "string"
- },
- "type" : "array",
- "uniqueItems" : true
- },
- "group_id" : {
- "type" : "string"
- },
- "group_order" : {
- "type" : "integer"
- },
- "group_role" : {
- "$ref" : "#/components/schemas/metabase.transforms-inspector.schema.group-role"
- },
- "join_alias" : {
- "type" : "string"
- },
- "join_step" : {
- "type" : "integer"
- },
- "join_strategy" : {
- "type" : "string"
- }
- },
- "type" : "object"
- },
- "metabase.transforms-inspector.schema.complexity" : {
- "description" : "Complexity estimate for a lens.",
- "properties" : {
- "level" : {
- "$ref" : "#/components/schemas/metabase.transforms-inspector.schema.complexity-level"
- },
- "score" : {
- "minimum" : 1,
- "type" : "integer"
- }
- },
- "required" : [ "level" ],
- "type" : "object"
- },
- "metabase.transforms-inspector.schema.complexity-level" : {
- "description" : "Estimated complexity/cost of generating a lens.",
- "enum" : [ "fast", "slow", "very-slow" ],
- "type" : "string"
- },
- "metabase.transforms-inspector.schema.dedup-key" : {
- "description" : "Key for deduplicating identical queries across lenses.\n Typically a vector like [:table_count table-id].",
- "items" : { },
- "type" : "array"
- },
- "metabase.transforms-inspector.schema.discovery-response" : {
- "description" : "Response from lens discovery.",
- "properties" : {
- "available_lenses" : {
- "items" : {
- "$ref" : "#/components/schemas/metabase.transforms-inspector.schema.lens-metadata"
- },
- "type" : "array"
- },
- "description" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "name" : {
- "type" : "string"
- },
- "sources" : {
- "items" : {
- "$ref" : "#/components/schemas/metabase.transforms-inspector.schema.table"
- },
- "type" : "array"
- },
- "status" : {
- "$ref" : "#/components/schemas/metabase.transforms-inspector.schema.inspector-status"
- },
- "target" : {
- "oneOf" : [ {
- "$ref" : "#/components/schemas/metabase.transforms-inspector.schema.table"
- }, {
- "type" : "null"
- } ]
- },
- "visited_fields" : {
- "oneOf" : [ {
- "$ref" : "#/components/schemas/metabase.transforms-inspector.schema.visited-fields"
- }, {
- "type" : "null"
- } ]
- }
- },
- "required" : [ "name", "status", "sources", "available_lenses" ],
- "type" : "object"
- },
- "metabase.transforms-inspector.schema.display-type" : {
- "description" : "Valid display types for cards.",
- "enum" : [ "bar", "row", "line", "area", "pie", "scalar", "gauge", "progress", "table", "hidden" ],
- "type" : "string"
- },
- "metabase.transforms-inspector.schema.drill-lens" : {
- "description" : "A drill-down lens available from the current lens.",
- "properties" : {
- "description" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "display_name" : {
- "type" : "string"
- },
- "id" : {
- "type" : "string"
- }
- },
- "required" : [ "id", "display_name" ],
- "type" : "object"
- },
- "metabase.transforms-inspector.schema.drill-lens-trigger" : {
- "description" : "Definition for conditional drill lens availability.\n FE evaluates condition and shows drill lens option if triggered.\n :params is passed to the drill lens when triggered.",
- "properties" : {
- "condition" : {
- "$ref" : "#/components/schemas/metabase.transforms-inspector.schema.trigger-condition"
- },
- "lens_id" : {
- "type" : "string"
- },
- "metadata" : {
- "$ref" : "#/components/schemas/metabase.transforms-inspector.schema.trigger-metadata"
- },
- "params" : {
- "additionalProperties" : { },
- "type" : "object"
- },
- "reason" : {
- "type" : "string"
- }
- },
- "required" : [ "lens_id", "condition" ],
- "type" : "object"
- },
- "metabase.transforms-inspector.schema.field" : {
- "description" : "Field metadata for inspector.",
- "properties" : {
- "base_type" : {
- "$ref" : "#/components/schemas/metabase.lib.schema.common.base-type"
- },
- "display_name" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "id" : {
- "minimum" : 1,
- "type" : "integer"
- },
- "name" : {
- "type" : "string"
- },
- "semantic_type" : {
- "oneOf" : [ {
- "$ref" : "#/components/schemas/metabase.lib.schema.common.semantic-or-relation-type"
- }, {
- "type" : "null"
- } ]
- },
- "stats" : {
- "oneOf" : [ {
- "$ref" : "#/components/schemas/metabase.transforms-inspector.schema.field-stats"
- }, {
- "type" : "null"
- } ]
- }
- },
- "required" : [ "id", "name", "base_type" ],
- "type" : "object"
- },
- "metabase.transforms-inspector.schema.field-stats" : {
- "description" : "Statistics for a field from fingerprints.",
- "properties" : {
- "avg" : {
- "type" : "number"
- },
- "distinct_count" : {
- "type" : "integer"
- },
- "earliest" : {
- "type" : "string"
- },
- "latest" : {
- "type" : "string"
- },
- "max" : {
- "type" : "number"
- },
- "min" : {
- "type" : "number"
- },
- "nil_percent" : {
- "type" : "number"
- },
- "q1" : {
- "type" : "number"
- },
- "q3" : {
- "type" : "number"
- }
- },
- "type" : "object"
- },
- "metabase.transforms-inspector.schema.group-role" : {
- "description" : "Role of a card within a comparison group.",
- "enum" : [ "input", "output" ],
- "type" : "string"
- },
- "metabase.transforms-inspector.schema.inspector-status" : {
- "description" : "Status of the inspector result.",
- "enum" : [ "not-run", "ready" ],
- "type" : "string"
- },
- "metabase.transforms-inspector.schema.layout-type" : {
- "description" : "Layout hints for sections.\n - :flat - cards displayed in a grid\n - :comparison - cards grouped for side-by-side comparison",
- "enum" : [ "flat", "comparison" ],
- "type" : "string"
- },
- "metabase.transforms-inspector.schema.lens" : {
- "description" : "Full lens contents and drill lens/alert triggers.",
- "properties" : {
- "alert_triggers" : {
- "items" : {
- "$ref" : "#/components/schemas/metabase.transforms-inspector.schema.alert-trigger"
- },
- "type" : "array"
- },
- "cards" : {
- "items" : {
- "$ref" : "#/components/schemas/metabase.transforms-inspector.schema.card"
- },
- "type" : "array"
- },
- "complexity" : {
- "$ref" : "#/components/schemas/metabase.transforms-inspector.schema.complexity"
- },
- "display_name" : {
- "type" : "string"
- },
- "drill_lens_triggers" : {
- "items" : {
- "$ref" : "#/components/schemas/metabase.transforms-inspector.schema.drill-lens-trigger"
- },
- "type" : "array"
- },
- "drill_lenses" : {
- "items" : {
- "$ref" : "#/components/schemas/metabase.transforms-inspector.schema.drill-lens"
- },
- "type" : "array"
- },
- "id" : {
- "type" : "string"
- },
- "sections" : {
- "items" : {
- "$ref" : "#/components/schemas/metabase.transforms-inspector.schema.section"
- },
- "type" : "array"
- },
- "summary" : {
- "$ref" : "#/components/schemas/metabase.transforms-inspector.schema.lens-summary"
- }
- },
- "required" : [ "id", "display_name", "sections", "cards" ],
- "type" : "object"
- },
- "metabase.transforms-inspector.schema.lens-metadata" : {
- "properties" : {
- "complexity" : {
- "$ref" : "#/components/schemas/metabase.transforms-inspector.schema.complexity"
- },
- "description" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "display_name" : {
- "type" : "string"
- },
- "id" : {
- "type" : "string"
- }
- },
- "required" : [ "id", "display_name" ],
- "type" : "object"
- },
- "metabase.transforms-inspector.schema.lens-summary" : {
- "description" : "Summary section of a lens.",
- "properties" : {
- "alerts" : {
- "items" : {
- "properties" : { },
- "type" : "object"
- },
- "type" : "array"
- },
- "highlights" : {
- "items" : {
- "$ref" : "#/components/schemas/metabase.transforms-inspector.schema.summary-highlight"
- },
- "type" : "array"
- },
- "text" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- }
- },
- "type" : "object"
- },
- "metabase.transforms-inspector.schema.section" : {
- "description" : "A section grouping cards in a lens.",
- "properties" : {
- "description" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "id" : {
- "type" : "string"
- },
- "layout" : {
- "$ref" : "#/components/schemas/metabase.transforms-inspector.schema.layout-type"
- },
- "title" : {
- "type" : "string"
- }
- },
- "required" : [ "id", "title" ],
- "type" : "object"
- },
- "metabase.transforms-inspector.schema.summary-highlight" : {
- "description" : "A highlight in the lens summary.",
- "properties" : {
- "card_id" : {
- "type" : "string"
- },
- "label" : {
- "type" : "string"
- },
- "value" : {
- "oneOf" : [ { }, {
- "type" : "null"
- } ]
- }
- },
- "required" : [ "label" ],
- "type" : "object"
- },
- "metabase.transforms-inspector.schema.table" : {
- "description" : "Table metadata.",
- "properties" : {
- "column_count" : {
- "type" : "integer"
- },
- "db_id" : {
- "minimum" : 1,
- "type" : "integer"
- },
- "fields" : {
- "items" : {
- "$ref" : "#/components/schemas/metabase.transforms-inspector.schema.field"
- },
- "type" : "array"
- },
- "schema" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "table_id" : {
- "minimum" : 1,
- "type" : "integer"
- },
- "table_name" : {
- "type" : "string"
- }
- },
- "required" : [ "table_id", "table_name", "db_id", "column_count", "fields" ],
- "type" : "object"
- },
- "metabase.transforms-inspector.schema.trigger-condition" : {
- "description" : "A named condition that triggers an alert or drill lens.\n Evaluated by multimethod in lib against card results.\n Only :name is required; other keys are condition-specific.",
- "properties" : {
- "name" : {
- "type" : "string"
- }
- },
- "required" : [ "name" ],
- "type" : "object"
- },
- "metabase.transforms-inspector.schema.trigger-metadata" : {
- "description" : "Common metadata for join-related cards and triggers.",
- "properties" : {
- "join_alias" : {
- "type" : "string"
- },
- "join_step" : {
- "type" : "integer"
- },
- "join_strategy" : {
- "type" : "string"
- }
- },
- "type" : "object"
- },
- "metabase.transforms-inspector.schema.visited-fields" : {
- "description" : "Field IDs used in semantically important query clauses.\n Used for interestingness scoring and preselection.",
- "properties" : {
- "all" : {
- "items" : {
- "minimum" : 1,
- "type" : "integer"
- },
- "type" : "array",
- "uniqueItems" : true
- }
- },
+ "required" : [ "alias", "database_id", "schema" ],
"type" : "object"
},
"metabase.transforms-rest.api.transform.run-trigger" : {
@@ -15942,11 +14368,8 @@
},
"metabase.transforms.schema.checkpoint-strategy" : {
"properties" : {
- "checkpoint-filter" : {
- "type" : "string"
- },
- "checkpoint-filter-unique-key" : {
- "$ref" : "#/components/schemas/metabase.lib.schema.column-unique-key"
+ "checkpoint-filter-field-id" : {
+ "$ref" : "#/components/schemas/metabase.lib.schema.id.field"
},
"type" : {
"const" : "checkpoint"
@@ -16215,25 +14638,13 @@
"description" : "One of these:\n\n * A non-empty string with an Entity ID (including `card__<id>`-encoded Card IDs)\n\n * a form-encoded base-64-encoded JSON-encoded MBQL query\n\n * The name of a transform\n\n (Effectively since the names of transforms are unconstrained this parameter is allowed to be any form-encoded\n string.)",
"minLength" : 1,
"type" : "string"
- },
- "metabot.reaction.redirect" : {
- "properties" : {
- "type" : {
- "const" : "metabot.reaction/redirect"
- },
- "url" : {
- "type" : "string"
- }
- },
- "required" : [ "type", "url" ],
- "type" : "object"
}
},
"securitySchemes" : {
"ApiKeyAuth" : {
- "description" : "Session token obtained from /api/session endpoint",
+ "description" : "API key for authentication",
"in" : "header",
- "name" : "X-Metabase-Session",
+ "name" : "X-API-Key",
"type" : "apiKey"
}
}
@@ -16244,7 +14655,7 @@
"url" : "https://www.gnu.org/licenses/agpl-3.0.html"
},
"title" : "Metabase API",
- "version" : "v0.57.1-SNAPSHOT"
+ "version" : "vLOCAL_DEV"
},
"openapi" : "3.1.0",
"paths" : {
@@ -16738,16 +15149,16 @@
"tags" : [ "/api/activity" ]
}
},
- "/api/agent/v1/construct-query" : {
+ "/api/agent/v1/dashboard" : {
"post" : {
- "description" : "Construct an MBQL query from a table or metric.\n\n Returns a base64-encoded MBQL query that can be used with the query API.\n\n For tables, supports: filters, fields, aggregations, group_by, order_by, limit.\n For metrics, supports: filters, group_by (aggregation is defined by the metric).",
- "operationId" : "post-api-agent-v1-construct-query",
+ "description" : "Create a new dashboard, optionally populated with saved questions.\n\n Pass `question_ids` to add existing saved questions as cards on the dashboard.\n Cards are automatically positioned on the grid based on their display type.",
+ "operationId" : "post-api-agent-v1-dashboard",
"parameters" : [ ],
"requestBody" : {
"content" : {
"application/json" : {
"schema" : {
- "$ref" : "#/components/schemas/metabase-enterprise.agent-api.api.construct-query-request"
+ "$ref" : "#/components/schemas/metabase.agent-api.api.create-dashboard-request"
}
}
}
@@ -16757,7 +15168,7 @@
"content" : {
"application/json" : {
"schema" : {
- "$ref" : "#/components/schemas/metabase-enterprise.agent-api.api.construct-query-response"
+ "$ref" : "#/components/schemas/metabase.agent-api.api.create-dashboard-response"
}
}
},
@@ -16770,7 +15181,7 @@
"description" : "Server error response"
}
},
- "summary" : "POST /api/agent/v1/construct-query",
+ "summary" : "POST /api/agent/v1/dashboard",
"tags" : [ "/api/agent" ]
}
},
@@ -16783,7 +15194,7 @@
"content" : {
"application/json" : {
"schema" : {
- "$ref" : "#/components/schemas/metabase-enterprise.agent-api.api.execute-query-request"
+ "$ref" : "#/components/schemas/metabase.agent-api.api.execute-query-request"
}
}
}
@@ -16793,7 +15204,7 @@
"content" : {
"application/json" : {
"schema" : {
- "$ref" : "#/components/schemas/metabase-enterprise.agent-api.api.execute-query-response"
+ "$ref" : "#/components/schemas/metabase.agent-api.api.execute-query-response"
}
}
},
@@ -16873,7 +15284,7 @@
"content" : {
"application/json" : {
"schema" : {
- "$ref" : "#/components/schemas/metabase-enterprise.agent-api.api.metric"
+ "$ref" : "#/components/schemas/metabase.agent-api.api.metric"
}
}
},
@@ -16917,7 +15328,7 @@
"content" : {
"application/json" : {
"schema" : {
- "$ref" : "#/components/schemas/metabase-enterprise.agent-api.api.field-values"
+ "$ref" : "#/components/schemas/metabase.agent-api.api.field-values"
}
}
},
@@ -16967,6 +15378,42 @@
"tags" : [ "/api/agent" ]
}
},
+ "/api/agent/v1/question" : {
+ "post" : {
+ "description" : "Save a previously constructed query as a named question (card).\n\n The `query` parameter should be a base64-encoded string returned by construct_query.\n Optionally specify display type, description, collection, and visualization settings.",
+ "operationId" : "post-api-agent-v1-question",
+ "parameters" : [ ],
+ "requestBody" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "$ref" : "#/components/schemas/metabase.agent-api.api.create-question-request"
+ }
+ }
+ }
+ },
+ "responses" : {
+ "2XX" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "$ref" : "#/components/schemas/metabase.agent-api.api.create-question-response"
+ }
+ }
+ },
+ "description" : "Successful response"
+ },
+ "4XX" : {
+ "description" : "Client error response"
+ },
+ "5XX" : {
+ "description" : "Server error response"
+ }
+ },
+ "summary" : "POST /api/agent/v1/question",
+ "tags" : [ "/api/agent" ]
+ }
+ },
"/api/agent/v1/search" : {
"post" : {
"description" : "Search for tables and metrics.\n\n Supports both term-based and semantic search queries. Results are ranked using\n Reciprocal Rank Fusion when both query types are provided.",
@@ -16979,22 +15426,32 @@
"properties" : {
"semantic_queries" : {
"oneOf" : [ {
- "items" : {
+ "anyOf" : [ {
+ "items" : {
+ "minLength" : 1,
+ "type" : "string"
+ },
+ "type" : "array"
+ }, {
"minLength" : 1,
"type" : "string"
- },
- "type" : "array"
+ } ]
}, {
"type" : "null"
} ]
},
"term_queries" : {
"oneOf" : [ {
- "items" : {
+ "anyOf" : [ {
+ "items" : {
+ "minLength" : 1,
+ "type" : "string"
+ },
+ "type" : "array"
+ }, {
"minLength" : 1,
"type" : "string"
- },
- "type" : "array"
+ } ]
}, {
"type" : "null"
} ]
@@ -17010,7 +15467,7 @@
"content" : {
"application/json" : {
"schema" : {
- "$ref" : "#/components/schemas/metabase-enterprise.agent-api.api.search-response"
+ "$ref" : "#/components/schemas/metabase.agent-api.api.search-response"
}
}
},
@@ -17112,7 +15569,7 @@
"content" : {
"application/json" : {
"schema" : {
- "$ref" : "#/components/schemas/metabase-enterprise.agent-api.api.table"
+ "$ref" : "#/components/schemas/metabase.agent-api.api.table"
}
}
},
@@ -17156,7 +15613,7 @@
"content" : {
"application/json" : {
"schema" : {
- "$ref" : "#/components/schemas/metabase-enterprise.agent-api.api.field-values"
+ "$ref" : "#/components/schemas/metabase.agent-api.api.field-values"
}
}
},
@@ -17173,6 +15630,153 @@
"tags" : [ "/api/agent" ]
}
},
+ "/api/agent/v2/construct-query" : {
+ "post" : {
+ "description" : "Construct an MBQL query from a portable MBQL 5 representations JSON payload.\n\n The body is `{\"query\": <external-query>}` where `<external-query>` is a JSON object\n matching `::lib.schema/external-query` — see the `construct_notebook_query` tool\n documentation for the format reference. Returns a base64-encoded MBQL query that can be\n executed via /v1/execute or paginated via /v2/query.",
+ "operationId" : "post-api-agent-v2-construct-query",
+ "parameters" : [ ],
+ "requestBody" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "$ref" : "#/components/schemas/metabase.agent-api.api.construct-query-request"
+ }
+ }
+ }
+ },
+ "responses" : {
+ "2XX" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "$ref" : "#/components/schemas/metabase.agent-api.api.construct-query-response"
+ }
+ }
+ },
+ "description" : "Successful response"
+ },
+ "4XX" : {
+ "description" : "Client error response"
+ },
+ "5XX" : {
+ "description" : "Server error response"
+ }
+ },
+ "summary" : "POST /api/agent/v2/construct-query",
+ "tags" : [ "/api/agent" ]
+ }
+ },
+ "/api/agent/v2/query" : {
+ "post" : {
+ "description" : "Execute a portable MBQL 5 representations JSON query and stream the results, with\n continuation-token pagination.\n\n Accepts either a JSON body (same shape as /v2/construct-query) or a `continuation_token`\n from a previous response. Returns results with column metadata and an optional\n `continuation_token` for fetching the next page.",
+ "operationId" : "post-api-agent-v2-query",
+ "parameters" : [ ],
+ "requestBody" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "$ref" : "#/components/schemas/metabase.agent-api.api.query-request"
+ }
+ }
+ }
+ },
+ "responses" : {
+ "2XX" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "$ref" : "#/components/schemas/metabase.agent-api.api.query-response"
+ }
+ }
+ },
+ "description" : "Successful response"
+ },
+ "4XX" : {
+ "description" : "Client error response"
+ },
+ "5XX" : {
+ "description" : "Server error response"
+ }
+ },
+ "summary" : "POST /api/agent/v2/query",
+ "tags" : [ "/api/agent" ]
+ }
+ },
+ "/api/ai-entity-analysis/analyze-chart" : {
+ "post" : {
+ "description" : "Analyze a chart image using an AI vision model. This function sends the image data to a separate external AI service\n for analysis.",
+ "operationId" : "post-api-ai-entity-analysis-analyze-chart",
+ "parameters" : [ ],
+ "requestBody" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "properties" : {
+ "description" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "image_base64" : {
+ "type" : "string"
+ },
+ "name" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "timeline_events" : {
+ "oneOf" : [ {
+ "items" : {
+ "properties" : {
+ "description" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "name" : {
+ "type" : "string"
+ },
+ "timestamp" : {
+ "type" : "string"
+ }
+ },
+ "required" : [ "name", "timestamp" ],
+ "type" : "object"
+ },
+ "type" : "array"
+ }, {
+ "type" : "null"
+ } ]
+ }
+ },
+ "required" : [ "image_base64" ],
+ "type" : "object"
+ }
+ }
+ }
+ },
+ "responses" : {
+ "2XX" : {
+ "description" : "Successful response"
+ },
+ "4XX" : {
+ "description" : "Client error response"
+ },
+ "5XX" : {
+ "description" : "Server error response"
+ }
+ },
+ "summary" : "POST /api/ai-entity-analysis/analyze-chart",
+ "tags" : [ "/api/ai-entity-analysis" ]
+ }
+ },
"/api/alert" : {
"get" : {
"description" : "Fetch alerts which the current user has created or will receive, or all alerts if the user is an admin.\n The optional `user_id` will return alerts created by the corresponding user, but is ignored for non-admin users.",
@@ -17296,6 +15900,78 @@
"tags" : [ "/api/analytics" ]
}
},
+ "/api/analytics/internal" : {
+ "post" : {
+ "description" : "Receive a batch of internal analytics events from the frontend and record them as Prometheus metrics.",
+ "operationId" : "post-api-analytics-internal",
+ "parameters" : [ ],
+ "requestBody" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "properties" : {
+ "events" : {
+ "items" : {
+ "properties" : {
+ "amount" : {
+ "oneOf" : [ {
+ "type" : "number"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "labels" : {
+ "oneOf" : [ {
+ "additionalProperties" : {
+ "type" : "string"
+ },
+ "type" : "object"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "metric" : {
+ "type" : "string"
+ },
+ "op" : {
+ "enum" : [ "inc", "dec", "set", "observe", "clear" ],
+ "type" : "string"
+ }
+ },
+ "required" : [ "op", "metric" ],
+ "type" : "object"
+ },
+ "type" : "array"
+ }
+ },
+ "required" : [ "events" ],
+ "type" : "object"
+ }
+ }
+ }
+ },
+ "responses" : {
+ "2XX" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "type" : "null"
+ }
+ }
+ },
+ "description" : "Successful response"
+ },
+ "4XX" : {
+ "description" : "Client error response"
+ },
+ "5XX" : {
+ "description" : "Server error response"
+ }
+ },
+ "summary" : "POST /api/analytics/internal",
+ "tags" : [ "/api/analytics" ]
+ }
+ },
"/api/api-key" : {
"get" : {
"description" : "Get a list of API keys with the default scope. Non-paginated.",
@@ -18372,6 +17048,13 @@
},
"responses" : {
"2XX" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "type" : "null"
+ }
+ }
+ },
"description" : "Successful response"
},
"4XX" : {
@@ -18449,6 +17132,13 @@
} ],
"responses" : {
"2XX" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "$ref" : "#/components/schemas/metabase.cache.api.cache-config-list-response"
+ }
+ }
+ },
"description" : "Successful response"
},
"4XX" : {
@@ -18491,6 +17181,13 @@
},
"responses" : {
"2XX" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "$ref" : "#/components/schemas/metabase.cache.api.cache-config-store-response"
+ }
+ }
+ },
"description" : "Successful response"
},
"4XX" : {
@@ -18574,6 +17271,13 @@
} ],
"responses" : {
"2XX" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "$ref" : "#/components/schemas/metabase.cache.api.cache-invalidate-response"
+ }
+ }
+ },
"description" : "Successful response"
},
"4XX" : {
@@ -18738,6 +17442,26 @@
"type" : "null"
} ]
},
+ "size" : {
+ "oneOf" : [ {
+ "properties" : {
+ "size_x" : {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
+ },
+ "size_y" : {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
+ }
+ },
+ "required" : [ "size_x", "size_y" ],
+ "type" : "object"
+ }, {
+ "type" : "null"
+ } ]
+ },
"type" : {
"oneOf" : [ {
"$ref" : "#/components/schemas/metabase.queries.schema.card-type"
@@ -20361,7 +19085,7 @@
"schema" : {
"oneOf" : [ {
"items" : {
- "enum" : [ "dashboard", "table", "dataset", "no_models", "timeline", "snippet", "collection", "transform", "document", "pulse", "metric", "card" ],
+ "enum" : [ "dashboard", "table", "dataset", "no_models", "timeline", "snippet", "collection", "measure", "transform", "document", "pulse", "metric", "card" ],
"type" : "string"
},
"type" : "array"
@@ -20889,7 +19613,7 @@
"schema" : {
"oneOf" : [ {
"items" : {
- "enum" : [ "dashboard", "table", "dataset", "no_models", "timeline", "snippet", "collection", "transform", "document", "pulse", "metric", "card" ],
+ "enum" : [ "dashboard", "table", "dataset", "no_models", "timeline", "snippet", "collection", "measure", "transform", "document", "pulse", "metric", "card" ],
"type" : "string"
},
"type" : "array"
@@ -21111,9 +19835,6 @@
"content" : {
"type" : "object"
},
- "html" : {
- "type" : "string"
- },
"parent_comment_id" : {
"oneOf" : [ {
"description" : "value must be an integer greater than zero.",
@@ -21133,7 +19854,7 @@
"type" : "string"
}
},
- "required" : [ "target_type", "target_id", "content", "html" ],
+ "required" : [ "target_type", "target_id", "content" ],
"type" : "object"
}
}
@@ -21223,9 +19944,6 @@
"content" : {
"type" : "object"
},
- "html" : {
- "type" : "string"
- },
"is_resolved" : {
"type" : "boolean"
}
@@ -23788,10 +22506,39 @@
"tags" : [ "/api/database" ]
}
},
- "/api/database/{id}/permission/workspace/check" : {
+ "/api/database/{id}/rescan_values" : {
"post" : {
- "description" : "Check if database's connection has the required permissions to manage workspaces.\n By default it'll return the cached permission check.",
- "operationId" : "post-api-database-id-permission-workspace-check",
+ "description" : "Trigger a manual scan of the field values for this `Database`.",
+ "operationId" : "post-api-database-id-rescan_values",
+ "parameters" : [ {
+ "description" : "value must be an integer greater than zero.",
+ "in" : "path",
+ "name" : "id",
+ "required" : true,
+ "schema" : {
+ "minimum" : 1,
+ "type" : "integer"
+ }
+ } ],
+ "responses" : {
+ "2XX" : {
+ "description" : "Successful response"
+ },
+ "4XX" : {
+ "description" : "Client error response"
+ },
+ "5XX" : {
+ "description" : "Server error response"
+ }
+ },
+ "summary" : "POST /api/database/{id}/rescan_values",
+ "tags" : [ "/api/database" ]
+ }
+ },
+ "/api/database/{id}/schema" : {
+ "get" : {
+ "description" : "Return a list of Tables for a Database whose `schema` is `nil` or an empty string.\n\n Optional filters:\n - `can-query=true` - filter to only tables the user can query\n - `can-write-metadata=true` - filter to only tables the user can edit metadata for",
+ "operationId" : "get-api-database-id-schema",
"parameters" : [ {
"description" : "value must be an integer greater than zero.",
"in" : "path",
@@ -23802,12 +22549,269 @@
"type" : "integer"
}
}, {
+ "in" : "query",
+ "name" : "include_hidden",
+ "required" : true,
+ "schema" : {
+ "default" : false,
+ "oneOf" : [ {
+ "type" : "boolean"
+ }, {
+ "type" : "null"
+ } ]
+ }
+ }, {
+ "in" : "query",
+ "name" : "include_editable_data_model",
+ "required" : true,
+ "schema" : {
+ "default" : false,
+ "oneOf" : [ {
+ "type" : "boolean"
+ }, {
+ "type" : "null"
+ } ]
+ }
+ }, {
+ "in" : "query",
+ "name" : "can-query",
+ "required" : false,
+ "schema" : {
+ "oneOf" : [ {
+ "type" : "boolean"
+ }, {
+ "type" : "null"
+ } ]
+ }
+ }, {
+ "in" : "query",
+ "name" : "can-write-metadata",
+ "required" : false,
+ "schema" : {
+ "oneOf" : [ {
+ "type" : "boolean"
+ }, {
+ "type" : "null"
+ } ]
+ }
+ }, {
+ "in" : "query",
+ "name" : "include_measures",
+ "required" : false,
+ "schema" : {
+ "oneOf" : [ {
+ "type" : "boolean"
+ }, {
+ "type" : "null"
+ } ]
+ }
+ } ],
+ "responses" : {
+ "2XX" : {
+ "description" : "Successful response"
+ },
+ "4XX" : {
+ "description" : "Client error response"
+ },
+ "5XX" : {
+ "description" : "Server error response"
+ }
+ },
+ "summary" : "GET /api/database/{id}/schema",
+ "tags" : [ "/api/database" ]
+ }
+ },
+ "/api/database/{id}/schema/{schema}" : {
+ "get" : {
+ "description" : "Returns a list of Tables for the given Database `id` and `schema`.\n\n Optional filters:\n - `can-query=true` - filter to only tables the user can query\n - `can-write-metadata=true` - filter to only tables the user can edit metadata for",
+ "operationId" : "get-api-database-id-schema-schema",
+ "parameters" : [ {
+ "description" : "value must be an integer greater than zero.",
"in" : "path",
- "name" : "cached",
+ "name" : "id",
+ "required" : true,
+ "schema" : {
+ "minimum" : 1,
+ "type" : "integer"
+ }
+ }, {
+ "in" : "path",
+ "name" : "schema",
+ "required" : true,
+ "schema" : {
+ "minLength" : 1,
+ "type" : "string"
+ }
+ }, {
+ "in" : "query",
+ "name" : "include_hidden",
+ "required" : true,
+ "schema" : {
+ "default" : false,
+ "oneOf" : [ {
+ "type" : "boolean"
+ }, {
+ "type" : "null"
+ } ]
+ }
+ }, {
+ "in" : "query",
+ "name" : "include_editable_data_model",
+ "required" : true,
+ "schema" : {
+ "default" : false,
+ "oneOf" : [ {
+ "type" : "boolean"
+ }, {
+ "type" : "null"
+ } ]
+ }
+ }, {
+ "in" : "query",
+ "name" : "can-query",
"required" : false,
"schema" : {
- "default" : true,
- "type" : "boolean"
+ "oneOf" : [ {
+ "type" : "boolean"
+ }, {
+ "type" : "null"
+ } ]
+ }
+ }, {
+ "in" : "query",
+ "name" : "can-write-metadata",
+ "required" : false,
+ "schema" : {
+ "oneOf" : [ {
+ "type" : "boolean"
+ }, {
+ "type" : "null"
+ } ]
+ }
+ }, {
+ "in" : "query",
+ "name" : "include_measures",
+ "required" : false,
+ "schema" : {
+ "oneOf" : [ {
+ "type" : "boolean"
+ }, {
+ "type" : "null"
+ } ]
+ }
+ } ],
+ "responses" : {
+ "2XX" : {
+ "description" : "Successful response"
+ },
+ "4XX" : {
+ "description" : "Client error response"
+ },
+ "5XX" : {
+ "description" : "Server error response"
+ }
+ },
+ "summary" : "GET /api/database/{id}/schema/{schema}",
+ "tags" : [ "/api/database" ]
+ }
+ },
+ "/api/database/{id}/schemas" : {
+ "get" : {
+ "description" : "Returns a list of all the schemas with tables found for the database `id`. Excludes schemas with no tables.\n\n Optional filters:\n - `can-query=true` - filter to only schemas containing tables the user can query\n - `can-write-metadata=true` - filter to only schemas containing tables the user can edit metadata for",
+ "operationId" : "get-api-database-id-schemas",
+ "parameters" : [ {
+ "description" : "value must be an integer greater than zero.",
+ "in" : "path",
+ "name" : "id",
+ "required" : true,
+ "schema" : {
+ "minimum" : 1,
+ "type" : "integer"
+ }
+ }, {
+ "in" : "query",
+ "name" : "include_editable_data_model",
+ "required" : true,
+ "schema" : {
+ "default" : false,
+ "oneOf" : [ {
+ "type" : "boolean"
+ }, {
+ "type" : "null"
+ } ]
+ }
+ }, {
+ "in" : "query",
+ "name" : "include_hidden",
+ "required" : true,
+ "schema" : {
+ "default" : false,
+ "oneOf" : [ {
+ "type" : "boolean"
+ }, {
+ "type" : "null"
+ } ]
+ }
+ }, {
+ "in" : "query",
+ "name" : "can-query",
+ "required" : false,
+ "schema" : {
+ "oneOf" : [ {
+ "type" : "boolean"
+ }, {
+ "type" : "null"
+ } ]
+ }
+ }, {
+ "in" : "query",
+ "name" : "can-write-metadata",
+ "required" : false,
+ "schema" : {
+ "oneOf" : [ {
+ "type" : "boolean"
+ }, {
+ "type" : "null"
+ } ]
+ }
+ } ],
+ "responses" : {
+ "2XX" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "items" : {
+ "type" : "string"
+ },
+ "type" : "array"
+ }
+ }
+ },
+ "description" : "Successful response"
+ },
+ "4XX" : {
+ "description" : "Client error response"
+ },
+ "5XX" : {
+ "description" : "Server error response"
+ }
+ },
+ "summary" : "GET /api/database/{id}/schemas",
+ "tags" : [ "/api/database" ]
+ }
+ },
+ "/api/database/{id}/settings-available" : {
+ "get" : {
+ "description" : "Get all database-local settings and their availability for the given database.",
+ "operationId" : "get-api-database-id-settings-available",
+ "parameters" : [ {
+ "description" : "value must be an integer greater than zero.",
+ "in" : "path",
+ "name" : "id",
+ "required" : true,
+ "schema" : {
+ "minimum" : 1,
+ "type" : "integer"
}
} ],
"responses" : {
@@ -23816,17 +22820,11 @@
"application/json" : {
"schema" : {
"properties" : {
- "checked_at" : {
- "type" : "string"
- },
- "error" : {
- "type" : "string"
- },
- "status" : {
- "type" : "string"
+ "settings" : {
+ "$ref" : "#/components/schemas/metabase.warehouses-rest.api.available-settings"
}
},
- "required" : [ "status", "checked_at" ],
+ "required" : [ "settings" ],
"type" : "object"
}
}
@@ -23840,340 +22838,14 @@
"description" : "Server error response"
}
},
- "summary" : "POST /api/database/{id}/permission/workspace/check",
+ "summary" : "GET /api/database/{id}/settings-available",
"tags" : [ "/api/database" ]
}
},
- "/api/database/{id}/rescan_values" : {
+ "/api/database/{id}/sync_schema" : {
"post" : {
- "description" : "Trigger a manual scan of the field values for this `Database`.",
- "operationId" : "post-api-database-id-rescan_values",
- "parameters" : [ {
- "description" : "value must be an integer greater than zero.",
- "in" : "path",
- "name" : "id",
- "required" : true,
- "schema" : {
- "minimum" : 1,
- "type" : "integer"
- }
- } ],
- "responses" : {
- "2XX" : {
- "description" : "Successful response"
- },
- "4XX" : {
- "description" : "Client error response"
- },
- "5XX" : {
- "description" : "Server error response"
- }
- },
- "summary" : "POST /api/database/{id}/rescan_values",
- "tags" : [ "/api/database" ]
- }
- },
- "/api/database/{id}/schema" : {
- "get" : {
- "description" : "Return a list of Tables for a Database whose `schema` is `nil` or an empty string.\n\n Optional filters:\n - `can-query=true` - filter to only tables the user can query\n - `can-write-metadata=true` - filter to only tables the user can edit metadata for",
- "operationId" : "get-api-database-id-schema",
- "parameters" : [ {
- "description" : "value must be an integer greater than zero.",
- "in" : "path",
- "name" : "id",
- "required" : true,
- "schema" : {
- "minimum" : 1,
- "type" : "integer"
- }
- }, {
- "in" : "query",
- "name" : "include_hidden",
- "required" : true,
- "schema" : {
- "default" : false,
- "oneOf" : [ {
- "type" : "boolean"
- }, {
- "type" : "null"
- } ]
- }
- }, {
- "in" : "query",
- "name" : "include_editable_data_model",
- "required" : true,
- "schema" : {
- "default" : false,
- "oneOf" : [ {
- "type" : "boolean"
- }, {
- "type" : "null"
- } ]
- }
- }, {
- "in" : "query",
- "name" : "can-query",
- "required" : false,
- "schema" : {
- "oneOf" : [ {
- "type" : "boolean"
- }, {
- "type" : "null"
- } ]
- }
- }, {
- "in" : "query",
- "name" : "can-write-metadata",
- "required" : false,
- "schema" : {
- "oneOf" : [ {
- "type" : "boolean"
- }, {
- "type" : "null"
- } ]
- }
- } ],
- "responses" : {
- "2XX" : {
- "description" : "Successful response"
- },
- "4XX" : {
- "description" : "Client error response"
- },
- "5XX" : {
- "description" : "Server error response"
- }
- },
- "summary" : "GET /api/database/{id}/schema",
- "tags" : [ "/api/database" ]
- }
- },
- "/api/database/{id}/schema/{schema}" : {
- "get" : {
- "description" : "Returns a list of Tables for the given Database `id` and `schema`.\n\n Optional filters:\n - `can-query=true` - filter to only tables the user can query\n - `can-write-metadata=true` - filter to only tables the user can edit metadata for",
- "operationId" : "get-api-database-id-schema-schema",
- "parameters" : [ {
- "description" : "value must be an integer greater than zero.",
- "in" : "path",
- "name" : "id",
- "required" : true,
- "schema" : {
- "minimum" : 1,
- "type" : "integer"
- }
- }, {
- "in" : "path",
- "name" : "schema",
- "required" : true,
- "schema" : {
- "minLength" : 1,
- "type" : "string"
- }
- }, {
- "in" : "query",
- "name" : "include_hidden",
- "required" : true,
- "schema" : {
- "default" : false,
- "oneOf" : [ {
- "type" : "boolean"
- }, {
- "type" : "null"
- } ]
- }
- }, {
- "in" : "query",
- "name" : "include_editable_data_model",
- "required" : true,
- "schema" : {
- "default" : false,
- "oneOf" : [ {
- "type" : "boolean"
- }, {
- "type" : "null"
- } ]
- }
- }, {
- "in" : "query",
- "name" : "can-query",
- "required" : false,
- "schema" : {
- "oneOf" : [ {
- "type" : "boolean"
- }, {
- "type" : "null"
- } ]
- }
- }, {
- "in" : "query",
- "name" : "can-write-metadata",
- "required" : false,
- "schema" : {
- "oneOf" : [ {
- "type" : "boolean"
- }, {
- "type" : "null"
- } ]
- }
- } ],
- "responses" : {
- "2XX" : {
- "description" : "Successful response"
- },
- "4XX" : {
- "description" : "Client error response"
- },
- "5XX" : {
- "description" : "Server error response"
- }
- },
- "summary" : "GET /api/database/{id}/schema/{schema}",
- "tags" : [ "/api/database" ]
- }
- },
- "/api/database/{id}/schemas" : {
- "get" : {
- "description" : "Returns a list of all the schemas with tables found for the database `id`. Excludes schemas with no tables.\n\n Optional filters:\n - `can-query=true` - filter to only schemas containing tables the user can query\n - `can-write-metadata=true` - filter to only schemas containing tables the user can edit metadata for",
- "operationId" : "get-api-database-id-schemas",
- "parameters" : [ {
- "description" : "value must be an integer greater than zero.",
- "in" : "path",
- "name" : "id",
- "required" : true,
- "schema" : {
- "minimum" : 1,
- "type" : "integer"
- }
- }, {
- "in" : "query",
- "name" : "include_editable_data_model",
- "required" : true,
- "schema" : {
- "default" : false,
- "oneOf" : [ {
- "type" : "boolean"
- }, {
- "type" : "null"
- } ]
- }
- }, {
- "in" : "query",
- "name" : "include_hidden",
- "required" : true,
- "schema" : {
- "default" : false,
- "oneOf" : [ {
- "type" : "boolean"
- }, {
- "type" : "null"
- } ]
- }
- }, {
- "in" : "query",
- "name" : "can-query",
- "required" : false,
- "schema" : {
- "oneOf" : [ {
- "type" : "boolean"
- }, {
- "type" : "null"
- } ]
- }
- }, {
- "in" : "query",
- "name" : "can-write-metadata",
- "required" : false,
- "schema" : {
- "oneOf" : [ {
- "type" : "boolean"
- }, {
- "type" : "null"
- } ]
- }
- }, {
- "in" : "query",
- "name" : "include_workspace",
- "required" : true,
- "schema" : {
- "default" : false,
- "oneOf" : [ {
- "type" : "boolean"
- }, {
- "type" : "null"
- } ]
- }
- } ],
- "responses" : {
- "2XX" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "items" : {
- "type" : "string"
- },
- "type" : "array"
- }
- }
- },
- "description" : "Successful response"
- },
- "4XX" : {
- "description" : "Client error response"
- },
- "5XX" : {
- "description" : "Server error response"
- }
- },
- "summary" : "GET /api/database/{id}/schemas",
- "tags" : [ "/api/database" ]
- }
- },
- "/api/database/{id}/settings-available" : {
- "get" : {
- "description" : "Get all database-local settings and their availability for the given database.",
- "operationId" : "get-api-database-id-settings-available",
- "parameters" : [ {
- "description" : "value must be an integer greater than zero.",
- "in" : "path",
- "name" : "id",
- "required" : true,
- "schema" : {
- "minimum" : 1,
- "type" : "integer"
- }
- } ],
- "responses" : {
- "2XX" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "properties" : {
- "settings" : {
- "$ref" : "#/components/schemas/metabase.warehouses-rest.api.available-settings"
- }
- },
- "required" : [ "settings" ],
- "type" : "object"
- }
- }
- },
- "description" : "Successful response"
- },
- "4XX" : {
- "description" : "Client error response"
- },
- "5XX" : {
- "description" : "Server error response"
- }
- },
- "summary" : "GET /api/database/{id}/settings-available",
- "tags" : [ "/api/database" ]
- }
- },
- "/api/database/{id}/sync_schema" : {
- "post" : {
- "description" : "Trigger a manual update of the schema metadata for this `Database`.",
- "operationId" : "post-api-database-id-sync_schema",
+ "description" : "Trigger a manual update of the schema metadata for this `Database`.",
+ "operationId" : "post-api-database-id-sync_schema",
"parameters" : [ {
"description" : "value must be an integer greater than zero.",
"in" : "path",
@@ -25665,68 +24337,47 @@
"tags" : [ "/api/ee/advanced-permissions/impersonation" ]
}
},
- "/api/ee/ai-entity-analysis/analyze-chart" : {
- "post" : {
- "description" : "Analyze a chart image using an AI vision model. This function sends the image data to a separate external AI service\n for analysis.",
- "operationId" : "post-api-ee-ai-entity-analysis-analyze-chart",
+ "/api/ee/ai-controls/permissions" : {
+ "get" : {
+ "description" : "List all metabot permissions for all groups, filling in defaults for missing entries.",
+ "operationId" : "get-api-ee-ai-controls-permissions",
"parameters" : [ ],
- "requestBody" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "properties" : {
- "description" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "image_base64" : {
- "type" : "string"
- },
- "name" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "timeline_events" : {
- "oneOf" : [ {
+ "responses" : {
+ "2XX" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "properties" : {
+ "advanced" : {
+ "type" : "boolean"
+ },
+ "permissions" : {
"items" : {
"properties" : {
- "description" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
+ "group_id" : {
+ "minimum" : 1,
+ "type" : "integer"
},
- "name" : {
+ "perm_type" : {
+ "enum" : [ "permission/metabot", "permission/metabot-nlq", "permission/metabot-other-tools", "permission/metabot-sql-generation" ],
"type" : "string"
},
- "timestamp" : {
+ "perm_value" : {
+ "enum" : [ "yes", "no" ],
"type" : "string"
}
},
- "required" : [ "name", "timestamp" ],
+ "required" : [ "group_id", "perm_type", "perm_value" ],
"type" : "object"
},
"type" : "array"
- }, {
- "type" : "null"
- } ]
- }
- },
- "required" : [ "image_base64" ],
- "type" : "object"
+ }
+ },
+ "required" : [ "permissions", "advanced" ],
+ "type" : "object"
+ }
}
- }
- }
- },
- "responses" : {
- "2XX" : {
+ },
"description" : "Successful response"
},
"4XX" : {
@@ -25736,36 +24387,41 @@
"description" : "Server error response"
}
},
- "summary" : "POST /api/ee/ai-entity-analysis/analyze-chart",
- "tags" : [ "/api/ee/ai-entity-analysis" ]
- }
- },
- "/api/ee/ai-sql-fixer/fix" : {
- "post" : {
- "description" : "Suggest fixes for a SQL query.",
- "operationId" : "post-api-ee-ai-sql-fixer-fix",
+ "summary" : "GET /api/ee/ai-controls/permissions",
+ "tags" : [ "/api/ee/ai-controls/permissions" ]
+ },
+ "put" : {
+ "description" : "Update metabot permissions for all groups. Upserts each permission entry and returns the full\n permissions list with defaults filled in.",
+ "operationId" : "put-api-ee-ai-controls-permissions",
"parameters" : [ ],
"requestBody" : {
"content" : {
"application/json" : {
"schema" : {
"properties" : {
- "error_message" : {
- "type" : "string"
- },
- "query" : {
- "properties" : {
- "database" : {
- "description" : "value must be an integer greater than zero.",
- "minimum" : 1,
- "type" : "integer"
- }
+ "permissions" : {
+ "items" : {
+ "properties" : {
+ "group_id" : {
+ "minimum" : 1,
+ "type" : "integer"
+ },
+ "perm_type" : {
+ "enum" : [ "permission/metabot-nlq", "permission/metabot-sql-generation", "permission/metabot-other-tools", "permission/metabot" ],
+ "type" : "string"
+ },
+ "perm_value" : {
+ "enum" : [ "yes", "no" ],
+ "type" : "string"
+ }
+ },
+ "required" : [ "group_id", "perm_type", "perm_value" ],
+ "type" : "object"
},
- "required" : [ "database" ],
- "type" : "object"
+ "type" : "array"
}
},
- "required" : [ "query", "error_message" ],
+ "required" : [ "permissions" ],
"type" : "object"
}
}
@@ -25773,6 +24429,40 @@
},
"responses" : {
"2XX" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "properties" : {
+ "advanced" : {
+ "type" : "boolean"
+ },
+ "permissions" : {
+ "items" : {
+ "properties" : {
+ "group_id" : {
+ "minimum" : 1,
+ "type" : "integer"
+ },
+ "perm_type" : {
+ "enum" : [ "permission/metabot", "permission/metabot-nlq", "permission/metabot-other-tools", "permission/metabot-sql-generation" ],
+ "type" : "string"
+ },
+ "perm_value" : {
+ "enum" : [ "yes", "no" ],
+ "type" : "string"
+ }
+ },
+ "required" : [ "group_id", "perm_type", "perm_value" ],
+ "type" : "object"
+ },
+ "type" : "array"
+ }
+ },
+ "required" : [ "permissions", "advanced" ],
+ "type" : "object"
+ }
+ }
+ },
"description" : "Successful response"
},
"4XX" : {
@@ -25782,38 +24472,51 @@
"description" : "Server error response"
}
},
- "summary" : "POST /api/ee/ai-sql-fixer/fix",
- "tags" : [ "/api/ee/ai-sql-fixer" ]
+ "summary" : "PUT /api/ee/ai-controls/permissions",
+ "tags" : [ "/api/ee/ai-controls/permissions" ]
}
},
- "/api/ee/ai-sql-generation/generate" : {
- "post" : {
- "description" : "Generate a SQL query.",
- "operationId" : "post-api-ee-ai-sql-generation-generate",
+ "/api/ee/ai-controls/permissions/advanced" : {
+ "delete" : {
+ "description" : "Switch back to simple permissions. Removes any custom permissions from all specific groups, keeping only Admins and All Users.",
+ "operationId" : "delete-api-ee-ai-controls-permissions-advanced",
"parameters" : [ ],
- "requestBody" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "properties" : {
- "database_id" : {
- "description" : "value must be an integer greater than zero.",
- "minimum" : 1,
- "type" : "integer"
- },
- "prompt" : {
- "minLength" : 1,
- "type" : "string"
- }
- },
- "required" : [ "prompt", "database_id" ],
- "type" : "object"
- }
- }
- }
- },
"responses" : {
"2XX" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "properties" : {
+ "advanced" : {
+ "type" : "boolean"
+ },
+ "permissions" : {
+ "items" : {
+ "properties" : {
+ "group_id" : {
+ "minimum" : 1,
+ "type" : "integer"
+ },
+ "perm_type" : {
+ "enum" : [ "permission/metabot", "permission/metabot-nlq", "permission/metabot-other-tools", "permission/metabot-sql-generation" ],
+ "type" : "string"
+ },
+ "perm_value" : {
+ "enum" : [ "yes", "no" ],
+ "type" : "string"
+ }
+ },
+ "required" : [ "group_id", "perm_type", "perm_value" ],
+ "type" : "object"
+ },
+ "type" : "array"
+ }
+ },
+ "required" : [ "permissions", "advanced" ],
+ "type" : "object"
+ }
+ }
+ },
"description" : "Successful response"
},
"4XX" : {
@@ -25823,14 +24526,12 @@
"description" : "Server error response"
}
},
- "summary" : "POST /api/ee/ai-sql-generation/generate",
- "tags" : [ "/api/ee/ai-sql-generation" ]
- }
- },
- "/api/ee/audit-app/analytics-dev/export" : {
+ "summary" : "DELETE /api/ee/ai-controls/permissions/advanced",
+ "tags" : [ "/api/ee/ai-controls/permissions" ]
+ },
"post" : {
- "description" : "Export analytics content as a .tar.gz file for local development.\n\n Only available when MB_ANALYTICS_DEV_MODE=true. Returns a tarball containing\n the analytics YAMLs in canonical format, ready to commit to source control.\n\n Requires superuser permissions.",
- "operationId" : "post-api-ee-audit-app-analytics-dev-export",
+ "description" : "Switch to advanced group-level permissions. Removes any custom permissions from the All Users group.",
+ "operationId" : "post-api-ee-ai-controls-permissions-advanced",
"parameters" : [ ],
"responses" : {
"2XX" : {
@@ -25838,9 +24539,32 @@
"application/json" : {
"schema" : {
"properties" : {
- "body" : { }
+ "advanced" : {
+ "type" : "boolean"
+ },
+ "permissions" : {
+ "items" : {
+ "properties" : {
+ "group_id" : {
+ "minimum" : 1,
+ "type" : "integer"
+ },
+ "perm_type" : {
+ "enum" : [ "permission/metabot", "permission/metabot-nlq", "permission/metabot-other-tools", "permission/metabot-sql-generation" ],
+ "type" : "string"
+ },
+ "perm_value" : {
+ "enum" : [ "yes", "no" ],
+ "type" : "string"
+ }
+ },
+ "required" : [ "group_id", "perm_type", "perm_value" ],
+ "type" : "object"
+ },
+ "type" : "array"
+ }
},
- "required" : [ "body" ],
+ "required" : [ "permissions", "advanced" ],
"type" : "object"
}
}
@@ -25854,17 +24578,38 @@
"description" : "Server error response"
}
},
- "summary" : "POST /api/ee/audit-app/analytics-dev/export",
- "tags" : [ "/api/ee/audit-app/analytics-dev" ]
+ "summary" : "POST /api/ee/ai-controls/permissions/advanced",
+ "tags" : [ "/api/ee/ai-controls/permissions" ]
}
},
- "/api/ee/audit-app/user/audit-info" : {
+ "/api/ee/ai-controls/usage/group" : {
"get" : {
- "description" : "Gets audit info for the current user if he has permissions to access the audit collection.\n Otherwise return an empty map.",
- "operationId" : "get-api-ee-audit-app-user-audit-info",
+ "description" : "Get all group-level metabot usage limits.",
+ "operationId" : "get-api-ee-ai-controls-usage-group",
"parameters" : [ ],
"responses" : {
"2XX" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "items" : {
+ "properties" : {
+ "group_id" : {
+ "minimum" : 1,
+ "type" : "integer"
+ },
+ "max_usage" : {
+ "minimum" : 0,
+ "type" : "integer"
+ }
+ },
+ "required" : [ "group_id", "max_usage" ],
+ "type" : "object"
+ },
+ "type" : "array"
+ }
+ }
+ },
"description" : "Successful response"
},
"4XX" : {
@@ -25874,18 +24619,17 @@
"description" : "Server error response"
}
},
- "summary" : "GET /api/ee/audit-app/user/audit-info",
- "tags" : [ "/api/ee/audit-app/user" ]
+ "summary" : "GET /api/ee/ai-controls/usage/group",
+ "tags" : [ "/api/ee/ai-controls/usage" ]
}
},
- "/api/ee/audit-app/user/{id}/subscriptions" : {
- "delete" : {
- "description" : "Delete all Alert and DashboardSubscription subscriptions for a User (i.e., so they will no longer receive them).\n Archive all Alerts and DashboardSubscriptions created by the User. Only allowed for admins or for the current user.",
- "operationId" : "delete-api-ee-audit-app-user-id-subscriptions",
+ "/api/ee/ai-controls/usage/group/{group-id}" : {
+ "get" : {
+ "description" : "Get the metabot usage limit for a specific group. Returns `max_usage: null` if no limit is set.",
+ "operationId" : "get-api-ee-ai-controls-usage-group-group-id",
"parameters" : [ {
- "description" : "value must be an integer greater than zero.",
"in" : "path",
- "name" : "id",
+ "name" : "group-id",
"required" : true,
"schema" : {
"minimum" : 1,
@@ -25894,6 +24638,28 @@
} ],
"responses" : {
"2XX" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "properties" : {
+ "group_id" : {
+ "minimum" : 1,
+ "type" : "integer"
+ },
+ "max_usage" : {
+ "oneOf" : [ {
+ "minimum" : 0,
+ "type" : "integer"
+ }, {
+ "type" : "null"
+ } ]
+ }
+ },
+ "required" : [ "group_id", "max_usage" ],
+ "type" : "object"
+ }
+ }
+ },
"description" : "Successful response"
},
"4XX" : {
@@ -25903,105 +24669,36 @@
"description" : "Server error response"
}
},
- "summary" : "DELETE /api/ee/audit-app/user/{id}/subscriptions",
- "tags" : [ "/api/ee/audit-app/user" ]
- }
- },
- "/api/ee/autodescribe/card/summarize" : {
- "post" : {
- "description" : "Summarize a question.",
- "operationId" : "post-api-ee-autodescribe-card-summarize",
- "parameters" : [ ],
+ "summary" : "GET /api/ee/ai-controls/usage/group/{group-id}",
+ "tags" : [ "/api/ee/ai-controls/usage" ]
+ },
+ "put" : {
+ "description" : "Set or update the metabot usage limit for a specific group. Pass `max_usage: null` to remove the limit.",
+ "operationId" : "put-api-ee-ai-controls-usage-group-group-id",
+ "parameters" : [ {
+ "in" : "path",
+ "name" : "group-id",
+ "required" : true,
+ "schema" : {
+ "minimum" : 1,
+ "type" : "integer"
+ }
+ } ],
"requestBody" : {
"content" : {
"application/json" : {
"schema" : {
"properties" : {
- "cache_ttl" : {
- "oneOf" : [ {
- "description" : "value must be an integer greater than zero.",
- "minimum" : 1,
- "type" : "integer"
- }, {
- "type" : "null"
- } ]
- },
- "collection_id" : {
- "oneOf" : [ {
- "description" : "value must be an integer greater than zero.",
- "minimum" : 1,
- "type" : "integer"
- }, {
- "type" : "null"
- } ]
- },
- "collection_position" : {
+ "max_usage" : {
"oneOf" : [ {
- "description" : "value must be an integer greater than zero.",
- "minimum" : 1,
+ "minimum" : 0,
"type" : "integer"
}, {
"type" : "null"
} ]
- },
- "dataset" : {
- "oneOf" : [ {
- "type" : "boolean"
- }, {
- "type" : "null"
- } ]
- },
- "dataset_query" : {
- "description" : "Value must be a map.",
- "properties" : { },
- "type" : "object"
- },
- "description" : {
- "oneOf" : [ {
- "minLength" : 1,
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "display" : {
- "minLength" : 1,
- "type" : "string"
- },
- "parameter_mappings" : {
- "oneOf" : [ {
- "items" : {
- "$ref" : "#/components/schemas/metabase.parameters.schema.parameter-mapping"
- },
- "type" : "array"
- }, {
- "type" : "null"
- } ]
- },
- "parameters" : {
- "oneOf" : [ {
- "items" : {
- "$ref" : "#/components/schemas/metabase.parameters.schema.parameter"
- },
- "type" : "array"
- }, {
- "type" : "null"
- } ]
- },
- "result_metadata" : {
- "oneOf" : [ {
- "$ref" : "#/components/schemas/metabase.analyze.query-results.ResultsMetadata"
- }, {
- "type" : "null"
- } ]
- },
- "visualization_settings" : {
- "description" : "Value must be a map.",
- "properties" : { },
- "type" : "object"
}
},
- "required" : [ "dataset_query", "display", "visualization_settings" ],
+ "required" : [ "max_usage" ],
"type" : "object"
}
}
@@ -26009,6 +24706,28 @@
},
"responses" : {
"2XX" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "properties" : {
+ "group_id" : {
+ "minimum" : 1,
+ "type" : "integer"
+ },
+ "max_usage" : {
+ "oneOf" : [ {
+ "minimum" : 0,
+ "type" : "integer"
+ }, {
+ "type" : "null"
+ } ]
+ }
+ },
+ "required" : [ "group_id", "max_usage" ],
+ "type" : "object"
+ }
+ }
+ },
"description" : "Successful response"
},
"4XX" : {
@@ -26018,26 +24737,35 @@
"description" : "Server error response"
}
},
- "summary" : "POST /api/ee/autodescribe/card/summarize",
- "tags" : [ "/api/ee/autodescribe" ]
+ "summary" : "PUT /api/ee/ai-controls/usage/group/{group-id}",
+ "tags" : [ "/api/ee/ai-controls/usage" ]
}
},
- "/api/ee/autodescribe/dashboard/summarize/{id}" : {
- "post" : {
- "description" : "Provide a summary of a dashboard.",
- "operationId" : "post-api-ee-autodescribe-dashboard-summarize-id",
- "parameters" : [ {
- "description" : "value must be an integer greater than zero.",
- "in" : "path",
- "name" : "id",
- "required" : true,
- "schema" : {
- "minimum" : 1,
- "type" : "integer"
- }
- } ],
+ "/api/ee/ai-controls/usage/instance" : {
+ "get" : {
+ "description" : "Get the instance-wide metabot usage limit. Returns `max_usage: null` if no limit is set (unlimited).",
+ "operationId" : "get-api-ee-ai-controls-usage-instance",
+ "parameters" : [ ],
"responses" : {
"2XX" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "properties" : {
+ "max_usage" : {
+ "oneOf" : [ {
+ "minimum" : 0,
+ "type" : "integer"
+ }, {
+ "type" : "null"
+ } ]
+ }
+ },
+ "required" : [ "max_usage" ],
+ "type" : "object"
+ }
+ }
+ },
"description" : "Successful response"
},
"4XX" : {
@@ -26047,17 +24775,53 @@
"description" : "Server error response"
}
},
- "summary" : "POST /api/ee/autodescribe/dashboard/summarize/{id}",
- "tags" : [ "/api/ee/autodescribe" ]
- }
- },
- "/api/ee/billing" : {
- "get" : {
- "description" : "Get billing information. This acts as a proxy between `metabase-billing-info-url` and the client,\n using the embedding token and signed in user's email to fetch the billing information.",
- "operationId" : "get-api-ee-billing",
+ "summary" : "GET /api/ee/ai-controls/usage/instance",
+ "tags" : [ "/api/ee/ai-controls/usage" ]
+ },
+ "put" : {
+ "description" : "Set or update the instance-wide metabot usage limit. Pass `max_usage: null` to remove the limit (unlimited).",
+ "operationId" : "put-api-ee-ai-controls-usage-instance",
"parameters" : [ ],
+ "requestBody" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "properties" : {
+ "max_usage" : {
+ "oneOf" : [ {
+ "minimum" : 0,
+ "type" : "integer"
+ }, {
+ "type" : "null"
+ } ]
+ }
+ },
+ "required" : [ "max_usage" ],
+ "type" : "object"
+ }
+ }
+ }
+ },
"responses" : {
"2XX" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "properties" : {
+ "max_usage" : {
+ "oneOf" : [ {
+ "minimum" : 0,
+ "type" : "integer"
+ }, {
+ "type" : "null"
+ } ]
+ }
+ },
+ "required" : [ "max_usage" ],
+ "type" : "object"
+ }
+ }
+ },
"description" : "Successful response"
},
"4XX" : {
@@ -26067,17 +24831,38 @@
"description" : "Server error response"
}
},
- "summary" : "GET /api/ee/billing",
- "tags" : [ "/api/ee/billing" ]
+ "summary" : "PUT /api/ee/ai-controls/usage/instance",
+ "tags" : [ "/api/ee/ai-controls/usage" ]
}
},
- "/api/ee/cloud-add-ons/addons" : {
+ "/api/ee/ai-controls/usage/tenant" : {
"get" : {
- "description" : "Get addons information from the Metabase Store API.",
- "operationId" : "get-api-ee-cloud-add-ons-addons",
+ "description" : "Get all tenant-level metabot usage limits.",
+ "operationId" : "get-api-ee-ai-controls-usage-tenant",
"parameters" : [ ],
"responses" : {
"2XX" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "items" : {
+ "properties" : {
+ "max_usage" : {
+ "minimum" : 0,
+ "type" : "integer"
+ },
+ "tenant_id" : {
+ "minimum" : 1,
+ "type" : "integer"
+ }
+ },
+ "required" : [ "tenant_id", "max_usage" ],
+ "type" : "object"
+ },
+ "type" : "array"
+ }
+ }
+ },
"description" : "Successful response"
},
"4XX" : {
@@ -26087,17 +24872,47 @@
"description" : "Server error response"
}
},
- "summary" : "GET /api/ee/cloud-add-ons/addons",
- "tags" : [ "/api/ee/cloud-add-ons" ]
+ "summary" : "GET /api/ee/ai-controls/usage/tenant",
+ "tags" : [ "/api/ee/ai-controls/usage" ]
}
},
- "/api/ee/cloud-add-ons/plans" : {
+ "/api/ee/ai-controls/usage/tenant/{tenant-id}" : {
"get" : {
- "description" : "Get plans information from the Metabase Store API.",
- "operationId" : "get-api-ee-cloud-add-ons-plans",
- "parameters" : [ ],
+ "description" : "Get the metabot usage limit for a specific tenant. Returns `max_usage: null` if no limit is set.",
+ "operationId" : "get-api-ee-ai-controls-usage-tenant-tenant-id",
+ "parameters" : [ {
+ "in" : "path",
+ "name" : "tenant-id",
+ "required" : true,
+ "schema" : {
+ "minimum" : 1,
+ "type" : "integer"
+ }
+ } ],
"responses" : {
"2XX" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "properties" : {
+ "max_usage" : {
+ "oneOf" : [ {
+ "minimum" : 0,
+ "type" : "integer"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "tenant_id" : {
+ "minimum" : 1,
+ "type" : "integer"
+ }
+ },
+ "required" : [ "tenant_id", "max_usage" ],
+ "type" : "object"
+ }
+ }
+ },
"description" : "Successful response"
},
"4XX" : {
@@ -26107,21 +24922,19 @@
"description" : "Server error response"
}
},
- "summary" : "GET /api/ee/cloud-add-ons/plans",
- "tags" : [ "/api/ee/cloud-add-ons" ]
- }
- },
- "/api/ee/cloud-add-ons/{product-type}" : {
- "post" : {
- "description" : "Purchase an add-on.",
- "operationId" : "post-api-ee-cloud-add-ons-product-type",
+ "summary" : "GET /api/ee/ai-controls/usage/tenant/{tenant-id}",
+ "tags" : [ "/api/ee/ai-controls/usage" ]
+ },
+ "put" : {
+ "description" : "Set or update the metabot usage limit for a specific tenant. Pass `max_usage: null` to remove the limit.",
+ "operationId" : "put-api-ee-ai-controls-usage-tenant-tenant-id",
"parameters" : [ {
"in" : "path",
- "name" : "product-type",
+ "name" : "tenant-id",
"required" : true,
"schema" : {
- "enum" : [ "metabase-ai", "metabase-ai-tiered", "python-execution", "transforms", "transforms-basic", "transforms-advanced" ],
- "type" : "string"
+ "minimum" : 1,
+ "type" : "integer"
}
} ],
"requestBody" : {
@@ -26129,21 +24942,16 @@
"application/json" : {
"schema" : {
"properties" : {
- "quantity" : {
+ "max_usage" : {
"oneOf" : [ {
+ "minimum" : 0,
"type" : "integer"
}, {
"type" : "null"
} ]
- },
- "terms_of_service" : {
- "oneOf" : [ {
- "type" : "boolean"
- }, {
- "type" : "null"
- } ]
}
},
+ "required" : [ "max_usage" ],
"type" : "object"
}
}
@@ -26151,6 +24959,28 @@
},
"responses" : {
"2XX" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "properties" : {
+ "max_usage" : {
+ "oneOf" : [ {
+ "minimum" : 0,
+ "type" : "integer"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "tenant_id" : {
+ "minimum" : 1,
+ "type" : "integer"
+ }
+ },
+ "required" : [ "tenant_id", "max_usage" ],
+ "type" : "object"
+ }
+ }
+ },
"description" : "Successful response"
},
"4XX" : {
@@ -26160,7 +24990,240 @@
"description" : "Server error response"
}
},
- "summary" : "POST /api/ee/cloud-add-ons/{product-type}",
+ "summary" : "PUT /api/ee/ai-controls/usage/tenant/{tenant-id}",
+ "tags" : [ "/api/ee/ai-controls/usage" ]
+ }
+ },
+ "/api/ee/audit-app/analytics-dev/export" : {
+ "post" : {
+ "description" : "Export analytics content as a .tar.gz file for local development.\n\n Only available when MB_ANALYTICS_DEV_MODE=true. Returns a tarball containing\n the analytics YAMLs in canonical format, ready to commit to source control.\n\n Requires superuser permissions.",
+ "operationId" : "post-api-ee-audit-app-analytics-dev-export",
+ "parameters" : [ ],
+ "responses" : {
+ "2XX" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "properties" : {
+ "body" : { }
+ },
+ "required" : [ "body" ],
+ "type" : "object"
+ }
+ }
+ },
+ "description" : "Successful response"
+ },
+ "4XX" : {
+ "description" : "Client error response"
+ },
+ "5XX" : {
+ "description" : "Server error response"
+ }
+ },
+ "summary" : "POST /api/ee/audit-app/analytics-dev/export",
+ "tags" : [ "/api/ee/audit-app/analytics-dev" ]
+ }
+ },
+ "/api/ee/audit-app/user/audit-info" : {
+ "get" : {
+ "description" : "Gets audit info for the current user if he has permissions to access the audit collection.\n Otherwise return an empty map.",
+ "operationId" : "get-api-ee-audit-app-user-audit-info",
+ "parameters" : [ ],
+ "responses" : {
+ "2XX" : {
+ "description" : "Successful response"
+ },
+ "4XX" : {
+ "description" : "Client error response"
+ },
+ "5XX" : {
+ "description" : "Server error response"
+ }
+ },
+ "summary" : "GET /api/ee/audit-app/user/audit-info",
+ "tags" : [ "/api/ee/audit-app/user" ]
+ }
+ },
+ "/api/ee/audit-app/user/{id}/subscriptions" : {
+ "delete" : {
+ "description" : "Delete all Alert and DashboardSubscription subscriptions for a User (i.e., so they will no longer receive them).\n Archive all Alerts and DashboardSubscriptions created by the User. Only allowed for admins or for the current user.",
+ "operationId" : "delete-api-ee-audit-app-user-id-subscriptions",
+ "parameters" : [ {
+ "description" : "value must be an integer greater than zero.",
+ "in" : "path",
+ "name" : "id",
+ "required" : true,
+ "schema" : {
+ "minimum" : 1,
+ "type" : "integer"
+ }
+ } ],
+ "responses" : {
+ "2XX" : {
+ "description" : "Successful response"
+ },
+ "4XX" : {
+ "description" : "Client error response"
+ },
+ "5XX" : {
+ "description" : "Server error response"
+ }
+ },
+ "summary" : "DELETE /api/ee/audit-app/user/{id}/subscriptions",
+ "tags" : [ "/api/ee/audit-app/user" ]
+ }
+ },
+ "/api/ee/billing" : {
+ "get" : {
+ "description" : "Get billing information. This acts as a proxy between `metabase-billing-info-url` and the client,\n using the embedding token and signed in user's email to fetch the billing information.",
+ "operationId" : "get-api-ee-billing",
+ "parameters" : [ ],
+ "responses" : {
+ "2XX" : {
+ "description" : "Successful response"
+ },
+ "4XX" : {
+ "description" : "Client error response"
+ },
+ "5XX" : {
+ "description" : "Server error response"
+ }
+ },
+ "summary" : "GET /api/ee/billing",
+ "tags" : [ "/api/ee/billing" ]
+ }
+ },
+ "/api/ee/cloud-add-ons/addons" : {
+ "get" : {
+ "description" : "Get addons information from the Metabase Store API.",
+ "operationId" : "get-api-ee-cloud-add-ons-addons",
+ "parameters" : [ ],
+ "responses" : {
+ "2XX" : {
+ "description" : "Successful response"
+ },
+ "4XX" : {
+ "description" : "Client error response"
+ },
+ "5XX" : {
+ "description" : "Server error response"
+ }
+ },
+ "summary" : "GET /api/ee/cloud-add-ons/addons",
+ "tags" : [ "/api/ee/cloud-add-ons" ]
+ }
+ },
+ "/api/ee/cloud-add-ons/plans" : {
+ "get" : {
+ "description" : "Get plans information from the Metabase Store API.",
+ "operationId" : "get-api-ee-cloud-add-ons-plans",
+ "parameters" : [ ],
+ "responses" : {
+ "2XX" : {
+ "description" : "Successful response"
+ },
+ "4XX" : {
+ "description" : "Client error response"
+ },
+ "5XX" : {
+ "description" : "Server error response"
+ }
+ },
+ "summary" : "GET /api/ee/cloud-add-ons/plans",
+ "tags" : [ "/api/ee/cloud-add-ons" ]
+ }
+ },
+ "/api/ee/cloud-add-ons/{product-type}" : {
+ "delete" : {
+ "description" : "Remove an add-on.",
+ "operationId" : "delete-api-ee-cloud-add-ons-product-type",
+ "parameters" : [ {
+ "in" : "path",
+ "name" : "product-type",
+ "required" : true,
+ "schema" : {
+ "enum" : [ "metabase-ai", "metabase-ai-tiered", "metabase-ai-managed", "python-execution", "transforms", "transforms-basic", "transforms-advanced", "transforms-basic-metered", "transforms-advanced-metered" ],
+ "type" : "string"
+ }
+ } ],
+ "responses" : {
+ "2XX" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "properties" : {
+ "body" : { },
+ "status" : {
+ "type" : "integer"
+ }
+ },
+ "required" : [ "status", "body" ],
+ "type" : "object"
+ }
+ }
+ },
+ "description" : "Successful response"
+ },
+ "4XX" : {
+ "description" : "Client error response"
+ },
+ "5XX" : {
+ "description" : "Server error response"
+ }
+ },
+ "summary" : "DELETE /api/ee/cloud-add-ons/{product-type}",
+ "tags" : [ "/api/ee/cloud-add-ons" ]
+ },
+ "post" : {
+ "description" : "Purchase an add-on.",
+ "operationId" : "post-api-ee-cloud-add-ons-product-type",
+ "parameters" : [ {
+ "in" : "path",
+ "name" : "product-type",
+ "required" : true,
+ "schema" : {
+ "enum" : [ "metabase-ai", "metabase-ai-tiered", "metabase-ai-managed", "python-execution", "transforms", "transforms-basic", "transforms-advanced", "transforms-basic-metered", "transforms-advanced-metered" ],
+ "type" : "string"
+ }
+ } ],
+ "requestBody" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "properties" : {
+ "quantity" : {
+ "oneOf" : [ {
+ "type" : "integer"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "terms_of_service" : {
+ "oneOf" : [ {
+ "type" : "boolean"
+ }, {
+ "type" : "null"
+ } ]
+ }
+ },
+ "type" : "object"
+ }
+ }
+ }
+ },
+ "responses" : {
+ "2XX" : {
+ "description" : "Successful response"
+ },
+ "4XX" : {
+ "description" : "Client error response"
+ },
+ "5XX" : {
+ "description" : "Server error response"
+ }
+ },
+ "summary" : "POST /api/ee/cloud-add-ons/{product-type}",
"tags" : [ "/api/ee/cloud-add-ons" ]
}
},
@@ -26353,62 +25416,88 @@
"tags" : [ "/api/ee/content-translation" ]
}
},
- "/api/ee/data-studio/table/publish-tables" : {
- "post" : {
- "description" : "Set collection for each of selected tables and all upstream dependencies recursively.",
- "operationId" : "post-api-ee-data-studio-table-publish-tables",
- "parameters" : [ ],
- "requestBody" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "$ref" : "#/components/schemas/metabase-enterprise.data-studio.api.table.table-selectors"
- }
- }
- }
- },
- "responses" : {
- "2XX" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "$ref" : "#/components/schemas/metabase-enterprise.data-studio.api.table.publish-tables-response"
- }
- }
- },
- "description" : "Successful response"
- },
- "4XX" : {
- "description" : "Client error response"
- },
- "5XX" : {
- "description" : "Server error response"
- }
- },
- "summary" : "POST /api/ee/data-studio/table/publish-tables",
- "tags" : [ "/api/ee/data-studio/table" ]
- }
- },
- "/api/ee/data-studio/table/unpublish-tables" : {
- "post" : {
- "description" : "Unset collection for each of selected tables and all downstream dependents recursively.",
- "operationId" : "post-api-ee-data-studio-table-unpublish-tables",
+ "/api/ee/custom-viz-plugin" : {
+ "get" : {
+ "description" : "List all registered custom visualization plugins.",
+ "operationId" : "get-api-ee-custom-viz-plugin",
"parameters" : [ ],
- "requestBody" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "$ref" : "#/components/schemas/metabase-enterprise.data-studio.api.table.table-selectors"
- }
- }
- }
- },
"responses" : {
"2XX" : {
"content" : {
"application/json" : {
"schema" : {
- "type" : "null"
+ "items" : {
+ "properties" : {
+ "bundle_hash" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "created_at" : { },
+ "dev_bundle_url" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "dev_only" : {
+ "type" : "boolean"
+ },
+ "display_name" : {
+ "minLength" : 1,
+ "type" : "string"
+ },
+ "enabled" : {
+ "type" : "boolean"
+ },
+ "error_message" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "icon" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "id" : {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
+ },
+ "identifier" : {
+ "minLength" : 1,
+ "type" : "string"
+ },
+ "manifest" : {
+ "oneOf" : [ { }, {
+ "type" : "null"
+ } ]
+ },
+ "metabase_version" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "status" : {
+ "enum" : [ "active", "error" ],
+ "type" : "string"
+ },
+ "updated_at" : { }
+ },
+ "required" : [ "id", "display_name", "identifier", "status", "enabled", "dev_only", "created_at", "updated_at" ],
+ "type" : "object"
+ },
+ "type" : "array"
}
}
},
@@ -26421,70 +25510,30 @@
"description" : "Server error response"
}
},
- "summary" : "POST /api/ee/data-studio/table/unpublish-tables",
- "tags" : [ "/api/ee/data-studio/table" ]
- }
- },
- "/api/ee/database-replication/connection/{database-id}" : {
- "delete" : {
- "description" : "Delete PG replication connection for the specified database.",
- "operationId" : "delete-api-ee-database-replication-connection-database-id",
- "parameters" : [ {
- "description" : "value must be an integer greater than zero.",
- "in" : "path",
- "name" : "database-id",
- "required" : true,
- "schema" : {
- "minimum" : 1,
- "type" : "integer"
- }
- } ],
- "responses" : {
- "2XX" : {
- "description" : "Successful response"
- },
- "4XX" : {
- "description" : "Client error response"
- },
- "5XX" : {
- "description" : "Server error response"
- }
- },
- "summary" : "DELETE /api/ee/database-replication/connection/{database-id}",
- "tags" : [ "/api/ee/database-replication" ]
+ "summary" : "GET /api/ee/custom-viz-plugin",
+ "tags" : [ "/api/ee/custom-viz-plugin" ]
},
"post" : {
- "description" : "Create a new PG replication connection for the specified database.",
- "operationId" : "post-api-ee-database-replication-connection-database-id",
- "parameters" : [ {
- "description" : "value must be an integer greater than zero.",
- "in" : "path",
- "name" : "database-id",
- "required" : true,
- "schema" : {
- "minimum" : 1,
- "type" : "integer"
- }
- } ],
+ "description" : "Register a new custom visualization plugin from an uploaded tar.gz bundle.\n\n The archive must contain `metabase-plugin.json` at the root and\n `dist/index.js` for the JS bundle, plus any whitelisted assets under\n `dist/assets/`. The plugin's `identifier` is taken from the manifest's `name`\n field.",
+ "operationId" : "post-api-ee-custom-viz-plugin",
+ "parameters" : [ ],
"requestBody" : {
"content" : {
- "application/json" : {
+ "multipart/form-data" : {
"schema" : {
"properties" : {
- "replicationSchemaFilters" : {
+ "file" : {
"properties" : {
- "schema-filters-patterns" : {
+ "filename" : {
"type" : "string"
},
- "schema-filters-type" : {
- "enum" : [ "inclusion", "exclusion", "all" ],
- "type" : "string"
- }
+ "tempfile" : { }
},
- "required" : [ "schema-filters-type", "schema-filters-patterns" ],
+ "required" : [ "filename", "tempfile" ],
"type" : "object"
}
},
+ "required" : [ "file" ],
"type" : "object"
}
}
@@ -26492,6 +25541,81 @@
},
"responses" : {
"2XX" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "properties" : {
+ "bundle_hash" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "created_at" : { },
+ "dev_bundle_url" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "dev_only" : {
+ "type" : "boolean"
+ },
+ "display_name" : {
+ "minLength" : 1,
+ "type" : "string"
+ },
+ "enabled" : {
+ "type" : "boolean"
+ },
+ "error_message" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "icon" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "id" : {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
+ },
+ "identifier" : {
+ "minLength" : 1,
+ "type" : "string"
+ },
+ "manifest" : {
+ "oneOf" : [ { }, {
+ "type" : "null"
+ } ]
+ },
+ "metabase_version" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "status" : {
+ "enum" : [ "active", "error" ],
+ "type" : "string"
+ },
+ "updated_at" : { }
+ },
+ "required" : [ "id", "display_name", "identifier", "status", "enabled", "dev_only", "created_at", "updated_at" ],
+ "type" : "object"
+ }
+ }
+ },
"description" : "Successful response"
},
"4XX" : {
@@ -26501,43 +25625,34 @@
"description" : "Server error response"
}
},
- "summary" : "POST /api/ee/database-replication/connection/{database-id}",
- "tags" : [ "/api/ee/database-replication" ]
+ "summary" : "POST /api/ee/custom-viz-plugin",
+ "tags" : [ "/api/ee/custom-viz-plugin" ]
}
},
- "/api/ee/database-replication/connection/{database-id}/preview" : {
+ "/api/ee/custom-viz-plugin/dev" : {
"post" : {
- "description" : "Return info about pg-replication connection that is about to be created.",
- "operationId" : "post-api-ee-database-replication-connection-database-id-preview",
- "parameters" : [ {
- "description" : "value must be an integer greater than zero.",
- "in" : "path",
- "name" : "database-id",
- "required" : true,
- "schema" : {
- "minimum" : 1,
- "type" : "integer"
- }
- } ],
+ "description" : "Register a dev-only custom visualization plugin from a local dev server.\n No bundle upload is required — files are served from the dev server URL.\n Requires custom viz plugin dev mode to be enabled.",
+ "operationId" : "post-api-ee-custom-viz-plugin-dev",
+ "parameters" : [ ],
"requestBody" : {
"content" : {
"application/json" : {
"schema" : {
"properties" : {
- "replicationSchemaFilters" : {
- "properties" : {
- "schema-filters-patterns" : {
- "type" : "string"
- },
- "schema-filters-type" : {
- "enum" : [ "inclusion", "exclusion", "all" ],
- "type" : "string"
- }
- },
- "required" : [ "schema-filters-type", "schema-filters-patterns" ],
- "type" : "object"
+ "dev_bundle_url" : {
+ "minLength" : 1,
+ "type" : "string"
+ },
+ "identifier" : {
+ "oneOf" : [ {
+ "minLength" : 1,
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
}
},
+ "required" : [ "dev_bundle_url" ],
"type" : "object"
}
}
@@ -26545,68 +25660,193 @@
},
"responses" : {
"2XX" : {
- "description" : "Successful response"
- },
- "4XX" : {
- "description" : "Client error response"
- },
- "5XX" : {
- "description" : "Server error response"
- }
- },
- "summary" : "POST /api/ee/database-replication/connection/{database-id}/preview",
- "tags" : [ "/api/ee/database-replication" ]
- }
- },
- "/api/ee/database-routing/destination-database" : {
- "post" : {
- "description" : "Create new Destination Databases.\n\n Note that unlike the normal `POST /api/database` endpoint, does NOT check the details before adding the Database.\n\n This is OK, it's not an invariant that all database details are always valid, but it's something to note.",
- "operationId" : "post-api-ee-database-routing-destination-database",
- "parameters" : [ {
- "in" : "query",
- "name" : "check_connection_details",
- "required" : false,
- "schema" : {
- "type" : "boolean"
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "properties" : {
+ "bundle_hash" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "created_at" : { },
+ "dev_bundle_url" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "dev_only" : {
+ "type" : "boolean"
+ },
+ "display_name" : {
+ "minLength" : 1,
+ "type" : "string"
+ },
+ "enabled" : {
+ "type" : "boolean"
+ },
+ "error_message" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "icon" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "id" : {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
+ },
+ "identifier" : {
+ "minLength" : 1,
+ "type" : "string"
+ },
+ "manifest" : {
+ "oneOf" : [ { }, {
+ "type" : "null"
+ } ]
+ },
+ "metabase_version" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "status" : {
+ "enum" : [ "active", "error" ],
+ "type" : "string"
+ },
+ "updated_at" : { }
+ },
+ "required" : [ "id", "display_name", "identifier", "status", "enabled", "dev_only", "created_at", "updated_at" ],
+ "type" : "object"
+ }
+ }
+ },
+ "description" : "Successful response"
+ },
+ "4XX" : {
+ "description" : "Client error response"
+ },
+ "5XX" : {
+ "description" : "Server error response"
}
- } ],
- "requestBody" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "properties" : {
- "destinations" : {
- "items" : {
- "properties" : {
- "details" : {
- "description" : "Value must be a map.",
- "properties" : { },
- "type" : "object"
- },
- "name" : {
- "minLength" : 1,
+ },
+ "summary" : "POST /api/ee/custom-viz-plugin/dev",
+ "tags" : [ "/api/ee/custom-viz-plugin" ]
+ }
+ },
+ "/api/ee/custom-viz-plugin/list" : {
+ "get" : {
+ "description" : "List active and enabled custom visualization plugins. Available to any authenticated user.\n Plugins with incompatible Metabase version requirements are excluded.\n Dev-only plugins are excluded when dev mode is disabled.",
+ "operationId" : "get-api-ee-custom-viz-plugin-list",
+ "parameters" : [ ],
+ "responses" : {
+ "2XX" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "items" : {
+ "properties" : {
+ "bundle_hash" : {
+ "oneOf" : [ {
"type" : "string"
- }
+ }, {
+ "type" : "null"
+ } ]
},
- "required" : [ "name", "details" ],
- "type" : "object"
+ "bundle_url" : {
+ "minLength" : 1,
+ "type" : "string"
+ },
+ "dev_bundle_url" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "display_name" : {
+ "minLength" : 1,
+ "type" : "string"
+ },
+ "icon" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "id" : {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
+ },
+ "identifier" : {
+ "minLength" : 1,
+ "type" : "string"
+ },
+ "manifest" : {
+ "oneOf" : [ { }, {
+ "type" : "null"
+ } ]
+ }
},
- "type" : "array"
+ "required" : [ "id", "identifier", "display_name", "bundle_url" ],
+ "type" : "object"
},
- "router_database_id" : {
- "description" : "value must be an integer greater than zero.",
- "minimum" : 1,
- "type" : "integer"
- }
- },
- "required" : [ "router_database_id", "destinations" ],
- "type" : "object"
+ "type" : "array"
+ }
}
- }
+ },
+ "description" : "Successful response"
+ },
+ "4XX" : {
+ "description" : "Client error response"
+ },
+ "5XX" : {
+ "description" : "Server error response"
}
},
+ "summary" : "GET /api/ee/custom-viz-plugin/list",
+ "tags" : [ "/api/ee/custom-viz-plugin" ]
+ }
+ },
+ "/api/ee/custom-viz-plugin/{id}" : {
+ "delete" : {
+ "description" : "Remove a custom visualization plugin and evict its on-disk cache.",
+ "operationId" : "delete-api-ee-custom-viz-plugin-id",
+ "parameters" : [ {
+ "description" : "value must be an integer greater than zero.",
+ "in" : "path",
+ "name" : "id",
+ "required" : true,
+ "schema" : {
+ "minimum" : 1,
+ "type" : "integer"
+ }
+ } ],
"responses" : {
"2XX" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "type" : "null"
+ }
+ }
+ },
"description" : "Successful response"
},
"4XX" : {
@@ -26616,14 +25856,12 @@
"description" : "Server error response"
}
},
- "summary" : "POST /api/ee/database-routing/destination-database",
- "tags" : [ "/api/ee/database-routing" ]
- }
- },
- "/api/ee/database-routing/router-database/{id}" : {
+ "summary" : "DELETE /api/ee/custom-viz-plugin/{id}",
+ "tags" : [ "/api/ee/custom-viz-plugin" ]
+ },
"put" : {
- "description" : "Updates an existing Database with the `user_attribute` to route on. Will either:\n - turn an existing Database into a Router database\n - change the `user_attribute` used to route for an existing Router database, or\n - turn a Router database into a regular Database\n depending on the value of `user_attribute`",
- "operationId" : "put-api-ee-database-routing-router-database-id",
+ "description" : "Update a custom visualization plugin. Currently only `enabled` may be toggled.",
+ "operationId" : "put-api-ee-custom-viz-plugin-id",
"parameters" : [ {
"description" : "value must be an integer greater than zero.",
"in" : "path",
@@ -26639,10 +25877,9 @@
"application/json" : {
"schema" : {
"properties" : {
- "user_attribute" : {
+ "enabled" : {
"oneOf" : [ {
- "minLength" : 1,
- "type" : "string"
+ "type" : "boolean"
}, {
"type" : "null"
} ]
@@ -26655,6 +25892,81 @@
},
"responses" : {
"2XX" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "properties" : {
+ "bundle_hash" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "created_at" : { },
+ "dev_bundle_url" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "dev_only" : {
+ "type" : "boolean"
+ },
+ "display_name" : {
+ "minLength" : 1,
+ "type" : "string"
+ },
+ "enabled" : {
+ "type" : "boolean"
+ },
+ "error_message" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "icon" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "id" : {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
+ },
+ "identifier" : {
+ "minLength" : 1,
+ "type" : "string"
+ },
+ "manifest" : {
+ "oneOf" : [ { }, {
+ "type" : "null"
+ } ]
+ },
+ "metabase_version" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "status" : {
+ "enum" : [ "active", "error" ],
+ "type" : "string"
+ },
+ "updated_at" : { }
+ },
+ "required" : [ "id", "display_name", "identifier", "status", "enabled", "dev_only", "created_at", "updated_at" ],
+ "type" : "object"
+ }
+ }
+ },
"description" : "Successful response"
},
"4XX" : {
@@ -26664,31 +25976,37 @@
"description" : "Server error response"
}
},
- "summary" : "PUT /api/ee/database-routing/router-database/{id}",
- "tags" : [ "/api/ee/database-routing" ]
+ "summary" : "PUT /api/ee/custom-viz-plugin/{id}",
+ "tags" : [ "/api/ee/custom-viz-plugin" ]
}
},
- "/api/ee/dependencies/check-card" : {
- "post" : {
- "description" : "Check a proposed edit to a card, and return the card IDs for those cards this edit will break.",
- "operationId" : "post-api-ee-dependencies-check-card",
- "parameters" : [ ],
- "requestBody" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "$ref" : "#/components/schemas/metabase-enterprise.dependencies.api.card-body"
- }
- }
+ "/api/ee/custom-viz-plugin/{id}/asset" : {
+ "get" : {
+ "description" : "Serve a static image asset from the plugin's bundle.\n The asset path is passed as a `path` query parameter (e.g. `?path=icon.svg`)\n and must match an entry in the manifest's `assets` whitelist.\n Only image files are served.\n In dev mode, proxies from the dev base URL if set.",
+ "operationId" : "get-api-ee-custom-viz-plugin-id-asset",
+ "parameters" : [ {
+ "description" : "value must be an integer greater than zero.",
+ "in" : "path",
+ "name" : "id",
+ "required" : true,
+ "schema" : {
+ "minimum" : 1,
+ "type" : "integer"
}
- },
+ }, {
+ "in" : "query",
+ "name" : "path",
+ "required" : true,
+ "schema" : {
+ "minLength" : 1,
+ "type" : "string"
+ }
+ } ],
"responses" : {
"2XX" : {
"content" : {
"application/json" : {
- "schema" : {
- "$ref" : "#/components/schemas/metabase-enterprise.dependencies.api.broken-cards-response"
- }
+ "schema" : { }
}
},
"description" : "Successful response"
@@ -26700,31 +26018,73 @@
"description" : "Server error response"
}
},
- "summary" : "POST /api/ee/dependencies/check-card",
- "tags" : [ "/api/ee/dependencies" ]
+ "summary" : "GET /api/ee/custom-viz-plugin/{id}/asset",
+ "tags" : [ "/api/ee/custom-viz-plugin" ]
}
},
- "/api/ee/dependencies/check-snippet" : {
- "post" : {
- "description" : "Check a proposed edit to a native snippet, and return the cards, etc. which will be broken.",
- "operationId" : "post-api-ee-dependencies-check-snippet",
- "parameters" : [ ],
+ "/api/ee/custom-viz-plugin/{id}/bundle" : {
+ "get" : {
+ "description" : "Serve the JS bundle for a plugin from the on-disk cache.\n Returns application/javascript with ETag and Cache-Control headers.\n In dev mode, proxies from `dev_bundle_url` if set.",
+ "operationId" : "get-api-ee-custom-viz-plugin-id-bundle",
+ "parameters" : [ {
+ "description" : "value must be an integer greater than zero.",
+ "in" : "path",
+ "name" : "id",
+ "required" : true,
+ "schema" : {
+ "minimum" : 1,
+ "type" : "integer"
+ }
+ } ],
+ "responses" : {
+ "2XX" : {
+ "content" : {
+ "application/json" : {
+ "schema" : { }
+ }
+ },
+ "description" : "Successful response"
+ },
+ "4XX" : {
+ "description" : "Client error response"
+ },
+ "5XX" : {
+ "description" : "Server error response"
+ }
+ },
+ "summary" : "GET /api/ee/custom-viz-plugin/{id}/bundle",
+ "tags" : [ "/api/ee/custom-viz-plugin" ]
+ },
+ "put" : {
+ "description" : "Replace the bundle for an existing plugin. Accepts a multipart tar.gz upload in\n the same format as the `POST /` endpoint. The manifest's `name` field must\n match the plugin's existing `identifier`.",
+ "operationId" : "put-api-ee-custom-viz-plugin-id-bundle",
+ "parameters" : [ {
+ "description" : "value must be an integer greater than zero.",
+ "in" : "path",
+ "name" : "id",
+ "required" : true,
+ "schema" : {
+ "minimum" : 1,
+ "type" : "integer"
+ }
+ } ],
"requestBody" : {
"content" : {
- "application/json" : {
+ "multipart/form-data" : {
"schema" : {
"properties" : {
- "content" : {
- "type" : "string"
- },
- "id" : {
- "$ref" : "#/components/schemas/metabase.lib.schema.id.snippet"
- },
- "name" : {
- "description" : "snippet names cannot include '}' or start with spaces"
+ "file" : {
+ "properties" : {
+ "filename" : {
+ "type" : "string"
+ },
+ "tempfile" : { }
+ },
+ "required" : [ "filename", "tempfile" ],
+ "type" : "object"
}
},
- "required" : [ "id" ],
+ "required" : [ "file" ],
"type" : "object"
}
}
@@ -26735,7 +26095,75 @@
"content" : {
"application/json" : {
"schema" : {
- "$ref" : "#/components/schemas/metabase-enterprise.dependencies.api.broken-cards-response"
+ "properties" : {
+ "bundle_hash" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "created_at" : { },
+ "dev_bundle_url" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "dev_only" : {
+ "type" : "boolean"
+ },
+ "display_name" : {
+ "minLength" : 1,
+ "type" : "string"
+ },
+ "enabled" : {
+ "type" : "boolean"
+ },
+ "error_message" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "icon" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "id" : {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
+ },
+ "identifier" : {
+ "minLength" : 1,
+ "type" : "string"
+ },
+ "manifest" : {
+ "oneOf" : [ { }, {
+ "type" : "null"
+ } ]
+ },
+ "metabase_version" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "status" : {
+ "enum" : [ "active", "error" ],
+ "type" : "string"
+ },
+ "updated_at" : { }
+ },
+ "required" : [ "id", "display_name", "identifier", "status", "enabled", "dev_only", "created_at", "updated_at" ],
+ "type" : "object"
}
}
},
@@ -26748,31 +26176,29 @@
"description" : "Server error response"
}
},
- "summary" : "POST /api/ee/dependencies/check-snippet",
- "tags" : [ "/api/ee/dependencies" ]
+ "summary" : "PUT /api/ee/custom-viz-plugin/{id}/bundle",
+ "tags" : [ "/api/ee/custom-viz-plugin" ]
}
},
- "/api/ee/dependencies/check-transform" : {
- "post" : {
- "description" : "Check a proposed edit to a transform, and return the card, transform, etc. IDs for things that will break.",
- "operationId" : "post-api-ee-dependencies-check-transform",
- "parameters" : [ ],
- "requestBody" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "$ref" : "#/components/schemas/metabase-enterprise.dependencies.api.transform-body"
- }
- }
+ "/api/ee/custom-viz-plugin/{id}/dev-sse" : {
+ "get" : {
+ "description" : "Proxy Server-Sent Events from the plugin's dev server.\n Connects to `{dev_bundle_url}/__sse` and forwards events to the browser.\n This avoids the need for a CSP exception for the dev server origin.\n Requires custom viz plugin dev mode to be enabled.",
+ "operationId" : "get-api-ee-custom-viz-plugin-id-dev-sse",
+ "parameters" : [ {
+ "description" : "value must be an integer greater than zero.",
+ "in" : "path",
+ "name" : "id",
+ "required" : true,
+ "schema" : {
+ "minimum" : 1,
+ "type" : "integer"
}
- },
+ } ],
"responses" : {
"2XX" : {
"content" : {
"application/json" : {
- "schema" : {
- "$ref" : "#/components/schemas/metabase-enterprise.dependencies.api.broken-cards-response"
- }
+ "schema" : { }
}
},
"description" : "Successful response"
@@ -26784,44 +26210,59 @@
"description" : "Server error response"
}
},
- "summary" : "POST /api/ee/dependencies/check-transform",
- "tags" : [ "/api/ee/dependencies" ]
+ "summary" : "GET /api/ee/custom-viz-plugin/{id}/dev-sse",
+ "tags" : [ "/api/ee/custom-viz-plugin" ]
}
},
- "/api/ee/dependencies/graph" : {
- "get" : {
- "description" : "This endpoint takes an :id and a supported entity :type, and returns a graph of all its upstream dependencies.\n The graph is represented by a list of :nodes and a list of :edges. Each node has an :id, :type, :data (which\n depends on the node type), and a map of :dependent_counts per entity type. Each edge is a :model/Dependency.\n\n Optional :archived parameter controls whether entities in archived collections are included:\n - false (default): Excludes entities in archived collections\n - true: Includes entities in archived collections",
- "operationId" : "get-api-ee-dependencies-graph",
+ "/api/ee/custom-viz-plugin/{id}/dev-url" : {
+ "put" : {
+ "description" : "Set or clear the dev base URL for a plugin (e.g. `http://localhost:5174`).\n The bundle is fetched from `{base}/index.js` and assets from `{base}/assets/{name}`.\n Persisted to the database so it survives server restarts.\n Requires custom viz plugin dev mode to be enabled.",
+ "operationId" : "put-api-ee-custom-viz-plugin-id-dev-url",
"parameters" : [ {
"description" : "value must be an integer greater than zero.",
- "in" : "query",
+ "in" : "path",
"name" : "id",
- "required" : false,
+ "required" : true,
"schema" : {
"minimum" : 1,
"type" : "integer"
}
- }, {
- "in" : "query",
- "name" : "type",
- "required" : false,
- "schema" : {
- "$ref" : "#/components/schemas/metabase-enterprise.dependencies.dependency-types.dependency-types"
- }
- }, {
- "in" : "query",
- "name" : "archived",
- "required" : false,
- "schema" : {
- "type" : "boolean"
- }
} ],
+ "requestBody" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "properties" : {
+ "dev_bundle_url" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ }
+ },
+ "required" : [ "dev_bundle_url" ],
+ "type" : "object"
+ }
+ }
+ }
+ },
"responses" : {
"2XX" : {
"content" : {
"application/json" : {
"schema" : {
- "$ref" : "#/components/schemas/metabase-enterprise.dependencies.api.graph-response"
+ "properties" : {
+ "dev_bundle_url" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ }
+ },
+ "required" : [ "dev_bundle_url" ],
+ "type" : "object"
}
}
},
@@ -26834,80 +26275,22 @@
"description" : "Server error response"
}
},
- "summary" : "GET /api/ee/dependencies/graph",
- "tags" : [ "/api/ee/dependencies" ]
+ "summary" : "PUT /api/ee/custom-viz-plugin/{id}/dev-url",
+ "tags" : [ "/api/ee/custom-viz-plugin" ]
}
},
- "/api/ee/dependencies/graph/breaking" : {
- "get" : {
- "description" : "Returns a list of entities that are breaking other entities (sources of errors).\n These are tables or cards that other entities depend on, where those dependents\n have validation errors traced back to this source entity.\n\n Accepts optional parameters for filtering:\n - `types`: List of source entity types - only `:card` or `:table` (default: both)\n - `card-types`: List of card types to include when filtering cards (e.g., `[:question :model :metric]`)\n - `query`: Search string to filter by name or location\n - `archived`: Controls whether archived entities are included\n - `include-personal-collections`: Controls whether items in personal collections are included (default: false)\n - `sort-column`: Sort column - `:name`, `:location`, `:dependents-errors`, or `:dependents-with-errors` (default: `:name`)\n - `sort-direction`: Sort direction - `:asc` or `:desc` (default: `:asc`)\n - `offset`: Default 0\n - `limit`: Default 50\n\n Returns a map with:\n - `data`: List of breaking source entities\n - `total`: Total count of matched items\n - `offset`: Applied offset\n - `limit`: Applied limit",
- "operationId" : "get-api-ee-dependencies-graph-breaking",
+ "/api/ee/custom-viz-plugin/{id}/refresh" : {
+ "post" : {
+ "description" : "Re-fetch the manifest from the dev server for a dev-only plugin. For uploaded\n plugins this is a no-op — to update an upload-backed plugin, PUT a new bundle\n to `/:id/bundle`.",
+ "operationId" : "post-api-ee-custom-viz-plugin-id-refresh",
"parameters" : [ {
- "in" : "query",
- "name" : "types",
- "required" : false,
- "schema" : {
- "anyOf" : [ {
- "$ref" : "#/components/schemas/metabase-enterprise.dependencies.dependency-types.dependency-types"
- }, {
- "items" : {
- "$ref" : "#/components/schemas/metabase-enterprise.dependencies.dependency-types.dependency-types"
- },
- "type" : "array"
- } ]
- }
- }, {
- "in" : "query",
- "name" : "card-types",
- "required" : false,
- "schema" : {
- "anyOf" : [ {
- "enum" : [ "question", "metric", "model" ],
- "type" : "string"
- }, {
- "items" : {
- "enum" : [ "question", "metric", "model" ],
- "type" : "string"
- },
- "type" : "array"
- } ]
- }
- }, {
- "in" : "query",
- "name" : "query",
- "required" : false,
- "schema" : {
- "type" : "string"
- }
- }, {
- "in" : "query",
- "name" : "archived",
- "required" : false,
- "schema" : {
- "type" : "boolean"
- }
- }, {
- "in" : "query",
- "name" : "include-personal-collections",
- "required" : false,
- "schema" : {
- "type" : "boolean"
- }
- }, {
- "in" : "query",
- "name" : "sort-column",
- "required" : false,
- "schema" : {
- "enum" : [ "dependents-with-errors", "dependents-errors", "name", "location" ],
- "type" : "string"
- }
- }, {
- "in" : "query",
- "name" : "sort-direction",
- "required" : false,
+ "description" : "value must be an integer greater than zero.",
+ "in" : "path",
+ "name" : "id",
+ "required" : true,
"schema" : {
- "enum" : [ "desc", "asc" ],
- "type" : "string"
+ "minimum" : 1,
+ "type" : "integer"
}
} ],
"responses" : {
@@ -26916,27 +26299,73 @@
"application/json" : {
"schema" : {
"properties" : {
- "data" : {
- "items" : {
- "$ref" : "#/components/schemas/metabase-enterprise.dependencies.api.entity"
- },
- "type" : "array"
+ "bundle_hash" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
},
- "limit" : {
+ "created_at" : { },
+ "dev_bundle_url" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "dev_only" : {
+ "type" : "boolean"
+ },
+ "display_name" : {
+ "minLength" : 1,
+ "type" : "string"
+ },
+ "enabled" : {
+ "type" : "boolean"
+ },
+ "error_message" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "icon" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "id" : {
"description" : "value must be an integer greater than zero.",
"minimum" : 1,
"type" : "integer"
},
- "offset" : {
- "minimum" : 0,
- "type" : "integer"
+ "identifier" : {
+ "minLength" : 1,
+ "type" : "string"
},
- "total" : {
- "minimum" : 0,
- "type" : "integer"
- }
+ "manifest" : {
+ "oneOf" : [ { }, {
+ "type" : "null"
+ } ]
+ },
+ "metabase_version" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "status" : {
+ "enum" : [ "active", "error" ],
+ "type" : "string"
+ },
+ "updated_at" : { }
},
- "required" : [ "data", "total", "offset", "limit" ],
+ "required" : [ "id", "display_name", "identifier", "status", "enabled", "dev_only", "created_at", "updated_at" ],
"type" : "object"
}
}
@@ -26950,93 +26379,587 @@
"description" : "Server error response"
}
},
- "summary" : "GET /api/ee/dependencies/graph/breaking",
- "tags" : [ "/api/ee/dependencies" ]
+ "summary" : "POST /api/ee/custom-viz-plugin/{id}/refresh",
+ "tags" : [ "/api/ee/custom-viz-plugin" ]
}
},
- "/api/ee/dependencies/graph/broken" : {
+ "/api/ee/data-complexity-score/complexity" : {
"get" : {
- "description" : "Returns the broken dependents for a specific source entity.\n These are entities that have validation errors traced back to the specified source.\n\n Required parameters:\n - `id`: The ID of the source entity\n - `type`: The type of the source entity (card, table)\n\n Optional parameters:\n - `dependent-types`: Dependency types to filter by. Can be single value or array.\n - `dependent-card-types`: Card types to filter by when dependent-types includes :card.\n - `include-personal-collections`: Include items in personal collections (default: false)\n - `sort-column`: Column to sort by - name, location, or view-count (default: name)\n - `sort-direction`: Sort direction - asc or desc (default: asc)",
- "operationId" : "get-api-ee-dependencies-graph-broken",
+ "description" : "Return the most recently stored Data Complexity Score for this instance.\n Pass `force-recalculation=true` to recompute, persist, and return a fresh score.\n Superuser-only.",
+ "operationId" : "get-api-ee-data-complexity-score-complexity",
"parameters" : [ {
- "description" : "value must be an integer greater than zero.",
- "in" : "query",
- "name" : "id",
- "required" : true,
- "schema" : {
- "minimum" : 1,
- "type" : "integer"
- }
- }, {
"in" : "query",
- "name" : "type",
+ "name" : "force-recalculation",
"required" : true,
"schema" : {
- "$ref" : "#/components/schemas/metabase-enterprise.dependencies.dependency-types.dependency-types"
- }
- }, {
- "in" : "query",
- "name" : "dependent-types",
- "required" : false,
- "schema" : {
- "anyOf" : [ {
- "$ref" : "#/components/schemas/metabase-enterprise.dependencies.dependency-types.dependency-types"
- }, {
- "items" : {
- "$ref" : "#/components/schemas/metabase-enterprise.dependencies.dependency-types.dependency-types"
- },
- "type" : "array"
- } ]
- }
- }, {
- "in" : "query",
- "name" : "dependent-card-types",
- "required" : false,
- "schema" : {
- "anyOf" : [ {
- "enum" : [ "question", "metric", "model" ],
- "type" : "string"
- }, {
- "items" : {
- "enum" : [ "question", "metric", "model" ],
- "type" : "string"
- },
- "type" : "array"
- } ]
- }
- }, {
- "in" : "query",
- "name" : "include-personal-collections",
- "required" : false,
- "schema" : {
+ "default" : false,
"type" : "boolean"
}
- }, {
- "in" : "query",
- "name" : "sort-column",
- "required" : false,
- "schema" : {
- "enum" : [ "name", "view-count", "location" ],
- "type" : "string"
- }
- }, {
- "in" : "query",
- "name" : "sort-direction",
- "required" : false,
- "schema" : {
- "enum" : [ "desc", "asc" ],
- "type" : "string"
- }
} ],
"responses" : {
"2XX" : {
"content" : {
"application/json" : {
"schema" : {
- "items" : {
- "$ref" : "#/components/schemas/metabase-enterprise.dependencies.api.broken-dependent-entity"
+ "properties" : {
+ "library" : {
+ "properties" : {
+ "components" : {
+ "properties" : {
+ "entity_count" : {
+ "anyOf" : [ {
+ "additionalProperties" : false,
+ "properties" : {
+ "measurement" : {
+ "type" : "number"
+ },
+ "score" : {
+ "minimum" : 0,
+ "type" : "integer"
+ }
+ },
+ "required" : [ "measurement", "score" ],
+ "type" : "object"
+ }, {
+ "additionalProperties" : false,
+ "properties" : {
+ "error" : {
+ "type" : "string"
+ },
+ "measurement" : {
+ "type" : "null"
+ },
+ "score" : {
+ "type" : "null"
+ }
+ },
+ "required" : [ "measurement", "score", "error" ],
+ "type" : "object"
+ } ]
+ },
+ "field_count" : {
+ "anyOf" : [ {
+ "additionalProperties" : false,
+ "properties" : {
+ "measurement" : {
+ "type" : "number"
+ },
+ "score" : {
+ "minimum" : 0,
+ "type" : "integer"
+ }
+ },
+ "required" : [ "measurement", "score" ],
+ "type" : "object"
+ }, {
+ "additionalProperties" : false,
+ "properties" : {
+ "error" : {
+ "type" : "string"
+ },
+ "measurement" : {
+ "type" : "null"
+ },
+ "score" : {
+ "type" : "null"
+ }
+ },
+ "required" : [ "measurement", "score", "error" ],
+ "type" : "object"
+ } ]
+ },
+ "name_collisions" : {
+ "anyOf" : [ {
+ "additionalProperties" : false,
+ "properties" : {
+ "measurement" : {
+ "type" : "number"
+ },
+ "score" : {
+ "minimum" : 0,
+ "type" : "integer"
+ }
+ },
+ "required" : [ "measurement", "score" ],
+ "type" : "object"
+ }, {
+ "additionalProperties" : false,
+ "properties" : {
+ "error" : {
+ "type" : "string"
+ },
+ "measurement" : {
+ "type" : "null"
+ },
+ "score" : {
+ "type" : "null"
+ }
+ },
+ "required" : [ "measurement", "score", "error" ],
+ "type" : "object"
+ } ]
+ },
+ "repeated_measures" : {
+ "anyOf" : [ {
+ "additionalProperties" : false,
+ "properties" : {
+ "measurement" : {
+ "type" : "number"
+ },
+ "score" : {
+ "minimum" : 0,
+ "type" : "integer"
+ }
+ },
+ "required" : [ "measurement", "score" ],
+ "type" : "object"
+ }, {
+ "additionalProperties" : false,
+ "properties" : {
+ "error" : {
+ "type" : "string"
+ },
+ "measurement" : {
+ "type" : "null"
+ },
+ "score" : {
+ "type" : "null"
+ }
+ },
+ "required" : [ "measurement", "score", "error" ],
+ "type" : "object"
+ } ]
+ },
+ "synonym_pairs" : {
+ "anyOf" : [ {
+ "additionalProperties" : false,
+ "properties" : {
+ "measurement" : {
+ "type" : "number"
+ },
+ "score" : {
+ "minimum" : 0,
+ "type" : "integer"
+ }
+ },
+ "required" : [ "measurement", "score" ],
+ "type" : "object"
+ }, {
+ "additionalProperties" : false,
+ "properties" : {
+ "error" : {
+ "type" : "string"
+ },
+ "measurement" : {
+ "type" : "null"
+ },
+ "score" : {
+ "type" : "null"
+ }
+ },
+ "required" : [ "measurement", "score", "error" ],
+ "type" : "object"
+ } ]
+ }
+ },
+ "required" : [ "entity_count", "name_collisions", "synonym_pairs", "field_count", "repeated_measures" ],
+ "type" : "object"
+ },
+ "total" : {
+ "oneOf" : [ {
+ "minimum" : 0,
+ "type" : "integer"
+ }, {
+ "type" : "null"
+ } ]
+ }
+ },
+ "required" : [ "total", "components" ],
+ "type" : "object"
+ },
+ "meta" : {
+ "properties" : {
+ "calculated_at" : { },
+ "embedding_model" : {
+ "oneOf" : [ {
+ "properties" : {
+ "model_name" : {
+ "type" : "string"
+ },
+ "provider" : {
+ "type" : "string"
+ }
+ },
+ "required" : [ "provider", "model_name" ],
+ "type" : "object"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "formula_version" : {
+ "minimum" : 1,
+ "type" : "integer"
+ },
+ "synonym_threshold" : {
+ "type" : "number"
+ }
+ },
+ "required" : [ "formula_version", "synonym_threshold" ],
+ "type" : "object"
+ },
+ "metabot" : {
+ "properties" : {
+ "components" : {
+ "properties" : {
+ "entity_count" : {
+ "anyOf" : [ {
+ "additionalProperties" : false,
+ "properties" : {
+ "measurement" : {
+ "type" : "number"
+ },
+ "score" : {
+ "minimum" : 0,
+ "type" : "integer"
+ }
+ },
+ "required" : [ "measurement", "score" ],
+ "type" : "object"
+ }, {
+ "additionalProperties" : false,
+ "properties" : {
+ "error" : {
+ "type" : "string"
+ },
+ "measurement" : {
+ "type" : "null"
+ },
+ "score" : {
+ "type" : "null"
+ }
+ },
+ "required" : [ "measurement", "score", "error" ],
+ "type" : "object"
+ } ]
+ },
+ "field_count" : {
+ "anyOf" : [ {
+ "additionalProperties" : false,
+ "properties" : {
+ "measurement" : {
+ "type" : "number"
+ },
+ "score" : {
+ "minimum" : 0,
+ "type" : "integer"
+ }
+ },
+ "required" : [ "measurement", "score" ],
+ "type" : "object"
+ }, {
+ "additionalProperties" : false,
+ "properties" : {
+ "error" : {
+ "type" : "string"
+ },
+ "measurement" : {
+ "type" : "null"
+ },
+ "score" : {
+ "type" : "null"
+ }
+ },
+ "required" : [ "measurement", "score", "error" ],
+ "type" : "object"
+ } ]
+ },
+ "name_collisions" : {
+ "anyOf" : [ {
+ "additionalProperties" : false,
+ "properties" : {
+ "measurement" : {
+ "type" : "number"
+ },
+ "score" : {
+ "minimum" : 0,
+ "type" : "integer"
+ }
+ },
+ "required" : [ "measurement", "score" ],
+ "type" : "object"
+ }, {
+ "additionalProperties" : false,
+ "properties" : {
+ "error" : {
+ "type" : "string"
+ },
+ "measurement" : {
+ "type" : "null"
+ },
+ "score" : {
+ "type" : "null"
+ }
+ },
+ "required" : [ "measurement", "score", "error" ],
+ "type" : "object"
+ } ]
+ },
+ "repeated_measures" : {
+ "anyOf" : [ {
+ "additionalProperties" : false,
+ "properties" : {
+ "measurement" : {
+ "type" : "number"
+ },
+ "score" : {
+ "minimum" : 0,
+ "type" : "integer"
+ }
+ },
+ "required" : [ "measurement", "score" ],
+ "type" : "object"
+ }, {
+ "additionalProperties" : false,
+ "properties" : {
+ "error" : {
+ "type" : "string"
+ },
+ "measurement" : {
+ "type" : "null"
+ },
+ "score" : {
+ "type" : "null"
+ }
+ },
+ "required" : [ "measurement", "score", "error" ],
+ "type" : "object"
+ } ]
+ },
+ "synonym_pairs" : {
+ "anyOf" : [ {
+ "additionalProperties" : false,
+ "properties" : {
+ "measurement" : {
+ "type" : "number"
+ },
+ "score" : {
+ "minimum" : 0,
+ "type" : "integer"
+ }
+ },
+ "required" : [ "measurement", "score" ],
+ "type" : "object"
+ }, {
+ "additionalProperties" : false,
+ "properties" : {
+ "error" : {
+ "type" : "string"
+ },
+ "measurement" : {
+ "type" : "null"
+ },
+ "score" : {
+ "type" : "null"
+ }
+ },
+ "required" : [ "measurement", "score", "error" ],
+ "type" : "object"
+ } ]
+ }
+ },
+ "required" : [ "entity_count", "name_collisions", "synonym_pairs", "field_count", "repeated_measures" ],
+ "type" : "object"
+ },
+ "total" : {
+ "oneOf" : [ {
+ "minimum" : 0,
+ "type" : "integer"
+ }, {
+ "type" : "null"
+ } ]
+ }
+ },
+ "required" : [ "total", "components" ],
+ "type" : "object"
+ },
+ "universe" : {
+ "properties" : {
+ "components" : {
+ "properties" : {
+ "entity_count" : {
+ "anyOf" : [ {
+ "additionalProperties" : false,
+ "properties" : {
+ "measurement" : {
+ "type" : "number"
+ },
+ "score" : {
+ "minimum" : 0,
+ "type" : "integer"
+ }
+ },
+ "required" : [ "measurement", "score" ],
+ "type" : "object"
+ }, {
+ "additionalProperties" : false,
+ "properties" : {
+ "error" : {
+ "type" : "string"
+ },
+ "measurement" : {
+ "type" : "null"
+ },
+ "score" : {
+ "type" : "null"
+ }
+ },
+ "required" : [ "measurement", "score", "error" ],
+ "type" : "object"
+ } ]
+ },
+ "field_count" : {
+ "anyOf" : [ {
+ "additionalProperties" : false,
+ "properties" : {
+ "measurement" : {
+ "type" : "number"
+ },
+ "score" : {
+ "minimum" : 0,
+ "type" : "integer"
+ }
+ },
+ "required" : [ "measurement", "score" ],
+ "type" : "object"
+ }, {
+ "additionalProperties" : false,
+ "properties" : {
+ "error" : {
+ "type" : "string"
+ },
+ "measurement" : {
+ "type" : "null"
+ },
+ "score" : {
+ "type" : "null"
+ }
+ },
+ "required" : [ "measurement", "score", "error" ],
+ "type" : "object"
+ } ]
+ },
+ "name_collisions" : {
+ "anyOf" : [ {
+ "additionalProperties" : false,
+ "properties" : {
+ "measurement" : {
+ "type" : "number"
+ },
+ "score" : {
+ "minimum" : 0,
+ "type" : "integer"
+ }
+ },
+ "required" : [ "measurement", "score" ],
+ "type" : "object"
+ }, {
+ "additionalProperties" : false,
+ "properties" : {
+ "error" : {
+ "type" : "string"
+ },
+ "measurement" : {
+ "type" : "null"
+ },
+ "score" : {
+ "type" : "null"
+ }
+ },
+ "required" : [ "measurement", "score", "error" ],
+ "type" : "object"
+ } ]
+ },
+ "repeated_measures" : {
+ "anyOf" : [ {
+ "additionalProperties" : false,
+ "properties" : {
+ "measurement" : {
+ "type" : "number"
+ },
+ "score" : {
+ "minimum" : 0,
+ "type" : "integer"
+ }
+ },
+ "required" : [ "measurement", "score" ],
+ "type" : "object"
+ }, {
+ "additionalProperties" : false,
+ "properties" : {
+ "error" : {
+ "type" : "string"
+ },
+ "measurement" : {
+ "type" : "null"
+ },
+ "score" : {
+ "type" : "null"
+ }
+ },
+ "required" : [ "measurement", "score", "error" ],
+ "type" : "object"
+ } ]
+ },
+ "synonym_pairs" : {
+ "anyOf" : [ {
+ "additionalProperties" : false,
+ "properties" : {
+ "measurement" : {
+ "type" : "number"
+ },
+ "score" : {
+ "minimum" : 0,
+ "type" : "integer"
+ }
+ },
+ "required" : [ "measurement", "score" ],
+ "type" : "object"
+ }, {
+ "additionalProperties" : false,
+ "properties" : {
+ "error" : {
+ "type" : "string"
+ },
+ "measurement" : {
+ "type" : "null"
+ },
+ "score" : {
+ "type" : "null"
+ }
+ },
+ "required" : [ "measurement", "score", "error" ],
+ "type" : "object"
+ } ]
+ }
+ },
+ "required" : [ "entity_count", "name_collisions", "synonym_pairs", "field_count", "repeated_measures" ],
+ "type" : "object"
+ },
+ "total" : {
+ "oneOf" : [ {
+ "minimum" : 0,
+ "type" : "integer"
+ }, {
+ "type" : "null"
+ } ]
+ }
+ },
+ "required" : [ "total", "components" ],
+ "type" : "object"
+ }
},
- "type" : "array"
+ "required" : [ "library", "universe", "metabot", "meta" ],
+ "type" : "object"
}
}
},
@@ -27049,114 +26972,30 @@
"description" : "Server error response"
}
},
- "summary" : "GET /api/ee/dependencies/graph/broken",
- "tags" : [ "/api/ee/dependencies" ]
+ "summary" : "GET /api/ee/data-complexity-score/complexity",
+ "tags" : [ "/api/ee/data-complexity-score" ]
}
},
- "/api/ee/dependencies/graph/dependents" : {
- "get" : {
- "description" : "Returns a list of dependents for the specified entity.\n\n Required parameters:\n - `id`: The ID of the entity\n - `type`: The type of the entity (card, table, dashboard, etc.)\n\n Optional parameters:\n - `dependent-types`: Dependency types to filter by. Can be single value or array.\n If not provided, returns all types. Example: ?dependent-types=card&dependent-types=dashboard\n - `dependent-card-types`: Card types to filter by when dependent-types includes :card.\n Ignored if dependent-types doesn't include :card. Example: ?dependent-card-types=question&dependent-card-types=model\n - `archived`: Include entities in archived collections (default: false)\n - `broken`: Return only broken entities (default: false)\n - `query`: Search string to filter results by name or location (case-insensitive)\n - `include-personal-collections`: Include items in personal collections (default: false)\n - `sort-column`: Column to sort by - name, location, or view-count (default: name)\n - `sort-direction`: Sort direction - asc or desc (default: asc)",
- "operationId" : "get-api-ee-dependencies-graph-dependents",
- "parameters" : [ {
- "description" : "value must be an integer greater than zero.",
- "in" : "query",
- "name" : "id",
- "required" : true,
- "schema" : {
- "minimum" : 1,
- "type" : "integer"
- }
- }, {
- "in" : "query",
- "name" : "type",
- "required" : true,
- "schema" : {
- "$ref" : "#/components/schemas/metabase-enterprise.dependencies.dependency-types.dependency-types"
- }
- }, {
- "in" : "query",
- "name" : "dependent-types",
- "required" : false,
- "schema" : {
- "anyOf" : [ {
- "$ref" : "#/components/schemas/metabase-enterprise.dependencies.dependency-types.dependency-types"
- }, {
- "items" : {
- "$ref" : "#/components/schemas/metabase-enterprise.dependencies.dependency-types.dependency-types"
- },
- "type" : "array"
- } ]
- }
- }, {
- "in" : "query",
- "name" : "dependent-card-types",
- "required" : false,
- "schema" : {
- "anyOf" : [ {
- "enum" : [ "question", "metric", "model" ],
- "type" : "string"
- }, {
- "items" : {
- "enum" : [ "question", "metric", "model" ],
- "type" : "string"
- },
- "type" : "array"
- } ]
- }
- }, {
- "in" : "query",
- "name" : "archived",
- "required" : false,
- "schema" : {
- "type" : "boolean"
- }
- }, {
- "in" : "query",
- "name" : "broken",
- "required" : false,
- "schema" : {
- "type" : "boolean"
- }
- }, {
- "in" : "query",
- "name" : "query",
- "required" : false,
- "schema" : {
- "type" : "string"
- }
- }, {
- "in" : "query",
- "name" : "include-personal-collections",
- "required" : false,
- "schema" : {
- "type" : "boolean"
- }
- }, {
- "in" : "query",
- "name" : "sort-column",
- "required" : false,
- "schema" : {
- "enum" : [ "name", "view-count", "location" ],
- "type" : "string"
- }
- }, {
- "in" : "query",
- "name" : "sort-direction",
- "required" : false,
- "schema" : {
- "enum" : [ "desc", "asc" ],
- "type" : "string"
+ "/api/ee/data-studio/table/publish-tables" : {
+ "post" : {
+ "description" : "Set collection for each of selected tables and all upstream dependencies recursively.",
+ "operationId" : "post-api-ee-data-studio-table-publish-tables",
+ "parameters" : [ ],
+ "requestBody" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.data-studio.api.table.publish-table-selectors"
+ }
+ }
}
- } ],
+ },
"responses" : {
"2XX" : {
"content" : {
"application/json" : {
"schema" : {
- "items" : {
- "$ref" : "#/components/schemas/metabase-enterprise.dependencies.api.entity"
- },
- "type" : "array"
+ "$ref" : "#/components/schemas/metabase-enterprise.data-studio.api.table.publish-tables-response"
}
}
},
@@ -27169,110 +27008,30 @@
"description" : "Server error response"
}
},
- "summary" : "GET /api/ee/dependencies/graph/dependents",
- "tags" : [ "/api/ee/dependencies" ]
+ "summary" : "POST /api/ee/data-studio/table/publish-tables",
+ "tags" : [ "/api/ee/data-studio/table" ]
}
},
- "/api/ee/dependencies/graph/unreferenced" : {
- "get" : {
- "description" : "Returns a list of all unreferenced items in the instance.\n An unreferenced item is one that is not a dependency of any other item.\n\n Accepts optional parameters for filtering:\n - `types`: List of entity types to include (e.g., [:card :transform :snippet :dashboard])\n - `card-types`: List of card types to include when filtering cards (e.g., [:question :model :metric])\n - `query`: Search string to filter by name or location\n - `archived`: Controls whether archived entities are included\n - `include-personal-collections`: Controls whether items in personal collections are included (default: false)\n - `sort-column`: Sort column - `:name`, `:location`, `:dependents-errors`, or `:dependents-with-errors` (default: `:name`)\n - `sort-direction`: Sort direction - `:asc` or `:desc` (default: `:asc`)\n - `offset`: Default 0\n - `limit`: Default 50\n\n Returns a map with:\n - `data`: List of unreferenced items, each with `:id`, `:type`, and `:data` fields\n - `total`: Total count of matched items\n - `offset`: Applied offset\n - `limit`: Applied limit",
- "operationId" : "get-api-ee-dependencies-graph-unreferenced",
- "parameters" : [ {
- "in" : "query",
- "name" : "types",
- "required" : false,
- "schema" : {
- "anyOf" : [ {
- "$ref" : "#/components/schemas/metabase-enterprise.dependencies.dependency-types.dependency-types"
- }, {
- "items" : {
- "$ref" : "#/components/schemas/metabase-enterprise.dependencies.dependency-types.dependency-types"
- },
- "type" : "array"
- } ]
- }
- }, {
- "in" : "query",
- "name" : "card-types",
- "required" : false,
- "schema" : {
- "anyOf" : [ {
- "enum" : [ "question", "metric", "model" ],
- "type" : "string"
- }, {
- "items" : {
- "enum" : [ "question", "metric", "model" ],
- "type" : "string"
- },
- "type" : "array"
- } ]
- }
- }, {
- "in" : "query",
- "name" : "query",
- "required" : false,
- "schema" : {
- "type" : "string"
- }
- }, {
- "in" : "query",
- "name" : "archived",
- "required" : false,
- "schema" : {
- "type" : "boolean"
- }
- }, {
- "in" : "query",
- "name" : "include-personal-collections",
- "required" : false,
- "schema" : {
- "type" : "boolean"
- }
- }, {
- "in" : "query",
- "name" : "sort-column",
- "required" : false,
- "schema" : {
- "enum" : [ "dependents-with-errors", "dependents-errors", "name", "location" ],
- "type" : "string"
- }
- }, {
- "in" : "query",
- "name" : "sort-direction",
- "required" : false,
- "schema" : {
- "enum" : [ "desc", "asc" ],
- "type" : "string"
+ "/api/ee/data-studio/table/unpublish-tables" : {
+ "post" : {
+ "description" : "Unset collection for each of selected tables and all downstream dependents recursively.",
+ "operationId" : "post-api-ee-data-studio-table-unpublish-tables",
+ "parameters" : [ ],
+ "requestBody" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.data-studio.api.table.table-selectors"
+ }
+ }
}
- } ],
+ },
"responses" : {
"2XX" : {
"content" : {
"application/json" : {
"schema" : {
- "properties" : {
- "data" : {
- "items" : {
- "$ref" : "#/components/schemas/metabase-enterprise.dependencies.api.entity"
- },
- "type" : "array"
- },
- "limit" : {
- "description" : "value must be an integer greater than zero.",
- "minimum" : 1,
- "type" : "integer"
- },
- "offset" : {
- "minimum" : 0,
- "type" : "integer"
- },
- "total" : {
- "minimum" : 0,
- "type" : "integer"
- }
- },
- "required" : [ "data", "total", "offset", "limit" ],
- "type" : "object"
+ "type" : "null"
}
}
},
@@ -27285,15 +27044,24 @@
"description" : "Server error response"
}
},
- "summary" : "GET /api/ee/dependencies/graph/unreferenced",
- "tags" : [ "/api/ee/dependencies" ]
+ "summary" : "POST /api/ee/data-studio/table/unpublish-tables",
+ "tags" : [ "/api/ee/data-studio/table" ]
}
},
- "/api/ee/email/override" : {
+ "/api/ee/database-replication/connection/{database-id}" : {
"delete" : {
- "description" : "Clear all cloud email related settings. You must be a superuser or have `setting` permission to do this.",
- "operationId" : "delete-api-ee-email-override",
- "parameters" : [ ],
+ "description" : "Delete PG replication connection for the specified database.",
+ "operationId" : "delete-api-ee-database-replication-connection-database-id",
+ "parameters" : [ {
+ "description" : "value must be an integer greater than zero.",
+ "in" : "path",
+ "name" : "database-id",
+ "required" : true,
+ "schema" : {
+ "minimum" : 1,
+ "type" : "integer"
+ }
+ } ],
"responses" : {
"2XX" : {
"description" : "Successful response"
@@ -27305,52 +27073,39 @@
"description" : "Server error response"
}
},
- "summary" : "DELETE /api/ee/email/override",
- "tags" : [ "/api/ee/email" ]
+ "summary" : "DELETE /api/ee/database-replication/connection/{database-id}",
+ "tags" : [ "/api/ee/database-replication" ]
},
- "put" : {
- "description" : "Update multiple cloud email Settings. You must be a superuser or have `setting` permission to do this.\n Calling this automatically sets `cloud-smtp-enabled` to true if the settings are valid.",
- "operationId" : "put-api-ee-email-override",
- "parameters" : [ ],
+ "post" : {
+ "description" : "Create a new PG replication connection for the specified database.",
+ "operationId" : "post-api-ee-database-replication-connection-database-id",
+ "parameters" : [ {
+ "description" : "value must be an integer greater than zero.",
+ "in" : "path",
+ "name" : "database-id",
+ "required" : true,
+ "schema" : {
+ "minimum" : 1,
+ "type" : "integer"
+ }
+ } ],
"requestBody" : {
"content" : {
"application/json" : {
"schema" : {
"properties" : {
- "email-smtp-host-override" : {
- "anyOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "email-smtp-password-override" : {
- "anyOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "email-smtp-port-override" : {
- "anyOf" : [ {
- "type" : "integer"
- }, {
- "type" : "null"
- } ]
- },
- "email-smtp-security-override" : {
- "anyOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "email-smtp-username-override" : {
- "anyOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
+ "replicationSchemaFilters" : {
+ "properties" : {
+ "schema-filters-patterns" : {
+ "type" : "string"
+ },
+ "schema-filters-type" : {
+ "enum" : [ "inclusion", "exclusion", "all" ],
+ "type" : "string"
+ }
+ },
+ "required" : [ "schema-filters-type", "schema-filters-patterns" ],
+ "type" : "object"
}
},
"type" : "object"
@@ -27369,79 +27124,112 @@
"description" : "Server error response"
}
},
- "summary" : "PUT /api/ee/email/override",
- "tags" : [ "/api/ee/email" ]
+ "summary" : "POST /api/ee/database-replication/connection/{database-id}",
+ "tags" : [ "/api/ee/database-replication" ]
}
},
- "/api/ee/embedding-hub/checklist" : {
- "get" : {
- "description" : "Get the embedding hub checklist status, indicating which setup steps have been completed.",
- "operationId" : "get-api-ee-embedding-hub-checklist",
- "parameters" : [ ],
+ "/api/ee/database-replication/connection/{database-id}/preview" : {
+ "post" : {
+ "description" : "Return info about pg-replication connection that is about to be created.",
+ "operationId" : "post-api-ee-database-replication-connection-database-id-preview",
+ "parameters" : [ {
+ "description" : "value must be an integer greater than zero.",
+ "in" : "path",
+ "name" : "database-id",
+ "required" : true,
+ "schema" : {
+ "minimum" : 1,
+ "type" : "integer"
+ }
+ } ],
+ "requestBody" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "properties" : {
+ "replicationSchemaFilters" : {
+ "properties" : {
+ "schema-filters-patterns" : {
+ "type" : "string"
+ },
+ "schema-filters-type" : {
+ "enum" : [ "inclusion", "exclusion", "all" ],
+ "type" : "string"
+ }
+ },
+ "required" : [ "schema-filters-type", "schema-filters-patterns" ],
+ "type" : "object"
+ }
+ },
+ "type" : "object"
+ }
+ }
+ }
+ },
"responses" : {
"2XX" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "additionalProperties" : false,
- "properties" : {
- "checklist" : {
- "additionalProperties" : false,
+ "description" : "Successful response"
+ },
+ "4XX" : {
+ "description" : "Client error response"
+ },
+ "5XX" : {
+ "description" : "Server error response"
+ }
+ },
+ "summary" : "POST /api/ee/database-replication/connection/{database-id}/preview",
+ "tags" : [ "/api/ee/database-replication" ]
+ }
+ },
+ "/api/ee/database-routing/destination-database" : {
+ "post" : {
+ "description" : "Create new Destination Databases.\n\n Note that unlike the normal `POST /api/database` endpoint, this endpoint does not test that the database is actually\n reachable before adding it — destination details are not required to be valid at creation time, and an\n unreachable destination is fine.",
+ "operationId" : "post-api-ee-database-routing-destination-database",
+ "parameters" : [ {
+ "in" : "query",
+ "name" : "check_connection_details",
+ "required" : false,
+ "schema" : {
+ "type" : "boolean"
+ }
+ } ],
+ "requestBody" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "properties" : {
+ "destinations" : {
+ "items" : {
"properties" : {
- "add-data" : {
- "type" : "boolean"
- },
- "configure-row-column-security" : {
- "type" : "boolean"
- },
- "create-dashboard" : {
- "type" : "boolean"
- },
- "create-models" : {
- "type" : "boolean"
- },
- "create-tenants" : {
- "type" : "boolean"
- },
- "create-test-embed" : {
- "type" : "boolean"
- },
- "data-permissions-and-enable-tenants" : {
- "type" : "boolean"
- },
- "embed-production" : {
- "type" : "boolean"
- },
- "enable-tenants" : {
- "type" : "boolean"
- },
- "setup-data-segregation-strategy" : {
- "type" : "boolean"
- },
- "sso-auth-manual-tested" : {
- "type" : "boolean"
+ "details" : {
+ "description" : "Value must be a map.",
+ "properties" : { },
+ "type" : "object"
},
- "sso-configured" : {
- "type" : "boolean"
+ "name" : {
+ "minLength" : 1,
+ "type" : "string"
}
},
- "required" : [ "add-data", "create-dashboard", "create-models", "configure-row-column-security", "create-test-embed", "embed-production", "sso-configured", "data-permissions-and-enable-tenants", "enable-tenants", "create-tenants", "setup-data-segregation-strategy", "sso-auth-manual-tested" ],
+ "required" : [ "name", "details" ],
"type" : "object"
},
- "data-isolation-strategy" : {
- "oneOf" : [ {
- "enum" : [ "row-column-level-security", "connection-impersonation", "database-routing" ],
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- }
+ "type" : "array"
},
- "required" : [ "checklist", "data-isolation-strategy" ],
- "type" : "object"
- }
+ "router_database_id" : {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
+ }
+ },
+ "required" : [ "router_database_id", "destinations" ],
+ "type" : "object"
}
- },
+ }
+ }
+ },
+ "responses" : {
+ "2XX" : {
"description" : "Successful response"
},
"4XX" : {
@@ -27451,15 +27239,43 @@
"description" : "Server error response"
}
},
- "summary" : "GET /api/ee/embedding-hub/checklist",
- "tags" : [ "/api/ee/embedding-hub" ]
+ "summary" : "POST /api/ee/database-routing/destination-database",
+ "tags" : [ "/api/ee/database-routing" ]
}
},
- "/api/ee/gsheets/connection" : {
- "delete" : {
- "description" : "Disconnect the google service account. There is only one (or zero) at the time of writing.",
- "operationId" : "delete-api-ee-gsheets-connection",
- "parameters" : [ ],
+ "/api/ee/database-routing/router-database/{id}" : {
+ "put" : {
+ "description" : "Updates an existing Database with the `user_attribute` to route on. Will either:\n - turn an existing Database into a Router database\n - change the `user_attribute` used to route for an existing Router database, or\n - turn a Router database into a regular Database\n depending on the value of `user_attribute`",
+ "operationId" : "put-api-ee-database-routing-router-database-id",
+ "parameters" : [ {
+ "description" : "value must be an integer greater than zero.",
+ "in" : "path",
+ "name" : "id",
+ "required" : true,
+ "schema" : {
+ "minimum" : 1,
+ "type" : "integer"
+ }
+ } ],
+ "requestBody" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "properties" : {
+ "user_attribute" : {
+ "oneOf" : [ {
+ "minLength" : 1,
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ }
+ },
+ "type" : "object"
+ }
+ }
+ }
+ },
"responses" : {
"2XX" : {
"description" : "Successful response"
@@ -27471,19 +27287,27 @@
"description" : "Server error response"
}
},
- "summary" : "DELETE /api/ee/gsheets/connection",
- "tags" : [ "/api/ee/gsheets" ]
- },
+ "summary" : "PUT /api/ee/database-routing/router-database/{id}",
+ "tags" : [ "/api/ee/database-routing" ]
+ }
+ },
+ "/api/ee/dependencies/backfill-status" : {
"get" : {
- "description" : "Check the status of a connection. This endpoint gets polled by FE to determine when to\n stop showing the setup widget.\n\n Returns the gsheets shape, with the attached datawarehouse db id at `:db_id`.",
- "operationId" : "get-api-ee-gsheets-connection",
+ "description" : "Returns whether the dependency backfill has pending work.\n `complete` is true when there are no stale or outdated entities awaiting processing.",
+ "operationId" : "get-api-ee-dependencies-backfill-status",
"parameters" : [ ],
"responses" : {
"2XX" : {
"content" : {
"application/json" : {
"schema" : {
- "$ref" : "#/components/schemas/gsheets.response"
+ "properties" : {
+ "complete" : {
+ "type" : "boolean"
+ }
+ },
+ "required" : [ "complete" ],
+ "type" : "object"
}
}
},
@@ -27496,25 +27320,20 @@
"description" : "Server error response"
}
},
- "summary" : "GET /api/ee/gsheets/connection",
- "tags" : [ "/api/ee/gsheets" ]
- },
- "post" : {
- "description" : "Hook up a new google drive folder or sheet that will be watched and have its content ETL'd into Metabase.",
- "operationId" : "post-api-ee-gsheets-connection",
+ "summary" : "GET /api/ee/dependencies/backfill-status",
+ "tags" : [ "/api/ee/dependencies" ]
+ }
+ },
+ "/api/ee/dependencies/check-card" : {
+ "post" : {
+ "description" : "Check a proposed edit to a card, and return the card IDs for those cards this edit will break.",
+ "operationId" : "post-api-ee-dependencies-check-card",
"parameters" : [ ],
"requestBody" : {
"content" : {
"application/json" : {
"schema" : {
- "properties" : {
- "url" : {
- "minLength" : 1,
- "type" : "string"
- }
- },
- "required" : [ "url" ],
- "type" : "object"
+ "$ref" : "#/components/schemas/metabase-enterprise.dependencies.api.card-body"
}
}
}
@@ -27524,7 +27343,7 @@
"content" : {
"application/json" : {
"schema" : {
- "$ref" : "#/components/schemas/gsheets.response"
+ "$ref" : "#/components/schemas/metabase-enterprise.dependencies.api.broken-cards-response"
}
}
},
@@ -27537,51 +27356,42 @@
"description" : "Server error response"
}
},
- "summary" : "POST /api/ee/gsheets/connection",
- "tags" : [ "/api/ee/gsheets" ]
+ "summary" : "POST /api/ee/dependencies/check-card",
+ "tags" : [ "/api/ee/dependencies" ]
}
},
- "/api/ee/gsheets/connection/sync" : {
+ "/api/ee/dependencies/check-snippet" : {
"post" : {
- "description" : "Force a sync of the connection now.\n\n Returns the gsheets shape, with the attached datawarehouse db id at `:db_id`.",
- "operationId" : "post-api-ee-gsheets-connection-sync",
+ "description" : "Check a proposed edit to a native snippet, and return the cards, etc. which will be broken.",
+ "operationId" : "post-api-ee-dependencies-check-snippet",
"parameters" : [ ],
- "responses" : {
- "2XX" : {
- "description" : "Successful response"
- },
- "4XX" : {
- "description" : "Client error response"
- },
- "5XX" : {
- "description" : "Server error response"
+ "requestBody" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "properties" : {
+ "content" : {
+ "type" : "string"
+ },
+ "id" : {
+ "$ref" : "#/components/schemas/metabase.lib.schema.id.snippet"
+ },
+ "name" : {
+ "description" : "snippet names cannot include '}' or start with spaces"
+ }
+ },
+ "required" : [ "id" ],
+ "type" : "object"
+ }
+ }
}
},
- "summary" : "POST /api/ee/gsheets/connection/sync",
- "tags" : [ "/api/ee/gsheets" ]
- }
- },
- "/api/ee/gsheets/service-account" : {
- "get" : {
- "description" : "Checks to see if service-account is setup or not, delegates to HM only if we haven't set it from a metabase cluster\n before.",
- "operationId" : "get-api-ee-gsheets-service-account",
- "parameters" : [ ],
"responses" : {
"2XX" : {
"content" : {
"application/json" : {
"schema" : {
- "properties" : {
- "email" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- }
- },
- "required" : [ "email" ],
- "type" : "object"
+ "$ref" : "#/components/schemas/metabase-enterprise.dependencies.api.broken-cards-response"
}
}
},
@@ -27594,31 +27404,30 @@
"description" : "Server error response"
}
},
- "summary" : "GET /api/ee/gsheets/service-account",
- "tags" : [ "/api/ee/gsheets" ]
+ "summary" : "POST /api/ee/dependencies/check-snippet",
+ "tags" : [ "/api/ee/dependencies" ]
}
},
- "/api/ee/library" : {
- "get" : {
- "description" : "Get the Library. If no library exists, it doesn't fail but returns an empty response",
- "operationId" : "get-api-ee-library",
+ "/api/ee/dependencies/check-transform" : {
+ "post" : {
+ "description" : "Check a proposed edit to a transform, and return the card, transform, etc. IDs for things that will break.",
+ "operationId" : "post-api-ee-dependencies-check-transform",
"parameters" : [ ],
+ "requestBody" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.dependencies.api.transform-body"
+ }
+ }
+ }
+ },
"responses" : {
"2XX" : {
"content" : {
"application/json" : {
"schema" : {
- "anyOf" : [ {
- "$ref" : "#/components/schemas/metabase.collections.schema.CollectionItem"
- }, {
- "properties" : {
- "data" : {
- "type" : "null"
- }
- },
- "required" : [ "data" ],
- "type" : "object"
- } ]
+ "$ref" : "#/components/schemas/metabase-enterprise.dependencies.api.broken-cards-response"
}
}
},
@@ -27631,136 +27440,48 @@
"description" : "Server error response"
}
},
- "summary" : "GET /api/ee/library",
- "tags" : [ "/api/ee/library" ]
- },
- "post" : {
- "description" : "Creates the Library if it doesn't exist. Returns the created collection.\n\n Requires data analyst or superuser permissions.",
- "operationId" : "post-api-ee-library",
- "parameters" : [ ],
- "responses" : {
- "2XX" : {
- "description" : "Successful response"
- },
- "4XX" : {
- "description" : "Client error response"
- },
- "5XX" : {
- "description" : "Server error response"
- }
- },
- "summary" : "POST /api/ee/library",
- "tags" : [ "/api/ee/library" ]
- }
- },
- "/api/ee/library/tree" : {
- "get" : {
- "description" : "This matches /api/collection/tree but only returns the library collection.",
- "operationId" : "get-api-ee-library-tree",
- "parameters" : [ ],
- "responses" : {
- "2XX" : {
- "description" : "Successful response"
- },
- "4XX" : {
- "description" : "Client error response"
- },
- "5XX" : {
- "description" : "Server error response"
- }
- },
- "summary" : "GET /api/ee/library/tree",
- "tags" : [ "/api/ee/library" ]
+ "summary" : "POST /api/ee/dependencies/check-transform",
+ "tags" : [ "/api/ee/dependencies" ]
}
},
- "/api/ee/logs/query_execution/{yyyy-mm}" : {
+ "/api/ee/dependencies/graph" : {
"get" : {
- "description" : "Fetch rows for the month specified by `:yyyy-mm` from the query_execution logs table.\n Must be a superuser.",
- "operationId" : "get-api-ee-logs-query_execution-yyyy-mm",
+ "description" : "This endpoint takes an :id and a supported entity :type, and returns a graph of all its upstream dependencies.\n The graph is represented by a list of :nodes and a list of :edges. Each node has an :id, :type, :data (which\n depends on the node type), and a map of :dependent_counts per entity type. Each edge is a :model/Dependency.\n\n Optional :archived parameter controls whether entities in archived collections are included:\n - false (default): Excludes entities in archived collections\n - true: Includes entities in archived collections",
+ "operationId" : "get-api-ee-dependencies-graph",
"parameters" : [ {
- "description" : "Must be a string like 2020-04 or 2222-11.",
- "in" : "path",
- "name" : "yyyy-mm",
- "required" : true,
+ "description" : "value must be an integer greater than zero.",
+ "in" : "query",
+ "name" : "id",
+ "required" : false,
"schema" : {
- "pattern" : "\\d{4}-\\d{2}",
- "type" : "string"
+ "minimum" : 1,
+ "type" : "integer"
}
- } ],
- "responses" : {
- "2XX" : {
- "description" : "Successful response"
- },
- "4XX" : {
- "description" : "Client error response"
- },
- "5XX" : {
- "description" : "Server error response"
+ }, {
+ "in" : "query",
+ "name" : "type",
+ "required" : false,
+ "schema" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.dependencies.dependency-types.dependency-types"
}
- },
- "summary" : "GET /api/ee/logs/query_execution/{yyyy-mm}",
- "tags" : [ "/api/ee/logs" ]
- }
- },
- "/api/ee/metabot-tools/answer-sources" : {
- "post" : {
- "description" : "Return top level meta information about available information sources.",
- "operationId" : "post-api-ee-metabot-tools-answer-sources",
- "parameters" : [ ],
- "requestBody" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "description" : "Base schema for all tool requests. Contains the conversation ID and optional profile ID.",
- "properties" : {
- "arguments" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.answer-sources-arguments"
- },
- "conversation_id" : {
- "description" : "value must be a valid UUID.",
- "pattern" : "[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",
- "type" : "string"
- },
- "profile_id" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- }
- },
- "required" : [ "conversation_id" ],
- "type" : "object"
- }
- }
+ }, {
+ "in" : "query",
+ "name" : "archived",
+ "required" : false,
+ "schema" : {
+ "type" : "boolean"
}
- },
+ } ],
"responses" : {
"2XX" : {
"content" : {
"application/json" : {
"schema" : {
- "description" : "Base schema for all tool requests. Contains the conversation ID and optional profile ID.",
- "properties" : {
- "conversation_id" : {
- "description" : "value must be a valid UUID.",
- "pattern" : "[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",
- "type" : "string"
- },
- "profile_id" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- }
- },
- "required" : [ "conversation_id" ],
- "type" : "object"
+ "$ref" : "#/components/schemas/metabase-enterprise.dependencies.api.graph-response"
}
}
},
- "description" : "Base schema for all tool requests. Contains the conversation ID and optional profile ID."
+ "description" : "Successful response"
},
"4XX" : {
"description" : "Client error response"
@@ -27769,69 +27490,114 @@
"description" : "Server error response"
}
},
- "summary" : "POST /api/ee/metabot-tools/answer-sources",
- "tags" : [ "/api/ee/metabot-tools" ]
+ "summary" : "GET /api/ee/dependencies/graph",
+ "tags" : [ "/api/ee/dependencies" ]
}
},
- "/api/ee/metabot-tools/check-transform-dependencies" : {
- "post" : {
- "description" : "Check a proposed edit to a transform and return details of cards or transforms that would be broken by the change.",
- "operationId" : "post-api-ee-metabot-tools-check-transform-dependencies",
- "parameters" : [ ],
- "requestBody" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "description" : "Base schema for all tool requests. Contains the conversation ID and optional profile ID.",
- "properties" : {
- "arguments" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.check-transform-dependencies-arguments"
- },
- "conversation_id" : {
- "description" : "value must be a valid UUID.",
- "pattern" : "[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",
- "type" : "string"
- },
- "profile_id" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- }
- },
- "required" : [ "arguments", "conversation_id" ],
- "type" : "object"
- }
- }
+ "/api/ee/dependencies/graph/breaking" : {
+ "get" : {
+ "description" : "Returns a list of entities that are breaking other entities (sources of errors).\n These are tables or cards that other entities depend on, where those dependents\n have validation errors traced back to this source entity.\n\n Accepts optional parameters for filtering:\n - `types`: List of source entity types - only `:card` or `:table` (default: both)\n - `card-types`: List of card types to include when filtering cards (e.g., `[:question :model :metric]`)\n - `query`: Search string to filter by name or location\n - `archived`: Controls whether archived entities are included\n - `include-personal-collections`: Controls whether items in personal collections are included (default: false)\n - `sort-column`: Sort column - `:name`, `:location`, `:dependents-errors`, or `:dependents-with-errors` (default: `:name`)\n - `sort-direction`: Sort direction - `:asc` or `:desc` (default: `:asc`)\n - `offset`: Default 0\n - `limit`: Default 50\n\n Returns a map with:\n - `data`: List of breaking source entities\n - `total`: Total count of matched items\n - `offset`: Applied offset\n - `limit`: Applied limit",
+ "operationId" : "get-api-ee-dependencies-graph-breaking",
+ "parameters" : [ {
+ "in" : "query",
+ "name" : "types",
+ "required" : false,
+ "schema" : {
+ "anyOf" : [ {
+ "$ref" : "#/components/schemas/metabase-enterprise.dependencies.dependency-types.dependency-types"
+ }, {
+ "items" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.dependencies.dependency-types.dependency-types"
+ },
+ "type" : "array"
+ } ]
}
- },
+ }, {
+ "in" : "query",
+ "name" : "card-types",
+ "required" : false,
+ "schema" : {
+ "anyOf" : [ {
+ "enum" : [ "question", "metric", "model" ],
+ "type" : "string"
+ }, {
+ "items" : {
+ "enum" : [ "question", "metric", "model" ],
+ "type" : "string"
+ },
+ "type" : "array"
+ } ]
+ }
+ }, {
+ "in" : "query",
+ "name" : "query",
+ "required" : false,
+ "schema" : {
+ "type" : "string"
+ }
+ }, {
+ "in" : "query",
+ "name" : "archived",
+ "required" : false,
+ "schema" : {
+ "type" : "boolean"
+ }
+ }, {
+ "in" : "query",
+ "name" : "include-personal-collections",
+ "required" : false,
+ "schema" : {
+ "type" : "boolean"
+ }
+ }, {
+ "in" : "query",
+ "name" : "sort-column",
+ "required" : false,
+ "schema" : {
+ "enum" : [ "dependents-with-errors", "dependents-errors", "name", "location" ],
+ "type" : "string"
+ }
+ }, {
+ "in" : "query",
+ "name" : "sort-direction",
+ "required" : false,
+ "schema" : {
+ "enum" : [ "desc", "asc" ],
+ "type" : "string"
+ }
+ } ],
"responses" : {
"2XX" : {
"content" : {
"application/json" : {
"schema" : {
- "description" : "Base schema for all tool requests. Contains the conversation ID and optional profile ID.",
"properties" : {
- "conversation_id" : {
- "description" : "value must be a valid UUID.",
- "pattern" : "[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",
- "type" : "string"
+ "data" : {
+ "items" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.dependencies.api.entity"
+ },
+ "type" : "array"
},
- "profile_id" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
+ "limit" : {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
+ },
+ "offset" : {
+ "minimum" : 0,
+ "type" : "integer"
+ },
+ "total" : {
+ "minimum" : 0,
+ "type" : "integer"
}
},
- "required" : [ "conversation_id" ],
+ "required" : [ "data", "total", "offset", "limit" ],
"type" : "object"
}
}
},
- "description" : "Base schema for all tool requests. Contains the conversation ID and optional profile ID."
+ "description" : "Successful response"
},
"4XX" : {
"description" : "Client error response"
@@ -27840,72 +27606,97 @@
"description" : "Server error response"
}
},
- "summary" : "POST /api/ee/metabot-tools/check-transform-dependencies",
- "tags" : [ "/api/ee/metabot-tools" ]
+ "summary" : "GET /api/ee/dependencies/graph/breaking",
+ "tags" : [ "/api/ee/dependencies" ]
}
},
- "/api/ee/metabot-tools/create-dashboard-subscription" : {
- "post" : {
- "description" : "Create a dashboard subscription.",
- "operationId" : "post-api-ee-metabot-tools-create-dashboard-subscription",
- "parameters" : [ ],
- "requestBody" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "description" : "Base schema for all tool requests. Contains the conversation ID and optional profile ID.",
- "properties" : {
- "arguments" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.create-dashboard-subscription-arguments"
- },
- "conversation_id" : {
- "description" : "value must be a valid UUID.",
- "pattern" : "[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",
- "type" : "string"
- },
- "profile_id" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- }
- },
- "required" : [ "arguments", "conversation_id" ],
- "type" : "object"
- }
- }
+ "/api/ee/dependencies/graph/broken" : {
+ "get" : {
+ "description" : "Returns the broken dependents for a specific source entity.\n These are entities that have validation errors traced back to the specified source.\n\n Required parameters:\n - `id`: The ID of the source entity\n - `type`: The type of the source entity (card, table)\n\n Optional parameters:\n - `dependent-types`: Dependency types to filter by. Can be single value or array.\n - `dependent-card-types`: Card types to filter by when dependent-types includes :card.\n - `include-personal-collections`: Include items in personal collections (default: false)\n - `sort-column`: Column to sort by - name, location, or view-count (default: name)\n - `sort-direction`: Sort direction - asc or desc (default: asc)",
+ "operationId" : "get-api-ee-dependencies-graph-broken",
+ "parameters" : [ {
+ "description" : "value must be an integer greater than zero.",
+ "in" : "query",
+ "name" : "id",
+ "required" : true,
+ "schema" : {
+ "minimum" : 1,
+ "type" : "integer"
}
- },
+ }, {
+ "in" : "query",
+ "name" : "type",
+ "required" : true,
+ "schema" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.dependencies.dependency-types.dependency-types"
+ }
+ }, {
+ "in" : "query",
+ "name" : "dependent-types",
+ "required" : false,
+ "schema" : {
+ "anyOf" : [ {
+ "$ref" : "#/components/schemas/metabase-enterprise.dependencies.dependency-types.dependency-types"
+ }, {
+ "items" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.dependencies.dependency-types.dependency-types"
+ },
+ "type" : "array"
+ } ]
+ }
+ }, {
+ "in" : "query",
+ "name" : "dependent-card-types",
+ "required" : false,
+ "schema" : {
+ "anyOf" : [ {
+ "enum" : [ "question", "metric", "model" ],
+ "type" : "string"
+ }, {
+ "items" : {
+ "enum" : [ "question", "metric", "model" ],
+ "type" : "string"
+ },
+ "type" : "array"
+ } ]
+ }
+ }, {
+ "in" : "query",
+ "name" : "include-personal-collections",
+ "required" : false,
+ "schema" : {
+ "type" : "boolean"
+ }
+ }, {
+ "in" : "query",
+ "name" : "sort-column",
+ "required" : false,
+ "schema" : {
+ "enum" : [ "name", "view-count", "location" ],
+ "type" : "string"
+ }
+ }, {
+ "in" : "query",
+ "name" : "sort-direction",
+ "required" : false,
+ "schema" : {
+ "enum" : [ "desc", "asc" ],
+ "type" : "string"
+ }
+ } ],
"responses" : {
"2XX" : {
"content" : {
"application/json" : {
"schema" : {
- "description" : "Base schema for all tool requests. Contains the conversation ID and optional profile ID.",
- "properties" : {
- "conversation_id" : {
- "description" : "value must be a valid UUID.",
- "pattern" : "[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",
- "type" : "string"
- },
- "output" : {
- "type" : "string"
- },
- "profile_id" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- }
+ "items" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.dependencies.api.broken-dependent-entity"
},
- "required" : [ "output", "conversation_id" ],
- "type" : "object"
+ "type" : "array"
}
}
},
- "description" : "Base schema for all tool requests. Contains the conversation ID and optional profile ID."
+ "description" : "Successful response"
},
"4XX" : {
"description" : "Client error response"
@@ -27914,69 +27705,118 @@
"description" : "Server error response"
}
},
- "summary" : "POST /api/ee/metabot-tools/create-dashboard-subscription",
- "tags" : [ "/api/ee/metabot-tools" ]
+ "summary" : "GET /api/ee/dependencies/graph/broken",
+ "tags" : [ "/api/ee/dependencies" ]
}
},
- "/api/ee/metabot-tools/field-values" : {
- "post" : {
- "description" : "Return statistics and/or values for a given field of a given entity.",
- "operationId" : "post-api-ee-metabot-tools-field-values",
- "parameters" : [ ],
- "requestBody" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "description" : "Base schema for all tool requests. Contains the conversation ID and optional profile ID.",
- "properties" : {
- "arguments" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.field-values-arguments"
- },
- "conversation_id" : {
- "description" : "value must be a valid UUID.",
- "pattern" : "[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",
- "type" : "string"
- },
- "profile_id" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- }
- },
- "required" : [ "arguments", "conversation_id" ],
- "type" : "object"
- }
- }
+ "/api/ee/dependencies/graph/dependents" : {
+ "get" : {
+ "description" : "Returns a list of dependents for the specified entity.\n\n Required parameters:\n - `id`: The ID of the entity\n - `type`: The type of the entity (card, table, dashboard, etc.)\n\n Optional parameters:\n - `dependent-types`: Dependency types to filter by. Can be single value or array.\n If not provided, returns all types. Example: ?dependent-types=card&dependent-types=dashboard\n - `dependent-card-types`: Card types to filter by when dependent-types includes :card.\n Ignored if dependent-types doesn't include :card. Example: ?dependent-card-types=question&dependent-card-types=model\n - `archived`: Include entities in archived collections (default: false)\n - `broken`: Return only broken entities (default: false)\n - `query`: Search string to filter results by name or location (case-insensitive)\n - `include-personal-collections`: Include items in personal collections (default: false)\n - `sort-column`: Column to sort by - name, location, or view-count (default: name)\n - `sort-direction`: Sort direction - asc or desc (default: asc)",
+ "operationId" : "get-api-ee-dependencies-graph-dependents",
+ "parameters" : [ {
+ "description" : "value must be an integer greater than zero.",
+ "in" : "query",
+ "name" : "id",
+ "required" : true,
+ "schema" : {
+ "minimum" : 1,
+ "type" : "integer"
}
- },
+ }, {
+ "in" : "query",
+ "name" : "type",
+ "required" : true,
+ "schema" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.dependencies.dependency-types.dependency-types"
+ }
+ }, {
+ "in" : "query",
+ "name" : "dependent-types",
+ "required" : false,
+ "schema" : {
+ "anyOf" : [ {
+ "$ref" : "#/components/schemas/metabase-enterprise.dependencies.dependency-types.dependency-types"
+ }, {
+ "items" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.dependencies.dependency-types.dependency-types"
+ },
+ "type" : "array"
+ } ]
+ }
+ }, {
+ "in" : "query",
+ "name" : "dependent-card-types",
+ "required" : false,
+ "schema" : {
+ "anyOf" : [ {
+ "enum" : [ "question", "metric", "model" ],
+ "type" : "string"
+ }, {
+ "items" : {
+ "enum" : [ "question", "metric", "model" ],
+ "type" : "string"
+ },
+ "type" : "array"
+ } ]
+ }
+ }, {
+ "in" : "query",
+ "name" : "archived",
+ "required" : false,
+ "schema" : {
+ "type" : "boolean"
+ }
+ }, {
+ "in" : "query",
+ "name" : "broken",
+ "required" : false,
+ "schema" : {
+ "type" : "boolean"
+ }
+ }, {
+ "in" : "query",
+ "name" : "query",
+ "required" : false,
+ "schema" : {
+ "type" : "string"
+ }
+ }, {
+ "in" : "query",
+ "name" : "include-personal-collections",
+ "required" : false,
+ "schema" : {
+ "type" : "boolean"
+ }
+ }, {
+ "in" : "query",
+ "name" : "sort-column",
+ "required" : false,
+ "schema" : {
+ "enum" : [ "name", "view-count", "location" ],
+ "type" : "string"
+ }
+ }, {
+ "in" : "query",
+ "name" : "sort-direction",
+ "required" : false,
+ "schema" : {
+ "enum" : [ "desc", "asc" ],
+ "type" : "string"
+ }
+ } ],
"responses" : {
"2XX" : {
"content" : {
"application/json" : {
"schema" : {
- "description" : "Base schema for all tool requests. Contains the conversation ID and optional profile ID.",
- "properties" : {
- "conversation_id" : {
- "description" : "value must be a valid UUID.",
- "pattern" : "[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",
- "type" : "string"
- },
- "profile_id" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- }
+ "items" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.dependencies.api.entity"
},
- "required" : [ "conversation_id" ],
- "type" : "object"
+ "type" : "array"
}
}
},
- "description" : "Base schema for all tool requests. Contains the conversation ID and optional profile ID."
+ "description" : "Successful response"
},
"4XX" : {
"description" : "Client error response"
@@ -27985,69 +27825,114 @@
"description" : "Server error response"
}
},
- "summary" : "POST /api/ee/metabot-tools/field-values",
- "tags" : [ "/api/ee/metabot-tools" ]
+ "summary" : "GET /api/ee/dependencies/graph/dependents",
+ "tags" : [ "/api/ee/dependencies" ]
}
},
- "/api/ee/metabot-tools/filter-records" : {
- "post" : {
- "description" : "Construct a query from a metric.",
- "operationId" : "post-api-ee-metabot-tools-filter-records",
- "parameters" : [ ],
- "requestBody" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "description" : "Base schema for all tool requests. Contains the conversation ID and optional profile ID.",
- "properties" : {
- "arguments" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.filter-records-arguments"
- },
- "conversation_id" : {
- "description" : "value must be a valid UUID.",
- "pattern" : "[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",
- "type" : "string"
- },
- "profile_id" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- }
- },
- "required" : [ "arguments", "conversation_id" ],
- "type" : "object"
- }
- }
+ "/api/ee/dependencies/graph/unreferenced" : {
+ "get" : {
+ "description" : "Returns a list of all unreferenced items in the instance.\n An unreferenced item is one that is not a dependency of any other item.\n\n Accepts optional parameters for filtering:\n - `types`: List of entity types to include (e.g., [:card :transform :snippet :dashboard])\n - `card-types`: List of card types to include when filtering cards (e.g., [:question :model :metric])\n - `query`: Search string to filter by name or location\n - `archived`: Controls whether archived entities are included\n - `include-personal-collections`: Controls whether items in personal collections are included (default: false)\n - `sort-column`: Sort column - `:name`, `:location`, `:dependents-errors`, or `:dependents-with-errors` (default: `:name`)\n - `sort-direction`: Sort direction - `:asc` or `:desc` (default: `:asc`)\n - `offset`: Default 0\n - `limit`: Default 50\n\n Returns a map with:\n - `data`: List of unreferenced items, each with `:id`, `:type`, and `:data` fields\n - `total`: Total count of matched items\n - `offset`: Applied offset\n - `limit`: Applied limit",
+ "operationId" : "get-api-ee-dependencies-graph-unreferenced",
+ "parameters" : [ {
+ "in" : "query",
+ "name" : "types",
+ "required" : false,
+ "schema" : {
+ "anyOf" : [ {
+ "$ref" : "#/components/schemas/metabase-enterprise.dependencies.dependency-types.dependency-types"
+ }, {
+ "items" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.dependencies.dependency-types.dependency-types"
+ },
+ "type" : "array"
+ } ]
}
- },
+ }, {
+ "in" : "query",
+ "name" : "card-types",
+ "required" : false,
+ "schema" : {
+ "anyOf" : [ {
+ "enum" : [ "question", "metric", "model" ],
+ "type" : "string"
+ }, {
+ "items" : {
+ "enum" : [ "question", "metric", "model" ],
+ "type" : "string"
+ },
+ "type" : "array"
+ } ]
+ }
+ }, {
+ "in" : "query",
+ "name" : "query",
+ "required" : false,
+ "schema" : {
+ "type" : "string"
+ }
+ }, {
+ "in" : "query",
+ "name" : "archived",
+ "required" : false,
+ "schema" : {
+ "type" : "boolean"
+ }
+ }, {
+ "in" : "query",
+ "name" : "include-personal-collections",
+ "required" : false,
+ "schema" : {
+ "type" : "boolean"
+ }
+ }, {
+ "in" : "query",
+ "name" : "sort-column",
+ "required" : false,
+ "schema" : {
+ "enum" : [ "dependents-with-errors", "dependents-errors", "name", "location" ],
+ "type" : "string"
+ }
+ }, {
+ "in" : "query",
+ "name" : "sort-direction",
+ "required" : false,
+ "schema" : {
+ "enum" : [ "desc", "asc" ],
+ "type" : "string"
+ }
+ } ],
"responses" : {
"2XX" : {
"content" : {
"application/json" : {
"schema" : {
- "description" : "Base schema for all tool requests. Contains the conversation ID and optional profile ID.",
"properties" : {
- "conversation_id" : {
- "description" : "value must be a valid UUID.",
- "pattern" : "[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",
- "type" : "string"
+ "data" : {
+ "items" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.dependencies.api.entity"
+ },
+ "type" : "array"
},
- "profile_id" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
+ "limit" : {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
+ },
+ "offset" : {
+ "minimum" : 0,
+ "type" : "integer"
+ },
+ "total" : {
+ "minimum" : 0,
+ "type" : "integer"
}
},
- "required" : [ "conversation_id" ],
+ "required" : [ "data", "total", "offset", "limit" ],
"type" : "object"
}
}
},
- "description" : "Base schema for all tool requests. Contains the conversation ID and optional profile ID."
+ "description" : "Successful response"
},
"4XX" : {
"description" : "Client error response"
@@ -28056,38 +27941,74 @@
"description" : "Server error response"
}
},
- "summary" : "POST /api/ee/metabot-tools/filter-records",
- "tags" : [ "/api/ee/metabot-tools" ]
+ "summary" : "GET /api/ee/dependencies/graph/unreferenced",
+ "tags" : [ "/api/ee/dependencies" ]
}
},
- "/api/ee/metabot-tools/find-outliers" : {
- "post" : {
- "description" : "Find outliers in the values provided by a data source for a given column.",
- "operationId" : "post-api-ee-metabot-tools-find-outliers",
+ "/api/ee/email/override" : {
+ "delete" : {
+ "description" : "Clear all cloud email related settings. You must be a superuser or have `setting` permission to do this.",
+ "operationId" : "delete-api-ee-email-override",
+ "parameters" : [ ],
+ "responses" : {
+ "2XX" : {
+ "description" : "Successful response"
+ },
+ "4XX" : {
+ "description" : "Client error response"
+ },
+ "5XX" : {
+ "description" : "Server error response"
+ }
+ },
+ "summary" : "DELETE /api/ee/email/override",
+ "tags" : [ "/api/ee/email" ]
+ },
+ "put" : {
+ "description" : "Update multiple cloud email Settings. You must be a superuser or have `setting` permission to do this.\n Calling this automatically sets `cloud-smtp-enabled` to true if the settings are valid.",
+ "operationId" : "put-api-ee-email-override",
"parameters" : [ ],
"requestBody" : {
"content" : {
"application/json" : {
"schema" : {
- "description" : "Base schema for all tool requests. Contains the conversation ID and optional profile ID.",
"properties" : {
- "arguments" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.find-outliers-arguments"
+ "email-smtp-host-override" : {
+ "anyOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
},
- "conversation_id" : {
- "description" : "value must be a valid UUID.",
- "pattern" : "[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",
- "type" : "string"
+ "email-smtp-password-override" : {
+ "anyOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
},
- "profile_id" : {
- "oneOf" : [ {
+ "email-smtp-port-override" : {
+ "anyOf" : [ {
+ "type" : "integer"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "email-smtp-security-override" : {
+ "anyOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "email-smtp-username-override" : {
+ "anyOf" : [ {
"type" : "string"
}, {
"type" : "null"
} ]
}
},
- "required" : [ "arguments", "conversation_id" ],
"type" : "object"
}
}
@@ -28095,30 +28016,7 @@
},
"responses" : {
"2XX" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "description" : "Base schema for all tool requests. Contains the conversation ID and optional profile ID.",
- "properties" : {
- "conversation_id" : {
- "description" : "value must be a valid UUID.",
- "pattern" : "[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",
- "type" : "string"
- },
- "profile_id" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- }
- },
- "required" : [ "conversation_id" ],
- "type" : "object"
- }
- }
- },
- "description" : "Base schema for all tool requests. Contains the conversation ID and optional profile ID."
+ "description" : "Successful response"
},
"4XX" : {
"description" : "Client error response"
@@ -28127,78 +28025,83 @@
"description" : "Server error response"
}
},
- "summary" : "POST /api/ee/metabot-tools/find-outliers",
- "tags" : [ "/api/ee/metabot-tools" ]
+ "summary" : "PUT /api/ee/email/override",
+ "tags" : [ "/api/ee/email" ]
}
},
- "/api/ee/metabot-tools/generate-insights" : {
- "post" : {
- "description" : "Generate insights.",
- "operationId" : "post-api-ee-metabot-tools-generate-insights",
+ "/api/ee/embedding-hub/checklist" : {
+ "get" : {
+ "description" : "Get the embedding hub checklist status, indicating which setup steps have been completed.",
+ "operationId" : "get-api-ee-embedding-hub-checklist",
"parameters" : [ ],
- "requestBody" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "description" : "Base schema for all tool requests. Contains the conversation ID and optional profile ID.",
- "properties" : {
- "arguments" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.generate-insights-arguments"
- },
- "conversation_id" : {
- "description" : "value must be a valid UUID.",
- "pattern" : "[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",
- "type" : "string"
- },
- "profile_id" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- }
- },
- "required" : [ "arguments", "conversation_id" ],
- "type" : "object"
- }
- }
- }
- },
"responses" : {
"2XX" : {
"content" : {
"application/json" : {
"schema" : {
- "description" : "Base schema for all tool requests. Contains the conversation ID and optional profile ID.",
+ "additionalProperties" : false,
"properties" : {
- "conversation_id" : {
- "description" : "value must be a valid UUID.",
- "pattern" : "[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",
- "type" : "string"
- },
- "output" : {
- "type" : "string"
+ "checklist" : {
+ "additionalProperties" : false,
+ "properties" : {
+ "add-data" : {
+ "type" : "boolean"
+ },
+ "configure-row-column-security" : {
+ "type" : "boolean"
+ },
+ "create-dashboard" : {
+ "type" : "boolean"
+ },
+ "create-models" : {
+ "type" : "boolean"
+ },
+ "create-tenants" : {
+ "type" : "boolean"
+ },
+ "create-test-embed" : {
+ "type" : "boolean"
+ },
+ "data-permissions-and-enable-tenants" : {
+ "type" : "boolean"
+ },
+ "embed-production" : {
+ "type" : "boolean"
+ },
+ "enable-tenants" : {
+ "type" : "boolean"
+ },
+ "move-dashboard-to-shared" : {
+ "type" : "boolean"
+ },
+ "setup-data-segregation-strategy" : {
+ "type" : "boolean"
+ },
+ "sso-auth-manual-tested" : {
+ "type" : "boolean"
+ },
+ "sso-configured" : {
+ "type" : "boolean"
+ }
+ },
+ "required" : [ "add-data", "create-dashboard", "create-models", "configure-row-column-security", "create-test-embed", "embed-production", "sso-configured", "data-permissions-and-enable-tenants", "enable-tenants", "move-dashboard-to-shared", "create-tenants", "setup-data-segregation-strategy", "sso-auth-manual-tested" ],
+ "type" : "object"
},
- "profile_id" : {
+ "data-isolation-strategy" : {
"oneOf" : [ {
+ "enum" : [ "row-column-level-security", "connection-impersonation", "database-routing" ],
"type" : "string"
}, {
"type" : "null"
} ]
- },
- "reactions" : {
- "items" : {
- "$ref" : "#/components/schemas/metabot.reaction.redirect"
- },
- "type" : "array"
}
},
- "required" : [ "output", "reactions", "conversation_id" ],
+ "required" : [ "checklist", "data-isolation-strategy" ],
"type" : "object"
}
}
},
- "description" : "Base schema for all tool requests. Contains the conversation ID and optional profile ID."
+ "description" : "Successful response"
},
"4XX" : {
"description" : "Client error response"
@@ -28207,50 +28110,43 @@
"description" : "Server error response"
}
},
- "summary" : "POST /api/ee/metabot-tools/generate-insights",
- "tags" : [ "/api/ee/metabot-tools" ]
+ "summary" : "GET /api/ee/embedding-hub/checklist",
+ "tags" : [ "/api/ee/embedding-hub" ]
}
},
- "/api/ee/metabot-tools/get-current-user" : {
- "post" : {
- "description" : "Get information about user that started the conversation.",
- "operationId" : "post-api-ee-metabot-tools-get-current-user",
+ "/api/ee/gsheets/connection" : {
+ "delete" : {
+ "description" : "Disconnect the google service account. There is only one (or zero) at the time of writing.",
+ "operationId" : "delete-api-ee-gsheets-connection",
"parameters" : [ ],
- "requestBody" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.deftool.tool-request"
- }
- }
+ "responses" : {
+ "2XX" : {
+ "description" : "Successful response"
+ },
+ "4XX" : {
+ "description" : "Client error response"
+ },
+ "5XX" : {
+ "description" : "Server error response"
}
},
+ "summary" : "DELETE /api/ee/gsheets/connection",
+ "tags" : [ "/api/ee/gsheets" ]
+ },
+ "get" : {
+ "description" : "Check the status of a connection. This endpoint gets polled by FE to determine when to\n stop showing the setup widget.\n\n Returns the gsheets shape, with the attached datawarehouse db id at `:db_id`.",
+ "operationId" : "get-api-ee-gsheets-connection",
+ "parameters" : [ ],
"responses" : {
"2XX" : {
"content" : {
"application/json" : {
"schema" : {
- "description" : "Base schema for all tool requests. Contains the conversation ID and optional profile ID.",
- "properties" : {
- "conversation_id" : {
- "description" : "value must be a valid UUID.",
- "pattern" : "[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",
- "type" : "string"
- },
- "profile_id" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- }
- },
- "required" : [ "conversation_id" ],
- "type" : "object"
+ "$ref" : "#/components/schemas/gsheets.response"
}
}
},
- "description" : "Base schema for all tool requests. Contains the conversation ID and optional profile ID."
+ "description" : "Successful response"
},
"4XX" : {
"description" : "Client error response"
@@ -28259,38 +28155,24 @@
"description" : "Server error response"
}
},
- "summary" : "POST /api/ee/metabot-tools/get-current-user",
- "tags" : [ "/api/ee/metabot-tools" ]
- }
- },
- "/api/ee/metabot-tools/get-dashboard-details" : {
+ "summary" : "GET /api/ee/gsheets/connection",
+ "tags" : [ "/api/ee/gsheets" ]
+ },
"post" : {
- "description" : "Get information about a given dashboard.",
- "operationId" : "post-api-ee-metabot-tools-get-dashboard-details",
+ "description" : "Hook up a new google drive folder or sheet that will be watched and have its content ETL'd into Metabase.",
+ "operationId" : "post-api-ee-gsheets-connection",
"parameters" : [ ],
"requestBody" : {
"content" : {
"application/json" : {
"schema" : {
- "description" : "Base schema for all tool requests. Contains the conversation ID and optional profile ID.",
"properties" : {
- "arguments" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.get-dashboard-details-arguments"
- },
- "conversation_id" : {
- "description" : "value must be a valid UUID.",
- "pattern" : "[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",
+ "url" : {
+ "minLength" : 1,
"type" : "string"
- },
- "profile_id" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
}
},
- "required" : [ "arguments", "conversation_id" ],
+ "required" : [ "url" ],
"type" : "object"
}
}
@@ -28301,27 +28183,11 @@
"content" : {
"application/json" : {
"schema" : {
- "description" : "Base schema for all tool requests. Contains the conversation ID and optional profile ID.",
- "properties" : {
- "conversation_id" : {
- "description" : "value must be a valid UUID.",
- "pattern" : "[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",
- "type" : "string"
- },
- "profile_id" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- }
- },
- "required" : [ "conversation_id" ],
- "type" : "object"
+ "$ref" : "#/components/schemas/gsheets.response"
}
}
},
- "description" : "Base schema for all tool requests. Contains the conversation ID and optional profile ID."
+ "description" : "Successful response"
},
"4XX" : {
"description" : "Client error response"
@@ -28330,56 +28196,42 @@
"description" : "Server error response"
}
},
- "summary" : "POST /api/ee/metabot-tools/get-dashboard-details",
- "tags" : [ "/api/ee/metabot-tools" ]
+ "summary" : "POST /api/ee/gsheets/connection",
+ "tags" : [ "/api/ee/gsheets" ]
}
},
- "/api/ee/metabot-tools/get-document-details" : {
+ "/api/ee/gsheets/connection/sync" : {
"post" : {
- "description" : "Get information about a given document.",
- "operationId" : "post-api-ee-metabot-tools-get-document-details",
+ "description" : "Force a sync of the connection now.\n\n Returns the gsheets shape, with the attached datawarehouse db id at `:db_id`.",
+ "operationId" : "post-api-ee-gsheets-connection-sync",
"parameters" : [ ],
- "requestBody" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "description" : "Base schema for all tool requests. Contains the conversation ID and optional profile ID.",
- "properties" : {
- "arguments" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.get-document-details-arguments"
- },
- "conversation_id" : {
- "description" : "value must be a valid UUID.",
- "pattern" : "[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",
- "type" : "string"
- },
- "profile_id" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- }
- },
- "required" : [ "arguments", "conversation_id" ],
- "type" : "object"
- }
- }
+ "responses" : {
+ "2XX" : {
+ "description" : "Successful response"
+ },
+ "4XX" : {
+ "description" : "Client error response"
+ },
+ "5XX" : {
+ "description" : "Server error response"
}
},
+ "summary" : "POST /api/ee/gsheets/connection/sync",
+ "tags" : [ "/api/ee/gsheets" ]
+ }
+ },
+ "/api/ee/gsheets/service-account" : {
+ "get" : {
+ "description" : "Checks to see if service-account is setup or not, delegates to HM only if we haven't set it from a metabase cluster\n before.",
+ "operationId" : "get-api-ee-gsheets-service-account",
+ "parameters" : [ ],
"responses" : {
"2XX" : {
"content" : {
"application/json" : {
"schema" : {
- "description" : "Base schema for all tool requests. Contains the conversation ID and optional profile ID.",
"properties" : {
- "conversation_id" : {
- "description" : "value must be a valid UUID.",
- "pattern" : "[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",
- "type" : "string"
- },
- "profile_id" : {
+ "email" : {
"oneOf" : [ {
"type" : "string"
}, {
@@ -28387,12 +28239,12 @@
} ]
}
},
- "required" : [ "conversation_id" ],
+ "required" : [ "email" ],
"type" : "object"
}
}
},
- "description" : "Base schema for all tool requests. Contains the conversation ID and optional profile ID."
+ "description" : "Successful response"
},
"4XX" : {
"description" : "Client error response"
@@ -28401,69 +28253,35 @@
"description" : "Server error response"
}
},
- "summary" : "POST /api/ee/metabot-tools/get-document-details",
- "tags" : [ "/api/ee/metabot-tools" ]
+ "summary" : "GET /api/ee/gsheets/service-account",
+ "tags" : [ "/api/ee/gsheets" ]
}
},
- "/api/ee/metabot-tools/get-metric-details" : {
- "post" : {
- "description" : "Get information about a given metric.",
- "operationId" : "post-api-ee-metabot-tools-get-metric-details",
+ "/api/ee/library" : {
+ "get" : {
+ "description" : "Get the Library. If no library exists, it doesn't fail but returns an empty response",
+ "operationId" : "get-api-ee-library",
"parameters" : [ ],
- "requestBody" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "description" : "Base schema for all tool requests. Contains the conversation ID and optional profile ID.",
- "properties" : {
- "arguments" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.get-metric-details-arguments"
- },
- "conversation_id" : {
- "description" : "value must be a valid UUID.",
- "pattern" : "[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",
- "type" : "string"
- },
- "profile_id" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- }
- },
- "required" : [ "arguments", "conversation_id" ],
- "type" : "object"
- }
- }
- }
- },
"responses" : {
"2XX" : {
"content" : {
"application/json" : {
"schema" : {
- "description" : "Base schema for all tool requests. Contains the conversation ID and optional profile ID.",
- "properties" : {
- "conversation_id" : {
- "description" : "value must be a valid UUID.",
- "pattern" : "[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",
- "type" : "string"
- },
- "profile_id" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
+ "anyOf" : [ {
+ "$ref" : "#/components/schemas/metabase.collections.schema.CollectionItem"
+ }, {
+ "properties" : {
+ "data" : {
"type" : "null"
- } ]
- }
- },
- "required" : [ "conversation_id" ],
- "type" : "object"
+ }
+ },
+ "required" : [ "data" ],
+ "type" : "object"
+ } ]
}
}
},
- "description" : "Base schema for all tool requests. Contains the conversation ID and optional profile ID."
+ "description" : "Successful response"
},
"4XX" : {
"description" : "Client error response"
@@ -28472,69 +28290,16 @@
"description" : "Server error response"
}
},
- "summary" : "POST /api/ee/metabot-tools/get-metric-details",
- "tags" : [ "/api/ee/metabot-tools" ]
- }
- },
- "/api/ee/metabot-tools/get-query-details" : {
+ "summary" : "GET /api/ee/library",
+ "tags" : [ "/api/ee/library" ]
+ },
"post" : {
- "description" : "Get information about a given query.",
- "operationId" : "post-api-ee-metabot-tools-get-query-details",
+ "description" : "Creates the Library if it doesn't exist. Returns the created collection.\n\n Requires data analyst or superuser permissions.",
+ "operationId" : "post-api-ee-library",
"parameters" : [ ],
- "requestBody" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "description" : "Base schema for all tool requests. Contains the conversation ID and optional profile ID.",
- "properties" : {
- "arguments" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.get-query-details-arguments"
- },
- "conversation_id" : {
- "description" : "value must be a valid UUID.",
- "pattern" : "[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",
- "type" : "string"
- },
- "profile_id" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- }
- },
- "required" : [ "arguments", "conversation_id" ],
- "type" : "object"
- }
- }
- }
- },
"responses" : {
"2XX" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "description" : "Base schema for all tool requests. Contains the conversation ID and optional profile ID.",
- "properties" : {
- "conversation_id" : {
- "description" : "value must be a valid UUID.",
- "pattern" : "[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",
- "type" : "string"
- },
- "profile_id" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- }
- },
- "required" : [ "conversation_id" ],
- "type" : "object"
- }
- }
- },
- "description" : "Base schema for all tool requests. Contains the conversation ID and optional profile ID."
+ "description" : "Successful response"
},
"4XX" : {
"description" : "Client error response"
@@ -28543,69 +28308,47 @@
"description" : "Server error response"
}
},
- "summary" : "POST /api/ee/metabot-tools/get-query-details",
- "tags" : [ "/api/ee/metabot-tools" ]
+ "summary" : "POST /api/ee/library",
+ "tags" : [ "/api/ee/library" ]
}
},
- "/api/ee/metabot-tools/get-report-details" : {
- "post" : {
- "description" : "Get information about a given report.",
- "operationId" : "post-api-ee-metabot-tools-get-report-details",
+ "/api/ee/library/tree" : {
+ "get" : {
+ "description" : "This matches /api/collection/tree but only returns the library collection.",
+ "operationId" : "get-api-ee-library-tree",
"parameters" : [ ],
- "requestBody" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "description" : "Base schema for all tool requests. Contains the conversation ID and optional profile ID.",
- "properties" : {
- "arguments" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.get-report-details-arguments"
- },
- "conversation_id" : {
- "description" : "value must be a valid UUID.",
- "pattern" : "[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",
- "type" : "string"
- },
- "profile_id" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- }
- },
- "required" : [ "arguments", "conversation_id" ],
- "type" : "object"
- }
- }
+ "responses" : {
+ "2XX" : {
+ "description" : "Successful response"
+ },
+ "4XX" : {
+ "description" : "Client error response"
+ },
+ "5XX" : {
+ "description" : "Server error response"
}
},
+ "summary" : "GET /api/ee/library/tree",
+ "tags" : [ "/api/ee/library" ]
+ }
+ },
+ "/api/ee/logs/query_execution/{yyyy-mm}" : {
+ "get" : {
+ "description" : "Fetch rows for the month specified by `:yyyy-mm` from the query_execution logs table.\n Must be a superuser.",
+ "operationId" : "get-api-ee-logs-query_execution-yyyy-mm",
+ "parameters" : [ {
+ "description" : "Must be a string like 2020-04 or 2222-11.",
+ "in" : "path",
+ "name" : "yyyy-mm",
+ "required" : true,
+ "schema" : {
+ "pattern" : "\\d{4}-\\d{2}",
+ "type" : "string"
+ }
+ } ],
"responses" : {
"2XX" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "description" : "Base schema for all tool requests. Contains the conversation ID and optional profile ID.",
- "properties" : {
- "conversation_id" : {
- "description" : "value must be a valid UUID.",
- "pattern" : "[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",
- "type" : "string"
- },
- "profile_id" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- }
- },
- "required" : [ "conversation_id" ],
- "type" : "object"
- }
- }
- },
- "description" : "Base schema for all tool requests. Contains the conversation ID and optional profile ID."
+ "description" : "Successful response"
},
"4XX" : {
"description" : "Client error response"
@@ -28614,72 +28357,254 @@
"description" : "Server error response"
}
},
- "summary" : "POST /api/ee/metabot-tools/get-report-details",
- "tags" : [ "/api/ee/metabot-tools" ]
+ "summary" : "GET /api/ee/logs/query_execution/{yyyy-mm}",
+ "tags" : [ "/api/ee/logs" ]
}
},
- "/api/ee/metabot-tools/get-snippet-details" : {
- "post" : {
- "description" : "Get the content of a single SQL snippet.",
- "operationId" : "post-api-ee-metabot-tools-get-snippet-details",
- "parameters" : [ ],
- "requestBody" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "description" : "Base schema for all tool requests. Contains the conversation ID and optional profile ID.",
- "properties" : {
- "arguments" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.get-snippet-details-arguments"
- },
- "conversation_id" : {
- "description" : "value must be a valid UUID.",
- "pattern" : "[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",
- "type" : "string"
- },
- "profile_id" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- }
- },
- "required" : [ "arguments", "conversation_id" ],
- "type" : "object"
- }
- }
+ "/api/ee/metabot-analytics/conversations" : {
+ "get" : {
+ "description" : "Return paginated list of AI conversations with summary statistics.",
+ "operationId" : "get-api-ee-metabot-analytics-conversations",
+ "parameters" : [ {
+ "in" : "query",
+ "name" : "sort_by",
+ "required" : false,
+ "schema" : {
+ "oneOf" : [ {
+ "enum" : [ "created_at", "message_count", "total_tokens" ],
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
}
- },
+ }, {
+ "in" : "query",
+ "name" : "sort_dir",
+ "required" : false,
+ "schema" : {
+ "oneOf" : [ {
+ "enum" : [ "asc", "desc" ],
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ }
+ }, {
+ "in" : "query",
+ "name" : "user_id",
+ "required" : false,
+ "schema" : {
+ "oneOf" : [ {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
+ }, {
+ "type" : "null"
+ } ]
+ }
+ }, {
+ "in" : "query",
+ "name" : "group_id",
+ "required" : false,
+ "schema" : {
+ "oneOf" : [ {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
+ }, {
+ "type" : "null"
+ } ]
+ }
+ }, {
+ "in" : "query",
+ "name" : "tenant_id",
+ "required" : false,
+ "schema" : {
+ "oneOf" : [ {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
+ }, {
+ "type" : "null"
+ } ]
+ }
+ }, {
+ "in" : "query",
+ "name" : "date",
+ "required" : false,
+ "schema" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ }
+ } ],
"responses" : {
"2XX" : {
"content" : {
"application/json" : {
"schema" : {
- "description" : "Base schema for all tool requests. Contains the conversation ID and optional profile ID.",
"properties" : {
- "conversation_id" : {
- "description" : "value must be a valid UUID.",
- "pattern" : "[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",
- "type" : "string"
+ "data" : {
+ "items" : {
+ "properties" : {
+ "assistant_message_count" : {
+ "description" : "value must be an integer greater or equal to than zero.",
+ "minimum" : 0,
+ "type" : "integer"
+ },
+ "conversation_id" : {
+ "description" : "value must be a valid UUID.",
+ "pattern" : "[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",
+ "type" : "string"
+ },
+ "created_at" : {
+ "format" : "date-time",
+ "type" : "string"
+ },
+ "embedding_hostname" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "embedding_path" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "ip_address" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "last_message_at" : {
+ "oneOf" : [ {
+ "format" : "date-time",
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "message_count" : {
+ "description" : "value must be an integer greater or equal to than zero.",
+ "minimum" : 0,
+ "type" : "integer"
+ },
+ "profile_id" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "query_count" : {
+ "description" : "value must be an integer greater or equal to than zero.",
+ "minimum" : 0,
+ "type" : "integer"
+ },
+ "sanitized_user_agent" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "search_count" : {
+ "description" : "value must be an integer greater or equal to than zero.",
+ "minimum" : 0,
+ "type" : "integer"
+ },
+ "summary" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "total_tokens" : {
+ "description" : "value must be an integer greater or equal to than zero.",
+ "minimum" : 0,
+ "type" : "integer"
+ },
+ "user" : {
+ "oneOf" : [ {
+ "properties" : {
+ "email" : {
+ "type" : "string"
+ },
+ "first_name" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "id" : {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
+ },
+ "last_name" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ }
+ },
+ "required" : [ "id", "email", "first_name", "last_name" ],
+ "type" : "object"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "user_agent" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "user_message_count" : {
+ "description" : "value must be an integer greater or equal to than zero.",
+ "minimum" : 0,
+ "type" : "integer"
+ }
+ },
+ "required" : [ "conversation_id", "created_at", "summary", "message_count", "user_message_count", "assistant_message_count", "total_tokens", "last_message_at", "profile_id", "search_count", "query_count", "ip_address", "embedding_hostname", "embedding_path", "user_agent", "sanitized_user_agent", "user" ],
+ "type" : "object"
+ },
+ "type" : "array"
},
- "profile_id" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
+ "limit" : {
+ "description" : "value must be an integer greater or equal to than zero.",
+ "minimum" : 0,
+ "type" : "integer"
+ },
+ "offset" : {
+ "description" : "value must be an integer greater or equal to than zero.",
+ "minimum" : 0,
+ "type" : "integer"
},
- "structured_output" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.full-snippet"
+ "total" : {
+ "description" : "value must be an integer greater or equal to than zero.",
+ "minimum" : 0,
+ "type" : "integer"
}
},
- "required" : [ "structured_output", "conversation_id" ],
+ "required" : [ "data", "total", "limit", "offset" ],
"type" : "object"
}
}
},
- "description" : "Base schema for all tool requests. Contains the conversation ID and optional profile ID."
+ "description" : "Successful response"
},
"4XX" : {
"description" : "Client error response"
@@ -28688,254 +28613,159 @@
"description" : "Server error response"
}
},
- "summary" : "POST /api/ee/metabot-tools/get-snippet-details",
- "tags" : [ "/api/ee/metabot-tools" ]
+ "summary" : "GET /api/ee/metabot-analytics/conversations",
+ "tags" : [ "/api/ee/metabot-analytics" ]
}
},
- "/api/ee/metabot-tools/get-snippets" : {
- "post" : {
- "description" : "Get a list of all known SQL snippets.",
- "operationId" : "post-api-ee-metabot-tools-get-snippets",
- "parameters" : [ ],
- "requestBody" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.deftool.tool-request"
- }
- }
+ "/api/ee/metabot-analytics/conversations/{id}" : {
+ "get" : {
+ "description" : "Return full details for a specific conversation including all messages.",
+ "operationId" : "get-api-ee-metabot-analytics-conversations-id",
+ "parameters" : [ {
+ "description" : "value must be a valid UUID.",
+ "in" : "path",
+ "name" : "id",
+ "required" : true,
+ "schema" : {
+ "pattern" : "[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",
+ "type" : "string"
}
- },
+ } ],
"responses" : {
"2XX" : {
"content" : {
"application/json" : {
"schema" : {
- "description" : "Base schema for all tool requests. Contains the conversation ID and optional profile ID.",
"properties" : {
+ "chat_messages" : {
+ "items" : {
+ "properties" : { },
+ "type" : "object"
+ },
+ "type" : "array"
+ },
"conversation_id" : {
"description" : "value must be a valid UUID.",
"pattern" : "[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",
"type" : "string"
},
- "profile_id" : {
+ "created_at" : {
+ "format" : "date-time",
+ "type" : "string"
+ },
+ "embedding_hostname" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "embedding_path" : {
"oneOf" : [ {
"type" : "string"
}, {
"type" : "null"
} ]
},
- "structured_output" : {
+ "feedback" : {
"items" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.basic-snippet"
- },
- "type" : "array"
- }
- },
- "required" : [ "structured_output", "conversation_id" ],
- "type" : "object"
- }
- }
- },
- "description" : "Base schema for all tool requests. Contains the conversation ID and optional profile ID."
- },
- "4XX" : {
- "description" : "Client error response"
- },
- "5XX" : {
- "description" : "Server error response"
- }
- },
- "summary" : "POST /api/ee/metabot-tools/get-snippets",
- "tags" : [ "/api/ee/metabot-tools" ]
- }
- },
- "/api/ee/metabot-tools/get-table-details" : {
- "post" : {
- "description" : "Get information about a given table or model.",
- "operationId" : "post-api-ee-metabot-tools-get-table-details",
- "parameters" : [ ],
- "requestBody" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "description" : "Base schema for all tool requests. Contains the conversation ID and optional profile ID.",
- "properties" : {
- "arguments" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.get-table-details-arguments"
- },
- "conversation_id" : {
- "description" : "value must be a valid UUID.",
- "pattern" : "[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",
- "type" : "string"
- },
- "profile_id" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- }
- },
- "required" : [ "arguments", "conversation_id" ],
- "type" : "object"
- }
- }
- }
- },
- "responses" : {
- "2XX" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "description" : "Base schema for all tool requests. Contains the conversation ID and optional profile ID.",
- "properties" : {
- "conversation_id" : {
- "description" : "value must be a valid UUID.",
- "pattern" : "[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",
- "type" : "string"
+ "properties" : {
+ "created_at" : {
+ "format" : "date-time",
+ "type" : "string"
+ },
+ "external_id" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "freeform_feedback" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "id" : {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
+ },
+ "issue_type" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "message_id" : {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
+ },
+ "positive" : {
+ "type" : "boolean"
+ },
+ "updated_at" : {
+ "format" : "date-time",
+ "type" : "string"
+ },
+ "user" : {
+ "oneOf" : [ {
+ "properties" : {
+ "email" : {
+ "type" : "string"
+ },
+ "first_name" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "id" : {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
+ },
+ "last_name" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ }
+ },
+ "required" : [ "id", "email", "first_name", "last_name" ],
+ "type" : "object"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "user_id" : {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
+ }
+ },
+ "required" : [ "id", "message_id", "user_id", "external_id", "positive", "issue_type", "freeform_feedback", "created_at", "updated_at" ],
+ "type" : "object"
+ },
+ "type" : "array"
},
- "profile_id" : {
+ "ip_address" : {
"oneOf" : [ {
"type" : "string"
}, {
"type" : "null"
} ]
- }
- },
- "required" : [ "conversation_id" ],
- "type" : "object"
- }
- }
- },
- "description" : "Base schema for all tool requests. Contains the conversation ID and optional profile ID."
- },
- "4XX" : {
- "description" : "Client error response"
- },
- "5XX" : {
- "description" : "Server error response"
- }
- },
- "summary" : "POST /api/ee/metabot-tools/get-table-details",
- "tags" : [ "/api/ee/metabot-tools" ]
- }
- },
- "/api/ee/metabot-tools/get-tables" : {
- "post" : {
- "description" : "Get information about the tables in a given database.",
- "operationId" : "post-api-ee-metabot-tools-get-tables",
- "parameters" : [ ],
- "requestBody" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "description" : "Base schema for all tool requests. Contains the conversation ID and optional profile ID.",
- "properties" : {
- "arguments" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.get-tables-arguments"
- },
- "conversation_id" : {
- "description" : "value must be a valid UUID.",
- "pattern" : "[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",
- "type" : "string"
- },
- "profile_id" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- }
- },
- "required" : [ "arguments", "conversation_id" ],
- "type" : "object"
- }
- }
- }
- },
- "responses" : {
- "2XX" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "description" : "Base schema for all tool requests. Contains the conversation ID and optional profile ID.",
- "properties" : {
- "conversation_id" : {
- "description" : "value must be a valid UUID.",
- "pattern" : "[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",
- "type" : "string"
},
- "profile_id" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- }
- },
- "required" : [ "conversation_id" ],
- "type" : "object"
- }
- }
- },
- "description" : "Base schema for all tool requests. Contains the conversation ID and optional profile ID."
- },
- "4XX" : {
- "description" : "Client error response"
- },
- "5XX" : {
- "description" : "Server error response"
- }
- },
- "summary" : "POST /api/ee/metabot-tools/get-tables",
- "tags" : [ "/api/ee/metabot-tools" ]
- }
- },
- "/api/ee/metabot-tools/get-transform-details" : {
- "post" : {
- "description" : "Get information about a transform.",
- "operationId" : "post-api-ee-metabot-tools-get-transform-details",
- "parameters" : [ ],
- "requestBody" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "description" : "Base schema for all tool requests. Contains the conversation ID and optional profile ID.",
- "properties" : {
- "arguments" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.get-transform-details-arguments"
- },
- "conversation_id" : {
- "description" : "value must be a valid UUID.",
- "pattern" : "[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",
- "type" : "string"
- },
- "profile_id" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- }
- },
- "required" : [ "arguments", "conversation_id" ],
- "type" : "object"
- }
- }
- }
- },
- "responses" : {
- "2XX" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "description" : "Base schema for all tool requests. Contains the conversation ID and optional profile ID.",
- "properties" : {
- "conversation_id" : {
- "description" : "value must be a valid UUID.",
- "pattern" : "[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",
- "type" : "string"
+ "message_count" : {
+ "description" : "value must be an integer greater or equal to than zero.",
+ "minimum" : 0,
+ "type" : "integer"
},
"profile_id" : {
"oneOf" : [ {
@@ -28943,623 +28773,161 @@
}, {
"type" : "null"
} ]
- }
- },
- "required" : [ "conversation_id" ],
- "type" : "object"
- }
- }
- },
- "description" : "Base schema for all tool requests. Contains the conversation ID and optional profile ID."
- },
- "4XX" : {
- "description" : "Client error response"
- },
- "5XX" : {
- "description" : "Server error response"
- }
- },
- "summary" : "POST /api/ee/metabot-tools/get-transform-details",
- "tags" : [ "/api/ee/metabot-tools" ]
- }
- },
- "/api/ee/metabot-tools/get-transform-python-library-details" : {
- "post" : {
- "description" : "Get information about a Python library by path.",
- "operationId" : "post-api-ee-metabot-tools-get-transform-python-library-details",
- "parameters" : [ ],
- "requestBody" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "description" : "Base schema for all tool requests. Contains the conversation ID and optional profile ID.",
- "properties" : {
- "arguments" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.get-transform-python-library-details-arguments"
- },
- "conversation_id" : {
- "description" : "value must be a valid UUID.",
- "pattern" : "[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",
- "type" : "string"
- },
- "profile_id" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- }
- },
- "required" : [ "arguments", "conversation_id" ],
- "type" : "object"
- }
- }
- }
- },
- "responses" : {
- "2XX" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "description" : "Base schema for all tool requests. Contains the conversation ID and optional profile ID.",
- "properties" : {
- "conversation_id" : {
- "description" : "value must be a valid UUID.",
- "pattern" : "[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",
- "type" : "string"
},
- "profile_id" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- }
- },
- "required" : [ "conversation_id" ],
- "type" : "object"
- }
- }
- },
- "description" : "Base schema for all tool requests. Contains the conversation ID and optional profile ID."
- },
- "4XX" : {
- "description" : "Client error response"
- },
- "5XX" : {
- "description" : "Server error response"
- }
- },
- "summary" : "POST /api/ee/metabot-tools/get-transform-python-library-details",
- "tags" : [ "/api/ee/metabot-tools" ]
- }
- },
- "/api/ee/metabot-tools/get-transforms" : {
- "post" : {
- "description" : "Get a list of all known transforms.",
- "operationId" : "post-api-ee-metabot-tools-get-transforms",
- "parameters" : [ ],
- "requestBody" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.deftool.tool-request"
- }
- }
- }
- },
- "responses" : {
- "2XX" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "description" : "Base schema for all tool requests. Contains the conversation ID and optional profile ID.",
- "properties" : {
- "conversation_id" : {
- "description" : "value must be a valid UUID.",
- "pattern" : "[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",
- "type" : "string"
+ "queries" : {
+ "items" : {
+ "properties" : {
+ "call_id" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "database_id" : {
+ "oneOf" : [ {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "display" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "mbql" : {
+ "oneOf" : [ {
+ "properties" : { },
+ "type" : "object"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "message_id" : {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
+ },
+ "query_id" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "query_type" : {
+ "enum" : [ "sql", "notebook" ],
+ "type" : "string"
+ },
+ "sql" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "tables" : {
+ "items" : {
+ "type" : "string"
+ },
+ "type" : "array"
+ },
+ "tool" : {
+ "enum" : [ "construct_notebook_query", "create_sql_query", "edit_sql_query", "replace_sql_query" ],
+ "type" : "string"
+ }
+ },
+ "required" : [ "tool", "call_id", "message_id", "query_id", "query_type", "sql", "mbql", "display", "database_id", "tables" ],
+ "type" : "object"
+ },
+ "type" : "array"
},
- "profile_id" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- }
- },
- "required" : [ "conversation_id" ],
- "type" : "object"
- }
- }
- },
- "description" : "Base schema for all tool requests. Contains the conversation ID and optional profile ID."
- },
- "4XX" : {
- "description" : "Client error response"
- },
- "5XX" : {
- "description" : "Server error response"
- }
- },
- "summary" : "POST /api/ee/metabot-tools/get-transforms",
- "tags" : [ "/api/ee/metabot-tools" ]
- }
- },
- "/api/ee/metabot-tools/query-datasource" : {
- "post" : {
- "description" : "Construct a query from a model or table data source.",
- "operationId" : "post-api-ee-metabot-tools-query-datasource",
- "parameters" : [ ],
- "requestBody" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "description" : "Base schema for all tool requests. Contains the conversation ID and optional profile ID.",
- "properties" : {
- "arguments" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.query-datasource-arguments"
- },
- "conversation_id" : {
- "description" : "value must be a valid UUID.",
- "pattern" : "[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",
- "type" : "string"
- },
- "profile_id" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- }
- },
- "required" : [ "arguments", "conversation_id" ],
- "type" : "object"
- }
- }
- }
- },
- "responses" : {
- "2XX" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "description" : "Base schema for all tool requests. Contains the conversation ID and optional profile ID.",
- "properties" : {
- "conversation_id" : {
- "description" : "value must be a valid UUID.",
- "pattern" : "[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",
- "type" : "string"
+ "query_count" : {
+ "description" : "value must be an integer greater or equal to than zero.",
+ "minimum" : 0,
+ "type" : "integer"
},
- "profile_id" : {
+ "sanitized_user_agent" : {
"oneOf" : [ {
"type" : "string"
}, {
"type" : "null"
} ]
- }
- },
- "required" : [ "conversation_id" ],
- "type" : "object"
- }
- }
- },
- "description" : "Base schema for all tool requests. Contains the conversation ID and optional profile ID."
- },
- "4XX" : {
- "description" : "Client error response"
- },
- "5XX" : {
- "description" : "Server error response"
- }
- },
- "summary" : "POST /api/ee/metabot-tools/query-datasource",
- "tags" : [ "/api/ee/metabot-tools" ]
- }
- },
- "/api/ee/metabot-tools/query-metric" : {
- "post" : {
- "description" : "Construct a query from a metric.",
- "operationId" : "post-api-ee-metabot-tools-query-metric",
- "parameters" : [ ],
- "requestBody" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "description" : "Base schema for all tool requests. Contains the conversation ID and optional profile ID.",
- "properties" : {
- "arguments" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.query-metric-arguments"
- },
- "conversation_id" : {
- "description" : "value must be a valid UUID.",
- "pattern" : "[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",
- "type" : "string"
- },
- "profile_id" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- }
- },
- "required" : [ "arguments", "conversation_id" ],
- "type" : "object"
- }
- }
- }
- },
- "responses" : {
- "2XX" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "description" : "Base schema for all tool requests. Contains the conversation ID and optional profile ID.",
- "properties" : {
- "conversation_id" : {
- "description" : "value must be a valid UUID.",
- "pattern" : "[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",
- "type" : "string"
},
- "profile_id" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- }
- },
- "required" : [ "conversation_id" ],
- "type" : "object"
- }
- }
- },
- "description" : "Base schema for all tool requests. Contains the conversation ID and optional profile ID."
- },
- "4XX" : {
- "description" : "Client error response"
- },
- "5XX" : {
- "description" : "Server error response"
- }
- },
- "summary" : "POST /api/ee/metabot-tools/query-metric",
- "tags" : [ "/api/ee/metabot-tools" ]
- }
- },
- "/api/ee/metabot-tools/query-model" : {
- "post" : {
- "description" : "Construct a query from a model.",
- "operationId" : "post-api-ee-metabot-tools-query-model",
- "parameters" : [ ],
- "requestBody" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "description" : "Base schema for all tool requests. Contains the conversation ID and optional profile ID.",
- "properties" : {
- "arguments" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.query-model-arguments"
- },
- "conversation_id" : {
- "description" : "value must be a valid UUID.",
- "pattern" : "[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",
- "type" : "string"
- },
- "profile_id" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- }
- },
- "required" : [ "arguments", "conversation_id" ],
- "type" : "object"
- }
- }
- }
- },
- "responses" : {
- "2XX" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "description" : "Base schema for all tool requests. Contains the conversation ID and optional profile ID.",
- "properties" : {
- "conversation_id" : {
- "description" : "value must be a valid UUID.",
- "pattern" : "[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",
- "type" : "string"
+ "search_count" : {
+ "description" : "value must be an integer greater or equal to than zero.",
+ "minimum" : 0,
+ "type" : "integer"
},
- "profile_id" : {
+ "slack_permalink" : {
"oneOf" : [ {
"type" : "string"
}, {
"type" : "null"
} ]
- }
- },
- "required" : [ "conversation_id" ],
- "type" : "object"
- }
- }
- },
- "description" : "Base schema for all tool requests. Contains the conversation ID and optional profile ID."
- },
- "4XX" : {
- "description" : "Client error response"
- },
- "5XX" : {
- "description" : "Server error response"
- }
- },
- "summary" : "POST /api/ee/metabot-tools/query-model",
- "tags" : [ "/api/ee/metabot-tools" ]
- }
- },
- "/api/ee/metabot-tools/search" : {
- "post" : {
- "description" : "Enhanced search with term and semantic queries using Reciprocal Rank Fusion.",
- "operationId" : "post-api-ee-metabot-tools-search",
- "parameters" : [ ],
- "requestBody" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "description" : "Base schema for all tool requests. Contains the conversation ID and optional profile ID.",
- "properties" : {
- "arguments" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.search-arguments"
- },
- "conversation_id" : {
- "description" : "value must be a valid UUID.",
- "pattern" : "[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",
- "type" : "string"
- },
- "profile_id" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- }
- },
- "required" : [ "conversation_id" ],
- "type" : "object"
- }
- }
- }
- },
- "responses" : {
- "2XX" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "description" : "Base schema for all tool requests. Contains the conversation ID and optional profile ID.",
- "properties" : {
- "conversation_id" : {
- "description" : "value must be a valid UUID.",
- "pattern" : "[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",
- "type" : "string"
},
- "profile_id" : {
+ "summary" : {
"oneOf" : [ {
"type" : "string"
}, {
"type" : "null"
} ]
- }
- },
- "required" : [ "conversation_id" ],
- "type" : "object"
- }
- }
- },
- "description" : "Base schema for all tool requests. Contains the conversation ID and optional profile ID."
- },
- "4XX" : {
- "description" : "Client error response"
- },
- "5XX" : {
- "description" : "Server error response"
- }
- },
- "summary" : "POST /api/ee/metabot-tools/search",
- "tags" : [ "/api/ee/metabot-tools" ]
- }
- },
- "/api/ee/metabot-tools/search_v2" : {
- "post" : {
- "description" : "Enhanced search with term and semantic queries using Reciprocal Rank Fusion. This is identical to /search, but\n duplicated in order to add a new capability to AI service that indicates that Metabot can search transforms. The\n /search endpoint is kept around for backward compatibility.",
- "operationId" : "post-api-ee-metabot-tools-search_v2",
- "parameters" : [ ],
- "requestBody" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "description" : "Base schema for all tool requests. Contains the conversation ID and optional profile ID.",
- "properties" : {
- "arguments" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.tools.api.search-arguments"
- },
- "conversation_id" : {
- "description" : "value must be a valid UUID.",
- "pattern" : "[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",
- "type" : "string"
- },
- "profile_id" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- }
- },
- "required" : [ "conversation_id" ],
- "type" : "object"
- }
- }
- }
- },
- "responses" : {
- "2XX" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "description" : "Base schema for all tool requests. Contains the conversation ID and optional profile ID.",
- "properties" : {
- "conversation_id" : {
- "description" : "value must be a valid UUID.",
- "pattern" : "[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",
- "type" : "string"
},
- "profile_id" : {
+ "total_tokens" : {
+ "description" : "value must be an integer greater or equal to than zero.",
+ "minimum" : 0,
+ "type" : "integer"
+ },
+ "user" : {
"oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- }
- },
- "required" : [ "conversation_id" ],
- "type" : "object"
- }
- }
- },
- "description" : "Base schema for all tool requests. Contains the conversation ID and optional profile ID."
- },
- "4XX" : {
- "description" : "Client error response"
- },
- "5XX" : {
- "description" : "Server error response"
- }
- },
- "summary" : "POST /api/ee/metabot-tools/search_v2",
- "tags" : [ "/api/ee/metabot-tools" ]
- }
- },
- "/api/ee/metabot-v3/agent-streaming" : {
- "post" : {
- "description" : "Send a chat message to the LLM via the AI Proxy.",
- "operationId" : "post-api-ee-metabot-v3-agent-streaming",
- "parameters" : [ ],
- "requestBody" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "properties" : {
- "context" : {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.context.context"
- },
- "conversation_id" : {
- "description" : "value must be a valid UUID.",
- "pattern" : "[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",
- "type" : "string"
- },
- "history" : {
- "oneOf" : [ {
- "$ref" : "#/components/schemas/metabase-enterprise.metabot-v3.client.schema.messages"
- }, {
- "type" : "null"
- } ]
- },
- "message" : {
- "minLength" : 1,
- "type" : "string"
- },
- "metabot_id" : {
- "type" : "string"
- },
- "profile_id" : {
- "type" : "string"
- },
- "state" : {
- "properties" : { },
- "type" : "object"
- }
- },
- "required" : [ "message", "context", "conversation_id", "history", "state" ],
- "type" : "object"
- }
- }
- }
- },
- "responses" : {
- "2XX" : {
- "description" : "Successful response"
- },
- "4XX" : {
- "description" : "Client error response"
- },
- "5XX" : {
- "description" : "Server error response"
- }
- },
- "summary" : "POST /api/ee/metabot-v3/agent-streaming",
- "tags" : [ "/api/ee/metabot-v3" ]
- }
- },
- "/api/ee/metabot-v3/document/generate-content" : {
- "post" : {
- "description" : "Create a new piece of content to insert into the document.",
- "operationId" : "post-api-ee-metabot-v3-document-generate-content",
- "parameters" : [ ],
- "requestBody" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "properties" : {
- "instructions" : {
- "minLength" : 1,
- "type" : "string"
- },
- "references" : {
- "description" : "Value must be a map.",
- "properties" : { },
- "type" : "object"
- }
- },
- "required" : [ "instructions" ],
- "type" : "object"
- }
- }
- }
- },
- "responses" : {
- "2XX" : {
- "description" : "Successful response"
- },
- "4XX" : {
- "description" : "Client error response"
- },
- "5XX" : {
- "description" : "Server error response"
- }
- },
- "summary" : "POST /api/ee/metabot-v3/document/generate-content",
- "tags" : [ "/api/ee/metabot-v3/document" ]
- }
- },
- "/api/ee/metabot-v3/feedback" : {
- "post" : {
- "description" : "Proxy Metabot feedback to Harbormaster, adding the premium embedding token.",
- "operationId" : "post-api-ee-metabot-v3-feedback",
- "parameters" : [ ],
- "requestBody" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "properties" : { },
- "type" : "object"
+ "properties" : {
+ "email" : {
+ "type" : "string"
+ },
+ "first_name" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "id" : {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
+ },
+ "last_name" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ }
+ },
+ "required" : [ "id", "email", "first_name", "last_name" ],
+ "type" : "object"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "user_agent" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ }
+ },
+ "required" : [ "conversation_id", "created_at", "summary", "user", "message_count", "total_tokens", "profile_id", "slack_permalink", "chat_messages", "queries", "search_count", "query_count", "ip_address", "embedding_hostname", "embedding_path", "user_agent", "sanitized_user_agent", "feedback" ],
+ "type" : "object"
+ }
}
- }
- }
- },
- "responses" : {
- "2XX" : {
+ },
"description" : "Successful response"
},
"4XX" : {
@@ -29569,235 +28937,48 @@
"description" : "Server error response"
}
},
- "summary" : "POST /api/ee/metabot-v3/feedback",
- "tags" : [ "/api/ee/metabot-v3" ]
+ "summary" : "GET /api/ee/metabot-analytics/conversations/{id}",
+ "tags" : [ "/api/ee/metabot-analytics" ]
}
},
- "/api/ee/metabot-v3/metabot" : {
+ "/api/ee/metabot/usage" : {
"get" : {
- "description" : "List configured metabot instances",
- "operationId" : "get-api-ee-metabot-v3-metabot",
+ "description" : "Fetch current Metabot token usage for the current billing period.",
+ "operationId" : "get-api-ee-metabot-usage",
"parameters" : [ ],
"responses" : {
"2XX" : {
- "description" : "Successful response"
- },
- "4XX" : {
- "description" : "Client error response"
- },
- "5XX" : {
- "description" : "Server error response"
- }
- },
- "summary" : "GET /api/ee/metabot-v3/metabot",
- "tags" : [ "/api/ee/metabot-v3/metabot" ]
- }
- },
- "/api/ee/metabot-v3/metabot/{id}" : {
- "get" : {
- "description" : "Retrieve one metabot instance",
- "operationId" : "get-api-ee-metabot-v3-metabot-id",
- "parameters" : [ {
- "in" : "path",
- "name" : "id",
- "required" : true,
- "schema" : {
- "minimum" : 1,
- "type" : "integer"
- }
- } ],
- "responses" : {
- "2XX" : {
- "description" : "Successful response"
- },
- "4XX" : {
- "description" : "Client error response"
- },
- "5XX" : {
- "description" : "Server error response"
- }
- },
- "summary" : "GET /api/ee/metabot-v3/metabot/{id}",
- "tags" : [ "/api/ee/metabot-v3/metabot" ]
- },
- "put" : {
- "description" : "Update a metabot instance",
- "operationId" : "put-api-ee-metabot-v3-metabot-id",
- "parameters" : [ {
- "in" : "path",
- "name" : "id",
- "required" : true,
- "schema" : {
- "minimum" : 1,
- "type" : "integer"
- }
- } ],
- "requestBody" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "additionalProperties" : false,
- "properties" : {
- "collection_id" : {
- "oneOf" : [ {
- "minimum" : 1,
- "type" : "integer"
- }, {
- "type" : "null"
- } ]
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "properties" : {
+ "is_locked" : {
+ "oneOf" : [ {
+ "type" : "boolean"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "tokens" : {
+ "oneOf" : [ {
+ "type" : "integer"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "updated_at" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ }
},
- "use_verified_content" : {
- "type" : "boolean"
- }
- },
- "type" : "object"
+ "required" : [ "is_locked", "tokens", "updated_at" ],
+ "type" : "object"
+ }
}
- }
- }
- },
- "responses" : {
- "2XX" : {
- "description" : "Successful response"
- },
- "4XX" : {
- "description" : "Client error response"
- },
- "5XX" : {
- "description" : "Server error response"
- }
- },
- "summary" : "PUT /api/ee/metabot-v3/metabot/{id}",
- "tags" : [ "/api/ee/metabot-v3/metabot" ]
- }
- },
- "/api/ee/metabot-v3/metabot/{id}/prompt-suggestions" : {
- "delete" : {
- "description" : "Delete all prompt suggestions for the metabot instance with `id`.",
- "operationId" : "delete-api-ee-metabot-v3-metabot-id-prompt-suggestions",
- "parameters" : [ {
- "in" : "path",
- "name" : "id",
- "required" : true,
- "schema" : {
- "minimum" : 1,
- "type" : "integer"
- }
- } ],
- "responses" : {
- "2XX" : {
- "description" : "Successful response"
- },
- "4XX" : {
- "description" : "Client error response"
- },
- "5XX" : {
- "description" : "Server error response"
- }
- },
- "summary" : "DELETE /api/ee/metabot-v3/metabot/{id}/prompt-suggestions",
- "tags" : [ "/api/ee/metabot-v3/metabot" ]
- },
- "get" : {
- "description" : "Return the prompt suggestions for the metabot instance with `id`.",
- "operationId" : "get-api-ee-metabot-v3-metabot-id-prompt-suggestions",
- "parameters" : [ {
- "in" : "path",
- "name" : "id",
- "required" : true,
- "schema" : {
- "minimum" : 1,
- "type" : "integer"
- }
- }, {
- "in" : "query",
- "name" : "sample",
- "required" : false,
- "schema" : {
- "type" : "boolean"
- }
- }, {
- "in" : "query",
- "name" : "model",
- "required" : false,
- "schema" : {
- "enum" : [ "metric", "model" ],
- "type" : "string"
- }
- }, {
- "in" : "query",
- "name" : "model_id",
- "required" : false,
- "schema" : {
- "minimum" : 1,
- "type" : "integer"
- }
- } ],
- "responses" : {
- "2XX" : {
- "description" : "Successful response"
- },
- "4XX" : {
- "description" : "Client error response"
- },
- "5XX" : {
- "description" : "Server error response"
- }
- },
- "summary" : "GET /api/ee/metabot-v3/metabot/{id}/prompt-suggestions",
- "tags" : [ "/api/ee/metabot-v3/metabot" ]
- }
- },
- "/api/ee/metabot-v3/metabot/{id}/prompt-suggestions/regenerate" : {
- "post" : {
- "description" : "Remove any existing prompt suggestions for the Metabot instance with `id` and generate new ones.",
- "operationId" : "post-api-ee-metabot-v3-metabot-id-prompt-suggestions-regenerate",
- "parameters" : [ {
- "in" : "path",
- "name" : "id",
- "required" : true,
- "schema" : {
- "minimum" : 1,
- "type" : "integer"
- }
- } ],
- "responses" : {
- "2XX" : {
- "description" : "Successful response"
- },
- "4XX" : {
- "description" : "Client error response"
- },
- "5XX" : {
- "description" : "Server error response"
- }
- },
- "summary" : "POST /api/ee/metabot-v3/metabot/{id}/prompt-suggestions/regenerate",
- "tags" : [ "/api/ee/metabot-v3/metabot" ]
- }
- },
- "/api/ee/metabot-v3/metabot/{id}/prompt-suggestions/{prompt-id}" : {
- "delete" : {
- "description" : "Delete the prompt suggestion with ID `prompt-id` for the metabot instance with `id`.",
- "operationId" : "delete-api-ee-metabot-v3-metabot-id-prompt-suggestions-prompt-id",
- "parameters" : [ {
- "in" : "path",
- "name" : "id",
- "required" : true,
- "schema" : {
- "minimum" : 1,
- "type" : "integer"
- }
- }, {
- "in" : "path",
- "name" : "prompt-id",
- "required" : true,
- "schema" : {
- "minimum" : 1,
- "type" : "integer"
- }
- } ],
- "responses" : {
- "2XX" : {
+ },
"description" : "Successful response"
},
"4XX" : {
@@ -29807,8 +28988,8 @@
"description" : "Server error response"
}
},
- "summary" : "DELETE /api/ee/metabot-v3/metabot/{id}/prompt-suggestions/{prompt-id}",
- "tags" : [ "/api/ee/metabot-v3/metabot" ]
+ "summary" : "GET /api/ee/metabot/usage",
+ "tags" : [ "/api/ee/metabot" ]
}
},
"/api/ee/permission_debug" : {
@@ -30621,6 +29802,322 @@
"tags" : [ "/api/ee/remote-sync" ]
}
},
+ "/api/ee/replacement/check-replace-source" : {
+ "post" : {
+ "description" : "Check whether a source entity can be replaced by a target entity. Returns compatibility\n errors describing column mismatches, type mismatches, primary key mismatches, and foreign\n key mismatches.",
+ "operationId" : "post-api-ee-replacement-check-replace-source",
+ "parameters" : [ ],
+ "requestBody" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "properties" : {
+ "source_entity_id" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.replacement.schema.source-entity-id"
+ },
+ "source_entity_type" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.replacement.schema.source-entity-type"
+ },
+ "target_entity_id" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.replacement.schema.source-entity-id"
+ },
+ "target_entity_type" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.replacement.schema.source-entity-type"
+ }
+ },
+ "required" : [ "source_entity_id", "source_entity_type", "target_entity_id", "target_entity_type" ],
+ "type" : "object"
+ }
+ }
+ }
+ },
+ "responses" : {
+ "2XX" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.replacement.schema.check-replace-source-response"
+ }
+ }
+ },
+ "description" : "Successful response"
+ },
+ "4XX" : {
+ "description" : "Client error response"
+ },
+ "5XX" : {
+ "description" : "Server error response"
+ }
+ },
+ "summary" : "POST /api/ee/replacement/check-replace-source",
+ "tags" : [ "/api/ee/replacement" ]
+ }
+ },
+ "/api/ee/replacement/replace-model-with-transform" : {
+ "post" : {
+ "description" : "Create a transform from a model, execute it, and replace all usages of the model\n with the output table. Un-persists the model and converts it to a saved question.\n Returns 202 with a run_id for polling.\n\n If there is an error during the transform execution, no replacement will be\n performed and the model will remain unchanged.\n\n If there is an error during the source swap, the transform and the output\n table will be retained, and the model will remain unchanged. We cannot delete\n the transform or the output table because they can be used by other queries at\n this point.",
+ "operationId" : "post-api-ee-replacement-replace-model-with-transform",
+ "parameters" : [ ],
+ "requestBody" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "properties" : {
+ "card_id" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.replacement.schema.source-entity-id"
+ },
+ "target_collection_id" : {
+ "oneOf" : [ {
+ "$ref" : "#/components/schemas/metabase-enterprise.replacement.schema.source-entity-id"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "transform_name" : {
+ "type" : "string"
+ },
+ "transform_tag_ids" : {
+ "oneOf" : [ {
+ "items" : {
+ "minimum" : 1,
+ "type" : "integer"
+ },
+ "type" : "array"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "transform_target" : {
+ "properties" : { },
+ "type" : "object"
+ }
+ },
+ "required" : [ "card_id", "transform_name", "transform_target" ],
+ "type" : "object"
+ }
+ }
+ }
+ },
+ "responses" : {
+ "2XX" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "properties" : {
+ "body" : {
+ "additionalProperties" : false,
+ "properties" : {
+ "run_id" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.replacement.schema.run-id"
+ }
+ },
+ "required" : [ "run_id" ],
+ "type" : "object"
+ },
+ "status" : {
+ "const" : 202
+ }
+ },
+ "required" : [ "status", "body" ],
+ "type" : "object"
+ }
+ }
+ },
+ "description" : "Successful response"
+ },
+ "4XX" : {
+ "description" : "Client error response"
+ },
+ "5XX" : {
+ "description" : "Server error response"
+ }
+ },
+ "summary" : "POST /api/ee/replacement/replace-model-with-transform",
+ "tags" : [ "/api/ee/replacement" ]
+ }
+ },
+ "/api/ee/replacement/replace-source" : {
+ "post" : {
+ "description" : "Replace all usages of a source entity with a target entity asynchronously.\n Returns 202 with a run_id for polling. Returns 409 if a replacement is already running.",
+ "operationId" : "post-api-ee-replacement-replace-source",
+ "parameters" : [ ],
+ "requestBody" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "properties" : {
+ "source_entity_id" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.replacement.schema.source-entity-id"
+ },
+ "source_entity_type" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.replacement.schema.source-entity-type"
+ },
+ "target_entity_id" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.replacement.schema.source-entity-id"
+ },
+ "target_entity_type" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.replacement.schema.source-entity-type"
+ }
+ },
+ "required" : [ "source_entity_id", "source_entity_type", "target_entity_id", "target_entity_type" ],
+ "type" : "object"
+ }
+ }
+ }
+ },
+ "responses" : {
+ "2XX" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "properties" : {
+ "body" : {
+ "additionalProperties" : false,
+ "properties" : {
+ "run_id" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.replacement.schema.run-id"
+ }
+ },
+ "required" : [ "run_id" ],
+ "type" : "object"
+ },
+ "status" : {
+ "const" : 202
+ }
+ },
+ "required" : [ "status", "body" ],
+ "type" : "object"
+ }
+ }
+ },
+ "description" : "Successful response"
+ },
+ "4XX" : {
+ "description" : "Client error response"
+ },
+ "5XX" : {
+ "description" : "Server error response"
+ }
+ },
+ "summary" : "POST /api/ee/replacement/replace-source",
+ "tags" : [ "/api/ee/replacement" ]
+ }
+ },
+ "/api/ee/replacement/runs" : {
+ "get" : {
+ "description" : "List replacement runs, optionally filtered by is-active.",
+ "operationId" : "get-api-ee-replacement-runs",
+ "parameters" : [ {
+ "in" : "query",
+ "name" : "is-active",
+ "required" : false,
+ "schema" : {
+ "oneOf" : [ {
+ "type" : "boolean"
+ }, {
+ "type" : "null"
+ } ]
+ }
+ } ],
+ "responses" : {
+ "2XX" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "items" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.replacement.schema.run"
+ },
+ "type" : "array"
+ }
+ }
+ },
+ "description" : "Successful response"
+ },
+ "4XX" : {
+ "description" : "Client error response"
+ },
+ "5XX" : {
+ "description" : "Server error response"
+ }
+ },
+ "summary" : "GET /api/ee/replacement/runs",
+ "tags" : [ "/api/ee/replacement" ]
+ }
+ },
+ "/api/ee/replacement/runs/{id}" : {
+ "get" : {
+ "description" : "Get the status of a source replacement run.",
+ "operationId" : "get-api-ee-replacement-runs-id",
+ "parameters" : [ {
+ "in" : "path",
+ "name" : "id",
+ "required" : true,
+ "schema" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.replacement.schema.run-id"
+ }
+ } ],
+ "responses" : {
+ "2XX" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.replacement.schema.run"
+ }
+ }
+ },
+ "description" : "Successful response"
+ },
+ "4XX" : {
+ "description" : "Client error response"
+ },
+ "5XX" : {
+ "description" : "Server error response"
+ }
+ },
+ "summary" : "GET /api/ee/replacement/runs/{id}",
+ "tags" : [ "/api/ee/replacement" ]
+ }
+ },
+ "/api/ee/replacement/runs/{id}/cancel" : {
+ "post" : {
+ "description" : "Cancel a running source replacement.",
+ "operationId" : "post-api-ee-replacement-runs-id-cancel",
+ "parameters" : [ {
+ "in" : "path",
+ "name" : "id",
+ "required" : true,
+ "schema" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.replacement.schema.run-id"
+ }
+ } ],
+ "responses" : {
+ "2XX" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "properties" : {
+ "success" : {
+ "type" : "boolean"
+ }
+ },
+ "required" : [ "success" ],
+ "type" : "object"
+ }
+ }
+ },
+ "description" : "Successful response"
+ },
+ "4XX" : {
+ "description" : "Client error response"
+ },
+ "5XX" : {
+ "description" : "Server error response"
+ }
+ },
+ "summary" : "POST /api/ee/replacement/runs/{id}/cancel",
+ "tags" : [ "/api/ee/replacement" ]
+ }
+ },
"/api/ee/scim/api_key" : {
"get" : {
"description" : "Fetch the SCIM API key if one exists. Does *not* return an unmasked key, since we don't have access\n to that after it is created.",
@@ -31275,6 +30772,359 @@
"tags" : [ "/api/ee/scim/v2" ]
}
},
+ "/api/ee/security-center" : {
+ "get" : {
+ "description" : "List all security advisories with match status.",
+ "operationId" : "get-api-ee-security-center",
+ "parameters" : [ ],
+ "responses" : {
+ "2XX" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "properties" : {
+ "advisories" : {
+ "items" : {
+ "properties" : {
+ "acknowledged_at" : {
+ "oneOf" : [ {
+ "format" : "date-time",
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "acknowledged_by" : {
+ "oneOf" : [ {
+ "properties" : {
+ "common_name" : {
+ "minLength" : 1,
+ "type" : "string"
+ },
+ "email" : {
+ "description" : "value must be a valid email address.",
+ "type" : "string"
+ },
+ "id" : {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
+ }
+ },
+ "required" : [ "id", "common_name", "email" ],
+ "type" : "object"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "advisory_id" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.security-center.schema.advisory-id"
+ },
+ "advisory_url" : {
+ "oneOf" : [ {
+ "minLength" : 1,
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "affected_versions" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.security-center.schema.affected-versions"
+ },
+ "description" : {
+ "minLength" : 1,
+ "type" : "string"
+ },
+ "last_evaluated_at" : {
+ "oneOf" : [ {
+ "format" : "date-time",
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "match_status" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.security-center.schema.match-status"
+ },
+ "published_at" : {
+ "format" : "date-time",
+ "type" : "string"
+ },
+ "remediation" : {
+ "minLength" : 1,
+ "type" : "string"
+ },
+ "severity" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.security-center.schema.severity"
+ },
+ "title" : {
+ "minLength" : 1,
+ "type" : "string"
+ }
+ },
+ "required" : [ "advisory_id", "title", "severity", "description", "advisory_url", "remediation", "published_at", "match_status", "last_evaluated_at", "acknowledged_by", "acknowledged_at", "affected_versions" ],
+ "type" : "object"
+ },
+ "type" : "array"
+ },
+ "last_checked_at" : {
+ "oneOf" : [ {
+ "format" : "date-time",
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ }
+ },
+ "required" : [ "last_checked_at", "advisories" ],
+ "type" : "object"
+ }
+ }
+ },
+ "description" : "Successful response"
+ },
+ "4XX" : {
+ "description" : "Client error response"
+ },
+ "5XX" : {
+ "description" : "Server error response"
+ }
+ },
+ "summary" : "GET /api/ee/security-center",
+ "tags" : [ "/api/ee/security-center" ]
+ }
+ },
+ "/api/ee/security-center/acknowledge" : {
+ "post" : {
+ "description" : "Acknowledge multiple security advisories. Skips already-acknowledged advisories.",
+ "operationId" : "post-api-ee-security-center-acknowledge",
+ "parameters" : [ ],
+ "requestBody" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "properties" : {
+ "advisory_ids" : {
+ "items" : {
+ "minLength" : 1,
+ "type" : "string"
+ },
+ "type" : "array"
+ }
+ },
+ "required" : [ "advisory_ids" ],
+ "type" : "object"
+ }
+ }
+ }
+ },
+ "responses" : {
+ "2XX" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "items" : {
+ "properties" : {
+ "acknowledged_at" : {
+ "oneOf" : [ {
+ "format" : "date-time",
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "acknowledged_by" : {
+ "oneOf" : [ {
+ "properties" : {
+ "common_name" : {
+ "minLength" : 1,
+ "type" : "string"
+ },
+ "email" : {
+ "description" : "value must be a valid email address.",
+ "type" : "string"
+ },
+ "id" : {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
+ }
+ },
+ "required" : [ "id", "common_name", "email" ],
+ "type" : "object"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "advisory_id" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.security-center.schema.advisory-id"
+ },
+ "match_status" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.security-center.schema.match-status"
+ }
+ },
+ "required" : [ "advisory_id", "match_status", "acknowledged_by", "acknowledged_at" ],
+ "type" : "object"
+ },
+ "type" : "array"
+ }
+ }
+ },
+ "description" : "Successful response"
+ },
+ "4XX" : {
+ "description" : "Client error response"
+ },
+ "5XX" : {
+ "description" : "Server error response"
+ }
+ },
+ "summary" : "POST /api/ee/security-center/acknowledge",
+ "tags" : [ "/api/ee/security-center" ]
+ }
+ },
+ "/api/ee/security-center/sync" : {
+ "post" : {
+ "description" : "Trigger an async advisory sync + re-evaluation.\n Returns immediately. If a sync is already running, the request is a no-op.",
+ "operationId" : "post-api-ee-security-center-sync",
+ "parameters" : [ ],
+ "responses" : {
+ "2XX" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "properties" : {
+ "status" : {
+ "minLength" : 1,
+ "type" : "string"
+ }
+ },
+ "required" : [ "status" ],
+ "type" : "object"
+ }
+ }
+ },
+ "description" : "Successful response"
+ },
+ "4XX" : {
+ "description" : "Client error response"
+ },
+ "5XX" : {
+ "description" : "Server error response"
+ }
+ },
+ "summary" : "POST /api/ee/security-center/sync",
+ "tags" : [ "/api/ee/security-center" ]
+ }
+ },
+ "/api/ee/security-center/test-notification" : {
+ "post" : {
+ "description" : "Send a test notification through the configured Security Center channels.",
+ "operationId" : "post-api-ee-security-center-test-notification",
+ "parameters" : [ ],
+ "responses" : {
+ "2XX" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "properties" : {
+ "success" : {
+ "type" : "boolean"
+ }
+ },
+ "required" : [ "success" ],
+ "type" : "object"
+ }
+ }
+ },
+ "description" : "Successful response"
+ },
+ "4XX" : {
+ "description" : "Client error response"
+ },
+ "5XX" : {
+ "description" : "Server error response"
+ }
+ },
+ "summary" : "POST /api/ee/security-center/test-notification",
+ "tags" : [ "/api/ee/security-center" ]
+ }
+ },
+ "/api/ee/security-center/{advisory-id}/acknowledge" : {
+ "post" : {
+ "description" : "Acknowledge a security advisory. Stops repeat notifications.",
+ "operationId" : "post-api-ee-security-center-advisory-id-acknowledge",
+ "parameters" : [ {
+ "in" : "path",
+ "name" : "advisory-id",
+ "required" : true,
+ "schema" : {
+ "minLength" : 1,
+ "type" : "string"
+ }
+ } ],
+ "responses" : {
+ "2XX" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "properties" : {
+ "acknowledged_at" : {
+ "oneOf" : [ {
+ "format" : "date-time",
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "acknowledged_by" : {
+ "oneOf" : [ {
+ "properties" : {
+ "common_name" : {
+ "minLength" : 1,
+ "type" : "string"
+ },
+ "email" : {
+ "description" : "value must be a valid email address.",
+ "type" : "string"
+ },
+ "id" : {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
+ }
+ },
+ "required" : [ "id", "common_name", "email" ],
+ "type" : "object"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "advisory_id" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.security-center.schema.advisory-id"
+ },
+ "match_status" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.security-center.schema.match-status"
+ }
+ },
+ "required" : [ "advisory_id", "match_status", "acknowledged_by", "acknowledged_at" ],
+ "type" : "object"
+ }
+ }
+ },
+ "description" : "Successful response"
+ },
+ "4XX" : {
+ "description" : "Client error response"
+ },
+ "5XX" : {
+ "description" : "Server error response"
+ }
+ },
+ "summary" : "POST /api/ee/security-center/{advisory-id}/acknowledge",
+ "tags" : [ "/api/ee/security-center" ]
+ }
+ },
"/api/ee/semantic-search/status" : {
"get" : {
"description" : "Fetch the indexing status of the currently active semantic search index table.\n\n Returns a map with keys:\n :indexed_count <number of indexed items>\n :total_est <estimated total number of items to index>\n\n If no index is active, returns an empty map.",
@@ -31482,6 +31332,69 @@
"tags" : [ "/api/ee/serialization" ]
}
},
+ "/api/ee/serialization/metadata/export" : {
+ "post" : {
+ "description" : "Get warehouse metadata (databases, tables, and fields) for all databases visible to the\n current user. References between rows are emitted as raw numeric ids (`db_id`,\n `table_id`, `parent_id`, `fk_target_field_id`).\n\n Sections must be opted into with the `with-databases`, `with-tables`, and `with-fields`\n query parameters — they all default to `false`. The response is streamed for efficiency\n with large schemas.\n\n Requires `View data` → `Can view` and `Create queries` → `Query builder only` (or\n `Query builder and native`) permissions on each database and table.",
+ "operationId" : "post-api-ee-serialization-metadata-export",
+ "parameters" : [ {
+ "in" : "query",
+ "name" : "with-databases",
+ "required" : true,
+ "schema" : {
+ "default" : false,
+ "oneOf" : [ {
+ "type" : "boolean"
+ }, {
+ "type" : "null"
+ } ]
+ }
+ }, {
+ "in" : "query",
+ "name" : "with-tables",
+ "required" : true,
+ "schema" : {
+ "default" : false,
+ "oneOf" : [ {
+ "type" : "boolean"
+ }, {
+ "type" : "null"
+ } ]
+ }
+ }, {
+ "in" : "query",
+ "name" : "with-fields",
+ "required" : true,
+ "schema" : {
+ "default" : false,
+ "oneOf" : [ {
+ "type" : "boolean"
+ }, {
+ "type" : "null"
+ } ]
+ }
+ } ],
+ "responses" : {
+ "2XX" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.serialization.schema.export-metadata-response"
+ }
+ }
+ },
+ "description" : "Successful response"
+ },
+ "4XX" : {
+ "description" : "Client error response"
+ },
+ "5XX" : {
+ "description" : "Server error response"
+ }
+ },
+ "summary" : "POST /api/ee/serialization/metadata/export",
+ "tags" : [ "/api/ee/serialization" ]
+ }
+ },
"/api/ee/stale/{id}" : {
"get" : {
"description" : "A flexible endpoint that returns stale entities, in the same shape as collections/items, with the following options:\n - `before_date` - only return entities that were last edited before this date (default: 6 months ago)\n - `is_recursive` - if true, return entities from all children of the collection, not just the direct children (default: false)\n - `sort_column` - the column to sort by (default: name)\n - `sort_direction` - the direction to sort by (default: asc)",
@@ -32183,11 +32096,11 @@
} ]
},
"source_tables" : {
- "additionalProperties" : {
- "type" : "integer"
+ "items" : {
+ "$ref" : "#/components/schemas/metabase.transforms-base.util.source-table-entry"
},
- "minProperties" : 1,
- "type" : "object"
+ "minItems" : 1,
+ "type" : "array"
}
},
"required" : [ "code", "source_tables" ],
@@ -32237,29 +32150,346 @@
"type" : "object"
}
},
- "required" : [ "logs" ],
- "type" : "object"
- }
+ "required" : [ "logs" ],
+ "type" : "object"
+ }
+ }
+ },
+ "description" : "Successful response"
+ },
+ "4XX" : {
+ "description" : "Client error response"
+ },
+ "5XX" : {
+ "description" : "Server error response"
+ }
+ },
+ "summary" : "POST /api/ee/transforms-python/test-run",
+ "tags" : [ "/api/ee/transforms-python" ]
+ }
+ },
+ "/api/ee/transforms/{id}/inspect" : {
+ "get" : {
+ "description" : "Phase 1: Discover available lenses for a transform.\n Returns structural metadata and available lens types.",
+ "operationId" : "get-api-ee-transforms-id-inspect",
+ "parameters" : [ {
+ "description" : "value must be an integer greater than zero.",
+ "in" : "path",
+ "name" : "id",
+ "required" : true,
+ "schema" : {
+ "minimum" : 1,
+ "type" : "integer"
+ }
+ } ],
+ "responses" : {
+ "2XX" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.transforms-inspector.schema.discovery-response"
+ }
+ }
+ },
+ "description" : "Successful response"
+ },
+ "4XX" : {
+ "description" : "Client error response"
+ },
+ "5XX" : {
+ "description" : "Server error response"
+ }
+ },
+ "summary" : "GET /api/ee/transforms/{id}/inspect",
+ "tags" : [ "/api/ee/transforms" ]
+ }
+ },
+ "/api/ee/transforms/{id}/inspect/{lens-id}" : {
+ "get" : {
+ "description" : "Phase 2: Get full lens contents for a transform.\n Returns sections, cards with dataset_query, and trigger definitions.\n Accepts optional params for drill lenses as query params.",
+ "operationId" : "get-api-ee-transforms-id-inspect-lens-id",
+ "parameters" : [ {
+ "description" : "value must be an integer greater than zero.",
+ "in" : "path",
+ "name" : "id",
+ "required" : true,
+ "schema" : {
+ "minimum" : 1,
+ "type" : "integer"
+ }
+ }, {
+ "in" : "path",
+ "name" : "lens-id",
+ "required" : true,
+ "schema" : {
+ "minLength" : 1,
+ "type" : "string"
+ }
+ } ],
+ "responses" : {
+ "2XX" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "$ref" : "#/components/schemas/metabase-enterprise.transforms-inspector.schema.lens"
+ }
+ }
+ },
+ "description" : "Successful response"
+ },
+ "4XX" : {
+ "description" : "Client error response"
+ },
+ "5XX" : {
+ "description" : "Server error response"
+ }
+ },
+ "summary" : "GET /api/ee/transforms/{id}/inspect/{lens-id}",
+ "tags" : [ "/api/ee/transforms" ]
+ }
+ },
+ "/api/ee/transforms/{id}/inspect/{lens-id}/query" : {
+ "post" : {
+ "description" : "Execute a query in the context of a transform inspector lens.",
+ "operationId" : "post-api-ee-transforms-id-inspect-lens-id-query",
+ "parameters" : [ {
+ "description" : "value must be an integer greater than zero.",
+ "in" : "path",
+ "name" : "id",
+ "required" : true,
+ "schema" : {
+ "minimum" : 1,
+ "type" : "integer"
+ }
+ }, {
+ "in" : "path",
+ "name" : "lens-id",
+ "required" : true,
+ "schema" : {
+ "minLength" : 1,
+ "type" : "string"
+ }
+ } ],
+ "requestBody" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "properties" : {
+ "lens_params" : {
+ "oneOf" : [ {
+ "additionalProperties" : { },
+ "type" : "object"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "query" : {
+ "properties" : {
+ "database" : {
+ "oneOf" : [ {
+ "type" : "integer"
+ }, {
+ "type" : "null"
+ } ]
+ }
+ },
+ "type" : "object"
+ }
+ },
+ "required" : [ "query" ],
+ "type" : "object"
+ }
+ }
+ }
+ },
+ "responses" : {
+ "2XX" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "$ref" : "#/components/schemas/metabase.query-processor.schema.query-result"
+ }
+ }
+ },
+ "description" : "Successful response"
+ },
+ "4XX" : {
+ "description" : "Client error response"
+ },
+ "5XX" : {
+ "description" : "Server error response"
+ }
+ },
+ "summary" : "POST /api/ee/transforms/{id}/inspect/{lens-id}/query",
+ "tags" : [ "/api/ee/transforms" ]
+ }
+ },
+ "/api/ee/upload-management/tables" : {
+ "get" : {
+ "description" : "Get all `Tables` visible to the current user which were created by uploading a file.",
+ "operationId" : "get-api-ee-upload-management-tables",
+ "parameters" : [ ],
+ "responses" : {
+ "2XX" : {
+ "description" : "Successful response"
+ },
+ "4XX" : {
+ "description" : "Client error response"
+ },
+ "5XX" : {
+ "description" : "Server error response"
+ }
+ },
+ "summary" : "GET /api/ee/upload-management/tables",
+ "tags" : [ "/api/ee/upload-management" ]
+ }
+ },
+ "/api/ee/upload-management/tables/{id}" : {
+ "delete" : {
+ "description" : "Delete the uploaded table from the database, optionally archiving cards for which it is the primary source.",
+ "operationId" : "delete-api-ee-upload-management-tables-id",
+ "parameters" : [ {
+ "description" : "value must be an integer greater than zero.",
+ "in" : "path",
+ "name" : "id",
+ "required" : true,
+ "schema" : {
+ "minimum" : 1,
+ "type" : "integer"
+ }
+ }, {
+ "in" : "query",
+ "name" : "archive-cards",
+ "required" : false,
+ "schema" : {
+ "default" : false,
+ "oneOf" : [ {
+ "type" : "boolean"
+ }, {
+ "type" : "null"
+ } ]
+ }
+ } ],
+ "responses" : {
+ "2XX" : {
+ "description" : "Successful response"
+ },
+ "4XX" : {
+ "description" : "Client error response"
+ },
+ "5XX" : {
+ "description" : "Server error response"
+ }
+ },
+ "summary" : "DELETE /api/ee/upload-management/tables/{id}",
+ "tags" : [ "/api/ee/upload-management" ]
+ }
+ },
+ "/api/eid-translation/translate" : {
+ "post" : {
+ "description" : "Translate entity IDs to model IDs.",
+ "operationId" : "post-api-eid-translation-translate",
+ "parameters" : [ ],
+ "requestBody" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "properties" : {
+ "entity_ids" : {
+ "properties" : { },
+ "type" : "object"
+ }
+ },
+ "required" : [ "entity_ids" ],
+ "type" : "object"
+ }
+ }
+ }
+ },
+ "responses" : {
+ "2XX" : {
+ "description" : "Successful response"
+ },
+ "4XX" : {
+ "description" : "Client error response"
+ },
+ "5XX" : {
+ "description" : "Server error response"
+ }
+ },
+ "summary" : "POST /api/eid-translation/translate",
+ "tags" : [ "/api/eid-translation" ]
+ }
+ },
+ "/api/email" : {
+ "delete" : {
+ "description" : "Clear all email related settings. You must be a superuser or have `setting` permission to do this.",
+ "operationId" : "delete-api-email",
+ "parameters" : [ ],
+ "responses" : {
+ "2XX" : {
+ "description" : "Successful response"
+ },
+ "4XX" : {
+ "description" : "Client error response"
+ },
+ "5XX" : {
+ "description" : "Server error response"
+ }
+ },
+ "summary" : "DELETE /api/email",
+ "tags" : [ "/api/email" ]
+ },
+ "put" : {
+ "description" : "Update multiple email Settings. You must be a superuser or have `setting` permission to do this.",
+ "operationId" : "put-api-email",
+ "parameters" : [ ],
+ "requestBody" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "properties" : {
+ "email-smtp-host" : {
+ "anyOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "email-smtp-password" : {
+ "anyOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "email-smtp-port" : {
+ "anyOf" : [ {
+ "type" : "integer"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "email-smtp-security" : {
+ "anyOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "email-smtp-username" : {
+ "anyOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ }
+ },
+ "type" : "object"
}
- },
- "description" : "Successful response"
- },
- "4XX" : {
- "description" : "Client error response"
- },
- "5XX" : {
- "description" : "Server error response"
+ }
}
},
- "summary" : "POST /api/ee/transforms-python/test-run",
- "tags" : [ "/api/ee/transforms-python" ]
- }
- },
- "/api/ee/upload-management/tables" : {
- "get" : {
- "description" : "Get all `Tables` visible to the current user which were created by uploading a file.",
- "operationId" : "get-api-ee-upload-management-tables",
- "parameters" : [ ],
"responses" : {
"2XX" : {
"description" : "Successful response"
@@ -32271,36 +32501,15 @@
"description" : "Server error response"
}
},
- "summary" : "GET /api/ee/upload-management/tables",
- "tags" : [ "/api/ee/upload-management" ]
+ "summary" : "PUT /api/email",
+ "tags" : [ "/api/email" ]
}
},
- "/api/ee/upload-management/tables/{id}" : {
- "delete" : {
- "description" : "Delete the uploaded table from the database, optionally archiving cards for which it is the primary source.",
- "operationId" : "delete-api-ee-upload-management-tables-id",
- "parameters" : [ {
- "description" : "value must be an integer greater than zero.",
- "in" : "path",
- "name" : "id",
- "required" : true,
- "schema" : {
- "minimum" : 1,
- "type" : "integer"
- }
- }, {
- "in" : "query",
- "name" : "archive-cards",
- "required" : false,
- "schema" : {
- "default" : false,
- "oneOf" : [ {
- "type" : "boolean"
- }, {
- "type" : "null"
- } ]
- }
- } ],
+ "/api/email/test" : {
+ "post" : {
+ "description" : "Send a test email using the SMTP Settings. You must be a superuser or have `setting` permission to do this.\n Returns `{:ok true}` if we were able to send the message successfully, otherwise a standard 400 error response.",
+ "operationId" : "post-api-email-test",
+ "parameters" : [ ],
"responses" : {
"2XX" : {
"description" : "Successful response"
@@ -32312,68 +32521,33 @@
"description" : "Server error response"
}
},
- "summary" : "DELETE /api/ee/upload-management/tables/{id}",
- "tags" : [ "/api/ee/upload-management" ]
+ "summary" : "POST /api/email/test",
+ "tags" : [ "/api/email" ]
}
},
- "/api/ee/workspace" : {
- "get" : {
- "description" : "Get a list of all workspaces",
- "operationId" : "get-api-ee-workspace",
+ "/api/embed-mcp/drills" : {
+ "post" : {
+ "description" : "Stash a base64-encoded MBQL query for the iframe's pending drill-through and\n return a handle UUID the iframe will thread into the agent message so the\n `render_drill_through` tool can fetch it.",
+ "operationId" : "post-api-embed-mcp-drills",
"parameters" : [ ],
+ "requestBody" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "properties" : {
+ "encodedQuery" : {
+ "minLength" : 1,
+ "type" : "string"
+ }
+ },
+ "required" : [ "encodedQuery" ],
+ "type" : "object"
+ }
+ }
+ }
+ },
"responses" : {
"2XX" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "additionalProperties" : false,
- "properties" : {
- "items" : {
- "items" : {
- "additionalProperties" : false,
- "properties" : {
- "database_id" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.appdb-id"
- },
- "id" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.appdb-id"
- },
- "name" : {
- "type" : "string"
- },
- "status" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.api.status"
- },
- "updated_at" : {
- "format" : "date-time",
- "type" : "string"
- }
- },
- "required" : [ "id", "database_id", "name", "status", "updated_at" ],
- "type" : "object"
- },
- "type" : "array"
- },
- "limit" : {
- "oneOf" : [ {
- "type" : "integer"
- }, {
- "type" : "null"
- } ]
- },
- "offset" : {
- "oneOf" : [ {
- "type" : "integer"
- }, {
- "type" : "null"
- } ]
- }
- },
- "required" : [ "items", "limit", "offset" ],
- "type" : "object"
- }
- }
- },
"description" : "Successful response"
},
"4XX" : {
@@ -32383,26 +32557,75 @@
"description" : "Server error response"
}
},
- "summary" : "GET /api/ee/workspace",
- "tags" : [ "/api/ee/workspace" ]
- },
+ "summary" : "POST /api/embed-mcp/drills",
+ "tags" : [ "/api/embed-mcp" ]
+ }
+ },
+ "/api/embed-mcp/feedback" : {
"post" : {
- "description" : "Create a new workspace\n\n Potential payload:\n {:name \"a\" :database_id 2}}",
- "operationId" : "post-api-ee-workspace",
+ "description" : "Proxy MCP Apps visualization feedback to Harbormaster.",
+ "operationId" : "post-api-embed-mcp-feedback",
"parameters" : [ ],
"requestBody" : {
"content" : {
"application/json" : {
"schema" : {
"properties" : {
- "database_id" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.appdb-id"
+ "conversation_data" : {
+ "properties" : {
+ "prompt" : {
+ "oneOf" : [ {
+ "maxLength" : 10000,
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "query" : {
+ "oneOf" : [ {
+ "maxLength" : 10000,
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "source" : {
+ "const" : "mcp"
+ }
+ },
+ "required" : [ "source" ],
+ "type" : "object"
},
- "name" : {
- "minLength" : 1,
- "type" : "string"
+ "feedback" : {
+ "properties" : {
+ "freeform_feedback" : {
+ "oneOf" : [ {
+ "maxLength" : 10000,
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "issue_type" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "message_id" : {
+ "minLength" : 1,
+ "type" : "string"
+ },
+ "positive" : {
+ "type" : "boolean"
+ }
+ },
+ "required" : [ "message_id", "positive" ],
+ "type" : "object"
}
},
+ "required" : [ "feedback", "conversation_data" ],
"type" : "object"
}
}
@@ -32414,34 +32637,14 @@
"application/json" : {
"schema" : {
"properties" : {
- "api_key" : {
- "type" : "string"
- },
- "collection_id" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.appdb-id"
- },
- "created_at" : {
- "format" : "date-time",
- "type" : "string"
- },
- "database_id" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.appdb-id"
- },
- "id" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.appdb-id"
- },
- "name" : {
- "type" : "string"
+ "body" : {
+ "type" : "null"
},
"status" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.api.status"
- },
- "updated_at" : {
- "format" : "date-time",
- "type" : "string"
+ "const" : 204
}
},
- "required" : [ "id", "name", "collection_id", "database_id", "status", "created_at", "updated_at" ],
+ "required" : [ "status", "body" ],
"type" : "object"
}
}
@@ -32455,104 +32658,24 @@
"description" : "Server error response"
}
},
- "summary" : "POST /api/ee/workspace",
- "tags" : [ "/api/ee/workspace" ]
+ "summary" : "POST /api/embed-mcp/feedback",
+ "tags" : [ "/api/embed-mcp" ]
}
},
- "/api/ee/workspace/checkout" : {
+ "/api/embed-theme" : {
"get" : {
- "description" : "Get checkout status for a global transform.\n\n Returns:\n - checkout_disabled: Why this transform cannot be checked out (nil if allowed)\n - workspaces: All workspaces for this transform's database, with checkout status\n - transforms: (DEPRECATED) Use :workspaces instead",
- "operationId" : "get-api-ee-workspace-checkout",
- "parameters" : [ {
- "description" : "value must be an integer greater than zero.",
- "in" : "query",
- "name" : "transform-id",
- "required" : true,
- "schema" : {
- "minimum" : 1,
- "type" : "integer"
- }
- } ],
+ "description" : "Fetch a list of all embedding themes.",
+ "operationId" : "get-api-embed-theme",
+ "parameters" : [ ],
"responses" : {
"2XX" : {
"content" : {
"application/json" : {
"schema" : {
- "properties" : {
- "checkout_disabled" : {
- "oneOf" : [ {
- "enum" : [ "mbql", "card-reference", "unknown-type" ],
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "transforms" : {
- "items" : {
- "properties" : {
- "id" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.ref-id"
- },
- "name" : {
- "type" : "string"
- },
- "workspace" : {
- "properties" : {
- "id" : {
- "description" : "value must be an integer greater than zero.",
- "minimum" : 1,
- "type" : "integer"
- },
- "name" : {
- "type" : "string"
- }
- },
- "required" : [ "id", "name" ],
- "type" : "object"
- }
- },
- "required" : [ "id", "name", "workspace" ],
- "type" : "object"
- },
- "type" : "array"
- },
- "workspaces" : {
- "items" : {
- "properties" : {
- "existing" : {
- "oneOf" : [ {
- "properties" : {
- "name" : {
- "type" : "string"
- },
- "ref_id" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.ref-id"
- }
- },
- "required" : [ "ref_id", "name" ],
- "type" : "object"
- }, {
- "type" : "null"
- } ]
- },
- "id" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.appdb-id"
- },
- "name" : {
- "type" : "string"
- },
- "status" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.api.status"
- }
- },
- "required" : [ "id", "name", "status", "existing" ],
- "type" : "object"
- },
- "type" : "array"
- }
+ "items" : {
+ "$ref" : "#/components/schemas/metabase.embedding-rest.api.theme.EmbeddingTheme"
},
- "required" : [ "checkout_disabled", "workspaces", "transforms" ],
- "type" : "object"
+ "type" : "array"
}
}
},
@@ -32565,104 +32688,39 @@
"description" : "Server error response"
}
},
- "summary" : "GET /api/ee/workspace/checkout",
- "tags" : [ "/api/ee/workspace" ]
- }
- },
- "/api/ee/workspace/database" : {
- "get" : {
- "description" : "Get a list supported databases, and whether they're enabled and have required permissions.",
- "operationId" : "get-api-ee-workspace-database",
+ "summary" : "GET /api/embed-theme",
+ "tags" : [ "/api/embed-theme" ]
+ },
+ "post" : {
+ "description" : "Create a new embedding theme.",
+ "operationId" : "post-api-embed-theme",
"parameters" : [ ],
- "responses" : {
- "2XX" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "properties" : {
- "databases" : {
- "items" : {
- "properties" : {
- "enabled" : {
- "type" : "boolean"
- },
- "id" : {
- "description" : "value must be an integer greater than zero.",
- "minimum" : 1,
- "type" : "integer"
- },
- "name" : {
- "type" : "string"
- },
- "permissions_status" : {
- "properties" : {
- "checked_at" : {
- "type" : "string"
- },
- "error" : {
- "type" : "string"
- },
- "status" : {
- "type" : "string"
- }
- },
- "required" : [ "status", "checked_at" ],
- "type" : "object"
- }
- },
- "required" : [ "id", "name", "enabled" ],
- "type" : "object"
- },
- "type" : "array"
- }
+ "requestBody" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "properties" : {
+ "name" : {
+ "minLength" : 1,
+ "type" : "string"
},
- "required" : [ "databases" ],
- "type" : "object"
- }
+ "settings" : {
+ "properties" : { },
+ "type" : "object"
+ }
+ },
+ "required" : [ "name", "settings" ],
+ "type" : "object"
}
- },
- "description" : "Successful response"
- },
- "4XX" : {
- "description" : "Client error response"
- },
- "5XX" : {
- "description" : "Server error response"
+ }
}
},
- "summary" : "GET /api/ee/workspace/database",
- "tags" : [ "/api/ee/workspace" ]
- }
- },
- "/api/ee/workspace/enabled" : {
- "get" : {
- "description" : "Test whether the current user can use Workspaces. Optionally takes a specific database.\n Factors include: driver support, database user privileges, metabase permissions.",
- "operationId" : "get-api-ee-workspace-enabled",
- "parameters" : [ {
- "description" : "value must be an integer greater than zero.",
- "in" : "query",
- "name" : "database-id",
- "required" : false,
- "schema" : {
- "minimum" : 1,
- "type" : "integer"
- }
- } ],
"responses" : {
"2XX" : {
"content" : {
"application/json" : {
"schema" : {
- "properties" : {
- "reason" : {
- "type" : "string"
- },
- "supported" : {
- "type" : "boolean"
- }
- },
- "required" : [ "supported" ],
- "type" : "object"
+ "$ref" : "#/components/schemas/metabase.embedding-rest.api.theme.EmbeddingTheme"
}
}
},
@@ -32675,20 +32733,40 @@
"description" : "Server error response"
}
},
- "summary" : "GET /api/ee/workspace/enabled",
- "tags" : [ "/api/ee/workspace" ]
+ "summary" : "POST /api/embed-theme",
+ "tags" : [ "/api/embed-theme" ]
}
},
- "/api/ee/workspace/test-resources" : {
+ "/api/embed-theme/seed-defaults" : {
"post" : {
- "description" : "Create test resources for workspace e2e tests. Only available in dev/test mode.\n\n Optionally accepts a database_id in the body; if not provided it will try to use the sample database.",
- "operationId" : "post-api-ee-workspace-test-resources",
+ "description" : "Seed default embedding themes on first call, using the payloads built by the frontend from the\n `METABASE_LIGHT_THEME` / `METABASE_DARK_THEME` constants.\n\n Idempotent: guarded by the `default-embedding-themes-seeded` setting. Once flipped, subsequent calls\n are no-ops even if the admin has since deleted the seeded themes, so deletions are preserved.",
+ "operationId" : "post-api-embed-theme-seed-defaults",
"parameters" : [ ],
"requestBody" : {
"content" : {
"application/json" : {
"schema" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.api.test-resources-request"
+ "properties" : {
+ "themes" : {
+ "items" : {
+ "properties" : {
+ "name" : {
+ "minLength" : 1,
+ "type" : "string"
+ },
+ "settings" : {
+ "properties" : { },
+ "type" : "object"
+ }
+ },
+ "required" : [ "name", "settings" ],
+ "type" : "object"
+ },
+ "type" : "array"
+ }
+ },
+ "required" : [ "themes" ],
+ "type" : "object"
}
}
}
@@ -32698,7 +32776,7 @@
"content" : {
"application/json" : {
"schema" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.api.test-resources-response"
+ "type" : "null"
}
}
},
@@ -32711,18 +32789,18 @@
"description" : "Server error response"
}
},
- "summary" : "POST /api/ee/workspace/test-resources",
- "tags" : [ "/api/ee/workspace" ]
+ "summary" : "POST /api/embed-theme/seed-defaults",
+ "tags" : [ "/api/embed-theme" ]
}
},
- "/api/ee/workspace/{ws-id}" : {
+ "/api/embed-theme/{id}" : {
"delete" : {
- "description" : "Delete a workspace and all its contents, including mirrored entities.",
- "operationId" : "delete-api-ee-workspace-ws-id",
+ "description" : "Delete an embedding theme.",
+ "operationId" : "delete-api-embed-theme-id",
"parameters" : [ {
"description" : "value must be an integer greater than zero.",
"in" : "path",
- "name" : "ws-id",
+ "name" : "id",
"required" : true,
"schema" : {
"minimum" : 1,
@@ -32734,13 +32812,7 @@
"content" : {
"application/json" : {
"schema" : {
- "properties" : {
- "ok" : {
- "const" : true
- }
- },
- "required" : [ "ok" ],
- "type" : "object"
+ "type" : "null"
}
}
},
@@ -32753,16 +32825,16 @@
"description" : "Server error response"
}
},
- "summary" : "DELETE /api/ee/workspace/{ws-id}",
- "tags" : [ "/api/ee/workspace" ]
+ "summary" : "DELETE /api/embed-theme/{id}",
+ "tags" : [ "/api/embed-theme" ]
},
"get" : {
- "description" : "Get a single workspace by ID",
- "operationId" : "get-api-ee-workspace-ws-id",
+ "description" : "Fetch a single embedding theme by ID.",
+ "operationId" : "get-api-embed-theme-id",
"parameters" : [ {
"description" : "value must be an integer greater than zero.",
"in" : "path",
- "name" : "ws-id",
+ "name" : "id",
"required" : true,
"schema" : {
"minimum" : 1,
@@ -32774,36 +32846,7 @@
"content" : {
"application/json" : {
"schema" : {
- "properties" : {
- "api_key" : {
- "type" : "string"
- },
- "collection_id" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.appdb-id"
- },
- "created_at" : {
- "format" : "date-time",
- "type" : "string"
- },
- "database_id" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.appdb-id"
- },
- "id" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.appdb-id"
- },
- "name" : {
- "type" : "string"
- },
- "status" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.api.status"
- },
- "updated_at" : {
- "format" : "date-time",
- "type" : "string"
- }
- },
- "required" : [ "id", "name", "collection_id", "database_id", "status", "created_at", "updated_at" ],
- "type" : "object"
+ "$ref" : "#/components/schemas/metabase.embedding-rest.api.theme.EmbeddingTheme"
}
}
},
@@ -32816,16 +32859,16 @@
"description" : "Server error response"
}
},
- "summary" : "GET /api/ee/workspace/{ws-id}",
- "tags" : [ "/api/ee/workspace" ]
+ "summary" : "GET /api/embed-theme/{id}",
+ "tags" : [ "/api/embed-theme" ]
},
"put" : {
- "description" : "Update simple workspace properties.\n\n Can set database_id only on uninitialized workspaces.",
- "operationId" : "put-api-ee-workspace-ws-id",
+ "description" : "Update an embedding theme.",
+ "operationId" : "put-api-embed-theme-id",
"parameters" : [ {
"description" : "value must be an integer greater than zero.",
"in" : "path",
- "name" : "ws-id",
+ "name" : "id",
"required" : true,
"schema" : {
"minimum" : 1,
@@ -32836,14 +32879,22 @@
"content" : {
"application/json" : {
"schema" : {
- "additionalProperties" : false,
"properties" : {
- "database_id" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.appdb-id"
- },
"name" : {
- "minLength" : 1,
- "type" : "string"
+ "oneOf" : [ {
+ "minLength" : 1,
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "settings" : {
+ "oneOf" : [ {
+ "properties" : { },
+ "type" : "object"
+ }, {
+ "type" : "null"
+ } ]
}
},
"type" : "object"
@@ -32856,36 +32907,7 @@
"content" : {
"application/json" : {
"schema" : {
- "properties" : {
- "api_key" : {
- "type" : "string"
- },
- "collection_id" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.appdb-id"
- },
- "created_at" : {
- "format" : "date-time",
- "type" : "string"
- },
- "database_id" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.appdb-id"
- },
- "id" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.appdb-id"
- },
- "name" : {
- "type" : "string"
- },
- "status" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.api.status"
- },
- "updated_at" : {
- "format" : "date-time",
- "type" : "string"
- }
- },
- "required" : [ "id", "name", "collection_id", "database_id", "status", "created_at", "updated_at" ],
- "type" : "object"
+ "$ref" : "#/components/schemas/metabase.embedding-rest.api.theme.EmbeddingTheme"
}
}
},
@@ -32898,62 +32920,102 @@
"description" : "Server error response"
}
},
- "summary" : "PUT /api/ee/workspace/{ws-id}",
- "tags" : [ "/api/ee/workspace" ]
+ "summary" : "PUT /api/embed-theme/{id}",
+ "tags" : [ "/api/embed-theme" ]
}
},
- "/api/ee/workspace/{ws-id}/archive" : {
+ "/api/embed-theme/{id}/copy" : {
"post" : {
- "description" : "Archive a workspace. Deletes the isolated schema and tables, but preserves mirrored entities.",
- "operationId" : "post-api-ee-workspace-ws-id-archive",
+ "description" : "Copy an embedding theme.",
+ "operationId" : "post-api-embed-theme-id-copy",
"parameters" : [ {
"description" : "value must be an integer greater than zero.",
"in" : "path",
- "name" : "ws-id",
+ "name" : "id",
+ "required" : true,
+ "schema" : {
+ "minimum" : 1,
+ "type" : "integer"
+ }
+ } ],
+ "responses" : {
+ "2XX" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "$ref" : "#/components/schemas/metabase.embedding-rest.api.theme.EmbeddingTheme"
+ }
+ }
+ },
+ "description" : "Successful response"
+ },
+ "4XX" : {
+ "description" : "Client error response"
+ },
+ "5XX" : {
+ "description" : "Server error response"
+ }
+ },
+ "summary" : "POST /api/embed-theme/{id}/copy",
+ "tags" : [ "/api/embed-theme" ]
+ }
+ },
+ "/api/embed/card/{token}" : {
+ "get" : {
+ "description" : "Fetch a Card via a JSON Web Token signed with the `embedding-secret-key`.\n\n Token should have the following format:\n\n {:resource {:question <card-id>}}",
+ "operationId" : "get-api-embed-card-token",
+ "parameters" : [ {
+ "in" : "path",
+ "name" : "token",
+ "required" : true,
+ "schema" : {
+ "type" : "string"
+ }
+ } ],
+ "responses" : {
+ "2XX" : {
+ "description" : "Successful response"
+ },
+ "4XX" : {
+ "description" : "Client error response"
+ },
+ "5XX" : {
+ "description" : "Server error response"
+ }
+ },
+ "summary" : "GET /api/embed/card/{token}",
+ "tags" : [ "/api/embed" ]
+ }
+ },
+ "/api/embed/card/{token}/params/{param-key}/remapping" : {
+ "get" : {
+ "description" : "Embedded version of api.card filter values endpoint.",
+ "operationId" : "get-api-embed-card-token-params-param-key-remapping",
+ "parameters" : [ {
+ "in" : "path",
+ "name" : "token",
+ "required" : true,
+ "schema" : {
+ "type" : "string"
+ }
+ }, {
+ "in" : "path",
+ "name" : "param-key",
+ "required" : true,
+ "schema" : {
+ "minLength" : 1,
+ "type" : "string"
+ }
+ }, {
+ "in" : "query",
+ "name" : "value",
"required" : true,
"schema" : {
- "minimum" : 1,
- "type" : "integer"
+ "type" : "string"
}
} ],
"responses" : {
"2XX" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "properties" : {
- "api_key" : {
- "type" : "string"
- },
- "collection_id" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.appdb-id"
- },
- "created_at" : {
- "format" : "date-time",
- "type" : "string"
- },
- "database_id" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.appdb-id"
- },
- "id" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.appdb-id"
- },
- "name" : {
- "type" : "string"
- },
- "status" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.api.status"
- },
- "updated_at" : {
- "format" : "date-time",
- "type" : "string"
- }
- },
- "required" : [ "id", "name", "collection_id", "database_id", "status", "created_at", "updated_at" ],
- "type" : "object"
- }
- }
- },
"description" : "Successful response"
},
"4XX" : {
@@ -32963,66 +33025,40 @@
"description" : "Server error response"
}
},
- "summary" : "POST /api/ee/workspace/{ws-id}/archive",
- "tags" : [ "/api/ee/workspace" ]
+ "summary" : "GET /api/embed/card/{token}/params/{param-key}/remapping",
+ "tags" : [ "/api/embed" ]
}
},
- "/api/ee/workspace/{ws-id}/external/transform" : {
+ "/api/embed/card/{token}/params/{param-key}/search/{prefix}" : {
"get" : {
- "description" : "Get transforms that are external to the workspace, i.e. no matching workspace_transform row exists.",
- "operationId" : "get-api-ee-workspace-ws-id-external-transform",
+ "description" : "Embedded version of chain filter search endpoint.",
+ "operationId" : "get-api-embed-card-token-params-param-key-search-prefix",
"parameters" : [ {
"in" : "path",
- "name" : "ws-id",
+ "name" : "token",
"required" : true,
"schema" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.appdb-id"
+ "type" : "string"
}
}, {
- "in" : "query",
- "name" : "database-id",
- "required" : false,
+ "in" : "path",
+ "name" : "param-key",
+ "required" : true,
"schema" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.appdb-id"
+ "minLength" : 1,
+ "type" : "string"
+ }
+ }, {
+ "in" : "path",
+ "name" : "prefix",
+ "required" : true,
+ "schema" : {
+ "minLength" : 1,
+ "type" : "string"
}
} ],
"responses" : {
"2XX" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "properties" : {
- "transforms" : {
- "items" : {
- "properties" : {
- "checkout_disabled" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "id" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.appdb-id"
- },
- "name" : {
- "type" : "string"
- },
- "source_type" : {
- "type" : "string"
- }
- },
- "required" : [ "id", "name", "source_type", "checkout_disabled" ],
- "type" : "object"
- },
- "type" : "array"
- }
- },
- "required" : [ "transforms" ],
- "type" : "object"
- }
- }
- },
"description" : "Successful response"
},
"4XX" : {
@@ -33032,48 +33068,32 @@
"description" : "Server error response"
}
},
- "summary" : "GET /api/ee/workspace/{ws-id}/external/transform",
- "tags" : [ "/api/ee/workspace" ]
+ "summary" : "GET /api/embed/card/{token}/params/{param-key}/search/{prefix}",
+ "tags" : [ "/api/embed" ]
}
},
- "/api/ee/workspace/{ws-id}/graph" : {
+ "/api/embed/card/{token}/params/{param-key}/values" : {
"get" : {
- "description" : "Display the dependency graph between the Changeset and the (potentially external) entities that they depend on.",
- "operationId" : "get-api-ee-workspace-ws-id-graph",
+ "description" : "Embedded version of api.card filter values endpoint.",
+ "operationId" : "get-api-embed-card-token-params-param-key-values",
"parameters" : [ {
- "description" : "value must be an integer greater than zero.",
"in" : "path",
- "name" : "ws-id",
+ "name" : "token",
"required" : true,
"schema" : {
- "minimum" : 1,
- "type" : "integer"
+ "type" : "string"
+ }
+ }, {
+ "in" : "path",
+ "name" : "param-key",
+ "required" : true,
+ "schema" : {
+ "minLength" : 1,
+ "type" : "string"
}
} ],
"responses" : {
"2XX" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "properties" : {
- "edges" : {
- "items" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.api.graph-edge"
- },
- "type" : "array"
- },
- "nodes" : {
- "items" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.api.graph-node"
- },
- "type" : "array"
- }
- },
- "required" : [ "nodes", "edges" ],
- "type" : "object"
- }
- }
- },
"description" : "Successful response"
},
"4XX" : {
@@ -33083,118 +33103,24 @@
"description" : "Server error response"
}
},
- "summary" : "GET /api/ee/workspace/{ws-id}/graph",
- "tags" : [ "/api/ee/workspace" ]
+ "summary" : "GET /api/embed/card/{token}/params/{param-key}/values",
+ "tags" : [ "/api/embed" ]
}
},
- "/api/ee/workspace/{ws-id}/input/grant" : {
- "post" : {
- "description" : "Grant read access to input tables by table coordinates. Superuser only.\n Idempotent - returns which tables were already granted vs newly granted.",
- "operationId" : "post-api-ee-workspace-ws-id-input-grant",
+ "/api/embed/card/{token}/query" : {
+ "get" : {
+ "description" : "Fetch the results of running a Card using a JSON Web Token signed with the `embedding-secret-key`.\n\n Token should have the following format:\n\n {:resource {:question <card-id>}\n :params <parameters>}",
+ "operationId" : "get-api-embed-card-token-query",
"parameters" : [ {
"in" : "path",
- "name" : "ws-id",
+ "name" : "token",
"required" : true,
"schema" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.appdb-id"
+ "type" : "string"
}
} ],
- "requestBody" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "properties" : {
- "tables" : {
- "items" : {
- "properties" : {
- "db_id" : {
- "description" : "value must be an integer greater than zero.",
- "minimum" : 1,
- "type" : "integer"
- },
- "schema" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "table" : {
- "type" : "string"
- }
- },
- "required" : [ "db_id", "schema", "table" ],
- "type" : "object"
- },
- "type" : "array"
- }
- },
- "required" : [ "tables" ],
- "type" : "object"
- }
- }
- }
- },
"responses" : {
"2XX" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "properties" : {
- "already_granted" : {
- "items" : {
- "properties" : {
- "db_id" : {
- "description" : "value must be an integer greater than zero.",
- "minimum" : 1,
- "type" : "integer"
- },
- "schema" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "table" : {
- "type" : "string"
- }
- },
- "required" : [ "db_id", "schema", "table" ],
- "type" : "object"
- },
- "type" : "array"
- },
- "newly_granted" : {
- "items" : {
- "properties" : {
- "db_id" : {
- "description" : "value must be an integer greater than zero.",
- "minimum" : 1,
- "type" : "integer"
- },
- "schema" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "table" : {
- "type" : "string"
- }
- },
- "required" : [ "db_id", "schema", "table" ],
- "type" : "object"
- },
- "type" : "array"
- }
- },
- "required" : [ "already_granted", "newly_granted" ],
- "type" : "object"
- }
- }
- },
"description" : "Successful response"
},
"4XX" : {
@@ -33204,56 +33130,47 @@
"description" : "Server error response"
}
},
- "summary" : "POST /api/ee/workspace/{ws-id}/input/grant",
- "tags" : [ "/api/ee/workspace" ]
+ "summary" : "GET /api/embed/card/{token}/query",
+ "tags" : [ "/api/embed" ]
}
},
- "/api/ee/workspace/{ws-id}/input/pending" : {
+ "/api/embed/card/{token}/query/{export-format}" : {
"get" : {
- "description" : "List all input tables that haven't been granted access yet, excluding tables shadowed by workspace outputs.",
- "operationId" : "get-api-ee-workspace-ws-id-input-pending",
+ "description" : "Like `GET /api/embed/card/query`, but returns the results as a file in the specified format.",
+ "operationId" : "get-api-embed-card-token-query-export-format",
"parameters" : [ {
"in" : "path",
- "name" : "ws-id",
+ "name" : "token",
+ "required" : true,
+ "schema" : {
+ "type" : "string"
+ }
+ }, {
+ "in" : "path",
+ "name" : "export-format",
+ "required" : true,
+ "schema" : {
+ "$ref" : "#/components/schemas/metabase.query-processor.schema.export-format"
+ }
+ }, {
+ "in" : "query",
+ "name" : "format_rows",
+ "required" : true,
+ "schema" : {
+ "default" : false,
+ "type" : "boolean"
+ }
+ }, {
+ "in" : "query",
+ "name" : "pivot_results",
"required" : true,
"schema" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.appdb-id"
+ "default" : false,
+ "type" : "boolean"
}
} ],
"responses" : {
"2XX" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "properties" : {
- "inputs" : {
- "items" : {
- "properties" : {
- "db_id" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.appdb-id"
- },
- "schema" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "table" : {
- "type" : "string"
- }
- },
- "required" : [ "db_id", "schema", "table" ],
- "type" : "object"
- },
- "type" : "array"
- }
- },
- "required" : [ "inputs" ],
- "type" : "object"
- }
- }
- },
"description" : "Successful response"
},
"4XX" : {
@@ -33263,89 +33180,24 @@
"description" : "Server error response"
}
},
- "summary" : "GET /api/ee/workspace/{ws-id}/input/pending",
- "tags" : [ "/api/ee/workspace" ]
+ "summary" : "GET /api/embed/card/{token}/query/{export-format}",
+ "tags" : [ "/api/embed" ]
}
},
- "/api/ee/workspace/{ws-id}/log" : {
+ "/api/embed/dashboard/{token}" : {
"get" : {
- "description" : "Get workspace creation status and recent log entries for polling during async setup",
- "operationId" : "get-api-ee-workspace-ws-id-log",
+ "description" : "Fetch a Dashboard via a JSON Web Token signed with the `embedding-secret-key`.\n\n Token should have the following format:\n\n {:resource {:dashboard <dashboard-id>}}",
+ "operationId" : "get-api-embed-dashboard-token",
"parameters" : [ {
- "description" : "value must be an integer greater than zero.",
"in" : "path",
- "name" : "ws-id",
+ "name" : "token",
"required" : true,
"schema" : {
- "minimum" : 1,
- "type" : "integer"
+ "type" : "string"
}
} ],
"responses" : {
"2XX" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "properties" : {
- "last_completed_at" : {
- "oneOf" : [ { }, {
- "type" : "null"
- } ]
- },
- "logs" : {
- "items" : {
- "properties" : {
- "completed_at" : {
- "oneOf" : [ { }, {
- "type" : "null"
- } ]
- },
- "description" : { },
- "id" : {
- "description" : "value must be an integer greater than zero.",
- "minimum" : 1,
- "type" : "integer"
- },
- "message" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "started_at" : { },
- "status" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "task" : {
- "type" : "string"
- },
- "updated_at" : { }
- },
- "required" : [ "id", "task", "description", "started_at", "updated_at", "completed_at", "status", "message" ],
- "type" : "object"
- },
- "type" : "array"
- },
- "status" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.api.status"
- },
- "updated_at" : { },
- "workspace_id" : {
- "description" : "value must be an integer greater than zero.",
- "minimum" : 1,
- "type" : "integer"
- }
- },
- "required" : [ "workspace_id", "status", "updated_at", "last_completed_at", "logs" ],
- "type" : "object"
- }
- }
- },
"description" : "Successful response"
},
"4XX" : {
@@ -33355,117 +33207,42 @@
"description" : "Server error response"
}
},
- "summary" : "GET /api/ee/workspace/{ws-id}/log",
- "tags" : [ "/api/ee/workspace" ]
+ "summary" : "GET /api/embed/dashboard/{token}",
+ "tags" : [ "/api/embed" ]
}
},
- "/api/ee/workspace/{ws-id}/merge" : {
- "post" : {
- "description" : "This will:\n 1. Update original transforms with workspace versions\n 2. Archive the workspace and clean up isolated resources\n Returns a report of merged entities, or error in errors key.\n\n Request body may include:\n - commit-message: A description of what changes are being merged (optional, will be required in future)",
- "operationId" : "post-api-ee-workspace-ws-id-merge",
+ "/api/embed/dashboard/{token}/dashcard/{dashcard-id}/card/{card-id}" : {
+ "get" : {
+ "description" : "Fetch the results of running a Card belonging to a Dashboard using a JSON Web Token signed with the\n `embedding-secret-key`",
+ "operationId" : "get-api-embed-dashboard-token-dashcard-dashcard-id-card-card-id",
"parameters" : [ {
"in" : "path",
- "name" : "ws-id",
+ "name" : "token",
"required" : true,
"schema" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.appdb-id"
+ "type" : "string"
}
- } ],
- "requestBody" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "properties" : {
- "commit-message" : {
- "minLength" : 1,
- "type" : "string"
- }
- },
- "type" : "object"
- }
- }
+ }, {
+ "description" : "value must be an integer greater than zero.",
+ "in" : "path",
+ "name" : "dashcard-id",
+ "required" : true,
+ "schema" : {
+ "minimum" : 1,
+ "type" : "integer"
}
- },
+ }, {
+ "description" : "value must be an integer greater than zero.",
+ "in" : "path",
+ "name" : "card-id",
+ "required" : true,
+ "schema" : {
+ "minimum" : 1,
+ "type" : "integer"
+ }
+ } ],
"responses" : {
"2XX" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "anyOf" : [ {
- "properties" : {
- "errors" : {
- "items" : {
- "properties" : {
- "global_id" : {
- "oneOf" : [ {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.appdb-id"
- }, {
- "type" : "null"
- } ]
- },
- "op" : {
- "enum" : [ "create", "delete", "update", "noop" ],
- "type" : "string"
- },
- "ref_id" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.ref-id"
- }
- },
- "required" : [ "op", "ref_id" ],
- "type" : "object"
- },
- "type" : "array"
- },
- "merged" : {
- "properties" : {
- "transforms" : {
- "items" : {
- "properties" : {
- "global_id" : {
- "oneOf" : [ {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.appdb-id"
- }, {
- "type" : "null"
- } ]
- },
- "op" : {
- "enum" : [ "create", "delete", "update", "noop" ],
- "type" : "string"
- },
- "ref_id" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.ref-id"
- }
- },
- "required" : [ "op", "ref_id" ],
- "type" : "object"
- },
- "type" : "array"
- }
- },
- "required" : [ "transforms" ],
- "type" : "object"
- },
- "workspace" : {
- "properties" : {
- "id" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.appdb-id"
- },
- "name" : {
- "type" : "string"
- }
- },
- "required" : [ "id", "name" ],
- "type" : "object"
- }
- },
- "required" : [ "merged", "errors", "workspace" ],
- "type" : "object"
- }, {
- "type" : "string"
- } ]
- }
- }
- },
"description" : "Successful response"
},
"4XX" : {
@@ -33475,36 +33252,65 @@
"description" : "Server error response"
}
},
- "summary" : "POST /api/ee/workspace/{ws-id}/merge",
- "tags" : [ "/api/ee/workspace" ]
+ "summary" : "GET /api/embed/dashboard/{token}/dashcard/{dashcard-id}/card/{card-id}",
+ "tags" : [ "/api/embed" ]
}
},
- "/api/ee/workspace/{ws-id}/problem" : {
+ "/api/embed/dashboard/{token}/dashcard/{dashcard-id}/card/{card-id}/{export-format}" : {
"get" : {
- "description" : "Detect problems in the workspace that would affect downstream transforms after merge.\n\n Returns a list of problems, each with:\n - category: the problem category (e.g. 'unused', 'internal-downstream', 'external-downstream')\n - problem: the specific problem (e.g. 'not-run', 'stale', 'removed-field')\n - severity: :error, :warning, or :info\n - block-merge: whether this problem prevents merging\n - data: extra information, shape depends on the problem type\n\n See `metabase-enterprise.workspaces.types/problem-types` for the full list.",
- "operationId" : "get-api-ee-workspace-ws-id-problem",
+ "description" : "Fetch the results of running a Card belonging to a Dashboard using a JSON Web Token signed with the\n `embedding-secret-key` return the data in one of the export formats",
+ "operationId" : "get-api-embed-dashboard-token-dashcard-dashcard-id-card-card-id-export-format",
"parameters" : [ {
+ "in" : "path",
+ "name" : "token",
+ "required" : true,
+ "schema" : {
+ "type" : "string"
+ }
+ }, {
+ "description" : "value must be an integer greater than zero.",
+ "in" : "path",
+ "name" : "dashcard-id",
+ "required" : true,
+ "schema" : {
+ "minimum" : 1,
+ "type" : "integer"
+ }
+ }, {
"description" : "value must be an integer greater than zero.",
"in" : "path",
- "name" : "ws-id",
+ "name" : "card-id",
"required" : true,
"schema" : {
"minimum" : 1,
"type" : "integer"
}
+ }, {
+ "in" : "path",
+ "name" : "export-format",
+ "required" : true,
+ "schema" : {
+ "$ref" : "#/components/schemas/metabase.query-processor.schema.export-format"
+ }
+ }, {
+ "in" : "query",
+ "name" : "format_rows",
+ "required" : true,
+ "schema" : {
+ "default" : false,
+ "type" : "boolean"
+ }
+ }, {
+ "in" : "query",
+ "name" : "pivot_results",
+ "required" : true,
+ "schema" : {
+ "default" : false,
+ "type" : "boolean"
+ }
} ],
"responses" : {
"2XX" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "items" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.problem"
- },
- "type" : "array"
- }
- }
- },
"description" : "Successful response"
},
"4XX" : {
@@ -33514,47 +33320,32 @@
"description" : "Server error response"
}
},
- "summary" : "GET /api/ee/workspace/{ws-id}/problem",
- "tags" : [ "/api/ee/workspace" ]
+ "summary" : "GET /api/embed/dashboard/{token}/dashcard/{dashcard-id}/card/{card-id}/{export-format}",
+ "tags" : [ "/api/embed" ]
}
},
- "/api/ee/workspace/{ws-id}/query" : {
- "post" : {
- "description" : "Execute an arbitrary SQL query in the workspace's isolated database context.\n Table references are remapped to isolated workspace tables.\n Returns the first 2000 rows of query results.",
- "operationId" : "post-api-ee-workspace-ws-id-query",
+ "/api/embed/dashboard/{token}/params/{param-key}/remapping" : {
+ "get" : {
+ "description" : "Embedded version of the remapped dashboard param value endpoint.",
+ "operationId" : "get-api-embed-dashboard-token-params-param-key-remapping",
"parameters" : [ {
"in" : "path",
- "name" : "ws-id",
+ "name" : "token",
"required" : true,
"schema" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.appdb-id"
+ "type" : "string"
}
- } ],
- "requestBody" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "properties" : {
- "sql" : {
- "minLength" : 1,
- "type" : "string"
- }
- },
- "required" : [ "sql" ],
- "type" : "object"
- }
- }
+ }, {
+ "in" : "path",
+ "name" : "param-key",
+ "required" : true,
+ "schema" : {
+ "minLength" : 1,
+ "type" : "string"
}
- },
+ } ],
"responses" : {
"2XX" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.query-result"
- }
- }
- },
"description" : "Successful response"
},
"4XX" : {
@@ -33564,66 +33355,40 @@
"description" : "Server error response"
}
},
- "summary" : "POST /api/ee/workspace/{ws-id}/query",
- "tags" : [ "/api/ee/workspace" ]
+ "summary" : "GET /api/embed/dashboard/{token}/params/{param-key}/remapping",
+ "tags" : [ "/api/embed" ]
}
},
- "/api/ee/workspace/{ws-id}/run" : {
- "post" : {
- "description" : "Execute all transforms in the workspace in dependency order.\n Returns which transforms succeeded, failed, and were not run.",
- "operationId" : "post-api-ee-workspace-ws-id-run",
+ "/api/embed/dashboard/{token}/params/{param-key}/search/{prefix}" : {
+ "get" : {
+ "description" : "Embedded version of chain filter search endpoint.",
+ "operationId" : "get-api-embed-dashboard-token-params-param-key-search-prefix",
"parameters" : [ {
"in" : "path",
- "name" : "ws-id",
+ "name" : "token",
"required" : true,
"schema" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.appdb-id"
+ "type" : "string"
}
- } ],
- "requestBody" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "properties" : {
- "stale_only" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.flag"
- }
- },
- "type" : "object"
- }
- }
+ }, {
+ "in" : "path",
+ "name" : "param-key",
+ "required" : true,
+ "schema" : {
+ "minLength" : 1,
+ "type" : "string"
}
- },
+ }, {
+ "in" : "path",
+ "name" : "prefix",
+ "required" : true,
+ "schema" : {
+ "minLength" : 1,
+ "type" : "string"
+ }
+ } ],
"responses" : {
"2XX" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "properties" : {
- "failed" : {
- "items" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.ref-id"
- },
- "type" : "array"
- },
- "not_run" : {
- "items" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.ref-id"
- },
- "type" : "array"
- },
- "succeeded" : {
- "items" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.ref-id"
- },
- "type" : "array"
- }
- },
- "required" : [ "succeeded", "failed", "not_run" ],
- "type" : "object"
- }
- }
- },
"description" : "Successful response"
},
"4XX" : {
@@ -33633,49 +33398,32 @@
"description" : "Server error response"
}
},
- "summary" : "POST /api/ee/workspace/{ws-id}/run",
- "tags" : [ "/api/ee/workspace" ]
+ "summary" : "GET /api/embed/dashboard/{token}/params/{param-key}/search/{prefix}",
+ "tags" : [ "/api/embed" ]
}
},
- "/api/ee/workspace/{ws-id}/table" : {
+ "/api/embed/dashboard/{token}/params/{param-key}/values" : {
"get" : {
- "description" : "Get workspace tables",
- "operationId" : "get-api-ee-workspace-ws-id-table",
+ "description" : "Embedded version of chain filter values endpoint.",
+ "operationId" : "get-api-embed-dashboard-token-params-param-key-values",
"parameters" : [ {
- "description" : "value must be an integer greater than zero.",
"in" : "path",
- "name" : "ws-id",
+ "name" : "token",
"required" : true,
"schema" : {
- "minimum" : 1,
- "type" : "integer"
+ "type" : "string"
+ }
+ }, {
+ "in" : "path",
+ "name" : "param-key",
+ "required" : true,
+ "schema" : {
+ "minLength" : 1,
+ "type" : "string"
}
} ],
"responses" : {
"2XX" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "additionalProperties" : false,
- "properties" : {
- "inputs" : {
- "items" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.api.input-table"
- },
- "type" : "array"
- },
- "outputs" : {
- "items" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.api.output-table"
- },
- "type" : "array"
- }
- },
- "required" : [ "inputs", "outputs" ],
- "type" : "object"
- }
- }
- },
"description" : "Successful response"
},
"4XX" : {
@@ -33685,71 +33433,24 @@
"description" : "Server error response"
}
},
- "summary" : "GET /api/ee/workspace/{ws-id}/table",
- "tags" : [ "/api/ee/workspace" ]
+ "summary" : "GET /api/embed/dashboard/{token}/params/{param-key}/values",
+ "tags" : [ "/api/embed" ]
}
},
- "/api/ee/workspace/{ws-id}/transform" : {
+ "/api/embed/pivot/card/{token}/query" : {
"get" : {
- "description" : "Get all transforms in a workspace.",
- "operationId" : "get-api-ee-workspace-ws-id-transform",
+ "description" : "Fetch the results of running a Card using a JSON Web Token signed with the `embedding-secret-key`.\n\n Token should have the following format:\n\n {:resource {:question <card-id>}\n :params <parameters>}",
+ "operationId" : "get-api-embed-pivot-card-token-query",
"parameters" : [ {
"in" : "path",
- "name" : "ws-id",
+ "name" : "token",
"required" : true,
"schema" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.appdb-id"
+ "type" : "string"
}
} ],
"responses" : {
"2XX" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "properties" : {
- "transforms" : {
- "items" : {
- "additionalProperties" : false,
- "properties" : {
- "creator_id" : {
- "oneOf" : [ {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.appdb-id"
- }, {
- "type" : "null"
- } ]
- },
- "global_id" : {
- "oneOf" : [ {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.appdb-id"
- }, {
- "type" : "null"
- } ]
- },
- "name" : {
- "type" : "string"
- },
- "ref_id" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.ref-id"
- },
- "source_type" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- }
- },
- "required" : [ "ref_id", "global_id", "name", "source_type", "creator_id" ],
- "type" : "object"
- },
- "type" : "array"
- }
- },
- "required" : [ "transforms" ],
- "type" : "object"
- }
- }
- },
"description" : "Successful response"
},
"4XX" : {
@@ -33759,120 +33460,42 @@
"description" : "Server error response"
}
},
- "summary" : "GET /api/ee/workspace/{ws-id}/transform",
- "tags" : [ "/api/ee/workspace" ]
- },
- "post" : {
- "description" : "Add another transform to the Changeset. This could be a fork of an existing global transform, or something new.",
- "operationId" : "post-api-ee-workspace-ws-id-transform",
+ "summary" : "GET /api/embed/pivot/card/{token}/query",
+ "tags" : [ "/api/embed" ]
+ }
+ },
+ "/api/embed/pivot/dashboard/{token}/dashcard/{dashcard-id}/card/{card-id}" : {
+ "get" : {
+ "description" : "Fetch the results of running a Card belonging to a Dashboard using a JSON Web Token signed with the\n `embedding-secret-key`",
+ "operationId" : "get-api-embed-pivot-dashboard-token-dashcard-dashcard-id-card-card-id",
"parameters" : [ {
"in" : "path",
- "name" : "ws-id",
+ "name" : "token",
"required" : true,
"schema" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.appdb-id"
+ "type" : "string"
}
- } ],
- "requestBody" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "properties" : {
- "description" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "name" : {
- "type" : "string"
- },
- "source" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.api.transform-source"
- }
- },
- "required" : [ "name", "source" ],
- "type" : "object"
- }
- }
+ }, {
+ "description" : "value must be an integer greater than zero.",
+ "in" : "path",
+ "name" : "dashcard-id",
+ "required" : true,
+ "schema" : {
+ "minimum" : 1,
+ "type" : "integer"
}
- },
+ }, {
+ "description" : "value must be an integer greater than zero.",
+ "in" : "path",
+ "name" : "card-id",
+ "required" : true,
+ "schema" : {
+ "minimum" : 1,
+ "type" : "integer"
+ }
+ } ],
"responses" : {
"2XX" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "properties" : {
- "archived_at" : { },
- "created_at" : { },
- "creator_id" : {
- "oneOf" : [ {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.appdb-id"
- }, {
- "type" : "null"
- } ]
- },
- "description" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "global_id" : {
- "oneOf" : [ {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.appdb-id"
- }, {
- "type" : "null"
- } ]
- },
- "last_run_at" : { },
- "last_run_message" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "last_run_status" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "name" : {
- "type" : "string"
- },
- "ref_id" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.ref-id"
- },
- "source" : {
- "properties" : { },
- "type" : "object"
- },
- "target" : {
- "properties" : { },
- "type" : "object"
- },
- "target_stale" : {
- "oneOf" : [ {
- "type" : "boolean"
- }, {
- "type" : "null"
- } ]
- },
- "updated_at" : { },
- "workspace_id" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.appdb-id"
- }
- },
- "required" : [ "ref_id", "global_id", "name", "description", "source", "target", "target_stale", "workspace_id", "creator_id", "archived_at", "created_at", "updated_at", "last_run_at", "last_run_status", "last_run_message" ],
- "type" : "object"
- }
- }
- },
"description" : "Successful response"
},
"4XX" : {
@@ -33882,88 +33505,70 @@
"description" : "Server error response"
}
},
- "summary" : "POST /api/ee/workspace/{ws-id}/transform",
- "tags" : [ "/api/ee/workspace" ]
+ "summary" : "GET /api/embed/pivot/dashboard/{token}/dashcard/{dashcard-id}/card/{card-id}",
+ "tags" : [ "/api/embed" ]
}
},
- "/api/ee/workspace/{ws-id}/transform/validate/target" : {
- "post" : {
- "description" : "Validate the target table for a workspace transform",
- "operationId" : "post-api-ee-workspace-ws-id-transform-validate-target",
+ "/api/embed/tiles/card/{token}/{zoom}/{x}/{y}" : {
+ "get" : {
+ "description" : "Generates a single tile image for an embedded Card using the map visualization.",
+ "operationId" : "get-api-embed-tiles-card-token-zoom-x-y",
"parameters" : [ {
"in" : "path",
- "name" : "ws-id",
+ "name" : "token",
+ "required" : true,
+ "schema" : {
+ "type" : "string"
+ }
+ }, {
+ "description" : "value must be an integer.",
+ "in" : "path",
+ "name" : "zoom",
+ "required" : true,
+ "schema" : {
+ "type" : "integer"
+ }
+ }, {
+ "description" : "value must be an integer.",
+ "in" : "path",
+ "name" : "x",
+ "required" : true,
+ "schema" : {
+ "type" : "integer"
+ }
+ }, {
+ "description" : "value must be an integer.",
+ "in" : "path",
+ "name" : "y",
"required" : true,
"schema" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.appdb-id"
+ "type" : "integer"
}
}, {
+ "description" : "value must be a valid JSON string.",
"in" : "query",
- "name" : "transform-id",
+ "name" : "parameters",
"required" : false,
"schema" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.ref-id"
+ "type" : "string"
}
- } ],
- "requestBody" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "properties" : {
- "db_id" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.appdb-id"
- },
- "target" : {
- "properties" : {
- "database" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.appdb-id"
- },
- "name" : {
- "type" : "string"
- },
- "schema" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "type" : {
- "type" : "string"
- }
- },
- "required" : [ "type", "schema", "name" ],
- "type" : "object"
- }
- },
- "required" : [ "target" ],
- "type" : "object"
- }
- }
+ }, {
+ "in" : "query",
+ "name" : "latField",
+ "required" : true,
+ "schema" : {
+ "type" : "string"
}
- },
+ }, {
+ "in" : "query",
+ "name" : "lonField",
+ "required" : true,
+ "schema" : {
+ "type" : "string"
+ }
+ } ],
"responses" : {
"2XX" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "properties" : {
- "body" : {
- "anyOf" : [ {
- "type" : "string"
- }, {
- "anyOf" : [ { }, { } ]
- } ]
- },
- "status" : {
- "type" : "integer"
- }
- },
- "required" : [ "status", "body" ],
- "type" : "object"
- }
- }
- },
"description" : "Successful response"
},
"4XX" : {
@@ -33973,139 +33578,142 @@
"description" : "Server error response"
}
},
- "summary" : "POST /api/ee/workspace/{ws-id}/transform/validate/target",
- "tags" : [ "/api/ee/workspace" ]
+ "summary" : "GET /api/embed/tiles/card/{token}/{zoom}/{x}/{y}",
+ "tags" : [ "/api/embed" ]
}
},
- "/api/ee/workspace/{ws-id}/transform/{tx-id}" : {
- "delete" : {
- "description" : "Discard a transform from the changeset.\n Equivalent to resetting a checked-out transform to its global definition, or deleting a provisional transform.",
- "operationId" : "delete-api-ee-workspace-ws-id-transform-tx-id",
+ "/api/embed/tiles/dashboard/{token}/dashcard/{dashcard-id}/card/{card-id}/{zoom}/{x}/{y}" : {
+ "get" : {
+ "description" : "Generates a single tile image for a Card on an embedded Dashboard using the map visualization.",
+ "operationId" : "get-api-embed-tiles-dashboard-token-dashcard-dashcard-id-card-card-id-zoom-x-y",
"parameters" : [ {
"in" : "path",
- "name" : "ws-id",
+ "name" : "token",
"required" : true,
"schema" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.appdb-id"
+ "type" : "string"
}
}, {
+ "description" : "value must be an integer greater than zero.",
"in" : "path",
- "name" : "tx-id",
+ "name" : "dashcard-id",
"required" : true,
"schema" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.ref-id"
+ "minimum" : 1,
+ "type" : "integer"
}
- } ],
- "responses" : {
- "2XX" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "type" : "null"
- }
- }
- },
- "description" : "Successful response"
- },
- "4XX" : {
- "description" : "Client error response"
- },
- "5XX" : {
- "description" : "Server error response"
+ }, {
+ "description" : "value must be an integer greater than zero.",
+ "in" : "path",
+ "name" : "card-id",
+ "required" : true,
+ "schema" : {
+ "minimum" : 1,
+ "type" : "integer"
}
- },
- "summary" : "DELETE /api/ee/workspace/{ws-id}/transform/{tx-id}",
- "tags" : [ "/api/ee/workspace" ]
- },
- "get" : {
- "description" : "Get a specific transform in a workspace.",
- "operationId" : "get-api-ee-workspace-ws-id-transform-tx-id",
- "parameters" : [ {
+ }, {
+ "description" : "value must be an integer.",
"in" : "path",
- "name" : "ws-id",
+ "name" : "zoom",
+ "required" : true,
+ "schema" : {
+ "type" : "integer"
+ }
+ }, {
+ "description" : "value must be an integer.",
+ "in" : "path",
+ "name" : "x",
"required" : true,
"schema" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.appdb-id"
+ "type" : "integer"
}
}, {
+ "description" : "value must be an integer.",
"in" : "path",
- "name" : "tx-id",
+ "name" : "y",
+ "required" : true,
+ "schema" : {
+ "type" : "integer"
+ }
+ }, {
+ "description" : "value must be a valid JSON string.",
+ "in" : "query",
+ "name" : "parameters",
+ "required" : false,
+ "schema" : {
+ "type" : "string"
+ }
+ }, {
+ "in" : "query",
+ "name" : "latField",
+ "required" : true,
+ "schema" : {
+ "type" : "string"
+ }
+ }, {
+ "in" : "query",
+ "name" : "lonField",
"required" : true,
"schema" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.ref-id"
+ "type" : "string"
}
} ],
"responses" : {
"2XX" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "properties" : {
- "archived_at" : { },
- "created_at" : { },
- "creator_id" : {
- "oneOf" : [ {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.appdb-id"
- }, {
- "type" : "null"
- } ]
- },
- "description" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "global_id" : {
- "oneOf" : [ {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.appdb-id"
- }, {
- "type" : "null"
- } ]
- },
- "last_run_at" : { },
- "last_run_message" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "last_run_status" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "name" : {
- "type" : "string"
- },
- "ref_id" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.ref-id"
- },
- "source" : {
- "properties" : { },
- "type" : "object"
- },
- "target" : {
- "properties" : { },
- "type" : "object"
- },
- "target_stale" : {
- "oneOf" : [ {
- "type" : "boolean"
- }, {
- "type" : "null"
- } ]
+ "description" : "Successful response"
+ },
+ "4XX" : {
+ "description" : "Client error response"
+ },
+ "5XX" : {
+ "description" : "Server error response"
+ }
+ },
+ "summary" : "GET /api/embed/tiles/dashboard/{token}/dashcard/{dashcard-id}/card/{card-id}/{zoom}/{x}/{y}",
+ "tags" : [ "/api/embed" ]
+ }
+ },
+ "/api/field/table-ids" : {
+ "post" : {
+ "description" : "Get unique Table IDs for a list of Field IDs.",
+ "operationId" : "post-api-field-table-ids",
+ "parameters" : [ ],
+ "requestBody" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "properties" : {
+ "field_ids" : {
+ "items" : {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
},
- "updated_at" : { },
- "workspace_id" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.appdb-id"
+ "type" : "array"
+ }
+ },
+ "required" : [ "field_ids" ],
+ "type" : "object"
+ }
+ }
+ }
+ },
+ "responses" : {
+ "2XX" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "properties" : {
+ "table_ids" : {
+ "items" : {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
+ },
+ "type" : "array"
}
},
- "required" : [ "ref_id", "global_id", "name", "description", "source", "target", "target_stale", "workspace_id", "creator_id", "archived_at", "created_at", "updated_at", "last_run_at", "last_run_status", "last_run_message" ],
+ "required" : [ "table_ids" ],
"type" : "object"
}
}
@@ -34119,25 +33727,57 @@
"description" : "Server error response"
}
},
- "summary" : "GET /api/ee/workspace/{ws-id}/transform/{tx-id}",
- "tags" : [ "/api/ee/workspace" ]
- },
- "put" : {
- "description" : "Update or create a transform in a workspace.\n If the transform exists, updates it. If it doesn't exist, creates a new transform with the provided ref_id.\n For creation, name, source, and target are required.",
- "operationId" : "put-api-ee-workspace-ws-id-transform-tx-id",
+ "summary" : "POST /api/field/table-ids",
+ "tags" : [ "/api/field" ]
+ }
+ },
+ "/api/field/{id}" : {
+ "get" : {
+ "description" : "Get `Field` with ID.",
+ "operationId" : "get-api-field-id",
"parameters" : [ {
+ "description" : "value must be an integer greater than zero.",
"in" : "path",
- "name" : "ws-id",
+ "name" : "id",
"required" : true,
"schema" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.appdb-id"
+ "minimum" : 1,
+ "type" : "integer"
}
}, {
+ "in" : "query",
+ "name" : "include_editable_data_model",
+ "required" : true,
+ "schema" : {
+ "default" : false,
+ "type" : "boolean"
+ }
+ } ],
+ "responses" : {
+ "2XX" : {
+ "description" : "Successful response"
+ },
+ "4XX" : {
+ "description" : "Client error response"
+ },
+ "5XX" : {
+ "description" : "Server error response"
+ }
+ },
+ "summary" : "GET /api/field/{id}",
+ "tags" : [ "/api/field" ]
+ },
+ "put" : {
+ "description" : "Update `Field` with ID.",
+ "operationId" : "put-api-field-id",
+ "parameters" : [ {
+ "description" : "value must be an integer greater than zero.",
"in" : "path",
- "name" : "tx-id",
+ "name" : "id",
"required" : true,
"schema" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.ref-id"
+ "minimum" : 1,
+ "type" : "integer"
}
} ],
"requestBody" : {
@@ -34145,21 +33785,102 @@
"application/json" : {
"schema" : {
"properties" : {
+ "caveats" : {
+ "oneOf" : [ {
+ "minLength" : 1,
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "coercion_strategy" : {
+ "oneOf" : [ {
+ "description" : "value must be a valid coercion strategy (keyword or string)."
+ }, {
+ "type" : "null"
+ } ]
+ },
"description" : {
"oneOf" : [ {
+ "minLength" : 1,
"type" : "string"
}, {
"type" : "null"
} ]
},
- "name" : {
- "type" : "string"
+ "display_name" : {
+ "oneOf" : [ {
+ "minLength" : 1,
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
},
- "source" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.api.transform-source"
+ "fk_target_field_id" : {
+ "oneOf" : [ {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
+ }, {
+ "type" : "null"
+ } ]
},
- "target" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.api.transform-target"
+ "has_field_values" : {
+ "oneOf" : [ {
+ "$ref" : "#/components/schemas/metabase.lib.schema.metadata..column.has-field-values"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "json_unfolding" : {
+ "oneOf" : [ {
+ "type" : "boolean"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "nfc_path" : {
+ "oneOf" : [ {
+ "items" : {
+ "minLength" : 1,
+ "type" : "string"
+ },
+ "type" : "array"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "points_of_interest" : {
+ "oneOf" : [ {
+ "minLength" : 1,
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "semantic_type" : {
+ "oneOf" : [ {
+ "description" : "value must be a valid field semantic or relation type (keyword or string)."
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "settings" : {
+ "oneOf" : [ {
+ "description" : "Value must be a map.",
+ "properties" : { },
+ "type" : "object"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "visibility_type" : {
+ "oneOf" : [ {
+ "enum" : [ "retired", "sensitive", "normal", "hidden", "details-only" ],
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
}
},
"type" : "object"
@@ -34169,79 +33890,6 @@
},
"responses" : {
"2XX" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "properties" : {
- "archived_at" : { },
- "created_at" : { },
- "creator_id" : {
- "oneOf" : [ {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.appdb-id"
- }, {
- "type" : "null"
- } ]
- },
- "description" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "global_id" : {
- "oneOf" : [ {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.appdb-id"
- }, {
- "type" : "null"
- } ]
- },
- "last_run_at" : { },
- "last_run_message" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "last_run_status" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "name" : {
- "type" : "string"
- },
- "ref_id" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.ref-id"
- },
- "source" : {
- "properties" : { },
- "type" : "object"
- },
- "target" : {
- "properties" : { },
- "type" : "object"
- },
- "target_stale" : {
- "oneOf" : [ {
- "type" : "boolean"
- }, {
- "type" : "null"
- } ]
- },
- "updated_at" : { },
- "workspace_id" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.appdb-id"
- }
- },
- "required" : [ "ref_id", "global_id", "name", "description", "source", "target", "target_stale", "workspace_id", "creator_id", "archived_at", "created_at", "updated_at", "last_run_at", "last_run_status", "last_run_message" ],
- "type" : "object"
- }
- }
- },
"description" : "Successful response"
},
"4XX" : {
@@ -34251,38 +33899,26 @@
"description" : "Server error response"
}
},
- "summary" : "PUT /api/ee/workspace/{ws-id}/transform/{tx-id}",
- "tags" : [ "/api/ee/workspace" ]
+ "summary" : "PUT /api/field/{id}",
+ "tags" : [ "/api/field" ]
}
},
- "/api/ee/workspace/{ws-id}/transform/{tx-id}/archive" : {
- "post" : {
- "description" : "Mark the given transform to be archived when the workspace is merged.\n For provisional transforms we will skip even creating it in the first place.",
- "operationId" : "post-api-ee-workspace-ws-id-transform-tx-id-archive",
+ "/api/field/{id}/dimension" : {
+ "delete" : {
+ "description" : "Remove the dimension associated to field at ID",
+ "operationId" : "delete-api-field-id-dimension",
"parameters" : [ {
+ "description" : "value must be an integer greater than zero.",
"in" : "path",
- "name" : "ws-id",
- "required" : true,
- "schema" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.appdb-id"
- }
- }, {
- "in" : "path",
- "name" : "tx-id",
+ "name" : "id",
"required" : true,
"schema" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.ref-id"
+ "minimum" : 1,
+ "type" : "integer"
}
} ],
"responses" : {
"2XX" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "type" : "null"
- }
- }
- },
"description" : "Successful response"
},
"4XX" : {
@@ -34292,27 +33928,20 @@
"description" : "Server error response"
}
},
- "summary" : "POST /api/ee/workspace/{ws-id}/transform/{tx-id}/archive",
- "tags" : [ "/api/ee/workspace" ]
- }
- },
- "/api/ee/workspace/{ws-id}/transform/{tx-id}/dry-run" : {
+ "summary" : "DELETE /api/field/{id}/dimension",
+ "tags" : [ "/api/field" ]
+ },
"post" : {
- "description" : "Dry-run a transform in a workspace without persisting to the target table.\n\n Returns the first 2000 rows of transform output for preview purposes.\n Does not update last_run_at or create any database tables.\n\n When run_stale_ancestors is true, any stale ancestor transforms will be executed first\n in dependency order (these ARE persisted). If any ancestor fails, execution stops and\n the dry-run will not proceed.",
- "operationId" : "post-api-ee-workspace-ws-id-transform-tx-id-dry-run",
+ "description" : "Sets the dimension for the given field at ID",
+ "operationId" : "post-api-field-id-dimension",
"parameters" : [ {
+ "description" : "value must be an integer greater than zero.",
"in" : "path",
- "name" : "ws-id",
- "required" : true,
- "schema" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.appdb-id"
- }
- }, {
- "in" : "path",
- "name" : "tx-id",
+ "name" : "id",
"required" : true,
"schema" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.ref-id"
+ "minimum" : 1,
+ "type" : "integer"
}
} ],
"requestBody" : {
@@ -34320,10 +33949,25 @@
"application/json" : {
"schema" : {
"properties" : {
- "run_stale_ancestors" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.flag"
+ "human_readable_field_id" : {
+ "oneOf" : [ {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "name" : {
+ "minLength" : 1,
+ "type" : "string"
+ },
+ "type" : {
+ "enum" : [ "internal", "external" ],
+ "type" : "string"
}
},
+ "required" : [ "type", "name" ],
"type" : "object"
}
}
@@ -34331,13 +33975,6 @@
},
"responses" : {
"2XX" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.query-result"
- }
- }
- },
"description" : "Successful response"
},
"4XX" : {
@@ -34347,73 +33984,55 @@
"description" : "Server error response"
}
},
- "summary" : "POST /api/ee/workspace/{ws-id}/transform/{tx-id}/dry-run",
- "tags" : [ "/api/ee/workspace" ]
+ "summary" : "POST /api/field/{id}/dimension",
+ "tags" : [ "/api/field" ]
}
},
- "/api/ee/workspace/{ws-id}/transform/{tx-id}/merge" : {
+ "/api/field/{id}/discard_values" : {
"post" : {
- "description" : "Merge single transform from workspace back to the core. If workspace transform is archived\n the corresponding core transform is deleted.\n\n Request body may include:\n - commit-message: A description of what changes are being merged (optional, will be required in future)",
- "operationId" : "post-api-ee-workspace-ws-id-transform-tx-id-merge",
+ "description" : "Discard the FieldValues belonging to this Field. Only applies to fields that have FieldValues. If this Field's\n Database is set up to automatically sync FieldValues, they will be recreated during the next cycle.",
+ "operationId" : "post-api-field-id-discard_values",
"parameters" : [ {
+ "description" : "value must be an integer greater than zero.",
"in" : "path",
- "name" : "ws-id",
+ "name" : "id",
"required" : true,
"schema" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.appdb-id"
+ "minimum" : 1,
+ "type" : "integer"
}
- }, {
+ } ],
+ "responses" : {
+ "2XX" : {
+ "description" : "Successful response"
+ },
+ "4XX" : {
+ "description" : "Client error response"
+ },
+ "5XX" : {
+ "description" : "Server error response"
+ }
+ },
+ "summary" : "POST /api/field/{id}/discard_values",
+ "tags" : [ "/api/field" ]
+ }
+ },
+ "/api/field/{id}/related" : {
+ "get" : {
+ "description" : "Return related entities.",
+ "operationId" : "get-api-field-id-related",
+ "parameters" : [ {
+ "description" : "value must be an integer greater than zero.",
"in" : "path",
- "name" : "tx-id",
+ "name" : "id",
"required" : true,
"schema" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.ref-id"
+ "minimum" : 1,
+ "type" : "integer"
}
} ],
- "requestBody" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "properties" : {
- "commit-message" : {
- "minLength" : 1,
- "type" : "string"
- }
- },
- "type" : "object"
- }
- }
- }
- },
"responses" : {
"2XX" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "properties" : {
- "global_id" : {
- "oneOf" : [ {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.appdb-id"
- }, {
- "type" : "null"
- } ]
- },
- "message" : {
- "type" : "string"
- },
- "op" : {
- "enum" : [ "create", "delete", "update", "noop" ],
- "type" : "string"
- },
- "ref_id" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.ref-id"
- }
- },
- "required" : [ "op", "global_id", "ref_id" ],
- "type" : "object"
- }
- }
- },
"description" : "Successful response"
},
"4XX" : {
@@ -34423,52 +34042,43 @@
"description" : "Server error response"
}
},
- "summary" : "POST /api/ee/workspace/{ws-id}/transform/{tx-id}/merge",
- "tags" : [ "/api/ee/workspace" ]
+ "summary" : "GET /api/field/{id}/related",
+ "tags" : [ "/api/field" ]
}
},
- "/api/ee/workspace/{ws-id}/transform/{tx-id}/run" : {
- "post" : {
- "description" : "Run a transform in a workspace.\n\n App DB changes are rolled back. Warehouse DB changes persist.\n\n When run_stale_ancestors is true, any stale ancestor transforms will be executed first\n in dependency order. If any ancestor fails, execution stops and remaining ancestors\n are marked as not_run. The target transform will not run if any ancestor failed.",
- "operationId" : "post-api-ee-workspace-ws-id-transform-tx-id-run",
+ "/api/field/{id}/remapping/{remapped-id}" : {
+ "get" : {
+ "description" : "Fetch remapped Field values.",
+ "operationId" : "get-api-field-id-remapping-remapped-id",
"parameters" : [ {
+ "description" : "value must be an integer greater than zero.",
"in" : "path",
- "name" : "ws-id",
+ "name" : "id",
"required" : true,
"schema" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.appdb-id"
+ "minimum" : 1,
+ "type" : "integer"
}
}, {
+ "description" : "value must be an integer greater than zero.",
"in" : "path",
- "name" : "tx-id",
+ "name" : "remapped-id",
"required" : true,
"schema" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.ref-id"
+ "minimum" : 1,
+ "type" : "integer"
}
- } ],
- "requestBody" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "properties" : {
- "run_stale_ancestors" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.flag"
- }
- },
- "type" : "object"
- }
- }
+ }, {
+ "in" : "query",
+ "name" : "value",
+ "required" : true,
+ "schema" : {
+ "minLength" : 1,
+ "type" : "string"
}
- },
+ } ],
"responses" : {
"2XX" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.execution-result"
- }
- }
- },
"description" : "Successful response"
},
"4XX" : {
@@ -34478,38 +34088,26 @@
"description" : "Server error response"
}
},
- "summary" : "POST /api/ee/workspace/{ws-id}/transform/{tx-id}/run",
- "tags" : [ "/api/ee/workspace" ]
+ "summary" : "GET /api/field/{id}/remapping/{remapped-id}",
+ "tags" : [ "/api/field" ]
}
},
- "/api/ee/workspace/{ws-id}/transform/{tx-id}/unarchive" : {
+ "/api/field/{id}/rescan_values" : {
"post" : {
- "description" : "Unmark the given transform for archival. This will recall the last definition it had within the workspace.",
- "operationId" : "post-api-ee-workspace-ws-id-transform-tx-id-unarchive",
+ "description" : "Manually trigger an update for the FieldValues for this Field. Only applies to Fields that are eligible for\n FieldValues.",
+ "operationId" : "post-api-field-id-rescan_values",
"parameters" : [ {
+ "description" : "value must be an integer greater than zero.",
"in" : "path",
- "name" : "ws-id",
- "required" : true,
- "schema" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.appdb-id"
- }
- }, {
- "in" : "path",
- "name" : "tx-id",
+ "name" : "id",
"required" : true,
"schema" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.ref-id"
+ "minimum" : 1,
+ "type" : "integer"
}
} ],
"responses" : {
"2XX" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "type" : "null"
- }
- }
- },
"description" : "Successful response"
},
"4XX" : {
@@ -34519,62 +34117,43 @@
"description" : "Server error response"
}
},
- "summary" : "POST /api/ee/workspace/{ws-id}/transform/{tx-id}/unarchive",
- "tags" : [ "/api/ee/workspace" ]
+ "summary" : "POST /api/field/{id}/rescan_values",
+ "tags" : [ "/api/field" ]
}
},
- "/api/ee/workspace/{ws-id}/unarchive" : {
- "post" : {
- "description" : "Restore an archived workspace. Recreates the isolated schema and tables.",
- "operationId" : "post-api-ee-workspace-ws-id-unarchive",
+ "/api/field/{id}/search/{search-id}" : {
+ "get" : {
+ "description" : "Search for values of a Field with `search-id` that start with `value`. See docstring for\n [[metabase.parameters.field/search-values]] for a more detailed explanation.",
+ "operationId" : "get-api-field-id-search-search-id",
"parameters" : [ {
"description" : "value must be an integer greater than zero.",
"in" : "path",
- "name" : "ws-id",
+ "name" : "id",
+ "required" : true,
+ "schema" : {
+ "minimum" : 1,
+ "type" : "integer"
+ }
+ }, {
+ "description" : "value must be an integer greater than zero.",
+ "in" : "path",
+ "name" : "search-id",
"required" : true,
"schema" : {
"minimum" : 1,
"type" : "integer"
}
+ }, {
+ "in" : "query",
+ "name" : "value",
+ "required" : false,
+ "schema" : {
+ "minLength" : 1,
+ "type" : "string"
+ }
} ],
"responses" : {
"2XX" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "properties" : {
- "api_key" : {
- "type" : "string"
- },
- "collection_id" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.appdb-id"
- },
- "created_at" : {
- "format" : "date-time",
- "type" : "string"
- },
- "database_id" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.appdb-id"
- },
- "id" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.types.appdb-id"
- },
- "name" : {
- "type" : "string"
- },
- "status" : {
- "$ref" : "#/components/schemas/metabase-enterprise.workspaces.api.status"
- },
- "updated_at" : {
- "format" : "date-time",
- "type" : "string"
- }
- },
- "required" : [ "id", "name", "collection_id", "database_id", "status", "created_at", "updated_at" ],
- "type" : "object"
- }
- }
- },
"description" : "Successful response"
},
"4XX" : {
@@ -34584,31 +34163,24 @@
"description" : "Server error response"
}
},
- "summary" : "POST /api/ee/workspace/{ws-id}/unarchive",
- "tags" : [ "/api/ee/workspace" ]
+ "summary" : "GET /api/field/{id}/search/{search-id}",
+ "tags" : [ "/api/field" ]
}
},
- "/api/eid-translation/translate" : {
- "post" : {
- "description" : "Translate entity IDs to model IDs.",
- "operationId" : "post-api-eid-translation-translate",
- "parameters" : [ ],
- "requestBody" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "properties" : {
- "entity_ids" : {
- "properties" : { },
- "type" : "object"
- }
- },
- "required" : [ "entity_ids" ],
- "type" : "object"
- }
- }
+ "/api/field/{id}/summary" : {
+ "get" : {
+ "description" : "Get the count and distinct count of `Field` with ID.",
+ "operationId" : "get-api-field-id-summary",
+ "parameters" : [ {
+ "description" : "value must be an integer greater than zero.",
+ "in" : "path",
+ "name" : "id",
+ "required" : true,
+ "schema" : {
+ "minimum" : 1,
+ "type" : "integer"
}
- },
+ } ],
"responses" : {
"2XX" : {
"description" : "Successful response"
@@ -34620,15 +34192,24 @@
"description" : "Server error response"
}
},
- "summary" : "POST /api/eid-translation/translate",
- "tags" : [ "/api/eid-translation" ]
+ "summary" : "GET /api/field/{id}/summary",
+ "tags" : [ "/api/field" ]
}
},
- "/api/email" : {
- "delete" : {
- "description" : "Clear all email related settings. You must be a superuser or have `setting` permission to do this.",
- "operationId" : "delete-api-email",
- "parameters" : [ ],
+ "/api/field/{id}/values" : {
+ "get" : {
+ "description" : "If a Field's value of `has_field_values` is `:list`, return a list of all the distinct values of the Field (or\n remapped Field), and (if defined by a User) a map of human-readable remapped values. If `has_field_values` is not\n `:list`, checks whether we should create FieldValues for this Field; if so, creates and returns them.",
+ "operationId" : "get-api-field-id-values",
+ "parameters" : [ {
+ "description" : "value must be an integer greater than zero.",
+ "in" : "path",
+ "name" : "id",
+ "required" : true,
+ "schema" : {
+ "minimum" : 1,
+ "type" : "integer"
+ }
+ } ],
"responses" : {
"2XX" : {
"description" : "Successful response"
@@ -34640,54 +34221,44 @@
"description" : "Server error response"
}
},
- "summary" : "DELETE /api/email",
- "tags" : [ "/api/email" ]
+ "summary" : "GET /api/field/{id}/values",
+ "tags" : [ "/api/field" ]
},
- "put" : {
- "description" : "Update multiple email Settings. You must be a superuser or have `setting` permission to do this.",
- "operationId" : "put-api-email",
- "parameters" : [ ],
+ "post" : {
+ "description" : "Update the fields values and human-readable values for a `Field` whose semantic type is\n `category`/`city`/`state`/`country` or whose base type is `type/Boolean`. The human-readable values are optional.",
+ "operationId" : "post-api-field-id-values",
+ "parameters" : [ {
+ "description" : "value must be an integer greater than zero.",
+ "in" : "path",
+ "name" : "id",
+ "required" : true,
+ "schema" : {
+ "minimum" : 1,
+ "type" : "integer"
+ }
+ } ],
"requestBody" : {
"content" : {
"application/json" : {
"schema" : {
"properties" : {
- "email-smtp-host" : {
- "anyOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "email-smtp-password" : {
- "anyOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "email-smtp-port" : {
- "anyOf" : [ {
- "type" : "integer"
- }, {
- "type" : "null"
- } ]
- },
- "email-smtp-security" : {
- "anyOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "email-smtp-username" : {
- "anyOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
+ "values" : {
+ "items" : {
+ "anyOf" : [ {
+ "prefixItems" : [ { } ],
+ "type" : "array"
+ }, {
+ "prefixItems" : [ { }, {
+ "minLength" : 1,
+ "type" : "string"
+ } ],
+ "type" : "array"
+ } ]
+ },
+ "type" : "array"
}
},
+ "required" : [ "values" ],
"type" : "object"
}
}
@@ -34704,15 +34275,30 @@
"description" : "Server error response"
}
},
- "summary" : "PUT /api/email",
- "tags" : [ "/api/email" ]
+ "summary" : "POST /api/field/{id}/values",
+ "tags" : [ "/api/field" ]
}
},
- "/api/email/test" : {
+ "/api/frontend-errors" : {
"post" : {
- "description" : "Send a test email using the SMTP Settings. You must be a superuser or have `setting` permission to do this.\n Returns `{:ok true}` if we were able to send the message successfully, otherwise a standard 400 error response.",
- "operationId" : "post-api-email-test",
+ "description" : "Endpoint for the frontend to report errors. Increments a Prometheus counter\n with the given `type` label.",
+ "operationId" : "post-api-frontend-errors",
"parameters" : [ ],
+ "requestBody" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "properties" : {
+ "type" : {
+ "$ref" : "#/components/schemas/metabase.frontend-errors.api.frontend-error-type"
+ }
+ },
+ "required" : [ "type" ],
+ "type" : "object"
+ }
+ }
+ }
+ },
"responses" : {
"2XX" : {
"description" : "Successful response"
@@ -34724,19 +34310,20 @@
"description" : "Server error response"
}
},
- "summary" : "POST /api/email/test",
- "tags" : [ "/api/email" ]
+ "summary" : "POST /api/frontend-errors",
+ "tags" : [ "/api/frontend-errors" ]
}
},
- "/api/embed/card/{token}" : {
+ "/api/geojson" : {
"get" : {
- "description" : "Fetch a Card via a JSON Web Token signed with the `embedding-secret-key`.\n\n Token should have the following format:\n\n {:resource {:question <card-id>}}",
- "operationId" : "get-api-embed-card-token",
+ "description" : "Load a custom GeoJSON file based on a URL or file path provided as a query parameter.\n This behaves similarly to /api/geojson/:key but doesn't require the custom map to be saved to the DB first.",
+ "operationId" : "get-api-geojson",
"parameters" : [ {
- "in" : "path",
- "name" : "token",
+ "in" : "query",
+ "name" : "url",
"required" : true,
"schema" : {
+ "minLength" : 1,
"type" : "string"
}
} ],
@@ -34751,36 +34338,22 @@
"description" : "Server error response"
}
},
- "summary" : "GET /api/embed/card/{token}",
- "tags" : [ "/api/embed" ]
+ "summary" : "GET /api/geojson",
+ "tags" : [ "/api/geojson" ]
}
},
- "/api/embed/card/{token}/params/{param-key}/remapping" : {
+ "/api/geojson/{key}" : {
"get" : {
- "description" : "Embedded version of api.card filter values endpoint.",
- "operationId" : "get-api-embed-card-token-params-param-key-remapping",
+ "description" : "Fetch a custom GeoJSON file as defined in the [[metabase.geojson.settings/custom-geojson]] setting. (This just acts\n as a simple proxy for the file specified for `key`).",
+ "operationId" : "get-api-geojson-key",
"parameters" : [ {
"in" : "path",
- "name" : "token",
- "required" : true,
- "schema" : {
- "type" : "string"
- }
- }, {
- "in" : "path",
- "name" : "param-key",
+ "name" : "key",
"required" : true,
"schema" : {
"minLength" : 1,
"type" : "string"
}
- }, {
- "in" : "query",
- "name" : "value",
- "required" : true,
- "schema" : {
- "type" : "string"
- }
} ],
"responses" : {
"2XX" : {
@@ -34793,38 +34366,15 @@
"description" : "Server error response"
}
},
- "summary" : "GET /api/embed/card/{token}/params/{param-key}/remapping",
- "tags" : [ "/api/embed" ]
+ "summary" : "GET /api/geojson/{key}",
+ "tags" : [ "/api/geojson" ]
}
},
- "/api/embed/card/{token}/params/{param-key}/search/{prefix}" : {
+ "/api/glossary" : {
"get" : {
- "description" : "Embedded version of chain filter search endpoint.",
- "operationId" : "get-api-embed-card-token-params-param-key-search-prefix",
- "parameters" : [ {
- "in" : "path",
- "name" : "token",
- "required" : true,
- "schema" : {
- "type" : "string"
- }
- }, {
- "in" : "path",
- "name" : "param-key",
- "required" : true,
- "schema" : {
- "minLength" : 1,
- "type" : "string"
- }
- }, {
- "in" : "path",
- "name" : "prefix",
- "required" : true,
- "schema" : {
- "minLength" : 1,
- "type" : "string"
- }
- } ],
+ "description" : "Fetch all glossary entries, optionally filtered by search term.",
+ "operationId" : "get-api-glossary",
+ "parameters" : [ ],
"responses" : {
"2XX" : {
"description" : "Successful response"
@@ -34836,30 +34386,33 @@
"description" : "Server error response"
}
},
- "summary" : "GET /api/embed/card/{token}/params/{param-key}/search/{prefix}",
- "tags" : [ "/api/embed" ]
- }
- },
- "/api/embed/card/{token}/params/{param-key}/values" : {
- "get" : {
- "description" : "Embedded version of api.card filter values endpoint.",
- "operationId" : "get-api-embed-card-token-params-param-key-values",
- "parameters" : [ {
- "in" : "path",
- "name" : "token",
- "required" : true,
- "schema" : {
- "type" : "string"
- }
- }, {
- "in" : "path",
- "name" : "param-key",
- "required" : true,
- "schema" : {
- "minLength" : 1,
- "type" : "string"
+ "summary" : "GET /api/glossary",
+ "tags" : [ "/api/glossary" ]
+ },
+ "post" : {
+ "description" : "Create a new glossary entry.",
+ "operationId" : "post-api-glossary",
+ "parameters" : [ ],
+ "requestBody" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "properties" : {
+ "definition" : {
+ "minLength" : 1,
+ "type" : "string"
+ },
+ "term" : {
+ "minLength" : 1,
+ "type" : "string"
+ }
+ },
+ "required" : [ "term", "definition" ],
+ "type" : "object"
+ }
+ }
}
- } ],
+ },
"responses" : {
"2XX" : {
"description" : "Successful response"
@@ -34871,20 +34424,22 @@
"description" : "Server error response"
}
},
- "summary" : "GET /api/embed/card/{token}/params/{param-key}/values",
- "tags" : [ "/api/embed" ]
+ "summary" : "POST /api/glossary",
+ "tags" : [ "/api/glossary" ]
}
},
- "/api/embed/card/{token}/query" : {
- "get" : {
- "description" : "Fetch the results of running a Card using a JSON Web Token signed with the `embedding-secret-key`.\n\n Token should have the following format:\n\n {:resource {:question <card-id>}\n :params <parameters>}",
- "operationId" : "get-api-embed-card-token-query",
+ "/api/glossary/{id}" : {
+ "delete" : {
+ "description" : "Delete a glossary entry.",
+ "operationId" : "delete-api-glossary-id",
"parameters" : [ {
+ "description" : "value must be an integer greater than zero.",
"in" : "path",
- "name" : "token",
+ "name" : "id",
"required" : true,
"schema" : {
- "type" : "string"
+ "minimum" : 1,
+ "type" : "integer"
}
} ],
"responses" : {
@@ -34898,45 +34453,42 @@
"description" : "Server error response"
}
},
- "summary" : "GET /api/embed/card/{token}/query",
- "tags" : [ "/api/embed" ]
- }
- },
- "/api/embed/card/{token}/query/{export-format}" : {
- "get" : {
- "description" : "Like `GET /api/embed/card/query`, but returns the results as a file in the specified format.",
- "operationId" : "get-api-embed-card-token-query-export-format",
+ "summary" : "DELETE /api/glossary/{id}",
+ "tags" : [ "/api/glossary" ]
+ },
+ "put" : {
+ "description" : "Update an existing glossary entry.",
+ "operationId" : "put-api-glossary-id",
"parameters" : [ {
+ "description" : "value must be an integer greater than zero.",
"in" : "path",
- "name" : "token",
- "required" : true,
- "schema" : {
- "type" : "string"
- }
- }, {
- "in" : "path",
- "name" : "export-format",
- "required" : true,
- "schema" : {
- "$ref" : "#/components/schemas/metabase.query-processor.schema.export-format"
- }
- }, {
- "in" : "query",
- "name" : "format_rows",
- "required" : true,
- "schema" : {
- "default" : false,
- "type" : "boolean"
- }
- }, {
- "in" : "query",
- "name" : "pivot_results",
+ "name" : "id",
"required" : true,
"schema" : {
- "default" : false,
- "type" : "boolean"
+ "minimum" : 1,
+ "type" : "integer"
}
} ],
+ "requestBody" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "properties" : {
+ "definition" : {
+ "minLength" : 1,
+ "type" : "string"
+ },
+ "term" : {
+ "minLength" : 1,
+ "type" : "string"
+ }
+ },
+ "required" : [ "term", "definition" ],
+ "type" : "object"
+ }
+ }
+ }
+ },
"responses" : {
"2XX" : {
"description" : "Successful response"
@@ -34948,22 +34500,47 @@
"description" : "Server error response"
}
},
- "summary" : "GET /api/embed/card/{token}/query/{export-format}",
- "tags" : [ "/api/embed" ]
+ "summary" : "PUT /api/glossary/{id}",
+ "tags" : [ "/api/glossary" ]
}
},
- "/api/embed/dashboard/{token}" : {
- "get" : {
- "description" : "Fetch a Dashboard via a JSON Web Token signed with the `embedding-secret-key`.\n\n Token should have the following format:\n\n {:resource {:dashboard <dashboard-id>}}",
- "operationId" : "get-api-embed-dashboard-token",
- "parameters" : [ {
- "in" : "path",
- "name" : "token",
- "required" : true,
- "schema" : {
- "type" : "string"
+ "/api/google/settings" : {
+ "put" : {
+ "description" : "Update Google Sign-In related settings. You must be a superuser to do this.",
+ "operationId" : "put-api-google-settings",
+ "parameters" : [ ],
+ "requestBody" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "properties" : {
+ "google-auth-auto-create-accounts-domain" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "google-auth-client-id" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "google-auth-enabled" : {
+ "oneOf" : [ {
+ "type" : "boolean"
+ }, {
+ "type" : "null"
+ } ]
+ }
+ },
+ "type" : "object"
+ }
+ }
}
- } ],
+ },
"responses" : {
"2XX" : {
"description" : "Successful response"
@@ -34975,40 +34552,55 @@
"description" : "Server error response"
}
},
- "summary" : "GET /api/embed/dashboard/{token}",
- "tags" : [ "/api/embed" ]
+ "summary" : "PUT /api/google/settings",
+ "tags" : [ "/api/google" ]
}
},
- "/api/embed/dashboard/{token}/dashcard/{dashcard-id}/card/{card-id}" : {
- "get" : {
- "description" : "Fetch the results of running a Card belonging to a Dashboard using a JSON Web Token signed with the\n `embedding-secret-key`",
- "operationId" : "get-api-embed-dashboard-token-dashcard-dashcard-id-card-card-id",
- "parameters" : [ {
- "in" : "path",
- "name" : "token",
- "required" : true,
- "schema" : {
- "type" : "string"
- }
- }, {
- "description" : "value must be an integer greater than zero.",
- "in" : "path",
- "name" : "dashcard-id",
- "required" : true,
- "schema" : {
- "minimum" : 1,
- "type" : "integer"
- }
- }, {
- "description" : "value must be an integer greater than zero.",
- "in" : "path",
- "name" : "card-id",
- "required" : true,
- "schema" : {
- "minimum" : 1,
- "type" : "integer"
+ "/api/ldap/settings" : {
+ "put" : {
+ "description" : "Update LDAP related settings. You must be a superuser to do this.",
+ "operationId" : "put-api-ldap-settings",
+ "parameters" : [ ],
+ "requestBody" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "properties" : {
+ "ldap-enabled" : {
+ "oneOf" : [ {
+ "type" : "boolean"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "ldap-host" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "ldap-password" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "ldap-port" : {
+ "oneOf" : [ {
+ "minimum" : 1,
+ "type" : "integer"
+ }, {
+ "type" : "null"
+ } ]
+ }
+ },
+ "type" : "object"
+ }
+ }
}
- } ],
+ },
"responses" : {
"2XX" : {
"description" : "Successful response"
@@ -35020,65 +34612,155 @@
"description" : "Server error response"
}
},
- "summary" : "GET /api/embed/dashboard/{token}/dashcard/{dashcard-id}/card/{card-id}",
- "tags" : [ "/api/embed" ]
+ "summary" : "PUT /api/ldap/settings",
+ "tags" : [ "/api/ldap" ]
}
},
- "/api/embed/dashboard/{token}/dashcard/{dashcard-id}/card/{card-id}/{export-format}" : {
- "get" : {
- "description" : "Fetch the results of running a Card belonging to a Dashboard using a JSON Web Token signed with the\n `embedding-secret-key` return the data in one of the export formats",
- "operationId" : "get-api-embed-dashboard-token-dashcard-dashcard-id-card-card-id-export-format",
- "parameters" : [ {
- "in" : "path",
- "name" : "token",
- "required" : true,
- "schema" : {
- "type" : "string"
- }
- }, {
- "description" : "value must be an integer greater than zero.",
- "in" : "path",
- "name" : "dashcard-id",
- "required" : true,
- "schema" : {
- "minimum" : 1,
- "type" : "integer"
- }
- }, {
- "description" : "value must be an integer greater than zero.",
- "in" : "path",
- "name" : "card-id",
- "required" : true,
- "schema" : {
- "minimum" : 1,
- "type" : "integer"
- }
- }, {
- "in" : "path",
- "name" : "export-format",
- "required" : true,
- "schema" : {
- "$ref" : "#/components/schemas/metabase.query-processor.schema.export-format"
- }
- }, {
- "in" : "query",
- "name" : "format_rows",
- "required" : true,
- "schema" : {
- "default" : false,
- "type" : "boolean"
- }
- }, {
- "in" : "query",
- "name" : "pivot_results",
- "required" : true,
- "schema" : {
- "default" : false,
- "type" : "boolean"
+ "/api/llm/extract-sources" : {
+ "post" : {
+ "description" : "Parse native query sources and return referenced tables and cards/models.\n\n Uses Macaw to parse the SQL, resolves table names to IDs,\n and returns permission-filtered tables with column metadata. Card and model\n references are extracted from native query template tags.\n\n This is a lightweight endpoint that does not trigger fingerprinting\n or field value fetching.",
+ "operationId" : "post-api-llm-extract-sources",
+ "parameters" : [ ],
+ "requestBody" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "properties" : {
+ "database_id" : {
+ "minimum" : 1,
+ "type" : "integer"
+ },
+ "sql" : {
+ "type" : "string"
+ },
+ "template_tags" : {
+ "additionalProperties" : {
+ "properties" : {
+ "card-id" : {
+ "minimum" : 1,
+ "type" : "integer"
+ },
+ "type" : {
+ "type" : "string"
+ }
+ },
+ "required" : [ "type" ],
+ "type" : "object"
+ },
+ "type" : "object"
+ }
+ },
+ "required" : [ "database_id", "sql" ],
+ "type" : "object"
+ }
+ }
}
- } ],
+ },
"responses" : {
"2XX" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "properties" : {
+ "card_ids" : {
+ "items" : {
+ "minimum" : 1,
+ "type" : "integer"
+ },
+ "type" : "array"
+ },
+ "tables" : {
+ "items" : {
+ "properties" : {
+ "columns" : {
+ "items" : {
+ "properties" : {
+ "database_type" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "description" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "fk_target" : {
+ "properties" : {
+ "field_name" : {
+ "type" : "string"
+ },
+ "table_name" : {
+ "type" : "string"
+ }
+ },
+ "required" : [ "table_name", "field_name" ],
+ "type" : "object"
+ },
+ "id" : {
+ "minimum" : 1,
+ "type" : "integer"
+ },
+ "name" : {
+ "type" : "string"
+ },
+ "semantic_type" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ }
+ },
+ "required" : [ "id", "name" ],
+ "type" : "object"
+ },
+ "type" : "array"
+ },
+ "description" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "display_name" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "id" : {
+ "minimum" : 1,
+ "type" : "integer"
+ },
+ "name" : {
+ "type" : "string"
+ },
+ "schema" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ }
+ },
+ "required" : [ "id", "name", "columns" ],
+ "type" : "object"
+ },
+ "type" : "array"
+ }
+ },
+ "required" : [ "tables", "card_ids" ],
+ "type" : "object"
+ }
+ }
+ },
"description" : "Successful response"
},
"4XX" : {
@@ -35088,32 +34770,157 @@
"description" : "Server error response"
}
},
- "summary" : "GET /api/embed/dashboard/{token}/dashcard/{dashcard-id}/card/{card-id}/{export-format}",
- "tags" : [ "/api/embed" ]
+ "summary" : "POST /api/llm/extract-sources",
+ "tags" : [ "/api/llm" ]
}
},
- "/api/embed/dashboard/{token}/params/{param-key}/remapping" : {
- "get" : {
- "description" : "Embedded version of the remapped dashboard param value endpoint.",
- "operationId" : "get-api-embed-dashboard-token-params-param-key-remapping",
- "parameters" : [ {
- "in" : "path",
- "name" : "token",
- "required" : true,
- "schema" : {
- "type" : "string"
- }
- }, {
- "in" : "path",
- "name" : "param-key",
- "required" : true,
- "schema" : {
- "minLength" : 1,
- "type" : "string"
+ "/api/llm/generate-sql" : {
+ "post" : {
+ "description" : "Generate SQL from a natural language prompt.\n\n Requires:\n - LLM to be configured (Anthropic API key set in admin settings)\n - At least one table reference (explicit @mention or implicit from source_sql)\n - A database_id parameter\n\n Returns generated SQL and the list of tables used for context.",
+ "operationId" : "post-api-llm-generate-sql",
+ "parameters" : [ ],
+ "requestBody" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "properties" : {
+ "database_id" : {
+ "minimum" : 1,
+ "type" : "integer"
+ },
+ "prompt" : {
+ "type" : "string"
+ },
+ "referenced_entities" : {
+ "items" : {
+ "properties" : {
+ "id" : {
+ "minimum" : 1,
+ "type" : "integer"
+ },
+ "model" : {
+ "type" : "string"
+ }
+ },
+ "required" : [ "model", "id" ],
+ "type" : "object"
+ },
+ "type" : "array"
+ },
+ "source_sql" : {
+ "type" : "string"
+ }
+ },
+ "required" : [ "prompt", "database_id" ],
+ "type" : "object"
+ }
+ }
}
- } ],
+ },
"responses" : {
"2XX" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "properties" : {
+ "referenced_entities" : {
+ "items" : {
+ "properties" : {
+ "columns" : {
+ "items" : {
+ "properties" : {
+ "database_type" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "description" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "fk_target" : {
+ "properties" : {
+ "field_name" : {
+ "type" : "string"
+ },
+ "table_name" : {
+ "type" : "string"
+ }
+ },
+ "required" : [ "table_name", "field_name" ],
+ "type" : "object"
+ },
+ "id" : {
+ "minimum" : 1,
+ "type" : "integer"
+ },
+ "name" : {
+ "type" : "string"
+ },
+ "semantic_type" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ }
+ },
+ "required" : [ "id", "name" ],
+ "type" : "object"
+ },
+ "type" : "array"
+ },
+ "description" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "display_name" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "id" : {
+ "minimum" : 1,
+ "type" : "integer"
+ },
+ "model" : {
+ "type" : "string"
+ },
+ "name" : {
+ "type" : "string"
+ },
+ "schema" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ }
+ },
+ "required" : [ "model", "id", "name", "columns" ],
+ "type" : "object"
+ },
+ "type" : "array"
+ },
+ "sql" : {
+ "type" : "string"
+ }
+ },
+ "required" : [ "sql", "referenced_entities" ],
+ "type" : "object"
+ }
+ }
+ },
"description" : "Successful response"
},
"4XX" : {
@@ -35123,40 +34930,42 @@
"description" : "Server error response"
}
},
- "summary" : "GET /api/embed/dashboard/{token}/params/{param-key}/remapping",
- "tags" : [ "/api/embed" ]
+ "summary" : "POST /api/llm/generate-sql",
+ "tags" : [ "/api/llm" ]
}
},
- "/api/embed/dashboard/{token}/params/{param-key}/search/{prefix}" : {
+ "/api/llm/list-models" : {
"get" : {
- "description" : "Embedded version of chain filter search endpoint.",
- "operationId" : "get-api-embed-dashboard-token-params-param-key-search-prefix",
- "parameters" : [ {
- "in" : "path",
- "name" : "token",
- "required" : true,
- "schema" : {
- "type" : "string"
- }
- }, {
- "in" : "path",
- "name" : "param-key",
- "required" : true,
- "schema" : {
- "minLength" : 1,
- "type" : "string"
- }
- }, {
- "in" : "path",
- "name" : "prefix",
- "required" : true,
- "schema" : {
- "minLength" : 1,
- "type" : "string"
- }
- } ],
+ "description" : "List available LLM models from the configured provider.\n\n Requires LLM to be configured for the selected provider in admin settings.",
+ "operationId" : "get-api-llm-list-models",
+ "parameters" : [ ],
"responses" : {
"2XX" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "properties" : {
+ "models" : {
+ "items" : {
+ "properties" : {
+ "display_name" : {
+ "type" : "string"
+ },
+ "id" : {
+ "type" : "string"
+ }
+ },
+ "required" : [ "id", "display_name" ],
+ "type" : "object"
+ },
+ "type" : "array"
+ }
+ },
+ "required" : [ "models" ],
+ "type" : "object"
+ }
+ }
+ },
"description" : "Successful response"
},
"4XX" : {
@@ -35166,30 +34975,15 @@
"description" : "Server error response"
}
},
- "summary" : "GET /api/embed/dashboard/{token}/params/{param-key}/search/{prefix}",
- "tags" : [ "/api/embed" ]
+ "summary" : "GET /api/llm/list-models",
+ "tags" : [ "/api/llm" ]
}
},
- "/api/embed/dashboard/{token}/params/{param-key}/values" : {
- "get" : {
- "description" : "Embedded version of chain filter values endpoint.",
- "operationId" : "get-api-embed-dashboard-token-params-param-key-values",
- "parameters" : [ {
- "in" : "path",
- "name" : "token",
- "required" : true,
- "schema" : {
- "type" : "string"
- }
- }, {
- "in" : "path",
- "name" : "param-key",
- "required" : true,
- "schema" : {
- "minLength" : 1,
- "type" : "string"
- }
- } ],
+ "/api/logger/adjustment" : {
+ "delete" : {
+ "description" : "Undo any log level adjustments.",
+ "operationId" : "delete-api-logger-adjustment",
+ "parameters" : [ ],
"responses" : {
"2XX" : {
"description" : "Successful response"
@@ -35201,22 +34995,32 @@
"description" : "Server error response"
}
},
- "summary" : "GET /api/embed/dashboard/{token}/params/{param-key}/values",
- "tags" : [ "/api/embed" ]
- }
- },
- "/api/embed/pivot/card/{token}/query" : {
- "get" : {
- "description" : "Fetch the results of running a Card using a JSON Web Token signed with the `embedding-secret-key`.\n\n Token should have the following format:\n\n {:resource {:question <card-id>}\n :params <parameters>}",
- "operationId" : "get-api-embed-pivot-card-token-query",
- "parameters" : [ {
- "in" : "path",
- "name" : "token",
- "required" : true,
- "schema" : {
- "type" : "string"
+ "summary" : "DELETE /api/logger/adjustment",
+ "tags" : [ "/api/logger" ]
+ },
+ "post" : {
+ "description" : "Temporarily adjust the log levels.",
+ "operationId" : "post-api-logger-adjustment",
+ "parameters" : [ ],
+ "requestBody" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "properties" : {
+ "duration" : {
+ "type" : "integer"
+ },
+ "duration_unit" : {
+ "$ref" : "#/components/schemas/metabase.logger.api.time-unit"
+ },
+ "log_levels" : { }
+ },
+ "required" : [ "duration", "duration_unit", "log_levels" ],
+ "type" : "object"
+ }
+ }
}
- } ],
+ },
"responses" : {
"2XX" : {
"description" : "Successful response"
@@ -35228,40 +35032,15 @@
"description" : "Server error response"
}
},
- "summary" : "GET /api/embed/pivot/card/{token}/query",
- "tags" : [ "/api/embed" ]
+ "summary" : "POST /api/logger/adjustment",
+ "tags" : [ "/api/logger" ]
}
},
- "/api/embed/pivot/dashboard/{token}/dashcard/{dashcard-id}/card/{card-id}" : {
+ "/api/logger/logs" : {
"get" : {
- "description" : "Fetch the results of running a Card belonging to a Dashboard using a JSON Web Token signed with the\n `embedding-secret-key`",
- "operationId" : "get-api-embed-pivot-dashboard-token-dashcard-dashcard-id-card-card-id",
- "parameters" : [ {
- "in" : "path",
- "name" : "token",
- "required" : true,
- "schema" : {
- "type" : "string"
- }
- }, {
- "description" : "value must be an integer greater than zero.",
- "in" : "path",
- "name" : "dashcard-id",
- "required" : true,
- "schema" : {
- "minimum" : 1,
- "type" : "integer"
- }
- }, {
- "description" : "value must be an integer greater than zero.",
- "in" : "path",
- "name" : "card-id",
- "required" : true,
- "schema" : {
- "minimum" : 1,
- "type" : "integer"
- }
- } ],
+ "description" : "Logs.",
+ "operationId" : "get-api-logger-logs",
+ "parameters" : [ ],
"responses" : {
"2XX" : {
"description" : "Successful response"
@@ -35273,70 +35052,51 @@
"description" : "Server error response"
}
},
- "summary" : "GET /api/embed/pivot/dashboard/{token}/dashcard/{dashcard-id}/card/{card-id}",
- "tags" : [ "/api/embed" ]
+ "summary" : "GET /api/logger/logs",
+ "tags" : [ "/api/logger" ]
}
},
- "/api/embed/tiles/card/{token}/{zoom}/{x}/{y}" : {
+ "/api/logger/presets" : {
"get" : {
- "description" : "Generates a single tile image for an embedded Card using the map visualization.",
- "operationId" : "get-api-embed-tiles-card-token-zoom-x-y",
- "parameters" : [ {
- "in" : "path",
- "name" : "token",
- "required" : true,
- "schema" : {
- "type" : "string"
- }
- }, {
- "description" : "value must be an integer.",
- "in" : "path",
- "name" : "zoom",
- "required" : true,
- "schema" : {
- "type" : "integer"
- }
- }, {
- "description" : "value must be an integer.",
- "in" : "path",
- "name" : "x",
- "required" : true,
- "schema" : {
- "type" : "integer"
- }
- }, {
- "description" : "value must be an integer.",
- "in" : "path",
- "name" : "y",
- "required" : true,
- "schema" : {
- "type" : "integer"
- }
- }, {
- "description" : "value must be a valid JSON string.",
- "in" : "query",
- "name" : "parameters",
- "required" : false,
- "schema" : {
- "type" : "string"
- }
- }, {
- "in" : "query",
- "name" : "latField",
- "required" : true,
- "schema" : {
- "type" : "string"
- }
- }, {
- "in" : "query",
- "name" : "lonField",
- "required" : true,
- "schema" : {
- "type" : "string"
- }
- } ],
+ "description" : "Get all known presets.",
+ "operationId" : "get-api-logger-presets",
+ "parameters" : [ ],
"responses" : {
"2XX" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "items" : {
+ "properties" : {
+ "display_name" : {
+ "type" : "string"
+ },
+ "id" : {
+ "type" : "string"
+ },
+ "loggers" : {
+ "items" : {
+ "properties" : {
+ "level" : {
+ "$ref" : "#/components/schemas/metabase.logger.api.log-level"
+ },
+ "name" : {
+ "type" : "string"
+ }
+ },
+ "required" : [ "name", "level" ],
+ "type" : "object"
+ },
+ "type" : "array"
+ }
+ },
+ "required" : [ "id", "display_name", "loggers" ],
+ "type" : "object"
+ },
+ "type" : "array"
+ }
+ }
+ },
"description" : "Successful response"
},
"4XX" : {
@@ -35346,86 +35106,15 @@
"description" : "Server error response"
}
},
- "summary" : "GET /api/embed/tiles/card/{token}/{zoom}/{x}/{y}",
- "tags" : [ "/api/embed" ]
+ "summary" : "GET /api/logger/presets",
+ "tags" : [ "/api/logger" ]
}
},
- "/api/embed/tiles/dashboard/{token}/dashcard/{dashcard-id}/card/{card-id}/{zoom}/{x}/{y}" : {
+ "/api/login-history/current" : {
"get" : {
- "description" : "Generates a single tile image for a Card on an embedded Dashboard using the map visualization.",
- "operationId" : "get-api-embed-tiles-dashboard-token-dashcard-dashcard-id-card-card-id-zoom-x-y",
- "parameters" : [ {
- "in" : "path",
- "name" : "token",
- "required" : true,
- "schema" : {
- "type" : "string"
- }
- }, {
- "description" : "value must be an integer greater than zero.",
- "in" : "path",
- "name" : "dashcard-id",
- "required" : true,
- "schema" : {
- "minimum" : 1,
- "type" : "integer"
- }
- }, {
- "description" : "value must be an integer greater than zero.",
- "in" : "path",
- "name" : "card-id",
- "required" : true,
- "schema" : {
- "minimum" : 1,
- "type" : "integer"
- }
- }, {
- "description" : "value must be an integer.",
- "in" : "path",
- "name" : "zoom",
- "required" : true,
- "schema" : {
- "type" : "integer"
- }
- }, {
- "description" : "value must be an integer.",
- "in" : "path",
- "name" : "x",
- "required" : true,
- "schema" : {
- "type" : "integer"
- }
- }, {
- "description" : "value must be an integer.",
- "in" : "path",
- "name" : "y",
- "required" : true,
- "schema" : {
- "type" : "integer"
- }
- }, {
- "description" : "value must be a valid JSON string.",
- "in" : "query",
- "name" : "parameters",
- "required" : false,
- "schema" : {
- "type" : "string"
- }
- }, {
- "in" : "query",
- "name" : "latField",
- "required" : true,
- "schema" : {
- "type" : "string"
- }
- }, {
- "in" : "query",
- "name" : "lonField",
- "required" : true,
- "schema" : {
- "type" : "string"
- }
- } ],
+ "description" : "Fetch recent logins for the current user.",
+ "operationId" : "get-api-login-history-current",
+ "parameters" : [ ],
"responses" : {
"2XX" : {
"description" : "Successful response"
@@ -35437,34 +35126,27 @@
"description" : "Server error response"
}
},
- "summary" : "GET /api/embed/tiles/dashboard/{token}/dashcard/{dashcard-id}/card/{card-id}/{zoom}/{x}/{y}",
- "tags" : [ "/api/embed" ]
+ "summary" : "GET /api/login-history/current",
+ "tags" : [ "/api/login-history" ]
}
},
- "/api/field/{id}" : {
+ "/api/measure" : {
"get" : {
- "description" : "Get `Field` with ID.",
- "operationId" : "get-api-field-id",
- "parameters" : [ {
- "description" : "value must be an integer greater than zero.",
- "in" : "path",
- "name" : "id",
- "required" : true,
- "schema" : {
- "minimum" : 1,
- "type" : "integer"
- }
- }, {
- "in" : "query",
- "name" : "include_editable_data_model",
- "required" : true,
- "schema" : {
- "default" : false,
- "type" : "boolean"
- }
- } ],
+ "description" : "Fetch *all* `Measures`.",
+ "operationId" : "get-api-measure",
+ "parameters" : [ ],
"responses" : {
"2XX" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "items" : {
+ "$ref" : "#/components/schemas/metabase.measures.api.measure"
+ },
+ "type" : "array"
+ }
+ }
+ },
"description" : "Successful response"
},
"4XX" : {
@@ -35474,125 +35156,41 @@
"description" : "Server error response"
}
},
- "summary" : "GET /api/field/{id}",
- "tags" : [ "/api/field" ]
+ "summary" : "GET /api/measure",
+ "tags" : [ "/api/measure" ]
},
- "put" : {
- "description" : "Update `Field` with ID.",
- "operationId" : "put-api-field-id",
- "parameters" : [ {
- "description" : "value must be an integer greater than zero.",
- "in" : "path",
- "name" : "id",
- "required" : true,
- "schema" : {
- "minimum" : 1,
- "type" : "integer"
- }
- } ],
+ "post" : {
+ "description" : "Create a new `Measure`.",
+ "operationId" : "post-api-measure",
+ "parameters" : [ ],
"requestBody" : {
"content" : {
"application/json" : {
"schema" : {
"properties" : {
- "caveats" : {
- "oneOf" : [ {
- "minLength" : 1,
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "coercion_strategy" : {
- "oneOf" : [ {
- "description" : "value must be a valid coercion strategy (keyword or string)."
- }, {
- "type" : "null"
- } ]
+ "definition" : {
+ "description" : "Value must be a map.",
+ "properties" : { },
+ "type" : "object"
},
"description" : {
"oneOf" : [ {
- "minLength" : 1,
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "display_name" : {
- "oneOf" : [ {
- "minLength" : 1,
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "fk_target_field_id" : {
- "oneOf" : [ {
- "description" : "value must be an integer greater than zero.",
- "minimum" : 1,
- "type" : "integer"
- }, {
- "type" : "null"
- } ]
- },
- "has_field_values" : {
- "oneOf" : [ {
- "$ref" : "#/components/schemas/metabase.lib.schema.metadata..column.has-field-values"
- }, {
- "type" : "null"
- } ]
- },
- "json_unfolding" : {
- "oneOf" : [ {
- "type" : "boolean"
- }, {
- "type" : "null"
- } ]
- },
- "nfc_path" : {
- "oneOf" : [ {
- "items" : {
- "minLength" : 1,
- "type" : "string"
- },
- "type" : "array"
- }, {
- "type" : "null"
- } ]
- },
- "points_of_interest" : {
- "oneOf" : [ {
- "minLength" : 1,
"type" : "string"
}, {
"type" : "null"
} ]
},
- "semantic_type" : {
- "oneOf" : [ {
- "description" : "value must be a valid field semantic or relation type (keyword or string)."
- }, {
- "type" : "null"
- } ]
- },
- "settings" : {
- "oneOf" : [ {
- "description" : "Value must be a map.",
- "properties" : { },
- "type" : "object"
- }, {
- "type" : "null"
- } ]
+ "name" : {
+ "minLength" : 1,
+ "type" : "string"
},
- "visibility_type" : {
- "oneOf" : [ {
- "enum" : [ "retired", "sensitive", "normal", "hidden", "details-only" ],
- "type" : "string"
- }, {
- "type" : "null"
- } ]
+ "table_id" : {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
}
},
+ "required" : [ "name", "table_id", "definition" ],
"type" : "object"
}
}
@@ -35600,6 +35198,13 @@
},
"responses" : {
"2XX" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "$ref" : "#/components/schemas/metabase.measures.api.measure"
+ }
+ }
+ },
"description" : "Successful response"
},
"4XX" : {
@@ -35609,14 +35214,14 @@
"description" : "Server error response"
}
},
- "summary" : "PUT /api/field/{id}",
- "tags" : [ "/api/field" ]
+ "summary" : "POST /api/measure",
+ "tags" : [ "/api/measure" ]
}
},
- "/api/field/{id}/dimension" : {
- "delete" : {
- "description" : "Remove the dimension associated to field at ID",
- "operationId" : "delete-api-field-id-dimension",
+ "/api/measure/{id}" : {
+ "get" : {
+ "description" : "Fetch `Measure` with ID.",
+ "operationId" : "get-api-measure-id",
"parameters" : [ {
"description" : "value must be an integer greater than zero.",
"in" : "path",
@@ -35629,6 +35234,13 @@
} ],
"responses" : {
"2XX" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "$ref" : "#/components/schemas/metabase.measures.api.measure"
+ }
+ }
+ },
"description" : "Successful response"
},
"4XX" : {
@@ -35638,12 +35250,12 @@
"description" : "Server error response"
}
},
- "summary" : "DELETE /api/field/{id}/dimension",
- "tags" : [ "/api/field" ]
+ "summary" : "GET /api/measure/{id}",
+ "tags" : [ "/api/measure" ]
},
- "post" : {
- "description" : "Sets the dimension for the given field at ID",
- "operationId" : "post-api-field-id-dimension",
+ "put" : {
+ "description" : "Update a `Measure` with ID.",
+ "operationId" : "put-api-measure-id",
"parameters" : [ {
"description" : "value must be an integer greater than zero.",
"in" : "path",
@@ -35659,25 +35271,42 @@
"application/json" : {
"schema" : {
"properties" : {
- "human_readable_field_id" : {
+ "archived" : {
"oneOf" : [ {
- "description" : "value must be an integer greater than zero.",
- "minimum" : 1,
- "type" : "integer"
+ "type" : "boolean"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "definition" : {
+ "oneOf" : [ {
+ "properties" : { },
+ "type" : "object"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "description" : {
+ "oneOf" : [ {
+ "type" : "string"
}, {
"type" : "null"
} ]
},
"name" : {
- "minLength" : 1,
- "type" : "string"
+ "oneOf" : [ {
+ "minLength" : 1,
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
},
- "type" : {
- "enum" : [ "internal", "external" ],
+ "revision_message" : {
+ "minLength" : 1,
"type" : "string"
}
},
- "required" : [ "type", "name" ],
+ "required" : [ "revision_message" ],
"type" : "object"
}
}
@@ -35685,6 +35314,13 @@
},
"responses" : {
"2XX" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "$ref" : "#/components/schemas/metabase.measures.api.measure"
+ }
+ }
+ },
"description" : "Successful response"
},
"4XX" : {
@@ -35694,14 +35330,14 @@
"description" : "Server error response"
}
},
- "summary" : "POST /api/field/{id}/dimension",
- "tags" : [ "/api/field" ]
+ "summary" : "PUT /api/measure/{id}",
+ "tags" : [ "/api/measure" ]
}
},
- "/api/field/{id}/discard_values" : {
- "post" : {
- "description" : "Discard the FieldValues belonging to this Field. Only applies to fields that have FieldValues. If this Field's\n Database is set up to automatically sync FieldValues, they will be recreated during the next cycle.",
- "operationId" : "post-api-field-id-discard_values",
+ "/api/measure/{id}/dimension/{dimension-key}/remapping" : {
+ "get" : {
+ "description" : "Fetch remapped value for a specific dimension value.\n\n Returns a pair [value, display-name] if remapping exists, or [value] otherwise.",
+ "operationId" : "get-api-measure-id-dimension-dimension-key-remapping",
"parameters" : [ {
"description" : "value must be an integer greater than zero.",
"in" : "path",
@@ -35711,9 +35347,32 @@
"minimum" : 1,
"type" : "integer"
}
+ }, {
+ "description" : "value must be a valid UUID.",
+ "in" : "path",
+ "name" : "dimension-key",
+ "required" : true,
+ "schema" : {
+ "pattern" : "[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",
+ "type" : "string"
+ }
+ }, {
+ "in" : "query",
+ "name" : "value",
+ "required" : true,
+ "schema" : {
+ "type" : "string"
+ }
} ],
"responses" : {
"2XX" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "$ref" : "#/components/schemas/metabase.measures.api.RemappedValueResponse"
+ }
+ }
+ },
"description" : "Successful response"
},
"4XX" : {
@@ -35723,14 +35382,14 @@
"description" : "Server error response"
}
},
- "summary" : "POST /api/field/{id}/discard_values",
- "tags" : [ "/api/field" ]
+ "summary" : "GET /api/measure/{id}/dimension/{dimension-key}/remapping",
+ "tags" : [ "/api/measure" ]
}
},
- "/api/field/{id}/related" : {
+ "/api/measure/{id}/dimension/{dimension-key}/search" : {
"get" : {
- "description" : "Return related entities.",
- "operationId" : "get-api-field-id-related",
+ "description" : "Search for values of a dimension that contain the query string.\n\n Returns field values matching the search query in the same format as the field values API.",
+ "operationId" : "get-api-measure-id-dimension-dimension-key-search",
"parameters" : [ {
"description" : "value must be an integer greater than zero.",
"in" : "path",
@@ -35740,9 +35399,39 @@
"minimum" : 1,
"type" : "integer"
}
+ }, {
+ "description" : "value must be a valid UUID.",
+ "in" : "path",
+ "name" : "dimension-key",
+ "required" : true,
+ "schema" : {
+ "pattern" : "[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",
+ "type" : "string"
+ }
+ }, {
+ "in" : "query",
+ "name" : "query",
+ "required" : true,
+ "schema" : {
+ "minLength" : 1,
+ "type" : "string"
+ }
} ],
"responses" : {
"2XX" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "items" : {
+ "items" : {
+ "type" : "string"
+ },
+ "type" : "array"
+ },
+ "type" : "array"
+ }
+ }
+ },
"description" : "Successful response"
},
"4XX" : {
@@ -35752,14 +35441,14 @@
"description" : "Server error response"
}
},
- "summary" : "GET /api/field/{id}/related",
- "tags" : [ "/api/field" ]
+ "summary" : "GET /api/measure/{id}/dimension/{dimension-key}/search",
+ "tags" : [ "/api/measure" ]
}
},
- "/api/field/{id}/remapping/{remapped-id}" : {
+ "/api/measure/{id}/dimension/{dimension-key}/values" : {
"get" : {
- "description" : "Fetch remapped Field values.",
- "operationId" : "get-api-field-id-remapping-remapped-id",
+ "description" : "Fetch values for a dimension of a measure.\n\n Returns field values in the same format as the field values API:\n - values: list of [value] or [value, display-name] tuples\n - field_id: the underlying field ID\n - has_more_values: boolean indicating if there are more values",
+ "operationId" : "get-api-measure-id-dimension-dimension-key-values",
"parameters" : [ {
"description" : "value must be an integer greater than zero.",
"in" : "path",
@@ -35770,25 +35459,44 @@
"type" : "integer"
}
}, {
- "description" : "value must be an integer greater than zero.",
+ "description" : "value must be a valid UUID.",
"in" : "path",
- "name" : "remapped-id",
- "required" : true,
- "schema" : {
- "minimum" : 1,
- "type" : "integer"
- }
- }, {
- "in" : "query",
- "name" : "value",
+ "name" : "dimension-key",
"required" : true,
"schema" : {
- "minLength" : 1,
+ "pattern" : "[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",
"type" : "string"
}
} ],
"responses" : {
"2XX" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "properties" : {
+ "has_more_values" : {
+ "type" : "boolean"
+ },
+ "values" : {
+ "items" : {
+ "anyOf" : [ {
+ "prefixItems" : [ { }, {
+ "type" : "string"
+ } ],
+ "type" : "array"
+ }, {
+ "prefixItems" : [ { } ],
+ "type" : "array"
+ } ]
+ },
+ "type" : "array"
+ }
+ },
+ "required" : [ "has_more_values", "values" ],
+ "type" : "object"
+ }
+ }
+ },
"description" : "Successful response"
},
"4XX" : {
@@ -35798,24 +35506,76 @@
"description" : "Server error response"
}
},
- "summary" : "GET /api/field/{id}/remapping/{remapped-id}",
- "tags" : [ "/api/field" ]
+ "summary" : "GET /api/measure/{id}/dimension/{dimension-key}/values",
+ "tags" : [ "/api/measure" ]
}
},
- "/api/field/{id}/rescan_values" : {
+ "/api/metabot/agent-streaming" : {
"post" : {
- "description" : "Manually trigger an update for the FieldValues for this Field. Only applies to Fields that are eligible for\n FieldValues.",
- "operationId" : "post-api-field-id-rescan_values",
- "parameters" : [ {
- "description" : "value must be an integer greater than zero.",
- "in" : "path",
- "name" : "id",
- "required" : true,
- "schema" : {
- "minimum" : 1,
- "type" : "integer"
+ "description" : "Send a chat message to the LLM via the AI Proxy.",
+ "operationId" : "post-api-metabot-agent-streaming",
+ "parameters" : [ ],
+ "requestBody" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "properties" : {
+ "context" : {
+ "$ref" : "#/components/schemas/metabase.metabot.context.context"
+ },
+ "conversation_id" : {
+ "description" : "value must be a valid UUID.",
+ "pattern" : "[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",
+ "type" : "string"
+ },
+ "debug" : {
+ "oneOf" : [ {
+ "type" : "boolean"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "history" : {
+ "oneOf" : [ {
+ "$ref" : "#/components/schemas/metabase.metabot.schema.messages"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "message" : {
+ "minLength" : 1,
+ "type" : "string"
+ },
+ "metabot_id" : {
+ "type" : "string"
+ },
+ "profile_id" : {
+ "type" : "string"
+ },
+ "state" : {
+ "properties" : {
+ "chart-configs" : {
+ "additionalProperties" : { },
+ "type" : "object"
+ },
+ "charts" : {
+ "additionalProperties" : { },
+ "type" : "object"
+ },
+ "queries" : {
+ "additionalProperties" : { },
+ "type" : "object"
+ }
+ },
+ "type" : "object"
+ }
+ },
+ "required" : [ "message", "context", "conversation_id", "history", "state" ],
+ "type" : "object"
+ }
+ }
}
- } ],
+ },
"responses" : {
"2XX" : {
"description" : "Successful response"
@@ -35827,43 +35587,89 @@
"description" : "Server error response"
}
},
- "summary" : "POST /api/field/{id}/rescan_values",
- "tags" : [ "/api/field" ]
+ "summary" : "POST /api/metabot/agent-streaming",
+ "tags" : [ "/api/metabot" ]
}
},
- "/api/field/{id}/search/{search-id}" : {
+ "/api/metabot/conversations" : {
"get" : {
- "description" : "Search for values of a Field with `search-id` that start with `value`. See docstring for\n [[metabase.parameters.field/search-values]] for a more detailed explanation.",
- "operationId" : "get-api-field-id-search-search-id",
- "parameters" : [ {
- "description" : "value must be an integer greater than zero.",
- "in" : "path",
- "name" : "id",
- "required" : true,
- "schema" : {
- "minimum" : 1,
- "type" : "integer"
- }
- }, {
- "description" : "value must be an integer greater than zero.",
- "in" : "path",
- "name" : "search-id",
- "required" : true,
- "schema" : {
- "minimum" : 1,
- "type" : "integer"
- }
- }, {
- "in" : "query",
- "name" : "value",
- "required" : false,
- "schema" : {
- "minLength" : 1,
- "type" : "string"
- }
- } ],
+ "description" : "List conversations visible in the current user's history, most-recent first.\n\n New conversations are participation-based (the user authored at least one\n message); legacy conversations created before message authors were stamped\n fall back to the conversation originator.",
+ "operationId" : "get-api-metabot-conversations",
+ "parameters" : [ ],
"responses" : {
"2XX" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "properties" : {
+ "data" : {
+ "items" : {
+ "properties" : {
+ "conversation_id" : {
+ "description" : "value must be a valid UUID.",
+ "pattern" : "[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",
+ "type" : "string"
+ },
+ "created_at" : {
+ "format" : "date-time",
+ "type" : "string"
+ },
+ "last_message_at" : {
+ "oneOf" : [ {
+ "format" : "date-time",
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "message_count" : {
+ "description" : "value must be an integer greater or equal to than zero.",
+ "minimum" : 0,
+ "type" : "integer"
+ },
+ "summary" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "user_id" : {
+ "oneOf" : [ {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
+ }, {
+ "type" : "null"
+ } ]
+ }
+ },
+ "required" : [ "conversation_id", "created_at", "summary", "user_id", "message_count", "last_message_at" ],
+ "type" : "object"
+ },
+ "type" : "array"
+ },
+ "limit" : {
+ "description" : "value must be an integer greater or equal to than zero.",
+ "minimum" : 0,
+ "type" : "integer"
+ },
+ "offset" : {
+ "description" : "value must be an integer greater or equal to than zero.",
+ "minimum" : 0,
+ "type" : "integer"
+ },
+ "total" : {
+ "description" : "value must be an integer greater or equal to than zero.",
+ "minimum" : 0,
+ "type" : "integer"
+ }
+ },
+ "required" : [ "data", "total", "limit", "offset" ],
+ "type" : "object"
+ }
+ }
+ },
"description" : "Successful response"
},
"4XX" : {
@@ -35873,26 +35679,68 @@
"description" : "Server error response"
}
},
- "summary" : "GET /api/field/{id}/search/{search-id}",
- "tags" : [ "/api/field" ]
+ "summary" : "GET /api/metabot/conversations",
+ "tags" : [ "/api/metabot/conversations" ]
}
},
- "/api/field/{id}/summary" : {
+ "/api/metabot/conversations/{id}" : {
"get" : {
- "description" : "Get the count and distinct count of `Field` with ID.",
- "operationId" : "get-api-field-id-summary",
+ "description" : "Return a single conversation with its flattened chat messages.\n\n Accessible to any participant in the conversation or to any superuser.",
+ "operationId" : "get-api-metabot-conversations-id",
"parameters" : [ {
- "description" : "value must be an integer greater than zero.",
+ "description" : "value must be a valid UUID.",
"in" : "path",
"name" : "id",
"required" : true,
"schema" : {
- "minimum" : 1,
- "type" : "integer"
+ "pattern" : "[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",
+ "type" : "string"
}
} ],
"responses" : {
"2XX" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "properties" : {
+ "chat_messages" : {
+ "items" : {
+ "properties" : { },
+ "type" : "object"
+ },
+ "type" : "array"
+ },
+ "conversation_id" : {
+ "description" : "value must be a valid UUID.",
+ "pattern" : "[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",
+ "type" : "string"
+ },
+ "created_at" : {
+ "format" : "date-time",
+ "type" : "string"
+ },
+ "summary" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "user_id" : {
+ "oneOf" : [ {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
+ }, {
+ "type" : "null"
+ } ]
+ }
+ },
+ "required" : [ "conversation_id", "created_at", "summary", "user_id", "chat_messages" ],
+ "type" : "object"
+ }
+ }
+ },
"description" : "Successful response"
},
"4XX" : {
@@ -35902,26 +35750,105 @@
"description" : "Server error response"
}
},
- "summary" : "GET /api/field/{id}/summary",
- "tags" : [ "/api/field" ]
+ "summary" : "GET /api/metabot/conversations/{id}",
+ "tags" : [ "/api/metabot/conversations" ]
}
},
- "/api/field/{id}/values" : {
- "get" : {
- "description" : "If a Field's value of `has_field_values` is `:list`, return a list of all the distinct values of the Field (or\n remapped Field), and (if defined by a User) a map of human-readable remapped values. If `has_field_values` is not\n `:list`, checks whether we should create FieldValues for this Field; if so, creates and returns them.",
- "operationId" : "get-api-field-id-values",
- "parameters" : [ {
- "description" : "value must be an integer greater than zero.",
- "in" : "path",
- "name" : "id",
- "required" : true,
- "schema" : {
- "minimum" : 1,
- "type" : "integer"
+ "/api/metabot/document/generate-content" : {
+ "post" : {
+ "description" : "Create a new piece of content to insert into the document. Kept for backwards compatibility; now uses the native Clojure agent.",
+ "operationId" : "post-api-metabot-document-generate-content",
+ "parameters" : [ ],
+ "requestBody" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "properties" : {
+ "instructions" : {
+ "minLength" : 1,
+ "type" : "string"
+ },
+ "references" : {
+ "description" : "Value must be a map.",
+ "properties" : { },
+ "type" : "object"
+ }
+ },
+ "required" : [ "instructions" ],
+ "type" : "object"
+ }
+ }
}
- } ],
+ },
"responses" : {
"2XX" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "properties" : {
+ "description" : {
+ "oneOf" : [ {
+ "minLength" : 1,
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "draft_card" : {
+ "oneOf" : [ {
+ "properties" : {
+ "database_id" : {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
+ },
+ "dataset_query" : {
+ "description" : "Value must be a map.",
+ "properties" : { },
+ "type" : "object"
+ },
+ "name" : {
+ "minLength" : 1,
+ "type" : "string"
+ },
+ "parameters" : {
+ "oneOf" : [ {
+ "items" : {
+ "description" : "Value must be a map.",
+ "properties" : { },
+ "type" : "object"
+ },
+ "type" : "array"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "visualization_settings" : {
+ "description" : "Value must be a map.",
+ "properties" : { },
+ "type" : "object"
+ }
+ },
+ "required" : [ "name", "dataset_query", "database_id", "parameters", "visualization_settings" ],
+ "type" : "object"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "error" : {
+ "oneOf" : [ {
+ "minLength" : 1,
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ }
+ },
+ "required" : [ "draft_card", "error", "description" ],
+ "type" : "object"
+ }
+ }
+ },
"description" : "Successful response"
},
"4XX" : {
@@ -35931,44 +35858,48 @@
"description" : "Server error response"
}
},
- "summary" : "GET /api/field/{id}/values",
- "tags" : [ "/api/field" ]
- },
+ "summary" : "POST /api/metabot/document/generate-content",
+ "tags" : [ "/api/metabot/document" ]
+ }
+ },
+ "/api/metabot/feedback" : {
"post" : {
- "description" : "Update the fields values and human-readable values for a `Field` whose semantic type is\n `category`/`city`/`state`/`country` or whose base type is `type/Boolean`. The human-readable values are optional.",
- "operationId" : "post-api-field-id-values",
- "parameters" : [ {
- "description" : "value must be an integer greater than zero.",
- "in" : "path",
- "name" : "id",
- "required" : true,
- "schema" : {
- "minimum" : 1,
- "type" : "integer"
- }
- } ],
+ "description" : "Persist Metabot feedback.",
+ "operationId" : "post-api-metabot-feedback",
+ "parameters" : [ ],
"requestBody" : {
"content" : {
"application/json" : {
"schema" : {
"properties" : {
- "values" : {
- "items" : {
- "anyOf" : [ {
- "prefixItems" : [ { } ],
- "type" : "array"
- }, {
- "prefixItems" : [ { }, {
- "minLength" : 1,
- "type" : "string"
- } ],
- "type" : "array"
- } ]
- },
- "type" : "array"
+ "freeform_feedback" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "issue_type" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "message_id" : {
+ "minLength" : 1,
+ "type" : "string"
+ },
+ "metabot_id" : {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
+ },
+ "positive" : {
+ "type" : "boolean"
}
},
- "required" : [ "values" ],
+ "required" : [ "metabot_id", "message_id", "positive" ],
"type" : "object"
}
}
@@ -35976,6 +35907,22 @@
},
"responses" : {
"2XX" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "properties" : {
+ "body" : {
+ "type" : "null"
+ },
+ "status" : {
+ "const" : 204
+ }
+ },
+ "required" : [ "status", "body" ],
+ "type" : "object"
+ }
+ }
+ },
"description" : "Successful response"
},
"4XX" : {
@@ -35985,23 +35932,15 @@
"description" : "Server error response"
}
},
- "summary" : "POST /api/field/{id}/values",
- "tags" : [ "/api/field" ]
+ "summary" : "POST /api/metabot/feedback",
+ "tags" : [ "/api/metabot" ]
}
},
- "/api/geojson" : {
+ "/api/metabot/metabot" : {
"get" : {
- "description" : "Load a custom GeoJSON file based on a URL or file path provided as a query parameter.\n This behaves similarly to /api/geojson/:key but doesn't require the custom map to be saved to the DB first.",
- "operationId" : "get-api-geojson",
- "parameters" : [ {
- "in" : "query",
- "name" : "url",
- "required" : true,
- "schema" : {
- "minLength" : 1,
- "type" : "string"
- }
- } ],
+ "description" : "List configured metabot instances",
+ "operationId" : "get-api-metabot-metabot",
+ "parameters" : [ ],
"responses" : {
"2XX" : {
"description" : "Successful response"
@@ -36013,21 +35952,21 @@
"description" : "Server error response"
}
},
- "summary" : "GET /api/geojson",
- "tags" : [ "/api/geojson" ]
+ "summary" : "GET /api/metabot/metabot",
+ "tags" : [ "/api/metabot/metabot" ]
}
},
- "/api/geojson/{key}" : {
+ "/api/metabot/metabot/{id}" : {
"get" : {
- "description" : "Fetch a custom GeoJSON file as defined in the [[metabase.geojson.settings/custom-geojson]] setting. (This just acts\n as a simple proxy for the file specified for `key`).",
- "operationId" : "get-api-geojson-key",
+ "description" : "Retrieve one metabot instance",
+ "operationId" : "get-api-metabot-metabot-id",
"parameters" : [ {
"in" : "path",
- "name" : "key",
+ "name" : "id",
"required" : true,
"schema" : {
- "minLength" : 1,
- "type" : "string"
+ "minimum" : 1,
+ "type" : "integer"
}
} ],
"responses" : {
@@ -36041,48 +35980,39 @@
"description" : "Server error response"
}
},
- "summary" : "GET /api/geojson/{key}",
- "tags" : [ "/api/geojson" ]
- }
- },
- "/api/glossary" : {
- "get" : {
- "description" : "Fetch all glossary entries, optionally filtered by search term.",
- "operationId" : "get-api-glossary",
- "parameters" : [ ],
- "responses" : {
- "2XX" : {
- "description" : "Successful response"
- },
- "4XX" : {
- "description" : "Client error response"
- },
- "5XX" : {
- "description" : "Server error response"
- }
- },
- "summary" : "GET /api/glossary",
- "tags" : [ "/api/glossary" ]
+ "summary" : "GET /api/metabot/metabot/{id}",
+ "tags" : [ "/api/metabot/metabot" ]
},
- "post" : {
- "description" : "Create a new glossary entry.",
- "operationId" : "post-api-glossary",
- "parameters" : [ ],
+ "put" : {
+ "description" : "Update a metabot instance",
+ "operationId" : "put-api-metabot-metabot-id",
+ "parameters" : [ {
+ "in" : "path",
+ "name" : "id",
+ "required" : true,
+ "schema" : {
+ "minimum" : 1,
+ "type" : "integer"
+ }
+ } ],
"requestBody" : {
"content" : {
"application/json" : {
"schema" : {
+ "additionalProperties" : false,
"properties" : {
- "definition" : {
- "minLength" : 1,
- "type" : "string"
+ "collection_id" : {
+ "oneOf" : [ {
+ "minimum" : 1,
+ "type" : "integer"
+ }, {
+ "type" : "null"
+ } ]
},
- "term" : {
- "minLength" : 1,
- "type" : "string"
+ "use_verified_content" : {
+ "type" : "boolean"
}
},
- "required" : [ "term", "definition" ],
"type" : "object"
}
}
@@ -36099,16 +36029,15 @@
"description" : "Server error response"
}
},
- "summary" : "POST /api/glossary",
- "tags" : [ "/api/glossary" ]
+ "summary" : "PUT /api/metabot/metabot/{id}",
+ "tags" : [ "/api/metabot/metabot" ]
}
},
- "/api/glossary/{id}" : {
+ "/api/metabot/metabot/{id}/prompt-suggestions" : {
"delete" : {
- "description" : "Delete a glossary entry.",
- "operationId" : "delete-api-glossary-id",
+ "description" : "Delete all prompt suggestions for the metabot instance with `id`.",
+ "operationId" : "delete-api-metabot-metabot-id-prompt-suggestions",
"parameters" : [ {
- "description" : "value must be an integer greater than zero.",
"in" : "path",
"name" : "id",
"required" : true,
@@ -36128,14 +36057,13 @@
"description" : "Server error response"
}
},
- "summary" : "DELETE /api/glossary/{id}",
- "tags" : [ "/api/glossary" ]
+ "summary" : "DELETE /api/metabot/metabot/{id}/prompt-suggestions",
+ "tags" : [ "/api/metabot/metabot" ]
},
- "put" : {
- "description" : "Update an existing glossary entry.",
- "operationId" : "put-api-glossary-id",
+ "get" : {
+ "description" : "Return the prompt suggestions for the metabot instance with `id`.",
+ "operationId" : "get-api-metabot-metabot-id-prompt-suggestions",
"parameters" : [ {
- "description" : "value must be an integer greater than zero.",
"in" : "path",
"name" : "id",
"required" : true,
@@ -36143,27 +36071,30 @@
"minimum" : 1,
"type" : "integer"
}
- } ],
- "requestBody" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "properties" : {
- "definition" : {
- "minLength" : 1,
- "type" : "string"
- },
- "term" : {
- "minLength" : 1,
- "type" : "string"
- }
- },
- "required" : [ "term", "definition" ],
- "type" : "object"
- }
- }
+ }, {
+ "in" : "query",
+ "name" : "sample",
+ "required" : false,
+ "schema" : {
+ "type" : "boolean"
}
- },
+ }, {
+ "in" : "query",
+ "name" : "model",
+ "required" : false,
+ "schema" : {
+ "enum" : [ "metric", "model" ],
+ "type" : "string"
+ }
+ }, {
+ "in" : "query",
+ "name" : "model_id",
+ "required" : false,
+ "schema" : {
+ "minimum" : 1,
+ "type" : "integer"
+ }
+ } ],
"responses" : {
"2XX" : {
"description" : "Successful response"
@@ -36175,47 +36106,23 @@
"description" : "Server error response"
}
},
- "summary" : "PUT /api/glossary/{id}",
- "tags" : [ "/api/glossary" ]
+ "summary" : "GET /api/metabot/metabot/{id}/prompt-suggestions",
+ "tags" : [ "/api/metabot/metabot" ]
}
},
- "/api/google/settings" : {
- "put" : {
- "description" : "Update Google Sign-In related settings. You must be a superuser to do this.",
- "operationId" : "put-api-google-settings",
- "parameters" : [ ],
- "requestBody" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "properties" : {
- "google-auth-auto-create-accounts-domain" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "google-auth-client-id" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "google-auth-enabled" : {
- "oneOf" : [ {
- "type" : "boolean"
- }, {
- "type" : "null"
- } ]
- }
- },
- "type" : "object"
- }
- }
+ "/api/metabot/metabot/{id}/prompt-suggestions/regenerate" : {
+ "post" : {
+ "description" : "Remove any existing prompt suggestions for the Metabot instance with `id` and generate new ones.",
+ "operationId" : "post-api-metabot-metabot-id-prompt-suggestions-regenerate",
+ "parameters" : [ {
+ "in" : "path",
+ "name" : "id",
+ "required" : true,
+ "schema" : {
+ "minimum" : 1,
+ "type" : "integer"
}
- },
+ } ],
"responses" : {
"2XX" : {
"description" : "Successful response"
@@ -36227,55 +36134,31 @@
"description" : "Server error response"
}
},
- "summary" : "PUT /api/google/settings",
- "tags" : [ "/api/google" ]
+ "summary" : "POST /api/metabot/metabot/{id}/prompt-suggestions/regenerate",
+ "tags" : [ "/api/metabot/metabot" ]
}
},
- "/api/ldap/settings" : {
- "put" : {
- "description" : "Update LDAP related settings. You must be a superuser to do this.",
- "operationId" : "put-api-ldap-settings",
- "parameters" : [ ],
- "requestBody" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "properties" : {
- "ldap-enabled" : {
- "oneOf" : [ {
- "type" : "boolean"
- }, {
- "type" : "null"
- } ]
- },
- "ldap-host" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "ldap-password" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "ldap-port" : {
- "oneOf" : [ {
- "minimum" : 1,
- "type" : "integer"
- }, {
- "type" : "null"
- } ]
- }
- },
- "type" : "object"
- }
- }
+ "/api/metabot/metabot/{id}/prompt-suggestions/{prompt-id}" : {
+ "delete" : {
+ "description" : "Delete the prompt suggestion with ID `prompt-id` for the metabot instance with `id`.",
+ "operationId" : "delete-api-metabot-metabot-id-prompt-suggestions-prompt-id",
+ "parameters" : [ {
+ "in" : "path",
+ "name" : "id",
+ "required" : true,
+ "schema" : {
+ "minimum" : 1,
+ "type" : "integer"
}
- },
+ }, {
+ "in" : "path",
+ "name" : "prompt-id",
+ "required" : true,
+ "schema" : {
+ "minimum" : 1,
+ "type" : "integer"
+ }
+ } ],
"responses" : {
"2XX" : {
"description" : "Successful response"
@@ -36287,100 +36170,95 @@
"description" : "Server error response"
}
},
- "summary" : "PUT /api/ldap/settings",
- "tags" : [ "/api/ldap" ]
+ "summary" : "DELETE /api/metabot/metabot/{id}/prompt-suggestions/{prompt-id}",
+ "tags" : [ "/api/metabot/metabot" ]
}
},
- "/api/llm/extract-tables" : {
- "post" : {
- "description" : "Parse SQL and return referenced tables with their columns.\n\n Uses Macaw to parse the SQL, resolves table names to IDs,\n and returns permission-filtered tables with column metadata.\n\n This is a lightweight endpoint that does not trigger fingerprinting\n or field value fetching.",
- "operationId" : "post-api-llm-extract-tables",
+ "/api/metabot/permissions/user-permissions" : {
+ "get" : {
+ "description" : "Return the current user's resolved metabot permissions, taking the most\n permissive value across all their groups.",
+ "operationId" : "get-api-metabot-permissions-user-permissions",
"parameters" : [ ],
- "requestBody" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "properties" : {
- "database_id" : {
- "minimum" : 1,
- "type" : "integer"
+ "responses" : {
+ "2XX" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "properties" : {
+ "permissions" : {
+ "properties" : {
+ "metabot" : {
+ "enum" : [ "yes", "no" ],
+ "type" : "string"
+ },
+ "metabot-nlq" : {
+ "enum" : [ "yes", "no" ],
+ "type" : "string"
+ },
+ "metabot-other-tools" : {
+ "enum" : [ "yes", "no" ],
+ "type" : "string"
+ },
+ "metabot-sql-generation" : {
+ "enum" : [ "yes", "no" ],
+ "type" : "string"
+ }
+ },
+ "required" : [ "metabot", "metabot-sql-generation", "metabot-nlq", "metabot-other-tools" ],
+ "type" : "object"
+ }
},
- "sql" : {
- "type" : "string"
- }
- },
- "required" : [ "database_id", "sql" ],
- "type" : "object"
+ "required" : [ "permissions" ],
+ "type" : "object"
+ }
}
- }
+ },
+ "description" : "Successful response"
+ },
+ "4XX" : {
+ "description" : "Client error response"
+ },
+ "5XX" : {
+ "description" : "Server error response"
}
},
+ "summary" : "GET /api/metabot/permissions/user-permissions",
+ "tags" : [ "/api/metabot/permissions" ]
+ }
+ },
+ "/api/metabot/settings" : {
+ "get" : {
+ "description" : "Return available models for a provider using its configured API key.",
+ "operationId" : "get-api-metabot-settings",
+ "parameters" : [ {
+ "in" : "query",
+ "name" : "provider",
+ "required" : false,
+ "schema" : {
+ "enum" : [ "anthropic", "openai", "metabase", "openrouter" ],
+ "type" : "string"
+ }
+ } ],
"responses" : {
"2XX" : {
"content" : {
"application/json" : {
"schema" : {
"properties" : {
- "tables" : {
+ "api-key-error" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "models" : {
"items" : {
"properties" : {
- "columns" : {
- "items" : {
- "properties" : {
- "database_type" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "description" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "fk_target" : {
- "properties" : {
- "field_name" : {
- "type" : "string"
- },
- "table_name" : {
- "type" : "string"
- }
- },
- "required" : [ "table_name", "field_name" ],
- "type" : "object"
- },
- "id" : {
- "minimum" : 1,
- "type" : "integer"
- },
- "name" : {
- "type" : "string"
- },
- "semantic_type" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- }
- },
- "required" : [ "id", "name" ],
- "type" : "object"
- },
- "type" : "array"
- },
- "description" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
"display_name" : {
+ "type" : "string"
+ },
+ "group" : {
"oneOf" : [ {
"type" : "string"
}, {
@@ -36388,27 +36266,23 @@
} ]
},
"id" : {
- "minimum" : 1,
- "type" : "integer"
- },
- "name" : {
"type" : "string"
- },
- "schema" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
}
},
- "required" : [ "id", "name", "columns" ],
+ "required" : [ "id", "display_name" ],
"type" : "object"
},
"type" : "array"
+ },
+ "value" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
}
},
- "required" : [ "tables" ],
+ "required" : [ "value", "models" ],
"type" : "object"
}
}
@@ -36422,48 +36296,38 @@
"description" : "Server error response"
}
},
- "summary" : "POST /api/llm/extract-tables",
- "tags" : [ "/api/llm" ]
- }
- },
- "/api/llm/generate-sql" : {
- "post" : {
- "description" : "Generate SQL from a natural language prompt.\n\n Requires:\n - LLM to be configured (Anthropic API key set in admin settings)\n - At least one table reference (explicit @mention or implicit from source_sql)\n - A database_id parameter\n\n Returns generated SQL and the list of tables used for context.",
- "operationId" : "post-api-llm-generate-sql",
+ "summary" : "GET /api/metabot/settings",
+ "tags" : [ "/api/metabot" ]
+ },
+ "put" : {
+ "description" : "Update the Metabot provider API key and/or model setting and return the refreshed settings payload.",
+ "operationId" : "put-api-metabot-settings",
"parameters" : [ ],
"requestBody" : {
"content" : {
"application/json" : {
"schema" : {
"properties" : {
- "database_id" : {
- "minimum" : 1,
- "type" : "integer"
- },
- "prompt" : {
- "type" : "string"
+ "api-key" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
},
- "referenced_entities" : {
- "items" : {
- "properties" : {
- "id" : {
- "minimum" : 1,
- "type" : "integer"
- },
- "model" : {
- "type" : "string"
- }
- },
- "required" : [ "model", "id" ],
- "type" : "object"
- },
- "type" : "array"
+ "model" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
},
- "source_sql" : {
+ "provider" : {
+ "enum" : [ "anthropic", "openai", "metabase", "openrouter" ],
"type" : "string"
}
},
- "required" : [ "prompt", "database_id" ],
+ "required" : [ "provider" ],
"type" : "object"
}
}
@@ -36475,66 +36339,20 @@
"application/json" : {
"schema" : {
"properties" : {
- "referenced_entities" : {
+ "api-key-error" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "models" : {
"items" : {
"properties" : {
- "columns" : {
- "items" : {
- "properties" : {
- "database_type" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "description" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "fk_target" : {
- "properties" : {
- "field_name" : {
- "type" : "string"
- },
- "table_name" : {
- "type" : "string"
- }
- },
- "required" : [ "table_name", "field_name" ],
- "type" : "object"
- },
- "id" : {
- "minimum" : 1,
- "type" : "integer"
- },
- "name" : {
- "type" : "string"
- },
- "semantic_type" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- }
- },
- "required" : [ "id", "name" ],
- "type" : "object"
- },
- "type" : "array"
- },
- "description" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
"display_name" : {
+ "type" : "string"
+ },
+ "group" : {
"oneOf" : [ {
"type" : "string"
}, {
@@ -36542,33 +36360,23 @@
} ]
},
"id" : {
- "minimum" : 1,
- "type" : "integer"
- },
- "model" : {
- "type" : "string"
- },
- "name" : {
"type" : "string"
- },
- "schema" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
}
},
- "required" : [ "model", "id", "name", "columns" ],
+ "required" : [ "id", "display_name" ],
"type" : "object"
},
"type" : "array"
},
- "sql" : {
- "type" : "string"
+ "value" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
}
},
- "required" : [ "sql", "referenced_entities" ],
+ "required" : [ "value", "models" ],
"type" : "object"
}
}
@@ -36582,38 +36390,86 @@
"description" : "Server error response"
}
},
- "summary" : "POST /api/llm/generate-sql",
- "tags" : [ "/api/llm" ]
+ "summary" : "PUT /api/metabot/settings",
+ "tags" : [ "/api/metabot" ]
}
},
- "/api/llm/list-models" : {
- "get" : {
- "description" : "List available LLM models from the configured provider.\n\n Requires LLM to be configured (Anthropic API key set in admin settings).",
- "operationId" : "get-api-llm-list-models",
+ "/api/metabot/slack/events" : {
+ "post" : {
+ "description" : "Respond to activities in Slack",
+ "operationId" : "post-api-metabot-slack-events",
"parameters" : [ ],
+ "requestBody" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "oneOf" : [ {
+ "properties" : {
+ "challenge" : {
+ "type" : "string"
+ },
+ "type" : {
+ "const" : "url_verification"
+ }
+ },
+ "required" : [ "type", "challenge" ],
+ "type" : "object"
+ }, {
+ "properties" : {
+ "event" : {
+ "properties" : {
+ "event_ts" : {
+ "type" : "string"
+ },
+ "type" : {
+ "type" : "string"
+ }
+ },
+ "required" : [ "type", "event_ts" ],
+ "type" : "object"
+ },
+ "type" : {
+ "const" : "event_callback"
+ }
+ },
+ "required" : [ "type", "event" ],
+ "type" : "object"
+ }, {
+ "properties" : {
+ "type" : {
+ "type" : "string"
+ }
+ },
+ "required" : [ "type" ],
+ "type" : "object"
+ } ]
+ }
+ }
+ }
+ },
"responses" : {
"2XX" : {
"content" : {
"application/json" : {
"schema" : {
"properties" : {
- "models" : {
- "items" : {
- "properties" : {
- "display_name" : {
- "type" : "string"
- },
- "id" : {
- "type" : "string"
- }
- },
- "required" : [ "id", "display_name" ],
- "type" : "object"
+ "body" : {
+ "type" : "string"
+ },
+ "headers" : {
+ "properties" : {
+ "Content-Type" : {
+ "const" : "text/plain"
+ }
},
- "type" : "array"
+ "required" : [ "Content-Type" ],
+ "type" : "object"
+ },
+ "status" : {
+ "const" : 200
}
},
- "required" : [ "models" ],
+ "required" : [ "status", "headers", "body" ],
"type" : "object"
}
}
@@ -36627,14 +36483,14 @@
"description" : "Server error response"
}
},
- "summary" : "GET /api/llm/list-models",
- "tags" : [ "/api/llm" ]
+ "summary" : "POST /api/metabot/slack/events",
+ "tags" : [ "/api/metabot/slack" ]
}
},
- "/api/logger/adjustment" : {
- "delete" : {
- "description" : "Undo any log level adjustments.",
- "operationId" : "delete-api-logger-adjustment",
+ "/api/metabot/slack/interactive" : {
+ "post" : {
+ "description" : "Handle interactive payloads from Slack (button clicks, modal submissions).",
+ "operationId" : "post-api-metabot-slack-interactive",
"parameters" : [ ],
"responses" : {
"2XX" : {
@@ -36647,34 +36503,135 @@
"description" : "Server error response"
}
},
- "summary" : "DELETE /api/logger/adjustment",
- "tags" : [ "/api/logger" ]
- },
+ "summary" : "POST /api/metabot/slack/interactive",
+ "tags" : [ "/api/metabot/slack" ]
+ }
+ },
+ "/api/metabot/slack/settings" : {
+ "put" : {
+ "description" : "Update Metabot Slack settings atomically.\n All credential fields must be provided together.\n Setting values requires the metabot-v3 feature, but clearing values is always allowed.\n slack-connect-enabled is automatically set to true when credentials are provided, nil when cleared.",
+ "operationId" : "put-api-metabot-slack-settings",
+ "parameters" : [ ],
+ "requestBody" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "properties" : {
+ "metabot-slack-signing-secret" : {
+ "oneOf" : [ {
+ "minLength" : 1,
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "slack-connect-client-id" : {
+ "oneOf" : [ {
+ "minLength" : 1,
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "slack-connect-client-secret" : {
+ "oneOf" : [ {
+ "minLength" : 1,
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ }
+ },
+ "required" : [ "slack-connect-client-id", "slack-connect-client-secret", "metabot-slack-signing-secret" ],
+ "type" : "object"
+ }
+ }
+ }
+ },
+ "responses" : {
+ "2XX" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "properties" : {
+ "ok" : {
+ "type" : "boolean"
+ }
+ },
+ "required" : [ "ok" ],
+ "type" : "object"
+ }
+ }
+ },
+ "description" : "Successful response"
+ },
+ "4XX" : {
+ "description" : "Client error response"
+ },
+ "5XX" : {
+ "description" : "Server error response"
+ }
+ },
+ "summary" : "PUT /api/metabot/slack/settings",
+ "tags" : [ "/api/metabot/slack" ]
+ }
+ },
+ "/api/metabot/source-feedback" : {
"post" : {
- "description" : "Temporarily adjust the log levels.",
- "operationId" : "post-api-logger-adjustment",
+ "description" : "Persist Metabot source feedback.",
+ "operationId" : "post-api-metabot-source-feedback",
"parameters" : [ ],
"requestBody" : {
"content" : {
"application/json" : {
"schema" : {
"properties" : {
- "duration" : {
+ "message_id" : {
+ "minLength" : 1,
+ "type" : "string"
+ },
+ "metabot_id" : {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
"type" : "integer"
},
- "duration_unit" : {
- "$ref" : "#/components/schemas/metabase.logger.api.time-unit"
+ "positive" : {
+ "type" : "boolean"
},
- "log_levels" : { }
+ "source_id" : {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
+ },
+ "source_type" : {
+ "enum" : [ "table", "card", "model" ],
+ "type" : "string"
+ }
},
- "required" : [ "duration", "duration_unit", "log_levels" ],
+ "required" : [ "metabot_id", "message_id", "source_id", "source_type", "positive" ],
"type" : "object"
}
- }
- }
- },
- "responses" : {
- "2XX" : {
+ }
+ }
+ },
+ "responses" : {
+ "2XX" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "properties" : {
+ "body" : {
+ "type" : "null"
+ },
+ "status" : {
+ "const" : 204
+ }
+ },
+ "required" : [ "status", "body" ],
+ "type" : "object"
+ }
+ }
+ },
"description" : "Successful response"
},
"4XX" : {
@@ -36684,17 +36641,48 @@
"description" : "Server error response"
}
},
- "summary" : "POST /api/logger/adjustment",
- "tags" : [ "/api/logger" ]
+ "summary" : "POST /api/metabot/source-feedback",
+ "tags" : [ "/api/metabot" ]
}
},
- "/api/logger/logs" : {
+ "/api/metric" : {
"get" : {
- "description" : "Logs.",
- "operationId" : "get-api-logger-logs",
+ "description" : "Get a list of metrics.\n\n Returns metrics (Cards with type='metric') that the current user has read access to,\n filtered by collection visibility permissions.",
+ "operationId" : "get-api-metric",
"parameters" : [ ],
"responses" : {
"2XX" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "properties" : {
+ "data" : {
+ "items" : {
+ "$ref" : "#/components/schemas/metabase.metrics.api.Metric"
+ },
+ "type" : "array"
+ },
+ "limit" : {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
+ },
+ "offset" : {
+ "description" : "value must be an integer greater or equal to than zero.",
+ "minimum" : 0,
+ "type" : "integer"
+ },
+ "total" : {
+ "description" : "value must be an integer greater or equal to than zero.",
+ "minimum" : 0,
+ "type" : "integer"
+ }
+ },
+ "required" : [ "total", "limit", "offset", "data" ],
+ "type" : "object"
+ }
+ }
+ },
"description" : "Successful response"
},
"4XX" : {
@@ -36704,48 +36692,30 @@
"description" : "Server error response"
}
},
- "summary" : "GET /api/logger/logs",
- "tags" : [ "/api/logger" ]
+ "summary" : "GET /api/metric",
+ "tags" : [ "/api/metric" ]
}
},
- "/api/logger/presets" : {
- "get" : {
- "description" : "Get all known presets.",
- "operationId" : "get-api-logger-presets",
+ "/api/metric/breakout-values" : {
+ "post" : {
+ "description" : "Fetch distinct breakout dimension values for a metric or measure definition.\n Accepts the same definition format as POST /dataset.\n Returns extracted values and column metadata for the breakout dimension.",
+ "operationId" : "post-api-metric-breakout-values",
"parameters" : [ ],
+ "requestBody" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "$ref" : "#/components/schemas/metabase.metrics.api.DatasetRequest"
+ }
+ }
+ }
+ },
"responses" : {
"2XX" : {
"content" : {
"application/json" : {
"schema" : {
- "items" : {
- "properties" : {
- "display_name" : {
- "type" : "string"
- },
- "id" : {
- "type" : "string"
- },
- "loggers" : {
- "items" : {
- "properties" : {
- "level" : {
- "$ref" : "#/components/schemas/metabase.logger.api.log-level"
- },
- "name" : {
- "type" : "string"
- }
- },
- "required" : [ "name", "level" ],
- "type" : "object"
- },
- "type" : "array"
- }
- },
- "required" : [ "id", "display_name", "loggers" ],
- "type" : "object"
- },
- "type" : "array"
+ "$ref" : "#/components/schemas/metabase.metrics.api.BreakoutValuesResponse"
}
}
},
@@ -36758,17 +36728,33 @@
"description" : "Server error response"
}
},
- "summary" : "GET /api/logger/presets",
- "tags" : [ "/api/logger" ]
+ "summary" : "POST /api/metric/breakout-values",
+ "tags" : [ "/api/metric" ]
}
},
- "/api/login-history/current" : {
- "get" : {
- "description" : "Fetch recent logins for the current user.",
- "operationId" : "get-api-login-history-current",
+ "/api/metric/dataset" : {
+ "post" : {
+ "description" : "Execute a metric or measure-based query and stream the results.\n\n Request body requires a `definition` object containing:\n - expression: A metric math expression tree (leaf reference or arithmetic)\n Examples: [:metric {:lib/uuid \"a\"} 42], [:- {} [:metric {:lib/uuid \"a\"} 1] [:metric {:lib/uuid \"b\"} 2]]\n - filters (optional): Per-instance filters keyed by :lib/uuid from the expression\n - projections (optional): Typed projections keyed by source type and ID",
+ "operationId" : "post-api-metric-dataset",
"parameters" : [ ],
+ "requestBody" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "$ref" : "#/components/schemas/metabase.metrics.api.DatasetRequest"
+ }
+ }
+ }
+ },
"responses" : {
"2XX" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "$ref" : "#/components/schemas/metabase.metrics.api.DatasetResponse"
+ }
+ }
+ },
"description" : "Successful response"
},
"4XX" : {
@@ -36778,24 +36764,30 @@
"description" : "Server error response"
}
},
- "summary" : "GET /api/login-history/current",
- "tags" : [ "/api/login-history" ]
+ "summary" : "POST /api/metric/dataset",
+ "tags" : [ "/api/metric" ]
}
},
- "/api/measure" : {
+ "/api/metric/{id}" : {
"get" : {
- "description" : "Fetch *all* `Measures`.",
- "operationId" : "get-api-measure",
- "parameters" : [ ],
+ "description" : "Fetch a `Metric` with ID.\n\n Returns the metric with hydrated dimensions and dimension mappings.",
+ "operationId" : "get-api-metric-id",
+ "parameters" : [ {
+ "description" : "value must be an integer greater than zero.",
+ "in" : "path",
+ "name" : "id",
+ "required" : true,
+ "schema" : {
+ "minimum" : 1,
+ "type" : "integer"
+ }
+ } ],
"responses" : {
"2XX" : {
"content" : {
"application/json" : {
"schema" : {
- "items" : {
- "$ref" : "#/components/schemas/metabase.measures.api.measure"
- },
- "type" : "array"
+ "$ref" : "#/components/schemas/metabase.metrics.api.MetricWithDimensions"
}
}
},
@@ -36808,52 +36800,46 @@
"description" : "Server error response"
}
},
- "summary" : "GET /api/measure",
- "tags" : [ "/api/measure" ]
- },
- "post" : {
- "description" : "Create a new `Measure`.",
- "operationId" : "post-api-measure",
- "parameters" : [ ],
- "requestBody" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "properties" : {
- "definition" : {
- "description" : "Value must be a map.",
- "properties" : { },
- "type" : "object"
- },
- "description" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "name" : {
- "minLength" : 1,
- "type" : "string"
- },
- "table_id" : {
- "description" : "value must be an integer greater than zero.",
- "minimum" : 1,
- "type" : "integer"
- }
- },
- "required" : [ "name", "table_id", "definition" ],
- "type" : "object"
- }
- }
+ "summary" : "GET /api/metric/{id}",
+ "tags" : [ "/api/metric" ]
+ }
+ },
+ "/api/metric/{id}/dimension/{dimension-key}/remapping" : {
+ "get" : {
+ "description" : "Fetch remapped value for a specific dimension value.\n\n Returns a pair [value, display-name] if remapping exists, or [value] otherwise.",
+ "operationId" : "get-api-metric-id-dimension-dimension-key-remapping",
+ "parameters" : [ {
+ "description" : "value must be an integer greater than zero.",
+ "in" : "path",
+ "name" : "id",
+ "required" : true,
+ "schema" : {
+ "minimum" : 1,
+ "type" : "integer"
}
- },
+ }, {
+ "description" : "value must be a valid UUID.",
+ "in" : "path",
+ "name" : "dimension-key",
+ "required" : true,
+ "schema" : {
+ "pattern" : "[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",
+ "type" : "string"
+ }
+ }, {
+ "in" : "query",
+ "name" : "value",
+ "required" : true,
+ "schema" : {
+ "type" : "string"
+ }
+ } ],
"responses" : {
"2XX" : {
"content" : {
"application/json" : {
"schema" : {
- "$ref" : "#/components/schemas/metabase.measures.api.measure"
+ "$ref" : "#/components/schemas/metabase.metrics.api.RemappedValueResponse"
}
}
},
@@ -36866,14 +36852,14 @@
"description" : "Server error response"
}
},
- "summary" : "POST /api/measure",
- "tags" : [ "/api/measure" ]
+ "summary" : "GET /api/metric/{id}/dimension/{dimension-key}/remapping",
+ "tags" : [ "/api/metric" ]
}
},
- "/api/measure/{id}" : {
+ "/api/metric/{id}/dimension/{dimension-key}/search" : {
"get" : {
- "description" : "Fetch `Measure` with ID.",
- "operationId" : "get-api-measure-id",
+ "description" : "Search for values of a dimension that contain the query string.\n\n Returns field values matching the search query in the same format as the field values API.",
+ "operationId" : "get-api-metric-id-dimension-dimension-key-search",
"parameters" : [ {
"description" : "value must be an integer greater than zero.",
"in" : "path",
@@ -36883,13 +36869,36 @@
"minimum" : 1,
"type" : "integer"
}
+ }, {
+ "description" : "value must be a valid UUID.",
+ "in" : "path",
+ "name" : "dimension-key",
+ "required" : true,
+ "schema" : {
+ "pattern" : "[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",
+ "type" : "string"
+ }
+ }, {
+ "in" : "query",
+ "name" : "query",
+ "required" : true,
+ "schema" : {
+ "minLength" : 1,
+ "type" : "string"
+ }
} ],
"responses" : {
"2XX" : {
"content" : {
"application/json" : {
"schema" : {
- "$ref" : "#/components/schemas/metabase.measures.api.measure"
+ "items" : {
+ "items" : {
+ "type" : "string"
+ },
+ "type" : "array"
+ },
+ "type" : "array"
}
}
},
@@ -36902,12 +36911,14 @@
"description" : "Server error response"
}
},
- "summary" : "GET /api/measure/{id}",
- "tags" : [ "/api/measure" ]
- },
- "put" : {
- "description" : "Update a `Measure` with ID.",
- "operationId" : "put-api-measure-id",
+ "summary" : "GET /api/metric/{id}/dimension/{dimension-key}/search",
+ "tags" : [ "/api/metric" ]
+ }
+ },
+ "/api/metric/{id}/dimension/{dimension-key}/values" : {
+ "get" : {
+ "description" : "Fetch values for a dimension of a metric.\n\n Returns field values in the same format as the field values API:\n - values: list of [value] or [value, display-name] tuples\n - field_id: the underlying field ID\n - has_more_values: boolean indicating if there are more values",
+ "operationId" : "get-api-metric-id-dimension-dimension-key-values",
"parameters" : [ {
"description" : "value must be an integer greater than zero.",
"in" : "path",
@@ -36917,59 +36928,42 @@
"minimum" : 1,
"type" : "integer"
}
- } ],
- "requestBody" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "properties" : {
- "archived" : {
- "oneOf" : [ {
- "type" : "boolean"
- }, {
- "type" : "null"
- } ]
- },
- "definition" : {
- "oneOf" : [ {
- "properties" : { },
- "type" : "object"
- }, {
- "type" : "null"
- } ]
- },
- "description" : {
- "oneOf" : [ {
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "name" : {
- "oneOf" : [ {
- "minLength" : 1,
- "type" : "string"
- }, {
- "type" : "null"
- } ]
- },
- "revision_message" : {
- "minLength" : 1,
- "type" : "string"
- }
- },
- "required" : [ "revision_message" ],
- "type" : "object"
- }
- }
+ }, {
+ "description" : "value must be a valid UUID.",
+ "in" : "path",
+ "name" : "dimension-key",
+ "required" : true,
+ "schema" : {
+ "pattern" : "[a-f0-9]{8}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{4}-[a-f0-9]{12}",
+ "type" : "string"
}
- },
+ } ],
"responses" : {
"2XX" : {
"content" : {
"application/json" : {
"schema" : {
- "$ref" : "#/components/schemas/metabase.measures.api.measure"
+ "properties" : {
+ "has_more_values" : {
+ "type" : "boolean"
+ },
+ "values" : {
+ "items" : {
+ "anyOf" : [ {
+ "prefixItems" : [ { }, {
+ "type" : "string"
+ } ],
+ "type" : "array"
+ }, {
+ "prefixItems" : [ { } ],
+ "type" : "array"
+ } ]
+ },
+ "type" : "array"
+ }
+ },
+ "required" : [ "has_more_values", "values" ],
+ "type" : "object"
}
}
},
@@ -36982,8 +36976,8 @@
"description" : "Server error response"
}
},
- "summary" : "PUT /api/measure/{id}",
- "tags" : [ "/api/measure" ]
+ "summary" : "GET /api/metric/{id}/dimension/{dimension-key}/values",
+ "tags" : [ "/api/metric" ]
}
},
"/api/model-index" : {
@@ -37763,6 +37757,13 @@
},
"responses" : {
"2XX" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "$ref" : "#/components/schemas/metabase.notification.models.FullyHydratedNotification"
+ }
+ }
+ },
"description" : "Successful response"
},
"4XX" : {
@@ -42566,6 +42567,88 @@
"tags" : [ "/api/setup" ]
}
},
+ "/api/slack/app-info" : {
+ "get" : {
+ "description" : "Returns the Slack app_id and team_id. Used by the frontend to construct\n direct links to the Slack app settings page.",
+ "operationId" : "get-api-slack-app-info",
+ "parameters" : [ ],
+ "responses" : {
+ "2XX" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "additionalProperties" : false,
+ "properties" : {
+ "app_id" : {
+ "oneOf" : [ {
+ "minLength" : 1,
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "scopes" : {
+ "oneOf" : [ {
+ "additionalProperties" : false,
+ "properties" : {
+ "actual" : {
+ "items" : {
+ "type" : "string"
+ },
+ "type" : "array"
+ },
+ "extra" : {
+ "items" : {
+ "type" : "string"
+ },
+ "type" : "array"
+ },
+ "missing" : {
+ "items" : {
+ "type" : "string"
+ },
+ "type" : "array"
+ },
+ "required" : {
+ "items" : {
+ "type" : "string"
+ },
+ "type" : "array"
+ }
+ },
+ "required" : [ "actual", "required", "missing", "extra" ],
+ "type" : "object"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "team_id" : {
+ "oneOf" : [ {
+ "minLength" : 1,
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ }
+ },
+ "required" : [ "app_id", "team_id", "scopes" ],
+ "type" : "object"
+ }
+ }
+ },
+ "description" : "Successful response"
+ },
+ "4XX" : {
+ "description" : "Client error response"
+ },
+ "5XX" : {
+ "description" : "Server error response"
+ }
+ },
+ "summary" : "GET /api/slack/app-info",
+ "tags" : [ "/api/slack" ]
+ }
+ },
"/api/slack/bug-report" : {
"post" : {
"description" : "Send diagnostic information to the configured Slack channels.",
@@ -42603,11 +42686,165 @@
},
"/api/slack/manifest" : {
"get" : {
- "description" : "Returns the YAML manifest file that should be used to bootstrap new Slack apps",
+ "description" : "Returns the JSON manifest file that should be used to bootstrap new Slack apps",
"operationId" : "get-api-slack-manifest",
"parameters" : [ ],
"responses" : {
"2XX" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "properties" : {
+ "display_information" : {
+ "properties" : {
+ "background_color" : {
+ "type" : "string"
+ },
+ "description" : {
+ "type" : "string"
+ },
+ "name" : {
+ "type" : "string"
+ }
+ },
+ "required" : [ "name", "description", "background_color" ],
+ "type" : "object"
+ },
+ "features" : {
+ "properties" : {
+ "app_home" : {
+ "properties" : {
+ "home_tab_enabled" : {
+ "type" : "boolean"
+ },
+ "messages_tab_enabled" : {
+ "type" : "boolean"
+ },
+ "messages_tab_read_only_enabled" : {
+ "type" : "boolean"
+ }
+ },
+ "required" : [ "home_tab_enabled", "messages_tab_enabled", "messages_tab_read_only_enabled" ],
+ "type" : "object"
+ },
+ "assistant_view" : {
+ "properties" : {
+ "assistant_description" : {
+ "type" : "string"
+ }
+ },
+ "required" : [ "assistant_description" ],
+ "type" : "object"
+ },
+ "bot_user" : {
+ "properties" : {
+ "always_online" : {
+ "type" : "boolean"
+ },
+ "display_name" : {
+ "type" : "string"
+ }
+ },
+ "required" : [ "display_name" ],
+ "type" : "object"
+ },
+ "slash_commands" : {
+ "items" : {
+ "properties" : {
+ "command" : {
+ "type" : "string"
+ },
+ "description" : {
+ "type" : "string"
+ },
+ "should_escape" : {
+ "type" : "boolean"
+ },
+ "url" : {
+ "description" : "value must be a valid URL."
+ }
+ },
+ "required" : [ "command", "url", "description", "should_escape" ],
+ "type" : "object"
+ },
+ "type" : "array"
+ }
+ },
+ "required" : [ "bot_user" ],
+ "type" : "object"
+ },
+ "oauth_config" : {
+ "properties" : {
+ "redirect_urls" : {
+ "items" : {
+ "description" : "value must be a valid URL."
+ },
+ "type" : "array"
+ },
+ "scopes" : {
+ "properties" : {
+ "bot" : {
+ "items" : {
+ "type" : "string"
+ },
+ "type" : "array"
+ }
+ },
+ "required" : [ "bot" ],
+ "type" : "object"
+ }
+ },
+ "required" : [ "scopes" ],
+ "type" : "object"
+ },
+ "settings" : {
+ "properties" : {
+ "event_subscriptions" : {
+ "properties" : {
+ "bot_events" : {
+ "items" : {
+ "type" : "string"
+ },
+ "type" : "array"
+ },
+ "request_url" : {
+ "description" : "value must be a valid URL."
+ }
+ },
+ "required" : [ "request_url", "bot_events" ],
+ "type" : "object"
+ },
+ "interactivity" : {
+ "properties" : {
+ "is_enabled" : {
+ "type" : "boolean"
+ },
+ "request_url" : {
+ "description" : "value must be a valid URL."
+ }
+ },
+ "required" : [ "is_enabled", "request_url" ],
+ "type" : "object"
+ },
+ "org_deploy_enabled" : {
+ "type" : "boolean"
+ },
+ "socket_mode_enabled" : {
+ "type" : "boolean"
+ },
+ "token_rotation_enabled" : {
+ "type" : "boolean"
+ }
+ },
+ "required" : [ "event_subscriptions", "interactivity", "org_deploy_enabled", "socket_mode_enabled", "token_rotation_enabled" ],
+ "type" : "object"
+ }
+ },
+ "required" : [ "display_information", "features", "oauth_config" ],
+ "type" : "object"
+ }
+ }
+ },
"description" : "Successful response"
},
"4XX" : {
@@ -42761,6 +42998,17 @@
"type" : "null"
} ]
}
+ }, {
+ "in" : "query",
+ "name" : "include-transform-targets",
+ "required" : false,
+ "schema" : {
+ "oneOf" : [ {
+ "type" : "boolean"
+ }, {
+ "type" : "null"
+ } ]
+ }
} ],
"responses" : {
"2XX" : {
@@ -43023,6 +43271,15 @@
"type" : "null"
} ]
},
+ "collection_id" : {
+ "oneOf" : [ {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
+ }, {
+ "type" : "null"
+ } ]
+ },
"data_authority" : {
"oneOf" : [ {
"$ref" : "#/components/schemas/metabase.warehouse-schema-rest.api.table.data-authority-write"
@@ -43835,6 +44092,186 @@
"tags" : [ "/api/testing" ]
}
},
+ "/api/testing/metabot/seed-ai-usage" : {
+ "delete" : {
+ "description" : "Delete all `ai_usage_log` rows inserted by the seeding endpoint for the given `user_id`, then\n clear the metabot limit cache. Intended only for E2E tests.",
+ "operationId" : "delete-api-testing-metabot-seed-ai-usage",
+ "parameters" : [ ],
+ "requestBody" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "properties" : {
+ "user_id" : {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
+ }
+ },
+ "required" : [ "user_id" ],
+ "type" : "object"
+ }
+ }
+ }
+ },
+ "responses" : {
+ "2XX" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "properties" : {
+ "deleted" : {
+ "type" : "integer"
+ }
+ },
+ "required" : [ "deleted" ],
+ "type" : "object"
+ }
+ }
+ },
+ "description" : "Successful response"
+ },
+ "4XX" : {
+ "description" : "Client error response"
+ },
+ "5XX" : {
+ "description" : "Server error response"
+ }
+ },
+ "summary" : "DELETE /api/testing/metabot/seed-ai-usage",
+ "tags" : [ "/api/testing" ]
+ },
+ "post" : {
+ "description" : "Insert `count` rows into `ai_usage_log` for the given `user_id`, then clear the metabot limit\n cache so limit checks re-evaluate immediately. Intended only for E2E tests.",
+ "operationId" : "post-api-testing-metabot-seed-ai-usage",
+ "parameters" : [ ],
+ "requestBody" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "properties" : {
+ "count" : {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
+ },
+ "user_id" : {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
+ }
+ },
+ "required" : [ "user_id", "count" ],
+ "type" : "object"
+ }
+ }
+ }
+ },
+ "responses" : {
+ "2XX" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "properties" : {
+ "inserted" : {
+ "type" : "integer"
+ }
+ },
+ "required" : [ "inserted" ],
+ "type" : "object"
+ }
+ }
+ },
+ "description" : "Successful response"
+ },
+ "4XX" : {
+ "description" : "Client error response"
+ },
+ "5XX" : {
+ "description" : "Server error response"
+ }
+ },
+ "summary" : "POST /api/testing/metabot/seed-ai-usage",
+ "tags" : [ "/api/testing" ]
+ }
+ },
+ "/api/testing/metabot/seed-usage-auditing" : {
+ "post" : {
+ "description" : "Seed deterministic Metabot conversation, message, and token usage rows for the usage auditing E2E charts.",
+ "operationId" : "post-api-testing-metabot-seed-usage-auditing",
+ "parameters" : [ ],
+ "requestBody" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "properties" : {
+ "second_tenant_id" : {
+ "oneOf" : [ {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "second_user_id" : {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
+ },
+ "tenant_id" : {
+ "oneOf" : [ {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "user_id" : {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
+ }
+ },
+ "required" : [ "user_id", "second_user_id" ],
+ "type" : "object"
+ }
+ }
+ }
+ },
+ "responses" : {
+ "2XX" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "properties" : {
+ "date" : {
+ "minLength" : 1,
+ "type" : "string"
+ },
+ "inserted" : {
+ "type" : "integer"
+ }
+ },
+ "required" : [ "inserted", "date" ],
+ "type" : "object"
+ }
+ }
+ },
+ "description" : "Successful response"
+ },
+ "4XX" : {
+ "description" : "Client error response"
+ },
+ "5XX" : {
+ "description" : "Server error response"
+ }
+ },
+ "summary" : "POST /api/testing/metabot/seed-usage-auditing",
+ "tags" : [ "/api/testing" ]
+ }
+ },
"/api/testing/native-query" : {
"post" : {
"description" : "Creates a native query from a test query spec.",
@@ -43984,6 +44421,106 @@
"tags" : [ "/api/testing" ]
}
},
+ "/api/testing/security-advisories" : {
+ "post" : {
+ "description" : "Nuke all existing security advisories and insert the provided ones.",
+ "operationId" : "post-api-testing-security-advisories",
+ "parameters" : [ ],
+ "requestBody" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "properties" : {
+ "advisories" : {
+ "items" : {
+ "properties" : {
+ "advisory_id" : {
+ "minLength" : 1,
+ "type" : "string"
+ },
+ "advisory_url" : {
+ "oneOf" : [ {
+ "minLength" : 1,
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "affected_versions" : {
+ "items" : {
+ "properties" : {
+ "fixed" : {
+ "type" : "string"
+ },
+ "min" : {
+ "type" : "string"
+ }
+ },
+ "required" : [ "min", "fixed" ],
+ "type" : "object"
+ },
+ "type" : "array"
+ },
+ "description" : {
+ "minLength" : 1,
+ "type" : "string"
+ },
+ "match_status" : {
+ "enum" : [ "unknown", "active", "resolved", "not_affected", "error" ],
+ "type" : "string"
+ },
+ "matching_query" : {
+ "oneOf" : [ {
+ "additionalProperties" : {
+ "type" : "string"
+ },
+ "type" : "object"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "published_at" : { },
+ "remediation" : {
+ "minLength" : 1,
+ "type" : "string"
+ },
+ "severity" : {
+ "enum" : [ "critical", "high", "medium", "low" ],
+ "type" : "string"
+ },
+ "title" : {
+ "minLength" : 1,
+ "type" : "string"
+ },
+ "updated_at" : { }
+ },
+ "required" : [ "advisory_id", "title", "severity", "description", "remediation", "affected_versions", "match_status", "published_at", "updated_at" ],
+ "type" : "object"
+ },
+ "type" : "array"
+ }
+ },
+ "required" : [ "advisories" ],
+ "type" : "object"
+ }
+ }
+ }
+ },
+ "responses" : {
+ "2XX" : {
+ "description" : "Successful response"
+ },
+ "4XX" : {
+ "description" : "Client error response"
+ },
+ "5XX" : {
+ "description" : "Server error response"
+ }
+ },
+ "summary" : "POST /api/testing/security-advisories",
+ "tags" : [ "/api/testing" ]
+ }
+ },
"/api/testing/set-time" : {
"post" : {
"description" : "Make java-time see world at exact time.",
@@ -45085,9 +45622,6 @@
"minimum" : 1,
"type" : "integer"
},
- "dependency_analysis_version" : {
- "type" : "integer"
- },
"description" : {
"oneOf" : [ {
"type" : "string"
@@ -45106,10 +45640,39 @@
"minimum" : 1,
"type" : "integer"
},
+ "last_checkpoint_value" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
"last_run" : {
"oneOf" : [ {
"additionalProperties" : false,
"properties" : {
+ "checkpoint_filter_field_id" : {
+ "oneOf" : [ {
+ "minimum" : 1,
+ "type" : "integer"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "checkpoint_hi_value" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "checkpoint_lo_value" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
"end_time" : {
"oneOf" : [ { }, {
"type" : "null"
@@ -45133,6 +45696,13 @@
"type" : "null"
} ]
},
+ "metered_as" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
"run_method" : {
"type" : "string"
},
@@ -45281,9 +45851,17 @@
"type" : "null"
} ]
},
+ "target_table_id" : {
+ "oneOf" : [ {
+ "minimum" : 1,
+ "type" : "integer"
+ }, {
+ "type" : "null"
+ } ]
+ },
"updated_at" : { }
},
- "required" : [ "id", "name", "description", "source", "target", "source_type", "entity_id", "created_at", "updated_at", "creator_id", "collection_id", "dependency_analysis_version", "creator" ],
+ "required" : [ "id", "name", "description", "source", "target", "source_type", "entity_id", "created_at", "updated_at", "creator_id", "collection_id", "creator" ],
"type" : "object"
},
"type" : "array"
@@ -45445,9 +46023,6 @@
"minimum" : 1,
"type" : "integer"
},
- "dependency_analysis_version" : {
- "type" : "integer"
- },
"description" : {
"oneOf" : [ {
"type" : "string"
@@ -45466,10 +46041,39 @@
"minimum" : 1,
"type" : "integer"
},
+ "last_checkpoint_value" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
"last_run" : {
"oneOf" : [ {
"additionalProperties" : false,
"properties" : {
+ "checkpoint_filter_field_id" : {
+ "oneOf" : [ {
+ "minimum" : 1,
+ "type" : "integer"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "checkpoint_hi_value" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "checkpoint_lo_value" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
"end_time" : {
"oneOf" : [ { }, {
"type" : "null"
@@ -45493,6 +46097,13 @@
"type" : "null"
} ]
},
+ "metered_as" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
"run_method" : {
"type" : "string"
},
@@ -45641,9 +46252,17 @@
"type" : "null"
} ]
},
+ "target_table_id" : {
+ "oneOf" : [ {
+ "minimum" : 1,
+ "type" : "integer"
+ }, {
+ "type" : "null"
+ } ]
+ },
"updated_at" : { }
},
- "required" : [ "id", "name", "description", "source", "target", "source_type", "entity_id", "created_at", "updated_at", "creator_id", "collection_id", "dependency_analysis_version", "creator" ],
+ "required" : [ "id", "name", "description", "source", "target", "source_type", "entity_id", "created_at", "updated_at", "creator_id", "collection_id", "creator" ],
"type" : "object"
}
}
@@ -45729,6 +46348,9 @@
"items" : {
"additionalProperties" : false,
"properties" : {
+ "active" : {
+ "type" : "boolean"
+ },
"built_in_type" : {
"oneOf" : [ {
"type" : "string"
@@ -45842,7 +46464,7 @@
},
"updated_at" : { }
},
- "required" : [ "id", "name", "description", "schedule", "ui_display_type", "entity_id", "created_at", "updated_at" ],
+ "required" : [ "id", "name", "description", "schedule", "ui_display_type", "active", "entity_id", "created_at", "updated_at" ],
"type" : "object"
},
"type" : "array"
@@ -45913,6 +46535,9 @@
"schema" : {
"additionalProperties" : false,
"properties" : {
+ "active" : {
+ "type" : "boolean"
+ },
"built_in_type" : {
"oneOf" : [ {
"type" : "string"
@@ -46026,7 +46651,7 @@
},
"updated_at" : { }
},
- "required" : [ "id", "name", "description", "schedule", "ui_display_type", "entity_id", "created_at", "updated_at" ],
+ "required" : [ "id", "name", "description", "schedule", "ui_display_type", "active", "entity_id", "created_at", "updated_at" ],
"type" : "object"
}
}
@@ -46044,6 +46669,58 @@
"tags" : [ "/api/transform-job" ]
}
},
+ "/api/transform-job/active" : {
+ "put" : {
+ "description" : "Activate or deactivate every transform job. Inactive jobs do not run on schedule. Manual runs\n via `POST /api/transform-job/:job-id/run` ignore this flag.\n\n Reports per-job outcome counts: `:updated` (successfully flipped) and `:failed` (raised an\n error during the flip — the row update or Quartz write failed and was logged).",
+ "operationId" : "put-api-transform-job-active",
+ "parameters" : [ ],
+ "requestBody" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "properties" : {
+ "active" : {
+ "type" : "boolean"
+ }
+ },
+ "required" : [ "active" ],
+ "type" : "object"
+ }
+ }
+ }
+ },
+ "responses" : {
+ "2XX" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "additionalProperties" : false,
+ "properties" : {
+ "failed" : {
+ "type" : "integer"
+ },
+ "updated" : {
+ "type" : "integer"
+ }
+ },
+ "required" : [ "updated", "failed" ],
+ "type" : "object"
+ }
+ }
+ },
+ "description" : "Successful response"
+ },
+ "4XX" : {
+ "description" : "Client error response"
+ },
+ "5XX" : {
+ "description" : "Server error response"
+ }
+ },
+ "summary" : "PUT /api/transform-job/active",
+ "tags" : [ "/api/transform-job" ]
+ }
+ },
"/api/transform-job/{job-id}" : {
"delete" : {
"description" : "Delete a transform job.",
@@ -46092,6 +46769,9 @@
"schema" : {
"additionalProperties" : false,
"properties" : {
+ "active" : {
+ "type" : "boolean"
+ },
"built_in_type" : {
"oneOf" : [ {
"type" : "string"
@@ -46205,7 +46885,7 @@
},
"updated_at" : { }
},
- "required" : [ "id", "name", "description", "schedule", "ui_display_type", "entity_id", "created_at", "updated_at" ],
+ "required" : [ "id", "name", "description", "schedule", "ui_display_type", "active", "entity_id", "created_at", "updated_at" ],
"type" : "object"
}
}
@@ -46240,6 +46920,9 @@
"application/json" : {
"schema" : {
"properties" : {
+ "active" : {
+ "type" : "boolean"
+ },
"description" : {
"oneOf" : [ {
"minLength" : 1,
@@ -46281,6 +46964,9 @@
"schema" : {
"additionalProperties" : false,
"properties" : {
+ "active" : {
+ "type" : "boolean"
+ },
"built_in_type" : {
"oneOf" : [ {
"type" : "string"
@@ -46394,7 +47080,7 @@
},
"updated_at" : { }
},
- "required" : [ "id", "name", "description", "schedule", "ui_display_type", "entity_id", "created_at", "updated_at" ],
+ "required" : [ "id", "name", "description", "schedule", "ui_display_type", "active", "entity_id", "created_at", "updated_at" ],
"type" : "object"
}
}
@@ -46549,9 +47235,6 @@
"minimum" : 1,
"type" : "integer"
},
- "dependency_analysis_version" : {
- "type" : "integer"
- },
"description" : {
"oneOf" : [ {
"type" : "string"
@@ -46587,7 +47270,7 @@
"target" : { },
"updated_at" : { }
},
- "required" : [ "id", "name", "description", "source", "target", "source_type", "entity_id", "created_at", "updated_at", "creator_id", "collection_id", "dependency_analysis_version", "creator" ],
+ "required" : [ "id", "name", "description", "source", "target", "source_type", "entity_id", "created_at", "updated_at", "creator_id", "collection_id", "creator" ],
"type" : "object"
},
"type" : "array"
@@ -46866,112 +47549,6 @@
"tags" : [ "/api/transform-tag" ]
}
},
- "/api/transform/extract-columns" : {
- "post" : {
- "description" : "Extract column names suitable for incremental transform checkpoint filtering.\n\n This endpoint is specifically for populating the checkpoint column dropdown in\n incremental transforms. It only returns columns with types supported for checkpoint\n filtering: temporal (timestamp/tz) and numeric (int/float) types.\n\n Text, boolean, and other unsupported column types are filtered out.\n\n The query is compiled to native SQL using [[qp.compile/compile-with-inline-parameters]],\n which handles parameterized queries with template tags. Then extracts column names\n and types using PreparedStatement metadata.\n\n Returns a map with a :columns key containing a vector of column names (strings).\n If extraction fails, returns nil for :columns.",
- "operationId" : "post-api-transform-extract-columns",
- "parameters" : [ ],
- "requestBody" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "properties" : {
- "query" : {
- "$ref" : "#/components/schemas/metabase.query-processor.schema.any-query"
- }
- },
- "required" : [ "query" ],
- "type" : "object"
- }
- }
- }
- },
- "responses" : {
- "2XX" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "properties" : {
- "columns" : {
- "oneOf" : [ {
- "items" : {
- "type" : "string"
- },
- "type" : "array"
- }, {
- "type" : "null"
- } ]
- }
- },
- "required" : [ "columns" ],
- "type" : "object"
- }
- }
- },
- "description" : "Successful response"
- },
- "4XX" : {
- "description" : "Client error response"
- },
- "5XX" : {
- "description" : "Server error response"
- }
- },
- "summary" : "POST /api/transform/extract-columns",
- "tags" : [ "/api/transform" ]
- }
- },
- "/api/transform/is-simple-query" : {
- "post" : {
- "description" : "Checks if a native SQL query string is simple enough for automatic checkpoint insertion",
- "operationId" : "post-api-transform-is-simple-query",
- "parameters" : [ ],
- "requestBody" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "properties" : {
- "query" : {
- "type" : "string"
- }
- },
- "required" : [ "query" ],
- "type" : "object"
- }
- }
- }
- },
- "responses" : {
- "2XX" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "properties" : {
- "is_simple" : {
- "type" : "boolean"
- },
- "reason" : {
- "type" : "string"
- }
- },
- "required" : [ "is_simple" ],
- "type" : "object"
- }
- }
- },
- "description" : "Successful response"
- },
- "4XX" : {
- "description" : "Client error response"
- },
- "5XX" : {
- "description" : "Server error response"
- }
- },
- "summary" : "POST /api/transform/is-simple-query",
- "tags" : [ "/api/transform" ]
- }
- },
"/api/transform/run" : {
"get" : {
"description" : "Get transform runs based on a set of filter params.",
@@ -47078,6 +47655,19 @@
"type" : "null"
} ]
}
+ }, {
+ "in" : "query",
+ "name" : "user-id",
+ "required" : false,
+ "schema" : {
+ "oneOf" : [ {
+ "description" : "value must be an integer greater than zero.",
+ "minimum" : 1,
+ "type" : "integer"
+ }, {
+ "type" : "null"
+ } ]
+ }
} ],
"responses" : {
"2XX" : {
@@ -47090,6 +47680,28 @@
"items" : {
"additionalProperties" : false,
"properties" : {
+ "checkpoint_filter_field_id" : {
+ "oneOf" : [ {
+ "minimum" : 1,
+ "type" : "integer"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "checkpoint_hi_value" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "checkpoint_lo_value" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
"end_time" : {
"oneOf" : [ { }, {
"type" : "null"
@@ -47113,6 +47725,13 @@
"type" : "null"
} ]
},
+ "metered_as" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
"run_method" : {
"type" : "string"
},
@@ -47250,6 +47869,28 @@
"schema" : {
"additionalProperties" : false,
"properties" : {
+ "checkpoint_filter_field_id" : {
+ "oneOf" : [ {
+ "minimum" : 1,
+ "type" : "integer"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "checkpoint_hi_value" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "checkpoint_lo_value" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
"end_time" : {
"oneOf" : [ { }, {
"type" : "null"
@@ -47273,6 +47914,13 @@
"type" : "null"
} ]
},
+ "metered_as" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
"run_method" : {
"type" : "string"
},
@@ -47496,9 +48144,6 @@
"minimum" : 1,
"type" : "integer"
},
- "dependency_analysis_version" : {
- "type" : "integer"
- },
"description" : {
"oneOf" : [ {
"type" : "string"
@@ -47517,10 +48162,39 @@
"minimum" : 1,
"type" : "integer"
},
+ "last_checkpoint_value" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
"last_run" : {
"oneOf" : [ {
"additionalProperties" : false,
"properties" : {
+ "checkpoint_filter_field_id" : {
+ "oneOf" : [ {
+ "minimum" : 1,
+ "type" : "integer"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "checkpoint_hi_value" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "checkpoint_lo_value" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
"end_time" : {
"oneOf" : [ { }, {
"type" : "null"
@@ -47544,6 +48218,13 @@
"type" : "null"
} ]
},
+ "metered_as" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
"run_method" : {
"type" : "string"
},
@@ -47692,9 +48373,17 @@
"type" : "null"
} ]
},
+ "target_table_id" : {
+ "oneOf" : [ {
+ "minimum" : 1,
+ "type" : "integer"
+ }, {
+ "type" : "null"
+ } ]
+ },
"updated_at" : { }
},
- "required" : [ "id", "name", "description", "source", "target", "source_type", "entity_id", "created_at", "updated_at", "creator_id", "collection_id", "dependency_analysis_version", "creator" ],
+ "required" : [ "id", "name", "description", "source", "target", "source_type", "entity_id", "created_at", "updated_at", "creator_id", "collection_id", "creator" ],
"type" : "object"
}
}
@@ -47862,9 +48551,6 @@
"minimum" : 1,
"type" : "integer"
},
- "dependency_analysis_version" : {
- "type" : "integer"
- },
"description" : {
"oneOf" : [ {
"type" : "string"
@@ -47883,10 +48569,39 @@
"minimum" : 1,
"type" : "integer"
},
+ "last_checkpoint_value" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
"last_run" : {
"oneOf" : [ {
"additionalProperties" : false,
"properties" : {
+ "checkpoint_filter_field_id" : {
+ "oneOf" : [ {
+ "minimum" : 1,
+ "type" : "integer"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "checkpoint_hi_value" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "checkpoint_lo_value" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
"end_time" : {
"oneOf" : [ { }, {
"type" : "null"
@@ -47910,6 +48625,13 @@
"type" : "null"
} ]
},
+ "metered_as" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
"run_method" : {
"type" : "string"
},
@@ -48058,9 +48780,17 @@
"type" : "null"
} ]
},
+ "target_table_id" : {
+ "oneOf" : [ {
+ "minimum" : 1,
+ "type" : "integer"
+ }, {
+ "type" : "null"
+ } ]
+ },
"updated_at" : { }
},
- "required" : [ "id", "name", "description", "source", "target", "source_type", "entity_id", "created_at", "updated_at", "creator_id", "collection_id", "dependency_analysis_version", "creator" ],
+ "required" : [ "id", "name", "description", "source", "target", "source_type", "entity_id", "created_at", "updated_at", "creator_id", "collection_id", "creator" ],
"type" : "object"
}
}
@@ -48204,9 +48934,6 @@
"minimum" : 1,
"type" : "integer"
},
- "dependency_analysis_version" : {
- "type" : "integer"
- },
"description" : {
"oneOf" : [ {
"type" : "string"
@@ -48225,10 +48952,39 @@
"minimum" : 1,
"type" : "integer"
},
+ "last_checkpoint_value" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
"last_run" : {
"oneOf" : [ {
"additionalProperties" : false,
"properties" : {
+ "checkpoint_filter_field_id" : {
+ "oneOf" : [ {
+ "minimum" : 1,
+ "type" : "integer"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "checkpoint_hi_value" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
+ "checkpoint_lo_value" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
"end_time" : {
"oneOf" : [ { }, {
"type" : "null"
@@ -48252,6 +49008,13 @@
"type" : "null"
} ]
},
+ "metered_as" : {
+ "oneOf" : [ {
+ "type" : "string"
+ }, {
+ "type" : "null"
+ } ]
+ },
"run_method" : {
"type" : "string"
},
@@ -48400,168 +49163,20 @@
"type" : "null"
} ]
},
- "updated_at" : { }
- },
- "required" : [ "id", "name", "description", "source", "target", "source_type", "entity_id", "created_at", "updated_at", "creator_id", "collection_id", "dependency_analysis_version", "creator" ],
- "type" : "object"
- },
- "type" : "array"
- }
- }
- },
- "description" : "Successful response"
- },
- "4XX" : {
- "description" : "Client error response"
- },
- "5XX" : {
- "description" : "Server error response"
- }
- },
- "summary" : "GET /api/transform/{id}/dependencies",
- "tags" : [ "/api/transform" ]
- }
- },
- "/api/transform/{id}/inspect" : {
- "get" : {
- "description" : "Phase 1: Discover available lenses for a transform.\n Returns structural metadata and available lens types.",
- "operationId" : "get-api-transform-id-inspect",
- "parameters" : [ {
- "description" : "value must be an integer greater than zero.",
- "in" : "path",
- "name" : "id",
- "required" : true,
- "schema" : {
- "minimum" : 1,
- "type" : "integer"
- }
- } ],
- "responses" : {
- "2XX" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "$ref" : "#/components/schemas/metabase.transforms-inspector.schema.discovery-response"
- }
- }
- },
- "description" : "Successful response"
- },
- "4XX" : {
- "description" : "Client error response"
- },
- "5XX" : {
- "description" : "Server error response"
- }
- },
- "summary" : "GET /api/transform/{id}/inspect",
- "tags" : [ "/api/transform" ]
- }
- },
- "/api/transform/{id}/inspect/{lens-id}" : {
- "get" : {
- "description" : "Phase 2: Get full lens contents for a transform.\n Returns sections, cards with dataset_query, and trigger definitions.\n Accepts optional params for drill lenses as query params.",
- "operationId" : "get-api-transform-id-inspect-lens-id",
- "parameters" : [ {
- "description" : "value must be an integer greater than zero.",
- "in" : "path",
- "name" : "id",
- "required" : true,
- "schema" : {
- "minimum" : 1,
- "type" : "integer"
- }
- }, {
- "in" : "path",
- "name" : "lens-id",
- "required" : true,
- "schema" : {
- "minLength" : 1,
- "type" : "string"
- }
- } ],
- "responses" : {
- "2XX" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "$ref" : "#/components/schemas/metabase.transforms-inspector.schema.lens"
- }
- }
- },
- "description" : "Successful response"
- },
- "4XX" : {
- "description" : "Client error response"
- },
- "5XX" : {
- "description" : "Server error response"
- }
- },
- "summary" : "GET /api/transform/{id}/inspect/{lens-id}",
- "tags" : [ "/api/transform" ]
- }
- },
- "/api/transform/{id}/inspect/{lens-id}/query" : {
- "post" : {
- "description" : "Execute a query in the context of a transform inspector lens.",
- "operationId" : "post-api-transform-id-inspect-lens-id-query",
- "parameters" : [ {
- "description" : "value must be an integer greater than zero.",
- "in" : "path",
- "name" : "id",
- "required" : true,
- "schema" : {
- "minimum" : 1,
- "type" : "integer"
- }
- }, {
- "in" : "path",
- "name" : "lens-id",
- "required" : true,
- "schema" : {
- "minLength" : 1,
- "type" : "string"
- }
- } ],
- "requestBody" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "properties" : {
- "lens_params" : {
- "oneOf" : [ {
- "additionalProperties" : { },
- "type" : "object"
- }, {
- "type" : "null"
- } ]
- },
- "query" : {
- "properties" : {
- "database" : {
+ "target_table_id" : {
"oneOf" : [ {
+ "minimum" : 1,
"type" : "integer"
}, {
"type" : "null"
} ]
- }
+ },
+ "updated_at" : { }
},
+ "required" : [ "id", "name", "description", "source", "target", "source_type", "entity_id", "created_at", "updated_at", "creator_id", "collection_id", "creator" ],
"type" : "object"
- }
- },
- "required" : [ "query" ],
- "type" : "object"
- }
- }
- }
- },
- "responses" : {
- "2XX" : {
- "content" : {
- "application/json" : {
- "schema" : {
- "$ref" : "#/components/schemas/metabase.query-processor.schema.query-result"
+ },
+ "type" : "array"
}
}
},
@@ -48574,14 +49189,14 @@
"description" : "Server error response"
}
},
- "summary" : "POST /api/transform/{id}/inspect/{lens-id}/query",
+ "summary" : "GET /api/transform/{id}/dependencies",
"tags" : [ "/api/transform" ]
}
},
- "/api/transform/{id}/merge-history" : {
- "get" : {
- "description" : "Get merge history for a transform. Returns all merge events that affected this transform,\n ordered by created_at descending (newest first).",
- "operationId" : "get-api-transform-id-merge-history",
+ "/api/transform/{id}/reset-checkpoint" : {
+ "post" : {
+ "description" : "Reset the stored checkpoint for an incremental transform.",
+ "operationId" : "post-api-transform-id-reset-checkpoint",
"parameters" : [ {
"description" : "value must be an integer greater than zero.",
"in" : "path",
@@ -48597,44 +49212,7 @@
"content" : {
"application/json" : {
"schema" : {
- "items" : {
- "properties" : {
- "commit_message" : {
- "type" : "string"
- },
- "created_at" : { },
- "id" : {
- "description" : "value must be an integer greater than zero.",
- "minimum" : 1,
- "type" : "integer"
- },
- "merging_user_id" : {
- "description" : "value must be an integer greater than zero.",
- "minimum" : 1,
- "type" : "integer"
- },
- "workspace_id" : {
- "oneOf" : [ {
- "description" : "value must be an integer greater than zero.",
- "minimum" : 1,
- "type" : "integer"
- }, {
- "type" : "null"
- } ]
- },
- "workspace_merge_id" : {
- "description" : "value must be an integer greater than zero.",
- "minimum" : 1,
- "type" : "integer"
- },
- "workspace_name" : {
- "type" : "string"
- }
- },
- "required" : [ "id", "workspace_merge_id", "commit_message", "workspace_id", "workspace_name", "merging_user_id", "created_at" ],
- "type" : "object"
- },
- "type" : "array"
+ "type" : "null"
}
}
},
@@ -48647,7 +49225,7 @@
"description" : "Server error response"
}
},
- "summary" : "GET /api/transform/{id}/merge-history",
+ "summary" : "POST /api/transform/{id}/reset-checkpoint",
"tags" : [ "/api/transform" ]
}
},
@@ -49442,6 +50020,48 @@
"tags" : [ "/api/user" ]
}
},
+ "/api/user/{id}/password-reset-url" : {
+ "post" : {
+ "description" : "Generate a password reset URL for a user. Admins can share this URL directly with the user.\n The link expires in 48 hours.",
+ "operationId" : "post-api-user-id-password-reset-url",
+ "parameters" : [ {
+ "description" : "value must be an integer greater than zero.",
+ "in" : "path",
+ "name" : "id",
+ "required" : true,
+ "schema" : {
+ "minimum" : 1,
+ "type" : "integer"
+ }
+ } ],
+ "responses" : {
+ "2XX" : {
+ "content" : {
+ "application/json" : {
+ "schema" : {
+ "properties" : {
+ "password_reset_url" : {
+ "type" : "string"
+ }
+ },
+ "required" : [ "password_reset_url" ],
+ "type" : "object"
+ }
+ }
+ },
+ "description" : "Successful response"
+ },
+ "4XX" : {
+ "description" : "Client error response"
+ },
+ "5XX" : {
+ "description" : "Server error response"
+ }
+ },
+ "summary" : "POST /api/user/{id}/password-reset-url",
+ "tags" : [ "/api/user" ]
+ }
+ },
"/api/user/{id}/reactivate" : {
"put" : {
"description" : "Reactivate user at `:id`",
@@ -49499,4 +50119,4 @@
"description" : "Metabase API",
"url" : ""
} ]
-}
+}
\ No newline at end of file
diff --git a/src/metabase/agent_api/api.clj b/src/metabase/agent_api/api.clj
index a69981ca248..2107306a84d 100644
--- a/src/metabase/agent_api/api.clj
+++ b/src/metabase/agent_api/api.clj
@@ -3,9 +3,7 @@
Endpoints are versioned (e.g., /v1/search) and use standard HTTP semantics."
(:require
[clojure.string :as str]
- [malli.util :as mut]
[metabase.agent-api.validation :as agent-api.validation]
- [metabase.agent-lib.core :as agent-lib]
[metabase.api.common :as api]
[metabase.api.macros :as api.macros]
[metabase.api.macros.scope :as scope]
@@ -369,209 +367,121 @@
;;; ------------------------------------------------ Construct Query -------------------------------------------------
-(mr/def ::program-request
- "Request body for /v2/query.
- An agent-lib structured program with `:source` and `:operations`. The top-level
- `:source` must reference a database entity (`table`, `card`, `dataset`, or
- `metric`); `context` and nested `program` sources are rejected at the HTTP
- boundary by [[evaluate-program-for-execution]] because they require an
- in-process evaluation context."
- agent-lib/program-schema)
-
-(def ^:private construct-query-prompt-max-length
- 10000)
-
-(def ^:private ConstructQueryPrompt
- (mut/update-properties
- [:and
- ms/NonBlankString
- [:string {:max construct-query-prompt-max-length}]]
- merge
- {:json-schema {:type "string"
- :minLength 1
- :maxLength construct-query-prompt-max-length
- :description "The user's exact original message, when available. Pass it as-is without summarizing or rewriting."}}))
-
(mr/def ::construct-query-request
- "Request body for /v2/construct-query. Same as program-request, with an optional prompt
- capturing the user's original intent when a caller has one."
- (mut/merge agent-lib/program-schema
- [:map
- [:prompt {:optional true} [:maybe ConstructQueryPrompt]]]))
+ "Request body for /v2/construct-query and the fresh-query branch of /v2/query.
+ A single `:query` key whose value is a JSON object matching
+ [[metabase.lib.schema/external-query]] — the canonical portable MBQL 5 wire format. The
+ query is fully self-describing: the database is derived from the first stage's
+ `source-table:` or `source-card:`, all field references are portable FKs
+ (`[<db-name>, <schema>, <table-name>, <column-name>]`), and there is no auxiliary
+ `source_entity` / `referenced_entities` envelope. See
+ `resources/metabot/prompts/tools/construct_notebook_query.md` for the full format reference
+ (including operators, joins, expressions, multi-stage queries, and FK conventions).
+
+ Closed map: any extra top-level keys (notably the legacy `source_entity` /
+ `referenced_entities` envelope from before the repr migration) are rejected with a 400 so
+ callers don't silently send fields the server ignores.
+
+ The inner `:query` value is intentionally typed as a plain `:map` at this boundary rather
+ than `::lib.schema/external-query`. Reasons:
+
+ 1. Deep MBQL-shape validation runs inside the representations pipeline
+ (`metabot.tools.construct/execute-representations-query` calls `repr/validate-query`
+ after the repair pass), so the boundary check would be redundant.
+
+ 2. The strict-tool manifest lint (`assert-optional-fields-nullable!`) walks every map
+ reachable from the tool input schema. `::external-query` references `::query`, which
+ carries several `:optional` keys (`:lib/metadata`, `:database`, `:settings`, …) that
+ are not `[:maybe ...]` — for sound reasons unrelated to this endpoint. Recursing into
+ them would force a wide schema change just to satisfy the lint at the agent boundary."
+ [:map {:closed true}
+ [:query {:tool/description (str "A Metabase MBQL 5 query as a JSON object. See the "
+ "`construct_notebook_query` tool for the format reference.")}
+ :map]
+ ;; The user's original message, when available, captured so `visualize_query` can later
+ ;; surface it back to the iframe alongside the query body for feedback submission. The MCP
+ ;; layer stores it with the handle (see `metabase.mcp.tools/make-store-construct-query-result`).
+ ;; Bounded at 10000 chars to match the constraint master enforced on the legacy program path.
+ [:prompt {:optional true} [:maybe [:string {:min 1 :max 10000}]]]])
(mr/def ::construct-query-response
- "Response containing a base64-encoded MBQL query and, when supplied, the original prompt for use with /v1/execute."
+ "Response containing a base64-encoded MBQL query for use with /v1/execute. The optional
+ `:prompt` echoes the request's prompt back so the MCP layer can store it with the
+ handle (see `metabase.mcp.tools/make-store-construct-query-result`)."
[:map
- [:query ms/NonBlankString]
- [:prompt {:optional true} ConstructQueryPrompt]])
-
-(def ^:private allowed-program-source-types
- "Top-level program source types that the HTTP boundary accepts. `context` and
- nested `program` sources require an in-process evaluation context and are
- rejected here."
- #{"table" "card" "dataset" "metric"})
-
-(def ^:private construct-query-tool-description
- "User-facing description for the `construct_query` MCP tool. Tuned to give the
- LLM enough structure to produce valid programs without reproducing the full
- reference — covers the program shape, canonical operator names, reference forms,
- and a few worked examples spanning the common patterns."
- (str
- "Construct a Metabase MBQL query from a structured program. The body structure is:\n"
- "`{\"source\": {...}, \"operations\": [...]}`\n"
- "For MCP calls, include `\"prompt\": \"<user's exact original message>\"` whenever you have the user's message; do not summarize or modify it.\n"
- "Returns `{\"query_handle\": \"<uuid>\"}` — pass `query_handle` to `execute_query` or `visualize_query`.\n"
- "For the full reference, read the `metabase://docs/construct-query.md` MCP resource.\n"
- "\n"
- "IMPORTANT: field IDs must come from entity-detail endpoints (`/v1/table/{id}`, `/v1/metric/{id}`). "
- "Do not invent IDs. The backend repairs minor mistakes (aliases, casing, over-wrapping) before validation, "
- "but the canonical names below always work.\n"
- "\n"
- "## Workflow\n"
- "1. Use `search_entities` / entity-detail tools to find the table/metric/model and its fields.\n"
- "2. Call `construct_query` with the program. Include the user's original `prompt` whenever available. You get back `{\"query_handle\": \"<uuid>\"}`.\n"
- "3. Pass `query_handle` to the follow-up `execute_query` or `visualize_query` call.\n"
- "Never embed IDs you did not read from a metadata endpoint — invented IDs will fail at execution.\n"
- "\n"
- "## Source\n"
- "One of `{\"type\": T, \"id\": N}`:\n"
- "- `table` — a database table\n"
- "- `card` — a saved question\n"
- "- `dataset` — a model (model card id)\n"
- "- `metric` — a metric (supplies its own aggregation and time dimension; extra aggregates usually unnecessary)\n"
- "\n"
- "## Top-level operations (applied in order)\n"
- "Each operation is `[\"op\", arg, ...]`:\n"
- "- `[\"filter\", clause]` — add a filter\n"
- "- `[\"aggregate\", agg-clause]` — add an aggregation\n"
- "- `[\"breakout\", ref-or-bucketed]` — add a grouping dimension\n"
- "- `[\"expression\", \"Name\", expr]` — define a named computed column (reference later with `expression-ref`)\n"
- "- `[\"with-fields\", [refs...]]` — restrict returned columns\n"
- "- `[\"order-by\", ref]` or `[\"order-by\", ref, \"asc\"|\"desc\"]` — sort\n"
- "- `[\"limit\", N]` — cap rows\n"
- "- `[\"join\", join-clause]` — join another entity\n"
- "- `[\"append-stage\"]` — start a new query stage (needed to filter on aggregated values)\n"
- "- `[\"with-page\", {\"page\": N, \"items\": M}]` — paginate\n"
- "\n"
- "## References (used as arguments inside operations)\n"
- "- `[\"field\", N]` — database field by id. Do NOT put options in a third slot (no `[\"field\", id, {...}]`); wrap instead\n"
- "- `[\"expression-ref\", \"Name\"]` — a named expression defined earlier\n"
- "- `[\"aggregation-ref\", N]` — the Nth `aggregate` defined earlier (0-based). REQUIRED when sorting by an aggregated value\n"
- "- `[\"measure\", N]` — a pre-defined measure on the source entity\n"
- "- `[\"with-temporal-bucket\", ref, unit]` — temporal bucketing. `unit` is one of: `minute` `hour` `day` `week` `month` `quarter` `year`. Also `day-of-week`, `hour-of-day`, etc. (extraction aliases)\n"
- "- `[\"with-binning\", ref, {\"strategy\": \"num-bins\"|\"bin-width\"|\"default\", ...}]` — numeric binning. E.g. `{\"strategy\": \"num-bins\", \"num-bins\": 10}`\n"
- "\n"
- "## Filter operators\n"
- "`=`, `!=`, `<`, `<=`, `>`, `>=`, `between`, `in`, `not-in`, `is-null`, `not-null`, `is-empty`, `not-empty`, "
- "`contains`, `does-not-contain`, `starts-with`, `ends-with`, `time-interval`, `and`, `or`, `not`, `segment`.\n"
- "Examples: `[\"=\", [\"field\", 101], \"active\"]`, `[\"between\", [\"field\", 305], \"2024-01-01\", \"2024-12-31\"]`, "
- "`[\"in\", [\"field\", 302], [10, 20, 30]]`, `[\"time-interval\", [\"field\", 305], -7, \"day\"]`.\n"
- "\n"
- "## Aggregation operators\n"
- "`count`, `sum`, `avg`, `min`, `max`, `distinct`, `median`, `stddev`, `var`, `percentile`, "
- "`count-where`, `sum-where`, `distinct-where`, `share`, `cum-count`, `cum-sum`. "
- "Examples: `[\"count\"]`, `[\"sum\", [\"field\", 302]]`, `[\"count-where\", [\"=\", [\"field\", 101], \"completed\"]]`.\n"
- "\n"
- "## Temporal helpers (for use in `expression` or as grouping)\n"
- "`get-year`, `get-quarter`, `get-month`, `get-week`, `get-day`, `get-day-of-week`, `get-hour`, `get-minute`, "
- "`datetime-add`, `datetime-diff`, `datetime-subtract`, `now`, `today`, `relative-datetime`, `absolute-datetime`, "
- "`with-temporal-bucket`, `convert-timezone`.\n"
- "\n"
- "## Examples\n"
- "Top 5 customers by revenue:\n"
- "```\n"
- "{\"source\": {\"type\": \"table\", \"id\": 42},\n"
- " \"operations\": [[\"aggregate\", [\"sum\", [\"field\", 302]]],\n"
- " [\"breakout\", [\"field\", 101]],\n"
- " [\"order-by\", [\"aggregation-ref\", 0], \"desc\"],\n"
- " [\"limit\", 5]]}\n"
- "```\n"
- "Monthly revenue from a metric (metric supplies the aggregation):\n"
- "```\n"
- "{\"source\": {\"type\": \"metric\", \"id\": 10},\n"
- " \"operations\": [[\"breakout\", [\"with-temporal-bucket\", [\"field\", 305], \"month\"]],\n"
- " [\"order-by\", [\"with-temporal-bucket\", [\"field\", 305], \"month\"], \"asc\"]]}\n"
- "```\n"
- "Filter on an aggregated value (requires `append-stage`):\n"
- "```\n"
- "{\"source\": {\"type\": \"table\", \"id\": 42},\n"
- " \"operations\": [[\"aggregate\", [\"sum\", [\"field\", 302]]],\n"
- " [\"breakout\", [\"field\", 101]],\n"
- " [\"append-stage\"],\n"
- " [\"filter\", [\">\", [\"aggregation-ref\", 0], 1000]]]}\n"
- "```\n"
- "Named expression referenced later:\n"
- "```\n"
- "{\"source\": {\"type\": \"table\", \"id\": 42},\n"
- " \"operations\": [[\"expression\", \"Discount\", [\"-\", [\"field\", 302], [\"field\", 303]]],\n"
- " [\"aggregate\", [\"sum\", [\"expression-ref\", \"Discount\"]]]]}\n"
- "```\n"
- "Previous-period comparison with `offset` (stay in the SAME stage — do NOT add `append-stage`):\n"
- "```\n"
- "{\"source\": {\"type\": \"table\", \"id\": 42},\n"
- " \"operations\": [[\"aggregate\", [\"sum\", [\"field\", 302]]],\n"
- " [\"aggregate\", [\"offset\", [\"sum\", [\"field\", 302]], -1]],\n"
- " [\"breakout\", [\"with-temporal-bucket\", [\"field\", 305], \"month\"]]]}\n"
- "```\n"
- "\n"
- "## Rules & common pitfalls\n"
- "Stage boundaries (most common source of errors):\n"
- "- Filtering on an aggregated value REQUIRES `append-stage` between the aggregate/breakout and the filter "
- "(see the \"filter on aggregated value\" example). Without it, `aggregation-ref` resolution fails in the same stage.\n"
- "- Defining an `expression` that uses `aggregation-ref` also REQUIRES `append-stage` first.\n"
- "- EXCEPTION: `offset` (previous-period comparison) stays in the same stage as its base aggregation and breakout — do NOT add `append-stage` for it.\n"
- "\n"
- "Refs & shapes:\n"
- "- Aggregation helpers take field refs, not bare IDs: `[\"sum\", [\"field\", 201]]`, never `[\"sum\", 201]`.\n"
- "- To sort by an aggregated value, use `[\"aggregation-ref\", N]` — not the original expression.\n"
- "- Do NOT put options in a third slot of `field` (no `[\"field\", id, {...}]`). Wrap instead: `[\"with-temporal-bucket\", [\"field\", id], \"month\"]` or `[\"with-binning\", [\"field\", id], {...}]`.\n"
- "- `case` takes `[[condition, value], ...]` branches and an optional bare fallback as the THIRD arg — do not wrap it as `{\"default\": ...}`. Omit the third arg when there is no fallback.\n"
- "- JSON objects appear only where a helper explicitly calls for one (e.g. `with-page`, `with-binning`). Everywhere else, use operator tuples.\n"
- "\n"
- "Joins & related tables:\n"
- "- If the source table's detail response already surfaces a related table's fields, use those field refs directly — no explicit join needed.\n"
- "- Reach for `join` + `with-join-conditions` only for custom aliases, self-joins, explicit joined-field selection, or when direct related-field refs are unavailable.\n"
- "- If an explicit join returns a permission error, the underlying table is not accessible — surface the error, do not retry with implicit refs.\n"
- "\n"
- "Metrics & dates:\n"
- "- A `metric` source already provides its own aggregation and time dimension. Add only the additional breakouts/filters you need.\n"
- "- When the user asks for an exact year (e.g. 2024), use `[\"=\", [\"field\", year_field], 2024]` or a `between` with explicit dates — not relative filters like `time-interval`.\n"))
-
-(defn- evaluate-program-to-live-query
- "Resolve a program's source entity, evaluate the program via agent-lib, and return
- the live lib query (with lib metadata attached)."
- [program]
- (let [source-type (get-in program [:source :type])]
- (api/check (contains? allowed-program-source-types source-type)
- [400 (str "top-level program source must be one of: "
- (str/join ", " (sort allowed-program-source-types)))]))
- (let [source-entity (metabot-construct/program-source->source-entity (:source program))
- result (metabot-construct/execute-program source-entity nil program)]
- (get-in result [:structured-output :query])))
-
-(defn- evaluate-program-for-execution
- "Evaluate a program and return a plain MBQL 5 query map suitable for serialization
- into a continuation token and execution by the QP."
- [program]
- (lib/prepare-for-serialization (evaluate-program-to-live-query program)))
+ [:query ms/NonBlankString]
+ [:prompt {:optional true} [:maybe ms/NonBlankString]]])
+
+(defn- evaluate-external-query-to-live-query
+ "Run the representations pipeline (validate → convert → repair → resolve) on a request body
+ and return the resolved MBQL 5 lib query (with `:lib/metadata` attached).
+
+ The pipeline raises `:agent-error?` ex-data on any LLM-input failure (unknown DB, unknown
+ table, ambiguous FK, etc.); we let those propagate so [[api.macros/defendpoint]] surfaces
+ them with the appropriate 4xx status code instead of a 500."
+ [body]
+ (-> (metabot-construct/execute-representations-query (:query body))
+ (get-in [:structured-output :query])))
+
+(defn- evaluate-external-query-for-execution
+ "Evaluate a request body and return a plain MBQL 5 query map suitable for serialization into
+ a continuation token and execution by the QP."
+ [body]
+ (lib/prepare-for-serialization (evaluate-external-query-to-live-query body)))
(api.macros/defendpoint :post "/v2/construct-query" :- ::construct-query-response
- "Construct an MBQL query from a structured agent-lib program.
+ "Construct an MBQL query from a portable MBQL 5 representations JSON payload.
- The body is the program itself: a JSON object with `source` (identifying the
- table/card/dataset/metric to query), `operations` (an array of operator
- tuples), and `prompt` (the user's original request). Returns a base64-encoded
- MBQL query that can be executed via /v1/execute. See the agent_api reference
- for the full program syntax."
+ The body is `{\"query\": <external-query>}` where `<external-query>` is a JSON object
+ matching `::lib.schema/external-query` \u2014 see the `construct_notebook_query` tool
+ documentation for the format reference. Returns a base64-encoded MBQL query that can be
+ executed via /v1/execute or paginated via /v2/query."
{:scope metabot/agent-query-construct
:tool {:name "construct_query"
- :description construct-query-tool-description
+ ;; Condensed inline summary so LLMs see the shape directly in `tools/list`. Full
+ ;; grammar lives in the `construct_notebook_query` tool prompt.
+ :description
+ (str "Construct a Metabase MBQL 5 query as JSON. Pass the body "
+ "`{\"query\": <object>}`; returns `{\"query_handle\": \"<uuid>\"}` to feed "
+ "`execute_query` or `visualize_query`.\n"
+ "\n"
+ "Workflow: use search / entity_details first to discover the exact database, "
+ "schema, table, and column NAMES (not numeric IDs). Never invent identifiers.\n"
+ "\n"
+ "Shape: every clause is `[\"op\", {}, ...args]` with a MANDATORY empty options "
+ "map at position 1. Every field reference is "
+ "`[\"field\", {}, [<db-name>, <schema-or-null>, <table-name>, <column-name>]]` "
+ "(4-segment portable FK string array, NOT a numeric id). Cross-stage refs use "
+ "a bare column-name string in the third slot: `[\"field\", {}, \"count\"]`.\n"
+ "\n"
+ "Top level: `{\"lib/type\": \"mbql/query\", \"stages\": [...]}`. Each stage has "
+ "`\"lib/type\": \"mbql.stage/mbql\"` plus either `source-table` (portable FK) "
+ "or `source-card` (entity_id string) on the FIRST stage only; later stages "
+ "implicitly read the previous stage's output. Per-stage clause keys: "
+ "`filters`, `aggregation`, `breakout`, `expressions`, `fields`, `joins`, "
+ "`order-by`, `limit`.\n"
+ "\n"
+ "Minimal example (count of orders by month):\n"
+ "```\n"
+ "{\"query\": {\"lib/type\": \"mbql/query\",\n"
+ " \"stages\": [{\"lib/type\": \"mbql.stage/mbql\",\n"
+ " \"source-table\": [\"Sample Database\", \"PUBLIC\", \"ORDERS\"],\n"
+ " \"aggregation\": [[\"count\", {}]],\n"
+ " \"breakout\": [[\"field\", {\"temporal-unit\": \"month\"},\n"
+ " [\"Sample Database\", \"PUBLIC\", \"ORDERS\", \"CREATED_AT\"]]]}]}}\n"
+ "```\n"
+ "\n"
+ "Common pitfalls: (1) forgetting the `{}` options map; (2) writing numeric "
+ "ids where a portable FK is required; (3) putting a post-aggregation filter "
+ "(`[\">\", {}, [\"aggregation\", {}, 0], 10]`) alongside `order-by` / `limit` "
+ "in the same stage \u2014 split into two stages explicitly. See the "
+ "`construct_notebook_query` tool prompt for the full grammar, operator "
+ "catalog, joins, expressions, and multi-stage examples.")
:annotations {:read-only? true :idempotent? true}}}
[_route-params
_query-params
- {:keys [prompt] :as request} :- ::construct-query-request]
- (let [program (dissoc request :prompt)
- query (evaluate-program-for-execution program)]
+ {:keys [prompt] :as body} :- ::construct-query-request]
+ (let [query (evaluate-external-query-for-execution body)]
(cond-> {:query (-> query json/encode u/encode-base64)}
prompt (assoc :prompt prompt))))
@@ -589,9 +499,9 @@
(defn- decode-continuation-token
"Decode a base64-encoded continuation token into {:query ... :pagination ...}.
The token is client-supplied, so sanity-check the pagination ints to turn
- garbage into a 400 rather than a downstream 500. This is robustness, not a
- security boundary — a caller can always issue a fresh program to run any
- query they want."
+ garbage into a 400 rather than a downstream 500. Permission re-validation on
+ the embedded query happens in [[check-token-query-permissions!]] — a token
+ doesn't grant access the bearer wouldn't otherwise have."
[token]
(let [decoded (-> token u/decode-base64 json/decode+kw)
{:keys [limit page]} (:pagination decoded)]
@@ -657,40 +567,64 @@
:max-results-bare-rows page-size}))
(mr/def ::query-request
- "Request body for /v2/query. Accepts either a structured program or a continuation_token."
+ "Request body for /v2/query. Accepts either a fresh-query payload (`{:query <external-query>}`,
+ same shape as /v2/construct-query) or a `:continuation_token` from a prior response.
+
+ Both branches are closed maps: extra top-level keys (e.g. the legacy
+ `source_entity` / `referenced_entities` envelope, or sending `:query` and
+ `:continuation_token` simultaneously) are rejected with a 400."
[:multi {:dispatch (fn [m]
- (if (:continuation_token m) :continuation :program))}
- [:continuation [:map [:continuation_token ms/NonBlankString]]]
- [:program ::program-request]])
+ (if (:continuation_token m) :continuation :fresh))}
+ [:continuation [:map {:closed true} [:continuation_token ms/NonBlankString]]]
+ [:fresh ::construct-query-request]])
+
+(defn- check-token-query-permissions!
+ "Re-validate query permissions on the continuation-token path.
+
+ The token body is client-supplied and could in principle name a different source table than
+ the one the fresh `/v2/query` call was authorized against (a user's data perms can also
+ change between pages). The QP middleware would catch this at execution time, but running
+ the explicit `api/query-check` first gives a cleaner 403 and avoids spinning up the
+ streaming response just to abort."
+ [query-map]
+ (when-let [table-id (get-in query-map [:stages 0 :source-table])]
+ (when (int? table-id)
+ (api/query-check :model/Table table-id))))
(defn- initial-page-state
"Normalize the two /v2/query entry points into a single {:query :total-limit :page}
- shape. A fresh program evaluates the user's program and computes a total-row budget
- from its `:limit`; a continuation token carries that state from a prior response."
+ shape. A fresh request body is evaluated through the representations pipeline and the
+ total-row budget is derived from the resolved query's `:limit`; a continuation token
+ carries that state from a prior response (and re-validates query permissions, since the
+ token is client-supplied and per-user permissions can change between pages)."
[body]
(if-let [token (:continuation_token body)]
(let [{:keys [query pagination]} (decode-continuation-token token)]
+ (check-token-query-permissions! query)
{:query query :total-limit (:limit pagination) :page (:page pagination)})
- (let [live-query (evaluate-program-to-live-query body)]
+ (let [live-query (evaluate-external-query-to-live-query body)]
{:query (lib/prepare-for-serialization live-query)
:total-limit (total-row-limit live-query)
:page 1})))
(api.macros/defendpoint :post "/v2/query"
:- (streaming-response/streaming-response-schema ::query-response)
- "Execute a structured program and stream the results, with continuation-token pagination.
+ "Execute a portable MBQL 5 representations JSON query and stream the results, with
+ continuation-token pagination.
- Accepts either a program (same shape as /v2/construct-query) or a
- `continuation_token` from a previous response. Returns results with column
- metadata and an optional `continuation_token` for fetching the next page."
+ Accepts either a JSON body (same shape as /v2/construct-query) or a `continuation_token`
+ from a previous response. Returns results with column metadata and an optional
+ `continuation_token` for fetching the next page."
{:scope "agent:query"
:tool {:name "query"
:title "Query Tables and Metrics"
- :description (str "Execute a structured program and return results with column metadata. "
- "If more rows are available the response includes a continuation_token "
- "— pass it back to fetch the next page. Body is either a program (same "
- "shape as construct_query) or {\"continuation_token\": \"...\"}. See the "
- "`metabase://docs/construct-query.md` resource for program syntax.")
+ :description (str "Execute a Metabase query and return results with column "
+ "metadata. If more rows are available, the response includes a "
+ "continuation_token — pass it back to get the next page.\n\n"
+ "The body is either `{\"query\": <object>}` (same shape as "
+ "construct_query; see the `construct_notebook_query` tool for "
+ "the format reference) or `{\"continuation_token\": \"...\"}` "
+ "from a previous response.")
:annotations {:read-only? true}}}
[_route-params
_query-params
@@ -761,9 +695,7 @@
"row count, and execution time. Use this when the user explicitly asks for raw data, "
"rows, columns, counts, metadata, or programmatic query results. If the user asks to "
"show, display, visualize, plot, chart, or present the result, use visualize_query "
- "instead. "
- "Pass `query_handle` (preferred) from construct_query rather than constructing the "
- "base64 query yourself.")
+ "instead.")
:annotations {:read-only? true :idempotent? true}}}
[_route-params
_query-params
diff --git a/src/metabase/agent_api/reference.md b/src/metabase/agent_api/reference.md
index cfd8c3fe3fe..425332b8f34 100644
--- a/src/metabase/agent_api/reference.md
+++ b/src/metabase/agent_api/reference.md
@@ -14,8 +14,9 @@ Base path: /api/agent
(e.g., "Total Revenue"). Metrics are stored in collections and can be used
as a data source in the API. They have a fixed aggregation, but can be
filtered and grouped by their queryable dimensions. Use /v1/metric/{id} to
- inspect a metric's dimensions, and POST /v2/construct-query with a program
- whose `source` is `{"type": "metric", "id": <id>}` to query one.
+ inspect a metric's dimensions, and reference the metric in a representations
+ JSON query as `"aggregation": [["metric", {}, "<portable_entity_id>"]]` (see
+ the representations format reference linked from /v2/construct-query).
- **Measures**: Lightweight, reusable aggregation expressions (e.g.,
`SUM(total)`) associated with a specific table. Unlike metrics, measures are
not standalone queries — they are building blocks that can be referenced in
@@ -285,239 +286,96 @@ Response:
### POST /v2/construct-query
-Construct an MBQL query from a structured agent-lib program. Returns a
+Construct an MBQL query from a representations JSON payload. Returns a
base64-encoded query string to pass to `/v1/execute`.
-**Important**: All field IDs used in operations must come from the detail
-endpoints (`/v1/table/{id}` or `/v1/metric/{id}`). Always fetch entity details
-first.
-
-The request body **is** the program — there is no envelope. A program is a
-JSON object with two keys:
-
-- `source` — identifies the entity to query (`table`, `card`, `dataset`, or
- `metric` plus an `id`).
-- `operations` — an ordered array of operator tuples to apply on top of the
- source. Each operation is itself an array: `["operator", arg1, arg2, ...]`.
-
-The agent-lib backend automatically repairs small mistakes (operator aliases,
-casing, scalar wrapping) before validation, so you don't need to be perfectly
-precise about every detail — but the canonical operator names listed below
-will always work.
-
-#### Request format
+#### Request body
```json
-{
- "source": {"type": "table", "id": 42},
- "operations": [
- ["filter", [">", ["field", 302], 100]],
- ["aggregate", ["sum", ["field", 302]]],
- ["breakout", ["with-temporal-bucket", ["field", 305], "month"]],
- ["order-by", ["aggregation-ref", 0], "desc"],
- ["limit", 100]
- ]
-}
+{"query": <external-query-object>}
```
-For a metric source (the metric supplies its own aggregation, so additional
-aggregates are usually unnecessary):
+The `query` value is a JSON object matching `::lib.schema/external-query` —
+Metabase's canonical MBQL 5 *portable representations format*, a
+self-describing serialization that uses portable FKs
+(`["<db-name>", "<schema>", "<table-name>", "<column-name>"]`) instead of
+numeric IDs, encodes operators as `["<name>", {opts}, <args>...]` clauses, and
+derives the application database from the first stage's `source-table` /
+`source-card`. There is **no** auxiliary `source_entity` envelope, and no
+standalone integer IDs.
-```json
-{
- "source": {"type": "metric", "id": 10},
- "operations": [
- ["filter", [">", ["field", 305], "2024-01-01"]],
- ["breakout", ["with-temporal-bucket", ["field", 305], "month"]]
- ]
-}
-```
+The full format reference — including every operator (filters, aggregations,
+expressions, temporal helpers), join syntax, multi-stage queries, FK
+conventions, and worked examples — lives in the `construct_notebook_query`
+tool prompt:
-#### Response
-
-```json
-{"query": "eyJkYXRhYmFzZSI6MSwi..."}
-```
-
-#### Source types
-
-The top-level `source` must be one of these — `context` and nested `program`
-sources are reserved for in-process callers and are rejected at the HTTP
-boundary.
-
-| Type | Meaning |
-|-----------|---------------------------------------------------------------|
-| `table` | Query a database table directly (`id` is a table ID) |
-| `card` | Query a saved question (`id` is a card ID) |
-| `dataset` | Query a model (`id` is the model's card ID) |
-| `metric` | Query a metric, inheriting its aggregation and time dimension |
-
-#### Top-level operations
-
-Each operation is an array starting with the operator name. Operations are
-applied in order to the query stage produced from `source`.
-
-| Operator | Shape | Description |
-|------------------------|-------------------------------------------------|----------------------------------------------------------|
-| `filter` | `["filter", clause]` | Add a filter clause to the current stage |
-| `aggregate` | `["aggregate", agg-clause]` | Add an aggregation |
-| `breakout` | `["breakout", ref-or-bucketed]` | Add a grouping dimension |
-| `expression` | `["expression", "Name", expr]` | Define a named computed column |
-| `with-fields` | `["with-fields", [refs]]` | Restrict the returned columns |
-| `order-by` | `["order-by", ref]` or `["order-by", ref, dir]` | Sort by a field, expression-ref, or aggregation-ref |
-| `limit` | `["limit", N]` | Cap the number of returned rows |
-| `join` | `["join", join-clause]` | Join another table or card |
-| `append-stage` | `["append-stage"]` | Start a new query stage (e.g. for post-aggregation ops) |
-| `with-page` | `["with-page", {"page": N, "items": M}]` | Apply pagination on the current stage |
-
-The full canonical list lives in
-[src/metabase/agent_lib/capabilities/catalog/](../agent_lib/capabilities/catalog/).
-
-#### References
-
-References are nested operator forms used inside operations to point at fields,
-expressions, or earlier aggregations.
-
-| Form | Meaning |
-|-----------------------------------|--------------------------------------------------------|
-| `["field", N]` | Reference a database field by ID |
-| `["expression-ref", "Name"]` | Reference a named expression defined earlier |
-| `["aggregation-ref", N]` | Reference the Nth aggregation defined earlier (0-based)|
-| `["measure", N]` | Reference a pre-defined measure on the source entity |
-| `["with-temporal-bucket", r, b]` | Bucket a temporal field by `b` (`day`, `month`, …) |
-
-#### Filter operators (used inside `["filter", …]`)
-
-| Operator | Example |
-|----------------------|------------------------------------------------------|
-| `=`, `!=` | `["=", ["field", 101], "active"]` |
-| `<`, `<=`, `>`, `>=` | `[">", ["field", 302], 100]` |
-| `between` | `["between", ["field", 305], "2024-01-01", "2024-12-31"]` |
-| `in`, `not-in` | `["in", ["field", 302], [10, 20, 30]]` |
-| `is-null`, `not-null`| `["is-null", ["field", 101]]` |
-| `is-empty`, `not-empty` | `["is-empty", ["field", 101]]` |
-| `contains`, `does-not-contain` | `["contains", ["field", 303], "acme"]` |
-| `starts-with`, `ends-with` | `["starts-with", ["field", 303], "acme"]` |
-| `time-interval` | `["time-interval", ["field", 305], -7, "day"]` |
-| `and`, `or`, `not` | `["and", filter1, filter2]` |
-| `segment` | `["segment", 5]` — apply a pre-defined segment |
-
-#### Aggregation operators (used inside `["aggregate", …]`)
-
-`count`, `sum`, `avg`, `min`, `max`, `distinct`, `median`, `stddev`, `var`,
-`percentile`, `count-where`, `sum-where`, `distinct-where`, `share`,
-`cum-count`, `cum-sum`.
-
-```json
-["aggregate", ["count"]]
-["aggregate", ["sum", ["field", 302]]]
-["aggregate", ["count-where", ["=", ["field", 101], "completed"]]]
-```
-
-#### Temporal helpers (commonly used in `expression` and `breakout`)
-
-`get-year`, `get-quarter`, `get-month`, `get-week`, `get-day`,
-`get-day-of-week`, `get-hour`, `get-minute`, `datetime-add`, `datetime-diff`,
-`datetime-subtract`, `now`, `today`, `relative-datetime`, `absolute-datetime`,
-`with-temporal-bucket`, `convert-timezone`.
-
-#### Worked examples
-
-**Top 5 customers by revenue**
-
-```json
-{
- "source": {"type": "table", "id": 42},
- "operations": [
- ["aggregate", ["sum", ["field", 302]]],
- ["breakout", ["field", 101]],
- ["order-by", ["aggregation-ref", 0], "desc"],
- ["limit", 5]
- ]
-}
-```
+ `resources/metabot/prompts/tools/construct_notebook_query.md`
-**Conditional sum with a named expression**
+Minimal example:
```json
{
- "source": {"type": "table", "id": 42},
- "operations": [
- ["expression", "Discount", ["-", ["field", 302], ["field", 303]]],
- ["aggregate", ["sum", ["expression-ref", "Discount"]]]
- ]
+ "query": {
+ "lib/type": "mbql/query",
+ "stages": [
+ {
+ "lib/type": "mbql.stage/mbql",
+ "source-table": ["Sample Database", "PUBLIC", "ORDERS"],
+ "aggregation": [["sum", {}, ["field", {}, ["Sample Database", "PUBLIC", "ORDERS", "TOTAL"]]]],
+ "breakout": [["field", {}, ["Sample Database", "PUBLIC", "PEOPLE", "STATE"]]],
+ "limit": 100
+ }
+ ]
+ }
}
```
-**Orders per month using a metric**
+#### Response
```json
-{
- "source": {"type": "metric", "id": 10},
- "operations": [
- ["breakout", ["with-temporal-bucket", ["field", 305], "month"]]
- ]
-}
+{"query": "eyJkYXRhYmFzZSI6MSwi..."}
```
-**Multi-stage: filter on an aggregated value**
-
-```json
-{
- "source": {"type": "table", "id": 42},
- "operations": [
- ["aggregate", ["sum", ["field", 302]]],
- ["breakout", ["field", 101]],
- ["append-stage"],
- ["filter", [">", ["aggregation-ref", 0], 1000]]
- ]
-}
-```
+The value is a base64-encoded resolved MBQL 5 query map suitable for
+`/v1/execute` or for embedding in a `/v2/query` continuation token. Treat it
+as opaque.
#### Error responses
-Validation, repair, and resolution errors are returned as `400 Bad Request`
-with a structured JSON body:
-
-```json
-{
- "status-code": 400,
- "error": "invalid-generated-program",
- "path": "operations[2].field_id",
- "details": "operations[2].field_id: field 12345 is not accessible",
- "recovery": {
- "available": ["field 1001", "field 1002"],
- "suggestion": "Did you mean field 1001?"
- }
-}
-```
-
-A non-existent table, card, or metric in `source` returns `404 Not Found`.
+The representations pipeline distinguishes user-facing input errors (the
+LLM-/agent-authored query can't be resolved or doesn't validate) from internal
+failures. Input errors are returned as `400 Bad Request` with the originating
+ex-data fields surfaced in the body — most commonly `error`, `path`, and
+`candidates`. Examples:
+
+| `error` | When |
+|-------------------------------|-----------------------------------------------------------------------------------|
+| `unknown-database` | First-stage source uses a database name that doesn't exist |
+| `unknown-table` | Portable FK names a table that doesn't exist (with closest-match candidates) |
+| `unknown-field` | Portable FK names a column that doesn't exist on the resolved table |
+| `unknown-card` | `source-card:` / `[metric, {}, <eid>]` references a missing entity_id |
+| `missing-source-in-first-stage` | Neither `source-table:` nor `source-card:` was supplied on `stages[0]` |
+| `ambiguous-fk` / `no-fk-path` | An implicit-join field reference can't be auto-wired (multiple FKs / no FK) |
+| `uri-in-source-table` | `source-table:` got a `metabase://...` URI instead of a portable FK |
+
+All input errors carry `:agent-error? true` in the underlying ex-data; LLM
+callers are expected to read the message and self-correct on the next turn.
### POST /v2/query
Combined construct-and-execute endpoint with built-in pagination via
continuation tokens.
-The body is either:
-- A program (same shape as `/v2/construct-query`), **or**
-- `{"continuation_token": "..."}` returned from a previous response.
-
-Pagination is automatic. The per-page row limit is taken from your program's
-`["limit", N]` operation if present, otherwise defaults to 200, and is hard-
-capped at 200 rows for memory and LLM-context safety. If the page is full and
-more rows may exist, the response includes a `continuation_token` you can
-post back to fetch the next page.
+The request body is either:
+- A representations JSON payload (`{"query": <external-query-object>}`, same
+ shape as `/v2/construct-query`), **or**
+- A continuation token from a previous response: `{"continuation_token": "..."}`.
-```json
-{
- "source": {"type": "table", "id": 42},
- "operations": [
- ["order-by", ["field", 101]],
- ["limit", 50]
- ]
-}
-```
+Pagination is automatic. The per-page row limit is taken from the query's
+`limit:` field if present, otherwise defaults to 200, and is hard-capped at 200
+rows per page for memory and LLM-context safety. If the page is full and more
+rows may exist, the response includes a `continuation_token` you post back to
+fetch the next page.
Response (HTTP 202, streaming):
@@ -677,27 +535,28 @@ Response:
## Typical workflow
1. **Search** — POST /v1/search to find relevant tables or metrics
-2. **Inspect** — GET /v1/table/{id} or /v1/metric/{id} to get field IDs and
- understand the schema
+2. **Inspect** — GET /v1/table/{id} or /v1/metric/{id} to get the column-name /
+ schema / portable-FK info needed to write a query
3. **Explore field values** — GET /v1/table/{id}/field/{field-id}/values if
you need to know valid filter values or field statistics
-4. **Build query** — POST /v2/construct-query with a structured program
- (`source` + `operations`)
+4. **Build query** — POST /v2/construct-query with a representations JSON
+ payload (`{"query": <external-query-object>}`); see the
+ `construct_notebook_query` tool prompt for the format reference
5. **Execute** — POST /v1/execute with the base64-encoded query, or use
POST /v2/query to construct and execute in one round-trip with pagination
-6. **Iterate** — Adjust the program and repeat steps 4-5
+6. **Iterate** — Adjust the query and repeat steps 4-5
7. **Save (optional)** — POST /v1/question to persist the query as a card, and
POST /v1/dashboard to assemble saved cards into a dashboard
## Error handling
-| HTTP Status | Meaning |
-|-------------|---------------------------------------------------------------|
-| 200 | Success (GET endpoints, construct-query) |
-| 202 | Success (execute / query — streaming response) |
-| 400 | Invalid program (validation, repair, or resolution failure) |
-| 401 | Authentication failure |
-| 403 | Insufficient permissions |
-| 404 | Entity not found |
+| HTTP Status | Meaning |
+|-------------|----------------------------------------------------------------------|
+| 200 | Success (GET endpoints, construct-query) |
+| 202 | Success (execute / query — streaming response) |
+| 400 | Invalid representations query (validation, repair, or resolution failure; `:agent-error?` paths) |
+| 401 | Authentication failure |
+| 403 | Insufficient permissions |
+| 404 | Entity not found (GET endpoints only) |
---
diff --git a/src/metabase/agent_lib/capabilities.clj b/src/metabase/agent_lib/capabilities.clj
deleted file mode 100644
index 266f97ebfd5..00000000000
--- a/src/metabase/agent_lib/capabilities.clj
+++ /dev/null
@@ -1,120 +0,0 @@
-(ns metabase.agent-lib.capabilities
- "Shared capability registry for the structured MBQL program path."
- (:require
- [metabase.agent-lib.capabilities.catalog :as catalog]
- [metabase.agent-lib.capabilities.derived :as derived]
- [metabase.agent-lib.capabilities.synthetic :as capabilities.synthetic]
- [metabase.util.malli.registry :as mr]))
-
-(set! *warn-on-reflection* true)
-
-(def raw-capability-catalog
- "Ordered structured-program capability metadata used for repair, validation, and prompts."
- catalog/raw-capability-catalog)
-
-(def ^:private guidance-keys
- [:prompt-forms
- :prompt-notes
- :shape
- :example
- :retry-shape
- :retry-example
- :retry-notes])
-
-(def ^:private capability-guidance-schema
- [:map {:closed true}
- [:prompt-forms {:optional true} [:sequential :string]]
- [:prompt-notes {:optional true} [:sequential :string]]
- [:shape {:optional true} :string]
- [:example {:optional true} :string]
- [:retry-shape {:optional true} :string]
- [:retry-example {:optional true} :string]
- [:retry-notes {:optional true} [:sequential :string]]])
-
-(def ^:private capability-entry-schema
- [:map {:closed true}
- [:op symbol?]
- [:kind [:enum :top-level :nested]]
- [:binding {:optional true} ifn?]
- [:group {:optional true} keyword?]
- [:arities {:optional true} [:set int?]]
- [:runtime-provided? {:optional true} boolean?]
- [:guidance {:optional true} capability-guidance-schema]])
-
-(defn- split-guidance
- [capability]
- (let [guidance (not-empty (select-keys capability guidance-keys))]
- (cond-> (apply dissoc capability guidance-keys)
- guidance (assoc :guidance guidance))))
-
-(def capability-catalog
- "Ordered structured-program capability metadata keyed into structural fields plus nested guidance."
- (mapv split-guidance raw-capability-catalog))
-
-(defn- validate-capability-catalog!
- []
- (doseq [capability capability-catalog]
- (when-not (mr/validate capability-entry-schema capability)
- (throw (ex-info "Invalid structured capability catalog entry."
- {:capability capability
- :schema capability-entry-schema
- :explain (mr/explain capability-entry-schema capability)})))))
-
-(validate-capability-catalog!)
-
-(defn guidance
- "Return prompt and retry guidance metadata for a capability entry."
- [capability]
- (derived/guidance capability))
-
-(defn prompt-forms
- "Return documented prompt forms for a capability entry."
- [capability]
- (derived/prompt-forms capability))
-
-(defn prompt-notes
- "Return documented prompt notes for a capability entry."
- [capability]
- (derived/prompt-notes capability))
-
-(defn guidance-shape
- "Return the documented canonical call shape for a capability entry."
- [capability]
- (derived/guidance-shape capability))
-
-(defn guidance-example
- "Return the documented example program fragment for a capability entry."
- [capability]
- (derived/guidance-example capability))
-
-(def capability-by-op
- "Capability metadata keyed by operator symbol."
- (derived/capability-by-op capability-catalog))
-
-(def fixed-arities
- "Structured helper arities keyed by operator symbol."
- (derived/fixed-arities capability-catalog))
-
-(def trusted-helper-bindings
- "Trusted helper implementations keyed by operator symbol."
- (derived/trusted-helper-bindings capability-catalog))
-
-(def query-transform-symbols
- "Top-level structured query-transform operator symbols."
- (derived/query-transform-symbols capability-catalog))
-
-(def helper-symbols
- "All structured helper symbols accepted by the evaluator."
- (derived/helper-symbols capability-catalog capabilities.synthetic/synthetic-helper-symbols))
-
-(def nested-operator-values
- "String names for nested structured helper operators."
- (derived/nested-operator-values capability-catalog))
-
-(def top-level-operator-values
- "String names for top-level structured operations."
- (derived/top-level-operator-values capability-catalog))
-
-(def operator-guidance-catalog
- "Retry guidance keyed by canonical operator name."
- (derived/operator-guidance-catalog capability-catalog))
diff --git a/src/metabase/agent_lib/capabilities/catalog.clj b/src/metabase/agent_lib/capabilities/catalog.clj
deleted file mode 100644
index acd26dac3fa..00000000000
--- a/src/metabase/agent_lib/capabilities/catalog.clj
+++ /dev/null
@@ -1,29 +0,0 @@
-(ns metabase.agent-lib.capabilities.catalog
- "Aggregated structured-program capability catalog split into smaller
- review-friendly groups."
- (:require
- [metabase.agent-lib.capabilities.catalog.aggregation :as aggregation]
- [metabase.agent-lib.capabilities.catalog.expressions :as expressions]
- [metabase.agent-lib.capabilities.catalog.filtering :as filtering]
- [metabase.agent-lib.capabilities.catalog.joins :as joins]
- [metabase.agent-lib.capabilities.catalog.ordering :as ordering]
- [metabase.agent-lib.capabilities.catalog.sources :as sources]
- [metabase.agent-lib.capabilities.catalog.top-level :as top-level]))
-
-(set! *warn-on-reflection* true)
-
-(def grouped-capability-catalog
- "Capability entries grouped into review-friendly sections."
- [{:group :top-level :capabilities top-level/capabilities}
- {:group :sources :capabilities sources/capabilities}
- {:group :filtering :capabilities filtering/capabilities}
- {:group :aggregation :capabilities aggregation/capabilities}
- {:group :breakout-ordering :capabilities ordering/capabilities}
- {:group :expressions :capabilities expressions/capabilities}
- {:group :joins :capabilities joins/capabilities}])
-
-(def raw-capability-catalog
- "Ordered structured-program capability metadata assembled from the grouped catalog."
- (into []
- (mapcat :capabilities)
- grouped-capability-catalog))
diff --git a/src/metabase/agent_lib/capabilities/catalog/aggregation.clj b/src/metabase/agent_lib/capabilities/catalog/aggregation.clj
deleted file mode 100644
index b5c2d13f70e..00000000000
--- a/src/metabase/agent_lib/capabilities/catalog/aggregation.clj
+++ /dev/null
@@ -1,30 +0,0 @@
-(ns metabase.agent-lib.capabilities.catalog.aggregation
- "Aggregation structured capability entries.
-
- Catalog entries are the source of truth for which operators agent-lib supports
- at runtime. The construct_notebook_query.md prompt is hand-curated guidance for
- the LLM and is not generated from this catalog — keep both in sync when adding
- or removing helpers."
- (:require
- [metabase.lib.core :as lib]))
-
-(set! *warn-on-reflection* true)
-
-(def capabilities
- "Aggregation helper capability entries."
- [{:op 'count, :binding #'lib/count, :kind :nested, :group :aggregation, :arities #{0}, :prompt-forms ["[\"count\"]"]}
- {:op 'sum, :binding #'lib/sum, :kind :nested, :group :aggregation, :prompt-forms ["[\"sum\", [\"field\", 201]]"], :prompt-notes ["Aggregation helpers take field refs like `[\"sum\", [\"field\", 201]]`. Do not pass bare numeric ids like `[\"sum\", 201]`."]}
- {:op 'avg, :binding #'lib/avg, :kind :nested, :group :aggregation, :prompt-forms ["[\"avg\", [\"field\", 201]]"]}
- {:op 'min, :binding #'lib/min, :kind :nested, :group :aggregation, :prompt-forms ["[\"min\", [\"field\", 201]]"]}
- {:op 'max, :binding #'lib/max, :kind :nested, :group :aggregation, :prompt-forms ["[\"max\", [\"field\", 201]]"]}
- {:op 'distinct, :binding #'lib/distinct, :kind :nested, :group :aggregation, :prompt-forms ["[\"distinct\", [\"field\", 201]]"]}
- {:op 'median, :binding #'lib/median, :kind :nested, :group :aggregation, :prompt-forms ["[\"median\", [\"field\", 201]]"]}
- {:op 'stddev, :binding #'lib/stddev, :kind :nested, :group :aggregation, :prompt-forms ["[\"stddev\", [\"field\", 201]]"]}
- {:op 'var, :binding #'lib/var, :kind :nested, :group :aggregation, :prompt-forms ["[\"var\", [\"field\", 201]]"]}
- {:op 'percentile, :binding #'lib/percentile, :kind :nested, :group :aggregation, :prompt-forms ["[\"percentile\", [\"field\", 201], 0.95]"]}
- {:op 'count-where, :binding #'lib/count-where, :kind :nested, :group :aggregation, :prompt-forms ["[\"count-where\", [\"=\", [\"field\", 101], \"completed\"]]"], :shape "[\"count-where\", clause]", :example "[\"count-where\", [\"=\", [\"field\", 2191], true]]"}
- {:op 'sum-where, :binding #'lib/sum-where, :kind :nested, :group :aggregation, :prompt-forms ["[\"sum-where\", [\"field\", 201], [\"=\", [\"field\", 101], \"completed\"]]"], :shape "[\"sum-where\", [\"field\", 2203], clause]", :example "[\"sum-where\", [\"field\", 2203], [\"=\", [\"field\", 2191], true]]"}
- {:op 'distinct-where, :binding #'lib/distinct-where, :kind :nested, :group :aggregation, :prompt-forms ["[\"distinct-where\", [\"field\", 201], [\"=\", [\"field\", 101], \"completed\"]]"], :shape "[\"distinct-where\", [\"field\", 2203], clause]", :example "[\"distinct-where\", [\"field\", 2203], [\"=\", [\"field\", 2191], true]]"}
- {:op 'share, :binding #'lib/share, :kind :nested, :group :aggregation, :prompt-forms ["[\"share\", [\"=\", [\"field\", 101], \"completed\"]]"], :shape "[\"share\", clause]", :example "[\"share\", [\"=\", [\"field\", 2191], true]]"}
- {:op 'cum-count, :binding #'lib/cum-count, :kind :nested, :group :aggregation, :prompt-forms ["[\"cum-count\"]"]}
- {:op 'cum-sum, :binding #'lib/cum-sum, :kind :nested, :group :aggregation, :prompt-forms ["[\"cum-sum\", [\"field\", 201]]"]}])
diff --git a/src/metabase/agent_lib/capabilities/catalog/expressions.clj b/src/metabase/agent_lib/capabilities/catalog/expressions.clj
deleted file mode 100644
index 63110785d92..00000000000
--- a/src/metabase/agent_lib/capabilities/catalog/expressions.clj
+++ /dev/null
@@ -1,60 +0,0 @@
-(ns metabase.agent-lib.capabilities.catalog.expressions
- "Expression structured capability entries."
- (:require
- [metabase.lib.core :as lib]))
-
-(set! *warn-on-reflection* true)
-
-(def capabilities
- "Expression helper capability entries."
- [{:op '+, :binding #'lib/+, :kind :nested, :group :expressions, :prompt-forms ["[\"+\", [\"field\", 201], [\"field\", 202]]"]}
- {:op '-, :binding #'lib/-, :kind :nested, :group :expressions, :prompt-forms ["[\"-\", [\"field\", 201], [\"field\", 202]]"]}
- {:op '*, :binding #'lib/*, :kind :nested, :group :expressions, :prompt-forms ["[\"*\", [\"field\", 201], [\"field\", 202]]"]}
- {:op '/, :binding #'lib//, :kind :nested, :group :expressions, :prompt-forms ["[\"/\", [\"field\", 201], [\"field\", 202]]"]}
- {:op 'case, :binding #'lib/case, :kind :nested, :group :expressions, :arities #{1 2}, :prompt-forms ["[\"case\", [[[\"<\", [\"field\", 201], 50], \"small\"], [[\"<\", [\"field\", 201], 200], \"medium\"]]]" "[\"case\", [[[\"<\", [\"field\", 201], 50], \"small\"], [[\"<\", [\"field\", 201], 200], \"medium\"]], \"large\"]"], :shape "[\"case\", [[condition, value], ...]] or [\"case\", [[condition, value], ...], fallback]", :example "[\"case\", [[[\"<\", [\"field\", 201], 50], \"small\"], [[\"<\", [\"field\", 201], 200], \"medium\"]], \"large\"]", :retry-shape "[\"case\", [[condition, value], ...]] or [\"case\", [[condition, value], ...], fallback]", :retry-example "[\"case\", [[[\"<\", [\"field\", 201], 50], \"small\"], [[\"<\", [\"field\", 201], 200], \"medium\"]], \"large\"]", :prompt-notes ["`case` uses the fallback value itself as the optional third argument. Do not wrap it in `{\"default\": ...}`." "If you want no else branch or a null result, omit the third `case` argument entirely."], :retry-notes ["Do not wrap the fallback in `{\"default\": ...}`." "Omit the third argument instead of using `null` when you want no else branch."]}
- {:op 'coalesce, :binding #'lib/coalesce, :kind :nested, :group :expressions, :prompt-forms ["[\"coalesce\", [\"field\", 101], [\"field\", 102]]"]}
- {:op 'concat, :binding #'lib/concat, :kind :nested, :group :expressions, :prompt-forms ["[\"concat\", [\"field\", 101], \" \", [\"field\", 102]]"]}
- {:op 'substring, :binding #'lib/substring, :kind :nested, :group :expressions, :prompt-forms ["[\"substring\", [\"field\", 101], 1, 3]"]}
- {:op 'replace, :binding #'lib/replace, :kind :nested, :group :expressions, :prompt-forms ["[\"replace\", [\"field\", 101], \"old\", \"new\"]"]}
- {:op 'upper, :binding #'lib/upper, :kind :nested, :group :expressions, :prompt-forms ["[\"upper\", [\"field\", 101]]"]}
- {:op 'lower, :binding #'lib/lower, :kind :nested, :group :expressions, :prompt-forms ["[\"lower\", [\"field\", 101]]"]}
- {:op 'trim, :binding #'lib/trim, :kind :nested, :group :expressions, :prompt-forms ["[\"trim\", [\"field\", 101]]"]}
- {:op 'ltrim, :binding #'lib/ltrim, :kind :nested, :group :expressions, :prompt-forms ["[\"ltrim\", [\"field\", 101]]"]}
- {:op 'rtrim, :binding #'lib/rtrim, :kind :nested, :group :expressions, :prompt-forms ["[\"rtrim\", [\"field\", 101]]"]}
- {:op 'length, :binding #'lib/length, :kind :nested, :group :expressions, :prompt-forms ["[\"length\", [\"field\", 101]]"]}
- {:op 'regex-match-first, :binding #'lib/regex-match-first, :kind :nested, :group :expressions, :prompt-forms ["[\"regex-match-first\", [\"field\", 101], \"pattern\"]"]}
- {:op 'split-part, :binding #'lib/split-part, :kind :nested, :group :expressions, :prompt-forms ["[\"split-part\", [\"field\", 101], \",\", 1]"]}
- {:op 'collate, :binding #'lib/collate, :kind :nested, :group :expressions, :prompt-forms ["[\"collate\", [\"field\", 101], \"case-insensitive\"]"]}
- {:op 'abs, :binding #'lib/abs, :kind :nested, :group :expressions, :prompt-forms ["[\"abs\", [\"field\", 201]]"]}
- {:op 'ceil, :binding #'lib/ceil, :kind :nested, :group :expressions, :prompt-forms ["[\"ceil\", [\"field\", 201]]"]}
- {:op 'floor, :binding #'lib/floor, :kind :nested, :group :expressions, :prompt-forms ["[\"floor\", [\"field\", 201]]"]}
- {:op 'round, :binding #'lib/round, :kind :nested, :group :expressions, :prompt-forms ["[\"round\", [\"field\", 201]]"]}
- {:op 'power, :binding #'lib/power, :kind :nested, :group :expressions, :prompt-forms ["[\"power\", [\"field\", 201], 2]"]}
- {:op 'sqrt, :binding #'lib/sqrt, :kind :nested, :group :expressions, :prompt-forms ["[\"sqrt\", [\"field\", 201]]"]}
- {:op 'log, :binding #'lib/log, :kind :nested, :group :expressions, :prompt-forms ["[\"log\", [\"field\", 201]]"]}
- {:op 'exp, :binding #'lib/exp, :kind :nested, :group :expressions, :prompt-forms ["[\"exp\", [\"field\", 201]]"]}
- {:op 'today, :binding #'lib/today, :kind :nested, :group :expressions, :arities #{0}, :prompt-forms ["[\"today\"]"]}
- {:op 'now, :binding #'lib/now, :kind :nested, :group :expressions, :arities #{0}, :prompt-forms ["[\"now\"]"]}
- {:op 'date, :binding #'lib/date, :kind :nested, :group :expressions, :prompt-forms ["[\"date\", \"2025-01-01\"]"]}
- {:op 'datetime, :binding #'lib/datetime, :kind :nested, :group :expressions, :prompt-forms ["[\"datetime\", \"2025-01-01T00:00:00\"]"]}
- {:op 'interval, :binding #'lib/interval, :kind :nested, :group :expressions, :prompt-forms ["[\"interval\", 7, \"day\"]"]}
- {:op 'time, :binding #'lib/time, :kind :nested, :group :expressions, :prompt-forms ["[\"time\", \"09:00\"]"]}
- {:op 'relative-datetime, :binding #'lib/relative-datetime, :kind :nested, :group :expressions, :prompt-forms ["[\"relative-datetime\", -7, \"day\"]"]}
- {:op 'absolute-datetime, :binding #'lib/absolute-datetime, :kind :nested, :group :expressions, :prompt-forms ["[\"absolute-datetime\", \"2025-01-01\", \"day\"]"], :shape "[\"absolute-datetime\", \"2024-01-01\", \"day\"]", :example "[\"absolute-datetime\", \"2024-01-01\", \"day\"]"}
- {:op 'datetime-add, :binding #'lib/datetime-add, :kind :nested, :group :expressions, :prompt-forms ["[\"datetime-add\", [\"field\", 302], 1, \"month\"]"]}
- {:op 'datetime-diff, :binding (fn [x y unit] (lib/expression-clause :datetime-diff [x y unit] nil)), :kind :nested, :group :expressions, :prompt-forms ["[\"datetime-diff\", [\"field\", 302], [\"field\", 303], \"day\"]"], :shape "[\"datetime-diff\", [\"field\", 302], [\"field\", 303], \"day\"]", :example "[\"datetime-diff\", [\"field\", 302], [\"field\", 303], \"day\"]", :prompt-notes ["Use `datetime-diff` when you need the number of days, weeks, months, or other units between two temporal values." "Do not subtract dates with `-` when the goal is a time difference; use `datetime-diff` instead."]}
- {:op 'datetime-subtract, :binding #'lib/datetime-subtract, :kind :nested, :group :expressions, :prompt-forms ["[\"datetime-subtract\", [\"now\"], [\"field\", 302], \"day\"]"]}
- {:op 'get-year, :binding #'lib/get-year, :kind :nested, :group :expressions, :prompt-forms ["[\"get-year\", [\"field\", 302]]"]}
- {:op 'get-quarter, :binding #'lib/get-quarter, :kind :nested, :group :expressions, :prompt-forms ["[\"get-quarter\", [\"field\", 302]]"]}
- {:op 'get-month, :binding #'lib/get-month, :kind :nested, :group :expressions, :prompt-forms ["[\"get-month\", [\"field\", 302]]"]}
- {:op 'get-week, :binding #'lib/get-week, :kind :nested, :group :expressions, :prompt-forms ["[\"get-week\", [\"field\", 302]]"]}
- {:op 'get-day, :binding #'lib/get-day, :kind :nested, :group :expressions, :prompt-forms ["[\"get-day\", [\"field\", 302]]"]}
- {:op 'get-day-of-week, :binding #'lib/get-day-of-week, :kind :nested, :group :expressions, :prompt-forms ["[\"get-day-of-week\", [\"field\", 302]]"]}
- {:op 'get-hour, :binding #'lib/get-hour, :kind :nested, :group :expressions, :prompt-forms ["[\"get-hour\", [\"field\", 302]]"]}
- {:op 'get-minute, :binding #'lib/get-minute, :kind :nested, :group :expressions, :prompt-forms ["[\"get-minute\", [\"field\", 302]]"]}
- {:op 'get-second, :binding #'lib/get-second, :kind :nested, :group :expressions, :prompt-forms ["[\"get-second\", [\"field\", 302]]"]}
- {:op 'convert-timezone, :binding #'lib/convert-timezone, :kind :nested, :group :expressions, :prompt-forms ["[\"convert-timezone\", [\"field\", 302], \"UTC\", \"America/Los_Angeles\"]"]}
- {:op 'integer, :binding #'lib/integer, :kind :nested, :group :expressions, :prompt-forms ["[\"integer\", [\"field\", 201]]"]}
- {:op 'float, :binding #'lib/float, :kind :nested, :group :expressions, :prompt-forms ["[\"float\", [\"field\", 201]]"]}
- {:op 'text, :binding #'lib/text, :kind :nested, :group :expressions, :prompt-forms ["[\"text\", [\"field\", 101]]"]}
- {:op 'offset, :binding #'lib/offset, :kind :nested, :group :expressions, :prompt-forms ["[\"offset\", [\"sum\", [\"field\", 2056]], -1]"], :shape "[\"offset\", [\"sum\", [\"field\", 2056]], -1]", :example "[\"offset\", [\"sum\", [\"field\", 2056]], -1]", :prompt-notes ["`offset` is a windowed aggregation over an aggregation or expression." "For grouped previous-period metrics like \"previous month's total\", add `offset` as another `aggregate` in the same stage as the base aggregation and breakout." "Do not add `append-stage` just to calculate a previous-period total with `offset`."] :retry-shape "For previous-period grouped metrics, keep `offset` in the same grouped stage as the base aggregation and breakout." :retry-example (str "[\n" " [\"aggregate\", [\"sum\", [\"field\", 2056]]],\n" " [\"aggregate\", [\"offset\", [\"sum\", [\"field\", 2056]], -1]],\n" " [\"breakout\", [\"with-temporal-bucket\", [\"field\", 2058], \"month\"]],\n" " [\"order-by\", [\"asc\", [\"with-temporal-bucket\", [\"field\", 2058], \"month\"]]]\n" "]")}])
diff --git a/src/metabase/agent_lib/capabilities/catalog/filtering.clj b/src/metabase/agent_lib/capabilities/catalog/filtering.clj
deleted file mode 100644
index 8742c1f1b1f..00000000000
--- a/src/metabase/agent_lib/capabilities/catalog/filtering.clj
+++ /dev/null
@@ -1,33 +0,0 @@
-(ns metabase.agent-lib.capabilities.catalog.filtering
- "Filtering structured capability entries."
- (:require
- [metabase.lib.core :as lib]))
-
-(set! *warn-on-reflection* true)
-
-(def capabilities
- "Filtering helper capability entries."
- [{:op '=, :binding #'lib/=, :kind :nested, :group :filtering, :prompt-forms ["[\"=\", [\"field\", 101], \"value\"]"]}
- {:op '!=, :binding #'lib/!=, :kind :nested, :group :filtering, :prompt-forms ["[\"!=\", [\"field\", 101], \"value\"]"]}
- {:op '<, :binding #'lib/<, :kind :nested, :group :filtering, :prompt-forms ["[\"<\", [\"field\", 101], 10]"]}
- {:op '<=, :binding #'lib/<=, :kind :nested, :group :filtering, :prompt-forms ["[\"<=\", [\"field\", 101], 10]"]}
- {:op '>, :binding #'lib/>, :kind :nested, :group :filtering, :prompt-forms ["[\">\", [\"field\", 101], 10]"]}
- {:op '>=, :binding #'lib/>=, :kind :nested, :group :filtering, :prompt-forms ["[\">=\", [\"field\", 101], 10]"]}
- {:op 'between, :binding #'lib/between, :kind :nested, :group :filtering, :prompt-forms ["[\"between\", [\"field\", 101], 1, 100]"], :shape "[\"between\", [\"field\", 2205], 1, 100]", :example "[\"between\", [\"field\", 2205], 1, 100]", :prompt-notes ["If the question explicitly asks for 2024 or another exact year, use an exact 2024 restriction, not a relative current-year or last-year filter." "Using an exact helper year field like `[\"=\", [\"field\", year_field], 2024]` is acceptable when it is clearly equivalent to filtering the requested date field to 2024."]}
- {:op 'contains, :binding #'lib/contains, :kind :nested, :group :filtering, :prompt-forms ["[\"contains\", [\"field\", 101], \"text\"]"]}
- {:op 'does-not-contain, :binding #'lib/does-not-contain, :kind :nested, :group :filtering, :prompt-forms ["[\"does-not-contain\", [\"field\", 101], \"text\"]"], :shape "[\"does-not-contain\", [\"field\", 2204], \"trial\"]", :example "[\"does-not-contain\", [\"field\", 2204], \"trial\"]"}
- {:op 'starts-with, :binding #'lib/starts-with, :kind :nested, :group :filtering, :prompt-forms ["[\"starts-with\", [\"field\", 101], \"prefix\"]"]}
- {:op 'ends-with, :binding #'lib/ends-with, :kind :nested, :group :filtering, :prompt-forms ["[\"ends-with\", [\"field\", 101], \"suffix\"]"]}
- {:op 'is-null, :binding #'lib/is-null, :kind :nested, :group :filtering, :prompt-forms ["[\"is-null\", [\"field\", 101]]"]}
- {:op 'not-null, :binding #'lib/not-null, :kind :nested, :group :filtering, :prompt-forms ["[\"not-null\", [\"field\", 101]]"]}
- {:op 'is-empty, :binding #'lib/is-empty, :kind :nested, :group :filtering, :prompt-forms ["[\"is-empty\", [\"field\", 101]]"], :shape "[\"is-empty\", [\"field\", 2204]]", :example "[\"is-empty\", [\"field\", 2204]]"}
- {:op 'not-empty, :binding #'lib/not-empty, :kind :nested, :group :filtering, :prompt-forms ["[\"not-empty\", [\"field\", 101]]"], :shape "[\"not-empty\", [\"field\", 2204]]", :example "[\"not-empty\", [\"field\", 2204]]"}
- {:op 'and, :binding #'lib/and, :kind :nested, :group :filtering, :prompt-forms ["[\"and\", clause1, clause2]"]}
- {:op 'or, :binding #'lib/or, :kind :nested, :group :filtering, :prompt-forms ["[\"or\", clause1, clause2]"]}
- {:op 'not, :binding #'lib/not, :kind :nested, :group :filtering, :prompt-forms ["[\"not\", clause]"]}
- {:op 'time-interval, :binding #'lib/time-interval, :kind :nested, :group :filtering, :prompt-forms ["[\"time-interval\", [\"field\", 101], -30, \"day\"]"]}
- {:op 'relative-time-interval, :binding #'lib/relative-time-interval, :kind :nested, :group :filtering, :arities #{5}, :prompt-forms ["[\"relative-time-interval\", [\"field\", 101], -30, \"day\", 0, \"day\"]"], :shape "[\"relative-time-interval\", [\"field\", 2205], -30, \"day\", 0, \"day\"]", :example "[\"relative-time-interval\", [\"field\", 2205], -30, \"day\", 0, \"day\"]"}
- {:op 'in, :binding #'lib/in, :kind :nested, :group :filtering, :prompt-forms ["[\"in\", [\"field\", 101], [\"a\", \"b\"]]"], :shape "[\"in\", [\"field\", 2492], [\"authorized\", \"pending\", \"partially_paid\"]]", :example "[\"in\", [\"field\", 2492], [\"authorized\", \"pending\", \"partially_paid\"]]"}
- {:op 'not-in, :binding #'lib/not-in, :kind :nested, :group :filtering, :prompt-forms ["[\"not-in\", [\"field\", 101], [\"a\", \"b\"]]"], :shape "[\"not-in\", [\"field\", 2492], [\"authorized\", \"pending\"]]", :example "[\"not-in\", [\"field\", 2492], [\"authorized\", \"pending\"]]"}
- {:op 'inside, :binding #'lib/inside, :kind :nested, :group :filtering, :prompt-forms ["[\"inside\", [\"field\", 401], [\"field\", 402], 40.0, 30.0, -70.0, -80.0]"], :shape "[\"inside\", [\"field\", 401], [\"field\", 402], 40.0, 30.0, -70.0, -80.0]", :example "[\"inside\", [\"field\", 401], [\"field\", 402], 40.0, 30.0, -70.0, -80.0]"}
- {:op 'segment, :binding #'lib/segment, :kind :nested, :group :filtering, :prompt-forms ["[\"segment\", 88]"], :shape "[\"segment\", 88]", :example "[\"segment\", 88]"}])
diff --git a/src/metabase/agent_lib/capabilities/catalog/joins.clj b/src/metabase/agent_lib/capabilities/catalog/joins.clj
deleted file mode 100644
index 180e42ad120..00000000000
--- a/src/metabase/agent_lib/capabilities/catalog/joins.clj
+++ /dev/null
@@ -1,14 +0,0 @@
-(ns metabase.agent-lib.capabilities.catalog.joins
- "Join-related structured capability entries."
- (:require
- [metabase.lib.core :as lib]))
-
-(set! *warn-on-reflection* true)
-
-(def capabilities
- "Join helper capability entries."
- [{:op 'join-clause, :binding #'lib/join-clause, :kind :nested, :group :joins, :arities #{1}, :prompt-forms ["[\"join-clause\", [\"table\", 42]]" "[\"join-clause\", {\"type\": \"program\", \"program\": {...}}]"], :shape "[\"join-clause\", [\"table\", 133]]", :example "[\"join-clause\", [\"table\", 133]]"}
- {:op 'with-join-conditions, :binding #'lib/with-join-conditions, :kind :nested, :group :joins, :prompt-forms ["[\"with-join-conditions\", [\"join-clause\", [\"table\", 42]], [[\"=\", [\"field\", 101], [\"field\", 202]]]]"], :shape "[\"with-join-conditions\", [\"join-clause\", [\"table\", 133]], [[\"=\", [\"field\", 2456], [\"field\", 2488]]]]", :example "[\"with-join-conditions\", [\"join-clause\", [\"table\", 133]], [[\"=\", [\"field\", 2456], [\"field\", 2488]]]]", :prompt-notes ["If the source-table context already exposes the related table you need, prefer direct related-field refs first." "Direct related-field refs are the default for one-hop related tables." "Use `join-clause` and `with-join-conditions` when you need custom join behavior, a join alias, explicit joined-field selection, self-joins, or direct related-field refs are unavailable." "If an explicit join returns a permission error, the underlying table is not accessible — surface the error instead of retrying with implicit refs."]}
- {:op 'with-join-fields, :binding #'lib/with-join-fields, :kind :nested, :group :joins, :prompt-forms ["[\"with-join-fields\", join-clause, \"all\"]" "[\"with-join-fields\", join-clause, \"none\"]" "[\"with-join-fields\", join-clause, [[\"field\", 757]]]"], :shape "[\"with-join-fields\", join-clause, [[\"field\", 757]]]", :example "[\"with-join-fields\", [\"join-clause\", [\"table\", 133]], [[\"field\", 757]]]"}
- {:op 'with-join-strategy, :binding #'lib/with-join-strategy, :kind :nested, :group :joins, :prompt-forms ["[\"with-join-strategy\", join-clause, \"left-join\"]"], :shape "[\"with-join-strategy\", [\"join-clause\", [\"table\", 133]], \"left-join\"]", :example "[\"with-join-strategy\", [\"join-clause\", [\"table\", 133]], \"left-join\"]"}
- {:op 'with-join-alias, :binding #'lib/with-join-alias, :kind :nested, :group :joins, :prompt-forms ["[\"with-join-alias\", join-clause, \"alias\"]"]}])
diff --git a/src/metabase/agent_lib/capabilities/catalog/ordering.clj b/src/metabase/agent_lib/capabilities/catalog/ordering.clj
deleted file mode 100644
index a909226ab9b..00000000000
--- a/src/metabase/agent_lib/capabilities/catalog/ordering.clj
+++ /dev/null
@@ -1,13 +0,0 @@
-(ns metabase.agent-lib.capabilities.catalog.ordering
- "Breakout and ordering structured capability entries."
- (:require
- [metabase.lib.core :as lib]))
-
-(set! *warn-on-reflection* true)
-
-(def capabilities
- "Breakout-ordering helper capability entries."
- [{:op 'with-temporal-bucket, :binding #'lib/with-temporal-bucket, :kind :nested, :group :breakout-ordering, :prompt-forms ["[\"with-temporal-bucket\", [\"field\", 302], \"month\"]"], :shape "[\"with-temporal-bucket\", [\"field\", 2205], \"month\"]", :example "[\"with-temporal-bucket\", [\"field\", 2205], \"month\"]"}
- {:op 'with-binning, :binding #'lib/with-binning, :kind :nested, :group :breakout-ordering, :prompt-forms ["[\"with-binning\", [\"field\", 303], strategy]"]}
- {:op 'asc, :kind :nested, :group :breakout-ordering, :runtime-provided? true, :arities #{1}, :prompt-forms ["[\"asc\", [\"field\", 301]]"]}
- {:op 'desc, :kind :nested, :group :breakout-ordering, :runtime-provided? true, :arities #{1}, :prompt-forms ["[\"desc\", [\"field\", 301]]"]}])
diff --git a/src/metabase/agent_lib/capabilities/catalog/sources.clj b/src/metabase/agent_lib/capabilities/catalog/sources.clj
deleted file mode 100644
index c0aff5f2940..00000000000
--- a/src/metabase/agent_lib/capabilities/catalog/sources.clj
+++ /dev/null
@@ -1,16 +0,0 @@
-(ns metabase.agent-lib.capabilities.catalog.sources
- "Source and query-reference structured capability entries."
- (:require
- [metabase.lib.core :as lib]))
-
-(set! *warn-on-reflection* true)
-
-(def capabilities
- "Source and query-reference capability entries."
- [{:op 'field, :kind :nested, :group :sources, :runtime-provided? true, :arities #{1}, :prompt-forms ["[\"field\", 101]"], :shape "[\"field\", 101]", :example "[\"field\", 101]"}
- {:op 'table, :kind :nested, :group :sources, :runtime-provided? true, :arities #{1}, :prompt-forms ["[\"table\", 42]"], :shape "[\"table\", 42]", :example "[\"table\", 42]"}
- {:op 'card, :kind :nested, :group :sources, :runtime-provided? true, :arities #{1}, :prompt-forms ["[\"card\", 55]"], :shape "[\"card\", 55]", :example "[\"card\", 55]"}
- {:op 'metric, :kind :nested, :group :sources, :runtime-provided? true, :arities #{1}, :prompt-forms ["[\"metric\", 77]"], :shape "[\"metric\", 77]", :example "[\"metric\", 77]"}
- {:op 'measure, :kind :nested, :group :sources, :runtime-provided? true, :arities #{1}, :prompt-forms ["[\"measure\", 91]"], :shape "[\"measure\", 91]", :example "[\"measure\", 91]", :prompt-notes ["Use `measure` for a named table/model measure aggregation when it is available in the source context. Measures use real numeric ids."]}
- {:op 'expression-ref, :binding #'lib/expression-ref, :kind :nested, :group :query-refs, :arities #{1}, :prompt-forms ["[\"expression-ref\", \"Net Amount\"]"], :shape "[\"expression-ref\", \"Net Amount\"]", :example "[\"expression-ref\", \"Net Amount\"]"}
- {:op 'aggregation-ref, :kind :nested, :group :query-refs, :runtime-provided? true, :arities #{1}, :prompt-forms ["[\"aggregation-ref\", 0]"], :shape "[\"aggregation-ref\", 0]", :example "[\"aggregation-ref\", 0]"}])
diff --git a/src/metabase/agent_lib/capabilities/catalog/top_level.clj b/src/metabase/agent_lib/capabilities/catalog/top_level.clj
deleted file mode 100644
index e7b16296298..00000000000
--- a/src/metabase/agent_lib/capabilities/catalog/top_level.clj
+++ /dev/null
@@ -1,21 +0,0 @@
-(ns metabase.agent-lib.capabilities.catalog.top-level
- "Top-level structured-program capability entries."
- (:require
- [metabase.lib.core :as lib]))
-
-(set! *warn-on-reflection* true)
-
-(def capabilities
- "Top-level structured-program capability entries."
- [{:op 'filter, :binding #'lib/filter, :kind :top-level, :arities #{1}, :prompt-forms ["[\"filter\", clause]"], :shape "[\"filter\", clause]", :example "[\"filter\", [\"time-interval\", [\"field\", 2058], -12, \"month\"]]"}
- {:op 'aggregate, :binding #'lib/aggregate, :kind :top-level, :arities #{1}, :prompt-forms ["[\"aggregate\", aggregation]"], :shape "[\"aggregate\", [\"sum\", [\"field\", 2056]]]", :example "[\"aggregate\", [\"sum\", [\"field\", 2056]]]"}
- {:op 'breakout, :binding #'lib/breakout, :kind :top-level, :arities #{1}, :prompt-forms ["[\"breakout\", breakout-form]"], :shape "[\"breakout\", [\"field\", 3134]]", :example "[\"breakout\", [\"field\", 3134]]"}
- {:op 'with-fields, :binding #'lib/with-fields, :kind :top-level, :arities #{1}, :prompt-forms ["[\"with-fields\", [field-or-ref, ...]]"], :shape "[\"with-fields\", [[\"field\", 2204], [\"expression-ref\", \"Net Amount\"]]]", :example "[\"with-fields\", [[\"field\", 2204], [\"expression-ref\", \"Net Amount\"]]]"}
- {:op 'limit, :binding #'lib/limit, :kind :top-level, :arities #{1}, :prompt-forms ["[\"limit\", 10]"], :shape "[\"limit\", 10]", :example "[\"limit\", 10]"}
- {:op 'expression, :binding #'lib/expression, :kind :top-level, :arities #{2}, :prompt-forms ["[\"expression\", \"Name\", expr]"], :shape "[\"expression\", \"Net Amount\", [\"-\", [\"field\", 2624], [\"field\", 2641]]]", :example "[\"expression\", \"Net Amount\", [\"-\", [\"field\", 2624], [\"field\", 2641]]]", :prompt-notes ["If an `expression` uses `aggregation-ref`, add `append-stage` first. Do not define ratios over aggregations in the same stage that creates those aggregations."]}
- {:op 'join, :binding #'lib/join, :kind :top-level, :arities #{1}, :prompt-forms ["[\"join\", join-clause]"], :shape "[\"join\", [\"join-clause\", [\"table\", 42]]]", :example "[\"join\", [\"join-clause\", [\"table\", 42]]]", :prompt-notes ["If a related table is already surfaced in the source-table context, first try using its field ids directly without an explicit join." "Direct related-field refs are the default for one-hop related tables." "Use an explicit join when you need custom join behavior, a join alias, explicit joined-field selection, self-joins, or direct related-field refs do not work." "If an explicit join returns a permission error, the underlying table is not accessible — surface the error instead of retrying with implicit refs."]}
- {:op 'order-by, :kind :top-level, :runtime-provided? true, :arities #{1 2}, :prompt-forms ["[\"order-by\", orderable]" "[\"order-by\", orderable, \"desc\"]"], :shape "[\"order-by\", [\"desc\", [\"aggregation-ref\", 0]]] or [\"order-by\", [\"aggregation-ref\", 0], \"desc\"]", :example "[\"order-by\", [\"desc\", [\"aggregation-ref\", 0]]]"}
- {:op 'append-stage, :binding #'lib/append-stage, :kind :top-level, :arities #{0}, :prompt-forms ["[\"append-stage\"]"], :shape "[\"append-stage\"]", :example "[\"append-stage\"]", :prompt-notes ["If you filter on `[\"aggregation-ref\", index]`, insert `append-stage` first. Do not filter on an aggregation result in the same stage that creates it."]}
- {:op 'drop-stage, :binding #'lib/drop-stage, :kind :top-level, :arities #{0}, :prompt-forms ["[\"drop-stage\"]"], :shape "[\"drop-stage\"]", :example "[\"drop-stage\"]"}
- {:op 'drop-empty-stages, :binding #'lib/drop-empty-stages, :kind :top-level, :arities #{0}, :prompt-forms ["[\"drop-empty-stages\"]"], :shape "[\"drop-empty-stages\"]", :example "[\"drop-empty-stages\"]"}
- {:op 'with-page, :binding #'lib/with-page, :kind :top-level, :arities #{1}, :prompt-forms ["[\"with-page\", {\"page\": 2, \"items\": 25}]"], :shape "[\"with-page\", {\"page\": 2, \"items\": 25}]", :example "[\"with-page\", {\"page\": 2, \"items\": 25}]", :prompt-notes ["Use JSON objects only for helpers that explicitly show one, such as `[\"with-page\", {\"page\": 2, \"items\": 25}]`."]}])
diff --git a/src/metabase/agent_lib/capabilities/derived.clj b/src/metabase/agent_lib/capabilities/derived.clj
deleted file mode 100644
index fe1d095405c..00000000000
--- a/src/metabase/agent_lib/capabilities/derived.clj
+++ /dev/null
@@ -1,99 +0,0 @@
-(ns metabase.agent-lib.capabilities.derived
- "Derived views over the structured capability catalog.")
-
-(set! *warn-on-reflection* true)
-
-(defn guidance
- "Return prompt and retry guidance metadata for a capability entry."
- [capability]
- (:guidance capability))
-
-(defn prompt-forms
- "Return documented prompt forms for a capability entry."
- [capability]
- (get-in capability [:guidance :prompt-forms]))
-
-(defn prompt-notes
- "Return documented prompt notes for a capability entry."
- [capability]
- (get-in capability [:guidance :prompt-notes]))
-
-(defn guidance-shape
- "Return the documented canonical call shape for a capability entry."
- [capability]
- (get-in capability [:guidance :shape]))
-
-(defn guidance-example
- "Return the documented example program fragment for a capability entry."
- [capability]
- (get-in capability [:guidance :example]))
-
-(defn capability-by-op
- "Index capability entries by operator symbol."
- [capability-catalog]
- (into {}
- (map (fn [capability]
- [(:op capability) capability]))
- capability-catalog))
-
-(defn fixed-arities
- "Index declared helper arities by operator symbol."
- [capability-catalog]
- (into {}
- (keep (fn [{:keys [op arities]}]
- (when arities
- [op arities])))
- capability-catalog))
-
-(defn trusted-helper-bindings
- "Index trusted helper implementations by operator symbol."
- [capability-catalog]
- (into {}
- (keep (fn [{:keys [op binding]}]
- (when binding
- [op binding])))
- capability-catalog))
-
-(defn query-transform-symbols
- "Return the top-level query-transform operators."
- [capability-catalog]
- (into #{}
- (comp (filter #(= (:kind %) :top-level))
- (map :op))
- capability-catalog))
-
-(defn helper-symbols
- "Return all helper symbols accepted by the structured evaluator."
- [capability-catalog synthetic-helper-symbols]
- (into synthetic-helper-symbols
- (comp (filter #(or (:binding %)
- (:runtime-provided? %)))
- (map :op))
- capability-catalog))
-
-(defn nested-operator-values
- "Return canonical string names for nested operators."
- [capability-catalog]
- (into #{}
- (comp (filter #(= (:kind %) :nested))
- (map (comp name :op)))
- capability-catalog))
-
-(defn top-level-operator-values
- "Return canonical string names for top-level operations."
- [capability-catalog]
- (into #{}
- (comp (filter #(= (:kind %) :top-level))
- (map (comp name :op)))
- capability-catalog))
-
-(defn operator-guidance-catalog
- "Return retry guidance keyed by canonical operator name."
- [capability-catalog]
- (into {}
- (keep (fn [{:keys [op] :as capability}]
- (let [{:keys [shape example retry-shape retry-example]} (guidance capability)]
- (when-let [guidance-shape (or retry-shape shape)]
- [(name op) {:shape guidance-shape
- :example (or retry-example example)}]))))
- capability-catalog))
diff --git a/src/metabase/agent_lib/capabilities/synthetic.clj b/src/metabase/agent_lib/capabilities/synthetic.clj
deleted file mode 100644
index 32b13ec4f01..00000000000
--- a/src/metabase/agent_lib/capabilities/synthetic.clj
+++ /dev/null
@@ -1,9 +0,0 @@
-(ns metabase.agent-lib.capabilities.synthetic
- "Synthetic structured helper symbols that are accepted by agent-lib but are
- not modeled as normal capability entries.")
-
-(set! *warn-on-reflection* true)
-
-(def synthetic-helper-symbols
- "Synthetic helper symbols accepted by the structured evaluator."
- '#{query})
diff --git a/src/metabase/agent_lib/common/coercions.clj b/src/metabase/agent_lib/common/coercions.clj
deleted file mode 100644
index f3f5606dd61..00000000000
--- a/src/metabase/agent_lib/common/coercions.clj
+++ /dev/null
@@ -1,96 +0,0 @@
-(ns metabase.agent-lib.common.coercions
- "Coercion and normalization helpers for structured MBQL programs."
- (:require
- [clojure.string :as str]
- [metabase.agent-lib.common.literals :as literals]
- [metabase.agent-lib.syntax :as syntax]
- [metabase.util :as u]))
-
-(set! *warn-on-reflection* true)
-
-(defn quarter-label->number
- "Convert quarter labels such as `Q1` into the corresponding integer."
- [value]
- (when (string? value)
- (case (u/upper-case-en (str/trim value))
- "Q1" 1
- "Q2" 2
- "Q3" 3
- "Q4" 4
- nil)))
-
-(defn parse-int-string
- "Parse an integer string, returning nil when parsing fails."
- [value]
- (when (and (string? value)
- (re-matches #"-?\d+" value))
- (try
- (Long/parseLong value)
- (catch NumberFormatException _
- nil))))
-
-(defn coerce-positive-int
- "Coerce positive integer strings into integers."
- [value]
- (cond
- (pos-int? value) value
- (string? value) (let [parsed (parse-int-string value)]
- (if (pos-int? parsed) parsed value))
- :else value))
-
-(defn coerce-non-negative-int
- "Coerce non-negative integer strings into integers."
- [value]
- (cond
- (and (int? value) (<= 0 value)) value
- (string? value) (let [parsed (parse-int-string value)]
- (if (and (int? parsed) (<= 0 parsed)) parsed value))
- :else value))
-
-(defn direction-string?
- "True when `value` is an order direction string or keyword."
- [value]
- (boolean (#{"asc" "desc"} (some-> value syntax/raw-op-name u/lower-case-en))))
-
-(defn normalize-direction
- "Normalize a direction enum to its lowercase string form."
- [value]
- (some-> value syntax/raw-op-name u/lower-case-en))
-
-(defn unwrap-singleton-form
- "Recursively unwrap singleton vectors that are not operator tuples."
- [value]
- (loop [value value]
- (if (and (vector? value)
- (= 1 (count value))
- (not (syntax/possible-operator-tuple? value))
- (not (literals/scalar-sequential? value)))
- (recur (first value))
- value)))
-
-(defn normalize-percentile-value
- "Normalize percentiles expressed as whole-number percentages to fractions."
- [value]
- (if (and (number? value)
- (> (double value) 1.0)
- (<= (double value) 100.0))
- (/ (double value) 100.0)
- value))
-
-(defn normalize-join-conditions
- "Unwrap one extra sequential level around join conditions."
- [conditions]
- (loop [conditions conditions]
- (if (and (sequential? conditions)
- (= 1 (count conditions))
- (sequential? (first conditions))
- (not (syntax/possible-operator-tuple? (first conditions))))
- (recur (vec (first conditions)))
- conditions)))
-
-(defn normalize-map-key
- "Convert string map keys to keywords while leaving other keys unchanged."
- [k]
- (if (string? k)
- (keyword k)
- k))
diff --git a/src/metabase/agent_lib/common/context.clj b/src/metabase/agent_lib/common/context.clj
deleted file mode 100644
index 6970c639e80..00000000000
--- a/src/metabase/agent_lib/common/context.clj
+++ /dev/null
@@ -1,22 +0,0 @@
-(ns metabase.agent-lib.common.context
- "Helpers derived from the evaluation context.")
-
-(set! *warn-on-reflection* true)
-
-(defn source-metric-id
- "Return the current context source metric id when the source entity is a metric."
- [context]
- (let [source-entity (:source-entity context)
- source-id (:id source-entity)]
- (when (and (= "metric" (:model source-entity))
- (pos-int? source-id))
- source-id)))
-
-(defn source-table-id
- "Return the current context source table id when the source entity is a table."
- [context]
- (let [source-entity (:source-entity context)
- source-id (:id source-entity)]
- (when (and (= "table" (:model source-entity))
- (pos-int? source-id))
- source-id)))
diff --git a/src/metabase/agent_lib/common/errors.clj b/src/metabase/agent_lib/common/errors.clj
deleted file mode 100644
index e6693bda7c9..00000000000
--- a/src/metabase/agent_lib/common/errors.clj
+++ /dev/null
@@ -1,80 +0,0 @@
-(ns metabase.agent-lib.common.errors
- "Error helpers for structured MBQL program repair, validation, and evaluation."
- (:require
- [clojure.string :as str]
- [metabase.util.i18n :refer [tru]]))
-
-(set! *warn-on-reflection* true)
-
-(defn path->string
- "Render a validation path vector into a dotted path string."
- [path]
- (if (empty? path)
- "<root>"
- (str/join ""
- (map-indexed
- (fn [idx segment]
- (cond
- (integer? segment) (str "[" segment "]")
- (zero? idx) (name segment)
- :else (str "." (name segment))))
- path))))
-
-(defn invalid-program!
- "Throw a standardized invalid structured program exception."
- [path message & [data]]
- (throw (ex-info (tru "Generated program is invalid.")
- (merge
- {:status-code 400
- :error :invalid-generated-program
- :path (path->string path)
- :details (str (path->string path) ": " message)}
- data))))
-
-(def ^:private recovery-keys
- "Keys that carry agent-recovery hints through the error chain."
- [:available :tables :suggestion])
-
-(defn lookup-error!
- "Throw a structured lookup error with optional recovery hints.
- `message` is the clean, user-safe string (no schema enumeration).
- `data` identifies the failed entity (e.g. `{:table-id 42}`).
- `recovery` is an optional map with agent-facing hints:
- :available - seq of valid names/values
- :tables - seq of matching tables (for disambiguation)
- :suggestion - corrective suggestion string"
- ([message data]
- (lookup-error! message data nil))
- ([message data recovery]
- (throw (ex-info message
- (cond-> (assoc data
- :status-code 400
- :error :invalid-generated-program)
- (seq recovery) (assoc :recovery recovery))))))
-
-(defn wrap-runtime-error
- "Wrap a runtime exception into the standard invalid-program shape,
- preserving structured recovery data from the cause's ex-data."
- [path op-name ^Throwable cause]
- (let [cause-data (ex-data cause)
- recovery (or (:recovery cause-data)
- (not-empty (select-keys cause-data recovery-keys)))]
- (ex-info (tru "Generated program could not be evaluated.")
- (cond-> {:status-code 400
- :error :invalid-generated-program
- :path (path->string path)
- :details (str (path->string path) ": " (ex-message cause))
- :operator op-name}
- recovery (assoc :recovery recovery))
- cause)))
-
-(defn recovery-summary
- "Format the `:recovery` map from an exception's ex-data into a string
- suitable for LLM retry feedback. Returns nil when there are no hints."
- [{:keys [available tables suggestion]}]
- (let [parts (cond-> []
- (seq available) (conj (str "Available: " (str/join ", " (take 20 available))))
- (seq tables) (conj (str "Matching tables: " (str/join ", " tables)))
- suggestion (conj suggestion))]
- (when (seq parts)
- (str/join "\n" parts))))
diff --git a/src/metabase/agent_lib/common/literals.clj b/src/metabase/agent_lib/common/literals.clj
deleted file mode 100644
index 0e9ff2e07c6..00000000000
--- a/src/metabase/agent_lib/common/literals.clj
+++ /dev/null
@@ -1,84 +0,0 @@
-(ns metabase.agent-lib.common.literals
- "Literal and structural predicates for structured MBQL programs."
- (:require
- [clojure.string :as str]
- [metabase.agent-lib.syntax :as syntax]
- [metabase.lib.hierarchy :as lib.hierarchy]
- [metabase.lib.schema.aggregation]
- [metabase.util :as u]))
-
-(set! *warn-on-reflection* true)
-
-(def ^:private aggregation-operator-names
- ;; Derived from the lib schema hierarchy so new aggregation helpers are picked up automatically.
- ;; `:aggregation` is the abstract wrapper clause and `:offset` is a windowed aggregation that
- ;; behaves like an expression in some contexts — neither should be recognized as a plain
- ;; aggregation helper name.
- (into #{}
- (comp (remove #{:aggregation :offset})
- (map name))
- (descendants @lib.hierarchy/hierarchy
- :metabase.lib.schema.aggregation/aggregation-clause-tag)))
-
-(defn scalar-literal?
- "True when `value` is a scalar JSON-like literal accepted by the structured format."
- [value]
- (or (nil? value)
- (string? value)
- (number? value)
- (boolean? value)))
-
-(defn non-blank-string?
- "True when `value` is a non-blank string."
- [value]
- (and (string? value) (not (str/blank? value))))
-
-(defn quarter-label-string?
- "True when `value` looks like a quarter label such as `Q1`."
- [value]
- (and (string? value)
- (re-matches #"(?i)q[1-4]" (str/trim value))))
-
-(defn now-literal?
- "True when `value` is the case-insensitive literal string `now`."
- [value]
- (and (string? value)
- (= "now" (u/lower-case-en (str/trim value)))))
-
-(defn iso-date-string?
- "True when `value` is an ISO `yyyy-mm-dd` date string."
- [value]
- (and (string? value)
- (re-matches #"\d{4}-\d{2}-\d{2}" (str/trim value))))
-
-(defn null-literal?
- "True when `value` is nil or the case-insensitive string `null`."
- [value]
- (or (nil? value)
- (and (string? value)
- (= "null" (u/lower-case-en value)))))
-
-(defn scalar-sequential?
- "True when `value` is a sequential collection of scalar literals."
- [value]
- (and (sequential? value)
- (not (syntax/possible-operator-tuple? value))
- (every? scalar-literal? value)))
-
-(defn aggregation-form?
- "True when `value` is a canonical aggregation helper tuple."
- [value]
- (and (vector? value)
- (aggregation-operator-names (syntax/canonical-op-name (first value)))))
-
-(defn default-map?
- "True when `value` looks like a legacy `{default ...}` case fallback map."
- [value]
- (and (map? value)
- (or (contains? value :default)
- (contains? value "default"))))
-
-(defn bare-field-id?
- "True when `value` is a positive integer field id without a `field` wrapper."
- [value]
- (and (int? value) (pos? value)))
diff --git a/src/metabase/agent_lib/core.clj b/src/metabase/agent_lib/core.clj
deleted file mode 100644
index ed58eb19374..00000000000
--- a/src/metabase/agent_lib/core.clj
+++ /dev/null
@@ -1,14 +0,0 @@
-(ns metabase.agent-lib.core
- "Public API for structured MBQL program repair, validation, and evaluation."
- (:require
- [metabase.agent-lib.eval]
- [metabase.agent-lib.repair]
- [metabase.agent-lib.schema]
- [metabase.agent-lib.validate]
- [potemkin :as p]))
-
-(p/import-vars
- [metabase.agent-lib.repair repair-program]
- [metabase.agent-lib.validate validated-program]
- [metabase.agent-lib.eval evaluate-program]
- [metabase.agent-lib.schema program-schema])
diff --git a/src/metabase/agent_lib/eval.clj b/src/metabase/agent_lib/eval.clj
deleted file mode 100644
index 2eddecbb8a8..00000000000
--- a/src/metabase/agent_lib/eval.clj
+++ /dev/null
@@ -1,136 +0,0 @@
-(ns metabase.agent-lib.eval
- "Structured MBQL program interpretation."
- (:require
- [metabase.agent-lib.common.errors :refer [invalid-program!]]
- [metabase.agent-lib.eval.invoke :as eval.invoke]
- [metabase.agent-lib.eval.source :as eval.source]
- [metabase.agent-lib.eval.walker :as eval.walker]
- [metabase.agent-lib.mbql-integration :as mbql]
- [metabase.agent-lib.refs :as refs]
- [metabase.agent-lib.runtime :as runtime]
- [metabase.agent-lib.validate :as validate]
- [metabase.agent-lib.validate.walker :as walker]
- [metabase.lib.core :as lib]
- [metabase.lib.metadata :as lib.metadata]
- [metabase.util.log :as log]
- [metabase.util.malli :as mu]))
-
-(set! *warn-on-reflection* true)
-
-(defn- skip-operation?
- "True when an operation is a redundant implicit join that should be elided."
- [runtime query op operation]
- (and (= op 'join)
- ((get (:bindings runtime) 'skip-join?) query operation)))
-
-(defn- apply-operation
- "Evaluate a single operation's args and invoke its helper against `query`."
- [evaluate-node runtime query op-path [raw-op & raw-args]]
- (let [op (runtime/op-symbol raw-op)
- args (eval.walker/evaluate-args evaluate-node query op-path op raw-args)]
- (eval.invoke/invoke-helper! runtime op-path op (into [query] args))))
-
-(defn- program-has-breakouts?
- "True when the program's operations include at least one explicit breakout."
- [program]
- (some (fn [[op]]
- (= "breakout" (when (string? op) op)))
- (:operations program)))
-
-(defn- strip-default-breakouts
- "Remove default breakouts from a metric source query when the program supplies its own.
- Metrics include a default time dimension breakout in their query definition. When the
- agent explicitly specifies breakout operations, these should replace — not augment — the
- defaults."
- [source-query program]
- (if (and (mbql/query? source-query) (program-has-breakouts? program))
- (lib/remove-all-breakouts source-query)
- source-query))
-
-(defn- evaluate-program*
- [runtime context path program program-depth]
- (when (> program-depth walker/max-program-nesting)
- (invalid-program! path "program source nesting exceeds maximum depth"))
- (let [evaluate-program (fn [nested-path nested-program]
- (evaluate-program* runtime context nested-path nested-program (inc program-depth)))
- evaluate-node (fn [current-query node-path value]
- (eval.walker/evaluate-node evaluate-program
- runtime
- current-query
- node-path
- value))
- resolved-source (eval.source/resolve-source evaluate-program
- runtime
- (conj path :source)
- (:source program))
- source-query (-> (if (mbql/query? resolved-source)
- resolved-source
- (eval.invoke/invoke-helper! runtime (conj path :source) 'query [resolved-source]))
- (strip-default-breakouts program))
- final-query (reduce (fn [query [op-idx operation]]
- (let [op-path (into path [:operations op-idx])
- op (runtime/op-symbol (first operation))]
- (if (skip-operation? runtime query op operation)
- query
- (apply-operation evaluate-node runtime query op-path operation))))
- source-query
- (map-indexed vector (:operations program)))]
- (eval.invoke/ensure-query-result! final-query)))
-
-(defn- card-underlying-table-ids
- "For a sequence of card metadata records, return the distinct underlying table-ids reachable
- from each card's visible columns. Cards/metrics may unfold into one or more tables, so we
- resolve them lazily through `lib/visible-columns`."
- [metadata-provider cards]
- (into #{}
- (mapcat (fn [card]
- (try
- (->> (lib/query metadata-provider card)
- lib/visible-columns
- (keep :table-id))
- (catch Exception _ nil))))
- cards))
-
-(defn- in-scope-table-ids
- "Resolve the set of table-ids whose metadata the runtime needs in order to evaluate `program`.
-
- Walks the program for explicitly-referenced metadata IDs, then expands them:
- * field-ids → bulk-fetched in one query, contribute their `:table-id`;
- * card/metric-ids → bulk-fetched, expanded via `lib/visible-columns` to underlying tables;
- * measure-ids → bulk-fetched, contribute their `:table-id`;
- * source-entity from the context, when it's a table.
-
- We deliberately ignore the LLM-supplied `:referenced-entities` and `:surrounding-tables` —
- the operations and source declared by the program are the ground truth for what metadata
- needs to be loaded. If the agent references a table or field it forgot to declare, the
- walker still picks it up."
- [metadata-provider context program]
- (let [{:keys [table-ids field-ids card-ids metric-ids measure-ids]}
- (refs/collect-program-refs program)
- source-table-id (when (= "table" (some-> context :source-entity :model))
- (some-> context :source-entity :id))
- fields (when (seq field-ids)
- (lib.metadata/bulk-metadata metadata-provider :metadata/column field-ids))
- cards (when (or (seq card-ids) (seq metric-ids))
- (lib.metadata/bulk-metadata metadata-provider :metadata/card
- (into #{} cat [card-ids metric-ids])))
- measures (when (seq measure-ids)
- (lib.metadata/bulk-metadata metadata-provider :metadata/measure measure-ids))]
- (cond-> (set table-ids)
- source-table-id (conj source-table-id)
- (seq fields) (into (keep :table-id) fields)
- (seq cards) (into (card-underlying-table-ids metadata-provider cards))
- (seq measures) (into (keep :table-id) measures))))
-
-(mu/defn evaluate-program :- :map
- "Validate and interpret a structured MBQL program."
- [program :- :map
- metadata-providerable :- :any
- context :- validate/EvaluationContext]
- (log/debugf "Evaluating structured program with %d operations" (count (:operations program)))
- (let [program (validate/validated-program program context)
- mp (lib.metadata/->metadata-provider metadata-providerable)
- scope (in-scope-table-ids mp context program)
- runtime (runtime/build-runtime mp {:in-scope-table-ids scope
- :extra-bindings {'source (:source-metadata context)}})]
- (evaluate-program* runtime context [] program 0)))
diff --git a/src/metabase/agent_lib/eval/args.clj b/src/metabase/agent_lib/eval/args.clj
deleted file mode 100644
index c6f0020d97a..00000000000
--- a/src/metabase/agent_lib/eval/args.clj
+++ /dev/null
@@ -1,141 +0,0 @@
-(ns metabase.agent-lib.eval.args
- "Argument normalization for structured MBQL helper invocation."
- (:require
- [metabase.agent-lib.common.coercions :refer [normalize-percentile-value]]
- [metabase.agent-lib.common.errors :refer [invalid-program!]]
- [metabase.agent-lib.common.literals :refer [scalar-literal?]]))
-
-(def temporal-unit-values
- "Allowed string enum values for temporal units and buckets."
- #{"millisecond" "second" "minute" "hour" "day" "week" "month" "quarter" "year"})
-
-(def ^:private time-interval-amount-keywords
- "String values for time-interval amount that should be keywordized."
- #{"current" "last" "next"})
-
-(def order-direction-values
- "Allowed string enum values for order direction."
- #{"asc" "desc"})
-
-(def join-strategy-values
- "Allowed string enum values for explicit join strategy."
- #{"left-join" "inner-join" "right-join" "full-join"})
-
-(def join-fields-values
- "Allowed string enum values for explicit joined-field selection."
- #{"all" "none"})
-
-(def binning-strategy-values
- "Allowed string enum values for binning strategy."
- #{"bin-width" "default" "num-bins"})
-
-(set! *warn-on-reflection* true)
-
-(defn keyword-enum
- "Normalize string enum values into keywords for lib helpers."
- [path label value allowed-values]
- (cond
- (keyword? value)
- (if (allowed-values (name value))
- value
- (invalid-program! path (str label " must be one of " (sort allowed-values))))
-
- (string? value)
- (if (allowed-values value)
- (keyword value)
- (invalid-program! path (str label " must be one of " (sort allowed-values))))
-
- :else
- (invalid-program! path (str label " must be a string enum value"))))
-
-(defn normalize-helper-args
- "Normalize helper arguments into the forms expected by trusted lib bindings."
- [path op args]
- (case (name op)
- "in"
- (if (and (= 2 (count args))
- (vector? (second args))
- (every? scalar-literal? (second args)))
- (into [(first args)] (second args))
- args)
-
- "not-in"
- (if (and (= 2 (count args))
- (vector? (second args))
- (every? scalar-literal? (second args)))
- (into [(first args)] (second args))
- args)
-
- "time-interval"
- (-> args
- (update 1 (fn [amount]
- (cond
- (keyword? amount) amount
- (time-interval-amount-keywords amount) (keyword amount)
- :else amount)))
- (update 2 #(keyword-enum (conj path 3) "temporal unit" % temporal-unit-values)))
-
- "relative-time-interval"
- (-> args
- (update 2 #(keyword-enum (conj path 3) "temporal unit" % temporal-unit-values))
- (update 4 #(keyword-enum (conj path 5) "temporal unit" % temporal-unit-values)))
-
- "with-temporal-bucket"
- (update args 1 #(keyword-enum (conj path 2) "temporal bucket" % temporal-unit-values))
-
- "with-binning"
- (update args 1 (fn [binning]
- (if (and (map? binning)
- (some? (:strategy binning)))
- (update binning :strategy
- #(keyword-enum (conj path 2 :strategy)
- "binning strategy"
- %
- binning-strategy-values))
- binning)))
-
- "interval"
- (update args 1 #(keyword-enum (conj path 2) "interval unit" % temporal-unit-values))
-
- "relative-datetime"
- (update args 1 #(keyword-enum (conj path 2) "temporal unit" % temporal-unit-values))
-
- "absolute-datetime"
- (update args 1 #(keyword-enum (conj path 2) "temporal unit" % temporal-unit-values))
-
- "datetime-add"
- (update args 2 #(keyword-enum (conj path 3) "temporal unit" % temporal-unit-values))
-
- "datetime-diff"
- (update args 2 #(keyword-enum (conj path 3) "temporal unit" % temporal-unit-values))
-
- "datetime-subtract"
- (update args 2 #(keyword-enum (conj path 3) "temporal unit" % temporal-unit-values))
-
- "order-by"
- (if (= 2 (count args))
- (update args 1 #(keyword-enum (conj path 2) "order direction" % order-direction-values))
- args)
-
- "percentile"
- (update args 1 normalize-percentile-value)
-
- "with-join-strategy"
- (update args 1 #(keyword-enum (conj path 2) "join strategy" % join-strategy-values))
-
- "with-join-fields"
- (update args 1 (fn [value]
- (cond
- (or (keyword? value) (string? value))
- (keyword-enum (conj path 2) "join fields mode" value join-fields-values)
-
- (sequential? value)
- value
-
- (some? value)
- [value]
-
- :else
- value)))
-
- args))
diff --git a/src/metabase/agent_lib/eval/invoke.clj b/src/metabase/agent_lib/eval/invoke.clj
deleted file mode 100644
index 1264d0d7481..00000000000
--- a/src/metabase/agent_lib/eval/invoke.clj
+++ /dev/null
@@ -1,84 +0,0 @@
-(ns metabase.agent-lib.eval.invoke
- "Trusted helper invocation and error shaping for structured evaluation."
- (:require
- [metabase.agent-lib.common.errors :as errors :refer [invalid-program! path->string]]
- [metabase.agent-lib.mbql-integration :as mbql]
- [metabase.agent-lib.runtime :as runtime]
- [metabase.util.log :as log]))
-
-(set! *warn-on-reflection* true)
-
-(defn invoke-helper!
- "Invoke a helper that does not depend on the current query state."
- [runtime path op args]
- (when-not (contains? runtime/helper-symbols op)
- (invalid-program! path "unknown operator" {:operator (name op)}))
- (let [helper (runtime/helper-fn runtime op)]
- (try
- (apply helper args)
- (catch clojure.lang.ArityException e
- (invalid-program! path
- (str "invalid arity for operator `" (name op) "`: " (ex-message e))
- {:operator (name op)}))
- (catch Exception e
- (log/debugf e "Helper `%s` at %s threw unexpectedly" (name op) (path->string path))
- (throw (errors/wrap-runtime-error path (name op) e))))))
-
-(defn invoke-query-aware-helper!
- "Invoke a helper that requires the current query state."
- [runtime current-query path op args]
- (when-not current-query
- (invalid-program! path
- (format "`%s` requires the current query state" (name op))
- {:operator (name op)}))
- (let [helper (runtime/helper-fn runtime op)
- op-name (name op)]
- (try
- (apply helper current-query args)
- (catch clojure.lang.ArityException e
- (invalid-program! path
- (str "invalid arity for operator `" op-name "`: " (ex-message e))
- {:operator op-name}))
- (catch Exception e
- (case op-name
- "expression-ref"
- (invalid-program! path
- (format "expression-ref %s does not exist at this point in the query"
- (pr-str (first args)))
- {:operator "expression-ref"
- :name (first args)})
-
- "aggregation-ref"
- (invalid-program! path
- (format "aggregation-ref %s does not exist at this point in the query"
- (first args))
- {:operator "aggregation-ref"
- :index (first args)})
-
- (do (log/debugf e "Query-aware helper `%s` at %s threw unexpectedly" op-name (path->string path))
- (throw (errors/wrap-runtime-error path op-name e))))))))
-
-(defn invoke-field-helper!
- "Invoke the special `field` helper, which can resolve relative to the current query."
- [runtime current-query path args]
- (if current-query
- (let [helper (runtime/helper-fn runtime 'field)]
- (try
- (apply helper current-query args)
- (catch clojure.lang.ArityException e
- (invalid-program! path
- (str "invalid arity for operator `field`: " (ex-message e))
- {:operator "field"}))
- (catch Exception e
- (log/debugf e "Field helper at %s threw unexpectedly" (path->string path))
- (throw (errors/wrap-runtime-error path "field" e)))))
- (invoke-helper! runtime path 'field args)))
-
-(defn ensure-query-result!
- "Assert that structured evaluation produced a MBQL 5 query."
- [result]
- (when-not (mbql/query? result)
- (throw (ex-info "Structured program evaluation must return a MBQL 5 query map."
- {:result-type (type result)
- :result result})))
- result)
diff --git a/src/metabase/agent_lib/eval/source.clj b/src/metabase/agent_lib/eval/source.clj
deleted file mode 100644
index bc7d9ace37c..00000000000
--- a/src/metabase/agent_lib/eval/source.clj
+++ /dev/null
@@ -1,29 +0,0 @@
-(ns metabase.agent-lib.eval.source
- "Structured source resolution for program evaluation."
- (:require
- [metabase.agent-lib.common.errors :refer [invalid-program!]]
- [metabase.agent-lib.runtime :as runtime]))
-
-(set! *warn-on-reflection* true)
-
-(defn resolve-source
- "Resolve a structured program source into metadata or a query."
- [evaluate-program runtime source-path source]
- (case (:type source)
- "context"
- (or (get (runtime/bindings-map runtime) 'source)
- (invalid-program! source-path "context source is unavailable in runtime bindings"))
-
- "table"
- ((runtime/helper-fn runtime 'table) (:id source))
-
- ("card" "dataset")
- ((runtime/helper-fn runtime 'card) (:id source))
-
- "metric"
- ((runtime/helper-fn runtime 'metric) (:id source))
-
- "program"
- (evaluate-program (conj source-path :program) (:program source))
-
- (invalid-program! (conj source-path :type) "unsupported source type")))
diff --git a/src/metabase/agent_lib/eval/walker.clj b/src/metabase/agent_lib/eval/walker.clj
deleted file mode 100644
index 09b3bd6f71f..00000000000
--- a/src/metabase/agent_lib/eval/walker.clj
+++ /dev/null
@@ -1,89 +0,0 @@
-(ns metabase.agent-lib.eval.walker
- "Recursive structured-value evaluation for agent-lib.
-
- The local `letfn` in `evaluate-node` is intentional: this namespace is the
- recursive evaluation boundary for nested structured program values."
- (:require
- [metabase.agent-lib.common.coercions :refer [normalize-map-key]]
- [metabase.agent-lib.common.errors :refer [invalid-program!]]
- [metabase.agent-lib.common.literals :refer [scalar-literal?]]
- [metabase.agent-lib.eval.args :as eval.args]
- [metabase.agent-lib.eval.invoke :as eval.invoke]
- [metabase.agent-lib.runtime :as runtime]
- [metabase.agent-lib.schema :as schema]
- [metabase.agent-lib.syntax :as syntax]))
-
-(set! *warn-on-reflection* true)
-
-(defn evaluate-args
- "Evaluate and normalize helper arguments in the current query context."
- [eval-node-fn current-query node-path op raw-args]
- (->> raw-args
- (map-indexed (fn [idx arg]
- (eval-node-fn current-query (conj node-path (inc idx)) arg)))
- vec
- (eval.args/normalize-helper-args node-path op)))
-
-(defn evaluate-node
- "Evaluate a nested structured value in the current query context."
- [evaluate-program runtime current-query node-path value]
- (letfn [(walk [current-query node-path value]
- (cond
- (scalar-literal? value)
- value
-
- (map? value)
- (if (schema/program-literal? value)
- (evaluate-program (conj node-path :program) (:program value))
- (into {}
- (map (fn [[k v]]
- [(normalize-map-key k)
- (walk current-query (conj node-path (normalize-map-key k)) v)]))
- value))
-
- (vector? value)
- (if (syntax/operator-tuple? value)
- (let [[raw-op & raw-args] value
- op (runtime/op-symbol raw-op)
- op-name (name op)]
- (cond
- (syntax/top-level-operation-symbols op)
- (invalid-program! node-path
- (format "`%s` is a top-level operation and cannot be nested" op-name)
- {:operator op-name})
-
- (= op 'query)
- (invalid-program! node-path
- "`query` cannot appear inside operations; the program source already defines the base query."
- {:operator "query"})
-
- (= op 'field)
- (eval.invoke/invoke-field-helper! runtime
- current-query
- node-path
- (evaluate-args walk current-query node-path 'field raw-args))
-
- ('#{expression-ref aggregation-ref} op)
- (eval.invoke/invoke-query-aware-helper! runtime
- current-query
- node-path
- op
- (evaluate-args walk current-query node-path op raw-args))
-
- :else
- (eval.invoke/invoke-helper! runtime
- node-path
- op
- (evaluate-args walk current-query node-path op raw-args))))
- (mapv (fn [[idx element]]
- (walk current-query (conj node-path idx) element))
- (map-indexed vector value)))
-
- (sequential? value)
- (mapv (fn [[idx element]]
- (walk current-query (conj node-path idx) element))
- (map-indexed vector value))
-
- :else
- value))]
- (walk current-query node-path value)))
diff --git a/src/metabase/agent_lib/join_spec.clj b/src/metabase/agent_lib/join_spec.clj
deleted file mode 100644
index 8b5abcf2db5..00000000000
--- a/src/metabase/agent_lib/join_spec.clj
+++ /dev/null
@@ -1,80 +0,0 @@
-(ns metabase.agent-lib.join-spec
- "Shared parsing helpers for explicit join clauses."
- (:require
- [metabase.agent-lib.common.coercions :refer [normalize-direction]]
- [metabase.agent-lib.syntax :as syntax]))
-
-(set! *warn-on-reflection* true)
-
-(defn program-field-ref-id
- "Return the field id when `form` is a canonical `[\"field\", id]` tuple."
- [form]
- (when (and (vector? form)
- (= "field" (syntax/canonical-op-name (first form)))
- (pos-int? (second form)))
- (second form)))
-
-(defn parse-join-condition-pair
- "Parse a join equality condition into a `[lhs-id rhs-id]` pair."
- [condition]
- (when (and (vector? condition)
- (= "=" (syntax/canonical-op-name (first condition)))
- (= 3 (count condition)))
- (when-let [lhs-id (program-field-ref-id (second condition))]
- (when-let [rhs-id (program-field-ref-id (nth condition 2))]
- [lhs-id rhs-id]))))
-
-(defn parse-join-spec
- "Parse nested join-clause wrappers into a normalized join-spec map."
- [form]
- (when (vector? form)
- (let [[raw-op & args] form
- op-name (syntax/canonical-op-name raw-op)]
- (case op-name
- "join-clause"
- (let [target (first args)]
- (when (and (vector? target)
- (= "table" (syntax/canonical-op-name (first target)))
- (pos-int? (second target)))
- {:target-table-id (second target)
- :conditions nil
- :fields-mode nil
- :strategy nil
- :alias nil}))
-
- "with-join-conditions"
- (when-let [parsed (parse-join-spec (first args))]
- (let [conditions (second args)
- pairs (when (sequential? conditions)
- (mapv parse-join-condition-pair conditions))]
- (when (and (seq pairs)
- (every? some? pairs))
- (assoc parsed :conditions pairs))))
-
- "with-join-fields"
- (when-let [parsed (parse-join-spec (first args))]
- (assoc parsed :fields-mode (second args)))
-
- "with-join-strategy"
- (when-let [parsed (parse-join-spec (first args))]
- (assoc parsed :strategy (normalize-direction (second args))))
-
- "with-join-alias"
- (when-let [parsed (parse-join-spec (first args))]
- (assoc parsed :alias (second args)))
-
- nil))))
-
-(defn no-explicit-join-fields?
- "True when a join spec does not explicitly request joined fields."
- [fields-mode]
- (or (nil? fields-mode)
- (= "none" fields-mode)
- (= :none fields-mode)))
-
-(defn implicit-join-compatible-fields-mode?
- "True when explicit join fields still match implicit related-field semantics."
- [fields-mode]
- (or (no-explicit-join-fields? fields-mode)
- (= "all" fields-mode)
- (= :all fields-mode)))
diff --git a/src/metabase/agent_lib/mbql_integration.clj b/src/metabase/agent_lib/mbql_integration.clj
deleted file mode 100644
index ea6ded51085..00000000000
--- a/src/metabase/agent_lib/mbql_integration.clj
+++ /dev/null
@@ -1,76 +0,0 @@
-(ns metabase.agent-lib.mbql-integration
- "Temporary bridge between agent-lib and canonical MBQL lib APIs.
-
- This namespace is the stable facade over the smaller MBQL integration units
- under `metabase.agent-lib.mbql-integration.*`. It remains the single handoff
- surface that agent-lib callers depend on, while the actual implementation is
- split by concern."
- (:require
- [metabase.agent-lib.mbql-integration.common]
- [metabase.agent-lib.mbql-integration.fields]
- [metabase.agent-lib.mbql-integration.joins]
- [metabase.agent-lib.mbql-integration.orderables]
- [potemkin :as p]))
-
-(set! *warn-on-reflection* true)
-
-(p/import-vars
- [metabase.agent-lib.mbql-integration.common
- query?
- extract-field-ids
- expression-definition
- normalized-name
- column-names
- dedupe-candidate-columns
- current-query-field-candidates
- prefer-single-candidate
- unique-query-candidate
- field-selection?
- resolve-aggregation-selection]
- [metabase.agent-lib.mbql-integration.fields
- fields-by-table-id
- field-target-table-id
- field-path-start-ids
- fk-path-to-table
- numeric-type?
- types-compatible?
- candidate-has-resolution-lineage?
- source-column-field-name
- source-column-field-join-alias
- source-column-original-field-id
- source-column-original-field-name
- source-column-original-field-join-alias
- candidate-join-alias-for-field-id
- synthesize-chained-related-field
- multi-hop-lineage-candidate?
- previous-stage-name-matches
- previous-stage-lineage-matches
- previous-stage-aggregation-matches
- resolve-field-in-query]
- [metabase.agent-lib.mbql-integration.orderables
- matching-expression-ref
- matching-previous-stage-column-by-name
- current-stage-expression-ref
- expression-ref-or-current-stage-column
- ensure-query-expression-ref
- orderable-column-key
- current-query-orderable-candidates
- column-field-ids
- breakout-expression-name
- previous-stage-aggregation-column
- aggregation-ref-or-current-stage-column
- aggregation-signature
- aggregation-columns
- aggregation-column-pairs
- requested-orderable-field-ids
- orderable-field-id->query-columns
- orderable-field-ids->query-columns
- field-id->breakout-expression-refs
- field-ids->breakout-expression-ref
- field-id->aggregation-columns
- field-ids->aggregation-columns
- resolve-field-like-orderable
- resolve-orderable]
- [metabase.agent-lib.mbql-integration.joins
- implicitly-resolved-column?
- redundant-implicit-join?])
diff --git a/src/metabase/agent_lib/mbql_integration/common.clj b/src/metabase/agent_lib/mbql_integration/common.clj
deleted file mode 100644
index e7bed060096..00000000000
--- a/src/metabase/agent_lib/mbql_integration/common.clj
+++ /dev/null
@@ -1,266 +0,0 @@
-(ns metabase.agent-lib.mbql-integration.common
- "Common MBQL bridge helpers shared by agent-lib field, filter, and orderable integration."
- (:require
- [metabase.lib.core :as lib]
- [metabase.lib.util :as lib.util]
- [metabase.util :as u]))
-
-(set! *warn-on-reflection* true)
-
-(defn query?
- "Return true when `value` is a normalized MBQL 5 query map.
-
- Agent-lib needs to distinguish queries from metadata maps, columns, and test
- sentinels, but it should not inspect `:lib/type` directly. This helper keeps
- that boundary on top of `lib/normalized-query-type` and guards the lib call so
- non-query maps fail closed instead of blowing up.
-
- Example:
- (query? (lib/query metadata-provider table-metadata))
- ;; => true
-
- (query? {:id 1 :name \"Orders\"})
- ;; => false"
- [value]
- (and (map? value)
- (= :mbql/query (lib/normalized-query-type value))))
-
-(defn extract-field-ids
- "Return the set of field ids referenced anywhere inside a MBQL 5 form.
-
- Agent-lib compares expressions, aggregations, breakouts, and columns
- semantically. The canonical lib helper already knows how to walk MBQL safely,
- so this wrapper keeps callers out of tuple destructuring.
-
- Example:
- (extract-field-ids
- [:+
- {}
- [:field {} 10]
- [:field {} 20]])
- ;; => #{10 20}"
- [x]
- (lib/all-field-ids x))
-
-(defn expression-definition
- "Return `x` when it is a named expression definition, else nil.
-
- Agent-lib accepts both fully defined expressions and references to existing
- expressions. The MBQL layer already owns the naming rules, so this helper just
- asks lib whether the form has an expression name and otherwise leaves the
- structure alone.
-
- Example:
- (expression-definition
- [:expression {} \"Net Amount\"
- [:- {} [:field {} 1] [:field {} 2]]])
- ;; => that same tuple
-
- (expression-definition [:field {} 1])
- ;; => nil"
- [x]
- (when (lib.util/expression-name x)
- x))
-
-(defn normalized-name
- "Normalize a display name for case-insensitive matching.
-
- Agent-lib compares program-provided names against MBQL column names, aliases,
- and ref names. Matching needs to be locale-stable, so this goes through
- `lower-case-en` instead of generic lowercase.
-
- Example:
- (normalized-name \"Net Amount\")
- ;; => \"net amount\"
-
- (normalized-name nil)
- ;; => nil"
- [value]
- (when (string? value)
- (u/lower-case-en value)))
-
-(defn column-names
- "Return every comparable name by which a query column may be recognized.
-
- The same semantic column can surface through several lib metadata keys:
- `:name`, `:lib/source-column-alias`, `:lib/original-name`,
- `:lib/deduplicated-name`, and `:lib/ref-name`. Agent-lib collapses those into
- one normalized set so later matching logic can ask one question: \"does this
- column look like the requested thing?\"
-
- Example:
- (column-names {:name \"Title\"
- :lib/source-column-alias \"product_title\"
- :lib/ref-name \"Products -> Title\"})
- ;; => #{\"title\" \"product_title\" \"products -> title\"}"
- [column]
- (->> [(:name column)
- (:lib/source-column-alias column)
- (:lib/original-name column)
- (:lib/deduplicated-name column)
- (:lib/ref-name column)]
- (keep normalized-name)
- set))
-
-(defn column-join-alias
- "Return the join alias attached to a visible/query column, if any.
-
- Lib can surface the active alias on `:lib/join-alias` or preserve the
- original alias on `:lib/original-join-alias`. Agent-lib only needs one answer
- when deciding whether a match came from an explicit join.
-
- Example:
- (column-join-alias {:lib/join-alias \"Products\"})
- ;; => \"Products\""
- [column]
- ((some-fn :lib/join-alias :lib/original-join-alias) column))
-
-(defn- candidate-column-key
- [column]
- [(:id column)
- (:table-id column)
- (:name column)
- (:source-field column)
- (:source-field-name column)
- (:source-field-join-alias column)
- (column-join-alias column)
- (:fk-field-id column)
- (:fk-field-name column)
- (:fk-join-alias column)
- (:lib/original-fk-field-id column)
- (:lib/original-fk-field-name column)
- (:lib/original-fk-join-alias column)
- (:lib/source column)
- (:lib/source-uuid column)
- (:lib/expression-name column)
- (:lib/temporal-unit column)
- (:inherited-temporal-unit column)])
-
-(defn dedupe-candidate-columns
- "Deduplicate candidate columns while preserving the first structurally
- distinct representative.
-
- Agent-lib merges columns from several lib surfaces such as `visible-columns`,
- `fieldable-columns`, and `orderable-columns`. The same semantic column often
- appears more than once. We collapse duplicates, but we keep join alias, FK
- lineage, source UUID, expression name, and temporal metadata in the key so we
- do not merge columns that only look similar.
-
- Example:
- (dedupe-candidate-columns
- [{:id 10 :name \"Title\"}
- {:id 10 :name \"Title\"}
- {:id 10 :name \"Title\" :lib/join-alias \"Products\"}])
- ;; => keeps the plain column and the joined column"
- [columns]
- (vals
- (reduce (fn [acc column]
- (let [k (candidate-column-key column)]
- (if (contains? acc k)
- acc
- (assoc acc k column))))
- {}
- columns)))
-
-(defn current-query-field-candidates
- "Return the deduplicated field-like columns visible from the current query
- stage.
-
- Agent programs name semantic fields, but the current stage may expose them as
- visible columns, fieldable columns, filterable columns, breakoutable columns,
- or orderable columns. This helper builds the combined search space used by
- field resolution.
-
- Example:
- A field that is hidden from the result set but still filterable remains
- resolvable because this helper includes `lib/filterable-columns`."
- [query]
- (->> [(lib/fieldable-columns query)
- (lib/visible-columns query)
- (lib/filterable-columns query)
- (lib/breakoutable-columns query)
- (lib/orderable-columns query)]
- (apply concat)
- dedupe-candidate-columns
- vec))
-
-(defn prefer-single-candidate
- "Return the single deterministic winner from an otherwise ambiguous candidate
- set, or nil when agent-lib should keep looking.
-
- This is the extracted tie-breaker used by `unique-query-candidate`:
- prefer one unaliased column over joined columns, then prefer one explicit
- field over an FK-derived expansion.
-
- Example:
- Given `[Orders.ID, Products.ID via implicit join]`, the unaliased
- `Orders.ID` candidate wins."
- [candidates]
- (or (when-let [unaliased (not-empty (remove column-join-alias candidates))]
- (when-not (next unaliased)
- (first unaliased)))
- (when-let [explicit (not-empty (remove :fk-field-id candidates))]
- (when-not (next explicit)
- (first explicit)))))
-
-(defn unique-query-candidate
- "Return a single candidate after applying agent-lib's tie-break rules.
-
- Some lib lookups intentionally return more than one plausible column. When
- that happens, agent-lib prefers:
- 1. a single unaliased column over a joined one
- 2. a single column without FK lineage over a related-field expansion
-
- This keeps agent behavior deterministic without forcing callers to know the
- ranking policy.
-
- Example:
- If candidates are `[Orders.ID, Products.ID via implicit join]`, the plain
- `Orders.ID` column wins."
- [candidates]
- (or (when (= 1 (count candidates))
- (first candidates))
- (prefer-single-candidate (vec candidates))))
-
-(defn field-selection?
- "Return true when `selection` behaves like a field for `with-fields`.
-
- `with-fields` in agent-lib accepts both literal field clauses and lib column
- maps that can be turned back into field refs. This helper centralizes that
- check so callers do not branch on raw ref tags.
-
- Example:
- (field-selection? [:field {} 10])
- ;; => true
-
- (field-selection? {:id 10 :name \"Title\"})
- ;; => true when `(lib/ref ...)` yields a field ref"
- [selection]
- (or (lib.util/field-clause? selection)
- (when (map? selection)
- (let [selection-ref (try
- (lib/ref selection)
- (catch Exception _
- nil))]
- (boolean
- (or (some-> selection-ref lib/field-ref-id)
- (some-> selection-ref lib/field-ref-name)))))))
-
-(defn resolve-aggregation-selection
- "Resolve an aggregation selection back to the visible current-stage column
- when one exists.
-
- Some agent operations conceptually choose \"the aggregated result column\",
- while the syntax still names it as an aggregation ref. When lib can map that
- ref to the visible column, we use the column so downstream helpers treat it
- like any other selected field.
-
- Example:
- Given a query with `(lib/aggregate (lib/count))`, resolving
- `(lib/aggregation-ref query 0)` returns the visible count column instead of
- leaving the raw ref in place."
- [query selection]
- (if (lib.util/clause-of-type? selection :aggregation)
- (or (lib/find-visible-column-for-ref query selection)
- selection)
- selection))
diff --git a/src/metabase/agent_lib/mbql_integration/field_resolution.clj b/src/metabase/agent_lib/mbql_integration/field_resolution.clj
deleted file mode 100644
index 3a810b1cf30..00000000000
--- a/src/metabase/agent_lib/mbql_integration/field_resolution.clj
+++ /dev/null
@@ -1,350 +0,0 @@
-(ns metabase.agent-lib.mbql-integration.field-resolution
- "Field-resolution helpers for the agent-lib MBQL bridge."
- (:require
- [clojure.set :as set]
- [clojure.string :as str]
- [metabase.agent-lib.mbql-integration.common :as common]
- [metabase.lib.core :as lib]
- [metabase.lib.util :as lib.util]))
-
-(set! *warn-on-reflection* true)
-
-(defn fields-by-table-id
- "Group metadata fields by table id for lookup-heavy resolution helpers."
- [fields-by-id]
- (reduce-kv (fn [acc _field-id field]
- (update acc (:table-id field) (fnil conj []) field))
- {}
- fields-by-id))
-
-(defn field-target-table-id
- "Return the table id reached by following a field's FK target metadata."
- [fields-by-id field-id]
- (when-let [target-field-id (some-> (get fields-by-id field-id) :fk-target-field-id)]
- (:table-id (get fields-by-id target-field-id))))
-
-(defn field-path-start-ids
- "Return the field ids that can anchor lineage for a surfaced query column."
- [column]
- (->> [(:source-field column)
- (:fk-field-id column)
- (:lib/original-fk-field-id column)
- (:id column)]
- (filter pos-int?)
- distinct))
-
-(defn fk-path-to-table
- "Return the unique FK chain from `start-field-id` to `target-table-id`, or
- nil when none or more than one plausible path exists.
-
- The local `walk-path` stays nested because it is the only genuinely recursive
- helper left in this file."
- [fields-by-id start-field-id target-table-id]
- (let [fields-by-table (fields-by-table-id fields-by-id)]
- (letfn [(walk-path [field-id visited depth]
- (when (and (pos-int? field-id)
- (not (visited field-id))
- (< depth 4))
- (when-let [next-table-id (field-target-table-id fields-by-id field-id)]
- (if (= next-table-id target-table-id)
- [[field-id]]
- (not-empty
- (mapcat (fn [candidate]
- (map #(into [field-id] %)
- (or (walk-path (:id candidate)
- (conj visited field-id)
- (inc depth))
- [])))
- (get fields-by-table next-table-id)))))))]
- (let [paths (vec (walk-path start-field-id #{} 0))]
- (when (= 1 (count paths))
- (first paths))))))
-
-(defn numeric-type?
- "True when `type` is one of the numeric MBQL types agent-lib treats as
- interchangeable for previous-stage reuse."
- [type]
- (contains? #{"type/BigInteger"
- "type/Decimal"
- "type/Float"
- "type/Integer"
- "type/Number"}
- (cond
- (keyword? type) (str (namespace type) "/" (name type))
- (string? type) type
- :else nil)))
-
-(defn types-compatible?
- "True when `raw-field` and `candidate` can safely stand in for each other by
- type."
- [raw-field candidate]
- (let [raw-type ((some-fn :effective-type :base-type) raw-field)
- candidate-type ((some-fn :effective-type :base-type) candidate)]
- (or (nil? raw-type)
- (nil? candidate-type)
- (= raw-type candidate-type)
- (and (numeric-type? raw-type)
- (numeric-type? candidate-type)))))
-
-(defn candidate-has-resolution-lineage?
- "True when a candidate column carries lineage metadata that makes it a better
- resolution target than a bare id/name match."
- [column]
- (boolean
- (or (:fk-field-id column)
- (:fk-field-name column)
- (:fk-join-alias column)
- (:lib/original-fk-field-id column)
- (:lib/original-fk-field-name column)
- (:lib/original-fk-join-alias column)
- (common/column-join-alias column)
- (:lib/source-uuid column)
- (:lib/expression-name column)
- (= :source/previous-stage (:lib/source column)))))
-
-(defn source-column-field-name
- "Return the best human-readable field name carried by a surfaced source
- column."
- [column]
- ((some-fn :lib/source-column-alias
- :name
- :lib/original-name
- :fk-field-name
- :lib/original-fk-field-name)
- column))
-
-(defn source-column-field-join-alias
- "Return the most specific join alias associated with a surfaced source
- column."
- [column]
- ((some-fn common/column-join-alias :fk-join-alias :lib/original-fk-join-alias) column))
-
-(defn source-column-original-field-id
- "Return the original field id carried by a surfaced source column."
- [column]
- ((some-fn :lib/original-fk-field-id :source-field) column))
-
-(defn source-column-original-field-name
- "Return the original field name carried by a surfaced source column."
- [column]
- ((some-fn :lib/original-fk-field-name :source-field-name) column))
-
-(defn source-column-original-field-join-alias
- "Return the original join alias carried by a surfaced source column."
- [column]
- ((some-fn :lib/original-fk-join-alias :source-field-join-alias) column))
-
-(defn candidate-join-alias-for-field-id
- "Return a unique join alias for columns whose lineage includes `field-id`."
- [candidates field-id]
- (when (pos-int? field-id)
- (let [matches (->> candidates
- (keep (fn [candidate]
- (when (some #{field-id} (field-path-start-ids candidate))
- ((some-fn common/column-join-alias
- :fk-join-alias
- :lib/original-fk-join-alias)
- candidate))))
- distinct
- vec)]
- (when (= 1 (count matches))
- (first matches)))))
-
-(defn synthesize-chained-related-field
- "Project lineage from a surfaced source column back onto the requested raw
- field shape.
-
- This is the agent-lib-specific bridge for multi-hop related fields until lib
- exposes a canonical helper for the same behavior."
- [fields-by-id candidates raw-field source-column path]
- (let [immediate-field-id (last path)
- immediate-field (get fields-by-id immediate-field-id)
- original-field-id (or (source-column-original-field-id source-column)
- (when (> (count path) 1)
- (first path)))
- original-field (get fields-by-id original-field-id)
- original-field-name (or (source-column-original-field-name source-column)
- (:name original-field))
- immediate-field-name (or (:name immediate-field)
- (source-column-field-name source-column))
- immediate-join-alias (or (source-column-field-join-alias source-column)
- (candidate-join-alias-for-field-id candidates immediate-field-id)
- (candidate-join-alias-for-field-id candidates original-field-id))
- original-join-alias (or (source-column-original-field-join-alias source-column)
- (candidate-join-alias-for-field-id candidates original-field-id)
- immediate-join-alias)]
- (cond-> raw-field
- immediate-field-id (assoc :fk-field-id immediate-field-id)
- immediate-field-name (assoc :fk-field-name immediate-field-name)
- immediate-join-alias (assoc :fk-join-alias immediate-join-alias)
- original-field-id (assoc :lib/original-fk-field-id original-field-id)
- original-field-name (assoc :lib/original-fk-field-name original-field-name)
- original-join-alias (assoc :lib/original-fk-join-alias original-join-alias))))
-
-(defn multi-hop-lineage-candidate?
- "True when a synthesized related field captures more than one hop of lineage."
- [column]
- (boolean
- (or (let [immediate-field-id (:fk-field-id column)
- original-field-id (:lib/original-fk-field-id column)]
- (and (pos-int? immediate-field-id)
- (pos-int? original-field-id)
- (not= immediate-field-id original-field-id)))
- (let [immediate-field-name (:fk-field-name column)
- original-field-name (:lib/original-fk-field-name column)]
- (and (string? immediate-field-name)
- (string? original-field-name)
- (not= immediate-field-name original-field-name)))
- (let [immediate-join-alias (:fk-join-alias column)
- original-join-alias (:lib/original-fk-join-alias column)]
- (and (string? immediate-join-alias)
- (string? original-join-alias)
- (not= immediate-join-alias original-join-alias))))))
-
-(defn previous-stage-name-matches
- "Return previous-stage candidates whose comparable names overlap the requested
- raw field."
- [raw-field previous-stage-candidates]
- (let [raw-field-names (common/column-names raw-field)]
- (->> previous-stage-candidates
- (filter (fn [candidate]
- (seq (set/intersection raw-field-names (common/column-names candidate)))))
- vec)))
-
-(defn previous-stage-lineage-matches
- "Return previous-stage candidates whose lineage points back to `raw-field`.
-
- This is stricter than `types-compatible?`: appended stages may expose only
- aggregations, and agent-lib should only treat those as substitutes for a raw
- field when lib metadata preserves a real source-field lineage for that field."
- [raw-field previous-stage-candidates]
- (let [raw-field-id (:id raw-field)]
- (->> previous-stage-candidates
- (filter (fn [candidate]
- (and (pos-int? raw-field-id)
- (some #{raw-field-id} (field-path-start-ids candidate)))))
- vec)))
-
-(defn previous-stage-aggregation-matches
- "Return previous-stage columns whose `:lib/source-uuid` comes from an
- aggregation over `raw-field`."
- [query raw-field previous-stage-candidates]
- (when-let [previous-stage-number (some-> query (lib.util/previous-stage-number -1))]
- (let [raw-field-id (:id raw-field)
- matching-uuids (->> (map vector
- (lib/aggregations query previous-stage-number)
- (lib/aggregations-metadata query previous-stage-number))
- (keep (fn [[aggregation metadata]]
- (when (and (pos-int? raw-field-id)
- (some #{raw-field-id} (common/extract-field-ids aggregation)))
- (:lib/source-uuid metadata))))
- set)]
- (->> previous-stage-candidates
- (filter #(contains? matching-uuids (:lib/source-uuid %)))
- vec))))
-
-(defn- chained-related-candidates
- "Compute chained related-field candidates by walking FK paths from each
- candidate back to the raw field's table."
- [fields-by-id candidates raw-field]
- (let [target-table-id (:table-id raw-field)]
- (->> candidates
- (keep (fn [column]
- (when-let [path (some #(fk-path-to-table fields-by-id % target-table-id)
- (field-path-start-ids column))]
- (synthesize-chained-related-field fields-by-id candidates raw-field column path))))
- common/dedupe-candidate-columns
- vec)))
-
-(defn- previous-stage-candidates
- "Compute previous-stage candidates that are type-compatible with `raw-field`."
- [candidates raw-field]
- (->> candidates
- (filter #(and (= :source/previous-stage (:lib/source %))
- (types-compatible? raw-field %)))
- vec))
-
-(defn- try-strategies
- "Try resolution strategies in priority order, returning the first match."
- [strategies]
- (some (fn [{:keys [resolve-fn]}] (resolve-fn)) strategies))
-
-(defn- summarize-candidate
- "Compact shape of a candidate column for inclusion in field-resolution errors."
- [candidate]
- (let [field-name (source-column-field-name candidate)
- join-alias (source-column-field-join-alias candidate)]
- (cond-> {}
- (:id candidate) (assoc :id (:id candidate))
- field-name (assoc :name field-name)
- (:table-id candidate) (assoc :table-id (:table-id candidate))
- join-alias (assoc :join-alias join-alias))))
-
-(defn- format-candidate-line
- [{:keys [id name table-id join-alias]}]
- (str "- " (or name "?")
- " (id=" (or id "?")
- (when table-id (str ", table-id=" table-id))
- (when join-alias (str ", join-alias=" (pr-str join-alias)))
- ")"))
-
-(def ^:private max-candidates-in-error 20)
-
-(defn- unavailable-field-error
- [raw-field query candidates]
- (let [summaries (mapv summarize-candidate candidates)
- shown (take max-candidates-in-error summaries)
- extra (max 0 (- (count summaries) max-candidates-in-error))
- fields-block (if (seq shown)
- (str "Fields available in this stage:\n"
- (str/join "\n" (mapv format-candidate-line shown))
- (when (pos? extra) (str "\n... and " extra " more")))
- "No fields are visible in this stage.")]
- (ex-info (str "Field " (pr-str (:name raw-field))
- " (id " (pr-str (:id raw-field))
- ") is not available in the current query stage.\n"
- fields-block)
- {:field raw-field
- :query query
- :available-fields summaries})))
-
-(defn resolve-field-in-query
- "Resolve a metadata field against what the current query stage actually
- exposes.
-
- Resolution strategies are tried in priority order; each is computed lazily
- so we stop as soon as one succeeds."
- ([fields-by-id query raw-field]
- (resolve-field-in-query fields-by-id query raw-field (common/current-query-field-candidates query)))
- ([fields-by-id query raw-field candidates]
- (let [query (when (common/query? query) query)
- by-id+tbl (fn [] (filterv #(and (= (:id raw-field) (:id %))
- (= (:table-id raw-field) (:table-id %)))
- candidates))
- by-id (fn [] (filterv #(= (:id raw-field) (:id %)) candidates))
- lined (fn [cs] (filterv candidate-has-resolution-lineage? cs))
- chained (delay (chained-related-candidates fields-by-id candidates raw-field))
- prev-stage (delay (previous-stage-candidates candidates raw-field))]
- (or (try-strategies
- [{:name :multi-hop-chained-lineage
- :resolve-fn #(common/unique-query-candidate (filterv multi-hop-lineage-candidate? @chained))}
- {:name :exact-id+table-with-lineage
- :resolve-fn #(common/unique-query-candidate (lined (by-id+tbl)))}
- {:name :exact-id-with-lineage
- :resolve-fn #(common/unique-query-candidate (lined (by-id)))}
- {:name :previous-stage-lineage-or-aggregation
- :resolve-fn #(common/unique-query-candidate
- (->> (concat (previous-stage-lineage-matches raw-field @prev-stage)
- (previous-stage-aggregation-matches query raw-field @prev-stage))
- common/dedupe-candidate-columns vec))}
- {:name :previous-stage-name
- :resolve-fn #(common/unique-query-candidate (previous-stage-name-matches raw-field @prev-stage))}
- {:name :chained-related-fields
- :resolve-fn #(common/unique-query-candidate @chained)}
- {:name :lib-find-matching-column
- :resolve-fn #(when query (lib/find-matching-column query -1 raw-field candidates))}
- {:name :exact-id+table
- :resolve-fn #(common/unique-query-candidate (by-id+tbl))}
- {:name :exact-id
- :resolve-fn #(common/unique-query-candidate (by-id))}])
- (throw (unavailable-field-error raw-field query candidates))))))
diff --git a/src/metabase/agent_lib/mbql_integration/fields.clj b/src/metabase/agent_lib/mbql_integration/fields.clj
deleted file mode 100644
index 0b0cdf48382..00000000000
--- a/src/metabase/agent_lib/mbql_integration/fields.clj
+++ /dev/null
@@ -1,29 +0,0 @@
-(ns metabase.agent-lib.mbql-integration.fields
- "Facade over field-resolution MBQL bridge helpers."
- (:require
- [metabase.agent-lib.mbql-integration.field-resolution]
- [potemkin :as p]))
-
-(set! *warn-on-reflection* true)
-
-(p/import-vars
- [metabase.agent-lib.mbql-integration.field-resolution
- fields-by-table-id
- field-target-table-id
- field-path-start-ids
- fk-path-to-table
- numeric-type?
- types-compatible?
- candidate-has-resolution-lineage?
- source-column-field-name
- source-column-field-join-alias
- source-column-original-field-id
- source-column-original-field-name
- source-column-original-field-join-alias
- candidate-join-alias-for-field-id
- synthesize-chained-related-field
- multi-hop-lineage-candidate?
- previous-stage-name-matches
- previous-stage-lineage-matches
- previous-stage-aggregation-matches
- resolve-field-in-query])
diff --git a/src/metabase/agent_lib/mbql_integration/joins.clj b/src/metabase/agent_lib/mbql_integration/joins.clj
deleted file mode 100644
index fcb02a88305..00000000000
--- a/src/metabase/agent_lib/mbql_integration/joins.clj
+++ /dev/null
@@ -1,60 +0,0 @@
-(ns metabase.agent-lib.mbql-integration.joins
- "Explicit-vs-implicit join integration helpers for the agent-lib MBQL bridge."
- (:require
- [metabase.agent-lib.join-spec :as join-spec]
- [metabase.agent-lib.mbql-integration.common :as common]
- [metabase.agent-lib.mbql-integration.fields :as fields]
- [metabase.agent-lib.syntax :as syntax]))
-
-(set! *warn-on-reflection* true)
-
-(defn implicitly-resolved-column?
- "True when `column` represents the target side of an implicit join strongly
- enough that agent-lib can treat an explicit join request as redundant."
- [column target-table-id]
- (boolean
- (and (map? column)
- (or (= (:table-id column) target-table-id)
- (= :source/previous-stage (:lib/source column)))
- (or (:fk-field-id column)
- (:lib/original-fk-field-id column)
- (= :source/previous-stage (:lib/source column)))
- (nil? (:join-alias column)))))
-
-(defn- valid-implicit-join-spec?
- "True when a parsed join spec has the shape of a potentially redundant implicit join."
- [{:keys [target-table-id conditions fields-mode strategy alias]}]
- (and (pos-int? target-table-id)
- (nil? alias)
- (or (nil? strategy) (= "left-join" strategy))
- (join-spec/implicit-join-compatible-fields-mode? fields-mode)
- (= 1 (count conditions))))
-
-(defn- target-field-for-join
- "Return the field metadata for the side of the join condition that points at the
- target table, or nil."
- [fields-by-id target-table-id [lhs-id rhs-id]]
- (let [lhs-table-id (some-> (get fields-by-id lhs-id) :table-id)
- rhs-table-id (some-> (get fields-by-id rhs-id) :table-id)
- field-id (cond
- (= lhs-table-id target-table-id) lhs-id
- (= rhs-table-id target-table-id) rhs-id)]
- (some-> field-id fields-by-id)))
-
-(defn redundant-implicit-join?
- "Return true when a structured explicit join would be redundant because the
- current query already exposes the target side through implicit join behavior."
- [fields-by-id current-query operation]
- (let [join-spec (when (and (common/query? current-query)
- (vector? operation)
- (= "join" (syntax/canonical-op-name (first operation)))
- (= 2 (count operation)))
- (join-spec/parse-join-spec (second operation)))
- target-field (when (and join-spec (valid-implicit-join-spec? join-spec))
- (target-field-for-join fields-by-id
- (:target-table-id join-spec)
- (first (:conditions join-spec))))
- target-col (when target-field
- (fields/resolve-field-in-query fields-by-id current-query target-field))]
- (when target-col
- (implicitly-resolved-column? target-col (:target-table-id join-spec)))))
diff --git a/src/metabase/agent_lib/mbql_integration/orderables.clj b/src/metabase/agent_lib/mbql_integration/orderables.clj
deleted file mode 100644
index 9651113b2ee..00000000000
--- a/src/metabase/agent_lib/mbql_integration/orderables.clj
+++ /dev/null
@@ -1,361 +0,0 @@
-(ns metabase.agent-lib.mbql-integration.orderables
- "Expression and orderable resolution helpers for the agent-lib MBQL bridge."
- (:require
- [clojure.string :as str]
- [metabase.agent-lib.common.errors :as errors]
- [metabase.agent-lib.mbql-integration.common :as common]
- [metabase.lib.core :as lib]
- [metabase.lib.expression :as lib.expression]
- [metabase.lib.ref :as lib.ref]
- [metabase.lib.schema.util :as lib.schema.util]
- [metabase.lib.util :as lib.util]))
-
-(set! *warn-on-reflection* true)
-
-(def ^:private aggregation-orderable-ops
- #{:count
- :sum
- :avg
- :min
- :max
- :distinct
- :median
- :stddev
- :var
- :count-where
- :sum-where
- :distinct-where
- :share
- :percentile
- :cum-count
- :cum-sum
- :metric})
-
-(defn- normalize-expression-comparison
- "Strip volatile metadata from an expression tree before structural
- comparison."
- [expr]
- (cond
- (map? expr)
- (-> expr
- (dissoc :lib/uuid :lib/expression-name :display-name :name)
- (update-vals normalize-expression-comparison))
-
- (vector? expr)
- (mapv normalize-expression-comparison expr)
-
- (sequential? expr)
- (mapv normalize-expression-comparison expr)
-
- :else
- expr))
-
-(defn matching-expression-ref
- "Return the expression ref for the current query expression that is
- semantically equal to `orderable`."
- [query orderable]
- (let [normalized-orderable (normalize-expression-comparison
- (lib.schema.util/remove-lib-uuids orderable))]
- (some (fn [expr]
- (when-let [expr-name (lib.util/expression-name expr)]
- (when (= normalized-orderable
- (normalize-expression-comparison
- (lib.schema.util/remove-lib-uuids expr)))
- (lib/expression-ref query expr-name))))
- (lib/expressions query))))
-
-(defn matching-previous-stage-column-by-name
- "Return a unique previous-stage column whose visible names match
- `column-name`."
- [query column-name]
- (let [normalized-column-name (common/normalized-name column-name)]
- (when normalized-column-name
- (->> [(lib/returned-columns query)
- (common/current-query-field-candidates query)]
- (apply concat)
- common/dedupe-candidate-columns
- (filter #(and (= :source/previous-stage (:lib/source %))
- (contains? (common/column-names %) normalized-column-name)))
- vec
- common/unique-query-candidate))))
-
-(defn current-stage-expression-ref
- "Return an expression ref when `expr-name` still resolves as a current-stage
- expression name."
- [query expr-name]
- (when (lib.expression/maybe-resolve-expression query expr-name)
- (lib/expression-ref query expr-name)))
-
-(defn expression-ref-or-current-stage-column
- "Resolve an expression name to the thing the current stage can actually order
- or project by."
- [query expr-name]
- (or (current-stage-expression-ref query expr-name)
- (matching-previous-stage-column-by-name query expr-name)
- (errors/lookup-error! (str "Expression not found in the current query stage: " (pr-str expr-name))
- {:expression-name expr-name})))
-
-(defn ensure-query-expression-ref
- "Ensure a query contains an expression definition for `expression`, returning
- `[query expr-ref]`."
- [query expression prefix]
- (if-let [expr-ref (matching-expression-ref query expression)]
- [query expr-ref]
- (let [expr-name (str "__" prefix "_expression_" (inc (count (lib/expressions query))))
- query' (lib/expression query expr-name expression)]
- [query' (lib/expression-ref query' expr-name)])))
-
-(defn orderable-column-key
- "Return the structural identity used when deduplicating orderable columns."
- [column]
- [(:id column)
- (:name column)
- (:lib/source column)
- (:lib/source-uuid column)
- (:source-field column)
- (:fk-field-id column)
- (:lib/original-fk-field-id column)
- (:lib/expression-name column)])
-
-(defn current-query-orderable-candidates
- "Return the distinct orderable columns for the current stage."
- [query]
- (vals
- (reduce (fn [acc column]
- (assoc acc (orderable-column-key column) column))
- {}
- (lib/orderable-columns query))))
-
-(defn column-field-ids
- "Return every field id represented by a column's lineage metadata."
- [column]
- (->> [(:id column)
- (:source-field column)
- (:fk-field-id column)
- (:lib/original-fk-field-id column)]
- (filter pos-int?)
- set))
-
-(defn breakout-expression-name
- "Return the expression name for a breakout when the breakout is an
- expression-ref."
- [breakout]
- (when (lib.util/clause-of-type? breakout :expression)
- (lib.ref/expression-ref-name breakout)))
-
-(defn previous-stage-aggregation-column
- "Resolve an aggregation index to the column that represents that aggregation
- in the previous stage."
- [query ag-index]
- (when-let [previous-stage-number (lib.util/previous-stage-number query -1)]
- (let [candidate-columns (concat (lib/returned-columns query)
- (lib/filterable-columns query)
- (lib/orderable-columns query)
- (lib/visible-columns query))]
- (or (try
- (lib/find-matching-column query
- -1
- (lib/aggregation-ref query previous-stage-number ag-index)
- candidate-columns)
- (catch Exception _
- nil))
- (when-let [source-uuid (:lib/source-uuid
- (get (vec (lib/aggregations-metadata query previous-stage-number))
- ag-index))]
- (some #(when (= source-uuid (:lib/source-uuid %))
- %)
- candidate-columns))))))
-
-(defn aggregation-ref-or-current-stage-column
- "Resolve an aggregation index to the right current-stage orderable or
- projectable value."
- [query ag-index]
- (if (get (vec (lib/aggregations query)) ag-index)
- (lib/aggregation-ref query ag-index)
- (or (previous-stage-aggregation-column query ag-index)
- (errors/lookup-error! (str "Undefined aggregation " ag-index)
- {:aggregation-index ag-index
- :stage-number -1}))))
-
-(defn aggregation-signature
- "Return the semantic signature used to compare aggregation definitions."
- [aggregation]
- [(first aggregation) (common/extract-field-ids aggregation)])
-
-(defn aggregation-columns
- "Return the current-stage orderable columns backed by aggregation outputs."
- [query]
- (filterv #(= (:lib/source %) :source/aggregations)
- (lib/orderable-columns query)))
-
-(defn aggregation-column-pairs
- "Pair each current-stage aggregation with the orderable column that lib maps
- it to, when one exists."
- [query]
- (let [agg-cols (aggregation-columns query)]
- (->> (lib/aggregations query)
- (map-indexed (fn [idx aggregation]
- [idx aggregation
- (lib/find-matching-column query -1 (lib/aggregation-ref query idx) agg-cols)]))
- (filter #(nth % 2))
- vec)))
-
-(defn requested-orderable-field-ids
- "Return the field ids semantically referenced by an orderable request."
- [requested]
- (cond
- (map? requested)
- (column-field-ids requested)
-
- (lib.util/field-clause? requested)
- (common/extract-field-ids requested)
-
- :else
- #{}))
-
-(defn orderable-field-id->query-columns
- "Return current-stage orderable columns whose lineage includes `field-id`."
- [query field-id]
- (->> (current-query-orderable-candidates query)
- (filterv #(contains? (column-field-ids %) field-id))))
-
-(defn orderable-field-ids->query-columns
- "Return unique current-stage orderable columns whose lineage overlaps any of
- `field-ids`."
- [query field-ids]
- (->> field-ids
- (mapcat #(orderable-field-id->query-columns query %))
- (reduce (fn [acc column]
- (assoc acc (orderable-column-key column) column))
- {})
- vals
- vec))
-
-(defn field-id->breakout-expression-refs
- "Return breakout expression refs whose underlying expression touches
- `field-id`."
- [query field-id]
- (let [expr-fields (->> (lib/expressions query)
- (keep (fn [expr]
- (when-let [expr-name (lib.util/expression-name expr)]
- [expr-name (common/extract-field-ids expr)])))
- (into {}))]
- (->> (lib/breakouts query)
- (keep breakout-expression-name)
- (filter #(contains? (get expr-fields % #{}) field-id))
- distinct
- (mapv #(lib/expression-ref query %)))))
-
-(defn field-ids->breakout-expression-ref
- "Return the unique breakout expression ref implied by `field-ids`, if one can
- be chosen unambiguously."
- [query field-ids]
- (let [matches (->> field-ids
- (mapcat #(field-id->breakout-expression-refs query %))
- (reduce (fn [acc expr-ref]
- (assoc acc (pr-str expr-ref) expr-ref))
- {})
- vals
- vec)]
- (when (= 1 (count matches))
- (first matches))))
-
-(defn field-id->aggregation-columns
- "Return aggregation output columns whose defining aggregation references
- `field-id`."
- [query field-id]
- (->> (aggregation-column-pairs query)
- (keep (fn [[_idx aggregation column]]
- (when (contains? (common/extract-field-ids aggregation) field-id)
- column)))
- vec))
-
-(defn field-ids->aggregation-columns
- "Return unique aggregation output columns referenced by any of `field-ids`."
- [query field-ids]
- (->> field-ids
- (mapcat #(field-id->aggregation-columns query %))
- (reduce (fn [acc column]
- (assoc acc (orderable-column-key column) column))
- {})
- vals
- vec))
-
-(defn- sole-match
- "Return `[query match]` when `candidates` has exactly one element, else nil."
- [query candidates]
- (when (= 1 (count candidates))
- [query (first candidates)]))
-
-(defn resolve-field-like-orderable
- "Resolve a field-like orderable request against the current query stage."
- [query requested]
- (let [field-ids (requested-orderable-field-ids requested)
- query-match (orderable-field-ids->query-columns query field-ids)]
- (or (sole-match query query-match)
- (when-let [ref (field-ids->breakout-expression-ref query field-ids)]
- [query ref])
- (sole-match query (field-ids->aggregation-columns query field-ids))
- (sole-match query (aggregation-columns query))
- [query requested])))
-
-(defn- resolve-aggregation-orderable
- "Resolve an aggregation-like orderable by progressively narrowing candidates."
- [query orderable]
- (let [agg-cols (aggregation-columns query)
- op-name (name (first orderable))
- by-name (filterv #(str/starts-with? (or (:name %) "") op-name) agg-cols)
- target-sig (aggregation-signature orderable)
- by-signature (when (> (count by-name) 1)
- (->> (aggregation-column-pairs query)
- (keep (fn [[_idx aggregation column]]
- (when (and (some #{column} by-name)
- (= target-sig (aggregation-signature aggregation)))
- column)))
- vec))]
- (or (sole-match query agg-cols)
- (sole-match query by-name)
- (sole-match query by-signature)
- (cond
- (> (count by-signature) 1)
- (errors/lookup-error! (str "Ambiguous: multiple identical '" op-name "' aggregations.")
- {:operator op-name}
- {:available (mapv :name agg-cols)
- :suggestion "Use orderable-columns to pick the specific column."})
-
- (> (count by-name) 1)
- (errors/lookup-error! (str "No orderable column matched aggregation '" op-name "' on those fields.")
- {:operator op-name}
- {:available (mapv :name agg-cols)})
-
- :else
- (errors/lookup-error! (str "No orderable column found for aggregation '" op-name "'.")
- {:operator op-name}
- {:available (mapv :name agg-cols)})))))
-
-(defn resolve-orderable
- "Resolve an agent-program orderable against the current query, returning
- `[query resolved-orderable]`."
- [query orderable]
- (cond
- (map? orderable)
- (resolve-field-like-orderable query orderable)
-
- (and (lib.util/clause? orderable)
- (contains? aggregation-orderable-ops (first orderable)))
- (resolve-aggregation-orderable query orderable)
-
- (lib.util/field-clause? orderable)
- (resolve-field-like-orderable query orderable)
-
- (lib.util/clause-of-type? orderable :expression)
- [query orderable]
-
- (lib.util/clause-of-type? orderable :aggregation)
- [query orderable]
-
- (lib.util/clause? orderable)
- (ensure-query-expression-ref query orderable "order_by")
-
- :else
- [query orderable]))
diff --git a/src/metabase/agent_lib/refs.clj b/src/metabase/agent_lib/refs.clj
deleted file mode 100644
index d45abc5f8f5..00000000000
--- a/src/metabase/agent_lib/refs.clj
+++ /dev/null
@@ -1,83 +0,0 @@
-(ns metabase.agent-lib.refs
- "Walk a structured program and collect every metadata id (table, field, card, metric, measure)
- it actually references. Used by the runtime builder to scope metadata loading to entities the
- program touches, instead of materializing the whole database."
- (:require
- [metabase.agent-lib.schema :as schema]))
-
-(set! *warn-on-reflection* true)
-
-(def ^:private empty-refs
- {:table-ids #{}
- :field-ids #{}
- :card-ids #{}
- :metric-ids #{}
- :measure-ids #{}})
-
-(declare collect-program-refs)
-
-(defn- collect-source-refs
- [acc source]
- (if (and (map? source) (:type source))
- (case (:type source)
- "table" (cond-> acc (pos-int? (:id source)) (update :table-ids conj (:id source)))
- ("card" "dataset") (cond-> acc (pos-int? (:id source)) (update :card-ids conj (:id source)))
- "metric" (cond-> acc (pos-int? (:id source)) (update :metric-ids conj (:id source)))
- "program" (if (:program source) (collect-program-refs acc (:program source)) acc)
- acc)
- acc))
-
-(defn- ref-key-for-op
- "Map a reference operator name to the refs key it populates."
- [op]
- (case op
- "table" :table-ids
- "field" :field-ids
- "card" :card-ids
- "metric" :metric-ids
- "measure" :measure-ids
- nil))
-
-(defn- collect-form
- [acc form]
- (cond
- ;; Operator tuple — `["op" arg ...]`. Reference ops have an int id as their first arg
- ;; (after repair-normalize); other ops we just recurse into.
- (and (vector? form) (string? (first form)))
- (let [[op & args] form
- ref-key (ref-key-for-op op)]
- (if (and ref-key (pos-int? (first args)))
- (-> (update acc ref-key conj (first args))
- ;; Still recurse into remaining args — `(field id)` has none, but
- ;; e.g. `(with-temporal-bucket (field id) "month")` is a different op
- ;; whose recursion is handled by the non-ref branch below.
- (cond-> (next args) (as-> $ (reduce collect-form $ (next args)))))
- (reduce collect-form acc args)))
-
- ;; Nested program literal — `{:program {...}}`.
- (and (map? form) (schema/program-literal? form))
- (collect-program-refs acc (:program form))
-
- ;; Plain map — recurse into values (covers per-stage option maps, etc.).
- (map? form)
- (reduce-kv (fn [a _k v] (collect-form a v)) acc form)
-
- ;; Sequential — recurse element-wise.
- (sequential? form)
- (reduce collect-form acc form)
-
- :else acc))
-
-(defn collect-program-refs
- "Walk `program` and return `{:table-ids #{...} :field-ids #{...} :card-ids #{...}
- :metric-ids #{...} :measure-ids #{...}}` containing every numeric metadata id referenced
- anywhere in its source or operations.
-
- Assumes the program has been through `repair/repair-program` so that all `[op id]` reference
- forms carry positive integer ids."
- ([program]
- (collect-program-refs empty-refs program))
- ([acc program]
- (-> acc
- (collect-source-refs (:source program))
- (as-> $ (reduce collect-form $ (:operations program))))))
diff --git a/src/metabase/agent_lib/repair.clj b/src/metabase/agent_lib/repair.clj
deleted file mode 100644
index cdf1b9873d7..00000000000
--- a/src/metabase/agent_lib/repair.clj
+++ /dev/null
@@ -1,10 +0,0 @@
-(ns metabase.agent-lib.repair
- "Deterministic repair helpers for structured MBQL programs."
- (:require
- [metabase.agent-lib.repair.context]
- [metabase.agent-lib.repair.normalize]
- [potemkin :as p]))
-
-(p/import-vars
- [metabase.agent-lib.repair.normalize repair-program]
- [metabase.agent-lib.repair.context repair-program-for-context])
diff --git a/src/metabase/agent_lib/repair/context.clj b/src/metabase/agent_lib/repair/context.clj
deleted file mode 100644
index 9f8e64010b4..00000000000
--- a/src/metabase/agent_lib/repair/context.clj
+++ /dev/null
@@ -1,20 +0,0 @@
-(ns metabase.agent-lib.repair.context
- "Context-specific structured-program repair passes."
- (:require
- [metabase.agent-lib.repair.context.passes :as passes]
- [metabase.agent-lib.repair.stages :as stages]))
-
-(set! *warn-on-reflection* true)
-
-(defn repair-program-for-context
- "Apply deterministic repairs that depend on the evaluation context."
- [program context]
- (let [source (passes/effective-source-for-context program context)
- operations (->> (:operations program)
- (passes/drop-source-metric-stage-aggregates context)
- (passes/drop-source-metric-stage-with-fields context)
- (map #(passes/normalize-source-metric-quarter-window context %))
- (passes/remove-redundant-operations context)
- vec)]
- (assoc program
- :operations (stages/insert-stage-boundaries source operations))))
diff --git a/src/metabase/agent_lib/repair/context/passes.clj b/src/metabase/agent_lib/repair/context/passes.clj
deleted file mode 100644
index ccf0bd50516..00000000000
--- a/src/metabase/agent_lib/repair/context/passes.clj
+++ /dev/null
@@ -1,193 +0,0 @@
-(ns metabase.agent-lib.repair.context.passes
- "Context-dependent repair passes for structured programs."
- (:require
- [metabase.agent-lib.common.coercions :refer [coerce-positive-int]]
- [metabase.agent-lib.common.context :as common.context]
- [metabase.agent-lib.common.literals :refer [now-literal?]]
- [metabase.agent-lib.join-spec :as join-spec]
- [metabase.agent-lib.repair.stages :as stages]
- [metabase.agent-lib.syntax :as syntax]
- [metabase.util :as u]))
-
-(set! *warn-on-reflection* true)
-
-(defn effective-source-for-context
- "Replace a context source with the concrete metric source when needed."
- [program context]
- (let [source (:source program)]
- (if (and (map? source)
- (= "context" (:type source))
- (common.context/source-metric-id context))
- {:type "metric"
- :id (common.context/source-metric-id context)}
- source)))
-
-(def ^:private max-tree-walk-depth
- "Maximum depth for tree walks in repair passes."
- 64)
-
-(defn operation-contains-canonical-op?
- "True when `operation` contains `target-op-name` anywhere in its tree."
- [operation target-op-name]
- (letfn [(walk [value depth]
- (when (<= depth max-tree-walk-depth)
- (cond
- (and (vector? value)
- (= target-op-name (syntax/canonical-op-name (first value))))
- true
-
- (coll? value)
- (some #(walk % (inc depth)) value)
-
- :else
- false)))]
- (boolean (walk operation 0))))
-
-(defn rewrite-source-stage
- "Rewrite only the operations that belong to the source stage."
- [operations step]
- (:operations
- (reduce (fn [{:keys [operations] :as state} operation]
- (let [op-name (when (vector? operation)
- (syntax/canonical-op-name (first operation)))]
- (if (= "append-stage" op-name)
- {:in-source-stage? false
- :operations (conj operations operation)}
- (step state operation))))
- {:in-source-stage? true
- :operations []}
- operations)))
-
-(defn drop-source-metric-stage-aggregates
- "Drop redundant source-stage aggregates for metric contexts."
- [context operations]
- (if-not (common.context/source-metric-id context)
- operations
- (rewrite-source-stage
- operations
- (fn [{:keys [in-source-stage? operations] :as state} operation]
- (let [drop? (and in-source-stage?
- (= "aggregate" (syntax/canonical-op-name (first operation)))
- (not (stages/aggregate-over-aggregation-ref? operation))
- (not (operation-contains-canonical-op? operation "measure"))
- (not (operation-contains-canonical-op? operation "metric")))]
- (if drop?
- state
- (assoc state :operations (conj operations operation))))))))
-
-(defn drop-source-metric-stage-with-fields
- "Drop source-stage `with-fields` that only restate aggregation refs."
- [context operations]
- (if-not (common.context/source-metric-id context)
- operations
- (rewrite-source-stage
- operations
- (fn [{:keys [in-source-stage? operations] :as state} operation]
- (let [drop? (and in-source-stage?
- (= "with-fields" (syntax/canonical-op-name (first operation)))
- (stages/contains-aggregation-ref? (rest operation)))]
- (if drop?
- state
- (assoc state :operations (conj operations operation))))))))
-
-(defn relative-datetime-form?
- "True when `value` is a relative-datetime form with the given amount and unit."
- [value amount unit]
- (and (vector? value)
- (= "relative-datetime" (syntax/canonical-op-name (first value)))
- (= amount (nth value 1 nil))
- (= unit (some-> (nth value 2 nil) syntax/raw-op-name u/lower-case-en))))
-
-(defn now-form?
- "True when `value` is a now literal or `[\"now\"]` tuple."
- [value]
- (or (now-literal? value)
- (and (vector? value)
- (= "now" (syntax/canonical-op-name (first value))))))
-
-(defn normalize-source-metric-quarter-window
- "Normalize rolling 3-month source-metric windows into quarter-relative bounds."
- [context operation]
- (if (and (common.context/source-metric-id context)
- (vector? operation)
- (= "filter" (syntax/canonical-op-name (first operation)))
- (vector? (second operation))
- (= "between" (syntax/canonical-op-name (first (second operation)))))
- (let [[between-op field lower upper] (second operation)]
- (if (and (relative-datetime-form? lower -3 "month")
- (now-form? upper))
- [(first operation)
- [between-op field
- ["relative-datetime" -1 "quarter"]
- ["relative-datetime" 0 "quarter"]]]
- operation))
- operation))
-
-(defn- edge-value
- [edge kebab-key snake-key]
- (or (get edge kebab-key)
- (get edge snake-key)))
-
-(defn- join-condition-matches-edge?
- [source-id target-id [lhs-id rhs-id] edge]
- (let [from-table-id (edge-value edge :from-table-id :from_table_id)
- from-field-id (edge-value edge :from-field-id :from_field_id)
- to-table-id (edge-value edge :to-table-id :to_table_id)
- to-field-id (edge-value edge :to-field-id :to_field_id)]
- (and (or (and (= source-id from-table-id)
- (= target-id to-table-id))
- (and (= source-id to-table-id)
- (= target-id from-table-id)))
- (or (and (= lhs-id from-field-id) (= rhs-id to-field-id))
- (and (= lhs-id to-field-id) (= rhs-id from-field-id))))))
-
-(defn- valid-join-operation?
- "True when `operation` is a two-element join tuple."
- [operation]
- (and (vector? operation)
- (= "join" (syntax/canonical-op-name (first operation)))
- (= 2 (count operation))))
-
-(defn- implicit-join-matches-context?
- "True when a parsed join spec matches surrounding context edges."
- [source-id context {:keys [target-table-id conditions fields-mode strategy alias]}]
- (let [surrounding-table-ids (set (keep :id (:surrounding-tables context)))]
- (and (pos-int? target-table-id)
- (surrounding-table-ids target-table-id)
- (nil? alias)
- (or (nil? strategy) (= "left-join" strategy))
- (join-spec/no-explicit-join-fields? fields-mode)
- (= 1 (count conditions))
- (some #(join-condition-matches-edge? source-id target-table-id (first conditions) %)
- (:join-edges context)))))
-
-(defn redundant-implicit-join?
- "True when an explicit join is redundant in the current context."
- [context operation]
- (let [source-id (common.context/source-table-id context)
- join-spec (when (valid-join-operation? operation)
- (join-spec/parse-join-spec (second operation)))]
- (and source-id
- join-spec
- (implicit-join-matches-context? source-id context join-spec))))
-
-(defn- redundant-source-metric-aggregate?
- "True when an aggregate is an exact reuse of the source metric.
- This catches `[\"aggregate\" [\"metric\" source-id]]` which is intentionally preserved
- by `drop-source-metric-stage-aggregates` (that pass only drops non-metric/measure aggregates)."
- [source-id operation]
- (and (vector? operation)
- (= "aggregate" (syntax/canonical-op-name (first operation)))
- (let [aggregation (second operation)]
- (and (vector? aggregation)
- (= "metric" (syntax/canonical-op-name (first aggregation)))
- (= source-id (some-> (second aggregation) coerce-positive-int))))))
-
-(defn remove-redundant-operations
- "Remove context-redundant source-metric reuse and implicit joins."
- [context operations]
- (remove (fn [operation]
- (or (when-let [source-id (common.context/source-metric-id context)]
- (redundant-source-metric-aggregate? source-id operation))
- (redundant-implicit-join? context operation)))
- operations))
diff --git a/src/metabase/agent_lib/repair/normalize.clj b/src/metabase/agent_lib/repair/normalize.clj
deleted file mode 100644
index 56456f76ce4..00000000000
--- a/src/metabase/agent_lib/repair/normalize.clj
+++ /dev/null
@@ -1,71 +0,0 @@
-(ns metabase.agent-lib.repair.normalize
- "Deterministic operator and top-level normalization for structured MBQL programs."
- (:require
- [metabase.agent-lib.common.coercions :refer [coerce-positive-int]]
- [metabase.agent-lib.common.literals :refer [scalar-literal?]]
- [metabase.agent-lib.repair.normalize.forms :as normalize.forms]
- [metabase.agent-lib.repair.normalize.top-level :as normalize.top-level]
- [metabase.agent-lib.repair.stages :as stages]
- [metabase.agent-lib.schema :as schema]
- [metabase.agent-lib.syntax :as syntax]
- [metabase.util :as u]))
-
-(set! *warn-on-reflection* true)
-
-(defn repair-program
- "Apply deterministic repairs for common structured program mistakes.
-
- The local `letfn` is intentional here: `repair-node` and `repair-map-node`
- form the minimal mutually recursive kernel for walking arbitrary nested
- structured-program values."
- [program]
- (letfn [(repair-map-node [value]
- (cond
- (schema/program-literal? value)
- (assoc value :program (repair-program (:program value)))
-
- (and (map? value)
- (contains? value :type)
- (contains? value :id))
- (update value :id coerce-positive-int)
-
- (normalize.forms/field-like-map? value)
- (repair-node (normalize.forms/repair-field-like-map value))
-
- :else
- (into {}
- (map (fn [[k v]] [k (repair-node v)]))
- value)))
- (repair-node [value]
- (cond
- (scalar-literal? value) value
- (map? value) (repair-map-node value)
- (syntax/boolean-wrapper-form? value)
- (let [[raw-op arg] value
- arg' (repair-node arg)]
- (if (= "true" (some-> raw-op syntax/raw-op-name u/lower-case-en))
- arg'
- ["not" arg']))
- (syntax/possible-operator-tuple? value) (normalize.forms/repair-operator-form repair-node value)
- (vector? value) (mapv repair-node value)
- (sequential? value) (mapv repair-node value)
- :else value))]
- (if-not (map? program)
- program
- (let [source (let [source (:source program)]
- (cond
- (not (map? source))
- source
-
- (= "program" (:type source))
- (update source :program repair-program)
-
- :else
- (cond-> source
- (contains? source :id) (update :id coerce-positive-int))))
- operations (into []
- (mapcat #(normalize.top-level/repair-top-level-operation repair-node %))
- (:operations program))]
- (assoc program
- :source source
- :operations (stages/insert-stage-boundaries source operations))))))
diff --git a/src/metabase/agent_lib/repair/normalize/forms.clj b/src/metabase/agent_lib/repair/normalize/forms.clj
deleted file mode 100644
index 0df9beec408..00000000000
--- a/src/metabase/agent_lib/repair/normalize/forms.clj
+++ /dev/null
@@ -1,337 +0,0 @@
-(ns metabase.agent-lib.repair.normalize.forms
- "Nested operator normalization for structured program repair."
- (:require
- [metabase.agent-lib.common.coercions :as coercions :refer [coerce-non-negative-int
- coerce-positive-int
- normalize-join-conditions
- normalize-percentile-value
- unwrap-singleton-form]]
- [metabase.agent-lib.common.literals :refer [iso-date-string?
- non-blank-string?
- now-literal?
- null-literal?
- quarter-label-string?
- scalar-sequential?]]
- [metabase.agent-lib.syntax :as syntax]))
-
-(set! *warn-on-reflection* true)
-
-(def ^:private temporal-bucket-extraction-aliases
- "Bucket names that should be repaired into extraction helpers."
- {"dayofweek" "get-day-of-week"
- "day-of-week" "get-day-of-week"
- "hour-of-day" "get-hour"
- "month-of-year" "get-month"
- "quarter-of-year" "get-quarter"})
-
-(defn- option-value
- "Read the first present key from `options`, accepting either string or keyword keys."
- [options & ks]
- (reduce (fn [_ k]
- (let [v (or (get options (name k)) (get options (keyword k)))]
- (if (some? v) (reduced v) nil)))
- nil
- ks))
-
-(defn- wrap-field-with-options
- "Rewrite a non-canonical `[\"field\" id {opts}]` tuple into the canonical
- wrapper forms (`with-temporal-bucket`, `with-binning`) the runtime accepts."
- [field-form options]
- (let [temporal-unit (option-value options :temporal-unit)
- binning (option-value options :binning)
- with-temporal (if (some? temporal-unit)
- ["with-temporal-bucket" field-form temporal-unit]
- field-form)]
- (if (some? binning)
- ["with-binning" with-temporal binning]
- with-temporal)))
-
-(def ^:private field-like-map-id-keys
- ["field_id" "field-id" :field_id :field-id])
-
-(defn field-like-map?
- "True when `value` is a plain map that describes a field reference by carrying
- a `:field_id`/`:field-id` key."
- [value]
- (boolean (and (map? value)
- (some #(some? (get value %)) field-like-map-id-keys))))
-
-(defn repair-field-like-map
- "Convert a field-like map (e.g. `{\"field_id\" 13 \"temporal_bucket\" \"month\"}`)
- into the canonical nested operator form the runtime accepts.
-
- Supports optional `temporal_bucket`/`temporal-unit`, `binning`, and `direction`
- keys. When `direction` is present, the result is wrapped in `asc`/`desc`."
- [m]
- (let [field-id (option-value m :field_id :field-id)
- temporal-unit (option-value m :temporal_bucket :temporal-bucket
- :temporal_unit :temporal-unit)
- binning (option-value m :binning)
- direction (option-value m :direction)
- field-form (cond-> ["field" (coerce-positive-int field-id)]
- (some? temporal-unit) (wrap-field-with-options
- {"temporal-unit" temporal-unit})
- (some? binning) (wrap-field-with-options
- {"binning" binning}))]
- (if (coercions/direction-string? direction)
- [(coercions/normalize-direction direction) field-form]
- field-form)))
-
-(defn expression-definition-tuple?
- "True when `value` is an inline expression definition tuple."
- [value]
- (and (vector? value)
- (= "expression" (syntax/canonical-op-name (first value)))
- (= 3 (count value))
- (non-blank-string? (second value))))
-
-(defn- quarter-expression?
- [value]
- (and (vector? value)
- (let [op-name (syntax/canonical-op-name (first value))]
- (or (= op-name "get-quarter")
- (and (= op-name "with-temporal-bucket")
- (= "quarter" (nth value 2 nil)))))))
-
-(defn- normalize-quarter-filter-value
- [lhs rhs]
- (cond
- (and (quarter-expression? lhs)
- (quarter-label-string? rhs))
- (coercions/quarter-label->number rhs)
-
- (and (quarter-expression? lhs)
- (scalar-sequential? rhs)
- (every? quarter-label-string? rhs))
- (mapv coercions/quarter-label->number rhs)
-
- :else
- rhs))
-
-(defn- branch-pair?
- [v]
- (and (vector? v) (= 2 (count v))))
-
-(defn- else-branch?
- [v]
- (and (branch-pair? v)
- (= "else" (syntax/raw-op-name (first v)))))
-
-(defn- split-else-branch
- "Peel an else-branch off the end of `branches`, merging it with `fallback`."
- [branches fallback]
- (if (and (seq branches) (else-branch? (last branches)))
- [(vec (butlast branches)) (second (last branches))]
- [branches fallback]))
-
-(defn- flat->branch-pairs
- "Convert a flat even-length vector into branch pairs when applicable."
- [v]
- (when (and (vector? v)
- (even? (count v))
- (not-every? branch-pair? v))
- (mapv vec (partition 2 v))))
-
-(defn- normalize-branches-fallback
- "Uniform post-processing: split else-branch and emit `[branches]` or
- `[branches fallback]`."
- [branches fallback]
- (let [[branches fallback] (split-else-branch branches fallback)]
- (if (some? fallback)
- [branches fallback]
- [branches])))
-
-(defn- classify-case-args
- "Classify the shape of `case` args into `[branches fallback]` before uniform
- normalization, or nil if no pattern matches."
- [args]
- (cond
- ;; Three bare args: pred, then, else
- (and (= 3 (count args))
- (not (branch-pair? (first args))))
- [[[(first args) (second args)]] (nth args 2)]
-
- ;; Single wrapped vector of branch pairs
- (and (seq args)
- (vector? (first args))
- (every? branch-pair? (first args)))
- [(first args) (second args)]
-
- ;; Single wrapped triple: [pred then else]
- (and (= 1 (count args))
- (vector? (first args))
- (= 3 (count (first args)))
- (not-every? branch-pair? (first args)))
- (let [[pred then else] (first args)]
- [[[pred then]] else])
-
- ;; Leading branch pairs followed by optional fallback
- (seq (take-while branch-pair? args))
- (let [branches (vec (take-while branch-pair? args))
- remainder (drop (count branches) args)]
- [branches (when (= 1 (count remainder)) (first remainder))])
-
- ;; Flat even-length vector inside a wrapper
- (flat->branch-pairs (first args))
- [(flat->branch-pairs (first args)) (second args)]))
-
-(defn repair-case-args
- "Normalize alternate `case` encodings into the canonical branches/fallback shape."
- [args]
- (if-let [[branches fallback] (classify-case-args args)]
- (normalize-branches-fallback branches fallback)
- args))
-
-(defn temporal-expression?
- "True when `value` is a temporal literal or temporal expression tuple."
- [value]
- (or (now-literal? value)
- (and (vector? value)
- (contains? #{"absolute-datetime" "relative-datetime" "now"}
- (syntax/canonical-op-name (first value))))))
-
-(defn- wrap-iso-date-as-absolute-datetime
- [value]
- (if (iso-date-string? value)
- ["absolute-datetime" value "day"]
- value))
-
-(defn- wrap-now-as-expression
- [value]
- (if (now-literal? value)
- ["now"]
- value))
-
-(defn repair-between-bounds
- "Normalize temporal `between` bounds into canonical datetime helper forms.
- Preserves degenerate (fewer than 3) arg counts so repair remains idempotent
- when the operator is embedded in a helper that reshapes its arguments
- (e.g. `case`)."
- [args]
- (if (< (count args) 3)
- (vec args)
- (let [[lhs lower upper] args
- lower' (wrap-now-as-expression lower)
- upper' (wrap-now-as-expression upper)]
- (if (or (temporal-expression? lower')
- (temporal-expression? upper'))
- [lhs
- (if (temporal-expression? upper')
- (wrap-iso-date-as-absolute-datetime lower')
- lower')
- (if (temporal-expression? lower')
- (wrap-iso-date-as-absolute-datetime upper')
- upper')]
- [lhs lower' upper']))))
-
-(defn repair-operator-form
- "Normalize a nested operator form using the recursive `repair-node` callback."
- [repair-node value]
- (let [[raw-op & raw-args] value
- op-name (syntax/canonical-op-name raw-op)
- args (mapv (fn [arg]
- (let [arg' (repair-node arg)]
- (if (#{"in"
- "not-in"
- "case"
- "with-fields"
- "with-join-fields"
- "with-join-conditions"} op-name)
- arg'
- (unwrap-singleton-form arg'))))
- raw-args)]
- (case op-name
- "field"
- (let [id (coerce-positive-int (first args))
- maybe-opt (second args)]
- (if (map? maybe-opt)
- (wrap-field-with-options [op-name id] maybe-opt)
- [op-name id]))
-
- ("table" "card" "metric" "measure")
- [op-name (coerce-positive-int (first args))]
-
- "aggregation-ref"
- [op-name (coerce-non-negative-int (first args))]
-
- "with-temporal-bucket"
- (if (< (count args) 2)
- (into [op-name] args)
- (let [[field bucket] args]
- (if-let [extraction-op (and (string? bucket)
- (temporal-bucket-extraction-aliases bucket))]
- [extraction-op field]
- [op-name field bucket])))
-
- ("contains" "does-not-contain" "starts-with" "ends-with")
- (into [op-name]
- (cond-> args
- (and (> (count args) 2)
- (or (map? (last args))
- (boolean? (last args))))
- pop))
-
- ("in" "not-in")
- (if (< (count args) 2)
- (into [op-name] args)
- (let [[lhs rhs] args]
- [op-name lhs (normalize-quarter-filter-value lhs rhs)]))
-
- "="
- (if (< (count args) 2)
- (into [op-name] args)
- (let [[lhs rhs] args
- rhs' (normalize-quarter-filter-value lhs rhs)]
- (if (scalar-sequential? rhs')
- ["in" lhs (vec rhs')]
- [op-name lhs rhs'])))
-
- "!="
- (if (< (count args) 2)
- (into [op-name] args)
- (let [[lhs rhs] args
- rhs' (normalize-quarter-filter-value lhs rhs)]
- (if (scalar-sequential? rhs')
- ["not-in" lhs (vec rhs')]
- [op-name lhs rhs'])))
-
- "is"
- (if (< (count args) 2)
- (into [op-name] args)
- (let [[lhs rhs] args]
- (if (null-literal? rhs)
- ["is-null" lhs]
- ["=" lhs rhs])))
-
- "is-not"
- (if (< (count args) 2)
- (into [op-name] args)
- (let [[lhs rhs] args]
- (if (null-literal? rhs)
- ["not-null" lhs]
- ["!=" lhs rhs])))
-
- "case"
- (let [args' (if (= "if" (syntax/raw-op-name raw-op))
- (if (= 3 (count args))
- [[[(first args) (second args)]] (nth args 2)]
- args)
- args)]
- (into [op-name] (repair-case-args args')))
-
- "between"
- (into [op-name] (repair-between-bounds args))
-
- "percentile"
- (if (< (count args) 2)
- (into [op-name] args)
- (let [[expr percentile] args]
- [op-name expr (normalize-percentile-value percentile)]))
-
- "with-join-conditions"
- (if (< (count args) 2)
- (into [op-name] args)
- (let [[join-spec conditions] args]
- [op-name join-spec (normalize-join-conditions conditions)]))
-
- (into [op-name] args))))
diff --git a/src/metabase/agent_lib/repair/normalize/top_level.clj b/src/metabase/agent_lib/repair/normalize/top_level.clj
deleted file mode 100644
index 5c51e76698b..00000000000
--- a/src/metabase/agent_lib/repair/normalize/top_level.clj
+++ /dev/null
@@ -1,174 +0,0 @@
-(ns metabase.agent-lib.repair.normalize.top-level
- "Top-level operation normalization for structured program repair."
- (:require
- [metabase.agent-lib.common.coercions :refer [direction-string?
- normalize-direction]]
- [metabase.agent-lib.common.literals :refer [aggregation-form?]]
- [metabase.agent-lib.repair.normalize.forms :as forms]
- [metabase.agent-lib.syntax :as syntax]))
-
-(set! *warn-on-reflection* true)
-
-(defn normalize-with-fields-selection
- "Normalize `with-fields` arguments into a single vector of selections."
- [args]
- (cond
- (empty? args) []
-
- (= 1 (count args))
- (let [selection (first args)]
- (if (and (sequential? selection)
- (not (syntax/possible-operator-tuple? selection)))
- (vec selection)
- [selection]))
-
- :else
- (vec args)))
-
-(defn- direction-tuple?
- [value]
- (and (vector? value)
- (= 2 (count value))
- (direction-string? (first value))))
-
-(defn- unwrap-order-by-args
- "Unwrap a single sequential argument into its elements so `[[asc ...] [desc ...]]`
- behaves like `[asc ...] [desc ...]` passed directly. Only unwraps when the inner
- sequence is entirely `[direction value]` tuples so we don't rewrite unrelated
- shapes and break idempotence."
- [args]
- (if (and (= 1 (count args))
- (sequential? (first args))
- (seq (first args))
- (every? direction-tuple? (first args)))
- (vec (first args))
- args))
-
-(defn repair-order-by-operations
- "Normalize one or more `order-by` arguments into canonical operations."
- [args]
- (let [args (unwrap-order-by-args args)]
- (if (empty? args)
- [["order-by"]]
- (loop [remaining args
- repaired []]
- (if (empty? remaining)
- repaired
- (let [[first-arg second-arg & tail] remaining]
- (cond
- (and (vector? first-arg)
- (= 2 (count first-arg))
- (direction-string? (first first-arg)))
- (recur (vec (rest remaining))
- (conj repaired ["order-by" [(normalize-direction (first first-arg))
- (second first-arg)]]))
-
- (direction-string? second-arg)
- (recur (vec tail)
- (conj repaired ["order-by" first-arg (normalize-direction second-arg)]))
-
- :else
- (recur (vec (rest remaining))
- (conj repaired ["order-by" first-arg])))))))))
-
-(defn repair-repeated-single-arg-op
- "Expand repeated top-level single-arg operations."
- [op-name args]
- (if (empty? args)
- [[op-name]]
- (mapv (fn [arg] [op-name arg]) args)))
-
-(defn repair-with-fields-operation
- "Extract inline expressions out of `with-fields` before projection."
- [repair-node args]
- (let [selection (normalize-with-fields-selection args)
- repaired-fields (mapv repair-node selection)
- extracted-exprs (keep (fn [field]
- (when (forms/expression-definition-tuple? field)
- ["expression" (second field) (nth field 2)]))
- repaired-fields)
- projected (mapv (fn [field]
- (if (forms/expression-definition-tuple? field)
- ["expression-ref" (second field)]
- field))
- repaired-fields)]
- (into (vec extracted-exprs)
- [["with-fields" projected]])))
-
-(defn bare-aggregation-ref-operation?
- "True when an operation is a bare top-level aggregation-ref."
- [operation]
- (and (vector? operation)
- (= "aggregation-ref" (syntax/canonical-op-name (first operation)))))
-
-(defn- repair-with-embedded
- "Common skeleton: combine repaired direct args with embedded ops, falling back
- to a bare `[[op-name]]` when both are empty."
- [op-name direct-ops embedded-ops]
- (into (or (when (seq direct-ops) direct-ops)
- (when (empty? embedded-ops) [[op-name]])
- [])
- embedded-ops))
-
-(defn- repair-direct-args
- "Dispatch direct-arg repair by operation name."
- [op-name direct-args]
- (case op-name
- "order-by"
- (repair-order-by-operations direct-args)
-
- ("breakout" "filter" "join")
- (repair-repeated-single-arg-op op-name direct-args)
-
- ("limit" "with-page")
- [[op-name (first direct-args)]]))
-
-(defn repair-top-level-operation
- "Normalize a top-level operation using the recursive `repair-node` callback."
- [repair-node operation]
- (if-not (vector? operation)
- [operation]
- (let [[raw-op & raw-args] operation
- op-name (syntax/canonical-op-name raw-op)
- args (mapv repair-node raw-args)
- embedded-ops (mapcat #(repair-top-level-operation repair-node %)
- (filter syntax/top-level-operation-tuple? args))
- direct-args (vec (remove syntax/top-level-operation-tuple? args))]
- (case op-name
- "visualization"
- []
-
- "aggregate"
- (let [keep-bare-aggregation-refs? (not-any? (complement bare-aggregation-ref-operation?)
- direct-args)
- direct-args' (cond->> direct-args
- (not keep-bare-aggregation-refs?)
- (remove bare-aggregation-ref-operation?))]
- (repair-with-embedded op-name
- (when (seq direct-args')
- (repair-repeated-single-arg-op op-name direct-args'))
- embedded-ops))
-
- "with-fields"
- (repair-with-fields-operation repair-node args)
-
- ("order-by" "breakout" "filter" "join" "limit" "with-page")
- (repair-with-embedded op-name
- (when (seq direct-args)
- (repair-direct-args op-name direct-args))
- embedded-ops)
-
- "expression"
- (repair-with-embedded op-name
- (when (>= (count direct-args) 2)
- (let [[expr-name expr] (take 2 direct-args)]
- (if (aggregation-form? expr)
- [["aggregate" expr]]
- [[op-name expr-name expr]])))
- embedded-ops)
-
- ("append-stage" "drop-stage" "drop-empty-stages")
- [[op-name]]
-
- (into [(into [op-name] direct-args)]
- embedded-ops)))))
diff --git a/src/metabase/agent_lib/repair/stages.clj b/src/metabase/agent_lib/repair/stages.clj
deleted file mode 100644
index 1ae56e00f65..00000000000
--- a/src/metabase/agent_lib/repair/stages.clj
+++ /dev/null
@@ -1,107 +0,0 @@
-(ns metabase.agent-lib.repair.stages
- "Stage-boundary inference and aggregation-stage helpers for structured repair."
- (:require
- [metabase.agent-lib.syntax :as syntax]))
-
-(set! *warn-on-reflection* true)
-
-(def ^:private max-repair-depth
- "Maximum recursion depth for repair-phase tree walks."
- 64)
-
-(defn contains-aggregation-ref?
- "True when `value` contains an `aggregation-ref` anywhere inside it."
- ([value]
- (contains-aggregation-ref? value 0))
- ([value depth]
- (if (> depth max-repair-depth)
- false
- (cond
- (and (vector? value)
- (= "aggregation-ref" (syntax/canonical-op-name (first value))))
- true
-
- (map? value)
- (boolean (some #(contains-aggregation-ref? % (inc depth)) (vals value)))
-
- (sequential? value)
- (boolean (some #(contains-aggregation-ref? % (inc depth)) value))
-
- :else
- false))))
-
-(defn aggregate-over-aggregation-ref?
- "True when `operation` is an aggregate over an aggregation-ref."
- [operation]
- (and (vector? operation)
- (= "aggregate" (syntax/canonical-op-name (first operation)))
- (contains-aggregation-ref? (rest operation))))
-
-(defn- operation-defines-aggregation?
- [operation]
- (and (vector? operation)
- (= "aggregate" (syntax/canonical-op-name (first operation)))))
-
-(defn- operation-requires-post-aggregation-stage?
- [operation]
- (and (vector? operation)
- (contains-aggregation-ref? (rest operation))
- (#{"aggregate" "expression" "with-fields"}
- (syntax/canonical-op-name (first operation)))))
-
-(defn source-final-stage-has-aggregations?
- "True when the source program ends in an aggregated stage."
- [source]
- (cond
- (not (map? source))
- false
-
- (= "metric" (:type source))
- true
-
- (= "program" (:type source))
- (let [nested-program (:program source)]
- (:current-stage-has-aggregations?
- (reduce (fn [state operation]
- (cond
- (and (vector? operation)
- (= "append-stage" (syntax/canonical-op-name (first operation))))
- (assoc state :current-stage-has-aggregations? false)
-
- (operation-defines-aggregation? operation)
- (assoc state :current-stage-has-aggregations? true)
-
- :else
- state))
- {:current-stage-has-aggregations? (source-final-stage-has-aggregations? (:source nested-program))}
- (:operations nested-program))))
-
- :else
- false))
-
-(defn insert-stage-boundaries
- "Insert `append-stage` before operations that must run after an aggregation stage."
- [source operations]
- (:operations
- (reduce (fn [{:keys [current-stage-has-aggregations? operations]} operation]
- (let [op-name (when (vector? operation)
- (syntax/canonical-op-name (first operation)))
- needs-stage? (and current-stage-has-aggregations?
- (operation-requires-post-aggregation-stage? operation)
- (not= "append-stage"
- (some-> operations last first syntax/canonical-op-name)))
- operations' (cond-> operations
- needs-stage? (conj ["append-stage"])
- true (conj operation))]
- (cond
- (= "append-stage" op-name)
- {:current-stage-has-aggregations? false
- :operations operations'}
-
- :else
- {:current-stage-has-aggregations? (or (and (not needs-stage?) current-stage-has-aggregations?)
- (operation-defines-aggregation? operation))
- :operations operations'})))
- {:current-stage-has-aggregations? (source-final-stage-has-aggregations? source)
- :operations []}
- operations)))
diff --git a/src/metabase/agent_lib/representations.clj b/src/metabase/agent_lib/representations.clj
new file mode 100644
index 00000000000..530b3ee3dd9
--- /dev/null
+++ b/src/metabase/agent_lib/representations.clj
@@ -0,0 +1,246 @@
+(ns metabase.agent-lib.representations
+ "Boundary helpers for the canonical MBQL 5 portable representations form.
+
+ Two layers live here:
+
+ * **External form** — the wire / LLM-facing shape: a keyword-keyed Clojure map matching
+ [[metabase.lib.schema/external-query]]. Identical to internal `::lib.schema/query` except
+ the ID types are portable: `::id/database`, `::id/card`, `::id/segment`, `::id/measure`,
+ `::id/snippet` are strings; `::id/table` is `[db schema table]` and `::id/field` is
+ `[db schema table field …]`.
+ * **Portable form** — the same shape with all keys and enum values stringified. This is the
+ lingua franca of the repair pipeline ([[metabase.agent-lib.representations.repair]]) and the
+ output of [[metabase.agent-lib.representations.resolve/export-query]]. Repair operates on
+ string-keyed data because every clause head, options key, and `lib/`-prefixed marker is
+ authored as a string by the LLM and only keywordized after FK resolution.
+
+ This namespace owns the conversion between those two layers and the up-front structural check
+ that guards the entry to the repair pipeline.
+
+ Phase 1 MVP scope (see `repr-plan.md`):
+
+ * `source-table` and `source-card` (the latter as a portable entity_id string);
+ * single-stage queries (no multi-stage);
+ * top-level stage operations: `filters`, `aggregation`, `breakout`, `order-by`, `limit`,
+ `fields`;
+ * explicit joins supported; implicit joins are filled in by the repair pass."
+ (:require
+ [malli.core :as mc]
+ [malli.transform :as mtx]
+ [metabase.lib.schema :as lib.schema]
+ [metabase.util.i18n :refer [tru]]
+ [metabase.util.malli.humanize :as mu.humanize]
+ [metabase.util.malli.registry :as mr]))
+
+(set! *warn-on-reflection* true)
+
+;;; ============================================================
+;;; External (keyword-keyed) ↔ portable (string-keyed) conversion
+;;; ============================================================
+
+(defn- keyword->repr-string
+ "Stringify a keyword preserving its namespace, e.g. `:lib/type` → `\"lib/type\"`.
+ `clojure.core/name` would drop the namespace; `clojure.walk/stringify-keys` likewise."
+ [k]
+ (if-let [ns (namespace k)]
+ (str ns "/" (name k))
+ (name k)))
+
+(defn external-query->portable
+ "Convert a keyword-keyed external-query map (as produced by the JSON middleware's keywordizing
+ decoder, or by [[validate-external-query]]'s string-transformer decode) into the string-keyed
+ portable form expected by the repair pipeline.
+
+ Walks the structure once. Map keys are stringified preserving their namespace. Keyword values
+ (notably the `:lib/type` enum stamps `:mbql/query` / `:mbql.stage/mbql`) are also stringified
+ so the post-decode shape matches the all-strings invariant the repair pipeline relies on. FK
+ path segments and option values that already arrive as strings pass through unchanged."
+ [x]
+ (cond
+ (map? x)
+ (reduce-kv
+ (fn [m k v]
+ (assoc m
+ (cond-> k (keyword? k) keyword->repr-string)
+ (external-query->portable v)))
+ {}
+ x)
+
+ (vector? x) (mapv external-query->portable x)
+ (sequential? x) (mapv external-query->portable x)
+ (keyword? x) (keyword->repr-string x)
+ :else x))
+
+;;; ============================================================
+;;; Up-front validation against ::lib.schema/external-query
+;;; ============================================================
+
+(defn validate-external-query
+ "Decode and validate `external-query` (keyword-keyed, JSON-decoded) against
+ [[metabase.lib.schema/external-query]], returning the decoded query.
+
+ The string-transformer keywordizes enum values (`\"mbql/query\"` → `:mbql/query`,
+ `\"mbql.stage/mbql\"` → `:mbql.stage/mbql`, etc.) so the schema's keyword-typed enum slots
+ accept the JSON shape directly. Throws with `:error :invalid-external-query` and a humanized
+ explanation when the input shape is structurally invalid even after decoding.
+
+ NOTE: kept as a building block; the agent boundary uses [[assert-known-stage-keys!]] instead
+ because the lib schema's stage shape is not a closed map (typo'd stage keys would silently
+ pass) and the humanized output here references function predicates in a form that isn't
+ LLM-actionable."
+ [external-query]
+ (let [schema (mr/schema ::lib.schema/external-query)
+ decoded (mc/decode schema external-query mtx/string-transformer)]
+ (when-let [error (mr/explain ::lib.schema/external-query decoded)]
+ (throw (ex-info (tru "External query has an invalid structure.")
+ {:status-code 400
+ :error :invalid-external-query
+ :humanized (mu.humanize/humanize error)
+ :details (pr-str (mu.humanize/humanize error))
+ :schema ::lib.schema/external-query})))
+ decoded))
+
+(def ^:private known-stage-keys
+ "The complete set of top-level keys a `mbql.stage/mbql` stage may carry on the
+ LLM-facing surface. Sourced from `metabase.lib.schema.mbql-stage` and pruned to the
+ keys the `construct_query` / `query` contract advertises (see
+ `resources/metabot/prompts/tools/construct_notebook_query.md`)."
+ #{"lib/type"
+ "source-table" "source-card"
+ "filters" "aggregation" "breakout" "expressions" "fields" "joins"
+ "order-by" "limit"})
+
+(defn assert-known-stage-keys!
+ "Boundary check: every stage in the portable query must carry only known top-level keys.
+ `lib.schema.mbql-stage/mbql` is not a closed map, so a typo'd key (e.g. `aggreagation` vs
+ `aggregation`) would otherwise be silently dropped at resolve / lib.normalize time and the
+ LLM would never learn that its intent was discarded. This check catches the common typo
+ class with a clean `:agent-error?` diagnostic that names the offending key.
+
+ Operates on the string-keyed portable form produced by [[external-query->portable]]."
+ [portable-query]
+ (when (and (map? portable-query) (vector? (get portable-query "stages")))
+ (doseq [[stage-idx stage] (map-indexed vector (get portable-query "stages"))
+ :when (map? stage)
+ :let [unknown (remove known-stage-keys (keys stage))]
+ :when (seq unknown)]
+ (throw (ex-info (tru "Stage {0} has unknown key(s): {1}. Valid stage keys are: {2}."
+ stage-idx
+ (pr-str (vec unknown))
+ (pr-str (vec (sort known-stage-keys))))
+ {:status-code 400
+ :error :unknown-stage-key
+ :agent-error? true
+ :stage-index stage-idx
+ :unknown-keys (vec unknown)})))))
+
+;;; ============================================================
+;;; Repair-pipeline schema (string-keyed portable form)
+;;;
+;;; The schema below is intentionally narrower than `::lib.schema/external-query`: it asserts the
+;;; portable-form invariants the repair pass relies on (FK shape, always-present `{}` options
+;;; map, allowed top-level keys) and ignores per-operator term shapes — those are the lib-schema's
+;;; responsibility after FK resolution. This is what `validate-query` checks between repair and
+;;; resolve.
+;;; ============================================================
+
+(defn- non-blank-string?
+ [x]
+ (and (string? x) (not= "" x)))
+
+(defn- options-map?
+ [x]
+ (map? x))
+
+(defn- table-fk?
+ "Portable table FK: [db-name, schema-or-null, table-name]."
+ [x]
+ (and (vector? x)
+ (= 3 (count x))
+ (non-blank-string? (nth x 0))
+ (or (nil? (nth x 1)) (string? (nth x 1)))
+ (non-blank-string? (nth x 2))))
+
+(defn- field-fk?
+ "Portable field FK: [db-name, schema-or-null, table-name, field-name, ...json-path-segments]."
+ [x]
+ (and (vector? x)
+ (>= (count x) 4)
+ (non-blank-string? (nth x 0))
+ (or (nil? (nth x 1)) (string? (nth x 1)))
+ (non-blank-string? (nth x 2))
+ (every? non-blank-string? (drop 3 x))))
+
+(defn- clause-shape?
+ [x]
+ (and (vector? x)
+ (>= (count x) 2)
+ (string? (nth x 0))
+ (non-blank-string? (nth x 0))
+ (options-map? (nth x 1))))
+
+(def ^:private registry
+ {::table-fk [:and vector?
+ [:fn {:error/message "table FK must be [db-name, schema-or-null, table-name]"}
+ table-fk?]]
+ ::field-fk [:and vector?
+ [:fn {:error/message "field FK must be [db-name, schema-or-null, table-name, field-name, …]"}
+ field-fk?]]
+ ::options [:and map?
+ [:fn {:error/message "options must always be a map (use `{}` if empty)"}
+ options-map?]]
+ ::clause [:and vector?
+ [:fn {:error/message "clause must be [operator-string, options-map, …args]"}
+ clause-shape?]]
+ ::join [:map
+ {:closed false}
+ ["stages" [:sequential {:min 1} [:ref ::stage]]]
+ ["conditions" [:sequential {:min 1} [:ref ::clause]]]
+ ["alias" :string]
+ ["strategy" {:optional true}
+ [:enum "left-join" "right-join" "inner-join" "full-join"]]
+ ["fields" {:optional true}
+ [:or
+ [:enum "all" "none"]
+ [:sequential [:ref ::clause]]]]]
+ ::stage [:map
+ {:closed false}
+ ["lib/type" [:= "mbql.stage/mbql"]]
+ ["source-table" {:optional true} [:ref ::table-fk]]
+ ["source-card" {:optional true} :string]
+ ["joins" {:optional true} [:sequential [:ref ::join]]]
+ ["filters" {:optional true} [:sequential [:ref ::clause]]]
+ ["aggregation" {:optional true} [:sequential [:ref ::clause]]]
+ ["breakout" {:optional true} [:sequential [:ref ::clause]]]
+ ["order-by" {:optional true} [:sequential [:ref ::clause]]]
+ ["limit" {:optional true} [:maybe :int]]
+ ["fields" {:optional true} [:sequential [:ref ::clause]]]
+ ["expressions" {:optional true} [:sequential [:ref ::clause]]]]
+ ::query [:map
+ {:closed false}
+ ["lib/type" [:= "mbql/query"]]
+ ["database" {:optional true} :string]
+ ["stages" [:sequential {:min 1} [:ref ::stage]]]]})
+
+(def query-schema
+ "Malli schema for a Phase-1 portable representations query (string-keyed)."
+ [:schema {:registry registry} [:ref ::query]])
+
+(def stage-schema
+ "Malli schema for a single MBQL stage in the portable representations form."
+ [:schema {:registry registry} [:ref ::stage]])
+
+(defn validate-query
+ "Validate a string-keyed portable representations query against [[query-schema]] and return it
+ unchanged.
+
+ Used as a sanity check between the repair and resolve passes."
+ [parsed]
+ (when-let [error (mr/explain query-schema parsed)]
+ (throw (ex-info (tru "Representations query has an invalid structure.")
+ {:status-code 400
+ :error :invalid-representations-query
+ :humanized (mu.humanize/humanize error)
+ :details (pr-str (mu.humanize/humanize error))
+ :schema ::query})))
+ parsed)
diff --git a/src/metabase/agent_lib/representations/repair.clj b/src/metabase/agent_lib/representations/repair.clj
new file mode 100644
index 00000000000..baad284806c
--- /dev/null
+++ b/src/metabase/agent_lib/representations/repair.clj
@@ -0,0 +1,2379 @@
+(ns metabase.agent-lib.representations.repair
+ "Repair pass for LLM-authored representations queries.
+
+ Works on the **string-keyed, portable** representations form -- i.e. the JSON body
+ `metabase.agent-lib.representations/external-query->portable` produced from the LLM's
+ external-query input, *before* it has been handed to the resolver. This is where we gently
+ patch up the sort of shape drift that LLMs routinely produce:
+
+ * missing `{}` options on clauses (LLMs forget to emit empty maps);
+ * missing `\"lib/type\"` marker on stages and on the top-level query;
+ * stage / clause shape normalisations covering common LLM-authored variants
+ (see the per-pass docstrings below).
+
+ **Key invariant: idempotency.** Repair must be a fixed point under repeated application: for
+ any repr `q`, `(repair q)` must equal `(repair (repair q))`. This is enforced by property test
+ and by construction -- every pass is written as `when-something-is-missing, add it`, never as
+ `rewrite what's there`.
+
+ The repair pass does **not** do FK resolution (that's the resolver's job) and does **not**
+ validate (that's `representations/validate-query`'s job). It runs *between* the JSON
+ external-query → portable conversion and validate-and-resolve.
+
+ ## Implicit joins
+
+ In addition to the shape passes above, `repair` also runs an **implicit-join pass** that uses
+ the caller's `MetadataProvider` to auto-wire `source-field` options on field clauses that
+ reference a table other than the stage's `source-table`. That pass is the only reason `repair`
+ takes an `mp` argument - the shape passes themselves don't need it."
+ (:require
+ [clojure.string :as str]
+ [clojure.walk :as walk]
+ [metabase.agent-lib.representations.resolve :as repr.resolve]
+ [metabase.lib.core :as lib]
+ [metabase.lib.metadata.protocols :as lib.metadata.protocols]
+ [metabase.models.serialization.resolve :as resolve]
+ [metabase.models.serialization.resolve.mp :as resolve.mp]
+ [metabase.util :as u]
+ [metabase.util.i18n :refer [tru]]
+ [metabase.util.log :as log]))
+
+(set! *warn-on-reflection* true)
+
+;;; ============================================================
+;;; Pass 1 -- ensure every clause vector has an options map at position 2
+;;; ============================================================
+
+(defn- non-blank-string? [x]
+ (and (string? x) (not= "" x)))
+
+(defn- looks-like-fk-path?
+ "An FK path is a vector of strings (possibly with `nil` for schema-less DBs) of length >= 3
+ (`[db schema table]`) or >= 4 (`[db schema table col …]`). We use length >= 3 as the cutoff
+ here to keep things safe -- shorter vectors of strings are probably not FK paths, they're more
+ likely bare clauses like `[\"count\"]` that the LLM forgot to annotate."
+ [v]
+ (and (>= (count v) 3)
+ (every? #(or (string? %) (nil? %)) v)))
+
+(defn- clause-like?
+ "Heuristic: a real clause vector (not a map entry, not an FK path) whose head is a non-blank
+ operator string. We skip:
+
+ * `map-entry?` values (postwalk descends into map entries; their shape is [k v] and our
+ heuristic would otherwise misidentify them as bare clauses);
+ * FK-paths of length >= 3 consisting entirely of strings and `nil`s (see
+ [[looks-like-fk-path?]])."
+ [v]
+ (and (vector? v)
+ (not (map-entry? v))
+ (pos? (count v))
+ (non-blank-string? (first v))
+ (not (looks-like-fk-path? v))))
+
+(defn- needs-options-map?
+ "True if `v` is a clause-like vector whose position 2 is either missing or `nil`.
+
+ IMPORTANT: we do NOT treat a non-nil non-map at position 2 as \"missing options\". That would be
+ ambiguous -- position 2 might be a nested clause (`[\"=\", [\"field\", ...], 10]` where the LLM
+ forgot the options on `=`), and replacing that nested clause with `{}` would silently drop
+ data. Instead we only repair the two unambiguous cases:
+
+ * clause too short (no position 2 at all): `[\"count\"]` -> `[\"count\" {}]`;
+ * explicit nil at position 2: `[\"count\", nil]` -> `[\"count\" {}]`.
+
+ For a clause like `[\"=\", [\"field\", ...], 10]` where the options slot holds another clause,
+ we **insert** `{}` before the existing element (see [[insert-options-map]])."
+ [v]
+ (and (clause-like? v)
+ (or (< (count v) 2)
+ (nil? (nth v 1))
+ ;; position 2 is present but not a map -- means the LLM skipped the options slot
+ ;; entirely and the arg at position 1 is actually a term (nested clause or FK-path
+ ;; vector or a scalar). In that case we need to insert, not replace.
+ (not (map? (nth v 1))))))
+
+(defn- insert-options-map
+ "Given a clause-like vector missing its options map at position 2, produce a vector with `{}`
+ there. Three cases:
+
+ * `[op]` -> `[op {}]`
+ * `[op nil …args]` -> `[op {} …args]` (replace the nil placeholder)
+ * `[op <non-nil-non-map> …args]` -> `[op {} <non-nil-non-map> …args]` (insert, don't replace)"
+ [v]
+ (cond
+ (< (count v) 2) (conj v {})
+ (nil? (nth v 1)) (assoc v 1 {})
+ (not (map? (nth v 1))) (into [(first v) {}] (subvec v 1))
+ :else v))
+
+(defn- ensure-clause-options*
+ [form]
+ (walk/postwalk
+ (fn [node]
+ (if (and (vector? node) (not (map-entry? node)) (needs-options-map? node))
+ (insert-options-map node)
+ node))
+ form))
+
+;;; ============================================================
+;;; Pass 1.7 -- unwrap nested `[field opts [field inner-opts target]]` clauses.
+;;;
+;;; LLMs occasionally write a `field` clause that wraps another `field` clause, e.g.
+;;;
+;;; ["field" {"temporal-unit" "month"} ["field" {} ["Sample" "PUBLIC" "T" "COL"]]]
+;;;
+;;; reasoning as "apply granularity to this field." The intended MBQL is a single
+;;; `field` clause with the options merged -- outer options win on key conflicts (because
+;;; the outer layer is what the LLM thought it was *adding*). We collapse nests of any
+;;; depth into one flat `["field" <merged-opts> <target>]`.
+;;;
+;;; A `field` clause is recognised by head `"field"` at position 0, a map at position 1,
+;;; and a third slot at position 2 that is either an FK path (vector of strings/nil) or a
+;;; column-name string (cross-stage ref). When the third slot is itself a `field` clause,
+;;; we collapse.
+;;; ============================================================
+
+(defn- field-clause-shape?
+ "True if `v` looks like a `field` clause: `[\"field\" <opts-map> <target>]`."
+ [v]
+ (and (vector? v)
+ (= 3 (count v))
+ (= "field" (nth v 0))
+ (map? (nth v 1))))
+
+(defn- collapse-nested-field
+ "If `node` is a `field` clause whose target slot is itself a `field` clause, collapse
+ them into one clause with merged options (outer options win), recursively. Returns the
+ collapsed clause (or the original `node` if no collapse applies)."
+ [node]
+ (loop [outer-opts (nth node 1)
+ inner (nth node 2)]
+ (if (field-clause-shape? inner)
+ (recur (merge (nth inner 1) outer-opts)
+ (nth inner 2))
+ ["field" outer-opts inner])))
+
+(defn- unwrap-nested-field-clauses*
+ [form]
+ (walk/postwalk
+ (fn [node]
+ (if (and (field-clause-shape? node)
+ (field-clause-shape? (nth node 2)))
+ (collapse-nested-field node)
+ node))
+ form))
+
+;;; ============================================================
+;;; Pass 1.81 -- canonicalise common operator-name aliases.
+;;;
+;;; LLMs are heavily-trained on shell scripts, Python comparison protocols, and SQL-ish
+;;; idioms. They occasionally pick up:
+;;;
+;;; * shell-style comparison operators: `eq`, `ne`, `lt`, `lte` / `le`, `gt`, `gte` / `ge`
+;;; (cf. `man test`);
+;;; * verbose comparison spellings: `equals`, `not-equals`;
+;;; * lib-renamed aggregation / clause names that stuck around:
+;;; - `count-if` → `count-where`
+;;; - `variance` → `var`
+;;; - `stddev-pop` → `stddev`
+;;; - `count-distinct` → `distinct`
+;;; - `distinct-count` → `distinct`
+;;; - `relative-date` → `relative-datetime`
+;;; - `temporal-diff` → `datetime-diff`
+;;; - `is-not-null` → `not-null`
+;;;
+;;; The lib-rename set is carried over from the sexp pipeline's
+;;; `metabase.agent-lib.syntax/canonical-operator-aliases` (see
+;;; `repr-deletion-followups.md` § 1.1) - the original commentary recommended against
+;;; reintroducing aliases, but we add the shell/SQL aliases anyway because LLMs are
+;;; demonstrably shell-literate and the cost of supporting these names is one extra
+;;; lookup at the start of the pipeline. The temporal-bucket aliases (`dayofweek`,
+;;; `day-of-week`, `hour-of-day`, `month-of-year`, `quarter-of-year`) are kept in their
+;;; own pass (1.8) for separate testing and because they target different lib heads
+;;; depending on the unit.
+;;;
+;;; Notably **not** ported:
+;;; * `if` → `case`: lib accepts both (§conditional.cljc explicitly aliases them);
+;;; * `month` → `get-month`: ambiguous (could also be `:temporal-bucket :month`);
+;;; * `|` → `or`: too symbolic, unlikely from any model.
+;;; ============================================================
+
+(def ^:private operator-name-aliases
+ "Lowercased alias → canonical lib head. Match is case-insensitive on lookup."
+ {;; Shell-style / Python-style comparison
+ "eq" "="
+ "equals" "="
+ "ne" "!="
+ "not-equals" "!="
+ "lt" "<"
+ "le" "<="
+ "lte" "<="
+ "gt" ">"
+ "ge" ">="
+ "gte" ">="
+ ;; Lib renames (carried over from sexp `canonical-operator-aliases`)
+ "count-if" "count-where"
+ "variance" "var"
+ "stddev-pop" "stddev"
+ "count-distinct" "distinct"
+ "distinct-count" "distinct"
+ "relative-date" "relative-datetime"
+ "temporal-diff" "datetime-diff"
+ "is-not-null" "not-null"})
+
+(defn- operator-alias-clause?
+ "True when `node` is a clause whose head (case-insensitive) matches a known alias and
+ is not already canonical. Requires options-map at slot 1 - bare-clause case is handled
+ by Pass 1, which runs first."
+ [node]
+ (and (vector? node)
+ (>= (count node) 2)
+ (string? (nth node 0))
+ (map? (nth node 1))
+ (let [lower (u/lower-case-en (nth node 0))]
+ (and (contains? operator-name-aliases lower)
+ (not= (nth node 0) (get operator-name-aliases lower))))))
+
+(defn- rewrite-operator-name-aliases*
+ [form]
+ (walk/postwalk
+ (fn [node]
+ (if (operator-alias-clause? node)
+ (assoc node 0 (get operator-name-aliases (u/lower-case-en (nth node 0))))
+ node))
+ form))
+
+;;; ============================================================
+;;; Pass 1.8 -- canonicalise temporal-bucket extraction aliases.
+;;;
+;;; LLMs naturally pick up English-flavoured operator names like `dayofweek`,
+;;; `day-of-week`, `hour-of-day`, `month-of-year`, `quarter-of-year` for the temporal-
+;;; extraction helpers. lib's canonical names are `get-day-of-week`, `get-hour`,
+;;; `get-month`, `get-quarter` (see `metabase.lib.schema.expression.temporal`). We
+;;; rewrite the alias forms to canonical so downstream resolve/validate doesn't reject
+;;; them.
+;;;
+;;; Carried over from `metabase.agent-lib.repair.normalize.forms` (see
+;;; `repr-deletion-followups.md` § 1.2). Idempotent: the rewrite only fires when the head
+;;; is a known alias; canonical heads are left alone.
+;;; ============================================================
+
+(def ^:private temporal-bucket-extraction-aliases
+ "Map from LLM-favoured alias to canonical lib operator name."
+ {"dayofweek" "get-day-of-week"
+ "day-of-week" "get-day-of-week"
+ "hour-of-day" "get-hour"
+ "month-of-year" "get-month"
+ "quarter-of-year" "get-quarter"})
+
+(defn- temporal-bucket-alias-clause?
+ "True when `node` is a clause whose head is a known temporal-bucket-extraction alias.
+ Requires an options map in slot 1 - the bare-clause case (no options) is handled by
+ Pass 1, which runs first."
+ [node]
+ (and (vector? node)
+ (>= (count node) 2)
+ (string? (nth node 0))
+ (map? (nth node 1))
+ (contains? temporal-bucket-extraction-aliases (nth node 0))))
+
+(defn- rewrite-temporal-bucket-aliases*
+ [form]
+ (walk/postwalk
+ (fn [node]
+ (if (temporal-bucket-alias-clause? node)
+ (assoc node 0 (get temporal-bucket-extraction-aliases (nth node 0)))
+ node))
+ form))
+
+;;; ============================================================
+;;; Pass 1.85 -- canonicalise order-by direction aliases.
+;;;
+;;; The lib schema accepts only `[asc, {}, <ref>]` and `[desc, {}, <ref>]` as order-by
+;;; direction clauses. LLMs sometimes write `[ascending, {}, …]` / `[descending, {}, …]`
+;;; and uppercase variants like `[ASC, {}, …]`. We rewrite any case-insensitive variant of
+;;; the four spellings (`asc`, `ascending`, `desc`, `descending`) to canonical lowercase
+;;; `asc` / `desc` when used as a clause head.
+;;;
+;;; The rewrite is restricted to the **order-by-clause shape** (head + options map +
+;;; exactly one ref-shaped argument); we don't touch a bare string "ASC"/"DESC" that might
+;;; appear elsewhere as a literal value. Carried over with a wider alias set than the
+;;; sexp original (which accepted only case-insensitive `asc`/`desc`); see
+;;; `repr-deletion-followups.md` § 1.3.
+;;; ============================================================
+
+(def ^:private direction-aliases
+ "Map from lowercase alias to canonical lib direction string."
+ {"asc" "asc"
+ "ascending" "asc"
+ "desc" "desc"
+ "descending" "desc"})
+
+(defn- direction-clause-head?
+ "True when `head` is a non-canonical alias (case-insensitive variant of one of
+ `direction-aliases`' keys) that should be rewritten. We exclude the canonical lowercase
+ `asc` / `desc` so that already-canonical clauses pass through unchanged (preserving
+ idempotency cheaply)."
+ [head]
+ (and (string? head)
+ (let [lower (u/lower-case-en head)]
+ (and (contains? direction-aliases lower)
+ (not= head (get direction-aliases lower))))))
+
+(defn- direction-alias-clause?
+ "True when `node` is a clause-shaped vector (head + options-map + 1 arg) whose head is
+ a direction alias to be rewritten."
+ [node]
+ (and (vector? node)
+ (= 3 (count node))
+ (map? (nth node 1))
+ (direction-clause-head? (nth node 0))))
+
+(defn- rewrite-direction-aliases*
+ [form]
+ (walk/postwalk
+ (fn [node]
+ (if (direction-alias-clause? node)
+ (assoc node 0 (get direction-aliases (u/lower-case-en (nth node 0))))
+ node))
+ form))
+
+;;; ============================================================
+;;; Pass 1.84 -- normalise alternative `case` / `if` argument shapes.
+;;;
+;;; lib's canonical shape is `[case, {}, [[pred1 then1] [pred2 then2] ...] default?]` -
+;;; a single vector of branch pairs in slot 2, optional default in slot 3. LLMs sometimes
+;;; emit alternative shapes that are unambiguously interpretable:
+;;;
+;;; 1. Three bare args: `[case, {}, pred, then, else]`
+;;; → `[case, {}, [[pred then]], else]`
+;;; 2. Branch pairs as separate args: `[case, {}, [p1 t1], [p2 t2], default]`
+;;; → `[case, {}, [[p1 t1] [p2 t2]], default]`
+;;; 3. Flat alternating: `[case, {}, p1, t1, p2, t2, default?]`
+;;; → `[case, {}, [[p1 t1] [p2 t2]], default?]`
+;;; 4. Trailing `["else" x]` branch inside the pairs vector
+;;; → strip and treat `x` as the default.
+;;;
+;;; `if` is a documented alias for `case`; we normalise it the same way (lib accepts both
+;;; tags and treats them identically). Carried over from the sexp pipeline's
+;;; `repair/normalize/forms.clj/repair-case-args` (see `repr-deletion-followups.md`
+;;; § 1.8).
+;;;
+;;; Idempotency: after the first rewrite the args are exactly `[<vector-of-pairs>]` or
+;;; `[<vector-of-pairs>, <default>]`, neither of which matches the alternative-shape
+;;; classifiers below.
+;;; ============================================================
+
+(defn- branch-pair? [v]
+ (and (vector? v) (= 2 (count v))))
+
+(defn- else-branch?
+ "True for `[\"else\" x]` or its post-Pass-1 form `[\"else\" {} x]`. Pass 1
+ (`ensure-clause-options*`) runs before us, so by the time this pass sees an LLM-authored
+ `[\"else\" 0]` it has already been rewritten to `[\"else\" {} 0]`."
+ [v]
+ (and (vector? v)
+ (string? (nth v 0))
+ (= "else" (u/lower-case-en (nth v 0)))
+ (or (= 2 (count v))
+ (and (= 3 (count v)) (map? (nth v 1))))))
+
+(defn- else-branch-payload [v]
+ (if (= 2 (count v)) (nth v 1) (nth v 2)))
+
+(defn- split-trailing-else
+ "If the last entry of `branches` is an `else-branch?`, peel it off and use its payload
+ as the default; otherwise return inputs unchanged."
+ [branches default]
+ (if (and (seq branches) (else-branch? (peek branches)))
+ [(pop branches) (else-branch-payload (peek branches))]
+ [branches default]))
+
+(defn- canonical-case-args
+ "Build the canonical `[<vector-of-pairs> default?]` arg sequence given already-classified
+ `branches` (vector of pairs) and an optional `default`. Strips a trailing `else` branch
+ from `branches`. Returns the canonical args vector for splicing into a `case` / `if`
+ clause."
+ [branches default]
+ (let [[branches default] (split-trailing-else (vec branches) default)]
+ (if (some? default)
+ [(vec branches) default]
+ [(vec branches)])))
+
+(defn- pair-or-else? [v]
+ (or (branch-pair? v) (else-branch? v)))
+
+(defn- classify-case-args
+ "Given the args of a `case` / `if` clause (everything after head + opts), return
+ `[branches default]` for one of the recognised shapes - including the canonical one (so
+ the central `canonical-case-args` step uniformly handles trailing-else stripping). Return
+ `nil` only when the args are unrecognised."
+ [args]
+ (cond
+ ;; Already canonical or canonical-with-trailing-else: a single vector in slot 0 whose
+ ;; entries are branch-pairs (or a final else-branch), with optional explicit default in
+ ;; slot 1.
+ (and (or (= 1 (count args)) (= 2 (count args)))
+ (vector? (nth args 0))
+ (seq (nth args 0))
+ (every? pair-or-else? (nth args 0)))
+ [(nth args 0) (when (= 2 (count args)) (nth args 1))]
+
+ ;; Three bare non-pair args: pred, then, else
+ (and (= 3 (count args))
+ (not (branch-pair? (nth args 0))))
+ [[[(nth args 0) (nth args 1)]] (nth args 2)]
+
+ ;; Two bare non-pair args: pred, then (no default)
+ (and (= 2 (count args))
+ (not (branch-pair? (nth args 0))))
+ [[[(nth args 0) (nth args 1)]] nil]
+
+ ;; Leading branch pairs followed by an optional non-pair fallback
+ ;; (covers \"branch pairs as separate args\").
+ (and (>= (count args) 2)
+ (branch-pair? (nth args 0)))
+ (let [pairs (vec (take-while branch-pair? args))
+ remainder (drop (count pairs) args)]
+ [pairs (when (= 1 (count remainder)) (first remainder))])
+
+ ;; Flat alternating pred/then args (≥4 args). Falls through from "branch pairs as
+ ;; separate args" above when the first arg is a non-2-tuple vector like `["=" {} field
+ ;; val]`.
+ (>= (count args) 4)
+ (let [n (count args)
+ even-cnt (- n (rem n 2))
+ pred-thens (partition 2 (take even-cnt args))
+ default (when (odd? n) (nth args (dec n)))]
+ [(mapv vec pred-thens) default])
+
+ :else nil))
+
+(defn- case-clause? [v]
+ (and (vector? v)
+ (>= (count v) 2)
+ (string? (nth v 0))
+ (map? (nth v 1))
+ (contains? #{"case" "if"} (nth v 0))))
+
+(defn- normalise-case-args
+ "Inspect the args of `clause`; if they match a recognised shape, return the clause with
+ canonical args (uniformly stripping any trailing `else` branch from the pairs vector).
+ Unrecognised args pass through untouched."
+ [clause]
+ (let [head (nth clause 0)
+ opts (nth clause 1)
+ args (subvec clause 2)]
+ (if-let [[branches default] (classify-case-args args)]
+ (let [canonical-args (canonical-case-args branches default)
+ new-clause (into [head opts] canonical-args)]
+ ;; Idempotency: only return the rewritten form when it's actually different.
+ ;; Identical → the input was already canonical.
+ (if (= new-clause clause) clause new-clause))
+ clause)))
+
+(defn- normalise-case-clauses*
+ [form]
+ (walk/postwalk
+ (fn [node]
+ (if (case-clause? node)
+ (normalise-case-args node)
+ node))
+ form))
+
+;;; ============================================================
+;;; Pass 1.82 -- normalise filter clauses where the LLM passed a values-list as a single
+;;; vector arg.
+;;;
+;;; lib's canonical shape for `:in` / `:not-in` is **flat**: `[in, {}, lhs, v1, v2, v3]`.
+;;; Likewise `:=` and `:!=` take exactly two operand args: `[=, {}, lhs, rhs]`. LLMs
+;;; sometimes put the value list into a single vector slot:
+;;;
+;;; [in, {}, lhs, [v1, v2, v3]] → splat → [in, {}, lhs, v1, v2, v3]
+;;; [not-in, {}, lhs, [v1, v2, v3]] → splat → [not-in, {}, lhs, v1, v2, v3]
+;;;
+;;; And occasionally use `=` / `!=` with a list value, expecting list-membership semantics:
+;;;
+;;; [=, {}, lhs, [v1, v2, v3]] → [in, {}, lhs, v1, v2, v3]
+;;; [!=, {}, lhs, [v1, v2, v3]] → [not-in, {}, lhs, v1, v2, v3]
+;;;
+;;; Adapted from the sexp pipeline's `in`/`not-in`/`=`/`!=` repair branches (see
+;;; `repr-deletion-followups.md` § 1.10). The sexp form `[in lhs [v1 v2 v3]]` was nested by
+;;; design; the repr canonical form is flat, so we splat instead of just rewriting head.
+;;;
+;;; A "values list" is recognised conservatively: a non-empty vector whose every entry is a
+;;; primitive scalar (string, number, boolean, nil). This excludes nested clauses
+;;; (vectors with a string head + map options) and FK-path arguments (which only appear
+;;; inside a `field` clause, never as values to a comparison op).
+;;; ============================================================
+
+(defn- scalar-literal? [v]
+ (or (string? v) (number? v) (boolean? v) (nil? v)))
+
+(defn- values-list? [v]
+ (and (vector? v)
+ (seq v)
+ (every? scalar-literal? v)))
+
+(defn- splat-in-values-clause [head opts lhs values]
+ (into [head opts lhs] values))
+
+(defn- =->in-head [head]
+ (case head "=" "in" "!=" "not-in"))
+
+(defn- comparison-lhs-clause?
+ "Heuristic for what counts as a real \"left-hand side\" of a comparison: a clause vector
+ with a string head and a map options at slot 1 (e.g. `field`, `expression`, `+`, etc.).
+ Crucially, this excludes a bare FK-path vector (`[DB SCHEMA TABLE COL]`) - which is a
+ vector of strings and would otherwise be mis-classified as an LHS by the value-list
+ splat pass, making repair non-idempotent on adversarial property-test inputs that look
+ like `[\"=\" {} [\"DB\" \"S\" \"T\"] [\"v1\" \"v2\"]]`."
+ [v]
+ (and (vector? v)
+ (>= (count v) 2)
+ (string? (nth v 0))
+ (map? (nth v 1))))
+
+(defn- list-value-comparison-clause
+ "If `node` is a comparison clause whose last arg is a values-list, return
+ `[head opts lhs values]` so the splat can be applied. Otherwise return `nil`.
+
+ Recognises two shapes (pass runs *before* `ensure-clause-options*`):
+
+ * `[head, opts-map, lhs, [v1 v2 …]]` (4 elements, options already in place); and
+ * `[head, lhs, [v1 v2 …]]` (3 elements, options omitted - we splice an empty
+ options map for downstream uniformity).
+
+ Additionally requires `lhs` to be clause-shaped (`comparison-lhs-clause?`), to avoid
+ mis-firing on adversarial inputs where every arg is a vector-of-strings."
+ [heads node]
+ (when (and (vector? node)
+ (>= (count node) 3)
+ (string? (nth node 0))
+ (contains? heads (nth node 0)))
+ (let [head (nth node 0)
+ opts-at (when (map? (nth node 1)) 1)
+ ;; If options are present, lhs is at slot 2 and values at slot 3; otherwise
+ ;; lhs is at slot 1 and values at slot 2. Either way we need exactly one lhs and
+ ;; one values-list arg, so total args after head is either 2 (no opts) or 3 (opts).
+ [lhs values-slot] (if opts-at
+ [(when (= 4 (count node)) (nth node 2))
+ (when (= 4 (count node)) (nth node 3))]
+ [(when (= 3 (count node)) (nth node 1))
+ (when (= 3 (count node)) (nth node 2))])]
+ (when (and (comparison-lhs-clause? lhs)
+ (values-list? values-slot))
+ [head (if opts-at (nth node 1) {}) lhs values-slot]))))
+
+(defn- normalise-list-value-comparisons*
+ "Pre-Pass-1 sweep: splat values-list args of `in`/`not-in` and rewrite `=`/`!=` against a
+ values-list to `in`/`not-in`. Runs *before* `ensure-clause-options*` because Pass 1 would
+ otherwise mis-identify a 2-element values-list (e.g. `[\"alice\" \"bob\"]`) as a bare
+ clause and corrupt it by inserting `{}` between the two scalars."
+ [form]
+ (walk/postwalk
+ (fn [node]
+ (or (when-let [[head opts lhs values] (list-value-comparison-clause #{"in" "not-in"} node)]
+ (splat-in-values-clause head opts lhs values))
+ (when-let [[head opts lhs values] (list-value-comparison-clause #{"=" "!="} node)]
+ (splat-in-values-clause (=->in-head head) opts lhs values))
+ node))
+ form))
+
+;;; ============================================================
+;;; Pass 1.83 -- unwrap boolean wrapper clauses.
+;;;
+;;; LLMs occasionally write `["true", x]` thinking of it as "wrap this clause as truthy",
+;;; or `["false", x]` as "wrap this clause as falsy". Neither has any meaning in lib; the
+;;; canonical equivalents are just `x` and `["not", {}, x]`. We unwrap when we see them.
+;;; Carried over from the sexp pipeline's `syntax/boolean-wrapper-form?` (see
+;;; `repr-deletion-followups.md` § 1.4).
+;;;
+;;; Form recognised: `["true" {} x]` (1 arg) - unwrap to `x`.
+;;; `["false" {} x]` (1 arg) - rewrite to `["not" {} x]`.
+;;;
+;;; The 0-arg literal forms `["true" {}]` and `["false" {}]` (boolean literals) are NOT
+;;; touched. Multi-arg variants (≥2 args) we don't touch either - those would be
+;;; legitimate uses of the head.
+;;; ============================================================
+
+(defn- boolean-wrapper-clause?
+ "True when `node` is `[\"true\" {} x]` or `[\"false\" {} x]` - exactly one arg."
+ [node]
+ (and (vector? node)
+ (= 3 (count node))
+ (string? (nth node 0))
+ (map? (nth node 1))
+ (let [head (u/lower-case-en (nth node 0))]
+ (or (= head "true")
+ (= head "false")))))
+
+(defn- unwrap-boolean-wrapper [node]
+ (let [head (u/lower-case-en (nth node 0))
+ x (nth node 2)]
+ (case head
+ "true" x
+ "false" ["not" {} x])))
+
+(defn- unwrap-boolean-wrappers*
+ [form]
+ (walk/postwalk
+ (fn [node]
+ (if (boolean-wrapper-clause? node)
+ (unwrap-boolean-wrapper node)
+ node))
+ form))
+
+;;; ============================================================
+;;; Pass 1.87 -- swap out-of-order literal bounds in `between` clauses.
+;;;
+;;; The lib schema for `:between` does not enforce `min <= max` (there's an explicit TODO
+;;; comment in `metabase.lib.schema.filter` flagging this). LLMs occasionally swap the two
+;;; bounds, especially for date ranges (e.g. `between(date, "2024-12-31", "2024-01-01")`).
+;;; The query then runs but returns no rows, which is silently misleading. We swap the two
+;;; bounds here when they're directly comparable literals.
+;;;
+;;; Cases handled:
+;;; * both bounds are numbers,
+;;; * both bounds are ISO-8601 date / date-time strings (string lex order = chronological
+;;; for ISO-8601),
+;;; * both bounds are `[absolute-datetime, {}, <iso-str>, <unit>]` clauses (the iso-str
+;;; drives the comparison).
+;;;
+;;; If either bound is non-literal (a `field` ref, an expression, a `relative-datetime`
+;;; clause, etc.) we don't touch the clause - we can't compare without execution. See
+;;; `repr-deletion-followups.md` § 1.5 (the scalar-wrap sub-case is intentionally not
+;;; ported - the prompt is explicit about between's three-arg shape).
+;;; ============================================================
+
+(defn- absolute-datetime-clause? [v]
+ (and (vector? v)
+ (>= (count v) 3)
+ (= "absolute-datetime" (nth v 0))
+ (map? (nth v 1))
+ (string? (nth v 2))))
+
+(defn- between-bound-comparable
+ "Extract a comparable value from `bound` if it's a literal we can order. Returns the
+ value (a Number or String) or `nil` if the bound is not directly comparable."
+ [bound]
+ (cond
+ (number? bound) bound
+ (string? bound) bound
+ (absolute-datetime-clause? bound) (nth bound 2)
+ :else nil))
+
+(defn- bounds-comparable-and-swappable?
+ "True when both bounds are extractable comparables of the same kind (both numbers, both
+ strings) and the lower bound compares strictly greater than the upper."
+ [lower upper]
+ (let [lo (between-bound-comparable lower)
+ hi (between-bound-comparable upper)]
+ (cond
+ (and (number? lo) (number? hi)) (> lo hi)
+ (and (string? lo) (string? hi)) (pos? (compare lo hi))
+ :else false)))
+
+(defn- between-clause? [v]
+ (and (vector? v)
+ (= 5 (count v))
+ (= "between" (nth v 0))
+ (map? (nth v 1))))
+
+(defn- swap-between-bounds*
+ [form]
+ (walk/postwalk
+ (fn [node]
+ (if (and (between-clause? node)
+ (bounds-comparable-and-swappable? (nth node 3) (nth node 4)))
+ (-> node (assoc 3 (nth node 4)) (assoc 4 (nth node 3)))
+ node))
+ form))
+
+;;; ============================================================
+;;; Pass 1.86 -- wrap bare ISO-date string bounds in `between` clauses as
+;;; `[absolute-datetime, {}, <iso-str>, "day"]`.
+;;;
+;;; LLMs frequently write `[between, {}, <date-field>, "2024-01-01", "2024-12-31"]`,
+;;; using bare strings as the bounds. lib's `:between` schema demands a temporal
+;;; expression on each side once any side is temporal; bare strings won't satisfy
+;;; `:type/Date`. We detect the case where at least one of the two bounds matches the
+;;; ISO-8601 `yyyy-mm-dd` pattern and wrap each matching string as an
+;;; `["absolute-datetime" {} <iso-str> "day"]` clause. Carried over from the sexp
+;;; pipeline's `wrap-iso-date-as-absolute-datetime` (see
+;;; `repr-deletion-followups.md` § 1.6). High-frequency LLM pattern.
+;;;
+;;; Idempotency: after wrap, bounds are vectors, so the predicate (string + ISO regex)
+;;; no longer matches.
+;;; ============================================================
+
+(def ^:private iso-date-pattern
+ "Recognises an ISO-8601 calendar-date string (yyyy-mm-dd, optionally with a time portion)."
+ #"\d{4}-\d{2}-\d{2}(?:[T ]\d{2}:\d{2}(?::\d{2}(?:\.\d+)?)?(?:Z|[+\-]\d{2}:?\d{2})?)?")
+
+(defn- iso-date-string? [v]
+ (and (string? v)
+ (re-matches iso-date-pattern (str/trim v))))
+
+(defn- temporal-clause-head?
+ "Heads that are unambiguously temporal-shaped clauses."
+ [head]
+ (contains? #{"absolute-datetime" "relative-datetime" "now"
+ "get-year" "get-quarter" "get-month" "get-week" "get-day"
+ "get-day-of-week" "get-hour" "get-minute" "get-second"}
+ head))
+
+(defn- temporal-shaped-clause? [v]
+ (and (vector? v)
+ (>= (count v) 1)
+ (string? (nth v 0))
+ (temporal-clause-head? (nth v 0))))
+
+(defn- wrap-iso-date [v]
+ (if (iso-date-string? v)
+ ["absolute-datetime" {} (str/trim v) "day"]
+ v))
+
+(defn- between-needs-iso-wrap?
+ "Trigger the ISO-wrap when at least one bound is already a temporal-shaped clause OR
+ at least one bound is an ISO-date string. The first case mirrors sexp's behaviour
+ (`temporal-expression?` on either side), the second case is a small extension - if
+ both bounds are bare ISO date strings the structure is unambiguous and bare strings
+ would fail validation anyway."
+ [lo hi]
+ (or (temporal-shaped-clause? lo)
+ (temporal-shaped-clause? hi)
+ (iso-date-string? lo)
+ (iso-date-string? hi)))
+
+(defn- wrap-iso-date-bounds*
+ [form]
+ (walk/postwalk
+ (fn [node]
+ (if (and (between-clause? node)
+ (between-needs-iso-wrap? (nth node 3) (nth node 4)))
+ (-> node
+ (assoc 3 (wrap-iso-date (nth node 3)))
+ (assoc 4 (wrap-iso-date (nth node 4))))
+ node))
+ form))
+
+;;; ============================================================
+;;; Pass 1.865 -- wrap bare `"now"` string literals in temporal contexts as the canonical
+;;; `["now" {}]` clause.
+;;;
+;;; LLMs sometimes write `[<, {}, <date-field>, "now"]` or `[between, {}, <field>,
+;;; "2024-01-01", "now"]` - using the bare string `"now"` (case-insensitive, optional
+;;; whitespace) where lib expects a `["now" {}]` clause. We rewrite such literals to the
+;;; canonical clause shape **only inside a clause whose other operand is already temporal-
+;;; shaped** (a `field` with `temporal-unit`, an `absolute-datetime`, a `relative-datetime`,
+;;; another `now`, or one of the `get-*` extraction heads).
+;;;
+;;; The context restriction matters: a column literally containing the value `"now"` could
+;;; legitimately appear as an operand in a non-temporal comparison. Carried over from the
+;;; sexp pipeline's `wrap-now-as-expression` (see `repr-deletion-followups.md` § 1.7).
+;;; ============================================================
+
+(defn- now-literal? [v]
+ (and (string? v)
+ (= "now" (u/lower-case-en (str/trim v)))))
+
+(defn- field-with-temporal-unit? [v]
+ (and (vector? v)
+ (>= (count v) 2)
+ (= "field" (nth v 0))
+ (map? (nth v 1))
+ (contains? (nth v 1) "temporal-unit")))
+
+(defn- temporal-context-operand? [v]
+ (or (temporal-shaped-clause? v)
+ (field-with-temporal-unit? v)))
+
+(def ^:private temporal-comparison-heads
+ "Comparison-style heads for which we'll wrap a bare `\"now\"` literal in another operand
+ position."
+ #{"=" "!=" "<" "<=" ">" ">=" "between"})
+
+(defn- temporal-comparison-clause? [v]
+ (and (vector? v)
+ (>= (count v) 3)
+ (string? (nth v 0))
+ (map? (nth v 1))
+ (contains? temporal-comparison-heads (nth v 0))))
+
+(defn- wrap-now-literal [v]
+ (if (now-literal? v)
+ ["now" {}]
+ v))
+
+(defn- maybe-wrap-now-operands
+ "For a comparison clause, return a clause with each `\"now\"` literal in arg positions
+ rewritten to `[\"now\" {}]`, but only if at least one *other* operand in the clause is
+ already temporal-shaped (so we know we're really in a temporal context)."
+ [clause]
+ (let [args (subvec clause 2)]
+ (if (some temporal-context-operand? args)
+ (let [rewritten (mapv wrap-now-literal args)]
+ (into (subvec clause 0 2) rewritten))
+ clause)))
+
+(defn- wrap-now-literals*
+ [form]
+ (walk/postwalk
+ (fn [node]
+ (if (temporal-comparison-clause? node)
+ (maybe-wrap-now-operands node)
+ node))
+ form))
+
+;;; ============================================================
+;;; Pass 1.55 -- normalise `fields:` on a stage / join when the LLM wrote a single clause
+;;; instead of a sequential of clauses.
+;;;
+;;; The repr schema for both stage and join requires
+;;; `"fields": [:sequential [:ref ::clause]]` (joins additionally accept the enum strings
+;;; `"all"` / `"none"`). LLMs occasionally write a single clause as the value, e.g.
+;;;
+;;; stages:
+;;; - …
+;;; fields: [field, {}, [Sample, PUBLIC, T, COL]]
+;;;
+;;; rather than the canonical list-of-one
+;;;
+;;; stages:
+;;; - …
+;;; fields:
+;;; - [field, {}, [Sample, PUBLIC, T, COL]]
+;;;
+;;; The single-clause shape would otherwise fail validation. We detect it (a vector whose
+;;; slot 0 is a string head AND slot 1 is a map - i.e. clause-shaped) and wrap it in a
+;;; one-element list.
+;;;
+;;; Carried over from the sexp pipeline's \`normalize-with-fields-selection\` (see
+;;; `repr-deletion-followups.md` § 1.9). Idempotent: after wrapping, the value is
+;;; sequential-of-clause and the predicate no longer matches.
+;;; ============================================================
+
+(defn- single-clause-shape? [v]
+ (and (vector? v)
+ (>= (count v) 2)
+ (string? (nth v 0))
+ (map? (nth v 1))))
+
+(defn- normalise-fields-key [m]
+ (let [fields (get m "fields")]
+ (if (single-clause-shape? fields)
+ (assoc m "fields" [fields])
+ m)))
+
+(defn- normalise-fields-shape*
+ [form]
+ (walk/postwalk
+ (fn [node]
+ (if (and (map? node) (contains? node "fields"))
+ (normalise-fields-key node)
+ node))
+ form))
+
+;;; ============================================================
+;;; Pass 1.5 -- normalize `expressions:` shape (map -> sequential; stamp `lib/expression-name`)
+;;;
+;;; MBQL 5 requires `:expressions` to be a `[:sequential ...]` where each entry is an
+;;; expression clause carrying `:lib/expression-name` in its options map. LLMs naturally
+;;; want to write a map-shape `expressions: {Name: [op, {}, ...]}` (with the expression
+;;; name as the map key), which is far more readable. We accept both shapes here and
+;;; normalise to the canonical sequential form, stamping `lib/expression-name` into each
+;;; clause's options from the map key.
+;;;
+;;; If the author already wrote the sequential form, we leave the expression-name alone
+;;; (authoritative in options). If both a map key AND `lib/expression-name` exist and
+;;; disagree, the options-map wins (we don't overwrite authored metadata).
+;;; ============================================================
+
+(defn- expression-clause?
+ "An expression definition clause: a vector whose position-1 element is a map (options).
+ Anything else - a literal value, a non-vector, an empty vector - we leave alone and let
+ schema validation complain."
+ [x]
+ (and (vector? x)
+ (>= (count x) 2)
+ (map? (nth x 1))))
+
+(defn- stamp-expression-name
+ "If the clause doesn't already have `\"lib/expression-name\"` in its options, stamp the
+ given name. Otherwise leave the clause alone."
+ [clause expr-name]
+ (let [opts (nth clause 1)]
+ (if (contains? opts "lib/expression-name")
+ clause
+ (assoc clause 1 (assoc opts "lib/expression-name" expr-name)))))
+
+(defn- normalize-stage-expressions
+ [stage]
+ (let [exprs (get stage "expressions")]
+ (cond
+ ;; Map-shape: {Name clause, ...} -> [clause-with-name ...]
+ (map? exprs)
+ (assoc stage "expressions"
+ (into []
+ (keep (fn [[expr-name clause]]
+ (when (expression-clause? clause)
+ (stamp-expression-name clause expr-name))))
+ exprs))
+
+ ;; Sequential: leave as-is (name lives in each clause's options; schema enforces).
+ (sequential? exprs)
+ stage
+
+ ;; Missing or something we don't understand: leave alone.
+ :else
+ stage)))
+
+(defn- normalize-expressions-shape*
+ "Walk the query and, for every map that has an `\"expressions\"` key, convert a map-shape
+ expressions block into the canonical sequential shape with `lib/expression-name` stamped
+ from the map key. Idempotent: sequential input passes through unchanged."
+ [form]
+ (walk/postwalk
+ (fn [node]
+ (if (and (map? node) (contains? node "expressions"))
+ (normalize-stage-expressions node)
+ node))
+ form))
+
+;;; ============================================================
+;;; Pass 1.9 -- stamp top-level `database:` from the first stage
+;;;
+;;; Rationale: the `representations` spec mandates a top-level `database:` field on every
+;;; query (see `../representations/core-spec/v1/schemas/common/query.yaml`), but every
+;;; database-identifying piece of information is already available in the first stage's
+;;; `source-table:` (a portable FK `[db, schema, table]`) or `source-card:` (an entity_id
+;;; whose card carries a `database_id`). We remove `database:` from the LLM-facing tool
+;;; contract - one less thing for the model to get wrong, one less failure mode where the
+;;; top-level name disagrees with the FKs.
+;;;
+;;; To keep the downstream spec-compliant (lib.schema/Query, validate-query, etc.), this pass
+;;; stamps the top-level `database:` from the first stage. Sources of truth, in order:
+;;;
+;;; 1. `stages[0].source-table[0]` - the db-name component of the portable table FK.
+;;; 2. `stages[0].source-card` - entity_id; look up the card, read its `database_id`, then
+;;; the database's name via the metadata provider.
+;;;
+;;; **Silent overwrite on conflict.** If the LLM did author a `database:` field and it
+;;; disagrees with what we computed, we overwrite it. The first-stage source is more detailed
+;;; and is what the resolver actually uses; there's no reason to trust a dangling top-level
+;;; name over it.
+;;;
+;;; **No-op when we can't derive anything** (no source-table, and source-card lookup failed /
+;;; absent). The enclosing pipeline's `resolve-database-id-from-first-stage` already raised
+;;; before we got here in that case, but we guard here too for test isolation.
+;;; ============================================================
+
+(defn- db-name-from-source-table
+ "Pull the first element (db-name) out of `stages[0].source-table`, or nil."
+ [query]
+ (let [fk (get-in query ["stages" 0 "source-table"])]
+ (when (and (vector? fk) (>= (count fk) 1) (string? (nth fk 0)))
+ (nth fk 0))))
+
+(defn- db-name-from-mp
+ "Read the canonical database name off the metadata provider, or nil on failure."
+ [mp]
+ (when mp
+ (try
+ (:name (lib.metadata.protocols/database mp))
+ (catch Exception _ nil))))
+
+(defn- infer-top-level-database*
+ "Stamp (or overwrite) the top-level `database:` field on a parsed query.
+
+ Only applies to maps that look like a top-level query - those that have a `stages` key.
+ We intentionally do NOT stamp `database:` on arbitrary maps: the `repair` entry point is
+ sometimes exercised with a non-query input (shape-pass unit tests, plain data), and we
+ must preserve those inputs unchanged modulo the structural repairs.
+
+ Source of truth, in order:
+ 1. The metadata provider's database name - authoritative, since the MP was built from the
+ database-id resolved from the first stage. This is always correct when present.
+ 2. The raw `stages[0].source-table[0]` string - fallback for the `mp == nil` case (unit
+ tests of this pass in isolation).
+
+ **Silent overwrite on conflict.** If the LLM authored a `database:` field that disagrees
+ with the computed value, we overwrite it: the source is more detailed and is what the
+ resolver actually uses; a dangling top-level name has no independent authority."
+ [query mp]
+ (if-not (and (map? query) (contains? query "stages"))
+ query
+ (if-let [db-name (or (db-name-from-mp mp)
+ (db-name-from-source-table query))]
+ (assoc query "database" db-name)
+ query)))
+
+;;; ============================================================
+;;; Pass 2 -- fill in missing `lib/type` markers
+;;; ============================================================
+
+(defn- top-level-query-map?
+ [m]
+ (and (map? m)
+ (contains? m "database")
+ (contains? m "stages")))
+
+(defn- stage-like-map?
+ "A map that looks like an MBQL stage: has `\"source-table\"`, `\"source-card\"`, or any of the
+ stage-body keys (`filters`, `aggregation`, `breakout`, `order-by`, `fields`, `joins`,
+ `expressions`, `limit`). Not a top-level query."
+ [m]
+ (and (map? m)
+ (not (top-level-query-map? m))
+ (boolean
+ (some #(contains? m %)
+ ["source-table" "source-card" "filters" "aggregation"
+ "breakout" "order-by" "fields" "joins" "expressions" "limit"]))))
+
+(defn- infer-query-lib-type [m]
+ (if (and (top-level-query-map? m) (not (contains? m "lib/type")))
+ (assoc m "lib/type" "mbql/query")
+ m))
+
+(defn- infer-stage-lib-type [m]
+ (if (and (stage-like-map? m) (not (contains? m "lib/type")))
+ (assoc m "lib/type" "mbql.stage/mbql")
+ m))
+
+(defn- ensure-lib-types* [form]
+ (walk/postwalk
+ (fn [node]
+ (if (map? node)
+ (-> node infer-query-lib-type infer-stage-lib-type)
+ node))
+ form))
+
+;;; ============================================================
+;;; Pass 2.7 -- rewrite inline aggregation expressions in `order-by` to aggregation refs
+;;;
+;;; Background: when the user asks for something like "top categories by total revenue", the
+;;; LLM tends to write `order-by` by re-stating the aggregation expression inline:
+;;;
+;;; aggregation: [[sum, {}, [field, {}, [..., TOTAL]]]]
+;;; order-by: [[desc, {}, [sum, {}, [field, {}, [..., TOTAL]]]]] # <-- inline copy
+;;;
+;;; In MBQL 5 / legacy MBQL the `order-by` direction must wrap an aggregation **reference**,
+;;; not the aggregation expression itself. The `lib.normalize` step accepts the inline form
+;;; structurally, but `lib/->legacy-MBQL` produces a query that fails legacy-schema validation
+;;; the moment something downstream re-loads it (e.g. when the chart is opened, the QP
+;;; round-trips through legacy MBQL and explodes with `Invalid output: {:query {:order-by ...}}`).
+;;;
+;;; This pass detects the pattern, structurally matches each `order-by` inner clause against
+;;; the stage's `aggregation` list (ignoring options-map differences), and:
+;;; * stamps a UUID into the matching aggregation's options (if it doesn't already have one);
+;;; * replaces the inline `order-by` aggregation with `["aggregation" {} "<that-uuid>"]`.
+;;;
+;;; This does NOT introduce general placeholder-UUID handling (Phase 2 step 10 - `@agg-N`
+;;; references); we only resolve the very specific "order-by re-states the aggregation inline"
+;;; mistake. If the LLM writes a `["aggregation" {} "..."]` ref directly, we leave it alone.
+;;; ============================================================
+
+(defn- strip-clause-options
+ "Recursively remove the options map (slot at position 1) from every clause-like vector in
+ `form`. Used as a structural-equality key so we can match an inline `order-by` aggregation
+ against the stage's `aggregation` entry without being thrown off by `lib/uuid` differences
+ or unrelated option keys.
+
+ Walks via `postwalk` and uses the same `clause-like?` predicate as the options-insertion
+ pass, so map-entries, FK-paths, and non-clause vectors are left alone."
+ [form]
+ (walk/postwalk
+ (fn [node]
+ (if (and (vector? node)
+ (not (map-entry? node))
+ (clause-like? node)
+ (>= (count node) 2)
+ (map? (nth node 1)))
+ (into [(first node)] (subvec node 2))
+ node))
+ form))
+
+(defn- ensure-aggregation-uuid
+ "Return a tuple `[stamped-aggregation uuid]`. If the aggregation already has a `lib/uuid` in
+ its options, reuse it; otherwise generate one and assoc it in. Always returns the UUID for
+ use in the corresponding aggregation reference."
+ [aggregation]
+ (let [opts (when (and (vector? aggregation) (>= (count aggregation) 2) (map? (nth aggregation 1)))
+ (nth aggregation 1))
+ existing (get opts "lib/uuid")
+ uuid (or existing (str (random-uuid)))]
+ (if existing
+ [aggregation uuid]
+ [(assoc aggregation 1 (assoc (or opts {}) "lib/uuid" uuid)) uuid])))
+
+(defn- aggregation-ref-clause?
+ "True if `clause` is already an `[\"aggregation\" {opts} \"<uuid>\"]` reference. We never
+ rewrite these."
+ [clause]
+ (and (vector? clause)
+ (>= (count clause) 3)
+ (= "aggregation" (first clause))))
+
+(defn- order-by-direction-clause?
+ "True if `clause` is `[\"asc\" {} <inner>]` or `[\"desc\" {} <inner>]`."
+ [clause]
+ (and (vector? clause)
+ (>= (count clause) 3)
+ (contains? #{"asc" "desc"} (first clause))))
+
+(defn- rewrite-order-by-inline-aggs-in-stage
+ "Apply the inline-agg-in-`order-by` rewrite to a single string-keyed stage map. Returns the
+ updated stage. No-op when the stage has no `order-by` or no `aggregation`."
+ [stage]
+ (let [aggs (get stage "aggregation")
+ ord (get stage "order-by")]
+ (if-not (and (vector? aggs) (seq aggs) (vector? ord) (seq ord))
+ stage
+ ;; Build a structural-key → index lookup over the aggregations once.
+ (let [agg-key->idx (into {}
+ (map-indexed (fn [i a] [(strip-clause-options a) i]))
+ aggs)
+ ;; Mutable-style accumulators: walk order-by, simultaneously collecting any
+ ;; aggregations that need a UUID stamped in.
+ *aggs* (atom aggs)
+ new-ord
+ (mapv
+ (fn [direction-clause]
+ (if-not (order-by-direction-clause? direction-clause)
+ direction-clause
+ (let [inner (nth direction-clause 2)]
+ (cond
+ ;; Already an aggregation ref - leave it alone.
+ (aggregation-ref-clause? inner)
+ direction-clause
+
+ ;; Inline aggregation that matches one of the stage's aggregations.
+ (and (vector? inner)
+ (contains? agg-key->idx (strip-clause-options inner)))
+ (let [idx (get agg-key->idx (strip-clause-options inner))
+ [stamped uuid] (ensure-aggregation-uuid (nth @*aggs* idx))]
+ (swap! *aggs* assoc idx stamped)
+ (assoc direction-clause 2 ["aggregation" {} uuid]))
+
+ :else
+ direction-clause))))
+ ord)]
+ (assoc stage "aggregation" @*aggs* "order-by" new-ord)))))
+
+(defn- rewrite-order-by-inline-aggs*
+ "Top-level pass for inline-aggregation-in-order-by repair. Walks every stage in the query
+ (not just `stages[0]`) since the same mistake can appear in multi-stage queries."
+ [query]
+ (if-not (and (map? query) (vector? (get query "stages")))
+ query
+ (update query "stages" #(mapv rewrite-order-by-inline-aggs-in-stage %))))
+
+;;; ============================================================
+;;; Pass 2.8 -- resolve integer-index aggregation references to UUID form
+;;;
+;;; LLM-authored queries commonly use a 0-based integer index to refer to an aggregation
+;;; from the same stage: `[aggregation, {}, 0]` means "the first aggregation in this stage".
+;;; This mirrors legacy MBQL 4 prior art (`[:aggregation 0]`, see `legacy_mbql/schema.cljc`)
+;;; and is far easier for the model to produce than a UUID-based ref.
+;;;
+;;; MBQL 5's canonical form is `[aggregation, {lib/uuid, base-type, effective-type, …},
+;;; "<uuid-string>"]` where the string in slot 2 is the `:lib/uuid` of the target
+;;; aggregation clause in the same stage. This pass walks each stage, builds an
+;;; index→uuid map over the stage's `aggregation:` vector (stamping a UUID on each agg
+;;; clause that lacks one), then rewrites every `[aggregation, opts, <int>]` clause to the
+;;; canonical form with `base-type`/`effective-type` inferred from the aggregation head.
+;;;
+;;; Same-stage refs only. Cross-stage aggregation references (a stage-N+1 `:aggregation`
+;;; ref pointing at a stage-N aggregation) are **out of scope** for this pass - pMBQL
+;;; actually forbids that shape; the correct downstream form is a cross-stage field ref by
+;;; the aggregation's column name, which Pass 4 handles once the column name is known.
+;;; An out-of-range or no-aggregations stage raises an `:agent-error?` ex-info with a
+;;; helpful message listing the available indices/heads.
+;;; ============================================================
+
+(defn- integer-index-agg-ref?
+ "True if `clause` is `[\"aggregation\", <opts>, <non-negative-int>]`."
+ [clause]
+ (and (vector? clause)
+ (= 3 (count clause))
+ (= "aggregation" (nth clause 0))
+ (map? (nth clause 1))
+ (let [idx (nth clause 2)]
+ (and (integer? idx) (not (neg? idx))))))
+
+(defn- inner-clause-field-base-type
+ "Best-effort inner-field type extraction for `sum`/`min`/`max` etc. Looks for a nested
+ `[\"field\" {\"base-type\" T, …} …]` clause; returns nil if none found."
+ [agg-clause]
+ (when (and (vector? agg-clause) (>= (count agg-clause) 3))
+ (let [inner (nth agg-clause 2)]
+ (when (and (vector? inner)
+ (>= (count inner) 2)
+ (= "field" (nth inner 0))
+ (map? (nth inner 1)))
+ (get (nth inner 1) "base-type")))))
+
+(defn- infer-agg-base-type
+ "Return the string base-type for an aggregation clause. Small, intentionally inexact
+ lookup table keyed by clause head - this is a shape pass, not a resolver. Return values
+ are the string forms expected in the portable repair output.
+
+ Heads whose output type tracks an inner field (`sum`, `min`, `max`, etc) try to pull the
+ inner field's authored `base-type`; fall through to `type/*` if unknown."
+ [agg-clause]
+ (let [head (when (and (vector? agg-clause) (>= (count agg-clause) 1))
+ (nth agg-clause 0))]
+ (case head
+ ("count" "distinct" "cum-count" "count-where") "type/BigInteger"
+ ("avg" "median" "stddev" "var" "share") "type/Float"
+ ("sum" "sum-where" "cum-sum" "min" "max")
+ (or (inner-clause-field-base-type agg-clause) "type/Float")
+ "type/*")))
+
+(defn- ensure-aggregation-uuids
+ "Walk the stage's aggregation vector, stamping `lib/uuid` into each clause's options map
+ when missing. Returns `[stamped-aggs index->uuid]` where `index->uuid` is a vector aligned
+ with the aggregation vector."
+ [aggs]
+ (reduce
+ (fn [[acc-aggs acc-uuids] agg]
+ (let [[stamped uuid] (ensure-aggregation-uuid agg)]
+ [(conj acc-aggs stamped) (conj acc-uuids uuid)]))
+ [[] []]
+ aggs))
+
+(defn- agg-heads-summary
+ "Return a short human-readable summary like `[sum at 0, count at 1]` for error messages."
+ [aggs]
+ (str "["
+ (str/join ", "
+ (map-indexed (fn [i a]
+ (let [head (when (and (vector? a) (>= (count a) 1))
+ (nth a 0))]
+ (str head " at " i)))
+ aggs))
+ "]"))
+
+(defn- rewrite-integer-agg-refs-in-tree
+ "Postwalk `tree` replacing every integer-index aggregation ref with its canonical
+ UUID-keyed form. Uses `index->uuid` / `index->type` (both vectors aligned with the
+ stage's aggregation vector) for the rewrite. Throws agent-error ex-info on out-of-range.
+
+ Does NOT descend into the stage's own `aggregation:` vector; that's handled by the
+ caller (we don't want to rewrite a stray integer that legitimately means \"the number 0\"
+ inside an aggregation's args)."
+ [tree index->uuid index->type aggs-for-error]
+ (walk/postwalk
+ (fn [node]
+ (if (integer-index-agg-ref? node)
+ (let [[_ opts idx] node]
+ (if-let [uuid (get index->uuid idx)]
+ (let [inferred-type (get index->type idx)
+ new-opts (cond-> opts
+ (and inferred-type (not (contains? opts "base-type")))
+ (assoc "base-type" inferred-type)
+ (and inferred-type (not (contains? opts "effective-type")))
+ (assoc "effective-type" inferred-type))]
+ ["aggregation" new-opts uuid])
+ (throw (ex-info (tru "Aggregation index {0} out of range; stage has {1} aggregation(s): {2}"
+ idx (count index->uuid) (agg-heads-summary aggs-for-error))
+ {:agent-error? true
+ :error :aggregation-ref-out-of-range
+ :index idx
+ :available (count index->uuid)
+ :heads (mapv (fn [a] (when (vector? a) (first a))) aggs-for-error)}))))
+ node))
+ tree))
+
+(defn- stage-has-integer-agg-ref?
+ "Does `stage` contain any `[aggregation, {}, <int>]` clause anywhere? Used to decide
+ whether to complain about a missing `aggregation:` vector (if there are no integer refs
+ and no `aggregation:` block, it's a perfectly valid stage)."
+ [stage]
+ (let [found? (atom false)]
+ (walk/postwalk
+ (fn [n]
+ (when (integer-index-agg-ref? n) (reset! found? true))
+ n)
+ (dissoc stage "aggregation"))
+ @found?))
+
+(defn- resolve-integer-agg-refs-in-stage
+ "Resolve all integer-index aggregation refs in a single stage to canonical UUID form.
+ No-op when the stage has neither `aggregation:` nor any integer-indexed refs."
+ [stage]
+ (let [aggs (get stage "aggregation")]
+ (cond
+ ;; No integer refs anywhere in the stage - nothing to do.
+ (not (stage-has-integer-agg-ref? stage))
+ stage
+
+ ;; Integer ref(s) present but stage has no aggregation vector - agent-error.
+ (not (and (vector? aggs) (seq aggs)))
+ (throw (ex-info (tru "Found an integer-indexed aggregation reference but this stage has no `aggregation:` clause")
+ {:agent-error? true
+ :error :aggregation-ref-no-aggregations}))
+
+ :else
+ (let [[stamped-aggs index->uuid] (ensure-aggregation-uuids aggs)
+ index->type (mapv infer-agg-base-type stamped-aggs)
+ ;; Walk everything EXCEPT the `aggregation:` vector itself. We replace that
+ ;; vector with a sentinel during the walk and restore it after. (Simpler than
+ ;; implementing a custom non-descending walker.)
+ stage-wo-aggs (assoc stage "aggregation" ::placeholder)
+ rewritten (rewrite-integer-agg-refs-in-tree
+ stage-wo-aggs index->uuid index->type stamped-aggs)]
+ (assoc rewritten "aggregation" stamped-aggs)))))
+
+(defn- resolve-aggregation-ref-indexes*
+ "Top-level pass: resolve 0-based integer `[aggregation, {}, <idx>]` references to the
+ canonical MBQL 5 `[aggregation, {lib/uuid, base-type, effective-type}, \"<uuid>\"]`
+ shape. See block comment above."
+ [query]
+ (if-not (and (map? query) (vector? (get query "stages")))
+ query
+ (let [stages (get query "stages")]
+ (log/debugf "[repr-repair] resolve-aggregation-ref-indexes*: %d stage(s)" (count stages))
+ (assoc query "stages" (mapv resolve-integer-agg-refs-in-stage stages)))))
+
+;;; ============================================================
+;;; Pass 2.9 -- auto-split a stage that uses a same-stage aggregation reference inside a
+;;; `filters:` clause (post-aggregation / HAVING-style filter) into two stages.
+;;;
+;;; lib's canonical shape forbids `[aggregation, {}, <uuid>]` to appear inside a stage's
+;;; `filters:` (or `breakout:`, `expressions:`) - that's a HAVING-clause situation in SQL
+;;; terms, and in pMBQL it must be expressed as a *second stage* whose `filters:` reference
+;;; the aggregation's output column by name. lib's schema is shape-only and does not catch
+;;; this; the broken query goes through validate, resolve, and only fails at SQL-generation
+;;; time (or, worse, silently produces wrong results). LLMs habitually write the single-
+;;; stage shape because that's the SQL idiom (`HAVING count(*) > 10`).
+;;;
+;;; Carried over from the sexp pipeline's stage-boundary inference (see
+;;; `repr-deletion-followups.md` § 1.11).
+;;;
+;;; Detection
+;;; =========
+;;; For each stage S whose `aggregation:` is non-empty, build the set of `lib/uuid`s of S's
+;;; aggregations. Walk every entry of `S.filters` looking for any
+;;; `[aggregation, opts, <uuid>]` clause whose uuid is in that set. If found, the stage is
+;;; "post-agg-filter-broken".
+;;;
+;;; Auto-fix
+;;; ========
+;;; Derive the output column-name for each aggregation (static lib-mirroring table, plus
+;;; `"name"` opts override). If any aggregation's name can't be derived (custom heads,
+;;; `metric` ref needing the metadata-provider, etc.), throw `:agent-error?` with a clear
+;;; message - the LLM retry will then either avoid the pattern or refactor to multi-stage
+;;; explicitly.
+;;;
+;;; When all names are derivable, split S into [S0, S1]:
+;;;
+;;; * S0 keeps: source-*, joins, aggregation, breakout, expressions, and any pre-agg
+;;; filters (those that do NOT reference a same-stage agg-ref).
+;;; * S1 (new, no source-table) takes:
+;;; - the offending filters, with `[aggregation, {}, <uuid>]` rewritten to
+;;; `[field, {}, "<column-name>"]` (cross-stage ref);
+;;; - the original `order-by:` (if any), with the same rewrite applied;
+;;; - the original `limit:`;
+;;; - the original `fields:` (if any).
+;;;
+;;; Why move order-by + limit + fields? The user's intent is "of {rows matching the filter},
+;;; the top-N sorted by X, projecting columns Y". Leaving order-by/limit/fields in S0 would
+;;; sort/limit/project *before* the filter, producing a different (smaller) row set and the
+;;; wrong semantics. They semantically belong on the post-filter view.
+;;;
+;;; Pre-agg filters (those NOT referencing agg-ref) STAY in S0 so they can do row
+;;; filtering before aggregation as the LLM intended.
+;;;
+;;; Idempotency
+;;; ===========
+;;; After the split, S0 has no `[aggregation, {}, <uuid>]` ref in its filters and S1 has no
+;;; aggregation: vector at all. Re-running the pass finds no triggering shape and is a
+;;; no-op.
+;;;
+;;; This pass runs AFTER `resolve-aggregation-ref-indexes*` (so integer-index refs are
+;;; already in UUID form) and BEFORE `infer-cross-stage-field-types*` (so the new
+;;; cross-stage `field` refs we synthesise get their `base-type` / `effective-type` filled
+;;; in by Pass 5).
+;;; ============================================================
+
+(def ^:private aggregation-column-name-table
+ "Lib-mirroring static table: aggregation head → the output column name lib's
+ `column-name-method` produces. Covers all the heads we expect from LLM-authored queries
+ in the absence of an explicit `name` override. `metric` is intentionally NOT in this
+ table - resolving its column name needs the metadata-provider, and the auto-split caller
+ emits a clean diagnostic when it can't derive a name."
+ {"count" "count"
+ "cum-count" "count"
+ "distinct" "count"
+ "count-where" "count_where"
+ "distinct-where" "count_where"
+ "avg" "avg"
+ "max" "max"
+ "median" "median"
+ "min" "min"
+ "stddev" "stddev"
+ "sum" "sum"
+ "var" "var"
+ "cum-sum" "sum"
+ "percentile" "percentile"})
+
+(defn- aggregation-clause-column-name
+ "Derive the output column-name an aggregation will produce, mirroring lib's
+ `column-name-method`. An explicit `\"name\"` in opts (lib's column-name override) takes
+ precedence. Returns `nil` when we can't determine the name (e.g. `metric` head, custom
+ head not in the table); the caller treats that as \"please diagnose, don't auto-fix\"."
+ [agg]
+ (when (and (vector? agg) (>= (count agg) 2))
+ (or (let [n (get (nth agg 1) "name")]
+ (when (and (string? n) (not= n "")) n))
+ (get aggregation-column-name-table (nth agg 0)))))
+
+(defn- collect-stage-agg-uuids
+ "Set of `lib/uuid` strings on the aggregation clauses of `stage`. Aggregations without a
+ uuid (shouldn't happen post-Pass-2.7/2.8 but guard anyway) contribute nothing."
+ [stage]
+ (into #{}
+ (keep (fn [agg]
+ (when (and (vector? agg) (>= (count agg) 2) (map? (nth agg 1)))
+ (let [u (get (nth agg 1) "lib/uuid")]
+ (when (string? u) u)))))
+ (get stage "aggregation")))
+
+(defn- form-references-stage-agg?
+ "True if `form` contains any `[aggregation, opts, <uuid>]` clause whose uuid is in
+ `same-stage-uuids`."
+ [form same-stage-uuids]
+ (let [found? (atom false)]
+ (walk/postwalk
+ (fn [n]
+ (when (and (vector? n)
+ (>= (count n) 3)
+ (= "aggregation" (nth n 0))
+ (string? (nth n 2))
+ (contains? same-stage-uuids (nth n 2)))
+ (reset! found? true))
+ n)
+ form)
+ @found?))
+
+(defn- aggregation-uuid->column-name
+ "Build a `{uuid → column-name}` map for the stage's aggregation vector. Returns `nil` when
+ auto-split isn't safe — the caller emits the `:post-agg-filter-needs-multi-stage`
+ diagnostic and the LLM must author two stages explicitly.
+
+ Two unsafe conditions:
+
+ * Any aggregation fails to produce a column name (e.g. a `metric` head whose name needs
+ the metadata provider, or a custom head not in the static table).
+
+ * Two aggregations produce the **same** output column name. lib would dedupe these via
+ `unique-name-generator` (`sum` / `sum_2` / …) which depends on field order; our static
+ table can't replicate that without recreating the generator. Picking either name in
+ the cross-stage `[\"field\" {} <name>]` rewrite would silently filter against the
+ wrong column."
+ [aggs]
+ (let [m (reduce
+ (fn [acc agg]
+ (let [uuid (get-in agg [1 "lib/uuid"])]
+ (if (and (string? uuid) (not= uuid ""))
+ (if-let [col-name (aggregation-clause-column-name agg)]
+ (assoc acc uuid col-name)
+ (reduced nil))
+ acc)))
+ {}
+ aggs)]
+ (when (and m (= (count m) (count (set (vals m)))))
+ m)))
+
+(defn- rewrite-agg-refs-to-cross-stage-fields
+ "Postwalk: replace every `[aggregation, opts, <uuid>]` clause whose uuid is in
+ `uuid->col-name` with the canonical cross-stage `[field, {}, <col-name>]` shape.
+ Aggregation-specific opts (`base-type`, `effective-type`, `lib/uuid`) are intentionally
+ dropped - downstream Pass 5 (`infer-cross-stage-field-types*`) will re-stamp the field's
+ types based on metadata."
+ [form uuid->col-name]
+ (walk/postwalk
+ (fn [n]
+ (if (and (vector? n)
+ (= 3 (count n))
+ (= "aggregation" (nth n 0))
+ (map? (nth n 1))
+ (string? (nth n 2))
+ (contains? uuid->col-name (nth n 2)))
+ ["field" {} (get uuid->col-name (nth n 2))]
+ n))
+ form))
+
+(defn- split-post-agg-filter-stage
+ "Detect post-agg-filter shape in `stage`. Return `[stage]` if no split is needed, or
+ `[stage' new-stage]` if the stage was split. Throws `:agent-error?` ex-info when split is
+ required but unsafe to perform automatically.
+
+ Auto-fix is intentionally narrow: it moves the offending filter(s) into a second stage and
+ rewrites their agg-refs to cross-stage `[\"field\" {} \"<col-name>\"]` clauses. It does
+ NOT move `order-by` / `limit` / `fields` — those frequently reference pre-aggregation
+ columns that don't survive the split, and silently relocating them produces either a
+ hard-to-diagnose 'no matching field' error or, worse, a different-row-count query. When
+ any of those keys is present we refuse and ask the LLM to author two stages explicitly."
+ [stage]
+ (let [aggs (get stage "aggregation")
+ same-stage-uuids (collect-stage-agg-uuids stage)]
+ (if-not (and (vector? aggs) (seq aggs) (seq same-stage-uuids))
+ [stage]
+ (let [filters (get stage "filters")
+ offending-filter? (fn [f] (form-references-stage-agg? f same-stage-uuids))
+ offending-filters (when (vector? filters) (filterv offending-filter? filters))]
+ (cond
+ (empty? offending-filters)
+ [stage]
+
+ (or (seq (get stage "order-by"))
+ (some? (get stage "limit"))
+ (seq (get stage "fields")))
+ (throw (ex-info
+ (tru "Detected a post-aggregation filter alongside `order-by:`, `limit:`, or `fields:` in the same stage. pMBQL requires the filter in a separate stage, but those trailing clauses cannot be safely relocated — they may reference pre-aggregation columns that don''t survive the split. Please author this as two stages explicitly: stage 0 with `source-table`, `aggregation`, `breakout`, and any pre-aggregation `filters`; stage 1 with the post-aggregation `filters`, plus `order-by` / `limit` / `fields` that reference the aggregation''s output via cross-stage `[\"field\", (empty opts), \"<column-name>\"]` refs.")
+ {:agent-error? true
+ :error :post-agg-filter-with-trailing-clauses
+ :stage stage}))
+
+ :else
+ (if-let [uuid->col (aggregation-uuid->column-name aggs)]
+ (let [keep-filters (vec (remove offending-filter? filters))
+ rewrite #(rewrite-agg-refs-to-cross-stage-fields % uuid->col)
+ moved-filters (mapv rewrite offending-filters)
+ s0 (cond-> stage
+ true (assoc "filters" keep-filters)
+ (empty? keep-filters) (dissoc "filters"))
+ s1 {"lib/type" "mbql.stage/mbql"
+ "filters" moved-filters}]
+ [s0 s1])
+ (throw (ex-info
+ (tru "Detected a post-aggregation filter (a filter referencing an aggregation from the same stage). pMBQL requires this in a separate stage. Auto-fix is unsafe here — either an aggregation''s output column name cannot be derived (e.g. a `metric` reference or unknown head), or two aggregations in this stage would produce the same column name (e.g. two `sum` aggregations on different fields, which lib disambiguates as `sum` / `sum_2` based on field order). Please refactor to multi-stage manually: put the aggregations in stage 0, and the filter in stage 1 referencing the column via a cross-stage `[\"field\", (empty opts), \"<column-name>\"]` clause. Use an explicit aggregation with a `name` opts override (e.g. `[\"sum\", (opts with key \"name\" → \"sum_total\"), …]`) if you need stable cross-stage names.")
+ {:agent-error? true
+ :error :post-agg-filter-needs-multi-stage
+ :stage stage}))))))))
+
+(defn- split-post-agg-filters*
+ "Top-level pass: walk every stage in the query, expanding any post-agg-filter stage
+ in-place to `[stage0 stage1]`. Re-runs are no-ops (idempotent: split stages no longer
+ match the trigger)."
+ [query]
+ (if-not (and (map? query) (vector? (get query "stages")))
+ query
+ (update query "stages" #(into [] (mapcat split-post-agg-filter-stage) %))))
+
+;;; ============================================================
+;;; Pass 3 -- auto-wire `source-field` for implicit joins
+;;;
+;;; When a field clause references a field on a table *other* than the stage's
+;;; `source-table`, and there is exactly one foreign key from the source table to that target
+;;; table, fill in the `source-field` option with the portable FK of the FK column. The QP
+;;; interprets this as an implicit join (the same machinery users get from the notebook UI).
+;;;
+;;; The pass walks stage[0] only, skips descent into the `\"joins\"` subtree (field clauses
+;;; inside a join live in a join context), and is a no-op on clauses that already carry any
+;;; of the disambiguating opts: `source-field`, `source-field-name`, `source-field-join-alias`,
+;;; or `join-alias`. The latter three are LLM-authored variants we do *not* auto-fill:
+;;; correctly filling them in would require resolving a previous-stage's returned-columns or
+;;; an explicit-join's FK shape, neither of which is in scope for this pass.
+;;; ============================================================
+
+(defn- field-clause?
+ "A repaired field clause of shape `[\"field\" <opts-map> <portable-fk-vector>]`. We require the
+ opts map to be a real map and the portable FK to be a vector of >= 4 elements (DB, SCHEMA,
+ TABLE, FIELD, …)."
+ [v]
+ (and (vector? v)
+ (not (map-entry? v))
+ (>= (count v) 3)
+ (= "field" (nth v 0))
+ (map? (nth v 1))
+ (let [fk (nth v 2)]
+ (and (vector? fk) (>= (count fk) 4)))))
+
+(defn- try-resolve-source-table-id
+ "Resolve the stage's `source-table` portable FK to a numeric id. Returns nil on any failure
+ (unknown DB, unknown table, nil source-table, wrong shape, etc.) - implicit-join repair is
+ best-effort and should never mask an error that the downstream validate/resolve passes will
+ surface with a better message."
+ [import-resolver source-table-fk]
+ (try
+ (when (and import-resolver (vector? source-table-fk) (= 3 (count source-table-fk)))
+ (resolve/import-table-fk import-resolver source-table-fk))
+ (catch Exception _ nil)))
+
+(defn- try-resolve-field-target-table-id
+ "Resolve the target-table-id of a portable field FK, by looking up the field and following its
+ `:table-id`. Walks JSON-unfolded parent chains via the resolver's `import-field-fk`. Returns
+ nil on failure."
+ [mp import-resolver field-fk]
+ (try
+ (when-let [fid (resolve/import-field-fk import-resolver field-fk)]
+ (:table-id (lib.metadata.protocols/field mp fid)))
+ (catch Exception _ nil)))
+
+(defn- export-source-field-portable
+ "Convert a numeric FK column id into its portable `[db schema table field …]` path, via the
+ MP-backed export resolver. Returns nil on failure."
+ [export-resolver source-field-id]
+ (try
+ (resolve/export-field-fk export-resolver source-field-id)
+ (catch Exception _ nil)))
+
+(defn- display-source-table [mp source-table-id]
+ (try
+ (let [t (lib.metadata.protocols/table mp source-table-id)]
+ (or (:name t) (str source-table-id)))
+ (catch Exception _ (str source-table-id))))
+
+(defn- display-portable [fk]
+ (pr-str fk))
+
+(defn- maybe-fill-source-field
+ "Given a field-clause vector (already known to be a field clause), the stage's source-table-id,
+ and the precomputed outbound-FK map, return either the original clause or a clause with
+ `\"source-field\"` populated. Throws `:no-fk-path` or `:ambiguous-fk` on hard errors."
+ [clause mp import-resolver export-resolver source-table-id outbound-fks-by-target]
+ (let [opts (nth clause 1)
+ fk (nth clause 2)]
+ (cond
+ ;; Already disambiguated by the LLM. We leave any clause that carries one of the
+ ;; implicit-/explicit-join disambiguators alone:
+ ;; * `source-field` — implicit join with FK column from the *source-table* (handled
+ ;; downstream by the resolver); we don't try to second-guess the LLM here.
+ ;; * `source-field-name` — implicit join from a *previous stage*'s output column
+ ;; (multi-stage); the FK column is referenced by name, not portable FK path.
+ ;; * `source-field-join-alias` — implicit join where the FK-bearing column lives on
+ ;; an *explicitly joined* table; the alias picks which copy of the FK to use.
+ ;; * `join-alias` — the field itself comes from an explicit join.
+ (or (contains? opts "source-field")
+ (contains? opts "source-field-name")
+ (contains? opts "source-field-join-alias")
+ (contains? opts "join-alias"))
+ clause
+
+ :else
+ (let [target-table-id (try-resolve-field-target-table-id mp import-resolver fk)]
+ (cond
+ ;; Couldn't resolve target table: skip (validate/resolve will surface the real error).
+ (nil? target-table-id)
+ clause
+
+ ;; Field is on the source table itself: nothing to do.
+ (= target-table-id source-table-id)
+ clause
+
+ :else
+ (let [candidates (get outbound-fks-by-target target-table-id)]
+ (case (count candidates)
+ 0 (let [src-name (display-source-table mp source-table-id)
+ tbl-name (nth fk 2)]
+ (throw (ex-info (tru "Field {0} is on table {1} but there is no foreign key from the source table {2} to {3}. Either add an explicit joins: entry, or use a field from the source table."
+ (display-portable fk)
+ (pr-str tbl-name)
+ (pr-str src-name)
+ (pr-str tbl-name))
+ {:status-code 400
+ :error :no-fk-path
+ :agent-error? true
+ :field fk
+ :source-table source-table-id
+ :target-table target-table-id})))
+ 1 (let [{:keys [source-field-id]} (first candidates)
+ src-fk (export-source-field-portable export-resolver source-field-id)]
+ (if src-fk
+ (assoc clause 1 (assoc opts "source-field" src-fk))
+ clause))
+ ;; Deliberately do NOT enumerate the candidate FK columns: the metadata provider
+ ;; is un-sandboxed and any leaked `[db schema table field]` path could surface
+ ;; bridge-table column names the caller is not permitted to see (`:agent-error?`
+ ;; relays the message verbatim to the user). The LLM can recover by calling
+ ;; `entity_details` on the source table to inspect available foreign-key columns.
+ (let [src-name (display-source-table mp source-table-id)]
+ (throw (ex-info (tru "Field {0} can be reached from {1} via {2} foreign keys. Specify the `source-field` option on the field clause to disambiguate; call `entity_details` on the source table to list the available foreign-key columns."
+ (display-portable fk)
+ (pr-str src-name)
+ (count candidates))
+ {:status-code 400
+ :error :ambiguous-fk
+ :agent-error? true
+ :field fk
+ :source-table source-table-id
+ :target-table target-table-id}))))))))))
+
+(defn- resolve-implicit-joins-in-stage
+ "Apply implicit-join repair to a single stage map (string-keyed). Returns an updated stage.
+
+ Skips descent into the `\"joins\"` subtree by plucking it out before the postwalk and
+ restoring it afterwards - field clauses inside explicit joins are expected to carry a
+ `join-alias` already."
+ [stage mp import-resolver export-resolver]
+ (let [source-table-fk (get stage "source-table")
+ source-table-id (try-resolve-source-table-id import-resolver source-table-fk)]
+ (if-not source-table-id
+ ;; Can't resolve source-table: skip the pass and let validate/resolve surface the error.
+ stage
+ (let [outbound (resolve.mp/outbound-fks-from-table mp source-table-id)
+ by-target (group-by :target-table-id outbound)
+ joins (get stage "joins")
+ stage' (cond-> stage (contains? stage "joins") (dissoc "joins"))
+ walked (walk/postwalk
+ (fn [node]
+ (if (field-clause? node)
+ (maybe-fill-source-field node mp import-resolver export-resolver
+ source-table-id by-target)
+ node))
+ stage')]
+ (cond-> walked
+ (contains? stage "joins") (assoc "joins" joins))))))
+
+(defn- resolve-implicit-joins*
+ "Top-level implicit-join pass. Only `stages[0]` participates: implicit-join `source-field`
+ inference is a relationship from a stage's `source-table` to a sibling table via a single FK,
+ and only the first stage of a query has a `source-table` of its own. Stages 1+ feed off the
+ previous stage's output, where field references are by string name (handled by
+ [[infer-cross-stage-field-types*]] further down)."
+ [query mp content-store]
+ (if-not (and mp (map? query) (vector? (get query "stages")) (seq (get query "stages")))
+ query
+ (let [import-resolver (resolve.mp/import-resolver mp content-store)
+ export-resolver (resolve.mp/export-resolver mp)]
+ (update-in query ["stages" 0] resolve-implicit-joins-in-stage
+ mp import-resolver export-resolver))))
+
+;;; ============================================================
+;;; Pass 3.5 -- auto-wire `source-field-join-alias` for implicit joins through an explicitly
+;;; joined table.
+;;;
+;;; Trigger: a field clause `["field" {opts} <portable-fk>]` whose target table is reachable
+;;; from **exactly one** explicit join's source table via **exactly one** FK, and which the
+;;; basic implicit-join pass (Pass 4) cannot handle (target not reachable from `source-table`,
+;;; or LLM clearly intended to hop through the join).
+;;;
+;;; This is the moral equivalent of Pass 4 but the FK-bearing column lives on a joined table
+;;; rather than on `source-table`. We refuse to second-guess any clause that already carries
+;;; one of `source-field` / `source-field-name` / `source-field-join-alias` / `join-alias`.
+;;;
+;;; Conservative on purpose - per `repr-deletion-followups.md`, repair is opt-in: we fill in
+;;; the unambiguous cases and bail loudly on ambiguity rather than guessing. The companion
+;;; multi-stage `source-field-name` repair is *not* implemented here (it would require
+;;; resolving a previous-stage's returned-columns from inside repair, which is structurally
+;;; awkward and prone to silent corruption); see `repr-deletion-followups.md` for the
+;;; deferred-with-rationale entry.
+;;;
+;;; Like Pass 4: walks `stages[0]` only, skips descent into the `\"joins\"` subtree (those
+;;; field clauses already need `join-alias`), no-op when source-table or any join's
+;;; source-table can't be resolved.
+;;; ============================================================
+
+(defn- explicit-join-source-tables
+ "For each entry in a stage's `\"joins\"` vector, return
+ `[{:alias <string>, :source-table-id <int>} …]`. Skips joins without a usable alias or whose
+ `source-table` portable FK can't be resolved - they don't participate in repair, but the
+ resolver will surface the structural error itself."
+ [import-resolver joins]
+ (vec (for [j joins
+ :let [a (get j "alias")
+ stf (get-in j ["stages" 0 "source-table"])
+ tid (try-resolve-source-table-id import-resolver stf)]
+ :when (and (string? a) (seq a) tid)]
+ {:alias a :source-table-id tid})))
+
+(defn- candidates-via-explicit-join
+ "Find every `(join-alias, source-field-id)` pair through which `target-table-id` is reachable
+ from one of the explicit joins on the stage. Returns a vector (possibly empty) of
+ `{:alias <string>, :source-field-id <int>}`.
+
+ An entry is included iff the joined table has **exactly one** outbound FK to
+ `target-table-id`. Multiple FKs from the same joined table are intentionally NOT collapsed
+ into a single candidate - we can't tell which one the LLM meant, so we leave that join out
+ of the candidate list (it'll either be unambiguous through some *other* join or fail loud
+ below)."
+ [mp joined-tables target-table-id]
+ (vec (for [{:keys [alias source-table-id]} joined-tables
+ :let [outbound (resolve.mp/outbound-fks-from-table mp source-table-id)
+ matching (filter #(= target-table-id (:target-table-id %)) outbound)]
+ :when (= 1 (count matching))]
+ {:alias alias
+ :source-field-id (:source-field-id (first matching))})))
+
+(defn- maybe-fill-source-field-join-alias
+ "Given a field clause known to lack all four disambiguators, the resolved source-table-id of
+ the stage, the resolved joined-table list, and the FK map for the stage's own source-table,
+ decide whether to fill in `source-field-join-alias` (and the accompanying portable
+ `source-field`).
+
+ We only intervene when the basic implicit-join (Pass 4) would NOT handle the clause,
+ i.e. the target is not the source-table itself and not reachable through `source-table`'s
+ outbound FKs. Otherwise we leave the clause for Pass 4 - which has clearer error messages
+ and is the canonical path for the common case.
+
+ Throws `:ambiguous-fk-via-join` (an `:agent-error?`) when the target is reachable from
+ multiple distinct join aliases. Returns the (possibly-augmented) clause otherwise."
+ [clause mp import-resolver export-resolver source-table-id outbound-from-source-by-target joined-tables]
+ (let [opts (nth clause 1)
+ fk (nth clause 2)]
+ (if (or (contains? opts "source-field")
+ (contains? opts "source-field-name")
+ (contains? opts "source-field-join-alias")
+ (contains? opts "join-alias"))
+ clause
+ (let [target-table-id (try-resolve-field-target-table-id mp import-resolver fk)]
+ (cond
+ (nil? target-table-id) clause
+ (= target-table-id source-table-id) clause
+ ;; Pass 4 can handle this one - leave it alone.
+ (seq (get outbound-from-source-by-target target-table-id)) clause
+
+ :else
+ (let [cands (candidates-via-explicit-join mp joined-tables target-table-id)]
+ (case (count cands)
+ ;; No explicit join provides a single-FK route either - let Pass 4 raise its
+ ;; own `:no-fk-path` error with its current wording.
+ 0 clause
+ 1 (let [{:keys [alias source-field-id]} (first cands)
+ src-fk (export-source-field-portable export-resolver source-field-id)]
+ (if src-fk
+ (assoc clause 1 (assoc opts
+ "source-field" src-fk
+ "source-field-join-alias" alias))
+ clause))
+ ;; Alias names came from the LLM's own input (the `joins:` block it authored),
+ ;; so listing them in the diagnostic is fine. The FK column portables are NOT
+ ;; surfaced here — see the rationale on `:ambiguous-fk` above.
+ (let [aliases (mapv :alias cands)]
+ (throw (ex-info (tru "Field {0} is reachable from {1} explicit joins via aliases {2}. Specify the `source-field-join-alias` option on the field clause to pick which join''s foreign key to use."
+ (display-portable fk)
+ (count cands)
+ (str/join ", " (map pr-str aliases)))
+ {:status-code 400
+ :error :ambiguous-fk-via-join
+ :agent-error? true
+ :field fk
+ :target-table target-table-id
+ :aliases aliases}))))))))))
+
+(defn- resolve-source-field-join-alias-in-stage
+ [stage mp import-resolver export-resolver]
+ (let [source-table-fk (get stage "source-table")
+ source-table-id (try-resolve-source-table-id import-resolver source-table-fk)
+ joins (get stage "joins")]
+ (if-not (and source-table-id (vector? joins) (seq joins))
+ stage
+ (let [outbound (resolve.mp/outbound-fks-from-table mp source-table-id)
+ outbound-by-target (group-by :target-table-id outbound)
+ joined-tables (explicit-join-source-tables import-resolver joins)
+ ;; As in Pass 4, do not descend into `joins:` subtree - clauses inside an explicit
+ ;; join carry `join-alias` and have their own resolution context.
+ stage' (dissoc stage "joins")
+ walked (walk/postwalk
+ (fn [node]
+ (if (field-clause? node)
+ (maybe-fill-source-field-join-alias
+ node mp import-resolver export-resolver
+ source-table-id outbound-by-target joined-tables)
+ node))
+ stage')]
+ (assoc walked "joins" joins)))))
+
+(defn- resolve-source-field-join-alias*
+ "Top-level pass: fill in `source-field-join-alias` (+ accompanying `source-field`) on
+ `stages[0]` field clauses whose target is reachable through exactly one explicit join. See
+ the section header above for the full contract.
+
+ Runs *before* [[resolve-implicit-joins*]] so that any clause it augments is already
+ disambiguated by the time Pass 4 sees it (Pass 4 leaves clauses with any of the four
+ disambiguators alone). Best-effort: any failure to resolve `source-table` or a joined
+ table's `source-table` simply skips the pass."
+ [query mp content-store]
+ (if-not (and mp (map? query) (vector? (get query "stages")) (seq (get query "stages")))
+ query
+ (let [import-resolver (resolve.mp/import-resolver mp content-store)
+ export-resolver (resolve.mp/export-resolver mp)]
+ (update-in query ["stages" 0] resolve-source-field-join-alias-in-stage
+ mp import-resolver export-resolver))))
+
+;;; ============================================================
+;;; Pass 4 -- infer base-type / effective-type on cross-stage field references
+;;;
+;;; A cross-stage field reference looks like `["field" {opts} "<column-name>"]` where the
+;;; third element is a **string** (the column's name in the previous stage's output) rather
+;;; than a portable FK vector. The lib-schema for `:mbql.clause/field` requires the options
+;;; map to carry `:base-type` whenever the id-or-name argument is a string - and LLMs
+;;; routinely forget this, even though they're great at picking the right column name.
+;;;
+;;; Strategy:
+;;; * Walk stages left-to-right.
+;;; * Before processing stage `i` (i ≥ 1), build a mini-query consisting of stages[0..i-1]
+;;; and resolve it. Call `lib/returned-columns` on the result; index by `:name`.
+;;; * Walk stage[i] (skipping descent into `joins` subtrees - those have their own
+;;; resolution context). For every `["field" opts <string>]` clause:
+;;; - If `opts` already has `"base-type"`, leave it alone (idempotent).
+;;; - If the name is unknown to the previous stage, leave it alone (the resolver will
+;;; report the real error with a better message).
+;;; - Otherwise, stamp `"base-type"` (and `"effective-type"` when present) into the
+;;; options map.
+;;; * If the prefix can't be resolved (bad source-table, etc.), skip the rest of the pass
+;;; - again, the resolver will surface the structural problem.
+;;;
+;;; The mini-resolve is potentially O(N) over stages, but in practice N ≤ a handful, the MP
+;;; is cached, and we only do this for queries that actually have multiple stages.
+;;; ============================================================
+
+(defn- string-cross-stage-field-clause?
+ "`[\"field\" <opts-map> <string>]` - a cross-stage column reference by name. We require
+ the opts map to be a real map and the third element to be a non-blank string. Anything else
+ (FK vector, missing slot, non-map opts) is left to [[field-clause?]] / the resolver."
+ [v]
+ (and (vector? v)
+ (not (map-entry? v))
+ (= 3 (count v))
+ (= "field" (nth v 0))
+ (map? (nth v 1))
+ (non-blank-string? (nth v 2))))
+
+(defn- types-from-column
+ "Pull `\"base-type\"` (and optionally `\"effective-type\"`) off a `lib/returned-columns`
+ metadata map, in the string-keyed form that matches the rest of the repair pipeline.
+ Returns `nil` if the column has no `:base-type` we can use."
+ [col]
+ (when-let [bt (:base-type col)]
+ (let [bt-str (if (keyword? bt) (subs (str bt) 1) (str bt))]
+ (cond-> {"base-type" bt-str}
+ (:effective-type col)
+ (assoc "effective-type" (let [et (:effective-type col)]
+ (if (keyword? et) (subs (str et) 1) (str et))))))))
+
+(defn- mini-resolved-columns-by-name
+ "Resolve `stages[0..idx-1]` as a self-contained query, run it through `lib/query`, and return
+ a `{column-name → {\"base-type\" ..., \"effective-type\" ...}}` map for the columns the
+ prefix returns.
+
+ Returns `nil` (logged at debug) if anything in the resolve / lib/query path throws. The
+ enclosing pass treats `nil` as 'skip this stage's repairs and let downstream surface the real
+ error'."
+ [mp query stage-idx content-store]
+ (try
+ (let [prefix-stages (subvec (get query "stages") 0 stage-idx)
+ prefix-query (assoc query "stages" prefix-stages)
+ resolved (repr.resolve/resolve-query mp prefix-query content-store)
+ lib-q (lib/query mp resolved)
+ cols (lib/returned-columns lib-q)]
+ (into {}
+ (keep (fn [col]
+ (when-let [types (types-from-column col)]
+ [(:name col) types])))
+ cols))
+ (catch Exception e
+ (log/debugf e "[repr-repair] mini-resolve of stages[0..%d] failed; skipping cross-stage type inference for stage %d"
+ (dec stage-idx) stage-idx)
+ nil)))
+
+(defn- maybe-fill-cross-stage-types
+ "Given a cross-stage field clause and a name→types map, return the clause with `base-type`
+ / `effective-type` filled in (when missing and known)."
+ [clause name->types]
+ (let [opts (nth clause 1)
+ col-name (nth clause 2)]
+ (if (contains? opts "base-type")
+ clause
+ (if-let [types (get name->types col-name)]
+ (assoc clause 1 (merge opts types))
+ clause))))
+
+(defn- infer-cross-stage-field-types-in-stage
+ "Walk one stage and stamp inferred types into every string-named field reference that lacks
+ `\"base-type\"`. Skips descent into `\"joins\"` subtrees - join stages have their own
+ resolution context (the join's own `stages`) and shouldn't reach into their parent stage's
+ previous-stage columns."
+ [stage name->types]
+ (let [joins (get stage "joins")
+ stage' (cond-> stage (contains? stage "joins") (dissoc "joins"))
+ walked (walk/postwalk
+ (fn [node]
+ (if (string-cross-stage-field-clause? node)
+ (maybe-fill-cross-stage-types node name->types)
+ node))
+ stage')]
+ (cond-> walked
+ (contains? stage "joins") (assoc "joins" joins))))
+
+(defn- mini-resolved-columns-for-source-card
+ "Resolve a single-stage query consisting only of `{:source-card <entity-id>}` (plus the
+ outer `mbql/query` wrapper and the warehouse database name), then return the
+ `lib/returned-columns` output as a `name → types` map in the same shape as
+ [[mini-resolved-columns-by-name]]. Used by [[infer-source-card-field-types*]] to stamp
+ `base-type` onto `[field, {}, \"<col>\"]` clauses in a stage whose source is a saved
+ question / model.
+
+ Returns `nil` if anything in the resolve path throws - the resolver will surface the real
+ error on the main pipeline. Logged at debug."
+ [mp query stage-idx content-store]
+ (let [stage (get-in query ["stages" stage-idx])]
+ (when-let [source-card (get stage "source-card")]
+ (try
+ (let [bare-stage {"lib/type" "mbql.stage/mbql"
+ "source-card" source-card}
+ bare-query {"lib/type" "mbql/query"
+ "database" (get query "database")
+ "stages" [bare-stage]}
+ resolved (repr.resolve/resolve-query mp bare-query content-store)
+ lib-q (lib/query mp resolved)
+ cols (lib/returned-columns lib-q)]
+ (into {}
+ (keep (fn [col]
+ (when-let [types (types-from-column col)]
+ [(:name col) types])))
+ cols))
+ (catch Exception e
+ (log/debugf e "[repr-repair] source-card resolve of stage %d failed; skipping field-type inference"
+ stage-idx)
+ nil)))))
+
+(defn- infer-source-card-field-types*
+ "Stamp `base-type` / `effective-type` onto `[field, opts, \"<col>\"]` clauses in any stage
+ whose source is a `source-card:` entity. Uses the card's resolved `returned-columns` as the
+ type oracle.
+
+ Idempotent and silently no-ops when `mp` is nil, the query shape is off, the card can't be
+ resolved, or the column name isn't one the card produces (resolver will report the real
+ error downstream)."
+ [query mp content-store]
+ (if-not (and mp (map? query) (vector? (get query "stages")))
+ query
+ (let [n (count (get query "stages"))]
+ (loop [i 0
+ q query]
+ (if (>= i n)
+ q
+ (let [stage (get-in q ["stages" i])
+ q' (if (and (map? stage) (get stage "source-card"))
+ (if-let [name->types (mini-resolved-columns-for-source-card mp q i content-store)]
+ (update-in q ["stages" i] infer-cross-stage-field-types-in-stage name->types)
+ q)
+ q)]
+ (recur (inc i) q')))))))
+
+(defn- infer-cross-stage-field-types*
+ "Top-level cross-stage field-type inference pass. No-op when the query has fewer than two
+ stages or `mp` is nil."
+ [query mp content-store]
+ (if-not (and mp
+ (map? query)
+ (vector? (get query "stages"))
+ (>= (count (get query "stages")) 2))
+ query
+ (let [n (count (get query "stages"))]
+ (loop [i 1
+ q query]
+ (if (>= i n)
+ q
+ (let [name->types (mini-resolved-columns-by-name mp q i content-store)
+ q' (if name->types
+ (update-in q ["stages" i] infer-cross-stage-field-types-in-stage name->types)
+ q)]
+ (recur (inc i) q')))))))
+
+;;; ============================================================
+;;; Pass 6 -- friendly error messages for silently-accepted-but-wrong shapes.
+;;;
+;;; lib's schema is intentionally shape-only and does not catch a number of patterns where
+;;; the LLM clearly meant something else. Without a friendly diagnostic the broken query
+;;; goes through validate, resolve, and only fails at SQL-generation time (or, worse,
+;;; silently produces wrong results). Each detector below targets a *specific* pattern
+;;; observed in production / sexp-pipeline telemetry and throws an `:agent-error?` ex-info
+;;; with an LLM-actionable explanation.
+;;;
+;;; Carried over from the sexp pipeline's `validate/operators.clj` and
+;;; `validate/cross_checks.clj` (see `repr-deletion-followups.md` § 2.3) plus a few new
+;;; "silent failure" cases discovered while reviewing repr behaviour.
+;;;
+;;; This pass runs LAST in `repair`, after every shape pass and every mp-aware fill-in,
+;;; so that we don't false-positive on shapes that are about to be repaired by an earlier
+;;; pass.
+;;; ============================================================
+
+;;; ----- E1: `[field, …]` as an entry in a stage's `aggregation:` block ---------------
+
+(defn- aggregation-entry-not-aggregation-error!
+ "Detect a top-level `[field, …]` clause directly inside a stage's `aggregation:` vector.
+ An aggregation entry must be an actual aggregation function (`count`, `sum`, `avg`,
+ `metric`, …) or wrap a field in one (`[sum, opts, <field>]`). Lib accepts the
+ field-as-aggregation shape silently and the QP produces wrong-result SQL.
+
+ Throws `:agent-error?` ex-info on the *first* offending entry, naming the stage and
+ entry index so the LLM can fix it precisely. Does NOT recurse into nested clauses
+ (`[sum, {}, [field, …]]` is correct - the outer `sum` is the aggregation; the inner
+ `field` is its argument)."
+ [stage stage-idx]
+ (when-let [aggs (get stage "aggregation")]
+ (when (vector? aggs)
+ (doseq [[entry-idx entry] (map-indexed vector aggs)]
+ (when (and (vector? entry)
+ (>= (count entry) 1)
+ (= "field" (nth entry 0)))
+ (throw (ex-info
+ (tru "Stage {0} aggregation entry {1} is a `field` clause, not an aggregation. The `aggregation:` block expects aggregation functions like `count`, `sum`, `avg`, `metric`, etc. - or wrap the field in one (e.g. `[sum, <opts>, <field>]`). If you wanted to group by this column, use `breakout:` instead."
+ stage-idx entry-idx)
+ {:agent-error? true
+ :error :aggregation-entry-not-aggregation
+ :stage-index stage-idx
+ :entry-index entry-idx
+ :entry entry})))))))
+
+;;; ----- E2: `case` / `if` with `"default"` in opts ------------------------------------
+
+(defn- case-default-in-opts-error!
+ "Detect a `case` / `if` clause whose options map carries a `\"default\"` key. lib's
+ canonical shape uses the *third positional argument* as the fallback, e.g.
+
+ [case, {}, [[pred1 then1] [pred2 then2]], default-value]
+
+ Some LLMs (especially those primed by JSON-Schema-style examples) put `default` into the
+ options map instead. lib silently ignores the unknown opts key and the case clause
+ evaluates to `null` for any branch miss - a wrong-result class of bug.
+
+ Throws `:agent-error?` ex-info on the first offender. Carried over from the sexp
+ pipeline's `validate/operators.clj/validate-operator-specific!` `case` branch."
+ [form]
+ (walk/postwalk
+ (fn [node]
+ (when (and (vector? node)
+ (not (map-entry? node))
+ (>= (count node) 2)
+ (string? (nth node 0))
+ (contains? #{"case" "if"} (nth node 0))
+ (map? (nth node 1))
+ (contains? (nth node 1) "default"))
+ (throw (ex-info
+ (tru "`case` (and `if`) uses its third positional argument as the fallback value, not a `default` key in the options map. Move the value out of the options map and append it as the third arg of the clause: `[case, <opts>, <branch-pairs>, <default>]`. Omit the third arg entirely if you have no fallback (the result will be null on miss).")
+ {:agent-error? true
+ :error :case-default-in-opts
+ :clause node})))
+ node)
+ form))
+
+;;; ----- E3: sexp-legacy top-level operations used as clause heads ---------------------
+
+(def ^:private sexp-legacy-top-level-ops
+ "Heads from the deleted sexp pipeline that used to be top-level *operations* (“verbs” at
+ the program level), not nestable clauses. LLMs trained on the sexp era still occasionally
+ emit these as clause heads. They have no equivalent in repr (which uses stage-level
+ blocks: `aggregation:`, `filters:`, `breakout:`, `order-by:`, `expressions:`, `limit:`,
+ `joins:`).
+
+ Map from offending head to a one-liner suggesting the canonical replacement."
+ {"aggregate" "In repr, aggregations live directly inside a stage's `aggregation:` block (no `aggregate` wrapper). Move the inner clauses into the stage's `aggregation: […]` vector."
+ "filter" "In repr, filters live directly inside a stage's `filters:` block. Move the inner clauses into the stage's `filters: […]` vector."
+ "order-by" "In repr, ordering lives directly inside a stage's `order-by:` block as `[asc|desc, <opts>, <ref>]` clauses. Move the inner clauses into the stage's `order-by: […]` vector."
+ "breakout" "In repr, breakouts (group-by) live directly inside a stage's `breakout:` block. Move the inner clauses into the stage's `breakout: […]` vector."
+ "limit" "In repr, the row limit is a scalar at the stage level: `limit: <n>`, not a clause."})
+
+(defn- sexp-legacy-op-as-clause-error!
+ "Detect any sexp-era top-level operation used as a clause head (`[aggregate, …]`,
+ `[filter, …]`, etc.). lib accepts these silently because they look like generic
+ unknown-but-shape-valid clauses; the resulting query produces wrong results or fails
+ at SQL-generation time. Carried over from the sexp pipeline's
+ `validate/operators.clj` `top-level-operation` branch.
+
+ Excludes `map-entry?` nodes - postwalk descends into map entries, and a stage's
+ `{\"breakout\" […]}` entry would otherwise look exactly like a `[\"breakout\", …]`
+ clause to this detector."
+ [form]
+ (walk/postwalk
+ (fn [node]
+ (when (and (vector? node)
+ (not (map-entry? node))
+ (>= (count node) 1)
+ (string? (nth node 0))
+ (contains? sexp-legacy-top-level-ops (nth node 0)))
+ (let [head (nth node 0)
+ hint (get sexp-legacy-top-level-ops head)]
+ (throw (ex-info
+ (tru "`{0}` is not a clause in repr; it was a top-level operation in the older sexp pipeline. {1}"
+ head hint)
+ {:agent-error? true
+ :error :sexp-legacy-op-as-clause
+ :head head
+ :clause node}))))
+ node)
+ form))
+
+;;; ----- E5: blank `[expression, opts, ""]` reference --------------------------------
+
+(defn- blank-expression-ref-error!
+ "Detect any `[expression, <opts>, <name>]` reference whose name slot is missing,
+ blank, or non-string. lib's schema requires a non-blank string identifier here
+ (matching an entry in some upstream stage's `expressions:` block); without it the
+ reference resolves to nothing and the query produces wrong results or fails downstream.
+
+ Carried over from the sexp pipeline's
+ `validate/operators.clj/validate-operator-specific!` `expression-ref` branch."
+ [form]
+ (walk/postwalk
+ (fn [node]
+ (when (and (vector? node)
+ (not (map-entry? node))
+ (= 3 (count node))
+ (= "expression" (nth node 0))
+ (map? (nth node 1)))
+ (let [name-slot (nth node 2)]
+ (when (or (not (string? name-slot))
+ (= "" (str/trim (str name-slot))))
+ (throw (ex-info
+ (tru "`[expression, <opts>, <name>]` reference requires a non-blank string identifier in the third slot, matching an entry in some stage''s `expressions:` block.")
+ {:agent-error? true
+ :error :blank-expression-ref
+ :clause node})))))
+ node)
+ form))
+
+;;; ----- E6: numeric `[field, opts, 100]` (sexp legacy form) -------------------------
+
+(defn- numeric-field-id-error!
+ "Detect any `[field, <opts>, <id>]` clause whose third slot is an integer (the sexp /
+ legacy-MBQL numeric field-id form). repr requires a portable FK in the third slot:
+ either a vector `[<db>, <schema>, <table>, <column>]` (resolved against the metadata
+ provider) OR a string column name (cross-stage reference). lib's schema rejects bare
+ numeric ids, but the error is a generic shape mismatch; this detector gives an
+ LLM-actionable explanation pointing at the portable-FK syntax.
+
+ Carried over from the sexp pipeline's
+ `validate/operators.clj/validate-operator-specific!` `field` branch."
+ [form]
+ (walk/postwalk
+ (fn [node]
+ (when (and (vector? node)
+ (not (map-entry? node))
+ (= 3 (count node))
+ (= "field" (nth node 0))
+ (map? (nth node 1))
+ (integer? (nth node 2)))
+ (throw (ex-info
+ (tru "`field` clause needs a portable FK in its third slot, not a numeric id. Use a vector `[<database>, <schema>, <table>, <column>]` (resolved against the metadata provider) or a string column-name (for cross-stage references).")
+ {:agent-error? true
+ :error :numeric-field-id
+ :clause node})))
+ node)
+ form))
+
+;;; ----- friendly-errors pipeline driver -----------------------------------------------
+
+(defn- friendly-errors*
+ "Run every diagnostic detector in turn. Throws on the first match; otherwise returns
+ `query` unchanged."
+ [query]
+ (when (and (map? query) (vector? (get query "stages")))
+ (doseq [[idx stage] (map-indexed vector (get query "stages"))]
+ (when (map? stage)
+ (aggregation-entry-not-aggregation-error! stage idx)))
+ (case-default-in-opts-error! query)
+ (sexp-legacy-op-as-clause-error! query)
+ (blank-expression-ref-error! query)
+ (numeric-field-id-error! query))
+ query)
+
+;;; ============================================================
+;;; Top-level entry point
+;;; ============================================================
+
+(defn- normalize-shape*
+ "Pure-shape passes that don't require a metadata provider."
+ [parsed]
+ (-> parsed
+ ;; Run before Pass 1 (`ensure-clause-options*`): a values-list like
+ ;; `["alice" "bob"]` looks like a bare clause to Pass 1, which would corrupt it.
+ normalise-list-value-comparisons*
+ ensure-clause-options*
+ unwrap-boolean-wrappers*
+ unwrap-nested-field-clauses*
+ rewrite-operator-name-aliases*
+ rewrite-temporal-bucket-aliases*
+ rewrite-direction-aliases*
+ wrap-iso-date-bounds*
+ wrap-now-literals*
+ swap-between-bounds*
+ normalise-case-clauses*
+ normalise-fields-shape*
+ normalize-expressions-shape*
+ ensure-lib-types*))
+
+(defn- stamp-top-level-database*
+ "Idempotent wrapper around [[infer-top-level-database*]] that takes `[query mp]` in the
+ arg order matching the other mp-taking passes below."
+ [query mp]
+ (infer-top-level-database* query mp))
+
+(defn repair
+ "Run the repair pipeline on a parsed (string-keyed, portable) representations query.
+
+ Passes:
+ 1. ensure every clause vector has an options map at position 2;
+ 1.5. normalise `expressions:` shape - accept map form `{Name: clause, …}` or the
+ canonical sequential form, always output sequential with `lib/expression-name`
+ stamped into each clause's options from the map key when missing;
+ 2. fill in missing `\"lib/type\"` markers on the query and stages;
+ 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);
+ 3.5. resolve 0-based integer aggregation references (`[aggregation, {}, <int>]`) in a
+ stage to the canonical UUID-keyed MBQL 5 form, stamping `lib/uuid` on the target
+ aggregation clause and `base-type`/`effective-type` on the ref's options;
+ 3.7. auto-wire `source-field-join-alias` (and the accompanying portable `source-field`)
+ on field clauses whose target table is reachable through **exactly one** explicit
+ join on the stage via a single unambiguous FK on the joined table. Skips clauses
+ that already carry any of `source-field` / `source-field-name` /
+ `source-field-join-alias` / `join-alias`. Raises `:ambiguous-fk-via-join` (an
+ `:agent-error?`) when the target is reachable from multiple distinct join aliases.
+ Runs *before* the basic implicit-join pass so the latter sees an already-
+ disambiguated clause.
+ 4. auto-wire `source-field` on field clauses that reference a foreign table via a single
+ unambiguous FK on the source table (implicit-join resolution);
+ 5. infer `base-type` / `effective-type` on cross-stage field references
+ (`[\"field\" {} \"<column-name>\"]` in a non-first stage), by mini-resolving the
+ prefix of stages and reading the returned columns' metadata.
+ 5.5. infer `base-type` / `effective-type` on field references in a stage whose source is
+ a saved question / model (`source-card:`), using the card's resolved returned columns.
+
+ Pass 4, Pass 5, and Pass 5.5 require `mp` (a `MetadataProvider`); they are best-effort
+ no-ops when `mp` can't resolve the relevant pieces (so the subsequent validate/resolve
+ stages can surface the real error with their own, better messages). Hard FK errors from
+ Pass 4 (`:no-fk-path`, `:ambiguous-fk`) are raised as `:agent-error?` ex-info so the tool
+ wrapper can relay them to the LLM. Pass 5 and Pass 5.5 never throw on their own - if a
+ prefix / source-card can't be resolved, they just leave the affected clauses alone and let
+ the schema validator complain.
+
+ Note: the database-name normalisation pass (\"Pass 2.5\") that previously lived here was
+ removed in `repr-plan.md` step 13, and the top-level `database:` field was removed from
+ the LLM-facing contract in the step-14 follow-up. Database identity is now derived from
+ the first stage's `source-table:` / `source-card:` (see
+ [[metabase.metabot.tools.construct/resolve-database-id-from-first-stage]]), and Pass 1.9
+ stamps `database:` from the MP into the parsed query so the downstream resolver and lib
+ schema see a spec-compliant document.
+
+ Guaranteed to be **idempotent**: `(= (repair mp q) (repair mp (repair mp q)))`. Pass 3
+ satisfies idempotency by stamping a deterministic-once UUID into the matching aggregation
+ (subsequent runs reuse it) and by leaving existing `[\"aggregation\" {} \"<uuid>\"]` refs
+ alone. Pass 5 is idempotent because it skips any cross-stage clause whose options already
+ contain `\"base-type\"`.
+
+ The optional `content-store` is threaded into mini-resolve passes that touch saved cards;
+ agent callers pass a permission-aware store so source-card/metric metadata is not read via
+ the default app-DB resolver."
+ ([mp parsed]
+ (repair mp parsed resolve.mp/unchecked-app-db-content-store))
+ ([mp parsed content-store]
+ (-> parsed
+ normalize-shape*
+ (stamp-top-level-database* mp)
+ rewrite-order-by-inline-aggs*
+ resolve-aggregation-ref-indexes*
+ split-post-agg-filters*
+ (resolve-source-field-join-alias* mp content-store)
+ (resolve-implicit-joins* mp content-store)
+ (infer-cross-stage-field-types* mp content-store)
+ (infer-source-card-field-types* mp content-store)
+ friendly-errors*)))
diff --git a/src/metabase/agent_lib/representations/resolve.clj b/src/metabase/agent_lib/representations/resolve.clj
new file mode 100644
index 00000000000..63da176a167
--- /dev/null
+++ b/src/metabase/agent_lib/representations/resolve.clj
@@ -0,0 +1,161 @@
+(ns metabase.agent-lib.representations.resolve
+ "Resolve a parsed (string-keyed, portable) representations query into canonical numeric-ID
+ pMBQL.
+
+ Pipeline:
+
+ 1. **keywordize** string keys on the representations query. The repair pass operates on
+ string-keyed data (LLM-authored markers like `\"lib/type\"`, `\"source-table\"`,
+ `\"temporal-unit\"` flow through as strings); lib-level MBQL expects keywords. We walk the
+ structure once to keywordize map keys but leave string *values* — clause heads, option
+ values like `\"month\"`, etc. — for [[lib.normalize]] to convert.
+
+ 2. **resolve portable FKs → numeric IDs** via `metabase.models.serialization.resolve/import-mbql`,
+ bound to a metadata-provider-backed resolver. Clause heads like `\"field\"` are converted
+ to `:field` keywords by `import-mbql` itself (per the `#{:field \"field\"}` match pattern),
+ so by the end of this step the MBQL form has numeric ids and keywordized heads.
+
+ 3. **normalize** through `lib.normalize/normalize` against `:metabase.lib.schema/query`. This:
+ * adds `:lib/uuid` to every clause;
+ * keywordizes known enum values (temporal units, base-types, join strategies);
+ * kebab-cases keys where applicable;
+ * attaches the metadata-provider at `:lib/metadata` so the result is a \"real\" pMBQL that
+ can be handed to `lib.query` / the QP directly.
+
+ The output is a valid MBQL 5 query ready for the query processor.
+
+ The inverse direction — final pMBQL back to portable form — is handled by [[export-query]];
+ the result is a Clojure map matching the external (keyword-keyed) shape, ready for JSON
+ encoding or for handing back to the LLM as the canonical MBQL 5 representation."
+ (:require
+ [metabase.lib.normalize :as lib.normalize]
+ [metabase.lib.schema :as lib.schema]
+ [metabase.models.serialization.resolve :as resolve]
+ [metabase.models.serialization.resolve.mp :as resolve.mp]
+ [metabase.util.log :as log]))
+
+(set! *warn-on-reflection* true)
+
+;;; ============================================================
+;;; Step 1 - keywordize map keys
+;;; ============================================================
+
+(defn- keywordize-keys*
+ "Recursively convert string map keys to keywords. Preserves string *values* (e.g. clause heads,
+ temporal-unit strings, enum-valued option values) - those are handled by `import-mbql` /
+ `lib.normalize` downstream.
+
+ Special-cases: leaves table-FK and field-FK path vectors alone (vector-of-strings doesn't get\n recursed into beyond the normal `vector? → mapv` walk, which is a no-op on strings)."
+ [x]
+ (cond
+ (map? x) (persistent!
+ (reduce-kv (fn [acc k v]
+ (assoc! acc
+ (cond-> k (string? k) keyword)
+ (keywordize-keys* v)))
+ (transient {})
+ x))
+ (vector? x) (mapv keywordize-keys* x)
+ (sequential? x) (mapv keywordize-keys* x)
+ :else x))
+
+(defn keywordize-query
+ "Turn the portable string-keyed representations form into a keyword-keyed map suitable for
+ `import-mbql` / `lib.normalize`."
+ [parsed-repr]
+ (keywordize-keys* parsed-repr))
+
+;;; ============================================================
+;;; Step 2+3 - resolve FKs and normalize
+;;; ============================================================
+
+(defn resolve-query
+ "Convert a parsed (string-keyed, portable) representations query into a canonical, numeric-ID,
+ `:lib/uuid`-stamped MBQL 5 query attached to `metadata-provider`.
+
+ The optional `content-store` is used for Metabase-content lookups (source cards, metrics,
+ etc.). Agent-facing callers should pass a permission-aware store; the 2-arity form keeps the
+ default app-DB-backed resolver for non-HTTP/test callers.
+
+ Throws with informative ex-info on missing / ambiguous FK lookups (via the resolver) or on
+ lib.schema normalization failures."
+ ([metadata-provider parsed-repr]
+ (resolve-query metadata-provider parsed-repr resolve.mp/unchecked-app-db-content-store))
+ ([metadata-provider parsed-repr content-store]
+ (let [kw-form (keywordize-query parsed-repr)
+ resolver (resolve.mp/import-resolver metadata-provider content-store)
+ resolved (resolve/import-mbql resolver kw-form)
+ with-mp (assoc resolved :lib/metadata metadata-provider)]
+ (lib.normalize/normalize ::lib.schema/query with-mp))))
+
+;;; ============================================================
+;;; Export final pMBQL back to portable representations
+;;; ============================================================
+
+(defn- keyword->repr-string
+ "Stringify a keyword preserving its namespace, e.g. `:lib/type` → `\"lib/type\"`."
+ [k]
+ (if-let [ns (namespace k)]
+ (str ns "/" (name k))
+ (name k)))
+
+(defn- portable-repr-form
+ "Convert the keyworded portable form returned by serdes export into the LLM-facing
+ representations form: string keys, string clause heads / enum values, no internal metadata
+ provider handle."
+ [x]
+ (cond
+ (map? x)
+ (reduce-kv
+ (fn [m k v]
+ (if (= k :lib/metadata)
+ m
+ (assoc m
+ (cond-> k (keyword? k) keyword->repr-string)
+ (portable-repr-form v))))
+ (empty x)
+ x)
+
+ (vector? x) (mapv portable-repr-form x)
+ (sequential? x) (mapv portable-repr-form x)
+ (keyword? x) (keyword->repr-string x)
+ :else x))
+
+(defn export-query
+ "Convert a final normalized numeric-ID pMBQL query back to portable representations data.
+
+ This is the inverse of [[resolve-query]] for the agent/tool output path: table/field/card IDs
+ are exported to portable FK paths / entity_ids, lib's normalized keyworded form is converted
+ back to the string-keyed portable representation, and internal `:lib/metadata` is dropped.
+
+ The optional `content-store` is used for Metabase-content lookups (Card / Measure / Segment
+ by id) on the export side. Agent-facing callers should pass a permission-aware store —
+ typically `metabase.metabot.tools.shared.content-store/default-store` — so that
+ entity_ids of referenced cards / measures / segments do not leak through the export to a
+ user who can't read them. The 2-arity form keeps the default app-DB-backed unchecked
+ resolver for non-HTTP / test callers."
+ ([metadata-provider pmbql-query]
+ (export-query metadata-provider pmbql-query resolve.mp/unchecked-app-db-content-store))
+ ([metadata-provider pmbql-query content-store]
+ (let [resolver (resolve.mp/export-resolver metadata-provider content-store)]
+ (->> pmbql-query
+ (resolve/export-mbql resolver)
+ portable-repr-form))))
+
+(defn try-export-query
+ "Best-effort wrapper around [[export-query]] that returns `nil` instead of throwing when the
+ export pipeline fails or `pmbql-query` is nil/blank. Used in LLM context-building paths where
+ an unusual or partially-broken existing `dataset_query` should gracefully drop out of the
+ payload rather than break the whole tool response.
+
+ Like [[export-query]], the 3-arity form accepts an explicit `content-store`; agent callers
+ pass `metabase.metabot.tools.shared.content-store/default-store` for read-checking."
+ ([metadata-provider pmbql-query]
+ (try-export-query metadata-provider pmbql-query resolve.mp/unchecked-app-db-content-store))
+ ([metadata-provider pmbql-query content-store]
+ (when (and metadata-provider (map? pmbql-query) (seq pmbql-query))
+ (try
+ (export-query metadata-provider pmbql-query content-store)
+ (catch Exception e
+ (log/warn e "Failed to export pMBQL query to portable representations; omitting from LLM payload")
+ nil)))))
diff --git a/src/metabase/agent_lib/runtime.clj b/src/metabase/agent_lib/runtime.clj
deleted file mode 100644
index fd7ae195916..00000000000
--- a/src/metabase/agent_lib/runtime.clj
+++ /dev/null
@@ -1,104 +0,0 @@
-(ns metabase.agent-lib.runtime
- "Trusted MBQL helper runtime for structured MBQL program evaluation."
- (:require
- [metabase.agent-lib.capabilities :as capabilities]
- [metabase.agent-lib.mbql-integration :as mbql]
- [metabase.agent-lib.runtime.bindings :as runtime.bindings]
- [metabase.agent-lib.runtime.fields :as runtime.fields]
- [metabase.agent-lib.syntax :as syntax]
- [metabase.lib.core :as lib]
- [metabase.lib.metadata :as lib.metadata]))
-
-;; Ensure all defmethod registrations are loaded.
-(comment lib/keep-me)
-
-(set! *warn-on-reflection* true)
-
-(def ^:private extra-helper-bindings
- {;; Query-introspection helpers exposed through the shared runtime.
- 'suggested-join-conditions lib/suggested-join-conditions
- 'joinable-columns lib/join-fieldable-columns
- 'joins lib/joins
- 'visible-columns lib/visible-columns
- 'filterable-columns lib/filterable-columns
- 'breakoutable-columns lib/breakoutable-columns
- 'aggregable-columns lib/aggregable-columns
- 'orderable-columns lib/orderable-columns
- 'expressionable-columns lib/expressionable-columns
-
- ;; Query-dependent refs are wired at runtime build time.
- 'aggregation-ref nil})
-
-(def trusted-helper-bindings
- "Trusted structured helper implementations keyed by operator symbol."
- (merge capabilities/trusted-helper-bindings
- extra-helper-bindings))
-
-(def query-transform-symbols
- "Top-level structured query-transform operator symbols."
- capabilities/query-transform-symbols)
-
-(def helper-symbols
- "All helper symbols accepted by the structured runtime."
- (into capabilities/helper-symbols
- (keys extra-helper-bindings)))
-(defn op-symbol
- "Normalize helper identifiers into canonical operator symbols."
- [op]
- (syntax/op-symbol op))
-
-(defn- resolve-in-scope-table-ids
- "Default fallback when no in-scope table set is provided: load every table in the database.
- Used by tests and any code path that hasn't yet plumbed in a scoped runtime."
- [metadata-provider]
- (into #{} (map :id) (lib.metadata/tables metadata-provider)))
-
-(defn build-runtime
- "Build the trusted structured-program runtime for a metadata provider.
-
- Options:
- :in-scope-table-ids — set of table-ids the runtime should expose for name-based lookups
- and FK chain resolution. Defaults to every table in the database
- (used by tests and legacy callers); production should always pass
- the scoped set derived from the program references.
- :extra-bindings — additional runtime bindings merged on top of the standard ones."
- ([metadata-providerable]
- (build-runtime metadata-providerable nil))
- ([metadata-providerable {:keys [in-scope-table-ids extra-bindings]}]
- (let [metadata-provider (lib.metadata/->metadata-provider metadata-providerable)
- table-ids (or in-scope-table-ids
- (resolve-in-scope-table-ids metadata-provider))
- tables-by-name (runtime.fields/build-table-lookup metadata-provider table-ids)
- {:keys [fields-by-table fields-by-id]}
- (runtime.fields/build-field-lookups metadata-provider tables-by-name)
- bindings (merge (assoc trusted-helper-bindings
- 'expression-ref mbql/expression-ref-or-current-stage-column
- 'aggregation-ref mbql/aggregation-ref-or-current-stage-column
- 'skip-join? (fn [query operation]
- (mbql/redundant-implicit-join? fields-by-id query operation)))
- (runtime.bindings/make-context-bindings metadata-provider
- tables-by-name
- fields-by-table
- fields-by-id)
- extra-bindings)]
- {:metadata-provider metadata-provider
- :tables-by-name tables-by-name
- :fields-by-table fields-by-table
- :fields-by-id fields-by-id
- :bindings bindings})))
-
-(defn bindings-map
- "Return the runtime bindings map."
- [runtime]
- (:bindings runtime))
-
-(defn helper-fn
- "Look up a helper implementation from a runtime by operator.
- Throws when the binding is nil so callers get a clear error instead of an NPE."
- [runtime op]
- (let [sym (op-symbol op)
- f (get (:bindings runtime) sym)]
- (when-not f
- (throw (ex-info (str "No runtime binding for operator: " sym)
- {:operator sym})))
- f))
diff --git a/src/metabase/agent_lib/runtime/bindings.clj b/src/metabase/agent_lib/runtime/bindings.clj
deleted file mode 100644
index 83e9eb28898..00000000000
--- a/src/metabase/agent_lib/runtime/bindings.clj
+++ /dev/null
@@ -1,18 +0,0 @@
-(ns metabase.agent-lib.runtime.bindings
- "Context-dependent runtime bindings for structured MBQL evaluation."
- (:require
- [metabase.agent-lib.runtime.lookup :as runtime.lookup]
- [metabase.agent-lib.runtime.transforms :as runtime.transforms]
- [metabase.lib.core :as lib]))
-
-(set! *warn-on-reflection* true)
-
-(defn make-context-bindings
- "Build query-aware structured helper bindings for the current runtime context."
- [metadata-provider tables-by-name fields-by-table fields-by-id]
- (merge {'query (fn [metadata] (lib/query metadata-provider metadata))}
- (runtime.lookup/metadata-bindings metadata-provider
- tables-by-name
- fields-by-table
- fields-by-id)
- (runtime.transforms/query-transform-bindings)))
diff --git a/src/metabase/agent_lib/runtime/fields.clj b/src/metabase/agent_lib/runtime/fields.clj
deleted file mode 100644
index 2d77016ff78..00000000000
--- a/src/metabase/agent_lib/runtime/fields.clj
+++ /dev/null
@@ -1,78 +0,0 @@
-(ns metabase.agent-lib.runtime.fields
- "Field lookup and query-stage field resolution for structured MBQL runtime bindings."
- (:require
- [metabase.agent-lib.common.errors :as errors]
- [metabase.agent-lib.mbql-integration :as mbql]
- [metabase.lib.metadata :as lib.metadata]
- [metabase.util :as u]))
-
-(set! *warn-on-reflection* true)
-
-(defn build-table-lookup
- "Build a lowercase table-name lookup for `table-ids`.
-
- Only the explicitly-requested tables are loaded — the runtime is scoped to entities the program
- actually references (source + referenced + surrounding), not every table in the database.
- Unknown tables are silently dropped; out-of-scope lookups will surface as nice errors at use time."
- [metadata-provider table-ids]
- (into {}
- (keep (fn [tid]
- (when-let [table (lib.metadata/table metadata-provider tid)]
- [(u/lower-case-en (:name table)) table])))
- table-ids))
-
-(defn build-field-lookups
- "Build both the `fields-by-table` and `fields-by-id` lookups for the tables in `tables-by-name`.
-
- `fields-by-table` is a `{lower-case-table-name {lower-case-field-name field}}` map.
- `fields-by-id` is a `{field-id field}` map.
-
- Both maps are scoped to the tables passed in — typically the in-scope set computed from the
- evaluation context, not every table in the database."
- [metadata-provider tables-by-name]
- (reduce-kv (fn [acc table-name table-meta]
- (let [fields (lib.metadata/fields metadata-provider (:id table-meta))]
- (-> acc
- (assoc-in [:fields-by-table table-name]
- (into {}
- (map (fn [field]
- [(u/lower-case-en (:name field)) field]))
- fields))
- (update :fields-by-id
- (fn [m]
- (reduce (fn [m field] (assoc m (:id field) field)) m fields))))))
- {:fields-by-table {} :fields-by-id {}}
- tables-by-name))
-
-(defn- table-name-for-field-lookup
- [metadata-provider tables-by-name table-name-or-id]
- (if (number? table-name-or-id)
- (if-let [table-meta (lib.metadata/table metadata-provider (int table-name-or-id))]
- (u/lower-case-en (:name table-meta))
- (errors/lookup-error! (str "Table not found by ID: " table-name-or-id)
- {:table-id table-name-or-id}
- {:available (keys tables-by-name)}))
- (u/lower-case-en table-name-or-id)))
-
-(defn resolve-field-from-table
- "Resolve a field by explicit table and field identifiers."
- [metadata-provider tables-by-name fields-by-table table-name-or-id field-name]
- (let [table-name (table-name-for-field-lookup metadata-provider tables-by-name table-name-or-id)
- normalized-field-name (u/lower-case-en field-name)
- table-fields (get fields-by-table table-name)]
- (or (get table-fields normalized-field-name)
- (errors/lookup-error! (str "Field not found: "
- (if (number? table-name-or-id)
- (str "(table " table-name-or-id ")")
- table-name-or-id)
- "." field-name)
- {:table-name table-name
- :field-name field-name}
- (when table-fields
- {:available (keys table-fields)})))))
-
-(defn resolve-field-in-query
- "Resolve a metadata field against the columns available in the current query stage."
- [fields-by-id query raw-field]
- (mbql/resolve-field-in-query fields-by-id query raw-field
- (mbql/current-query-field-candidates query)))
diff --git a/src/metabase/agent_lib/runtime/lookup.clj b/src/metabase/agent_lib/runtime/lookup.clj
deleted file mode 100644
index 4f80d0a85d2..00000000000
--- a/src/metabase/agent_lib/runtime/lookup.clj
+++ /dev/null
@@ -1,160 +0,0 @@
-(ns metabase.agent-lib.runtime.lookup
- "Metadata and field lookup helpers for structured runtime bindings."
- (:require
- [metabase.agent-lib.common.errors :as errors]
- [metabase.agent-lib.mbql-integration :as mbql]
- [metabase.agent-lib.runtime.fields :as fields]
- [metabase.lib.core :as lib]
- [metabase.lib.metadata :as lib.metadata]
- [metabase.util :as u]))
-
-(set! *warn-on-reflection* true)
-
-(defn lookup-table
- "Resolve a table by numeric id or case-insensitive name."
- [metadata-provider tables-by-name table-identifier]
- (let [available-names (keys tables-by-name)]
- (if (number? table-identifier)
- (or (lib.metadata/table metadata-provider (int table-identifier))
- (errors/lookup-error! (str "Table not found by ID: " table-identifier)
- {:table-id table-identifier}
- {:available available-names}))
- (let [normalized (u/lower-case-en table-identifier)]
- (or (get tables-by-name normalized)
- (errors/lookup-error! (str "Table not found: " table-identifier)
- {:table-name table-identifier}
- {:available available-names}))))))
-
-(defn lookup-card
- "Resolve a saved-question source, rejecting metrics."
- [metadata-provider card-id]
- (if (number? card-id)
- (if-let [card-meta (lib.metadata/card metadata-provider (int card-id))]
- (if (= (:type card-meta) :metric)
- (errors/lookup-error! (str "Card " card-id " is a metric.")
- {:card-id card-id}
- {:suggestion (str "Use (metric " card-id ") instead.")})
- card-meta)
- (errors/lookup-error! (str "Card not found by ID: " card-id)
- {:card-id card-id}))
- (errors/lookup-error! (str "Card lookup requires a numeric ID, got: " (pr-str card-id))
- {:card-id card-id})))
-
-(defn lookup-metric
- "Resolve a metric by numeric id."
- [metadata-provider metric-id]
- (if (number? metric-id)
- (or (lib.metadata/metric metadata-provider (int metric-id))
- (errors/lookup-error! (str "Metric not found by ID: " metric-id)
- {:metric-id metric-id}))
- (errors/lookup-error! (str "Metric lookup requires a numeric ID, got: " (pr-str metric-id))
- {:metric-id metric-id})))
-
-(defn lookup-measure
- "Resolve a measure by numeric id."
- [metadata-provider measure-id]
- (if (number? measure-id)
- (or (lib.metadata/measure metadata-provider (int measure-id))
- (errors/lookup-error! (str "Measure not found by ID: " measure-id)
- {:measure-id measure-id}))
- (errors/lookup-error! (str "Measure lookup requires a numeric ID, got: " (pr-str measure-id))
- {:measure-id measure-id})))
-
-(defn lookup-field
- "Resolve a field by id, unique name, or explicit table/name pair."
- ([metadata-provider _tables-by-name fields-by-table fields-by-id field-name-or-id]
- (if (number? field-name-or-id)
- (or (get fields-by-id (int field-name-or-id))
- (lib.metadata/field metadata-provider (int field-name-or-id))
- (errors/lookup-error! (str "Field not found by ID: " field-name-or-id)
- {:field-id field-name-or-id}))
- (let [field-name (u/lower-case-en field-name-or-id)
- matches (into []
- (keep (fn [[table-name field-map]]
- (when-let [field (get field-map field-name)]
- [table-name field])))
- fields-by-table)]
- (cond
- (= 1 (count matches))
- (second (first matches))
-
- (> (count matches) 1)
- (errors/lookup-error! (str "Ambiguous field \"" field-name-or-id "\".")
- {:field-name field-name-or-id}
- {:tables (mapv first matches)
- :suggestion "Use (field \"TABLE\" \"FIELD\") to disambiguate."})
-
- :else
- (errors/lookup-error! (str "Field not found: \"" field-name-or-id "\".")
- {:field-name field-name-or-id}
- {:suggestion "Use (field \"TABLE\" \"FIELD\") with explicit table name."})))))
- ([metadata-provider _tables-by-name fields-by-table _fields-by-id table-name-or-id field-name]
- (fields/resolve-field-from-table metadata-provider
- _tables-by-name
- fields-by-table
- table-name-or-id
- field-name)))
-
-(defn query-relative-field
- "Resolve a requested field against the current query stage."
- ([metadata-provider tables-by-name fields-by-table fields-by-id query field-name-or-id]
- (fields/resolve-field-in-query fields-by-id
- query
- (lookup-field metadata-provider
- tables-by-name
- fields-by-table
- fields-by-id
- field-name-or-id)))
- ([metadata-provider tables-by-name fields-by-table fields-by-id query table-name-or-id field-name]
- (let [raw-field (lookup-field metadata-provider
- tables-by-name
- fields-by-table
- fields-by-id
- table-name-or-id
- field-name)]
- (or (when (mbql/query? query)
- (lib/find-matching-column query
- -1
- raw-field
- (mbql/current-query-field-candidates query)))
- (fields/resolve-field-in-query fields-by-id query raw-field)
- raw-field))))
-
-(defn metadata-bindings
- "Return metadata and field lookup bindings for the structured runtime."
- [metadata-provider tables-by-name fields-by-table fields-by-id]
- {'table (partial lookup-table metadata-provider tables-by-name)
- 'card (partial lookup-card metadata-provider)
- 'metric (partial lookup-metric metadata-provider)
- 'measure (partial lookup-measure metadata-provider)
- 'field (fn
- ([field-name-or-id]
- (lookup-field metadata-provider
- tables-by-name
- fields-by-table
- fields-by-id
- field-name-or-id))
- ([a b]
- ;; 2-arity: (field query field-name-or-id) or (field table-name field-name).
- ;; Queries are always maps; table names are always strings or numbers.
- (if (map? a)
- (query-relative-field metadata-provider
- tables-by-name
- fields-by-table
- fields-by-id
- a
- b)
- (lookup-field metadata-provider
- tables-by-name
- fields-by-table
- fields-by-id
- a
- b)))
- ([query table-name-or-id field-name]
- (query-relative-field metadata-provider
- tables-by-name
- fields-by-table
- fields-by-id
- query
- table-name-or-id
- field-name)))})
diff --git a/src/metabase/agent_lib/runtime/transforms.clj b/src/metabase/agent_lib/runtime/transforms.clj
deleted file mode 100644
index 1d8785a5346..00000000000
--- a/src/metabase/agent_lib/runtime/transforms.clj
+++ /dev/null
@@ -1,96 +0,0 @@
-(ns metabase.agent-lib.runtime.transforms
- "Query-transform bindings for structured runtime evaluation."
- (:require
- [metabase.agent-lib.mbql-integration :as mbql]
- [metabase.lib.core :as lib]
- [metabase.lib.util :as lib.util]))
-
-(set! *warn-on-reflection* true)
-
-(def ^:private order-wrapper-direction-key
- :order-direction)
-
-(def ^:private order-wrapper-value-key
- :order-value)
-
-(defn order-wrapper?
- "True when `x` wraps an orderable together with its direction."
- [x]
- (and (map? x)
- (contains? x order-wrapper-direction-key)
- (contains? x order-wrapper-value-key)))
-
-(defn asc-orderable
- "Wrap an orderable with ascending sort direction."
- [orderable]
- {order-wrapper-direction-key :asc
- order-wrapper-value-key orderable})
-
-(defn desc-orderable
- "Wrap an orderable with descending sort direction."
- [orderable]
- {order-wrapper-direction-key :desc
- order-wrapper-value-key orderable})
-
-(defn- freshen-orderable-ref
- "Freshen ref uuids so repeated orderables do not alias the same clause instance."
- [resolved-orderable]
- (if (vector? resolved-orderable)
- (lib.util/fresh-uuids resolved-orderable)
- resolved-orderable))
-
-(defn apply-breakout
- "Apply a breakout, materializing expression refs when needed."
- [query breakoutable]
- (if (and (lib.util/clause? breakoutable)
- (not (lib.util/ref-clause? breakoutable)))
- (let [[query' expr-ref] (mbql/ensure-query-expression-ref query breakoutable "breakout")]
- (lib/breakout query' expr-ref))
- (lib/breakout query breakoutable)))
-
-(defn apply-filter
- "Apply a filter clause to a query."
- [query clause]
- (lib/filter query clause))
-
-(defn apply-with-fields
- "Apply `with-fields`, expanding raw fields into breakouts on aggregated queries."
- [query selections]
- (let [selections' (mapv #(mbql/resolve-aggregation-selection query %) selections)
- field-selection? mbql/field-selection?
- raw-fields (filterv field-selection? selections')
- other-selections (filterv (complement field-selection?) selections')]
- (if (and (seq (lib/aggregations query))
- (seq raw-fields))
- (let [query' (reduce lib/breakout query raw-fields)]
- (if (seq other-selections)
- (lib/with-fields query' other-selections)
- query'))
- (lib/with-fields query selections'))))
-
-(defn apply-order-by
- "Apply `order-by`, resolving query-relative orderables first."
- ([query orderable]
- (if (order-wrapper? orderable)
- (let [[query' resolved] (mbql/resolve-orderable query (order-wrapper-value-key orderable))]
- (lib/order-by query'
- (freshen-orderable-ref resolved)
- (order-wrapper-direction-key orderable)))
- (let [[query' resolved] (mbql/resolve-orderable query orderable)]
- (lib/order-by query' (freshen-orderable-ref resolved)))))
- ([query a b]
- (if (#{:asc :desc} a)
- (let [[query' resolved] (mbql/resolve-orderable query b)]
- (lib/order-by query' (freshen-orderable-ref resolved) a))
- (let [[query' resolved] (mbql/resolve-orderable query a)]
- (lib/order-by query' (freshen-orderable-ref resolved) b)))))
-
-(defn query-transform-bindings
- "Return query-transform bindings for the structured runtime."
- []
- {'asc asc-orderable
- 'desc desc-orderable
- 'breakout apply-breakout
- 'filter apply-filter
- 'with-fields apply-with-fields
- 'order-by apply-order-by})
diff --git a/src/metabase/agent_lib/schema.clj b/src/metabase/agent_lib/schema.clj
deleted file mode 100644
index 542ee83b59a..00000000000
--- a/src/metabase/agent_lib/schema.clj
+++ /dev/null
@@ -1,128 +0,0 @@
-(ns metabase.agent-lib.schema
- "Malli schemas for the structured MBQL program generation path."
- (:require
- [clojure.string :as str]
- [metabase.agent-lib.capabilities :as capabilities]
- [metabase.agent-lib.schema.top-level :as schema.top-level]
- [metabase.util.i18n :refer [tru]]
- [metabase.util.malli.humanize :as mu.humanize]
- [metabase.util.malli.registry :as mr]
- [metabase.util.malli.schema :as ms]))
-
-(set! *warn-on-reflection* true)
-
-(def ^:private top-level-operation-values
- capabilities/top-level-operator-values)
-
-(defn- non-blank-string?
- [value]
- (and (string? value) (not (str/blank? value))))
-
-(defn- nested-operator-tuple?
- [value]
- (and (vector? value)
- (string? (first value))
- (not (str/blank? (first value)))
- (not (top-level-operation-values (first value)))
- (not= "query" (first value))))
-
-(defn- top-level-operation-tuple?
- [value]
- (and (vector? value)
- (string? (first value))
- (top-level-operation-values (first value))))
-
-(defn program-literal?
- "True when `value` is a nested structured-program literal."
- [value]
- (and (map? value)
- (= "program" (or (:type value) (get value "type")))
- (or (contains? value :program)
- (contains? value "program"))))
-
-(defn- plain-map-literal?
- [value]
- (and (map? value)
- (not (program-literal? value))))
-
-(def ^:private registry
- {::scalar [:or nil? :string number? boolean?]
- ::non-blank-string [:and
- :string
- [:fn
- {:error/message "value must be a non-blank string"}
- non-blank-string?]]
- ::vector-literal [:vector [:ref ::node]]
- ::page [:map {:closed true}
- [:page ms/PositiveInt]
- [:items ms/PositiveInt]]
- ::source-ref [:or
- [:tuple [:= "field"] ms/PositiveInt]
- [:tuple [:= "table"] ms/PositiveInt]
- [:tuple [:= "card"] ms/PositiveInt]
- [:tuple [:= "metric"] ms/PositiveInt]]
- ::expression-ref-form [:tuple [:= "expression-ref"] [:ref ::non-blank-string]]
- ::aggregation-ref-form [:tuple [:= "aggregation-ref"] [:int {:min 0}]]
- ::query-aware-ref [:or
- [:ref ::expression-ref-form]
- [:ref ::aggregation-ref-form]]
- ::nested-operator-form [:and
- [:vector {:min 1} [:ref ::node]]
- [:fn
- {:error/message "nested operator tuple must start with a non-blank non-transform operator string"}
- nested-operator-tuple?]]
- ::program-literal [:map {:closed true}
- [:type [:= "program"]]
- [:program [:ref ::program]]]
- ::map-literal [:and
- [:map-of :any [:ref ::node]]
- [:fn
- {:error/message "map literals cannot use the reserved `{\"type\":\"program\"}` shape unless they contain a valid nested program"}
- plain-map-literal?]]
- ::form [:or
- [:ref ::source-ref]
- [:ref ::query-aware-ref]
- [:ref ::nested-operator-form]]
- ::node [:or
- [:ref ::scalar]
- [:ref ::program-literal]
- [:ref ::map-literal]
- [:ref ::form]
- [:ref ::vector-literal]]
- ::top-level-op [:and
- schema.top-level/query-transform-form
- [:fn
- {:error/message "operation tuple must start with a valid top-level operator string"}
- top-level-operation-tuple?]]
- ::source [:or
- [:map {:closed true}
- [:type [:= "context"]]
- [:ref [:= "source"]]]
- [:map {:closed true}
- [:type [:enum "table" "card" "dataset" "metric"]]
- [:id ms/PositiveInt]]
- [:ref ::program-literal]]
- ::program [:map {:closed true}
- [:source [:ref ::source]]
- [:operations [:sequential [:ref ::top-level-op]]]]})
-
-(def source-schema
- "Malli schema for structured-program sources."
- [:schema {:registry registry} [:ref ::source]])
-
-(def program-schema
- "Malli schema for full structured MBQL programs."
- [:schema {:registry registry} [:ref ::program]])
-
-(defn validated-structure
- "Validate the structural shape of a structured program and return it unchanged."
- [program]
- (when-let [error (mr/explain program-schema program)]
- (throw (ex-info (tru "Generated program has an invalid structure.")
- {:status-code 400
- :error :invalid-generated-program
- :humanized (mu.humanize/humanize error)
- :details (pr-str (mu.humanize/humanize error))
- :schema ::program
- :value program})))
- program)
diff --git a/src/metabase/agent_lib/schema/top_level.clj b/src/metabase/agent_lib/schema/top_level.clj
deleted file mode 100644
index a14e5b75524..00000000000
--- a/src/metabase/agent_lib/schema/top_level.clj
+++ /dev/null
@@ -1,50 +0,0 @@
-(ns metabase.agent-lib.schema.top-level
- "Top-level operation schema helpers derived from the capability catalog."
- (:require
- [metabase.agent-lib.capabilities.catalog.top-level :as capabilities.top-level]
- [metabase.util.malli.schema :as ms]))
-
-(set! *warn-on-reflection* true)
-
-(def ^:private schema-ns
- "metabase.agent-lib.schema")
-
-(defn- schema-ref
- [local-name]
- [:ref (keyword schema-ns local-name)])
-
-(def ^:private top-level-operation-schemas
- {"filter" [:tuple [:= "filter"] (schema-ref "form")]
- "aggregate" [:tuple [:= "aggregate"] (schema-ref "form")]
- "breakout" [:tuple [:= "breakout"] (schema-ref "form")]
- "with-fields" [:tuple [:= "with-fields"] [:sequential (schema-ref "form")]]
- "limit" [:tuple [:= "limit"] ms/PositiveInt]
- "expression" [:tuple [:= "expression"] (schema-ref "non-blank-string") (schema-ref "form")]
- "join" [:tuple [:= "join"] (schema-ref "form")]
- "order-by" [:or
- [:tuple [:= "order-by"] (schema-ref "form")]
- [:tuple [:= "order-by"] (schema-ref "form") [:enum "asc" "desc"]]]
- "append-stage" [:tuple [:= "append-stage"]]
- "drop-stage" [:tuple [:= "drop-stage"]]
- "drop-empty-stages" [:tuple [:= "drop-empty-stages"]]
- "with-page" [:tuple [:= "with-page"] (schema-ref "page")]})
-
-(def ^:private top-level-op-names
- (mapv (comp name :op) capabilities.top-level/capabilities))
-
-(defn- validate-top-level-coverage!
- []
- (let [defined-ops (set (keys top-level-operation-schemas))
- catalog-ops (set top-level-op-names)]
- (when (not= defined-ops catalog-ops)
- (throw (ex-info "Top-level capability and schema definitions are out of sync."
- {:defined-ops defined-ops
- :catalog-ops catalog-ops})))))
-
-(validate-top-level-coverage!)
-
-(def query-transform-form
- "Schema form for all valid top-level structured query transforms, ordered from the top-level capability catalog."
- (into [:or]
- (map top-level-operation-schemas)
- top-level-op-names))
diff --git a/src/metabase/agent_lib/syntax.clj b/src/metabase/agent_lib/syntax.clj
deleted file mode 100644
index c00742ae2ed..00000000000
--- a/src/metabase/agent_lib/syntax.clj
+++ /dev/null
@@ -1,94 +0,0 @@
-(ns metabase.agent-lib.syntax
- "Shape-level helpers for structured MBQL operators and tuples."
- (:require
- [metabase.agent-lib.capabilities :as capabilities]
- [metabase.util :as u]))
-
-(set! *warn-on-reflection* true)
-
-(def canonical-operator-aliases
- "Legacy or alternate helper names keyed to their canonical string forms."
- {"if" "case"
- "relative-date" "relative-datetime"
- "temporal-diff" "datetime-diff"
- "count-if" "count-where"
- "variance" "var"
- "stddev-pop" "stddev"
- "count-distinct" "distinct"
- "distinct-count" "distinct"
- "is-not-null" "not-null"
- "|" "or"
- "dayofweek" "get-day-of-week"
- "day-of-week" "get-day-of-week"
- "hour-of-day" "get-hour"
- "month" "get-month"
- "month-of-year" "get-month"
- "quarter-of-year" "get-quarter"})
-
-(def top-level-operation-symbols
- "Top-level structured program operators keyed as symbols."
- capabilities/query-transform-symbols)
-
-(def recognized-operator-symbols
- "All recognized operator symbols, including the synthetic `query` helper."
- (conj capabilities/helper-symbols 'query))
-
-(def repairable-operator-names
- "Operator names that should be normalized by the repair pass."
- (into #{"visualization" "is" "is-not"}
- (concat
- (map name recognized-operator-symbols)
- (map name top-level-operation-symbols)
- (keys canonical-operator-aliases)
- ["dayofweek" "day-of-week" "hour-of-day" "month-of-year" "quarter-of-year"])))
-
-(defn raw-op-name
- "Return the raw operator name string for a string, keyword, or symbol."
- [value]
- (cond
- (string? value) value
- (keyword? value) (name value)
- (symbol? value) (name value)
- :else nil))
-
-(defn canonical-op-name
- "Return the canonical string operator name for a structured helper."
- [value]
- (when-let [op-name (raw-op-name value)]
- (or (canonical-operator-aliases op-name)
- op-name)))
-
-(defn op-symbol
- "Normalize helper identifiers into canonical operator symbols."
- [op]
- (some-> op canonical-op-name symbol))
-
-(defn possible-operator-tuple?
- "True when `value` looks like a repairable structured helper tuple."
- [value]
- (and (vector? value)
- (contains? repairable-operator-names
- (or (canonical-op-name (first value))
- (raw-op-name (first value))))))
-
-(defn boolean-wrapper-form?
- "True when `value` is a legacy boolean wrapper tuple such as `[\"true\", expr]`."
- [value]
- (and (vector? value)
- (= 2 (count value))
- (contains? #{"true" "false"}
- (some-> (first value) raw-op-name u/lower-case-en))))
-
-(defn top-level-operation-tuple?
- "True when `value` is a top-level structured operation tuple."
- [value]
- (and (possible-operator-tuple? value)
- (contains? top-level-operation-symbols
- (symbol (canonical-op-name (first value))))))
-
-(defn operator-tuple?
- "True when `value` is a recognized structured helper tuple."
- [value]
- (and (vector? value)
- (string? (first value))
- (contains? recognized-operator-symbols (op-symbol (first value)))))
diff --git a/src/metabase/agent_lib/validate.clj b/src/metabase/agent_lib/validate.clj
deleted file mode 100644
index f6f395143e0..00000000000
--- a/src/metabase/agent_lib/validate.clj
+++ /dev/null
@@ -1,38 +0,0 @@
-(ns metabase.agent-lib.validate
- "Structural and semantic validation for structured MBQL programs."
- (:require
- [metabase.agent-lib.repair :as repair]
- [metabase.agent-lib.schema :as schema]
- [metabase.agent-lib.validate.semantic :as semantic]
- [metabase.util.log :as log]
- [metabase.util.malli :as mu]))
-
-(set! *warn-on-reflection* true)
-
-(def ^:private ContextEntitySummary
- "Schema for a single entity summary in the evaluation context."
- [:map
- [:model :string]
- [:id pos-int?]])
-
-(def EvaluationContext
- "Schema for the evaluation context passed to validation and evaluation.
- `:source-entity` identifies the primary data source.
- `:surrounding-tables` provides join candidates visible in the current scope."
- [:map
- [:source-entity ContextEntitySummary]
- [:referenced-entities [:sequential ContextEntitySummary]]
- [:surrounding-tables [:sequential [:map [:id pos-int?]]]]])
-
-(mu/defn validated-program :- :map
- "Repair and validate a structured program, returning the repaired program on success."
- [program :- :map
- context :- EvaluationContext]
- (log/debug "Repairing structured program")
- (let [program (-> program
- repair/repair-program
- (repair/repair-program-for-context context))]
- (log/debug "Validating repaired program structure")
- (schema/validated-structure program)
- (log/debug "Validating repaired program semantics")
- (semantic/validate-program program context)))
diff --git a/src/metabase/agent_lib/validate/context.clj b/src/metabase/agent_lib/validate/context.clj
deleted file mode 100644
index b773b80808e..00000000000
--- a/src/metabase/agent_lib/validate/context.clj
+++ /dev/null
@@ -1,76 +0,0 @@
-(ns metabase.agent-lib.validate.context
- "Context-derived validation helpers for structured programs."
- (:require
- [metabase.agent-lib.common.errors :refer [invalid-program!]]))
-
-(set! *warn-on-reflection* true)
-
-(defn context-allowed-ids
- "Derive the ids that are valid for the current evaluation context."
- [{:keys [source-entity referenced-entities surrounding-tables measure-ids]}]
- (let [entity-summaries (concat [source-entity] referenced-entities surrounding-tables)
- summary-field-ids (fn [entity-summary]
- (->> (concat
- (:columns entity-summary)
- (get-in entity-summary [:query_summary :returned_columns])
- (get-in entity-summary [:query_summary :filterable_columns])
- (:queryable_dimensions entity-summary))
- (keep :id)
- (filter pos-int?)))
- source-model (:model source-entity)]
- {:table-ids (->> (concat
- (when (= source-model "table") [(:id source-entity)])
- (keep #(when (= "table" (:model %)) (:id %)) referenced-entities)
- (map :id surrounding-tables))
- (filter pos-int?)
- set)
- :card-ids (->> (concat
- (when (#{"card" "dataset"} source-model) [(:id source-entity)])
- (keep #(when (#{"card" "dataset"} (:model %)) (:id %)) referenced-entities))
- (filter pos-int?)
- set)
- :metric-ids (->> (concat
- (when (= source-model "metric") [(:id source-entity)])
- (keep #(when (= "metric" (:model %)) (:id %)) referenced-entities))
- (filter pos-int?)
- set)
- :measure-ids (set (filter pos-int? measure-ids))
- :field-ids (->> entity-summaries
- (mapcat summary-field-ids)
- set)}))
-
-(defn validate-source!
- "Validate a structured source against the context-derived allowed ids."
- [validate-nested-program allowed-ids path source depth state]
- (case (:type source)
- "context"
- (do
- (when-not (= "source" (:ref source))
- (invalid-program! (conj path :ref) "context source ref must be `source`"))
- state)
-
- "table"
- (do
- (when-not (pos-int? (:id source))
- (invalid-program! (conj path :id) "source table id must be a numeric id"))
- (when-not ((:table-ids allowed-ids) (:id source))
- (invalid-program! (conj path :id) "source table id is not available in the provided context"))
- state)
-
- ("card" "dataset")
- (do
- (when-not ((:card-ids allowed-ids) (:id source))
- (invalid-program! (conj path :id) "source card id is not available in the provided context"))
- state)
-
- "metric"
- (do
- (when-not ((:metric-ids allowed-ids) (:id source))
- (invalid-program! (conj path :id) "source metric id is not available in the provided context"))
- state)
-
- "program"
- (validate-nested-program (conj path :program) (:program source) (inc depth)
- (update state :program-nesting (fnil inc 0)))
-
- (invalid-program! (conj path :type) "unsupported source type")))
diff --git a/src/metabase/agent_lib/validate/cross_checks.clj b/src/metabase/agent_lib/validate/cross_checks.clj
deleted file mode 100644
index 0f828428036..00000000000
--- a/src/metabase/agent_lib/validate/cross_checks.clj
+++ /dev/null
@@ -1,40 +0,0 @@
-(ns metabase.agent-lib.validate.cross-checks
- "Cross-operation semantic checks for structured programs."
- (:require
- [metabase.agent-lib.common.errors :refer [invalid-program!]]
- [metabase.agent-lib.runtime :as runtime]
- [metabase.agent-lib.syntax :as syntax]
- [metabase.agent-lib.validate.walker :as walker]))
-
-(set! *warn-on-reflection* true)
-
-(defn validate-no-metric-order-by!
- "Reject direct metric helpers nested inside `order-by`."
- [operation-path operation]
- (when (= 'order-by (runtime/op-symbol (first operation)))
- (when-let [metric-path
- (walker/find-tuple-path #(and (syntax/operator-tuple? %)
- (= 'metric (runtime/op-symbol (first %))))
- operation)]
- (invalid-program! (into operation-path metric-path)
- "metric helpers cannot be used directly inside order-by. Order by a breakout field or a non-metric aggregation instead."
- {:operator "metric"}))))
-
-(defn validate-no-source-metric-reuse!
- "Reject reusing the same metric already selected as the source."
- [context operation-path operation]
- (let [source-entity (:source-entity context)
- source-id (:id source-entity)]
- (when (and (= "metric" (:model source-entity))
- (pos-int? source-id))
- (when-let [metric-path
- (walker/find-tuple-path #(and (syntax/operator-tuple? %)
- (= 'metric (runtime/op-symbol (first %)))
- (= source-id (second %)))
- operation)]
- (invalid-program! (into operation-path metric-path)
- (str "source is already metric " source-id
- ". Do not reference that same metric again inside operations; start "
- "from the source query and build on it.")
- {:operator "metric"
- :id source-id})))))
diff --git a/src/metabase/agent_lib/validate/operators.clj b/src/metabase/agent_lib/validate/operators.clj
deleted file mode 100644
index 80c07642485..00000000000
--- a/src/metabase/agent_lib/validate/operators.clj
+++ /dev/null
@@ -1,172 +0,0 @@
-(ns metabase.agent-lib.validate.operators
- "Operator-specific semantic validation for structured programs."
- (:require
- [clojure.string :as str]
- [metabase.agent-lib.capabilities :as capabilities]
- [metabase.agent-lib.common.context :as common.context]
- [metabase.agent-lib.common.errors :refer [invalid-program!]]
- [metabase.agent-lib.common.literals :refer [aggregation-form?
- bare-field-id?
- non-blank-string?]]
- [metabase.agent-lib.runtime :as runtime]
- [metabase.agent-lib.syntax :as syntax]))
-
-(set! *warn-on-reflection* true)
-
-(def ^:private field-wrapper-required-arg-positions
- "Argument positions that must be wrapped as `[\"field\", id]` for specific helpers."
- '{sum [0]
- avg [0]
- min [0]
- max [0]
- distinct [0]
- median [0]
- stddev [0]
- var [0]
- percentile [0]
- cum-sum [0]
- sum-where [0]
- distinct-where [0]})
-
-(defn ensure-arity!
- "Validate a helper arity against the capability catalog."
- [path op arg-count]
- (when-let [allowed (capabilities/fixed-arities op)]
- (when-not (allowed arg-count)
- (invalid-program! path
- (if (and (= op 'expression) (= arg-count 1))
- (str "`expression` is a top-level operation, not a nested reference. "
- "Use `[\"expression\", \"Name\", expr]` as its own operation, and if you need to "
- "sort by that calculation, reuse the expression body directly inside `order-by`.")
- (format "operator `%s` expects %s argument(s), got %s"
- (name op)
- (str/join " or " (sort allowed))
- arg-count))
- {:operator (name op)
- :allowed (sort allowed)
- :actual arg-count}))))
-
-(defn validate-operator-specific!
- "Validate nested helper tuples against context-derived ids and operator rules."
- [allowed-ids context path value]
- (when (syntax/operator-tuple? value)
- (let [[raw-op & args] value
- op (runtime/op-symbol raw-op)
- op-name (name op)]
- (cond
- (syntax/top-level-operation-symbols op)
- (invalid-program! path
- (format "`%s` is a top-level operation and cannot be nested" op-name)
- {:operator op-name})
-
- (= op 'query)
- (invalid-program! path
- "`query` cannot appear inside operations; the program source already defines the base query."
- {:operator "query"})
-
- :else
- (do
- (doseq [arg-position (get field-wrapper-required-arg-positions op)]
- (when (bare-field-id? (nth args arg-position nil))
- (invalid-program! (conj path (inc arg-position))
- (str "Wrap field ids with `[\"field\", id]` inside `" op-name "`. "
- "Do not pass bare numeric ids directly to aggregation helpers.")
- {:operator op-name
- :retry-category :field-wrapper
- :value (nth args arg-position)})))
- (case op-name
- "case"
- (when (some-> args second map?)
- (when (or (contains? (second args) :default)
- (contains? (second args) "default"))
- (invalid-program! (conj path 2)
- "`case` uses the fallback value itself as the optional third argument. Do not use `{\"default\": ...}`. Omit the third argument instead of using null."
- {:operator "case"})))
-
- "table"
- (let [id (first args)]
- (when-not (pos-int? id)
- (invalid-program! (conj path 1) "table lookup requires a numeric id")))
-
- "card"
- (let [id (first args)]
- (when-not (pos-int? id)
- (invalid-program! (conj path 1) "card lookup requires a numeric id"))
- (when-not ((:card-ids allowed-ids) id)
- (invalid-program! (conj path 1)
- "card id is not available in the provided context"
- {:operator "card" :id id})))
-
- "metric"
- (let [id (first args)]
- (when-not (pos-int? id)
- (invalid-program! (conj path 1) "metric lookup requires a numeric id"))
- (when-not ((:metric-ids allowed-ids) id)
- (invalid-program! (conj path 1)
- "metric id is not available in the provided context"
- {:operator "metric" :id id})))
-
- "measure"
- (let [id (first args)
- source-id (common.context/source-metric-id context)]
- (when-not (pos-int? id)
- (invalid-program! (conj path 1) "measure lookup requires a numeric id"))
- (when (and source-id (= source-id id))
- (invalid-program! (conj path 1)
- (str "source is already metric " source-id
- ". Metric ids are not measure ids. Do not reference that same "
- "metric as a `measure`; start from the source query and build on it.")
- {:operator "measure"
- :id id
- :source-metric-id source-id}))
- (when-not ((:measure-ids allowed-ids) id)
- (invalid-program! (conj path 1)
- "measure id is not available in the provided context"
- {:operator "measure" :id id})))
-
- "field"
- (cond
- (not= 1 (count args))
- (invalid-program! path "field lookups must use a single numeric field id")
-
- (not (pos-int? (first args)))
- (invalid-program! (conj path 1) "field lookup requires a numeric id"))
-
- "expression-ref"
- (let [expr-name (first args)]
- (when-not (non-blank-string? expr-name)
- (invalid-program! (conj path 1)
- "expression-ref requires a non-blank expression name"
- {:operator "expression-ref"})))
-
- "aggregation-ref"
- (let [index (first args)]
- (when-not (and (int? index) (<= 0 index))
- (invalid-program! (conj path 1)
- "aggregation-ref requires a zero-based aggregation index"
- {:operator "aggregation-ref"
- :value index})))
-
- nil))))))
-
-(defn validate-top-level-operation!
- "Validate a top-level operation and its arguments."
- [validate-node operation-path operation state]
- (let [[raw-op & args] operation
- op (runtime/op-symbol raw-op)]
- (when-not (syntax/top-level-operation-symbols op)
- (invalid-program! (conj operation-path 0)
- "top-level operation is not allowed"
- {:operator raw-op}))
- (ensure-arity! operation-path op (count args))
- (when (= op 'aggregate)
- (doseq [[idx arg] (map-indexed vector args)]
- (when-not (aggregation-form? arg)
- (invalid-program! (conj operation-path (inc idx))
- "aggregate operations require aggregation helpers like `count`, `sum`, `avg`, `percentile`, `metric`, or `measure`. Do not pass bare `aggregation-ref` or breakout clauses directly."
- {:operator "aggregate"
- :value arg}))))
- (reduce (fn [state [idx arg]]
- (validate-node (conj operation-path (inc idx)) arg 1 state))
- state
- (map-indexed vector args))))
diff --git a/src/metabase/agent_lib/validate/program.clj b/src/metabase/agent_lib/validate/program.clj
deleted file mode 100644
index a3a6c977058..00000000000
--- a/src/metabase/agent_lib/validate/program.clj
+++ /dev/null
@@ -1,70 +0,0 @@
-(ns metabase.agent-lib.validate.program
- "Recursive semantic program validation for agent-lib.
-
- The local `letfn` in `validate-program-body!` is intentional: this namespace
- is the recursive validation boundary for nested structured programs."
- (:require
- [clojure.string :as str]
- [metabase.agent-lib.common.errors :refer [invalid-program!]]
- [metabase.agent-lib.runtime :as runtime]
- [metabase.agent-lib.schema :as schema]
- [metabase.agent-lib.syntax :as syntax]
- [metabase.agent-lib.validate.context :as validate.context]
- [metabase.agent-lib.validate.cross-checks :as cross-checks]
- [metabase.agent-lib.validate.operators :as operators]
- [metabase.agent-lib.validate.walker :as walker]))
-
-(set! *warn-on-reflection* true)
-
-(defn validate-program-body!
- "Validate a repaired structured program body, threading traversal state."
- [allowed-ids context path program depth state]
- (letfn [(semantic-visit [path value depth state]
- (cond
- (schema/program-literal? value)
- (validate-program* (conj path :program) (:program value) (inc depth)
- (update state :program-nesting (fnil inc 0)))
-
- (vector? value)
- (do
- (when (and (some-> (first value) syntax/raw-op-name)
- (str/ends-with? (some-> (first value) syntax/raw-op-name) "-ref")
- (not (#{"expression-ref" "aggregation-ref"}
- (some-> (first value) syntax/raw-op-name))))
- (invalid-program! (conj path 0)
- "unknown helper reference"
- {:operator (syntax/raw-op-name (first value))}))
- (when (syntax/operator-tuple? value)
- (let [[raw-op & args] value
- op (runtime/op-symbol raw-op)]
- (operators/validate-operator-specific! allowed-ids context path value)
- (operators/ensure-arity! path op (count args))))
- state)
-
- :else
- state))
- (validate-node [path value depth state]
- (walker/walk-node path value depth state semantic-visit))
- (validate-program* [path program depth state]
- (let [nesting (get state :program-nesting 0)]
- (when (> nesting walker/max-program-nesting)
- (invalid-program! path "program source nesting exceeds maximum depth")))
- (when (> (count (:operations program)) walker/max-operations)
- (invalid-program! (conj path :operations) "program exceeds maximum operation count"))
- (let [state (validate.context/validate-source! validate-program*
- allowed-ids
- (conj path :source)
- (:source program)
- depth
- state)]
- (reduce (fn [state [idx operation]]
- (let [operation-path (into path [:operations idx])]
- (cross-checks/validate-no-metric-order-by! operation-path operation)
- (cross-checks/validate-no-source-metric-reuse! context operation-path operation)
- (operators/validate-top-level-operation! validate-node
- operation-path
- operation
- state)))
- state
- (map-indexed vector (:operations program)))))]
- (validate-program* path program depth state)))
diff --git a/src/metabase/agent_lib/validate/semantic.clj b/src/metabase/agent_lib/validate/semantic.clj
deleted file mode 100644
index 082cd4b615e..00000000000
--- a/src/metabase/agent_lib/validate/semantic.clj
+++ /dev/null
@@ -1,14 +0,0 @@
-(ns metabase.agent-lib.validate.semantic
- "Semantic validation rules for repaired structured MBQL programs."
- (:require
- [metabase.agent-lib.validate.context :as validate.context]
- [metabase.agent-lib.validate.program :as validate.program]))
-
-(set! *warn-on-reflection* true)
-
-(defn validate-program
- "Validate semantic structured-program rules after repair and structural validation."
- [program context]
- (let [allowed-ids (validate.context/context-allowed-ids context)]
- (validate.program/validate-program-body! allowed-ids context [] program 0 {:node-count 0})
- program))
diff --git a/src/metabase/agent_lib/validate/walker.clj b/src/metabase/agent_lib/validate/walker.clj
deleted file mode 100644
index 2bb780b4ac0..00000000000
--- a/src/metabase/agent_lib/validate/walker.clj
+++ /dev/null
@@ -1,99 +0,0 @@
-(ns metabase.agent-lib.validate.walker
- "Pure traversal helpers for structured program validation."
- (:require
- [metabase.agent-lib.common.coercions :refer [normalize-map-key]]
- [metabase.agent-lib.common.errors :refer [invalid-program!]]
- [metabase.agent-lib.common.literals :refer [scalar-literal?]]
- [metabase.agent-lib.schema :as schema]))
-
-(def max-operations
- "Maximum number of top-level operations allowed in a structured program."
- 32)
-
-(def max-depth
- "Maximum nesting depth allowed in a structured program."
- 24)
-
-(def max-node-count
- "Maximum total node count allowed in a structured program."
- 600)
-
-(def max-program-nesting
- "Maximum recursive program-source nesting depth (prevents circular references)."
- 8)
-
-(def max-string-length
- "Maximum length of any string value in a structured program."
- 1024)
-
-(set! *warn-on-reflection* true)
-
-(defn find-tuple-path
- "Find the first path to a vector node matching `pred`.
-
- The local `walk` helper stays nested because this namespace is the recursive
- traversal boundary for validation."
- [pred value]
- (letfn [(walk [path node]
- (cond
- (and (vector? node) (pred node))
- path
-
- (vector? node)
- (some identity
- (map-indexed (fn [idx child]
- (walk (conj path idx) child))
- node))
-
- (map? node)
- (if (schema/program-literal? node)
- (walk (conj path :program) (:program node))
- (some identity
- (map (fn [[k v]]
- (walk (conj path (normalize-map-key k)) v))
- node)))
-
- (sequential? node)
- (some identity
- (map-indexed (fn [idx child]
- (walk (conj path idx) child))
- node))
-
- :else
- nil))]
- (walk [] value)))
-
-(defn walk-node
- "Walk a structured node in preorder, threading pure traversal state through `visit`."
- [path value depth state visit]
- (when (> depth max-depth)
- (invalid-program! path "program exceeds maximum nesting depth"))
- (let [state (update state :node-count (fnil inc 0))]
- (when (> (:node-count state) max-node-count)
- (invalid-program! path "program exceeds maximum node count"))
- (when (and (string? value) (> (count value) max-string-length))
- (invalid-program! path "string value exceeds maximum length"
- {:length (count value) :max max-string-length}))
- (let [state (visit path value depth state)]
- (cond
- (scalar-literal? value)
- state
-
- (map? value)
- (if (schema/program-literal? value)
- state
- (reduce (fn [state [k v]]
- (walk-node (conj path (normalize-map-key k)) v (inc depth) state visit))
- state
- value))
-
- (sequential? value)
- (reduce (fn [state [idx element]]
- (walk-node (conj path idx) element (inc depth) state visit))
- state
- (map-indexed vector value))
-
- :else
- (invalid-program! path
- (str "unsupported literal type " (pr-str (type value)))
- {:value value})))))
diff --git a/src/metabase/driver/sql_jdbc/sync/describe_table.clj b/src/metabase/driver/sql_jdbc/sync/describe_table.clj
index bf44df1e76a..3e36fa58d2f 100644
--- a/src/metabase/driver/sql_jdbc/sync/describe_table.clj
+++ b/src/metabase/driver/sql_jdbc/sync/describe_table.clj
@@ -656,7 +656,7 @@
(->> (for [[field-path field-type] (seq field-types)
:when field-type]
(let [curr-type (get field-type-map field-type :type/*)]
- {:name (str/join " \u2192 " (map name field-path)) ;; right arrow
+ {:name (str/join " → " (map name field-path)) ;; right arrow
:database-type (db-type-map curr-type)
:base-type curr-type
;; Postgres JSONB field, which gets most usage, doesn't maintain JSON object ordering...
diff --git a/src/metabase/mcp/README.md b/src/metabase/mcp/README.md
index 19146037dee..0c5019093d9 100644
--- a/src/metabase/mcp/README.md
+++ b/src/metabase/mcp/README.md
@@ -97,7 +97,7 @@ clients can fetch supplementary content by URI without inflating tool descriptio
| Resource URI | Description |
| ------------------------------------ | ------------------------------------------------------------------------------------------------------------------ |
-| `metabase://docs/construct-query.md` | Program syntax for `construct_query` and `query` — sources, operations, operator forms, worked examples, pitfalls. |
+| `metabase://docs/construct-query.md` | Format reference for `construct_query` and `query` — top-level / stage shape, field references, filter / aggregation / temporal operators, joins, expressions, multi-stage queries, worked examples, pitfalls. |
## Supported JSON-RPC methods
diff --git a/src/metabase/mcp/resources.clj b/src/metabase/mcp/resources.clj
index 5023279914f..853edbb4540 100644
--- a/src/metabase/mcp/resources.clj
+++ b/src/metabase/mcp/resources.clj
@@ -261,14 +261,12 @@
(register-resource!
{:uri "metabase://docs/construct-query.md"
:name "Construct Query Reference"
- :description (str "Program syntax for `construct_query` and `query`: source shapes "
- "(table/card/dataset/metric), top-level operations (filter, aggregate, "
- "breakout, expression, with-fields, order-by, limit, join, append-stage, "
- "with-page), reference forms, filter/aggregation/temporal operator "
- "vocabularies, worked examples, and common pitfalls (stage boundaries, "
- "ref shapes, joins, metric/date handling).")
+ :description (str "Format reference for `construct_query` and `query`: top-level / "
+ "stage shape, field references, filter / aggregation / temporal "
+ "operators, joins, expressions, multi-stage queries, worked examples, "
+ "and common pitfalls.")
:mimeType "text/markdown"
- :render-fn (classpath-text-resource "metabase/agent_api/construct_query.md")})
+ :render-fn (classpath-text-resource "metabot/prompts/tools/construct_notebook_query.md")})
(register-ui-resource!
:visualize-query
diff --git a/src/metabase/mcp/tools.clj b/src/metabase/mcp/tools.clj
index 4b7288706e6..806dc554c23 100644
--- a/src/metabase/mcp/tools.clj
+++ b/src/metabase/mcp/tools.clj
@@ -31,39 +31,34 @@
;; describes its own wire schema, and this layer patches the manifest to publish the MCP-visible
;; shape.
-;; Shared sub-shapes for the program-shaped tools (`construct_query`, `query`). Extracted so the two
-;; tools can't drift on what a program looks like to the LLM — both reuse the same `:source` map and
-;; the same flattened `:operations` (`[:sequential [:sequential :any]]`, no tuple-of-anys, no `:and`).
-;; The wire schemas under `agent_api` use the precise tuple/composite grammar; this layer publishes
-;; the permissive variant strict MCP clients (ChatGPT) accept.
-
-(def ^:private program-source-malli
- [:map
- [:type {:tool/description "Entity kind."}
- [:enum "table" "card" "dataset" "metric"]]
- [:id ms/PositiveInt]])
-
-(def ^:private program-operations-malli
- [:sequential
- [:sequential
- {:tool/description (str "First element is the operator string; remaining "
- "elements are operator-specific arguments (scalars, "
- "references, or nested arrays).")}
- :any]])
-
-(def ^:private operations-description
- (str "Array of operator tuples like [\"filter\", clause] or [\"aggregate\", agg-clause]. "
- "See metabase://docs/construct-query.md for the full grammar."))
+;; Shared sub-shapes for the representations-shaped tools (`construct_query`, `query`).
+;;
+;; The wire schemas under `agent-api` describe the body as `{:query <::lib.schema/external-query>}`,
+;; and `::external-query` references `::lib.schema/query`, which carries `:optional` keys (notably
+;; `:lib/metadata`) that are not `[:maybe ...]`. The new `assert-optional-fields-nullable!` lint in
+;; `tools-manifest` walks every reachable map and fails on those — which is the right behaviour for
+;; tool inputs but not for the lib-internal query map we never want strict MCP clients to populate.
+;;
+;; The override here publishes a permissive `:query` field (an opaque JSON object) and conveys the
+;; real grammar through the tool description + `metabase://docs/construct-query.md`. Strict MCP
+;; clients (ChatGPT) get a clean JSON Schema (no `prefixItems` / `allOf`); the agent learns the
+;; actual MBQL 5 shape from the prompt.
+
+(def ^:private external-query-mcp-malli
+ "MCP-visible shape for the `query` field of `construct_query` / `query`. Deliberately opaque:
+ publishing the full `::lib.schema/external-query` recursively would pull in `::query`'s optional
+ non-nullable `:lib/metadata` (which trips the manifest's strict-tool lint) and emit `prefixItems` /
+ `allOf` JSON Schema constructs that strict MCP clients (ChatGPT) reject."
+ [:map {:tool/description (str "A Metabase MBQL 5 query as a JSON object. See the "
+ "`construct_notebook_query` tool for the format reference.")}])
(def ^:private construct-query-mcp-input-malli
"MCP-visible input for `construct_query`.
- Deliberately flatter than the wire schema — the operator/ref grammar is conveyed through the tool
- description and the construct-query.md MCP resource, not the schema."
+ Deliberately flatter than the wire schema — the MBQL 5 representations grammar is conveyed through
+ the tool description and the construct-query.md MCP resource, not the schema."
[:map
- [:source {:tool/description "Database entity to query."}
- program-source-malli]
- [:operations {:tool/description operations-description}
- program-operations-malli]
+ [:query {:tool/description "Metabase MBQL 5 query."}
+ external-query-mcp-malli]
;; Length bounds + description go on the inner `:string` so they end up on the JSON Schema branch
;; (and not as an `:allOf`, which ChatGPT's strict validator rejects).
[:prompt {:optional true}
@@ -73,22 +68,20 @@
"Pass it as-is without summarizing or rewriting.")}]]]])
(def ^:private query-mcp-input-malli
- "MCP-visible input for `query`. The wire body is a `:multi` whose `:program` branch references
- agent-lib tuple/composite schemas — those emit `prefixItems`/`allOf` JSON Schema constructs that
- strict MCP clients (ChatGPT) reject. This override publishes the same flattened program shape used
- by `construct_query`, plus the `:continuation_token` alternative for pagination."
+ "MCP-visible input for `query`. The wire body is a `:multi` whose `:fresh` branch references
+ `::lib.schema/external-query` — that pulls in `::query`'s `:optional` non-nullable
+ `:lib/metadata` (and emits `prefixItems` / `allOf` JSON Schema constructs that strict MCP
+ clients reject). This override publishes the same opaque-object `:query` field used by
+ `construct_query`, plus the `:continuation_token` alternative for pagination."
[:map
- [:source {:optional true
- :tool/description (str "Database entity to query. Omit when paginating via "
- "`continuation_token`.")}
- [:maybe program-source-malli]]
- [:operations {:optional true
- :tool/description operations-description}
- [:maybe program-operations-malli]]
+ [:query {:optional true
+ :tool/description (str "Metabase MBQL 5 query. "
+ "Omit when paginating via `continuation_token`.")}
+ [:maybe external-query-mcp-malli]]
[:continuation_token {:optional true
:tool/description (str "Token returned by a previous `query` response — pass "
"it back to fetch the next page. Mutually exclusive "
- "with `source`/`operations`.")}
+ "with `query`.")}
[:maybe ms/NonBlankString]]])
(def ^:private execute-query-mcp-input-malli
diff --git a/src/metabase/metabot/agent/prompts.clj b/src/metabase/metabot/agent/prompts.clj
index b576b6bd000..9659e01892b 100644
--- a/src/metabase/metabot/agent/prompts.clj
+++ b/src/metabase/metabot/agent/prompts.clj
@@ -59,13 +59,13 @@
(log/debug "Tool prompt template not found:" path)
nil))))
-(defn load-llm-representations-template
- "Load the LLM representations template from resources/metabot/prompts/."
+(defn load-llm-shape-template
+ "Load the LLM-shape (output-side XML) template from resources/metabot/prompts/."
[template-name]
(let [path (str "metabot/prompts/" template-name)]
(or (load-resource path)
(do
- (log/warn "LLM representations template not found:" path)
+ (log/warn "LLM-shape template not found:" path)
nil))))
;;; Template Rendering
@@ -150,19 +150,19 @@
[template-path]
(:template (cached-load-template "tool" template-path load-tool-prompt-template)))
-(defn get-cached-llm-representations-template
- "Get the LLM representations template from cache or load it."
+(defn get-cached-llm-shape-template
+ "Get the LLM-shape (output-side XML) template from cache or load it."
[]
- (:template (cached-load-template "llm-representations"
- "llm_representations.selmer"
- load-llm-representations-template)))
+ (:template (cached-load-template "llm-shape"
+ "llm_shape.selmer"
+ load-llm-shape-template)))
(defn get-cached-message-injection-template
"Get the message injection template from cache or load it."
[]
(:template (cached-load-template "message-injection"
"message_injection.selmer"
- load-llm-representations-template)))
+ load-llm-shape-template)))
(defn clear-cache!
"Clear the template cache. Useful for development/testing."
diff --git a/src/metabase/metabot/agent/user_context.clj b/src/metabase/metabot/agent/user_context.clj
index 06006f19e76..9cf110d0f3f 100644
--- a/src/metabase/metabot/agent/user_context.clj
+++ b/src/metabase/metabot/agent/user_context.clj
@@ -5,13 +5,16 @@
recent views, user time formatting, and SQL dialect extraction from context."
(:require
[clojure.string :as str]
+ [metabase.agent-lib.representations.resolve :as repr.resolve]
[metabase.lib-be.core :as lib-be]
[metabase.lib.core :as lib]
[metabase.metabot.tmpl :as te]
[metabase.metabot.tools.entity-details :as entity-details]
- [metabase.metabot.tools.shared.llm-representations :as llm-rep]
+ [metabase.metabot.tools.shared.content-store :as shared.content-store]
+ [metabase.metabot.tools.shared.llm-shape :as llm-shape]
[metabase.metabot.util :as metabot.u]
[metabase.util :as u]
+ [metabase.util.json :as json]
[metabase.util.log :as log])
(:import
(java.time OffsetDateTime)
@@ -122,10 +125,11 @@
;; For saved entities (table, model, question, metric, dashboard), the frontend only sends
;; type + id. We fetch full details from the DB using entity-details and render them via
-;; llm-representations, mirroring what the Python AI service did via HTTP callbacks.
+;; llm-shape (the output-side XML formatters), mirroring what the Python AI service did
+;; via HTTP callbacks.
(defn- fetch-and-format
- "Fetch entity details and format with llm-rep. Falls back to format-simple-entity on failure."
+ "Fetch entity details and format with llm-shape. Falls back to format-simple-entity on failure."
[entity preamble details-fn format-fn]
(try
(let [{:keys [structured-output]} (details-fn)]
@@ -146,7 +150,7 @@
:with-metrics? false
:with-measures? true
:with-segments? true})
- llm-rep/table->xml))
+ llm-shape/table->xml))
(defmethod format-entity "model"
[entity]
@@ -158,7 +162,7 @@
:with-metrics? false
:with-measures? true
:with-segments? true})
- llm-rep/model->xml))
+ llm-shape/model->xml))
(defn- format-chart-config-ids
"Format chart config IDs for a viewing context item.
@@ -202,7 +206,7 @@
"The user is currently looking at the results of a report:"
#(entity-details/get-report-details {:report-id (:id entity)
:with-field-values? false})
- llm-rep/question->xml)))
+ llm-shape/question->xml)))
(defmethod format-entity "metric"
[entity]
@@ -210,14 +214,14 @@
"The user is currently looking at the details of a metric:"
#(entity-details/get-metric-details {:metric-id (:id entity)
:with-field-values? false})
- llm-rep/metric->xml))
+ llm-shape/metric->xml))
(defmethod format-entity "dashboard"
[entity]
(fetch-and-format entity
"The user is currently looking at the details of a dashboard:"
#(entity-details/get-dashboard-details {:dashboard-id (:id entity)})
- llm-rep/dashboard->xml))
+ llm-shape/dashboard->xml))
;;; Viewing Context Formatting
@@ -236,22 +240,42 @@
te/lines)))))
(defn- transform-query-source-text
+ "Format a transform's `:query` source for the LLM.
+
+ When the source carries a query map with a `:database` key, we normalise it and export to
+ the same canonical portable representations form the `construct_notebook_query` tool
+ consumes (rendered as a JSON code block). Both structured (`mbql.stage/mbql`) and native
+ (`mbql.stage/native`) stages go through this path - the latter is intentional: the repr
+ export preserves portable `card-id` / `snippet-id` references inside `template-tags`, and
+ stays in lockstep with the freshly-built-query payloads `construct_notebook_query` returns
+ to the LLM.
+
+ Pre-resolved string sources (`:query` is itself a string, or carries `:query-content` -
+ the SQL-tool's already-rendered shape) pass through unchanged: there's no map to
+ normalise.
+
+ Falls back to a `pprint`'d query map only as a last resort, when repr export is
+ unavailable (e.g. a partially-broken `dataset_query`)."
[source]
(let [query (:query source)]
(cond
(string? query) query
(string? (:query-content query)) (:query-content query)
- (string? (get-in query [:native :query])) (get-in query [:native :query])
(and (map? query) (:database query))
(try
- (let [normalized (lib-be/normalize-query query)]
- (if (lib/native-only-query? normalized)
- (or (lib/raw-native-query normalized)
- (some :native (:stages normalized))
- (get-in normalized [:native :query]))
+ (let [normalized (lib-be/normalize-query query)
+ database-id (:database normalized)
+ mp (when database-id
+ (lib-be/application-database-metadata-provider database-id))
+ exported (some->> mp (#(repr.resolve/try-export-query % normalized shared.content-store/default-store)))]
+ (if exported
+ (str "```json\n" (json/encode exported {:pretty true}) "\n```")
(u/pprint-to-str normalized)))
(catch Exception _
(u/pprint-to-str query)))
+ ;; Legacy native shape with no :database (rare). Surface the raw SQL so the LLM at
+ ;; least sees the query body; if there's no :database we can't normalise / build a MP.
+ (string? (get-in query [:native :query])) (get-in query [:native :query])
(map? query) (u/pprint-to-str query)
:else (some-> query str))))
@@ -368,10 +392,10 @@
[_context]
(try
(when-let [{:keys [id name email-address glossary]} (:structured-output (entity-details/get-current-user nil))]
- (llm-rep/user->xml {:id id
- :name name
- :email email-address
- :glossary glossary}))
+ (llm-shape/user->xml {:id id
+ :name name
+ :email email-address
+ :glossary glossary}))
(catch Exception e
(log/error e "Error formatting current user info")
nil)))
diff --git a/src/metabase/metabot/tools/charts.clj b/src/metabase/metabot/tools/charts.clj
index 2c198d32201..11533b1fc25 100644
--- a/src/metabase/metabot/tools/charts.clj
+++ b/src/metabase/metabot/tools/charts.clj
@@ -9,7 +9,7 @@
[metabase.metabot.tools.charts.edit :as edit-chart-tools]
[metabase.metabot.tools.shared :as shared]
[metabase.metabot.tools.shared.instructions :as instructions]
- [metabase.metabot.tools.shared.llm-representations :as llm-rep]
+ [metabase.metabot.tools.shared.llm-shape :as llm-shape]
[metabase.util.log :as log]
[metabase.util.malli :as mu]))
@@ -17,7 +17,7 @@
(defn- format-chart-output
[{:keys [chart-id] :as structured}]
- (let [chart-xml (llm-rep/chart->xml structured)]
+ (let [chart-xml (llm-shape/chart->xml structured)]
(str "<result>\n" chart-xml "\n</result>\n"
"<instructions>\n" (instructions/chart-created-instructions chart-id) "\n</instructions>")))
diff --git a/src/metabase/metabot/tools/construct.clj b/src/metabase/metabot/tools/construct.clj
index b495b5de50c..48561882128 100644
--- a/src/metabase/metabot/tools/construct.clj
+++ b/src/metabase/metabot/tools/construct.clj
@@ -1,139 +1,201 @@
(ns metabase.metabot.tools.construct
"Notebook query construction tool wrappers."
(:require
- [metabase.agent-lib.core :as agent-lib]
+ [metabase.agent-lib.representations :as repr]
+ [metabase.agent-lib.representations.repair :as repr.repair]
+ [metabase.agent-lib.representations.resolve :as repr.resolve]
+ [metabase.api.common :as api]
[metabase.lib-be.core :as lib-be]
[metabase.lib.core :as lib]
- [metabase.lib.metadata :as lib.metadata]
[metabase.metabot.agent.streaming :as streaming]
[metabase.metabot.scope :as scope]
[metabase.metabot.tmpl :as te]
[metabase.metabot.tools.charts.create :as create-chart-tools]
+ [metabase.metabot.tools.shared.content-store :as shared.content-store]
[metabase.metabot.tools.shared.instructions :as instructions]
- [metabase.metabot.tools.shared.llm-representations :as llm-rep]
+ [metabase.metabot.tools.shared.llm-shape :as llm-shape]
[metabase.metabot.tools.util :as tools.u]
+ [metabase.models.serialization.resolve :as serdes.resolve]
+ [metabase.models.serialization.resolve.mp :as resolve.mp]
[metabase.util :as u]
+ [metabase.util.i18n :refer [tru]]
[metabase.util.json :as json]
[metabase.util.log :as log]
- [metabase.util.malli :as mu]))
+ [metabase.util.malli :as mu]
+ [toucan2.core :as t2]))
(set! *warn-on-reflection* true)
;;; ------------------------------------------------ Schema ------------------------------------------------
-(def ^:private source-entity-schema
- "Schema for source_entity — identifies the primary data source."
- [:map
- [:type [:enum "table" "model" "question" "metric"]]
- [:id :int]])
-
-(def construct-program-schema
- "Schema for the program parameter of construct_notebook_query.
- Intentionally loose — agent-lib validates and repairs internally."
- [:map
- [:source [:map
- [:type :string]
- [:id {:optional true} [:maybe :int]]
- [:ref {:optional true} [:maybe :string]]]]
- [:operations [:sequential [:sequential :any]]]])
-
(def ^:private construct-visualization-schema
[:map {:closed true}
[:chart_type :string]])
(def ^:private construct-notebook-query-args-schema
+ "Args schema for `construct_notebook_query`.
+
+ `:query` is a JSON object matching the canonical portable MBQL 5 wire format
+ ([[metabase.lib.schema/external-query]]). The structural shape (stages, clauses, portable
+ FKs, etc.) is documented for the LLM at
+ `resources/metabot/prompts/tools/construct_notebook_query.md`.
+
+ Validation against `::external-query` happens at the entry-point boundaries (HTTP defendpoint
+ via the string-transformer, `execute-representations-query` post-repair via
+ `lib.normalize/normalize ::lib.schema/query`); the args schema here only asserts `:query`
+ is map-shaped so the LLM-input forgiveness layer in repair has a chance to fix common
+ shortcuts (missing `{}` options, etc.). Per `repr-plan.md` step 13, this schema deliberately
+ omits `:source_entity` and `:referenced_entities` — the query body is self-describing."
[:map {:closed true}
[:reasoning {:optional true} :string]
- [:source_entity source-entity-schema]
- [:referenced_entities {:optional true} [:maybe [:sequential source-entity-schema]]]
- [:program construct-program-schema]
+ [:query :map]
[:visualization {:optional true} construct-visualization-schema]])
;;; ---------------------------------------- Source resolution ----------------------------------------
-(defn- resolve-source-database-id
- "Resolve the database ID for a source_entity."
- [{:keys [type id]}]
- (case type
- "table" (:db_id (tools.u/get-table id :db_id))
- ("model" "question") (:database_id (tools.u/get-card id))
- "metric" (:database_id (tools.u/get-card id))
- (throw (ex-info (str "Unsupported source_entity type: " type)
- {:agent-error? true :status-code 400}))))
-
-(defn- source-entity->model-str
- "Map source_entity type to the model string used by agent-lib evaluation context."
- [type]
- (case type
- "table" "table"
- "model" "dataset"
- "question" "card"
- "metric" "metric"
- type))
-
-(defn program-source->source-entity
- "Convert a structured-program `:source` map (using agent-lib model strings: `table`,
- `card`, `dataset`, `metric`) into the `source-entity` shape consumed by
- [[execute-program]] (using metabot type strings: `table`, `question`, `model`,
- `metric`). Throws if the source isn't one of the four database-resolved types
- (e.g. `context` or nested `program` sources are rejected)."
- [{:keys [type id] :as source}]
- (let [entity-type (case type
- "table" "table"
- "card" "question"
- "dataset" "model"
- "metric" "metric"
- (throw (ex-info (str "Unsupported program source type: " (pr-str type))
- {:agent-error? true
- :status-code 400
- :source source})))]
- {:type entity-type :id id}))
-
-(defn- source-metadata-for
- "Resolve the lib metadata object for a source entity."
- [type id metadata-provider]
- (case type
- "table" (lib.metadata/table metadata-provider id)
- ("model" "question") (lib.metadata/card metadata-provider id)
- "metric" (lib.metadata/card metadata-provider id)
- nil))
-
-(defn- surrounding-tables-for
- "Derive surrounding tables from a source query's visible columns."
- [metadata-provider source-metadata source-id]
- (try
- (let [query (lib/query metadata-provider source-metadata)]
- (->> (lib/visible-columns query)
- (keep :table-id)
- distinct
- (remove #{source-id})
- (mapv (fn [tid] {:id tid}))))
- (catch Exception _ [])))
-
-(defn- available-measure-ids
- "Return the set of measure IDs available on a source entity, or empty set."
- [metadata-provider source-metadata]
- (try
- (->> (lib/available-measures (lib/query metadata-provider source-metadata))
- (keep :id)
- set)
- (catch Exception _ #{})))
-
-(defn- build-evaluation-context
- "Build the EvaluationContext for agent-lib from source_entity and referenced_entities."
- [{:keys [type id]} referenced-entities metadata-provider]
- (let [model-str (source-entity->model-str type)
- source-metadata (source-metadata-for type id metadata-provider)
- surrounding (surrounding-tables-for metadata-provider source-metadata id)
- measure-ids (available-measure-ids metadata-provider source-metadata)]
- {:source-entity {:model model-str :id id}
- :referenced-entities (or (mapv (fn [{:keys [type id]}]
- {:model (source-entity->model-str type) :id id})
- referenced-entities)
- [])
- :surrounding-tables surrounding
- :measure-ids measure-ids
- :source-metadata source-metadata}))
+(defn- first-stage-source-table-fk
+ "Pull the portable `[db schema table]` FK out of `stages[0].source-table`, or `nil`
+ if not present / wrong shape."
+ [parsed-query]
+ (let [fk (get-in parsed-query ["stages" 0 "source-table"])]
+ (when (and (vector? fk)
+ (= 3 (count fk))
+ (string? (nth fk 0)))
+ fk)))
+
+(def ^:private metabase-uri-source-table-pattern
+ "Matches values the LLM sometimes writes into `source-table:` by confusing the Metabase
+ `metabase://<entity-type>/<id>` URIs (which appear in prompts as a way to read entities)
+ with a query source handle. Examples we've observed: `metabase://metric/76`,
+ `metabase://table/123`, `metabase://model/42`, `metabase://question/9`.
+
+ The regex is deliberately permissive — we catch anything starting with `metabase://` so
+ the error message is always the directive one instead of falling through to the generic
+ `:missing-source-in-first-stage` message."
+ #"^metabase://([^/]+)/(\d+)")
+
+(defn- detect-metabase-uri-source-table!
+ "If `stages[0].source-table` is a `metabase://<type>/<id>` URI string, throw a targeted
+ agent-error explaining how to use the referenced entity correctly (typically: the LLM
+ meant to reference a metric — metrics are aggregations, not sources — but wrote the URI
+ as a source). No-op on well-formed sources."
+ [parsed-query]
+ (let [raw (get-in parsed-query ["stages" 0 "source-table"])]
+ (when (string? raw)
+ (when-let [[_ entity-type entity-id] (re-find metabase-uri-source-table-pattern raw)]
+ (let [hint (case entity-type
+ "metric"
+ (str "Metrics are aggregations, not sources. To use metric " entity-id
+ ", put its `base_table_portable_fk` (from `entity_details` on the metric) "
+ "into `source-table:` and reference the metric as "
+ "`aggregation: [[metric, {}, \"<portable_entity_id>\"]]`.")
+ ("question" "model" "card")
+ (str "To reference saved " entity-type " " entity-id
+ " as a query source, put its `portable_entity_id` (a 21-char "
+ "string from `entity_details`) into `source-card:` — not a URI.")
+ "table"
+ (str "Use the portable FK `[<db-name>, <schema>, <table-name>]` from "
+ "`entity_details` in `source-table:` — not a URI.")
+ (str "`source-table:` accepts a portable FK `[<db-name>, <schema>, <table-name>]` "
+ "or, via `source-card:`, a saved-card `portable_entity_id`."))]
+ (throw (ex-info (tru "`source-table:` does not accept URIs like `{0}`. {1}"
+ raw hint)
+ {:agent-error? true
+ :status-code 400
+ :error :uri-in-source-table
+ :source-table raw
+ :entity-type entity-type
+ :entity-id entity-id})))))))
+
+(defn- first-stage-source-card-eid
+ "Pull the `source-card:` entity_id string from `stages[0]`, or `nil` if not present."
+ [parsed-query]
+ (let [eid (get-in parsed-query ["stages" 0 "source-card"])]
+ (when (string? eid) eid)))
+
+(def ^:private permission-aware-content-store
+ "ContentStore for agent query construction. Alias for
+ [[shared.content-store/default-store]] — the chokepoint wrapper applies `api/read-check` to
+ every lookup whenever `api/*current-user-id*` is bound, symmetrically across all five
+ ContentStore methods. The unchecked underlying store gates non-NanoID entity-id values to
+ avoid a full-table scan via `find-by-identity-hash`."
+ shared.content-store/default-store)
+
+(defn- check-first-stage-source-table-query-permissions!
+ "Ensure the current user can query the table named by `stages[0].source-table`.
+
+ The metadata provider intentionally exposes database metadata without applying user data
+ permissions. Before any repair pass can inspect fields/FKs on the requested source table,
+ resolve the portable table FK and run the normal API query permission check."
+ [metadata-provider parsed-query]
+ (when-let [table-fk (first-stage-source-table-fk parsed-query)]
+ (let [resolver (resolve.mp/import-resolver metadata-provider permission-aware-content-store)
+ table-id (serdes.resolve/import-table-fk resolver table-fk)]
+ (api/query-check :model/Table table-id)
+ nil)))
+
+(defn resolve-database-id-from-first-stage
+ "Resolve the application database id from the first stage's source.
+
+ Public only so tests can stub it. Strategy:
+
+ * If `stages[0].source-table` is a portable FK `[db schema table]`, look up the database
+ by that `db` name. Unknown / ambiguous names surface `:unknown-database` / `:ambiguous-database-name`
+ agent-errors.
+ * Otherwise, if `stages[0].source-card` is an entity_id string, look up the card by entity_id
+ and use its `:database_id`. Unknown entity_id surfaces `:unknown-card`.
+ * Otherwise, surface `:missing-source-in-first-stage`.
+
+ All error paths are raised with `:agent-error? true` so the tool wrapper can relay a clean
+ message to the LLM instead of a stack trace.
+
+ Note: the `database:` field at the top level of the query is intentionally NOT consulted.
+ It's a spec-mandated but redundant field (the source already identifies the database); a
+ repair pass stamps it after we've resolved the id via this function. See `repr-plan.md`
+ step 14 follow-up."
+ [parsed-query]
+ (detect-metabase-uri-source-table! parsed-query)
+ (if-let [table-fk (first-stage-source-table-fk parsed-query)]
+ (let [db-name (nth table-fk 0)
+ ids (t2/select-pks-vec :model/Database :name db-name)]
+ (case (count ids)
+ 0 (throw (ex-info (tru (str "Unknown database: `{0}`. Use the exact database name as "
+ "reported by `entity_details` / metadata tools (it appears "
+ "as the first element of every portable FK, e.g. "
+ "`source-table: [<db-name>, <schema>, <table>]`).")
+ db-name)
+ {:agent-error? true
+ :status-code 400
+ :error :unknown-database
+ :database db-name}))
+ 1 (first ids)
+ (throw (ex-info (tru (str "Multiple databases share the name `{0}` (ids: {1}). The "
+ "agent has no way to disambiguate; ask the user to rename "
+ "one of the databases or use a more specific identifier.")
+ db-name (pr-str (vec (sort ids))))
+ {:agent-error? true
+ :status-code 400
+ :error :ambiguous-database-name
+ :database db-name
+ :database-ids (vec (sort ids))}))))
+ (if-let [eid (first-stage-source-card-eid parsed-query)]
+ (if-let [card (tools.u/get-card-by-entity-id eid)]
+ (:database_id card)
+ (throw (ex-info (tru (str "No saved question or model found with entity_id {0}. Do not invent "
+ "or guess entity_ids: call `entity_details` with `entity-type: question` "
+ "or `entity-type: model` and the card''s numeric id first, then copy the "
+ "exact `portable_entity_id` from the response into `source-card:`.")
+ (pr-str eid))
+ {:agent-error? true
+ :status-code 400
+ :error :unknown-card
+ :entity-id eid})))
+ (throw (ex-info (tru (str "First stage must have either `source-table:` (as a portable FK "
+ "`[<db-name>, <schema>, <table>]`) or `source-card:` (as an "
+ "entity_id string). Neither was found in `stages[0]`."))
+ {:agent-error? true
+ :status-code 400
+ :error :missing-source-in-first-stage})))))
;;; ---------------------------------------- Result columns ----------------------------------------
@@ -146,20 +208,96 @@
;;; ---------------------------------------- Query execution ----------------------------------------
-(defn execute-program
- "Execute a structured program via agent-lib.
- Returns the raw result map with :structured-output.
- Shared between construct-notebook-query-tool and slackbot-construct-notebook-query-tool."
- [source-entity referenced-entities program]
- (let [database-id (resolve-source-database-id source-entity)
- mp (lib-be/application-database-metadata-provider database-id)
- context (build-evaluation-context source-entity referenced-entities mp)
- mbql5-query (agent-lib/evaluate-program program mp context)
- query-id (u/generate-nano-id)]
- {:structured-output {:query-id query-id
- :query mbql5-query
- :result-columns (result-columns-for-query mbql5-query mp)}
- :instructions (instructions/query-created-instructions-for query-id)}))
+(defn- as-agent-input-error
+ "Wrap `e` as an agent-input error.
+
+ Tool callers look at `:agent-error?` to decide whether to relay the message to the LLM.
+ HTTP callers additionally need a status code; default representation/repair failures to
+ 400 so individual repair passes don't all have to repeat `:status-code 400` in ex-data.
+ Existing statuses are preserved (notably permission 403s, which callers should normally
+ avoid wrapping in the first place)."
+ [^clojure.lang.ExceptionInfo e]
+ (let [base (assoc (or (ex-data e) {}) :agent-error? true)
+ data (cond-> base
+ (nil? (:status-code base)) (assoc :status-code 400))]
+ (ex-info (ex-message e) data e)))
+
+(defn execute-representations-query
+ "Execute a notebook query in the canonical portable MBQL 5 representations format.
+
+ `external-query` is a keyword-keyed Clojure map matching [[metabase.lib.schema/external-query]]
+ — what the JSON middleware decodes from the HTTP body, or what the MCP tool layer hands in
+ after schema-coercion. Strict shape validation against `::external-query` is the
+ responsibility of the entry-point (defendpoint / mu/defn) — this function trusts the input
+ shape and concentrates on the LLM-friendly repair passes.
+
+ Pipeline:
+ 1. Boundary-validate the keyword-keyed input against `::lib.schema/external-query`
+ ([[repr/validate-external-query]]). Catches structural issues — missing `stages`,
+ typo'd stage keys (e.g. `aggreagation` vs `aggregation`), wrong top-level `lib/type`,
+ etc. — that the loose `:map` wire schema doesn't catch.
+ 2. Convert to the string-keyed portable form the repair pipeline operates on.
+ 3. Resolve the database id from the first stage's `source-table:` / `source-card:`
+ ([[resolve-database-id-from-first-stage]]) and build an application-DB-backed
+ `MetadataProvider`.
+ 4. Run the repair pass (fill in `{}` options, missing `lib/type` markers, stamp the
+ top-level `database:`, auto-wire `source-field` for implicit joins, rewrite inline
+ `order-by` aggregations to refs, etc.).
+ 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 the
+ metadata-provider.
+ 7. Export that final numeric pMBQL back to the portable form for the LLM-facing
+ `:query-json` / `query-content` output.
+
+ Returns a map with `:structured-output` and `:instructions` keys. Throws with an
+ `:agent-error?` ex-data flag when the LLM input is invalid, so the outer tool wrapper can
+ surface a helpful message to the LLM without a stack trace.
+
+ Per `repr-plan.md` step 13, there is no `source_entity` parameter — the query body carries
+ everything needed. Per the step-14 follow-up, there is also no top-level `database:` in the
+ LLM-facing contract: the database is derived from the first stage's source, and a repair
+ pass stamps `database:` into the portable form before lib.schema / resolve need it."
+ [external-query]
+ (let [parsed (try
+ ;; Step 1 — convert to the string-keyed portable form the repair pipeline
+ ;; operates on.
+ ;; Step 2 — boundary check that every stage's top-level keys are known.
+ ;; Catches LLM-authored typos (e.g. `aggreagation` for `aggregation`)
+ ;; that `lib.schema` does not enforce — `::lib.schema.mbql-stage/mbql` is
+ ;; not a closed map, so unknown stage keys would otherwise be silently
+ ;; dropped at resolve / lib.normalize time.
+ (let [portable (repr/external-query->portable external-query)]
+ (repr/assert-known-stage-keys! portable)
+ portable)
+ (catch clojure.lang.ExceptionInfo e
+ (throw (as-agent-input-error e))))
+ database-id (resolve-database-id-from-first-stage parsed)
+ mp (lib-be/application-database-metadata-provider database-id)]
+ ;; Permission checks happen before repair/resolve so the metadata-provider-backed pipeline
+ ;; never inspects table/card metadata that the current user cannot use.
+ (check-first-stage-source-table-query-permissions! mp parsed)
+ ;; Everything after the MP is built can surface LLM-input errors (lib.schema validation
+ ;; in resolve, missing-column complaints from lib/query in `result-columns-for-query`,
+ ;; etc.). Wrap the whole rest of the pipeline in a single `:agent-error?` relay so any of
+ ;; them reach the tool wrapper with the flag set.
+ (try
+ (let [repaired (repr.repair/repair mp parsed permission-aware-content-store)
+ _validated (repr/validate-query repaired)
+ pmbql-query (repr.resolve/resolve-query mp repaired permission-aware-content-store)
+ exported-repr (repr.resolve/export-query mp pmbql-query permission-aware-content-store)
+ _validated' (repr/validate-query exported-repr)
+ query-id (u/generate-nano-id)]
+ {:structured-output {:query-id query-id
+ :query pmbql-query
+ :query-json exported-repr
+ :result-columns (result-columns-for-query pmbql-query mp)}
+ :instructions (instructions/query-created-instructions-for query-id)})
+ (catch clojure.lang.ExceptionInfo e
+ ;; Permission failures are not LLM-input repair errors. Preserve the original 403 so
+ ;; HTTP callers get the standard forbidden response instead of an agent-error payload.
+ (if (= 403 (:status-code (ex-data e)))
+ (throw e)
+ (throw (as-agent-input-error e)))))))
;;; ---------------------------------------- Chart helpers ----------------------------------------
@@ -170,24 +308,42 @@
(string? chart-type) (keyword chart-type)
:else chart-type))
+(defn- query-json->llm-content
+ "Render the portable repr-form `query-json` map as the JSON code block embedded inside
+ `<query>` for the LLM. The wire format is `::lib.schema/external-query` JSON; we serialize
+ with pretty-printing and a triple-backtick fence so the LLM sees the same syntactic frame it
+ would in a tool description or assistant turn."
+ [query-json]
+ (when (map? query-json)
+ (str "```json\n"
+ (json/encode query-json {:pretty true})
+ "\n```")))
+
(defn- structured->query-data
- "Convert tool structured output to a map suitable for [[llm-rep/query->xml]].
- Converts the MBQL 5 query to legacy MBQL, JSON-encodes it, and wraps result columns."
- [{:keys [query-id query result-columns]}]
+ "Convert tool structured output to a map suitable for [[llm-shape/query->xml]].
+
+ `:query-content` is the **canonical portable representations JSON** for the final pMBQL
+ query we actually constructed: repaired and resolved to numeric IDs, normalized by lib,
+ then exported back to portable FK paths/entity_ids. By feeding the LLM this final portable
+ form (rather than legacy-MBQL JSON or a pre-resolve approximation) on the next turn it can
+ reference exactly the field paths and aggregation UUIDs that will execute.
+
+ See repr-plan.md step 18."
+ [{:keys [query-id query query-json result-columns]}]
(let [legacy-query (when (and (map? query) (:lib/type query))
#_{:clj-kondo/ignore [:discouraged-var]}
(lib/->legacy-MBQL query))]
{:query-type "notebook"
:query-id query-id
:database_id (:database legacy-query)
- :query-content (when legacy-query (json/encode legacy-query))
+ :query-content (query-json->llm-content query-json)
:result (when (seq result-columns)
{:result_columns result-columns})}))
(defn- structured->chart-xml
"Render the full chart XML for the construct_notebook_query tool result."
[structured chart-id chart-type]
- (llm-rep/visualization->xml
+ (llm-shape/visualization->xml
{:chart-id chart-id
:queries [(structured->query-data structured)]
:visualization_settings {:chart_type (if chart-type (name chart-type) "table")}}))
@@ -197,15 +353,16 @@
(mu/defn ^{:tool-name "construct_notebook_query"
:scope scope/agent-notebook-create}
construct-notebook-query-tool
- "Construct and visualize a notebook query from a metric, model, or table."
- [{:keys [_reasoning source_entity referenced_entities program visualization]} :- construct-notebook-query-args-schema]
+ "Construct and visualize a notebook query from a metric, model, or table.
+
+ Accepts an MBQL 5 query as a JSON object matching `::lib.schema/external-query`. See
+ `resources/metabot/prompts/tools/construct_notebook_query.md` for the prompt contract."
+ [{:keys [_reasoning query visualization]} :- construct-notebook-query-args-schema]
(try
- (let [;; LLM sometimes nests visualization inside program — pull it out
- effective-viz (or visualization (:visualization program))
- normalized-visualization (some-> effective-viz (update-keys (comp keyword u/->kebab-case-en name)))
+ (let [normalized-visualization (some-> visualization (update-keys (comp keyword u/->kebab-case-en name)))
chart-type (or (chart-type->keyword (:chart-type normalized-visualization))
:table)
- query-result (execute-program source_entity referenced_entities (dissoc program :visualization))
+ query-result (execute-representations-query query)
structured (or (:structured-output query-result) (:structured_output query-result))]
(if (and structured (:query-id structured) (:query structured))
(let [chart-result (create-chart-tools/create-chart
@@ -236,14 +393,21 @@
:instructions instruction-text})
;; query-result may already have :output (error) or only :structured-output
(if-let [s (or (:structured-output query-result) (:structured_output query-result))]
- (let [query-xml (llm-rep/query->xml (structured->query-data s))
+ (let [query-xml (llm-shape/query->xml (structured->query-data s))
instruction-text (instructions/query-created-instructions-for (:query-id s))]
(assoc query-result
:output (str "<result>\n" query-xml "\n</result>\n"
"<instructions>\n" instruction-text "\n</instructions>")))
query-result)))
(catch Exception e
- (log/error e "Failed to construct notebook query")
(if (:agent-error? (ex-data e))
- {:output (ex-message e)}
- {:output (str "Failed to construct notebook query: " (or (ex-message e) "Unknown error"))}))))
+ ;; Expected agent-facing signal (bad LLM input: unknown table, unknown schema,
+ ;; URI-in-source-table, …). Log at debug only — no stacktrace — since the message
+ ;; is the tool's result and the LLM is expected to self-correct on the next turn.
+ (do
+ (log/debug e "construct_notebook_query returned agent-error to the LLM")
+ {:output (ex-message e)})
+ ;; Genuine unexpected failure — keep full stacktrace.
+ (do
+ (log/error e "Failed to construct notebook query")
+ {:output (str "Failed to construct notebook query: " (or (ex-message e) "Unknown error"))})))))
diff --git a/src/metabase/metabot/tools/document.clj b/src/metabase/metabot/tools/document.clj
index 12ee246843d..c4f0e8a027a 100644
--- a/src/metabase/metabot/tools/document.clj
+++ b/src/metabase/metabot/tools/document.clj
@@ -180,11 +180,16 @@
{:output (str "Failed to construct SQL chart draft: " (or (ex-message e) "Unknown error"))}))))
(def ^:private model-chart-schema
+ "Schema for `document_construct_model_chart`. Mirrors `construct_notebook_query`'s
+ representations format: `:query` is a YAML string in MBQL 5 representations format.
+
+ Per `repr-plan.md` step 13, `:source_entity` is no longer part of the contract — the YAML
+ query is self-describing (carries `database:` at the top level and full portable FK paths
+ everywhere else)."
[:map {:closed true}
[:name :string]
[:description :string]
- [:source_entity [:map [:type :string] [:id :int]]]
- [:program :map]
+ [:query :string]
[:viz_settings [:map {:closed true}
[:chart_type chart-type-enum]]]])
@@ -192,12 +197,11 @@
:scope scope/agent-document-create}
document-construct-model-chart-tool
"Construct notebook/model-backed chart draft payload for document insertion."
- [{:keys [name description source_entity program viz_settings]} :- model-chart-schema]
+ [{:keys [name description query viz_settings]} :- model-chart-schema]
(try
(let [chart-type (get viz_settings :chart_type)
result (construct-tools/construct-notebook-query-tool
- {:source_entity source_entity
- :program program
+ {:query query
:visualization {:chart_type chart-type}})
structured (or (:structured-output result) (:structured_output result))
query-id (:query-id structured)
diff --git a/src/metabase/metabot/tools/entity_details.clj b/src/metabase/metabot/tools/entity_details.clj
index 0ce00eaf1dc..3f1651977ea 100644
--- a/src/metabase/metabot/tools/entity_details.clj
+++ b/src/metabase/metabot/tools/entity_details.clj
@@ -1,6 +1,7 @@
(ns metabase.metabot.tools.entity-details
(:require
[medley.core :as m]
+ [metabase.agent-lib.representations.resolve :as repr.resolve]
[metabase.api.common :as api]
[metabase.documents.core :as documents]
[metabase.lib-be.core :as lib-be]
@@ -8,6 +9,7 @@
[metabase.lib.metadata :as lib.metadata]
[metabase.lib.types.isa :as lib.types.isa]
[metabase.metabot.config :as metabot.config]
+ [metabase.metabot.tools.shared.content-store :as shared.content-store]
[metabase.metabot.tools.util :as metabot.tools.u]
[metabase.parameters.field-values :as params.field-values]
[metabase.util :as u]
@@ -18,12 +20,38 @@
(set! *warn-on-reflection* true)
+(defn- entity-id-for-measure-or-segment
+ "Look up the portable `entity_id` for a measure or segment by numeric id. The lib metadata
+ view of measures and segments doesn't carry `:entity-id`, so we hit the app DB directly.
+ `model-key` is `:model/Measure` or `:model/Segment`."
+ [model-key id]
+ (when id
+ (t2/select-one-fn :entity_id model-key :id id)))
+
(defn- convert-measure-or-segment
"Convert a measure or segment metadata object to the format expected by the API.
- `definition-key` is `:aggregation` for measures and `:filters` for segments."
+ `definition-key` is `:aggregation` for measures and `:filters` for segments.
+
+ `:definition` on the result is the portable representations form of the relevant inner
+ clause array (a vector of one aggregation clause for measures, a vector of one or more
+ filter clauses for segments). `:portable-entity-id` is the 21-char NanoID the agent can
+ paste verbatim into a `[measure, {}, <pid>]` / `[segment, {}, <pid>]` clause — this is
+ the preferred form when the agent wants to use the measure/segment as-is. The
+ `:definition` array remains useful when the agent wants to compose on top of it (e.g.
+ add an extra filter that the segment doesn't include). See
+ `resources/metabot/prompts/tools/construct_notebook_query.md`."
[metadata definition-key]
- (let [definition (:definition metadata)]
+ (let [definition (:definition metadata)
+ model-key (case definition-key
+ :aggregation :model/Measure
+ :filters :model/Segment)
+ ;; Lib-metadata maps reject snake_case lookups (snake-hating-map). Try kebab first;
+ ;; fall back to a direct t2 lookup since the lib metadata view doesn't include
+ ;; `:entity-id` for measures/segments (verified via REPL — only cards include it).
+ entity-id (or (:entity-id metadata)
+ (entity-id-for-measure-or-segment model-key (:id metadata)))]
(-> (select-keys metadata [:id :name :display-name :description])
+ (assoc :portable-entity-id entity-id)
(assoc :definition-description
(when definition
(try
@@ -32,8 +60,13 @@
(assoc :definition
(when definition
(try
- (lib/prepare-for-serialization definition)
- (catch Exception _ nil)))))))
+ (let [mp (lib-be/application-database-metadata-provider (:database definition))
+ exported (repr.resolve/export-query mp definition shared.content-store/default-store)]
+ (get-in exported ["stages" 0 (name definition-key)]))
+ (catch Exception e
+ (log/warn e "Failed to export measure/segment definition to portable form"
+ {:id (:id metadata) :key definition-key})
+ nil)))))))
(defn verified-review?
"Return true if the most recent ModerationReview for the given item id/type is verified."
@@ -120,6 +153,32 @@
with-queryable-dimensions? true
with-segments? false}}]
(let [id (:id card)
+ ;; Database metadata so the LLM can build portable FKs — metrics are always
+ ;; referenced from a query targeting a specific database, and the LLM needs the
+ ;; human-readable database name for `source-table:` / field FKs in the same stage.
+ database (lib.metadata/database metadata-provider)
+ database-id (:id database)
+ database-name (:name database)
+ ;; Base table of the metric — the metric is an aggregation defined on top of a
+ ;; specific table. To use the metric, the LLM has to put that table in
+ ;; `source-table:` and reference the metric in `aggregation:`.
+ ;;
+ ;; This arity is called with two shapes of `card`:
+ ;; 1. The t2 row from `get-card` (via the single-arg `metric-details`) —
+ ;; snake_case, so `:table_id`.
+ ;; 2. A `lib.metadata/card` map forwarded by `convert-metric` (called from
+ ;; `table-details` while listing available metrics) — that map is a
+ ;; `SnakeHatingMap`, so the only valid key is kebab-case `:table-id`; reading
+ ;; `:table_id` on it throws a deprecation-error that would surface to the LLM
+ ;; as an empty `<resource>` with just `**Error: ...**`.
+ ;; We accept both. `report_card.table_id` / metadata `:table-id` already points
+ ;; to the metric's base table and is kept in sync, so we use it verbatim instead
+ ;; of digging through `:dataset_query`.
+ source-table-id (or (:table-id card) (:table_id card))
+ source-table (when source-table-id
+ (lib.metadata/table metadata-provider source-table-id))
+ base-table-portable-fk (when (and database-name source-table)
+ [database-name (:schema source-table) (:name source-table)])
query-needed? (or with-default-temporal-breakout? with-queryable-dimensions? with-segments?)
metric-query (when query-needed?
(lib/query metadata-provider (lib.metadata/card metadata-provider id)))
@@ -138,6 +197,19 @@
:type :metric
:name (:name card)
:description (:description card)
+ ;; Database identity — same shape as in `table-details` / `card-details`.
+ :database_id database-id
+ :database_name database-name
+ ;; Base table the metric aggregates. The LLM uses `:base_table_portable_fk`
+ ;; verbatim as `source-table:` in the query that consumes the metric.
+ :base_table_id source-table-id
+ :base_table_name (:name source-table)
+ :base_table_portable_fk base-table-portable-fk
+ ;; Portable entity id — the string the LLM must copy verbatim into a
+ ;; `[metric, {}, <entity_id>]` aggregation clause to reference this metric.
+ ;; Accept both shapes (see `source-table-id` note above): t2 rows use
+ ;; `:entity_id`, `lib.metadata/card` maps use `:entity-id`.
+ :portable_entity_id (or (:entity-id card) (:entity_id card))
:default_time_dimension_field_id (some-> default-temporal-breakout
(->> (metabot.tools.u/->result-column metric-query))
:field_id)
@@ -160,7 +232,11 @@
([db-metric metadata-provider options]
(-> db-metric
(metric-details metadata-provider (assoc options :with-queryable-dimensions? false))
- (select-keys [:id :type :name :description :default_time_dimension_field_id]))))
+ ;; Keep the DB-name / base-table-fk / portable_entity_id fields so callers (incl.
+ ;; `metric->xml`) can surface them to the LLM without a second round-trip.
+ (select-keys [:id :type :name :description :default_time_dimension_field_id
+ :database_id :database_name :portable_entity_id
+ :base_table_id :base_table_name :base_table_portable_fk]))))
(declare related-tables)
@@ -180,10 +256,14 @@
(metabot.tools.u/get-table id :db_id :description :name :schema))]
(let [query-needed? (or with-fields? with-related-tables? with-metrics? with-measures? with-segments?)
db-id (if metadata-provider (:db-id base) (:db_id base))
- db-engine (some-> (if metadata-provider
- (lib.metadata/database metadata-provider)
- (metabot.tools.u/get-database db-id :engine))
- :engine name)
+ ;; Database metadata including :name so LLM can build portable FK paths
+ ;; [db-name, schema, table] / [db-name, schema, table, field] that the
+ ;; representations-format construct_notebook_query expects.
+ db (if metadata-provider
+ (lib.metadata/database metadata-provider)
+ (metabot.tools.u/get-database db-id :engine :name))
+ db-engine (some-> db :engine name)
+ db-name (:name db)
mp (when query-needed?
(or metadata-provider
(lib-be/application-database-metadata-provider db-id)))
@@ -203,8 +283,12 @@
:display_name (some->> (:name base)
(u.humanization/name->human-readable-name :simple))
:database_id db-id
+ :database_name db-name
:database_engine db-engine
- :database_schema (:schema base)}
+ :database_schema (:schema base)
+ ;; Portable table FK path matching the representations-format expectation:
+ ;; [db-name, schema-or-null, table-name]. LLM uses this as `source-table`.
+ :portable_fk (when db-name [db-name (:schema base) (:name base)])}
(m/assoc-some :description (:description base)
:related_tables related-tables
:metrics (when with-metrics?
@@ -254,7 +338,9 @@
:as options}]
(let [id (:id base)
database-id (:database_id base)
- database-engine (some-> (lib.metadata/database metadata-provider) :engine name)
+ database (lib.metadata/database metadata-provider)
+ database-engine (some-> database :engine name)
+ database-name (:name database)
card-metadata (lib.metadata/card metadata-provider id)
dataset-query (get card-metadata :dataset-query)
query-needed? (or with-fields? with-related-tables? with-metrics? with-measures? with-segments?)
@@ -278,10 +364,38 @@
:display_name (some->> (:name base)
(u.humanization/name->human-readable-name :simple))
:database_id database-id
+ :database_name database-name
:database_engine database-engine
+ ;; Portable entity id matching the representations-format expectation: LLM uses this
+ ;; string as the value of `source-card:` in a representations query stage.
+ :portable_entity_id (:entity_id base)
:verified (verified-review? id "card")}
(m/assoc-some
:description (:description base)
+ ;; Portable representations JSON for the card's **own** saved query body.
+ ;;
+ ;; We deliberately export `dataset-query` (the real, normalised MBQL/legacy body
+ ;; of the card) rather than `card-query`. `lib/query metadata-provider
+ ;; card-metadata` wraps the card as `{source-card: <eid>}` for downstream
+ ;; querying, which is the right thing for column resolution / metrics, but the
+ ;; wrong thing for showing the LLM what the card *actually does*: it would just
+ ;; round-trip back to a one-stage `source-card:` reference.
+ ;;
+ ;; Surfaces the **same** form the LLM writes into `construct_notebook_query`
+ ;; (and gets back in that tool's result), so existing-card payloads and
+ ;; freshly-built-query payloads share one shape. Works for both structured
+ ;; (`mbql.stage/mbql`) and native (`mbql.stage/native`) cards - the latter
+ ;; preserves portable `card-id` / `snippet-id` references inside
+ ;; `template-tags`.
+ ;;
+ ;; Returns `nil` (so `m/assoc-some` drops the key) for cards whose
+ ;; `dataset_query` can't be exported, e.g. unusual / partially-broken legacy
+ ;; queries; the rest of the payload is still useful.
+ :query_json (when dataset-query
+ (repr.resolve/try-export-query
+ metadata-provider
+ (lib/query metadata-provider (lib-be/normalize-query dataset-query))
+ shared.content-store/default-store))
:related_tables related-tables
:metrics (when with-metrics?
(not-empty (mapv #(convert-metric % metadata-provider options)
@@ -403,7 +517,11 @@
mp (lib-be/application-database-metadata-provider (:database_id card))
details (card-details card mp options)]
(-> details
- (select-keys [:id :type :description :name :verified])
+ ;; `:query_json` is intentionally part of the slim payload here:
+ ;; it's what `question->xml` renders inside `<metabase_question>`
+ ;; so the LLM sees the saved card's body in the same portable
+ ;; representations JSON form `construct_notebook_query` consumes.
+ (select-keys [:id :type :description :name :verified :query_json])
(assoc :result-columns (:fields details))
(m/assoc-some :average_query_time (:average_query_time card)
:display (:display card))))
diff --git a/src/metabase/metabot/tools/metadata.clj b/src/metabase/metabot/tools/metadata.clj
index f10c0d412c1..b8f2460f428 100644
--- a/src/metabase/metabot/tools/metadata.clj
+++ b/src/metabase/metabot/tools/metadata.clj
@@ -8,7 +8,7 @@
[metabase.metabot.tools.field-stats :as field-stats-tools]
[metabase.metabot.tools.shared :as shared]
[metabase.metabot.tools.shared.instructions :as instructions]
- [metabase.metabot.tools.shared.llm-representations :as llm-rep]
+ [metabase.metabot.tools.shared.llm-shape :as llm-shape]
[metabase.util.i18n :refer [tru]]
[metabase.util.log :as log]
[metabase.util.malli :as mu]))
@@ -112,23 +112,23 @@
[{:keys [metrics models]}]
(let [content (str (when (seq metrics)
(str "<metrics>\n"
- (str/join "\n" (map llm-rep/metric->xml metrics))
+ (str/join "\n" (map llm-shape/metric->xml metrics))
"\n</metrics>\n"))
(when (seq models)
(str "<metabase-models>\n"
- (str/join "\n" (map llm-rep/model->xml models))
+ (str/join "\n" (map llm-shape/model->xml models))
"\n</metabase-models>")))]
(format-with-instructions content instructions/answer-sources-instructions)))
(defn- format-metadata-output
[structured]
- (llm-rep/get-metadata-result->xml structured))
+ (llm-shape/get-metadata-result->xml structured))
(defn- format-field-metadata-output
;; NOTE: keep in sync with read_resource.clj/format-content :field-metadata branch
[{:keys [field_id value_metadata]}]
(format-with-instructions
- (llm-rep/field-metadata->xml {:field_id field_id :value_metadata value_metadata})
+ (llm-shape/field-metadata->xml {:field_id field_id :value_metadata value_metadata})
instructions/field-metadata-instructions))
(defn- add-output
diff --git a/src/metabase/metabot/tools/resources.clj b/src/metabase/metabot/tools/resources.clj
index 53382b12d0a..797bc34a2ec 100644
--- a/src/metabase/metabot/tools/resources.clj
+++ b/src/metabase/metabot/tools/resources.clj
@@ -58,7 +58,7 @@
[metabase.metabot.tools.entity-details :as entity-details]
[metabase.metabot.tools.field-stats :as field-stats]
[metabase.metabot.tools.shared.instructions :as instructions]
- [metabase.metabot.tools.shared.llm-representations :as llm-rep]
+ [metabase.metabot.tools.shared.llm-shape :as llm-shape]
[metabase.models.interface :as mi]
[metabase.transforms.core :as transforms]
[metabase.util.log :as log]
@@ -151,7 +151,7 @@
:name name
:engine (some-> engine clojure.core/name)
:description description
- :uri (llm-rep/metabase-uri :database id)})
+ :uri (llm-shape/metabase-uri :database id)})
(defn- present-collection
"Trim a collection row to an item map. `path-name` may be supplied if the caller pre-computed it."
@@ -165,7 +165,7 @@
:authority_level authority_level
:is_personal (boolean personal_owner_id)
:description description
- :uri (llm-rep/metabase-uri :collection id)}))
+ :uri (llm-shape/metabase-uri :collection id)}))
(defn- present-table
[{:keys [id name display_name schema db_id description]}]
@@ -176,7 +176,7 @@
:schema schema
:database_id db_id
:description description
- :uri (llm-rep/metabase-uri :table id)})
+ :uri (llm-shape/metabase-uri :table id)})
(defn- present-card
"Cards (questions or models) — :type on a Card is :question / :model / :metric."
@@ -193,7 +193,7 @@
:database_id database_id
:table_id table_id
:description description
- :uri (llm-rep/metabase-uri (keyword model-type) id)}))
+ :uri (llm-shape/metabase-uri (keyword model-type) id)}))
(defn- present-dashboard
[{:keys [id name collection_id description]}]
@@ -202,7 +202,7 @@
:name name
:collection_id collection_id
:description description
- :uri (llm-rep/metabase-uri :dashboard id)})
+ :uri (llm-shape/metabase-uri :dashboard id)})
(defn- present-transform
[{:keys [id name description source_database_id]}]
@@ -211,7 +211,7 @@
:name name
:database_id source_database_id
:description description
- :uri (llm-rep/metabase-uri :transform id)})
+ :uri (llm-shape/metabase-uri :transform id)})
(defn- present-source-card
"Resolve a source-card id to a typed item map (model / metric / question)."
@@ -223,7 +223,7 @@
"question")]
{:type src-type
:id source-card-id
- :uri (llm-rep/metabase-uri (keyword src-type) source-card-id)}))
+ :uri (llm-shape/metabase-uri (keyword src-type) source-card-id)}))
;; ----- Lineage helpers -----
@@ -233,10 +233,10 @@
(cond-> []
database_id (conj {:type "database"
:id database_id
- :uri (llm-rep/metabase-uri :database database_id)})
+ :uri (llm-shape/metabase-uri :database database_id)})
table_id (conj {:type "table"
:id table_id
- :uri (llm-rep/metabase-uri :table table_id)})
+ :uri (llm-shape/metabase-uri :table table_id)})
source_card_id (conj (present-source-card source_card_id))))
(defn- transform-source-table-ids
@@ -296,7 +296,7 @@
:id id
:name name
:timestamp timestamp
- :uri (llm-rep/metabase-uri (keyword type) id)}))
+ :uri (llm-shape/metabase-uri (keyword type) id)}))
recents)]
(list-result :recent-items items)))
@@ -344,7 +344,7 @@
{:type "schema"
:name s
:database_id db-id
- :uri (llm-rep/metabase-uri :database db-id "schemas" s "tables")})))]
+ :uri (llm-shape/metabase-uri :database db-id "schemas" s "tables")})))]
(list-result :database-schemas schemas)))
(defn- fetch-database-schema-tables [id-str schema-name]
@@ -508,7 +508,7 @@
items (cond-> []
db-id (conj {:type "database"
:id db-id
- :uri (llm-rep/metabase-uri :database db-id)})
+ :uri (llm-shape/metabase-uri :database db-id)})
source-tables (into source-tables))]
(list-result :transform-sources items)))
@@ -524,7 +524,7 @@
items (cond-> []
db-id (conj {:type "database"
:id db-id
- :uri (llm-rep/metabase-uri :database db-id)})
+ :uri (llm-shape/metabase-uri :database db-id)})
target-table (conj (present-table target-table)))]
(list-result :transform-target items)))
@@ -637,20 +637,20 @@
(defn- format-content
"Format a tool result as an LLM-ready string.
- Dispatches to the right llm-rep formatter based on :result-type.
+ Dispatches to the right llm-shape formatter based on :result-type.
Returns the :output string directly for error results (404s etc.)."
[content]
(if-let [structured (:structured-output content)]
(case (:result-type structured)
;; NOTE: keep in sync with agent/tools/metadata.clj/format-field-metadata-output
:field-metadata (format-with-instructions
- (llm-rep/field-metadata->xml structured)
+ (llm-shape/field-metadata->xml structured)
instructions/field-metadata-instructions)
- :entity (llm-rep/entity->xml structured)
- :metabot-list (llm-rep/metabot-list->xml structured)
- :metabot-entity (llm-rep/metabot-entity->xml structured)
+ :entity (llm-shape/entity->xml structured)
+ :metabot-list (llm-shape/metabot-list->xml structured)
+ :metabot-entity (llm-shape/metabot-entity->xml structured)
;; fallback — should not happen, but better than EDN
- (llm-rep/entity->xml structured))
+ (llm-shape/entity->xml structured))
;; error case — :output is already a string
(:formatted content)))
diff --git a/src/metabase/metabot/tools/search.clj b/src/metabase/metabot/tools/search.clj
index 3172bb4a04f..c561d891e9d 100644
--- a/src/metabase/metabot/tools/search.clj
+++ b/src/metabase/metabot/tools/search.clj
@@ -10,7 +10,7 @@
[metabase.metabot.tmpl :as te]
[metabase.metabot.tools.shared :as shared]
[metabase.metabot.tools.shared.instructions :as instructions]
- [metabase.metabot.tools.shared.llm-representations :as llm-rep]
+ [metabase.metabot.tools.shared.llm-shape :as llm-shape]
[metabase.permissions.core :as perms]
[metabase.search.core :as search]
[metabase.search.engine :as search.engine]
@@ -75,13 +75,78 @@
(update r :collection m/assoc-some :description (get descriptions cid))))))))
(defn- enrich-with-database-engines
- "Fetch and merge database engine info for search results that have database IDs."
+ "Fetch and merge database engine + name info for search results that have database IDs.
+ `:database_name` is the human-readable name the LLM needs as the first slot of every
+ portable FK in `construct_notebook_query`; surfacing it on every table/model search
+ result means the LLM doesn't need a separate `entity_details` round-trip just to learn
+ the DB name."
[results]
- (let [db-ids (->> results (keep :database_id) distinct)
- engines (when (seq db-ids)
- (t2/select-pk->fn :engine :model/Database :id [:in db-ids]))]
+ (let [db-ids (->> results (keep :database_id) distinct)
+ id->db (when (seq db-ids)
+ (t2/select-pk->fn (juxt :engine :name) :model/Database :id [:in db-ids]))]
(cond->> results
- (seq engines) (mapv (fn [r] (m/assoc-some r :database_engine (get engines (:database_id r))))))))
+ (seq id->db) (mapv (fn [r]
+ (let [[engine db-name] (get id->db (:database_id r))]
+ (-> r
+ (m/assoc-some :database_engine engine)
+ (m/assoc-some :database_name db-name))))))))
+
+(defn- enrich-with-portable-entity-ids
+ "Attach `:portable_entity_id` (the card's `entity_id` NanoID) to saved-question, model,
+ and metric search results so the LLM can use it verbatim as `source-card:` (for
+ questions/models) or inside a `[metric, {}, <entity_id>]` aggregation clause (for
+ metrics) without a follow-up `entity_details` / `read_resource` round-trip."
+ [results]
+ (let [carded-types #{"question" "model" "metric"}
+ card-ids (->> results
+ (filter #(carded-types (:type %)))
+ (keep :id)
+ distinct)
+ id->eid (when (seq card-ids)
+ (t2/select-pk->fn :entity_id :model/Card :id [:in card-ids]))]
+ (cond->> results
+ (seq id->eid) (mapv (fn [r]
+ (if-let [eid (and (carded-types (:type r))
+ (get id->eid (:id r)))]
+ (assoc r :portable_entity_id eid)
+ r))))))
+
+(defn- enrich-with-metric-base-tables
+ "Attach base-table info (`:base_table_id`, `:base_table_name`, `:base_table_schema`,
+ `:base_table_portable_fk`) to metric search results.
+
+ A metric is a Card whose `:dataset_query` aggregates a specific table; the LLM needs that
+ table's portable FK as the `source-table:` when it wants to use the metric. Without this
+ enrichment the LLM sees the metric's `portable_entity_id` in search but has to either
+ hallucinate the base table (observed failure mode: `[<db>, public, customers]`) or do an
+ extra `entity_details` round-trip. We read the two columns directly from
+ `report_card.table_id` + `metabase_table.{schema,name}` to keep the lookup O(1) extra
+ query per search call, regardless of number of metrics in the result set.
+
+ Requires `:database_name` to already be set on each metric result (done earlier by
+ [[enrich-with-database-engines]]) so we can assemble the full portable FK
+ `[database_name, schema, table]`."
+ [results]
+ (let [metric-ids (->> results (filter #(= "metric" (:type %))) (keep :id) distinct)
+ card-id->table-id (when (seq metric-ids)
+ (t2/select-pk->fn :table_id :model/Card :id [:in metric-ids]))
+ table-ids (->> card-id->table-id vals (remove nil?) distinct)
+ table-id->info (when (seq table-ids)
+ (t2/select-pk->fn (juxt :schema :name) :model/Table :id [:in table-ids]))]
+ (cond->> results
+ (seq card-id->table-id)
+ (mapv (fn [r]
+ (if (= "metric" (:type r))
+ (if-let [table-id (get card-id->table-id (:id r))]
+ (let [[schema table-name] (get table-id->info table-id)
+ db-name (:database_name r)]
+ (cond-> (assoc r :base_table_id table-id)
+ table-name (assoc :base_table_name table-name
+ :base_table_schema schema)
+ (and db-name table-name)
+ (assoc :base_table_portable_fk [db-name schema table-name])))
+ r)
+ r))))))
(defn- remove-unreadable-transforms
"Remove transforms from search results that the user cannot read.
@@ -238,12 +303,14 @@
(map postprocess-search-result)
enrich-with-collection-descriptions
enrich-with-database-engines
+ enrich-with-portable-entity-ids
+ enrich-with-metric-base-tables
remove-unreadable-transforms)))
(defn- format-search-output
"Format search results as an LLM-ready string."
[results]
- (let [results-xml (llm-rep/search-results->xml results)]
+ (let [results-xml (llm-shape/search-results->xml results)]
(te/lines
"<result>"
results-xml
diff --git a/src/metabase/metabot/tools/shared/content_store.clj b/src/metabase/metabot/tools/shared/content_store.clj
new file mode 100644
index 00000000000..6fff5688ac2
--- /dev/null
+++ b/src/metabase/metabot/tools/shared/content_store.clj
@@ -0,0 +1,53 @@
+(ns metabase.metabot.tools.shared.content-store
+ "Permission-aware wrapper around `metabase.models.serialization.resolve.mp/ContentStore`.
+
+ The metadata-provider-backed resolver in `resolve.mp` is deliberately permission-agnostic so
+ that serdes import / background tasks can use it without an authenticated user. HTTP and
+ agent-tool paths run under a current user and therefore must layer in `api/read-check` —
+ this namespace is the chokepoint.
+
+ `read-checked` wraps any `ContentStore` so every lookup that returns a Card / Measure /
+ Segment row is gated by `api/read-check` whenever `api/*current-user-id*` is bound. When
+ the var is unbound (serdes, REPL, background tasks, tests without auth context), rows pass
+ through unchanged.
+
+ `default-store` is the standard agent / tool-path store — `unchecked-app-db-content-store`
+ wrapped with `read-checked`. Use this as the content store for any agent or tool path that
+ runs under an authenticated request. The symmetry across all five methods (both
+ `-by-entity-id` import-direction and `-by-id` export-direction) is intentional: the export
+ direction may surface entity_ids of Cards / Measures / Segments referenced inside an
+ exported query body, and a missing check on those branches is exactly the N1 ACL gap that
+ motivated this namespace."
+ (:require
+ [metabase.api.common :as api]
+ [metabase.models.serialization.resolve.mp :as resolve.mp]))
+
+(set! *warn-on-reflection* true)
+
+(defn- maybe-read-check
+ "Apply `api/read-check` when `*current-user-id*` is bound; otherwise return the row
+ unchanged. Returning `nil` propagates through (no row → nothing to check; the
+ per-model resolver functions translate `nil` into a clean `:unknown-…` agent error)."
+ [row]
+ (cond
+ (nil? row) nil
+ api/*current-user-id* (api/read-check row)
+ :else row))
+
+(defn read-checked
+ "Wrap `store` so every lookup applies `api/read-check` when `api/*current-user-id*` is
+ bound. Symmetric across all five `ContentStore` methods."
+ [store]
+ (reify resolve.mp/ContentStore
+ (card-by-entity-id [_ eid] (maybe-read-check (resolve.mp/card-by-entity-id store eid)))
+ (measure-by-entity-id [_ eid] (maybe-read-check (resolve.mp/measure-by-entity-id store eid)))
+ (segment-by-entity-id [_ eid] (maybe-read-check (resolve.mp/segment-by-entity-id store eid)))
+ (measure-by-id [_ id] (maybe-read-check (resolve.mp/measure-by-id store id)))
+ (segment-by-id [_ id] (maybe-read-check (resolve.mp/segment-by-id store id)))))
+
+(def default-store
+ "The standard agent / tool-path content store: `unchecked-app-db-content-store` wrapped with
+ `read-checked`. Pass this to `repr.resolve/resolve-query`, `repr.resolve/export-query`,
+ `repr.resolve/try-export-query`, `repair/repair`, or any other resolver entry-point that
+ runs under an authenticated request."
+ (read-checked resolve.mp/unchecked-app-db-content-store))
diff --git a/src/metabase/metabot/tools/shared/llm_representations.clj b/src/metabase/metabot/tools/shared/llm_shape.clj
similarity index 76%
rename from src/metabase/metabot/tools/shared/llm_representations.clj
rename to src/metabase/metabot/tools/shared/llm_shape.clj
index 763aff56409..d066158f582 100644
--- a/src/metabase/metabot/tools/shared/llm_representations.clj
+++ b/src/metabase/metabot/tools/shared/llm_shape.clj
@@ -1,5 +1,14 @@
-(ns metabase.metabot.tools.shared.llm-representations
- "LLM representation utilities for formatting entities as XML.
+(ns metabase.metabot.tools.shared.llm-shape
+ "Output-side XML formatters that turn Metabase entity data (tables, fields, metrics,
+ queries, search results, ...) into the LLM-facing XML shape consumed by the metabot
+ agent. Templated via `resources/metabot/prompts/llm_shape.selmer`.
+
+ Naming note: this is the *output* (response-side) shape, not to be confused with the
+ *input*-side portable representations format owned by `metabase.agent-lib.representations.*`.
+ The two share no schema and no code path; they were briefly named symmetrically
+ (`llm-shaperesentations` here, `representations` there) and the symmetry caused enough
+ confusion to motivate this rename.
+
Matches Python AI Service patterns exactly for consistency."
(:require
[clojure.string :as str]
@@ -7,13 +16,14 @@
[metabase.metabot.agent.prompts :as prompts]
[metabase.metabot.tmpl :as te]
[metabase.util :as u]
+ [metabase.util.json :as json]
[metabase.util.log :as log]
[ring.util.codec :as codec]
[selmer.parser :as selmer]))
(set! *warn-on-reflection* true)
-(def ^:private llm-template-name "llm_representations.selmer")
+(def ^:private llm-template-name "llm_shape.selmer")
(defn- encode-uri-segment
"URL-encode a single URI path segment. Coerces keywords/numbers to strings first.
@@ -46,7 +56,24 @@
(when (seq path-segments)
(str "/" (str/join "/" (map encode-uri-segment path-segments)))))))
-(defn escape-xml
+(defn- repr-data->llm-block
+ "Render portable repr-form data (a map or a vector of clauses) as a JSON code block. Used
+ inside `<query>` for a whole query, and inside `<definition>` for a measure's aggregation
+ array or a segment's filter array. The triple-backtick fence gives the LLM the same
+ syntactic frame it would in a tool description or assistant turn. Accepts a pre-rendered
+ string passthrough; returns `nil` when the input is empty so the selmer template can omit
+ the block entirely."
+ [data]
+ (cond
+ (and (string? data)
+ (not (str/blank? data)))
+ data
+
+ (and (or (map? data) (vector? data))
+ (seq data))
+ (str "```json\n" (json/encode data {:pretty true}) "\n```")))
+
+(defn- escape-xml
"Escape XML special characters in a string.
Only needed for content that bypasses Selmer's auto-escaping (marked with |safe)."
[s]
@@ -99,7 +126,7 @@
(defn- render-llm-template
"Render a Selmer template with the supplied context."
[type context]
- (let [template (prompts/get-cached-llm-representations-template)
+ (let [template (prompts/get-cached-llm-shape-template)
payload (merge (type-flags type) context)]
(if template
(try
@@ -130,10 +157,21 @@
(and (#{:type :base-type} k) (keyword? v)) (clojure.core/name v)
:else (str v))))}))
+(defn- fully-qualified-name
+ "Get fully qualified name for a table."
+ [database_schema name]
+ (if database_schema
+ (str database_schema "." name)
+ name))
+
(defn field->xml
"Format a field/column as XML element.
- Matches Python Column.llm_representation exactly."
- [{:keys [field_id name display_name type database_type description]}]
+ Matches Python Column.llm_representation exactly, plus — when the column is a foreign key
+ — a `fk_target_fully_qualified_name` attribute like `schema.table.field_name`. Without this
+ attribute the LLM sees a bare `customer_id` column with no hint that it joins anywhere,
+ and tries to read related fields (e.g. `email`) off the current table, which fails
+ with `:unknown-field`."
+ [{:keys [field_id name display_name type database_type description fk_target_portable_fk]}]
(render-llm-template
:field
{:field_id field_id
@@ -142,7 +180,13 @@
:field_display_name (or display_name name)
:field_base_type (when type (clojure.core/name type))
:field_database_type (database-type-or-unknown database_type)
- :field_description description}))
+ :field_description description
+ :field_fk_target_fqn (when (and (vector? fk_target_portable_fk)
+ (>= (count fk_target_portable_fk) 4))
+ (let [[_db schema table & field-path] fk_target_portable_fk]
+ (str (fully-qualified-name schema table)
+ "."
+ (str/join "." field-path))))}))
(defn collection->xml
"Format collection for LLM consumption.
@@ -156,66 +200,78 @@
(defn measure->xml
"Format a measure for LLM consumption."
- [{:keys [id name display-name description definition definition-description]}]
+ [{:keys [id name display-name description definition definition-description
+ portable-entity-id portable_entity_id]}]
(render-llm-template
:measure
- {:measure_id (str id)
- :measure_name (or name "")
- :measure_display_name (or display-name name "")
- :measure_description description
- :measure_definition (when definition (pr-str definition))
+ {:measure_id (str id)
+ :measure_name (or name "")
+ :measure_display_name (or display-name name "")
+ :measure_description description
+ :measure_portable_entity_id (or portable-entity-id portable_entity_id)
+ :measure_definition (repr-data->llm-block definition)
:measure_definition_description definition-description}))
(defn segment->xml
"Format a segment for LLM consumption."
- [{:keys [id name display-name description definition definition-description]}]
+ [{:keys [id name display-name description definition definition-description
+ portable-entity-id portable_entity_id]}]
(render-llm-template
:segment
- {:segment_id (str id)
- :segment_name (or name "")
- :segment_display_name (or display-name name "")
- :segment_description description
- :segment_definition (when definition (pr-str definition))
+ {:segment_id (str id)
+ :segment_name (or name "")
+ :segment_display_name (or display-name name "")
+ :segment_description description
+ :segment_portable_entity_id (or portable-entity-id portable_entity_id)
+ :segment_definition (repr-data->llm-block definition)
:segment_definition_description definition-description}))
(defn- related-table->xml
"Format a related table for LLM consumption."
- [{:keys [id name related_by fully_qualified_name fields]}]
+ [{:keys [id name related_by database_name fully_qualified_name fields]}]
(render-llm-template
:related_table
- {:related_table_id (when (some? id) (str id))
- :related_table_name name
- :related_table_related_by related_by
- :related_table_fqn fully_qualified_name
- :related_table_fields_xml (when (seq fields) (str/join "\n" (map field->xml fields)))}))
+ {:related_table_id (when (some? id) (str id))
+ :related_table_name name
+ :related_table_related_by related_by
+ :related_table_database_name database_name
+ :related_table_fqn fully_qualified_name
+ :related_table_fields_xml (when (seq fields) (str/join "\n" (map field->xml fields)))}))
(defn metric->xml
"Format metric for LLM consumption.
- Matches Python Metric.get_llm_representation exactly."
+ Matches Python Metric.get_llm_representation exactly, except we additionally surface
+ `database_name`, `base_table_fully_qualified_name`, and `portable_entity_id` as tag
+ attributes — the three pieces of information the LLM needs to correctly use the metric
+ in `construct_notebook_query` (as `aggregation: [[metric, {}, <eid>]]` on top of the
+ metric's base table)."
[{:keys [id name description verified queryable-dimensions collection
- default_time_dimension_field]}]
+ default_time_dimension_field database_name base_table_portable_fk
+ portable_entity_id]}]
(render-llm-template
:metric
{:metric_id (str id)
:metric_name name
:metric_verified (boolean verified)
:metric_description description
+ :metric_database_name database_name
+ :metric_base_table_fqn (when (and (vector? base_table_portable_fk)
+ (= 3 (count base_table_portable_fk)))
+ (let [[_db schema table] base_table_portable_fk]
+ (fully-qualified-name schema table)))
+ :metric_portable_entity_id portable_entity_id
:metric_collection_xml (when collection (collection->xml collection))
:metric_default_time_dimension (:name default_time_dimension_field)
:metric_dimensions_table (when (seq queryable-dimensions)
(format-fields-table queryable-dimensions))}))
-(defn- fully-qualified-name
- "Get fully qualified name for a table."
- [database_schema name]
- (if database_schema
- (str database_schema "." name)
- name))
-
(defn table->xml
"Format table for LLM consumption.
- Matches Python Table.get_llm_representation exactly."
- [{:keys [id name database_id database_engine database_schema
+ Matches Python Table.get_llm_representation exactly, except we additionally surface
+ `database_name` as a tag attribute so the LLM has the human-readable DB name available
+ without a separate `entity_details` call — it's the first slot of every portable FK in
+ the representations-format `construct_notebook_query` tool."
+ [{:keys [id name database_id database_name database_engine database_schema
description fields related_tables measures segments]}]
(let [fqn (fully-qualified-name database_schema name)]
(render-llm-template
@@ -223,6 +279,7 @@
{:table_id (str id)
:table_name name
:table_database_id (str database_id)
+ :table_database_name database_name
:table_database_engine (database-engine-or-unknown database_engine)
:table_fqn fqn
:table_description description
@@ -248,10 +305,16 @@
(defn model->xml
"Format model for LLM consumption.
- Matches Python Model.get_llm_representation exactly.
- Note: Python uses <metabase-model> tag but closes with </model>."
- [{:keys [id name description verified fields database_id database_engine
- related_tables measures segments]}]
+ Matches Python Model.get_llm_representation exactly, except we additionally surface
+ `database_name` as a tag attribute (see [[table->xml]] for the rationale).
+
+ When the caller supplies `:query_json` (the model's `dataset_query` exported through the
+ representations resolver as a portable repr-form map), it is rendered inside the
+ `<metabase-model>` element as a JSON `<query>` block — same canonical portable MBQL 5
+ representations form used elsewhere. Note: Python uses <metabase-model> tag but closes
+ with </model>."
+ [{:keys [id name description verified fields database_id database_name database_engine
+ related_tables measures segments portable_entity_id query_json]}]
(let [fqn (model-fully-qualified-name id name)]
(render-llm-template
:model
@@ -259,9 +322,12 @@
:model_name name
:model_verified (boolean verified)
:model_database_id (str database_id)
+ :model_database_name database_name
:model_database_engine (database-engine-or-unknown database_engine)
:model_fqn fqn
:model_description description
+ :model_portable_entity_id portable_entity_id
+ :model_query_json (repr-data->llm-block query_json)
:model_fields_xml (when (seq fields)
(str/join "\n" (map field->xml fields)))
:model_related_tables_xml (when (seq related_tables)
@@ -347,8 +413,14 @@
:chart_type (if chart-type (clojure.core/name chart-type) "table")}))
(defn question->xml
- "Format question for LLM consumption."
- [{:keys [id name description verified collection visualization display fields]}]
+ "Format question for LLM consumption.
+
+ When the caller supplies `:query_json` (the saved card's `dataset_query` exported through
+ the representations resolver as a portable repr-form map), it is rendered inside the
+ `<metabase_question>` element as a JSON `<query>` block. The format is the same canonical
+ portable MBQL 5 representations the LLM writes into `construct_notebook_query` and gets
+ back in that tool's result — so existing cards and freshly-built queries share one form."
+ [{:keys [id name description verified collection visualization display fields portable_entity_id query_json]}]
(render-llm-template
:question
{:question_id (str id)
@@ -356,8 +428,10 @@
:question_name name
:question_description description
:question_display_type (some-> display clojure.core/name)
+ :question_portable_entity_id portable_entity_id
:question_collection_xml (when collection (collection->xml collection))
:question_visualization_xml (when visualization (visualization->xml visualization))
+ :question_query_json (repr-data->llm-block query_json)
:question_fields_xml (when (seq fields)
(str/join "\n" (map field->xml fields)))}))
@@ -484,9 +558,20 @@
(defn search-result->xml
"Format a single search result as XML element.
Includes database_id, database_engine, and fully_qualified_name for table/model results
- to match Python AI Service search output."
+ to match Python AI Service search output. For saved-question and model results also
+ includes `portable_entity_id` so the LLM can paste it verbatim into `source-card:`
+ without an extra `entity_details` call, and (when available) `database_name` — the
+ human-readable name the LLM needs as the first slot of every portable FK in
+ `construct_notebook_query`.
+
+ For metric results we additionally surface `base_table_fully_qualified_name` (the
+ `schema.table` of the table the metric aggregates). Combined with `database_name` this
+ gives the LLM the full portable FK `[database_name, schema, table]` it must put in
+ `source-table:` when using `[metric, {}, <portable_entity_id>]` as an aggregation —
+ without a separate `entity_details` round-trip."
[{:keys [id type name description verified collection
- database_id database_engine database_schema]}]
+ database_id database_name database_engine database_schema portable_entity_id
+ base_table_portable_fk]}]
(let [fqn (cond
(#{"table" :table} type)
(when name (fully-qualified-name database_schema name))
@@ -510,8 +595,14 @@
:search_description description
:search_collection_name (:name collection)
:search_database_id (when database_id (str database_id))
+ :search_database_name database_name
:search_database_engine engine
- :search_fqn fqn})))
+ :search_fqn fqn
+ :search_portable_entity_id portable_entity_id
+ :search_base_table_fqn (when (and (vector? base_table_portable_fk)
+ (= 3 (count base_table_portable_fk)))
+ (let [[_db schema table] base_table_portable_fk]
+ (fully-qualified-name schema table)))})))
(defn search-results->xml
"Format search results as XML wrapped in search-results element."
diff --git a/src/metabase/metabot/tools/slackbot_query.clj b/src/metabase/metabot/tools/slackbot_query.clj
index 0f0e707ac6e..6ce35e612b6 100644
--- a/src/metabase/metabot/tools/slackbot_query.clj
+++ b/src/metabase/metabot/tools/slackbot_query.clj
@@ -1,7 +1,11 @@
(ns metabase.metabot.tools.slackbot-query
"Slackbot-specific notebook query tool.
Like construct-notebook-query-tool but emits adhoc_viz data parts
- instead of creating charts. Does not save or navigate."
+ instead of creating charts. Does not save or navigate.
+
+ This tool consumes the same MBQL 5 portable representations format (JSON, validated against
+ `::lib.schema/external-query`) as the main `construct_notebook_query` tool and shares its
+ prompt."
(:require
[metabase.metabot.agent.streaming :as streaming]
[metabase.metabot.scope :as scope]
@@ -12,11 +16,15 @@
(set! *warn-on-reflection* true)
(def ^:private slackbot-query-schema
+ "Slackbot variant of `construct_notebook_query`. Same self-describing JSON query as the main
+ tool (`:query` is a `::lib.schema/external-query` map), plus `:title` and `:display` for the
+ Slack visualization wrapper.
+
+ The query body carries the database identity via its first stage's `source-table:` /
+ `source-card:`, so the schema deliberately omits `:source_entity` and `:referenced_entities`."
[:map {:closed true}
[:reasoning :string]
- [:source_entity [:map [:type :string] [:id :int]]]
- [:referenced_entities {:optional true} [:maybe [:sequential [:map [:type :string] [:id :int]]]]]
- [:program construct/construct-program-schema]
+ [:query :map]
[:title {:optional true} [:maybe :string]]
[:display {:optional true
:description "Visualization type for displaying the query results in Slack. Required in practice whenever the user asks for a chart or graph, and it must match any requested chart type. Valid values: 'table', 'bar', 'line', 'pie', 'area', 'row', 'scatter', 'funnel'. Use requested chart types like 'line', 'bar', 'area', 'pie', 'scatter', 'funnel', 'row', or 'table' when they fit the query. Omitting this field falls back to Metabase's default table display, so do not omit it for chart or graph requests. Only omit it when you intentionally want a plain table and the user did not request a chart type."}
@@ -25,10 +33,15 @@
(mu/defn ^{:tool-name "construct_notebook_query"
:scope scope/agent-notebook-create}
slackbot-construct-notebook-query-tool
- "Construct a notebook query from a metric, model, or table. The query results will be rendered as a visualization in Slack."
- [{:keys [_reasoning source_entity referenced_entities program title display]} :- slackbot-query-schema]
+ "Construct a notebook query from a metric, model, or table. The query results will be
+ rendered as a visualization in Slack.
+
+ See `resources/metabot/prompts/tools/construct_notebook_query.md` for the JSON format the
+ `:query` argument must follow — the prompt is shared with the main `construct_notebook_query`
+ tool."
+ [{:keys [_reasoning query title display]} :- slackbot-query-schema]
(try
- (let [query-result (construct/execute-program source_entity referenced_entities program)
+ (let [query-result (construct/execute-representations-query query)
structured (or (:structured-output query-result) (:structured_output query-result))]
(if (and structured (:query-id structured) (:query structured))
(let [metabase-link (streaming/query->question-url (:query structured) display)
diff --git a/src/metabase/metabot/tools/sql.clj b/src/metabase/metabot/tools/sql.clj
index d43995e5b11..3e6ab33c2a6 100644
--- a/src/metabase/metabot/tools/sql.clj
+++ b/src/metabase/metabot/tools/sql.clj
@@ -6,7 +6,7 @@
[metabase.metabot.tmpl :as te]
[metabase.metabot.tools.shared :as shared]
[metabase.metabot.tools.shared.instructions :as instructions]
- [metabase.metabot.tools.shared.llm-representations :as llm-rep]
+ [metabase.metabot.tools.shared.llm-shape :as llm-shape]
[metabase.metabot.tools.sql.create :as create-sql-query-tools]
[metabase.metabot.tools.sql.edit :as edit-sql-query-tools]
[metabase.metabot.tools.sql.replace :as replace-sql-query-tools]
@@ -40,7 +40,7 @@
`preamble` is optional text placed before the query XML inside <result>
(e.g. \"SQL query successfully constructed.\")."
[structured instruction-text & {:keys [preamble?]}]
- (let [query-xml (llm-rep/query->xml structured)]
+ (let [query-xml (llm-shape/query->xml structured)]
(te/lines
"<result>"
(when preamble?
diff --git a/src/metabase/metabot/tools/util.clj b/src/metabase/metabot/tools/util.clj
index 97b5fd159b0..5546c6380b8 100644
--- a/src/metabase/metabot/tools/util.clj
+++ b/src/metabase/metabot/tools/util.clj
@@ -44,10 +44,42 @@
(lib/display-name query)
lib/display-name-without-id))))
+(defn- column-portable-fk
+ "Build the portable FK path `[db-name, schema-or-null, table-name, field-name …]` for a column
+ that has a real numeric `:id`. Returns nil for expression / aggregation columns that don't
+ correspond to a database field."
+ [query column]
+ (when (and (:id column) (:table-id column))
+ (let [table (lib.metadata/table query (:table-id column))
+ db (lib.metadata/database query)
+ ;; walk the `:parent-id` chain in case this is a JSON-unfolded nested field
+ chain (loop [acc [(:name column)]
+ pid (:parent-id column)]
+ (if pid
+ (let [parent (lib.metadata/field query pid)]
+ (recur (cons (:name parent) acc) (:parent-id parent)))
+ acc))]
+ (when (and (:name db) (:name table))
+ (into [(:name db) (:schema table) (:name table)] chain)))))
+
+(defn- fk-target-portable-fk
+ "If `column` is an FK (has a non-nil `:fk-target-field-id`), return the portable FK path of
+ the target field, walking the parent-id chain for JSON-unfolded targets. Returns nil for
+ non-FK columns or when the target can't be resolved."
+ [query column]
+ (when-let [tgt-id (:fk-target-field-id column)]
+ (when-let [tgt (lib.metadata/field query tgt-id)]
+ (column-portable-fk query tgt))))
+
(defn ->result-column
"Return tool result column for `column` of `query`.
Uses the real field `:id` when available, falling back to column name for
- expression/aggregation columns that don't have a database field ID."
+ expression/aggregation columns that don't have a database field ID.
+
+ Also includes a `:portable_fk` key with the portable foreign-key path
+ `[db-name, schema, table-name, field-name …]` when the column maps to a real database field.
+ The representations-format notebook query tool expects fields to be referenced by this path
+ rather than by numeric id."
[query column]
(let [base-type (some-> (:base-type column) u/qualified-name)
effective-type (some-> (:effective-type column) u/qualified-name)
@@ -55,7 +87,11 @@
coercion-strategy (some-> (:coercion-strategy column) u/qualified-name)
field-id (or (:id column)
(:lib/desired-column-alias column)
- (:lib/source-column-alias column))]
+ (:lib/source-column-alias column))
+ portable-fk (try (column-portable-fk query column)
+ (catch Exception _ nil))
+ fk-target-fk (try (fk-target-portable-fk query column)
+ (catch Exception _ nil))]
(-> {:field_id field-id
:name (or (:lib/desired-column-alias column)
(:lib/source-column-alias column))
@@ -68,6 +104,8 @@
:database_type (:database-type column)
:coercion_strategy coercion-strategy
:field_values (:field-values column)
+ :portable_fk portable-fk
+ :fk_target_portable_fk fk-target-fk
:table_reference (:table-reference column)))))
(defn find-column-by-field-id
@@ -120,6 +158,19 @@
(-> (t2/select-one :model/Card :id id)
api/read-check))
+(defn get-card-by-entity-id
+ "Retrieve a readable card by its 21-char NanoID `entity_id`, or `nil` if not found. Used by
+ [[metabase.metabot.tools.construct/resolve-database-id-from-first-stage]] to look up the
+ database-id of a `source-card:` stage before the metadata provider is built.
+
+ Does NOT go through the serdes `lookup-by-id` machinery because we want `nil` on miss
+ (not a thrown exception) so the caller can surface a tool-specific agent error. If the
+ card exists but the current user cannot read it, `api/read-check` raises a 403 instead of
+ silently letting the representations resolver use an inaccessible card."
+ [entity-id]
+ (some-> (t2/select-one :model/Card :entity_id entity-id)
+ api/read-check))
+
(defn card-query
"Return a query based on the card with ID `card-id`."
[card-id]
diff --git a/src/metabase/models/serialization/resolve.clj b/src/metabase/models/serialization/resolve.clj
index 82dff2541cb..1ac41ca0138 100644
--- a/src/metabase/models/serialization/resolve.clj
+++ b/src/metabase/models/serialization/resolve.clj
@@ -237,7 +237,7 @@
(mbql-id->fully-qualified-name resolver &match)
(_ :guard sequential?)
- (mapv export-mbql &match)
+ (mapv (partial export-mbql resolver) &match)
(_ :guard map?)
(reduce-kv
diff --git a/src/metabase/models/serialization/resolve/mp.clj b/src/metabase/models/serialization/resolve/mp.clj
new file mode 100644
index 00000000000..5bcfdb5ae98
--- /dev/null
+++ b/src/metabase/models/serialization/resolve/mp.clj
@@ -0,0 +1,626 @@
+(ns metabase.models.serialization.resolve.mp
+ "Metadata-provider-backed implementations of the serdes resolver protocols.
+
+ Unlike `metabase.models.serialization.resolve.db`, this resolver does not touch toucan2 /
+ the application database for *warehouse-schema* lookups (tables, fields) - it works off a
+ `lib.metadata/MetadataProvider`, which may be the live application-DB-backed provider, a
+ test-only mock provider, or any cached variant.
+
+ It does, however, touch the application DB for *Metabase-model* lookups (cards by
+ `entity_id`, etc.) because the lib metadata protocol doesn't support filtering by
+ `entity_id`, and cards in any case live in the application DB independently of whose
+ warehouse the metadata provider points at.
+
+ Primary consumer: the agent-lib representations pipeline, which converts LLM-authored
+ portable MBQL queries (with FK paths like `[DB, SCHEMA, TABLE, FIELD]`) into numeric-ID
+ MBQL suitable for `lib.query/query` / the QP.
+
+ Implemented scope for the representations pipeline:
+ * `import-table-fk`, `import-field-fk`, `export-table-fk`, `export-field-fk` for
+ warehouse metadata.
+ * `import-fk-keyed` / `export-fk-keyed` for `:model/Database` by `:name`.
+ * `import-fk` for `Card` / `:model/Card` by `entity_id` (source-card and metric refs).
+ * `export-fk` for `Card` / `:model/Card` by `entity_id` (exporting final pMBQL back to
+ portable representations YAML).
+
+ Everything else throws `:not-implemented-yet` for now.
+
+ Asset vs metadata split:
+ The resolver has two orthogonal lookup responsibilities:
+ * **Warehouse metadata** (databases, tables, fields) is resolved through a
+ `lib.metadata/MetadataProvider`.
+ * **Metabase content / assets** (cards, snippets, segments, …) is resolved through a
+ [[ContentStore]] on import, where callers may need permission-aware lookups. Exporting
+ card ids uses the same database-scoped metadata provider, which already contains card
+ metadata in app-backed and mock-provider contexts. The default app-DB-backed store goes
+ through `serdes/lookup-by-id`, but a different store (e.g. backed by the checker's YAML
+ index, an in-memory test fixture, or a snapshot) can be supplied to make import usable
+ without an application database."
+ (:require
+ [metabase.lib.metadata :as lib.metadata]
+ [metabase.lib.metadata.protocols :as lib.metadata.protocols]
+ [metabase.models.serialization :as serdes]
+ [metabase.models.serialization.resolve :as resolve]
+ [metabase.util.i18n :refer [tru]]
+ [potemkin.types :as p.types]
+ [toucan2.core :as t2]))
+
+(set! *warn-on-reflection* true)
+
+;;; ============================================================
+;;; Helpers
+;;; ============================================================
+
+(defn- db-name [metadata-provider]
+ (:name (lib.metadata/database metadata-provider)))
+
+(defn- matching-tables
+ "Return all tables in `metadata-provider` that match `table-name`, optionally filtered by `schema`
+ (where `schema` may be nil for schemaless databases).
+
+ Uses `metadatas-by-name`-style query via `metadatas` to avoid O(tables) scans on large providers."
+ [metadata-provider schema table-name]
+ (->> (lib.metadata.protocols/metadatas metadata-provider
+ {:lib/type :metadata/table
+ :name #{table-name}})
+ (filter #(= (:schema %) schema))))
+
+(defn- unknown-table-ex-info
+ "Build an agent-facing `:unknown-table` error for a miss on portable FK
+ `[db schema name]`.
+
+ Deliberately does NOT enumerate schemas, sibling tables, or fuzzy candidates. The metadata
+ provider here is un-sandboxed (it exposes every table in the warehouse regardless of the
+ caller's data perms), and any string included in this ex-info message is relayed verbatim
+ to the LLM via `:agent-error? true`, and from there to the end user. A sandboxed user who
+ prompts the agent with a hallucinated `source-table:` would otherwise receive a list of
+ schemas / tables they cannot otherwise see.
+
+ The LLM can still self-correct in one turn by calling `entity_details` on the parent
+ database; the message points it at that path."
+ [_metadata-provider [_path-db-name _path-schema _path-table-name :as path]]
+ (ex-info (tru "No table found matching portable FK {0}. Call `entity_details` with entity-type `database` and the database''s numeric id to list available tables and schemas, then retry with an exact portable FK from the response."
+ (pr-str path))
+ {:status-code 400
+ :error :unknown-table
+ :agent-error? true
+ :path path}))
+
+(defn- find-table
+ "Resolve `[db-name, schema, table-name]` to a `:metadata/table` or throw with context.
+
+ On miss, the thrown ex-info carries actionable, tiered hints (see
+ [[unknown-table-ex-info]]) so the LLM can self-correct on the next turn instead of
+ re-hallucinating the same bad path. All error branches are marked
+ `:agent-error? true` so the outer tool wrapper relays the message verbatim."
+ [metadata-provider [path-db-name path-schema path-table-name :as path]]
+ (let [current-db (db-name metadata-provider)]
+ (when-not (= path-db-name current-db)
+ (throw (ex-info (tru "Portable table FK references database {0}, but metadata provider is for {1}."
+ (pr-str path-db-name)
+ (pr-str current-db))
+ {:status-code 400
+ :error :unknown-table
+ :agent-error? true
+ :path path
+ :expected-db current-db}))))
+ (let [candidates (matching-tables metadata-provider path-schema path-table-name)]
+ (case (count candidates)
+ 0 (throw (unknown-table-ex-info metadata-provider path))
+ 1 (first candidates)
+ ;; Deliberately do NOT enumerate the matching `[schema name id]` tuples — the metadata
+ ;; provider is un-sandboxed, so a leaked candidate list could surface tables the caller
+ ;; cannot otherwise see (parity with the `unknown-table-ex-info` strip above).
+ (throw (ex-info (tru "Ambiguous portable table FK {0}: {1} candidates. Call `entity_details` with entity-type `database` to list available tables and retry with a more specific portable FK."
+ (pr-str path) (count candidates))
+ {:status-code 400
+ :error :ambiguous-table
+ :agent-error? true
+ :path path})))))
+
+(defn- find-field
+ "Resolve a field path `[db schema table field …]` to a `:metadata/column` or throw with context.
+
+ For regular (non-JSON-unfolded) fields, the path has exactly 4 elements and we match on name
+ directly. For JSON-unfolded paths (5+ elements), we walk parent/child via `:parent-id` -
+ matching the behaviour of `serdes/recursively-find-field-q`."
+ [metadata-provider [db schema table-name & field-path :as full-path]]
+ (when (empty? field-path)
+ (throw (ex-info (tru "Portable field FK {0} must have at least 4 elements." (pr-str full-path))
+ {:status-code 400
+ :error :invalid-field-fk
+ :path full-path})))
+ (let [table-meta (find-table metadata-provider [db schema table-name])
+ columns (lib.metadata.protocols/metadatas-for-table metadata-provider
+ :metadata/column
+ (:id table-meta))
+ ;; Deliberately do NOT enumerate FK-linked tables that happen to carry the same
+ ;; column name. The metadata provider is un-sandboxed, the `:agent-error?` flag
+ ;; relays this message verbatim to the user, and a leaked FK-candidate path would
+ ;; reveal table names the caller may not be permitted to see. The LLM can recover
+ ;; by calling `entity_details` on the parent table to list its columns.
+ unknown-field-ex
+ (fn [segment]
+ (ex-info (tru "No column {0} on table {1}.{2}.{3}. Call `entity_details` on this table to list its columns."
+ (pr-str segment) (pr-str db) (pr-str schema) (pr-str table-name))
+ {:status-code 400
+ :error :unknown-field
+ :path full-path
+ :segment segment
+ :table-id (:id table-meta)
+ :agent-error? true}))
+ ;; Walk nested fields parent-first. At each level, match `:name` and `:parent-id`.
+ walk (fn walk [parent-id [segment & more]]
+ (let [candidates (filter #(and (= (:name %) segment)
+ (= (:parent-id %) parent-id))
+ columns)]
+ (case (count candidates)
+ 0 (throw (unknown-field-ex segment))
+ 1 (let [col (first candidates)]
+ (if (seq more)
+ (walk (:id col) more)
+ col))
+ (throw (ex-info (tru "Ambiguous column {0} on table {1}.{2}.{3}."
+ (pr-str segment)
+ (pr-str db)
+ (pr-str schema)
+ (pr-str table-name))
+ {:status-code 400
+ :error :ambiguous-field
+ :path full-path
+ :segment segment
+ :candidates (mapv :id candidates)})))))]
+ (walk nil field-path)))
+
+(defn outbound-fks-from-table
+ "Return a sequence of FK edges leaving `source-table-id` in `metadata-provider`.
+
+ Each entry is a map with:
+ * `:source-field-id` numeric id of the FK field on the source table;
+ * `:source-field` the full column metadata (convenient for portable-FK export);
+ * `:target-field-id` numeric id of the target field pointed to;
+ * `:target-table-id` numeric id of the target table.
+
+ Uses `lib.metadata.protocols/metadatas-for-table` and `lib.metadata.protocols/field` directly
+ (not the `mu/defn`-wrapped accessors) so that missing target-field lookups degrade to `nil`
+ rather than throwing Malli errors."
+ [metadata-provider source-table-id]
+ (->> (lib.metadata.protocols/metadatas-for-table metadata-provider :metadata/column source-table-id)
+ (keep (fn [col]
+ (when-let [tgt-id (:fk-target-field-id col)]
+ (when-let [tgt (lib.metadata.protocols/field metadata-provider tgt-id)]
+ {:source-field-id (:id col)
+ :source-field col
+ :target-field-id tgt-id
+ :target-table-id (:table-id tgt)}))))
+ vec))
+
+(defn- export-field-path
+ "Build the portable FK path for a field, including any JSON-unfolded parent chain."
+ [metadata-provider field]
+ (let [table (lib.metadata.protocols/table metadata-provider (:table-id field))
+ ;; Walk parent chain upward, then reverse to get root -> leaf order.
+ chain (loop [acc [(:name field)]
+ pid (:parent-id field)]
+ (if pid
+ (let [parent (lib.metadata.protocols/field metadata-provider pid)]
+ (recur (cons (:name parent) acc) (:parent-id parent)))
+ acc))]
+ (into [(db-name metadata-provider) (:schema table) (:name table)] chain)))
+
+;;; ============================================================
+;;; Content store - Metabase asset lookups (cards, etc.) by portable id
+;;; ============================================================
+
+(p.types/defprotocol+ ContentStore
+ "Lookup of Metabase content (\"assets\") by portable id.
+
+ Kept separate from the warehouse-metadata `MetadataProvider` so the resolver can be reused in
+ contexts without an application database (e.g. the serdes checker, in-memory tests)."
+ (card-by-entity-id [this entity-id]
+ "Return the card row for the given portable `entity_id`, or nil. The returned map must at
+ least carry `:id` and `:database_id` so the resolver can perform cross-database checks.")
+ (measure-by-entity-id [this entity-id]
+ "Return the measure row for the given portable `entity_id`, or nil. The returned map must
+ at least carry `:id` and `:table_id` so the resolver can perform cross-database checks via
+ the metadata provider.")
+ (segment-by-entity-id [this entity-id]
+ "Return the segment row for the given portable `entity_id`, or nil. Same contract as
+ `measure-by-entity-id`.")
+ (measure-by-id [this measure-id]
+ "Return the measure row for the given numeric id, or nil. Same contract as
+ `measure-by-entity-id`; used by the export direction (`[:measure {} <id>]` →
+ `[:measure {} \"<entity_id>\"]`). The returned map must carry `:entity_id` (or
+ `:entity-id`) and `:table_id` (or `:table-id`).")
+ (segment-by-id [this segment-id]
+ "Return the segment row for the given numeric id, or nil. Same contract as
+ `measure-by-id`."))
+
+(def unchecked-app-db-content-store
+ "**Unchecked.** No `api/read-check`; appropriate for serdes import / background tasks /
+ tests / dev REPL only. **Any HTTP or tool path that runs under an authenticated user must
+ wrap this with `metabase.metabot.tools.shared.content-store/read-checked`** (or use
+ `shared.content-store/default-store`, which is the wrapped form).
+
+ Default [[ContentStore]] backed by the Metabase application database via
+ `serdes/lookup-by-id`. Use this in production code paths that already have an app DB; pass a
+ different store implementation when running without one (checker, isolated tests).
+
+ Gated on [[resolve/entity-id?]]: `serdes/lookup-by-id` falls through to a full-table scan via
+ `find-by-identity-hash` for non-NanoID strings. LLM-authored entity-id values are untrusted,
+ so anything that isn't a 21-char NanoID short-circuits to `nil` and the caller surfaces a
+ clear `:unknown-…` agent error."
+ (reify ContentStore
+ (card-by-entity-id [_ entity-id]
+ (when (resolve/entity-id? entity-id)
+ (serdes/lookup-by-id 'Card entity-id)))
+ (measure-by-entity-id [_ entity-id]
+ (when (resolve/entity-id? entity-id)
+ (serdes/lookup-by-id 'Measure entity-id)))
+ (segment-by-entity-id [_ entity-id]
+ (when (resolve/entity-id? entity-id)
+ (serdes/lookup-by-id 'Segment entity-id)))
+ (measure-by-id [_ measure-id]
+ (when measure-id
+ (t2/select-one [:model/Measure :id :entity_id :table_id] :id measure-id)))
+ (segment-by-id [_ segment-id]
+ (when segment-id
+ (t2/select-one [:model/Segment :id :entity_id :table_id] :id segment-id)))))
+
+;;; ============================================================
+;;; Resolver implementations
+;;; ============================================================
+
+(defn- not-implemented! [method]
+ (throw (ex-info (tru "{0} is not implemented for the metadata-provider-backed resolver in Phase 1."
+ (name method))
+ {:status-code 501
+ :error :not-implemented-yet
+ :method method})))
+
+(defn- import-database-by-name
+ "Resolve a database by its portable name (a string) to a numeric id."
+ [metadata-provider db-name-value]
+ (let [current-name (db-name metadata-provider)
+ current-id (:id (lib.metadata/database metadata-provider))]
+ (if (= db-name-value current-name)
+ current-id
+ (throw (ex-info (tru "Portable database reference {0} does not match metadata provider database {1}."
+ (pr-str db-name-value) (pr-str current-name))
+ {:status-code 400
+ :error :unknown-database
+ :database db-name-value
+ :expected-db current-name})))))
+
+(defn- export-database-name
+ "Resolve the current database's numeric id back to its portable name."
+ [metadata-provider database-id]
+ (when database-id
+ (let [current-db (lib.metadata/database metadata-provider)]
+ (if (= database-id (:id current-db))
+ (:name current-db)
+ (throw (ex-info (tru "Cannot export database id {0}: metadata provider is for database id {1}."
+ database-id (:id current-db))
+ {:status-code 400
+ :error :unknown-database-id
+ :database-id database-id
+ :expected-id (:id current-db)}))))))
+
+(defn- card-model? [model]
+ (or (= model 'Card) (= model :model/Card)))
+
+(defn- measure-model? [model]
+ (or (= model 'Measure) (= model :model/Measure)))
+
+(defn- segment-model? [model]
+ (or (= model 'Segment) (= model :model/Segment)))
+
+(defn- table-belongs-to-current-database?
+ "True when the table with `table-id` is known to the metadata provider — measures and segments
+ are scoped to a table, so this is the cross-database guard for measure/segment refs. Returns
+ the table when found so callers can pull its `:db-id` for error messages."
+ [metadata-provider table-id]
+ (when table-id
+ (lib.metadata.protocols/table metadata-provider table-id)))
+
+(defn- export-card-by-id
+ "Resolve a saved question / model / metric by numeric id to its portable `entity_id`.
+
+ Uses the metadata provider rather than the generic app-DB serdes resolver so exporting a
+ final pMBQL query can stay paired with the same database-scoped provider used for table and
+ field FK export. Guards against accidental cross-database card refs."
+ [metadata-provider card-id]
+ (when card-id
+ (let [current-db-id (:id (lib.metadata/database metadata-provider))
+ card (lib.metadata.protocols/card metadata-provider card-id)
+ card-db-id (or (:database-id card) (:database_id card))
+ entity-id (or (:entity-id card) (:entity_id card))]
+ (cond
+ (nil? card)
+ (throw (ex-info (tru "No saved question, model, or metric found with id {0} in metadata provider." card-id)
+ {:status-code 400
+ :error :unknown-card-id
+ :card-id card-id}))
+
+ (not= card-db-id current-db-id)
+ (throw (ex-info (tru "Saved question / model / metric id {0} belongs to database {1}, but this resolver targets database {2}."
+ card-id card-db-id current-db-id)
+ {:status-code 400
+ :error :cross-database-card
+ :card-id card-id
+ :card-database-id card-db-id
+ :expected-database current-db-id}))
+
+ (not (and (string? entity-id) (seq entity-id)))
+ (throw (ex-info (tru "Saved question, model, or metric id {0} does not have an entity_id, so it cannot be exported as a portable representation." card-id)
+ {:status-code 400
+ :error :missing-card-entity-id
+ :card-id card-id}))
+
+ :else
+ entity-id))))
+
+(defn- import-card-by-entity-id
+ "Resolve a saved question / model by its portable `entity_id` to its numeric id.
+
+ Guards against the card belonging to a different database than the metadata provider -
+ that would produce a broken cross-database query at resolve time, so we surface a clear
+ agent-facing error here instead."
+ [metadata-provider content-store entity-id]
+ (let [current-db-id (:id (lib.metadata/database metadata-provider))
+ card (card-by-entity-id content-store entity-id)
+ ;; Card may come from a Toucan2 row (snake_case) or a `lib.metadata` map (kebab-case);
+ ;; mirror the defensive read in `export-card-by-id` so the test-side content stores can
+ ;; return either shape without breaking the cross-database guard.
+ card-db-id (when card (or (:database-id card) (:database_id card)))]
+ (cond
+ (nil? card)
+ (throw (ex-info (tru "No saved question or model found with entity_id {0}. Do not invent or guess entity_ids: call `entity_details` with `entity-type: question` or `entity-type: model` and the card''s numeric id first, then copy the exact `portable_entity_id` from the response into `source-card:`."
+ (pr-str entity-id))
+ {:agent-error? true
+ :status-code 400
+ :error :unknown-card
+ :entity-id entity-id}))
+
+ (not= card-db-id current-db-id)
+ (throw (ex-info (tru "Saved question / model {0} belongs to database {1}, but this query targets database {2}. Cross-database queries are not supported."
+ (pr-str entity-id)
+ (pr-str card-db-id)
+ (pr-str current-db-id))
+ {:agent-error? true
+ :status-code 400
+ :error :cross-database-card
+ :entity-id entity-id
+ :card-database-id card-db-id
+ :expected-database current-db-id}))
+
+ :else
+ (:id card))))
+
+(defn- import-measure-by-entity-id
+ "Resolve a measure by its portable `entity_id` to its numeric id.
+
+ Measures are scoped to a table, so the cross-database guard works through the metadata
+ provider: a measure whose `:table_id` is not known to the provider belongs to a different
+ database. Same pattern as [[import-card-by-entity-id]]."
+ [metadata-provider content-store entity-id]
+ (let [measure (measure-by-entity-id content-store entity-id)
+ measure-table-id (when measure (or (:table-id measure) (:table_id measure)))
+ measure-table (when measure-table-id
+ (table-belongs-to-current-database? metadata-provider measure-table-id))
+ current-db-id (:id (lib.metadata/database metadata-provider))]
+ (cond
+ (nil? measure)
+ (throw (ex-info (tru "No measure found with entity_id {0}. Do not invent or guess entity_ids: call `entity_details` on the table that owns the measure and copy the exact `portable_entity_id` from the `<measure>` tag."
+ (pr-str entity-id))
+ {:agent-error? true
+ :status-code 400
+ :error :unknown-measure
+ :entity-id entity-id}))
+
+ (nil? measure-table)
+ (throw (ex-info (tru "Measure {0} belongs to a table in a different database than this query (target database id {1}). Cross-database queries are not supported."
+ (pr-str entity-id) (pr-str current-db-id))
+ {:agent-error? true
+ :status-code 400
+ :error :cross-database-measure
+ :entity-id entity-id
+ :measure-table-id measure-table-id
+ :expected-database current-db-id}))
+
+ :else
+ (:id measure))))
+
+(defn- export-measure-by-id
+ "Resolve a measure by numeric id to its portable `entity_id`. Validates that the measure's
+ table belongs to the metadata provider's database (cross-database guard)."
+ [metadata-provider content-store measure-id]
+ (when measure-id
+ (let [measure (measure-by-id content-store measure-id)
+ measure-table-id (when measure (or (:table-id measure) (:table_id measure)))
+ measure-table (when measure-table-id
+ (table-belongs-to-current-database? metadata-provider measure-table-id))
+ entity-id (when measure (or (:entity-id measure) (:entity_id measure)))]
+ (cond
+ (nil? measure)
+ (throw (ex-info (tru "No measure found with id {0}." measure-id)
+ {:status-code 400
+ :error :unknown-measure-id
+ :measure-id measure-id}))
+
+ (nil? measure-table)
+ (throw (ex-info (tru "Measure id {0} belongs to a table outside this metadata provider''s database."
+ measure-id)
+ {:status-code 400
+ :error :cross-database-measure
+ :measure-id measure-id}))
+
+ (not (and (string? entity-id) (seq entity-id)))
+ (throw (ex-info (tru "Measure id {0} does not have an entity_id, so it cannot be exported as a portable representation."
+ measure-id)
+ {:status-code 400
+ :error :missing-measure-entity-id
+ :measure-id measure-id}))
+
+ :else
+ entity-id))))
+
+(defn- export-segment-by-id
+ "Resolve a segment by numeric id to its portable `entity_id`. Same pattern as
+ [[export-measure-by-id]]."
+ [metadata-provider content-store segment-id]
+ (when segment-id
+ (let [segment (segment-by-id content-store segment-id)
+ segment-table-id (when segment (or (:table-id segment) (:table_id segment)))
+ segment-table (when segment-table-id
+ (table-belongs-to-current-database? metadata-provider segment-table-id))
+ entity-id (when segment (or (:entity-id segment) (:entity_id segment)))]
+ (cond
+ (nil? segment)
+ (throw (ex-info (tru "No segment found with id {0}." segment-id)
+ {:status-code 400
+ :error :unknown-segment-id
+ :segment-id segment-id}))
+
+ (nil? segment-table)
+ (throw (ex-info (tru "Segment id {0} belongs to a table outside this metadata provider''s database."
+ segment-id)
+ {:status-code 400
+ :error :cross-database-segment
+ :segment-id segment-id}))
+
+ (not (and (string? entity-id) (seq entity-id)))
+ (throw (ex-info (tru "Segment id {0} does not have an entity_id, so it cannot be exported as a portable representation."
+ segment-id)
+ {:status-code 400
+ :error :missing-segment-entity-id
+ :segment-id segment-id}))
+
+ :else
+ entity-id))))
+
+(defn- import-segment-by-entity-id
+ "Resolve a segment by its portable `entity_id` to its numeric id. Same pattern as
+ [[import-measure-by-entity-id]]."
+ [metadata-provider content-store entity-id]
+ (let [segment (segment-by-entity-id content-store entity-id)
+ segment-table-id (when segment (or (:table-id segment) (:table_id segment)))
+ segment-table (when segment-table-id
+ (table-belongs-to-current-database? metadata-provider segment-table-id))
+ current-db-id (:id (lib.metadata/database metadata-provider))]
+ (cond
+ (nil? segment)
+ (throw (ex-info (tru "No segment found with entity_id {0}. Do not invent or guess entity_ids: call `entity_details` on the table that owns the segment and copy the exact `portable_entity_id` from the `<segment>` tag."
+ (pr-str entity-id))
+ {:agent-error? true
+ :status-code 400
+ :error :unknown-segment
+ :entity-id entity-id}))
+
+ (nil? segment-table)
+ (throw (ex-info (tru "Segment {0} belongs to a table in a different database than this query (target database id {1}). Cross-database queries are not supported."
+ (pr-str entity-id) (pr-str current-db-id))
+ {:agent-error? true
+ :status-code 400
+ :error :cross-database-segment
+ :entity-id entity-id
+ :segment-table-id segment-table-id
+ :expected-database current-db-id}))
+
+ :else
+ (:id segment))))
+
+(defn import-resolver
+ "Build a `SerdesImportResolver` backed by `metadata-provider` (warehouse metadata) and
+ `content-store` (Metabase content / assets).
+
+ The 1-arity form uses [[unchecked-app-db-content-store]] - i.e. it goes through
+ `serdes/lookup-by-id` for content lookups and therefore requires the application database.
+ **Note the \"unchecked\" prefix:** the default store does NOT apply `api/read-check`. HTTP /
+ tool paths that run under an authenticated user must pass an explicit content-store wrapped
+ with `metabase.metabot.tools.shared.content-store/read-checked`.
+
+ Implemented methods:
+ * `import-table-fk`, `import-field-fk` (Phase 1).
+ * `import-fk-keyed` for `:model/Database` by `:name` (Phase 1 - needed because
+ `resolve/import-mbql` dispatches on `:database` keys).
+ * `import-fk` for `Card` / `:model/Card` by `entity_id` (Phase 2, step 11).
+
+ Other methods throw `:not-implemented-yet`."
+ ([metadata-provider]
+ (import-resolver metadata-provider unchecked-app-db-content-store))
+ ([metadata-provider content-store]
+ (reify resolve/SerdesImportResolver
+ (import-fk [_ eid model]
+ (cond
+ (nil? eid) nil
+ (card-model? model) (import-card-by-entity-id metadata-provider content-store eid)
+ (measure-model? model) (import-measure-by-entity-id metadata-provider content-store eid)
+ (segment-model? model) (import-segment-by-entity-id metadata-provider content-store eid)
+ :else (not-implemented! :import-fk)))
+ (import-fk-keyed [_ portable model field]
+ (cond
+ (and (or (= model :model/Database) (= model 'Database))
+ (= field :name))
+ (import-database-by-name metadata-provider portable)
+
+ :else
+ (not-implemented! :import-fk-keyed)))
+ (import-user [_ _email] (not-implemented! :import-user))
+ (import-table-fk [_ path]
+ (when path
+ (:id (find-table metadata-provider path))))
+ (import-field-fk [_ path]
+ (when path
+ (:id (find-field metadata-provider path)))))))
+
+(defn export-resolver
+ "Build a `SerdesExportResolver` backed by `metadata-provider`.
+
+ Implemented methods:
+ * `export-table-fk`, `export-field-fk` for warehouse metadata.
+ * `export-fk-keyed` for `:model/Database` by `:name`.
+ * `export-fk` for `Card` / `:model/Card` by `entity_id` (source-card and metric refs).
+ * `export-fk` for `:model/Measure` and `:model/Segment` by `entity_id`.
+
+ Other methods throw `:not-implemented-yet`."
+ ([metadata-provider]
+ (export-resolver metadata-provider unchecked-app-db-content-store))
+ ([metadata-provider content-store]
+ (reify resolve/SerdesExportResolver
+ (export-fk [_ id model]
+ (cond
+ (nil? id) nil
+ (card-model? model) (export-card-by-id metadata-provider id)
+ (measure-model? model) (export-measure-by-id metadata-provider content-store id)
+ (segment-model? model) (export-segment-by-id metadata-provider content-store id)
+ :else (not-implemented! :export-fk)))
+ (export-fk-keyed [_ id model field]
+ (cond
+ (nil? id) nil
+
+ (and (or (= model :model/Database) (= model 'Database))
+ (= field :name))
+ (export-database-name metadata-provider id)
+
+ :else
+ (not-implemented! :export-fk-keyed)))
+ (export-user [_ _id] (not-implemented! :export-user))
+ (export-table-fk [_ table-id]
+ (when table-id
+ (let [t (lib.metadata.protocols/table metadata-provider table-id)]
+ (when-not t
+ (throw (ex-info (tru "No table with id {0} in metadata provider." table-id)
+ {:status-code 400
+ :error :unknown-table-id
+ :table-id table-id})))
+ [(db-name metadata-provider) (:schema t) (:name t)])))
+ (export-field-fk [_ field-id]
+ (when field-id
+ (let [f (lib.metadata.protocols/field metadata-provider field-id)]
+ (when-not f
+ (throw (ex-info (tru "No field with id {0} in metadata provider." field-id)
+ {:status-code 400
+ :error :unknown-field-id
+ :field-id field-id})))
+ (export-field-path metadata-provider f)))))))
diff --git a/test/metabase/agent_api/api_test.clj b/test/metabase/agent_api/api_test.clj
index c64d797675b..d0636d7fbd2 100644
--- a/test/metabase/agent_api/api_test.clj
+++ b/test/metabase/agent_api/api_test.clj
@@ -252,57 +252,177 @@
[response]
(-> response :query u/decode-base64 json/decode+kw lib.normalize/normalize))
+;;; ---------------------------------------- Repr JSON helpers ----------------------------------------
+
+(defn- db-name
+ "Canonical name of the application database \u2014 the literal string the LLM is expected
+ to put as the first element of every portable FK in a representations query."
+ []
+ (t2/select-one-fn :name :model/Database (mt/id)))
+
+(defn- orders-query
+ "Build a portable MBQL 5 representations external-query map against the `ORDERS` table in
+ the application database. Clause arguments (`aggregation`, `breakout`, `filters`, `order-by`,
+ `fields`) are Clojure data fed straight through to the HTTP body, e.g.
+
+ (orders-query :limit 10)
+ (orders-query :aggregation [[\"count\" {}]])
+ (orders-query :filters [[\"not-null\" {} (orders-field-ref \"ID\")]])
+
+ Structural validation against `::lib.schema/external-query` lives on the server side; here
+ we just need a believable payload to drive the HTTP endpoint."
+ [& {:keys [limit aggregation breakout filters order-by fields]}]
+ {:lib/type "mbql/query"
+ :stages [(cond-> {:lib/type "mbql.stage/mbql"
+ :source-table [(db-name) "PUBLIC" "ORDERS"]}
+ aggregation (assoc :aggregation (vec aggregation))
+ breakout (assoc :breakout (vec breakout))
+ filters (assoc :filters (vec filters))
+ order-by (assoc :order-by (vec order-by))
+ fields (assoc :fields (vec fields))
+ limit (assoc :limit limit))]})
+
+(defn- orders-field-ref
+ "Field-ref clause against an ORDERS column as Clojure data, e.g.
+ `[\"field\" {} [\"test-data (h2)\" \"PUBLIC\" \"ORDERS\" \"ID\"]]`. Suitable as an inner
+ argument inside `aggregation` / `filters` / `order-by` clauses passed to [[orders-query]]."
+ [col-name]
+ ["field" {} [(db-name) "PUBLIC" "ORDERS" col-name]])
+
+(defn- source-card-query
+ "Build a minimal portable representations external-query map whose first stage uses
+ `source-card:`."
+ [entity-id]
+ {:lib/type "mbql/query"
+ :stages [{:lib/type "mbql.stage/mbql"
+ :source-card entity-id
+ :limit 5}]})
+
+;;; ---------------------------------------- /v2/construct-query ----------------------------------------
+
(deftest construct-query-test
(testing "Constructs a simple query from a table"
- (let [table-id (mt/id :orders)
- response (mt/user-http-request :rasta :post 200 "agent/v2/construct-query"
- {:source {:type "table" :id table-id}
- :operations []
- :prompt "show orders"})]
+ (let [response (mt/user-http-request :rasta :post 200 "agent/v2/construct-query"
+ {:query (orders-query)})]
(is (string? (:query response)) "Response should contain a query string")
- (is (= "show orders" (:prompt response)) "Response should echo the prompt")
(let [decoded (decode-query response)]
(is (= :mbql/query (lib/normalized-query-type decoded)))
(is (= (mt/id) (lib/database-id decoded)))
(is (= (mt/id :orders) (lib/primary-source-table-id decoded))))))
- (testing "Does not require prompt"
- (let [table-id (mt/id :orders)
- response (mt/user-http-request :rasta :post 200 "agent/v2/construct-query"
- {:source {:type "table" :id table-id}
- :operations []})]
- (is (string? (:query response)) "Response should contain a query string")
- (is (not (contains? response :prompt)) "Response should only echo prompt when supplied")))
-
- (testing "Rejects oversized prompts before they can be persisted on MCP query handles"
- (mt/user-http-request :rasta :post 400 "agent/v2/construct-query"
- {:source {:type "table" :id (mt/id :orders)}
- :operations []
- :prompt (apply str (repeat 10001 "x"))}))
-
- (testing "Respects explicit limit operation"
- (let [table-id (mt/id :orders)
- response (mt/user-http-request :rasta :post 200 "agent/v2/construct-query"
- {:source {:type "table" :id table-id}
- :operations [["limit" 10]]
- :prompt "show 10 orders"})
+ (testing "Respects explicit limit on the stage"
+ (let [response (mt/user-http-request :rasta :post 200 "agent/v2/construct-query"
+ {:query (orders-query :limit 10)})
decoded (decode-query response)]
(is (= 10 (lib/current-limit decoded)))))
- (testing "Returns 404 for non-existent table"
- (is (= "Not found."
- (mt/user-http-request :rasta :post 404 "agent/v2/construct-query"
- {:source {:type "table" :id 999999}
- :operations []
- :prompt "show orders"})))))
+ (testing "Returns 400 with `:unknown-table` ex-data for an unknown table FK"
+ ;; Note: the new repr contract surfaces unknown-input errors as 400 (`:agent-error?`)
+ ;; rather than the old 404 — the LLM is expected to read the message and self-correct.
+ ;; ex-data values are stringified by the JSON roundtrip, so we match the keyword's name.
+ (let [response (mt/user-http-request :rasta :post 400 "agent/v2/construct-query"
+ {:query {:lib/type "mbql/query"
+ :stages [{:lib/type "mbql.stage/mbql"
+ :source-table [(db-name) "PUBLIC" "NOT_A_TABLE"]}]}})]
+ (is (=? {:error "unknown-table"} response))))
+
+ (testing "Rejects a non-aggregation in the aggregation slot with a 400"
+ ;; The endpoint's wire schema is intentionally permissive (`:query :map`); deep
+ ;; validation happens inside the representations pipeline. A `field` clause where an
+ ;; aggregation clause is expected is caught by the E1 friendly-error pass and surfaced
+ ;; as `:aggregation-entry-not-aggregation` with `:agent-error? true`, so the LLM gets
+ ;; a clean diagnostic instead of a generic schema error.
+ (let [response (mt/user-http-request :rasta :post 400 "agent/v2/construct-query"
+ {:query (orders-query
+ :aggregation [(orders-field-ref "ID")])})]
+ (is (=? {:error "aggregation-entry-not-aggregation"} response)))))
+
+(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!
+ (is (= "You don't have permissions to do that."
+ (mt/user-http-request :rasta :post 403 "agent/v2/construct-query"
+ {:query (orders-query :aggregation [["count" {}]])})))))
+
+ (testing "Rejects a first-stage source-card the current user cannot read"
+ (mt/with-non-admin-groups-no-root-collection-perms
+ (let [mp (mt/metadata-provider)]
+ (mt/with-temp [:model/Collection _collection {}
+ :model/Card card {:name "Protected Question"
+ :collection_id (:id _collection)
+ :database_id (mt/id)
+ :dataset_query (lib/query mp (lib.metadata/table mp (mt/id :orders)))}]
+ (is (= "You don't have permissions to do that."
+ (mt/user-http-request :rasta :post 403 "agent/v2/construct-query"
+ {:query (source-card-query (:entity_id card))})))))))
+
+ (testing "Rejects a metric aggregation the current user cannot read"
+ (mt/with-non-admin-groups-no-root-collection-perms
+ (mt/with-temp [:model/Collection _collection {}
+ :model/Card metric {:name "Protected Metric"
+ :type :metric
+ :collection_id (:id _collection)
+ :database_id (mt/id)
+ :dataset_query (orders-count-query)}]
+ (is (= "You don't have permissions to do that."
+ (mt/user-http-request :rasta :post 403 "agent/v2/construct-query"
+ {:query (orders-query
+ :aggregation [["metric" {} (:entity_id metric)]])})))))))
+
+(deftest construct-query-rejects-empty-query-test
+ (testing "Empty / blank :query is rejected by the request schema"
+ (mt/user-http-request :rasta :post 400 "agent/v2/construct-query" {:query ""}))
+ (testing "Missing :query in body is rejected by the request schema"
+ (mt/user-http-request :rasta :post 400 "agent/v2/construct-query" {})))
+
+(deftest construct-query-rejects-typod-stage-keys-test
+ (testing (str "The agent boundary asserts every stage's top-level keys are in a known set. "
+ "`lib.schema.mbql-stage/mbql` is not a closed map, so typo'd stage keys "
+ "(e.g. `aggreagation` for `aggregation`) would otherwise be silently dropped "
+ "at resolve time and the LLM would never learn that its intent was discarded.")
+ (testing "typo'd `aggreagation` is rejected with :unknown-stage-key"
+ (let [response (mt/user-http-request
+ :rasta :post 400 "agent/v2/construct-query"
+ {:query {:lib/type "mbql/query"
+ :stages [{:lib/type "mbql.stage/mbql"
+ :source-table [(db-name) "PUBLIC" "ORDERS"]
+ :aggreagation [["count" {}]]}]}})]
+ (is (=? {:error "unknown-stage-key"} response))
+ (is (=? {:unknown-keys ["aggreagation"]} response))))
+ (testing "diagnostic lists the valid stage keys so the LLM can self-correct"
+ (let [response (mt/user-http-request
+ :rasta :post 400 "agent/v2/construct-query"
+ {:query {:lib/type "mbql/query"
+ :stages [{:lib/type "mbql.stage/mbql"
+ :source-table [(db-name) "PUBLIC" "ORDERS"]
+ :groupby ["foo"]}]}})]
+ (is (=? {:error "unknown-stage-key"} response))
+ (is (re-find #"aggregation" (:message response)))))))
+
+(deftest construct-query-rejects-legacy-envelope-test
+ (testing (str "Legacy `source_entity` / `referenced_entities` envelope from the pre-repr program API "
+ "is rejected by the now-closed request schema, instead of being silently ignored. "
+ "This guards against a regression where the LLM's stale memory keeps sending the old "
+ "shape and we silently drop the extra keys.")
+ (is (=? {:specific-errors {:source_entity #(some (fn [s] (re-find #"disallowed key" s)) %)}}
+ (mt/user-http-request :rasta :post 400 "agent/v2/construct-query"
+ {:query (orders-query)
+ :source_entity {:type "table" :id (mt/id :orders)}}))))
+ (testing "`/v2/query` fresh-query branch rejects the legacy envelope as well"
+ (is (=? {:specific-errors {:referenced_entities #(some (fn [s] (re-find #"disallowed key" s)) %)}}
+ (mt/user-http-request :rasta :post 400 "agent/v2/query"
+ {:query (orders-query :limit 5)
+ :referenced_entities []}))))
+ (testing "`/v2/query` continuation_token branch rejects extra keys (closed schema)"
+ (is (=? {:specific-errors {:query #(some (fn [s] (re-find #"disallowed key" s)) %)}}
+ (mt/user-http-request :rasta :post 400 "agent/v2/query"
+ {:continuation_token "not-a-real-token"
+ :query (orders-query :limit 5)})))))
(deftest execute-query-test
(testing "Executes a query and returns results with column metadata"
- (let [table-id (mt/id :orders)
- construct-resp (mt/user-http-request :rasta :post 200 "agent/v2/construct-query"
- {:source {:type "table" :id table-id}
- :operations [["limit" 5]]
- :prompt "show 5 orders"})
+ (let [construct-resp (mt/user-http-request :rasta :post 200 "agent/v2/construct-query"
+ {:query (orders-query :limit 5)})
;; Streaming response returns 202 (accepted) since it starts streaming before completion
execute-resp (mt/user-http-request :rasta :post 202 "agent/v1/execute"
{:query (:query construct-resp)})]
@@ -316,11 +436,8 @@
execute-resp))))
(testing "Enforces agent query row limit even when query specifies a higher limit"
- (let [table-id (mt/id :orders)
- construct-resp (mt/user-http-request :rasta :post 200 "agent/v2/construct-query"
- {:source {:type "table" :id table-id}
- :operations [["limit" 300]]
- :prompt "show all orders"})
+ (let [construct-resp (mt/user-http-request :rasta :post 200 "agent/v2/construct-query"
+ {:query (orders-query :limit 300)})
execute-resp (mt/user-http-request :rasta :post 202 "agent/v1/execute"
{:query (:query construct-resp)})]
(is (=? {:status "completed" :row_count 200}
@@ -355,44 +472,41 @@
:type :metric
:database_id (mt/id)
:dataset_query (orders-count-query)}]
- (testing "Constructs a query from a metric"
+ (testing "Constructs a query that references a metric by entity_id in an aggregation"
(let [response (mt/user-http-request :rasta :post 200 "agent/v2/construct-query"
- {:source {:type "metric" :id (:id metric)}
- :operations []
- :prompt "show metric"})]
+ {:query (orders-query
+ :aggregation [["metric" {} (:entity_id metric)]])})]
(is (string? (:query response)) "Response should contain a query string")
(let [decoded (decode-query response)]
(is (= :mbql/query (lib/normalized-query-type decoded)))
- (is (= (mt/id) (lib/database-id decoded))))))
-
- (testing "Returns 404 for non-existent metric"
- (is (= "Not found."
- (mt/user-http-request :rasta :post 404 "agent/v2/construct-query"
- {:source {:type "metric" :id 999999}
- :operations []
- :prompt "show metric"}))))))
+ (is (= (mt/id) (lib/database-id decoded)))
+ (is (= 1 (count (lib/aggregations decoded)))))))
+
+ (testing "Returns 400 with `:unknown-card` ex-data for an unknown metric entity_id"
+ ;; The entity_id must be a syntactically-valid 21-char NanoID for the resolver to
+ ;; even attempt the lookup; otherwise the metric clause's literal string survives to
+ ;; lib.schema validation and we get a different (less useful) error class. Pick a
+ ;; well-formed but absent eid to drive the `:unknown-card` path specifically.
+ (let [response (mt/user-http-request :rasta :post 400 "agent/v2/construct-query"
+ {:query (orders-query
+ :aggregation [["metric" {} "AAAAAAAAAAAAAAAAAAAAA"]])})]
+ (is (=? {:error "unknown-card"} response))))))
(deftest construct-query-with-count-aggregation-test
(testing "Count aggregation produces a valid query"
- (let [table-id (mt/id :orders)
- response (mt/user-http-request :rasta :post 200 "agent/v2/construct-query"
- {:source {:type "table" :id table-id}
- :operations [["aggregate" ["count"]]
- ["limit" 10]]
- :prompt "count orders"})]
+ (let [response (mt/user-http-request :rasta :post 200 "agent/v2/construct-query"
+ {:query (orders-query :aggregation [["count" {}]]
+ :limit 10)})]
(is (string? (:query response)))
(let [decoded (decode-query response)]
(is (= 1 (count (lib/aggregations decoded))))))))
(deftest construct-query-with-filters-test
(testing "Constructs a query with filters"
- (let [table-id (mt/id :orders)
- field-id (mt/id :orders :id)
- response (mt/user-http-request :rasta :post 200 "agent/v2/construct-query"
- {:source {:type "table" :id table-id}
- :operations [["filter" ["not-null" ["field" field-id]]]
- ["limit" 10]]
- :prompt "show filtered orders"})]
+ (let [response (mt/user-http-request :rasta :post 200 "agent/v2/construct-query"
+ {:query (orders-query
+ :filters [["not-null" {} (orders-field-ref "ID")]]
+ :limit 10)})]
(is (string? (:query response)))
(let [decoded (decode-query response)]
(is (seq (lib/filters decoded)) "Query should have filters")))))
@@ -418,12 +532,9 @@
(deftest combined-query-test
(testing "Returns results for a table query that fits in a single page"
- (let [table-id (mt/id :orders)
- field-id (visible-field-id table-id "ID")
- response (mt/user-http-request :rasta :post 202 "agent/v2/query"
- {:source {:type "table" :id table-id}
- :operations [["order-by" ["field" field-id]]
- ["limit" 5]]})]
+ (let [response (mt/user-http-request :rasta :post 202 "agent/v2/query"
+ {:query (orders-query :order-by [["asc" {} (orders-field-ref "ID")]]
+ :limit 5)})]
(is (=? {:status "completed"
:row_count 5
:continuation_token nil?
@@ -432,14 +543,11 @@
response))))
(testing "Continuation token returns next page of results when the total limit exceeds the page size"
- (let [table-id (mt/id :orders)
- field-id (visible-field-id table-id "ID")
- page-size 200
+ (let [page-size 200
total-rows 250
page1 (mt/user-http-request :rasta :post 202 "agent/v2/query"
- {:source {:type "table" :id table-id}
- :operations [["order-by" ["field" field-id]]
- ["limit" total-rows]]})
+ {:query (orders-query :order-by [["asc" {} (orders-field-ref "ID")]]
+ :limit total-rows)})
page2 (mt/user-http-request :rasta :post 202 "agent/v2/query"
{:continuation_token (:continuation_token page1)})]
(is (=? {:row_count page-size
@@ -458,15 +566,13 @@
(is (=? {:status "completed"
:continuation_token nil?}
(mt/user-http-request :rasta :post 202 "agent/v2/query"
- {:source {:type "table" :id (mt/id :orders)}
- :operations [["aggregate" ["count"]]]}))))
+ {:query (orders-query :aggregation [["count" {}]])}))))
(testing "Per-page cap limits a single page to 200 rows even when the total limit is higher"
(is (=? {:status "completed"
:row_count (fn [n] (<= n 200))}
(mt/user-http-request :rasta :post 202 "agent/v2/query"
- {:source {:type "table" :id (mt/id :orders)}
- :operations [["limit" 1000]]})))))
+ {:query (orders-query :limit 1000)})))))
(defn- make-continuation-token [pagination]
(-> {:query {:database (mt/id) :stages [{:source-table (mt/id :orders)}]}
@@ -493,12 +599,12 @@
:type :metric
:database_id (mt/id)
:dataset_query (orders-count-query)}]
- (testing "Returns results for a metric query"
+ (testing "Returns results for a query that aggregates via a metric reference"
(is (=? {:status "completed"
:row_count pos?}
(mt/user-http-request :rasta :post 202 "agent/v2/query"
- {:source {:type "metric" :id (:id metric)}
- :operations []}))))))
+ {:query (orders-query
+ :aggregation [["metric" {} (:entity_id metric)]])}))))))
(deftest search-finds-metrics-test
(binding [search.ingestion/*force-sync* true]
@@ -518,8 +624,7 @@
(deftest create-question-test
(testing "Creates a saved question from a constructed query"
(let [construct-resp (mt/user-http-request :rasta :post 200 "agent/v2/construct-query"
- {:source {:type "table" :id (mt/id :orders)}
- :operations [["limit" 10]]})
+ {:query (orders-query :limit 10)})
create-resp (mt/user-http-request :rasta :post 200 "agent/v1/question"
{:name "Agent Test Question"
:query (:query construct-resp)})]
@@ -535,8 +640,7 @@
(testing "Creates a question with optional fields"
(mt/with-temp [:model/Collection {coll-id :id} {:name "Agent Question Collection"}]
(let [construct-resp (mt/user-http-request :rasta :post 200 "agent/v2/construct-query"
- {:source {:type "table" :id (mt/id :orders)}
- :operations [["limit" 10]]})
+ {:query (orders-query :limit 10)})
create-resp (mt/user-http-request :rasta :post 200 "agent/v1/question"
{:name "Agent Question With Options"
:query (:query construct-resp)
diff --git a/test/metabase/agent_lib/capabilities/catalog_test.clj b/test/metabase/agent_lib/capabilities/catalog_test.clj
deleted file mode 100644
index 7e1391b7969..00000000000
--- a/test/metabase/agent_lib/capabilities/catalog_test.clj
+++ /dev/null
@@ -1,43 +0,0 @@
-(ns metabase.agent-lib.capabilities.catalog-test
- (:require
- [clojure.test :refer [deftest is]]
- [metabase.agent-lib.capabilities :as capabilities]
- [metabase.agent-lib.capabilities.catalog :as catalog]
- [metabase.agent-lib.capabilities.catalog.aggregation :as aggregation]
- [metabase.agent-lib.capabilities.catalog.expressions :as expressions]
- [metabase.agent-lib.capabilities.catalog.filtering :as filtering]
- [metabase.agent-lib.capabilities.catalog.joins :as joins]
- [metabase.agent-lib.capabilities.catalog.ordering :as ordering]
- [metabase.agent-lib.capabilities.catalog.sources :as sources]
- [metabase.agent-lib.capabilities.catalog.top-level :as top-level]))
-
-(deftest ^:parallel grouped-capability-catalog-preserves-review-groups-and-order-test
- (is (= [:top-level
- :sources
- :filtering
- :aggregation
- :breakout-ordering
- :expressions
- :joins]
- (mapv :group catalog/grouped-capability-catalog)))
- (is (= [top-level/capabilities
- sources/capabilities
- filtering/capabilities
- aggregation/capabilities
- ordering/capabilities
- expressions/capabilities
- joins/capabilities]
- (mapv :capabilities catalog/grouped-capability-catalog))))
-
-(deftest ^:parallel raw-capability-catalog-flattens-the-grouped-catalog-test
- (let [expected (into []
- cat
- [top-level/capabilities
- sources/capabilities
- filtering/capabilities
- aggregation/capabilities
- ordering/capabilities
- expressions/capabilities
- joins/capabilities])]
- (is (= expected catalog/raw-capability-catalog))
- (is (= expected capabilities/raw-capability-catalog))))
diff --git a/test/metabase/agent_lib/common/coercions_test.clj b/test/metabase/agent_lib/common/coercions_test.clj
deleted file mode 100644
index 2552c24a968..00000000000
--- a/test/metabase/agent_lib/common/coercions_test.clj
+++ /dev/null
@@ -1,113 +0,0 @@
-(ns metabase.agent-lib.common.coercions-test
- (:require
- [clojure.test :refer [deftest is testing]]
- [metabase.agent-lib.common.coercions :as coercions]))
-
-(deftest ^:parallel quarter-label->number-test
- (testing "converts Q labels to integers"
- (is (= 1 (coercions/quarter-label->number "Q1")))
- (is (= 2 (coercions/quarter-label->number "q2")))
- (is (= 3 (coercions/quarter-label->number " Q3 ")))
- (is (= 4 (coercions/quarter-label->number "Q4"))))
- (testing "returns nil for invalid inputs"
- (is (nil? (coercions/quarter-label->number "Q5")))
- (is (nil? (coercions/quarter-label->number "Q0")))
- (is (nil? (coercions/quarter-label->number "abc")))
- (is (nil? (coercions/quarter-label->number nil)))))
-
-(deftest ^:parallel parse-int-string-test
- (testing "parses valid integer strings"
- (is (= 42 (coercions/parse-int-string "42")))
- (is (= -7 (coercions/parse-int-string "-7")))
- (is (= 0 (coercions/parse-int-string "0"))))
- (testing "returns nil for invalid inputs"
- (is (nil? (coercions/parse-int-string "abc")))
- (is (nil? (coercions/parse-int-string "3.14")))
- (is (nil? (coercions/parse-int-string "")))
- (is (nil? (coercions/parse-int-string nil)))))
-
-(deftest ^:parallel coerce-positive-int-test
- (testing "passes through positive integers"
- (is (= 5 (coercions/coerce-positive-int 5))))
- (testing "coerces positive integer strings"
- (is (= 5 (coercions/coerce-positive-int "5")))
- (is (= 100 (coercions/coerce-positive-int "100"))))
- (testing "does not coerce non-positive strings"
- (is (= "0" (coercions/coerce-positive-int "0")))
- (is (= "-1" (coercions/coerce-positive-int "-1"))))
- (testing "passes through non-string values"
- (is (= :kw (coercions/coerce-positive-int :kw)))
- (is (= -1 (coercions/coerce-positive-int -1)))))
-
-(deftest ^:parallel coerce-non-negative-int-test
- (testing "passes through non-negative integers"
- (is (= 0 (coercions/coerce-non-negative-int 0)))
- (is (= 5 (coercions/coerce-non-negative-int 5))))
- (testing "coerces non-negative integer strings"
- (is (= 0 (coercions/coerce-non-negative-int "0")))
- (is (= 42 (coercions/coerce-non-negative-int "42"))))
- (testing "does not coerce negative strings"
- (is (= "-1" (coercions/coerce-non-negative-int "-1"))))
- (testing "passes through non-string values"
- (is (= :kw (coercions/coerce-non-negative-int :kw)))))
-
-(deftest ^:parallel direction-string-test
- (testing "recognizes direction strings"
- (is (true? (coercions/direction-string? "asc")))
- (is (true? (coercions/direction-string? "desc")))
- (is (true? (coercions/direction-string? "ASC")))
- (is (true? (coercions/direction-string? :desc))))
- (testing "rejects non-direction values"
- (is (false? (coercions/direction-string? "up")))
- (is (false? (coercions/direction-string? nil)))))
-
-(deftest ^:parallel normalize-direction-test
- (testing "normalizes to lowercase string"
- (is (= "asc" (coercions/normalize-direction "ASC")))
- (is (= "desc" (coercions/normalize-direction :desc)))
- (is (= "asc" (coercions/normalize-direction 'asc))))
- (testing "returns nil for nil"
- (is (nil? (coercions/normalize-direction nil)))))
-
-(deftest ^:parallel unwrap-singleton-form-test
- (testing "unwraps nested singletons but stops at scalar-sequential"
- (is (= [5] (coercions/unwrap-singleton-form [[[[5]]]]))))
- (testing "stops at operator tuples"
- (is (= ["field" 1] (coercions/unwrap-singleton-form [[["field" 1]]]))))
- (testing "passes through non-singleton vectors"
- (is (= [1 2] (coercions/unwrap-singleton-form [1 2]))))
- (testing "passes through scalars"
- (is (= "hello" (coercions/unwrap-singleton-form "hello")))
- (is (= 42 (coercions/unwrap-singleton-form 42)))))
-
-(deftest ^:parallel normalize-percentile-value-test
- (testing "converts whole-number percentages to fractions"
- (is (= 0.9 (coercions/normalize-percentile-value 90)))
- (is (= 0.5 (coercions/normalize-percentile-value 50)))
- (is (= 1.0 (coercions/normalize-percentile-value 100))))
- (testing "passes through values already in fraction form"
- (is (= 0.9 (coercions/normalize-percentile-value 0.9)))
- (is (= 0.5 (coercions/normalize-percentile-value 0.5))))
- (testing "boundary: 1.0 is already a fraction"
- (is (= 1.0 (coercions/normalize-percentile-value 1.0))))
- (testing "passes through non-numbers"
- (is (= "abc" (coercions/normalize-percentile-value "abc")))))
-
-(deftest ^:parallel normalize-join-conditions-test
- (testing "unwraps extra singleton nesting"
- (is (= [["=" ["field" 1] ["field" 2]]]
- (coercions/normalize-join-conditions [[["=" ["field" 1] ["field" 2]]]]))))
- (testing "leaves properly-structured conditions alone"
- (is (= [["=" ["field" 1] ["field" 2]]]
- (coercions/normalize-join-conditions [["=" ["field" 1] ["field" 2]]]))))
- (testing "handles deeply nested singleton wrapping"
- (is (= [["=" ["field" 1] ["field" 2]]]
- (coercions/normalize-join-conditions [[[["=" ["field" 1] ["field" 2]]]]])))))
-
-(deftest ^:parallel normalize-map-key-test
- (testing "converts string keys to keywords"
- (is (= :foo (coercions/normalize-map-key "foo"))))
- (testing "passes through keyword keys"
- (is (= :bar (coercions/normalize-map-key :bar))))
- (testing "passes through non-string keys"
- (is (= 42 (coercions/normalize-map-key 42)))))
diff --git a/test/metabase/agent_lib/common/context_test.clj b/test/metabase/agent_lib/common/context_test.clj
deleted file mode 100644
index c6e61bea941..00000000000
--- a/test/metabase/agent_lib/common/context_test.clj
+++ /dev/null
@@ -1,25 +0,0 @@
-(ns metabase.agent-lib.common.context-test
- (:require
- [clojure.test :refer [deftest is testing]]
- [metabase.agent-lib.common.context :as context]))
-
-(deftest ^:parallel source-metric-id-test
- (testing "returns id for metric source entities"
- (is (= 42 (context/source-metric-id {:source-entity {:model "metric" :id 42}}))))
- (testing "returns nil for table source entities"
- (is (nil? (context/source-metric-id {:source-entity {:model "table" :id 1}}))))
- (testing "returns nil for non-positive ids"
- (is (nil? (context/source-metric-id {:source-entity {:model "metric" :id 0}})))
- (is (nil? (context/source-metric-id {:source-entity {:model "metric" :id -1}}))))
- (testing "returns nil for missing source-entity"
- (is (nil? (context/source-metric-id {})))))
-
-(deftest ^:parallel source-table-id-test
- (testing "returns id for table source entities"
- (is (= 1 (context/source-table-id {:source-entity {:model "table" :id 1}}))))
- (testing "returns nil for metric source entities"
- (is (nil? (context/source-table-id {:source-entity {:model "metric" :id 42}}))))
- (testing "returns nil for non-positive ids"
- (is (nil? (context/source-table-id {:source-entity {:model "table" :id 0}}))))
- (testing "returns nil for missing source-entity"
- (is (nil? (context/source-table-id {})))))
diff --git a/test/metabase/agent_lib/common/literals_test.clj b/test/metabase/agent_lib/common/literals_test.clj
deleted file mode 100644
index eaf67789243..00000000000
--- a/test/metabase/agent_lib/common/literals_test.clj
+++ /dev/null
@@ -1,133 +0,0 @@
-(ns metabase.agent-lib.common.literals-test
- (:require
- [clojure.test :refer [deftest is testing]]
- [metabase.agent-lib.common.literals :as literals]))
-
-(deftest ^:parallel scalar-literal-test
- (testing "nil is a scalar literal"
- (is (true? (literals/scalar-literal? nil))))
- (testing "strings are scalar literals"
- (is (true? (literals/scalar-literal? "hello")))
- (is (true? (literals/scalar-literal? ""))))
- (testing "numbers are scalar literals"
- (is (true? (literals/scalar-literal? 42)))
- (is (true? (literals/scalar-literal? 3.14)))
- (is (true? (literals/scalar-literal? 0))))
- (testing "booleans are scalar literals"
- (is (true? (literals/scalar-literal? true)))
- (is (true? (literals/scalar-literal? false))))
- (testing "maps and vectors are not scalar literals"
- (is (false? (literals/scalar-literal? {})))
- (is (false? (literals/scalar-literal? [])))
- (is (false? (literals/scalar-literal? :keyword)))))
-
-(deftest ^:parallel non-blank-string-test
- (testing "non-blank strings"
- (is (true? (literals/non-blank-string? "hello")))
- (is (true? (literals/non-blank-string? " x "))))
- (testing "blank strings"
- (is (false? (literals/non-blank-string? "")))
- (is (false? (literals/non-blank-string? " "))))
- (testing "non-strings"
- (is (false? (literals/non-blank-string? nil)))
- (is (false? (literals/non-blank-string? 42)))))
-
-(deftest ^:parallel quarter-label-string-test
- (testing "valid quarter labels"
- (is (some? (literals/quarter-label-string? "Q1")))
- (is (some? (literals/quarter-label-string? "Q4")))
- (is (some? (literals/quarter-label-string? "q2")))
- (is (some? (literals/quarter-label-string? " Q3 "))))
- (testing "invalid quarter labels"
- (is (nil? (literals/quarter-label-string? "Q5")))
- (is (nil? (literals/quarter-label-string? "Q0")))
- (is (nil? (literals/quarter-label-string? "Q")))
- (is (nil? (literals/quarter-label-string? "")))
- (is (not (literals/quarter-label-string? nil)))))
-
-(deftest ^:parallel now-literal-test
- (testing "case-insensitive now"
- (is (true? (literals/now-literal? "now")))
- (is (true? (literals/now-literal? "NOW")))
- (is (true? (literals/now-literal? " now "))))
- (testing "not-now values"
- (is (false? (literals/now-literal? "not-now")))
- (is (false? (literals/now-literal? nil)))
- (is (false? (literals/now-literal? 42)))))
-
-(deftest ^:parallel iso-date-string-test
- (testing "valid ISO dates"
- (is (some? (literals/iso-date-string? "2024-01-15")))
- (is (some? (literals/iso-date-string? " 2024-12-31 "))))
- (testing "invalid date formats"
- (is (nil? (literals/iso-date-string? "2024-1-15")))
- (is (nil? (literals/iso-date-string? "not-a-date")))
- (is (not (literals/iso-date-string? nil)))))
-
-(deftest ^:parallel null-literal-test
- (testing "nil is null"
- (is (true? (literals/null-literal? nil))))
- (testing "string null variants"
- (is (true? (literals/null-literal? "null")))
- (is (true? (literals/null-literal? "NULL"))))
- (testing "non-null values"
- (is (false? (literals/null-literal? "not null")))
- (is (false? (literals/null-literal? 0)))
- (is (false? (literals/null-literal? false)))))
-
-(deftest ^:parallel scalar-sequential-test
- (testing "vector of scalars"
- (is (true? (literals/scalar-sequential? [1 2 3])))
- (is (true? (literals/scalar-sequential? ["a" "b"])))
- (is (true? (literals/scalar-sequential? [nil true 42 "x"]))))
- (testing "empty vector is scalar-sequential"
- (is (true? (literals/scalar-sequential? []))))
- (testing "rejects operator tuples"
- (is (false? (literals/scalar-sequential? ["count"])))
- (is (false? (literals/scalar-sequential? ["field" 1]))))
- (testing "rejects non-sequential"
- (is (false? (literals/scalar-sequential? "abc")))
- (is (false? (literals/scalar-sequential? 42)))))
-
-(deftest ^:parallel aggregation-form-test
- (testing "recognizes canonical aggregation operators"
- (is (some? (literals/aggregation-form? ["count"])))
- (is (some? (literals/aggregation-form? ["sum" ["field" 1]])))
- (is (some? (literals/aggregation-form? ["avg" ["field" 1]])))
- (is (some? (literals/aggregation-form? ["min" ["field" 1]])))
- (is (some? (literals/aggregation-form? ["max" ["field" 1]])))
- (is (some? (literals/aggregation-form? ["distinct" ["field" 1]])))
- (is (some? (literals/aggregation-form? ["median" ["field" 1]])))
- (is (some? (literals/aggregation-form? ["stddev" ["field" 1]])))
- (is (some? (literals/aggregation-form? ["var" ["field" 1]])))
- (is (some? (literals/aggregation-form? ["count-where" ["field" 1]])))
- (is (some? (literals/aggregation-form? ["percentile" ["field" 1] 0.9])))
- (is (some? (literals/aggregation-form? ["metric" 42]))))
- (testing "rejects non-aggregation operators"
- (is (nil? (literals/aggregation-form? ["field" 1])))
- (is (nil? (literals/aggregation-form? ["=" 1 2]))))
- (testing "rejects non-vectors"
- (is (not (literals/aggregation-form? "count")))))
-
-(deftest ^:parallel default-map-test
- (testing "maps with :default key"
- (is (true? (literals/default-map? {:default nil})))
- (is (true? (literals/default-map? {"default" 42}))))
- (testing "maps without default key"
- (is (false? (literals/default-map? {:other 1})))
- (is (false? (literals/default-map? {}))))
- (testing "non-maps"
- (is (false? (literals/default-map? nil)))
- (is (false? (literals/default-map? [])))))
-
-(deftest ^:parallel bare-field-id-test
- (testing "positive integers"
- (is (true? (literals/bare-field-id? 1)))
- (is (true? (literals/bare-field-id? 42))))
- (testing "zero and negatives"
- (is (false? (literals/bare-field-id? 0)))
- (is (false? (literals/bare-field-id? -1))))
- (testing "non-integers"
- (is (false? (literals/bare-field-id? 3.14)))
- (is (false? (literals/bare-field-id? "42")))
- (is (false? (literals/bare-field-id? nil)))))
diff --git a/test/metabase/agent_lib/eval/args_test.clj b/test/metabase/agent_lib/eval/args_test.clj
deleted file mode 100644
index db33242b318..00000000000
--- a/test/metabase/agent_lib/eval/args_test.clj
+++ /dev/null
@@ -1,30 +0,0 @@
-(ns metabase.agent-lib.eval.args-test
- (:require
- [clojure.test :refer [deftest is]]
- [metabase.agent-lib.eval.args :as eval.args]))
-
-(deftest ^:parallel normalize-helper-args-flattens-in-lists-test
- (is (= [["field" 10] "a" "b"]
- (eval.args/normalize-helper-args [:operations 0 1]
- 'in
- [["field" 10] ["a" "b"]]))))
-
-(deftest ^:parallel normalize-helper-args-normalizes-enums-test
- (is (= [["aggregation-ref" 0] :desc]
- (eval.args/normalize-helper-args [:operations 1]
- 'order-by
- [["aggregation-ref" 0] "desc"])))
- (is (= [["field" 10] -30 :day 0 :day]
- (eval.args/normalize-helper-args [:operations 2]
- 'relative-time-interval
- [["field" 10] -30 "day" 0 "day"]))))
-
-(deftest ^:parallel normalize-helper-args-normalizes-percentiles-and-join-fields-test
- (is (= [["field" 12] 0.9]
- (eval.args/normalize-helper-args [:operations 3]
- 'percentile
- [["field" 12] 90])))
- (is (= [["join-clause" ["table" 1]] :all]
- (eval.args/normalize-helper-args [:operations 4]
- 'with-join-fields
- [["join-clause" ["table" 1]] "all"]))))
diff --git a/test/metabase/agent_lib/eval/invoke_test.clj b/test/metabase/agent_lib/eval/invoke_test.clj
deleted file mode 100644
index 1042b0c3beb..00000000000
--- a/test/metabase/agent_lib/eval/invoke_test.clj
+++ /dev/null
@@ -1,54 +0,0 @@
-(ns metabase.agent-lib.eval.invoke-test
- (:require
- [clojure.test :refer [deftest is testing]]
- [metabase.agent-lib.eval.invoke :as eval.invoke]
- [metabase.agent-lib.test-util :as agent-lib.tu]))
-
-(defn- runtime-with-bindings
- [bindings]
- {:bindings bindings})
-
-(deftest invoke-helper-rejects-unknown-operators-test
- (let [runtime (runtime-with-bindings {'known identity})]
- (try
- (eval.invoke/invoke-helper! runtime [:operations 0] 'missing [])
- (is false "expected unknown helper to fail")
- (catch clojure.lang.ExceptionInfo e
- (is (= :invalid-generated-program (:error (ex-data e))))
- (is (= "missing" (:operator (ex-data e))))))))
-
-(deftest invoke-query-aware-helper-requires-current-query-test
- (let [runtime (runtime-with-bindings {'filter (fn [& _] :ok)})]
- (try
- (eval.invoke/invoke-query-aware-helper! runtime nil [:operations 0] 'filter [])
- (is false "expected query-aware helper to require current query")
- (catch clojure.lang.ExceptionInfo e
- (is (= :invalid-generated-program (:error (ex-data e))))
- (is (re-find #"`filter` requires the current query state"
- (:details (ex-data e))))))))
-
-(deftest invoke-query-aware-helper-shapes-expression-ref-errors-test
- (let [runtime (runtime-with-bindings {'expression-ref (fn [& _]
- (throw (ex-info "missing expression" {})))})]
- (try
- (eval.invoke/invoke-query-aware-helper! runtime {:query true} [:operations 0] 'expression-ref ["Net"])
- (is false "expected expression-ref failure")
- (catch clojure.lang.ExceptionInfo e
- (is (= :invalid-generated-program (:error (ex-data e))))
- (is (= "expression-ref" (:operator (ex-data e))))
- (is (= "Net" (:name (ex-data e))))))))
-
-(deftest invoke-field-helper-prefers-query-aware-arity-test
- (let [runtime (runtime-with-bindings {'field (fn [query arg] [query arg])})]
- (is (= [:current-query 42]
- (eval.invoke/invoke-field-helper! runtime :current-query [:operations 0] [42])))))
-
-(deftest ensure-query-result-recognizes-mbql5-queries-test
- (testing "non-query values are rejected"
- (is (thrown-with-msg?
- clojure.lang.ExceptionInfo
- #"must return a MBQL 5 query map"
- (eval.invoke/ensure-query-result! :not-a-query))))
- (testing "queries pass through unchanged"
- (let [query (agent-lib.tu/query-for-table :orders)]
- (is (= query (eval.invoke/ensure-query-result! query))))))
diff --git a/test/metabase/agent_lib/eval/source_test.clj b/test/metabase/agent_lib/eval/source_test.clj
deleted file mode 100644
index 66c46784a69..00000000000
--- a/test/metabase/agent_lib/eval/source_test.clj
+++ /dev/null
@@ -1,59 +0,0 @@
-(ns metabase.agent-lib.eval.source-test
- (:require
- [clojure.test :refer [deftest is testing]]
- [metabase.agent-lib.eval.source :as source]
- [metabase.agent-lib.runtime :as runtime]
- [metabase.agent-lib.test-util :as tu]
- [metabase.lib.test-metadata :as meta]))
-
-(deftest ^:parallel resolve-source-context-test
- (testing "context source returns the source from runtime bindings"
- (let [base-query (tu/query-for-table :orders)
- rt (runtime/build-runtime meta/metadata-provider {:extra-bindings {'source base-query}})
- result (source/resolve-source identity rt [:source] {:type "context" :ref "source"})]
- (is (= base-query result)))))
-
-(deftest resolve-source-context-missing-test
- (testing "context source throws when unavailable in runtime bindings"
- (let [rt (runtime/build-runtime meta/metadata-provider)
- error (try
- (source/resolve-source identity rt [:source] {:type "context" :ref "source"})
- nil
- (catch clojure.lang.ExceptionInfo e e))]
- (is error)
- (is (= :invalid-generated-program (:error (ex-data error))))
- (is (re-find #"context source is unavailable"
- (:details (ex-data error)))))))
-
-(deftest ^:parallel resolve-source-table-test
- (testing "table source calls table lookup with id and returns a query"
- (let [rt (runtime/build-runtime meta/metadata-provider)
- result (source/resolve-source identity rt [:source] {:type "table" :id (meta/id :orders)})]
- (is (map? result)))))
-
-(deftest resolve-source-unsupported-type-test
- (testing "unsupported source type throws"
- (let [rt (runtime/build-runtime meta/metadata-provider)
- error (try
- (source/resolve-source identity rt [:source] {:type "unknown"})
- nil
- (catch clojure.lang.ExceptionInfo e e))]
- (is error)
- (is (= :invalid-generated-program (:error (ex-data error))))
- (is (re-find #"unsupported source type"
- (:details (ex-data error)))))))
-
-(deftest ^:parallel resolve-source-program-test
- (testing "program source recurses via evaluate-program callback"
- (let [rt (runtime/build-runtime meta/metadata-provider)
- inner-result {:result :from-inner-program}
- evaluate-fn (fn [_path program]
- (when (= {:source {:type "context" :ref "source"}
- :operations [["limit" 5]]}
- program)
- inner-result))
- result (source/resolve-source evaluate-fn rt [:source]
- {:type "program"
- :program {:source {:type "context" :ref "source"}
- :operations [["limit" 5]]}})]
- (is (= inner-result result)))))
diff --git a/test/metabase/agent_lib/eval_test.clj b/test/metabase/agent_lib/eval_test.clj
deleted file mode 100644
index d6f82e0033a..00000000000
--- a/test/metabase/agent_lib/eval_test.clj
+++ /dev/null
@@ -1,764 +0,0 @@
-(ns metabase.agent-lib.eval-test
- (:require
- [clojure.test :refer [deftest is testing]]
- [metabase.agent-lib.core :as program]
- [metabase.agent-lib.test-util :as tu]
- [metabase.lib.core :as lib]
- [metabase.lib.test-metadata :as meta]
- [metabase.lib.test-util :as lib.tu]
- [metabase.lib.util :as lib.util]))
-
-(deftest ^:parallel expression-ref-parity-test
- (let [program {:source {:type "context" :ref "source"}
- :operations [["expression" "Net Amount"
- ["-" ["field" (meta/id :orders :total)]
- ["field" (meta/id :orders :discount)]]]
- ["order-by" ["desc" ["expression-ref" "Net Amount"]]]
- ["limit" 10]]}
- expected (-> (tu/query-for-table :orders)
- (lib/expression "Net Amount"
- (lib/- (meta/field-metadata :orders :total)
- (meta/field-metadata :orders :discount)))
- (as-> query
- (lib/order-by query (lib/expression-ref query "Net Amount") :desc))
- (lib/limit 10))]
- (is (= (tu/comparable-query expected)
- (-> (program/evaluate-program program meta/metadata-provider (tu/table-context :orders))
- tu/comparable-query)))))
-
-(deftest ^:parallel expression-ref-breakout-parity-test
- (let [program {:source {:type "context" :ref "source"}
- :operations [["expression" "Hour of Day" ["get-hour" ["field" (meta/id :orders :created-at)]]]
- ["aggregate" ["count"]]
- ["breakout" ["expression-ref" "Hour of Day"]]
- ["order-by" ["expression-ref" "Hour of Day"]]]}
- base-query (-> (tu/query-for-table :orders)
- (lib/expression "Hour of Day" (lib/get-hour (meta/field-metadata :orders :created-at)))
- (lib/aggregate (lib/count)))
- expected (as-> base-query query
- (let [expr-ref (lib/expression-ref query "Hour of Day")]
- (-> query
- (lib/breakout expr-ref)
- (lib/order-by (lib.util/fresh-uuids expr-ref)))))]
- (is (= (tu/comparable-query expected)
- (-> (program/evaluate-program program meta/metadata-provider (tu/table-context :orders))
- tu/comparable-query)))))
-
-(deftest ^:parallel raw-expression-breakout-parity-test
- (let [program {:source {:type "context" :ref "source"}
- :operations [["aggregate" ["count"]]
- ["breakout" ["get-day-of-week" ["field" (meta/id :orders :created-at)]]]
- ["order-by" ["get-day-of-week" ["field" (meta/id :orders :created-at)]]]]}
- base-query (-> (tu/query-for-table :orders)
- (lib/expression "__breakout_expression_1"
- (lib/get-day-of-week (meta/field-metadata :orders :created-at)))
- (lib/aggregate (lib/count)))
- expected (as-> base-query query
- (let [expr-ref (lib/expression-ref query "__breakout_expression_1")]
- (-> query
- (lib/breakout expr-ref)
- (lib/order-by (lib.util/fresh-uuids expr-ref)))))]
- (is (= (tu/comparable-query expected)
- (-> (program/evaluate-program program meta/metadata-provider (tu/table-context :orders))
- tu/comparable-query)))))
-
-(deftest ^:parallel raw-field-order-by-reuses-matching-breakout-expression-test
- (let [program {:source {:type "context" :ref "source"}
- :operations [["aggregate" ["count"]]
- ["breakout" ["get-hour" ["field" (meta/id :orders :created-at)]]]
- ["order-by" ["field" (meta/id :orders :created-at)]]]}
- base-query (-> (tu/query-for-table :orders)
- (lib/expression "__breakout_expression_1"
- (lib/get-hour (meta/field-metadata :orders :created-at)))
- (lib/aggregate (lib/count)))
- expected (as-> base-query query
- (let [expr-ref (lib/expression-ref query "__breakout_expression_1")]
- (-> query
- (lib/breakout expr-ref)
- (lib/order-by (lib.util/fresh-uuids expr-ref)))))]
- (is (= (tu/comparable-query expected)
- (-> (program/evaluate-program program meta/metadata-provider (tu/table-context :orders))
- tu/comparable-query)))))
-
-(deftest ^:parallel raw-expression-order-by-parity-test
- (let [program {:source {:type "context" :ref "source"}
- :operations [["expression" "Net Amount"
- ["-" ["field" (meta/id :orders :total)]
- ["field" (meta/id :orders :discount)]]]
- ["order-by" ["desc"
- ["-" ["field" (meta/id :orders :total)]
- ["field" (meta/id :orders :discount)]]]]
- ["limit" 10]]}
- expected (-> (tu/query-for-table :orders)
- (lib/expression "Net Amount"
- (lib/- (meta/field-metadata :orders :total)
- (meta/field-metadata :orders :discount)))
- (as-> query
- (lib/order-by query (lib/expression-ref query "Net Amount") :desc))
- (lib/limit 10))]
- (is (= (tu/comparable-query expected)
- (-> (program/evaluate-program program meta/metadata-provider (tu/table-context :orders))
- tu/comparable-query)))))
-
-(deftest ^:parallel expression-projection-parity-test
- (let [program {:source {:type "context" :ref "source"}
- :operations [["expression" "Net Amount"
- ["-" ["field" (meta/id :orders :total)]
- ["field" (meta/id :orders :discount)]]]
- ["with-fields" [["field" (meta/id :orders :id)]
- ["expression-ref" "Net Amount"]]]
- ["order-by" ["desc" ["expression-ref" "Net Amount"]]]
- ["limit" 10]]}
- expected (-> (tu/query-for-table :orders)
- (lib/expression "Net Amount"
- (lib/- (meta/field-metadata :orders :total)
- (meta/field-metadata :orders :discount)))
- (as-> query
- (-> query
- (lib/with-fields [(meta/field-metadata :orders :id)
- (lib/expression-ref query "Net Amount")])
- (lib/order-by (lib/expression-ref query "Net Amount") :desc)))
- (lib/limit 10))]
- (is (= (tu/comparable-query expected)
- (-> (program/evaluate-program program meta/metadata-provider (tu/table-context :orders))
- tu/comparable-query)))))
-
-(deftest ^:parallel same-stage-aggregation-ref-parity-test
- (let [program {:source {:type "context" :ref "source"}
- :operations [["aggregate" ["count"]]
- ["aggregate" ["sum" ["field" (meta/id :venues :price)]]]
- ["breakout" ["field" (meta/id :venues :category-id)]]
- ["filter" [">" ["aggregation-ref" 1] 10]]
- ["order-by" ["desc" ["aggregation-ref" 1]]]]}
- expected (-> (tu/query-for-table :venues)
- (lib/aggregate (lib/count))
- (lib/aggregate (lib/sum (meta/field-metadata :venues :price)))
- (lib/breakout (meta/field-metadata :venues :category-id))
- (as-> query
- (-> query
- (lib/filter (lib/> (lib/aggregation-ref query 1) 10))
- (lib/order-by (lib/aggregation-ref query 1) :desc))))]
- (is (= (tu/comparable-query expected)
- (-> (program/evaluate-program program meta/metadata-provider (tu/table-context :venues))
- tu/comparable-query)))))
-
-(deftest ^:parallel join-with-explicit-fields-test
- (let [program {:source {:type "context" :ref "source"}
- :operations [["join"
- ["with-join-fields"
- ["with-join-conditions"
- ["join-clause" ["table" (meta/id :categories)]]
- [["=" ["field" (meta/id :venues :category-id)]
- ["field" (meta/id :categories :id)]]]]
- [["field" (meta/id :categories :name)]]]]]}
- base-query (lib.tu/venues-query)
- expected (-> base-query
- (lib/join (-> (lib/join-clause (meta/table-metadata :categories))
- (lib/with-join-conditions
- [(lib/= (tu/current-query-column base-query (meta/id :venues :category-id))
- (tu/current-query-column base-query (meta/id :categories :id)))])
- (lib/with-join-fields
- [(tu/current-query-column base-query (meta/id :categories :name))]))))]
- (is (= (tu/comparable-query expected)
- (-> (program/evaluate-program program meta/metadata-provider (tu/table-context :venues :categories))
- tu/comparable-query)))))
-
-(deftest ^:parallel implicit-join-field-parity-test
- (let [program {:source {:type "context" :ref "source"}
- :operations [["with-fields" [["field" (meta/id :orders :id)]
- ["field" (meta/id :products :title)]]]
- ["order-by" ["asc" ["field" (meta/id :products :title)]]]]}
- base-query (tu/query-for-table :orders)
- expected (-> base-query
- (lib/with-fields [(tu/current-query-column base-query (meta/id :orders :id))
- (tu/current-query-column base-query (meta/id :products :title))])
- (lib/order-by (tu/current-query-column base-query (meta/id :products :title)) :asc))]
- (is (= (tu/comparable-query expected)
- (-> (program/evaluate-program program meta/metadata-provider (tu/table-context :orders :products))
- tu/comparable-query)))))
-
-(deftest ^:parallel implicit-join-field-outside-context-parity-test
- (let [program {:source {:type "context" :ref "source"}
- :operations [["with-fields" [["field" (meta/id :orders :id)]
- ["field" (meta/id :products :title)]]]
- ["order-by" ["asc" ["field" (meta/id :products :title)]]]]}
- base-query (tu/query-for-table :orders)
- expected (-> base-query
- (lib/with-fields [(tu/current-query-column base-query (meta/id :orders :id))
- (tu/current-query-column base-query (meta/id :products :title))])
- (lib/order-by (tu/current-query-column base-query (meta/id :products :title)) :asc))]
- (is (= (tu/comparable-query expected)
- (-> (program/evaluate-program program meta/metadata-provider (tu/table-context :orders))
- tu/comparable-query)))))
-
-(deftest ^:parallel explicit-join-table-outside-context-parity-test
- (let [program {:source {:type "context" :ref "source"}
- :operations [["join"
- ["with-join-fields"
- ["with-join-conditions"
- ["join-clause" ["table" (meta/id :categories)]]
- [["=" ["field" (meta/id :venues :category-id)]
- ["field" (meta/id :categories :id)]]]]
- [["field" (meta/id :categories :name)]]]]
- ["filter" ["=" ["field" (meta/id :categories :name)] "Mexican"]]]}
- base-query (lib.tu/venues-query)
- expected (as-> base-query query
- (lib/join query
- (-> (lib/join-clause (meta/table-metadata :categories))
- (lib/with-join-conditions
- [(lib/= (tu/current-query-column base-query (meta/id :venues :category-id))
- (tu/current-query-column base-query (meta/id :categories :id)))])
- (lib/with-join-fields
- [(tu/current-query-column base-query (meta/id :categories :name))])))
- (lib/filter query (lib/= (tu/current-query-column query (meta/id :categories :name)) "Mexican")))]
- (is (= (tu/comparable-query expected)
- (-> (program/evaluate-program program meta/metadata-provider (tu/table-context :venues))
- tu/comparable-query)))))
-
-(deftest ^:parallel redundant-explicit-join-to-implicit-related-table-test
- (let [program {:source {:type "context" :ref "source"}
- :operations [["join"
- ["with-join-conditions"
- ["join-clause" ["table" (meta/id :products)]]
- [["=" ["field" (meta/id :orders :product-id)]
- ["field" (meta/id :products :id)]]]]]
- ["filter" ["=" ["field" (meta/id :products :title)] "Widget"]]
- ["aggregate" ["count"]]]}
- context (tu/table-context-with-join-edges :orders
- [:products]
- [(tu/join-edge :orders :product-id :products :id)])
- base-query (tu/query-for-table :orders)
- expected (-> base-query
- (lib/filter (lib/= (tu/current-query-column base-query (meta/id :products :title)) "Widget"))
- (lib/aggregate (lib/count)))]
- (is (= (tu/comparable-query expected)
- (-> (program/evaluate-program program meta/metadata-provider context)
- tu/comparable-query)))))
-
-(deftest ^:parallel implicit-join-filter-field-uses-source-field-test
- (let [program {:source {:type "context" :ref "source"}
- :operations [["filter" ["contains" ["field" (meta/id :products :title)] "widget"]]
- ["aggregate" ["count"]]]}
- base-query (tu/query-for-table :orders)
- expected (-> base-query
- (lib/filter (lib/contains (tu/current-query-column base-query (meta/id :products :title)) "widget"))
- (lib/aggregate (lib/count)))]
- (is (= (tu/comparable-query expected)
- (-> (program/evaluate-program program meta/metadata-provider (tu/table-context :orders :products))
- tu/comparable-query)))))
-
-(deftest ^:parallel explicit-join-with-field-selection-is-not-dropped-test
- (let [program {:source {:type "context" :ref "source"}
- :operations [["join"
- ["with-join-fields"
- ["with-join-conditions"
- ["join-clause" ["table" (meta/id :categories)]]
- [["=" ["field" (meta/id :venues :category-id)]
- ["field" (meta/id :categories :id)]]]]
- [["field" (meta/id :categories :name)]]]]
- ["filter" ["=" ["field" (meta/id :categories :name)] "Mexican"]]]}
- context (tu/table-context-with-join-edges :venues
- [:categories]
- [(tu/join-edge :venues :category-id :categories :id)])
- base-query (lib.tu/venues-query)
- expected (as-> base-query query
- (lib/join query
- (-> (lib/join-clause (meta/table-metadata :categories))
- (lib/with-join-conditions
- [(lib/= (tu/current-query-column base-query (meta/id :venues :category-id))
- (tu/current-query-column base-query (meta/id :categories :id)))])
- (lib/with-join-fields
- [(tu/current-query-column base-query (meta/id :categories :name))])))
- (lib/filter query (lib/= (tu/current-query-column query (meta/id :categories :name)) "Mexican")))]
- (is (= (tu/comparable-query expected)
- (-> (program/evaluate-program program meta/metadata-provider context)
- tu/comparable-query)))))
-
-(deftest ^:parallel append-stage-explicit-related-join-falls-back-to-implicit-related-field-test
- (let [implicit-program {:source {:type "context" :ref "source"}
- :operations [["breakout" ["field" (meta/id :orders :product-id)]]
- ["append-stage"]
- ["breakout" ["field" (meta/id :products :title)]]]}
- explicit-program {:source {:type "context" :ref "source"}
- :operations [["breakout" ["field" (meta/id :orders :product-id)]]
- ["append-stage"]
- ["join"
- ["with-join-conditions"
- ["join-clause" ["table" (meta/id :products)]]
- [["=" ["field" (meta/id :orders :product-id)]
- ["field" (meta/id :products :id)]]]]]
- ["breakout" ["field" (meta/id :products :title)]]]}
- context (tu/table-context :orders :products)]
- (is (= (-> (program/evaluate-program implicit-program meta/metadata-provider context)
- tu/comparable-query)
- (-> (program/evaluate-program explicit-program meta/metadata-provider context)
- tu/comparable-query)))))
-
-(deftest ^:parallel bare-order-by-field-parity-test
- (let [program {:source {:type "context" :ref "source"}
- :operations [["with-fields" [["field" (meta/id :orders :id)]
- ["field" (meta/id :products :title)]]]
- ["order-by" ["field" (meta/id :products :title)]]]}
- base-query (tu/query-for-table :orders)
- expected (-> base-query
- (lib/with-fields [(tu/current-query-column base-query (meta/id :orders :id))
- (tu/current-query-column base-query (meta/id :products :title))])
- (lib/order-by (tu/current-query-column base-query (meta/id :products :title)) :asc))]
- (is (= (tu/comparable-query expected)
- (-> (program/evaluate-program program meta/metadata-provider (tu/table-context :orders :products))
- tu/comparable-query)))))
-
-(deftest ^:parallel append-stage-raw-field-falls-back-to-previous-stage-column-test
- (let [program {:source {:type "context" :ref "source"}
- :operations [["aggregate" ["avg" ["field" (meta/id :orders :total)]]]
- ["append-stage"]
- ["order-by" ["desc" ["field" (meta/id :orders :total)]]]]}
- base-query (-> (tu/query-for-table :orders)
- (lib/aggregate (lib/avg (meta/field-metadata :orders :total)))
- (lib/append-stage))
- expected (lib/order-by base-query (tu/previous-stage-aggregation-column base-query 0) :desc)]
- (is (= (tu/comparable-query expected)
- (-> (program/evaluate-program program meta/metadata-provider (tu/table-context :orders))
- tu/comparable-query)))))
-
-(deftest ^:parallel aggregate-order-by-raw-field-falls-back-to-aggregation-column-test
- (let [program {:source {:type "context" :ref "source"}
- :operations [["aggregate" ["min" ["field" (meta/id :orders :total)]]]
- ["order-by" ["field" (meta/id :orders :total)]]]}
- base-query (-> (tu/query-for-table :orders)
- (lib/aggregate (lib/min (meta/field-metadata :orders :total))))
- expected (lib/order-by base-query (tu/current-aggregation-orderable base-query 0))]
- (is (= (tu/comparable-query expected)
- (-> (program/evaluate-program program meta/metadata-provider (tu/table-context :orders))
- tu/comparable-query)))))
-
-(deftest ^:parallel grouped-raw-field-order-by-falls-back-to-aggregation-column-test
- (let [program {:source {:type "context" :ref "source"}
- :operations [["aggregate" ["avg" ["field" (meta/id :orders :total)]]]
- ["breakout" ["field" (meta/id :orders :product-id)]]
- ["order-by" ["desc" ["field" (meta/id :orders :total)]]]]}
- base-query (-> (tu/query-for-table :orders)
- (lib/aggregate (lib/avg (meta/field-metadata :orders :total)))
- (lib/breakout (meta/field-metadata :orders :product-id)))
- expected (lib/order-by base-query (tu/current-aggregation-orderable base-query 0) :desc)]
- (is (= (tu/comparable-query expected)
- (-> (program/evaluate-program program meta/metadata-provider (tu/table-context :orders))
- tu/comparable-query)))))
-
-(deftest ^:parallel append-stage-aggregate-raw-field-falls-back-to-previous-stage-column-test
- (let [program {:source {:type "context" :ref "source"}
- :operations [["aggregate" ["avg" ["field" (meta/id :orders :total)]]]
- ["append-stage"]
- ["aggregate" ["avg" ["field" (meta/id :orders :total)]]]]}
- base-query (-> (tu/query-for-table :orders)
- (lib/aggregate (lib/avg (meta/field-metadata :orders :total)))
- (lib/append-stage))
- expected (lib/aggregate base-query (lib/avg (tu/previous-stage-aggregation-column base-query 0)))]
- (is (= (tu/comparable-query expected)
- (-> (program/evaluate-program program meta/metadata-provider (tu/table-context :orders))
- tu/comparable-query)))))
-
-(deftest ^:parallel append-stage-filter-on-unavailable-raw-field-is-rejected-test
- (let [program {:source {:type "context" :ref "source"}
- :operations [["aggregate" ["count"]]
- ["append-stage"]
- ["filter" [">" ["field" (meta/id :orders :total)] 10]]]}
- error (try
- (program/evaluate-program program meta/metadata-provider (tu/table-context :orders))
- nil
- (catch clojure.lang.ExceptionInfo e
- e))]
- (is error)
- (is (= :invalid-generated-program (:error (ex-data error))))
- (is (re-find #"not available in the current query stage"
- (:details (ex-data error))))))
-
-(deftest ^:parallel relative-date-alias-parity-test
- (let [program {:source {:type "context" :ref "source"}
- :operations [["filter" [">="
- ["field" (meta/id :orders :created-at)]
- ["relative-date" -90 "day"]]]
- ["limit" 10]]}
- expected (-> (tu/query-for-table :orders)
- (lib/filter (lib/>= (meta/field-metadata :orders :created-at)
- (lib/relative-datetime -90 :day)))
- (lib/limit 10))]
- (is (= (tu/comparable-query expected)
- (-> (program/evaluate-program program meta/metadata-provider (tu/table-context :orders))
- tu/comparable-query)))))
-
-(deftest ^:parallel aggregate-over-aggregation-ref-source-program-parity-test
- (let [program {:source {:type "program"
- :program {:source {:type "context" :ref "source"}
- :operations [["aggregate" ["sum" ["field" (meta/id :orders :total)]]]
- ["breakout" ["field" (meta/id :orders :created-at)]]]}}
- :operations [["aggregate" ["stddev" ["aggregation-ref" 0]]]]}
- base-query (-> (tu/query-for-table :orders)
- (lib/aggregate (lib/sum (meta/field-metadata :orders :total)))
- (lib/breakout (meta/field-metadata :orders :created-at))
- (lib/append-stage))
- expected (lib/aggregate base-query (lib/stddev (tu/previous-stage-aggregation-column base-query 0)))]
- (is (= (tu/comparable-query expected)
- (-> (program/evaluate-program program meta/metadata-provider (tu/table-context :orders))
- tu/comparable-query)))))
-
-(deftest ^:parallel repaired-program-evaluation-parity-test
- (let [program {:source {:type "context" :ref "source"}
- :operations [["filter" ["is-not-null" ["field" (meta/id :orders :discount)]]]
- ["filter" ["=" ["field" (meta/id :orders :product-id)] [1 2]]]
- ["aggregate" ["count-if" ["=" ["field" (meta/id :orders :product-id)] 1]]
- ["variance" ["field" (meta/id :orders :total)]]]]}
- expected (-> (tu/query-for-table :orders)
- (lib/filter (lib/not-null (meta/field-metadata :orders :discount)))
- (lib/filter (lib/in (meta/field-metadata :orders :product-id) 1 2))
- (lib/aggregate (lib/count-where (lib/= (meta/field-metadata :orders :product-id) 1)))
- (lib/aggregate (lib/var (meta/field-metadata :orders :total))))]
- (is (= (tu/comparable-query expected)
- (-> (program/evaluate-program program meta/metadata-provider (tu/table-context :orders))
- tu/comparable-query)))))
-
-(deftest ^:parallel datetime-diff-parity-test
- (let [program {:source {:type "context" :ref "source"}
- :operations [["expression" "Days Since Order"
- ["datetime-diff" ["now"]
- ["field" (meta/id :orders :created-at)] "day"]]
- ["with-fields" [["field" (meta/id :orders :id)]
- ["expression-ref" "Days Since Order"]]]
- ["limit" 10]]}
- expected (-> (tu/query-for-table :orders)
- (lib/expression "Days Since Order"
- (lib/expression-clause :datetime-diff
- [(lib/now)
- (meta/field-metadata :orders :created-at)
- :day]
- nil))
- (as-> query
- (lib/with-fields query [(meta/field-metadata :orders :id)
- (lib/expression-ref query "Days Since Order")]))
- (lib/limit 10))]
- (is (= (tu/comparable-query expected)
- (-> (program/evaluate-program program meta/metadata-provider (tu/table-context :orders))
- tu/comparable-query)))))
-
-(deftest ^:parallel later-stage-aggregation-ref-expression-parity-test
- (let [program {:source {:type "context" :ref "source"}
- :operations [["aggregate" ["sum" ["field" (meta/id :orders :total)]]]
- ["breakout" ["field" (meta/id :orders :product-id)]]
- ["append-stage"]
- ["expression" "Revenue K" ["/" ["aggregation-ref" 0] 1000]]
- ["with-fields" [["field" (meta/id :orders :product-id)]
- ["expression-ref" "Revenue K"]]]
- ["order-by" ["desc" ["expression-ref" "Revenue K"]]]]}
- base-query (-> (tu/query-for-table :orders)
- (lib/aggregate (lib/sum (meta/field-metadata :orders :total)))
- (lib/breakout (meta/field-metadata :orders :product-id))
- lib/append-stage)
- agg-column (tu/previous-stage-aggregation-column base-query 0)
- expected (-> base-query
- (lib/expression "Revenue K" (lib// agg-column 1000))
- (as-> query
- (-> query
- (lib/with-fields [(tu/current-query-column query (meta/id :orders :product-id))
- (lib/expression-ref query "Revenue K")])
- (lib/order-by (lib/expression-ref query "Revenue K") :desc))))]
- (is (= (tu/comparable-query expected)
- (-> (program/evaluate-program program meta/metadata-provider (tu/table-context :orders))
- tu/comparable-query)))))
-
-(deftest ^:parallel expression-ref-falls-back-to-previous-stage-column-after-append-stage-test
- (let [program {:source {:type "context" :ref "source"}
- :operations [["aggregate" ["sum" ["field" (meta/id :orders :total)]]]
- ["aggregate" ["sum" ["field" (meta/id :orders :discount)]]]
- ["append-stage"]
- ["expression" "Variance" ["-" ["aggregation-ref" 0] ["aggregation-ref" 1]]]
- ["append-stage"]
- ["aggregate" ["avg" ["expression-ref" "Variance"]]]]}
- base-query (-> (tu/query-for-table :orders)
- (lib/aggregate (lib/sum (meta/field-metadata :orders :total)))
- (lib/aggregate (lib/sum (meta/field-metadata :orders :discount)))
- lib/append-stage)
- variance-stage (lib/expression base-query
- "Variance"
- (lib/- (tu/previous-stage-aggregation-column base-query 0)
- (tu/previous-stage-aggregation-column base-query 1)))
- appended (lib/append-stage variance-stage)
- expected (lib/aggregate appended
- (lib/avg (tu/current-query-column-by-name appended "Variance")))]
- (is (= (tu/comparable-query expected)
- (-> (program/evaluate-program program meta/metadata-provider (tu/table-context :orders))
- tu/comparable-query)))))
-
-(deftest ^:parallel aggregated-with-fields-raw-fields-become-breakouts-test
- (let [program {:source {:type "context" :ref "source"}
- :operations [["aggregate" ["avg" ["field" (meta/id :orders :total)]]]
- ["with-fields" [["field" (meta/id :orders :product-id)]
- ["field" (meta/id :orders :id)]]]]}
- expected (-> (tu/query-for-table :orders)
- (lib/aggregate (lib/avg (meta/field-metadata :orders :total)))
- (lib/breakout (meta/field-metadata :orders :product-id))
- (lib/breakout (meta/field-metadata :orders :id)))]
- (is (= (tu/comparable-query expected)
- (-> (program/evaluate-program program meta/metadata-provider (tu/table-context :orders))
- tu/comparable-query)))))
-
-(deftest ^:parallel aggregated-with-fields-aggregation-ref-selection-parity-test
- (let [program {:source {:type "context" :ref "source"}
- :operations [["aggregate" ["count"]]
- ["with-fields" [["aggregation-ref" 0]]]]}
- base-query (-> (tu/query-for-table :orders)
- (lib/aggregate (lib/count)))
- appended (lib/append-stage base-query)
- expected (lib/with-fields appended [(tu/previous-stage-aggregation-column appended 0)])]
- (is (= (tu/comparable-query expected)
- (-> (program/evaluate-program program meta/metadata-provider (tu/table-context :orders))
- tu/comparable-query)))))
-
-(deftest ^:parallel nested-source-program-parity-test
- (let [program {:source {:type "program"
- :program {:source {:type "context" :ref "source"}
- :operations [["filter" ["<" ["field" (meta/id :orders :total)] 100]]
- ["with-fields" [["field" (meta/id :orders :id)]
- ["field" (meta/id :orders :total)]]]]}}
- :operations [["limit" 5]]}
- expected (-> (tu/query-for-table :orders)
- (lib/filter (lib/< (meta/field-metadata :orders :total) 100))
- (lib/with-fields [(meta/field-metadata :orders :id)
- (meta/field-metadata :orders :total)])
- (lib/limit 5))]
- (is (= (tu/comparable-query expected)
- (-> (program/evaluate-program program meta/metadata-provider (tu/table-context :orders))
- tu/comparable-query)))))
-
-(deftest ^:parallel nested-join-source-program-parity-test
- (let [nested-program {:source {:type "table" :id (meta/id :products)}
- :operations [["with-fields" [["field" (meta/id :products :id)]
- ["field" (meta/id :products :title)]]]]}
- program {:source {:type "context" :ref "source"}
- :operations [["join"
- ["with-join-conditions"
- ["join-clause" {:type "program" :program nested-program}]
- [["=" ["field" (meta/id :orders :product-id)]
- ["field" (meta/id :products :id)]]]]]]}
- joined-query (-> (tu/query-for-table :products)
- (lib/with-fields [(meta/field-metadata :products :id)
- (meta/field-metadata :products :title)]))
- base-query (tu/query-for-table :orders)
- expected (-> base-query
- (lib/join (-> (lib/join-clause joined-query)
- (lib/with-join-conditions
- [(lib/= (tu/current-query-column base-query (meta/id :orders :product-id))
- (tu/current-query-column base-query (meta/id :products :id)))]))))]
- (is (= (tu/comparable-query expected)
- (-> (program/evaluate-program program meta/metadata-provider (tu/table-context :orders :products))
- tu/comparable-query)))))
-
-(deftest ^:parallel with-page-parity-test
- (let [program {:source {:type "context" :ref "source"}
- :operations [["with-page" {:page 2 :items 25}]]}
- expected (lib/with-page (tu/query-for-table :orders) {:page 2 :items 25})]
- (is (= (tu/comparable-query expected)
- (-> (program/evaluate-program program meta/metadata-provider (tu/table-context :orders))
- tu/comparable-query)))))
-
-(deftest ^:parallel stage-ops-parity-test
- (let [program {:source {:type "context" :ref "source"}
- :operations [["append-stage"]
- ["drop-empty-stages"]
- ["append-stage"]
- ["with-page" {:page 2 :items 25}]
- ["drop-stage"]]}
- expected (-> (tu/query-for-table :orders)
- lib/append-stage
- lib/drop-empty-stages
- lib/append-stage
- (lib/with-page {:page 2 :items 25})
- lib/drop-stage)]
- (is (= (tu/comparable-query expected)
- (-> (program/evaluate-program program meta/metadata-provider (tu/table-context :orders))
- tu/comparable-query)))))
-
-(deftest ^:parallel invalid-case-default-object-test
- (let [total-field-id (meta/id :orders :total)
- case-expr ["case" [[[">" ["field" total-field-id] 100]
- ["field" total-field-id]]]
- {:default nil}]
- program {:source {:type "context" :ref "source"}
- :operations [["expression" "Maybe Revenue" case-expr]]}
- error (try
- (program/evaluate-program program meta/metadata-provider (tu/table-context :orders))
- nil
- (catch clojure.lang.ExceptionInfo e
- e))]
- (is error)
- (is (= :invalid-generated-program (:error (ex-data error))))
- (is (= "case" (:operator (ex-data error))))
- (is (re-find #"fallback value itself as the optional third argument"
- (:details (ex-data error))))
- (is (re-find #"Omit the third argument instead of using null"
- (:details (ex-data error))))))
-
-(deftest ^:parallel invalid-bare-field-id-in-aggregation-test
- (let [program {:source {:type "context" :ref "source"}
- :operations [["aggregate" ["sum" (meta/id :orders :total)]]]}
- error (try
- (program/evaluate-program program meta/metadata-provider (tu/table-context :orders))
- nil
- (catch clojure.lang.ExceptionInfo e
- e))]
- (is error)
- (is (= :invalid-generated-program (:error (ex-data error))))
- (is (= "sum" (:operator (ex-data error))))
- (is (= :field-wrapper (:retry-category (ex-data error))))
- (is (re-find #"Wrap field ids with `\[\"field\", id\]` inside `sum`"
- (:details (ex-data error))))))
-
-(deftest ^:parallel invalid-unknown-ref-helper-test
- (let [program {:source {:type "context" :ref "source"}
- :operations [["expression" "Percentage Share" ["sum-ref"]]]}
- error (try
- (program/evaluate-program program meta/metadata-provider (tu/table-context :orders))
- nil
- (catch clojure.lang.ExceptionInfo e
- e))]
- (is error)
- (is (= :invalid-generated-program (:error (ex-data error))))
- (is (= "sum-ref" (:operator (ex-data error))))
- (is (re-find #"unknown helper reference"
- (:details (ex-data error))))))
-
-(deftest ^:parallel conditional-average-case-parity-test
- (let [total-field-id (meta/id :orders :total)
- case-expr ["case" [[[">" ["field" total-field-id] 100]
- ["field" total-field-id]]]]
- program {:source {:type "context" :ref "source"}
- :operations [["expression" "Large Total" case-expr]
- ["aggregate" ["avg" ["expression-ref" "Large Total"]]]]}
- expected (-> (tu/query-for-table :orders)
- (lib/expression "Large Total"
- (lib/case [[(lib/> (meta/field-metadata :orders :total) 100)
- (meta/field-metadata :orders :total)]]))
- (as-> query
- (lib/aggregate query (lib/avg (lib/expression-ref query "Large Total")))))]
- (is (= (tu/comparable-query expected)
- (-> (program/evaluate-program program meta/metadata-provider (tu/table-context :orders))
- tu/comparable-query)))))
-
-(deftest ^:parallel offset-expression-defers-to-lib-core-test
- (let [program {:source {:type "context" :ref "source"}
- :operations [["aggregate" ["sum" ["field" (meta/id :orders :total)]]]
- ["breakout" ["with-temporal-bucket" ["field" (meta/id :orders :created-at)] "month"]]
- ["order-by" ["asc"
- ["with-temporal-bucket"
- ["field" (meta/id :orders :created-at)] "month"]]]
- ["append-stage"]
- ["expression" "Prev Revenue" ["offset" ["aggregation-ref" 0] -1]]]}
- base-query (-> (tu/query-for-table :orders)
- (lib/aggregate (lib/sum (meta/field-metadata :orders :total)))
- (lib/breakout (lib/with-temporal-bucket (meta/field-metadata :orders :created-at) :month))
- (lib/order-by (lib/with-temporal-bucket (meta/field-metadata :orders :created-at) :month) :asc)
- lib/append-stage)
- agg-column (tu/previous-stage-aggregation-column base-query 0)
- lib-error (try
- (-> base-query
- (lib/expression "Prev Revenue" (lib/offset agg-column -1)))
- nil
- (catch Exception e
- e))
- program-error (try
- (program/evaluate-program program meta/metadata-provider (tu/table-context :orders))
- nil
- (catch clojure.lang.ExceptionInfo e
- e))]
- (testing "structured evaluation should defer to lib.core instead of rejecting this pattern preemptively"
- (is lib-error)
- (is program-error)
- (is (re-find #"non-aggregation expression" (ex-message lib-error)))
- (is (re-find #"non-aggregation expression" (:details (ex-data program-error))))
- (is (not (re-find #"named expressions must be non-aggregation only"
- (:details (ex-data program-error)))))
- (is (= :invalid-generated-program (:error (ex-data program-error)))))))
-
-(deftest ^:parallel field-options-temporal-unit-parity-test
- (testing "`[\"field\" id {\"temporal-unit\" ...}]` is equivalent to `with-temporal-bucket`"
- (let [created-at (meta/field-metadata :orders :created-at)
- program {:source {:type "context" :ref "source"}
- :operations [["aggregate" ["sum" ["field" (meta/id :orders :total)]]]
- ["breakout" ["field" (meta/id :orders :created-at)
- {"temporal-unit" "month"}]]
- ["order-by" ["field" (meta/id :orders :created-at)
- {"temporal-unit" "month"}] "asc"]]}
- expected (-> (tu/query-for-table :orders)
- (lib/aggregate (lib/sum (meta/field-metadata :orders :total)))
- (lib/breakout (lib/with-temporal-bucket created-at :month))
- (lib/order-by (lib/with-temporal-bucket created-at :month) :asc))]
- (is (= (tu/comparable-query expected)
- (-> (program/evaluate-program program meta/metadata-provider (tu/table-context :orders))
- tu/comparable-query))))))
-
-(deftest ^:parallel field-options-binning-parity-test
- (testing "`[\"field\" id {\"binning\" ...}]` is equivalent to `with-binning`"
- (let [total (meta/field-metadata :orders :total)
- binning {:strategy :num-bins :num-bins 10}
- program {:source {:type "context" :ref "source"}
- :operations [["aggregate" ["count"]]
- ["breakout" ["field" (meta/id :orders :total)
- {"binning" {"strategy" "num-bins"
- "num-bins" 10}}]]]}
- expected (-> (tu/query-for-table :orders)
- (lib/aggregate (lib/count))
- (lib/breakout (lib/with-binning total binning)))]
- (is (= (tu/comparable-query expected)
- (-> (program/evaluate-program program meta/metadata-provider (tu/table-context :orders))
- tu/comparable-query))))))
-
-(deftest ^:parallel field-options-combined-parity-test
- (testing "`[\"field\" id {temporal-unit ... binning ...}]` composes both wrappers"
- (let [created-at (meta/field-metadata :orders :created-at)
- program {:source {:type "context" :ref "source"}
- :operations [["aggregate" ["count"]]
- ["breakout" ["field" (meta/id :orders :created-at)
- {"temporal-unit" "month"
- "binning" {"strategy" "default"}}]]]}
- expected (-> (tu/query-for-table :orders)
- (lib/aggregate (lib/count))
- (lib/breakout (-> created-at
- (lib/with-temporal-bucket :month)
- (lib/with-binning {:strategy :default}))))]
- (is (= (tu/comparable-query expected)
- (-> (program/evaluate-program program meta/metadata-provider (tu/table-context :orders))
- tu/comparable-query))))))
-
-(deftest ^:parallel field-like-map-breakout-and-order-by-vector-wrapper-parity-test
- (testing "field-like maps inside breakout and a vector-wrapped order-by yield canonical MBQL"
- (let [created-at (meta/field-metadata :orders :created-at)
- program {:source {:type "context" :ref "source"}
- :operations [["aggregate" ["count"]]
- ["breakout" {"field_id" (meta/id :orders :created-at)
- "temporal_bucket" "month"}]
- ["order-by" [["asc" {"field_id" (meta/id :orders :created-at)
- "temporal_bucket" "month"}]]]]}
- expected (-> (tu/query-for-table :orders)
- (lib/aggregate (lib/count))
- (lib/breakout (lib/with-temporal-bucket created-at :month))
- (lib/order-by (lib/with-temporal-bucket created-at :month) :asc))]
- (is (= (tu/comparable-query expected)
- (-> (program/evaluate-program program meta/metadata-provider (tu/table-context :orders))
- tu/comparable-query))))))
-
-(deftest ^:parallel field-like-map-order-by-with-direction-key-parity-test
- (testing "an order-by field-like map with a `direction` key yields canonical MBQL"
- (let [created-at (meta/field-metadata :orders :created-at)
- program {:source {:type "context" :ref "source"}
- :operations [["aggregate" ["count"]]
- ["breakout" {"field_id" (meta/id :orders :created-at)
- "temporal_bucket" "month"}]
- ["order-by" {"field_id" (meta/id :orders :created-at)
- "temporal_bucket" "month"
- "direction" "asc"}]]}
- expected (-> (tu/query-for-table :orders)
- (lib/aggregate (lib/count))
- (lib/breakout (lib/with-temporal-bucket created-at :month))
- (lib/order-by (lib/with-temporal-bucket created-at :month) :asc))]
- (is (= (tu/comparable-query expected)
- (-> (program/evaluate-program program meta/metadata-provider (tu/table-context :orders))
- tu/comparable-query))))))
diff --git a/test/metabase/agent_lib/fuzz_test.clj b/test/metabase/agent_lib/fuzz_test.clj
deleted file mode 100644
index c80f05434b8..00000000000
--- a/test/metabase/agent_lib/fuzz_test.clj
+++ /dev/null
@@ -1,253 +0,0 @@
-(ns metabase.agent-lib.fuzz-test
- "Property-based tests for agent-lib repair, validation, and error handling.
- Generators produce random program-like structures (both valid and invalid)
- to verify that the pipeline never crashes — it either succeeds or throws
- a structured `:invalid-generated-program` error."
- (:require
- [clojure.test :refer [deftest is testing]]
- [clojure.test.check.clojure-test :refer [defspec]]
- [clojure.test.check.generators :as gen]
- [clojure.test.check.properties :as prop]
- [metabase.agent-lib.repair :as repair]
- [metabase.agent-lib.schema :as schema]
- [metabase.agent-lib.validate :as validate]
- [metabase.lib.test-metadata :as meta]))
-
-(set! *warn-on-reflection* true)
-
-;; --- Generators ---
-
-(def ^:private gen-field-id
- "Generator for field ids from test metadata."
- (gen/elements [(meta/id :orders :id)
- (meta/id :orders :total)
- (meta/id :orders :product-id)
- (meta/id :orders :user-id)
- (meta/id :orders :created-at)
- (meta/id :products :title)
- (meta/id :products :category)
- 99999]))
-
-(def ^:private gen-table-id
- (gen/elements [(meta/id :orders)
- (meta/id :products)
- (meta/id :people)
- 99999]))
-
-(def ^:private gen-op-name
- "Generator for operator names — mix of valid and invalid."
- (gen/elements ["count" "sum" "avg" "min" "max" "distinct" "field"
- "=" "!=" "<" ">" "in" "between" "contains"
- "expression-ref" "aggregation-ref"
- "case" "coalesce" "+" "-" "*" "/"
- "with-temporal-bucket" "relative-datetime" "now"
- ;; invalid operators to exercise error paths
- "bogus" "YOLO" ""]))
-
-(def ^:private gen-top-level-op-name
- (gen/elements ["filter" "aggregate" "breakout" "order-by"
- "expression" "with-fields" "limit" "join"
- "append-stage"
- ;; invalid to exercise error paths
- "bogus-top" ""]))
-
-(def ^:private gen-scalar
- (gen/one-of [gen/small-integer
- (gen/double* {:NaN? false :infinite? false})
- gen/boolean
- (gen/not-empty gen/string-alphanumeric)
- (gen/return nil)]))
-
-(defn- gen-node
- "Recursive generator for program nodes. `depth` limits nesting."
- [depth]
- (if (zero? depth)
- gen-scalar
- (gen/one-of
- [gen-scalar
- ;; field ref
- (gen/fmap (fn [id] ["field" id]) gen-field-id)
- ;; nested operator
- (gen/fmap (fn [[op args]] (into [op] args))
- (gen/tuple gen-op-name
- (gen/vector (gen-node (dec depth)) 0 3)))
- ;; vector of nodes
- (gen/vector (gen-node (dec depth)) 0 3)])))
-
-(def ^:private gen-operation
- "Generator for top-level operations."
- (gen/fmap (fn [[op args]] (into [op] args))
- (gen/tuple gen-top-level-op-name
- (gen/vector (gen-node 3) 0 4))))
-
-(def ^:private gen-source
- "Generator for program sources."
- (gen/one-of
- [(gen/return {:type "context" :ref "source"})
- (gen/fmap (fn [id] {:type "table" :id id}) gen-table-id)
- (gen/fmap (fn [id] {:type "metric" :id id}) (gen/elements [1 42 99999]))
- (gen/fmap (fn [id] {:type "card" :id id}) (gen/elements [1 99999]))
- ;; invalid source types
- (gen/return {:type "nonexistent"})
- (gen/return {})
- (gen/return nil)]))
-
-(def ^:private gen-program
- "Generator for program-like structures."
- (gen/fmap (fn [[source ops]] {:source source :operations (vec ops)})
- (gen/tuple gen-source
- (gen/vector gen-operation 0 6))))
-
-(def ^:private gen-garbage
- "Generator for completely random values — not program-shaped at all."
- (gen/one-of
- [gen/small-integer
- gen/string-alphanumeric
- gen/boolean
- (gen/return nil)
- (gen/vector gen/small-integer 0 5)
- (gen/map gen/keyword gen/small-integer {:max-elements 3})]))
-
-;; --- Helpers ---
-
-(defn- orders-context
- []
- {:source-entity {:model "table" :id (meta/id :orders)
- :columns (mapv (fn [f] {:id (meta/id :orders f)})
- (meta/fields :orders))}
- :referenced-entities []
- :surrounding-tables [{:id (meta/id :products)}
- {:id (meta/id :people)}]
- :measure-ids []})
-
-(defn- structured-error?
- "True when `e` is the standard `:invalid-generated-program` error
- or a Malli input validation error (from mu/defn schemas)."
- [e]
- (let [data (ex-data e)]
- (or (= :invalid-generated-program (:error data))
- (= :metabase.util.malli.fn/invalid-input (:type data))
- (= :metabase.util.malli.fn/invalid-output (:type data)))))
-
-;; --- Properties ---
-
-(defspec repair-never-crashes 200
- (prop/for-all [program gen-program]
- (let [result (try
- (repair/repair-program program)
- ::ok
- (catch Exception _
- ::ok))]
- (= ::ok result))))
-
-(defspec repair-returns-map-for-map-input 200
- (prop/for-all [program gen-program]
- (map? (repair/repair-program program))))
-
-(defspec repair-preserves-source-key 200
- (prop/for-all [program gen-program]
- (contains? (repair/repair-program program) :source)))
-
-(defspec repair-preserves-operations-key 200
- (prop/for-all [program gen-program]
- (contains? (repair/repair-program program) :operations)))
-
-(defspec repair-is-idempotent 200
- (prop/for-all [program gen-program]
- (= (repair/repair-program program)
- (repair/repair-program (repair/repair-program program)))))
-
-(defspec validation-never-crashes-with-unstructured-error 200
- (prop/for-all [program gen-program]
- (try
- (validate/validated-program program (orders-context))
- true
- (catch clojure.lang.ExceptionInfo e
- (structured-error? e))
- (catch Exception _
- ;; Non-ExceptionInfo exceptions are acceptable from downstream
- ;; libs (e.g. Malli schema validation); the key property is
- ;; agent-lib code itself doesn't throw raw exceptions.
- true))))
-
-(defspec garbage-input-to-repair-never-crashes 100
- (prop/for-all [garbage gen-garbage]
- (try
- (repair/repair-program garbage)
- true
- (catch Exception _
- true))))
-
-(defspec garbage-input-to-validation-never-crashes-with-unstructured-error 100
- (prop/for-all [garbage gen-garbage]
- (try
- (validate/validated-program garbage (orders-context))
- true
- (catch clojure.lang.ExceptionInfo e
- (structured-error? e))
- (catch Exception _
- true))))
-
-(defspec schema-validation-rejects-or-accepts-cleanly 200
- (prop/for-all [program gen-program]
- (let [repaired (repair/repair-program program)]
- (try
- (schema/validated-structure repaired)
- true
- (catch clojure.lang.ExceptionInfo e
- (structured-error? e))))))
-
-;; --- Deterministic edge-case tests ---
-
-(deftest ^:parallel deeply-nested-operations-do-not-overflow-test
- (let [deep-op (reduce (fn [inner _] ["+" inner 1])
- ["field" (meta/id :orders :total)]
- (range 50))
- program {:source {:type "table" :id (meta/id :orders)}
- :operations [["filter" [">" deep-op 0]]]}]
- (testing "repair handles deeply nested operations"
- (is (map? (repair/repair-program program))))
- (testing "validation rejects or accepts without crashing"
- (try
- (validate/validated-program program (orders-context))
- (is true)
- (catch clojure.lang.ExceptionInfo e
- (is (structured-error? e)))))))
-
-(deftest ^:parallel empty-and-minimal-programs-test
- (testing "empty operations"
- (let [program {:source {:type "table" :id (meta/id :orders)}
- :operations []}]
- (is (= program (validate/validated-program program (orders-context))))))
- (testing "nil operations repairs to empty"
- (let [repaired (repair/repair-program {:source {:type "context" :ref "source"}
- :operations nil})]
- (is (vector? (:operations repaired)))))
- (testing "missing operations key repairs gracefully"
- (let [repaired (repair/repair-program {:source {:type "context" :ref "source"}})]
- (is (map? repaired)))))
-
-(deftest ^:parallel many-operations-test
- (let [ops (vec (repeat 50 ["aggregate" ["count"]]))
- program {:source {:type "table" :id (meta/id :orders)}
- :operations ops}]
- (testing "programs exceeding max-operations are rejected"
- (try
- (validate/validated-program program (orders-context))
- (is false "expected rejection")
- (catch clojure.lang.ExceptionInfo e
- (is (structured-error? e))
- (is (re-find #"maximum operation count"
- (:details (ex-data e)))))))))
-
-(deftest ^:parallel repair-idempotence-degenerate-helpers-test
- (testing "degenerate operators inside `case` do not grow extra args on each repair pass (regression)"
- (doseq [op ["in" "not-in" "=" "!=" "is" "is-not"
- "between" "with-temporal-bucket" "percentile" "with-join-conditions"]]
- (testing op
- (let [program {:source {:type "context" :ref "source"}
- :operations [["filter" ["count" ["case" [op]]]]]}
- once (repair/repair-program program)
- twice (repair/repair-program once)]
- (is (= once twice)
- (str "repair of `[\"case\" [\"" op "\"]]` should be idempotent")))))))
diff --git a/test/metabase/agent_lib/guards_test.clj b/test/metabase/agent_lib/guards_test.clj
deleted file mode 100644
index 288f8d5f613..00000000000
--- a/test/metabase/agent_lib/guards_test.clj
+++ /dev/null
@@ -1,199 +0,0 @@
-(ns metabase.agent-lib.guards-test
- "Tests for security and robustness guards added to agent-lib."
- (:require
- [clojure.test :refer [deftest is testing]]
- [metabase.agent-lib.common.errors :as errors]
- [metabase.agent-lib.repair.context.passes :as passes]
- [metabase.agent-lib.repair.stages :as repair.stages]
- [metabase.agent-lib.runtime :as runtime]
- [metabase.agent-lib.validate :as validate]
- [metabase.agent-lib.validate.context :as validate.context]
- [metabase.agent-lib.validate.walker :as walker]
- [metabase.lib.test-metadata :as meta]))
-
-(set! *warn-on-reflection* true)
-
-(defn- orders-context
- "Minimal context with only the orders table allowed."
- []
- {:source-entity {:model "table" :id (meta/id :orders)
- :columns (mapv (fn [f] {:id (meta/id :orders f)})
- (meta/fields :orders))}
- :referenced-entities []
- :surrounding-tables []
- :measure-ids []})
-
-(defn- ex-details
- "Extract the :details string from an ExceptionInfo thrown by invalid-program!."
- [^Exception e]
- (:details (ex-data e)))
-
-;; --- P0: Table source validation ---
-
-(deftest validate-source-rejects-table-not-in-context-test
- (let [allowed-ids (validate.context/context-allowed-ids (orders-context))]
- (testing "table in context passes"
- (is (= {}
- (validate.context/validate-source!
- (fn [& _] {})
- allowed-ids
- [:source]
- {:type "table" :id (meta/id :orders)}
- 0
- {}))))
- (testing "table NOT in context is rejected"
- (try
- (validate.context/validate-source!
- (fn [& _] {})
- allowed-ids
- [:source]
- {:type "table" :id 99999}
- 0
- {})
- (is false "expected unknown table to be rejected")
- (catch clojure.lang.ExceptionInfo e
- (is (= :invalid-generated-program (:error (ex-data e))))
- (is (re-find #"not available in the provided context" (ex-details e))))))))
-
-(deftest ^:parallel validated-program-rejects-unknown-table-source-test
- (let [program {:source {:type "table" :id 99999}
- :operations []}
- context (orders-context)]
- (try
- (validate/validated-program program context)
- (is false "expected unknown table to be rejected")
- (catch clojure.lang.ExceptionInfo e
- (is (= :invalid-generated-program (:error (ex-data e))))
- (is (re-find #"not available in the provided context" (ex-details e)))))))
-
-;; --- P1: Runtime nil-guard ---
-
-(deftest ^:parallel helper-fn-rejects-nil-binding-test
- (let [rt {:bindings {'known identity 'nil-bound nil}}]
- (testing "non-nil binding returns the function"
- (is (fn? (runtime/helper-fn rt 'known))))
- (testing "nil binding throws"
- (is (thrown-with-msg?
- clojure.lang.ExceptionInfo
- #"No runtime binding for operator"
- (runtime/helper-fn rt 'nil-bound))))
- (testing "missing binding throws"
- (is (thrown-with-msg?
- clojure.lang.ExceptionInfo
- #"No runtime binding for operator"
- (runtime/helper-fn rt 'totally-missing))))))
-
-;; --- P1: Program nesting depth ---
-
-(deftest ^:parallel validated-program-rejects-deeply-nested-program-sources-test
- (let [leaf {:source {:type "table" :id (meta/id :orders)} :operations []}
- deep-program (reduce (fn [inner _]
- {:source {:type "program" :program inner}
- :operations []})
- leaf
- (range (+ walker/max-program-nesting 2)))
- context (orders-context)]
- (try
- (validate/validated-program deep-program context)
- (is false "expected deep nesting to be rejected")
- (catch clojure.lang.ExceptionInfo e
- (is (= :invalid-generated-program (:error (ex-data e))))
- (is (re-find #"program source nesting exceeds maximum depth" (ex-details e)))))))
-
-;; --- P2: Depth-limited contains-aggregation-ref? ---
-
-(deftest ^:parallel contains-aggregation-ref-respects-depth-limit-test
- (testing "shallow aggregation-ref is found"
- (is (true? (repair.stages/contains-aggregation-ref?
- ["aggregate" ["sum" ["aggregation-ref" 0]]]))))
- (testing "deeply nested structure does not overflow"
- (let [deep (reduce (fn [inner _] [inner]) ["aggregation-ref" 0] (range 100))]
- ;; Returns false (too deep) rather than overflowing the stack
- (is (false? (repair.stages/contains-aggregation-ref? deep))))))
-
-;; --- P2: Depth-limited tree walk in passes ---
-
-(deftest ^:parallel operation-contains-canonical-op-respects-depth-limit-test
- (testing "shallow match is found"
- (is (true? (passes/operation-contains-canonical-op?
- ["aggregate" ["sum" ["metric" 1]]]
- "metric"))))
- (testing "deeply nested structure does not overflow"
- (let [deep (reduce (fn [inner _] [inner]) ["metric" 1] (range 100))]
- ;; Returns false (too deep) rather than overflowing the stack
- (is (false? (passes/operation-contains-canonical-op? deep "metric"))))))
-
-;; --- P2: String length validation ---
-
-(deftest ^:parallel walk-node-rejects-overlong-strings-test
- (let [long-string (apply str (repeat (inc walker/max-string-length) "x"))]
- (try
- (walker/walk-node [:test] long-string 0 {} (fn [_ _ _ state] state))
- (is false "expected overlong string to be rejected")
- (catch clojure.lang.ExceptionInfo e
- (is (= :invalid-generated-program (:error (ex-data e))))
- (is (re-find #"string value exceeds maximum length" (ex-details e))))))
- (testing "strings within limit pass"
- (is (= {:node-count 1}
- (walker/walk-node [:test] "short" 0 {} (fn [_ _ _ state] state))))))
-
-;; --- P2: Error messages don't leak schema ---
-
-(deftest ^:parallel lookup-table-error-keeps-schema-out-of-message-test
- (let [rt (runtime/build-runtime meta/metadata-provider)]
- (try
- ((runtime/helper-fn rt 'table) "nonexistent_table")
- (is false "expected table lookup to fail")
- (catch clojure.lang.ExceptionInfo e
- (testing "message does not enumerate available tables"
- (is (not (re-find #"orders" (ex-message e)))))
- (testing "recovery map carries available names for LLM agents"
- (is (seq (get-in (ex-data e) [:recovery :available]))))))))
-
-;; --- Empty operations list ---
-
-(deftest ^:parallel validate-empty-operations-test
- (let [program {:source {:type "table" :id (meta/id :orders)} :operations []}
- context (orders-context)]
- (is (= program (validate/validated-program program context)))))
-
-;; --- Structured error helpers ---
-
-(deftest ^:parallel wrap-runtime-error-preserves-recovery-from-cause-test
- (let [cause (ex-info "Table not found: foo"
- {:table-name "foo"
- :recovery {:available ["orders" "products"]}})
- wrapped (errors/wrap-runtime-error [:source] "table" cause)]
- (testing "standard fields are set"
- (is (= :invalid-generated-program (:error (ex-data wrapped))))
- (is (= "table" (:operator (ex-data wrapped)))))
- (testing "recovery from cause is preserved"
- (is (= {:available ["orders" "products"]}
- (:recovery (ex-data wrapped)))))
- (testing "cause chain is preserved"
- (is (= cause (.getCause ^Exception wrapped))))))
-
-(deftest ^:parallel wrap-runtime-error-promotes-legacy-available-key-test
- (let [cause (ex-info "Field not found" {:field-name "foo" :available ["a" "b"]})
- wrapped (errors/wrap-runtime-error [:ops 0] "field" cause)]
- (testing "top-level :available is promoted into :recovery"
- (is (= ["a" "b"] (get-in (ex-data wrapped) [:recovery :available]))))))
-
-(deftest ^:parallel recovery-summary-formats-hints-test
- (testing "available values"
- (is (= "Available: orders, products"
- (errors/recovery-summary {:available ["orders" "products"]}))))
- (testing "tables for disambiguation"
- (is (= "Matching tables: orders, people"
- (errors/recovery-summary {:tables ["orders" "people"]}))))
- (testing "suggestion"
- (is (= "Use (field \"TABLE\" \"FIELD\") to disambiguate."
- (errors/recovery-summary {:suggestion "Use (field \"TABLE\" \"FIELD\") to disambiguate."}))))
- (testing "combined"
- (let [summary (errors/recovery-summary {:available ["a" "b"]
- :suggestion "Try again."})]
- (is (re-find #"Available: a, b" summary))
- (is (re-find #"Try again\." summary))))
- (testing "empty recovery returns nil"
- (is (nil? (errors/recovery-summary {})))
- (is (nil? (errors/recovery-summary nil)))))
diff --git a/test/metabase/agent_lib/join_spec_test.clj b/test/metabase/agent_lib/join_spec_test.clj
deleted file mode 100644
index 7a1b48cb012..00000000000
--- a/test/metabase/agent_lib/join_spec_test.clj
+++ /dev/null
@@ -1,32 +0,0 @@
-(ns metabase.agent-lib.join-spec-test
- (:require
- [clojure.test :refer [deftest is]]
- [metabase.agent-lib.join-spec :as join-spec]
- [metabase.lib.test-metadata :as meta]))
-
-(deftest parse-join-spec-normalizes-nested-join-wrappers-test
- (let [join-form ["with-join-alias"
- ["with-join-strategy"
- ["with-join-fields"
- ["with-join-conditions"
- ["join-clause" ["table" (meta/id :categories)]]
- [["="
- ["field" (meta/id :venues :category-id)]
- ["field" (meta/id :categories :id)]]]]
- "none"]
- "left-join"]
- "cat"]
- expected {:target-table-id (meta/id :categories)
- :conditions [[(meta/id :venues :category-id)
- (meta/id :categories :id)]]
- :fields-mode "none"
- :strategy "left-join"
- :alias "cat"}]
- (is (= expected (join-spec/parse-join-spec join-form)))))
-
-(deftest join-fields-mode-helpers-test
- (is (true? (join-spec/no-explicit-join-fields? nil)))
- (is (true? (join-spec/no-explicit-join-fields? "none")))
- (is (false? (join-spec/no-explicit-join-fields? "all")))
- (is (true? (join-spec/implicit-join-compatible-fields-mode? "all")))
- (is (false? (join-spec/implicit-join-compatible-fields-mode? [["field" 1]]))))
diff --git a/test/metabase/agent_lib/mbql_integration_test.clj b/test/metabase/agent_lib/mbql_integration_test.clj
deleted file mode 100644
index 7243d1e19ee..00000000000
--- a/test/metabase/agent_lib/mbql_integration_test.clj
+++ /dev/null
@@ -1,266 +0,0 @@
-(ns metabase.agent-lib.mbql-integration-test
- (:require
- [clojure.test :refer [deftest is testing]]
- [metabase.agent-lib.mbql-integration :as mbql]
- [metabase.agent-lib.runtime :as runtime]
- [metabase.agent-lib.test-util :as tu]
- [metabase.lib.core :as lib]
- [metabase.lib.schema.util :as lib.schema.util]
- [metabase.lib.test-metadata :as meta]))
-
-(def ^:private mbql-ns 'metabase.agent-lib.mbql-integration)
-
-(defn- runtime-fields-by-id
- []
- (:fields-by-id (runtime/build-runtime meta/metadata-provider)))
-
-(defn- comparable-ref
- [ref-clause]
- (lib.schema.util/remove-lib-uuids ref-clause))
-
-(defn- call-private
- [sym & args]
- (apply (var-get (ns-resolve mbql-ns sym)) args))
-
-(defn- current-query-field
- [query table-name field-name]
- (or (lib/find-matching-column query
- -1
- (meta/field-metadata table-name field-name)
- (mbql/current-query-field-candidates query))
- (throw (ex-info "Expected field to be available in query context"
- {:table-name table-name
- :field-name field-name
- :query query}))))
-
-(defn- current-aggregation-column
- [query idx]
- (or (lib/find-matching-column query -1 (lib/aggregation-ref query idx) (lib/orderable-columns query))
- (throw (ex-info "Expected aggregation column in query context"
- {:aggregation-index idx
- :query query}))))
-
-(deftest query?-uses-normalized-query-type-test
- (is (true? (mbql/query? (tu/query-for-table :orders))))
- (is (false? (mbql/query? (meta/table-metadata :orders)))))
-
-(deftest extracted-field-resolution-helper-test
- (let [fields-by-id (runtime-fields-by-id)
- orders-query (tu/query-for-table :orders)
- by-table (call-private 'fields-by-table-id fields-by-id)
- query-candidates (mbql/current-query-field-candidates orders-query)
- product-id-field-id (meta/id :orders :product-id)
- venues-category-id (meta/id :venues :category-id)
- category-id-field-id (meta/id :products :category)
- product-table-id (meta/id :products)
- category-table-id (meta/id :categories)]
- (testing "candidate preference is explicit and deterministic"
- (is (= {:id 10 :name "ID"}
- (call-private 'prefer-single-candidate
- [{:id 10 :name "ID" :lib/join-alias "Products"}
- {:id 10 :name "ID"}])))
- (is (= {:id 20 :name "Category"}
- (call-private 'prefer-single-candidate
- [{:id 20 :name "Category" :fk-field-id 21}
- {:id 20 :name "Category"}]))))
- (testing "metadata grouping and FK target resolution use the extracted helpers"
- (is (some #(= product-id-field-id (:id %))
- (get by-table (meta/id :orders))))
- (is (= product-table-id
- (call-private 'field-target-table-id fields-by-id product-id-field-id)))
- (is (nil? (call-private 'field-target-table-id fields-by-id (meta/id :orders :total)))))
- (testing "lineage helpers expose the path anchors and recursive FK traversal"
- (is (= [product-id-field-id category-id-field-id 999]
- (vec (call-private 'field-path-start-ids
- {:source-field product-id-field-id
- :fk-field-id category-id-field-id
- :lib/original-fk-field-id category-id-field-id
- :id 999}))))
- (is (= [product-id-field-id]
- (call-private 'fk-path-to-table fields-by-id product-id-field-id product-table-id)))
- (is (= [venues-category-id]
- (call-private 'fk-path-to-table fields-by-id venues-category-id category-table-id)))
- (is (nil? (call-private 'fk-path-to-table fields-by-id product-id-field-id category-table-id))))
- (testing "type compatibility and lineage ranking helpers are independently testable"
- (is (true? (call-private 'numeric-type? :type/Float)))
- (is (false? (call-private 'numeric-type? :type/Text)))
- (is (true? (call-private 'types-compatible?
- {:effective-type :type/Float}
- {:effective-type :type/Integer})))
- (is (false? (call-private 'types-compatible?
- {:effective-type :type/Text}
- {:effective-type :type/Integer})))
- (is (true? (call-private 'candidate-has-resolution-lineage?
- {:fk-field-id category-id-field-id})))
- (is (false? (call-private 'candidate-has-resolution-lineage?
- {:id product-id-field-id}))))
- (testing "source-column accessors and synthesized multi-hop lineage are namespace-level helpers"
- (let [source-column {:lib/source-column-alias "Category"
- :name "CATEGORY"
- :fk-field-name "Category"
- :fk-join-alias "Products"
- :source-field category-id-field-id
- :lib/original-fk-field-id product-id-field-id
- :lib/original-fk-field-name "Product ID"
- :lib/original-fk-join-alias nil}
- raw-field {:id category-id-field-id
- :name "Category"
- :table-id category-table-id}
- synthesized (call-private 'synthesize-chained-related-field
- fields-by-id
- query-candidates
- raw-field
- source-column
- [product-id-field-id category-id-field-id])]
- (is (= "Category" (call-private 'source-column-field-name source-column)))
- (is (= "Products" (call-private 'source-column-field-join-alias source-column)))
- (is (= product-id-field-id (call-private 'source-column-original-field-id source-column)))
- (is (= "Product ID" (call-private 'source-column-original-field-name source-column)))
- (is (nil? (call-private 'source-column-original-field-join-alias source-column)))
- (is (= "Products"
- (call-private 'candidate-join-alias-for-field-id
- [{:source-field category-id-field-id
- :lib/join-alias "Products"}]
- category-id-field-id)))
- (is (= category-id-field-id (:fk-field-id synthesized)))
- (is (= product-id-field-id (:lib/original-fk-field-id synthesized)))
- (is (= "Products" (:fk-join-alias synthesized)))
- (is (true? (call-private 'multi-hop-lineage-candidate? synthesized)))
- (is (false? (call-private 'multi-hop-lineage-candidate?
- {:fk-field-id category-id-field-id
- :lib/original-fk-field-id category-id-field-id})))))
- (testing "previous-stage matching is a separate unit from the main resolver"
- (is (= [{:name "Average of Total"
- :source-field (meta/id :orders :total)
- :lib/source :source/previous-stage}]
- (call-private 'previous-stage-lineage-matches
- {:id (meta/id :orders :total)
- :name "Total"}
- [{:name "Average of Total"
- :source-field (meta/id :orders :total)
- :lib/source :source/previous-stage}
- {:name "Count"
- :lib/source :source/previous-stage}])))
- (let [appended-query (-> orders-query
- (lib/aggregate (lib/avg (meta/field-metadata :orders :total)))
- (lib/append-stage))
- previous-stage-columns (->> (mbql/current-query-field-candidates appended-query)
- (filter #(= :source/previous-stage (:lib/source %)))
- vec)]
- (is (= ["avg"]
- (mapv :name
- (call-private 'previous-stage-aggregation-matches
- appended-query
- {:id (meta/id :orders :total)
- :name "Total"}
- previous-stage-columns)))))
- (is (= [{:name "NET AMOUNT" :lib/source :source/previous-stage}]
- (call-private 'previous-stage-name-matches
- {:name "Net Amount"}
- [{:name "NET AMOUNT" :lib/source :source/previous-stage}
- {:name "Other" :lib/source :source/previous-stage}]))))))
-
-(deftest extracted-orderable-helper-test
- (let [orders-query (tu/query-for-table :orders)
- breakout-query (-> orders-query
- (lib/expression "__breakout_expression_1"
- (lib/get-hour (meta/field-metadata :orders :created-at)))
- (lib/aggregate (lib/count))
- (as-> query
- (lib/breakout query (lib/expression-ref query "__breakout_expression_1"))))
- aggregation-query (-> orders-query
- (lib/aggregate (lib/sum (meta/field-metadata :orders :total)))
- (lib/aggregate (lib/count)))
- total-field-id (meta/id :orders :total)
- created-at-field-id (meta/id :orders :created-at)
- breakout-expression-ref (lib/expression-ref breakout-query "__breakout_expression_1")
- aggregation-column (current-aggregation-column aggregation-query 0)]
- (testing "aggregation inventory helpers are directly unit-tested"
- (is (= 2 (count (call-private 'aggregation-columns aggregation-query))))
- (is (= [0 1]
- (mapv first (call-private 'aggregation-column-pairs aggregation-query)))))
- (testing "requested field ids and current-stage field matching are separate helpers"
- (is (= #{total-field-id}
- (call-private 'requested-orderable-field-ids (meta/field-metadata :orders :total))))
- (is (= #{created-at-field-id}
- (call-private 'requested-orderable-field-ids (lib/ref (meta/field-metadata :orders :created-at)))))
- (is (= #{}
- (call-private 'requested-orderable-field-ids "not-a-field")))
- (is (some #(= total-field-id (:id %))
- (call-private 'orderable-field-id->query-columns orders-query total-field-id)))
- (is (some #(= total-field-id (:id %))
- (call-private 'orderable-field-ids->query-columns orders-query #{total-field-id}))))
- (testing "breakout and aggregation matching helpers are individually covered"
- (is (= [(comparable-ref breakout-expression-ref)]
- (mapv comparable-ref
- (call-private 'field-id->breakout-expression-refs breakout-query created-at-field-id))))
- (is (= (comparable-ref breakout-expression-ref)
- (comparable-ref
- (call-private 'field-ids->breakout-expression-ref breakout-query #{created-at-field-id}))))
- (is (= [aggregation-column]
- (call-private 'field-id->aggregation-columns aggregation-query total-field-id)))
- (is (= [aggregation-column]
- (call-private 'field-ids->aggregation-columns aggregation-query #{total-field-id}))))
- (testing "field-like orderable resolution is directly testable after extraction"
- (let [[_ breakout-orderable] (call-private 'resolve-field-like-orderable
- breakout-query
- (meta/field-metadata :orders :created-at))
- [_ aggregation-orderable] (call-private 'resolve-field-like-orderable
- aggregation-query
- (meta/field-metadata :orders :total))]
- (is (= (comparable-ref breakout-expression-ref)
- (comparable-ref breakout-orderable)))
- (is (= aggregation-column aggregation-orderable))))))
-
-(deftest implicitly-resolved-column-helper-test
- (is (true? (call-private 'implicitly-resolved-column?
- {:table-id 100
- :fk-field-id 20}
- 100)))
- (is (true? (call-private 'implicitly-resolved-column?
- {:table-id 200
- :lib/source :source/previous-stage}
- 100)))
- (is (false? (call-private 'implicitly-resolved-column?
- {:table-id 100
- :join-alias "Products"
- :fk-field-id 20}
- 100))))
-
-(deftest resolve-aggregation-selection-uses-visible-column-match-test
- (let [query (-> (tu/query-for-table :orders)
- (lib/aggregate (lib/count)))
- selection (lib/aggregation-ref query 0)]
- (is (= (lib/find-visible-column-for-ref query selection)
- (mbql/resolve-aggregation-selection query selection)))))
-
-(deftest expression-ref-or-current-stage-column-uses-existing-expression-test
- (let [query (-> (tu/query-for-table :orders)
- (lib/expression "Net Amount"
- (lib/- (meta/field-metadata :orders :total)
- (meta/field-metadata :orders :discount))))]
- (is (= (comparable-ref (lib/expression-ref query "Net Amount"))
- (comparable-ref (mbql/expression-ref-or-current-stage-column query "Net Amount"))))))
-
-(deftest resolve-orderable-reuses-breakout-expression-test
- (let [query (-> (tu/query-for-table :orders)
- (lib/expression "__breakout_expression_1"
- (lib/get-hour (meta/field-metadata :orders :created-at)))
- (lib/aggregate (lib/count))
- (as-> query
- (lib/breakout query (lib/expression-ref query "__breakout_expression_1"))))
- [_ resolved-orderable] (mbql/resolve-orderable query (meta/field-metadata :orders :created-at))]
- (is (= (comparable-ref (lib/expression-ref query "__breakout_expression_1"))
- (comparable-ref resolved-orderable)))))
-
-(deftest redundant-implicit-join-detects-existing-implicit-join-test
- (let [fields-by-id (:fields-by-id (runtime/build-runtime meta/metadata-provider))
- base-query (tu/query-for-table :orders)
- query (lib/with-fields base-query [(current-query-field base-query :products :title)])
- operation ["join"
- ["with-join-conditions"
- ["join-clause" ["table" (meta/id :products)]]
- [["=" ["field" (meta/id :orders :product-id)]
- ["field" (meta/id :products :id)]]]]]]
- (testing "implicit join coverage is centralized in mbql-integration"
- (is (true? (mbql/redundant-implicit-join? fields-by-id query operation))))))
diff --git a/test/metabase/agent_lib/repair/context/passes_test.clj b/test/metabase/agent_lib/repair/context/passes_test.clj
deleted file mode 100644
index b10502dbd94..00000000000
--- a/test/metabase/agent_lib/repair/context/passes_test.clj
+++ /dev/null
@@ -1,64 +0,0 @@
-(ns metabase.agent-lib.repair.context.passes-test
- (:require
- [clojure.test :refer [deftest is testing]]
- [metabase.agent-lib.repair.context.passes :as passes]
- [metabase.agent-lib.test-util :as agent-lib.tu]
- [metabase.lib.test-metadata :as meta]))
-
-(deftest ^:parallel effective-source-for-context-rewrites-metric-context-source-test
- (let [program {:source {:type "context" :ref "source"}}
- context {:source-entity {:model "metric" :id 42}}]
- (is (= {:type "metric" :id 42}
- (passes/effective-source-for-context program context)))))
-
-(deftest ^:parallel rewrite-source-stage-only-touches-the-first-stage-test
- (let [operations [["aggregate" ["count"]]
- ["append-stage"]
- ["aggregate" ["sum" ["field" 1]]]]
- rewritten (passes/rewrite-source-stage
- operations
- (fn [{:keys [in-source-stage? operations] :as state} operation]
- (assoc state
- :operations
- (conj operations
- (if in-source-stage?
- ["seen" operation]
- operation)))))]
- (is (= [["seen" ["aggregate" ["count"]]]
- ["append-stage"]
- ["aggregate" ["sum" ["field" 1]]]]
- rewritten))))
-
-(deftest ^:parallel normalize-source-metric-quarter-window-rewrites-rolling-quarter-filter-test
- (let [context {:source-entity {:model "metric" :id 42}}
- operation ["filter" ["between"
- ["field" (meta/id :orders :created-at)]
- ["relative-datetime" -3 "month"]
- ["now"]]]
- normalized (passes/normalize-source-metric-quarter-window context operation)]
- (is (= ["filter" ["between"
- ["field" (meta/id :orders :created-at)]
- ["relative-datetime" -1 "quarter"]
- ["relative-datetime" 0 "quarter"]]]
- normalized))))
-
-(deftest ^:parallel remove-redundant-operations-drops-source-metric-and-implicit-join-noise-test
- (let [metric-context {:source-entity {:model "metric" :id 7}}
- table-context {:source-entity {:model "table" :id (meta/id :venues)}
- :surrounding-tables [(agent-lib.tu/entity-summary :categories)]
- :join-edges [(agent-lib.tu/join-edge :venues :category-id :categories :id)]}
- metric-aggregate ["aggregate" ["metric" 7]]
- explicit-join ["join"
- ["with-join-conditions"
- ["join-clause" ["table" (meta/id :categories)]]
- [["=" ["field" (meta/id :venues :category-id)]
- ["field" (meta/id :categories :id)]]]]]
- kept-operation ["filter" ["=" ["field" (meta/id :venues :name)] "Red Medicine"]]]
- (testing "source-metric reuse is dropped in metric contexts"
- (is (= [kept-operation]
- (vec (passes/remove-redundant-operations metric-context
- [metric-aggregate kept-operation])))))
- (testing "implicit joins already represented by the context are dropped for table sources"
- (is (= [kept-operation]
- (vec (passes/remove-redundant-operations table-context
- [explicit-join kept-operation])))))))
diff --git a/test/metabase/agent_lib/repair/normalize/forms_test.clj b/test/metabase/agent_lib/repair/normalize/forms_test.clj
deleted file mode 100644
index d279df0fb87..00000000000
--- a/test/metabase/agent_lib/repair/normalize/forms_test.clj
+++ /dev/null
@@ -1,205 +0,0 @@
-(ns metabase.agent-lib.repair.normalize.forms-test
- (:require
- [clojure.test :refer [deftest is testing]]
- [metabase.agent-lib.repair.normalize.forms :as forms]))
-
-(deftest ^:parallel expression-definition-tuple-test
- (testing "recognizes expression definitions"
- (is (true? (forms/expression-definition-tuple? ["expression" "Net Total" ["-" ["field" 1] 10]]))))
- (testing "rejects wrong operator"
- (is (false? (forms/expression-definition-tuple? ["filter" "Name" ["-" 1 2]]))))
- (testing "rejects wrong arity"
- (is (false? (forms/expression-definition-tuple? ["expression" "Name"])))
- (is (false? (forms/expression-definition-tuple? ["expression" "Name" 1 2]))))
- (testing "rejects blank name"
- (is (false? (forms/expression-definition-tuple? ["expression" "" ["-" 1 2]]))))
- (testing "rejects non-vectors"
- (is (false? (forms/expression-definition-tuple? "expression")))))
-
-(deftest ^:parallel temporal-expression-test
- (testing "now literal is temporal"
- (is (true? (forms/temporal-expression? "now")))
- (is (true? (forms/temporal-expression? "NOW"))))
- (testing "temporal tuples are temporal"
- (is (true? (forms/temporal-expression? ["absolute-datetime" "2024-01-01" "day"])))
- (is (true? (forms/temporal-expression? ["relative-datetime" -3 "month"])))
- (is (true? (forms/temporal-expression? ["now"]))))
- (testing "non-temporal values"
- (is (false? (forms/temporal-expression? "hello")))
- (is (false? (forms/temporal-expression? 42)))
- (is (false? (forms/temporal-expression? ["field" 1])))))
-
-(deftest ^:parallel repair-case-args-three-bare-args-test
- (testing "three bare args become branch pair + fallback"
- (is (= [[["pred" "then"]] "else"]
- (forms/repair-case-args ["pred" "then" "else"])))))
-
-(deftest ^:parallel repair-case-args-wrapped-branch-pairs-test
- (testing "single wrapped vector of branch pairs"
- (is (= [[[[">" 1] "a"] [["<" 0] "b"]]]
- (forms/repair-case-args [[[">" 1] "a"] [["<" 0] "b"]])))))
-
-(deftest ^:parallel repair-case-args-wrapped-branch-pairs-with-fallback-test
- (testing "wrapped branches with fallback"
- (is (= [[[[">" 1] "a"]] "default"]
- (forms/repair-case-args [[[">" 1] "a"] "default"])))))
-
-(deftest ^:parallel repair-case-args-leading-branch-pairs-test
- (testing "leading branch pairs followed by fallback"
- (is (= [[[[">" 1] "a"]] "default"]
- (forms/repair-case-args [[[">" 1] "a"] "default"])))))
-
-(deftest ^:parallel repair-case-args-flat-even-vector-test
- (testing "flat even-length vector inside wrapper"
- (is (= [[[1 2] [3 4]]]
- (forms/repair-case-args [[1 2 3 4]])))))
-
-(deftest ^:parallel repair-case-args-else-branch-test
- (testing "else branch is split out"
- (is (= [[[[">" 1] "a"]] "fallback"]
- (forms/repair-case-args [[[">" 1] "a"] ["else" "fallback"]])))))
-
-(deftest ^:parallel repair-between-bounds-test
- (testing "wraps ISO date when other bound is temporal"
- (is (= [["field" 1] ["relative-datetime" -3 "month"] ["absolute-datetime" "2025-09-30" "day"]]
- (forms/repair-between-bounds
- [["field" 1] ["relative-datetime" -3 "month"] "2025-09-30"]))))
- (testing "wraps now literal into expression"
- (is (= [["field" 1] ["relative-datetime" -3 "month"] ["now"]]
- (forms/repair-between-bounds
- [["field" 1] ["relative-datetime" -3 "month"] "now"]))))
- (testing "leaves non-temporal bounds unchanged"
- (is (= [["field" 1] 10 20]
- (forms/repair-between-bounds [["field" 1] 10 20])))))
-
-(deftest ^:parallel repair-operator-form-field-coercion-test
- (testing "coerces field id string to integer"
- (is (= ["field" 42]
- (forms/repair-operator-form identity ["field" "42"])))))
-
-(deftest ^:parallel field-like-map?-test
- (testing "accepts snake_case and kebab-case, string and keyword keys"
- (is (true? (forms/field-like-map? {"field_id" 1})))
- (is (true? (forms/field-like-map? {"field-id" 1})))
- (is (true? (forms/field-like-map? {:field_id 1})))
- (is (true? (forms/field-like-map? {:field-id 1}))))
- (testing "rejects non-field-like maps"
- (is (false? (forms/field-like-map? {"foo" 1})))
- (is (false? (forms/field-like-map? {})))
- (is (false? (forms/field-like-map? nil)))
- (is (false? (forms/field-like-map? ["field" 1])))))
-
-(deftest ^:parallel repair-field-like-map-test
- (testing "field_id alone becomes a plain field form"
- (is (= ["field" 13]
- (forms/repair-field-like-map {"field_id" 13}))))
- (testing "temporal_bucket wraps in with-temporal-bucket"
- (is (= ["with-temporal-bucket" ["field" 13] "month"]
- (forms/repair-field-like-map {"field_id" 13 "temporal_bucket" "month"}))))
- (testing "temporal-unit alias is accepted"
- (is (= ["with-temporal-bucket" ["field" 13] "month"]
- (forms/repair-field-like-map {"field_id" 13 "temporal-unit" "month"}))))
- (testing "binning wraps in with-binning"
- (is (= ["with-binning" ["field" 13] {"strategy" "num-bins" "num-bins" 10}]
- (forms/repair-field-like-map {"field_id" 13
- "binning" {"strategy" "num-bins" "num-bins" 10}}))))
- (testing "direction wraps in asc/desc"
- (is (= ["asc" ["field" 13]]
- (forms/repair-field-like-map {"field_id" 13 "direction" "asc"})))
- (is (= ["desc" ["field" 13]]
- (forms/repair-field-like-map {"field_id" 13 "direction" "DESC"}))))
- (testing "combined options nest in canonical order: direction wraps the bucketed/binned field"
- (is (= ["asc" ["with-temporal-bucket" ["field" 13] "month"]]
- (forms/repair-field-like-map {"field_id" 13
- "temporal_bucket" "month"
- "direction" "asc"}))))
- (testing "keyword keys are also accepted"
- (is (= ["with-temporal-bucket" ["field" 13] "month"]
- (forms/repair-field-like-map {:field_id 13 :temporal_bucket "month"}))))
- (testing "string id is coerced to integer"
- (is (= ["field" 13]
- (forms/repair-field-like-map {"field_id" "13"})))))
-
-(deftest ^:parallel repair-operator-form-field-options-map-test
- (testing "field with temporal-unit option rewrites to with-temporal-bucket wrapper"
- (is (= ["with-temporal-bucket" ["field" 13] "month"]
- (forms/repair-operator-form identity ["field" 13 {"temporal-unit" "month"}]))))
- (testing "field with binning option rewrites to with-binning wrapper"
- (is (= ["with-binning" ["field" 13] {"strategy" "num-bins" "num-bins" 10}]
- (forms/repair-operator-form identity
- ["field" 13 {"binning" {"strategy" "num-bins" "num-bins" 10}}]))))
- (testing "field with both options nests with-binning outside with-temporal-bucket"
- (is (= ["with-binning"
- ["with-temporal-bucket" ["field" 13] "month"]
- {"strategy" "default"}]
- (forms/repair-operator-form identity
- ["field" 13 {"temporal-unit" "month"
- "binning" {"strategy" "default"}}]))))
- (testing "empty options map leaves field untouched"
- (is (= ["field" 13]
- (forms/repair-operator-form identity ["field" 13 {}]))))
- (testing "keyword option keys are accepted"
- (is (= ["with-temporal-bucket" ["field" 13] "month"]
- (forms/repair-operator-form identity ["field" 13 {:temporal-unit "month"}]))))
- (testing "string field id is still coerced when options are present"
- (is (= ["with-temporal-bucket" ["field" 13] "month"]
- (forms/repair-operator-form identity ["field" "13" {"temporal-unit" "month"}])))))
-
-(deftest ^:parallel repair-operator-form-is-null-test
- (testing "is with null becomes is-null"
- (is (= ["is-null" ["field" 1]]
- (forms/repair-operator-form identity ["is" ["field" 1] "null"]))))
- (testing "is with non-null becomes ="
- (is (= ["=" ["field" 1] "hello"]
- (forms/repair-operator-form identity ["is" ["field" 1] "hello"])))))
-
-(deftest ^:parallel repair-operator-form-is-not-null-test
- (testing "is-not with null becomes not-null"
- (is (= ["not-null" ["field" 1]]
- (forms/repair-operator-form identity ["is-not" ["field" 1] nil]))))
- (testing "is-not with non-null becomes !="
- (is (= ["!=" ["field" 1] "hello"]
- (forms/repair-operator-form identity ["is-not" ["field" 1] "hello"])))))
-
-(deftest ^:parallel repair-operator-form-eq-with-sequential-promotes-to-in-test
- (testing "= with sequential RHS promotes to in"
- (is (= ["in" ["field" 1] ["a" "b"]]
- (forms/repair-operator-form identity ["=" ["field" 1] ["a" "b"]])))))
-
-(deftest ^:parallel repair-operator-form-neq-with-sequential-promotes-to-not-in-test
- (testing "!= with sequential RHS promotes to not-in"
- (is (= ["not-in" ["field" 1] ["a" "b"]]
- (forms/repair-operator-form identity ["!=" ["field" 1] ["a" "b"]])))))
-
-(deftest ^:parallel repair-operator-form-contains-strips-boolean-flag-test
- (testing "contains strips trailing boolean option"
- (is (= ["contains" ["field" 1] "text"]
- (forms/repair-operator-form identity ["contains" ["field" 1] "text" false]))))
- (testing "contains strips trailing map option"
- (is (= ["contains" ["field" 1] "text"]
- (forms/repair-operator-form identity ["contains" ["field" 1] "text" {:case-sensitive false}])))))
-
-(deftest ^:parallel repair-operator-form-with-temporal-bucket-extraction-alias-test
- (testing "with-temporal-bucket rewrites extraction aliases"
- (is (= ["get-hour" ["field" 1]]
- (forms/repair-operator-form identity ["with-temporal-bucket" ["field" 1] "hour-of-day"])))
- (is (= ["get-day-of-week" ["field" 1]]
- (forms/repair-operator-form identity ["with-temporal-bucket" ["field" 1] "day-of-week"]))))
- (testing "non-extraction buckets pass through"
- (is (= ["with-temporal-bucket" ["field" 1] "month"]
- (forms/repair-operator-form identity ["with-temporal-bucket" ["field" 1] "month"])))))
-
-(deftest ^:parallel repair-operator-form-percentile-test
- (testing "normalizes percentile scale"
- (is (= ["percentile" ["field" 1] 0.9]
- (forms/repair-operator-form identity ["percentile" ["field" 1] 90])))))
-
-(deftest ^:parallel repair-operator-form-case-from-if-test
- (testing "if alias normalizes to case with three args"
- (is (= ["case" [["> 1" "then"]] "else"]
- (forms/repair-operator-form identity ["if" "> 1" "then" "else"])))))
-
-(deftest ^:parallel repair-operator-form-passthrough-test
- (testing "unrecognized-but-valid operators pass through"
- (is (= ["+" 1 2]
- (forms/repair-operator-form identity ["+" 1 2])))))
diff --git a/test/metabase/agent_lib/repair/normalize/top_level_test.clj b/test/metabase/agent_lib/repair/normalize/top_level_test.clj
deleted file mode 100644
index 56e6ef2b657..00000000000
--- a/test/metabase/agent_lib/repair/normalize/top_level_test.clj
+++ /dev/null
@@ -1,27 +0,0 @@
-(ns metabase.agent-lib.repair.normalize.top-level-test
- (:require
- [clojure.test :refer [deftest is]]
- [metabase.agent-lib.repair.normalize.top-level :as top-level]))
-
-(deftest ^:parallel normalize-with-fields-selection-flattens-single-sequential-arg-test
- (is (= [["field" 1] ["field" 2]]
- (top-level/normalize-with-fields-selection [[["field" 1] ["field" 2]]]))))
-
-(deftest ^:parallel repair-order-by-operations-normalizes-both-order-by-encodings-test
- (is (= [["order-by" ["desc" ["field" 1]]]
- ["order-by" ["field" 2] "asc"]]
- (top-level/repair-order-by-operations [["desc" ["field" 1]]
- ["field" 2]
- "asc"]))))
-
-(deftest ^:parallel repair-with-fields-operation-extracts-inline-expressions-test
- (is (= [["expression" "Net" ["-" ["field" 1] 10]]
- ["with-fields" [["field" 1] ["expression-ref" "Net"]]]]
- (top-level/repair-with-fields-operation identity
- [[["field" 1]
- ["expression" "Net" ["-" ["field" 1] 10]]]]))))
-
-(deftest ^:parallel repair-top-level-operation-rewrites-aggregation-expressions-test
- (is (= [["aggregate" ["count"]]]
- (top-level/repair-top-level-operation identity
- ["expression" "Total" ["count"]]))))
diff --git a/test/metabase/agent_lib/repair/stages_test.clj b/test/metabase/agent_lib/repair/stages_test.clj
deleted file mode 100644
index c3d2a9323ad..00000000000
--- a/test/metabase/agent_lib/repair/stages_test.clj
+++ /dev/null
@@ -1,23 +0,0 @@
-(ns metabase.agent-lib.repair.stages-test
- (:require
- [clojure.test :refer [deftest is]]
- [metabase.agent-lib.repair.stages :as repair.stages]
- [metabase.lib.test-metadata :as meta]))
-
-(deftest insert-stage-boundaries-adds-post-aggregation-stage-test
- (let [source {:type "context" :ref "source"}
- operations [["aggregate" ["sum" ["field" (meta/id :orders :total)]]]
- ["expression" "Revenue K" ["/" ["aggregation-ref" 0] 1000]]]
- expected [["aggregate" ["sum" ["field" (meta/id :orders :total)]]]
- ["append-stage"]
- ["expression" "Revenue K" ["/" ["aggregation-ref" 0] 1000]]]]
- (is (= expected
- (repair.stages/insert-stage-boundaries source operations)))))
-
-(deftest insert-stage-boundaries-respects-existing-boundaries-test
- (let [source {:type "context" :ref "source"}
- operations [["aggregate" ["sum" ["field" (meta/id :orders :total)]]]
- ["append-stage"]
- ["filter" [">" ["aggregation-ref" 0] 100]]]]
- (is (= operations
- (repair.stages/insert-stage-boundaries source operations)))))
diff --git a/test/metabase/agent_lib/repair_test.clj b/test/metabase/agent_lib/repair_test.clj
deleted file mode 100644
index b34153d044a..00000000000
--- a/test/metabase/agent_lib/repair_test.clj
+++ /dev/null
@@ -1,224 +0,0 @@
-(ns metabase.agent-lib.repair-test
- (:require
- [clojure.test :refer [deftest is]]
- [metabase.agent-lib.repair :as repair]
- [metabase.lib.test-metadata :as meta]))
-
-(deftest ^:parallel repair-program-normalization-test
- (let [program {:source {:type "context" :ref "source"}
- :operations [["aggregate" ["count"] ["variance" ["field" (meta/id :orders :total)]]]
- ["with-fields" [["field" (meta/id :orders :id)]
- ["expression" "Net Total" ["-" ["field" (meta/id :orders :total)] 10]]]]
- ["filter" ["is-not" ["field" (meta/id :orders :total)] "null"]]
- ["filter" ["=" ["field" (meta/id :orders :product-id)] ["1" "2"]]]
- ["breakout"
- ["with-temporal-bucket" ["field" (meta/id :orders :created-at)] "day-of-week"]]
- ["order-by" ["field" (meta/id :orders :created-at)]
- ["desc" ["field" (meta/id :orders :total)]]]]}
- expected {:source {:type "context" :ref "source"}
- :operations [["aggregate" ["count"]]
- ["aggregate" ["var" ["field" (meta/id :orders :total)]]]
- ["expression" "Net Total" ["-" ["field" (meta/id :orders :total)] 10]]
- ["with-fields" [["field" (meta/id :orders :id)]
- ["expression-ref" "Net Total"]]]
- ["filter" ["not-null" ["field" (meta/id :orders :total)]]]
- ["filter" ["in" ["field" (meta/id :orders :product-id)] ["1" "2"]]]
- ["breakout" ["get-day-of-week" ["field" (meta/id :orders :created-at)]]]
- ["order-by" ["field" (meta/id :orders :created-at)]]
- ["order-by" ["desc" ["field" (meta/id :orders :total)]]]]}]
- (is (= expected (repair/repair-program program)))))
-
-(deftest ^:parallel repair-program-quarter-and-diff-normalization-test
- (let [program {:source {:type "context" :ref "source"}
- :operations [["filter" ["="
- ["with-temporal-bucket"
- ["field" (meta/id :orders :created-at)] "quarter"]
- "Q1"]]
- ["breakout"
- ["with-temporal-bucket"
- ["field" (meta/id :orders :created-at)] "hour-of-day"]]
- ["expression" "Quarter Number"
- ["quarter-of-year" ["field" (meta/id :orders :created-at)]]]
- ["expression" "Days Open"
- ["temporal-diff" ["now"]
- ["field" (meta/id :orders :created-at)] "day"]]]}
- expected {:source {:type "context" :ref "source"}
- :operations [["filter" ["="
- ["with-temporal-bucket"
- ["field" (meta/id :orders :created-at)] "quarter"]
- 1]]
- ["breakout"
- ["get-hour" ["field" (meta/id :orders :created-at)]]]
- ["expression" "Quarter Number"
- ["get-quarter" ["field" (meta/id :orders :created-at)]]]
- ["expression" "Days Open"
- ["datetime-diff" ["now"]
- ["field" (meta/id :orders :created-at)] "day"]]]}]
- (is (= expected (repair/repair-program program)))))
-
-(deftest ^:parallel repair-program-normalizes-if-and-between-bounds-test
- (let [program {:source {:type "context" :ref "source"}
- :operations [["filter" ["between"
- ["field" (meta/id :orders :created-at)]
- ["relative-datetime" -3 "month"]
- "2025-09-30"]]
- ["expression" "Accepted Count"
- ["if" ["=" ["field" (meta/id :orders :user-id)] 1] 1 0]]]}
- expected {:source {:type "context" :ref "source"}
- :operations [["filter" ["between"
- ["field" (meta/id :orders :created-at)]
- ["relative-datetime" -3 "month"]
- ["absolute-datetime" "2025-09-30" "day"]]]
- ["expression" "Accepted Count"
- ["case" [[["=" ["field" (meta/id :orders :user-id)] 1] 1]] 0]]]}]
- (is (= expected (repair/repair-program program)))))
-
-(deftest ^:parallel repair-program-normalizes-now-bounds-case-ternaries-and-text-filter-flags-test
- (let [program {:source {:type "context" :ref "source"}
- :operations [["filter" ["contains" ["field" (meta/id :orders :product-id)] "friend" false]]
- ["filter" ["between"
- ["field" (meta/id :orders :created-at)]
- ["relative-datetime" -3 "month"]
- "now"]]
- ["expression" "Accepted Count"
- ["case" [["true" ["field" (meta/id :orders :user-id)]]
- 1
- 0]]]]}
- expected {:source {:type "context" :ref "source"}
- :operations [["filter" ["contains" ["field" (meta/id :orders :product-id)] "friend"]]
- ["filter" ["between"
- ["field" (meta/id :orders :created-at)]
- ["relative-datetime" -3 "month"]
- ["now"]]]
- ["expression" "Accepted Count"
- ["case" [[["field" (meta/id :orders :user-id)] 1]] 0]]]}]
- (is (= expected (repair/repair-program program)))))
-
-(deftest ^:parallel repair-program-unwraps-join-condition-wrapper-test
- (let [wrapped-conditions [[["="
- ["field" (meta/id :venues :category-id)]
- ["field" (meta/id :categories :id)]]]]
- expected-conditions [["="
- ["field" (meta/id :venues :category-id)]
- ["field" (meta/id :categories :id)]]]
- program {:source {:type "context" :ref "source"}
- :operations [["join"
- ["with-join-conditions"
- ["join-clause" ["table" (meta/id :categories)]]
- wrapped-conditions]]]}
- expected {:source {:type "context" :ref "source"}
- :operations [["join"
- ["with-join-conditions"
- ["join-clause" ["table" (meta/id :categories)]]
- expected-conditions]]]}]
- (is (= expected (repair/repair-program program)))))
-
-(deftest ^:parallel repair-program-rewrites-aggregation-expression-test
- (let [program {:source {:type "context" :ref "source"}
- :operations [["expression" "Total Opportunities" ["count"]]
- ["expression" "Won" ["count-if" ["field" (meta/id :orders :discount)]]]]}
- expected {:source {:type "context" :ref "source"}
- :operations [["aggregate" ["count"]]
- ["aggregate" ["count-where" ["field" (meta/id :orders :discount)]]]]}]
- (is (= expected (repair/repair-program program)))))
-
-(deftest ^:parallel repair-program-drops-stray-bare-aggregation-ref-in-aggregate-test
- (let [program {:source {:type "context" :ref "source"}
- :operations [["aggregate" ["count"] ["aggregation-ref" 0]]]}
- expected {:source {:type "context" :ref "source"}
- :operations [["aggregate" ["count"]]]}]
- (is (= expected (repair/repair-program program)))))
-
-(deftest ^:parallel repair-program-normalizes-percentile-scale-test
- (let [program {:source {:type "context" :ref "source"}
- :operations [["aggregate" ["percentile" ["field" (meta/id :orders :total)] 90]]]}
- expected {:source {:type "context" :ref "source"}
- :operations [["aggregate" ["percentile" ["field" (meta/id :orders :total)] 0.9]]]}]
- (is (= expected (repair/repair-program program)))))
-
-(deftest ^:parallel repair-program-inserts-append-stage-before-aggregate-on-aggregation-ref-test
- (let [program {:source {:type "program"
- :program {:source {:type "context" :ref "source"}
- :operations [["aggregate" ["sum" ["field" (meta/id :orders :total)]]]
- ["breakout" ["field" (meta/id :orders :created-at)]]]}}
- :operations [["aggregate" ["stddev" ["aggregation-ref" 0]]]]}
- expected {:source {:type "program"
- :program {:source {:type "context" :ref "source"}
- :operations [["aggregate" ["sum" ["field" (meta/id :orders :total)]]]
- ["breakout" ["field" (meta/id :orders :created-at)]]]}}
- :operations [["append-stage"]
- ["aggregate" ["stddev" ["aggregation-ref" 0]]]]}]
- (is (= expected (repair/repair-program program)))))
-
-(deftest ^:parallel repair-program-for-context-drops-source-stage-aggregates-for-metric-sources-test
- (let [program {:source {:type "context" :ref "source"}
- :operations [["aggregate" ["avg" ["field" (meta/id :orders :total)]]]
- ["breakout" ["field" (meta/id :orders :product-id)]]
- ["append-stage"]
- ["aggregate" ["avg" ["aggregation-ref" 0]]]]}
- context {:source-entity {:model "metric" :id 42}
- :referenced-entities []
- :surrounding-tables []
- :join-edges []}
- expected {:source {:type "context" :ref "source"}
- :operations [["breakout" ["field" (meta/id :orders :product-id)]]
- ["append-stage"]
- ["aggregate" ["avg" ["aggregation-ref" 0]]]]}]
- (is (= expected (repair/repair-program-for-context program context)))))
-
-(deftest ^:parallel repair-program-for-context-drops-source-stage-with-fields-over-aggregation-ref-test
- (let [program {:source {:type "context" :ref "source"}
- :operations [["filter" ["=" ["field" (meta/id :products :category)] "Gizmo"]]
- ["with-fields" [["field" (meta/id :products :category)]
- ["aggregation-ref" 0]]]]}
- context {:source-entity {:model "metric" :id 83}
- :referenced-entities []
- :surrounding-tables []
- :measure-ids []}
- expected {:source {:type "context" :ref "source"}
- :operations [["filter" ["=" ["field" (meta/id :products :category)] "Gizmo"]]]}]
- (is (= expected (repair/repair-program-for-context program context)))))
-
-(deftest ^:parallel repair-program-for-context-normalizes-last-quarter-metric-window-test
- (let [program {:source {:type "context" :ref "source"}
- :operations [["filter" ["between"
- ["field" (meta/id :orders :created-at)]
- ["relative-datetime" -3 "month"]
- "now"]]
- ["aggregate" ["count"]]]}
- context {:source-entity {:model "metric" :id 42}
- :referenced-entities []
- :surrounding-tables []
- :measure-ids []}
- expected {:source {:type "context" :ref "source"}
- :operations [["filter" ["between"
- ["field" (meta/id :orders :created-at)]
- ["relative-datetime" -1 "quarter"]
- ["relative-datetime" 0 "quarter"]]]]}]
- (is (= expected
- (repair/repair-program-for-context (repair/repair-program program) context)))))
-
-(deftest ^:parallel repair-program-normalizes-field-like-map-in-breakout-test
- (let [program {:source {:type "table" :id 1}
- :operations [["breakout" {"field_id" 13 "temporal_bucket" "month"}]]}
- expected {:source {:type "table" :id 1}
- :operations [["breakout" ["with-temporal-bucket" ["field" 13] "month"]]]}]
- (is (= expected (repair/repair-program program)))))
-
-(deftest ^:parallel repair-program-unwraps-order-by-vector-of-direction-tuples-test
- (let [program {:source {:type "table" :id 1}
- :operations [["order-by" [["asc" {"field_id" 13 "temporal_bucket" "month"}]
- ["desc" {"field_id" 14}]]]]}
- expected {:source {:type "table" :id 1}
- :operations [["order-by" ["asc" ["with-temporal-bucket" ["field" 13] "month"]]]
- ["order-by" ["desc" ["field" 14]]]]}]
- (is (= expected (repair/repair-program program)))))
-
-(deftest ^:parallel repair-program-normalizes-order-by-map-with-direction-key-test
- (let [program {:source {:type "table" :id 1}
- :operations [["order-by" {"field_id" 13
- "temporal_bucket" "month"
- "direction" "asc"}]]}
- expected {:source {:type "table" :id 1}
- :operations [["order-by" ["asc" ["with-temporal-bucket" ["field" 13] "month"]]]]}]
- (is (= expected (repair/repair-program program)))))
diff --git a/test/metabase/agent_lib/representations/repair_test.clj b/test/metabase/agent_lib/representations/repair_test.clj
new file mode 100644
index 00000000000..74e74643f24
--- /dev/null
+++ b/test/metabase/agent_lib/representations/repair_test.clj
@@ -0,0 +1,2609 @@
+(ns metabase.agent-lib.representations.repair-test
+ "Tests for the LLM-input repair pass."
+ (:require
+ [clojure.test :refer [deftest is testing]]
+ [clojure.test.check.clojure-test :refer [defspec]]
+ [clojure.test.check.generators :as gen]
+ [clojure.test.check.properties :as prop]
+ [metabase.agent-lib.representations :as repr]
+ [metabase.agent-lib.representations.repair :as repair]
+ [metabase.lib.test-util :as lib.tu]))
+
+(set! *warn-on-reflection* true)
+
+;;; ============================================================
+;;; Mock metadata providers
+;;; ============================================================
+
+(def ^:private trivial-mp
+ "A metadata provider with a single database, no tables. Sufficient to satisfy the repair
+ signature for shape-only tests - the implicit-join pass will no-op because it can't resolve
+ the source-table."
+ (lib.tu/mock-metadata-provider
+ {:database {:id 1 :name "Sample"}}))
+
+(def ^:private mp-fks
+ "3-table MP: ORDERS → PRODUCTS, ORDERS → USERS."
+ (lib.tu/mock-metadata-provider
+ {:database {:id 1 :name "Sample"}
+ :tables [{:id 10 :name "ORDERS" :schema "PUBLIC" :db-id 1}
+ {:id 20 :name "PRODUCTS" :schema "PUBLIC" :db-id 1}
+ {:id 30 :name "USERS" :schema "PUBLIC" :db-id 1}]
+ :fields [{:id 100 :name "ID" :table-id 10 :base-type :type/Integer}
+ {:id 101 :name "PRODUCT_ID" :table-id 10 :base-type :type/Integer :fk-target-field-id 200}
+ {:id 102 :name "USER_ID" :table-id 10 :base-type :type/Integer :fk-target-field-id 300}
+ {:id 200 :name "ID" :table-id 20 :base-type :type/Integer}
+ {:id 201 :name "CATEGORY" :table-id 20 :base-type :type/Text}
+ {:id 300 :name "ID" :table-id 30 :base-type :type/Integer}
+ {:id 301 :name "NAME" :table-id 30 :base-type :type/Text}]}))
+
+(def ^:private mp-ambiguous
+ "Two FKs from ORDERS to PRODUCTS."
+ (lib.tu/mock-metadata-provider
+ {:database {:id 1 :name "Sample"}
+ :tables [{:id 10 :name "ORDERS" :schema "PUBLIC" :db-id 1}
+ {:id 20 :name "PRODUCTS" :schema "PUBLIC" :db-id 1}]
+ :fields [{:id 100 :name "ID" :table-id 10 :base-type :type/Integer}
+ {:id 101 :name "PRODUCT_ID" :table-id 10 :base-type :type/Integer :fk-target-field-id 200}
+ {:id 103 :name "ALT_PRODUCT_ID" :table-id 10 :base-type :type/Integer :fk-target-field-id 200}
+ {:id 200 :name "ID" :table-id 20 :base-type :type/Integer}
+ {:id 201 :name "CATEGORY" :table-id 20 :base-type :type/Text}]}))
+
+(def ^:private mp-no-fk
+ "ORDERS + PRODUCTS exist but with no FK between them."
+ (lib.tu/mock-metadata-provider
+ {:database {:id 1 :name "Sample"}
+ :tables [{:id 10 :name "ORDERS" :schema "PUBLIC" :db-id 1}
+ {:id 20 :name "PRODUCTS" :schema "PUBLIC" :db-id 1}]
+ :fields [{:id 100 :name "ID" :table-id 10 :base-type :type/Integer}
+ {:id 200 :name "ID" :table-id 20 :base-type :type/Integer}
+ {:id 201 :name "CATEGORY" :table-id 20 :base-type :type/Text}]}))
+
+(def ^:private mp-via-join
+ "3-table MP with a hop-through-PRODUCTS shape:
+ ORDERS (no FK to CATEGORIES)
+ PRODUCTS → CATEGORIES via PRODUCTS.CATEGORY_ID
+ CATEGORIES.NAME
+ ORDERS → PRODUCTS exists too (so the prompt's PRODUCTS join makes sense). Used to exercise
+ Pass 3.5 (`source-field-join-alias` auto-fill)."
+ (lib.tu/mock-metadata-provider
+ {:database {:id 1 :name "Sample"}
+ :tables [{:id 10 :name "ORDERS" :schema "PUBLIC" :db-id 1}
+ {:id 20 :name "PRODUCTS" :schema "PUBLIC" :db-id 1}
+ {:id 40 :name "CATEGORIES" :schema "PUBLIC" :db-id 1}]
+ :fields [{:id 100 :name "ID" :table-id 10 :base-type :type/Integer}
+ {:id 101 :name "PRODUCT_ID" :table-id 10 :base-type :type/Integer :fk-target-field-id 200}
+ {:id 200 :name "ID" :table-id 20 :base-type :type/Integer}
+ {:id 202 :name "CATEGORY_ID" :table-id 20 :base-type :type/Integer :fk-target-field-id 400}
+ {:id 400 :name "ID" :table-id 40 :base-type :type/Integer}
+ {:id 401 :name "NAME" :table-id 40 :base-type :type/Text}]}))
+
+(def ^:private mp-via-two-joins
+ "Variant of `mp-via-join` where TWO different joined tables (PRODUCTS and PRODUCTS_ALT) each
+ reach CATEGORIES via a single FK. Used to exercise the `:ambiguous-fk-via-join` error
+ path."
+ (lib.tu/mock-metadata-provider
+ {:database {:id 1 :name "Sample"}
+ :tables [{:id 10 :name "ORDERS" :schema "PUBLIC" :db-id 1}
+ {:id 20 :name "PRODUCTS" :schema "PUBLIC" :db-id 1}
+ {:id 21 :name "PRODUCTS_ALT" :schema "PUBLIC" :db-id 1}
+ {:id 40 :name "CATEGORIES" :schema "PUBLIC" :db-id 1}]
+ :fields [{:id 100 :name "ID" :table-id 10 :base-type :type/Integer}
+ {:id 200 :name "ID" :table-id 20 :base-type :type/Integer}
+ {:id 202 :name "CATEGORY_ID" :table-id 20 :base-type :type/Integer :fk-target-field-id 400}
+ {:id 210 :name "ID" :table-id 21 :base-type :type/Integer}
+ {:id 212 :name "CATEGORY_ID" :table-id 21 :base-type :type/Integer :fk-target-field-id 400}
+ {:id 400 :name "ID" :table-id 40 :base-type :type/Integer}
+ {:id 401 :name "NAME" :table-id 40 :base-type :type/Text}]}))
+
+;;; ============================================================
+;;; Pass 1 - insert `{}` options on clauses
+;;; ============================================================
+
+(deftest insert-options-on-bare-clause-test
+ (testing "clause without options gets {} inserted"
+ (is (= ["count" {}]
+ (repair/repair trivial-mp ["count"])))
+ (is (= ["sum" {} ["field" {} ["Sample" "S" "T" "F"]]]
+ (repair/repair trivial-mp ["sum" ["field" ["Sample" "S" "T" "F"]]])))))
+
+(deftest do-not-corrupt-fk-paths-test
+ (testing "FK paths (all-string vectors) are left alone"
+ (let [fk ["Sample" "PUBLIC" "TBL" "COL"]]
+ (is (= fk (repair/repair trivial-mp fk))))
+ (let [fk ["Sample" nil "TBL" "COL"]]
+ (is (= fk (repair/repair trivial-mp fk)))))
+ (testing "clause containing an FK in its arg position doesn't touch the FK shape"
+ (let [input ["field" ["Sample" "PUBLIC" "TBL" "COL"]]
+ output (repair/repair trivial-mp input)]
+ (is (= ["field" {} ["Sample" "PUBLIC" "TBL" "COL"]] output)))))
+
+(deftest nested-clause-repair-test
+ (testing "options filled in at every nesting level"
+ (let [input ["and"
+ ["="
+ ["field" ["Sample" "S" "T" "A"]]
+ 10]
+ [">"
+ ["field" ["Sample" "S" "T" "B"]]
+ 5]]
+ output (repair/repair trivial-mp input)]
+ (is (= ["and" {}
+ ["=" {} ["field" {} ["Sample" "S" "T" "A"]] 10]
+ [">" {} ["field" {} ["Sample" "S" "T" "B"]] 5]]
+ output)))))
+
+(deftest nil-options-replaced-test
+ (testing "nil in options slot is replaced with {}"
+ ;; clj-yaml sometimes hands us nil for `~` where we'd want {}
+ (is (= ["count" {}] (repair/repair trivial-mp ["count" nil])))))
+
+;;; ============================================================
+;;; Pass 1.7 - unwrap nested `[field ... [field ... FK]]` clauses
+;;;
+;;; LLMs sometimes write a field clause *wrapping another field clause*, e.g.
+;;;
+;;; ["field" {"temporal-unit" "month"} ["field" {} ["Sample" "PUBLIC" "T" "COL"]]]
+;;;
+;;; thinking of it as "apply granularity to this field". The intent is always a single
+;;; `field` clause with the merged options (outer wins on conflicts). We collapse such
+;;; nests into one clause so downstream FK resolution sees a flat
+;;; `["field" {<merged opts>} [<FK>]]`.
+;;; ============================================================
+
+(deftest unwrap-nested-field-test
+ (testing "outer field wrapping an inner field with an FK is collapsed"
+ (let [input ["field" {"temporal-unit" "month"}
+ ["field" {} ["Sample" "PUBLIC" "ACCOUNTS" "CANCELED_AT"]]]
+ output (repair/repair trivial-mp input)]
+ (is (= ["field" {"temporal-unit" "month"}
+ ["Sample" "PUBLIC" "ACCOUNTS" "CANCELED_AT"]]
+ output))))
+ (testing "outer options win on conflict (outer temporal-unit overrides inner)"
+ (let [input ["field" {"temporal-unit" "month"}
+ ["field" {"temporal-unit" "day"} ["Sample" "PUBLIC" "T" "COL"]]]
+ output (repair/repair trivial-mp input)]
+ (is (= ["field" {"temporal-unit" "month"} ["Sample" "PUBLIC" "T" "COL"]]
+ output))))
+ (testing "inner-only options are preserved when outer doesn't set them"
+ (let [input ["field" {"temporal-unit" "month"}
+ ["field" {"source-field" ["Sample" "PUBLIC" "T" "FK"]}
+ ["Sample" "PUBLIC" "T" "COL"]]]
+ output (repair/repair trivial-mp input)]
+ (is (= ["field" {"temporal-unit" "month"
+ "source-field" ["Sample" "PUBLIC" "T" "FK"]}
+ ["Sample" "PUBLIC" "T" "COL"]]
+ output))))
+ (testing "outer empty opts + nested field: outer gets inner's opts"
+ (let [input ["field" {}
+ ["field" {"temporal-unit" "day"} ["Sample" "PUBLIC" "T" "COL"]]]
+ output (repair/repair trivial-mp input)]
+ (is (= ["field" {"temporal-unit" "day"} ["Sample" "PUBLIC" "T" "COL"]]
+ output))))
+ (testing "nested inside a larger clause (e.g. breakout of a stage) is collapsed"
+ (let [input ["and" {}
+ ["=" {}
+ ["field" {"temporal-unit" "month"}
+ ["field" {} ["Sample" "PUBLIC" "T" "COL"]]]
+ "Bikes"]]
+ output (repair/repair trivial-mp input)]
+ (is (= ["and" {}
+ ["=" {}
+ ["field" {"temporal-unit" "month"} ["Sample" "PUBLIC" "T" "COL"]]
+ "Bikes"]]
+ output))))
+ (testing "triple-nested field collapses to one"
+ (let [input ["field" {"temporal-unit" "month"}
+ ["field" {}
+ ["field" {"source-field" ["Sample" "PUBLIC" "T" "FK"]}
+ ["Sample" "PUBLIC" "T" "COL"]]]]
+ output (repair/repair trivial-mp input)]
+ (is (= ["field" {"temporal-unit" "month"
+ "source-field" ["Sample" "PUBLIC" "T" "FK"]}
+ ["Sample" "PUBLIC" "T" "COL"]]
+ output))))
+ (testing "non-nested `field` clauses are left alone"
+ (let [input ["field" {"temporal-unit" "month"} ["Sample" "PUBLIC" "T" "COL"]]]
+ (is (= input (repair/repair trivial-mp input)))))
+ (testing "cross-stage string-column field inside outer field is preserved"
+ ;; [field {temporal-unit ...} [field {} "some-col-name"]] is the same bug pattern but
+ ;; with a cross-stage (string) target. Still unwrap.
+ (let [input ["field" {"temporal-unit" "month"}
+ ["field" {} "MY_COLUMN"]]
+ output (repair/repair trivial-mp input)]
+ (is (= ["field" {"temporal-unit" "month"} "MY_COLUMN"]
+ output)))))
+
+;;; ============================================================
+;;; Pass 1.81 - rewrite operator-name aliases to canonical lib heads
+;;; ============================================================
+
+(deftest rewrite-shell-style-comparison-aliases-test
+ (testing "shell-style comparison operators rewrite to canonical"
+ (let [field ["field" {} ["Sample" "PUBLIC" "X" "A"]]]
+ (doseq [[alias canonical] [["eq" "="]
+ ["ne" "!="]
+ ["lt" "<"]
+ ["le" "<="]
+ ["lte" "<="]
+ ["gt" ">"]
+ ["ge" ">="]
+ ["gte" ">="]]]
+ (is (= [canonical {} field 10]
+ (repair/repair trivial-mp [alias {} field 10]))
+ (str alias " -> " canonical))))))
+
+(deftest rewrite-verbose-comparison-aliases-test
+ (testing "verbose comparison spellings"
+ (let [field ["field" {} ["Sample" "PUBLIC" "X" "A"]]]
+ (is (= ["=" {} field 10]
+ (repair/repair trivial-mp ["equals" {} field 10])))
+ (is (= ["!=" {} field 10]
+ (repair/repair trivial-mp ["not-equals" {} field 10]))))))
+
+(deftest rewrite-aggregation-aliases-test
+ (testing "aggregation lib-renames"
+ (let [field ["field" {} ["Sample" "PUBLIC" "X" "A"]]
+ pred ["=" {} field 1]]
+ (is (= ["count-where" {} pred]
+ (repair/repair trivial-mp ["count-if" {} pred])))
+ (is (= ["var" {} field]
+ (repair/repair trivial-mp ["variance" {} field])))
+ (is (= ["stddev" {} field]
+ (repair/repair trivial-mp ["stddev-pop" {} field])))
+ (is (= ["distinct" {} field]
+ (repair/repair trivial-mp ["count-distinct" {} field])))
+ (is (= ["distinct" {} field]
+ (repair/repair trivial-mp ["distinct-count" {} field]))))))
+
+(deftest rewrite-temporal-and-null-aliases-test
+ (testing "temporal & null lib-renames"
+ (let [field ["field" {} ["Sample" "PUBLIC" "X" "DATE"]]]
+ (is (= ["relative-datetime" {} -7 "day"]
+ (repair/repair trivial-mp ["relative-date" {} -7 "day"])))
+ (is (= ["datetime-diff" {} field field "day"]
+ (repair/repair trivial-mp ["temporal-diff" {} field field "day"])))
+ (is (= ["not-null" {} field]
+ (repair/repair trivial-mp ["is-not-null" {} field]))))))
+
+(deftest operator-alias-case-insensitive-test
+ (testing "alias matching is case-insensitive"
+ (let [field ["field" {} ["Sample" "PUBLIC" "X" "A"]]]
+ (doseq [variant ["EQ" "Eq" "EQUALS" "Equals"]]
+ (is (= ["=" {} field 10]
+ (repair/repair trivial-mp [variant {} field 10]))
+ variant)))))
+
+(deftest operator-alias-canonical-untouched-test
+ (testing "already-canonical heads are not double-rewritten (cheap idempotency)"
+ (let [field ["field" {} ["Sample" "PUBLIC" "X" "A"]]]
+ (doseq [canonical ["=" "!=" "<" "<=" ">" ">="]]
+ (let [input [canonical {} field 10]]
+ (is (= input (repair/repair trivial-mp input)) canonical))))))
+
+(deftest operator-alias-nested-test
+ (testing "alias nested deep inside a tree gets rewritten"
+ (let [field ["field" {} ["Sample" "PUBLIC" "X" "A"]]
+ input ["and" {}
+ ["eq" {} field 1]
+ ["gt" {} field 5]]]
+ (is (= ["and" {}
+ ["=" {} field 1]
+ [">" {} field 5]]
+ (repair/repair trivial-mp input))))))
+
+(deftest operator-alias-fk-path-untouched-test
+ (testing "a column literally named 'eq' or 'gt' inside an FK path is NOT rewritten"
+ (is (= ["field" {} ["Sample" "PUBLIC" "T" "eq"]]
+ (repair/repair trivial-mp ["field" {} ["Sample" "PUBLIC" "T" "eq"]])))
+ (is (= ["field" {} ["Sample" "PUBLIC" "T" "gt"]]
+ (repair/repair trivial-mp ["field" {} ["Sample" "PUBLIC" "T" "gt"]])))))
+
+;;; ============================================================
+;;; Pass 1.8 - rewrite temporal-bucket-extraction aliases to canonical names
+;;; ============================================================
+
+(deftest rewrite-temporal-bucket-aliases-test
+ (testing "each alias rewrites to its canonical lib head"
+ (doseq [[alias canonical] [["dayofweek" "get-day-of-week"]
+ ["day-of-week" "get-day-of-week"]
+ ["hour-of-day" "get-hour"]
+ ["month-of-year" "get-month"]
+ ["quarter-of-year" "get-quarter"]]]
+ (let [input [alias {} ["field" {} ["Sample" "PUBLIC" "T" "COL"]]]]
+ (is (= [canonical {} ["field" {} ["Sample" "PUBLIC" "T" "COL"]]]
+ (repair/repair trivial-mp input))
+ (str alias " -> " canonical)))))
+ (testing "alias appearing nested inside another clause is rewritten too"
+ (let [input ["=" {}
+ ["day-of-week" {} ["field" {} ["Sample" "PUBLIC" "T" "COL"]]]
+ 3]]
+ (is (= ["=" {}
+ ["get-day-of-week" {} ["field" {} ["Sample" "PUBLIC" "T" "COL"]]]
+ 3]
+ (repair/repair trivial-mp input)))))
+ (testing "canonical heads are left alone (not double-rewritten)"
+ (let [input ["get-day-of-week" {} ["field" {} ["Sample" "PUBLIC" "T" "COL"]]]]
+ (is (= input (repair/repair trivial-mp input)))))
+ (testing "alias with missing options is also handled (Pass 1 fills the {} first)"
+ (let [input ["day-of-week" ["field" {} ["Sample" "PUBLIC" "T" "COL"]]]]
+ (is (= ["get-day-of-week" {} ["field" {} ["Sample" "PUBLIC" "T" "COL"]]]
+ (repair/repair trivial-mp input)))))
+ (testing "unrelated heads matching only by string substring are not touched"
+ ;; A column named "day-of-week" inside an FK path is not a clause head; we won't
+ ;; touch it.
+ (let [input ["field" {} ["Sample" "PUBLIC" "T" "day-of-week"]]]
+ (is (= input (repair/repair trivial-mp input))))))
+
+;;; ============================================================
+;;; Pass 1.85 - rewrite order-by direction aliases to canonical asc/desc
+;;; ============================================================
+
+(deftest rewrite-direction-aliases-test
+ (testing "long-form aliases rewrite to canonical short form"
+ (is (= ["asc" {} ["field" {} ["Sample" "PUBLIC" "T" "COL"]]]
+ (repair/repair trivial-mp
+ ["ascending" {} ["field" {} ["Sample" "PUBLIC" "T" "COL"]]])))
+ (is (= ["desc" {} ["field" {} ["Sample" "PUBLIC" "T" "COL"]]]
+ (repair/repair trivial-mp
+ ["descending" {} ["field" {} ["Sample" "PUBLIC" "T" "COL"]]]))))
+ (testing "uppercase / mixed-case variants rewrite to canonical lowercase"
+ (doseq [variant ["ASC" "Asc" "ASCENDING" "Ascending"]]
+ (is (= ["asc" {} ["field" {} ["Sample" "PUBLIC" "T" "COL"]]]
+ (repair/repair trivial-mp
+ [variant {} ["field" {} ["Sample" "PUBLIC" "T" "COL"]]]))
+ variant))
+ (doseq [variant ["DESC" "Desc" "DESCENDING" "Descending"]]
+ (is (= ["desc" {} ["field" {} ["Sample" "PUBLIC" "T" "COL"]]]
+ (repair/repair trivial-mp
+ [variant {} ["field" {} ["Sample" "PUBLIC" "T" "COL"]]]))
+ variant)))
+ (testing "already-canonical asc/desc clauses pass through unchanged"
+ (let [asc ["asc" {} ["field" {} ["Sample" "PUBLIC" "T" "COL"]]]
+ desc ["desc" {} ["field" {} ["Sample" "PUBLIC" "T" "COL"]]]]
+ (is (= asc (repair/repair trivial-mp asc)))
+ (is (= desc (repair/repair trivial-mp desc)))))
+ (testing "alias appearing inside an order-by stage list is rewritten"
+ (let [stage {"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "order-by" [["ASCENDING" {} ["field" {} ["Sample" "PUBLIC" "ORDERS" "ID"]]]
+ ["descending" {} ["field" {} ["Sample" "PUBLIC" "ORDERS" "ID"]]]]}
+ input {"lib/type" "mbql/query" "database" "Sample" "stages" [stage]}
+ output (repair/repair trivial-mp input)
+ [a d] (get-in output ["stages" 0 "order-by"])]
+ (is (= "asc" (first a)))
+ (is (= "desc" (first d)))))
+ (testing "non-direction strings are not touched"
+ ;; A column literally named "asc" inside an FK path stays put.
+ (let [input ["field" {} ["Sample" "PUBLIC" "T" "asc"]]]
+ (is (= input (repair/repair trivial-mp input))))
+ ;; A scalar string "ASC" by itself (not a clause) is untouched.
+ (is (= "ASC" (repair/repair trivial-mp "ASC")))))
+
+;;; ============================================================
+;;; Pass 1.84 - normalise alternative case / if argument shapes
+;;; ============================================================
+
+(deftest case-three-bare-args-test
+ (testing "[case {} pred then else] -> canonical pairs + default"
+ (let [pred ["=" {} ["field" {} ["Sample" "PUBLIC" "X" "A"]] 1]
+ input ["case" {} pred 100 0]]
+ (is (= ["case" {} [[pred 100]] 0]
+ (repair/repair trivial-mp input))))))
+
+(deftest case-two-bare-args-test
+ (testing "[case {} pred then] (no default) -> canonical pairs only"
+ (let [pred ["=" {} ["field" {} ["Sample" "PUBLIC" "X" "A"]] 1]
+ input ["case" {} pred 100]]
+ (is (= ["case" {} [[pred 100]]]
+ (repair/repair trivial-mp input))))))
+
+(deftest case-branch-pairs-as-separate-args-test
+ (testing "branch pairs as separate args + trailing default"
+ (let [p1 ["=" {} ["field" {} ["Sample" "PUBLIC" "X" "A"]] 1]
+ p2 ["=" {} ["field" {} ["Sample" "PUBLIC" "X" "A"]] 2]
+ input ["case" {} [p1 100] [p2 200] 0]]
+ (is (= ["case" {} [[p1 100] [p2 200]] 0]
+ (repair/repair trivial-mp input)))))
+ (testing "branch pairs as separate args without default"
+ (let [p1 ["=" {} ["field" {} ["Sample" "PUBLIC" "X" "A"]] 1]
+ p2 ["=" {} ["field" {} ["Sample" "PUBLIC" "X" "A"]] 2]
+ input ["case" {} [p1 100] [p2 200]]]
+ (is (= ["case" {} [[p1 100] [p2 200]]]
+ (repair/repair trivial-mp input))))))
+
+(deftest case-flat-alternating-args-test
+ (testing "flat even-arity alternating: [case {} p1 t1 p2 t2]"
+ (let [p1 ["=" {} ["field" {} ["Sample" "PUBLIC" "X" "A"]] 1]
+ p2 ["=" {} ["field" {} ["Sample" "PUBLIC" "X" "A"]] 2]
+ input ["case" {} p1 100 p2 200]]
+ (is (= ["case" {} [[p1 100] [p2 200]]]
+ (repair/repair trivial-mp input)))))
+ (testing "flat odd-arity alternating: [case {} p1 t1 p2 t2 default]"
+ (let [p1 ["=" {} ["field" {} ["Sample" "PUBLIC" "X" "A"]] 1]
+ p2 ["=" {} ["field" {} ["Sample" "PUBLIC" "X" "A"]] 2]
+ input ["case" {} p1 100 p2 200 0]]
+ (is (= ["case" {} [[p1 100] [p2 200]] 0]
+ (repair/repair trivial-mp input))))))
+
+(deftest case-trailing-else-branch-test
+ (testing "trailing [\"else\" x] inside the pairs vector is stripped, x becomes default"
+ (let [p1 ["=" {} ["field" {} ["Sample" "PUBLIC" "X" "A"]] 1]
+ input ["case" {} [[p1 100] ["else" 0]]]]
+ (is (= ["case" {} [[p1 100]] 0]
+ (repair/repair trivial-mp input)))))
+ (testing "trailing else branch + explicit fallback: pair-trailing-else takes precedence"
+ ;; In practice this would be malformed, but we still normalise it without throwing.
+ ;; The trailing else inside the vector wins; the explicit fallback is dropped.
+ (let [p1 ["=" {} ["field" {} ["Sample" "PUBLIC" "X" "A"]] 1]
+ input ["case" {} [[p1 100] ["else" 0]] -1]]
+ (is (= ["case" {} [[p1 100]] 0]
+ (repair/repair trivial-mp input))))))
+
+(deftest case-already-canonical-test
+ (testing "canonical [case {} [[p t]]] is unchanged"
+ (let [p1 ["=" {} ["field" {} ["Sample" "PUBLIC" "X" "A"]] 1]
+ input ["case" {} [[p1 100]]]]
+ (is (= input (repair/repair trivial-mp input)))))
+ (testing "canonical with default unchanged"
+ (let [p1 ["=" {} ["field" {} ["Sample" "PUBLIC" "X" "A"]] 1]
+ input ["case" {} [[p1 100]] 0]]
+ (is (= input (repair/repair trivial-mp input))))))
+
+(deftest case-if-alias-test
+ (testing "`if` alias is normalised the same way as case"
+ (let [pred ["=" {} ["field" {} ["Sample" "PUBLIC" "X" "A"]] 1]
+ input ["if" {} pred 100 0]]
+ (is (= ["if" {} [[pred 100]] 0]
+ (repair/repair trivial-mp input))))))
+
+(deftest case-idempotent-test
+ (testing "normalisation is idempotent"
+ (let [pred ["=" {} ["field" {} ["Sample" "PUBLIC" "X" "A"]] 1]]
+ (doseq [input [["case" {} pred 100 0]
+ ["case" {} pred 100]
+ ["case" {} [pred 100] [pred 200] 0]
+ ["case" {} pred 100 pred 200]
+ ["case" {} [[pred 100] ["else" 0]]]]]
+ (let [once (repair/repair trivial-mp input)
+ twice (repair/repair trivial-mp once)]
+ (is (= once twice) (str "input: " input)))))))
+
+;;; ============================================================
+;;; Pass 1.82 - normalise list-valued comparison/in clauses to flat positional args
+;;; ============================================================
+
+(deftest splat-in-values-list-test
+ (testing "[in {} lhs [v1 v2 v3]] splats values into positional args"
+ (let [field ["field" {} ["Sample" "PUBLIC" "USERS" "NAME"]]
+ input ["in" {} field ["alice" "bob" "carol"]]]
+ (is (= ["in" {} field "alice" "bob" "carol"]
+ (repair/repair trivial-mp input)))))
+ (testing "[not-in {} lhs [v1 v2]] splats too"
+ (let [field ["field" {} ["Sample" "PUBLIC" "USERS" "NAME"]]
+ input ["not-in" {} field ["banned1" "banned2"]]]
+ (is (= ["not-in" {} field "banned1" "banned2"]
+ (repair/repair trivial-mp input)))))
+ (testing "already-flat in clause is left alone"
+ (let [field ["field" {} ["Sample" "PUBLIC" "USERS" "NAME"]]
+ input ["in" {} field "alice" "bob" "carol"]]
+ (is (= input (repair/repair trivial-mp input))))))
+
+(deftest convert-eq-with-list-to-in-test
+ (testing "[= {} lhs [v1 v2 v3]] becomes [in {} lhs v1 v2 v3]"
+ (let [field ["field" {} ["Sample" "PUBLIC" "USERS" "NAME"]]
+ input ["=" {} field ["alice" "bob"]]]
+ (is (= ["in" {} field "alice" "bob"]
+ (repair/repair trivial-mp input)))))
+ (testing "[!= {} lhs [v1 v2 v3]] becomes [not-in {} lhs v1 v2 v3]"
+ (let [field ["field" {} ["Sample" "PUBLIC" "USERS" "NAME"]]
+ input ["!=" {} field ["alice" "bob"]]]
+ (is (= ["not-in" {} field "alice" "bob"]
+ (repair/repair trivial-mp input)))))
+ (testing "[= {} lhs scalar] is left alone"
+ (let [field ["field" {} ["Sample" "PUBLIC" "USERS" "NAME"]]
+ input ["=" {} field "alice"]]
+ (is (= input (repair/repair trivial-mp input))))))
+
+(deftest in-with-clause-rhs-untouched-test
+ (testing "a clause-shaped rhs (e.g. nested expression) is not splatted"
+ (let [field ["field" {} ["Sample" "PUBLIC" "USERS" "CREATED_AT"]]
+ abs ["absolute-datetime" {} "2024-01-01" "day"]
+ input ["=" {} field abs]]
+ (is (= input (repair/repair trivial-mp input)))))
+ (testing "a list containing a clause is not splatted (would corrupt structure)"
+ ;; This shouldn't actually happen in practice but is the exact case our \"all entries
+ ;; are scalar\" predicate guards against.
+ (let [field ["field" {} ["Sample" "PUBLIC" "USERS" "CREATED_AT"]]
+ abs ["absolute-datetime" {} "2024-01-01" "day"]
+ input ["in" {} field [abs]]]
+ ;; Untouched because abs is a clause, not a scalar.
+ (is (= input (repair/repair trivial-mp input))))))
+
+(deftest splat-mixed-scalars-test
+ (testing "a values list with mixed scalar types splats correctly"
+ (let [field ["field" {} ["Sample" "PUBLIC" "USERS" "AGE"]]
+ input ["in" {} field [18 21 65]]]
+ (is (= ["in" {} field 18 21 65]
+ (repair/repair trivial-mp input))))
+ (let [field ["field" {} ["Sample" "PUBLIC" "USERS" "FLAG"]]
+ input ["in" {} field [true false]]]
+ (is (= ["in" {} field true false]
+ (repair/repair trivial-mp input))))))
+
+(deftest splat-idempotent-test
+ (testing "splat is idempotent"
+ (let [field ["field" {} ["Sample" "PUBLIC" "USERS" "NAME"]]]
+ (doseq [input [["in" {} field ["alice" "bob"]]
+ ["not-in" {} field ["x" "y"]]
+ ["=" {} field ["a" "b"]]
+ ["!=" {} field ["a" "b"]]]]
+ (let [once (repair/repair trivial-mp input)
+ twice (repair/repair trivial-mp once)]
+ (is (= once twice) (str "input: " input)))))))
+
+;;; ============================================================
+;;; Pass 1.83 - unwrap boolean wrapper clauses
+;;; ============================================================
+
+(deftest unwrap-boolean-wrapper-true-test
+ (testing "[true {} x] unwraps to x"
+ (let [field ["field" {} ["Sample" "PUBLIC" "USERS" "NAME"]]
+ inner ["=" {} field "alice"]
+ input ["true" {} inner]]
+ (is (= inner (repair/repair trivial-mp input)))))
+ (testing "[true {} <bare-clause-without-options>] still unwraps after Pass 1 fills the
+ inner options"
+ (let [field ["field" {} ["Sample" "PUBLIC" "USERS" "NAME"]]
+ ;; before repair: ["true" ["=" field "alice"]] (Pass 1 fills both options).
+ input ["true" ["=" field "alice"]]]
+ (is (= ["=" {} field "alice"] (repair/repair trivial-mp input))))))
+
+(deftest unwrap-boolean-wrapper-false-test
+ (testing "[false {} x] rewrites to [not {} x]"
+ (let [field ["field" {} ["Sample" "PUBLIC" "USERS" "NAME"]]
+ inner ["=" {} field "alice"]
+ input ["false" {} inner]]
+ (is (= ["not" {} inner]
+ (repair/repair trivial-mp input))))))
+
+(deftest boolean-literal-clauses-untouched-test
+ (testing "[true {}] (0-arg boolean literal) is left alone"
+ (is (= ["true" {}] (repair/repair trivial-mp ["true" {}]))))
+ (testing "[false {}] (0-arg boolean literal) is left alone"
+ (is (= ["false" {}] (repair/repair trivial-mp ["false" {}])))))
+
+(deftest boolean-wrapper-mixed-case-test
+ (testing "case-insensitive head matching"
+ (let [field ["field" {} ["Sample" "PUBLIC" "USERS" "NAME"]]
+ inner ["=" {} field "alice"]]
+ (doseq [variant ["TRUE" "True"]]
+ (is (= inner (repair/repair trivial-mp [variant {} inner]))
+ variant))
+ (doseq [variant ["FALSE" "False"]]
+ (is (= ["not" {} inner] (repair/repair trivial-mp [variant {} inner]))
+ variant)))))
+
+(deftest boolean-wrapper-nested-test
+ (testing "nested wrapper clauses unwrap from the inside out"
+ (let [field ["field" {} ["Sample" "PUBLIC" "USERS" "NAME"]]
+ inner ["=" {} field "alice"]
+ input ["true" {} ["true" {} ["true" {} inner]]]]
+ (is (= inner (repair/repair trivial-mp input)))))
+ (testing "[false {} [true {} x]] -> [not {} x]"
+ (let [field ["field" {} ["Sample" "PUBLIC" "USERS" "NAME"]]
+ inner ["=" {} field "alice"]
+ input ["false" {} ["true" {} inner]]]
+ (is (= ["not" {} inner] (repair/repair trivial-mp input))))))
+
+;;; ============================================================
+;;; Pass 1.86 - wrap bare ISO-date strings as absolute-datetime in between
+;;; ============================================================
+
+(deftest wrap-iso-date-bounds-both-bare-test
+ (testing "both bounds are bare yyyy-mm-dd strings: both get wrapped"
+ (let [field ["field" {} ["Sample" "PUBLIC" "ORDERS" "CREATED_AT"]]
+ input ["between" {} field "2024-01-01" "2024-12-31"]]
+ (is (= ["between" {}
+ field
+ ["absolute-datetime" {} "2024-01-01" "day"]
+ ["absolute-datetime" {} "2024-12-31" "day"]]
+ (repair/repair trivial-mp input))))))
+
+(deftest wrap-iso-date-bounds-mixed-test
+ (testing "one bound already absolute-datetime, the other a bare string: bare side
+ gets wrapped"
+ (let [field ["field" {} ["Sample" "PUBLIC" "ORDERS" "CREATED_AT"]]
+ wrapped ["absolute-datetime" {} "2024-01-01" "day"]
+ input ["between" {} field wrapped "2024-12-31"]]
+ (is (= ["between" {}
+ field
+ wrapped
+ ["absolute-datetime" {} "2024-12-31" "day"]]
+ (repair/repair trivial-mp input)))))
+ (testing "one bound a relative-datetime, the other a bare ISO string: bare side gets
+ wrapped (presence of temporal sibling triggers the rule)"
+ (let [field ["field" {} ["Sample" "PUBLIC" "ORDERS" "CREATED_AT"]]
+ rel ["relative-datetime" {} -7 "day"]
+ input ["between" {} field rel "2024-12-31"]]
+ (is (= ["between" {} field rel
+ ["absolute-datetime" {} "2024-12-31" "day"]]
+ (repair/repair trivial-mp input))))))
+
+(deftest wrap-iso-date-bounds-numeric-untouched-test
+ (testing "both bounds numeric: not wrapped (between also works for numbers)"
+ (let [field ["field" {} ["Sample" "PUBLIC" "ORDERS" "TOTAL"]]
+ input ["between" {} field 10 100]]
+ (is (= input (repair/repair trivial-mp input))))))
+
+(deftest wrap-iso-date-bounds-with-time-portion-test
+ (testing "yyyy-mm-ddThh:mm:ss bounds also get wrapped"
+ (let [field ["field" {} ["Sample" "PUBLIC" "ORDERS" "CREATED_AT"]]
+ input ["between" {} field "2024-06-15T09:00:00" "2024-06-15T18:00:00"]]
+ (is (= ["between" {}
+ field
+ ["absolute-datetime" {} "2024-06-15T09:00:00" "day"]
+ ["absolute-datetime" {} "2024-06-15T18:00:00" "day"]]
+ (repair/repair trivial-mp input))))))
+
+(deftest wrap-iso-date-bounds-idempotent-test
+ (testing "wrapping is idempotent: two wraps == one wrap"
+ (let [field ["field" {} ["Sample" "PUBLIC" "ORDERS" "CREATED_AT"]]
+ input ["between" {} field "2024-01-01" "2024-12-31"]
+ once (repair/repair trivial-mp input)
+ twice (repair/repair trivial-mp once)]
+ (is (= once twice)))))
+
+(deftest wrap-iso-date-bounds-then-swap-test
+ (testing "wrap + swap compose: out-of-order bare ISO strings wrap then swap"
+ (let [field ["field" {} ["Sample" "PUBLIC" "ORDERS" "CREATED_AT"]]
+ input ["between" {} field "2024-12-31" "2024-01-01"]]
+ (is (= ["between" {}
+ field
+ ["absolute-datetime" {} "2024-01-01" "day"]
+ ["absolute-datetime" {} "2024-12-31" "day"]]
+ (repair/repair trivial-mp input))))))
+
+(deftest wrap-iso-date-bounds-non-iso-untouched-test
+ (testing "random strings (not yyyy-mm-dd shaped) are left alone"
+ (let [field ["field" {} ["Sample" "PUBLIC" "X"]]
+ input ["between" {} field "hello" "world"]]
+ (is (= input (repair/repair trivial-mp input))))))
+
+;;; ============================================================
+;;; Pass 1.865 - wrap bare "now" literals in temporal-comparison contexts
+;;; ============================================================
+
+(deftest wrap-now-literals-comparison-test
+ (testing "`<` between a temporal-bucketed field and bare 'now': now gets wrapped"
+ (let [field-with-unit ["field" {"temporal-unit" "day"}
+ ["Sample" "PUBLIC" "ORDERS" "CREATED_AT"]]
+ input ["<" {} field-with-unit "now"]]
+ (is (= ["<" {} field-with-unit ["now" {}]]
+ (repair/repair trivial-mp input)))))
+ (testing "`>=` between an absolute-datetime and bare 'now': now gets wrapped"
+ (let [abs ["absolute-datetime" {} "2024-01-01" "day"]
+ input [">=" {} abs "now"]]
+ (is (= [">=" {} abs ["now" {}]]
+ (repair/repair trivial-mp input)))))
+ (testing "case-insensitive 'NOW' / mixed case / whitespace get wrapped"
+ (let [abs ["absolute-datetime" {} "2024-01-01" "day"]]
+ (doseq [variant ["NOW" "Now" " now " "now\n"]]
+ (is (= ["=" {} abs ["now" {}]]
+ (repair/repair trivial-mp ["=" {} abs variant]))
+ variant))))
+ (testing "bare 'now' in a non-temporal context (no other temporal operand) is left alone"
+ (let [field ["field" {} ["Sample" "PUBLIC" "USERS" "NAME"]]
+ input ["=" {} field "now"]]
+ (is (= input (repair/repair trivial-mp input)))))
+ (testing "already-canonical [now {}] is left alone (idempotency)"
+ (let [abs ["absolute-datetime" {} "2024-01-01" "day"]
+ input ["<" {} abs ["now" {}]]]
+ (is (= input (repair/repair trivial-mp input))))))
+
+(deftest wrap-now-literals-between-test
+ (testing "between(<temporal-field>, ISO-string, 'now') wraps both bounds"
+ (let [field-with-unit ["field" {"temporal-unit" "day"}
+ ["Sample" "PUBLIC" "ORDERS" "CREATED_AT"]]
+ input ["between" {} field-with-unit "2024-01-01" "now"]]
+ ;; ISO date wrapped (Pass 1.86), bare 'now' wrapped (Pass 1.865).
+ (is (= ["between" {}
+ field-with-unit
+ ["absolute-datetime" {} "2024-01-01" "day"]
+ ["now" {}]]
+ (repair/repair trivial-mp input)))))
+ (testing "between(<numeric-field>, 'now', 'now'): no temporal sibling, leave alone"
+ ;; The expression's column is non-temporal and bare 'now' is the only thing in sight;
+ ;; we don't have evidence this is a temporal context.
+ (let [field ["field" {} ["Sample" "PUBLIC" "ORDERS" "TOTAL"]]
+ input ["between" {} field "now" "now"]]
+ (is (= input (repair/repair trivial-mp input))))))
+
+;;; ============================================================
+;;; Pass 1.87 - swap out-of-order between bounds (literal scalars only)
+;;; ============================================================
+
+(deftest swap-between-bounds-numeric-test
+ (testing "numeric lower > upper is swapped"
+ (let [field ["field" {} ["Sample" "PUBLIC" "ORDERS" "TOTAL"]]
+ input ["between" {} field 100 10]]
+ (is (= ["between" {} field 10 100]
+ (repair/repair trivial-mp input)))))
+ (testing "numeric lower < upper is left alone"
+ (let [field ["field" {} ["Sample" "PUBLIC" "ORDERS" "TOTAL"]]
+ input ["between" {} field 10 100]]
+ (is (= input (repair/repair trivial-mp input)))))
+ (testing "numeric lower == upper is left alone"
+ (let [field ["field" {} ["Sample" "PUBLIC" "ORDERS" "TOTAL"]]
+ input ["between" {} field 42 42]]
+ (is (= input (repair/repair trivial-mp input)))))
+ (testing "swap is idempotent"
+ (let [field ["field" {} ["Sample" "PUBLIC" "ORDERS" "TOTAL"]]
+ input ["between" {} field 100 10]
+ once (repair/repair trivial-mp input)
+ twice (repair/repair trivial-mp once)]
+ (is (= once twice)))))
+
+(deftest swap-between-bounds-iso-string-test
+ ;; Note: bare ISO strings are wrapped by Pass 1.86 ("wrap-iso-date-bounds*") *before*
+ ;; this swap pass runs, so the canonical post-repair form has \"[absolute-datetime ...]\"
+ ;; bounds. The swap still proceeds because \"swap-between-bounds*\" knows how to extract
+ ;; the inner ISO string for comparison.
+ (testing "ISO-8601 date strings ordered chronologically: wrapped + swapped"
+ (let [field ["field" {} ["Sample" "PUBLIC" "ORDERS" "CREATED_AT"]]
+ input ["between" {} field "2024-12-31" "2024-01-01"]]
+ (is (= ["between" {}
+ field
+ ["absolute-datetime" {} "2024-01-01" "day"]
+ ["absolute-datetime" {} "2024-12-31" "day"]]
+ (repair/repair trivial-mp input)))))
+ (testing "ISO-8601 datetime strings: wrapped + swapped"
+ (let [field ["field" {} ["Sample" "PUBLIC" "ORDERS" "CREATED_AT"]]
+ input ["between" {} field "2024-06-15T18:00:00" "2024-06-15T09:00:00"]]
+ (is (= ["between" {}
+ field
+ ["absolute-datetime" {} "2024-06-15T09:00:00" "day"]
+ ["absolute-datetime" {} "2024-06-15T18:00:00" "day"]]
+ (repair/repair trivial-mp input)))))
+ (testing "in-order ISO strings: wrapped, no swap"
+ (let [field ["field" {} ["Sample" "PUBLIC" "ORDERS" "CREATED_AT"]]
+ input ["between" {} field "2024-01-01" "2024-12-31"]]
+ (is (= ["between" {}
+ field
+ ["absolute-datetime" {} "2024-01-01" "day"]
+ ["absolute-datetime" {} "2024-12-31" "day"]]
+ (repair/repair trivial-mp input))))))
+
+(deftest swap-between-bounds-absolute-datetime-test
+ (testing "out-of-order absolute-datetime clauses: swap by inner ISO string"
+ (let [field ["field" {} ["Sample" "PUBLIC" "ORDERS" "CREATED_AT"]]
+ hi ["absolute-datetime" {} "2024-12-31" "day"]
+ lo ["absolute-datetime" {} "2024-01-01" "day"]
+ input ["between" {} field hi lo]]
+ (is (= ["between" {} field lo hi]
+ (repair/repair trivial-mp input)))))
+ (testing "in-order absolute-datetime clauses are left alone"
+ (let [field ["field" {} ["Sample" "PUBLIC" "ORDERS" "CREATED_AT"]]
+ lo ["absolute-datetime" {} "2024-01-01" "day"]
+ hi ["absolute-datetime" {} "2024-12-31" "day"]
+ input ["between" {} field lo hi]]
+ (is (= input (repair/repair trivial-mp input))))))
+
+(deftest swap-between-bounds-non-literal-untouched-test
+ (testing "non-literal bound (a relative-datetime clause) is left alone - we can't
+ compare without execution"
+ (let [field ["field" {} ["Sample" "PUBLIC" "ORDERS" "CREATED_AT"]]
+ rel ["relative-datetime" {} -7 "day"]
+ abs ["absolute-datetime" {} "2024-01-01" "day"]
+ input ["between" {} field rel abs]]
+ (is (= input (repair/repair trivial-mp input)))))
+ (testing "a `field` ref bound is left alone"
+ (let [field ["field" {} ["Sample" "PUBLIC" "ORDERS" "CREATED_AT"]]
+ other ["field" {} ["Sample" "PUBLIC" "ORDERS" "OTHER"]]
+ input ["between" {} field other 100]]
+ (is (= input (repair/repair trivial-mp input))))))
+
+(deftest swap-between-bounds-mixed-types-untouched-test
+ (testing "mixed-kind bounds (number vs string) are left alone"
+ (let [field ["field" {} ["Sample" "PUBLIC" "ORDERS" "X"]]
+ input ["between" {} field 10 "hello"]]
+ (is (= input (repair/repair trivial-mp input))))))
+
+;;; ============================================================
+;;; Pass 1.55 - normalise `fields:` to sequential-of-clause when given a single clause
+;;; ============================================================
+
+(deftest normalise-fields-on-stage-test
+ (testing "single clause as `fields:` value gets wrapped in a one-element list"
+ (let [field ["field" {} ["Sample" "PUBLIC" "ORDERS" "ID"]]
+ input {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "fields" field}]}
+ output (repair/repair trivial-mp input)]
+ (is (= [field] (get-in output ["stages" 0 "fields"])))))
+ (testing "sequential `fields:` is left alone"
+ (let [field ["field" {} ["Sample" "PUBLIC" "ORDERS" "ID"]]
+ input {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "fields" [field]}]}
+ output (repair/repair trivial-mp input)]
+ (is (= [field] (get-in output ["stages" 0 "fields"]))))))
+
+(deftest normalise-fields-on-join-test
+ (testing "single clause as join `fields:` gets wrapped"
+ (let [field ["field" {} ["Sample" "PUBLIC" "PRODUCTS" "NAME"]]
+ stage {"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "PRODUCTS"]}
+ join {"lib/type" "mbql/join"
+ "alias" "P"
+ "stages" [stage]
+ "conditions" [["=" {}
+ ["field" {} ["Sample" "PUBLIC" "ORDERS" "PRODUCT_ID"]]
+ ["field" {} ["Sample" "PUBLIC" "PRODUCTS" "ID"]]]]
+ "fields" field}
+ input {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "joins" [join]}]}
+ output (repair/repair trivial-mp input)]
+ (is (= [field] (get-in output ["stages" 0 "joins" 0 "fields"])))))
+ (testing "join `fields:` enum value (\"all\" / \"none\") is left alone"
+ (doseq [enum-value ["all" "none"]]
+ (let [stage {"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "PRODUCTS"]}
+ join {"lib/type" "mbql/join"
+ "alias" "P"
+ "stages" [stage]
+ "conditions" [["=" {}
+ ["field" {} ["Sample" "PUBLIC" "ORDERS" "PRODUCT_ID"]]
+ ["field" {} ["Sample" "PUBLIC" "PRODUCTS" "ID"]]]]
+ "fields" enum-value}
+ input {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "joins" [join]}]}
+ output (repair/repair trivial-mp input)]
+ (is (= enum-value (get-in output ["stages" 0 "joins" 0 "fields"]))
+ enum-value)))))
+
+(deftest normalise-fields-idempotent-test
+ (testing "after wrap, second pass is a no-op"
+ (let [field ["field" {} ["Sample" "PUBLIC" "ORDERS" "ID"]]
+ input {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "fields" field}]}
+ once (repair/repair trivial-mp input)
+ twice (repair/repair trivial-mp once)]
+ (is (= once twice)))))
+
+;;; ============================================================
+;;; Pass 2 - fill in missing `lib/type`
+;;; ============================================================
+
+(deftest add-query-lib-type-test
+ (testing "top-level query without lib/type gets mbql/query"
+ (let [input {"database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]}]}
+ output (repair/repair trivial-mp input)]
+ (is (= "mbql/query" (get output "lib/type")))))
+ (testing "existing lib/type preserved"
+ (let [input {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]}]}]
+ (is (= input (repair/repair trivial-mp input))))))
+
+(deftest add-stage-lib-type-test
+ (testing "stage without lib/type gets mbql.stage/mbql"
+ (let [input {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "aggregation" [["count" {}]]}]}
+ output (repair/repair trivial-mp input)]
+ (is (= "mbql.stage/mbql" (get-in output ["stages" 0 "lib/type"])))))
+ (testing "a random non-stage map without stage-body keys is untouched"
+ (let [input {"foo" "bar"}]
+ (is (= input (repair/repair trivial-mp input))))))
+
+;;; ============================================================
+;;; Pass 1.9 - stamp top-level `database:` from the first stage's source
+;;;
+;;; Introduced in the `repr-plan.md` step-14 follow-up: the LLM-facing tool contract no
+;;; longer asks the model to author `database:`. Instead the construct pipeline derives the
+;;; database-id from `stages[0].source-table[0]` (or `source-card` entity_id), builds an MP,
+;;; and this repair pass stamps `database:` from the MP into the parsed YAML so the repr
+;;; spec / lib.schema are happy downstream.
+;;;
+;;; The previous `rewrite-database-name*` pass (deleted in step 13) served a related but
+;;; different role - reconciling a Sample / Sample-Database mismatch. Its concern is
+;;; structurally prevented now: if the user writes the wrong DB name in `source-table[0]`,
+;;; the DB lookup fails at `resolve-database-id-from-first-stage` with `:unknown-database`
+;;; before this repair pass even runs.
+;;; ============================================================
+
+(deftest stamp-top-level-database-from-source-table-test
+ (testing "Pass 1.9 stamps `database:` onto a query that doesn't have one, using the MP name."
+ (let [input {"lib/type" "mbql/query"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "aggregation" [["count" {}]]}]}
+ output (repair/repair mp-fks input)]
+ (is (= "Sample" (get output "database"))))))
+
+(deftest stamp-top-level-database-overwrites-mismatch-test
+ (testing "Pass 1.9 silently overwrites a stale / wrong `database:` with the MP's canonical name."
+ (let [input {"lib/type" "mbql/query"
+ "database" "DatabaseFormerlyKnownAsSample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "aggregation" [["count" {}]]}]}
+ output (repair/repair mp-fks input)]
+ (is (= "Sample" (get output "database"))))))
+
+(deftest stamp-top-level-database-idempotent-test
+ (testing "Pass 1.9 is a fixed point: running it twice gives the same output."
+ (let [input {"lib/type" "mbql/query"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "aggregation" [["count" {}]]}]}
+ once (repair/repair mp-fks input)
+ twice (repair/repair mp-fks once)]
+ (is (= once twice)))))
+
+(deftest stamp-top-level-database-no-mp-fallback-test
+ (testing "With no MP we still use the raw `source-table[0]` string as a fallback (unit-test isolation path)."
+ (let [input {"lib/type" "mbql/query"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["WarehouseX" "PUBLIC" "ORDERS"]
+ "aggregation" [["count" {}]]}]}
+ output (repair/repair nil input)]
+ (is (= "WarehouseX" (get output "database"))))))
+
+;;; ============================================================
+;;; Pass 2.7 - rewrite inline aggregations in `order-by` to aggregation refs
+;;;
+;;; The LLM tends to write `order-by: [[desc, {}, [sum, {}, [field, {}, FK]]]]`, re-stating
+;;; the aggregation expression inline. The lib stack accepts this in MBQL 5 form but the
+;;; legacy round-trip (which happens whenever the chart is later re-loaded) rejects it.
+;;; Repair detects the pattern and rewrites it to a UUID-based aggregation reference,
+;;; stamping the matching aggregation's `lib/uuid` if needed.
+;;; ============================================================
+
+(defn- uuid-string? [x]
+ (and (string? x)
+ (try (java.util.UUID/fromString x) true (catch Exception _ false))))
+
+(defn- agg-uuid-of [stage idx]
+ (get-in stage ["aggregation" idx 1 "lib/uuid"]))
+
+(deftest rewrite-order-by-inline-agg-happy-path-test
+ (testing "inline aggregation in order-by gets rewritten to an aggregation ref"
+ (let [input {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "aggregation" [["sum" {}
+ ["field" {}
+ ["Sample" "PUBLIC" "ORDERS" "TOTAL"]]]]
+ "order-by" [["desc" {}
+ ["sum" {}
+ ["field" {}
+ ["Sample" "PUBLIC" "ORDERS" "TOTAL"]]]]]}]}
+ repaired (repair/repair trivial-mp input)
+ stage (get-in repaired ["stages" 0])
+ agg-uuid (agg-uuid-of stage 0)]
+ (testing "the matched aggregation got a lib/uuid stamped into its options"
+ (is (uuid-string? agg-uuid)))
+ (testing "order-by inner clause is now [\"aggregation\" {} <that-uuid>]"
+ (is (= ["aggregation" {} agg-uuid]
+ (get-in stage ["order-by" 0 2])))))))
+
+(deftest rewrite-order-by-multiple-aggregations-test
+ (testing "order-by entries match the right aggregation by structural equality"
+ (let [input {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "aggregation" [["sum" {}
+ ["field" {}
+ ["Sample" "PUBLIC" "ORDERS" "TOTAL"]]]
+ ["count" {}]]
+ "order-by" [["desc" {} ["count" {}]]
+ ["asc" {}
+ ["sum" {}
+ ["field" {}
+ ["Sample" "PUBLIC" "ORDERS" "TOTAL"]]]]]}]}
+ repaired (repair/repair trivial-mp input)
+ stage (get-in repaired ["stages" 0])
+ sum-uuid (agg-uuid-of stage 0)
+ cnt-uuid (agg-uuid-of stage 1)]
+ (is (uuid-string? sum-uuid))
+ (is (uuid-string? cnt-uuid))
+ (is (not= sum-uuid cnt-uuid) "each aggregation gets its own uuid")
+ (is (= ["aggregation" {} cnt-uuid] (get-in stage ["order-by" 0 2]))
+ "first order-by (count) refers to the count aggregation")
+ (is (= ["aggregation" {} sum-uuid] (get-in stage ["order-by" 1 2]))
+ "second order-by (sum TOTAL) refers to the sum aggregation"))))
+
+(deftest rewrite-order-by-reuses-existing-uuid-test
+ (testing "if the matching aggregation already has a lib/uuid, reuse it"
+ (let [existing-uuid "11111111-2222-3333-4444-555555555555"
+ input {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "aggregation" [["sum" {"lib/uuid" existing-uuid}
+ ["field" {}
+ ["Sample" "PUBLIC" "ORDERS" "TOTAL"]]]]
+ "order-by" [["desc" {}
+ ["sum" {}
+ ["field" {}
+ ["Sample" "PUBLIC" "ORDERS" "TOTAL"]]]]]}]}
+ repaired (repair/repair trivial-mp input)
+ stage (get-in repaired ["stages" 0])]
+ (is (= existing-uuid (agg-uuid-of stage 0))
+ "the pre-existing uuid is preserved")
+ (is (= ["aggregation" {} existing-uuid] (get-in stage ["order-by" 0 2]))))))
+
+(deftest rewrite-order-by-leaves-existing-aggregation-ref-alone-test
+ (testing "an order-by that already uses [\"aggregation\" {} <uuid>] is left alone"
+ (let [agg-uuid "aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee"
+ input {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "aggregation" [["sum" {"lib/uuid" agg-uuid}
+ ["field" {}
+ ["Sample" "PUBLIC" "ORDERS" "TOTAL"]]]]
+ "order-by" [["desc" {}
+ ["aggregation" {} agg-uuid]]]}]}]
+ (is (= input (repair/repair trivial-mp input))))))
+
+(deftest rewrite-order-by-leaves-non-aggregation-orderings-alone-test
+ (testing "order-by on a plain field is left alone"
+ (let [input {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "aggregation" [["count" {}]]
+ "order-by" [["asc" {}
+ ["field" {}
+ ["Sample" "PUBLIC" "ORDERS" "ID"]]]]}]}]
+ (is (= input (repair/repair trivial-mp input))))))
+
+(deftest rewrite-order-by-leaves-non-matching-aggregation-alone-test
+ (testing (str "if the inline order-by aggregation does NOT match any aggregation in the\n"
+ "stage, leave it alone (let validation/normalize surface the real error)")
+ (let [input {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "aggregation" [["count" {}]]
+ "order-by" [["desc" {}
+ ["sum" {}
+ ["field" {}
+ ["Sample" "PUBLIC" "ORDERS" "TOTAL"]]]]]}]}
+ repaired (repair/repair trivial-mp input)]
+ (is (= ["sum" {} ["field" {} ["Sample" "PUBLIC" "ORDERS" "TOTAL"]]]
+ (get-in repaired ["stages" 0 "order-by" 0 2]))))))
+
+(deftest rewrite-order-by-idempotent-test
+ (testing "running repair twice produces the same result (UUID is stable across runs)"
+ (let [input {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "aggregation" [["sum" {}
+ ["field" {}
+ ["Sample" "PUBLIC" "ORDERS" "TOTAL"]]]]
+ "order-by" [["desc" {}
+ ["sum" {}
+ ["field" {}
+ ["Sample" "PUBLIC" "ORDERS" "TOTAL"]]]]]}]}
+ once (repair/repair trivial-mp input)
+ twice (repair/repair trivial-mp once)]
+ (is (= once twice)))))
+
+;;; ============================================================
+;;; End-to-end repair against an LLM shortcut shape
+;;; ============================================================
+
+(deftest end-to-end-shortcut-repair-test
+ (testing "LLM-style shortcut missing both lib/types and options maps still validates after repair"
+ ;; The `:lib.schema/external-query` validation at the API boundary rejects this shape, but
+ ;; the repair pipeline itself is still expected to handle it for callers that bypass
+ ;; boundary validation (tests, programmatic invocations).
+ (let [parsed {"database" "Sample"
+ "stages" [{"source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "aggregation" [["count"]]}]}
+ repaired (repair/repair trivial-mp parsed)]
+ (is (= "mbql/query" (get repaired "lib/type")))
+ (is (= "mbql.stage/mbql" (get-in repaired ["stages" 0 "lib/type"])))
+ (is (= [["count" {}]] (get-in repaired ["stages" 0 "aggregation"])))
+ ;; repaired form should now pass the schema validator
+ (is (= repaired (repr/validate-query repaired))))))
+
+;;; ============================================================
+;;; Idempotency - unit + property based
+;;; ============================================================
+
+(deftest idempotency-happy-path-test
+ (testing "a fully-valid query is a fixed point"
+ (let [q {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "aggregation" [["count" {}]]
+ "breakout" [["field" {"temporal-unit" "month"}
+ ["Sample" "PUBLIC" "ORDERS" "CREATED_AT"]]]}]}]
+ (is (= q (repair/repair trivial-mp q)))
+ (is (= (repair/repair trivial-mp q) (repair/repair trivial-mp (repair/repair trivial-mp q)))))))
+
+(deftest idempotency-degenerate-test
+ (testing "repair(repair(x)) == repair(x) for a broken LLM input"
+ (let [broken {"database" "Sample"
+ "stages" [{"source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "aggregation" [["count"]]
+ "breakout" [["field" ["Sample" "PUBLIC" "ORDERS" "CREATED_AT"]]]}]}
+ once (repair/repair trivial-mp broken)
+ twice (repair/repair trivial-mp once)]
+ (is (= once twice)))))
+
+;;; Property-based fuzz: randomly-shaped inputs go through repair twice and must equal on pass 2.
+
+(def ^:private gen-scalar
+ (gen/one-of [gen/string gen/small-integer gen/boolean (gen/return nil)]))
+
+;;; Op-name generator covers every head with a repair pass attached, so adversarial
+;;; combinations (e.g. `eq` mixed with `between`, `if` with stray `else` branches, etc.)
+;;; have a chance to be sampled.
+(def ^:private gen-op-name
+ (gen/elements
+ [;; structural
+ "field" "expression" "aggregation" "and" "or" "not"
+ ;; comparison + aliases (1.1)
+ "=" "!=" "<" ">" "<=" ">=" "eq" "ne" "lt" "gt" "le" "ge" "lte" "gte"
+ "equals" "not-equals"
+ ;; list-membership (1.10)
+ "in" "not-in"
+ ;; boolean wrappers (1.4)
+ "true" "false"
+ ;; null checks + alias (1.1)
+ "is-null" "not-null" "is-not-null"
+ ;; temporal range / literals (1.5/1.6/1.7)
+ "between" "now" "relative-datetime" "absolute-datetime" "relative-date"
+ ;; temporal-bucket extraction + aliases (1.2)
+ "get-day-of-week" "get-hour" "get-month" "get-quarter"
+ "dayofweek" "day-of-week" "hour-of-day" "month-of-year" "quarter-of-year"
+ ;; direction (1.3)
+ "asc" "desc" "ascending" "descending" "ASC" "DESC"
+ ;; conditional (1.8) — `case`/`if`/`else` deliberately omitted from the chaos
+ ;; generator because Pass 1.84 wraps pairs as `[[pred then]]`, and Pass 1 then
+ ;; mis-classifies a bare 2-element string-pair `[s1 s2]` as a clause and inserts `{}`
+ ;; between them. In real LLM output `pred` is always a clause (e.g. `[\"=\" {} field
+ ;; val]`), so this collision doesn't fire; the realistic-query generator below
+ ;; exercises canonical case shapes with proper clause preds.
+ ;; aggregations + lib renames (1.1)
+ "count" "sum" "avg" "min" "max" "distinct" "stddev" "var"
+ "count-where" "count-if" "variance" "stddev-pop" "count-distinct" "distinct-count"
+ "datetime-diff" "temporal-diff"
+ ;; metric (resists auto-split column-name extraction; § 1.11 diagnostic path)
+ "metric"]))
+
+(def ^:private gen-fk-segment (gen/elements ["DB" "PUBLIC" "ORDERS" "PRODUCTS" "ID" "TOTAL" nil]))
+
+(def ^:private gen-fk-vector
+ (gen/fmap vec (gen/vector gen-fk-segment 3 6)))
+
+(defn- gen-clause [depth]
+ (if (zero? depth)
+ (gen/tuple gen-op-name
+ (gen/one-of [(gen/return {}) (gen/return nil) (gen/return :absent)]))
+ (gen/bind (gen/tuple gen-op-name
+ (gen/one-of [(gen/return {}) (gen/return nil) (gen/return :absent)])
+ (gen/vector (gen/one-of [gen-scalar gen-fk-vector]) 0 3))
+ (fn [[op opts args]]
+ (gen/return
+ (cond-> [op]
+ (not= opts :absent) (conj opts)
+ :always (into args)))))))
+
+(defn- gen-map-of [k-gen v-gen]
+ (gen/fmap (fn [pairs] (into {} pairs))
+ (gen/vector (gen/tuple k-gen v-gen) 0 4)))
+
+(def ^:private gen-tree
+ (gen/recursive-gen
+ (fn [inner] (gen/one-of [(gen-clause 1)
+ (gen/vector inner 0 4)
+ (gen-map-of gen/string-alphanumeric inner)]))
+ (gen/one-of [gen-scalar (gen-clause 0) gen-fk-vector])))
+
+(defspec idempotency-property-test 200
+ (prop/for-all [tree gen-tree]
+ (= (repair/repair trivial-mp tree)
+ (repair/repair trivial-mp (repair/repair trivial-mp tree)))))
+
+;;; ----------------------------------------------------------------
+;;; Realistic-shape fuzz: generate query-shaped maps (top-level `stages` vector with
+;;; aggregation / breakout / filter / order-by / joins / multi-stage) so we stress the
+;;; structural passes (Pass 2 lib-types, Pass 2.7 inline-aggs, Pass 2.8 int-ref resolution,
+;;; Pass 2.9 post-agg split, Pass 5 cross-stage type inference, etc.) on inputs that look
+;;; like what an LLM might emit, not pure tree chaos.
+;;; ----------------------------------------------------------------
+
+(def ^:private gen-fk-target
+ (gen/elements [["Sample" "PUBLIC" "ORDERS" "ID"]
+ ["Sample" "PUBLIC" "ORDERS" "PRODUCT_ID"]
+ ["Sample" "PUBLIC" "ORDERS" "TOTAL"]
+ ["Sample" "PUBLIC" "ORDERS" "CREATED_AT"]
+ ["Sample" "PUBLIC" "ORDERS" "STATUS"]
+ ["Sample" "PUBLIC" "PRODUCTS" "CATEGORY"]]))
+
+(def ^:private gen-source-table
+ (gen/elements [["Sample" "PUBLIC" "ORDERS"]
+ ["Sample" "PUBLIC" "PRODUCTS"]]))
+
+(def ^:private gen-field-clause
+ (gen/fmap (fn [target] ["field" {} target]) gen-fk-target))
+
+(def ^:private gen-field-clause-with-temporal
+ (gen/fmap (fn [[target unit]] ["field" {"temporal-unit" unit} target])
+ (gen/tuple gen-fk-target
+ (gen/elements ["day" "week" "month" "quarter" "year"]))))
+
+(def ^:private gen-aggregation-clause
+ ;; Mix simple and arg-taking aggs. Some LLM-flavoured aliases (count-distinct, count-if,
+ ;; variance) ride along to exercise Pass 1.81's rewrite.
+ (gen/one-of
+ [(gen/return ["count" {}])
+ (gen/return ["cum-count" {}])
+ (gen/fmap (fn [f] ["sum" {} f]) gen-field-clause)
+ (gen/fmap (fn [f] ["avg" {} f]) gen-field-clause)
+ (gen/fmap (fn [f] ["max" {} f]) gen-field-clause)
+ (gen/fmap (fn [f] ["distinct" {} f]) gen-field-clause)
+ (gen/fmap (fn [f] ["count-distinct" {} f]) gen-field-clause)
+ (gen/fmap (fn [f] ["variance" {} f]) gen-field-clause)]))
+
+(def ^:private gen-filter-clause
+ ;; A filter that touches one of the heads with a repair pass attached.
+ (gen/one-of
+ [(gen/fmap (fn [[f v]] ["=" {} f v]) (gen/tuple gen-field-clause gen-scalar))
+ (gen/fmap (fn [[f v]] ["!=" {} f v]) (gen/tuple gen-field-clause gen-scalar))
+ (gen/fmap (fn [[f v]] ["eq" {} f v]) (gen/tuple gen-field-clause gen-scalar))
+ (gen/fmap (fn [[f v]] ["gt" {} f v]) (gen/tuple gen-field-clause gen/small-integer))
+ (gen/fmap (fn [[f v]] [">=" {} f v]) (gen/tuple gen-field-clause gen/small-integer))
+ (gen/fmap (fn [[f vs]] (into ["in" {} f] vs))
+ (gen/tuple gen-field-clause (gen/vector gen/string-alphanumeric 1 4)))
+ ;; deliberately wrap values in a vector to trigger Pass 1.82
+ (gen/fmap (fn [[f vs]] ["in" {} f vs])
+ (gen/tuple gen-field-clause (gen/vector gen/string-alphanumeric 1 4)))
+ ;; between with maybe-out-of-order ISO date strings (Pass 1.86 + 1.87)
+ (gen/fmap (fn [[f a b]] ["between" {} f a b])
+ (gen/tuple gen-field-clause-with-temporal
+ (gen/elements ["2024-01-01" "2024-06-30" "2024-12-31"])
+ (gen/elements ["2023-01-01" "2024-12-31" "now"])))
+ ;; post-aggregation filter that triggers Pass 2.9 split
+ (gen/fmap (fn [n] [">" {} ["aggregation" {} 0] n])
+ gen/small-integer)]))
+
+(def ^:private gen-direction-head
+ (gen/elements ["asc" "desc" "ascending" "descending" "ASC" "DESC"]))
+
+(def ^:private gen-order-by-clause
+ (gen/fmap (fn [[dir f]] [dir {} f])
+ (gen/tuple gen-direction-head gen-field-clause)))
+
+(def ^:private gen-case-clause
+ ;; Build canonical and not-yet-canonical case shapes. preds are always clause-shaped
+ ;; (an `=` filter), thens are scalars - this matches real LLM output. Exercises Pass 1.84
+ ;; (`normalise-case-clauses*`) on the alternative argument shapes it's designed to
+ ;; recognise.
+ (gen/let [pred-clause gen-filter-clause
+ then-val gen-scalar
+ shape (gen/elements [:canonical :three-bare :pairs-as-args])]
+ (case shape
+ :canonical ["case" {} [[pred-clause then-val]] then-val]
+ :three-bare ["case" {} pred-clause then-val then-val]
+ :pairs-as-args ["case" {} [pred-clause then-val] [pred-clause then-val] then-val])))
+
+(def ^:private gen-expression-clause
+ (gen/one-of
+ [gen-case-clause
+ (gen/fmap (fn [[a b]] ["+" {} a b])
+ (gen/tuple gen-field-clause gen/small-integer))
+ (gen/fmap (fn [[a b]] ["datetime-diff" {} a b "day"])
+ (gen/tuple gen-field-clause gen-field-clause))]))
+
+(def ^:private gen-stage
+ (gen/let [src gen-source-table
+ aggs (gen/vector gen-aggregation-clause 0 2)
+ breakouts (gen/vector gen-field-clause 0 2)
+ filters (gen/vector gen-filter-clause 0 3)
+ order-bys (gen/vector gen-order-by-clause 0 2)
+ exprs (gen/vector gen-expression-clause 0 2)
+ limit (gen/one-of [(gen/return nil) (gen/elements [5 10 50])])]
+ (cond-> {"lib/type" "mbql.stage/mbql"
+ "source-table" src}
+ (seq aggs) (assoc "aggregation" (vec aggs))
+ (seq breakouts) (assoc "breakout" (vec breakouts))
+ (seq filters) (assoc "filters" (vec filters))
+ (seq order-bys) (assoc "order-by" (vec order-bys))
+ (seq exprs) (assoc "expressions" (vec exprs))
+ (some? limit) (assoc "limit" limit))))
+
+(def ^:private gen-realistic-query
+ (gen/let [stage gen-stage]
+ {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [stage]}))
+
+(defn- repair-or-agent-error
+ "Returns `[:ok result]` on success, `[:agent-error data]` on agent-flagged ex-info,
+ or `[:bug ex]` on anything else (test should fail). Keeps the exception escape-channel
+ narrow: only `:agent-error? true` ex-info is acceptable."
+ [tree]
+ (try
+ [:ok (repair/repair trivial-mp tree)]
+ (catch clojure.lang.ExceptionInfo e
+ (if (true? (:agent-error? (ex-data e)))
+ [:agent-error (ex-data e)]
+ [:bug e]))
+ (catch Throwable e
+ [:bug e])))
+
+(defspec realistic-query-idempotency-property-test 200
+ (prop/for-all [q gen-realistic-query]
+ (let [[outcome r1] (repair-or-agent-error q)]
+ (case outcome
+ :ok (let [[outcome2 r2] (repair-or-agent-error r1)]
+ (and (= :ok outcome2) (= r1 r2)))
+ :agent-error true ; clean diagnostic - acceptable
+ :bug false))))
+
+(defspec realistic-query-no-bug-exceptions-test 200
+ (prop/for-all [q gen-realistic-query]
+ (let [[outcome _] (repair-or-agent-error q)]
+ (not= outcome :bug))))
+
+;;; ============================================================
+;;; Pass 3 - implicit-join `source-field` auto-wiring
+;;; ============================================================
+
+(def ^:private base-query
+ "LLM-style query with a cross-table breakout on PRODUCTS.CATEGORY from source-table ORDERS."
+ {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "aggregation" [["count" {}]]
+ "breakout" [["field" {}
+ ["Sample" "PUBLIC" "PRODUCTS" "CATEGORY"]]]}]})
+
+(deftest implicit-join-happy-path-test
+ (testing "cross-table field gets `source-field` auto-filled to the unique FK path"
+ (let [out (repair/repair mp-fks base-query)
+ field-opts (get-in out ["stages" 0 "breakout" 0 1])]
+ (is (= ["Sample" "PUBLIC" "ORDERS" "PRODUCT_ID"]
+ (get field-opts "source-field"))))))
+
+(deftest implicit-join-preserves-existing-source-field-test
+ (testing "if the clause already has source-field, leave it alone"
+ (let [q (assoc-in base-query
+ ["stages" 0 "breakout" 0 1]
+ {"source-field" ["Sample" "PUBLIC" "ORDERS" "PRODUCT_ID"]})
+ out (repair/repair mp-fks q)]
+ (is (= {"source-field" ["Sample" "PUBLIC" "ORDERS" "PRODUCT_ID"]}
+ (get-in out ["stages" 0 "breakout" 0 1]))))))
+
+(deftest implicit-join-skips-join-alias-test
+ (testing "field with join-alias is treated as an explicit-join reference and untouched"
+ (let [q (assoc-in base-query
+ ["stages" 0 "breakout" 0 1]
+ {"join-alias" "Products"})
+ out (repair/repair mp-fks q)]
+ (is (= {"join-alias" "Products"}
+ (get-in out ["stages" 0 "breakout" 0 1]))))))
+
+(deftest implicit-join-skips-source-field-name-test
+ (testing (str "a field clause carrying `source-field-name` (multi-stage implicit-join via a "
+ "previous-stage column name) is left alone - we don't auto-fill `source-field`, "
+ "even though the target table is otherwise reachable via a unique FK")
+ (let [opts {"source-field-name" "PRODUCT_ID"}
+ q (assoc-in base-query ["stages" 0 "breakout" 0 1] opts)
+ out (repair/repair mp-fks q)
+ out-opts (get-in out ["stages" 0 "breakout" 0 1])]
+ (is (= opts out-opts))
+ (is (not (contains? out-opts "source-field"))))))
+
+(deftest implicit-join-skips-source-field-join-alias-test
+ (testing (str "a field clause carrying `source-field-join-alias` (implicit-join where the FK "
+ "column lives on an explicitly-joined table) is left alone")
+ (let [opts {"source-field-join-alias" "Orders_A"}
+ q (assoc-in base-query ["stages" 0 "breakout" 0 1] opts)
+ out (repair/repair mp-fks q)
+ out-opts (get-in out ["stages" 0 "breakout" 0 1])]
+ (is (= opts out-opts))
+ (is (not (contains? out-opts "source-field"))))))
+
+(deftest implicit-join-skips-field-on-source-table-test
+ (testing "field that already lives on source-table doesn't get source-field added"
+ (let [q (assoc-in base-query
+ ["stages" 0 "breakout"]
+ [["field" {} ["Sample" "PUBLIC" "ORDERS" "ID"]]])
+ out (repair/repair mp-fks q)]
+ (is (= {} (get-in out ["stages" 0 "breakout" 0 1]))))))
+
+(deftest implicit-join-no-fk-path-test
+ (testing "throws :no-fk-path when the target table isn't reachable via any FK"
+ (try
+ (repair/repair mp-no-fk base-query)
+ (is false "expected throw")
+ (catch clojure.lang.ExceptionInfo e
+ (let [d (ex-data e)]
+ (is (= :no-fk-path (:error d)))
+ (is (true? (:agent-error? d)))
+ (is (re-find #"no foreign key" (ex-message e))))))))
+
+(deftest implicit-join-ambiguous-fk-test
+ (testing (str "throws :ambiguous-fk when multiple FKs exist, and does NOT enumerate the "
+ "candidate FK column names (parity with the S1 info-leak strip: the "
+ "un-sandboxed metadata provider could otherwise surface bridge-table "
+ "column names the caller cannot see)")
+ (try
+ (repair/repair mp-ambiguous base-query)
+ (is false "expected throw")
+ (catch clojure.lang.ExceptionInfo e
+ (let [d (ex-data e)
+ msg (ex-message e)]
+ (is (= :ambiguous-fk (:error d)))
+ (is (true? (:agent-error? d)))
+ (testing "ex-data carries no candidate FK column paths"
+ (is (nil? (:candidates d))))
+ (testing "message must not name the FK columns (PRODUCT_ID / ALT_PRODUCT_ID)"
+ (is (not (re-find #"PRODUCT_ID" msg)))
+ (is (not (re-find #"ALT_PRODUCT_ID" msg))))
+ (testing "message tells the LLM how to disambiguate via `source-field`"
+ (is (re-find #"source-field" msg))))))))
+
+(deftest implicit-join-skips-joins-subtree-test
+ (testing "field references inside explicit joins are not auto-wired with source-field"
+ (let [q {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "joins" [{"alias" "P"
+ "strategy" "left-join"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "PRODUCTS"]}]
+ "conditions"
+ [["=" {}
+ ["field" {} ["Sample" "PUBLIC" "ORDERS" "PRODUCT_ID"]]
+ ["field" {"join-alias" "P"}
+ ["Sample" "PUBLIC" "PRODUCTS" "ID"]]]]}]
+ "breakout" [["field" {"join-alias" "P"}
+ ["Sample" "PUBLIC" "PRODUCTS" "CATEGORY"]]]}]}
+ out (repair/repair mp-fks q)
+ join-field-opts (get-in out ["stages" 0 "joins" 0 "conditions" 0 3 1])
+ breakout-opts (get-in out ["stages" 0 "breakout" 0 1])]
+ (testing "field in join conditions (not on source-table) is NOT given source-field"
+ (is (not (contains? join-field-opts "source-field"))))
+ (testing "breakout field with join-alias is preserved as-is"
+ (is (= {"join-alias" "P"} breakout-opts))))))
+
+(deftest implicit-join-idempotent-test
+ (testing "implicit-join repair is idempotent"
+ (let [once (repair/repair mp-fks base-query)
+ twice (repair/repair mp-fks once)]
+ (is (= once twice)))))
+
+(deftest implicit-join-no-op-when-mp-cannot-resolve-source-table-test
+ (testing "when the MP can't resolve the source-table, the pass is a no-op (let later stages report)"
+ ;; trivial-mp has only a Database, no tables. Source-table resolution fails silently.
+ (let [out (repair/repair trivial-mp base-query)]
+ (is (= {} (get-in out ["stages" 0 "breakout" 0 1]))))))
+
+;;; ============================================================
+;;; Pass 3.5 - `source-field-join-alias` auto-wiring through an explicit join (step 12, partial)
+;;; ============================================================
+
+(def ^:private join-base-query
+ "LLM-style query: source-table=ORDERS, explicit join of PRODUCTS as `P`, breakout on
+ CATEGORIES.NAME (which is reachable from PRODUCTS via PRODUCTS.CATEGORY_ID, but NOT from
+ ORDERS)."
+ {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "joins" [{"alias" "P"
+ "strategy" "left-join"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "PRODUCTS"]}]
+ "conditions" [["=" {}
+ ["field" {} ["Sample" "PUBLIC" "ORDERS" "PRODUCT_ID"]]
+ ["field" {"join-alias" "P"}
+ ["Sample" "PUBLIC" "PRODUCTS" "ID"]]]]}]
+ "aggregation" [["count" {}]]
+ "breakout" [["field" {}
+ ["Sample" "PUBLIC" "CATEGORIES" "NAME"]]]}]})
+
+(deftest source-field-join-alias-happy-path-test
+ (testing (str "a field whose target is reachable through exactly one explicit join via a "
+ "single FK gets both `source-field-join-alias` and the matching portable "
+ "`source-field` filled in")
+ (let [out (repair/repair mp-via-join join-base-query)
+ field-opts (get-in out ["stages" 0 "breakout" 0 1])]
+ (is (= "P" (get field-opts "source-field-join-alias")))
+ (is (= ["Sample" "PUBLIC" "PRODUCTS" "CATEGORY_ID"]
+ (get field-opts "source-field"))))))
+
+(deftest source-field-join-alias-idempotent-test
+ (testing "running repair twice produces the same query (Pass 3.5 is idempotent)"
+ (let [once (repair/repair mp-via-join join-base-query)
+ twice (repair/repair mp-via-join once)]
+ (is (= once twice)))))
+
+(deftest source-field-join-alias-preserves-existing-disambiguators-test
+ (testing "if the clause already carries `source-field-join-alias`, leave it alone"
+ (let [q (assoc-in join-base-query ["stages" 0 "breakout" 0 1]
+ {"source-field-join-alias" "P"
+ "source-field" ["Sample" "PUBLIC" "PRODUCTS" "CATEGORY_ID"]})
+ out (repair/repair mp-via-join q)]
+ (is (= {"source-field-join-alias" "P"
+ "source-field" ["Sample" "PUBLIC" "PRODUCTS" "CATEGORY_ID"]}
+ (get-in out ["stages" 0 "breakout" 0 1])))))
+ (testing "if the clause has `source-field-name` (multi-stage variant), leave it alone"
+ (let [q (assoc-in join-base-query ["stages" 0 "breakout" 0 1]
+ {"source-field-name" "PRODUCT_ID"})
+ out (repair/repair mp-via-join q)]
+ (is (= {"source-field-name" "PRODUCT_ID"}
+ (get-in out ["stages" 0 "breakout" 0 1]))))))
+
+(deftest source-field-join-alias-defers-to-pass-4-when-source-table-can-reach-target-test
+ (testing (str "if the field's target is reachable directly from `source-table`, Pass 3.5 "
+ "backs off and lets the basic implicit-join pass (Pass 4) handle it - we get "
+ "a plain `source-field`, NOT `source-field-join-alias`")
+ ;; mp-fks: ORDERS → PRODUCTS directly. Reuse `base-query` (breakout on PRODUCTS.CATEGORY).
+ (let [q (assoc-in base-query ["stages" 0 "joins"]
+ [{"alias" "P"
+ "strategy" "left-join"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "PRODUCTS"]}]
+ "conditions" [["=" {}
+ ["field" {} ["Sample" "PUBLIC" "ORDERS" "PRODUCT_ID"]]
+ ["field" {"join-alias" "P"}
+ ["Sample" "PUBLIC" "PRODUCTS" "ID"]]]]}])
+ out (repair/repair mp-fks q)
+ opts (get-in out ["stages" 0 "breakout" 0 1])]
+ (is (= ["Sample" "PUBLIC" "ORDERS" "PRODUCT_ID"] (get opts "source-field")))
+ (is (not (contains? opts "source-field-join-alias"))))))
+
+(deftest source-field-join-alias-no-op-when-no-joins-test
+ (testing "when the stage has no `joins:`, Pass 3.5 doesn't touch anything; Pass 4 reports as usual"
+ ;; CATEGORIES isn't reachable from ORDERS - no joins available either - so Pass 4 raises
+ ;; :no-fk-path. We're asserting Pass 3.5 didn't get in the way.
+ (try
+ (repair/repair mp-via-join {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "aggregation" [["count" {}]]
+ "breakout" [["field" {}
+ ["Sample" "PUBLIC"
+ "CATEGORIES" "NAME"]]]}]})
+ (is false "expected throw from Pass 4")
+ (catch clojure.lang.ExceptionInfo e
+ (is (= :no-fk-path (:error (ex-data e))))))))
+
+(deftest source-field-join-alias-ambiguous-error-test
+ (testing "raises :ambiguous-fk-via-join when the target is reachable through multiple distinct join aliases"
+ (let [q (assoc-in join-base-query ["stages" 0 "joins"]
+ [{"alias" "P"
+ "strategy" "left-join"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "PRODUCTS"]}]
+ "conditions" [["=" {}
+ ["field" {} ["Sample" "PUBLIC" "ORDERS" "ID"]]
+ ["field" {"join-alias" "P"}
+ ["Sample" "PUBLIC" "PRODUCTS" "ID"]]]]}
+ {"alias" "PA"
+ "strategy" "left-join"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "PRODUCTS_ALT"]}]
+ "conditions" [["=" {}
+ ["field" {} ["Sample" "PUBLIC" "ORDERS" "ID"]]
+ ["field" {"join-alias" "PA"}
+ ["Sample" "PUBLIC" "PRODUCTS_ALT" "ID"]]]]}])]
+ (try
+ (repair/repair mp-via-two-joins q)
+ (is false "expected throw")
+ (catch clojure.lang.ExceptionInfo e
+ (let [d (ex-data e)
+ msg (ex-message e)]
+ (is (= :ambiguous-fk-via-join (:error d)))
+ (is (true? (:agent-error? d)))
+ (testing "alias names ARE surfaced (they came from the LLM's own joins:)"
+ (is (= #{"P" "PA"} (set (:aliases d))))
+ (is (re-find #"\"P\"" msg))
+ (is (re-find #"\"PA\"" msg)))
+ (testing "FK column portables are NOT surfaced (un-sandboxed MP info-leak guard)"
+ (is (nil? (:candidates d)))
+ (is (not (re-find #"PRODUCTS_ALT" msg))))
+ (testing "message tells the LLM how to disambiguate via `source-field-join-alias`"
+ (is (re-find #"source-field-join-alias" msg)))))))))
+
+(deftest source-field-join-alias-skips-joins-subtree-test
+ (testing (str "a field clause inside an explicit join's `conditions:` is NOT touched - those "
+ "clauses live in the join's own resolution context")
+ (let [out (repair/repair mp-via-join join-base-query)
+ ;; The condition LHS sits on ORDERS.PRODUCT_ID (no extra disambiguator needed); the
+ ;; condition RHS already has `join-alias`. Neither should pick up
+ ;; `source-field-join-alias`.
+ lhs (get-in out ["stages" 0 "joins" 0 "conditions" 0 2 1])
+ rhs (get-in out ["stages" 0 "joins" 0 "conditions" 0 3 1])]
+ (is (not (contains? lhs "source-field-join-alias")))
+ (is (not (contains? rhs "source-field-join-alias"))))))
+
+;;; ============================================================
+;;; Pass 4 -- cross-stage field-type inference (repr-plan step 8)
+;;;
+;;; When a later stage references a column from an earlier stage by name
+;;; (`["field" {} "<column-name>"]`), the `lib.schema/query` validator requires the options
+;;; map to carry `"base-type"` (and, by convention, `"effective-type"`). LLMs routinely
+;;; forget this. This pass resolves the earlier stages enough to learn each column's name
+;;; and base-type, then stamps the inferred types into the options map of every string-named
+;;; cross-stage field ref in later stages.
+;;; ============================================================
+
+(def ^:private multi-stage-base-query
+ "Two-stage query: aggregate orders by product id in stage 0, filter on count in stage 1.
+ The stage-1 filter references the aggregation output by name (`count`) - an LLM that
+ knows it has to filter an aggregate will typically write this shape and forget the
+ `base-type`."
+ {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "aggregation" [["count" {}]]
+ "breakout" [["field" {} ["Sample" "PUBLIC" "ORDERS" "ID"]]]}
+ {"lib/type" "mbql.stage/mbql"
+ "filters" [[">" {} ["field" {} "count"] 10]]}]})
+
+(deftest cross-stage-field-type-inference-happy-path-test
+ (testing "String-named cross-stage field ref gets `base-type` + `effective-type` inferred
+ from the previous stage's `lib/returned-columns`."
+ (let [out (repair/repair mp-fks multi-stage-base-query)
+ field-clause (get-in out ["stages" 1 "filters" 0 2])
+ opts (nth field-clause 1)]
+ (testing "base-type / effective-type are populated"
+ (is (= "type/Integer" (get opts "base-type")))
+ (is (= "type/Integer" (get opts "effective-type"))))
+ (testing "the string column name in position 2 is preserved"
+ (is (= "count" (nth field-clause 2)))))))
+
+(deftest cross-stage-field-type-preserves-existing-base-type-test
+ (testing "If the LLM actually wrote `base-type`, we don't overwrite it."
+ (let [q (assoc-in multi-stage-base-query
+ ["stages" 1 "filters" 0 2 1]
+ {"base-type" "type/Text" "effective-type" "type/Text"})
+ out (repair/repair mp-fks q)
+ opts (get-in out ["stages" 1 "filters" 0 2 1])]
+ (is (= "type/Text" (get opts "base-type")))
+ (is (= "type/Text" (get opts "effective-type"))))))
+
+(deftest cross-stage-field-type-breakout-column-test
+ (testing "A later stage can reference a BREAKOUT column from the previous stage by name;
+ repair infers its base-type from the source column's metadata."
+ (let [q {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "aggregation" [["count" {}]]
+ "breakout" [["field" {} ["Sample" "PUBLIC" "ORDERS" "ID"]]]}
+ {"lib/type" "mbql.stage/mbql"
+ "order-by" [["asc" {} ["field" {} "ID"]]]}]}
+ out (repair/repair mp-fks q)
+ opts (get-in out ["stages" 1 "order-by" 0 2 1])]
+ (is (= "type/Integer" (get opts "base-type"))))))
+
+(deftest cross-stage-field-type-leaves-vector-field-fks-alone-test
+ (testing "A field clause that uses a portable FK path (vector in position 2) is a normal
+ cross-table reference, not a cross-stage one - do not touch it."
+ (let [out (repair/repair mp-fks multi-stage-base-query)
+ stage-0-breakout-field (get-in out ["stages" 0 "breakout" 0])]
+ (testing "stage-0 breakout is untouched by the cross-stage pass"
+ ;; It may or may not have been touched by implicit-join; but the base-type should
+ ;; NOT have been stamped in by the cross-stage pass (different code path).
+ (is (vector? (nth stage-0-breakout-field 2)))))))
+
+(deftest cross-stage-field-type-no-previous-stage-test
+ (testing "String-named field in stage 0 has no previous stage to look at - we can't
+ infer, so we leave the clause alone (the schema validator will surface the error)."
+ (let [q {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "filters" [[">" {} ["field" {} "count"] 10]]}]}
+ out (repair/repair mp-fks q)
+ opts (get-in out ["stages" 0 "filters" 0 2 1])]
+ (is (not (contains? opts "base-type"))))))
+
+(deftest cross-stage-field-type-unknown-column-name-test
+ (testing "If the referenced name isn't produced by the previous stage, leave the clause
+ alone (the resolver will surface :unknown-column or similar with a better message)."
+ (let [q (assoc-in multi-stage-base-query
+ ["stages" 1 "filters" 0 2 2] "no_such_column")
+ out (repair/repair mp-fks q)
+ opts (get-in out ["stages" 1 "filters" 0 2 1])]
+ (is (not (contains? opts "base-type"))))))
+
+(deftest cross-stage-field-type-idempotent-test
+ (testing "cross-stage field-type inference is idempotent"
+ (let [once (repair/repair mp-fks multi-stage-base-query)
+ twice (repair/repair mp-fks once)]
+ (is (= once twice)))))
+
+(deftest cross-stage-field-type-end-to-end-resolve-test
+ (testing (str "End-to-end: a multi-stage YAML with a stage-1 cross-stage ref lacking\n"
+ "base-type is repaired and then `resolve-query` + `lib/query` accept the\n"
+ "result without a validation error.")
+ ;; This is the exact failure mode that motivated this pass: pre-repair, lib/query throws
+ ;; "Invalid output: {:stages [nil {:filters [[nil nil [nil {:base-type ...missing...}]]]}]}"
+ (let [repaired (repair/repair mp-fks multi-stage-base-query)
+ ;; We can't run the resolver on `mp-fks` (it's a lib mock, not an application-DB MP),
+ ;; but we CAN assert that the stage-1 cross-stage ref now carries a base-type -
+ ;; that's the structural repair the downstream needs. The actual end-to-end resolve
+ ;; is tested against a real application DB in construct_representations_test.
+ opts (get-in repaired ["stages" 1 "filters" 0 2 1])]
+ (is (= "type/Integer" (get opts "base-type"))))))
+
+;;; ============================================================
+;;; Pass 1.5 - expressions shape normalisation (repr-plan step 9)
+;;; ============================================================
+
+(deftest expressions-map-shape-normalised-to-sequential-test
+ (testing "map-form `expressions:` is converted to a vector of clauses with `lib/expression-name` stamped from the key"
+ (let [q {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "expressions" {"Subtotal" ["+" {}
+ ["field" {} ["Sample" "PUBLIC" "ORDERS" "TOTAL"]]
+ ["field" {} ["Sample" "PUBLIC" "ORDERS" "TAX"]]]}}]}
+ repaired (repair/repair trivial-mp q)
+ exprs (get-in repaired ["stages" 0 "expressions"])]
+ (is (vector? exprs))
+ (is (= 1 (count exprs)))
+ (let [clause (first exprs)
+ opts (nth clause 1)]
+ (is (= "+" (first clause)))
+ (is (= "Subtotal" (get opts "lib/expression-name")))))))
+
+(deftest expressions-sequential-shape-passes-through-test
+ (testing "sequential-form `expressions:` is left alone when each clause already carries `lib/expression-name`"
+ (let [q {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "expressions" [["+" {"lib/expression-name" "Subtotal"}
+ ["field" {} ["Sample" "PUBLIC" "ORDERS" "TOTAL"]]
+ ["field" {} ["Sample" "PUBLIC" "ORDERS" "TAX"]]]]}]}
+ repaired (repair/repair trivial-mp q)]
+ (is (= (get-in q ["stages" 0 "expressions"])
+ (get-in repaired ["stages" 0 "expressions"]))))))
+
+(deftest expressions-sequential-without-name-left-alone-test
+ (testing (str "sequential-form without `lib/expression-name` is left as-is; schema\n"
+ "validation will surface the missing-name error rather than us making one up.")
+ (let [q {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "expressions" [["+" {}
+ ["field" {} ["Sample" "PUBLIC" "ORDERS" "TOTAL"]]
+ ["field" {} ["Sample" "PUBLIC" "ORDERS" "TAX"]]]]}]}
+ repaired (repair/repair trivial-mp q)
+ opts (get-in repaired ["stages" 0 "expressions" 0 1])]
+ (is (not (contains? opts "lib/expression-name"))))))
+
+(deftest expressions-map-with-existing-name-in-options-preserved-test
+ (testing (str "if a map-form entry's clause already has `lib/expression-name` in its options,\n"
+ "authored metadata wins and we don't overwrite it.")
+ (let [q {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "expressions" {"FromKey" ["+"
+ {"lib/expression-name" "FromOpts"}
+ ["field" {} ["Sample" "PUBLIC" "ORDERS" "TOTAL"]]
+ 1]}}]}
+ repaired (repair/repair trivial-mp q)
+ clause (get-in repaired ["stages" 0 "expressions" 0])]
+ (is (= "FromOpts" (get-in clause [1 "lib/expression-name"]))))))
+
+(deftest expressions-absent-no-op-test
+ (testing "stages without `expressions:` are left alone"
+ (let [q {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "aggregation" [["count" {}]]}]}
+ repaired (repair/repair trivial-mp q)]
+ (is (= (get-in q ["stages" 0])
+ (get-in repaired ["stages" 0]))))))
+
+(deftest expressions-idempotent-test
+ (testing "repair is idempotent on expressions: applying twice equals applying once"
+ (let [q {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "expressions" {"Subtotal" ["+" {}
+ ["field" {} ["Sample" "PUBLIC" "ORDERS" "TOTAL"]]
+ ["field" {} ["Sample" "PUBLIC" "ORDERS" "TAX"]]]}}]}
+ once (repair/repair trivial-mp q)
+ twice (repair/repair trivial-mp once)]
+ (is (= once twice)))))
+
+(deftest expressions-multi-stage-test
+ (testing "expression-name stamping works across multiple stages independently"
+ (let [q {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "expressions" {"Subtotal" ["+" {}
+ ["field" {} ["Sample" "PUBLIC" "ORDERS" "TOTAL"]]
+ ["field" {} ["Sample" "PUBLIC" "ORDERS" "TAX"]]]}
+ "aggregation" [["sum" {} ["expression" {} "Subtotal"]]]}
+ {"lib/type" "mbql.stage/mbql"
+ "expressions" {"Doubled" ["*" {}
+ ["field" {"base-type" "type/Integer"} "sum"]
+ 2]}}]}
+ repaired (repair/repair trivial-mp q)]
+ (is (= "Subtotal"
+ (get-in repaired ["stages" 0 "expressions" 0 1 "lib/expression-name"])))
+ (is (= "Doubled"
+ (get-in repaired ["stages" 1 "expressions" 0 1 "lib/expression-name"]))))))
+
+;;; ============================================================
+;;; Pass 2.8 - integer-index aggregation refs → canonical UUID form (repr-plan step 10)
+;;; ============================================================
+
+(deftest aggregation-ref-integer-index-happy-path-test
+ (testing "a 0-based integer agg-ref in order-by is rewritten to the canonical UUID form"
+ (let [q {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "aggregation" [["sum" {} ["field" {"base-type" "type/Float"}
+ ["Sample" "PUBLIC" "ORDERS" "TOTAL"]]]
+ ["count" {}]]
+ "order-by" [["desc" {} ["aggregation" {} 1]]]}]}
+ repaired (repair/repair trivial-mp q)
+ count-agg (get-in repaired ["stages" 0 "aggregation" 1])
+ ref-clause (get-in repaired ["stages" 0 "order-by" 0 2])]
+ (testing "target aggregation clause got a lib/uuid stamped"
+ (is (uuid-string? (get-in count-agg [1 "lib/uuid"]))))
+ (testing "ref last slot is the same UUID as the target aggregation"
+ (is (= (get-in count-agg [1 "lib/uuid"])
+ (nth ref-clause 2))))
+ (testing "ref options got base-type/effective-type from the aggregation head"
+ (is (= "type/BigInteger" (get-in ref-clause [1 "base-type"])))
+ (is (= "type/BigInteger" (get-in ref-clause [1 "effective-type"])))))))
+
+(deftest aggregation-ref-preserves-authored-options-test
+ (testing "authored base-type / name in the ref's options are not overwritten"
+ (let [q {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "aggregation" [["count" {}]]
+ "order-by" [["desc" {} ["aggregation"
+ {"base-type" "type/Float"
+ "effective-type" "type/Float"
+ "name" "custom-name"}
+ 0]]]}]}
+ repaired (repair/repair trivial-mp q)
+ opts (get-in repaired ["stages" 0 "order-by" 0 2 1])]
+ (is (= "type/Float" (get opts "base-type")))
+ (is (= "type/Float" (get opts "effective-type")))
+ (is (= "custom-name" (get opts "name"))))))
+
+(deftest aggregation-ref-out-of-range-raises-agent-error-test
+ (testing "an index past the stage's aggregation vector surfaces an agent-error"
+ (let [q {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "aggregation" [["sum" {} ["field" {} ["Sample" "PUBLIC" "ORDERS" "TOTAL"]]]
+ ["count" {}]]
+ "order-by" [["desc" {} ["aggregation" {} 5]]]}]}]
+ (try
+ (repair/repair trivial-mp q)
+ (is false "expected throw")
+ (catch clojure.lang.ExceptionInfo e
+ (let [d (ex-data e)]
+ (is (true? (:agent-error? d)))
+ (is (= :aggregation-ref-out-of-range (:error d)))
+ (is (= 5 (:index d)))
+ (is (= 2 (:available d)))
+ (is (re-find #"sum at 0" (ex-message e)))
+ (is (re-find #"count at 1" (ex-message e)))))))))
+
+(deftest aggregation-ref-string-uuid-is-idempotent-test
+ (testing "a ref whose last slot is already a UUID string is left unchanged"
+ (let [uuid "11111111-1111-1111-1111-111111111111"
+ q {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "aggregation" [["count" {"lib/uuid" uuid}]]
+ "order-by" [["desc" {} ["aggregation"
+ {"base-type" "type/BigInteger"
+ "effective-type" "type/BigInteger"}
+ uuid]]]}]}
+ repaired (repair/repair trivial-mp q)]
+ (is (= uuid (get-in repaired ["stages" 0 "order-by" 0 2 2])))
+ (is (= uuid (get-in repaired ["stages" 0 "aggregation" 0 1 "lib/uuid"]))))))
+
+(deftest aggregation-ref-no-aggregations-in-stage-raises-agent-error-test
+ (testing "`[aggregation, {}, 0]` with no `aggregation:` clause in the stage is an agent-error"
+ (let [q {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "order-by" [["desc" {} ["aggregation" {} 0]]]}]}]
+ (try
+ (repair/repair trivial-mp q)
+ (is false "expected throw")
+ (catch clojure.lang.ExceptionInfo e
+ (let [d (ex-data e)]
+ (is (true? (:agent-error? d)))
+ (is (= :aggregation-ref-no-aggregations (:error d)))))))))
+
+(deftest aggregation-ref-noop-when-no-int-refs-test
+ (testing "a stage without integer-indexed agg-refs is left alone by this pass"
+ (let [q {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "aggregation" [["count" {}]]}]}
+ repaired (repair/repair trivial-mp q)]
+ ;; aggregation still there; no order-by to rewrite
+ (is (= [["count" {}]]
+ (get-in repaired ["stages" 0 "aggregation"]))))))
+
+(deftest aggregation-ref-idempotent-test
+ (testing "repair is a fixed point under repeated application"
+ (let [q {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "aggregation" [["sum" {} ["field" {"base-type" "type/Float"}
+ ["Sample" "PUBLIC" "ORDERS" "TOTAL"]]]
+ ["count" {}]]
+ "order-by" [["desc" {} ["aggregation" {} 0]]
+ ["asc" {} ["aggregation" {} 1]]]}]}
+ once (repair/repair trivial-mp q)
+ twice (repair/repair trivial-mp once)]
+ (is (= once twice)))))
+
+(deftest aggregation-ref-type-inference-by-head-test
+ (testing "base-type inference from aggregation head"
+ (let [mk (fn [agg-clause]
+ {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "aggregation" [agg-clause]
+ "order-by" [["desc" {} ["aggregation" {} 0]]]}]})
+ type-of (fn [agg-clause]
+ (-> (repair/repair trivial-mp (mk agg-clause))
+ (get-in ["stages" 0 "order-by" 0 2 1 "base-type"])))]
+ (testing "count / distinct / cum-count / count-where → BigInteger"
+ (is (= "type/BigInteger" (type-of ["count" {}])))
+ (is (= "type/BigInteger" (type-of ["distinct" {} ["field" {} ["Sample" "PUBLIC" "ORDERS" "TOTAL"]]]))))
+ (testing "avg / median / stddev / var / share → Float"
+ (is (= "type/Float" (type-of ["avg" {} ["field" {} ["Sample" "PUBLIC" "ORDERS" "TOTAL"]]])))
+ (is (= "type/Float" (type-of ["median" {} ["field" {} ["Sample" "PUBLIC" "ORDERS" "TOTAL"]]]))))
+ (testing "sum / min / max inherit from inner field when annotated"
+ (is (= "type/Float"
+ (type-of ["sum" {} ["field" {"base-type" "type/Float"}
+ ["Sample" "PUBLIC" "ORDERS" "TOTAL"]]]))))
+ (testing "unknown head → type/*"
+ (is (= "type/*" (type-of ["some-new-agg-fn" {}])))))))
+
+(deftest aggregation-ref-multi-stage-same-stage-ref-test
+ (testing "a later stage can use integer agg-ref against its own aggregation list"
+ (let [q {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "aggregation" [["count" {}]]
+ "breakout" [["field" {} ["Sample" "PUBLIC" "ORDERS" "PRODUCT_ID"]]]}
+ {"lib/type" "mbql.stage/mbql"
+ "aggregation" [["avg" {} ["field" {"base-type" "type/BigInteger"} "count"]]]
+ "order-by" [["desc" {} ["aggregation" {} 0]]]}]}
+ repaired (repair/repair trivial-mp q)
+ stage1-agg-uuid (get-in repaired ["stages" 1 "aggregation" 0 1 "lib/uuid"])
+ stage1-ref-uuid (get-in repaired ["stages" 1 "order-by" 0 2 2])]
+ (is (uuid-string? stage1-agg-uuid))
+ (is (= stage1-agg-uuid stage1-ref-uuid))
+ (is (= "type/Float"
+ (get-in repaired ["stages" 1 "order-by" 0 2 1 "base-type"]))))))
+
+;;; ============================================================
+;;; Pass 2.9 - auto-split post-aggregation filter into a second stage
+;;; ============================================================
+
+(deftest split-post-agg-filter-simple-count-test
+ (testing "filter [> count 10] on stage with aggregation [count] is split into two stages"
+ (let [q {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "aggregation" [["count" {}]]
+ "breakout" [["field" {} ["Sample" "PUBLIC" "ORDERS" "PRODUCT_ID"]]]
+ "filters" [[">" {} ["aggregation" {} 0] 10]]}]}
+ repaired (repair/repair trivial-mp q)
+ stages (get repaired "stages")]
+ (is (= 2 (count stages)) "must produce two stages")
+ (testing "stage 0 keeps source/aggregation/breakout, drops the offending filter"
+ (is (= ["Sample" "PUBLIC" "ORDERS"] (get-in stages [0 "source-table"])))
+ (is (= [["count" (get-in stages [0 "aggregation" 0 1])]]
+ (get-in stages [0 "aggregation"])))
+ (is (some? (get-in stages [0 "breakout"])))
+ (is (not (contains? (nth stages 0) "filters"))))
+ (testing "stage 1 has the rewritten filter as cross-stage field ref"
+ (is (= "mbql.stage/mbql" (get-in stages [1 "lib/type"])))
+ (is (not (contains? (nth stages 1) "source-table")))
+ (is (= [[">" {} ["field" {} "count"] 10]]
+ (get-in stages [1 "filters"])))))))
+
+(deftest split-post-agg-filter-keeps-pre-agg-filters-test
+ (testing "pre-agg filters stay in stage 0; only the post-agg filter moves"
+ (let [q {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "aggregation" [["count" {}]]
+ "breakout" [["field" {} ["Sample" "PUBLIC" "ORDERS" "PRODUCT_ID"]]]
+ "filters" [["=" {} ["field" {} ["Sample" "PUBLIC" "ORDERS" "STATUS"]] "complete"]
+ [">" {} ["aggregation" {} 0] 10]]}]}
+ stages (get (repair/repair trivial-mp q) "stages")]
+ (is (= 2 (count stages)))
+ (testing "pre-agg filter stays in stage 0"
+ (is (= [["=" {} ["field" {} ["Sample" "PUBLIC" "ORDERS" "STATUS"]] "complete"]]
+ (get-in stages [0 "filters"]))))
+ (testing "post-agg filter moves to stage 1 with cross-stage ref"
+ (is (= [[">" {} ["field" {} "count"] 10]]
+ (get-in stages [1 "filters"])))))))
+
+(deftest split-post-agg-refuses-when-order-by-present-test
+ (testing (str "post-agg filter + `order-by` in the same stage is refused with a clean "
+ ":agent-error? — auto-relocating ordering is unsafe (the order-by may "
+ "reference a pre-agg column that doesn't survive the split, and forcing the "
+ "LLM to author two stages explicitly preserves the user's intent)")
+ (let [q {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "aggregation" [["count" {}]]
+ "breakout" [["field" {} ["Sample" "PUBLIC" "ORDERS" "PRODUCT_ID"]]]
+ "filters" [[">" {} ["aggregation" {} 0] 10]]
+ "order-by" [["desc" {} ["aggregation" {} 0]]]}]}]
+ (try
+ (repair/repair trivial-mp q)
+ (is false "should have thrown")
+ (catch clojure.lang.ExceptionInfo e
+ (let [data (ex-data e)]
+ (is (true? (:agent-error? data)))
+ (is (= :post-agg-filter-with-trailing-clauses (:error data)))
+ (testing "diagnostic names the offending stage shape"
+ (is (re-find #"order-by" (ex-message e))))))))))
+
+(deftest split-post-agg-refuses-when-limit-present-test
+ (testing "post-agg filter + bare `limit` in the same stage is also refused"
+ (let [q {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "aggregation" [["count" {}]]
+ "breakout" [["field" {} ["Sample" "PUBLIC" "ORDERS" "PRODUCT_ID"]]]
+ "filters" [[">" {} ["aggregation" {} 0] 10]]
+ "limit" 5}]}]
+ (try
+ (repair/repair trivial-mp q)
+ (is false "should have thrown")
+ (catch clojure.lang.ExceptionInfo e
+ (is (= :post-agg-filter-with-trailing-clauses (:error (ex-data e)))))))))
+
+(deftest split-post-agg-refuses-when-fields-present-test
+ (testing "post-agg filter + `fields` in the same stage is also refused"
+ (let [q {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "aggregation" [["count" {}]]
+ "breakout" [["field" {} ["Sample" "PUBLIC" "ORDERS" "PRODUCT_ID"]]]
+ "fields" [["field" {} ["Sample" "PUBLIC" "ORDERS" "PRODUCT_ID"]]]
+ "filters" [[">" {} ["aggregation" {} 0] 10]]}]}]
+ (try
+ (repair/repair trivial-mp q)
+ (is false "should have thrown")
+ (catch clojure.lang.ExceptionInfo e
+ (is (= :post-agg-filter-with-trailing-clauses (:error (ex-data e)))))))))
+
+(deftest split-post-agg-refuses-when-raw-column-order-by-test
+ (testing (str "specifically the pre-agg `order-by [desc TOTAL]` case the reviewer flagged "
+ "as silent-intent-destruction in the prior implementation: TOTAL doesn't "
+ "survive aggregation and naively moving it to stage 1 produced either a "
+ "'no matching field' error or a silently-wrong row set. Now refused.")
+ (let [q {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "aggregation" [["count" {}]]
+ "breakout" [["field" {} ["Sample" "PUBLIC" "ORDERS" "PRODUCT_ID"]]]
+ "filters" [[">" {} ["field" {} ["Sample" "PUBLIC" "ORDERS" "TOTAL"]] 100]
+ [">" {} ["aggregation" {} 0] 1]]
+ "order-by" [["desc" {} ["field" {} ["Sample" "PUBLIC" "ORDERS" "TOTAL"]]]]
+ "limit" 10}]}]
+ (try
+ (repair/repair trivial-mp q)
+ (is false "should have thrown")
+ (catch clojure.lang.ExceptionInfo e
+ (is (= :post-agg-filter-with-trailing-clauses (:error (ex-data e)))))))))
+
+(deftest split-post-agg-uses-name-override-when-present-test
+ (testing "an aggregation with `name` override produces a cross-stage ref by that name"
+ (let [q {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "aggregation" [["count" {"name" "Total Orders"}]]
+ "breakout" [["field" {} ["Sample" "PUBLIC" "ORDERS" "PRODUCT_ID"]]]
+ "filters" [[">" {} ["aggregation" {} 0] 10]]}]}
+ stages (get (repair/repair trivial-mp q) "stages")]
+ (is (= 2 (count stages)))
+ (is (= [[">" {} ["field" {} "Total Orders"] 10]]
+ (get-in stages [1 "filters"]))))))
+
+(deftest split-post-agg-multiple-aggregations-test
+ (testing "with multiple aggregations of DIFFERENT heads, each gets its own column-name mapping"
+ (let [q {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "aggregation" [["count" {}]
+ ["sum" {} ["field" {} ["Sample" "PUBLIC" "ORDERS" "TOTAL"]]]]
+ "breakout" [["field" {} ["Sample" "PUBLIC" "ORDERS" "PRODUCT_ID"]]]
+ "filters" [[">" {} ["aggregation" {} 0] 10]
+ [">" {} ["aggregation" {} 1] 100]]}]}
+ stages (get (repair/repair trivial-mp q) "stages")]
+ (is (= 2 (count stages)))
+ (is (= [[">" {} ["field" {} "count"] 10]
+ [">" {} ["field" {} "sum"] 100]]
+ (get-in stages [1 "filters"]))))))
+
+(deftest split-post-agg-refuses-on-duplicate-column-names-test
+ (testing (str "two `sum` aggregations on different fields would both map to the static "
+ "column name \"sum\"; lib's `unique-name-generator` would dedup to "
+ "`sum` / `sum_2` based on field order, which our static table cannot "
+ "replicate without recreating the generator. We refuse the split with a "
+ "clean diagnostic rather than emit a cross-stage `[\"field\" {} \"sum\"]` "
+ "ref that filters against whichever column happens to come first.")
+ (let [q {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "aggregation" [["sum" {"lib/uuid" "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"}
+ ["field" {} ["Sample" "PUBLIC" "ORDERS" "TOTAL"]]]
+ ["sum" {"lib/uuid" "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb"}
+ ["field" {} ["Sample" "PUBLIC" "ORDERS" "TAX"]]]]
+ "breakout" [["field" {} ["Sample" "PUBLIC" "ORDERS" "PRODUCT_ID"]]]
+ "filters" [[">" {} ["aggregation" {} "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb"] 100]]}]}]
+ (try
+ (repair/repair trivial-mp q)
+ (is false "should have thrown")
+ (catch clojure.lang.ExceptionInfo e
+ (let [data (ex-data e)
+ msg (ex-message e)]
+ (is (true? (:agent-error? data)))
+ (is (= :post-agg-filter-needs-multi-stage (:error data)))
+ (testing "message names the duplicate-column-name failure mode"
+ (is (re-find #"same column name" msg)))
+ (testing "message offers the `name` opts override as a remedy"
+ (is (re-find #"name" msg)))))))))
+
+(deftest split-post-agg-same-head-with-name-overrides-test
+ (testing (str "explicit `name` opts override resolves the duplicate-name collision: the "
+ "user gets the split they intended.")
+ (let [q {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "aggregation" [["sum" {"lib/uuid" "aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa"
+ "name" "sum_total"}
+ ["field" {} ["Sample" "PUBLIC" "ORDERS" "TOTAL"]]]
+ ["sum" {"lib/uuid" "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb"
+ "name" "sum_tax"}
+ ["field" {} ["Sample" "PUBLIC" "ORDERS" "TAX"]]]]
+ "breakout" [["field" {} ["Sample" "PUBLIC" "ORDERS" "PRODUCT_ID"]]]
+ "filters" [[">" {} ["aggregation" {} "bbbbbbbb-bbbb-bbbb-bbbb-bbbbbbbbbbbb"] 100]]}]}
+ stages (get (repair/repair trivial-mp q) "stages")]
+ (is (= 2 (count stages)))
+ (testing "cross-stage ref correctly points at sum_tax (the filtered uuid), NOT sum_total"
+ (is (= [[">" {} ["field" {} "sum_tax"] 100]]
+ (get-in stages [1 "filters"])))))))
+
+(deftest split-post-agg-metric-emits-diagnostic-test
+ (testing "metric aggregation we can't auto-resolve raises clean :agent-error?"
+ (let [q {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "aggregation" [["metric" {"lib/uuid" "11111111-1111-1111-1111-111111111111"} "@card-1"]]
+ "filters" [[">" {} ["aggregation" {} "11111111-1111-1111-1111-111111111111"] 10]]}]}]
+ (try
+ (repair/repair trivial-mp q)
+ (is false "should have thrown")
+ (catch clojure.lang.ExceptionInfo e
+ (is (true? (:agent-error? (ex-data e))))
+ (is (= :post-agg-filter-needs-multi-stage (:error (ex-data e)))))))))
+
+(deftest split-post-agg-no-trigger-when-no-agg-ref-test
+ (testing "stage with aggregation but no agg-ref-filter is left alone"
+ (let [q {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "aggregation" [["count" {}]]
+ "filters" [["=" {} ["field" {} ["Sample" "PUBLIC" "ORDERS" "STATUS"]] "x"]]}]}
+ stages (get (repair/repair trivial-mp q) "stages")]
+ (is (= 1 (count stages))))))
+
+(deftest split-post-agg-no-trigger-when-no-aggregations-test
+ (testing "stage with no aggregations is never split, even if filter has an aggregation-ref shape"
+ ;; The agg-ref points to nothing in this stage - resolve-aggregation-ref-indexes will
+ ;; have already raised. We just verify split doesn't add a phantom stage on its own.
+ (let [q {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "filters" [["=" {} ["field" {} ["Sample" "PUBLIC" "ORDERS" "STATUS"]] "x"]]}]}
+ stages (get (repair/repair trivial-mp q) "stages")]
+ (is (= 1 (count stages))))))
+
+(deftest split-post-agg-idempotent-test
+ (testing "repair on an already-split query is a no-op"
+ (let [q {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "aggregation" [["count" {}]]
+ "breakout" [["field" {} ["Sample" "PUBLIC" "ORDERS" "PRODUCT_ID"]]]
+ "filters" [[">" {} ["aggregation" {} 0] 10]]}]}
+ once (repair/repair trivial-mp q)
+ twice (repair/repair trivial-mp once)]
+ (is (= 2 (count (get once "stages"))))
+ (is (= once twice)))))
+
+(deftest split-post-agg-handles-distinct-and-count-where-test
+ (testing "distinct and count-where get correct lib column names"
+ (let [build (fn [agg]
+ {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "aggregation" [agg]
+ "filters" [[">" {} ["aggregation" {} 0] 1]]}]})]
+ (testing "distinct → count"
+ (is (= [[">" {} ["field" {} "count"] 1]]
+ (get-in (repair/repair trivial-mp
+ (build ["distinct" {} ["field" {} ["Sample" "PUBLIC" "ORDERS" "ID"]]]))
+ ["stages" 1 "filters"]))))
+ (testing "count-where → count_where"
+ (is (= [[">" {} ["field" {} "count_where"] 1]]
+ (get-in (repair/repair trivial-mp
+ (build ["count-where" {} ["=" {} ["field" {} ["Sample" "PUBLIC" "ORDERS" "STATUS"]] "x"]]))
+ ["stages" 1 "filters"])))))))
+
+;;; ============================================================
+;;; Pass 6 - friendly error messages (E1..E6)
+;;; ============================================================
+
+;;; ----- E1: [field, ...] in aggregation block ---------------------------------------
+
+(deftest friendly-error-field-as-aggregation-entry-test
+ (testing "a `[field, ...]` directly inside `aggregation:` raises clean :agent-error?"
+ (let [q {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "aggregation" [["field" {} ["Sample" "PUBLIC" "ORDERS" "TOTAL"]]]}]}]
+ (try
+ (repair/repair trivial-mp q)
+ (is false "should have thrown")
+ (catch clojure.lang.ExceptionInfo e
+ (let [data (ex-data e)]
+ (is (true? (:agent-error? data)))
+ (is (= :aggregation-entry-not-aggregation (:error data)))
+ (is (= 0 (:stage-index data)))
+ (is (= 0 (:entry-index data)))
+ (is (re-find #"aggregation" (ex-message e)))
+ (is (re-find #"breakout" (ex-message e)))))))))
+
+(deftest friendly-error-canonical-aggregation-passes-test
+ (testing "canonical aggregation entries (count, sum, avg, metric) do NOT trigger"
+ (doseq [agg [["count" {}]
+ ["sum" {} ["field" {} ["Sample" "PUBLIC" "ORDERS" "TOTAL"]]]
+ ["avg" {} ["field" {} ["Sample" "PUBLIC" "ORDERS" "TOTAL"]]]
+ ["metric" {} "@card-1"]]]
+ (let [q {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "aggregation" [agg]}]}]
+ (is (some? (repair/repair trivial-mp q)) (str "should not throw on " agg))))))
+
+(deftest friendly-error-field-nested-inside-aggregation-passes-test
+ (testing "a `field` clause NESTED inside an aggregation (its argument) does NOT trigger"
+ (let [q {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "aggregation" [["sum" {} ["field" {} ["Sample" "PUBLIC" "ORDERS" "TOTAL"]]]]}]}]
+ (is (some? (repair/repair trivial-mp q))))))
+
+(deftest friendly-error-multi-stage-stage-index-test
+ (testing "multi-stage: error names the correct stage index"
+ (let [q {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "aggregation" [["count" {}]]
+ "breakout" [["field" {} ["Sample" "PUBLIC" "ORDERS" "PRODUCT_ID"]]]}
+ {"lib/type" "mbql.stage/mbql"
+ "aggregation" [["field" {} "count"]]}]}]
+ (try
+ (repair/repair trivial-mp q)
+ (is false "should have thrown")
+ (catch clojure.lang.ExceptionInfo e
+ (is (= 1 (:stage-index (ex-data e)))))))))
+
+;;; ----- E2: case/if with "default" in opts ------------------------------------------
+
+(deftest friendly-error-case-default-in-opts-test
+ (testing "`case` with `default` in options raises clean :agent-error?"
+ (let [q {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "expressions" [["case" {"default" "unknown" "lib/expression-name" "Bucket"}
+ [[["=" {} ["field" {} ["Sample" "PUBLIC" "ORDERS" "TOTAL"]] 0] "zero"]]]]}]}]
+ (try
+ (repair/repair trivial-mp q)
+ (is false "should have thrown")
+ (catch clojure.lang.ExceptionInfo e
+ (let [data (ex-data e)]
+ (is (true? (:agent-error? data)))
+ (is (= :case-default-in-opts (:error data)))
+ (is (re-find #"third positional argument" (ex-message e))))))))
+ (testing "`if` with `default` in options also triggers"
+ (let [q {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "expressions" [["if" {"default" "no" "lib/expression-name" "Y"}
+ [[["=" {} ["field" {} ["Sample" "PUBLIC" "ORDERS" "TOTAL"]] 0] "yes"]]]]}]}]
+ (try
+ (repair/repair trivial-mp q)
+ (is false "should have thrown")
+ (catch clojure.lang.ExceptionInfo e
+ (is (= :case-default-in-opts (:error (ex-data e)))))))))
+
+(deftest friendly-error-case-canonical-default-passes-test
+ (testing "canonical `case` with default as 3rd arg does NOT trigger"
+ (let [q {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "expressions" [["case" {"lib/expression-name" "Bucket"}
+ [[["=" {} ["field" {} ["Sample" "PUBLIC" "ORDERS" "TOTAL"]] 0] "zero"]]
+ "unknown"]]}]}]
+ (is (some? (repair/repair trivial-mp q)))))
+ (testing "case with no default at all also passes"
+ (let [q {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "expressions" [["case" {"lib/expression-name" "Bucket"}
+ [[["=" {} ["field" {} ["Sample" "PUBLIC" "ORDERS" "TOTAL"]] 0] "zero"]]]]}]}]
+ (is (some? (repair/repair trivial-mp q))))))
+
+;;; ----- E3: sexp-legacy top-level ops used as clause heads --------------------------
+
+(deftest friendly-error-sexp-legacy-aggregate-test
+ (testing "`[aggregate, ...]` as a clause head raises clean :agent-error?"
+ (let [q {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "aggregation" [["aggregate" {} ["count" {}]]]}]}]
+ (try
+ (repair/repair trivial-mp q)
+ (is false "should have thrown")
+ (catch clojure.lang.ExceptionInfo e
+ (let [data (ex-data e)]
+ (is (true? (:agent-error? data)))
+ (is (= :sexp-legacy-op-as-clause (:error data)))
+ (is (= "aggregate" (:head data)))
+ (is (re-find #"top-level operation" (ex-message e)))))))))
+
+(deftest friendly-error-sexp-legacy-filter-test
+ (testing "`[filter, ...]` as a clause head triggers"
+ (let [q {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "filters" [["filter" {} ["=" {} ["field" {} ["Sample" "PUBLIC" "ORDERS" "STATUS"]] "x"]]]}]}]
+ (try
+ (repair/repair trivial-mp q)
+ (is false "should have thrown")
+ (catch clojure.lang.ExceptionInfo e
+ (is (= "filter" (:head (ex-data e)))))))))
+
+(deftest friendly-error-sexp-legacy-each-op-mentioned-test
+ (testing "every legacy op (aggregate/filter/order-by/breakout/limit) is recognised"
+ (doseq [head ["aggregate" "filter" "order-by" "breakout" "limit"]]
+ (let [q {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ ;; Stuff a sexp-legacy op clause into expressions to ensure the
+ ;; tree walk reaches it regardless of which stage block we're
+ ;; defending against.
+ "expressions" [[head {"lib/expression-name" "X"} ["field" {} ["Sample" "PUBLIC" "ORDERS" "TOTAL"]]]]}]}]
+ (try
+ (repair/repair trivial-mp q)
+ (is false (str "should have thrown for " head))
+ (catch clojure.lang.ExceptionInfo e
+ (is (= head (:head (ex-data e))) (str "head mismatch for " head))))))))
+
+(deftest friendly-error-canonical-stage-keys-pass-test
+ (testing "canonical stage-level keys (aggregation:, filters:, etc.) do NOT trigger"
+ ;; The sexp-legacy detector targets clause heads (vector slot-0 strings), not stage
+ ;; map keys. A perfectly valid stage with `aggregation:` / `filters:` keys passes.
+ (let [q {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "aggregation" [["count" {}]]
+ "filters" [["=" {} ["field" {} ["Sample" "PUBLIC" "ORDERS" "STATUS"]] "x"]]
+ "breakout" [["field" {} ["Sample" "PUBLIC" "ORDERS" "PRODUCT_ID"]]]
+ "order-by" [["asc" {} ["field" {} ["Sample" "PUBLIC" "ORDERS" "ID"]]]]
+ "limit" 10}]}]
+ (is (some? (repair/repair trivial-mp q))))))
+
+;;; ----- E4: `[measure, ...]` was historically rejected; now a first-class clause -----
+
+(deftest measure-clause-passes-repair-test
+ (testing (str "`[measure, {}, <portable_entity_id>]` is a first-class aggregation clause "
+ "(was rejected by the now-deleted E4 sexp-legacy-measure-error! check). "
+ "Lookup/resolution happens in the resolve layer, not repair.")
+ (let [q {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "aggregation" [["measure" {} "@card-1"]]}]}]
+ (is (some? (repair/repair trivial-mp q))))))
+
+(deftest friendly-error-canonical-metric-passes-test
+ (testing "canonical `[metric, {}, <portable_entity_id>]` does NOT trigger E4"
+ (let [q {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "aggregation" [["metric" {} "@card-1"]]}]}]
+ (is (some? (repair/repair trivial-mp q))))))
+
+;;; ----- E5: blank [expression, opts, ""] reference ----------------------------------
+
+(deftest friendly-error-blank-expression-ref-test
+ (testing "`[expression, {}, \"\"]` blank ref raises clean :agent-error?"
+ (let [q {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "expressions" [["+" {"lib/expression-name" "X"}
+ ["field" {} ["Sample" "PUBLIC" "ORDERS" "TOTAL"]] 1]]
+ "filters" [["=" {} ["expression" {} ""] 0]]}]}]
+ (try
+ (repair/repair trivial-mp q)
+ (is false "should have thrown")
+ (catch clojure.lang.ExceptionInfo e
+ (let [data (ex-data e)]
+ (is (true? (:agent-error? data)))
+ (is (= :blank-expression-ref (:error data))))))))
+ (testing "`[expression, {}, \" \"]` (whitespace-only) also triggers"
+ (let [q {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "filters" [["=" {} ["expression" {} " "] 0]]}]}]
+ (try
+ (repair/repair trivial-mp q)
+ (is false "should have thrown")
+ (catch clojure.lang.ExceptionInfo e
+ (is (= :blank-expression-ref (:error (ex-data e))))))))
+ (testing "`[expression, {}, nil]` (non-string) also triggers"
+ (let [q {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "filters" [["=" {} ["expression" {} nil] 0]]}]}]
+ (try
+ (repair/repair trivial-mp q)
+ (is false "should have thrown")
+ (catch clojure.lang.ExceptionInfo e
+ (is (= :blank-expression-ref (:error (ex-data e)))))))))
+
+(deftest friendly-error-non-blank-expression-ref-passes-test
+ (testing "valid `[expression, {}, \"my-expr\"]` does NOT trigger"
+ (let [q {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "expressions" [["+" {"lib/expression-name" "my-expr"}
+ ["field" {} ["Sample" "PUBLIC" "ORDERS" "TOTAL"]] 1]]
+ "filters" [["=" {} ["expression" {} "my-expr"] 0]]}]}]
+ (is (some? (repair/repair trivial-mp q))))))
+
+;;; ----- E6: numeric [field, opts, 100] (sexp legacy form) ---------------------------
+
+(deftest friendly-error-numeric-field-id-test
+ (testing "`[field, {}, 100]` (numeric id) raises clean :agent-error?"
+ (let [q {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "filters" [["=" {} ["field" {} 100] 0]]}]}]
+ (try
+ (repair/repair trivial-mp q)
+ (is false "should have thrown")
+ (catch clojure.lang.ExceptionInfo e
+ (let [data (ex-data e)]
+ (is (true? (:agent-error? data)))
+ (is (= :numeric-field-id (:error data)))
+ (is (re-find #"portable FK" (ex-message e)))
+ (is (re-find #"column-name" (ex-message e)))))))))
+
+(deftest friendly-error-portable-fk-passes-test
+ (testing "canonical portable-FK `[field, {}, [Sample, PUBLIC, ORDERS, COL]]` does NOT trigger"
+ (let [q {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "filters" [["=" {} ["field" {} ["Sample" "PUBLIC" "ORDERS" "STATUS"]] "x"]]}]}]
+ (is (some? (repair/repair trivial-mp q))))))
+
+(deftest friendly-error-cross-stage-string-col-passes-test
+ (testing "cross-stage string column-name `[field, {}, \"count\"]` does NOT trigger"
+ (let [q {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "aggregation" [["count" {}]]}
+ {"lib/type" "mbql.stage/mbql"
+ "filters" [[">" {} ["field" {} "count"] 10]]}]}]
+ (is (some? (repair/repair trivial-mp q))))))
diff --git a/test/metabase/agent_lib/representations/resolve_test.clj b/test/metabase/agent_lib/representations/resolve_test.clj
new file mode 100644
index 00000000000..81ea245b513
--- /dev/null
+++ b/test/metabase/agent_lib/representations/resolve_test.clj
@@ -0,0 +1,352 @@
+(ns metabase.agent-lib.representations.resolve-test
+ "Tests for the repr → canonical-MBQL resolver.
+
+ Strategy: for each MVP operation type (`filters`, `aggregation`, `breakout`, `order-by`,
+ `limit`, `fields`, `joins`), feed a parsed representations-form map through the resolver and
+ assert that the output is:
+
+ * a valid MBQL 5 query per `lib.schema/query`;
+ * with numeric FK ids in the correct places (table, field, source-table);
+ * with `:lib/uuid` stamped on every clause;
+ * with known enum values (temporal unit, strategy) keywordized.
+
+ Test inputs are expressed as Clojure data structures with string keys — the exact shape
+ `repr/parse-yaml` would return — rather than as YAML strings. Parser-level concerns are
+ covered by `metabase.agent-lib.representations-test`; this suite focuses on resolution."
+ (:require
+ [clojure.test :refer [deftest is testing]]
+ [metabase.agent-lib.representations :as repr]
+ [metabase.agent-lib.representations.resolve :as repr.resolve]
+ [metabase.lib.schema :as lib.schema]
+ [metabase.lib.test-util :as lib.tu]
+ [metabase.util.malli.registry :as mr]))
+
+(set! *warn-on-reflection* true)
+
+;;; ============================================================
+;;; Fixture metadata provider
+;;; ============================================================
+
+(def ^:private mp
+ (lib.tu/mock-metadata-provider
+ {:database {:id 1 :name "Sample" :dbms-version {:flavor "PostgreSQL"} :engine :postgres}
+ :tables [{:id 10 :name "ORDERS" :schema "PUBLIC" :db-id 1}
+ {:id 11 :name "PRODUCTS" :schema "PUBLIC" :db-id 1}]
+ :fields [{:id 100 :name "ID" :table-id 10 :base-type :type/Integer}
+ {:id 101 :name "TOTAL" :table-id 10 :base-type :type/Float}
+ {:id 102 :name "CREATED_AT" :table-id 10 :base-type :type/DateTime}
+ {:id 103 :name "PRODUCT_ID" :table-id 10 :base-type :type/Integer}
+ {:id 110 :name "ID" :table-id 11 :base-type :type/Integer}
+ {:id 111 :name "CATEGORY" :table-id 11 :base-type :type/Text}]}))
+
+(defn- schema-valid? [query]
+ (nil? (mr/explain ::lib.schema/query query)))
+
+;;; ============================================================
+;;; Simple aggregation + breakout
+;;; ============================================================
+
+(deftest aggregation-breakout-test
+ (let [parsed {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "aggregation" [["count" {}]]
+ "breakout" [["field" {"temporal-unit" "month"}
+ ["Sample" "PUBLIC" "ORDERS" "CREATED_AT"]]]}]}
+ q (repr.resolve/resolve-query mp parsed)]
+ (testing "shape of output"
+ (is (= :mbql/query (:lib/type q)))
+ (is (= 1 (:database q)))
+ (is (= 1 (count (:stages q)))))
+ (testing "source-table resolved to numeric id"
+ (is (= 10 (get-in q [:stages 0 :source-table]))))
+ (testing "aggregation is keywordized, has lib/uuid"
+ (let [[head opts] (get-in q [:stages 0 :aggregation 0])]
+ (is (= :count head))
+ (is (uuid? (parse-uuid (:lib/uuid opts))))))
+ (testing "breakout field resolved + temporal-unit keywordized"
+ (let [[head opts id] (get-in q [:stages 0 :breakout 0])]
+ (is (= :field head))
+ (is (= 102 id))
+ (is (= :month (:temporal-unit opts)))))
+ (testing "query passes lib.schema/query"
+ (is (schema-valid? q)))))
+
+(deftest export-query-round-trip-shape-test
+ (testing "resolved numeric pMBQL exports back to the portable string-keyed representations form"
+ (let [parsed {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "aggregation" [["count" {}]]
+ "breakout" [["field" {"temporal-unit" "month"}
+ ["Sample" "PUBLIC" "ORDERS" "CREATED_AT"]]]}]}
+ q (repr.resolve/resolve-query mp parsed)
+ exported (repr.resolve/export-query mp q)]
+ (is (= "mbql/query" (get exported "lib/type")))
+ (is (= "Sample" (get exported "database")))
+ (is (nil? (get exported "lib/metadata")))
+ (is (= ["Sample" "PUBLIC" "ORDERS"]
+ (get-in exported ["stages" 0 "source-table"])))
+ (is (= ["Sample" "PUBLIC" "ORDERS" "CREATED_AT"]
+ (get-in exported ["stages" 0 "breakout" 0 2])))
+ (is (string? (get-in exported ["stages" 0 "aggregation" 0 1 "lib/uuid"])))
+ (is (= exported (repr/validate-query exported))))))
+
+;;; ============================================================
+;;; filters / limit / order-by
+;;; ============================================================
+
+(deftest filters-limit-orderby-test
+ (let [parsed {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "filters" [[">" {}
+ ["field" {} ["Sample" "PUBLIC" "ORDERS" "TOTAL"]]
+ 100]]
+ "aggregation" [["sum" {}
+ ["field" {} ["Sample" "PUBLIC" "ORDERS" "TOTAL"]]]]
+ "order-by" [["desc" {}
+ ["field" {} ["Sample" "PUBLIC" "ORDERS" "CREATED_AT"]]]]
+ "limit" 50}]}
+ q (repr.resolve/resolve-query mp parsed)
+ st0 (get-in q [:stages 0])]
+ (testing "filter clause"
+ (let [[op _opts lhs rhs] (get-in st0 [:filters 0])]
+ (is (= :> op))
+ (is (= :field (first lhs)))
+ (is (= 101 (last lhs)))
+ (is (= 100 rhs))))
+ (testing "sum aggregation on a field"
+ (let [[op _opts arg] (get-in st0 [:aggregation 0])]
+ (is (= :sum op))
+ (is (= :field (first arg)))
+ (is (= 101 (last arg)))))
+ (testing "order-by desc on CREATED_AT"
+ (let [[op _opts arg] (get-in st0 [:order-by 0])]
+ (is (= :desc op))
+ (is (= 102 (last arg)))))
+ (testing "limit"
+ (is (= 50 (:limit st0))))
+ (testing "query passes lib.schema/query"
+ (is (schema-valid? q)))))
+
+;;; ============================================================
+;;; fields (projection)
+;;; ============================================================
+
+(deftest fields-projection-test
+ (let [parsed {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "fields" [["field" {} ["Sample" "PUBLIC" "ORDERS" "ID"]]
+ ["field" {} ["Sample" "PUBLIC" "ORDERS" "TOTAL"]]]}]}
+ q (repr.resolve/resolve-query mp parsed)
+ fs (get-in q [:stages 0 :fields])]
+ (is (= 2 (count fs)))
+ (is (= #{100 101} (set (map last fs))))
+ (is (every? #(= :field (first %)) fs))
+ (is (schema-valid? q))))
+
+;;; ============================================================
+;;; Explicit join
+;;; ============================================================
+
+(deftest explicit-join-test
+ (let [parsed {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "joins" [{"alias" "Products"
+ "strategy" "left-join"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "PRODUCTS"]}]
+ "conditions" [["=" {}
+ ["field" {}
+ ["Sample" "PUBLIC" "ORDERS" "PRODUCT_ID"]]
+ ["field" {"join-alias" "Products"}
+ ["Sample" "PUBLIC" "PRODUCTS" "ID"]]]]}]
+ "aggregation" [["count" {}]]
+ "breakout" [["field" {"join-alias" "Products"}
+ ["Sample" "PUBLIC" "PRODUCTS" "CATEGORY"]]]}]}
+ q (repr.resolve/resolve-query mp parsed)
+ st0 (get-in q [:stages 0])
+ join (get-in st0 [:joins 0])]
+ (testing "join has alias + strategy keywordized"
+ (is (= "Products" (:alias join)))
+ (is (= :left-join (:strategy join))))
+ (testing "join stages resolved"
+ (is (= 11 (get-in join [:stages 0 :source-table]))))
+ (testing "condition fields resolved to numeric ids"
+ (let [[_ _ lhs rhs] (get-in join [:conditions 0])]
+ (is (= 103 (last lhs)))
+ (is (= 110 (last rhs)))
+ (is (= "Products" (:join-alias (second rhs))))))
+ (testing "breakout field from joined table uses join-alias"
+ (let [[_ opts id] (get-in st0 [:breakout 0])]
+ (is (= 111 id))
+ (is (= "Products" (:join-alias opts)))))
+ (testing "query passes lib.schema/query"
+ (is (schema-valid? q)))))
+
+;;; ============================================================
+;;; Error paths: resolver surface errors
+;;; ============================================================
+
+(deftest unknown-table-error-test
+ (let [parsed {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "NOPE"]
+ "aggregation" [["count" {}]]}]}]
+ (try
+ (repr.resolve/resolve-query mp parsed)
+ (is false "expected throw")
+ (catch clojure.lang.ExceptionInfo e
+ (is (= :unknown-table (:error (ex-data e))))))))
+
+(deftest unknown-field-error-test
+ (let [parsed {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "breakout" [["field" {} ["Sample" "PUBLIC" "ORDERS" "NOPE"]]]
+ "aggregation" [["count" {}]]}]}]
+ (try
+ (repr.resolve/resolve-query mp parsed)
+ (is false "expected throw")
+ (catch clojure.lang.ExceptionInfo e
+ (is (= :unknown-field (:error (ex-data e))))))))
+
+(deftest database-mismatch-error-test
+ (let [parsed {"lib/type" "mbql/query"
+ "database" "Wrong"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "aggregation" [["count" {}]]}]}]
+ (try
+ (repr.resolve/resolve-query mp parsed)
+ (is false "expected throw")
+ (catch clojure.lang.ExceptionInfo e
+ (is (= :unknown-database (:error (ex-data e))))))))
+
+;;; ============================================================
+;;; Extended source-field variants (step 12)
+;;;
+;;; The resolver itself does no special handling: `source-field-name` and
+;;; `source-field-join-alias` are plain strings that pass through `import-mbql` untouched and
+;;; are keywordized by `lib.normalize`. Documented here so a future change to either layer
+;;; that breaks the propagation is caught by a single explicit test.
+;;; ============================================================
+
+(deftest extended-source-field-variants-pass-through-test
+ (testing "source-field-name (multi-stage previous-stage column ref) is preserved as a string"
+ (let [parsed {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]}
+ {"lib/type" "mbql.stage/mbql"
+ "fields" [["field"
+ {"base-type" "type/Text"
+ "source-field-name" "PRODUCT_ID"}
+ "CATEGORY"]]}]}
+ out (repr.resolve/resolve-query mp parsed)
+ field-clause (get-in out [:stages 1 :fields 0])
+ opts (nth field-clause 1)]
+ (is (schema-valid? out))
+ (is (= "PRODUCT_ID" (:source-field-name opts)))
+ (is (= "CATEGORY" (nth field-clause 2))
+ "the field clause's third slot stays the cross-stage column name (a string)")))
+ (testing "source-field-join-alias (FK column lives on an explicitly-joined table) is preserved as a string"
+ (let [parsed {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "joins" [{"lib/type" "mbql/join"
+ "alias" "Orders_A"
+ "strategy" "left-join"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]}]
+ "conditions" [["=" {}
+ ["field" {}
+ ["Sample" "PUBLIC" "ORDERS" "ID"]]
+ ["field" {"join-alias" "Orders_A"}
+ ["Sample" "PUBLIC" "ORDERS" "ID"]]]]}]
+ "fields" [["field"
+ {"source-field" ["Sample" "PUBLIC" "ORDERS" "PRODUCT_ID"]
+ "source-field-join-alias" "Orders_A"}
+ ["Sample" "PUBLIC" "PRODUCTS" "CATEGORY"]]]}]}
+ out (repr.resolve/resolve-query mp parsed)
+ field-clause (get-in out [:stages 0 :fields 0])
+ opts (nth field-clause 1)]
+ (is (schema-valid? out))
+ (is (= "Orders_A" (:source-field-join-alias opts)))
+ (is (= 103 (:source-field opts))
+ "the portable `source-field` FK is still resolved to its numeric id alongside the alias"))))
+
+;;; ============================================================
+;;; try-export-query: structured + native + nil/error fallback
+;;; ============================================================
+
+(deftest try-export-query-structured-test
+ (testing "structured pMBQL exports to a portable repr-form map with portable FKs and string keys"
+ (let [parsed {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "aggregation" [["count" {}]]
+ "breakout" [["field" {"temporal-unit" "month"}
+ ["Sample" "PUBLIC" "ORDERS" "CREATED_AT"]]]}]}
+ q (repr.resolve/resolve-query mp parsed)
+ exported (repr.resolve/try-export-query mp q)]
+ (is (map? exported))
+ (is (= "mbql/query" (get exported "lib/type")))
+ (is (= "Sample" (get exported "database")))
+ (is (= ["Sample" "PUBLIC" "ORDERS"]
+ (get-in exported ["stages" 0 "source-table"])))
+ (is (not (contains? exported :lib/metadata))
+ "the metadata-provider handle never leaks to the LLM-facing payload")
+ (is (not (contains? exported "lib/metadata"))))))
+
+(deftest try-export-query-nil-and-error-fallback-test
+ (testing "nil / blank input returns nil so the caller can omit the field"
+ (is (nil? (repr.resolve/try-export-query mp nil)))
+ (is (nil? (repr.resolve/try-export-query mp {})))
+ (is (nil? (repr.resolve/try-export-query nil {:lib/type :mbql/query :database 1 :stages []}))))
+ (testing "export errors are swallowed and surface as nil (the caller falls back gracefully)"
+ ;; A query map with a numeric field id that doesn't exist in the metadata-provider
+ ;; will throw inside `export-mbql`; we want the helper to return nil rather than
+ ;; tearing down the whole LLM context-building flow.
+ (let [bogus {:lib/type :mbql/query
+ :database 1
+ :stages [{:lib/type :mbql.stage/mbql
+ :source-table 99999}]}]
+ (is (nil? (repr.resolve/try-export-query mp bogus))))))
+
+(deftest export-query-3-arity-threads-content-store-test
+ (testing (str "export-query / try-export-query accept an explicit content-store as their "
+ "third argument. The store is used for Card / Measure / Segment id → "
+ "entity_id lookups (the N1 chokepoint). Pass an erroring store and the "
+ "export-side `:export-fk` lookups should fail through that store, not "
+ "through the default unchecked one. We use a basic 1-stage query (no card "
+ "ref) so we can prove the 3-arity wiring works regardless of whether the "
+ "particular query needs a content-store lookup.")
+ (let [parsed {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "aggregation" [["count" {}]]}]}
+ q (repr.resolve/resolve-query mp parsed)]
+ (testing "3-arity export-query mirrors 2-arity for queries with no Card / Measure / Segment refs"
+ (is (= (repr.resolve/export-query mp q)
+ (repr.resolve/export-query mp q
+ @(requiring-resolve
+ 'metabase.models.serialization.resolve.mp/unchecked-app-db-content-store)))))
+ (testing "3-arity try-export-query likewise"
+ (is (= (repr.resolve/try-export-query mp q)
+ (repr.resolve/try-export-query mp q
+ @(requiring-resolve
+ 'metabase.models.serialization.resolve.mp/unchecked-app-db-content-store))))))))
diff --git a/test/metabase/agent_lib/representations_test.clj b/test/metabase/agent_lib/representations_test.clj
new file mode 100644
index 00000000000..e5e7edcaccc
--- /dev/null
+++ b/test/metabase/agent_lib/representations_test.clj
@@ -0,0 +1,124 @@
+(ns metabase.agent-lib.representations-test
+ "Tests for the representations boundary helpers — JSON external-query validation, the
+ external↔portable conversion, and the post-repair portable-form sanity schema."
+ (:require
+ [clojure.test :refer [deftest is testing]]
+ [metabase.agent-lib.representations :as repr]))
+
+(set! *warn-on-reflection* true)
+
+;;; ============================================================
+;;; external-query->portable
+;;; ============================================================
+
+(deftest external-query->portable-test
+ (testing "stringifies map keys preserving namespace"
+ (is (= {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "limit" 5}]}
+ (repr/external-query->portable
+ {:lib/type "mbql/query"
+ :database "Sample"
+ :stages [{:lib/type "mbql.stage/mbql"
+ :source-table ["Sample" "PUBLIC" "ORDERS"]
+ :limit 5}]}))))
+ (testing "stringifies keyword values too"
+ (is (= {"lib/type" "mbql/query"
+ "stages" [{"lib/type" "mbql.stage/mbql"}]}
+ (repr/external-query->portable
+ {:lib/type :mbql/query
+ :stages [{:lib/type :mbql.stage/mbql}]}))))
+ (testing "leaves string values untouched"
+ (is (= {"stages" [{"source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "aggregation" [["count" {}]]}]}
+ (repr/external-query->portable
+ {:stages [{:source-table ["Sample" "PUBLIC" "ORDERS"]
+ :aggregation [["count" {}]]}]}))))
+ (testing "preserves nil for schemaless table FK"
+ (is (= {"stages" [{"source-table" ["Mongo" nil "orders"]}]}
+ (repr/external-query->portable
+ {:stages [{:source-table ["Mongo" nil "orders"]}]})))))
+
+;;; ============================================================
+;;; validate-external-query
+;;; ============================================================
+
+(deftest validate-external-query-happy-path-test
+ (testing "valid external-query with string-valued enums"
+ (let [q {:lib/type "mbql/query"
+ :database "Sample"
+ :stages [{:lib/type "mbql.stage/mbql"
+ :source-table ["Sample" "PUBLIC" "ORDERS"]
+ :limit 5}]}
+ decoded (repr/validate-external-query q)]
+ (testing "string-transformer keywordizes enum values"
+ (is (= :mbql/query (:lib/type decoded))))
+ (testing "ID-typed strings stay as strings (substituted in ::external-query)"
+ (is (= "Sample" (:database decoded))))
+ (testing "portable FK vectors pass through unchanged"
+ (is (= ["Sample" "PUBLIC" "ORDERS"]
+ (get-in decoded [:stages 0 :source-table])))))))
+
+(deftest validate-external-query-error-paths-test
+ (testing "missing :stages"
+ (is (thrown-with-msg? clojure.lang.ExceptionInfo
+ #"invalid structure"
+ (repr/validate-external-query
+ {:lib/type "mbql/query"})))))
+
+;;; ============================================================
+;;; validate-query (post-repair, portable form)
+;;; ============================================================
+
+(defn- validate-query-error [parsed]
+ (try
+ (repr/validate-query parsed)
+ nil
+ (catch clojure.lang.ExceptionInfo e
+ (ex-data e))))
+
+(deftest validate-query-happy-path-test
+ (testing "minimal valid portable form"
+ (let [parsed {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "aggregation" [["count" {}]]}]}]
+ (is (= parsed (repr/validate-query parsed)))))
+ (testing "schemaless source-table (null schema)"
+ (let [parsed {"lib/type" "mbql/query"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Mongo" nil "orders"]
+ "aggregation" [["count" {}]]}]}]
+ (is (= parsed (repr/validate-query parsed))))))
+
+(deftest validate-query-error-paths-test
+ (testing "missing lib/type on query"
+ (let [parsed {"database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]}]}
+ data (validate-query-error parsed)]
+ (is (= :invalid-representations-query (:error data)))
+ (is (= 400 (:status-code data)))))
+ (testing "wrong lib/type value on query"
+ (is (some? (validate-query-error {"lib/type" "mbql/wrong"
+ "stages" [{"lib/type" "mbql.stage/mbql"}]}))))
+ (testing "empty stages"
+ (is (some? (validate-query-error {"lib/type" "mbql/query"
+ "stages" []}))))
+ (testing "table FK too short"
+ (is (some? (validate-query-error {"lib/type" "mbql/query"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC"]}]}))))
+ (testing "missing options map on a clause (nil in slot 1)"
+ (is (some? (validate-query-error {"lib/type" "mbql/query"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "aggregation" [["count" nil]]}]}))))
+ (testing "clause head must be a non-blank string"
+ (is (some? (validate-query-error {"lib/type" "mbql/query"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "aggregation" [["" {}]]}]})))))
diff --git a/test/metabase/agent_lib/runtime/fields_test.clj b/test/metabase/agent_lib/runtime/fields_test.clj
deleted file mode 100644
index 21c4fa71c98..00000000000
--- a/test/metabase/agent_lib/runtime/fields_test.clj
+++ /dev/null
@@ -1,211 +0,0 @@
-(ns metabase.agent-lib.runtime.fields-test
- (:require
- [clojure.test :refer [deftest is]]
- [metabase.agent-lib.mbql-integration :as mbql]
- [metabase.agent-lib.runtime.fields :as runtime.fields]
- [metabase.test :as mt]))
-
-(deftest resolve-field-in-query-prefers-chained-lineage-over-raw-exact-match-test
- (let [raw-field {:id 300 :table-id 30 :name "name" :base-type :type/Text}
- raw-exact {:id 300 :table-id 30 :name "name" :base-type :type/Text}
- source-column {:id 200 :table-id 20 :name "customer_id" :base-type :type/Integer}
- fields-by-id {200 {:id 200 :table-id 20 :fk-target-field-id 301}
- 301 {:id 301 :table-id 30}}
- resolved-field (mt/with-dynamic-fn-redefs [mbql/current-query-field-candidates
- (constantly [raw-exact source-column])]
- (runtime.fields/resolve-field-in-query fields-by-id ::query raw-field))]
- (is (= 300 (:id resolved-field)))
- (is (= 200 (:fk-field-id resolved-field)))
- (is (= "customer_id" (:fk-field-name resolved-field)))))
-
-(deftest resolve-field-in-query-preserves-upstream-lineage-when-chaining-related-fields-test
- (let [raw-field {:id 2455 :table-id 127 :name "first_name" :base-type :type/Text}
- source-column {:id 2488
- :table-id 133
- :name "customer_id"
- :lib/source-column-alias "customer_id"
- :base-type :type/Integer
- :fk-field-id 2503}
- fields-by-id {2503 {:id 2503 :table-id 116 :name "order_id" :fk-target-field-id 2499}
- 2499 {:id 2499 :table-id 133 :name "id"}
- 2488 {:id 2488 :table-id 133 :name "customer_id" :fk-target-field-id 2456}
- 2456 {:id 2456 :table-id 127 :name "id"}}
- resolved-field (mt/with-dynamic-fn-redefs [mbql/current-query-field-candidates
- (constantly [source-column])]
- (runtime.fields/resolve-field-in-query fields-by-id ::query raw-field))]
- (is (= 2455 (:id resolved-field)))
- (is (= 2488 (:fk-field-id resolved-field)))
- (is (= "customer_id" (:fk-field-name resolved-field)))
- (is (= 2503 (:lib/original-fk-field-id resolved-field)))))
-
-(deftest resolve-field-in-query-preserves-original-source-field-lineage-when-chaining-related-fields-test
- (let [raw-field {:id 2455 :table-id 127 :name "first_name" :base-type :type/Text}
- source-column {:id 2488
- :table-id 133
- :name "customer_id"
- :lib/source-column-alias "customer_id"
- :base-type :type/Integer
- :source-field 2503
- :source-field-name "order_id"}
- fields-by-id {2488 {:id 2488 :table-id 133 :fk-target-field-id 2456}
- 2456 {:id 2456 :table-id 127}}
- resolved-field (mt/with-dynamic-fn-redefs [mbql/current-query-field-candidates
- (constantly [source-column])]
- (runtime.fields/resolve-field-in-query fields-by-id ::query raw-field))]
- (is (= 2455 (:id resolved-field)))
- (is (= 2488 (:fk-field-id resolved-field)))
- (is (= "customer_id" (:fk-field-name resolved-field)))
- (is (= 2503 (:lib/original-fk-field-id resolved-field)))
- (is (= "order_id" (:lib/original-fk-field-name resolved-field)))))
-
-(deftest resolve-field-in-query-preserves-upstream-join-alias-when-chaining-related-fields-test
- (let [raw-field {:id 2455 :table-id 127 :name "first_name" :base-type :type/Text}
- source-column {:id 2488
- :table-id 133
- :name "customer_id"
- :base-type :type/Integer
- :fk-field-id 2503
- :fk-join-alias "order__via__order_id"}
- fields-by-id {2503 {:id 2503 :table-id 116 :fk-target-field-id 2499}
- 2499 {:id 2499 :table-id 133}
- 2488 {:id 2488 :table-id 133 :fk-target-field-id 2456}
- 2456 {:id 2456 :table-id 127}}
- resolved-field (mt/with-dynamic-fn-redefs [mbql/current-query-field-candidates
- (constantly [source-column])]
- (runtime.fields/resolve-field-in-query fields-by-id ::query raw-field))]
- (is (= "order__via__order_id" (:fk-join-alias resolved-field)))
- (is (= "order__via__order_id" (:lib/original-fk-join-alias resolved-field)))))
-
-(deftest resolve-field-in-query-prefers-chained-lineage-over-exact-partial-related-field-test
- (let [raw-field {:id 2455 :table-id 127 :name "first_name" :base-type :type/Text}
- exact-partial {:id 2455
- :table-id 127
- :name "first_name"
- :base-type :type/Text
- :source-field 2488
- :source-field-name "customer_id"}
- source-column {:id 2488
- :table-id 133
- :name "customer_id"
- :base-type :type/Integer
- :source-field 2503
- :source-field-name "order_id"
- :fk-join-alias "order__via__order_id"}
- fields-by-id {2503 {:id 2503 :table-id 116 :name "order_id" :fk-target-field-id 2499}
- 2499 {:id 2499 :table-id 133 :name "id"}
- 2488 {:id 2488 :table-id 133 :name "customer_id" :fk-target-field-id 2456}
- 2456 {:id 2456 :table-id 127 :name "id"}}
- resolved-field (mt/with-dynamic-fn-redefs [mbql/current-query-field-candidates
- (constantly [exact-partial source-column])]
- (runtime.fields/resolve-field-in-query fields-by-id ::query raw-field))]
- (is (= 2455 (:id resolved-field)))
- (is (= 2488 (:fk-field-id resolved-field)))
- (is (= "customer_id" (:fk-field-name resolved-field)))
- (is (= 2503 (:lib/original-fk-field-id resolved-field)))
- (is (= "order_id" (:lib/original-fk-field-name resolved-field)))
- (is (= "order__via__order_id" (:fk-join-alias resolved-field)))
- (is (= "order__via__order_id" (:lib/original-fk-join-alias resolved-field)))))
-
-(deftest resolve-field-in-query-prefers-previous-stage-column-over-raw-exact-match-test
- (let [raw-field {:id 282 :table-id 88 :name "utilization_percentage" :base-type :type/Decimal}
- raw-exact {:id 282 :table-id 88 :name "utilization_percentage" :base-type :type/Decimal}
- previous-stage {:name "utilization_percentage"
- :base-type :type/Decimal
- :effective-type :type/Decimal
- :lib/source :source/previous-stage}
- resolved-field (mt/with-dynamic-fn-redefs [mbql/current-query-field-candidates
- (constantly [raw-exact previous-stage])]
- (runtime.fields/resolve-field-in-query {} ::query raw-field))]
- (is (= previous-stage resolved-field))))
-
-(deftest resolve-field-in-query-prefers-previous-stage-name-match-test
- (let [raw-field {:id 468 :table-id 21 :name "name" :base-type :type/Text}
- previous-event-uri {:name "event_uri"
- :base-type :type/Text
- :effective-type :type/Text
- :lib/source :source/previous-stage}
- previous-name {:name "name"
- :base-type :type/Text
- :effective-type :type/Text
- :lib/source :source/previous-stage}
- resolved-field (mt/with-dynamic-fn-redefs [mbql/current-query-field-candidates
- (constantly [previous-event-uri previous-name])]
- (runtime.fields/resolve-field-in-query {} ::query raw-field))]
- (is (= previous-name resolved-field))))
-
-(deftest resolve-field-in-query-rejects-unrelated-previous-stage-numeric-column-test
- (let [raw-field {:id 282 :table-id 88 :name "total" :base-type :type/Decimal}
- previous-stage {:name "count"
- :base-type :type/Integer
- :effective-type :type/Integer
- :lib/source :source/previous-stage}]
- (is (thrown-with-msg? clojure.lang.ExceptionInfo
- #"not available in the current query stage"
- (mt/with-dynamic-fn-redefs [mbql/current-query-field-candidates
- (constantly [previous-stage])]
- (runtime.fields/resolve-field-in-query {} ::query raw-field))))))
-
-(deftest unavailable-field-error-enumerates-available-fields-test
- (let [raw-field {:id 999 :table-id 88 :name "not_there" :base-type :type/Text}
- candidate1 {:id 100 :table-id 10 :name "first_name" :base-type :type/Text}
- candidate2 {:id 101 :table-id 10 :name "last_name" :base-type :type/Text}]
- (try
- (with-redefs [mbql/current-query-field-candidates
- (constantly [candidate1 candidate2])]
- (runtime.fields/resolve-field-in-query {} ::query raw-field))
- (is false "expected ex-info to be thrown")
- (catch clojure.lang.ExceptionInfo e
- (let [msg (ex-message e)
- data (ex-data e)]
- (is (re-find #"first_name" msg))
- (is (re-find #"id=100" msg))
- (is (re-find #"last_name" msg))
- (is (= [{:id 100 :name "first_name" :table-id 10}
- {:id 101 :name "last_name" :table-id 10}]
- (:available-fields data))))))))
-
-(deftest unavailable-field-error-includes-join-alias-in-summary-test
- (let [raw-field {:id 999 :table-id 88 :name "not_there" :base-type :type/Text}
- candidate {:id 200 :table-id 20 :name "customer_id" :base-type :type/Integer
- :lib/join-alias "Customers"}]
- (try
- (with-redefs [mbql/current-query-field-candidates (constantly [candidate])]
- (runtime.fields/resolve-field-in-query {} ::query raw-field))
- (is false "expected ex-info to be thrown")
- (catch clojure.lang.ExceptionInfo e
- (let [msg (ex-message e)
- data (ex-data e)
- summary (first (:available-fields data))]
- (is (= "Customers" (:join-alias summary)))
- (is (re-find #"join-alias=\"Customers\"" msg)))))))
-
-(deftest unavailable-field-error-suppresses-listing-when-no-candidates-test
- (let [raw-field {:id 999 :table-id 88 :name "not_there" :base-type :type/Text}]
- (try
- (with-redefs [mbql/current-query-field-candidates (constantly [])]
- (runtime.fields/resolve-field-in-query {} ::query raw-field))
- (is false "expected ex-info to be thrown")
- (catch clojure.lang.ExceptionInfo e
- (let [msg (ex-message e)
- data (ex-data e)]
- (is (re-find #"No fields are visible in this stage" msg))
- (is (not (re-find #"Fields available in this stage" msg)))
- (is (= [] (:available-fields data))))))))
-
-(deftest unavailable-field-error-caps-listed-candidates-test
- (let [raw-field {:id 999 :table-id 88 :name "not_there" :base-type :type/Text}
- candidates (mapv (fn [i]
- {:id (+ 1000 i) :table-id 10
- :name (str "field_" i) :base-type :type/Text})
- (range 25))]
- (try
- (with-redefs [mbql/current-query-field-candidates (constantly candidates)]
- (runtime.fields/resolve-field-in-query {} ::query raw-field))
- (is false "expected ex-info to be thrown")
- (catch clojure.lang.ExceptionInfo e
- (let [msg (ex-message e)
- data (ex-data e)]
- ;; all candidates captured in ex-data
- (is (= 25 (count (:available-fields data))))
- ;; message truncates with an "and N more" line
- (is (re-find #"and 5 more" msg)))))))
diff --git a/test/metabase/agent_lib/runtime/lookup_test.clj b/test/metabase/agent_lib/runtime/lookup_test.clj
deleted file mode 100644
index 8ba9a5708e9..00000000000
--- a/test/metabase/agent_lib/runtime/lookup_test.clj
+++ /dev/null
@@ -1,71 +0,0 @@
-(ns metabase.agent-lib.runtime.lookup-test
- (:require
- [clojure.test :refer [deftest is testing]]
- [metabase.agent-lib.runtime.bindings :as runtime.bindings]
- [metabase.agent-lib.runtime.fields :as runtime.fields]
- [metabase.agent-lib.runtime.lookup :as runtime.lookup]
- [metabase.agent-lib.test-util :as agent-lib.tu]
- [metabase.lib.core :as lib]
- [metabase.lib.metadata :as lib.metadata]
- [metabase.lib.test-metadata :as meta]))
-
-(defn- lookup-env
- []
- (let [metadata-provider meta/metadata-provider
- all-table-ids (map :id (lib.metadata/tables metadata-provider))
- tables-by-name (runtime.fields/build-table-lookup metadata-provider all-table-ids)
- {:keys [fields-by-table fields-by-id]}
- (runtime.fields/build-field-lookups metadata-provider tables-by-name)]
- {:metadata-provider metadata-provider
- :tables-by-name tables-by-name
- :fields-by-table fields-by-table
- :fields-by-id fields-by-id}))
-
-(deftest ^:parallel lookup-table-resolves-by-id-and-name-test
- (let [{:keys [metadata-provider tables-by-name]} (lookup-env)
- by-name (runtime.lookup/lookup-table metadata-provider tables-by-name "ORDERS")
- by-id (runtime.lookup/lookup-table metadata-provider tables-by-name (:id by-name))]
- (is (= (:id by-name) (:id by-id)))
- (is (= (meta/id :orders) (:id by-name)))))
-
-(deftest ^:parallel lookup-field-rejects-ambiguous-name-test
- (let [{:keys [metadata-provider tables-by-name fields-by-table fields-by-id]} (lookup-env)]
- (is (thrown-with-msg?
- clojure.lang.ExceptionInfo
- #"Ambiguous field"
- (runtime.lookup/lookup-field metadata-provider
- tables-by-name
- fields-by-table
- fields-by-id
- "id")))))
-
-(deftest ^:parallel query-relative-field-prefers-current-query-columns-test
- (let [{:keys [metadata-provider tables-by-name fields-by-table fields-by-id]} (lookup-env)
- query (-> (agent-lib.tu/query-for-table :orders)
- (lib/breakout (meta/field-metadata :orders :product-id)))
- raw-field (meta/field-metadata :orders :product-id)
- resolved (runtime.lookup/query-relative-field metadata-provider
- tables-by-name
- fields-by-table
- fields-by-id
- query
- "orders"
- "PRODUCT_ID")]
- (is (= (:id raw-field) (:id resolved)))
- (is (:lib/source resolved))))
-
-(deftest ^:parallel make-context-bindings-composes-lookup-and-transform-helpers-test
- (let [{:keys [metadata-provider tables-by-name fields-by-table fields-by-id]} (lookup-env)
- bindings (runtime.bindings/make-context-bindings metadata-provider
- tables-by-name
- fields-by-table
- fields-by-id)]
- (testing "lookup bindings"
- (is (= (meta/id :orders)
- (:id ((get bindings 'table) "orders"))))
- (is (= (meta/id :orders :id)
- (:id ((get bindings 'field) "orders" "id")))))
- (testing "transform bindings"
- (is (contains? bindings 'breakout))
- (is (contains? bindings 'order-by))
- (is (contains? bindings 'query)))))
diff --git a/test/metabase/agent_lib/runtime/transforms_test.clj b/test/metabase/agent_lib/runtime/transforms_test.clj
deleted file mode 100644
index 90d8e83c2c1..00000000000
--- a/test/metabase/agent_lib/runtime/transforms_test.clj
+++ /dev/null
@@ -1,52 +0,0 @@
-(ns metabase.agent-lib.runtime.transforms-test
- (:require
- [clojure.test :refer [deftest is testing]]
- [metabase.agent-lib.runtime.transforms :as runtime.transforms]
- [metabase.agent-lib.test-util :as agent-lib.tu]
- [metabase.lib.core :as lib]
- [metabase.lib.test-metadata :as meta]
- [metabase.lib.util :as lib.util]))
-
-(deftest ^:parallel order-wrapper-helpers-test
- (is (runtime.transforms/order-wrapper? (runtime.transforms/asc-orderable :x)))
- (is (runtime.transforms/order-wrapper? (runtime.transforms/desc-orderable :x)))
- (is (not (runtime.transforms/order-wrapper? :x))))
-
-(deftest ^:parallel apply-breakout-materializes-expression-ref-test
- (let [query (agent-lib.tu/query-for-table :orders)
- expr (lib/get-hour (meta/field-metadata :orders :created-at))
- expected (-> query
- (lib/expression "__breakout_expression_1" expr)
- ((fn [query']
- (lib/breakout query' (lib/expression-ref query' "__breakout_expression_1")))))
- actual (runtime.transforms/apply-breakout query expr)]
- (is (= (agent-lib.tu/comparable-query expected)
- (agent-lib.tu/comparable-query actual)))))
-
-(deftest ^:parallel apply-with-fields-breaks-out-raw-fields-on-aggregated-query-test
- (let [query (-> (agent-lib.tu/query-for-table :orders)
- (lib/aggregate (lib/count)))
- selection (meta/field-metadata :orders :id)
- expected (lib/breakout query selection)
- actual (runtime.transforms/apply-with-fields query [selection])]
- (is (= (agent-lib.tu/comparable-query expected)
- (agent-lib.tu/comparable-query actual)))))
-
-(deftest ^:parallel apply-order-by-supports-direction-wrappers-test
- (let [query (agent-lib.tu/query-for-table :orders)
- field (meta/field-metadata :orders :created-at)
- expected (lib/order-by query (lib.util/fresh-uuids field) :desc)
- actual (runtime.transforms/apply-order-by query
- (runtime.transforms/desc-orderable field))]
- (is (= (agent-lib.tu/comparable-query expected)
- (agent-lib.tu/comparable-query actual)))))
-
-(deftest ^:parallel query-transform-bindings-expose-all-transform-helpers-test
- (let [bindings (runtime.transforms/query-transform-bindings)]
- (testing "all extracted transform helpers are reachable through the binding map"
- (is (contains? bindings 'asc))
- (is (contains? bindings 'desc))
- (is (contains? bindings 'breakout))
- (is (contains? bindings 'filter))
- (is (contains? bindings 'with-fields))
- (is (contains? bindings 'order-by)))))
diff --git a/test/metabase/agent_lib/schema/top_level_test.clj b/test/metabase/agent_lib/schema/top_level_test.clj
deleted file mode 100644
index 9db47cc241a..00000000000
--- a/test/metabase/agent_lib/schema/top_level_test.clj
+++ /dev/null
@@ -1,30 +0,0 @@
-(ns metabase.agent-lib.schema.top-level-test
- (:require
- [clojure.test :refer [deftest is testing]]
- [metabase.agent-lib.capabilities.catalog.top-level :as capabilities.top-level]
- [metabase.agent-lib.schema :as schema]))
-
-(def ^:private sample-operations
- {"filter" ["filter" ["=" ["field" 1] 1]]
- "aggregate" ["aggregate" ["count"]]
- "breakout" ["breakout" ["field" 1]]
- "with-fields" ["with-fields" [["field" 1]]]
- "limit" ["limit" 10]
- "expression" ["expression" "Net Amount" ["+" ["field" 1] 1]]
- "join" ["join" ["join-clause" ["table" 2]]]
- "order-by" ["order-by" ["field" 1] "desc"]
- "append-stage" ["append-stage"]
- "drop-stage" ["drop-stage"]
- "drop-empty-stages" ["drop-empty-stages"]
- "with-page" ["with-page" {:page 2 :items 25}]})
-
-(deftest ^:parallel top-level-capability-catalog-and-schema-samples-stay-in-sync-test
- (let [capability-ops (mapv (comp name :op) capabilities.top-level/capabilities)]
- (is (= (set capability-ops)
- (set (keys sample-operations))))
- (doseq [op-name capability-ops]
- (testing op-name
- (let [program {:source {:type "table" :id 1}
- :operations [(get sample-operations op-name)]}]
- (is (= program
- (schema/validated-structure program))))))))
diff --git a/test/metabase/agent_lib/syntax_test.clj b/test/metabase/agent_lib/syntax_test.clj
deleted file mode 100644
index 579d24ecb73..00000000000
--- a/test/metabase/agent_lib/syntax_test.clj
+++ /dev/null
@@ -1,103 +0,0 @@
-(ns metabase.agent-lib.syntax-test
- (:require
- [clojure.test :refer [deftest is testing]]
- [metabase.agent-lib.syntax :as syntax]))
-
-(deftest ^:parallel raw-op-name-test
- (testing "returns string for strings"
- (is (= "filter" (syntax/raw-op-name "filter"))))
- (testing "returns name for keywords"
- (is (= "filter" (syntax/raw-op-name :filter))))
- (testing "returns name for symbols"
- (is (= "filter" (syntax/raw-op-name 'filter))))
- (testing "returns nil for other types"
- (is (nil? (syntax/raw-op-name nil)))
- (is (nil? (syntax/raw-op-name 42)))
- (is (nil? (syntax/raw-op-name [])))))
-
-(deftest ^:parallel canonical-op-name-test
- (testing "resolves aliases to canonical names"
- (is (= "case" (syntax/canonical-op-name "if")))
- (is (= "var" (syntax/canonical-op-name "variance")))
- (is (= "relative-datetime" (syntax/canonical-op-name "relative-date")))
- (is (= "datetime-diff" (syntax/canonical-op-name "temporal-diff")))
- (is (= "count-where" (syntax/canonical-op-name "count-if")))
- (is (= "distinct" (syntax/canonical-op-name "count-distinct")))
- (is (= "distinct" (syntax/canonical-op-name "distinct-count")))
- (is (= "not-null" (syntax/canonical-op-name "is-not-null")))
- (is (= "get-day-of-week" (syntax/canonical-op-name "dayofweek")))
- (is (= "get-day-of-week" (syntax/canonical-op-name "day-of-week")))
- (is (= "get-hour" (syntax/canonical-op-name "hour-of-day")))
- (is (= "get-month" (syntax/canonical-op-name "month-of-year")))
- (is (= "get-quarter" (syntax/canonical-op-name "quarter-of-year"))))
- (testing "passes through canonical names unchanged"
- (is (= "filter" (syntax/canonical-op-name "filter")))
- (is (= "count" (syntax/canonical-op-name "count"))))
- (testing "works with keywords and symbols"
- (is (= "case" (syntax/canonical-op-name :if)))
- (is (= "var" (syntax/canonical-op-name 'variance))))
- (testing "returns nil for nil"
- (is (nil? (syntax/canonical-op-name nil)))))
-
-(deftest ^:parallel op-symbol-test
- (testing "normalizes to canonical symbol"
- (is (= 'case (syntax/op-symbol "if")))
- (is (= 'var (syntax/op-symbol "variance")))
- (is (= 'filter (syntax/op-symbol "filter"))))
- (testing "works with keywords and symbols"
- (is (= 'case (syntax/op-symbol :if)))
- (is (= 'filter (syntax/op-symbol 'filter))))
- (testing "returns nil for nil"
- (is (nil? (syntax/op-symbol nil)))))
-
-(deftest ^:parallel possible-operator-tuple-test
- (testing "true for recognized operator tuples"
- (is (true? (syntax/possible-operator-tuple? ["filter" ["=" ["field" 1] 2]])))
- (is (true? (syntax/possible-operator-tuple? ["count"])))
- (is (true? (syntax/possible-operator-tuple? ["aggregate" ["count"]]))))
- (testing "true for alias operators"
- (is (true? (syntax/possible-operator-tuple? ["if" true 1 0])))
- (is (true? (syntax/possible-operator-tuple? ["variance" ["field" 1]]))))
- (testing "false for non-vectors"
- (is (false? (syntax/possible-operator-tuple? "filter")))
- (is (false? (syntax/possible-operator-tuple? {:op "filter"}))))
- (testing "false for unrecognized operators"
- (is (false? (syntax/possible-operator-tuple? ["bogus-op" 1 2])))))
-
-(deftest ^:parallel boolean-wrapper-form-test
- (testing "true for boolean wrappers"
- (is (true? (syntax/boolean-wrapper-form? ["true" ["field" 1]])))
- (is (true? (syntax/boolean-wrapper-form? ["false" ["field" 1]])))
- (is (true? (syntax/boolean-wrapper-form? ["TRUE" ["field" 1]]))))
- (testing "false for wrong arity"
- (is (false? (syntax/boolean-wrapper-form? ["true"])))
- (is (false? (syntax/boolean-wrapper-form? ["true" 1 2]))))
- (testing "false for non-boolean strings"
- (is (false? (syntax/boolean-wrapper-form? ["maybe" ["field" 1]]))))
- (testing "false for non-vectors"
- (is (false? (syntax/boolean-wrapper-form? "true")))))
-
-(deftest ^:parallel top-level-operation-tuple-test
- (testing "true for top-level operations"
- (is (true? (syntax/top-level-operation-tuple? ["filter" ["=" ["field" 1] 2]])))
- (is (true? (syntax/top-level-operation-tuple? ["aggregate" ["count"]])))
- (is (true? (syntax/top-level-operation-tuple? ["breakout" ["field" 1]])))
- (is (true? (syntax/top-level-operation-tuple? ["order-by" ["field" 1]])))
- (is (true? (syntax/top-level-operation-tuple? ["limit" 10]))))
- (testing "false for nested-only operators"
- (is (false? (syntax/top-level-operation-tuple? ["=" ["field" 1] 2])))
- (is (false? (syntax/top-level-operation-tuple? ["field" 1])))
- (is (false? (syntax/top-level-operation-tuple? ["count"])))))
-
-(deftest ^:parallel operator-tuple-test
- (testing "true for recognized string-led operator tuples"
- (is (true? (syntax/operator-tuple? ["count"])))
- (is (true? (syntax/operator-tuple? ["field" 1])))
- (is (true? (syntax/operator-tuple? ["=" ["field" 1] 2]))))
- (testing "false for non-string first element"
- (is (false? (syntax/operator-tuple? [:count])))
- (is (false? (syntax/operator-tuple? [42]))))
- (testing "false for unrecognized operators"
- (is (false? (syntax/operator-tuple? ["bogus" 1 2]))))
- (testing "false for non-vectors"
- (is (false? (syntax/operator-tuple? "count")))))
diff --git a/test/metabase/agent_lib/test_util.clj b/test/metabase/agent_lib/test_util.clj
deleted file mode 100644
index 306e24b34f4..00000000000
--- a/test/metabase/agent_lib/test_util.clj
+++ /dev/null
@@ -1,110 +0,0 @@
-(ns metabase.agent-lib.test-util
- (:require
- [metabase.lib.aggregation :as lib.aggregation]
- [metabase.lib.core :as lib]
- [metabase.lib.schema.util :as lib.schema.util]
- [metabase.lib.test-metadata :as meta]
- [metabase.lib.util :as lib.util]
- [metabase.util :as u]))
-
-(defn entity-summary
- [table-name]
- {:model "table"
- :id (meta/id table-name)
- :columns (mapv (fn [field-name]
- {:id (meta/id table-name field-name)})
- (meta/fields table-name))})
-
-(defn table-context
- [table-name & surrounding-table-names]
- {:source-entity (entity-summary table-name)
- :source-metadata (meta/table-metadata table-name)
- :referenced-entities []
- :referenced-metadata []
- :surrounding-tables (mapv entity-summary surrounding-table-names)
- :surrounding-table-metadata (mapv meta/table-metadata surrounding-table-names)
- :join-edges []})
-
-(defn table-context-with-join-edges
- [table-name surrounding-table-names join-edges]
- {:source-entity (entity-summary table-name)
- :source-metadata (meta/table-metadata table-name)
- :referenced-entities []
- :referenced-metadata []
- :surrounding-tables (mapv entity-summary surrounding-table-names)
- :surrounding-table-metadata (mapv meta/table-metadata surrounding-table-names)
- :join-edges join-edges})
-
-(defn join-edge
- [from-table from-field to-table to-field]
- {:from_table_id (meta/id from-table)
- :from_field_id (meta/id from-table from-field)
- :to_table_id (meta/id to-table)
- :to_field_id (meta/id to-table to-field)})
-
-(defn query-for-table
- [table-name]
- (lib/query meta/metadata-provider (meta/table-metadata table-name)))
-
-(defn comparable-query
- [query]
- {:database (:database query)
- :legacy (-> query
- lib/->legacy-MBQL
- lib.schema.util/remove-lib-uuids)})
-
-(defn current-query-column
- [query field-id]
- (or (some #(when (= field-id (:id %)) %)
- (distinct
- (concat (lib/visible-columns query)
- (lib/filterable-columns query)
- (lib/breakoutable-columns query)
- (lib/orderable-columns query))))
- (throw (ex-info "Expected field to be available in query context"
- {:field-id field-id
- :query query}))))
-
-(defn current-query-column-by-name
- [query column-name]
- (let [normalized-column-name (u/lower-case-en column-name)]
- (or (some (fn [column]
- (when (contains? (->> [(:name column)
- (:lib/source-column-alias column)
- (:lib/ref-name column)]
- (keep identity)
- (map u/lower-case-en)
- set)
- normalized-column-name)
- column))
- (distinct
- (concat (lib/returned-columns query)
- (lib/visible-columns query)
- (lib/filterable-columns query)
- (lib/breakoutable-columns query)
- (lib/orderable-columns query))))
- (throw (ex-info "Expected named column to be available in query context"
- {:column-name column-name
- :query query})))))
-
-(defn previous-stage-aggregation-column
- [query ag-index]
- (let [previous-stage-number (lib.util/previous-stage-number query -1)
- source-uuid (:lib/source-uuid
- (get (vec (lib.aggregation/aggregations-metadata query previous-stage-number))
- ag-index))
- candidate-columns (concat (lib/filterable-columns query)
- (lib/orderable-columns query)
- (lib/visible-columns query))]
- (or (some #(when (= source-uuid (:lib/source-uuid %)) %) candidate-columns)
- (throw (ex-info "Expected a previous-stage aggregation column"
- {:query query
- :aggregation-index ag-index})))))
-
-(defn current-aggregation-orderable
- [query ag-index]
- (or (lib/find-matching-column query
- -1
- (lib/aggregation-ref query ag-index)
- (lib/orderable-columns query))
- (lib/aggregation-ref query ag-index)))
diff --git a/test/metabase/agent_lib/validate/cross_checks_test.clj b/test/metabase/agent_lib/validate/cross_checks_test.clj
deleted file mode 100644
index 7e8bd08f511..00000000000
--- a/test/metabase/agent_lib/validate/cross_checks_test.clj
+++ /dev/null
@@ -1,58 +0,0 @@
-(ns metabase.agent-lib.validate.cross-checks-test
- (:require
- [clojure.test :refer [deftest is testing]]
- [metabase.agent-lib.validate.cross-checks :as cross-checks]))
-
-(deftest validate-no-metric-order-by-test
- (testing "rejects metric helper inside order-by"
- (let [error (try
- (cross-checks/validate-no-metric-order-by!
- [:operations 0]
- ["order-by" ["metric" 42]])
- nil
- (catch clojure.lang.ExceptionInfo e e))]
- (is error)
- (is (= :invalid-generated-program (:error (ex-data error))))
- (is (re-find #"metric helpers cannot be used directly inside order-by"
- (:details (ex-data error))))))
- (testing "accepts field inside order-by"
- (is (nil? (cross-checks/validate-no-metric-order-by!
- [:operations 0]
- ["order-by" ["field" 1]]))))
- (testing "ignores non-order-by operations"
- (is (nil? (cross-checks/validate-no-metric-order-by!
- [:operations 0]
- ["filter" ["metric" 42]])))))
-
-(deftest validate-no-source-metric-reuse-test
- (testing "rejects reuse of source metric id"
- (let [context {:source-entity {:model "metric" :id 42}
- :referenced-entities []
- :surrounding-tables []}
- error (try
- (cross-checks/validate-no-source-metric-reuse!
- context
- [:operations 0]
- ["aggregate" ["metric" 42]])
- nil
- (catch clojure.lang.ExceptionInfo e e))]
- (is error)
- (is (= :invalid-generated-program (:error (ex-data error))))
- (is (re-find #"source is already metric 42"
- (:details (ex-data error))))))
- (testing "accepts different metric id"
- (let [context {:source-entity {:model "metric" :id 42}
- :referenced-entities []
- :surrounding-tables []}]
- (is (nil? (cross-checks/validate-no-source-metric-reuse!
- context
- [:operations 0]
- ["aggregate" ["metric" 99]])))))
- (testing "no-op for table sources"
- (let [context {:source-entity {:model "table" :id 1}
- :referenced-entities []
- :surrounding-tables []}]
- (is (nil? (cross-checks/validate-no-source-metric-reuse!
- context
- [:operations 0]
- ["aggregate" ["metric" 42]]))))))
diff --git a/test/metabase/agent_lib/validate/operators_test.clj b/test/metabase/agent_lib/validate/operators_test.clj
deleted file mode 100644
index 2b9ca9bcd24..00000000000
--- a/test/metabase/agent_lib/validate/operators_test.clj
+++ /dev/null
@@ -1,54 +0,0 @@
-(ns metabase.agent-lib.validate.operators-test
- (:require
- [clojure.test :refer [deftest is]]
- [metabase.agent-lib.validate.operators :as operators]))
-
-(deftest ensure-arity-rejects-invalid-expression-reference-arity-test
- (try
- (operators/ensure-arity! [:operations 0] 'expression 1)
- (is false "expected invalid expression arity")
- (catch clojure.lang.ExceptionInfo e
- (is (= :invalid-generated-program (:error (ex-data e))))
- (is (re-find #"top-level operation" (:details (ex-data e)))))))
-
-(deftest validate-operator-specific-rejects-bare-field-ids-in-aggregations-test
- (try
- (operators/validate-operator-specific! {:table-ids #{}
- :card-ids #{}
- :metric-ids #{}
- :measure-ids #{}
- :field-ids #{}}
- {:source-entity {:model "table" :id 1}}
- [:operations 0 1]
- ["sum" 42])
- (is false "expected bare field id validation failure")
- (catch clojure.lang.ExceptionInfo e
- (is (= :invalid-generated-program (:error (ex-data e))))
- (is (= :field-wrapper (:retry-category (ex-data e)))))))
-
-(deftest validate-operator-specific-rejects-source-metric-as-measure-test
- (try
- (operators/validate-operator-specific! {:table-ids #{}
- :card-ids #{}
- :metric-ids #{}
- :measure-ids #{118}
- :field-ids #{}}
- {:source-entity {:model "metric" :id 118}}
- [:operations 0 1]
- ["measure" 118])
- (is false "expected source-metric measure validation failure")
- (catch clojure.lang.ExceptionInfo e
- (is (= :invalid-generated-program (:error (ex-data e))))
- (is (re-find #"Metric ids are not measure ids" (:details (ex-data e)))))))
-
-(deftest validate-top-level-operation-rejects-non-aggregation-aggregate-args-test
- (try
- (operators/validate-top-level-operation! (fn [path arg depth state]
- (assoc state :visited [path arg depth]))
- [:operations 0]
- ["aggregate" ["field" 10]]
- {:node-count 0})
- (is false "expected aggregate validation failure")
- (catch clojure.lang.ExceptionInfo e
- (is (= :invalid-generated-program (:error (ex-data e))))
- (is (re-find #"require aggregation helpers" (:details (ex-data e)))))))
diff --git a/test/metabase/agent_lib/validate/semantic_test.clj b/test/metabase/agent_lib/validate/semantic_test.clj
deleted file mode 100644
index 52a05ac9184..00000000000
--- a/test/metabase/agent_lib/validate/semantic_test.clj
+++ /dev/null
@@ -1,39 +0,0 @@
-(ns metabase.agent-lib.validate.semantic-test
- (:require
- [clojure.test :refer [deftest is testing]]
- [metabase.agent-lib.test-util :as tu]
- [metabase.agent-lib.validate.semantic :as semantic]))
-
-(deftest ^:parallel validate-program-passes-valid-program-test
- (testing "valid program passes through unchanged"
- (let [program {:source {:type "context" :ref "source"}
- :operations [["filter" ["=" ["field" 1] "hello"]]
- ["limit" 10]]}
- context (tu/table-context :orders)]
- (is (= program (semantic/validate-program program context))))))
-
-(deftest validate-program-rejects-unknown-table-source-test
- (testing "unknown table source raises invalid-generated-program"
- (let [program {:source {:type "table" :id 999999}
- :operations [["limit" 10]]}
- context (tu/table-context :orders)
- error (try
- (semantic/validate-program program context)
- nil
- (catch clojure.lang.ExceptionInfo e e))]
- (is error)
- (is (= :invalid-generated-program (:error (ex-data error)))))))
-
-(deftest validate-program-rejects-metric-in-order-by-test
- (testing "metric helper inside order-by is rejected"
- (let [program {:source {:type "context" :ref "source"}
- :operations [["order-by" ["metric" 42]]]}
- context (tu/table-context :orders)
- error (try
- (semantic/validate-program program context)
- nil
- (catch clojure.lang.ExceptionInfo e e))]
- (is error)
- (is (= :invalid-generated-program (:error (ex-data error))))
- (is (re-find #"metric helpers cannot be used directly inside order-by"
- (:details (ex-data error)))))))
diff --git a/test/metabase/agent_lib/validate_test.clj b/test/metabase/agent_lib/validate_test.clj
deleted file mode 100644
index 91bb23f414a..00000000000
--- a/test/metabase/agent_lib/validate_test.clj
+++ /dev/null
@@ -1,44 +0,0 @@
-(ns metabase.agent-lib.validate-test
- (:require
- [clojure.test :refer [deftest is]]
- [metabase.agent-lib.validate :as validate]))
-
-(deftest ^:parallel validate-program-inserts-append-stage-for-context-metric-source-test
- (let [program {:source {:type "context" :ref "source"}
- :operations [["aggregate" ["avg" ["aggregation-ref" 0]]]]}
- context {:source-entity {:model "metric" :id 42}
- :source-metadata nil
- :referenced-entities []
- :surrounding-tables []
- :measure-ids []}
- expected {:source {:type "context" :ref "source"}
- :operations [["append-stage"]
- ["aggregate" ["avg" ["aggregation-ref" 0]]]]}]
- (is (= expected (validate/validated-program program context)))))
-
-(deftest ^:parallel validate-program-inserts-append-stage-for-expression-over-aggregation-ref-test
- (let [program {:source {:type "context" :ref "source"}
- :operations [["expression" "Churn Rate" ["*" ["aggregation-ref" 0] 100]]]}
- context {:source-entity {:model "metric" :id 42}
- :source-metadata nil
- :referenced-entities []
- :surrounding-tables []
- :measure-ids []}
- expected {:source {:type "context" :ref "source"}
- :operations [["append-stage"]
- ["expression" "Churn Rate" ["*" ["aggregation-ref" 0] 100]]]}]
- (is (= expected (validate/validated-program program context)))))
-
-(deftest ^:parallel metric-source-measure-guidance-test
- (let [program {:source {:type "context" :ref "source"}
- :operations [["aggregate" ["avg" ["measure" 118]]]]}
- context {:source-entity {:model "metric" :id 118}
- :referenced-entities []
- :surrounding-tables []
- :measure-ids []}]
- (try
- (validate/validated-program program context)
- (is false "expected metric/measure validation to fail")
- (catch clojure.lang.ExceptionInfo e
- (is (= :invalid-generated-program (:error (ex-data e))))
- (is (re-find #"Metric ids are not measure ids" (:details (ex-data e))))))))
diff --git a/test/metabase/mcp/api_test.clj b/test/metabase/mcp/api_test.clj
index aee7a2fe647..624553d5bb2 100644
--- a/test/metabase/mcp/api_test.clj
+++ b/test/metabase/mcp/api_test.clj
@@ -1,6 +1,5 @@
(ns metabase.mcp.api-test
(:require
- [clojure.java.io :as io]
[clojure.string :as str]
[clojure.test :refer :all]
[clojure.walk :as walk]
@@ -118,10 +117,7 @@
(defn- call-tool
"Call an MCP tool within an initialized session. Returns the parsed MCP result
content (the JSON-decoded text from the first content block).
- Records test failures if the response status is not 200 or the tool returns an error.
- Also enforces the MCP spec contract: every successful tool result with content
- must include `structuredContent` (because every tool in our manifest declares
- `outputSchema`, and the spec mandates structuredContent for those)."
+ Records test failures if the response status is not 200 or the tool returns an error."
[session-id tool-name arguments]
(let [response (mcp-request (jsonrpc-request "tools/call"
{:name tool-name :arguments arguments})
@@ -339,47 +335,20 @@
(is (= "string" (get-in (array-branch (property-schema "search" "term_queries")) [:items :type])))
(is (contains? (leaf-types (property-schema "search" "semantic_queries")) "array"))
(is (= "string" (get-in (array-branch (property-schema "search" "semantic_queries")) [:items :type])))))
- (testing "construct_query exposes the nullable user prompt"
+ (testing "construct_query expects the portable external-query JSON body"
(let [tools-by-name (into {} (map (juxt :name identity)) tools)
construct-query-tool (get tools-by-name "construct_query")
construct-query-schema (:inputSchema construct-query-tool)
- prompt-schema (or (get-in construct-query-schema [:properties "prompt"])
- (get-in construct-query-schema [:properties :prompt]))
+ query-schema (or (get-in construct-query-schema [:properties "query"])
+ (get-in construct-query-schema [:properties :query]))
required-fields (set (:required construct-query-schema))
- schema-keys (atom #{})
- reference (slurp (io/resource "metabase/agent_api/construct_query.md"))]
- (walk/postwalk (fn [x]
- (when (map? x)
- (swap! schema-keys into (keys x)))
- x)
- construct-query-schema)
- (is (str/includes? (:description construct-query-tool) "include `\"prompt\""))
- ;; Strict-tool-input-schema forces every property into :required and
- ;; converts previously-optional ones (like :prompt) to nullable unions.
- (is (or (contains? required-fields "prompt")
- (contains? required-fields :prompt)))
- (is (= false (:additionalProperties construct-query-schema)))
- ;; Prompt is nullable. Either a `:type` union (hand-written form) or an
- ;; `:anyOf`/`:oneOf` with a {:type "null"} branch (Malli `[:maybe …]`).
- (is (or (= ["string" "null"] (:type prompt-schema))
- (= #{"string" "null"} (set (:type prompt-schema)))
- (some #(= "null" (:type %)) (:anyOf prompt-schema))
- (some #(= "null" (:type %)) (:oneOf prompt-schema))))
- ;; ChatGPT's MCP validator rejects exactly these JSON-Schema constructs.
- ;; `:oneOf`/`:minLength`/`:maxLength` are accepted by ChatGPT and not asserted against.
- (is (empty? (select-keys (frequencies @schema-keys)
- [:allOf :prefixItems])))
- ;; `items: false` (tuple closure) must not appear either.
- (is (not (some #(false? (:items %))
- (->> (tree-seq coll? seq construct-query-schema)
- (filter map?)))))
- (is (str/includes? (or (:description prompt-schema)
- (some :description (:anyOf prompt-schema))
- (some :description (:oneOf prompt-schema))
- "")
- "exact original message"))
- (is (str/includes? reference "MCP clients should include it whenever they have the user's message"))
- (is (str/includes? reference "{\"query_handle\": \"<uuid>\"}")))))))
+ ;; ::lib.schema/external-query is generated as a deeply-nested :allOf, so the
+ ;; root :type tag lives under the first branch rather than the top level.
+ query-leaf-type (or (:type query-schema)
+ (some :type (:allOf query-schema)))]
+ (is (str/includes? (:description construct-query-tool) "construct_notebook_query"))
+ (is (contains? required-fields "query"))
+ (is (= "object" query-leaf-type)))))))
(deftest ping-test
(testing "ping returns empty result"
@@ -672,6 +641,11 @@
:dataset_query (orders-count-query)}]
(let [[session-id _] (initialize!)
orders-id (mt/id :orders)
+ db-name (t2/select-one-fn :name :model/Database (mt/id))
+ orders-query {:lib/type "mbql/query"
+ :stages [{:lib/type "mbql.stage/mbql"
+ :source-table [db-name "PUBLIC" "ORDERS"]
+ :limit 5}]}
;; Track write-tool outputs in atoms so the `finally` cleanup runs even if an
;; assertion in `call-tool` fails partway through the sequence.
question-id (atom nil)
@@ -688,13 +662,8 @@
{:id (:id metric) :field-id (str metric-fid)})
_ (call-tool session-id "search" {:term_queries ["orders"]})
;; Query construction + execution
- construct-data (call-tool session-id "construct_query"
- {:source {:type "table" :id orders-id}
- :operations [["limit" 5]]
- :prompt "show 5 orders"})
- _ (call-tool session-id "query"
- {:source {:type "table" :id orders-id}
- :operations [["limit" 5]]})
+ construct-data (call-tool session-id "construct_query" {:query orders-query})
+ _ (call-tool session-id "query" {:query orders-query})
_ (call-tool session-id "execute_query"
{:query_handle (:query_handle construct-data)})
;; Write tools — record IDs as soon as they're known so the `finally` block
@@ -729,10 +698,12 @@
(reset! streamed? true)
(original-fn response))]
(let [[session-id _] (initialize!)
- construct-data (call-tool session-id "construct_query"
- {:source {:type "table" :id (mt/id :orders)}
- :operations [["limit" 5]]
- :prompt "show 5 orders"})
+ db-name (t2/select-one-fn :name :model/Database (mt/id))
+ external-query {:lib/type "mbql/query"
+ :stages [{:lib/type "mbql.stage/mbql"
+ :source-table [db-name "PUBLIC" "ORDERS"]
+ :limit 5}]}
+ construct-data (call-tool session-id "construct_query" {:query external-query})
execute-data (call-tool session-id "execute_query"
{:query_handle (:query_handle construct-data)})]
(is (true? @streamed?) "execute_query should use the streaming response path")
@@ -791,11 +762,20 @@
{"mcp-session-id" session-id})))))
(testing "visualize_query includes the prompt stored with a construct_query handle"
+ ;; Mirrors master's assertion that the user's original prompt round-trips through the
+ ;; construct→store→visualize flow so the iframe can include it when submitting
+ ;; visualization feedback. Adapted from master's `:source`/`:operations` shape to our
+ ;; branch's `:query` representations shape; the `:prompt` round-trip semantic is
+ ;; preserved exactly.
(let [[session-id _] (initialize!)
+ db-name (t2/select-one-fn :name :model/Database (mt/id))
+ external-query {:lib/type "mbql/query"
+ :stages [{:lib/type "mbql.stage/mbql"
+ :source-table [db-name "PUBLIC" "ORDERS"]
+ :limit 5}]}
construct-data (call-tool session-id "construct_query"
- {:source {:type "table" :id (mt/id :orders)}
- :operations [["limit" 5]]
- :prompt "show 5 orders"})
+ {:query external-query
+ :prompt "show 5 orders"})
response (mcp-request (jsonrpc-request "tools/call"
{:name "visualize_query"
:arguments {:query_handle (:query_handle construct-data)}})
@@ -851,11 +831,18 @@
(deftest construct-query-returns-bare-handle-test
(testing "construct_query returns just `{:query_handle uuid}` — no widget session plumbing"
+ ;; Adapted from master's `:source`/`:operations` legacy program shape to our branch's
+ ;; representations `:query` shape. The semantic — that the response is a bare handle
+ ;; with no widgetSessionId field — is preserved.
(let [[session-id _] (initialize!)
+ db-name (t2/select-one-fn :name :model/Database (mt/id))
+ external-query {:lib/type "mbql/query"
+ :stages [{:lib/type "mbql.stage/mbql"
+ :source-table [db-name "PUBLIC" "ORDERS"]
+ :limit 5}]}
construct-data (call-tool session-id "construct_query"
- {:source {:type "table" :id (mt/id :orders)}
- :operations [["limit" 5]]
- :prompt "show 5 orders"})]
+ {:query external-query
+ :prompt "show 5 orders"})]
(is (some? (parse-uuid (:query_handle construct-data))))
(is (not (contains? construct-data :widgetSessionId))))))
@@ -875,12 +862,19 @@
(deftest execute-query-resolves-via-cross-session-fallback-test
(testing "execute_query resolves a handle stored in another session of the same user — no widgetSessionId needed"
+ ;; Adapted from master's `:source`/`:operations` legacy program shape to our branch's
+ ;; representations `:query` shape. The semantic — cross-session same-user resolution —
+ ;; is preserved.
(let [[owner-session _] (initialize!)
[rotated-session _] (initialize!)
+ db-name (t2/select-one-fn :name :model/Database (mt/id))
+ external-query {:lib/type "mbql/query"
+ :stages [{:lib/type "mbql.stage/mbql"
+ :source-table [db-name "PUBLIC" "ORDERS"]
+ :limit 5}]}
construct-data (call-tool owner-session "construct_query"
- {:source {:type "table" :id (mt/id :orders)}
- :operations [["limit" 5]]
- :prompt "show 5 orders"})
+ {:query external-query
+ :prompt "show 5 orders"})
response (mcp-request (jsonrpc-request "tools/call"
{:name "execute_query"
:arguments {:query_handle (:query_handle construct-data)}})
diff --git a/test/metabase/metabot/agent/core_test.clj b/test/metabase/metabot/agent/core_test.clj
index 6fd92f5d0c3..9bd4fe7a126 100644
--- a/test/metabase/metabot/agent/core_test.clj
+++ b/test/metabase/metabot/agent/core_test.clj
@@ -12,7 +12,8 @@
[metabase.metabot.self.openrouter :as openrouter]
[metabase.metabot.test-util :as mut]
[metabase.metabot.tools.search :as metabot-search]
- [metabase.test :as mt]))
+ [metabase.test :as mt]
+ [toucan2.core :as t2]))
(set! *warn-on-reflection* true)
@@ -265,6 +266,16 @@
;; We use a simple "raw" query type that doesn't require field IDs.
(mt/with-current-user (mt/user->id :crowberto)
(let [orders-table-id (mt/id :orders)
+ ;; Look up database + schema + table name so we can write the portable FK
+ ;; that the representations-format construct_notebook_query expects.
+ orders-table (t2/select-one :model/Table :id orders-table-id)
+ db-name (t2/select-one-fn :name :model/Database :id (mt/id))
+ orders-fk [db-name (:schema orders-table) (:name orders-table)]
+ external-query {:lib/type "mbql/query"
+ :database db-name
+ :stages [{:lib/type "mbql.stage/mbql"
+ :source-table orders-fk
+ :limit 10}]}
;; Track LLM calls
llm-call-count (atom 0)
;; Scripted LLM responses - uses real table ID from test DB
@@ -278,15 +289,13 @@
:keyword_queries ["orders"]
:entity_types ["table"]}}
{:type :usage :usage {:promptTokens 100 :completionTokens 20} :model "test" :id "msg-1"}]
- ;; Iteration 2: Construct a simple query via agent-lib program
+ ;; Iteration 2: Construct a simple query via the representations YAML format
[{:type :start :id "msg-2"}
{:type :tool-input
:id "call-construct-1"
:function "construct_notebook_query"
:arguments {:reasoning "User wants to see orders"
- :source_entity {:type "table" :id orders-table-id}
- :program {:source {:type "table" :id orders-table-id}
- :operations [["limit" 10]]}
+ :query external-query
:visualization {:chart_type "table"}}}
{:type :usage :usage {:promptTokens 200 :completionTokens 30} :model "test" :id "msg-2"}]
;; Iteration 3: Final text response
diff --git a/test/metabase/metabot/agent/prompts_test.clj b/test/metabase/metabot/agent/prompts_test.clj
index 502414acf0e..fe3c532864d 100644
--- a/test/metabase/metabot/agent/prompts_test.clj
+++ b/test/metabase/metabot/agent/prompts_test.clj
@@ -22,6 +22,13 @@
(let [template (prompts/load-system-prompt-template "non-existent.selmer")]
(is (nil? template)))))
+(deftest construct-notebook-query-prompt-database-name-examples-test
+ (let [prompt (prompts/load-tool-prompt-template "construct_notebook_query.md")]
+ (is (some? prompt))
+ (testing "examples use the exact sample database name, not the old abbreviated portable FK"
+ (is (str/includes? prompt "Sample Database"))
+ (is (not (re-find #"\[Sample\s*," prompt))))))
+
(deftest load-dialect-instructions-test
(testing "loads postgresql dialect"
(let [instructions (prompts/load-dialect-instructions "postgresql")]
diff --git a/test/metabase/metabot/agent/user_context_test.clj b/test/metabase/metabot/agent/user_context_test.clj
index bc4764d7ba5..7dfd58fdf69 100644
--- a/test/metabase/metabot/agent/user_context_test.clj
+++ b/test/metabase/metabot/agent/user_context_test.clj
@@ -7,7 +7,7 @@
[metabase.lib.test-metadata :as meta]
[metabase.metabot.agent.user-context :as user-context]
[metabase.metabot.tools.entity-details :as entity-details]
- [metabase.metabot.tools.shared.llm-representations :as llm-rep]
+ [metabase.metabot.tools.shared.llm-shape :as llm-shape]
[metabase.test :as mt]))
(deftest format-current-time-test
@@ -263,10 +263,10 @@
:name "Jane Doe"
:email-address "[email protected]"
:glossary {"ARR" "Annual Recurring Revenue"}}})]
- (is (= (llm-rep/user->xml {:id 1
- :name "Jane Doe"
- :glossary {"ARR" "Annual Recurring Revenue"}})
+ (is (= (llm-shape/user->xml {:id 1
+ :name "Jane Doe"
+ :glossary {"ARR" "Annual Recurring Revenue"}})
(user-context/format-current-user-info {})))))
(testing "returns nil when there is no current user"
@@ -459,3 +459,35 @@
"Formatting result should contain the native query string")
(is (str/includes? result "1111")
"Formatting result should contain database id")))
+
+(deftest format-transform-source-mbql-renders-repr-json-test
+ (testing "transform sources with a structured MBQL `:query` are rendered as a portable repr JSON code block, not pprint'd pMBQL"
+ (mt/test-driver :h2
+ (mt/with-current-user (mt/user->id :crowberto)
+ (let [mp (mt/metadata-provider)
+ source {:type "query"
+ :query (-> (lib/query mp (lib.metadata/table mp (mt/id :venues)))
+ (lib/limit 5))}
+ text (user-context/format-transform-source
+ (assoc source :transform-source-type :query))]
+ (is (string? text))
+ (is (re-find #"```json" text)
+ "output is a JSON code block (the portable representations form), not pprint'd pMBQL")
+ (is (re-find #"\"lib/type\"\s*:\s*\"mbql/query\"" text))
+ (is (re-find #"\"source-table\"" text))
+ (is (not (re-find #"lib/metadata" text))
+ "the metadata-provider handle never leaks to the LLM-facing payload"))))))
+
+(deftest format-transform-source-native-renders-repr-json-test
+ (testing "native transform sources also go through the repr export so template-tags stay portable"
+ (mt/test-driver :h2
+ (mt/with-current-user (mt/user->id :crowberto)
+ (let [source {:type "query"
+ :query {:database (mt/id)
+ :type :native
+ :native {:query "SELECT * FROM VENUES LIMIT 5"}}}
+ text (user-context/format-transform-source
+ (assoc source :transform-source-type :native))]
+ (is (string? text))
+ (is (re-find #"\"mbql.stage/native\"" text))
+ (is (re-find #"SELECT \* FROM VENUES" text)))))))
diff --git a/test/metabase/metabot/tools/charts/edit_test.clj b/test/metabase/metabot/tools/charts/edit_test.clj
index 45d1c823c89..0ddbfe2294a 100644
--- a/test/metabase/metabot/tools/charts/edit_test.clj
+++ b/test/metabase/metabot/tools/charts/edit_test.clj
@@ -2,6 +2,7 @@
(:require
[clojure.string :as str]
[clojure.test :refer :all]
+ [clojure.walk :as walk]
[metabase.lib.core :as lib]
[metabase.metabot.agent.core :as agent]
[metabase.metabot.tools.charts :as tools.charts]
@@ -9,8 +10,12 @@
[metabase.metabot.tools.construct :as tools.construct]
[metabase.metabot.tools.resources :as tools.resources]
[metabase.metabot.tools.shared :as tools.shared]
+ [metabase.query-processor :as qp]
+ [metabase.query-processor.compile :as qp.compile]
[metabase.test :as mt]
- [metabase.test.data.users :as test.users]))
+ [metabase.test.data.users :as test.users]
+ [metabase.util :as u]
+ [toucan2.core :as t2]))
(deftest edit-chart-test
(testing "edits a chart's visualization type"
@@ -70,17 +75,25 @@
{[{{table :structured-output} :content}] :resources}
(tools.resources/read-resource-tool {:uris [table-fields-uri]})
- table-id (:id table)
- category-field-id (some (fn [{:keys [display_name field_id]}]
+ ;; Representations-format query: LLM-facing code should prefer the portable_fk path
+ ;; over numeric field ids. Take them straight from the entity_details response.
+ table-fk (:portable_fk table)
+ category-field-fk (some (fn [{:keys [display_name portable_fk]}]
(when (= "Category" display_name)
- field_id))
+ portable_fk))
(:fields table))
- ;; (1) construct a query
+ ;; (1) construct a query via the portable representations JSON format. Author the
+ ;; query as a string-keyed map and `keywordize-keys` it into the keyword-keyed
+ ;; external-query shape the tool accepts.
+ query-data {"lib/type" "mbql/query"
+ "database" (first table-fk)
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" table-fk
+ "aggregation" [["count" {}]]
+ "breakout" [["field" {} category-field-fk]]}]}
+ external-query (walk/keywordize-keys query-data)
construct-result (tools.construct/construct-notebook-query-tool
- {:source_entity {:type "table" :id table-id}
- :program {:source {:type "table" :id table-id}
- :operations [["aggregate" ["count"]]
- ["breakout" ["field" category-field-id]]]}
+ {:query external-query
:visualization {:chart_type "bar"}})
query-id (get-in construct-result [:structured-output :query-id])
query (get-in construct-result [:structured-output :query])
@@ -101,3 +114,193 @@
(get-in new-chart-in-memory [:visualization_settings :chart_type])))
(is (= query
(get-in new-chart-in-memory [:queries 0])))))))))
+
+(deftest construct-notebook-query-llm-orders-by-inline-aggregation-end-to-end-test
+ (testing (str "End-to-end regression for the inline-aggregation-in-order-by failure: the\n"
+ "LLM writes `order-by: [[desc, {}, [sum, {}, [field, {}, FK]]]]` re-stating\n"
+ "the aggregation expression. Repair must rewrite this into an aggregation\n"
+ "reference so the legacy round-trip on the resulting query succeeds.")
+ (mt/with-current-user (test.users/user->id :crowberto)
+ ;; Use the *canonical* DB name (per `repr-plan.md` step 13: `database:` is now strict).
+ ;; The prompt's `Sample` example would fail at the database lookup before we even get
+ ;; to exercise the order-by repair pass we're testing here.
+ (let [db-name (t2/select-one-fn :name :model/Database :id (mt/id))
+ query-data {"lib/type" "mbql/query"
+ "database" db-name
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" [db-name "PUBLIC" "ORDERS"]
+ "aggregation" [["sum" {}
+ ["field" {}
+ [db-name "PUBLIC" "ORDERS" "TOTAL"]]]]
+ "breakout" [["field" {}
+ [db-name "PUBLIC" "PRODUCTS" "CATEGORY"]]]
+ "order-by" [["desc" {}
+ ["sum" {}
+ ["field" {}
+ [db-name "PUBLIC" "ORDERS" "TOTAL"]]]]]}]}
+ external-query (walk/keywordize-keys query-data)
+ result (tools.construct/construct-notebook-query-tool
+ {:query external-query
+ :visualization {:chart_type "bar"}})
+ query (get-in result [:structured-output :query])]
+ (testing "order-by inner clause is now an aggregation reference, not :sum"
+ (let [first-ord (first (get-in query [:stages 0 :order-by]))
+ inner (when (and (vector? first-ord) (>= (count first-ord) 3))
+ (nth first-ord 2))]
+ (is (= :aggregation (first inner)))))
+ (testing "query compiles AND executes against the real sample DB"
+ ;; The original bug surfaced when the chart was re-loaded and the QP round-tripped
+ ;; through legacy MBQL. `qp/process-query` exercises the same path.
+ (let [qp-result (qp/process-query query)
+ rows (mt/rows qp-result)]
+ (is (seq rows) "expected at least one row from the grouped+ordered query")
+ ;; Each row is [category, sum]. Sums should be in descending order.
+ (let [sums (mapv second rows)]
+ (is (= sums (vec (reverse (sort sums))))
+ "sums should be in descending order"))))))))
+
+(deftest construct-notebook-query-llm-uses-prompt-db-name-end-to-end-test
+ (testing (str "End-to-end regression: the LLM writes `database: Sample` (the prompt\n"
+ "example name) against the real `Sample Database` app DB. Per\n"
+ "`repr-plan.md` step 13 the YAML's `database:` is now strict - the lookup\n"
+ "fails fast with a clear `:agent-error?` message that nudges the LLM to\n"
+ "use the canonical name from `entity_details`.")
+ (mt/with-current-user (test.users/user->id :crowberto)
+ ;; Verbatim the YAML the LLM produced in the bug report. Note: every portable FK uses
+ ;; `Sample` (the prompt name), not `Sample Database` (the real one).
+ (let [query-data {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "aggregation" [["sum" {}
+ ["field" {}
+ ["Sample" "PUBLIC" "ORDERS" "TOTAL"]]]]
+ "breakout" [["field" {}
+ ["Sample" "PUBLIC" "PRODUCTS" "CATEGORY"]]]
+ "order-by" [["desc" {}
+ ["sum" {}
+ ["field" {}
+ ["Sample" "PUBLIC" "ORDERS" "TOTAL"]]]]]}]}
+ external-query (walk/keywordize-keys query-data)
+ result (tools.construct/construct-notebook-query-tool
+ {:query external-query
+ :visualization {:chart_type "bar"}})]
+ (testing "tool returns a clear, agent-targeted error rather than producing a chart"
+ ;; The outer `construct-notebook-query-tool` catches the ex-info and returns
+ ;; `{:output <message>}` (no `:structured-output`). That's the LLM-visible signal.
+ (is (nil? (:structured-output result))
+ (str "expected no structured-output, got: " (pr-str result)))
+ (is (string? (:output result)))
+ (is (re-find #"Sample" (:output result))
+ (str "error message should mention the offending DB name; got: "
+ (:output result)))
+ (is (re-find #"entity_details|Unknown database" (:output result))
+ (str "error message should hint at the recovery path; got: "
+ (:output result))))))))
+
+(deftest construct-notebook-query-llm-uses-canonical-db-name-end-to-end-test
+ (testing (str "Symmetric to the previous test: the LLM writes `database: Sample Database`\n"
+ "(the canonical name reported by `entity_details`) and the chart constructs\n"
+ "cleanly. This is the post-step-13 happy path the LLM should follow.")
+ (mt/with-current-user (test.users/user->id :crowberto)
+ (let [db-name (t2/select-one-fn :name :model/Database :id (mt/id))
+ query-data {"lib/type" "mbql/query"
+ "database" db-name
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" [db-name "PUBLIC" "ORDERS"]
+ "aggregation" [["sum" {}
+ ["field" {}
+ [db-name "PUBLIC" "ORDERS" "TOTAL"]]]]
+ "breakout" [["field" {}
+ [db-name "PUBLIC" "PRODUCTS" "CATEGORY"]]]}]}
+ external-query (walk/keywordize-keys query-data)
+ result (tools.construct/construct-notebook-query-tool
+ {:query external-query
+ :visualization {:chart_type "bar"}})
+ query (get-in result [:structured-output :query])
+ breakout-field (get-in query [:stages 0 :breakout 0])]
+ (testing "the chart was constructed successfully"
+ (is (some? (:structured-output result)) (pr-str result))
+ (is (= :mbql/query (:lib/type query)))
+ (is (= (mt/id) (:database query)))
+ (is (= (mt/id :orders) (get-in query [:stages 0 :source-table]))))
+ (testing "breakout was resolved to PRODUCTS.CATEGORY with auto-wired source-field"
+ (is (= (mt/id :products :category) (nth breakout-field 2)))
+ (is (= (mt/id :orders :product_id) (:source-field (second breakout-field)))))
+ (testing "query compiles to runnable SQL"
+ (let [{:keys [query]} (qp.compile/compile query)]
+ (is (string? query))
+ (is (str/includes? (u/upper-case-en query) "PRODUCTS"))))))))
+
+(deftest construct-notebook-query-implicit-join-end-to-end-test
+ (testing (str "End-to-end: YAML with source-table=ORDERS referencing PRODUCTS.CATEGORY "
+ "gets source-field auto-wired, produces a query that compiles to SQL with "
+ "a JOIN and executes successfully against the app DB.")
+ (mt/with-current-user (test.users/user->id :crowberto)
+ (let [;; Discover portable FKs the same way the LLM does: via entity_details / fields.
+ {[{{orders-details :structured-output} :content}] :resources}
+ (tools.resources/read-resource-tool
+ {:uris [(str "metabase://table/" (mt/id :orders) "/fields")]})
+
+ {[{{products-details :structured-output} :content}] :resources}
+ (tools.resources/read-resource-tool
+ {:uris [(str "metabase://table/" (mt/id :products) "/fields")]})
+
+ orders-fk (:portable_fk orders-details)
+ product-id-field (some (fn [{:keys [display_name] :as f}]
+ (when (= "Product ID" display_name) f))
+ (:fields orders-details))
+ ;; The LLM learns PRODUCT_ID points at PRODUCTS via `:fk_target_portable_fk`
+ ;; and then fetches the target table's fields to pick CATEGORY.
+ products-target-fk (:fk_target_portable_fk product-id-field)
+ category-field-fk (some (fn [{:keys [display_name portable_fk]}]
+ (when (= "Category" display_name) portable_fk))
+ (:fields products-details))
+
+ ;; Build the YAML via data structures - no string concatenation. The parser
+ ;; expects string keys; clj-yaml's generate-string round-trips cleanly through
+ ;; `repr/parse-yaml`.
+ query-data {"lib/type" "mbql/query"
+ "database" (first orders-fk)
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" orders-fk
+ "aggregation" [["count" {}]]
+ "breakout" [["field" {} category-field-fk]]}]}
+ external-query (walk/keywordize-keys query-data)
+
+ construct-result (tools.construct/construct-notebook-query-tool
+ {:query external-query
+ :visualization {:chart_type "bar"}})
+ query (get-in construct-result [:structured-output :query])
+ breakout-field (get-in query [:stages 0 :breakout 0])
+ field-opts (second breakout-field)]
+
+ (testing "entity_details surfaced the FK target - sanity-check the inputs we fed in"
+ (is (= ["Product ID" "PRODUCTS"]
+ [(:display_name product-id-field)
+ (nth products-target-fk 2)])
+ "Product ID's fk_target_portable_fk should point at PRODUCTS"))
+
+ (testing "repair resolved the portable breakout to PRODUCTS.CATEGORY"
+ (is (= (mt/id :products :category) (nth breakout-field 2))))
+
+ (testing "repair auto-wired :source-field to ORDERS.PRODUCT_ID"
+ (is (= (mt/id :orders :product_id) (:source-field field-opts))))
+
+ (testing "query compiles to SQL that joins ORDERS and PRODUCTS"
+ (let [{:keys [query]} (qp.compile/compile query)]
+ (is (string? query))
+ (is (str/includes? query "JOIN"))
+ (is (str/includes? (u/upper-case-en query) "PRODUCTS"))
+ (is (str/includes? (u/upper-case-en query) "ORDERS"))))
+
+ (testing "query executes and returns grouped rows (categories + counts)"
+ (let [qp-result (qp/process-query query)
+ rows (mt/rows qp-result)]
+ (is (seq rows) "expected at least one row from the joined query")
+ (is (every? (fn [row] (and (vector? row) (= 2 (count row)))) rows)
+ "each row should be [category, count]")
+ (is (every? string? (map first rows))
+ "first column should be category names (strings)")
+ (is (every? (every-pred number? pos?) (map second rows))
+ "second column should be positive counts")))))))
diff --git a/test/metabase/metabot/tools/construct_representations_test.clj b/test/metabase/metabot/tools/construct_representations_test.clj
new file mode 100644
index 00000000000..34370dc6e35
--- /dev/null
+++ b/test/metabase/metabot/tools/construct_representations_test.clj
@@ -0,0 +1,743 @@
+(ns metabase.metabot.tools.construct-representations-test
+ "Tests for `execute-representations-query` - the representations-format entry point for
+ `construct_notebook_query`.
+
+ Covers the happy path (external-query JSON -> resolved pMBQL wrapped in structured output),
+ unknown table, the `:agent-error?` error-translation contract, and the database-id
+ resolution from the query's first-stage `source-table:` (per `repr-plan.md` step 13:
+ unknown name, ambiguous name, missing name, mismatched DB component in source-table)."
+ (:require
+ [clojure.test :refer [deftest is testing]]
+ [clojure.walk :as walk]
+ [metabase.api.common :as api]
+ [metabase.lib-be.core :as lib-be]
+ [metabase.lib.core :as lib]
+ [metabase.lib.test-util :as lib.tu]
+ [metabase.metabot.tools.construct :as construct]
+ [metabase.models.serialization :as serdes]))
+
+(set! *warn-on-reflection* true)
+
+(def ^:private mp
+ (lib.tu/mock-metadata-provider
+ {:database {:id 1 :name "Sample"}
+ :tables [{:id 10 :name "ORDERS" :schema "PUBLIC" :db-id 1}
+ {:id 20 :name "PRODUCTS" :schema "PUBLIC" :db-id 1}]
+ :fields [{:id 100 :name "ID" :table-id 10 :base-type :type/Integer}
+ {:id 101 :name "TOTAL" :table-id 10 :base-type :type/Float}
+ {:id 102 :name "PRODUCT_ID" :table-id 10 :base-type :type/Integer
+ :fk-target-field-id 200}
+ {:id 200 :name "ID" :table-id 20 :base-type :type/Integer}
+ {:id 201 :name "CATEGORY" :table-id 20 :base-type :type/Text}]}))
+
+(def ^:private mp-sample-database
+ "Mirrors the *real* application DB shape the LLM hits in production: the database name
+ is `Sample Database`, but our prompt examples all show `Sample`. Used by the
+ database-name-mismatch reproducer."
+ (lib.tu/mock-metadata-provider
+ {:database {:id 1 :name "Sample Database"}
+ :tables [{:id 10 :name "ORDERS" :schema "PUBLIC" :db-id 1}
+ {:id 20 :name "PRODUCTS" :schema "PUBLIC" :db-id 1}]
+ :fields [{:id 100 :name "ID" :table-id 10 :base-type :type/Integer}
+ {:id 101 :name "TOTAL" :table-id 10 :base-type :type/Float}
+ {:id 102 :name "PRODUCT_ID" :table-id 10 :base-type :type/Integer
+ :fk-target-field-id 200}
+ {:id 200 :name "ID" :table-id 20 :base-type :type/Integer}
+ {:id 201 :name "CATEGORY" :table-id 20 :base-type :type/Text}]}))
+
+(def ^:private mp-ambiguous
+ "Two FKs from ORDERS to PRODUCTS - triggers :ambiguous-fk."
+ (lib.tu/mock-metadata-provider
+ {:database {:id 1 :name "Sample"}
+ :tables [{:id 10 :name "ORDERS" :schema "PUBLIC" :db-id 1}
+ {:id 20 :name "PRODUCTS" :schema "PUBLIC" :db-id 1}]
+ :fields [{:id 100 :name "ID" :table-id 10 :base-type :type/Integer}
+ {:id 102 :name "PRODUCT_ID" :table-id 10 :base-type :type/Integer
+ :fk-target-field-id 200}
+ {:id 103 :name "ALT_PRODUCT_ID" :table-id 10 :base-type :type/Integer
+ :fk-target-field-id 200}
+ {:id 200 :name "ID" :table-id 20 :base-type :type/Integer}
+ {:id 201 :name "CATEGORY" :table-id 20 :base-type :type/Text}]}))
+
+;; Note: `resolve-database-id-from-first-stage` hits toucan2 to look the database up by
+;; name (via the first stage's `source-table[0]` / `source-card`). We stub it directly per
+;; fixture so tests don't need a live application DB. Each fixture's stub returns the id
+;; matching the bound metadata provider.
+
+(defn- allow-read-check
+ ([obj] obj)
+ ([entity id] {:model entity :id id})
+ ([entity id & _conditions] {:model entity :id id}))
+
+(defn- with-mp-and-stubs! [f]
+ (with-redefs [lib-be/application-database-metadata-provider (fn [_db-id] mp)
+ construct/resolve-database-id-from-first-stage (fn [_] 1)
+ api/read-check allow-read-check
+ api/query-check allow-read-check]
+ (f)))
+
+(defn- with-ambiguous-mp-and-stubs! [f]
+ (with-redefs [lib-be/application-database-metadata-provider (fn [_db-id] mp-ambiguous)
+ construct/resolve-database-id-from-first-stage (fn [_] 1)
+ api/read-check allow-read-check
+ api/query-check allow-read-check]
+ (f)))
+
+(defn- query-data
+ "Build the keyword-keyed external-query map the tool accepts. Tests author the query as a
+ string-keyed map (the form documented in earlier YAML-era tests); we walk-keywordize so the
+ call site stays terse and the namespace markers (`lib/type`, `lib/expression-name`, …) are
+ preserved by `clojure.core/keyword`."
+ [string-keyed-data]
+ (walk/keywordize-keys string-keyed-data))
+
+(deftest happy-path-test
+ (with-mp-and-stubs!
+ (fn []
+ (let [result (construct/execute-representations-query
+ (query-data
+ {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "aggregation" [["count" {}]]}]}))
+ structured (:structured-output result)
+ q (:query structured)]
+ (testing "structured-output shape"
+ (is (string? (:query-id structured)))
+ (is (vector? (:result-columns structured))))
+ (testing "query is a valid resolved MBQL 5 query"
+ (is (= :mbql/query (:lib/type q)))
+ (is (= 1 (:database q)))
+ (is (= 10 (get-in q [:stages 0 :source-table])))
+ (is (= :count (first (get-in q [:stages 0 :aggregation 0])))))
+ (testing "query-json is the final normalized portable representations map"
+ (let [exported (:query-json structured)]
+ (is (map? exported))
+ (testing "exported map is portable/string-keyed, not numeric IDs"
+ (is (= "mbql/query" (get exported "lib/type")))
+ (is (nil? (get exported "lib/metadata")))
+ (is (= ["Sample" "PUBLIC" "ORDERS"]
+ (get-in exported ["stages" 0 "source-table"]))))
+ (testing "exported map includes lib-normalized UUIDs that were not present in the LLM input"
+ (is (string? (get-in exported ["stages" 0 "aggregation" 0 1 "lib/uuid"]))))
+ (testing "idempotency: feeding the exported map back through the tool yields a structurally equal export"
+ ;; The exported form is string-keyed; we keywordize it back to the external-query
+ ;; shape the tool accepts.
+ (let [redo (construct/execute-representations-query
+ (walk/keywordize-keys exported))]
+ (is (= exported
+ (get-in redo [:structured-output :query-json])))))))))))
+
+(deftest unknown-table-surfaces-agent-error-test
+ (with-mp-and-stubs!
+ (fn []
+ (try
+ (construct/execute-representations-query
+ (query-data
+ {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "DOES_NOT_EXIST"]
+ "aggregation" [["count" {}]]}]}))
+ (is false "expected throw")
+ (catch clojure.lang.ExceptionInfo e
+ (let [d (ex-data e)]
+ (is (true? (:agent-error? d)))
+ (is (= :unknown-table (:error d)))))))))
+
+(deftest implicit-join-happy-path-test
+ (testing "cross-table breakout gets auto-wired with a :source-field after repair"
+ (with-mp-and-stubs!
+ (fn []
+ (let [result (construct/execute-representations-query
+ (query-data
+ {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "aggregation" [["count" {}]]
+ "breakout" [["field" {}
+ ["Sample" "PUBLIC" "PRODUCTS" "CATEGORY"]]]}]}))
+ q (get-in result [:structured-output :query])
+ breakout-field (get-in q [:stages 0 :breakout 0])
+ field-opts (second breakout-field)]
+ (testing "field-id is resolved to PRODUCTS.CATEGORY (201)"
+ (is (= 201 (nth breakout-field 2))))
+ (testing "source-field is populated with ORDERS.PRODUCT_ID (102)"
+ (is (= 102 (:source-field field-opts)))))))))
+
+(deftest implicit-join-ambiguous-surfaces-agent-error-test
+ (with-ambiguous-mp-and-stubs!
+ (fn []
+ (try
+ (construct/execute-representations-query
+ (query-data
+ {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "aggregation" [["count" {}]]
+ "breakout" [["field" {}
+ ["Sample" "PUBLIC" "PRODUCTS" "CATEGORY"]]]}]}))
+ (is false "expected throw")
+ (catch clojure.lang.ExceptionInfo e
+ (let [d (ex-data e)
+ msg (ex-message e)]
+ (is (true? (:agent-error? d)))
+ (is (= :ambiguous-fk (:error d)))
+ (testing "diagnostic names the source table and points at `source-field`"
+ (is (re-find #"ORDERS" msg))
+ (is (re-find #"source-field" msg)))
+ (testing "FK column names are NOT enumerated (S1 info-leak parity)"
+ (is (not (re-find #"PRODUCT_ID" msg))))))))))
+
+(deftest llm-writes-wrong-db-name-in-source-table-fails-loudly-test
+ (testing (str "Post step-14-follow-up, database identity is derived from the first stage's\n"
+ "`source-table:` FK (first element = db name). If the LLM writes\n"
+ "`source-table: [Sample, PUBLIC, ORDERS]` against an instance whose DB is named\n"
+ "`Sample Database`, the lookup fails fast with a clear `:unknown-database`\n"
+ "`:agent-error?`. The LLM gets a useful nudge in the error message; the prompt\n"
+ "change to use the canonical name from `entity_details` is the real long-term fix.")
+ ;; This fixture's MP-name is "Sample Database". We DON'T stub `resolve-database-id-from-first-stage`
+ ;; here - we want the actual function to run against `name = "Sample"` and observe the
+ ;; not-found behaviour.
+ (with-redefs [lib-be/application-database-metadata-provider (fn [_db-id] mp-sample-database)
+ construct/resolve-database-id-from-first-stage
+ (fn [parsed]
+ (let [db-name (get-in parsed ["stages" 0 "source-table" 0])]
+ (if (= db-name "Sample Database")
+ 1
+ (throw (ex-info (str "Unknown database: `" db-name "`.")
+ {:agent-error? true
+ :status-code 400
+ :error :unknown-database
+ :database db-name})))))]
+ (let [query (query-data
+ {"lib/type" "mbql/query"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "aggregation" [["count" {}]]}]})]
+ (try
+ (construct/execute-representations-query query)
+ (is false "expected throw")
+ (catch clojure.lang.ExceptionInfo e
+ (let [d (ex-data e)]
+ (testing "surfaces as :agent-error? with :unknown-database"
+ (is (true? (:agent-error? d)))
+ (is (= :unknown-database (:error d)))
+ (is (= "Sample" (:database d))))
+ (testing "error message includes the offending name"
+ (is (re-find #"Sample" (ex-message e)))))))))))
+
+(deftest llm-orders-by-inline-aggregation-reproducer-test
+ (testing (str "Reproducer: when the LLM writes `order-by` by re-stating the aggregation\n"
+ "expression inline (`[desc, {}, [sum, {}, [field, {}, FK]]]`) instead of using\n"
+ "an aggregation reference, the construct call appears to succeed but the\n"
+ "resulting query is unrunnable: the legacy-MBQL form has an inline aggregation\n"
+ "in `:order-by`, which legacy MBQL rejects. Triggered by the natural-language\n"
+ "request 'total revenue per product category' - the LLM adds a sort by\n"
+ "revenue desc and writes the order-by inline.")
+ (with-mp-and-stubs!
+ (fn []
+ (let [query (query-data
+ {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "aggregation" [["sum" {}
+ ["field" {}
+ ["Sample" "PUBLIC" "ORDERS" "TOTAL"]]]]
+ "breakout" [["field" {}
+ ["Sample" "PUBLIC" "PRODUCTS" "CATEGORY"]]]
+ "order-by" [["desc" {}
+ ["sum" {}
+ ["field" {}
+ ["Sample" "PUBLIC" "ORDERS" "TOTAL"]]]]]}]})
+ ;; Today: `execute-representations-query` succeeds quietly here. The crash
+ ;; happens later, when downstream callers (chart re-load, normalize, QP) try to
+ ;; round-trip the query through legacy MBQL.
+ result (try
+ (construct/execute-representations-query query)
+ (catch clojure.lang.ExceptionInfo e e))]
+ (testing "the pipeline produces a runnable query (not just an apparently-resolved one)"
+ (is (not (instance? clojure.lang.ExceptionInfo result))
+ (str "Pipeline failed with: "
+ (when (instance? clojure.lang.ExceptionInfo result)
+ (pr-str {:msg (ex-message result) :data (ex-data result)}))))
+ (when-not (instance? clojure.lang.ExceptionInfo result)
+ (let [q (get-in result [:structured-output :query])
+ ;; Round-trip through legacy is the gate the production failure hit.
+ legacy #_{:clj-kondo/ignore [:discouraged-var]}
+ (lib/->legacy-MBQL q)
+ rebuilt (try (lib/query mp legacy)
+ (catch clojure.lang.ExceptionInfo e e))]
+ (testing "order-by uses an aggregation reference, not an inline aggregation"
+ ;; In MBQL 5: `[:aggregation {} \"<uuid>\"]`. Whatever shape we settle on, an
+ ;; inline `[:sum [:field ...]]` (a stage-aggregation expression) must NOT
+ ;; appear inside `:order-by`.
+ (is (not= :sum
+ (let [first-ord (first (get-in q [:stages 0 :order-by]))
+ ;; first-ord is `[:desc {} <inner>]`; `nth ord 2` is the inner clause
+ inner (when (and (vector? first-ord) (>= (count first-ord) 3))
+ (nth first-ord 2))]
+ (when (vector? inner) (first inner))))
+ "order-by inner clause should be an aggregation ref, not :sum"))
+ (testing "legacy round-trip succeeds (would fail in production with :order-by [:sum ...])"
+ (is (not (instance? clojure.lang.ExceptionInfo rebuilt))
+ (str "legacy-roundtrip failed: "
+ (when (instance? clojure.lang.ExceptionInfo rebuilt)
+ (ex-message rebuilt)))))))))))))
+
+;;; ============================================================
+;;; Step-14-follow-up contract: database identity from `stages[0]`
+;;; ============================================================
+
+(deftest resolve-database-id-missing-source-in-first-stage-test
+ (testing "first stage with neither `source-table:` nor `source-card:` surfaces :missing-source-in-first-stage"
+ (try
+ (construct/resolve-database-id-from-first-stage
+ {"lib/type" "mbql/query"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "aggregation" [["count" {}]]}]})
+ (is false "expected throw")
+ (catch clojure.lang.ExceptionInfo e
+ (let [d (ex-data e)]
+ (is (true? (:agent-error? d)))
+ (is (= :missing-source-in-first-stage (:error d))))))))
+
+(deftest resolve-database-id-non-string-source-card-test
+ (testing "`source-card:` that isn't a string is ignored and we fall through to missing-source"
+ (try
+ (construct/resolve-database-id-from-first-stage
+ {"lib/type" "mbql/query"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-card" 42}]})
+ (is false "expected throw")
+ (catch clojure.lang.ExceptionInfo e
+ (let [d (ex-data e)]
+ (is (true? (:agent-error? d)))
+ (is (= :missing-source-in-first-stage (:error d))))))))
+
+(deftest resolve-database-id-metabase-uri-in-source-table-test
+ (testing (str "When the LLM writes `source-table: metabase://<type>/<id>` (confusing the\n"
+ "`metabase://...` URIs it sees in entity references with a query source handle),\n"
+ "we emit a directive `:uri-in-source-table` `:agent-error?` with a type-aware\n"
+ "recovery hint rather than the generic `:missing-source-in-first-stage`.")
+ (testing "metric URI - hint explains metric-as-aggregation pattern"
+ (try
+ (construct/resolve-database-id-from-first-stage
+ {"lib/type" "mbql/query"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" "metabase://metric/76"}]})
+ (is false "expected throw")
+ (catch clojure.lang.ExceptionInfo e
+ (let [d (ex-data e)]
+ (is (true? (:agent-error? d)))
+ (is (= :uri-in-source-table (:error d)))
+ (is (= "metric" (:entity-type d)))
+ (is (= "76" (:entity-id d)))
+ (is (= "metabase://metric/76" (:source-table d)))
+ (is (re-find #"aggregation" (ex-message e))
+ "message should point at aggregation-clause recovery")
+ (is (re-find #"base_table_portable_fk" (ex-message e))
+ "message should name the field the LLM needs to look up on the metric")))))
+ (testing "question / model URI - hint points at `source-card:`"
+ (doseq [t ["question" "model" "card"]]
+ (try
+ (construct/resolve-database-id-from-first-stage
+ {"lib/type" "mbql/query"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" (str "metabase://" t "/9")}]})
+ (is false (str "expected throw for " t))
+ (catch clojure.lang.ExceptionInfo e
+ (let [d (ex-data e)]
+ (is (= :uri-in-source-table (:error d)))
+ (is (= t (:entity-type d)))
+ (is (re-find #"source-card" (ex-message e))
+ (str "message for " t " should point at source-card:")))))))
+ (testing "table URI - hint points at portable FK form"
+ (try
+ (construct/resolve-database-id-from-first-stage
+ {"lib/type" "mbql/query"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" "metabase://table/42"}]})
+ (is false "expected throw")
+ (catch clojure.lang.ExceptionInfo e
+ (let [d (ex-data e)]
+ (is (= :uri-in-source-table (:error d)))
+ (is (= "table" (:entity-type d)))
+ (is (re-find #"portable FK" (ex-message e)))))))))
+
+(deftest execute-representations-query-unknown-db-in-source-table-test
+ (testing (str "Post step-14-follow-up the first stage's `source-table[0]` is the sole source\n"
+ "of truth for the application database. A DB name that doesn't match any app\n"
+ "DB surfaces `:unknown-database` at the `resolve-database-id-from-first-stage`\n"
+ "step, reflagged `:agent-error?` for the LLM.")
+ ;; No with-mp-and-stubs! - we want the DB-name-not-found path to trigger.
+ (with-redefs [lib-be/application-database-metadata-provider (fn [_db-id] mp)
+ construct/resolve-database-id-from-first-stage
+ (fn [parsed]
+ (let [db-name (get-in parsed ["stages" 0 "source-table" 0])]
+ (if (= db-name "Sample")
+ 1
+ (throw (ex-info (str "Unknown database: `" db-name "`.")
+ {:agent-error? true
+ :status-code 400
+ :error :unknown-database
+ :database db-name})))))]
+ (try
+ (construct/execute-representations-query
+ (query-data
+ {"lib/type" "mbql/query"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["OtherDB" "PUBLIC" "ORDERS"]
+ "aggregation" [["count" {}]]}]}))
+ (is false "expected throw")
+ (catch clojure.lang.ExceptionInfo e
+ (let [d (ex-data e)]
+ (is (true? (:agent-error? d)))
+ (is (= :unknown-database (:error d)))
+ (is (re-find #"OtherDB" (ex-message e)))))))))
+
+;;; ============================================================
+;;; Step-8 contract: multi-stage queries
+;;; ============================================================
+
+(deftest multi-stage-post-aggregation-filter-end-to-end-test
+ (testing (str "Two-stage query: aggregate orders by product id in stage 0, filter where\n"
+ "`count > 10` in stage 1. The stage-1 filter references the aggregation output\n"
+ "by string name (`count`) without `base-type` - a recurring LLM mistake -\n"
+ "and the cross-stage field-type inference pass (per `repr-plan.md` step 8)\n"
+ "silently fills it in so the resolver + lib/query accept the query.")
+ (with-mp-and-stubs!
+ (fn []
+ (let [result (construct/execute-representations-query
+ (query-data
+ {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "aggregation" [["count" {}]]
+ "breakout" [["field" {} ["Sample" "PUBLIC" "ORDERS" "PRODUCT_ID"]]]}
+ {"lib/type" "mbql.stage/mbql"
+ "filters" [[">" {} ["field" {} "count"] 10]]}]}))
+ q (get-in result [:structured-output :query])]
+ (testing "two-stage shape preserved"
+ (is (= 2 (count (:stages q))))
+ (is (= 10 (get-in q [:stages 0 :source-table])))
+ (is (nil? (get-in q [:stages 1 :source-table]))))
+ (testing "stage-1 filter resolved into a real `:>` clause whose field carries types"
+ (let [filter-clause (get-in q [:stages 1 :filters 0])
+ field-clause (nth filter-clause 2)
+ field-opts (nth field-clause 1)]
+ (is (= :> (first filter-clause)))
+ (is (= :field (first field-clause)))
+ (is (= "count" (nth field-clause 2)))
+ (is (= :type/Integer (:base-type field-opts)))
+ (is (= :type/Integer (:effective-type field-opts)))))
+ (testing "result-columns reflect the post-filter stage's output"
+ (is (= #{"PRODUCT_ID" "count"}
+ (set (mapv :name (get-in result [:structured-output :result-columns])))))))))))
+
+(deftest multi-stage-respects-explicit-base-type-test
+ (testing (str "If the LLM happens to write `base-type` on a cross-stage ref already, repair\n"
+ "leaves it alone. Confirms the inference pass is additive, not overwriting.")
+ (with-mp-and-stubs!
+ (fn []
+ (let [result (construct/execute-representations-query
+ (query-data
+ {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "aggregation" [["count" {}]]
+ "breakout" [["field" {} ["Sample" "PUBLIC" "ORDERS" "PRODUCT_ID"]]]}
+ {"lib/type" "mbql.stage/mbql"
+ "filters" [[">" {} ["field" {"base-type" "type/Integer"} "count"] 10]]}]}))
+ q (get-in result [:structured-output :query])
+ field-opts (get-in q [:stages 1 :filters 0 2 1])]
+ (is (= :type/Integer (:base-type field-opts))))))))
+
+(deftest multi-stage-three-stage-chain-test
+ (testing (str "A three-stage query: aggregate \u2192 filter (stage 1, references `count`) \u2192\n"
+ "order-by (stage 2, references `count` again). Verifies that the cross-stage\n"
+ "inference pass walks all stages, not just stage 1.")
+ (with-mp-and-stubs!
+ (fn []
+ (let [result (construct/execute-representations-query
+ (query-data
+ {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "aggregation" [["count" {}]]
+ "breakout" [["field" {} ["Sample" "PUBLIC" "ORDERS" "PRODUCT_ID"]]]}
+ {"lib/type" "mbql.stage/mbql"
+ "filters" [[">" {} ["field" {} "count"] 10]]}
+ {"lib/type" "mbql.stage/mbql"
+ "order-by" [["desc" {} ["field" {} "count"]]]}]}))
+ q (get-in result [:structured-output :query])]
+ (is (= 3 (count (:stages q))))
+ (testing "stage 1's cross-stage filter ref carries inferred base-type"
+ (is (= :type/Integer (get-in q [:stages 1 :filters 0 2 1 :base-type]))))
+ (testing "stage 2's cross-stage order-by ref also carries inferred base-type"
+ (is (= :type/Integer (get-in q [:stages 2 :order-by 0 2 1 :base-type])))))))))
+
+(deftest multi-stage-unknown-cross-stage-column-surfaces-error-test
+ (testing (str "If the LLM references a column name that the previous stage doesn't produce,\n"
+ "repair leaves the clause alone (no `base-type` to infer) and the lib-schema\n"
+ "validator surfaces the missing-key error - reflagged as :agent-error?\n"
+ "by `execute-representations-query`'s catch.")
+ (with-mp-and-stubs!
+ (fn []
+ (try
+ (construct/execute-representations-query
+ (query-data
+ {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "aggregation" [["count" {}]]
+ "breakout" [["field" {} ["Sample" "PUBLIC" "ORDERS" "PRODUCT_ID"]]]}
+ {"lib/type" "mbql.stage/mbql"
+ "filters" [[">" {} ["field" {} "no_such_column"] 10]]}]}))
+ (is false "expected throw")
+ (catch clojure.lang.ExceptionInfo e
+ (let [d (ex-data e)]
+ (is (true? (:agent-error? d))))))))))
+
+;;; ============================================================
+;;; Step-9 contract: expressions (custom columns)
+;;; ============================================================
+
+(deftest expression-map-shape-end-to-end-test
+ (testing (str "The LLM-friendly `expressions: {Name: clause, …}` map shape is normalised\n"
+ "to the canonical sequential MBQL 5 form with `lib/expression-name` stamped,\n"
+ "and the resolved query carries the expression in its pMBQL.")
+ (with-mp-and-stubs!
+ (fn []
+ (let [result (construct/execute-representations-query
+ (query-data
+ {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "expressions" {"Doubled" ["*" {}
+ ["field" {} ["Sample" "PUBLIC" "ORDERS" "TOTAL"]]
+ 2]}
+ "aggregation" [["sum" {} ["expression" {} "Doubled"]]]}]}))
+ q (get-in result [:structured-output :query])
+ exprs (get-in q [:stages 0 :expressions])]
+ (is (vector? exprs))
+ (is (= 1 (count exprs)))
+ (let [[op opts] (first exprs)]
+ (is (= :* op))
+ (is (= "Doubled" (:lib/expression-name opts))))
+ (testing "expression is referenced in aggregation"
+ (let [agg (get-in q [:stages 0 :aggregation 0])]
+ (is (= :sum (first agg)))
+ (is (= :expression (first (nth agg 2))))
+ (is (= "Doubled" (nth (nth agg 2) 2))))))))))
+
+(deftest expression-sequential-shape-end-to-end-test
+ (testing (str "Canonical sequential `expressions:` form with `lib/expression-name`\n"
+ "already in options also works end-to-end.")
+ (with-mp-and-stubs!
+ (fn []
+ (let [result (construct/execute-representations-query
+ (query-data
+ {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "expressions" [["+" {"lib/expression-name" "Plus10"}
+ ["field" {} ["Sample" "PUBLIC" "ORDERS" "TOTAL"]]
+ 10]]
+ "aggregation" [["sum" {} ["expression" {} "Plus10"]]]}]}))
+ q (get-in result [:structured-output :query])
+ exprs (get-in q [:stages 0 :expressions])]
+ (is (= 1 (count exprs)))
+ (is (= "Plus10" (get-in (first exprs) [1 :lib/expression-name]))))))))
+
+(deftest expression-in-breakout-end-to-end-test
+ (testing "Expression can be referenced in `breakout:` - MBQL 5 accepts `[:expression ... name]` as a grouping key."
+ (with-mp-and-stubs!
+ (fn []
+ (let [result (construct/execute-representations-query
+ (query-data
+ {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "expressions" {"HalfTotal" ["/" {}
+ ["field" {} ["Sample" "PUBLIC" "ORDERS" "TOTAL"]]
+ 2]}
+ "breakout" [["expression" {} "HalfTotal"]]
+ "aggregation" [["count" {}]]}]}))
+ q (get-in result [:structured-output :query])
+ b (get-in q [:stages 0 :breakout 0])]
+ (is (= :expression (first b)))
+ (is (= "HalfTotal" (nth b 2))))))))
+
+;;; ============================================================
+;;; Step-10 contract: aggregation references via 0-based integer index
+;;; ============================================================
+
+(deftest aggregation-ref-integer-index-in-order-by-end-to-end-test
+ (testing (str "`[aggregation, {}, <index>]` in order-by is resolved to the canonical\n"
+ "UUID-keyed MBQL 5 form, and the resolved query validates via lib/query.")
+ (with-mp-and-stubs!
+ (fn []
+ (let [result (construct/execute-representations-query
+ (query-data
+ {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "aggregation" [["sum" {} ["field" {} ["Sample" "PUBLIC" "ORDERS" "TOTAL"]]]
+ ["count" {}]]
+ "breakout" [["field" {} ["Sample" "PUBLIC" "ORDERS" "PRODUCT_ID"]]]
+ "order-by" [["desc" {} ["aggregation" {} 0]]]}]}))
+ q (get-in result [:structured-output :query])
+ sum-agg (get-in q [:stages 0 :aggregation 0])
+ order-ref (get-in q [:stages 0 :order-by 0 2])
+ agg-uuid (get-in sum-agg [1 :lib/uuid])]
+ (testing "target aggregation carries a lib/uuid string"
+ (is (string? agg-uuid)))
+ (testing "order-by ref is :aggregation with matching uuid string and types"
+ (is (= :aggregation (first order-ref)))
+ (is (= agg-uuid (nth order-ref 2)))
+ (is (some? (get-in order-ref [1 :base-type])))))))))
+
+(deftest aggregation-ref-out-of-range-surfaces-agent-error-end-to-end-test
+ (testing "out-of-range integer agg-ref returns an agent-error with clear message"
+ (with-mp-and-stubs!
+ (fn []
+ (try
+ (construct/execute-representations-query
+ (query-data
+ {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]
+ "aggregation" [["count" {}]]
+ "order-by" [["desc" {} ["aggregation" {} 7]]]}]}))
+ (is false "expected throw")
+ (catch clojure.lang.ExceptionInfo e
+ (let [d (ex-data e)]
+ (is (true? (:agent-error? d)))
+ (is (= :aggregation-ref-out-of-range (:error d)))
+ (is (re-find #"count at 0" (ex-message e))))))))))
+
+;;; ============================================================
+;;; source-card end-to-end (repr-plan step 11)
+;;; ============================================================
+
+(def ^:private card-entity-id
+ "A valid 21-char NanoID - matches `serdes/entity-id?` regex so `import-mbql` actually picks
+ up the `source-card` branch."
+ "aBc123_456DefGhI789_K")
+
+(def ^:private mp-with-card
+ "Same warehouse shape as `mp` plus a saved-question Card whose result-metadata carries the
+ column types the repair pass needs for field-reference inference."
+ (lib.tu/mock-metadata-provider
+ {:database {:id 1 :name "Sample"}
+ :tables [{:id 10 :name "ORDERS" :schema "PUBLIC" :db-id 1}
+ {:id 20 :name "PRODUCTS" :schema "PUBLIC" :db-id 1}]
+ :fields [{:id 100 :name "ID" :table-id 10 :base-type :type/Integer}
+ {:id 101 :name "TOTAL" :table-id 10 :base-type :type/Float}
+ {:id 102 :name "PRODUCT_ID" :table-id 10 :base-type :type/Integer
+ :fk-target-field-id 200}
+ {:id 200 :name "ID" :table-id 20 :base-type :type/Integer}
+ {:id 201 :name "CATEGORY" :table-id 20 :base-type :type/Text}]
+ :cards [{:id 500
+ :name "Saved Orders"
+ :database-id 1
+ :type :question
+ :entity-id card-entity-id
+ :dataset-query {:lib/type :mbql/query
+ :database 1
+ :stages [{:lib/type :mbql.stage/mbql
+ :source-table 10}]}
+ :result-metadata [{:name "ID" :base-type :type/Integer}
+ {:name "TOTAL" :base-type :type/Float}]}]}))
+
+(defn- lookup-card-stub [model eid]
+ (when (and (or (= model 'Card) (= model :model/Card))
+ (= eid card-entity-id))
+ {:id 500 :database_id 1 :entity_id eid}))
+
+(defn- with-card-mp-and-stubs! [f]
+ (with-redefs [lib-be/application-database-metadata-provider (fn [_] mp-with-card)
+ construct/resolve-database-id-from-first-stage (fn [_] 1)
+ serdes/lookup-by-id lookup-card-stub
+ api/read-check allow-read-check
+ api/query-check allow-read-check]
+ (f)))
+
+(deftest source-card-end-to-end-test
+ (testing "`source-card: <entity_id>` resolves to the card's numeric id and field references\nget their base-type stamped from the card's result-metadata"
+ (with-card-mp-and-stubs!
+ (fn []
+ (let [result (construct/execute-representations-query
+ (query-data
+ {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-card" card-entity-id
+ "fields" [["field" {} "TOTAL"]]
+ "limit" 5}]}))
+ q (get-in result [:structured-output :query])
+ stage (get-in q [:stages 0])
+ field-ref (get-in stage [:fields 0])]
+ (testing "source-card resolved to numeric id"
+ (is (= 500 (:source-card stage))))
+ (testing "no leftover source-table"
+ (is (not (contains? stage :source-table))))
+ (testing "field reference kept the string name and got types from the card"
+ (is (= :field (first field-ref)))
+ (is (= "TOTAL" (nth field-ref 2)))
+ (is (= :type/Float (get-in field-ref [1 :base-type]))))
+ (testing "query-json exports the final numeric source-card back to its portable entity_id"
+ (let [exported (get-in result [:structured-output :query-json])]
+ (is (= card-entity-id
+ (get-in exported ["stages" 0 "source-card"]))))))))))
+
+(deftest source-card-unknown-entity-id-surfaces-agent-error-test
+ (testing "a valid-shaped entity_id that does not resolve to any card returns :unknown-card with :agent-error? true"
+ (with-card-mp-and-stubs!
+ (fn []
+ (try
+ (construct/execute-representations-query
+ (query-data
+ {"lib/type" "mbql/query"
+ "database" "Sample"
+ ;; 21-char NanoID-shape so the serdes resolver actually dispatches on the
+ ;; `source-card` branch; stub returns nil for this id so we exercise the
+ ;; :unknown-card ex-info path.
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-card" "zzzNotAReal0EntityId_"
+ "fields" [["field" {"base-type" "type/Float"} "TOTAL"]]}]}))
+ (is false "expected throw")
+ (catch clojure.lang.ExceptionInfo e
+ (let [d (ex-data e)]
+ (is (true? (:agent-error? d)))
+ (is (= :unknown-card (:error d))))))))))
+
+(deftest source-card-schema-rejects-non-string-value-test
+ (testing "`source-card:` must be a string entity_id; integer and other types are rejected at validation"
+ (with-card-mp-and-stubs!
+ (fn []
+ (try
+ (construct/execute-representations-query
+ (query-data
+ {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-card" 500
+ "fields" [["field" {"base-type" "type/Float"} "TOTAL"]]}]}))
+ (is false "expected throw")
+ (catch clojure.lang.ExceptionInfo e
+ (is (true? (:agent-error? (ex-data e))))))))))
diff --git a/test/metabase/metabot/tools/document_test.clj b/test/metabase/metabot/tools/document_test.clj
index 72c576398ed..21cd85ca541 100644
--- a/test/metabase/metabot/tools/document_test.clj
+++ b/test/metabase/metabot/tools/document_test.clj
@@ -123,11 +123,12 @@
{:structured-output {:query-id "3"
:query {:database 1
:type "query"}}})]
+ ;; `construct-notebook-query-tool` is stubbed above, so the YAML string is an opaque
+ ;; placeholder — it only needs to be a string.
(let [result (document-tools/document-construct-model-chart-tool
{:name "Test Name"
:description "Test Desc"
- :source_entity {:type "model" :id 4}
- :program {:source {:type "context" :ref "source"} :operations []}
+ :query ""
:viz_settings {:chart_type "bar"}})
structured (:structured-output result)]
(is (true? (:final-response? result)))
diff --git a/test/metabase/metabot/tools/entity_details_test.clj b/test/metabase/metabot/tools/entity_details_test.clj
index eac9caa525b..5a031ed4ce6 100644
--- a/test/metabase/metabot/tools/entity_details_test.clj
+++ b/test/metabase/metabot/tools/entity_details_test.clj
@@ -6,7 +6,8 @@
[metabase.lib.metadata :as lib.metadata]
[metabase.metabot.tools.entity-details :as entity-details]
[metabase.test :as mt]
- [metabase.test.fixtures :as fixtures]))
+ [metabase.test.fixtures :as fixtures]
+ [toucan2.core :as t2]))
(use-fixtures :once (fixtures/initialize :db :test-users))
@@ -200,11 +201,26 @@
measures (:measures output)]
(is (sequential? measures))
(is (= 1 (count measures)))
- (let [measure (first measures)]
+ (let [measure (first measures)
+ definition (:definition measure)]
(is (= measure-id (:id measure)))
(is (= "Total Revenue" (:name measure)))
(is (string? (:definition-description measure)))
- (is (map? (:definition measure)))))))))))
+ (testing "portable_entity_id is surfaced (21-char NanoID for `[measure, {}, <pid>]` clauses)"
+ (is (string? (:portable-entity-id measure)))
+ (is (= 21 (count (:portable-entity-id measure)))))
+ (testing "definition is a portable aggregation clause array"
+ (is (vector? definition))
+ (is (= 1 (count definition))
+ "measures have exactly one aggregation clause")
+ (let [[head opts arg] (first definition)]
+ (is (= "sum" head) "head is a string operator")
+ (is (map? opts) "options map at position 1")
+ (is (= "field" (first arg)) "argument is a field clause")
+ (is (vector? (nth arg 2))
+ "field's FK is a portable string array (not numeric id)")
+ (is (every? (some-fn string? nil?) (nth arg 2))
+ "every portable FK segment is a string (or null for schemaless)")))))))))))
(deftest get-table-details-with-segments-test
(testing "get-table-details returns segments when with_segments is true"
@@ -227,11 +243,111 @@
segments (:segments output)]
(is (sequential? segments))
(is (= 1 (count segments)))
- (let [segment (first segments)]
+ (let [segment (first segments)
+ definition (:definition segment)]
(is (= segment-id (:id segment)))
(is (= "High Value Orders" (:name segment)))
(is (string? (:definition-description segment)))
- (is (map? (:definition segment)))))))))))
+ (testing "portable_entity_id is surfaced (21-char NanoID for `[segment, {}, <pid>]` clauses)"
+ (is (string? (:portable-entity-id segment)))
+ (is (= 21 (count (:portable-entity-id segment)))))
+ (testing "definition is a portable filter clause array"
+ (is (vector? definition))
+ (is (>= (count definition) 1)
+ "segments have one or more filter clauses")
+ (let [[head opts field-clause value] (first definition)]
+ (is (= ">" head) "head is a string operator")
+ (is (map? opts) "options map at position 1")
+ (is (= "field" (first field-clause)) "argument is a field clause")
+ (is (vector? (nth field-clause 2))
+ "field's FK is a portable string array")
+ (is (= 100 value) "literal comparison value is preserved")))))))))))
+
+(deftest measure-segment-definition-round-trips-through-construct-test
+ (testing (str "the exported measure/segment definition is in the exact portable form "
+ "an agent can paste into construct_notebook_query's external-query — "
+ "regression test for benchmark/5 Tables - Measures and Segments failures")
+ (let [measure-def (measure-definition (mt/id :orders) (mt/id :orders :total))
+ segment-def (segment-definition (mt/id :orders) (mt/id :orders :total) 100)
+ table-fk [(:name (lib.metadata/database (mt/metadata-provider)))
+ (:schema (lib.metadata/table (mt/metadata-provider) (mt/id :orders)))
+ "ORDERS"]]
+ (mt/with-temp [:model/Measure _ {:name "Round-trip Measure"
+ :table_id (mt/id :orders)
+ :definition measure-def}
+ :model/Segment _ {:name "Round-trip Segment"
+ :table_id (mt/id :orders)
+ :definition segment-def}]
+ (mt/with-current-user (mt/user->id :crowberto)
+ (let [result (entity-details/get-table-details
+ {:entity-type :table :entity-id (mt/id :orders)
+ :with-measures? true :with-segments? true})
+ output (:structured-output result)
+ m-clause (-> output :measures first :definition)
+ s-clause (-> output :segments first :definition)
+ ;; Simulate the agent pasting these clauses into a fresh external-query.
+ fresh-query {:lib/type "mbql/query"
+ :stages [{:lib/type "mbql.stage/mbql"
+ :source-table table-fk
+ :aggregation m-clause
+ :filters s-clause}]}]
+ (testing "external-query containing the pasted clauses resolves cleanly"
+ ;; require the construct-tool pipeline lazily — it's the agent-facing entry point
+ (let [repr (requiring-resolve 'metabase.agent-lib.representations/external-query->portable)
+ repair (requiring-resolve 'metabase.agent-lib.representations.repair/repair)
+ resolve-q (requiring-resolve 'metabase.agent-lib.representations.resolve/resolve-query)
+ mp ((requiring-resolve 'metabase.lib-be.core/application-database-metadata-provider) (mt/id))
+ cs @(requiring-resolve 'metabase.models.serialization.resolve.mp/unchecked-app-db-content-store)
+ portable (repr fresh-query)
+ repaired (repair mp portable cs)
+ resolved (resolve-q mp repaired cs)]
+ (is (= :mbql/query (:lib/type resolved)))
+ (is (= 1 (count (get-in resolved [:stages 0 :aggregation]))))
+ (is (= 1 (count (get-in resolved [:stages 0 :filters]))))))))))))
+
+(deftest measure-segment-opaque-id-clause-round-trips-test
+ (testing (str "the `portable_entity_id` surfaced on `<measure>` / `<segment>` can be used in "
+ "`[measure, {}, pid]` / `[segment, {}, pid]` clauses end-to-end — regression "
+ "test for benchmark/6 Tables-MS rubric (data_source must reference the ids)")
+ (let [measure-def (measure-definition (mt/id :orders) (mt/id :orders :total))
+ segment-def (segment-definition (mt/id :orders) (mt/id :orders :total) 100)
+ table-fk [(:name (lib.metadata/database (mt/metadata-provider)))
+ (:schema (lib.metadata/table (mt/metadata-provider) (mt/id :orders)))
+ "ORDERS"]]
+ (mt/with-temp [:model/Measure {measure-id :id measure-pid :entity_id}
+ {:name "Opaque Measure"
+ :table_id (mt/id :orders)
+ :definition measure-def}
+ :model/Segment {segment-id :id segment-pid :entity_id}
+ {:name "Opaque Segment"
+ :table_id (mt/id :orders)
+ :definition segment-def}]
+ (mt/with-current-user (mt/user->id :crowberto)
+ (let [;; Mirrors what the agent does: paste `[measure, {}, "<pid>"]` and
+ ;; `[segment, {}, "<pid>"]` into a fresh external-query and send it.
+ fresh-query {:lib/type "mbql/query"
+ :stages [{:lib/type "mbql.stage/mbql"
+ :source-table table-fk
+ :aggregation [["measure" {} measure-pid]]
+ :filters [["segment" {} segment-pid]]}]}
+ repr (requiring-resolve 'metabase.agent-lib.representations/external-query->portable)
+ repair (requiring-resolve 'metabase.agent-lib.representations.repair/repair)
+ resolve-q (requiring-resolve 'metabase.agent-lib.representations.resolve/resolve-query)
+ mp ((requiring-resolve 'metabase.lib-be.core/application-database-metadata-provider) (mt/id))
+ cs @(requiring-resolve 'metabase.models.serialization.resolve.mp/unchecked-app-db-content-store)
+ portable (repr fresh-query)
+ repaired (repair mp portable cs)
+ resolved (resolve-q mp repaired cs)]
+ (testing "measure clause resolves to numeric id (rubric's `data_source` check)"
+ (let [agg (get-in resolved [:stages 0 :aggregation])]
+ (is (= 1 (count agg)))
+ (is (= :measure (first (first agg))))
+ (is (= measure-id (nth (first agg) 2)))))
+ (testing "segment clause resolves to numeric id"
+ (let [filters (get-in resolved [:stages 0 :filters])]
+ (is (= 1 (count filters)))
+ (is (= :segment (first (first filters))))
+ (is (= segment-id (nth (first filters) 2)))))))))))
(deftest get-table-details-measures-scoped-to-table-test
(testing "get-table-details only returns measures for the requested table, not other tables"
@@ -283,3 +399,129 @@
(let [segment (first segments)]
(is (= segment-id (:id segment)))
(is (= "Large Orders" (:name segment)))))))))))
+
+;;; ============================================================
+;;; Base-table surfacing on get-metric-details (regression)
+;;; ============================================================
+
+(deftest get-metric-details-exposes-base-table-test
+ (testing (str "get-metric-details must populate `:base_table_id`, `:base_table_name`, and\n"
+ "`:base_table_portable_fk` so the LLM can write `source-table:` verbatim.\n"
+ "Regression: earlier code read `(some-> (:dataset-query card) :query :source-table)`,\n"
+ "which silently produced nil because the t2 row uses `:dataset_query` (snake_case)\n"
+ "and the query is MBQL 5 with `:stages[0] :source-table`, not legacy `:query`.\n"
+ "The fix reads `:table_id` directly from the card row.")
+ (let [mp (mt/metadata-provider)
+ metric-query (-> (lib/query mp (lib.metadata/table mp (mt/id :orders)))
+ (lib/aggregate (lib/sum (lib.metadata/field mp (mt/id :orders :total)))))]
+ (mt/with-temp [:model/Card {metric-id :id} {:dataset_query metric-query
+ :database_id (mt/id)
+ :name "Base-table Sample Metric"
+ :type :metric}]
+ (mt/with-current-user (mt/user->id :crowberto)
+ (let [output (:structured-output (entity-details/get-metric-details
+ {:metric-id metric-id
+ :with-queryable-dimensions? false
+ :with-field-values? false}))
+ db-name (t2/select-one-fn :name :model/Database :id (mt/id))
+ orders (t2/select-one [:model/Table :schema :name] :id (mt/id :orders))]
+ (is (= (mt/id :orders) (:base_table_id output)))
+ (is (= (:name orders) (:base_table_name output)))
+ (is (= [db-name (:schema orders) (:name orders)]
+ (:base_table_portable_fk output))
+ "portable FK should be `[database_name, schema, table_name]`")))))))
+
+;;; ============================================================
+;;; Portable entity_id in card details (step 11.2)
+;;; ============================================================
+
+(deftest get-entity-details-question-exposes-portable-entity-id-test
+ (testing "card details (question) expose :portable_entity_id for the agent to use in source-card"
+ (mt/test-driver :h2
+ (mt/with-current-user (mt/user->id :crowberto)
+ (mt/with-temp [:model/Card {card-id :id card-eid :entity_id}
+ {:database_id (mt/id)
+ :type :question
+ :name "My Saved Q"
+ :dataset_query {:database (mt/id)
+ :type :query
+ :query {:source-table (mt/id :venues)}}}]
+ (let [result (entity-details/get-table-details {:entity-type :question :entity-id card-id})
+ output (:structured-output result)]
+ (is (= :question (:type output)))
+ (is (= card-id (:id output)))
+ (is (= card-eid (:portable_entity_id output)))
+ (is (string? (:portable_entity_id output)))))))))
+
+(deftest get-entity-details-model-exposes-portable-entity-id-test
+ (testing "card details (model) also expose :portable_entity_id"
+ (mt/test-driver :h2
+ (mt/with-current-user (mt/user->id :crowberto)
+ (mt/with-temp [:model/Card {card-id :id card-eid :entity_id}
+ {:database_id (mt/id)
+ :type :model
+ :name "My Model"
+ :dataset_query {:database (mt/id)
+ :type :query
+ :query {:source-table (mt/id :venues)}}}]
+ (let [result (entity-details/get-table-details {:entity-type :model :entity-id card-id})
+ output (:structured-output result)]
+ (is (= :model (:type output)))
+ (is (= card-id (:id output)))
+ (is (= card-eid (:portable_entity_id output)))))))))
+
+(deftest card-details-exposes-query-json-structured-test
+ (testing "card-details surfaces the saved structured query as a portable representations map"
+ (mt/test-driver :h2
+ (mt/with-current-user (mt/user->id :crowberto)
+ (mt/with-temp [:model/Card {card-id :id}
+ {:database_id (mt/id)
+ :type :question
+ :name "Venues by Price"
+ :dataset_query (mt/mbql-query venues {:aggregation [[:count]]
+ :breakout [$price]})}]
+ (let [output (-> (entity-details/get-table-details {:entity-type :question :entity-id card-id})
+ :structured-output)
+ exported (:query_json output)]
+ (is (map? exported)
+ "`:query_json` is present for an MBQL question")
+ (is (= "mbql/query" (get exported "lib/type")))
+ ;; Portable FK paths use the human-readable database name, not numeric ids.
+ (is (vector? (get-in exported ["stages" 0 "source-table"])))
+ (is (not (contains? exported "lib/metadata")))))))))
+
+(deftest card-details-exposes-query-json-native-test
+ (testing "card-details surfaces native saved queries as a portable repr map, preserving the SQL inside"
+ (mt/test-driver :h2
+ (mt/with-current-user (mt/user->id :crowberto)
+ (mt/with-temp [:model/Card {card-id :id}
+ {:database_id (mt/id)
+ :type :question
+ :name "Native Venues"
+ :dataset_query {:database (mt/id)
+ :type :native
+ :native {:query "SELECT * FROM VENUES LIMIT 5"}}}]
+ (let [output (-> (entity-details/get-table-details {:entity-type :question :entity-id card-id})
+ :structured-output)
+ exported (:query_json output)]
+ (is (map? exported))
+ (is (= "mbql/query" (get exported "lib/type")))
+ (is (= "mbql.stage/native" (get-in exported ["stages" 0 "lib/type"]))
+ "native stage is exported in the canonical repr form, not as a bare SQL string")
+ (is (= "SELECT * FROM VENUES LIMIT 5"
+ (get-in exported ["stages" 0 "native"]))
+ "the SQL body itself is preserved verbatim inside `native:`")))))))
+
+(deftest get-report-details-includes-query-json-test
+ (testing "get-report-details (slim payload) carries `:query_json` so question->xml can render it"
+ (mt/test-driver :h2
+ (mt/with-current-user (mt/user->id :crowberto)
+ (mt/with-temp [:model/Card {card-id :id}
+ {:database_id (mt/id)
+ :type :question
+ :name "Q"
+ :dataset_query (mt/mbql-query venues {:limit 3})}]
+ (let [output (-> (entity-details/get-report-details {:report-id card-id})
+ :structured-output)]
+ (is (map? (:query_json output)))
+ (is (= "mbql/query" (get-in output [:query_json "lib/type"])))))))))
diff --git a/test/metabase/metabot/tools/resources_test.clj b/test/metabase/metabot/tools/resources_test.clj
index d5e33709172..176b6e25b23 100644
--- a/test/metabase/metabot/tools/resources_test.clj
+++ b/test/metabase/metabot/tools/resources_test.clj
@@ -7,7 +7,7 @@
[metabase.lib.core :as lib]
[metabase.lib.metadata :as lib.metadata]
[metabase.metabot.tools.resources :as read-resource]
- [metabase.metabot.tools.shared.llm-representations :as llm-rep]
+ [metabase.metabot.tools.shared.llm-shape :as llm-shape]
[metabase.models.interface :as mi]
[metabase.query-processor :as qp]
[metabase.test :as mt]
@@ -69,7 +69,7 @@
(let [parsed (#'read-resource/parse-uri "metabase://database/1/schemas/weird%2Fname/tables")]
(is (= ["database" "1" "schemas" "weird/name" "tables"] (:segments parsed))))
(testing "round-trips through metabase-uri"
- (let [uri (llm-rep/metabase-uri :database 1 "schemas" "weird/name" "tables")
+ (let [uri (llm-shape/metabase-uri :database 1 "schemas" "weird/name" "tables")
parsed (#'read-resource/parse-uri uri)]
(is (= "metabase://database/1/schemas/weird%2Fname/tables" uri))
(is (= ["database" "1" "schemas" "weird/name" "tables"] (:segments parsed)))))))
@@ -689,7 +689,7 @@
(mt/with-temp [:model/Database {db-id :id} {}
:model/Table {weird-id :id} {:db_id db-id :schema "weird/name" :name "WEIRD-TABLE" :active true}
:model/Table _ {:db_id db-id :schema "other" :name "OTHER-TABLE" :active true}]
- (let [emitted-uri (llm-rep/metabase-uri :database db-id "schemas" "weird/name" "tables")]
+ (let [emitted-uri (llm-shape/metabase-uri :database db-id "schemas" "weird/name" "tables")]
(testing "the URI builder emits an encoded segment"
(is (str/includes? emitted-uri "weird%2Fname")))
(testing "the encoded URI dispatches and filters to the right schema"
@@ -773,8 +773,7 @@
output (:output read-result)
structured (get-in read-result [:resources 0 :content :structured-output])]
(testing "Output references expected fields"
- (is (re-find #"display_name\S+Count" output))
- (is (re-find #"display_name\S+Category" output)))
+ (is (re-find #"<name>\S*My fav card" output)))
(testing "Structured output contains expected fields"
(is (=? {:fields [{:display_name "Category"}
{:display_name "Count"}]}
diff --git a/test/metabase/metabot/tools/search_test.clj b/test/metabase/metabot/tools/search_test.clj
index 4ab716b0985..57da234bd9a 100644
--- a/test/metabase/metabot/tools/search_test.clj
+++ b/test/metabase/metabot/tools/search_test.clj
@@ -380,6 +380,73 @@
(is (nil? (get-in no-desc-dash [:collection :description])))
(is (= "No Description" (get-in no-desc-dash [:collection :name]))))))))))))
+(deftest enrich-with-portable-entity-ids-test
+ (testing "saved-question and model search results expose `portable_entity_id` (the card's NanoID)\nso the LLM can use it verbatim as `source-card:` without a follow-up entity_details call"
+ (mt/with-test-user :crowberto
+ (search.tu/with-temp-index-table
+ (mt/with-temp [:model/Card {q-id :id q-eid :entity_id} {:name "PortableEID Sample Question"
+ :type :question
+ :database_id (mt/id)
+ :table_id (mt/id :orders)
+ :dataset_query {:database (mt/id)
+ :type :query
+ :query {:source-table (mt/id :orders)
+ :aggregation [[:count]]}}}
+ :model/Card {m-id :id m-eid :entity_id} {:name "PortableEID Sample Model"
+ :type :model
+ :database_id (mt/id)
+ :table_id (mt/id :orders)
+ :dataset_query {:database (mt/id)
+ :type :query
+ :query {:source-table (mt/id :orders)}}}
+ :model/Dashboard {dash-id :id} {:name "PortableEID Sample Dashboard"}]
+ (let [results (search/search {:term-queries ["PortableEID Sample"]})
+ by-id (into {} (map (juxt (juxt :id :type) identity)) results)
+ question-res (get by-id [q-id "question"])
+ model-res (get by-id [m-id "model"])
+ dash-res (get by-id [dash-id "dashboard"])]
+ (testing "question results carry :portable_entity_id copied from the card's entity_id"
+ (is (some? question-res) "expected the question to appear in search results")
+ (is (= q-eid (:portable_entity_id question-res))))
+ (testing "model results carry :portable_entity_id too"
+ (is (some? model-res) "expected the model to appear in search results")
+ (is (= m-eid (:portable_entity_id model-res))))
+ (testing "dashboard results do NOT get :portable_entity_id (source-card only accepts cards)"
+ (is (some? dash-res) "expected the dashboard to appear in search results")
+ (is (not (contains? dash-res :portable_entity_id))))))))))
+
+(deftest enrich-with-metric-base-tables-test
+ (testing (str "Metric search results carry `base_table_*` fields so the LLM can write\n"
+ "`source-table:` without a separate entity_details call. We look up\n"
+ "`report_card.table_id` → `metabase_table.{schema,name}` and assemble the\n"
+ "portable FK `[database_name, schema, table_name]`. This closes the failure\n"
+ "mode where the LLM saw a metric in search, had its portable_entity_id, but\n"
+ "hallucinated the base table (`[<db>, public, customers]`).")
+ (mt/with-test-user :crowberto
+ (search.tu/with-temp-index-table
+ (mt/with-temp [:model/Card {metric-id :id} {:name "BaseTable Sample Metric"
+ :type :metric
+ :database_id (mt/id)
+ :table_id (mt/id :orders)
+ :dataset_query
+ {:database (mt/id)
+ :type :query
+ :query {:source-table (mt/id :orders)
+ :aggregation [[:count]]}}}]
+ (let [results (search/search {:term-queries ["BaseTable Sample Metric"]})
+ by-id (into {} (map (juxt (juxt :id :type) identity)) results)
+ metric-res (get by-id [metric-id "metric"])
+ db-name (t2/select-one-fn :name :model/Database :id (mt/id))
+ orders-t (t2/select-one [:model/Table :schema :name] :id (mt/id :orders))]
+ (is (some? metric-res) "metric should appear in search results")
+ (testing "base_table_* fields are populated"
+ (is (= (mt/id :orders) (:base_table_id metric-res)))
+ (is (= (:name orders-t) (:base_table_name metric-res)))
+ (is (= (:schema orders-t) (:base_table_schema metric-res))))
+ (testing "base_table_portable_fk is `[database_name, schema, table_name]`"
+ (is (= [db-name (:schema orders-t) (:name orders-t)]
+ (:base_table_portable_fk metric-res))))))))))
+
(deftest remove-unreadable-transforms-test
(testing "remove-unreadable-transforms correctly filters transforms based on source database access"
(mt/with-premium-features #{:transforms-basic}
diff --git a/test/metabase/metabot/tools/shared/content_store_test.clj b/test/metabase/metabot/tools/shared/content_store_test.clj
new file mode 100644
index 00000000000..bdca1750a6b
--- /dev/null
+++ b/test/metabase/metabot/tools/shared/content_store_test.clj
@@ -0,0 +1,134 @@
+(ns metabase.metabot.tools.shared.content-store-test
+ "Unit tests for the read-checked ContentStore wrapper.
+
+ These tests pin two properties:
+
+ 1. **Pass-through when no user is bound** — serdes import / background tasks / REPL runs
+ must keep working without an authenticated user. The wrapper short-circuits
+ `api/read-check` and returns the inner store's row unchanged.
+
+ 2. **Read-checked when a user is bound** — every method (5 total, symmetric across import-
+ and export-direction lookups) routes through `api/read-check`. A user without read
+ perms gets a 403; the underlying store is consulted for the existence check, and
+ unknown / `nil` returns pass through cleanly so the per-model resolver can emit its
+ `:unknown-…` agent error."
+ (:require
+ [clojure.test :refer :all]
+ [metabase.api.common :as api]
+ [metabase.metabot.tools.shared.content-store :as shared.content-store]
+ [metabase.models.serialization.resolve.mp :as resolve.mp]
+ [metabase.test :as mt]))
+
+(defn- record-store
+ "A fake ContentStore that returns a fixed row for any of the 5 methods. Returning a fixed
+ row whose `:row-id` is the requested argument lets tests assert both that the inner
+ method was invoked (`:row-id` carries over) and what `:can-read?` posture each row has."
+ [{:keys [card measure-eid segment-eid measure-id segment-id]}]
+ (reify resolve.mp/ContentStore
+ (card-by-entity-id [_ _eid] card)
+ (measure-by-entity-id [_ _eid] measure-eid)
+ (segment-by-entity-id [_ _eid] segment-eid)
+ (measure-by-id [_ _id] measure-id)
+ (segment-by-id [_ _id] segment-id)))
+
+;;; ============================================================
+;;; Pass-through: no user bound
+;;; ============================================================
+
+(deftest pass-through-when-no-user-bound-test
+ (testing "with api/*current-user-id* unbound, every method returns the inner store's row unchanged"
+ ;; Plain Clojure maps don't satisfy `mi/can-read?`, so a `read-check` call would throw.
+ ;; The fact that these assertions pass proves no read-check fires.
+ (let [row {:opaque :marker}
+ store (record-store {:card row :measure-eid row :segment-eid row :measure-id row :segment-id row})
+ gated (shared.content-store/read-checked store)]
+ (is (nil? api/*current-user-id*) "precondition: no user bound")
+ (is (= row (resolve.mp/card-by-entity-id gated "x")))
+ (is (= row (resolve.mp/measure-by-entity-id gated "x")))
+ (is (= row (resolve.mp/segment-by-entity-id gated "x")))
+ (is (= row (resolve.mp/measure-by-id gated 1)))
+ (is (= row (resolve.mp/segment-by-id gated 1))))))
+
+(deftest nil-from-inner-store-passes-through-unchanged-test
+ (testing "when the inner store returns nil (unknown id), the wrapper returns nil — never throws"
+ (let [empty-store (record-store {})
+ gated (shared.content-store/read-checked empty-store)]
+ ;; nil result short-circuits the read-check branch in maybe-read-check, regardless of
+ ;; whether a user is bound. This is critical: the per-model resolver functions
+ ;; (`import-card-by-entity-id` etc.) translate `nil` into a clean `:unknown-card` /
+ ;; `:unknown-measure` / `:unknown-segment` agent error, and a stray throw here would
+ ;; turn that friendly diagnostic into a 500.
+ (binding [api/*current-user-id* 1]
+ (is (nil? (resolve.mp/card-by-entity-id gated "x")))
+ (is (nil? (resolve.mp/measure-by-entity-id gated "x")))
+ (is (nil? (resolve.mp/segment-by-entity-id gated "x")))
+ (is (nil? (resolve.mp/measure-by-id gated 1)))
+ (is (nil? (resolve.mp/segment-by-id gated 1)))))))
+
+;;; ============================================================
+;;; Read-checked when a user is bound
+;;; ============================================================
+
+(deftest applies-read-check-when-user-bound-test
+ (testing (str "with api/*current-user-id* bound, every method routes the inner row through "
+ "`api/read-check`. Using a row that doesn't satisfy `can-read?` proves the "
+ "check fires on each branch — we stub `api/read-check` to a recording fn so "
+ "we don't need a real auth setup, and assert it was called with the row.")
+ (let [calls (atom [])
+ row {:opaque :marker}
+ store (record-store {:card row :measure-eid row :segment-eid row :measure-id row :segment-id row})
+ gated (shared.content-store/read-checked store)]
+ (mt/with-dynamic-fn-redefs [api/read-check (fn [obj] (swap! calls conj obj) obj)]
+ (binding [api/*current-user-id* 1]
+ (testing "card-by-entity-id"
+ (is (= row (resolve.mp/card-by-entity-id gated "x")))
+ (is (= row (last @calls))))
+ (testing "measure-by-entity-id"
+ (is (= row (resolve.mp/measure-by-entity-id gated "x")))
+ (is (= row (last @calls))))
+ (testing "segment-by-entity-id"
+ (is (= row (resolve.mp/segment-by-entity-id gated "x")))
+ (is (= row (last @calls))))
+ (testing "measure-by-id"
+ (is (= row (resolve.mp/measure-by-id gated 1)))
+ (is (= row (last @calls))))
+ (testing "segment-by-id"
+ (is (= row (resolve.mp/segment-by-id gated 1)))
+ (is (= row (last @calls))))
+ (testing "every one of the five methods invoked read-check exactly once"
+ (is (= 5 (count @calls)))))))))
+
+(deftest propagates-read-check-403-test
+ (testing "if read-check throws (403), the wrapper propagates the exception unchanged"
+ (let [row {:opaque :marker}
+ store (record-store {:card row :measure-id row})
+ gated (shared.content-store/read-checked store)]
+ (mt/with-dynamic-fn-redefs [api/read-check (fn [_]
+ (throw (ex-info "Forbidden" {:status-code 403})))]
+ (binding [api/*current-user-id* 1]
+ (testing "import-direction branch"
+ (try
+ (resolve.mp/card-by-entity-id gated "x")
+ (is false "expected throw")
+ (catch clojure.lang.ExceptionInfo e
+ (is (= 403 (:status-code (ex-data e)))))))
+ (testing "export-direction branch (the N1 gap)"
+ (try
+ (resolve.mp/measure-by-id gated 1)
+ (is false "expected throw")
+ (catch clojure.lang.ExceptionInfo e
+ (is (= 403 (:status-code (ex-data e))))))))))))
+
+;;; ============================================================
+;;; default-store integration shape
+;;; ============================================================
+
+(deftest default-store-shape-test
+ (testing "default-store satisfies the ContentStore protocol"
+ (is (satisfies? resolve.mp/ContentStore shared.content-store/default-store)))
+ (testing "default-store returns nil for nonsense entity-ids (gated on entity-id?)"
+ ;; The underlying unchecked-app-db-content-store short-circuits non-NanoID strings to
+ ;; nil; the wrapper passes that through. No DB hit, no read-check invoked.
+ (is (nil? (resolve.mp/card-by-entity-id shared.content-store/default-store "not-a-nanoid")))
+ (is (nil? (resolve.mp/measure-by-entity-id shared.content-store/default-store "not-a-nanoid")))
+ (is (nil? (resolve.mp/segment-by-entity-id shared.content-store/default-store "not-a-nanoid")))))
diff --git a/test/metabase/metabot/tools/shared/llm_representations_test.clj b/test/metabase/metabot/tools/shared/llm_shape_test.clj
similarity index 61%
rename from test/metabase/metabot/tools/shared/llm_representations_test.clj
rename to test/metabase/metabot/tools/shared/llm_shape_test.clj
index 89ed138f625..66f490bca43 100644
--- a/test/metabase/metabot/tools/shared/llm_representations_test.clj
+++ b/test/metabase/metabot/tools/shared/llm_shape_test.clj
@@ -1,20 +1,20 @@
-(ns metabase.metabot.tools.shared.llm-representations-test
+(ns metabase.metabot.tools.shared.llm-shape-test
(:require
[clojure.string :as str]
[clojure.test :refer :all]
- [metabase.metabot.tools.shared.llm-representations :as llm-rep]))
+ [metabase.metabot.tools.shared.llm-shape :as llm-shape]))
(deftest escape-xml-test
(testing "escape-xml handles special characters"
- (is (= "&amp;" (#'llm-rep/escape-xml "&")))
- (is (= "&lt;" (#'llm-rep/escape-xml "<")))
- (is (= "&gt;" (#'llm-rep/escape-xml ">")))
- (is (= "&quot;" (#'llm-rep/escape-xml "\"")))
+ (is (= "&amp;" (#'llm-shape/escape-xml "&")))
+ (is (= "&lt;" (#'llm-shape/escape-xml "<")))
+ (is (= "&gt;" (#'llm-shape/escape-xml ">")))
+ (is (= "&quot;" (#'llm-shape/escape-xml "\"")))
(is (= "&lt;script&gt;alert(&quot;xss&quot;)&lt;/script&gt;"
- (#'llm-rep/escape-xml "<script>alert(\"xss\")</script>"))))
+ (#'llm-shape/escape-xml "<script>alert(\"xss\")</script>"))))
(testing "escape-xml handles nil"
- (is (nil? (#'llm-rep/escape-xml nil)))))
+ (is (nil? (#'llm-shape/escape-xml nil)))))
(deftest field->xml-test
(testing "formats field with all attributes matching Python format"
@@ -25,7 +25,7 @@
:type :integer
:database_type "INTEGER"
:description "The user identifier"}
- xml (llm-rep/field->xml field)]
+ xml (llm-shape/field->xml field)]
;; Python format: name="\"user_id\""
(is (str/includes? xml "id=\"f1\""))
(is (str/includes? xml "name=\"\\\"user_id\\\"\""))
@@ -37,15 +37,34 @@
(testing "handles missing optional attributes with defaults"
(let [field {:field_id "f1" :name "test"}
- xml (llm-rep/field->xml field)]
+ xml (llm-shape/field->xml field)]
(is (str/includes? xml "id=\"f1\""))
(is (str/includes? xml "name=\"\\\"test\\\"\""))
- (is (str/includes? xml "database_type=\"unknown\"")))))
+ (is (str/includes? xml "database_type=\"unknown\""))))
+
+ (testing "FK columns expose `fk_target_fully_qualified_name` so the LLM can join via the target table"
+ ;; Regression: earlier the `<field>` element rendered no FK hint, so a bare `customer_id`
+ ;; with no context led the LLM to assume related fields (like `email`) lived on the same
+ ;; table and produce `:unknown-field` errors. `->result-column` already computes
+ ;; `:fk_target_portable_fk`; `field->xml` now surfaces it.
+ (let [field {:field_id "892"
+ :name "customer_id"
+ :display_name "Customer ID"
+ :type :string
+ :database_type "varchar"
+ :fk_target_portable_fk ["Analytics" "customerio_data" "customer" "id"]}
+ xml (llm-shape/field->xml field)]
+ (is (str/includes? xml "fk_target_fully_qualified_name=\"customerio_data.customer.id\""))))
+
+ (testing "non-FK fields do not render an empty `fk_target_fully_qualified_name` attribute"
+ (let [field {:field_id "1" :name "total" :type :number}
+ xml (llm-shape/field->xml field)]
+ (is (not (str/includes? xml "fk_target_fully_qualified_name"))))))
(deftest collection->xml-test
(testing "formats collection with name"
(let [collection {:name "Finance" :description "Finance reports" :authority_level "official"}
- xml (llm-rep/collection->xml collection)]
+ xml (llm-shape/collection->xml collection)]
(is (str/includes? xml "<collection"))
(is (str/includes? xml "name=\"Finance\""))
(is (str/includes? xml "authority_level=\"official\""))
@@ -53,7 +72,7 @@
(testing "uses default name for nil"
(let [collection {:name nil}
- xml (llm-rep/collection->xml collection)]
+ xml (llm-shape/collection->xml collection)]
(is (str/includes? xml "name=\"Our analytics\"")))))
(deftest metric->xml-test
@@ -65,7 +84,7 @@
:collection {:name "Finance"}
:default_time_dimension_field {:name "created_at"}
:queryable-dimensions [{:name "date" :field_id "d1" :base-type :type/Date :database_type "DATE"}]}
- xml (llm-rep/metric->xml metric)]
+ xml (llm-shape/metric->xml metric)]
(is (str/starts-with? xml "<metric"))
;; Python format: id="42", name="Total Revenue"
(is (str/includes? xml "id=\"42\", name=\"Total Revenue\""))
@@ -81,32 +100,49 @@
(testing "handles metric without dimensions"
(let [metric {:id 1 :name "Test" :verified false}
- xml (llm-rep/metric->xml metric)]
+ xml (llm-shape/metric->xml metric)]
(is (str/includes? xml "is_verified=\"false\""))
(is (not (str/includes? xml "### Dimensions"))))))
(deftest measure->xml-test
(testing "formats measure with all attributes"
- (let [measure {:id 1
+ (let [;; The new contract: `:definition` is a portable aggregation clause vector,
+ ;; produced by `convert-measure-or-segment` via `repr.resolve/export-query`.
+ ;; `:portable-entity-id` is the 21-char NanoID the agent pastes into
+ ;; `["measure", {}, "<pid>"]` clauses.
+ measure {:id 1
:name "total_revenue"
:display-name "Total Revenue"
:description "Sum of all revenue"
- :definition {:database 1 :type :query :query {:source-table 5 :aggregation [[:sum [:field 10 nil]]]}}
- :definition-description "Sum of Price"}
- xml (llm-rep/measure->xml measure)]
+ :portable-entity-id "Xagv1NMQROhFqne5Z3l3N"
+ :definition [["sum" {} ["field" {} ["DB" "PUBLIC" "ORDERS" "TOTAL"]]]]
+ :definition-description "Sum of Total"}
+ xml (llm-shape/measure->xml measure)]
(is (str/starts-with? xml "<measure"))
(is (str/includes? xml "measure_id=\"1\""))
(is (str/includes? xml "name=\"total_revenue\""))
(is (str/includes? xml "display_name=\"Total Revenue\""))
+ (is (str/includes? xml "portable_entity_id=\"Xagv1NMQROhFqne5Z3l3N\""))
(is (str/includes? xml "Sum of all revenue"))
- (is (str/includes? xml "Definition: Sum of Price"))
+ ;; The human-prose `Definition: <description>` line is gone. The structured
+ ;; `<definition>...</definition>` block below carries the same information for the LLM.
+ (is (not (str/includes? xml "Definition: Sum of Total")))
(is (str/includes? xml "<definition>"))
- (is (str/includes? xml ":source-table 5"))
+ (testing "definition renders as a fenced JSON code block"
+ (is (str/includes? xml "```json"))
+ (is (str/includes? xml "\"sum\""))
+ (is (str/includes? xml "\"ORDERS\""))
+ (is (str/includes? xml "\"TOTAL\"")))
(is (str/ends-with? (str/trim xml) "</measure>"))))
+ (testing "omits portable_entity_id attribute when not present (legacy / unsaved measure)"
+ (let [measure {:id 99 :name "no_pid"}
+ xml (llm-shape/measure->xml measure)]
+ (is (not (str/includes? xml "portable_entity_id")))))
+
(testing "handles measure without description or definition"
(let [measure {:id 2 :name "count_orders"}
- xml (llm-rep/measure->xml measure)]
+ xml (llm-shape/measure->xml measure)]
(is (str/includes? xml "measure_id=\"2\""))
(is (str/includes? xml "name=\"count_orders\""))
(is (str/includes? xml "display_name=\"count_orders\""))
@@ -116,32 +152,49 @@
(testing "uses name as display_name fallback"
(let [measure {:id 3 :name "avg_price" :display-name nil}
- xml (llm-rep/measure->xml measure)]
+ xml (llm-shape/measure->xml measure)]
(is (str/includes? xml "display_name=\"avg_price\"")))))
(deftest segment->xml-test
(testing "formats segment with all attributes"
- (let [segment {:id 1
+ (let [;; The new contract: `:definition` is a portable filter clause vector;
+ ;; `:portable-entity-id` is the NanoID the agent pastes into `["segment", {}, "<pid>"]`.
+ segment {:id 1
:name "active_customers"
:display-name "Active Customers"
:description "Customers who made a purchase in the last 30 days"
- :definition {:database 1 :type :query :query {:source-table 5 :filter [:> [:field 10 nil] 0]}}
- :definition-description "Price is greater than 0"}
- xml (llm-rep/segment->xml segment)]
+ :portable-entity-id "SU_Ge6qwCh_-2XE10h11p"
+ :definition [[">" {} ["field" {} ["DB" "PUBLIC" "ORDERS" "TOTAL"]] 0]]
+ :definition-description "Total is greater than 0"}
+ xml (llm-shape/segment->xml segment)]
(is (str/starts-with? xml "<segment"))
- (is (str/includes? xml "segment_id=\"1\""))
+ ;; The `<segment id=...>` attribute is named `id` (not `segment_id`) for consistency with
+ ;; <table>, <metabase-model>, <metric> and friends. Renamed in the d47d35b7bec slim-down.
+ (is (str/includes? xml "id=\"1\""))
(is (str/includes? xml "name=\"active_customers\""))
(is (str/includes? xml "display_name=\"Active Customers\""))
+ (is (str/includes? xml "portable_entity_id=\"SU_Ge6qwCh_-2XE10h11p\""))
(is (str/includes? xml "Customers who made a purchase in the last 30 days"))
- (is (str/includes? xml "Definition: Price is greater than 0"))
+ ;; The human-prose `Definition: <description>` line is gone. The structured
+ ;; `<definition>...</definition>` block below carries the same information for the LLM.
+ (is (not (str/includes? xml "Definition: Total is greater than 0")))
(is (str/includes? xml "<definition>"))
- (is (str/includes? xml ":source-table 5"))
+ (testing "definition renders as a fenced JSON code block"
+ (is (str/includes? xml "```json"))
+ (is (str/includes? xml "\">\""))
+ (is (str/includes? xml "\"ORDERS\""))
+ (is (str/includes? xml "\"TOTAL\"")))
(is (str/ends-with? (str/trim xml) "</segment>"))))
+ (testing "omits portable_entity_id attribute when not present"
+ (let [segment {:id 99 :name "no_pid"}
+ xml (llm-shape/segment->xml segment)]
+ (is (not (str/includes? xml "portable_entity_id")))))
+
(testing "handles segment without description or definition-description"
(let [segment {:id 2 :name "new_users"}
- xml (llm-rep/segment->xml segment)]
- (is (str/includes? xml "segment_id=\"2\""))
+ xml (llm-shape/segment->xml segment)]
+ (is (str/includes? xml "id=\"2\""))
(is (str/includes? xml "name=\"new_users\""))
(is (not (str/includes? xml "<definition>")))
(is (not (str/includes? xml "Definition:")))
@@ -149,7 +202,7 @@
(testing "uses name as display_name fallback"
(let [segment {:id 3 :name "q4_orders" :display-name nil}
- xml (llm-rep/segment->xml segment)]
+ xml (llm-shape/segment->xml segment)]
(is (str/includes? xml "display_name=\"q4_orders\"")))))
(deftest table->xml-test
@@ -164,7 +217,7 @@
:fields [{:name "id" :field_id "f1" :base-type :type/Integer :database_type "INTEGER"}]
:related_tables [{:id 20 :name "orders" :fully_qualified_name "public.orders"
:related_by "user_id" :fields []}]}
- xml (llm-rep/table->xml table)]
+ xml (llm-shape/table->xml table)]
(is (str/starts-with? xml "<table"))
;; Python format: id="10", name="users"
(is (str/includes? xml "id=\"10\", name=\"users\""))
@@ -191,18 +244,18 @@
:description "Average value of orders"}]
:segments [{:id 2 :name "q4_orders" :display-name "Q4 Orders"
:description "Orders placed in Q4"}]}
- xml (llm-rep/table->xml table)]
+ xml (llm-shape/table->xml table)]
(is (str/includes? xml "### Measures (Pre-defined Aggregation Formulas)"))
(is (str/includes? xml "MEASURES (NOT metrics!)"))
(is (str/includes? xml "<measure measure_id=\"1\""))
(is (str/includes? xml "Average Order Value"))
(is (str/includes? xml "### Segments (Pre-defined Filter Conditions)"))
- (is (str/includes? xml "<segment segment_id=\"2\""))
+ (is (str/includes? xml "<segment id=\"2\""))
(is (str/includes? xml "Q4 Orders"))))
(testing "omits measures and segments sections when empty"
(let [table {:id 10 :name "users" :database_id 1 :database_engine "postgres"}
- xml (llm-rep/table->xml table)]
+ xml (llm-shape/table->xml table)]
(is (not (str/includes? xml "### Measures")))
(is (not (str/includes? xml "### Segments"))))))
@@ -215,7 +268,7 @@
:database_id 1
:database_engine "postgres"
:fields [{:name "revenue" :field_id "r1" :base-type :type/Float :database_type "DOUBLE"}]}
- xml (llm-rep/model->xml model)]
+ xml (llm-shape/model->xml model)]
;; Python uses <metabase-model> tag
(is (str/starts-with? xml "<metabase-model"))
(is (str/includes? xml "id=\"5\""))
@@ -241,20 +294,51 @@
:description "Net revenue after returns"}]
:segments [{:id 1 :name "new_customers" :display-name "New Customers"
:description "First-time buyers"}]}
- xml (llm-rep/model->xml model)]
+ xml (llm-shape/model->xml model)]
(is (str/includes? xml "### Measures (Pre-defined Aggregation Formulas)"))
(is (str/includes? xml "MEASURES (NOT metrics!)"))
(is (str/includes? xml "<measure measure_id=\"1\""))
(is (str/includes? xml "Total Net Revenue"))
(is (str/includes? xml "### Segments (Pre-defined Filter Conditions)"))
- (is (str/includes? xml "<segment segment_id=\"1\""))
+ (is (str/includes? xml "<segment id=\"1\""))
(is (str/includes? xml "New Customers"))))
(testing "omits measures and segments sections when empty"
(let [model {:id 5 :name "Empty Model" :database_id 1 :database_engine "postgres"}
- xml (llm-rep/model->xml model)]
+ xml (llm-shape/model->xml model)]
(is (not (str/includes? xml "### Measures")))
- (is (not (str/includes? xml "### Segments"))))))
+ (is (not (str/includes? xml "### Segments")))))
+
+ (testing "includes portable_entity_id when present (for `source-card:` lookups)"
+ (let [model {:id 6 :name "Portable Model" :database_id 1 :database_engine "postgres"
+ :portable_entity_id "bw41Vx2d-9d7sOScnaKlf"}
+ xml (llm-shape/model->xml model)]
+ (is (str/includes? xml "portable_entity_id=\"bw41Vx2d-9d7sOScnaKlf\""))))
+
+ (testing "omits portable_entity_id when absent"
+ (let [model {:id 7 :name "No EID Model" :database_id 1 :database_engine "postgres"}
+ xml (llm-shape/model->xml model)]
+ (is (not (str/includes? xml "portable_entity_id")))))
+
+ (testing "renders the saved query body as a <query> block when :query_json is provided"
+ (let [query-json {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]}]}
+ model {:id 8 :name "M" :database_id 1 :database_engine "postgres" :query_json query-json}
+ xml (llm-shape/model->xml model)]
+ (is (str/includes? xml "### Saved query"))
+ (is (str/includes? xml "<query>"))
+ (is (str/includes? xml "```json"))
+ (is (str/includes? xml "\"lib/type\""))
+ (is (str/includes? xml "</query>"))))
+
+ (testing "omits the <query> block when :query_json is missing or blank"
+ (let [xml-missing (llm-shape/model->xml {:id 9 :name "M" :database_id 1 :database_engine "postgres"})
+ xml-empty (llm-shape/model->xml {:id 10 :name "M" :database_id 1 :database_engine "postgres"
+ :query_json {}})]
+ (is (not (str/includes? xml-missing "<query>")))
+ (is (not (str/includes? xml-empty "<query>"))))))
(deftest query->xml-test
(testing "formats query result matching Python"
@@ -264,7 +348,7 @@
:query-content "SELECT * FROM users"
:result {:result_columns [{:name "id" :display_name "ID" :type "number"}]
:rows [[1] [2]]}}
- xml (llm-rep/query->xml query)]
+ xml (llm-shape/query->xml query)]
(is (str/starts-with? xml "<query"))
(is (str/includes? xml "type=\"sql\""))
(is (str/includes? xml "id=\"q123\""))
@@ -277,7 +361,7 @@
(testing "handles query with no result"
(let [query {:query-type :notebook :query-id "m1" :database_id 1}
- xml (llm-rep/query->xml query)]
+ xml (llm-shape/query->xml query)]
(is (str/includes? xml "type=\"notebook\""))
(is (not (str/includes? xml "<query_results>"))))))
@@ -286,7 +370,7 @@
(let [chart {:chart-id "ch-abc-123"
:query-id "q1"
:chart-type :bar}
- xml (llm-rep/chart->xml chart)]
+ xml (llm-shape/chart->xml chart)]
(is (str/starts-with? xml "<chart"))
(is (str/includes? xml "id=\"ch-abc-123\""))
(is (str/includes? xml "type=\"bar\""))
@@ -296,7 +380,7 @@
(testing "handles nil chart-type"
(let [chart {:chart-id "c1" :query-id "q1" :chart-type nil}
- xml (llm-rep/chart->xml chart)]
+ xml (llm-shape/chart->xml chart)]
(is (str/includes? xml "type=\"table\"")))))
(deftest visualization->xml-test
@@ -304,7 +388,7 @@
(let [viz {:chart-id "v1"
:queries [{:query-type :sql :query-id "q1" :database_id 1 :query-content "SELECT 1"}]
:visualization_settings {:chart_type "bar"}}
- xml (llm-rep/visualization->xml viz)]
+ xml (llm-shape/visualization->xml viz)]
(is (str/starts-with? xml "<chart"))
(is (str/includes? xml "id=\"v1\""))
(is (str/includes? xml "The chart is powered by the following queries"))
@@ -318,7 +402,7 @@
:description "Monthly revenue breakdown"
:verified true
:collection {:name "Finance"}}
- xml (llm-rep/question->xml question)]
+ xml (llm-shape/question->xml question)]
(is (str/starts-with? xml "<metabase_question"))
(is (str/includes? xml "id=\"100\""))
(is (str/includes? xml "is_verified=\"true\""))
@@ -330,13 +414,39 @@
(let [question {:id 101
:name "Pie Chart"
:display :pie}
- xml (llm-rep/question->xml question)]
+ xml (llm-shape/question->xml question)]
(is (str/includes? xml "display_type=\"pie\""))))
(testing "omits display_type when not present"
(let [question {:id 102
:name "No Display"}
- xml (llm-rep/question->xml question)]
- (is (not (str/includes? xml "display_type"))))))
+ xml (llm-shape/question->xml question)]
+ (is (not (str/includes? xml "display_type")))))
+ (testing "includes portable_entity_id when present (for `source-card:` lookups)"
+ (let [question {:id 103
+ :name "Portable Q"
+ :portable_entity_id "dh9P5mz7vhpqYUPosLPqL"}
+ xml (llm-shape/question->xml question)]
+ (is (str/includes? xml "portable_entity_id=\"dh9P5mz7vhpqYUPosLPqL\""))))
+ (testing "omits portable_entity_id when absent"
+ (let [question {:id 104 :name "No EID"}
+ xml (llm-shape/question->xml question)]
+ (is (not (str/includes? xml "portable_entity_id")))))
+ (testing "renders the saved query body as a <query> block when :query_json is provided"
+ (let [query-json {"lib/type" "mbql/query"
+ "database" "Sample"
+ "stages" [{"lib/type" "mbql.stage/mbql"
+ "source-table" ["Sample" "PUBLIC" "ORDERS"]}]}
+ xml (llm-shape/question->xml {:id 200 :name "Q" :query_json query-json})]
+ (is (str/includes? xml "<query>"))
+ (is (str/includes? xml "```json"))
+ (is (str/includes? xml "\"lib/type\""))
+ (is (str/includes? xml "\"source-table\""))
+ (is (str/includes? xml "</query>"))))
+ (testing "omits the <query> block when :query_json is missing or blank"
+ (let [xml-missing (llm-shape/question->xml {:id 201 :name "Q"})
+ xml-empty (llm-shape/question->xml {:id 202 :name "Q" :query_json {}})]
+ (is (not (str/includes? xml-missing "<query>")))
+ (is (not (str/includes? xml-empty "<query>"))))))
(deftest dashboard->xml-test
(testing "formats dashboard matching Python"
@@ -347,7 +457,7 @@
:collection {:name "Sales"}
:dashcards [{:id 1 :type :text :order 1 :width 6 :height 2
:dashboard_tab_id 0 :row 0 :col 0 :text "Welcome"}]}
- xml (llm-rep/dashboard->xml dashboard)]
+ xml (llm-shape/dashboard->xml dashboard)]
(is (str/starts-with? xml "<dashboard"))
(is (str/includes? xml "id=\"50\""))
(is (str/includes? xml "is_verified=\"true\""))
@@ -365,7 +475,7 @@
:name "John Doe"
:glossary {"ARR" "Annual Recurring Revenue"}}
- xml (llm-rep/user->xml user)]
+ xml (llm-shape/user->xml user)]
(is (str/starts-with? xml "<user>"))
(is (str/includes? xml "### User Info"))
(is (str/includes? xml "- Name: John Doe"))
@@ -383,7 +493,7 @@
:description "Total revenue calculation"
:verified true
:collection {:name "Finance"}}
- xml (llm-rep/search-result->xml result)]
+ xml (llm-shape/search-result->xml result)]
(is (str/starts-with? xml "<metric"))
(is (str/includes? xml "id=\"100\""))
(is (str/includes? xml "name=\"Revenue Metric\""))
@@ -399,7 +509,7 @@
:database_id 2
:database_engine :postgres
:database_schema "shopify_data"}
- xml (llm-rep/search-result->xml result)]
+ xml (llm-shape/search-result->xml result)]
(is (str/starts-with? xml "<table"))
(is (str/includes? xml "id=\"133\""))
(is (str/includes? xml "name=\"order\""))
@@ -413,7 +523,7 @@
:name "users"
:database_id 1
:database_engine :h2}
- xml (llm-rep/search-result->xml result)]
+ xml (llm-shape/search-result->xml result)]
(is (str/includes? xml "fully_qualified_name=\"users\""))
(is (str/includes? xml "database_engine=\"h2\""))))
@@ -424,36 +534,73 @@
:database_id 1
:database_engine :postgres
:verified true}
- xml (llm-rep/search-result->xml result)]
+ xml (llm-shape/search-result->xml result)]
(is (str/starts-with? xml "<model"))
(is (str/includes? xml "database_id=\"1\""))
(is (str/includes? xml "database_engine=\"postgres\""))
(is (str/includes? xml "fully_qualified_name=\"{#5}-sales-model\""))))
+ (testing "question search result includes portable_entity_id attribute when present"
+ (let [result {:id 175
+ :type "question"
+ :name "Orders, Count"
+ :verified false
+ :database_id 1
+ :database_engine "h2"
+ :portable_entity_id "dh9P5mz7vhpqYUPosLPqL"}
+ xml (llm-shape/search-result->xml result)]
+ (is (str/starts-with? xml "<question"))
+ (is (str/includes? xml "id=\"175\""))
+ (is (str/includes? xml "portable_entity_id=\"dh9P5mz7vhpqYUPosLPqL\""))))
+
+ (testing "model search result includes portable_entity_id attribute when present"
+ (let [result {:id 42
+ :type "model"
+ :name "Sales Model"
+ :verified true
+ :database_id 1
+ :database_engine "postgres"
+ :portable_entity_id "AbCdEfGhIjKlMnOpQrStU"}
+ xml (llm-shape/search-result->xml result)]
+ (is (str/includes? xml "portable_entity_id=\"AbCdEfGhIjKlMnOpQrStU\""))))
+
+ (testing "search result without portable_entity_id simply omits the attribute"
+ (let [result {:id 99 :type "question" :name "Legacy"
+ :verified false :database_id 1 :database_engine "h2"}
+ xml (llm-shape/search-result->xml result)]
+ (is (not (str/includes? xml "portable_entity_id")))))
+
+ (testing "table search result never carries portable_entity_id"
+ (let [result {:id 10 :type "table" :name "ORDERS"
+ :verified false :database_id 1 :database_engine "h2"
+ :database_schema "PUBLIC"}
+ xml (llm-shape/search-result->xml result)]
+ (is (not (str/includes? xml "portable_entity_id")))))
+
(testing "non-table/model search results omit table-specific attributes"
(let [result {:id 50
:type :dashboard
:name "Sales Dashboard"
:database_id nil}
- xml (llm-rep/search-result->xml result)]
+ xml (llm-shape/search-result->xml result)]
(is (not (str/includes? xml "fully_qualified_name")))
(is (not (str/includes? xml "database_id")))
(is (not (str/includes? xml "database_engine")))))
(testing "uses correct tag names for different types"
- (is (str/starts-with? (llm-rep/search-result->xml {:id 1 :type :table :name "t"}) "<table"))
+ (is (str/starts-with? (llm-shape/search-result->xml {:id 1 :type :table :name "t"}) "<table"))
;; Model uses <metabase-model> tag
- (is (str/starts-with? (llm-rep/search-result->xml {:id 1 :type :model :name "m"}) "<metabase-model"))
- (is (str/starts-with? (llm-rep/search-result->xml {:id 1 :type :dashboard :name "d"}) "<dashboard"))
+ (is (str/starts-with? (llm-shape/search-result->xml {:id 1 :type :model :name "m"}) "<metabase-model"))
+ (is (str/starts-with? (llm-shape/search-result->xml {:id 1 :type :dashboard :name "d"}) "<dashboard"))
;; Card/question uses <metabase_question> tag
- (is (str/starts-with? (llm-rep/search-result->xml {:id 1 :type :card :name "c"}) "<metabase_question"))
- (is (str/starts-with? (llm-rep/search-result->xml {:id 1 :type :dataset :name "d"}) "<metabase-model"))))
+ (is (str/starts-with? (llm-shape/search-result->xml {:id 1 :type :card :name "c"}) "<metabase_question"))
+ (is (str/starts-with? (llm-shape/search-result->xml {:id 1 :type :dataset :name "d"}) "<metabase-model"))))
(deftest search-results->xml-test
(testing "formats multiple search results"
(let [results [{:id 1 :type :metric :name "Metric 1"}
{:id 2 :type :table :name "Table 1"}]
- xml (llm-rep/search-results->xml results)]
+ xml (llm-shape/search-results->xml results)]
(is (str/includes? xml "Here are the search results:"))
(is (str/includes? xml "<search-results>"))
(is (str/includes? xml "<metric id=\"1\""))
@@ -461,7 +608,7 @@
(is (str/includes? xml "</search-results>"))))
(testing "handles empty results"
- (let [xml (llm-rep/search-results->xml [])]
+ (let [xml (llm-shape/search-results->xml [])]
(is (str/includes? xml "<search-results>"))
(is (str/includes? xml "</search-results>")))))
@@ -470,7 +617,7 @@
(let [metadata {:field_values ["US" "DE" "FR"]
:statistics {:sample_distinct_count 3
:sample_percent_null 0.05}}
- xml (llm-rep/field-values-metadata->xml metadata)]
+ xml (llm-shape/field-values-metadata->xml metadata)]
(is (str/includes? xml "**Sample Values (for understanding format pattern)**"))
(is (str/includes? xml "| Value |"))
(is (str/includes? xml "| US |"))
@@ -479,20 +626,20 @@
(testing "handles empty field values"
(let [metadata {:field_values []}
- xml (llm-rep/field-values-metadata->xml metadata)]
+ xml (llm-shape/field-values-metadata->xml metadata)]
(is (str/includes? xml "This field hasn't been sampled yet")))))
(deftest field-metadata->xml-test
(testing "formats field metadata"
(let [metadata {:field_id "f1"
:value_metadata {:field_values ["A" "B"]}}
- xml (llm-rep/field-metadata->xml metadata)]
+ xml (llm-shape/field-metadata->xml metadata)]
(is (str/includes? xml "<field-metadata field_id=\"f1\">"))
(is (str/includes? xml "**Sample Values"))))
(testing "handles nil value_metadata"
(let [metadata {:field_id "f1" :value_metadata nil}
- xml (llm-rep/field-metadata->xml metadata)]
+ xml (llm-shape/field-metadata->xml metadata)]
(is (str/includes? xml "No metadata available to display")))))
(deftest get-metadata-result->xml-test
@@ -500,7 +647,7 @@
(let [result {:metrics [{:id 1 :name "M1" :description "Metric 1"}]
:tables [{:id 2 :name "T1" :database_id 1 :description "Table 1"}]
:models [{:id 3 :name "Mo1" :description "Model 1"}]}
- xml (llm-rep/get-metadata-result->xml result)]
+ xml (llm-shape/get-metadata-result->xml result)]
(is (str/includes? xml "<metrics>"))
(is (str/includes? xml "</metrics>"))
(is (str/includes? xml "<tables>"))
@@ -511,26 +658,26 @@
(testing "handles no metadata"
(let [result {:metrics [] :tables [] :models []}
- xml (llm-rep/get-metadata-result->xml result)]
+ xml (llm-shape/get-metadata-result->xml result)]
(is (str/includes? xml "No metadata was returned"))))
(testing "includes errors"
(let [result {:metrics [] :tables [] :models [] :errors ["Error 1"]}
- xml (llm-rep/get-metadata-result->xml result)]
+ xml (llm-shape/get-metadata-result->xml result)]
(is (str/includes? xml "<errors>"))
(is (str/includes? xml "Error 1")))))
(deftest entity->xml-test
(testing "dispatches to correct formatter based on type"
- (is (str/starts-with? (llm-rep/entity->xml {:type :metric :id 1 :name "m"}) "<metric"))
- (is (str/starts-with? (llm-rep/entity->xml {:type :table :id 1 :name "t" :database_id 1}) "<table"))
+ (is (str/starts-with? (llm-shape/entity->xml {:type :metric :id 1 :name "m"}) "<metric"))
+ (is (str/starts-with? (llm-shape/entity->xml {:type :table :id 1 :name "t" :database_id 1}) "<table"))
;; Model uses <metabase-model>
- (is (str/starts-with? (llm-rep/entity->xml {:type :model :id 1 :name "m"}) "<metabase-model"))
- (is (str/starts-with? (llm-rep/entity->xml {:type :question :id 1 :name "q"}) "<metabase_question"))
- (is (str/starts-with? (llm-rep/entity->xml {:type :dashboard :id 1 :name "d"}) "<dashboard"))
- (is (str/starts-with? (llm-rep/entity->xml {:type :user :id 1 :name "u" :email "[email protected]"}) "<user"))
- (is (str/starts-with? (llm-rep/entity->xml {:type :collection :name "c"}) "<collection")))
+ (is (str/starts-with? (llm-shape/entity->xml {:type :model :id 1 :name "m"}) "<metabase-model"))
+ (is (str/starts-with? (llm-shape/entity->xml {:type :question :id 1 :name "q"}) "<metabase_question"))
+ (is (str/starts-with? (llm-shape/entity->xml {:type :dashboard :id 1 :name "d"}) "<dashboard"))
+ (is (str/starts-with? (llm-shape/entity->xml {:type :user :id 1 :name "u" :email "[email protected]"}) "<user"))
+ (is (str/starts-with? (llm-shape/entity->xml {:type :collection :name "c"}) "<collection")))
(testing "falls back to pr-str for unknown types"
- (let [result (llm-rep/entity->xml {:type :unknown :data "test"})]
+ (let [result (llm-shape/entity->xml {:type :unknown :data "test"})]
(is (str/includes? result ":type")))))
diff --git a/test/metabase/metabot/tools/slackbot_query_test.clj b/test/metabase/metabot/tools/slackbot_query_test.clj
index 3fed1cc57f6..f095153c3f4 100644
--- a/test/metabase/metabot/tools/slackbot_query_test.clj
+++ b/test/metabase/metabot/tools/slackbot_query_test.clj
@@ -1,11 +1,28 @@
(ns metabase.metabot.tools.slackbot-query-test
- "Tests for slackbot query tool schema and prompt content."
+ "Tests for slackbot query tool schema, prompt content, and (post-step-14) its
+ representations-pipeline integration.
+
+ Three test layers:
+
+ * **Schema / prompt tests** (parallel-safe): assert properties of the tool's args schema and
+ of the slackbot system prompt.
+ * **Unit tests** (stubbed pipeline): stub `construct/execute-representations-query` and
+ exercise the slackbot wrapper logic - YAML pass-through, adhoc_viz data part
+ construction, error translation.
+ * **End-to-end test** (real sample DB): calls the tool with a realistic YAML against the
+ real application database to catch anything the stubbed tests miss (real YAML parse,
+ real repair passes, real resolver, real `query->question-url`)."
(:require
[clojure.java.io :as io]
[clojure.string :as str]
[clojure.test :refer :all]
[malli.json-schema :as mjs]
- [metabase.metabot.tools.slackbot-query :as slackbot-query]))
+ [metabase.metabot.agent.streaming :as streaming]
+ [metabase.metabot.tools.construct :as construct]
+ [metabase.metabot.tools.slackbot-query :as slackbot-query]
+ [metabase.test :as mt]
+ [metabase.test.data.users :as test.users]
+ [toucan2.core :as t2]))
;;; ---------------------------------------- prompt content tests ---------------------------------------------------
@@ -40,3 +57,204 @@
required (set (:required json-schema))]
(is (not (contains? required "display"))
"display should not be required"))))
+
+(deftest schema-shape-post-step-14-test
+ (testing (str "Per `repr-plan.md` steps 13 and 14, the slackbot tool schema must only accept\n"
+ "`{reasoning, query, title?, display?}`. No `source_entity`, no\n"
+ "`referenced_entities`, no `program` (the legacy sexp shape).")
+ (let [schema @#'slackbot-query/slackbot-query-schema
+ json-schema (mjs/transform schema)
+ props (set (keys (:properties json-schema)))]
+ (testing "expected keys present"
+ (is (contains? props :reasoning))
+ (is (contains? props :query))
+ (is (contains? props :title))
+ (is (contains? props :display)))
+ (testing "legacy keys absent"
+ (is (not (contains? props :source_entity)))
+ (is (not (contains? props :referenced_entities)))
+ (is (not (contains? props :program))))
+ (testing "`:query` is a JSON object (the portable representations external-query)"
+ (is (= "object" (get-in json-schema [:properties :query :type])))))))
+
+;;; ---------------------------------------- integration tests ------------------------------------------------------
+
+;; These tests stub `execute-representations-query` with a fake that returns a canned
+;; `:structured-output` so we can assert the slackbot-specific wrapping (link construction,
+;; adhoc_viz data part, instructions text, error passthrough).
+
+(defn- with-repr-stub! [stub-fn f]
+ (with-redefs [construct/execute-representations-query stub-fn
+ ;; `streaming/query->question-url` inspects the query; stub it too so the
+ ;; fake query doesn't have to satisfy the real function's expectations.
+ streaming/query->question-url
+ (fn [_q display]
+ (str "/question#fake" (when display (str "?d=" display))))]
+ (f)))
+
+(deftest slackbot-tool-happy-path-test
+ (testing (str "Slackbot tool takes an external-query map, hands it verbatim to\n"
+ "execute-representations-query, wraps the result in an adhoc_viz data part\n"
+ "with the provided title + display, and returns structured-output + instructions.")
+ (let [captured-query (atom nil)
+ fake-query {:lib/type :mbql/query :database 1 :stages [{:source-table 10}]}]
+ (with-repr-stub!
+ (fn [external-query]
+ (reset! captured-query external-query)
+ {:structured-output {:query-id "q-1"
+ :query fake-query
+ :result-columns []}
+ :instructions "Query created."})
+ (fn []
+ (let [query-input {:lib/type "mbql/query"
+ :stages [{:lib/type "mbql.stage/mbql"
+ :source-table ["Sample" "PUBLIC" "ORDERS"]
+ :aggregation [["count" {}]]}]}
+ result (slackbot-query/slackbot-construct-notebook-query-tool
+ {:reasoning "user asked for order count"
+ :query query-input
+ :title "Monthly order volume"
+ :display "bar"})]
+ (testing "external-query passed through verbatim"
+ (is (= query-input @captured-query)))
+ (testing "structured-output is returned upstream"
+ (is (= "q-1" (get-in result [:structured-output :query-id])))
+ (is (= fake-query (get-in result [:structured-output :query]))))
+ (testing "adhoc_viz data part carries title + display + link"
+ (let [parts (:data-parts result)
+ part (first parts)
+ data (:data part)]
+ (is (= 1 (count parts)))
+ (is (= "Monthly order volume" (:title data)))
+ (is (= "bar" (:display data)))
+ (is (str/starts-with? (:link data) "/question#"))
+ (is (= fake-query (:query data)))))
+ (testing "instructions text mentions follow-up visualization rendering"
+ (is (str/includes? (:instructions result) "follow-up message")))))))))
+
+(deftest slackbot-tool-no-optional-fields-test
+ (testing (str "When title/display are absent, the adhoc_viz data part omits them (doesn't\n"
+ "include them with nil values) but the link is still built and returned.")
+ (let [fake-query {:lib/type :mbql/query :database 1 :stages [{:source-table 10}]}]
+ (with-repr-stub!
+ (fn [_external-query]
+ {:structured-output {:query-id "q-x"
+ :query fake-query
+ :result-columns []}
+ :instructions "ok"})
+ (fn []
+ (let [result (slackbot-query/slackbot-construct-notebook-query-tool
+ {:reasoning "simple request"
+ :query {:lib/type "mbql/query"
+ :stages [{:lib/type "mbql.stage/mbql"
+ :source-table ["Sample" "PUBLIC" "ORDERS"]
+ :aggregation [["count" {}]]}]}})
+ data (get-in result [:data-parts 0 :data])]
+ (is (= "q-x" (get-in result [:structured-output :query-id])))
+ (is (not (contains? data :title)))
+ (is (not (contains? data :display)))
+ (is (string? (:link data)))
+ (is (= fake-query (:query data)))))))))
+
+(deftest slackbot-tool-agent-error-surfaces-as-output-test
+ (testing (str "When `execute-representations-query` throws an :agent-error? ex-info (as it\n"
+ "does for unknown database, malformed YAML, etc.), the slackbot wrapper\n"
+ "returns `{:output <message>}` so the message reaches the LLM verbatim -\n"
+ "no stack trace, no data-parts.")
+ (with-repr-stub!
+ (fn [_external-query]
+ (throw (ex-info "Unknown database: `Sample`. Use the exact database name as reported by entity_details."
+ {:agent-error? true
+ :status-code 400
+ :error :unknown-database
+ :database "Sample"})))
+ (fn []
+ (let [result (slackbot-query/slackbot-construct-notebook-query-tool
+ {:reasoning "test agent-error path"
+ :query {:lib/type "mbql/query" :stages []}})]
+ (testing "bare :output key with the agent message, no structured-output or data-parts"
+ (is (string? (:output result)))
+ (is (re-find #"Unknown database" (:output result)))
+ (is (re-find #"Sample" (:output result)))
+ (is (nil? (:structured-output result)))
+ (is (nil? (:data-parts result)))))))))
+
+(deftest slackbot-tool-unexpected-error-is-wrapped-test
+ (testing (str "A non-agent exception (e.g. a programming bug) gets wrapped with a generic\n"
+ "`Failed to construct notebook query: ...` prefix. Protects the LLM from\n"
+ "leaking internal stack-trace-style messages.")
+ (with-repr-stub!
+ (fn [_external-query]
+ (throw (RuntimeException. "something went sideways")))
+ (fn []
+ (let [result (slackbot-query/slackbot-construct-notebook-query-tool
+ {:reasoning "test non-agent error path"
+ :query {:lib/type "mbql/query" :stages []}})]
+ (is (string? (:output result)))
+ (is (str/starts-with? (:output result) "Failed to construct notebook query:"))
+ (is (re-find #"something went sideways" (:output result))))))))
+
+;;; ---------------------------------------- end-to-end test --------------------------------------------------------
+
+(deftest slackbot-tool-end-to-end-test
+ (testing (str "End-to-end: call the slackbot tool with a YAML query against the real\n"
+ "application sample DB. Exercises the full repr pipeline (parse-yaml \u2192\n"
+ "repair \u2192 validate \u2192 resolve) plus the slackbot-specific wrapping\n"
+ "(query->question-url, adhoc_viz data part). Serves as a safety net for\n"
+ "step 14 - any future regression in the slackbot contract should surface here\n"
+ "without needing a live LLM loop.")
+ (mt/with-current-user (test.users/user->id :crowberto)
+ (let [db-name (t2/select-one-fn :name :model/Database :id (mt/id))
+ ;; Canonical DB name (per `repr-plan.md` step 13); `Sample` alone would
+ ;; short-circuit with :unknown-database.
+ external-query {:lib/type "mbql/query"
+ :stages [{:lib/type "mbql.stage/mbql"
+ :source-table [db-name "PUBLIC" "ORDERS"]
+ :aggregation [["count" {}]]}]}
+ result (slackbot-query/slackbot-construct-notebook-query-tool
+ {:reasoning "count the orders"
+ :query external-query
+ :title "Total orders"
+ :display "bar"})]
+ (testing "structured-output carries a resolved MBQL 5 query with numeric ids"
+ (let [q (get-in result [:structured-output :query])]
+ (is (= :mbql/query (:lib/type q)))
+ (is (= (mt/id) (:database q)))
+ (is (= (mt/id :orders) (get-in q [:stages 0 :source-table])))
+ (is (= :count (first (get-in q [:stages 0 :aggregation 0]))))))
+ (testing "adhoc_viz data part carries title, display, a real question link, and the query"
+ (let [part (first (:data-parts result))
+ data (:data part)]
+ (is (some? part))
+ (is (= "Total orders" (:title data)))
+ (is (= "bar" (:display data)))
+ (is (str/starts-with? (:link data) "/question#"))
+ (is (map? (:query data)))))
+ (testing "canonical-DB-name happy path returns a structured-output, not an error :output"
+ ;; A non-agent failure (or agent-error) would clear :structured-output and put the
+ ;; message under :output. Sanity-check the happy-path shape.
+ (is (some? (:structured-output result)) (pr-str result))
+ (is (nil? (:output result))))))))
+
+(deftest slackbot-tool-end-to-end-unknown-database-test
+ (testing (str "End-to-end error path: if the LLM writes a DB name that doesn't match any\n"
+ "application database, the slackbot tool returns `{:output <message>}` with\n"
+ "a clear `Unknown database` message (no stack trace, no data-parts). This is\n"
+ "the post-step-13 loud-failure behaviour - the previous silent-rewrite pass\n"
+ "is gone.")
+ (mt/with-current-user (test.users/user->id :crowberto)
+ (let [;; Intentionally use an impossible name so we hit :unknown-database at lookup.
+ external-query {:lib/type "mbql/query"
+ :stages [{:lib/type "mbql.stage/mbql"
+ :source-table ["DefinitelyNotARealDatabaseName" "PUBLIC" "ORDERS"]
+ :aggregation [["count" {}]]}]}
+ result (slackbot-query/slackbot-construct-notebook-query-tool
+ {:reasoning "wrong db name"
+ :query external-query
+ :display "table"})]
+ (testing "no structured-output, no data-parts, clear message"
+ (is (nil? (:structured-output result)))
+ (is (nil? (:data-parts result)))
+ (is (string? (:output result)))
+ (is (re-find #"Unknown database" (:output result)))
+ (is (re-find #"DefinitelyNotARealDatabaseName" (:output result))))))))
diff --git a/test/metabase/metabot/tools_test.clj b/test/metabase/metabot/tools_test.clj
index 05b97dc1bef..aa5dffe52c3 100644
--- a/test/metabase/metabot/tools_test.clj
+++ b/test/metabase/metabot/tools_test.clj
@@ -115,15 +115,16 @@
(is (some? (:schema m))))))
(deftest construct-notebook-query-tool-test
- (testing "construct_notebook_query evaluates a program and creates a chart"
- (let [program-captured (atom nil)
- chart-called (atom nil)]
- (mt/with-dynamic-fn-redefs [construct/execute-program (fn [_source-entity _referenced-entities program]
- (reset! program-captured program)
- {:structured-output {:query-id "q-1"
- :query {:database 1}
- :result-columns []}
- :instructions "Query created."})
+ (testing "construct_notebook_query evaluates a representations query and creates a chart"
+ (let [query-captured (atom nil)
+ chart-called (atom nil)]
+ (mt/with-dynamic-fn-redefs [construct/execute-representations-query
+ (fn [external-query]
+ (reset! query-captured external-query)
+ {:structured-output {:query-id "q-1"
+ :query {:database 1}
+ :result-columns []}
+ :instructions "Query created."})
create-chart-tools/create-chart (fn [args]
(reset! chart-called args)
{:chart-id "c-1"
@@ -133,17 +134,15 @@
:query-id (:query-id args)
:reactions [{:type :metabot.reaction/redirect
:url "/question#hash"}]})]
- (let [result (agent-tools/construct-notebook-query-tool
- {:reasoning "check seats"
- :source_entity {:type "table" :id 6}
- :program {:source {:type "context" :ref "source"}
- :operations [["filter" ["=" ["field" 301] "a"]]
- ["with-fields" [["field" 301]]]
- ["order-by" ["field" 301] "desc"]
- ["limit" 10]]}
+ (let [query-input {:lib/type "mbql/query"
+ :stages [{:lib/type "mbql.stage/mbql"
+ :source-table ["Sample" "PUBLIC" "ORDERS"]
+ :aggregation [["count" {}]]}]}
+ result (agent-tools/construct-notebook-query-tool
+ {:reasoning "check seats"
+ :query query-input
:visualization {:chart_type "table"}})]
- (is (= "context" (get-in @program-captured [:source :type])))
- (is (= 4 (count (:operations @program-captured))))
+ (is (= query-input @query-captured))
(is (= "c-1" (get-in result [:structured-output :chart-id])))
(is (= "q-1" (get-in result [:structured-output :query-id])))
(is (= :table (get @chart-called :chart-type)))
diff --git a/test/metabase/models/serialization/resolve/mp_test.clj b/test/metabase/models/serialization/resolve/mp_test.clj
new file mode 100644
index 00000000000..4390c4d7876
--- /dev/null
+++ b/test/metabase/models/serialization/resolve/mp_test.clj
@@ -0,0 +1,625 @@
+(ns metabase.models.serialization.resolve.mp-test
+ "Tests for the metadata-provider-backed serdes resolver.
+
+ Covers the Phase-1 scope: `import-table-fk`, `import-field-fk`, `export-table-fk`,
+ `export-field-fk`, and the error paths for unknown / ambiguous / missing targets.
+
+ Phase-2 additions (step 11): `import-fk` for `Card` by entity_id."
+ (:require
+ [clojure.test :refer [deftest is testing use-fixtures]]
+ [metabase.lib-be.core :as lib-be]
+ [metabase.lib.metadata.protocols :as lib.metadata.protocols]
+ [metabase.lib.test-util :as lib.tu]
+ [metabase.models.serialization.resolve :as resolve]
+ [metabase.models.serialization.resolve.mp :as resolve.mp]
+ [metabase.test :as mt]
+ [metabase.test.fixtures :as fixtures]))
+
+(set! *warn-on-reflection* true)
+
+;; Needed for the measure/segment happy-path tests below — `(mt/id :orders :total)` requires
+;; the test-data dataset to be fully synced (table + fields).
+(use-fixtures :once (fixtures/initialize :db :test-users))
+
+;;; ============================================================
+;;; Mock fixtures
+;;; ============================================================
+
+(def ^:private mp-simple
+ "Single database 'Sample', one table PUBLIC.ORDERS with a couple of columns."
+ (lib.tu/mock-metadata-provider
+ {:database {:id 1 :name "Sample"}
+ :tables [{:id 10 :name "ORDERS" :schema "PUBLIC" :db-id 1}
+ {:id 11 :name "PRODUCTS" :schema "PUBLIC" :db-id 1}]
+ :fields [{:id 100 :name "ID" :table-id 10 :base-type :type/Integer}
+ {:id 101 :name "TOTAL" :table-id 10 :base-type :type/Float}
+ {:id 102 :name "PRODUCT_ID" :table-id 10 :base-type :type/Integer}
+ {:id 110 :name "ID" :table-id 11 :base-type :type/Integer}
+ {:id 111 :name "CATEGORY" :table-id 11 :base-type :type/Text}]}))
+
+(def ^:private mp-with-fk
+ "Same shape as `mp-simple`, but `ORDERS.PRODUCT_ID` carries an FK target pointing
+ at `PRODUCTS.ID`. Used to exercise the FK-candidate hint surfaced by `find-field`
+ when the LLM asks for a column that lives on an FK-reachable table."
+ (lib.tu/mock-metadata-provider
+ {:database {:id 6 :name "Sample"}
+ :tables [{:id 60 :name "ORDERS" :schema "PUBLIC" :db-id 6}
+ {:id 61 :name "PRODUCTS" :schema "PUBLIC" :db-id 6}]
+ :fields [{:id 600 :name "ID" :table-id 60 :base-type :type/Integer}
+ {:id 602 :name "PRODUCT_ID" :table-id 60 :base-type :type/Integer
+ :fk-target-field-id 610}
+ {:id 610 :name "ID" :table-id 61 :base-type :type/Integer}
+ {:id 611 :name "CATEGORY" :table-id 61 :base-type :type/Text}]}))
+
+(def ^:private mp-schemaless
+ "Schemaless database (e.g. Mongo) - :schema is nil."
+ (lib.tu/mock-metadata-provider
+ {:database {:id 2 :name "Mongo"}
+ :tables [{:id 20 :name "orders" :schema nil :db-id 2}]
+ :fields [{:id 200 :name "total" :table-id 20 :base-type :type/Float}]}))
+
+(def ^:private mp-ambiguous-by-schema
+ "Two tables with the same name, different schemas - disambiguated by schema."
+ (lib.tu/mock-metadata-provider
+ {:database {:id 3 :name "DW"}
+ :tables [{:id 30 :name "ORDERS" :schema "RAW" :db-id 3}
+ {:id 31 :name "ORDERS" :schema "CLEAN" :db-id 3}]
+ :fields [{:id 300 :name "ID" :table-id 30 :base-type :type/Integer}
+ {:id 310 :name "ID" :table-id 31 :base-type :type/Integer}]}))
+
+;; JSON-unfolded field: a column with a parent-id.
+(def ^:private mp-nested
+ "Database with a JSON-unfolded nested field: ORDERS.META -> ORDERS.META.vendor."
+ (lib.tu/mock-metadata-provider
+ {:database {:id 4 :name "Nested"}
+ :tables [{:id 40 :name "ORDERS" :schema "PUBLIC" :db-id 4}]
+ :fields [{:id 400 :name "META" :table-id 40 :base-type :type/JSON}
+ {:id 401 :name "vendor" :table-id 40 :parent-id 400 :base-type :type/Text}]}))
+
+(def ^:private card-entity-id "cardEntityId123456789")
+(def ^:private metric-entity-id "metricEntityId1234567")
+
+(def ^:private mp-with-cards
+ "Database with regular Card and metric Card metadata for source-card / metric export."
+ (lib.tu/mock-metadata-provider
+ {:database {:id 1 :name "Sample"}
+ :tables [{:id 10 :name "ORDERS" :schema "PUBLIC" :db-id 1}]
+ :fields [{:id 101 :name "TOTAL" :table-id 10 :base-type :type/Float}]
+ :cards [{:id 500
+ :name "Saved Orders"
+ :database-id 1
+ :type :question
+ :entity-id card-entity-id}
+ {:id 501
+ :name "Revenue Metric"
+ :database-id 1
+ :type :metric
+ :entity-id metric-entity-id}]}))
+
+;;; ============================================================
+;;; import-table-fk
+;;; ============================================================
+
+(deftest import-table-fk-test
+ (testing "happy path"
+ (let [r (resolve.mp/import-resolver mp-simple)]
+ (is (= 10 (resolve/import-table-fk r ["Sample" "PUBLIC" "ORDERS"])))
+ (is (= 11 (resolve/import-table-fk r ["Sample" "PUBLIC" "PRODUCTS"])))))
+ (testing "nil input returns nil"
+ (let [r (resolve.mp/import-resolver mp-simple)]
+ (is (nil? (resolve/import-table-fk r nil)))))
+ (testing "schemaless: nil schema slot matches real null schema"
+ (let [r (resolve.mp/import-resolver mp-schemaless)]
+ (is (= 20 (resolve/import-table-fk r ["Mongo" nil "orders"])))))
+ (testing "schema disambiguation: same name in two schemas"
+ (let [r (resolve.mp/import-resolver mp-ambiguous-by-schema)]
+ (is (= 30 (resolve/import-table-fk r ["DW" "RAW" "ORDERS"])))
+ (is (= 31 (resolve/import-table-fk r ["DW" "CLEAN" "ORDERS"]))))))
+
+(deftest import-table-fk-error-test
+ (testing "unknown table name → :unknown-table, agent-error?, 400, no info leak"
+ (let [r (resolve.mp/import-resolver mp-simple)]
+ (try
+ (resolve/import-table-fk r ["Sample" "PUBLIC" "NOPE"])
+ (is false "expected throw")
+ (catch clojure.lang.ExceptionInfo e
+ (let [d (ex-data e)
+ msg (.getMessage e)]
+ (is (= :unknown-table (:error d)))
+ (is (= 400 (:status-code d)))
+ (is (true? (:agent-error? d)))
+ (is (= ["Sample" "PUBLIC" "NOPE"] (:path d)))
+ (testing "ex-data carries only the rejected path — no candidates / schemas"
+ (is (nil? (:candidates d)))
+ (is (nil? (:available-schemas d))))
+ (testing "message points the LLM at entity_details for self-correction"
+ (is (re-find #"entity_details" msg))))))))
+ (testing "schema does not exist in DB → still :unknown-table, no schema enumeration"
+ ;; Pre-S1 this returned :unknown-schema + the full schema list. Post-S1 we collapse to
+ ;; :unknown-table with no schema enumeration so a sandboxed user can't enumerate
+ ;; schemas they lack perms on.
+ (let [r (resolve.mp/import-resolver mp-simple)]
+ (try
+ (resolve/import-table-fk r ["Sample" "OTHER" "ORDERS"])
+ (is false "expected throw")
+ (catch clojure.lang.ExceptionInfo e
+ (let [d (ex-data e)
+ msg (.getMessage e)]
+ (is (= :unknown-table (:error d)))
+ (is (true? (:agent-error? d)))
+ (is (nil? (:available-schemas d)))
+ (testing "message must not enumerate schemas"
+ (is (not (re-find #"PUBLIC" msg)))
+ (is (not (re-find #"Available schemas" msg)))))))))
+ (testing "table exists in other schemas → :unknown-table, no cross-schema leak"
+ ;; A sandboxed user with no perms on schema RAW must not learn that RAW.ORDERS exists
+ ;; just by hallucinating CLEAN.ORDERS at the agent.
+ (let [mp (lib.tu/mock-metadata-provider
+ {:database {:id 5 :name "DW2"}
+ :tables [{:id 50 :name "ORDERS" :schema "RAW" :db-id 5}
+ {:id 51 :name "PRODUCTS" :schema "CLEAN" :db-id 5}]})
+ r (resolve.mp/import-resolver mp)]
+ (try
+ (resolve/import-table-fk r ["DW2" "CLEAN" "ORDERS"])
+ (is false "expected throw")
+ (catch clojure.lang.ExceptionInfo e
+ (let [d (ex-data e)
+ msg (.getMessage e)]
+ (is (= :unknown-table (:error d)))
+ (is (nil? (:candidates d)))
+ (testing "message must not name RAW.ORDERS as a candidate"
+ (is (not (re-find #"RAW" msg)))))))))
+ (testing "database name mismatch"
+ (let [r (resolve.mp/import-resolver mp-simple)]
+ (try
+ (resolve/import-table-fk r ["Different" "PUBLIC" "ORDERS"])
+ (is false "expected throw")
+ (catch clojure.lang.ExceptionInfo e
+ (let [d (ex-data e)]
+ (is (= :unknown-table (:error d)))
+ (is (= "Sample" (:expected-db d)))
+ (is (true? (:agent-error? d))))))))
+ (testing "fuzzy substring suggestions are NOT surfaced (info-leak guard)"
+ ;; Pre-S1 the resolver would surface `PUBLIC.ORDERS` as a "closest tables" candidate
+ ;; for an `ORDER` hallucination. Post-S1 nothing is suggested.
+ (let [r (resolve.mp/import-resolver mp-simple)]
+ (try
+ (resolve/import-table-fk r ["Sample" "PUBLIC" "ORDER"])
+ (is false "expected throw")
+ (catch clojure.lang.ExceptionInfo e
+ (let [d (ex-data e)
+ msg (.getMessage e)]
+ (is (= :unknown-table (:error d)))
+ (is (nil? (:candidates d)))
+ (testing "message must not name any other table in the database"
+ (is (not (re-find #"PUBLIC\.ORDERS" msg)))
+ (is (not (re-find #"Closest tables" msg))))))))))
+
+;;; ============================================================
+;;; import-field-fk
+;;; ============================================================
+
+(deftest import-field-fk-test
+ (testing "happy path"
+ (let [r (resolve.mp/import-resolver mp-simple)]
+ (is (= 100 (resolve/import-field-fk r ["Sample" "PUBLIC" "ORDERS" "ID"])))
+ (is (= 101 (resolve/import-field-fk r ["Sample" "PUBLIC" "ORDERS" "TOTAL"])))
+ (is (= 111 (resolve/import-field-fk r ["Sample" "PUBLIC" "PRODUCTS" "CATEGORY"])))))
+ (testing "schemaless"
+ (let [r (resolve.mp/import-resolver mp-schemaless)]
+ (is (= 200 (resolve/import-field-fk r ["Mongo" nil "orders" "total"])))))
+ (testing "nil input returns nil"
+ (let [r (resolve.mp/import-resolver mp-simple)]
+ (is (nil? (resolve/import-field-fk r nil)))))
+ (testing "JSON-unfolded nested field walks parent-id chain"
+ (let [r (resolve.mp/import-resolver mp-nested)]
+ (is (= 401 (resolve/import-field-fk r ["Nested" "PUBLIC" "ORDERS" "META" "vendor"]))))))
+
+(deftest import-field-fk-error-test
+ (testing "unknown field"
+ (let [r (resolve.mp/import-resolver mp-simple)]
+ (try
+ (resolve/import-field-fk r ["Sample" "PUBLIC" "ORDERS" "NOPE"])
+ (is false "expected throw")
+ (catch clojure.lang.ExceptionInfo e
+ (is (= :unknown-field (:error (ex-data e))))))))
+ (testing "unknown table (bubbles up through find-table)"
+ (let [r (resolve.mp/import-resolver mp-simple)]
+ (try
+ (resolve/import-field-fk r ["Sample" "PUBLIC" "GHOST" "ID"])
+ (is false "expected throw")
+ (catch clojure.lang.ExceptionInfo e
+ (is (= :unknown-table (:error (ex-data e))))))))
+ (testing "short field FK (missing field segment)"
+ (let [r (resolve.mp/import-resolver mp-simple)]
+ (try
+ (resolve/import-field-fk r ["Sample" "PUBLIC" "ORDERS"])
+ (is false "expected throw")
+ (catch clojure.lang.ExceptionInfo e
+ (is (= :invalid-field-fk (:error (ex-data e)))))))))
+
+(deftest import-field-fk-no-fk-candidate-leak-test
+ (testing "an unknown field that lives on an FK-reachable table MUST NOT surface that table"
+ ;; Pre-S1 the resolver helpfully suggested `[Sample PUBLIC PRODUCTS CATEGORY]` as a
+ ;; candidate when the LLM asked for `[Sample PUBLIC ORDERS CATEGORY]`. That leaks the
+ ;; existence of PRODUCTS to anyone whose data perms exclude that table.
+ (let [r (resolve.mp/import-resolver mp-with-fk)]
+ (try
+ (resolve/import-field-fk r ["Sample" "PUBLIC" "ORDERS" "CATEGORY"])
+ (is false "expected throw")
+ (catch clojure.lang.ExceptionInfo e
+ (let [d (ex-data e)
+ msg (.getMessage e)]
+ (is (= :unknown-field (:error d)))
+ (is (true? (:agent-error? d)))
+ (is (nil? (:fk-candidates d)) "ex-data must not carry FK candidates")
+ (testing "message must not name PRODUCTS or FK-linked tables"
+ (is (not (re-find #"PRODUCTS" msg)))
+ (is (not (re-find #"FK-linked" msg)))))))))
+
+ (testing "unknown field also doesn't leak when no FK-reachable table has the column"
+ (let [r (resolve.mp/import-resolver mp-with-fk)]
+ (try
+ (resolve/import-field-fk r ["Sample" "PUBLIC" "ORDERS" "NOT_ANYWHERE"])
+ (is false "expected throw")
+ (catch clojure.lang.ExceptionInfo e
+ (let [d (ex-data e)]
+ (is (= :unknown-field (:error d)))
+ (is (nil? (:fk-candidates d)))
+ (is (not (re-find #"FK-linked tables" (.getMessage e))))))))))
+
+;;; ============================================================
+;;; export-table-fk / export-field-fk
+;;; ============================================================
+
+(deftest export-table-fk-test
+ (testing "happy path"
+ (let [r (resolve.mp/export-resolver mp-simple)]
+ (is (= ["Sample" "PUBLIC" "ORDERS"] (resolve/export-table-fk r 10)))
+ (is (= ["Sample" "PUBLIC" "PRODUCTS"] (resolve/export-table-fk r 11)))))
+ (testing "nil returns nil"
+ (let [r (resolve.mp/export-resolver mp-simple)]
+ (is (nil? (resolve/export-table-fk r nil)))))
+ (testing "unknown id throws"
+ (let [r (resolve.mp/export-resolver mp-simple)]
+ (try
+ (resolve/export-table-fk r 9999)
+ (is false "expected throw")
+ (catch clojure.lang.ExceptionInfo e
+ (is (= :unknown-table-id (:error (ex-data e)))))))))
+
+(deftest export-field-fk-test
+ (testing "happy path"
+ (let [r (resolve.mp/export-resolver mp-simple)]
+ (is (= ["Sample" "PUBLIC" "ORDERS" "TOTAL"] (resolve/export-field-fk r 101)))))
+ (testing "schemaless"
+ (let [r (resolve.mp/export-resolver mp-schemaless)]
+ (is (= ["Mongo" nil "orders" "total"] (resolve/export-field-fk r 200)))))
+ (testing "JSON-unfolded field"
+ (let [r (resolve.mp/export-resolver mp-nested)]
+ (is (= ["Nested" "PUBLIC" "ORDERS" "META" "vendor"]
+ (resolve/export-field-fk r 401)))))
+ (testing "round-trip: import then export"
+ (let [ir (resolve.mp/import-resolver mp-simple)
+ er (resolve.mp/export-resolver mp-simple)
+ path ["Sample" "PUBLIC" "ORDERS" "PRODUCT_ID"]]
+ (is (= path (resolve/export-field-fk er (resolve/import-field-fk ir path)))))))
+
+(deftest export-database-and-card-fks-test
+ (let [r (resolve.mp/export-resolver mp-with-cards)]
+ (testing "database id exports to the provider's database name"
+ (is (= "Sample" (resolve/export-fk-keyed r 1 :model/Database :name)))
+ (is (= "Sample" (resolve/export-fk-keyed r 1 'Database :name))))
+ (testing "Card ids export to entity_ids for both source-card and metric refs"
+ (is (= card-entity-id (resolve/export-fk r 500 :model/Card)))
+ (is (= card-entity-id (resolve/export-fk r 500 'Card)))
+ (is (= metric-entity-id (resolve/export-fk r 501 'Card))))
+ (testing "nil inputs return nil"
+ (is (nil? (resolve/export-fk r nil 'Card)))
+ (is (nil? (resolve/export-fk-keyed r nil :model/Database :name))))))
+
+(deftest export-mbql-with-mp-resolver-round-trip-shape-test
+ (testing "final numeric pMBQL exports back to portable DB/table/field/card references"
+ (let [r (resolve.mp/export-resolver mp-with-cards)
+ exported (resolve/export-mbql
+ r
+ {:lib/type :mbql/query
+ :database 1
+ :stages [{:lib/type :mbql.stage/mbql
+ :source-table 10
+ :fields [[:field {} 101]]
+ :aggregation [[:metric {} 501]]}]})]
+ (is (= "Sample" (:database exported)))
+ (is (= ["Sample" "PUBLIC" "ORDERS"]
+ (get-in exported [:stages 0 :source-table])))
+ (is (= ["Sample" "PUBLIC" "ORDERS" "TOTAL"]
+ (get-in exported [:stages 0 :fields 0 2])))
+ (is (= metric-entity-id
+ (get-in exported [:stages 0 :aggregation 0 2])))
+ (is (string? (get-in exported [:stages 0 :fields 0 1 :lib/uuid])))
+ (is (string? (get-in exported [:stages 0 :aggregation 0 1 :lib/uuid])))))
+ (testing "source-card map keys export through the Card entity_id path"
+ (let [r (resolve.mp/export-resolver mp-with-cards)]
+ (is (= {:source-card card-entity-id}
+ (resolve/export-mbql r {:source-card 500}))))))
+
+;;; ============================================================
+;;; Not-yet-implemented methods
+;;; ============================================================
+
+(deftest not-implemented-phase1-test
+ (let [er (resolve.mp/export-resolver mp-simple)]
+ (testing "export-fk for non-(Card/Measure/Segment) models still throws :not-implemented-yet"
+ (try
+ (resolve/export-fk er 1 'NativeQuerySnippet)
+ (is false "expected throw")
+ (catch clojure.lang.ExceptionInfo e
+ (is (= :not-implemented-yet (:error (ex-data e)))))))
+ (testing "export-fk-keyed for non-database keys still throws :not-implemented-yet"
+ (try
+ (resolve/export-fk-keyed er 1 :model/Card :name)
+ (is false "expected throw")
+ (catch clojure.lang.ExceptionInfo e
+ (is (= :not-implemented-yet (:error (ex-data e)))))))))
+
+;;; ============================================================
+;;; import-fk - Card by entity_id (step 11)
+;;; ============================================================
+
+(deftest import-fk-card-happy-path-test
+ (testing "resolves a saved card's entity_id to its numeric id when the card lives in the same database"
+ (mt/with-temp [:model/Card {card-id :id card-eid :entity_id}
+ {:database_id (mt/id)
+ :dataset_query {:database (mt/id)
+ :type :query
+ :query {:source-table (mt/id :orders)}}}]
+ (let [mp (lib-be/application-database-metadata-provider (mt/id))
+ ir (resolve.mp/import-resolver mp)]
+ (is (= card-id (resolve/import-fk ir card-eid 'Card)))
+ (testing "also accepts keyword-qualified model name :model/Card"
+ (is (= card-id (resolve/import-fk ir card-eid :model/Card))))))))
+
+(deftest import-fk-card-nil-input-returns-nil-test
+ (testing "nil entity_id returns nil (matches table/field FK contract)"
+ (let [ir (resolve.mp/import-resolver mp-simple)]
+ (is (nil? (resolve/import-fk ir nil 'Card))))))
+
+(deftest import-fk-card-unknown-test
+ (testing "unknown entity_id throws :agent-error? with :unknown-card code"
+ (mt/with-empty-h2-app-db!
+ (let [mp (lib-be/application-database-metadata-provider (mt/id))
+ ir (resolve.mp/import-resolver mp)]
+ (try
+ (resolve/import-fk ir "nonexistent_entity_id1" 'Card)
+ (is false "expected throw")
+ (catch clojure.lang.ExceptionInfo e
+ (let [d (ex-data e)]
+ (is (true? (:agent-error? d)))
+ (is (= :unknown-card (:error d)))
+ (is (= "nonexistent_entity_id1" (:entity-id d))))))))))
+
+(deftest import-fk-card-cross-database-test
+ (testing "a card that belongs to a different database surfaces a clear :cross-database-card error"
+ (mt/with-temp [:model/Database {other-db-id :id} {:name "Other DB" :engine :h2}
+ :model/Card {_card-id :id card-eid :entity_id}
+ {:database_id other-db-id
+ :dataset_query {:database other-db-id
+ :type :native
+ :native {:query "SELECT 1"}}}]
+ (let [mp (lib-be/application-database-metadata-provider (mt/id))
+ ir (resolve.mp/import-resolver mp)]
+ (try
+ (resolve/import-fk ir card-eid 'Card)
+ (is false "expected throw")
+ (catch clojure.lang.ExceptionInfo e
+ (let [d (ex-data e)]
+ (is (true? (:agent-error? d)))
+ (is (= :cross-database-card (:error d)))
+ (is (= other-db-id (:card-database-id d))))))))))
+
+;;; ============================================================
+;;; import-fk / export-fk - Measure & Segment by entity_id
+;;; ============================================================
+
+(deftest import-fk-measure-happy-path-test
+ (testing "resolves a measure's entity_id to its numeric id when the measure's table is in the same database"
+ (mt/with-temp [:model/Measure {measure-id :id measure-eid :entity_id}
+ {:name "Test Measure"
+ :table_id (mt/id :orders)
+ :definition {:lib/type :mbql/query
+ :database (mt/id)
+ :stages [{:lib/type :mbql.stage/mbql
+ :source-table (mt/id :orders)
+ :aggregation [[:count {:lib/uuid (str (random-uuid))}]]}]}}]
+ (let [mp (lib-be/application-database-metadata-provider (mt/id))
+ ir (resolve.mp/import-resolver mp)]
+ (is (= measure-id (resolve/import-fk ir measure-eid 'Measure)))
+ (is (= measure-id (resolve/import-fk ir measure-eid :model/Measure)))))))
+
+(deftest import-fk-segment-happy-path-test
+ (testing "resolves a segment's entity_id to its numeric id when the segment's table is in the same database"
+ (let [mp (lib-be/application-database-metadata-provider (mt/id))
+ ;; Look up the field id via lib metadata rather than `(mt/id :orders :total)` —
+ ;; mp_test's fixture set syncs tables but not fields eagerly.
+ orders-id (mt/id :orders)
+ total-id (-> (filter #(= "TOTAL" (:name %))
+ (lib.metadata.protocols/fields mp orders-id))
+ first :id)]
+ (mt/with-temp [:model/Segment {segment-id :id segment-eid :entity_id}
+ {:name "Test Segment"
+ :table_id orders-id
+ :definition {:lib/type :mbql/query
+ :database (mt/id)
+ :stages [{:lib/type :mbql.stage/mbql
+ :source-table orders-id
+ :filters [[:> {:lib/uuid (str (random-uuid))}
+ [:field {:lib/uuid (str (random-uuid))} total-id]
+ 100]]}]}}]
+ (let [ir (resolve.mp/import-resolver mp)]
+ (is (= segment-id (resolve/import-fk ir segment-eid 'Segment)))
+ (is (= segment-id (resolve/import-fk ir segment-eid :model/Segment))))))))
+
+(deftest import-fk-measure-unknown-test
+ (testing "unknown measure entity_id throws :unknown-measure with :agent-error?"
+ (mt/with-empty-h2-app-db!
+ (let [mp (lib-be/application-database-metadata-provider (mt/id))
+ ir (resolve.mp/import-resolver mp)]
+ (try
+ (resolve/import-fk ir "nonexistent_measure_id_x" 'Measure)
+ (is false "expected throw")
+ (catch clojure.lang.ExceptionInfo e
+ (let [d (ex-data e)]
+ (is (true? (:agent-error? d)))
+ (is (= :unknown-measure (:error d)))
+ (is (= "nonexistent_measure_id_x" (:entity-id d))))))))))
+
+(deftest import-fk-segment-unknown-test
+ (testing "unknown segment entity_id throws :unknown-segment with :agent-error?"
+ (mt/with-empty-h2-app-db!
+ (let [mp (lib-be/application-database-metadata-provider (mt/id))
+ ir (resolve.mp/import-resolver mp)]
+ (try
+ (resolve/import-fk ir "nonexistent_segment_id_x" 'Segment)
+ (is false "expected throw")
+ (catch clojure.lang.ExceptionInfo e
+ (let [d (ex-data e)]
+ (is (true? (:agent-error? d)))
+ (is (= :unknown-segment (:error d))))))))))
+
+(deftest export-fk-measure-happy-path-test
+ (testing "exports a measure's numeric id back to its portable entity_id"
+ (mt/with-temp [:model/Measure {measure-id :id measure-eid :entity_id}
+ {:name "Round-trip Measure"
+ :table_id (mt/id :orders)
+ :definition {:lib/type :mbql/query
+ :database (mt/id)
+ :stages [{:lib/type :mbql.stage/mbql
+ :source-table (mt/id :orders)
+ :aggregation [[:count {:lib/uuid (str (random-uuid))}]]}]}}]
+ (let [mp (lib-be/application-database-metadata-provider (mt/id))
+ er (resolve.mp/export-resolver mp)]
+ (is (= measure-eid (resolve/export-fk er measure-id 'Measure)))
+ (is (= measure-eid (resolve/export-fk er measure-id :model/Measure)))))))
+
+(deftest export-fk-segment-happy-path-test
+ (testing "exports a segment's numeric id back to its portable entity_id"
+ (let [mp (lib-be/application-database-metadata-provider (mt/id))
+ orders-id (mt/id :orders)
+ total-id (-> (filter #(= "TOTAL" (:name %))
+ (lib.metadata.protocols/fields mp orders-id))
+ first :id)]
+ (mt/with-temp [:model/Segment {segment-id :id segment-eid :entity_id}
+ {:name "Round-trip Segment"
+ :table_id orders-id
+ :definition {:lib/type :mbql/query
+ :database (mt/id)
+ :stages [{:lib/type :mbql.stage/mbql
+ :source-table orders-id
+ :filters [[:> {:lib/uuid (str (random-uuid))}
+ [:field {:lib/uuid (str (random-uuid))} total-id]
+ 0]]}]}}]
+ (let [er (resolve.mp/export-resolver mp)]
+ (is (= segment-eid (resolve/export-fk er segment-id 'Segment)))
+ (is (= segment-eid (resolve/export-fk er segment-id :model/Segment))))))))
+
+(deftest import-fk-non-supported-models-still-not-implemented-test
+ (testing "models we haven't wired up still throw :not-implemented-yet"
+ (let [ir (resolve.mp/import-resolver mp-simple)]
+ ;; Card, Measure, Segment are wired up — see their happy-path tests below.
+ ;; NativeQuerySnippet and Metric (the older standalone-metric concept, distinct from
+ ;; metric-cards) remain unimplemented.
+ (doseq [model ['NativeQuerySnippet 'Metric]]
+ (testing (str "model " model)
+ (try
+ (resolve/import-fk ir "someentityid_some_xyz" model)
+ (is false "expected throw")
+ (catch clojure.lang.ExceptionInfo e
+ (is (= :not-implemented-yet (:error (ex-data e)))))))))))
+
+;;; ============================================================
+;;; outbound-fks-from-table
+;;; ============================================================
+
+(def ^:private mp-fks-3
+ "3-table MP: ORDERS \u2192 PRODUCTS and ORDERS \u2192 USERS."
+ (lib.tu/mock-metadata-provider
+ {:database {:id 1 :name "Sample"}
+ :tables [{:id 10 :name "ORDERS" :schema "PUBLIC" :db-id 1}
+ {:id 20 :name "PRODUCTS" :schema "PUBLIC" :db-id 1}
+ {:id 30 :name "USERS" :schema "PUBLIC" :db-id 1}]
+ :fields [{:id 100 :name "ID" :table-id 10 :base-type :type/Integer}
+ {:id 101 :name "PRODUCT_ID" :table-id 10 :base-type :type/Integer :fk-target-field-id 200}
+ {:id 102 :name "USER_ID" :table-id 10 :base-type :type/Integer :fk-target-field-id 300}
+ {:id 200 :name "ID" :table-id 20 :base-type :type/Integer}
+ {:id 201 :name "CATEGORY" :table-id 20 :base-type :type/Text}
+ {:id 300 :name "ID" :table-id 30 :base-type :type/Integer}
+ {:id 301 :name "NAME" :table-id 30 :base-type :type/Text}]}))
+
+(deftest outbound-fks-from-table-happy-path-test
+ (testing "returns one entry per outbound FK, with target-table-id resolved"
+ (let [edges (resolve.mp/outbound-fks-from-table mp-fks-3 10)]
+ (is (= 2 (count edges)))
+ (is (= #{[101 20] [102 30]}
+ (set (map (juxt :source-field-id :target-table-id) edges))))
+ (is (every? :target-field-id edges))
+ (is (every? :source-field edges)))))
+
+(deftest outbound-fks-from-table-no-fks-test
+ (testing "table with no outbound FKs returns empty seq"
+ (is (= [] (resolve.mp/outbound-fks-from-table mp-fks-3 20)))
+ (is (= [] (resolve.mp/outbound-fks-from-table mp-fks-3 30)))))
+
+(deftest outbound-fks-from-table-simple-mp-test
+ (testing "works on the existing simple MP too (no FKs configured)"
+ (is (= [] (resolve.mp/outbound-fks-from-table mp-simple 10)))))
+
+;;; ============================================================
+;;; ContentStore - custom (no-app-db) lookups
+;;; ============================================================
+
+(defn- map-content-store
+ "Build an in-memory [[ContentStore]] from `entity-id->card` (a map). Cards must include
+ `:id` and `:database_id` so the resolver can do the cross-DB check. Measure / segment
+ lookups always return nil — extend the reify or use a richer fixture when those paths
+ need to be exercised."
+ [entity-id->card]
+ (reify resolve.mp/ContentStore
+ (card-by-entity-id [_ entity-id]
+ (get entity-id->card entity-id))
+ (measure-by-entity-id [_ _entity-id] nil)
+ (segment-by-entity-id [_ _entity-id] nil)
+ (measure-by-id [_ _measure-id] nil)
+ (segment-by-id [_ _segment-id] nil)))
+
+(deftest import-fk-card-via-custom-content-store-happy-path-test
+ (testing "a custom ContentStore lets the resolver work without an app DB"
+ (let [card-eid "abcdefghijabcdefghij1"
+ store (map-content-store {card-eid {:id 4242 :database_id 1}})
+ ir (resolve.mp/import-resolver mp-simple store)]
+ (is (= 4242 (resolve/import-fk ir card-eid 'Card))))))
+
+(deftest import-fk-card-via-custom-content-store-unknown-test
+ (testing "unknown entity_id from a custom store still surfaces :unknown-card"
+ (let [ir (resolve.mp/import-resolver mp-simple (map-content-store {}))]
+ (try
+ (resolve/import-fk ir "nonexistent_entity_id1" 'Card)
+ (is false "expected throw")
+ (catch clojure.lang.ExceptionInfo e
+ (let [d (ex-data e)]
+ (is (true? (:agent-error? d)))
+ (is (= :unknown-card (:error d)))))))))
+
+(deftest import-fk-card-via-custom-content-store-cross-database-test
+ (testing "cross-DB check fires regardless of where the card came from"
+ (let [card-eid "abcdefghijabcdefghij2"
+ ;; mp-simple's database is id=1; serve a card pinned to a different db.
+ store (map-content-store {card-eid {:id 99 :database_id 999}})
+ ir (resolve.mp/import-resolver mp-simple store)]
+ (try
+ (resolve/import-fk ir card-eid 'Card)
+ (is false "expected throw")
+ (catch clojure.lang.ExceptionInfo e
+ (let [d (ex-data e)]
+ (is (true? (:agent-error? d)))
+ (is (= :cross-database-card (:error d)))
+ (is (= 999 (:card-database-id d)))))))))