Compare commits

...

838 Commits

Author SHA1 Message Date
Bryan Maass
6b8829bd58 Spike: sqlc -> Clojure query codegen with Malli schemas
Generate Clojure query fns with Malli result schemas from .sql files, using
sqlc for SQL parsing and type inference and sqlc-gen-json to expose its
analysis as JSON.

Verified end to end: migrations against Postgres 16 (1427 changesets, 190
tables), pg_dump fed to sqlc unmodified, real queries ported from the
glossary/sso HugSQL spike branches, and the generated file compiles with
schemas that accept valid rows and reject bad ones.

See dev/src/dev/sqlc/README.md for open issues (no H2 engine, weak param
type inference, no dynamic SQL).
2026-09-15 23:06:24 -06:00
Chris Vandoodewaard
14fe567687 only auto-patch current version (#82368)
only auto-patch latest
2026-09-11 14:56:29 -04:00
technomancy
daceb36e65 Snowflake schema specified in :additional-options should take precedence (#82364)
Fixes https://github.com/metabase/metabase/issues/65493

If you have a `details.schema` property set in your connection (this was
removed in v42 in favor of schema filters), you can't change it in the
UI in the current Metabase version.  If you wanted to specify a schema
through the "Additional JDBC connection string options", the old
buried schema property would take precedence anyway.

This makes it so the deprecated field is removed when the schema is
set in additional-options.

I've verified this using a real connection and querying `SELECT current_schema()`
as suggested in the bug report.
2026-09-11 11:20:31 -07:00
github-automation-metabase
1c561d056c Tighten ratchets (#82365)
Co-authored-by: github-actions <github-actions@github.com>
2026-09-11 17:42:07 +00:00
Chris Truter
dd9d8d0579 Ratchet module boundary escape hatches (#82300)
Protect against bad things happening because agents and reviewers aren't aware that they're bad.
2026-09-11 17:36:42 +00:00
metamben
d0cbe49c68 Prime app-db connection-pool before use (#81601)
* Prime app-db connection-pool before use

Closes QUE2-833
Closes #81440

* Fix linter warnings
2026-09-11 17:08:38 +00:00
Nick Fitzpatrick
3e83533d06 BE PDFs - target 300dpi for rendered visualizations (#81078) 2026-09-11 13:55:16 -03:00
Chris Truter
eff3209a34 Add hierarchy to the backend module system (#82301)
This will allow us to resolve a lot a cycles in the module graph, and increase encapsulation considerably.
2026-09-11 18:48:15 +02:00
Alex Yarosh
93aabef5d3 docs: expand data modeling overview (#82309)
* data modeling overview

* copy paste strikes again

* Apply suggestions from code review

Co-authored-by: Michael Eby <38187276+michaeleby1@users.noreply.github.com>

---------

Co-authored-by: Michael Eby <38187276+michaeleby1@users.noreply.github.com>
2026-09-11 16:37:49 +00:00
Anderson
1a8883d604 Revert "Apply responsive spacing and typography to dashboard chart cards" (#82346)
* Revert "Apply responsive spacing and typography to dashboard chart cards (#81…"

This reverts commit 13e00d55b9.

* Update Loki Snapshots

---------

Co-authored-by: Metabase Automation <github-automation@metabase.com>
2026-09-11 13:10:36 -03:00
Timofey Kachalov
0cf4be2fd2 Fixed MCP search response schema validation (#82205) 2026-09-11 20:02:54 +04:00
Eric Normand
615cfdb48b Fix race in detached-fetch!-sweeps-stalled-fetches-test (#82347)
The test read `:future-ref` straight off the registry entry as soon as the
fetch signalled it had started. But `detached-fetch!` registers the entry
before the fetch begins and only stores the future just after submitting it,
so the thunk can deliver `started` before the `reset!` lands. When it does,
`stalled-future` is nil and `future-cancelled?` throws an NPE.

Under 300 spinning threads a probe caught the window 1-4 times per 20000
fetches; inserting a 5ms sleep between the `future` and the `reset!` makes
the old test fail every run.

Poll for the future instead. Only the test is affected: the sweep acts on
entries older than *fetch-max-age-ms* (an hour), so it can never observe one
whose `:future-ref` is still unset.


Claude-Session: https://claude.ai/code/session_01J1yFPpYiWH2ik8LB9rs7BT

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-11 10:56:49 -05:00
Alex Yarosh
19989ab207 docs: cloud migration (#82305)
* Revise migration steps 

Updated migration guide to clarify steps and include images.

* Delete docs/cloud/images/migrate-button.png
2026-09-11 15:36:37 +00:00
Alex Yarosh
efb95e2e18 docs: add glossary article (#82308)
* add glossary article

* Optimized 2 images, saved 219.4 KB (42.5% smaller)

* link

* Update docs/data-modeling/semantic-layer/glossary.md

Co-authored-by: Jeff Bruemmer <jeff.bruemmer@gmail.com>

---------

Co-authored-by: Metabase Automation <github-automation@metabase.com>
Co-authored-by: Jeff Bruemmer <jeff.bruemmer@gmail.com>
2026-09-11 15:29:28 +00:00
Riley Thompson
3ad97e619d Use multiple jvms per runner for bigquery tests (#81204)
* multiple jvms per runner for bigquery

* trigger CI

* add failing test

* lower timeout

* remove debug stuff

* clean up comments

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-09-11 11:27:34 -04:00
Anna Tomka
5b7c89d8ee GDGT-2478 Translate PasswordInput toggle label at call time (#82338)
* GDGT-2478 Translate PasswordInput toggle label at call time

* Update Loki Snapshots

---------

Co-authored-by: Metabase Automation <github-automation@metabase.com>
2026-09-11 15:26:10 +00:00
Riley Thompson
05d2f186a0 Use calendar days for bigquery datetimeDiff (#82194)
* BigQuery: use calendar days for datetimeDiff day unit

Fixes #82193

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* Avoid :raw for date part in BigQuery day diff

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* clean up

* add timezone to test

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-11 10:53:37 -04:00
Phoomparin Mano
c8f77a0925 Data Apps Permissions (#79822)
* add saved question extraction prototype

* fix additional failure cases

* refactor: reconciler

* revert me: manual skill file edit for source swapping

* set data permissions to view for databases referenced in the query

* rename data app collection and group

* prevent agents from removing savedQuestionSourceId

* docs: clarify data app query location

* chore: cleanup query-sync canonical module

* refactor: split query tests into different files

* Swap query source for data app query hooks and apply dynamic filters on top of it (#79584)

* code improvements and bug-fixes for data apps permissions

* Add data apps model imports

* address reviews on data apps permissions

* run sync queries before vite build

* Add data app resource link (#79878)

add button to view data app resources

* Show permission error when users cannot access a data app (#79874)

show permission error page when user do not have permission to view data apps

* Add data app group link in overflow menu (#79873)

Add data app group link

* Store and reconcile data app entity ids in data_app.yaml (#79833)

* Store data app resource entity IDs

* make entity ids in data_app.yaml authoritative

* add top-level value after path key

* simplify data_app.yaml manifest parser

* only allow changing data app collection if empty

* consolidate backend test helpers and remove redundant tests

* chore: restore README changes

* ci: fix failing tests

* Add support of actions to Data App reconciler (#79842)

Add support of actions to Data App reconciler

* Fix bugs/inconsistency and add more e2e for data apps reconciler/syncing (#80002)

* Update semantic schema skill about preventing segments and measures in dynamic parts of a query in Data Apps (#80288)

* Grant view data access on a table-by-table basis in data app groups (#80189)

* grant view data on table instead of database level

* refactor table scan in reconciler

* update e2e tests for permission grants

* Grant data app view permissions per table

* Skip unchanged data app permissions

* add e2e data app test for sandboxing

* reset host app sources after runs

* Preserve sandboxing for data app users (#80406)

* add e2e data app test for sandboxing

* improve e2e tests for data apps

* Remove sandbox E2E from table permissions change

* preserve existing sandboxing from sandboxed groups in data apps

* assert that we grant non-sandboxed tables

* Explain data app sandbox exclusion

* Add data app sandbox E2E coverage

* Exercise sandbox preservation in data app E2E

* Disable saved question sources in data apps (#80139)

* Disable saved question sources in data apps

* Preserve question-only schema scope

* Remove the saved question schema parameter

* Copy table-sourced metrics into data app collection and do not codegen card-sourced metrics (#80086)

* copy table-sourced metrics into the data app collections

* copy table-sourced metrics into the data app collections

* Address metric sync review feedback

* Accept keyword metric display in query response

* Fix data app metric reconciliation ordering

* Remove old lockfile format

* exclude card-sourced metrics from schema generator

* do not use card terms in metrics to avoid ambiguity with card-sourced metrics

* fix model imports

* Fix data app metric reconciliation

* refactor: cleanup reconciler unit tests

* Fix duplicated metric client helper

* add safe metrics path

* Handle unsupported metric dependencies

* Fix data app CI test regressions

* Fix "Re-adding removed query fails to adopt deleted card" (#80341)

* Clean-up data apps permissions endpoints (#80825)

* Remove entity ids from data_app.yaml (#81317)

Remove data app entity ids from data_app.yaml

* Adjust data apps permissions code (#81093)

* Remove the data app table permission grants (#81584)

* Add permissions_group.is_data_app_group and hide data app permission groups from UI (#81705)

* Add data app user management and access warnings (#81839)

* Address data app user access review feedback

* additional e2e test cases for bugs in manage users page

* fix failing frontend type check on unit test

* fix migration id collision for data apps

* combine migration changes into one file

* fix data app metric sync after trashing copied metrics

* fix cli runtime dependency packaging for embedding sdk

* avoid loading data app bundle during resource setup

* prevent redundant data app collection permission updates

* allow admins to remove data app members after token expires

* update docs and add e2e test for missing resource collection case

* isolate data app sync using transactions

* do not leave user on an empty page when removing the last member on the page

* reserve sandbox-host slug in data app config

* ignore generated data app action fixtures

* move queries into db.clj

* preserve legacy permissions when adding data app members

* regenerate the kondo modules config

The data-apps module reaches for :model/Permissions and :model/DataPermissions,
neither of which was recorded in :model-imports, so metabase.core.modules-test
fails on the current tree.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011nNKkhQjjiUSM7qwLReyfP

* reject data app queries whose metrics read another card

Sync copies a referenced metric but rewrites nothing inside the copy, and
copies nothing that copy in turn reads, so those references still point at
the originals. The app publishes successfully and then fails for every
viewer without access to the originals' collections.

Checking while resolving the query, rather than at codegen, also catches a
metric edited into that shape after its schema was generated.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011nNKkhQjjiUSM7qwLReyfP

* exclude metrics that read a saved card anywhere from generated schemas

source-card-id only reads stage 0, so a table-sourced metric that joins a
saved question passed the codegen filter. The CLI checks the whole query and
rejects such a metric, aborting sync-resources for any app that uses it.

Checking the whole query here keeps codegen consistent with what sync
supports, and removes the database round trip that asked which of the
referenced cards were metrics -- the step that let a saved-question join
through in the first place.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011nNKkhQjjiUSM7qwLReyfP

* resolve copied resources' table dependencies through the server

Numeric source-table entries miss implicit joins: a copied model querying
Orders and reading Products.Category through a foreign key names Products
nowhere, so it was left out of the app's permission warnings.

Run the same metadata-based lookup the query endpoint uses, through a new
endpoint the CLI calls for copied models, actions and metrics, and drop the
JSON walk it replaces.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011nNKkhQjjiUSM7qwLReyfP

* cover the create-queries grant the database defaults leave on app groups

An app group that predates the first non-audit database is given
create-queries :query-builder-and-native by set-new-database-permissions!,
alongside the :blocked view-data it special-cases for app groups. A user with
data access through another group would gain native query authoring just by
joining the app.

The reconciler already resets it, but nothing failed when :perms/create-queries
was dropped from its list. The pairing cannot be produced through
set-database-permission!, which cascades view-data to :unrestricted for any
create-queries value other than :no, so the test writes the row the way the
defaults insert it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011nNKkhQjjiUSM7qwLReyfP

* prevent models based on saved questions from being copied

* return to a valid member page after overlapping removals

* do not resolve query objects when either enabled flag is false

* prevent shorthand properties and spreads from overriding generated ids

* prevent adding duplicate members and retry only members that are failed to add

* define schema for data app query endpoint

* reconcile only the current data app group during resource setup

* expand the schema fingerprint

* add data app group field in permission group schemas

* prevent new databases from granting query creation to data app groups

* throw validation errors when invalid query spec fields are passed

* do not fail validation on columns metadata

* add enabled metadata to query definition schema

* accept more data app specific query metadata and binning options

---------

Co-authored-by: Timofey Kachalov <timofei@metabase.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-11 15:41:01 +01:00
Timofey Kachalov
1626b31be7 Fix flaky child-frame realm gate in the data-app sandbox (#82324) 2026-09-11 18:07:04 +04:00
metamben
2659b87941 Throw on uncoerceable user attributes (#82118)
Closes QUE2-842
Closes #81821
2026-09-11 14:05:29 +00:00
metamben
b2c923e496 Remove explicit :fields on the last stage of pivot queries (#82111)
Closes QUE2-825
Closes #81203
2026-09-11 17:03:42 +03:00
Chris Vandoodewaard
cc1fa36312 add workflow combining quick and simple PR checks (#82126)
* combine workflows into single pr.checks.yml

* fixes and better checkout

* ignore parallel lint failure

* add filter to checkout to avoid slow checkouts

* remove check
2026-09-11 13:59:23 +00:00
github-automation-metabase
498dfc7435 Tighten ratchets (#82331)
Co-authored-by: github-actions <github-actions@github.com>
2026-09-11 13:16:25 +00:00
Ben Grabow
6780dbbf52 Allow multiple intermediate ns segments (#82125)
* Allow multiple intermediate ns segments

* Detangle llm settings

# Conflicts:
#	src/metabase/llm/provider.clj

* Move settings.providers to providers.settings

* Move providers.settings to provider.settings

* Loosen filter to include all `metabase.llm.*` settings

* Merge from master

* Delete obsolete linter ignore

* Clarify linter message
2026-09-11 08:11:09 -05:00
Jeff Bruemmer
86f64c3d9f docs - update docs job (#82327)
update docs job
2026-09-11 08:57:59 -04:00
Anna Tomka
ca17b89463 GDGT-2478 PasswordInput (#82117)
* test(ui): add PasswordInput Storybook story

* test(ui): add PasswordInput to Loki as baseline for restyle

* feat(ui): restyle PasswordInput from Figma and add input-background token

* test: cover PasswordInput visibility toggle in unit and e2e tests

* fix(PasswordInput): use highlight border color in focused error mode by overriding Input styles

* Update Loki Snapshots

* test(ui): add Loki reference for PasswordInput Overview story

* fix(PasswordInput): address review feedback

- keep border width constant and use an inset ring for focus/error to avoid layout shift
- tie right padding to the toggle button size so text clears it in lg
- restrict size prop to sm | md | lg
- order color keys alphabetically
- explicit visibility assertion in the e2e spec

* Update Loki Snapshots

---------

Co-authored-by: Metabase Automation <github-automation@metabase.com>
2026-09-11 14:18:41 +02:00
Anna Tomka
38b7b8c0b7 GDGT-3212 add missing inner border in dark theme (#82203)
* fix(Pill): add missing inner border in dark theme

* fix(Pill): drop explanatory comment per review
2026-09-11 14:18:11 +02:00
Kevin Kelleher
94e58da90d Fix auto-wiring dashboard filters to dashcards with multiple series (#81913)
* handle auto-wiring dashboard filters to dashcards with multiple series

* review feedback
2026-09-11 07:24:06 -04:00
Oleh K
6a035e234c Use JetBrains Mono as the code font (#82278)
* Use JetBrains Mono as the code font

Ship JetBrains Mono (regular + bold) and point the monospace font family
at it, replacing the hardcoded Monaco/Menlo stacks scattered across the
codebase.

- Add the woff2 files, @font-face declarations, and the type, fallback
  map, docs and backend test entries that keep the admin font picker in
  sync with the fonts directory.
- Route every monospace call site through
  --mb-default-monospace-font-family, and define that variable in the
  embedding SDK's variable set, where it was previously missing. With
  the variable always defined, the per-call-site `, monospace` fallback
  is redundant and is dropped.
- Inline the variable at the CodeMirror theme, which was the only
  consumer of monospaceFontFamily, and delete typography.ts.
- Set the Code component to 13px/22px per the design spec.

* Update Loki Snapshots

---------

Co-authored-by: Metabase Automation <github-automation@metabase.com>
2026-09-11 12:12:15 +02:00
Andrei Simionescu
b75caae5f3 AI settings docs: a provider connection takes credentials, not just an API key (#82026)
Bedrock takes an AWS access key pair and Google Gemini Enterprise a service
account key file, so the AI settings page can't keep calling every provider
connection an API key.
2026-09-11 09:18:39 +01:00
Fraser
a5af036433 Rehome the analytics export machinery to EE audit_app (#79808) 2026-09-11 19:04:08 +12:00
Romeo Van Snick
1c5ba041d6 Stop the metabot viewing-context tests from depending on absent entity ids (#82248)
The tests pass ids like 789 for entities they do not create. format-entity looks the
id up, and the test asserts on the fallback rendering that a 404 produces. When a
parallel test happens to hold that id, read-check gives a 403 instead, which renders
nothing, and the test fails.

Use Integer/MAX_VALUE, which no fixture allocates.


Claude-Session: https://claude.ai/code/session_01GCoSa7L7KrXh42rDRYR3Nk

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-11 15:11:30 +10:00
Romeo Van Snick
86c23eaf5e Read a card's UI parameters off its question (#82238)
* Read a card's UI parameters off its question

* Drop a tombstone comment

* Pin the agreement between getCardUiParameters and Question.parameters

* Type the unsaved card in the agreement test

* Format the agreement test
2026-09-11 15:11:21 +10:00
Fraser
1447d9cf97 Move the application permissions selector slot into current-user (#81846)
* Move the application permissions selector slot into current-user

PLUGIN_APPLICATION_PERMISSIONS.selectors was only read by current-user, so the slot now lives there as PLUGIN_APPLICATION_PERMISSIONS_SELECTORS with its OSS defaults, and the EE application permissions plugin registers into it from metabase/current-user. getRoutes and tabs stay in metabase/plugins for the admin permissions editor.
2026-09-11 16:42:11 +12:00
Romeo Van Snick
90688e49a7 Translate at call time, not at import time (#82147)
* Translate viz nouns and formatting operators on demand

`noun` was the one field on a visualization definition still translated at
import. `get noun()` matches what ObjectDetail and TreemapChart already do,
and the registry stores a definition by reference, so the getter survives.

The table-formatting operator names were four module-level objects. They are
functions now. `ALL_OPERATOR_NAMES` becomes `getAllOperatorNames()`, which
its three readers call.

25 of the 124 sites that translate before a catalogue can be applied.

* Translate settings titles on demand

`title` in a settings definition follows the same rule as the rest of the
object. 152 settings already use `get title()`; these 23 were the laggards.

The group-managers confirmation held two frozen strings, so it becomes a
function rather than an object with getters.

49 of 124.

* Lift translated containers into functions

Where a whole array or object is translations, the function goes on the
container so consumers keep a plain array or object: PieChart's ring titles,
the whitelabel illustration options and descriptions, PivotTable's partitions
(which held JSX built at import), the model-caching options, the cloud
migration messages, and the geo filter placeholders.

Where only a field or two of a mixed config is translated, and call sites read
it by property, the getter goes on the field instead. That covers the
collection configs, the permission option records and the loading messages,
none of which are spread anywhere.

Four files carried a whole-file disable rather than one per site, hiding 20
sites behind 4 directives. The real total is 140, not 124.

118 of 140.

* Clear the last module-scope translations

Validation schemas become functions, matching getOidcFormSchema and the other
lazy schemas already here. Module-local error strings become functions called
at their use sites. Three exported constants follow: NULL_DISPLAY_VALUE,
BEFORE_UNLOAD_UNSAVED_MESSAGE and NO_X_AXIS_VALUES_ERROR_MESSAGE, across 37
files.

The two Mantine `aria-label` defaults get a getter. Mantine merges
`defaultProps` by spread on each render, so the getter is read every time.

`ttag/no-module-declaration` now passes across all five trees it covers with
no opt-outs left, and `--report-unused-disable-directives` confirms none were
stranded.

* Stop spreads from flattening lazy translations

A spread or a rest destructure reads every getter it copies. Where an object
holds `get title()` so the string translates when it is read, spreading that
object at module scope translates it at import instead, which is the bug the
getters were meant to avoid.

Adds `mergeLazily` / `omitLazily`, which copy property descriptors instead,
and uses them where the flattening happened at import:

- `viz-core/lib/settings/utils.ts` flattened twice, once in the rest
  destructure and once in `...def`, so every setting built through
  `fieldSetting` / `metricSetting` / `dimensionSetting` froze at import.
- `palette/shortcuts/index.ts` spread five shortcut maps into one.
- `PaletteShortcutsModal` spread each shortcut again while grouping, so that
  now happens per render.

Measured with a test that imports every source module with `ttag` mocked:
40 modules and 370 translation calls at import, down to 35 and 256.

* Build parameter, admin and graph settings when read

* Build option lists when they are rendered

* Guard import-time translation with a test

* Make the instance analytics message a function so the plugin registry can replace it

* Resolve admin path names when the navbar renders them

* Give the enterprise caching tabs a lazy name too

* Skip generated cli-snippets from the side-effect scan

* Key the null slice by its untranslated label

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NUuaopJ7ZtMVvdwwxF6qyx

* Fail the import-time guard on unlisted import errors

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NUuaopJ7ZtMVvdwwxF6qyx

* Read lazy translations once per render, not per lookup

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NUuaopJ7ZtMVvdwwxF6qyx

* Let jest transform the MCP ext-apps package

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NUuaopJ7ZtMVvdwwxF6qyx

* Skip the SDK cli scripts in the import-time guard

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NUuaopJ7ZtMVvdwwxF6qyx

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-11 14:16:04 +10:00
Romeo Van Snick
60f2668137 Build dashboard and query-runner questions from the store (#82241)
* Build dashboard and query-runner questions from the store

* Cover the pivot endpoint selection
2026-09-11 14:13:19 +10:00
Romeo Van Snick
503c3bf068 Build the card embed and SDK questions from the store (#82253)
* Build the card embed questions from the store

* Read the SDK parameter values off the question
2026-09-11 10:27:16 +10:00
Fraser
a6de42f467 Re-tier styled-components to U4 and enforce its shared tiers (#82256) 2026-09-11 12:22:50 +12:00
github-automation-metabase
c998859487 Auto-update documentation for master (#82298)
Update generated docs (master)

Co-authored-by: github-actions <github-actions@github.com>
2026-09-10 23:37:23 +00:00
Alexander Polyankin
a491bd11be Namespace the table name BigQuery's compiled native form carries as :qp/table-name (#82275)
* Namespace the table name BigQuery's compiled native form carries as :qp/table-name

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* Update the BigQuery compile tests for :qp/table-name

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* Update the remaining BigQuery compile tests for :qp/table-name

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-10 19:23:06 -04:00
Anderson
0a30b63176 Trim redundant Data Studio TablePicker end-to-end tests (#81848)
Trim redundant Data Studio TablePicker E2Es
2026-09-10 19:18:50 -03:00
technomancy
f1ce332568 Refuse to create new tables in static datasets with Snowflake (#82222)
Refuse to create new tables in static datasets with Snowflake.

Table creation will always succeed on non-static datasets, but if it's
static then the table being created has to be a table that's in the
dataset definition.

Ensure all tests which alter the dataset by creating new tables
declare a non-static dataset. The transform-related tests switch over
to using transforms-dataset/transforms-test which most of them are
already using.

Upload tests have their dataset defined in a fixture so we can do it
all in one place instead of editing 60 different deftests.
2026-09-10 14:55:14 -07:00
Will Fry
1690028d0f GDGT-2653: uncomment E2E assertions (#82199) 2026-09-11 00:10:43 +03:00
Andrei Chernykh
0c76874681 Move SSO user provisioning a toggle card under server settings (#82232)
* Make SSO user provisioning a toggle card under server settings

* Debounce provisioning writes and drop the real timers from the spec
2026-09-10 13:52:45 -07:00
Chris Vandoodewaard
a6be073fb2 auto-merge e2e timing update prs (#82292)
* create PR using CLI, also auto-approve/merge

* cleanup string, check if things changed

* remove extra blank line

* namespace file
2026-09-10 15:05:29 -04:00
Ben Grabow
cb4541b965 Extract dispatch type hierarchy (#82226) 2026-09-10 13:37:56 -05:00
Ben Grabow
463fb9355b Extract entity types (#82265) 2026-09-10 13:23:50 -05:00
Andrei Chernykh
791b649cc0 bump qs to 6.16.0 (#82283) 2026-09-10 11:06:44 -07:00
Tyler Plude
085418edb8 [GIT-74095] Use git path separators in remote-sync export paths (#82284)
use git path separators in remote-sync export paths
2026-09-10 10:47:29 -07:00
Andrei Chernykh
1118c3e897 Bump js-yaml to 4.3.2 (#82282) 2026-09-10 10:36:08 -07:00
Alexander Polyankin
6e74e41eaf Strip undeclared keys from stored and legacy queries the way the request decoder does (#82273) 2026-09-10 13:32:50 -04:00
metabase-bot[bot]
38404fd9df [chore] Update E2E test timings with recent data (#81995)
Update E2E test timings with averaged data

Collected timing data from 7 days of test runs.
All specs with timing data were included (simple averages).

🤖 Generated automatically by update-e2e-timings workflow

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: GitHub Actions <actions@github.com>
2026-09-10 17:26:53 +00:00
Chris Vandoodewaard
8a7cd79f47 Bump backend deps to resolve security vulnerabilities (#82261)
* bump backend deps

* missed bump
2026-09-10 13:25:18 -04:00
Alex Yarosh
f3685652d3 docs: making semantic layer happen - org part (#82247)
* rename directories

* Revert "rename directories"

This reverts commit 13ebd4ae48.

* heard you like links

* what good is claude if it doesn't even find all the links

* Optimized 55 images, saved 698.8 KB (11.2% smaller)

* Fix docs links after merge

Co-authored-by: alexyarosh <16640109+alexyarosh@users.noreply.github.com>

* Fix merged docs regressions

Co-authored-by: alexyarosh <16640109+alexyarosh@users.noreply.github.com>

* Tighten merged docs links

Co-authored-by: alexyarosh <16640109+alexyarosh@users.noreply.github.com>

* Revert extra post-merge docs edits

Co-authored-by: alexyarosh <16640109+alexyarosh@users.noreply.github.com>

* link

---------

Co-authored-by: Metabase Automation <github-automation@metabase.com>
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: alexyarosh <16640109+alexyarosh@users.noreply.github.com>
2026-09-10 12:49:43 -04:00
Andrei Simionescu
08497ded2f Bump csv-parse to 7.0.2 (#82266) 2026-09-10 15:48:24 +00:00
appleby
bfe0b19738 Update map tile server settings with suggested copy from DOC-301 (#81835)
* Update map tile server settings with suggested copy from DOC-301

And also include a link to the relevant page in the metabase docs.

* Add a note about not including private keys to the docstring for map-tile-server-url

so that the warning also shows up in the env var docs.
2026-09-10 08:44:01 -07:00
Riley Thompson
a155c1f4ee Document bigquery median behaviour (#82201)
* BigQuery: use PERCENTILE_CONT for median and percentile

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* update docs

* update doc

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-10 11:42:36 -04:00
Braden Shepherdson
9f48230b57 [PDFs] Respect the text wrapping settings on tables (#77090)
Fixes UXW-4714.

The static viz for tables uses a fixed width, but it was too big for the
PDFs, causing tables with long text in columns to lay out badly.

This PR disables the fixed width of `780px` on tables for PDFs, so that
the tables now lay out correctly.
2026-09-10 15:39:28 +00:00
Ben Grabow
503349c6ae Fix duplicates of the same namespace name (#81974)
* Fix collisions on metabase.notification.payload.core-test namespace name. Lint for future collisions.

* Include .clj-kondo/{src,test} in backend check triggers

* Expect the new project test namespace

* Symbolically reference project test suite namespaces

* Include resources, test_resources, test_config dirs in project checks

* Return [namespace relative-path] pairs.
Skip local/src

* Catch read-file errors and explain why some files may not have ns forms

* Sort paths that collide
2026-09-10 10:24:17 -05:00
Jeff Bruemmer
4d60c4bcf5 docs - nav link check (#82211) 2026-09-10 15:08:17 +00:00
Chris Truter
d9f905b7da Fix H2 migration failures after running transforms (#82135)
* Copy the transform tables in dump-to-h2 and load-from-h2

None of the nine transform_* models were in copy/entities, but metabase_table is,
and it carries a transform_id FK to transform. A table row reached the target
referencing a transform row that never arrived, and the deferred FK check
rejected it at commit.

transform_run_cancelation also goes in entities-without-autoinc-ids, since its
primary key is run_id rather than an autoincrement id.

Adds copied-tables-have-copied-fk-parents-test, which migrates a throwaway H2
database and fails if any copied table's FK parent is not copied.

* Simplify the copy foreign-key regression test

* Clarify the foreign-key coverage test names
2026-09-10 14:42:03 +00:00
Andrei Simionescu
36f273d523 BOT-1790: Redact Metabot chain-of-thought details in embedded sessions (#81872) 2026-09-10 14:01:55 +01:00
Alexander Polyankin
38cda45f69 Type every :any and [:map-of :keyword ...] property in the API (#82196)
* Make defendpoint reject request schemas that reach an open map, a keyword-keyed map-of or :any

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* Close the MBQL 5 query and column schemas and declare the keys the query processor adds

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* Type the shared schemas requests reach and drop ms/Map and ms/JSONString

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* Close every map schema a request can reach

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* Regenerate the modules config

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* Keep action parameters string-keyed and type lens params and permission graph ids

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* Declare the sandbox coercion keys a column's options can carry

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* Declare the alias-info and Mongo keys a column can carry and strip internal keys from legacy column metadata

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* Carry the Mongo column keys in the serialize test fixture

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* Declare the keys the frontend and query processor put on columns, parameters and card embeds

- column metadata: :remapping, a typed :lib/options, the nest-breakouts option key
- query parameters accept the rest of a stored filter declaration
  (sectionId, isMultiSelect, values source config etc.)
- static-list values may be one-tuples; raw-value template tags may
  carry a nil widget-type
- card embed attrs declare chart_href, child_target_id and host_data;
  explore filter refs accept the legacy field_ref the chart column has
- notification card echoes a metric's query_description
- serialization deep-sort orders mixed keyword/string keys
- viz-settings column refs are normalized before matching; a Field
  hydrated with its table can be fingerprinted; broken segment
  definitions read back as nil
- test fixtures: real fingerprints, snippet tag type, http channel
  details, comment content, no min_duration_ms on duration strategies

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* Wire the defendpoint check, keep every map single-keyed, and apply the review findings

- defendpoint now calls closed-schemas/check! on every request schema;
  the walker no longer lets :any leak through collections, treats
  map?/:some as :any, skips :=/:enum/:fn values and never skips the
  default entry
- no map mixes keyword and string keys: ms/string-keyed-object gives an
  opaque JSON object string-keyed declared entries; ProseMirror attrs
  (documents, comments, explorations embeds), CSV upload parts, search
  weights and testing query specs use it and their readers use string
  keys; the serdes deep-sort comparator is back to master
- the Metabot context is fully typed from the frontend types instead of
  an opaque default; a draft transform query without a database is
  accepted
- permission graphs, settings PUT and SCIM PATCH reject a body whose
  map-of entries the decoder dropped; ad-hoc query endpoints drop a
  client-sent cache strategy; action parameter values keep collections
  out without nil-ing them; SCIM meta.resourceType is optional; sandbox
  user attributes are LoginAttributes; a metric filter clause carries its
  offset options; explore filter refs are the legacy field_ref the
  chart column has; result_metadata written by older releases and
  hasVariableTemplateTagTarget on parameters are declared; a bare
  map-of on a request path is guarded against scalars

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* Close the endpoints tests define and let a column's target and name field be an id reference

The check runs on every defendpoint, the ones test namespaces define included. A column's
:target and :name-field are hydrated Fields on the backend but id references in the
metadata the frontend hands over; the closed column schema nil'd the reference, which
lost the search field of a model's primary key.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* Hand an action's query only the parameter values, and fix two fixtures the closed schemas caught

A query action's stored parameters carry the frontend's widget settings; the query gets
the value keys. The Metabot viewing-context tests use ids no card can have, and the
Mongo cache test spells the strategy key the schema does.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* Declare the table name BigQuery's compiled native form carries on a native stage

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* Keep a BigQuery RECORD's sub-field sync metadata off its result column, and fix a binning fixture

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-10 08:17:08 -04:00
Timofey Kachalov
fc18a66b6c Add remaining data apps sandboxing e2e (#82170) 2026-09-10 15:44:38 +04:00
Chris Vandoodewaard
433561ad5b Move Snyk scans into the Lint Security workflow (#82197)
* Move Snyk scans into the Lint Security workflow

Fold snyk.yml's three jobs into lint.security.yml as snyk-generate-poms,
snyk-frontend-projects, and snyk-maven-projects, and delete snyk.yml.

Snyk now runs on the existing daily 11:00 UTC cron instead of its own
05:00 cron and dependency-file push trigger. The notify job reports Snyk
failures to Slack alongside CodeQL and Trivy, and Snyk's upload-sarif is
bumped from v3 to v4 to match the rest of the workflow.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* add timeouts

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-10 07:16:23 -04:00
Will Fry
3c23f921e2 GDGT-3132 fix misaligned undo toast (#82045)
* GDGT-3132 fix misaligned undo toast

* migrate UndoListing to from styled components to CSS module

* absolute px -> rem, compact -> compact-md

* fix inconsistent toast height, use line-height instead of measuring the DOM to handle single vs multi line layouts

* strip comments
2026-09-10 11:06:19 +00:00
Oleh K
7f4883cc49 Fix inefficiencies in formatValue (#82103)
* GDGT-3195: Fix inefficiencies in formatValue

formatValue is fine per-cell but pathological in bulk; the "Copy results"
button made this visible, with a 100x2000 grid spending ~4.5s in this path.

- Drop a dead dayjs strict parse. The format literal 'T' is not valid dayjs
  escaping (dayjs wants [T]), so isValid() returned false for every value.
  It sat above the string/number/boolean branches, so every non-date cell
  paid for it.
- Only JSON.parse the value when a markdown_template will consume it,
  instead of on every call.
- Memoize the per-column type predicates (isURL/isEmail/isTime/isDate/
  isNumber/isCoordinate/isBoolean) in a WeakMap keyed on the column. Each
  fans out into recursive type-hierarchy lookups that cross into CLJS, and
  they only depend on the column. Entries snapshot the type fields they
  were computed from, since the custom-viz API hands third-party code
  mutable column objects.
- Skip new URL() construction for values with no ":" in getUrlProtocol.
- Cache Intl.NumberFormat by its constructor options, bounded at 100
  entries with oldest-first eviction.

Also make the value-formatting signatures honest: formatUrl, getLinkText,
getLinkUrl and getRemappedValue take unknown, which is what they actually
receive. getUrlProtocol keeps its string signature, with getLinkUrl
narrowing before the call. This removes both `value as string` casts.

Benchmarked with a synthetic 100x2000 copy path (medians of 5):
full table 4512ms -> 440ms, text 1231 -> 12, currency 637 -> 20,
integer 535 -> 15, boolean 343 -> 5, email 101 -> 4.

Claude-Session: https://claude.ai/code/session_01KUcocQj2bJPwVBi4dXKyEP

* Cleanup

* Revert the createPlainCellFormatter change

Hoisting the options spread out of the per-cell closure is not worth the
churn. Measured in isolation with a realistic 22-key columnSettings, the
spread costs 0.023us per cell against 0.002us to reuse a hoisted
reference, so it saves ~4ms per 200k cells — a rounding error next to the
dead dayjs parse at ~13.5us per cell, and nothing at all for columns with
click behaviour, where both shapes spread per cell anyway.

* Address review feedback

Guard the markdown_template JSON.parse with a typeof check instead of
carrying the placeholder cast comment.

Cover the two changes the review called out as untested:

- numberFormatterForOptions returns the same formatter for equivalent
  options, a separate one for different options, and evicts the oldest
  entry once the cache is full. The eviction test resets the module so
  the 100-entry boundary does not depend on what earlier tests cached.
- formatUrl passes strings and numbers through untouched and renders
  booleans and objects rather than returning them raw.

Both were checked by mutation: breaking the coercion and stubbing the
cache lookup to always miss fails exactly those assertions.
2026-09-10 12:49:27 +02:00
Fraser
667d038d46 Move the upload error modal slot into status (#82242) 2026-09-10 21:18:59 +12:00
Fraser
19df422bbd Move the storage setup provider slot beside its context (#82243) 2026-09-10 17:44:42 +12:00
Fraser
9fff12013e Move the DataReference library pane slot into querying (#81858)
* Move the DataReference library pane slot into querying

DataReference is the slot's only reader and querying owns its props type, so the slot lives next to it as PLUGIN_DATA_REFERENCE.LibraryPane.
The enterprise library plugin registers into it at boot, and plugins/oss/library.ts no longer imports querying's DataReference types.
2026-09-10 17:44:28 +12:00
Fraser
4bc6ccb00c Move the verified search filter slot into search (#81860)
* Move the verified search filter slot into search

SearchSidebar is the only reader of PLUGIN_CONTENT_VERIFICATION.VerifiedFilter, so the field becomes PLUGIN_SEARCH_FILTERS in metabase/search/plugin, next to the other search filter components. The EE content verification plugin registers the filter there from initializePlugin, and the rest of PLUGIN_CONTENT_VERIFICATION stays in plugins without the search import.

* Declare the search filters slot with definePluginSlot

* Import definePluginSlot from the plugins entry point

* Describe the verified filter default without naming its consumer

* Cover enterprise feature gates and plugin reset behaviour

* Remove redundant plugin registration tests
2026-09-10 17:44:12 +12:00
Fraser
81049d6069 Move the entity icon slot into hooks (#81857)
* Move the useGetIcon plugin slot into hooks/use-icon

The hook is the slot's only reader, so the slot and its OSS default live next to it as PLUGIN_ICON.
The enterprise collections plugin registers into it at boot, and plugins/oss/collections.ts no longer imports metabase/hooks/use-icon.

* Declare the entity icon slot with definePluginSlot

* Import definePluginSlot from the plugins entry point

* Cover enterprise feature gates and plugin reset behaviour

* Remove redundant plugin registration tests
2026-09-10 17:43:59 +12:00
Fraser
85ce065045 Remove the stale dashboard selectors side-effect entry (#82252) 2026-09-10 17:43:34 +12:00
Romeo Van Snick
dcb85ae924 Trigger the stats workflows from Run tests, gated on the uberjar artifact (#82244)
* Trigger the stats workflows from Run tests, gated on the uberjar artifact

Both workflows have recorded nothing since 2026-09-03. PR #81238 took the push
trigger off `uberjar.yml`, so master merges reach it only through
`workflow_call`. A reusable workflow reached that way raises no `workflow_run`
event, and both watchers went quiet. 143 master commits went unmeasured.

They now watch "Run tests", which is what builds the jar on a master merge.
Its conclusion is not a usable gate, because it is `failure` on master more
often than `success`, from jobs that have nothing to do with the jar. The
uberjar artifact is the right gate: a new job looks it up without downloading
it, and a docs-only merge that skipped the build finds nothing and stops.

Calling both from `run-tests.yml` would have been lower latency, but a stats
failure would then turn the master run red, and `rerun-workflows.yml` watches
that run and would re-run master CI over it. Keeping them in their own run
keeps a stats problem to itself.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01171Lkmug15JzrcN2aMBLMk

* Let a PR run the size benchmark against its own uberjar

A `workflow_run` workflow always runs the copy on the default branch, so a
change here cannot be tried out before it merges. This matches the trigger
Bundle Load Stats already carries. A called run measures and reports; the
upload step stays gated on the `workflow_run` path, so it writes no row.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01171Lkmug15JzrcN2aMBLMk

* Trim the trigger comments in the stats workflows

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-10 14:38:31 +10:00
Romeo Van Snick
3403f82c0a Build the dashcard question and metric series from the store (#82250) 2026-09-10 14:32:27 +10:00
Romeo Van Snick
95306c12fc Take metadata options at the store door (#82249)
* Take metadata options at the store door

* Build the conversation detail questions from the store

* Select the test fixtures through the store door
2026-09-10 14:32:17 +10:00
github-automation-metabase
5d1e1ad8f1 Auto-update documentation for master (#82227)
Update generated docs (master)

Co-authored-by: github-actions <github-actions@github.com>
2026-09-10 00:06:10 -04:00
Romeo Van Snick
6465693b78 Take a metadata provider where the database is already known (#82160)
* Take a metadata provider where the database is already known

* Fold the source-code provider into a hook
2026-09-10 13:37:15 +10:00
Romeo Van Snick
4e4cbac853 Give the visualizations a question builder instead of the metadata object (#82158)
* Give the visualizations a question builder instead of the metadata object

* Let the visualizations read the question builder themselves

* Read the store when a chart brush builds its question

* Drop the single-use question helper

* Give the map and object-detail views the question builder too

* Drop the last v1 metadata reads from the visualization tree
2026-09-10 13:37:10 +10:00
Romeo Van Snick
9762d0e164 Keep the CSP nonce out of the DOM, and off script-src (#82161)
* Give a script-src nonce only to responses that opt in

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DEcoNcbcoVpvPsGsX3ceua

* Hand the CSP nonce to page JS via the script element, not a DOM-readable JSON block

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01DEcoNcbcoVpvPsGsX3ceua

* Pass the new script-nonce? arg at the common-test CSP call site

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01GCoSa7L7KrXh42rDRYR3Nk

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-10 13:01:23 +10:00
Anderson
13e00d55b9 Apply responsive spacing and typography to dashboard chart cards (#81906)
* Apply responsive spacing and typography to dashboard chart cards (UXW-5181)

* Update Loki Snapshots

* Fix preview height regression and update e2e tests for dashcard size tiers

* Fix card heading typography and non-cartesian chart bottom padding

* Update Loki Snapshots

* Apply new styles only on cartesian charts

* Move changed styled components to css modules

* Update Loki Snapshots

---------

Co-authored-by: Metabase Automation <github-automation@metabase.com>
2026-09-09 23:51:25 -03:00
Romeo Van Snick
ad2d269251 Send the Field columns a parameter widget reads, and stop re-resolving them (#81936)
* Send the Field columns a parameter widget reads in param_fields

* Stop re-resolving a parameter widget's fields through the store

* Keep the empty default a parameter widget's fields prop had

* Read the driver-dependent Field columns in param_fields expectations
2026-09-10 12:04:48 +10:00
Romeo Van Snick
a22958cee3 Track page load times on every master merge (#80978)
* Add a harness for measuring bundle load time

* Report the second load and make the benchmark safe to run in CI

* Run the load benchmark across network and CPU conditions

* Sign the load benchmark in to a real instance

* Track page load times on every master merge

* Backfill load times for recent master commits

* Rewrite the load-time backfill in TypeScript with a tested core

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Launch the benchmark jar the way we ship it, and lint the .ts scripts

* Measure the whole load, not just DOMContentLoaded

* Do not let the performance marks gate a reading

* Drop the backfill workflow

The goal is a global trend, which the per-merge job builds on its own after a
few days. Backfilling only bought a readable chart sooner, at the cost of a
second workflow and the largest script in the PR.

The commit date stamp goes with it. It existed so a backfilled row could claim
its commit's date rather than today's, and the per-merge job never set it.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012b67ubbXJVMuQrpuEksbeh

* Let a PR run the load benchmark against its own uberjar

A `workflow_run` workflow always runs the copy on the default branch, so a
change here cannot be tried out before it merges. The `workflow_call` trigger
lets CI hand the workflow a commit and reuse the uberjar it already built. A
called run measures and reports; it does not write rows to Stats.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01171Lkmug15JzrcN2aMBLMk

* Report each state from one load, not a median per reading

Every reading was medianed on its own, so a row described a load that never
happened. It could also put the readings out of order and print a page-ready
that precedes the TTFB beside it.

`measure.js` now picks the run whose DOMContentLoaded is the median of its
series and reports that run whole. The second visit happens once per browser
profile, so it stays the run itself, and its page-ready now comes from that same
load rather than from a median that included the series' first, uncached run.

`Cold spread %` still comes from all the cold runs. A spread is a property of the
series rather than of one load.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01171Lkmug15JzrcN2aMBLMk

* Read the largest paint with an observer, and cut the timeout

The first CI run reported a zero largest paint in all four conditions, and would
have done so forever. These entries never reach the performance timeline, so
`getEntriesByType` cannot see them. Only a `PerformanceObserver` can, and it has
to exist before the paint. Paint entries are buffered, which is why
first-contentful-paint needed none of this.

The browser keeps revising the value until the user interacts, and the reading is
taken once the page reports ready. It is a lower bound rather than the final
figure, which is what makes it comparable between commits.

That same run took 4.4 minutes, of which the measurement was 164 seconds. The
timeout drops from 25 minutes to 10.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01171Lkmug15JzrcN2aMBLMk

* Move the bench to frontend/test and write it in TypeScript

---------

Co-authored-by: Fraser <frasermcintosh1@gmail.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-09-10 11:42:14 +10:00
Fraser
e92dfab50e Refine TypeScript authoring and review skills (#82141) 2026-09-10 13:39:46 +12:00
Romeo Van Snick
7c4159eedd Read the query builder's cards and tables without the metadata object (#82159)
* Read the query builder's cards and tables without the metadata object

* Build the query builder's question from the store's builder
2026-09-10 11:19:39 +10:00
Romeo Van Snick
6dc53c3773 Keep the generated CLI snippets out of the side-effect registry (#82172) 2026-09-10 11:18:18 +10:00
Romeo Van Snick
86d1bf3ec7 Read table foreign keys from the store, not the metadata wrapper (#82163) 2026-09-10 11:17:59 +10:00
Chris Vandoodewaard
fe4e2beffa only re-run the failed specs for SDK component tests (#82220)
* granular re-run for sdk component tests

* update e2e-test to avoid clobering artifacts on multiple attempts
2026-09-10 12:27:57 +12:00
Romeo Van Snick
e096a361d8 Take a metadata provider in the detail-view query helpers (#82151)
* Take a metadata provider in the detail-view query helpers

* Select the detail-view queries instead of building them

* Take the provider for the table's own database

* Guard the table query selector's memoisation

* Type the table query guard against the API table
2026-09-10 09:13:56 +10:00
Ben Grabow
8b58b48375 Test registration fixes (#82130)
* Add missing requires

* Add missing requires

* Apply batched suggestions from code review

Co-authored-by: Ben Grabow <ben.grabow@metabase.com>

* Sort nses

* */keep-me
2026-09-09 17:28:31 -05:00
Fraser
ecde907aff Add definePluginSlot and a reset registry to metabase/plugins (#81926) 2026-09-10 10:01:23 +12:00
Andrei Chernykh
d1934fb897 Fix the JWT settings spec import after the store mocks move (#82228) 2026-09-09 14:45:58 -07:00
Jeff Bruemmer
03a39f47c8 docs - CLI updates (#81978) 2026-09-09 20:54:06 +00:00
thackervishal
ad22a8730c white_label - do not use hardcoded metabase in filenames for nonOSS (#81979)
* for EE/white_label - do not use hardcoded metabase in filenames
* test coverage includes test for special characters in application-name
* also use gibberish names in tests
2026-09-09 16:00:18 -04:00
Andrei Chernykh
3d145ccb73 Redesign the JWT group mapping section (#81928)
* Redesign the JWT group mapping section

* Tidy the JWT group mapping tests

* Type the group mapping hooks explicitly and tidy comments
2026-09-09 12:27:15 -07:00
metamben
1b93876984 Prevent inactive fields from breaking chain filtering (#82041)
Closes QUE2-820
Closes #80557

There are two changes:
1. handle `nil` nodes gracefully during traversal, and
2. don't add `nil` nodes to the graph in the first place.

Both of these changes alone fix the reported issue, but both make sense on their own.
2026-09-09 18:39:26 +00:00
Anderson
283b194a38 Stabilize Data Studio bulk-table e2e via shared TablePicker expand helpers (#81623)
* Stabilize Data Studio bulk-table e2e via shared TablePicker expand helpers

* Match unnamed-schema tables fetch and trim expand wait timeout to 25s
2026-09-09 15:33:00 -03:00
Alexander Polyankin
28b2ad9eb6 Remove Honey SQL arguments from db.clj (#82175) 2026-09-09 13:34:39 -04:00
Andrei Chernykh
5b705231d7 Collection filters UX followup (#79863)
* Stabilize collection type-filter options via an items-metadata endpoint, default the type checkboxes to unchecked, and hide the filters for collections of 10 or fewer items

* Show every type in the filter popover, disabling the ones without matching items

* Use kebab-case params on the metadata endpoint and adapt toolbar tests to the visibility threshold

* Scope the items metadata to the models the list shows, name its count total_items, and align root permissions with the items list

* Assert the restricted root metadata count against the items list instead of a fixture-dependent number

* Code review improvements

* Cleaned up kebob usage

* Adapt the branch to master's show-exploration-documents param and re-record kondo budgets

* Cover the items-metadata endpoint's exploration-document scoping

---------

Co-authored-by: Nathan Voxland <nathan@metabase.com>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-09 10:20:19 -07:00
Alex Yarosh
10f53bdcec Fix documentation URL for collection permissions (#82136) 2026-09-09 11:45:02 -04:00
Paolo Rascunà
2e1a0c1a2c BOT-1895: Stream reasoning tokens for 7 more LLM providers (#81956)
Every provider behind Metabot now streams reasoning to the chain-of-thought UI,
with one predicate per adapter deciding the settings gate, the request directive,
stream forwarding and replay together.

* BOT-1895: Shared groundwork. Drop the pre-registry saved-model fallback from
  Azure and Google; make tool_calls outrank reasoning in delta classification,
  which previously lost a tool call's only id/name chunk; consolidate
  reasoning-part coalescing into one helper.

* BOT-2027: Bedrock. Request thinking per model via the shared builders. The
  openai-family gate answers false — probes across all four GPT models confirm
  Bedrock never emits reasoning summaries.

* BOT-2028: Azure. Gate derived from the admin-typed deployment name, matched
  case-insensitively, which also fixes a latent temperature 400 on cased Claude
  deployments. Negative paths verified live; the positive path rests on docs.

* BOT-2025: Z.AI. Forward reasoning_content and send the thinking directive
  explicitly — GLM was already thinking invisibly on every chat. Thinking-only
  models get reasoning_effort and a 2048 floor on forced tool calls, flagged on
  the supported-models row so the sets cannot diverge.

* BOT-2024: OpenRouter. Forward flat delta.reasoning and classify all 26 models
  by live probe; the gpt-5.5/5.6 family streams under the server default, where
  an explicit enable verifiably suppresses it. Forced tool calls floored on
  mandatory-reasoning models.

* BOT-2026: Google Gemini. One catalog drives context windows, directive and
  gate. Thought summaries on chat, thinkingLevel LOW on structured (no off
  switch), and a 2048 floor — probed, a real prompt at 512 spent the whole
  budget thinking and returned no tool call.

* BOT-2030: Mistral. Net-new cost: the default sends no thinking and only
  "high"/"none" are accepted. Flattens vector content chunks into the shared
  xf's events, and adds the opt-in reasoning replay hook Mistral's docs require.

* BOT-2046: Moonshot. kimi-k3 always thinks — explicit effort, mandatory in-turn
  replay, 2048 floor; kimi-k2.6 is optional and disabled under a forced tool
  choice, which it rejects while thinking.

Co-authored-by: Paolo Rascuna <1936871+prascuna@users.noreply.github.com>
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-09 17:42:56 +02:00
Chris Vandoodewaard
e49b98186b remove quarantine-engine paramater from test-driver action (#82107)
* remove quarantine-engine param from test-driver action

* remove uses of quarantine-engine param

* add timeout
2026-09-09 11:13:42 -04:00
Nicolò Pretto
f74d32c39a make sdk analytics use specific client names for data app and mcp apps (#82110) 2026-09-09 17:06:12 +02:00
Anderson
6431bc412b Fix chart color settings not applying in the query builder sidebar (#82140) 2026-09-09 11:45:11 -03:00
Tyler Plude
40a15bc485 [GIT-81733] Handle jar native filesystem paths (#81927)
* return a native filesystem path from get-jar-path

* extract code-location->path and add jimfs-backed regression test
2026-09-09 15:39:32 +01:00
Ben Grabow
b0c8103cdb Make batch timing stubs more reliable (#82073) 2026-09-09 09:30:16 -05:00
metamben
4b88b2ae79 Make sure we provide an order by clause when paging with SQL Server (#82039)
Closes QUE2-841
Closes #81988
2026-09-09 16:49:24 +03:00
Nathan Voxland
d3c7576ccb Validate local infile (#81967) 2026-09-09 08:41:57 -05:00
github-automation-metabase
7dbf078a40 Auto-update documentation for master (#82133)
Update generated docs (master)

Co-authored-by: github-actions <github-actions@github.com>
2026-09-09 09:32:21 -04:00
Jakub Chodorowicz
c0949b1d38 Gdgt 2465 popover (#81561) 2026-09-09 15:26:04 +02:00
Romeo Van Snick
ebdcd6c743 Take a metadata provider in the shared query helpers (#82150)
* Take a metadata provider in the shared query helpers

* Select the segment query instead of building it

* Take the provider for the segment definition's database

* Guard the segment query selector's memoisation

* Guard the segment query assertion against a vacuous pass
2026-09-09 22:05:52 +10:00
Andrei Simionescu
66038ba6d0 BOT-1427: link conversation user groups to filtered usage stats (#81869)
* BOT-1427: link conversation user groups to filtered usage stats

* Take the group id as an argument to the usage URL helper
2026-09-09 12:48:52 +01:00
Romeo Van Snick
97d871c78a Build the new metric page's queries from the store's builder (#82153)
* Build the new metric page's queries from the store's builder

* Select the new metric page's queries instead of building them
2026-09-09 20:57:50 +10:00
Romeo Van Snick
6bb98bce1d Build action-creator questions from the store's builders (#82154)
* Build action-creator questions from the store's builders

* Select the action-creator question instead of building it
2026-09-09 20:21:30 +10:00
Romeo Van Snick
c908146299 Build the browse-tables virtual question from the store's builder (#82155)
* Build the browse-tables virtual question from the store's builder

* Select the browse-tables url instead of building it
2026-09-09 20:20:56 +10:00
Romeo Van Snick
2d80c0e360 Build the model and source-card questions from the card the loader fetched (#82156) 2026-09-09 20:20:25 +10:00
Romeo Van Snick
7f589be657 Build draft questions from the store's builder (#82144)
* Build draft questions from the store's builder

* Read the store when normalizing a transform source
2026-09-09 20:18:36 +10:00
Kamil Mielnik
12e5f16918 GDGT-2796 Namespacing custom viz settings (#81181) 2026-09-09 16:38:51 +07:00
Egor Grushin
979b344073 Fix light theme border-highlight token (#82157)
Fix light theme border-highlight: brand[30] -> brand[60] (GDGT-2484)
2026-09-09 11:30:55 +02:00
Romeo Van Snick
4558ce654d Narrow the dashboard navigation cards, and build their questions from the store (#82148) 2026-09-09 19:11:28 +10:00
Romeo Van Snick
e584e95d48 Drop the question the click-behavior source filters never read (#82149) 2026-09-09 16:50:23 +10:00
Romeo Van Snick
6ed9837a03 Build parameter fields from param_fields, not the metadata store (#81935)
* Build parameter fields from param_fields, not the metadata store

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HNvsg9cPuNQ6BHiDwa1bif

* Answer a field's remapped value from the store, not a v1 method

The parameter pipeline now carries plain API fields, which have no
`hasRemappedValue` or `remappedValue`. Both callers read the store
through one selector instead.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HNvsg9cPuNQ6BHiDwa1bif

* Carry an FK's target in param_fields for anonymous requests

The usual :target hydration reads the target Field through permissions,
which a public or embedded request does not have, so a public parameter
widget could not label an FK's values.
Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HNvsg9cPuNQ6BHiDwa1bif

* Give the number filter story a field with no values to list

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HNvsg9cPuNQ6BHiDwa1bif

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-09 15:17:40 +10:00
Romeo Van Snick
e4cc4a61ff Reduce the frontend to one memoize helper, and stop top-level caches leaking (#81866)
* Add a jest project for heap retention specs

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012b67ubbXJVMuQrpuEksbeh

* Scope the parsed x value cache to one getXValues pass

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012b67ubbXJVMuQrpuEksbeh

* Assert heap retention on the settled pass, not the first touch

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012b67ubbXJVMuQrpuEksbeh

* Key the log timestamp cache on the log object

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012b67ubbXJVMuQrpuEksbeh

* Key the schema viewer flow graph on the response object

The memo key serialized every table and field of the schema, so each distinct
schema held a megabyte-scale string forever. RTK Query returns a stable
reference per cache entry, so a WeakMap keeps the identity that useGraphSync
depends on without retaining the schema.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012b67ubbXJVMuQrpuEksbeh

* Key pie.rows on the dataset instead of a JSON copy of it

The memo key serialized every row and column, so each dataset the user viewed
held roughly its own size in cache key for the life of the tab. A WeakMap on
the dataset with a short settings subkey keeps the same hit rate.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012b67ubbXJVMuQrpuEksbeh

* Ban new uses of underscore's memoize

The 17 remaining call sites are allowlisted. The list may only shrink.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012b67ubbXJVMuQrpuEksbeh

* Narrow the memoize rule to module scope

A cache built inside a function, a component render, a class field or a
constructor is released with whatever owns it. Only a module scope cache lives
for the life of the tab, so the rule now flags just those.

This drops the allowlist from 17 files to 5, and each remaining entry carries
the reason its set of keys stays small.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012b67ubbXJVMuQrpuEksbeh

* Remove the memoize allowlist

Three of the five module scope caches are gone:

- getScrollBarSize takes no arguments, so it is a lazy value, not a cache.
- getScheduleExplanation returns a string that no caller compares by identity.
- cronToBuilderValue moves to the one caller that needs a stable identity.
  Schedule takes its value as a useMemo dependency, so StrategyForm now holds
  that memo itself. A user can write any number of cron strings, so a module
  cache for them was unbounded.

The remaining two carry an eslint-disable with the reason their set of keys
stays small.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012b67ubbXJVMuQrpuEksbeh

* Follow renderer_utils into the viz-core module

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012b67ubbXJVMuQrpuEksbeh

* Cover metabase/utils/memoize in the module scope rule

That memoize roots its WeakMap on the function it wraps, so it only releases
once that function does. At module scope the function never does, and the
nested Maps hold every argument ever passed. No call site does this today, but
the rule could not have caught one.

The rule now covers both sources, so it drops "underscore" from its name.
memoizeClass stays allowed: it keys on the instance.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* Drop re-reselect from the dashboard selectors

createCachedSelector keyed getQuestionByCard and
getDashcardParameterMappingOptions on the card id, a primitive, in a
FlatObjectCache. That cache is a plain object with no eviction, so a session
kept one Question per card id it ever saw, and each Question pins the whole
Metadata snapshot it was built with.

reselect v5 defaults to weakMapMemoize, which keys on the card and the metadata
objects themselves. Entries are released when their card leaves the store or
the metadata is replaced, and identity still holds for every card in the
working set, which is what connect and useSelector compare on.

Measured over 300 cards, with the states dropped: 6.2 MB retained before,
0.0 MB after. Per entry, 21462 B before and 51 B after.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* Drop re-reselect from the lockfile

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* Back metabase/utils/memoize with reselect's weakMapMemoize

The hand-rolled implementation had two problems. It allocated two arrays on
every call, including cache hits: 225 ms against 20 ms for weakMapMemoize over
two million hits. And its WeakMap was keyed on the wrapped function rather than
the wrapper, so a cache built around a module-level helper outlived the wrapper
that owned it. A plain Map would have been safer.

weakMapMemoize matches on the same terms, identity for objects and value for
primitives, so no call site changes. It also weak-keys object arguments, which
the old one held strongly.

definition-cache passed weakMapMemoize as the memoize and argsMemoize options.
reselect v5 already defaults to both, so those are dropped.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* Route all memoization through metabase/utils/memoize

underscore's memoize is gone from the app. Its 16 call sites now use the house
helper, which is reselect's weakMapMemoize. Three of them were in metabase-lib,
which cannot import metabase/utils, and all three took no arguments, so they
became plain lazy fields instead.

Two rules keep it that way:

- no-direct-memoize-import bans memoize from underscore and weakMapMemoize or
  lruMemoize from reselect, in any scope. Only metabase/utils/memoize may reach
  for an implementation.
- no-module-level-memoize keeps its job, now that the house helper is the only
  one left to police.

measureTextWidthSafely took a style object that was rebuilt on every render, so
identity keying would never have hit. Its third argument is now the font family
string, which is the only field any caller ever set.

useMemoizedCallback returns the callable shape rather than casting to T, since
the memoized function also carries clearCache and resultsCount.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* Build memoizeClass on the house memoize

It kept a module-level WeakMap and walked a nested Map trie keyed on the
instance, the method, the argument count and then each argument, assembling
that path into an array on every call.

Keying weakMapMemoize on the instance and then the arguments gives the same
per-instance caching. One cache per decorated method replaces the shared trie,
so the method no longer needs to be part of the key, and neither does the
argument count. The file is down to 61 lines from 128.

A leak spec covers the property this rests on: an instance's results are
released with the instance.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* Measure memoizeClass retention under load

2,000 instances per pass, 20 calls each, across a method with no arguments and
one taking a primitive and an object. Nothing is retained once the instances
are dropped.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* Delete memoizeClass

It decorated a prototype method by rewriting the property descriptor, and put
the memoization 600 lines away from the method it applied to. Its one consumer
memoized a method whose body uses no `this`, so the same caching comes from
assigning a memoized arrow to a class field. The field is created per instance,
so the cache is released with the instance, and the memoization is now visible
at the definition.

metabase/utils/memoize is 14 lines, from 128.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* Run the heap specs from their own jest config

They were a project inside jest.config.js, and a bare `jest` runs every
project, which is what CI does. So the sharded unit run picked them up, without
--expose-gc, and they failed as designed.

They now live in jest.memory.conf.js, the way the timezone specs live in their
own config. The shared base moves to jest.base.conf.js so neither file has to
duplicate it.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* Reduce the heap specs to one collection assertion each

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012b67ubbXJVMuQrpuEksbeh

* Follow the store mocks into test support

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_012b67ubbXJVMuQrpuEksbeh

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-09 15:02:13 +10:00
Alexander Polyankin
c1805286bb Convert db.clj public functions to mu/defn with schemas (#82139) 2026-09-09 04:47:13 +00:00
Chris Truter
22b2577799 Require credentials when changing LLM provider base URLs (#81450)
A settings manager could change a connection's base URL without entering its
masked secret again. The update merged the stored secret back in, and
credential verification sent it to the new host before anything was persisted.
A network policy cannot tell a legitimate provider from a public host the
caller controls.

Changing a connection's effective base URL now requires freshly submitted
credentials for every sensitive field that would otherwise carry a secret to
the new destination. Environment-owned credentials must be repointed through
deployment configuration. Trusted provisioning such as config.yml is
unchanged.

Generic writes to the llm-providers setting run the same field validators, so
PUT /api/setting cannot bypass the connection API's checks.
2026-09-09 06:33:41 +02:00
Romeo Van Snick
2a35f6390b Let the measure and segment query hooks reach the store themselves (#82152)
Claude-Session: https://claude.ai/code/session_01HNvsg9cPuNQ6BHiDwa1bif

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-09 13:59:17 +10:00
Chris Truter
f508214657 Enforce a network policy on LLM provider base URLs (#81301)
* Enforce a network policy on LLM provider base URLs

A settings manager could point any provider's base URL at an internal
host; the model listing behind the admin Connect button then fetched
GET /v1/models from it with bare clj-http, and a 4xx body preview came
back in the error. Semi-blind SSRF.

New llm-allowed-networks setting, same shape as warehouse-allowed-networks:
external-only on Cloud, allow-all self-hosted (vLLM/Ollama on localhost
or a private network is the normal case there). Admin-only, so the
settings-manager class can't loosen it.

Every base-url registry field validates against it on write, so the
API rejects a forbidden URL before verify-credentials! makes the
request. core/request and llm.anthropic/chat-completion check again at
request time and resolve DNS through the policy resolver, which closes
the rebinding gap. The AI proxy URL is operator config and is exempt.

e2e pins MB_LLM_ALLOWED_NETWORKS=allow-all next to the warehouse pin,
since the mock LLM server is on localhost.

* Cover the embedding and Google token sinks too

Semantic search posts embeddings to llm-openai-api-base-url and to the
settings-manager-writable ee-embedding-service-base-url with bare
clj-http, so the same writer class reached the same kind of sink. Those
now run the llm-allowed-networks check and DNS resolver; the operator's
ai-service-base-url is exempt, and ee-embedding-service-base-url is
validated on write.

A Google service account key carries its own token_uri, and the
credential library posts to it to mint an access token before any
request we guard. Keys are now refused unless token_uri is one of
Google's OAuth hosts.

* Use var links in LLM policy docstrings

* Keep SSRF rejections out of the embedder breaker

* Normalize connection-time LLM policy errors

* Link LLM timeout settings in request docs

* Fix reflection warnings in LLM URL validation

* Use explicit policies for managed AI endpoints

* Address final Copilot review feedback

* Reject non-global special-purpose addresses

* Align network policy terminology

* Make external-only the LLM network policy everywhere

llm-allowed-networks is now environment-only (:internal, no setter)
and defaults to external-only on every instance. A settings manager is
who it defends against, and on Cloud a customer admin loosening it
would be reaching for our own infrastructure, so nobody sets it through
the API. Self-hosted operators with a vLLM server on a private network
opt in with MB_LLM_ALLOWED_NETWORKS; a value that is not one of the
three policies fails closed with one warning.

The rejection message says what to do: self-hosted, it names the
setting and which value fits; on Cloud, that private networks are out
of reach. The vLLM field's placeholder and help text no longer
advertise a private host as the default setup.

The managed endpoints' :allow-private is now a floor rather than a
replacement, so an explicit allow-all keeps an AI service on localhost
reachable. An embedding service URL supplied by the environment gets
the same floor, since the setter cannot vet it.

* Enforce the LLM network policy at connection time only

The request-time check resolved the host with a blocking lookup that
the connection's DNS resolver then repeated, and in the embedding path
it ran ahead of the breaker's fast-fail. Requests now run only the
I/O-free syntax check up front; the resolver decides on the addresses
the connection actually opens, and its refusal maps to the same 400
the set-time check gives. The set-time check still resolves, so a bad
URL is refused when it is entered.

One helper, llm-request-opts, replaces the three hand-copied
sequences; the refusal is thrown from one constructor. It carries
:status 400 beside :status-code because the semantic-search dead-letter
queue files errors by :status and was retrying a refused endpoint on
the fast schedule.

A base URL with a username or password is refused outright, and the
refusal names only the host, since the message reaches Metabot chat
users and the API's 400 body. A connection-time refusal is logged; it
is the only trace a host that rebinds leaves.

* Read llm-allowed-networks from the environment alone

get-value-of-type falls back to the application database, so a value
stored there before the setter went away kept working. The getter now
reads only the environment variable, and the setting carries a :doc
string so the generated environment-variable docs keep it now that it
has no setter. On Cloud the default applies; the operator's environment
is still honored, which the e2e runner's pin relies on.

* Disable redirects for LLM requests

* Normalize embedding service base URLs

* Normalize configured embedding URLs on read

* Clarify LLM network policy documentation

* Revert "Clarify LLM network policy documentation"

This reverts commit 8f2cff7c4963efba6756c117927ca56492cd49c5.

* Polish new LLM security comments

* Clarify embedding API key fallback

* Treat unallocated IPv6 space as non-global

* Grant private-network policy floors to environment-supplied URLs only

* Refuse IPv6 space IANA has not allocated

2000::/3 is the global-unicast space, but everything in it from 2d00:: up
is reserved: no ISP routes it, so a name resolving there is either a
mistake or an internal network squatting on it. `3000::1` passed as public
before.

* Pin Google's token endpoints by whole URI

The transport posts to whatever `token_uri` says, so checking only the
scheme and host let through another path, port, or query string on
accounts.google.com.

* Validate connections written as the llm-providers setting

The connection endpoints check a base URL against the network policy, but
the list they write is a setting in its own right: PUT /api/setting or a
config.yml entry saved a loopback URL straight past them. Run the field
validators in the setter too, on the connections a write changes.

* Hold the token-cache invalidation to the LLM network policy

/api/premium-features/token/refresh POSTs to ai-service-base-url with the
premium token in the URL path. That setting is admin-writable, so the
request needs the same syntax check, redirect ban and DNS policy as any
other LLM request; only an environment-supplied URL earns the private
floor.

* Check the target host when a JVM proxy is in the way

clj-http's route planner honours -Dhttps.proxyHost, so the connection is
opened to the proxy and the :dns-resolver is handed the proxy's hostname:
the target is resolved by the proxy, out of reach, and a private egress
proxy is itself refused under external-only. Treat an operator-configured
proxy as the trusted boundary it is and check the target host up front
instead.

* Judge a NAT64 address by the IPv4 it reaches

64:ff9b::/96 is globally reachable, but its low 32 bits are the IPv4 a
gateway translates to, so 64:ff9b::7f00:1 passed external-only and reached
127.0.0.1. RFC 6052 forbids the prefix carrying a non-global IPv4; nothing
on this side of the gateway enforces that.

* Validate only the connection fields a write changes

Comparing whole connections meant rotating an API key re-ran the base URL
check, so a private URL stored before the check existed made its own
connection unwritable.

* Name a network policy that would change the outcome

A refusal under a deployment endpoint's allow-private floor advised
setting MB_LLM_ALLOWED_NETWORKS=allow-private, which was already in force.
The resolver records the policy it refused under; use that for the message
and the log line.

* Refuse an unresolvable host behind a JVM proxy

Everywhere else a host that will not resolve is allowed, because the
connection then fails on its own. Behind a proxy there is no connection to
fail: the proxy resolves the target, so a split-horizon or cluster-internal
name went out with nothing checked at all.

* Keep proxy-only DNS working

* Document and test the LLM proxy enforcement boundary

* Match JVM proxy detection to Apache routing and fix tile fixture
2026-09-09 03:56:22 +00:00
Romeo Van Snick
a24ac528b3 Build reference questions from a provider and the field itself (#82142)
Claude-Session: https://claude.ai/code/session_01HNvsg9cPuNQ6BHiDwa1bif

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-09 12:51:21 +10:00
Alexander Polyankin
e0c40554da Accept a plaintext numeric example-dashboard-id in BackfillExampleDashboardIdValueWithAad (#82143) 2026-09-08 22:03:55 -04:00
Romeo Van Snick
c9c2552964 Build SDK and document questions from the store's builder (#81867)
* Build query builder questions from the store's builder

* Build document questions from the store's builder

* Build SDK and document questions from the store's builder
2026-09-09 11:46:12 +10:00
Romeo Van Snick
b57475ab38 Build query builder questions from the store's builder (#81861)
* Build query builder questions from the store's builder

* Build document questions from the store's builder
2026-09-09 11:42:14 +10:00
Romeo Van Snick
758aade121 Take metadata from the store's own doors, not the raw Metadata object (#81847)
* Build queries from a provider, not the raw Metadata object

* Build questions from cards through the metadata store

* Type the dashcard menu against the question dashcards its callers pass

* Name the guard the callers actually use

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HNvsg9cPuNQ6BHiDwa1bif

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-09 10:10:30 +10:00
Romeo Van Snick
5db23f4182 Move the test-side store mocks into test support (#81499)
* Move the test-side store mocks into test support

* Drop the moved store mocks from the side-effect registry

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HNvsg9cPuNQ6BHiDwa1bif

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-09 09:06:24 +10:00
Andrei Simionescu
0efc4c2161 BOT-1575: Show the illustrations toggle whenever illustrations are off (#81871)
The illustrations switch only appeared next to a custom icon, so turning illustrations off
and then removing the icon left no way to switch them back on. It now appears whenever
illustrations are off as well.
2026-09-08 23:40:41 +01:00
Andrei Simionescu
f4b04b6966 BOT-1573: Slackbot posts specific copy for known error codes (#81200)
Clackbot answered every failure with "Something went wrong", so a user denied by AI
permissions or an admin with a misconfigured provider had nothing to act on. Both the
streamed error part and the thrown-exception path now look the failure up by error
code and reply with copy that names the problem, and usage-limit errors pass their
server-authored message through. Anything unrecognised keeps the generic line, so raw
provider errors stay out of shared Slack channels.
2026-09-08 22:14:02 +00:00
Romeo Van Snick
83ed9b6c3d Serve the metabase-lib provider from the metadata store (#81664)
* Serve the metabase-lib provider from the metadata store

* Serve metric metadata providers from the store too

* Serve providers for metrics and for per-item database lookups

* Take a provider lookup in the transforms query helpers

* Resolve SDK query sources from the RTK cache, not the mirror

* Delete the unused isSourceEmpty helper and the dead tableId prop chain

* Canonicalise getMetadata's options so both call shapes share one Metadata

* Build v1 Questions through the metadata store (#81666)
2026-09-09 08:01:09 +10:00
Andrei Chernykh
0cd9134160 Keep closed group mapping dropdowns unmounted (#82124) 2026-09-08 14:56:21 -07:00
Sloan Sparger
d273dc56b6 [Metabot] Context window improvements (#81133) 2026-09-08 21:49:40 +00:00
Sloan Sparger
2d6db97c9d [Metabot] Frontend convo message shape refactor (#80967) 2026-09-08 16:10:26 -05:00
Ben Grabow
3fb5cbcb74 Use explicit hierarchy for action keywords (#79464)
* Use explicit hierarchy for action keywords

The :table.row/* -> :table.row/common and :data-grid.row/* -> :data-grid.row/common
relationships lived in Clojure's global hierarchy, sharing one mutable namespace with model
keywords, hook traits and every other subsystem. Move them into metabase.actions.hierarchy,
mirroring metabase.events.hierarchy: a defonce var holding a hierarchy map, mutated through
derive!.

Four multimethods consume those parents -- action-arg-map-schema, normalize-action-arg-map,
validate-inputs! and default-mapping -- and now dispatch on the new hierarchy. Driver-level
action methods are untouched: they dispatch on [driver action] through the driver hierarchy
and only ever name leaf action keywords.

The enterprise action_v2 module derives through metabase.actions.core, which re-exports
derive!.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* State the real reason driver action dispatch is unaffected

The hierarchy docstring said driver-level action methods are safe because they only ever name leaf action
keywords. That describes an incidental convention -- `[:postgres :model.row/create]` happens to be the only
such method -- and implies a fragile dependency that does not exist.

`driver/hierarchy` is its own `(make-hierarchy)`, and `isa?` against an explicit hierarchy never consults the
global one for keyword parents, so the derives this namespace moves had no effect on `prepare-query*` before
the move either. Say that instead, and note it at `prepare-query*` too, where someone adding a driver method
will actually be reading.

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-authored-by: Chris Truter <chris@metabase.com>
2026-09-08 21:06:29 +00:00
Alex Yarosh
f52a94984a docs: typos (#82079)
* typos

* Update docs/developers-guide/api-changelog.md

Co-authored-by: Jeff Bruemmer <jeff.bruemmer@gmail.com>

* fine

* Apply suggestions from code review

Co-authored-by: Jeff Bruemmer <jeff.bruemmer@gmail.com>

---------

Co-authored-by: Jeff Bruemmer <jeff.bruemmer@gmail.com>
2026-09-08 20:38:33 +00:00
Jeff Bruemmer
8170a2ecdd docs - nav updates (#82116)
nav updates
2026-09-08 20:23:55 +00:00
Ben Grabow
ca2c341522 Use explicit hierarchy for auth identity providers (#79463)
* Use explicit hierarchy for auth providers

Provider relationships (:provider/saml -> ::provider/provider, etc.) lived in Clojure's
global hierarchy, sharing one mutable namespace with model keywords, hook traits and every
other subsystem. Move them into metabase.auth-identity.hierarchy, mirroring
metabase.events.hierarchy: a defonce var holding a hierarchy map, mutated through derive!
and underive!, read through isa? and descendants.

The three provider multimethods (validate, authenticate, login!) now dispatch on that
hierarchy via methodical's :hierarchy option.

Callers outside the module go through metabase.auth-identity.core, which re-exports the four
operations; namespaces inside the module use metabase.auth-identity.hierarchy directly, since
core requires them.

derive! is whitelisted as :parallel/safe because each test registers its own distinct
:provider/test-* keyword, so the additions never overlap. The plain `derive` calls it replaces
were equally global but escaped the linter by not ending in `!`.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* Register test providers at namespace level, not inside parallel tests

Each of these eight ^:parallel tests registered its provider by calling derive! and
methodical/defmethod in the test body. Both mutate process-wide state, so the tests were never
actually parallel-safe -- only derive! was visible to the linter, because defmethod does not
end in `!`.

Hoist both registrations above their deftest, alongside the test providers already registered
at the top of the namespace. The deftests are now pure assertions over providers that exist by
the time the namespace has loaded, which is what ^:parallel claims. No linter exemption for
metabase.auth-identity.core/derive! is needed, so .clj-kondo/ratchets.edn is untouched.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-authored-by: Chris Truter <chris@metabase.com>
2026-09-08 22:04:07 +02:00
Ben Grabow
3390d69763 Use explicit hierarchy for domain entity types (#79459)
Domain entity types derived from :DomainEntity/* in Clojure's global hierarchy, sharing one
mutable namespace with model keywords, hook traits and every other subsystem. Specs are loaded
from YAML files, so adding a spec file was writing into that shared space.

Move them into metabase.xrays.domain-entities.hierarchy, mirroring metabase.events.hierarchy:
a defonce var holding a hierarchy map, mutated through derive!. A leaf namespace rather than
an in-file var because both specs (which registers types and validates them) and core (which
ranks candidate entities by ancestor count) read it.

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-08 19:36:22 +00:00
Ben Grabow
adf3bd7254 Use explicit hierarchy for user-key-value namespaces (#79460)
Key-value namespaces registered by defnamespace derived from ::registered-namespace in
Clojure's global hierarchy, sharing one mutable namespace with model keywords, hook traits and
every other subsystem. Namespaces are loaded from EDN files on disk, so an operator adding a
file was writing into that shared space.

Move them into a hierarchy var private to this namespace, mutated through derive! -- the same
shape as metabase.events.hierarchy, kept in-file because defnamespace is the only writer and
known-namespaces the only reader.

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-08 19:31:31 +00:00
Chris Vandoodewaard
2357c1b843 refactor pr env cleanup into single workflow (#81817)
* refactor pr env cleanup into single workflow

* add timeout

* rename to match naming scheme
2026-09-08 19:21:42 +00:00
Ben Grabow
e85fa9c446 Fix BigQuery tests (#82106)
* Avoid wildcard scan against all similar datasets on the warehouse

* Update bigquery page fetch tests to match new adaptive page sizing API
2026-09-08 14:08:28 -05:00
Nathan Voxland
250868257e Improve LLM token usage for add_reseach_group (#79556) 2026-09-08 14:08:26 -05:00
Jakub Chodorowicz
27752c76e0 Gdgt 3198 allow setting metabase instance url when starting embedding (#82063)
allow setting metabase instance url for embedding storybook
2026-09-08 20:38:18 +02:00
Alexander Polyankin
15106f17fd Add kondo rule keeping Toucan 2 query calls in module db namespaces (#82099) 2026-09-08 14:07:41 -04:00
Alexander Polyankin
4b2cfdc623 Add MB_DISABLE_LEGACY_STARTUP_ENCRYPTION to refuse startup instead of encrypting legacy plaintext (#82097) 2026-09-08 13:38:39 -04:00
Will Fry
3439faff23 GDGT-3094: remove attachment limit tooltip (#82055) 2026-09-08 17:49:35 +01:00
Chris Truter
18f216de52 Ensure mage -test runs every test namespace (#82051)
* Fail the mage suite when a test namespace is not required

`mage -test` runs `run-all-tests`, which only sees namespaces that are already
loaded, and loading happens solely through this namespace's `:require`. A test
file missing from it never runs, and nothing says so.

`mage.quick-test-runner-test` and `mage.start-db-test` were missing that way.
They are required by `mage/test/mage/runtests.clj`, but CI runs `mage -test`,
which does not read that file, so their four tests had not been running.

* Drop the dead mage test runner and a test that cannot fail

Nothing referenced mage/test/mage/runtests.clj. It required three namespaces
directly, which made mage.quick-test-runner-test and mage.start-db-test look
wired up while `mage -test` never loaded either.

mage.start-db-test asserted a string literal, so it passed unconditionally.
Wiring it in would have added a green test covering nothing. start-db still
deserves real tests; this makes their absence visible.
2026-09-08 18:37:44 +02:00
Anderson
e354134858 Show table publisher and publish date in the Library (#81076)
* Show table publishing info in Library

* address review comments

* Refine publishing info response

* Clarify publishing audit lookup

* Fix publishing info database queries
2026-09-08 12:56:46 -03:00
Ben Grabow
34da51c654 Fix OIDC test isolation (#81987)
Use the right localhost-site-url test helper, and make sure the web server is initialized
2026-09-08 10:47:40 -05:00
github-automation-metabase
55f3c0f268 Add docs/util/data/nav.yml for master (#82078)
Add docs/util/data/nav.yml (seeded from docs.metabase.github.io)

Co-authored-by: github-actions <github-actions@github.com>
2026-09-08 11:34:19 -04:00
Sébastien
4cb99413ed Deflake the standalone cardEmbed supporting text test (#81772) 2026-09-08 15:58:27 +02:00
Ben Grabow
beb22cd1b5 Add missing fixtures init (#82007) 2026-09-08 08:44:03 -05:00
Voytek Pituła
eb7bcaa06f Add krever to team.json and github-slack-map.json (#82058)
Adds @krever to the Metabot team in .github/team.json and maps the
GitHub username to Slack ID U0BUSKQRN80 in release/github-slack-map.json.
2026-09-08 15:34:58 +02:00
github-automation-metabase
7e11715582 Update translations 2026-09-08 (#82056)
* Update translation sources 2026-09-08

* Update translations

---------

Co-authored-by: github-actions <github-actions@github.com>
2026-09-08 13:20:14 +00:00
Stas Gavrylov
c7a5060ca8 GDGT-2462: Update Switch component (#81709)
* GDGT-2462: Update Switch component

* GDGT-2462: Add Switch Loki references

* Update Loki Snapshots

* Address PR findings

---------

Co-authored-by: Metabase Automation <github-automation@metabase.com>
2026-09-08 15:42:53 +03:00
Kevin Kelleher
b7500371ca Remove duplicate in Gauge color picker (#81920)
fix duplicate in gauge color picker
2026-09-08 12:41:00 +00:00
lbrdnk
bf0186730c Add goldens triggers (#81873)
* Enable golden scopes

* Add label triggers

* Temporarily remove label input

* drop the input completely

* Re-add label
2026-09-08 14:40:41 +02:00
Timofey Kachalov
6ca683c042 Re-enable Shoppy sample app e2e (#82061) 2026-09-08 16:27:53 +04:00
Sébastien
c16a8abfa6 Fix EditableDashboard collapsing when entering edit mode (#82019)
* Fix EditableDashboard collapsing when entering edit mode without a sized parent

* Also fix EditableDashboard collapsing while sharing

* Revert "Also fix EditableDashboard collapsing while sharing"

This reverts commit be2f86c738.
2026-09-08 11:28:56 +02:00
Oleksandr Yakushev
074e967be7 [liquibase] Remove obsolete proxy package hack (#81480) 2026-09-08 11:51:55 +03:00
Bartosz Rybacki
47bc44f775 GDGT-2028 Fix wrong column headers in alerts with a remapped foreign key (#81896)
GDGT-2028: Fix wrong column headers in alerts with a remapped foreign key

The header titles and the header row were built separately and zipped by
index. Only the header row dropped the remap target column, so every title
after it shifted by one. Both now derive from `visible-columns`.
2026-09-08 10:31:41 +02:00
Andrei Simionescu
06d46ec0c2 BOT-2113: Copy metabot_permissions on every edition
An H2 dump made by an OSS build kept the metabot_permissions rows that migration 061 seeds into the fresh target instead of copying the source's own rows, because the table only appears in cmd.copy/entities when the Enterprise backend is on the classpath. The seed references the four magic groups at ids 1 to 4, which on the source are often different groups or no groups at all, so restoring that dump into Cloud either failed on a foreign key or handed Metabot permissions to whoever happened to sit at ids 3 and 4.

The table is now copied on every edition. The load side also skips rows whose group is missing from the dump, so the dumps customers have already sent restore once Cloud picks this up, and magic groups left without rows get the 061 seed re-run by magic_group_type so a restored instance matches a fresh one. Grants that landed on a real custom group cannot be told apart from a deliberate grant and stay a data fix, tracked in CLO-5999.
2026-09-08 08:30:46 +00:00
Romeo Van Snick
28a72bb30c Answer field remapping from the field, not the metadata store (#81932)
* Answer field remapping from the field, not the metadata store

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HNvsg9cPuNQ6BHiDwa1bif

* Say what a remappable field has to carry, and simplify the format type

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01HNvsg9cPuNQ6BHiDwa1bif

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-09-08 16:19:53 +10:00
Chris Truter
b57dc3f98e Prevent mage commands hanging on orphaned output pipes (#81699)
* Start subprocesses with ProcessBuilder

Runtime.exec's three-arg form has been deprecated since JDK 18, and it forced the command and environment
through String arrays with array type hints to match. ProcessBuilder takes both as collections, so the
call site is one line and the array juggling is gone. `:env` still replaces the parent environment rather
than adding to it, which is what the docstring promises: that is `.clear` then `.putAll`, not a bare
`.putAll`. read-lines now hints the BufferedReader the namespace already imports.

* Spend one timeout budget across a command's three waits

sh* waited for the exit code, then stdout, then stderr, giving each a fresh timeout-ms. A command that
dribbled output could take three times its budget, and the exception still claimed the single figure, so
"Timed out after 200 ms." could be thrown 600 ms in. The three waits now measure against one deadline
taken when the process starts.

* Measure the backend health-check wait with nanoTime

check-backend-health! polls for five minutes against a wall-clock start, so a clock adjustment mid-poll
could cut the wait short or stretch it. The interval literal is now written as a duration too.

* Kill the command however the wait ends, not only on timeout

Three fixes around sh*'s failure handling.

The catch was for ExceptionInfo carrying :timed-out?, so any other way out left the command running: a
reader future failing on the pipe, or the calling thread being interrupted. It now catches Throwable and
asks whether the process is still alive, which is the question that actually decides whether to kill.

:or does not fire on an explicit nil, so a caller computing :timeout-ms from an env var and handing us nil
got a NullPointerException building the deadline rather than the default.

The test's 200 ms budget left the shell to fork twice and write both pids with no margin. On a loaded
runner the file could come up a line short, failing the descendant assertion for the wrong reason. A
second is still far below the bound the test asserts.

* Stop waiting on a command that orphaned our output pipe

sh* could sit for as long as an orphan lived, whatever its timeout said: 62 s against a 500 ms budget in
the case that prompted this. with-open closed the BufferedReader, and that close takes the same lock a
blocked readLine holds, so it waited for EOF -- which a process the command left holding our stdout never
delivers. Closing the pipe underneath ends the read at once, so the streams are now closed directly.

Closing the pipe means a cut-off read reports EOF rather than an error, which would make truncation
invisible. Two things guard against that. The readers get a floor of their own once the exit code is in,
so a command that finished a moment inside its budget is not robbed of the output it had already written.
And if the pipe is still held when that floor runs out, sh* says so and throws, because half a command's
output returned as though it were all of it is worse than a failure.

The orphan itself is still running afterwards. Reaching it needs process-group handling, which is a
larger change and no mage command leaks one today.

* Rewrite the comments and docstrings in mage.shell

The docstrings now state the caller's contract and nothing else: what sh* returns, what it throws, what
the timeout actually covers now that one budget spans the whole command. Rationale about how the body
works moved down to the lines it explains -- why the descendants are listed before anything is signalled,
why the deadline is read off a monotonic clock, why the pipes are closed rather than the readers.

* Tighten the comments once more, and drop the duration glosses

A second pass over the comment wording, and a correction: a DST change does not move the epoch
milliseconds `currentTimeMillis` reports, so it was never one of the things nanoTime protects the deadline
from. NTP corrections and manual clock changes are.

The `; 5 seconds` style glosses are gone throughout. Writing the constant as `(* 5 1000)` already says
which unit it is in, and the name carries the rest.

* Serialize mage shell output and fix test namespace loading

`println` writes the text and its newline separately, so the stdout and
stderr readers could land halves of two lines on one line of the terminal.
Lock on the destination, which also keeps two commands streaming at once
from splitting each other.

`mage -test` runs `run-all-tests`, which only sees namespaces that are
already loaded, and nothing required mage.bot.pr-env-test or
mage.bot.repl-eval-test, so eight tests never ran. The `(comment ...)`
block meant to hold these requires open only referenced an alias that
existed for its own benefit; kondo does not flag alias-less requires, so
it was protecting nothing.
2026-09-08 01:03:13 +02:00
github-automation-metabase
ada3520e32 Auto-update documentation for master (#81981)
Update generated docs (master)

Co-authored-by: github-actions <github-actions@github.com>
2026-09-07 17:29:15 -04:00
Timofey Kachalov
33ebc8e671 Gate data apps remote sync logic under a token feature (#81946) 2026-09-07 20:04:42 +00:00
Andrei Simionescu
f1ea6b4ad5 BOT-1918: use the AWS default credentials chain for keyless Bedrock (#80512)
A Bedrock connection with no access key pair now signs with whatever the AWS
SDK default credentials chain resolves (environment, IRSA, EKS Pod Identity,
ECS task role, EC2 instance profile), and the SDK refreshes those on its own,
so a pod that already has a role needs no long-lived keys. Explicit keys still
override the chain, and half a pair or a lone session token is rejected.

On Metabase Cloud the chain would resolve our own identity rather than the
customer's, so a keyless connection is rejected there, and a token status the
license service could not confirm counts as hosted.
2026-09-07 18:24:18 +00:00
Will Fry
0de35e5dd3 Add Will Fry to team and slack map json files (#82028)
* Add Will Fry to team and slack map json files

* use exact casing for gh handle
2026-09-07 16:48:18 +00:00
Andrei Simionescu
0ed863ba11 BOT-1590: Test that the Conversations tab stays current on a conversation page (#81870) 2026-09-07 17:25:47 +01:00
Kamil Mielnik
da793ea976 GDGT-3189 Remove CustomVisualization['id'] and use CustomVisualization['getName'] (#82033) 2026-09-07 14:54:04 +00:00
Sébastien
7e6c62a105 Use consistent colors for the MCP errors-by-type pie chart (#81943)
* Avoid success-green slices in the MCP errors-by-type pie chart

* Use createMockStructuredDatasetQuery instead of a type cast
2026-09-07 16:51:27 +02:00
Paolo Rascunà
3ba6cb1479 BOT-2111: Stop the Gemini stream when the client cancels (#81959)
The streamGenerateContent xf walked each event's parts with a plain
`reduce`, which strips the `reduced` wrapper a cancelled consumer
returns. The stop never reached the outer reduction, so every event
that followed was still translated and pushed downstream — Google's
response was read to the end, and billed, after the client had gone.
The other adapters propagate the stop; only this one dropped it.

Use u/reduce-preserving-reduced so the early stop survives, and pin it
with a test that cancels on the first text delta: before the fix the
consumer kept receiving text from later events.

Co-authored-by: Paolo Rascuna <1936871+prascuna@users.noreply.github.com>
Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-07 14:23:37 +00:00
Stas Gavrylov
3c07580bcc GDGT-3188 Remove unintended elevation styles (#81958)
* GDGT-3188 Remove unintended elevation styles

* GDGT-3188 Fix remaining elevation regressions

* GDGT-3188 Update elevation guard expectations
2026-09-07 17:22:00 +03:00
Nicola Mometto
38fcd8e057 Scope tenant endpoints and pulse recipients by tenancy (#81765)
* Only serve tenant attributes and member_count to superusers

* Scope pulse recipients and the Slack directory by tenancy

* Update cross-tenant recipient test for non-superuser scoping
2026-09-07 15:15:20 +01:00
Nicola Mometto
c573e659f6 Read-check the transform in GET /api/transform/run/:run-id (#81761) 2026-09-07 14:45:17 +01:00
YB
f6ea5b6092 Fix ENOBUFS in the Create test plan CI step (#82025)
raise git ls-files maxbuffer so the test planner stops failing with enobufs
2026-09-07 21:33:49 +08:00
Sébastien
69256a104a Apply embedding theme colors to hand-picked chart series (#81014)
* fix: apply embedding theme colors to hand-picked chart series

* Clarify and dedupe chart color-picker naming

* Apply the instance's chart colors when rendering static visualizations
2026-09-07 15:00:00 +02:00
Kamil Mielnik
ff7b417ce6 GDGT-3184 Reject ':' in custom viz plugin identifiers (#81886) 2026-09-07 12:41:11 +00:00
Stas Gavrylov
0e7e969925 GDGT-2467: Curate Paper radius tokens (#81700)
* GDGT-2467: Restrict Paper padding/radius to curated token options

* Update Loki Snapshots

* GDGT-2467: Update entity picker width e2e expectation for Paper padding

* GDGT-2467: Keep Paper default padding at 0, add no-padding option to stories

* GDGT-2467: Keep all padding options in Paper stories, only curate radius

* Update Loki Snapshots

* GDGT-2467: Type PAPER_RADIUS_OPTIONS against RadiusScaleKey

---------

Co-authored-by: Metabase Automation <github-automation@metabase.com>
2026-09-07 15:07:41 +03:00
Nicola Mometto
1dfc2d1c90 Fix transform self cycle (#81676)
* Resolve the under-test transform's target live in cycle detection

* Split the change-target overwrite e2e test into the two cases it conflated

Retargeting onto the transform's own source table is a self-cycle (400), not a
target conflict, so exercise the conflict case with a table produced by another
transform and add a dedicated self-cycle case.

* Make the transform under test win target collisions in get-transform-cycle

* remove live-target-table-id
2026-09-07 09:49:13 +01:00
Nicola Mometto
78d3c10b00 perf: optimize fix-sql-params regex (#81893)
* Make fix-sql-params regex linear-time

The tag-body class excluded only `}`, so `\s*[^}]+\s*` had three overlapping
quantifiers and backtracked cubically on an unclosed `{ {` followed by
whitespace. Exclude `{` from the body and drop the redundant \s* so every
position matches in linear time.

* Use :standardsql dialect in test so no kondo ignore is needed
2026-09-07 09:48:49 +01:00
Kamil Mielnik
bbef4a31a2 GDGT-3185 Replace document viz settings instead of merging them (#81889) 2026-09-07 08:18:02 +00:00
Stas Gavrylov
ace7aa5dd0 Add Loki and Figma Desktop workflows to component skill (#81763) 2026-09-07 10:44:28 +03:00
Fraser
f531a39d14 Enforce the shared tiers for visualizations (#81990) 2026-09-07 16:59:45 +12:00
Romeo Van Snick
dbc843ce23 Derive each store root's state type from the slices it composes (#81481)
* Derive each store root's state type from the slices it composes

* Type the mirror's own selectors against the slice they read
2026-09-07 09:44:55 +10:00
metamben
e6216478c6 Introduce billing-project for BigQuery (#79489)
* Introduce billing-project for BigQuery

Closes QUE2-539
2026-09-05 22:29:39 +00:00
technomancy
42a8e9f77d Update create-transform-with-tags-test to be more specific about schema. (#81986)
Previously it was just picking a table at random and using that row,
but in redshift it turns out that table's row doesn't actually exist,
causing a bunch of failures. Let's look specifically at the people
test-data table instead of just using whatever.
2026-09-05 00:06:32 +00:00
Ben Grabow
6fdf223404 bgrabow/redshift-describe-database-probe (#81980)
* Probe for cause of describe database flakes

* Fix brittle test

* Delete obsolete probe test suite
2026-09-04 16:54:56 -05:00
Andrei Simionescu
70a3d8cb4a BOT-2110: sweep orphaned search index tables when a reindex starts (#81944)
Sweep orphaned search_index__* tables at the start of reindex! instead of at activation, so a rebuild
that dies partway is cleaned up by the next run instead of leaving its table behind. The sweep is best
effort and never aborts the reindex.
2026-09-04 21:52:11 +00:00
Fraser
8e3b90894e Move the drill layer from visualizations into querying (#79500) 2026-09-05 09:06:32 +12:00
Ben Grabow
a8db179087 Fix "The result set is closed" flaky reuse of connections (#80033) 2026-09-04 13:31:12 -05:00
Phoomparin Mano
ee9cd6a54e Fix getComputedStyle crash in data app sandbox (#81739)
* fix iframe parent distortion

Fix getComputedStyle calls in data app sandbox

fix frame parent distortion

* update distortion tests
2026-09-04 18:10:38 +00:00
Phoomparin Mano
96c905f643 Allow multiple useDataAppLocation consumers without crashing data apps (#81854)
Fix multiple data app location consumers
2026-09-05 01:06:40 +07:00
Riley Thompson
2a92db58c0 Don't merge db details if db engine was changed (#81968)
dont merge detials if new engine selected
2026-09-04 13:50:23 -04:00
Riley Thompson
cbfbeb3ce1 Fix implicit date conversion in postgres convertTimezone (#81912)
* add test

* Cast DATE inputs before timezone conversion on Oracle and SQL Server

`convertTimezone` on a `DATE` column failed on both drivers:

- Oracle: `FROM_TZ` only accepts a `TIMESTAMP` and refuses to implicitly
  promote a `DATE` (ORA-00932: inconsistent datatypes: expected TIMESTAMP got
  DATE). Cast date-typed inputs to `TIMESTAMP` first.
- SQL Server: `AT TIME ZONE` rejects a `date` argument (error 8116: Argument
  data type date is invalid for argument 1 of AT TIME ZONE function). Cast
  date-typed inputs to `datetime2` first.

Fixes `convert-timezone-date-column-test` for both drivers (#27186).

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RYP35BadwdEL9LAC9zHWQZ

* Derive expected DATE column values from the results timezone in test

`convert-timezone-date-column-test` hardcoded the raw `d` column as
midnight `+07:00`, which is only right for drivers that support
`:set-timezone`. SQL Server can't set a session timezone, so its results
timezone falls back to the database timezone (UTC in CI) and the column
formats as `Z`. Compute the expected values the same way `format-rows`
does so the assertion holds on every driver with `:convert-timezone`.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01RYP35BadwdEL9LAC9zHWQZ

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-09-04 17:37:51 +00:00
technomancy
234568bf20 Deprecate merged-column-info in driver-api. (#81965)
We want to drop as much usage of legacy-mbql as we can. This function
is never used internally, but it's exported in the driver-api. We
should mark it as deprecated since everything else in this namespace
is deprecated, so we can remove it when the time comes.

Need to get this in today so it's included in the 64 branch.
2026-09-04 17:32:16 +00:00
technomancy
4be1fd71c9 Replace Bigquery/Snowflake dataset tracking table; track by name instead (#81655)
* Replace Bigquery/Snowflake dataset tracking table; track by name instead.

The current system of using a tracking table was based on the
assumption that all datasets would need to be tracked by access
time. In fact, datasets fall into one of two buckets, either they are
static and immutable, or they are temporary one-offs. Static datasets
change *very* rarely and do not necessitate automated tracking. If we
neglect to clean them up, we could go for decades before the
accumulated datasets pose a real problem. But non-static datasets are
used once and accumulate *very* rapidly, needing to be cleaned up.

All datasets defined using `defdataset` are considered static.

Rather than using a database to track which ones must be cleaned up,
the logic can be much simpler; use the date embedded in the dataset's
name. It turns out it's even simpler because the logic to track
datasets based on their name has existed this entire time since 2023
in `metabase.driver.sql.test-util.unique-prefix`; we just stopped
using it in Snowflake/Bigquery in favor of the overly-complex tracking
table which A) leaked like mad and B) mistakenly marking static
datasets as old and causing them to get deleted while they were still
in use.

Redshift already uses the `unique-prefix` namespace generating its
schemas, so it only needs a few minor changes to adapt to the changes
in the gc job and the `unique-prefix` functions.

This also simplifies the gc nightly task; rather than having two
separate settings, we only need one setting for how many hours old a
non-static dataset has to be before cleaning it up. Also adds a
`dry-run?` option for manual testing.

* Address review feedback.

* Update workflow yaml to refer to single :hours parameter
* Remove 256-row limit from bigquery/snowflake
* Fix snowflake dataset :name in report data
* Get rid of with-write-stmt helper.
* Accept tracked? arg for manually GCing tracked datasets.
2026-09-04 09:24:56 -07:00
Nicolò Pretto
374e182461 add react_version to sdk analytics (#81954) 2026-09-04 17:03:33 +02:00
Anderson
35c9ea0a29 Fix flaky 'admin > allows to undo every action' test (#81020)
* Keep the data model in sync when a change is undone

* Extract shared TableSection update handlers into a hook

* Undo a custom field order with a single request

* Guard the optimistic table patch by table id

* Reproduce the dropped refetch scenario in the middleware test

* Link the upstream RTK issue from the dropped-refetch middleware and test
2026-09-04 13:52:40 +00:00
Nicolò Pretto
2176f18597 feat(sdk, eajs): add support to show "all" collections in the browser components (#80881)
* Accept "all" as a collection id in the browser public API

Adds the public api plumbing

* refactor: own the ItemsTable container query inside ItemsTable

The CSS container was defined in CollectionContent.module.css, which meant it only worked on ItemsTable when it was rendered inside CollectionItemsTable. The virtual "all collections" root renders ItemsTable on its own, so the container moves onto ItemsTable.

* refactor: split the collection breadcrumbs into a view and its data

We'll need to customize what breadcrumbs will be rendered for the virtual root.
This commit extracts the view that we'll use directly.

* Clear the browsed collection while the next one loads

RTK Query keeps serving the previous collection from `data` while the next one
loads, and keeps serving it once the argument becomes skipToken. A caller that
reads `can_write` during the switch therefore offers to create content in the
collection the user just left.

`currentData` drops to undefined on any argument change, so it covers both
cases and the manual clearing from 397a3e82e04 goes away.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Gdru2a8afSo6y24e99W6hy

* Don't let the popped stack entry override the clicked breadcrumb

Clicking a collection breadcrumb from inside a question landed on the
collection the browser was mounted on, not on the one the user clicked.

Opening a question, a metric or a model pushes a navigation stack entry, so the
back button keeps working. That entry carried an onPop that reset the view to
the mounted collection. The breadcrumb handler sets the view to the clicked
crumb and then pops the stack, so onPop ran last and overwrote the click.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Gdru2a8afSo6y24e99W6hy

* Render the virtual "all collections" root in the collection browser

collectionId="all" now lists everything the current user can reach, as flat
siblings, in the same order the entity picker uses: "Our analytics", the shared
tenant collections, "Our data" and the personal collection.

useAllCollectionsItems builds those rows:

- A 403 on GET /api/collection/root means the user cannot read "Our analytics"
  itself, so the hook falls back to /api/collection/root/items, which has no
  read check on the root. The models=collection argument is required: without
  it the endpoint returns no models at all.

- "Our analytics" needs a numeric id for the table, so it gets 0. Real
  collection ids start at 1, and the caller maps 0 back to "root".

- The shared tenant collections come from the collection tree, gated on the
  use-tenants setting and on the tenants plugin. shallow=true keeps the
  backend from building a nested tree the caller never reads.

- The backend excludes the tenant collection from /api/collection/root/items,
  so the hook adds it from the current user.

CollectionBrowser renders the rows with ItemsTable directly, without the
archive column: archiving resolves its permissions from a parent collection,
and the virtual root has none.

The breadcrumbs put a static "All collections" crumb in front of
CollectionBreadcrumbsView. The personal and the namespaced collections lose
their "Our analytics" crumb, because the API reports them as its children
while the virtual root shows them as siblings.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Gdru2a8afSo6y24e99W6hy

* Key the SDK breadcrumbs by type and id

Breadcrumb ids come from separate id spaces, so a collection and a dashboard
can both be 5. On an instance where collection 5 holds dashboard 5 the trail is
[all-collections "all", collection 5, dashboard 5], and two children of the
same list share the key 5. React warns about the duplicate key in the host
application's console.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Gdru2a8afSo6y24e99W6hy

* fix sdk package type

* e2e tests

* Unit test the virtual "all collections" root

* "all collections" -> "all-collections"

Co-authored-by: Mahatthana (Kelvin) Nomsawadi <me@bboykelvin.dev>

* pageSize support

* Assert the error message, not the error container

The virtual root error tests only checked that the sdk-error-container
testid rendered. That proves an error appeared, not which one, so any
other failure rendering into the same container would keep them green.
They now look for "Failed to load collections".

Verified by mutation: changing that string in CollectionBrowser turns
all four tests red, where the testid version stayed green.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01C9MrpBnd3VEiXVvYf15Qqd

* change root id from 0 to -1 and wrap the mapping

* import already existing defer

* not.toHaveLength(0) -> toBeGreaterThan(0)

* clarify that the root is 403 in the test

* `SdkBrowseCollectionId` -> `SdkBrowserCollectionId`

* docs(sdk): list the accepted collectionId values as bullets

The CollectionBrowser `collectionId` doc described five accepted values in
one running paragraph, and adding "all" pushed it past readable. Split it
into one bullet per value, and document the entity ID string, which the
paragraph never mentioned.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01UTu6CuVJnRjzS1HrmrJQT3

* else if

* rename the virtual root identifiers to all mode root

* refactor root status into union

* clarify when the root could be empty

* fix eslint

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
Co-authored-by: Mahatthana (Kelvin) Nomsawadi <me@bboykelvin.dev>
2026-09-04 14:59:46 +02:00
Kamil Mielnik
af22e8cf22 GDGT-3183 Sanitize ClickObject and HoverObject (#81885) 2026-09-04 19:57:23 +07:00
Kamil Mielnik
d3cb526e49 GDGT-3186 Custom viz SDK type-check (#81891) 2026-09-04 19:38:54 +07:00
Alexander Polyankin
6be1b2761e Warn when startup encrypts legacy plaintext, and make migrations leave none behind (#81898)
* Warn when startup or a migration encrypts data that was stored unencrypted

The settings backfill reports that settings saved by an older version are being
converted, the startup sweep reports each column whose plaintext values it
encrypted, and the migrations that encrypt existing rows report how many they
touched, so an operator can see when and why data changed at rest.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* Find legacy unencrypted values first and hand them to a handler before encrypting them

`legacy-unencrypted-value?` decides what counts as legacy plaintext, the startup
sweep and the encrypting migrations filter their rows with it, and
`handle-legacy-unencrypted-values!` is called with the count before anything is
encrypted, so it can turn from a warning into something else later. The
migrations keep private mirrors of both, as they do for the encrypted JSON
helpers, and read their rows eagerly: reducing a reducible query closes the
transaction's connection.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* Call the handler's location parameter title

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* Make the encryption migrations no-ops and move the app-db module's queries to db.clj

The Encrypt* custom migrations did the same work `encrypt-plaintext-columns!` does
on every startup, so their forward bodies are gone; the reversible ones keep their
decrypting rollback for downgrades. The handler now takes only a `table.column`
location. The encryption and setting namespaces run their Toucan 2 queries through
the new `metabase.app-db.db`, like the other modules.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* Drop the decrypting rollbacks of the no-op encryption migrations

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* Make a fresh install come out fully encrypted from the migrations alone

The encryption-touching data migrations that only rewrote existing rows are no-ops
now that the startup sweep covers their columns, and MigrateMetricsToV2 goes with
them. Two v58 changesets left rows a fresh install would then see as legacy: the
SQL copy of password authentication into auth_identity is retired from the
changelog and redone in Clojure with the credentials encrypted, and sample content
is created by CreateSampleContentV3 once setting.value_with_aad exists so the
example-dashboard-id row is written whole. The settings backfill skips the
encryption-check sentinel, which the encryption tooling rewrites itself. The
fresh-install test asserts that setup logs no app-db warning and that the sweep
afterwards finds nothing.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* Keep the sample-content migration tests in version order

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* Stop inserting the plaintext encryption-check marker on new databases

The v53 changeset that inserted it is retired from the changelog: the encryption
tooling writes the sentinel itself, whole, and reads a missing row the same way, so
the settings backfill no longer needs to special-case it.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* Delete the plaintext encryption-check marker instead of retiring its changeset

The v53 changeset inserted the marker on every new database, encrypted ones
included, so it never said anything about the actual state. It stays in the
changelog as a checksum-agnostic no-op, since a rollback to a release that still
has it must not re-run the insert, and a new changeset deletes the marker rows: with
no row the state is unknown and judged from the content, which the encryption
tooling already does.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* Leave the v53 encryption-check changeset untouched

Its checksum is recorded on every existing database and validCheckSum: ANY does
not lift the check, so it keeps inserting the plaintext marker on a new database
and the v58 changeset deletes the row right after.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* Keep the data migrations, retire the Encrypt* changesets, and never change a row's encryption state

The migrations that rewrite encrypted JSON columns are back with their original
bodies, but `encrypted-json-in` now writes a row back the way it was stored:
encrypted only when the stored value decrypts with the current key, so a
migration never turns plaintext into ciphertext or the reverse. The Encrypt*
migrations are removed outright, with a changeset retiring their changelog
records, since encrypting legacy plaintext is the startup sweep's job.
CreateSampleContentV2 is untouched again and a small migration fills its
setting's value_with_aad from the strictly decrypted value; the LLM providers
migration writes both columns too.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* Address the review: decide by decrypting, stream the sweep, and write NULL rather than an empty SET

The settings backfill now treats a value as encrypted only if it decrypts, so a
plaintext value that merely looks like ciphertext is filled in instead of being
skipped forever. update-setting-values! takes the columns to set as a map, so a
value that encrypts to nothing is written as NULL as before instead of compiling to
an empty SET. The startup sweep streams each column again, warning once before the
first row it encrypts. The unused bytes predicate is gone, the string one is
private, and the two changelog-retirement changesets are one, using the changelog
table property.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* Keep the SQL copy of password authentication; the startup sweep encrypts the credentials

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

* Give the internal user no password

It is inactive and can never log in, and a password would be copied into
auth_identity bare by the v58 SQL changesets, leaving a fresh install with one
row for the startup sweep to encrypt.

Co-Authored-By: Claude Fable 5.1 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5.1 <noreply@anthropic.com>
2026-09-04 08:01:14 -04:00
Fraser
21b94190f6 Move FieldPanel into the table columns settings widget (#81929) 2026-09-04 21:24:50 +12:00
Nicola Mometto
72951848e5 Use tighter schema for POST /api/notification/send (#81877)
The endpoint sends an unsaved notification, so its body has no row of its
own. Decode it with the create schema instead of the full hydrated one.
2026-09-04 09:54:48 +01:00
Fraser
364ec28c56 Move template_tags and native parameters list into parameters (#79127) 2026-09-04 15:32:45 +12:00
Fraser
63e4a7ccb2 Create the segments module (#81864) 2026-09-04 14:59:02 +12:00
Anderson
3fafdbd58a Aggregate static viz grid map cells when the mapped dimensions are not unique (#80354)
* Aggregate static viz grid map cells that share a lat/long bin

* Address review
2026-09-04 01:13:19 +00:00
Riley Thompson
df8d8a2f41 Add test for presto struct fields (#81903)
add test
2026-09-03 21:33:06 +00:00
Tyler Plude
7d07cc9ac8 [GHY-4377] Data sensitivity table scanning (#81752)
* add deterministic data_sensitivity rules classifier

* fill data_sensitivity rule table to full enum breadth

* add data_sensitivity scan step and opt-in setting

* register classify-data-sensitivity as the last analyze step

* document PUBLIC as scanned-or-reviewed for data_sensitivity; add end-to-end tests for the data_sensitivity scan

* label non-Text base types and integer/band variants in the data sensitivity classifier

* add reset-data-sensitivity! to clear classifier-written labels
2026-09-03 14:33:01 -07:00
github-automation-metabase
cf03ebca8d Auto-update documentation for master (#81921)
Update generated docs (master)

Co-authored-by: github-actions <github-actions@github.com>
2026-09-03 17:29:02 -04:00
Fraser
a00b3d7fd1 Move CollectionBadge into common/collections (#81856) 2026-09-04 09:05:48 +12:00
Fraser
c82c593a00 Move the no-results alert prompt from querying into notifications (#81853) 2026-09-04 09:05:19 +12:00
Riley Thompson
b7a39e92b3 Add test for cumulative sum of a literal number (#81806)
* Add test for cumulative sum of a literal number (#27807)

Adds a QP test verifying that a custom aggregation expression of
CumulativeSum(1) on the Products table, broken out by Created At by
month and ordered ascending, runs successfully instead of failing
with 'Field 1: Field does not exist'.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_011kKRbqUbfSKNViTEzS82ss

* clean up

* undo

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-09-03 23:43:36 +03:00
Aleksandr Lesnenko
8444d69eb9 Show errors from the body of http 500 responses to users (#74693)
surface http 500 error messages to users
2026-09-03 20:37:04 +00:00
Fraser
295d7eaabb Dispatch fetchTableMetadata directly instead of through loadMetadataForTable (#81852) 2026-09-04 08:35:08 +12:00
Cam Saul
cf6a95c3b8 Metadata for plain-:field expressions should propagate Field ID and Table ID (#81286)
* Metadata for plain-`:field` expressions should propagate Field ID and Table ID

* Fix 🔧

* Add tests 🔧

* Test fix 🔧

* Test fix 🔧

* Test fixes 🔧

* Test fix 🔧
2026-09-03 20:05:10 +00:00
Tyler Plude
e315710292 [GHY-4378] Add data_sensitivity col to field (#81744)
* add nullable data_sensitivity column to Field and its user-settings mirror

* Expose data_sensitivity on PUT /api/field/:id

* add tests for data_sensitivity survives sync, reactivation, and base-type changes

* add serdes round-trip tests for data_sensitivity on Field and FieldUserSettings

* Expose data_sensitivity in Lib column metadata

* tweak wording
2026-09-03 13:01:43 -07:00
Chris Vandoodewaard
2b35888297 containerize uberjar from uberjar workflow (#81238)
* merge containerize-uberjar into uberjar workflow

* big refactor

* move things around, add inputs to fetch-artifact action

* update conditional logic

* clean up comments

cleanup whitespace

* simplify conditional logic

* guard conditional matrix

* review cleanup

* add job names

* cleanup whitespace

* update get-docker-info to resolve repo/tag inputs

* trim trailing whitespace

* fix linting

* simplify fetch-artifact, use continue-on-error instead
2026-09-03 14:37:13 -04:00
Eric Normand
0dfca163f0 GHY-2937: On-demand field values can take forever to load (#81753)
* Keep on-demand FieldValues fetches alive past request cancellation

On-demand FieldValues are fetched on the request thread, so a canceled HTTP
request threw the warehouse scan away: every retry started the scan over and
nothing ever landed in the app DB, which is what makes these requests feel
like they take forever.

Run the fetch on a detached thread instead. It runs to completion and persists
what it fetched even when the caller stops waiting, and concurrent callers for
the same field (and sandboxing/constraint context) share the one in-flight run
rather than each kicking off their own scan.

Fixes GHY-2937 (#67843)

* Log detached FieldValues fetch failures

When every caller has walked away — the case detached-fetch! exists for —
nobody derefs the promise, so a thrown exception was dropped without a trace.

* Don't wipe cached FieldValues when the warehouse scan fails

`distinct-values` catches and logs warehouse errors, then returns nil — but
`create-or-update-full-field-values!` destructured that nil into empty values
and handed it to `persist-field-values!`, which reads empty as "this field has
no values" and calls `clear-field-values-for-field!`. So any failed or
timed-out scan deleted the values the field already had cached, and a field
slow enough to hit the QP timeout could never keep a cache at all.

Distinguish the two cases: nil means the scan failed, so leave whatever is
cached alone and return ::fv-fetch-failed. A scan that genuinely comes back
empty still clears, as before. The sync path already made this distinction
(see fetch-distinct-per-field's :failed-fields).

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XwGt3aocjPgJeGXTuEjujp

* Guarantee detached FieldValues fetches always complete

A registry entry left behind with its promise undelivered is worse than a
leak: every later caller for that key parks on it forever, holding a request
thread each. Two paths could do that.

The `log/warnf` added for failed fetches sits inside the catch, so an appender
that throws skips both the registry cleanup and the delivery. And the registry
entry is claimed before the work is submitted, so a rejected submit — which is
what `future`'s pool does once the JVM starts shutting down — orphans it.

Route both through `complete-fetch!`, which still drops the entry before
delivering so a woken caller starts a fresh fetch rather than re-attaching to
a finished one.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XwGt3aocjPgJeGXTuEjujp

* Sweep and cancel stalled detached FieldValues fetches

Nothing bounded the in-flight registry except every code path remembering to
clean up after itself, which is a property that keeps not holding — the
logging call has now stranded entries twice.

Give each entry a timer and its future, and sweep on the way into
detached-fetch!, which is the only moment the registry can grow. The sweep
cancels the work and *completes* the entry rather than just forgetting it:
callers park on the promise, so dropping one undelivered leaves them blocked
forever, each holding a request thread.

Only a fetch wedged outside the query processor can reach the max age — the
warehouse query is already capped by *query-timeout-ms* (20 minutes in prod).

Removing an entry is now conditional on it still being the registered one, so
a swept fetch that later finishes can't evict its own replacement.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XwGt3aocjPgJeGXTuEjujp

* Filter stalled fetches in the doseq rather than up front

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XwGt3aocjPgJeGXTuEjujp

* Cap the in-flight FieldValues registry at 100 entries

Callers park on their fetch, so the number in flight is today limited by the
request thread pool — but that is an accident of how these endpoints are
served, not something this namespace can guarantee, and it stops holding the
moment anything frees a caller early.

Past the cap, detached-fetch! stops detaching and runs the work on the calling
thread. That degrades to what happened before detaching existed — no
single-flighting, no surviving cancellation — rather than failing the request,
so a ceiling that should never be reached can't take a filter dropdown down
with it. Capacity is checked inside the swap, so the ceiling holds exactly
under concurrent claims.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XwGt3aocjPgJeGXTuEjujp

* Refuse FieldValues fetches past the in-flight cap

Reaching the cap means something is wrong — callers park on their fetch, so
the number in flight is bounded by the request thread pool unless that stops
holding. Absorb it by running the work inline and the ceiling stops being a
signal; throw a 503 and it says what it means.

Raised to 200 now that hitting it fails the request rather than degrading it:
an instance has to have raised MB_JETTY_MAXTHREADS well past its default of 50
before this is reachable at all.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XwGt3aocjPgJeGXTuEjujp

* Pin down that joining an in-flight fetch bypasses the cap

The behavior was already right — claim-fetch!'s `contains?` short-circuits
before the count check — but it reads as incidental, and a caller that only
attaches to existing work adds no entry, so the ceiling has no reason to
refuse it. Say so, and test it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XwGt3aocjPgJeGXTuEjujp

* Bound how long a caller waits on a detached FieldValues fetch

sweep-stalled-fetches! only runs when a request arrives, which is exactly what
the case it guards against prevents: callers parked on a wedged fetch are
request threads, so enough of them and nothing reaches the sweep to cancel
anything. The watchdog was only reachable while the system was healthy.

Bound the waiter's deref by the same max age. The expensive thing here is the
parked request threads rather than the registry entry, and giving those back
lets requests flow again — at which point the next one sweeps the corpse. No
scheduler needed.

fetch-max-age-ms stays a backstop rather than a request-latency bound: a value
nearer a sensible HTTP timeout would return the thread far sooner, but
answering before the values are ready changes what the endpoint promises, and
that wants deciding on its own.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XwGt3aocjPgJeGXTuEjujp

* Report scan failures from POST /api/field/:id/rescan_values

The endpoint discarded the result and always answered {:status :success}. That
was already misleading, and the cache-wipe fix made it worse: a failed scan now
leaves the existing FieldValues untouched, so there is no observable trace of
it at all — the caller is told the scan succeeded and sees the values it had
before.

Return a 500 when the scan failed. The button already toasts on error, so this
is the difference between "Scan triggered!" and a visible failure.

Unlike the table and database endpoints, this one runs the scan synchronously,
so it is in a position to know.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XwGt3aocjPgJeGXTuEjujp

* Serve warm advanced FieldValues without a detached fetch

The advanced branch wrapped the whole select-or-insert in detached-fetch!, so a
cache hit — one SELECT — paid a thread handoff and a registry sweep for a plain
read. field-id->field-values-for-current-user walks advanced fields serially,
so a sandboxed user with N filters paid N of them.

Look the row up on the calling thread and detach only on a miss, which is the
only case that scans the warehouse. This is what the full-values path at
get-or-create-full-field-values! already did.

The miss path gains one extra SELECT, since select-or-insert! still does its
own read before inserting. That is noise next to a warehouse scan, and keeping
select-or-insert! there is what makes two callers racing a genuine miss safe —
detached-fetch! only single-flights within one JVM.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XwGt3aocjPgJeGXTuEjujp

* Stop the FieldValues tests mutating JVM-global state

Two tests could only be trusted because of a test-runner setting. The cap test
stuffed 200 fake entries into the shared in-flight registry, so anything else
asking for field values during that window would have been refused with a 503;
three tests swapped distinct-values with `with-redefs`, which rebinds the root
for the whole process. Under the current runner nothing else is running, but
that is a property of `:multithread? :vars`, not of the tests — flip it and the
failures land in other people's namespaces.

Make the two knobs dynamic so the cap test can bind the ceiling to 0 and drive
everything through the public API instead: one real fetch held in flight, a new
key refused, and a joiner admitted. That tests more than the fake entries did.

Use the thread-local `mt/with-dynamic-fn-redefs` where the work stays on
threads that inherit bindings. Where it delegates to the original, capture it
with `mt/original-fn`: `patch-vars!` installs its proxy as the root for the
life of the JVM, so a bare symbol captured after some earlier test patched the
same var would have recursed into the proxy.

The rescan test keeps `with-redefs` — `mt/user-http-request` is served on a
Jetty worker that inherits nothing, so only a root rebind is visible there.
Commented so nobody "fixes" it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XwGt3aocjPgJeGXTuEjujp

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-09-03 13:16:43 -05:00
Alexander Polyankin
30e5526fa7 Cover enable-encryption against the read-only-mode guard reading settings (#81890) 2026-09-03 14:00:47 -04:00
Jeff Bruemmer
196032c3fe docs - banner cleanup (#81895)
banner cleanup
2026-09-03 13:51:49 -04:00
Alexander Polyankin
a865fd1ad7 Address the remaining db.clj review findings: metabot, sync, search and friends (#81865) 2026-09-03 11:53:29 -04:00
Andrei Simionescu
9c04238b16 BOT-2052: stop reading six Metabot settings from the environment (#81217)
The three system prompts, the two usage limit settings and the quota message no
longer read their environment variables, so they are set through the admin page,
the API or a config file like every other setting. Name, icon and
show-illustrations keep theirs, which matches the MB_APPLICATION_* whitelabel
settings that self-hosted deployments set once at startup.

Demoting a setting used to drop it from the config file template as well, because
the template generator shared the environment variable docs filter. That filter
now sits with the docs alone, which puts use-tenants back in the template.
transforms-setup-complete is derived and never read back, so it is marked
read-only and the template stops advertising a key that does nothing.
2026-09-03 14:46:53 +00:00
Timofey Kachalov
25060e4397 Fixed outdated data app sync skill/comment (#81790) 2026-09-03 18:29:31 +04:00
Kamil Mielnik
a2979abd20 GDGT-3182 Make checkRenderable optional in custom viz (#81884) 2026-09-03 21:10:50 +07:00
Andrei Simionescu
f1ddc2317b BOT-2003: Support GLM 5.3 (#81681)
Add GLM 5.3 to the model picker whitelist on both providers
2026-09-03 13:01:26 +00:00
Chris Vandoodewaard
cb5e5847c4 use gh cli to approve/automerge instead of 3rd party action (#81599) 2026-09-03 08:47:31 -04:00
Chris Vandoodewaard
00b57255ea remove ci release comments (#81598) 2026-09-03 08:46:34 -04:00
Andrei Simionescu
fa07f544d5 Metabot: remove extraneous data from non-500 errors with an error code (#81201)
An `:error-code` means the throw site wrote this as an API response rather than
hitting an unexpected failure, so the client gets the message and the error data
and nothing else. The Metabot token-limit 402 and the transforms trial-limit 402
both returned a full backend trace before this.

Validation errors, real 500s and the older `:error_code` spelling are untouched.
2026-09-03 12:07:03 +00:00
Kevin Kelleher
c8a8941508 Documents viz setting sidebar fixes (#81740)
* documents viz setting sidebar fixes

* use Ellipsified on viz name
2026-09-03 07:19:14 -04:00
Chris Truter
94d7dd520c Show what automated ratchet PRs shrink (#81807)
* Show what automated ratchet PRs shrink

* Tweak messaging

* Fix ratchet PR body test lint
2026-09-03 12:57:39 +02:00
Jakub Chodorowicz
e4cf63ff23 gate event apis on window instance (#81680) 2026-09-03 11:03:12 +02:00
Timofey Kachalov
c73e309b13 Adjust skill guidance telling agents not to offer a "deploy" step for data apps (#81791) 2026-09-03 11:45:58 +04:00
Timofey Kachalov
8196701636 Update data apps upsell (#81786) 2026-09-03 10:56:26 +04:00
github-automation-metabase
042ec24fe9 Tighten ratchets (#81862)
Co-authored-by: github-actions <github-actions@github.com>
2026-09-03 04:58:07 +00:00
Alexander Polyankin
ff335470e7 Route each module's app-DB queries through a db.clj namespace (#81824) 2026-09-03 04:52:56 +00:00
Fraser
75bce3e619 Move open-url out of visualizations into urls (#81842) 2026-09-03 16:14:55 +12:00
Fraser
9ddee1f434 Register the use-icon spec's own visualizations from viz-core (#81844) 2026-09-03 16:01:14 +12:00
Fraser
0337de20c1 Read the app slice instead of current-user in the redux hooks spec (#81841) 2026-09-03 15:46:09 +12:00
Fraser
c71cf2a379 Move useHelpLink from nav into common/hooks (#81843) 2026-09-03 15:45:42 +12:00
Fraser
06462d0005 Enforce shared tiers for urls (#81845) 2026-09-03 15:45:26 +12:00
Alexander Polyankin
e6aa23212c Write re-encrypted rows with plain SQL, not Toucan DML (#81829) 2026-09-02 23:42:56 +00:00
bryan
79041e2487 mcp-v2.00 prep: extract query guards + pulse helpers; additive shared-ns changes v2 needs (#81244)
* MCP v2 prep: extract query guards + pulse helpers; additive shared-ns changes v2 needs

Behavior-preserving groundwork for the v2 MCP surface, landed while v1 is
untouched and v2 is not yet present:

- NEW metabase.agent-api.query-guards (+ its test): query safety checks
  extracted so REST and MCP run identical guard logic.
- metabase.pulse: recipient-filtering and sensitive-metadata-stripping
  logic moved from private fns in api/pulse.clj into models/pulse.clj and
  exported via pulse.core / pulse.api, so REST and MCP share it. Pure move;
  existing REST pulse tests are the check (+ new direct tests).
- metabase.channel.urls: adds metric-path, transform-path, collection-path
  helpers (additive).
- metabase.metabot.scope: adds agent:{content,query,sql,delivery}:* scopes
  and collapses agent:viz:mcp-ui:{query,drill-through} into
  agent:viz:mcp-ui:* — a proven superset, backward-compatible with v1's
  gating (REPL-verified: old concrete scopes still match). Also regates
  agent:metric:* from SQL-generation to NLQ permission (scope_test).
- metabase.mcp.settings: adds mcp-v2-disabled-tools and
  mcp-query-handle-ttl-hours (additive; v1-safe; tests included).
- metabase.models.serialization.resolve{,.mp}: adds *numeric-ids-allowed?*
  dynvar; resolver miss messages no longer name a specific discovery tool
  (the calling surface owns the recovery sentence) — mp_test updated.
- metabase.server.streaming-response: optional :executor option threaded
  through do-f-async; default path (shared pool) unchanged. Needed by
  long-lived SSE keepalive streams so they can't exhaust the fixed pool.

Review question for this PR: does REST/v1 behavior stay identical?

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BjQcjQx7NPGr3Rpf6QaG4b

Review fixes (2026-08-27 deep review of #81244):
- native-marker? requires a truthy :native value (an explicit-null key from a
  JSON round-trip is not a marker); docstrings state the guard/agent-api
  sequencing explicitly (live v1 path untouched; call sites migrate at retirement).
- check-mcp-ui-native-query! accepts agent:sql:execute (v1's concrete scope)
  alongside agent:sql:run, and documents that scope claims arrive with the v2
  session rework — until then native-over-UI-credential fails closed.
- mcp-query-handle-ttl-hours getter no longer rethrows on an unparseable env
  var (falls back to the default instead of killing the GC task).
- *numeric-ids-allowed?* docstring rewritten in future tense naming its binder
  (the v2 query pipeline) and reader (the dialect rework PR).
- viz-scope comment corrected (v1 resources still register those strings until
  retirement; wildcard keeps them satisfied); mp.clj database-id tru args
  str-wrapped against MessageFormat locale grouping; streaming-response
  :executor docstring notes the Future.cancel(true) interruption requirement.

Follow-up (review round 2): the guards are now genuinely shared — agent-api's
private copies are deleted and its execution paths call query-guards directly.
Deliberate tightening: raw-scan native detection replaces normalize-then-inspect
(fail-closed on unparseable payloads). Full agent-api api-test green.

Re-review round: agent:sql:execute compat branch now tested; TTL getter's
catch path tested ("forever"); reject-native-query! no longer echoes the
payload in ex-data (matches the old live rejection shape); viz-scope comment
typo fixed; pure predicate tests ^:parallel; check-token-query-permissions!
docstring states the stage-0-fast-path/QP-backstop contract.

--- Close-out review response (slice 00's first adversarial round) ---

CRITICAL (native-query false-positive on legacy MBQL with a field/expression/tag named `native`)
FIXED. native-query? scanned the whole payload via tree-seq, so a legit query whose :expressions or
:template-tags map had a key named "native" was rejected (400) though it ran fine on master. It now
scans only the structural query-nesting edges (:stages/:joins, :query/:source-query), never
descending into caller-named :expressions/:template-tags; a malformed value off a structural edge is
still deep-scanned to stay fail-closed. Proven: a 17-case REPL matrix — every crafted false-positive
now false, every genuine native (legacy top/nested, MBQL5 stage, joins, string-keyed, malformed)
still true.

SECURITY (v1 MCP bearer authenticates a deactivated user) FIXED. resolve-access-token — the single
resolver shared by the v1 transport and the core session bearer bridge — now gates on
(t2/exists? :model/User :id user-id :is_active true). v1's transport dispatched straight on :user-id
with no active check; v2 was already refuse-only. Proven fails-when-broken: reverting the guard lets
a deactivated user's token resolve; restored, it is refused. v1 mcp.api-test (598 assertions) green.

IMPORTANT fixed: agent:delivery:write now granted by the metabot-other-tools bucket (was dead
config → alert_write would 403 everyone); metabot-nlq grants agent:content:read not :* (was
over-granting write to NLQ-only users); update-pulse-with-perm-checks! validates :cards against
CoercibleToCardRef (a bad string id was a 500, now a 400); check-mcp-ui-native-query!'s docstrings
now state it is dormant until the v2 session-rework slice wires it (was claiming to be live).

MINOR fixed: thrown-status test helper distinguishes no-throw from throw-without-status; kill-switch
check moved after the scope check (a scope-denied caller no longer learns the kill-switch state);
the query-handle-ttl default is one const, not two literals; mp_test gains positive assertions.

Re-verified (fresh JVM, run separately): query-guards + scope + settings + mp 328 assertions;
oauth + v1 mcp.api-test green. The one red in pulse-test is create-csv-xls-test = GDGT-3161, a
pre-existing EE-app-db bug (empty {} dataset_query -> download-perms 500) in the CREATE path (not
this fix's update path), reproducing on plain master — not introduced here. kondo 0/0; cljfmt clean;
modules-config regenerated (oauth-server :model-imports gains :model/User).

--- master parity sync (user-approved Option A) ---
Carries master 8c3ea6f40b (#80554 Remove Explorations dimension anchored blocks) + master search/appdb/index.clj (isolate-write! savepoint isolation). Stack forked before both; without them the dropped exploration_block.type migration is absent -> Liquibase changelog-integrity failure on real app-DBs (App-DB Part2 CI). Synced at base to restore parity. 41 files, all slice-untouched.

* Fix save-access-token! call arity after master merge

Master gave the test helper a 5th arg (client-id via
oauth-server.tu/with-oauth-client); the new
resolve-access-token-deactivated-user-test still called the 4-arg form.
Wrap it in with-oauth-client and pass client-id, matching every other
call site. Verified: full session-oauth-test namespace green locally
(10 tests, 27 assertions, 0 failures).

* Fix native-guard snake_case gap and make the tenant recipient filter work end-to-end

- native-map-edges gains :source_query/"source_query": legacy MBQL
  normalization canonicalizes the snake_case spelling too, so a payload
  like {"query" {"source_query" {"native" ...}}} reached the query
  processor as a native stage while native-query? said false — an
  MBQL-only-scoped caller could run raw SQL through /v1/execute,
  bypassing the scope split and the execute-sql kill switch. Regression
  tests cover both the string and keyword snake forms.

- The cross-tenant recipient filter compared :tenant_id on recipient
  maps that the :recipients hydration never populates, so a tenant
  caller lost every user recipient and a tenantless caller was filtered
  by nil = nil. Tenant membership is now looked up from the app DB
  inside the filter, and the filter only engages for a caller who
  belongs to a tenant — a tenantless user sees recipients unfiltered,
  as before tenants existed. The test now builds real users in real
  tenants (production-shaped recipient maps, ids only) instead of
  fabricating :tenant_id keys, and pins the tenantless-caller
  passthrough.

* Match native-SQL markers case- and separator-insensitively

`native-query?` matched edge names and markers case-exactly, but the QP
normalizer canonicalizes keys case-insensitively and treats `_` and `-`
alike. `{:query {:SOURCE_QUERY {:native "select 1"}}}` therefore scanned
as not-native and then executed as a native stage — REPL-confirmed, along
with `:Source_Query` and an uppercased `:NATIVE` marker.

That is a live bypass rather than a latent one: since
`+refuse-unscoped-native-sql` went live on /api/dataset, this scan is the
only gate between an unrestricted-stamped MCP UI credential and raw SQL.
The same scan backs `reject-native-query!` on the agent-api execution
paths, so those inherit the fix.

All key and value matching now goes through one `token` fn — namespace
kept, lowercased, `_` folded to `-`. Nodes are walked as `[token value]`
pairs rather than by fixed lookup, so a node carrying two spellings of
one edge has both scanned instead of one silently shadowing the other.

* Deep-scan a non-map stage element instead of throwing

`native-query?`'s `scan-map` iterated the node's entries without checking it was a map, so a
junk payload like `{:stages [1]}` threw "Don't know how to create ISeq from Integer" and
`/v2/query` answered 500 where shape validation should have answered 400
(`combined-query-rejects-malformed-payload-test`). A non-map where a stage belongs is now
deep-scanned like every other malformed sub-tree: never throws, and a marker after it still
trips the guard.

* Address round-3 review findings on the extraction slice

- The bearer resolver's is_active gate is defense in depth, not the primary control: deactivating
  through the model already revokes the user's tokens. The docstring now says so, and the test
  deactivates with a raw core_user UPDATE (the path the gate exists for) and asserts the token was
  not revoked, so the gate is what the test exercises.
- Pin that a tenant-scoped caller sees only same-tenant pulse recipients (tenantless users hidden).
- scope.clj comments described a wildcard collapse that is not in this diff; say what the slice
  does: adds scopes, removes none.
- Correct the guard test docstring: the /api/dataset gate is wired by the next slice.
- Pin the guard's deep-scan fallbacks and the streaming response's :executor option with tests.

* Widen the recipient merge-back to cover the tenant filter

Addresses review feedback on the tenant recipient filter: a filtered read
that is submitted back as a write silently deleted the recipients the
caller was never shown.

The `:channels` submitted to an update are authoritative --
`update-notification-channels!` deletes any recipient not present -- so
every recipient hidden on the read path has to be restored on the write
path. Master already did this for one read filter (sandboxed and
impersonated users, via `maybe-add-recipients`), but the tenant filter
added in this slice had no corresponding write-path compensation. A
tenant-scoped caller doing GET then PUT of the returned body therefore
dropped every other-tenant and tenantless recipient row.

Rather than add a second parallel mechanism, the tenant visibility rule
is now a single predicate (`recipient-visible-to-tenant-caller?`) used by
both sides: the read path filters with it, and the write path merges back
exactly what it excluded via `hidden-cross-tenant-recipients`.

Two supporting fixes:

- `maybe-add-recipients` now normalizes `:channel_type` the way
  `email-channel` does. The old `(= "email" ...)` string comparison only
  matched the REST shape, so a direct call with a hydrated pulse (keyword
  `:email`) skipped the merge entirely -- which also made the pre-existing
  sandbox protection REST-only.
- Merged recipients are de-duplicated by `(some-fn :id :email)`, the same
  key `update-pulse-with-perm-checks!` uses to diff recipients, so a
  caller matching both filters cannot get a recipient appended twice.

Verified in a REPL: the new endpoint-level round-trip test goes red
without the merge-back (two recipient rows destroyed) and green with it.
It asserts on `pulse_channel_recipient` rows rather than the API response,
since the response is filtered either way and cannot distinguish "hidden"
from "deleted". Pulse, pulse-channel and enterprise sandbox pulse suites
show no new failures (`create-csv-xls-test` fails identically on the
unmodified branch).

---------

Co-authored-by: Eric Normand <ericwnormand@gmail.com>
2026-09-02 23:18:07 +00:00
technomancy
9d216767d0 Remove be-tests-databricks-multi-catalog-ee job. (#81127)
In https://github.com/metabase/metabase/pull/80957 we trimmed this job
down so it no longer doubles the tests run. But it's still pointless
to have it as a separate job; it should be tested inline with the main
suite.

We still run some individual tests twice using the
`with-and-without-multi-level` macro when we need to cover both the
multi-catalog behavior and the non-multi-catalog behavior, but this is
only a handful of tests now instead of the entire suite or the entire
namespace.

Removal of `when-not (tx/db-test-env-var :databricks :multi-level-schema false)`
causes a lot of indentation changes here, so it's best to review with
whitespace diffs turned off.
2026-09-02 22:35:39 +00:00
Alexander Polyankin
a9a062731b Store setting values encrypted under the setting's name (#81751) 2026-09-02 17:26:10 -04:00
github-automation-metabase
a7090f30ba Auto-update documentation for master (#81820)
Update generated docs (master)

Co-authored-by: github-actions <github-actions@github.com>
2026-09-02 21:23:08 +00:00
Andrei Chernykh
8a7375b368 Split the SSO auth settings pages into card sections (#81750)
* Split the SSO auth settings pages into card sections

* Deflake modal escape close in data-model e2e specs

* Move docs changes to a separate PR

* Finish token-scale translation in the merged css modules

* Deflake dark mode toggle assertions in palette spec
2026-09-02 13:44:47 -07:00
Nathan Voxland
a55b6b6b8a Better handling of unparsable user settings (#78737) 2026-09-02 15:15:33 -05:00
Nathan Voxland
58819b5ea2 Pivot table download should respect currency formatting (#75969) 2026-09-02 14:23:06 -05:00
Tyler Plude
0c06e94821 [BOT-1838] Release JDBC savepoints when nested transactions OK (#77562)
* release JDBC savepoints when nested transactions succeed

* tighten inline comment

* pr feedback

* Release savepoints only when no later scope is still running
2026-09-02 12:09:44 -07:00
Andrei Simionescu
e34e6190c6 BOT-1927: gate audit-view chart queries behind a Run query button (#81215)
* BOT-1927: gate audit-view chart queries behind a Run query button

* Track the Run query click with useDisclosure instead of useState
2026-09-02 18:00:34 +00:00
github-automation-metabase
eeba22c5fe Tighten ratchets (#81805)
Co-authored-by: github-actions <github-actions@github.com>
2026-09-02 17:57:02 +00:00
Anna Tomka
a06e24c8bd GDGT-3104: Fix unreadable active tab count badge in dark theme (#81800)
Fix unreadable active tab count badge in dark theme (GDGT-3104)
2026-09-02 19:46:00 +02:00
Riley Thompson
af1c635d4e Fix sqlglot parse failure for ?::type placeholder casts (#81381)
* Fix sqlglot parse failure for ?::type placeholder casts (#81373)

With connection impersonation enabled, native queries are parsed by
sqlglot after template-variable substitution, when {{var}} has already
become a JDBC `?` placeholder. sqlglot's base tokenizer treats `?::` as
a single token (DuckDB's try-cast operator) in every dialect, and only
DuckDB's parser can consume it, so `{{var}}::date` -- a very common
pattern on Postgres/Redshift/Snowflake -- failed with "Unable to parse
native query".

Fix: before parsing in is_single_stmt_of_type, rewrite `?::` to `? ::`
(which sqlglot parses fine, emitting CAST(? AS type)). Occurrences are
located via the tokenizer's own QDCOLON tokens, so `?::` inside string
literals, dollar-quoted strings, and comments is left untouched, and
placeholder order is preserved in the re-emitted SQL. Multi-statement
rejection and the rest of the impersonation validation are unchanged.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XkBejATyUcaq2R74xFd5M1

* comments and tests

* Assert all placeholders survive; fix QDCOLON dialect guard (databricks, not duckdb)

Review feedback: the placeholder-cast test now asserts that every ? in the
input survives into the re-emitted SQL, not just that one does.

While adding duckdb coverage, it turned out the dialect guard in
_split_placeholder_casts named the wrong dialect: in sqlglot 28.6.0 the
?:: (QDCOLON) token is emitted by the *base* tokenizer but only
Databricks' parser consumes it (the expr?::type try-cast column
operator); duckdb's parser does not, so duckdb was still failing on
placeholder casts. The guard now skips databricks instead, duckdb gets
the same ?:: -> ? :: rewrite as everyone else, and tests cover both:
duckdb placeholder casts parse with placeholders preserved, and
databricks' native try-cast is left intact (re-emitted as TRY_CAST).

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* clean up

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-09-02 13:42:38 -04:00
Chris Truter
30f9f25ba9 Refine kondo ratchet commands and prompts (#81776)
* Make ratchet shrinking explicit, and check it in one place

The ratchet test fixture ran `fix!` on every non-CI run, so `project-tests
ratchets` rewrote .clj-kondo/ratchets.edn in your working tree before
asserting against it. A check that edits what it checks leaves a diff nobody
asked for, in the file every PR conflicts over, and its only reachable
failure was a bug in the fixer that had just run.

Removing the auto-fix forces the dev/CI split to go too: a strict local test
that no longer tightens would fail on every branch that removes an ignore.
So over-budget is now the rule everywhere, and shrinking is only
`./bin/mage kondo-ratchets-shrink`, which the shrink workflow runs on master.

That left two implementations of nearly the same check. The babashka
`check-report` gains the justification finding — the one assertion the JVM
suite had that it lacked — so `./bin/mage kondo-ratchets` covers over-budget,
config over-budget, unjustified ignores, normalization and unknown linters on
its own. CI runs it instead of booting a JVM, and the five now-duplicated
in-repo assertions leave the test namespace, which drops from 6.2s to 0.8s
because it no longer walks the source tree.

Task names follow: check-kondo-ratchets (which nothing called) becomes
kondo-ratchets, fix-kondo-ratchets becomes kondo-ratchets-shrink, and the
merge task becomes private -kondo-ratchets-merge, since only the git merge
driver invokes it. bin/merge-kondo-ratchets keeps its name; installed merge
drivers point at it.

* Polish kondo ratchet guidance

* Prime the ratchet shrink workflow

Intentionally raise the :case-symbol-test budget from 1 to 2 without adding a suppression. The read-only check allows the unused budget; after this PR merges, the shrink workflow should restore it to 1 through a Tighten ratchets automation PR.

* Make the ratchet suite check the project

Keep the ratchet tooling unit tests in the backend suite, but make project-tests ratchets run the read-only repository check. Include it in the bare project-tests command so local project-level checks still validate the checked-in ratchet policy.

* List project-test suites once

* Address review findings on the ratchet check

check-report threw NPE on a ratchets map without :comment-exempt, while
tolerating a missing :ignore-counts or :config-counts. Default it, so the
three policy keys behave alike.

The run-project-ratchet-checks description and the step comment both still
described the old wiring. The check now runs alongside the backend checks,
which no longer include it, and "no JVM" is not quite true: resolving
clj-kondo on a cold cache shells out to the JDK prepare-backend installs.

* Warn about stale comment exemptions

The only check that a :comment-exempt entry is still needed was a local-only
test, which went vacuous when the dev and CI semantics were unified, so
nothing named a stale exemption any more. The check now reports one the way
it reports an :unlimited policy nobody uses: informational, never a failure,
since only the shrink workflow removes them.

* Say why the merge driver finds mage through its own path

The script runs against whatever repository holds the conflict, which is not
always the one it lives in -- the tests merge stages in a throwaway repo. A
relative bin/mage looks plausible and fails there, so record the reason.

* Stop wrapping two comments that did not need it

One fits on a single line once it says less. The other breaks at its sentence
boundary rather than mid-clause.

* Break the ratchets header on its sentences

Four sentences started mid-line and wrapped mid-clause, one of them trailing
"in the PR." onto a line of its own. Same words, one sentence per line.

* Keep comment exemptions until someone removes them

fix! dropped a :comment-exempt entry as soon as every ignore of its linter
carried a comment, or the last uncommented one was deleted -- so an exemption
could disappear as a side effect of unrelated work, and getting it back is a
change to defend in review.

An exemption records a decision about a linter, not a count, which is the
reason :unlimited policies are already kept at zero and only warned about.
Treat the two alike: the check and the shrinker name a stale exemption, and a
person deletes it.
2026-09-02 17:37:16 +00:00
Jakub Chodorowicz
89da67a9f3 Gdgt 3146 remap cypress maildev ports so they don't conflict with app maildev 2026-09-02 19:36:37 +02:00
Ben Grabow
ae10677d61 Use a single future for a batched feature check in tests (#81743)
Use a single future for a batched feature check when per-feature memoization is disabled
2026-09-02 11:31:48 -05:00
Ben Grabow
3bcaab2e3b Avoid has_any_column_privilege run on entire cluster (#81734)
* Avoid has_any_column_privilege run on entire cluster

* Ensure that privilege filter only lets through `true?` values
2026-09-02 11:29:54 -05:00
Nathan Voxland
2921ecdcf9 Fix image tile url tracking (#81371) 2026-09-02 11:23:22 -05:00
Kevin Kelleher
8819a72555 Prompt to reload after changing settings that update CSP (#80906)
* new domains settings page with reload on save

* review feedback

* better null safety
2026-09-02 15:05:07 +00:00
metamben
22e8ddba1f Return mongodb's collection in QP /native API response (#80918)
Fixes QUE2-822
2026-09-02 17:23:43 +03:00
metamben
8dbfef0fe6 Use the underlying nested field name (#81640)
Closes QUE2-834
Closes #81546
2026-09-02 17:22:55 +03:00
metamben
de7cedfeb6 Only set SQL Server instanceName when specified (#81595)
Closes QUE2-829
Closes 81270
2026-09-02 17:22:35 +03:00
Stas Gavrylov
5885d30ad0 GDGT-2486 Add elevation, radius, and spacing scale variables (#80481)
* GDGT-2486 Add elevation, radius, and spacing scale variables

* GDGT-2486 Remap scale tokens in files merged from master

* Address review

Review fixes for the GDGT-2486 scale migration:

- Revert double-shifted tokens from the merge-remap pass: it re-applied
  the old-to-new mapping to 22 files already remapped by the first pass,
  shifting spacing values one extra step (e.g. xl 24px -> xxl 32px).
- Fix codemod escapes where old key names kept their name but changed px:
  Modal default padding (lg->xl, 24px), MultiSelect radius (sm->xs, 6px),
  MetricSearchInput radius-sm, ThemeEditor PreviewPanel radius-md,
  ColumnInput theme.spacing.xs->xxs, ChartTypeSettings Space h props,
  TableRowForCacheableItem icon placeholder w (md->lg, 16px),
  ResizeHandle/ResizableBoxHandle grip h (xs->xxs, 4px).
- Pin Group/Stack default gap to "lg" (16px): Mantine's default is
  "md", which is 12px in the new scale (was 16px in the old scale).
- Allowlist the runtime-defined --mantine-spacing-xxs/-xxl and
  --mantine-radius-xxs CSS variables in find-never-defined-css-variables
  (fixes fe-lint CI).
- Add theme.unit.spec.ts covering the spacing/radius/shadow scales,
  dark-mode shadow set, whitelabel independence, and a guard asserting
  every scale-based component default resolves to a defined key.
- Derive Card/Paper story argTypes options from the real scale.
- Augment MantineThemeSizesOverride so the custom scale tokens appear in
  editor autocomplete for p/m/gap/radius/shadow props.
- Update the emotion-migrate and metabase-ui-component-from-figma skill
  token tables to the new scale (spacing/radius values, shadow tokens,
  snap tables).

* Update Loki Snapshots

* Address review: fix h/w style props missed by the scale codemod

The codemod did not remap height/width style props, so every bare h=/w=
scale-key value silently changed px with the new scale. Remap each to the
px-preserving key (xs 4px->xxs, md 16px->lg, lg 24px->xl, xl 32px->xxl):

- PaneHeader breadcrumb row h xl->xxl (32px, restores data studio
  pane header height)
- BrowseDatabases logo boxes h/w xl->xxl (32px)
- DatabaseConnectionStringField rows h lg->xl (24px)
- DatabaseEngineList logo Center h/w lg->xl (24px)
- Metabot chat chevron flexes h/w md->lg (16px)
- MetricsFilterPill h lg->xl (24px)
- DatasetNotebook divider h xs->xxs (4px)
- DataReference NodeList icon w md->lg (16px)
- transforms-python ResizableBoxHandle grip h xs->xxs (4px)

Audited: no remaining bare h/w/maw/mah/miw/mih old-key props whose px
changed (verified line-identical against master for every occurrence).

* Address review: fix bdrs and responsive-object size tokens missed by the codemod

Two more escape classes from the scale codemod, found by a full sweep of
every touched-token form (string style props, responsive objects, CSS
vars, theme accessors) with each line compared against master:

- bdrs style prop (border-radius): remapped px-preservingly at 69 sites
  in 58 files (xs 4px->xxs, sm 6px->xs, md 8px->sm). The codemod remapped
  radius= but not its style-prop alias bdrs.
- Responsive object values (e.g. p={{ base: "md", sm: "xl" }}): remapped
  the token VALUES at 9 sites in 6 files (base/sm/md breakpoint keys are
  untouched; only their spacing values shifted: md 16->lg, xl 32->xxl,
  xs 4->xxs).

Sweep result after fixes: zero remaining line-identical old-key token
references to spacing xs/md/lg/xl, radius xs/sm/md, or shadow xs/md in
any form. Intentional survivors unchanged: radius/shadow/bdrs "lg"
(disclosed broken-key-now-16px class), spacing/radius sm where the
px value did not change.

Verified: tsc, eslint (changed files), metabase/ui jest suite.

* Address review: fix remaining token escape forms (object props, braces props, style objects)

Final codemod escape classes from the exhaustive token sweep, all
remapped px-preservingly:

- Object-literal / default-parameter prop values (15 sites / 8 files):
  ItemList picker-item default containerProps pb xs->xxs (4px, the
  reported gap), FormFooter pt lg->xl, SlackSetup pt lg->xl,
  EmbeddingSecretKeyWidget mb xs->xxs, CreateDashboardForm labelProps
  mb xs->xxs x2, databases styles mb lg->xl, NotebookDataPicker
  menuDropdownProps mt xl->xxl, Banner story py md->lg
- Braces-wrapped string props: CloudSMTPConnectionCard p lg->xl (24px)
  and gap md->lg (16px), SettingsLdapForm mt xs->xxs,
  DashboardLeaveConfirmationModal mb lg->xl
- style-object CSS properties: DatasetNotebook borderRadius xs->xxs
- Ternary token values inside responsive objects: SummarizeStep gap
  md->lg (16px)

Sweep now returns zero real misses across every checked form: string
style props (incl. h/w/bdrs), braces props, responsive objects with
ternaries, object-literal/default-param props, style-object CSS props,
CSS var() references, theme.* accessors. Remaining grep hits are
untouched scales (lh, fz, size, breakpoints) or px-identical sm values.

* Address review: preserve Mantine spacing defaults exposed by Loki

* Update Loki Snapshots

* Address review: fix remaining scale regressions and visual guards

* Address review: make Loki update capture new references

* Update Loki Snapshots

* Address review: keep only targeted Loki references

* Address review: assign ticket component elevations

* Update Loki Snapshots

* Address review: tighten MonthPicker header spacing

* Address review: refine elevation visual stories

* Update Loki Snapshots

* Address review: keep renamed Menu Loki story selected

* Update Loki Snapshots

* Address review: preserve inherited Mantine defaults

* Address review: allow stock Mantine shadow tokens

* Address review: replace token audit test with ESLint rule

* Address review: drop unrelated whitespace-only dev/src changes

* Address review: use rem() in radius scale and rem docs

* Update Loki Snapshots

* GDGT-2486: Address PR comments

* GDGT-2486: Adjust negative tokens

* GDGT-2486: Address review findings

* Update Loki Snapshots

---------

Co-authored-by: Metabase Automation <github-automation@metabase.com>
2026-09-02 17:21:33 +03:00
Nicola Mometto
0b4bbf0427 Use a generic error message for the parameter-permission 403 (#81762) 2026-09-02 15:20:45 +01:00
lbrdnk
74e847104b Clean up the ai benchmark workflow (#80532)
* Clean up the ai-benchmark.yml

* Address review
2026-09-02 15:24:31 +02:00
Sébastien
bf5778bc50 Fix flaky embed parameters e2e by pre-accepting embedding terms (#81322)
Pre-accept embedding terms in embed parameters e2e setup
2026-09-02 14:53:32 +02:00
Kevin Kelleher
386fe3b12a Fix small Explorations UI issues (#81730)
fix comment badge line height, background color overflowing rounded borders
2026-09-02 08:37:41 -04:00
Andrei Simionescu
dc3f2134cb Move the Metabot model capability checks into the provider catalog (#81679)
* Move the Metabot model capability checks into the provider catalog
* Move the fast-mode proxy check into the Claude adapter
2026-09-02 12:10:51 +01:00
Jakub Chodorowicz
30be3958a2 Fix double-coercion in DOM distortions (#81672) 2026-09-02 11:18:06 +02:00
Andrei Simionescu
58ad1ba564 BOT-1033: Add box plot support to the metabot chart tools (#81198)
* BOT-1033: Add box plot support to the metabot chart tools

* BOT-1033: Narrow the chart-types docstring to the enums that derive from it
2026-09-02 10:03:13 +01:00
Sébastien
0da75ad4a3 Deflake the SQL default-parameters embed wizard test (#81759)
Wait for the preview query before asserting embed parameter results
2026-09-02 10:56:38 +02:00
Bartosz Rybacki
b3365881d0 Add brybacki to team and slack map (#81702) 2026-09-02 10:26:14 +02:00
Anna Tomka
663a04c231 chore: add annatomka as team member (#81713) 2026-09-02 10:03:21 +02:00
Kamil Mielnik
fc3927c030 Add core-frontend-gadget as codeowners of custom viz (#81333) 2026-09-02 14:27:49 +07:00
Sébastien
7a20107f87 Prefer the X-Metabase-Session header over the session cookie (#81165)
* Prefer the X-Metabase-Session header over the session cookie

* Don't fall back to the session cookie when the header is stale

* comment
2026-09-02 06:41:28 +02:00
Romeo Van Snick
577f242c41 Move the entities store into the metadata module and hide normalizr (#81290)
* Move the entities store into the metadata module and hide normalizr

* Record the moved schema file's import-time effect

* Describe what the metadata reducers do, not what they replaced

* Move the mirror's fixtures and slice-name helpers into the module (#81297)

* Move the mirror's fixtures and slice-name helpers into the module

* Build the QuestionSources fixture through the metadata store barrel

* Document why the metadata store is not a deletable mirror slice

* Trim the barrel and write-door comments
2026-09-02 10:46:02 +10:00
Nathan Voxland
de202b144a Create personal colection on user create (#78714) 2026-09-01 17:35:56 -05:00
dpsutton
9bf3b136af only derive site-url from authenticated superuser requests (#81130)
* only derive site-url from authenticated superuser requests

`maybe-set-site-url*` (global Ring middleware) derived `site-url` from request
headers whenever `(or (not (setup/has-user-setup)) superuser?)`. The left arm
needed no authenticated caller, so an unauthenticated request reaching the
instance before its first user was created could pin `site-url` from a forged
Host/Origin/X-Forwarded-Host header. Because the write is first-writer-wins and
setup never overwrites it, that attacker-chosen value survived setup and
poisoned every later auth/email link (notably password-reset URLs) for the life
of the instance.

Gate derivation on `superuser?` alone. `:is-superuser?` is already on the request
by the time this middleware runs (wrap-current-user-info is inner/earlier in the
onion), so an admin's own request still auto-derives `site-url` -- which happens
on the operator's next request after an interactive setup. An unauthenticated
pre-setup request now writes nothing; `site-url` simply stays unset (nil is
handled everywhere it's consumed, and a reset link built on nil is relative,
never attacker-controlled).

Deployments that provision headlessly, run multi-tenant, or never sign in as an
admin will otherwise sit at a nil site-url, so note in the setting's docs that
they should set MB_SITE_URL explicitly.

* Read Quartz job-data blobs through a class allow-list

Quartz persists job data, calendars, and BLOB triggers as serialized objects.
Metabase's job data is only ever EDN-shaped data (keywords, strings, numbers,
maps/sets/vectors) wrapped in Quartz's own JobDataMap/trigger classes, so when we
read it back we constrain deserialization to exactly those classes and decline
anything else.

Install a per-DB DriverDelegate (StdJDBCDelegate for H2/MySQL, PostgreSQLDelegate
for Postgres) that overrides getObjectFromBlob to read through a class allow-list
built from the plain-data classes job data consists of. This is scoped to
Quartz's own blob reads, so nothing else in the JVM is affected.

- metabase.util.deserialization-allowlist: a reusable, composable ObjectInputFilter
  allow-list. clojure-data-prefixes covers the EDN value space; callers add their
  own wrapper prefixes and read via read-object / read-object-bytes.
- metabase.task.secure-delegate: the allow-set (EDN + org.quartz.*), the blob-read
  bodies, and install!, wired into task.bootstrap. The gen-class delegates are
  AOT-compiled in the jar; from source they're compiled on demand so the class is
  loadable by name through the classloader Quartz uses. That runtime compile is
  fenced to source only (config/jar?): from a jar a missing class is a build error.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BjQcjQx7NPGr3Rpf6QaG4b

* Don't deserialize Java objects from H2 query results

Metabase reads scalar and collection values out of query results, never
serialized Java objects. Register a JavaObjectSerializer on the H2 driver so H2's
JAVA_OBJECT (de)serialization is declined rather than reconstructing arbitrary
classes from stored bytes. With that in place the ad hoc JAVA_OBJECT check in
read-column-thunk is redundant, so it's removed; read-column-thunk keeps its CLOB
handling. Ordinary values are unaffected.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BjQcjQx7NPGr3Rpf6QaG4b

* Strip internal keys from binning maps

Add :decode/api and :encode/serialize remove-internal-keys hooks to the
::binning schema so clients can't smuggle internal query-processor keys in
through a :binning map.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* Strip internal keys from more client-submitted query maps

Extend the :decode/api / :encode/serialize remove-internal-keys hooks to the
::parameter, ::template-tag, ::constraints, ::middleware-options, and ::page
schemas so clients can't smuggle internal query-processor keys in through them.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* Reformat strip-internal-keys-test doseq bindings

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* test improvements and fix reflection warnings

* Validate HoneySQL idents at the app-DB compile step

Honey SQL renders an ident as bare, unquoted SQL in several positions --
a form head it doesn't recognize, an ORDER BY direction, a DDL modifier,
the function name of a `:%fn.arg` var -- so an ident reaching any of them
is raw SQL text. Hold every ident to a plain-identifier shape, with an
explicit allow-list for the keywords Honey SQL renders as fixed SQL of its
own (operators, DDL modifiers, column types, ORDER BY directions).

Also close two gaps found along the way: symbols walked past the `:raw` and
`:inline` gates, since Honey SQL resolves symbol heads and clause keys the
same as keywords; and `safe-value?` trusted any value shape it didn't
recognize, where it now enumerates the types bound as `?` parameters.

Query idents that were kebab-case are renamed in the SQL only -- the
Clojure keys they feed, including the `:metabase-user-id` request key, are
mapped back at the read site and unchanged for their consumers.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013rQMWmi2o1WGSqK5DDZ99u

* Allow the Postgres operators our drivers register globally

`metabase.driver.postgres` registers the PG JSON, array and regex operators
with `honey.sql/register-op!`, which makes them global -- and the app DB can
be Postgres, so app-DB queries reach for them too: the semantic-search
migration compiles a `[:->> ...]`. Add them, and a test that holds the
allow-list to every non-namespaced operator Honey SQL knows, so an upgrade
or a new registration can't silently leave one out.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013rQMWmi2o1WGSqK5DDZ99u

* Snake_case the remaining app-DB query idents

Four more sites the sweeps turned up, all renamed in the SQL only:

- `request/session.clj` selects the current user under the same kebab
  aliases the session middleware did, so it gets the same rename-at-the-read
  -site treatment.
- Search scorer names double as SQL aliases, and three of them are
  kebab-case. They also key the weights in `search.config` and name the
  scores the API returns, so the conversion happens at the one seam that
  writes and reads the alias, leaving the scorer name alone. The alias gains
  a `_score` suffix because `:view-count` and `:data-layer` are named after
  the very columns they read.
- The model alias registry in `api/common.clj` feeds
  `column-with-model-alias`, which assembles `alias.column` idents, so its
  six kebab aliases are snake_cased along with the literal uses in the
  in-place search engine.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013rQMWmi2o1WGSqK5DDZ99u

* Constrain embedded card parameter values by the locked parameters

A dashboard's parameter value lookups receive the values of the other
parameters as chain-filter constraints, so the values offered for an
enabled parameter are limited to the rows the locked ones select. The card
lookups had no constraint argument to receive them: `card-param-values`
bound the JWT's params, used them only to check the searched parameter was
enabled and not pinned, then resolved the parameter to a Field and returned
that Field's whole value list.

Give the card lookups the same constraint argument and pass the JWT's
locked values from the embed layer. The argument is optional, so the
authenticated and public routes keep their current behaviour.

`param-type->op` and `param-type->default-options` move from
`parameters.dashboard` to `parameters.params`, so both the dashboard and
card constraint builders can reach them.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013rQMWmi2o1WGSqK5DDZ99u

* Snake_case the app-DB query idents the guard rejects

CI caught `queries.models.query`, and a grep for the same shape found four
more sites the earlier sweeps had missed -- they were confined to the
app_db, collections, search and permissions modules. The aliases move to
snake_case in the SQL; where the keys they feed are confined to their own
namespace the readers move with them, and where they have to match a shape
from elsewhere they are renamed back at the read site:

- `queries.models.query` aliases so the app-DB branch matches the keys
  `lib.metadata/card` returns, so it renames rather than propagates.
- `cache.task.refresh-cache-configs` feeds its aliases through a nested
  subquery whose outer `:select` names them, so both levels move, along
  with the readers and the test's expectations.

Also widen `safe-parameter?`: a `query_hash` read back from H2 arrives as a
`java.sql.Blob` rather than a byte array, and the enumeration rejected it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013rQMWmi2o1WGSqK5DDZ99u

* Remove a scratch probe test

Committed by accident in the previous commit -- a throwaway namespace with
printlns, used while checking chain-filter behaviour.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013rQMWmi2o1WGSqK5DDZ99u

* Fix the locked-parameter constraints for previews and stale slugs

Three problems with the constraints the card parameter lookups build:

The preview routes passed the sanitized Card, whose `:parameters` has the
locked ones removed, so the constraints were always empty and a preview
offered wider value lists than the embed it previews. They now pass the
stored Card and take only `:embedding_params` from the token, which is what
the published routes already do.

`embedding_params` is keyed by slug and `:parameters` by id, and nothing
keeps them in sync; a locked slug naming no parameter produced no
constraint and widened the values rather than narrowing them. It is now
refused. `param-values-merged-params` refuses the same on dashboards, where
the slug otherwise became a nil key that the constraint builder dropped.

A locked value of `[]` reached the filter builder as a value rather than as
"no value", producing a `:=` clause with one argument.

The constraints also carry the parameter's own `:options` now, as the
dashboard builder does.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013rQMWmi2o1WGSqK5DDZ99u

* Allow a qualified argument in a :%fn.arg ident

`:%lower.metabase_field/name` renders `LOWER("metabase_field"."name")` --
Honey SQL splits the ident at the first `.` and formats what follows as
quoted entities, so a `/` there separates the parts of a qualified column
rather than landing in the SQL. Only the function name, which is rendered
unquoted, has to be a bare identifier.

The pattern rejected `/` anywhere after the `%`, which took the database
autocomplete endpoint with it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013rQMWmi2o1WGSqK5DDZ99u

* Snake_case more app-DB query idents, and allow the FOR UPDATE modifiers

Found by widening the search: the earlier grep looked for the alias and its
`:select` on one line, so it missed every alias sitting on a continuation
line -- which is most of them.

- `activity_feed`: the recent-views queries alias `database-name`,
  `initial-sync-status`, `entity-coll-id` and `moderated-status`. The keys
  are read only within their own namespace, which builds the API response
  from them under different names, so the readers move too.
- `xrays.automagic-dashboards`: `num-fields` and `list-like?` -- the latter
  loses its `?`, which no snake_case spelling keeps.
- `:skip-locked`, `:nowait` and `:no-wait` are lock modifiers Honey SQL
  matches by name in a `:for` clause, not idents it renders, so they join
  the allow-list rather than being rewritten.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013rQMWmi2o1WGSqK5DDZ99u

* Move the query-analyzer's readers to the renamed table id

`query-analyzer/tables-for-native` aliases its table id, and that alias was
snake_cased without moving one of its two readers: `used-tables` still asked
for `:table-id` and so silently collected nothing. Unlike the write side,
which the guard rejects outright, a reader left behind reads nil.

The `tables-for-native` redefs in the tests carried the old shape too, so
they asserted against a result the function no longer produces.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013rQMWmi2o1WGSqK5DDZ99u

* Revert the HoneySQL ident guard and the renames it required

The guard held every ident in an app-DB query to a plain-identifier shape,
which turned out to have a long tail: each release of it found more query
aliases to rename, and a rename that missed a reader failed silently rather
than loudly, since the reader simply got nil.

This reverts the guard along with every alias rename made to satisfy it,
leaving the parameter-value security fixes, which do not depend on it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013rQMWmi2o1WGSqK5DDZ99u

* Harden site-url derivation fix: fail-closed redirect check, discerning test

Follow-ups to gating site-url auto-derivation on authenticated superuser
requests.

- check-sso-redirect: fail closed when site-url is nil. Previously a nil
  site-url left our-host nil, so a redirect with a nil host but a non-nil
  scheme was non-relative yet matched (= nil nil) and passed -- an open
  redirect. Require a known host to match against: (and
  our-host (= (.getHost redirect) our-host)).

- misc-test: bind has-user-setup false in the non-superuser negative case.
  With has-user-setup true (the test-DB default) the old gate
  (or (not has-user-setup) superuser?) was already false for that request,
  so the test passed against the vulnerable code and distinguished nothing.

- misc: rewrite the SETTING SITE-URL block comment and the maybe-set-site-url
  docstring, which still described the removed behavior (site-url set on the
  initial setup request).

- system settings: drop the blank line in the site-url :doc (it made the new
  paragraph render as an indented code block in the generated env-var docs)
  and replace an em-dash with a comma.

* Read a card's parameters the way the rest of the code does

`card-param-constraints` read `:parameters` alone, but a native card can be
described entirely by its template tags and carry none -- which is how the
static embedding e2e fixture builds one. The locked slug then matched no
parameter and the lookup was refused. Use the same either/or source
`get-param-or-throw` uses a few lines above.

A parameter with no value constrains nothing whether or not it still
exists, so the existence check now runs after the empty-value guard rather
than before it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013rQMWmi2o1WGSqK5DDZ99u

* Fix jar startup crash when the jar's directory contains a space

find-in-current-jar built a jar: URL by string-concatenating
get-jar-path, but get-jar-path returns the *decoded* filesystem path
(URL -> URI -> .getPath turns %20 back into a literal space). URL.toURI
then throws URISyntaxException on the raw space, killing startup while
loading bundled driver manifests.

Open the jar via the Path-based nio-fs helper instead — Paths don't
round-trip through URI encoding, so spaces are fine. This also stops
closing a filesystem out from under other consumers: the old code, on
FileSystemAlreadyExistsException, grabbed the provider's *cached*
filesystem and closed it in with-open; the Path-based overload creates
an independent uncached instance whose close affects only itself.

Verified against a jar in a spaced directory: the manifest URI is found
and slurpable, and a concurrently-open URI-cached filesystem for the
same jar stays open and registered.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_013Fpja4n6bzdCy4QufM49Hb

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
Co-authored-by: Alexander Polyankin <alexander.polyankin@metabase.com>
2026-09-01 17:14:27 -05:00
Denis Berezin
84223a0d4d Restyle Number and Trend dashboard cards (UXW-5128) (#81131)
* Restyle Number and Trend dashboard cards (UXW-5128)

* Adjust sizes and tooltips

* Adjust sizes, fix icon

* fix

* Fixes after merge

* Update Loki Snapshots

* Fix multiple comparisons

* Add link to card title, Implement query builder view

* Undo scalar dashcard ellipsis menu styling changes

* Design review fixes

* Fix e2e

* Fix e2e

* Review fixes

* Update Loki Snapshots

* fix

* Self review fixes

* Self review fixes

* Add a "Show comparison value" display setting to the Trend visualization (#81148)

* Add Show comparison value setting to the Trend visualization

* Address review comments

* Standardize ellipsis menu styling across all dashboard cards (#81405)

* Standardize dashboard card ellipsis menus

* Update Loki Snapshots

* Update Loki Snapshots

* Refine dashcard menu button props

---------

Co-authored-by: Metabase Automation <github-automation@metabase.com>

* Fix review comments

* Update Loki Snapshots

* Add more tests

* Add keyboard navigation

* Fix borders for dark theme

* Update Loki Snapshots

---------

Co-authored-by: Metabase Automation <github-automation@metabase.com>
Co-authored-by: Anderson <anderson@metabase.com>
Co-authored-by: Anderson <ands.alves.nunes@gmail.com>
2026-09-02 01:11:13 +03:00
Chris Truter
e24150083f Report dynamic requires which linter cannot verify (#78082)
* Don't crash the modules require hook on dynamic requires

(requiring-resolve (:failing-test-var opts)) has no statically-known
namespace; unwrap-require now returns nil for such forms instead of
falling through, and both callers skip non-symbols. dev.clj has carried
a live :hook crash from this since the hook was added.

* Add a hook regression test for dynamic requiring-resolve

Covers the crash fix: dynamic arguments lint to nothing, static
cross-module violations still report. hooks.* test namespaces join the
outside-the-module-system prefix list.

* Fail closed on dynamic module requires

* Polish module require hook tests

* Assert module hook findings directly

* Document intentional dynamic module requires

* Update module linter ratchet
2026-09-01 21:51:21 +00:00
github-automation-metabase
70f9234106 Auto-update documentation for master (#81742)
Update generated docs (master)

Co-authored-by: github-actions <github-actions@github.com>
2026-09-01 21:35:27 +00:00
Nathan Voxland
540817adfe Improve document read/write performance (#76018) 2026-09-01 16:19:58 -05:00
Chris Truter
7f73a7464c Add merge tool for ratchet conflicts (#81341)
* Add a manual kondo ratchet conflict merger

* Split kondo ratchet merge tests

* Document the ratchet conflict merger

* Simplify unlimited ratchet merge policy

* Simplify ratchet merger for final policy schema

* Resolve ratchet conflicts to the stricter policy

Concurrent policy changes now always resolve: the smaller budget wins, a
finite budget beats :unlimited, and a removed entry beats any budget.
Comment exemptions merge on their own. Every stage is read through
read-ratchets and shape-checked before a disabled stage decides the result.

bin/merge-kondo-ratchets reads the index stages by number, so a file
deleted on one side and changed on the other exits nonzero with nothing
staged, and both-sides-add merges against an empty base. It runs from any
directory in the repository and stages only .clj-kondo/ratchets.edn.

mage.merge-kondo-ratchets-test drives the script against real conflicts
in temporary repositories.

* Point the clojure-write skill at the ratchet merge resolver

* Reject malformed stages before merging ratchets

The shape checks move out of read-ratchets into validate-policies, and merge-ratchets runs them on every stage, so a stage with :config-counts [] or :comment-exempt [] is an error rather than an empty set of policies that the merge would read as removals.

* Cover unreadable stages in the merger tests

An empty file, two forms, or a non-map stage now fails the reader instead of merging as no policies; the script leaves such a conflict for a human and stages nothing.

* Reject a non-map ratchet stage before merging

A nil stage passed every field check because dissoc, keys, and the defaults all accept nil, so a malformed stage could merge as an empty set of policies.

* Reject non-keyword linter names

The merge keys on (str linter) and renders the same way, so a string, nil or
symbol name was rewritten as a keyword, collided with one, or produced a file
that no longer read back -- and the script still exited 0 saying it had staged
the merge. Also describe the two sides by git stage: "current" and "incoming"
are inverted during a rebase.

* Run each refused merge once in the tests

leaves-unresolved? and output each ran the script, so every refusal ran it twice
and the "changed nothing" assertion covered a different run from the one whose
message was checked. Read the merged policies with the EDN reader while here.

* Compare the conflicted file, not just its status

A conflicted path reports UU, DU or UD however its contents are rewritten, so
comparing git status alone did not show that a refused run left the file alone.

* Tighten merge-tool docstrings and the ratchet conflict docs

* Compare the index stages of a refused merge too

Porcelain status reports a conflicted path as DU/UU whatever its stages hold, so it alone does not show
that a refused run left the conflict alone. The stages carry each side's blob.

* Spell out the unmerged status codes

UU/DU/UD as bare shorthand assumes the reader knows git's porcelain codes for a conflicted path.

* Clarify the unmerged-state snapshot comment
2026-09-01 21:08:21 +00:00
Nathan Voxland
85f1e975a5 Ensure CSV strings show as strings in excel (#81258) 2026-09-01 15:50:56 -05:00
Chris Truter
bc0200ece0 Enforce and maintain ratchet policies (#81319)
* Add trusted master ratchet shrinker

* Retry ratchet shrink after concurrent master pushes

* Test the check-kondo-ratchets report

* Apply ratchet policy to the check report

* Add severity-based inline ratchet policies

* Update ratchet policy documentation

* Finalize ratchet policy enforcement

* Move seeded linters to bounded ratchets

* Simplify unlimited ratchet policies

* Finish ratchet CI integration

* Document unlimited ratchet policy values

* Keep ignore counts as the policy map

* Validate ratchet policy keys against known linters

Policy keys in .clj-kondo/ratchets.edn must name a clj-kondo built-in from the
pinned version, a linter configured under .clj-kondo/, or an allowlisted
external diagnostic. The check and the fixer fail with one error listing every
unknown name instead of counting it. Config budgets must be non-negative
integers.

Drop :unresolved-require, a linter that never existed, from the semantic-search
ignore and the ratchets file.

* Keep unlimited ratchet policies with no ignores left

An :unlimited entry in :ignore-counts records a decision about the linter, so
the fixer no longer drops it when its count reaches zero. The check and the
fixer print one sorted warning naming such entries; it never fails CI. Bounded
zero budgets are still dropped, and :comment-exempt is unchanged.

* Deliver ratchet shrinking through an automation PR

* Validate seeds and read only tracked kondo configs

The known-linter set now comes from git-tracked `.edn` files under
`.clj-kondo`, so the dependency configs `mage kondo` copies in locally
(gitignored, absent from a clean checkout) no longer make validation
depend on the machine. `--seed` is checked against the same set before
anything is written, and a hand-written bounded `0` with no ignores
left is reported when the fixer drops it.

* Reopen the ratchet automation PR after a close

The "already carries this result" skip now requires an open PR, so a
branch left behind by a PR closed without merging is overwritten and
gets a fresh PR instead of silencing every later run. The compare step
reads PR state with the default token under `pull-requests: read`.

* Let the ratchet automation PR approve and merge itself

Copies the backport recipe: github-actions[bot] approves the PR with the default token (a user cannot approve their own PR, and the automation user owns it), then the automation user enables squash auto-merge. The commit identity is the docs generator's, which merges with that one approval. A ratchets-only change no longer flips backend_all, so the PR waits on the Project tests job alone.

* Describe the self-merging ratchet automation PR

* Expect the ratchet check namespace in the project-test suites

* Read the ratchets file as exactly one map

An empty file, a non-map, or a trailing second form used to read as an empty policy set, which the merger would have staged as the removal of every budget. Tracked kondo configs missing from the worktree (unstaged deletions, sparse checkouts) are skipped instead of failing the scan.

* Skip the uberjar for a ratchets-only change

* Keep fork PRs away from the ratchet automation steps

The head-branch lookup matched any repository's branch of that name, so a fork PR could have reached the approval and auto-merge steps; only an open PR from this repository counts now. Approval and auto-merge key on the open PR rather than on whether the branch was pushed, so a run that failed after opening the PR is repaired by the next one.

* Look up the ratchet automation PR by owner-qualified head

gh pr list caps at 30 results and filtered forks client-side, so enough fork PRs on the same branch name could hide the real automation PR and make the create step fail. The REST head=owner:branch filter is applied server-side and matches only this repository's branch.

* Stop checkout credentials from overriding the automation push token

actions/checkout persists GITHUB_TOKEN as an Authorization header, which takes precedence over the token embedded in the push URL, so the force-push to the automation branch would be rejected.

* Tolerate config budget and exemption reductions in CI

CI already let inline counts fall below their budgets so the shrinker could record them after merge, but a lowered config budget or a stale comment exemption still needed an exact match, so two PRs that each removed a suppression could fail the second merge. Config counts now fail CI only when they grow, stale exemptions never fail CI, and check-kondo-ratchets reports config growth alongside inline growth. Local runs stay exact.

* Say what CI rejects without listing the cases

* Keep actionable ratchets bounded

* Exclude the ratchets file with one pattern

Path filters are OR-ed, so a separate "!.clj-kondo/ratchets.edn" entry matched
every path that was not that file: backend_all became true for every PR, and
no_source_code_changes could never be true. The exclusion has to live inside the
pattern, as modules/drivers does above.

* Arm auto-merge against a known commit

The approve and merge steps keyed on the PR number alone, so nothing had checked
what the fixed automation branch name currently holds. Both paths now record the
sha they pushed or compared, and auto-merge matches it. Also guard the job to
this repository, as the workflow it replaces did.

* Report ratchet validation failures without a stack dump

check read and validated the file, then read it again. Now it parses once and
catches inside, so read-ratchets, validate-linters! and scan all report the same
one-line message. Also: CI=false was truthy in the tests, seeding a recorded
linter with no ignores said "nothing to seed" while dropping its policy, and
lowered-counts rebuilt the seeded set per entry.

* Keep the drift message off stdout

The drifted path prints its findings and then exits; folding it into fail! added
a summary line that check-reports-empty-unlimited-test pins. Split the throw from
the print so only messages the run has not already shown are printed.

* Tighten ratchet docstrings and the generated header

* Guard against standalone negations in the path filters

The patterns in a filter are OR-ed, so a "!..." entry matches every path the other entries don't
instead of subtracting from them, and the filter is then always on. The ratchets exclusion is written
inside one pattern for that reason; this keeps the next one from being written the other way.

* Reuse the automation PR on its ratchet file alone

The extra check that master had not touched ratchets.edn since the branch was cut only bites when master
moved to a different value that shrinks back to the same result, since any change to the result is already
caught by comparing the file. Dropping it means only a shallow fetch of the branch tip is needed.

* Force-push the automation PR when it conflicts

A PR whose ratchet file already matches is otherwise left alone, and a conflict is the one thing that
state cannot clear on its own. Mergeability is computed lazily, so UNKNOWN is polled past and, if it
never resolves, left for the next run.

* Ask once whether the automation PR conflicts

Polling for a definitive answer bought nothing: the next push to master runs this again within the hour,
so a mergeability check still in flight can read as not conflicted and be settled then.

* Say what the reuse comparison is against

git diff FETCH_HEAD -- <path> reads as a commit-to-commit diff. It is against the working tree, which is
the only reason comparing the branch tip answers whether the PR still delivers the right file.

* Fix the circular Filter type alias

Record<string, Filter> is expanded eagerly, so naming it inside Filter's own definition trips TS2456. An
inline index signature is deferred and holds the same shape.

* Prove a ratchets-only change skips the backend filters

* Run the path-filter specs when the filters change

* Use gh CLI to approve ratchet PRs
2026-09-01 20:31:30 +00:00
Ben Grabow
b4f84f1736 Skip some connection validity checks in test (#81725) 2026-09-01 15:22:41 -05:00
Nathan Voxland
52ba78451d Added map-tile-server-allowed-networks setting (#81243) 2026-09-01 15:10:53 -05:00
Ben Grabow
8e4e18f6d5 Don't hit DWH server when no parameters are being set (#81727) 2026-09-01 14:57:28 -05:00
Chris Truter
3c5d1111d7 Run project checks in a separate job (#81318) 2026-09-01 19:37:54 +00:00
Jeff Bruemmer
af549487df docs - ai connections (#81617) 2026-09-01 19:32:12 +00:00
github-automation-metabase
9e2fa97aa1 Auto-update documentation for master (#81619)
Update generated docs (master)

Co-authored-by: github-actions <github-actions@github.com>
2026-09-01 15:24:53 -04:00
github-automation-metabase
1d598c7af4 Update translations 2026-09-01 (#81668)
* Update translation sources 2026-09-01

* Update translations

---------

Co-authored-by: github-actions <github-actions@github.com>
2026-09-01 13:22:09 -06:00
Edward Paget
b244f3c7ca Give Quartz a dedicated app-db connection pool to prevent deadlocks (#72261)
* Reuse toucan2's current connection in Quartz to prevent deadlocks

When code inside a with-transaction or with-connection block triggers a
Quartz operation, Quartz would check out a new connection from the pool.
If the pool is saturated, this deadlocks the thread. Now the
ConnectionProvider checks for a bound toucan2 *current-connectable* and
reuses it via a non-closeable proxy that suppresses close/commit/rollback/
setAutoCommit, preventing interference with the outer transaction.

Closes UXW-307

* Address review comments

verify that asking for a connection while one is already bound via
t2.conn/*current-connectable* reuses the identical underlying connection
instead of checking out a new one. Plus fix an `if` that should be a
`when`.

* Revert Quartz connection-reuse proxy

Revert the non-closeable connection proxy that let Quartz reuse the
thread's bound toucan2 connection with close/commit/rollback/setAutoCommit
suppressed. Suppressing those methods breaks Quartz's data integrity:
JobStoreTX only releases its SELECT ... FOR UPDATE row locks on QRTZ_LOCKS
via commit/rollback, so the proxy either held the cluster lock for the
length of the outer transaction or, for autoCommit connections, defeated
the cluster mutex entirely, and made partial job-store writes
un-rollbackable.

The deadlock this was fixing (UXW-307) is addressed in the next commit by
giving Quartz its own connection pool instead.

* Give Quartz a dedicated app-db connection pool to prevent deadlocks

When code inside a with-transaction or with-connection block triggers a
Quartz operation, Quartz checks out a connection from the app-db pool. If
the pool is saturated, this deadlocks the thread (UXW-307). Fix it at the
root: Quartz now draws from its own small c3p0 pool, so job-store
operations never compete with application code for main-pool connections,
and Quartz keeps full control of its connections' transaction lifecycle.

- ApplicationDB now carries a quartz-data-source: a separate pool (max 5,
  min 1, configurable via MB_QUARTZ_MAX_CONNECTION_POOL_SIZE) when
  create-pool? is true, the raw data source otherwise. It inherits all the
  main pool's properties except sizing.
- mdb.connection/quartz-data-source exposes it behind the ApplicationDB
  read-write lock, re-exported via metabase.app-db.core.
- The Quartz ConnectionProvider draws from it; the tracing
  connection-interceptor hook is unchanged.
- Tests cover provider behavior (no reuse of the bound connection, not even
  wrapped), pool construction/sizing, lock-respecting acquisition, and a
  deterministic pool-of-1 deadlock regression test.

* Reject already-pooled data-sources for the dedicated Quartz pool

connection-pool-data-source returns an already-pooled data-source
as-is, so building the Quartz pool from one would silently hand Quartz
the main pool itself -- reintroducing the starvation deadlock the
dedicated pool exists to prevent. No current caller does this (the only
production :create-pool? true site uses the always-unpooled env-derived
data-source), but nothing stopped a future caller from doing it.

Fail fast instead: quartz-connection-pool-data-source now throws on
pooled input, and application-db documents that :create-pool? true
requires an unpooled data-source.

---------

Co-authored-by: John Swanson <john.swanson@metabase.com>
2026-09-01 12:09:11 -07:00
Chris Truter
3fd1f63cfc Refresh settings cache before reading LLM providers (#81714)
Refresh the settings cache before reading LLM provider connections

Provider connections all live in the one llm-providers setting, and settings
are cached in process, so an instance only learns about another instance's
edit when its cache next polls — once a minute.

Until then it answers a page load with a list that predates the edit, and it
decides whether an edit is allowed against that same list: a connection
another instance has just deleted still looks present, and the type it
belonged to still reports itself as connected, so a legitimate create is
refused.

Force the staleness check on the five endpoints that read the list. It costs
the one query that reads settings-last-updated, unless something has actually
changed.

This does not make the read-modify-write of the list atomic: two instances
editing different connections at the same moment still lose one of the two
edits. That needs a lock, and is left for its own change.
2026-09-01 20:08:03 +02:00
Egor Grushin
2459fe20ba Carry over picked schedule fields when the frequency changes (#80758)
* Carry over picked schedule fields when frequency changes (GDGT-3096)

* Drop redundant mid-frame test

* Hook normalizeScheduleValue to changeScheduleType

* TDD first

* reviewed

* reviewed

* reviewed

* reviewed

* reviewed

* reviewed

* reviewed

* reviewed

* reviewed
2026-09-01 18:52:23 +01:00
Nicola Mometto
0fec254d6d Compile the LIKE ESCAPE character as h2x/literal so driver inlining can't touch it (#81704)
With a driver bound, [:inline "!"] compiles through driver-specific
inline-value; MySQL emits the hex literal _utf8mb4 X'21', whose implicit
collation (utf8mb4's default, utf8mb4_0900_ai_ci) clashes with the
connection collation when MySQL aggregates collations for LIKE, failing
with 'Illegal mix of collations'. ::h2x/literal compiles through its own
registered formatter to a plain '!' on every dialect, which takes the
connection collation like the pattern parameter next to it.
2026-09-01 17:34:00 +00:00
Andrei Simionescu
ebad52172a Fix AdminSettingInput write race (#80737)
* Don't lose the last change to a setting when a save fails

* Drop a duplicated test title

* Drop the no-op catch on the write chain

* Replace the write queue with a pessimistic disabled state

* Extend the failed-save revert to select and radio inputs
2026-09-01 18:29:21 +01:00
Chris Truter
d7a519ab60 Stop timed-out mage commands and their descendants (#81463) 2026-09-01 19:20:43 +02:00
Riley Thompson
0e0e6ac82b Enforce single-statement impersonated queries on all sql-jdbc drivers (#81653)
* Enforce single-statement impersonated queries on all sql-jdbc drivers (SEC-1189)

Connection impersonation confines a non-admin's native queries to a restricted
DB role, which Metabase activates with a `SET ROLE` prefix. To stop a user from
appending `; SET ROLE <broader>` and climbing out of that role, impersonated
native queries must be a single statement. That guard
(`driver/validate-impersonated-query`) was only overridden for `:postgres` and
`:sqlserver`; every other impersonation-capable JDBC driver (MySQL, Snowflake,
ClickHouse, Starburst) inherited the no-op `:default` pass-through and ran the
stacked query verbatim. On MySQL a stacked `; SET ROLE ALL` activates every role
granted to the connection user, escaping the restricted role entirely.

Define `validate-impersonated-query` once at the `:sql-jdbc` floor so every
impersonation-supporting driver enforces the single-statement validation, and
remove the now-redundant per-driver `:postgres`/`:sqlserver` overrides.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01XM9HwBRFsa3ptVAP7UWV14

* clean up

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-09-01 11:53:13 -04:00
Kevin Kelleher
4348d9373e Improve Card type usage (#81409)
* improve card type usage

* fix a few more Card type casts

* use same gate for visualize another way button as in getVisualizerInitialState so button doesn't silently do nothing
2026-09-01 15:49:36 +00:00
Michael Eby
3e094bd928 docs: reorganize line, bar, and area chart docs (#81108)
* docs: reorganize line, bar, and area chart docs

* Optimized 1 images, saved 199.4 KB (55.6% smaller)

* add content from learn bar chart and histograms articles

* edits from jeff

* remove learn article reference

---------

Co-authored-by: Metabase Automation <github-automation@metabase.com>
2026-09-01 10:54:36 -04:00
Ryan Laurie
880bb31835 Treat EoL dates as unsupported (#81639)
treat EoL dates as unsupported
2026-09-01 08:36:22 -06:00
Sébastien
698fd4f1ee Fix flaky terms acceptance in sdk iframe embed setup wizard (#80826) 2026-09-01 14:46:24 +02:00
Sébastien
4dda44859b Move embed wizard copy-event tracking test from Cypress to Jest (#80821) 2026-09-01 14:45:52 +02:00
Sébastien
bd7048574b Gate embedding-hub sandbox column-update test on stepper settling (#80808) 2026-09-01 14:45:18 +02:00
Sébastien
7c8d735d20 Deflake SDK target-collection data-picker test (#81558) 2026-09-01 14:44:45 +02:00
Alexander Polyankin
8b29969f1c Public settings cleanup (#81452)
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-09-01 08:19:25 -04:00
Nicola Mometto
90b3db6dec Escape LIKE metacharacters in user-supplied search strings (#81161)
* Escape LIKE metacharacters in user-supplied search patterns (SEC-847)

Name the LIKE escape character explicitly so the escaping also holds on app DBs without a default one

Add h2x/like-substring and h2x/like-prefix and use them at every search sink

* Update in-place search filter tests for escaped LIKE patterns
2026-09-01 12:34:22 +01:00
Chris Truter
39ad1d5167 Keep ratchets off release branches (#81033) 2026-09-01 11:58:19 +02:00
Chris Truter
ba06454a57 Stabilize transform API tests with explicit native-query permissions (#81574)
Grant native create-queries explicitly in transform API tests

The transform API tests grant :perms/transforms explicitly but rely on the ambient db-level create-queries default (:query-builder-and-native) for the shared dataset DB.
That default is fragile: the native level only exists db-level, so any table-level create-queries row written for the group granularizes it down to :query-builder, and re-coalescing can never bring the native level back.
A target table synced by an async transform run during another test's snapshot-restore window leaves exactly such a row, and full-database-permission-for-user takes the most restrictive value across the DB.
When that happens, every test creating or running a native-query transform as a non-superuser 403s for the rest of the run while the MBQL-source tests keep passing (seen on the SQL Server 2022 driver job).

Replace the bare transforms grant with with-transform-db-perms!, which also grants db-level create-queries :query-builder-and-native.
A db-level set deletes every row of that perm type - leaked table rows included - so the grant repairs any polluted state for the test and the scoped restore puts the prior rows back afterwards.
2026-09-01 09:39:30 +00:00
Andrei Simionescu
a1059fff57 BOT-2018: Support Anthropic fast mode for Metabot (#80511)
Admins can turn on fast mode for Metabot when the selected Anthropic model offers it. A rejected fast request falls back to standard speed and holds it for five minutes, so the speed and the cache prefix stay put.
2026-09-01 10:16:58 +01:00
Andrei Simionescu
3d5011e100 BOT-1668: hide the MCP server URL when the MCP server is disabled (#81195) 2026-09-01 10:08:38 +01:00
Timofey Kachalov
08b90a304c Escape and anchor the www. strip in CSP host allowlist (#81182) 2026-09-01 12:06:14 +04:00
Timofey Kachalov
49af71fd44 Validate embedding-app-origins-interactive before it reaches headers (#81166) 2026-09-01 12:05:48 +04:00
Nathan Voxland
e34951e8b7 Improve quoting and literal handling (#80254) 2026-09-01 00:35:52 -05:00
Fraser
8d618a8620 Viz loading slot and small moves (#81625) 2026-09-01 10:56:10 +12:00
YB
72edd1917c Bump mariadb-java-client to 2.7.15 (#81456)
bump mariadb-java-client to 2.7.15
2026-09-01 06:51:56 +08:00
YB
bb4b24c65f Bump httpclient5 to 5.6.4 (#81556)
bump httpclient5 to 5.6.4
2026-09-01 06:45:52 +08:00
Alexander Polyankin
baa2f30a5d Model the request scheme as https/http/unknown (#81592) 2026-08-31 18:22:12 -04:00
Alexander Polyankin
2742202af1 Restrict :param_fields in public/embed endpoints to public Field columns and enabled parameters (#81383) 2026-08-31 18:17:31 -04:00
Romeo Van Snick
2bd8150f2c Give the metadata mirror an enforced public API at metabase/metadata/store (#81272) 2026-09-01 09:12:14 +12:00
Ben Grabow
bd77074097 Migrate H2 -> SQLite sample db even when we're in new-install mode (#81596) 2026-08-31 15:58:10 -05:00
Chris Truter
a93af09ff5 Bump the remaining Hive artifacts to 4.2.1 (#81508)
4.2.1 is published for eight more of the Hive pins in the hive-like driver,
so move them along with hive-common rather than leaving the family split
across two patch versions.

hive-jdbc, hive-service and hive-hplsql stay at 4.2.0 -- no 4.2.1 was
published for those three.
2026-08-31 20:45:01 +00:00
Phoomparin Mano
c5e99eb320 Refresh MCP Apps UI credentials before expiry (#81041)
* fix broken mcp apps authentication due to credentials being cached

* add server-side tool calls to mint ui capability tokens

* rename MCP Apps credential metadata key

* rely on server tools for MCP Apps credentials

* show MCP Apps host errors

* add a test that we do not break existing chats

* fix transient MCP UI credential refresh failures

* combine credential refresh into a single tool

* refactor: extract ui credential constants

* refactor: simplify to a single refresh tool in frontend

* refactor: cleanup

* refactor: simplify unit tests

* refactor: use retry utility

* refactor: remove unused session-id

* chore: copy changes

* chore: rename method to redact-ui-credential

* remove v2 resource prefix

* add test for redacting secret in trace

* Harden MCP UI credential refresh after review (#81454)

* Harden MCP UI credential refresh lifecycle

* Harden MCP UI credential backend contracts

* Accept compatible MCP App resource URIs

* refactor: extract mcp auth hooks and utilities

---------

Co-authored-by: Chris Truter <crisptrutski@users.noreply.github.com>
2026-08-31 20:10:50 +00:00
Andrei Chernykh
4b8fca4eb0 Delete no-op resolutions entries (#81408) 2026-08-31 12:48:35 -07:00
Romeo Van Snick
0b035e3f44 Cut four of the common module's back-edges (#80052) 2026-09-01 07:40:16 +12:00
Chris Vandoodewaard
1b7226c27a Require job-level timeout-minutes in GitHub workflows (#80353)
* Add a lint check requiring job-level timeout-minutes in workflows

A job without `timeout-minutes` inherits GitHub's 6-hour default, so a hung
job burns six hours of runner time - and holds up everything queued behind it -
before anyone notices.

actionlint cannot enforce this: its rule set is compiled into the binary, and
`.github/actionlint.yaml` only accepts `self-hosted-runner`, `config-variables`,
and `paths`, the last of which suppresses findings rather than adding them. So
the rule lives in a small yq-based script instead.

It runs in the lint job next to actionlint, gated on the same workflow-file
filter and passed the same changed-file list, and emits `::error file=,line=::`
annotations. Jobs that call a reusable workflow are skipped, since GitHub
rejects `timeout-minutes` there.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* Fold the actionlint path filter into the workflows filter

The `actionlint` filter matched exactly the same paths as `workflows`, and the
lint job was the only consumer of it. Drop the duplicate and point the actionlint
steps at `workflows` / `workflows_files`.

Also give lint.yml's own snowplow job a 10 minute timeout, so the workflow
passes the check it adds.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* Stop yq shifting reported line numbers on files with header comments

yq slurps a leading comment block before parsing unless
--header-preprocess=false, so every line number it reported was short by the
size of that block. Five workflows start with a comment; on cache-warm.yml the
`warm` job was annotated at line 18 instead of 42.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

* Update .github/file-paths.yaml

Co-authored-by: Ryan Laurie <30528226+iethree@users.noreply.github.com>

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
Co-authored-by: Ryan Laurie <30528226+iethree@users.noreply.github.com>
2026-08-31 19:20:45 +00:00
dpsutton
fd707ac9a3 Cache parse-approved-origins to stop per-request Invalid-URL log spam (#81126)
`parse-approved-origins` runs on essentially every API response (via
`approved-origin?` in the security-headers middleware, and again in the MCP
origin check) and re-parses the whole CORS-origins allowlist each time. Any
entry that fails to parse -- e.g. a malformed `http://localhost:3000:*` saved
into the SDK/MCP origins setting -- hits `log/errorf "Invalid URL"` on every
request, producing bursts of identical errors around each dashboard load.

The allowlist strings are slow-moving globals, so LRU-cache the parse. Callers
pass a couple of distinct strings (the merged SDK+MCP allowlist, and the
MCP-only one), so a small LRU bound keeps both cached without either evicting
the other, while remaining bounded.


Claude-Session: https://claude.ai/code/session_01BjQcjQx7NPGr3Rpf6QaG4b

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-31 13:39:30 -05:00
Chris Truter
4f81af5691 Prevent missing search index tables from aborting caller transactions (#81573) 2026-08-31 20:33:20 +02:00
John Swanson
f2cef9e46c More clarity around revoking credentials when "base" entity is gone/deactivated (#80556)
* Fail closed when an OAuth token's client is gone

resolve-access-token looked up the access token, checked expiry, and read the
user id off the token row — but never consulted oauth_client. So an access
token kept authenticating even if the client had been deleted.

Require the token's client_id to still exist in oauth_client, using the
client_id already present in the fetched token data — one indexed lookup on the
bearer path, no schema change. A missing client now fails closed (401).

Tests:
- core-test: token resolves while its client exists, returns nil once the
  client row is deleted.
- session_oauth_test: register the referenced oauth_client so the bearer-bridge
  tests exercise the new client-existence check (previously they minted tokens
  against a client_id with no row).

* Revoke sessions and OAuth tokens on user deactivation

Add an `:event/user-credentials-revoked` event, emitted in the user
`before-update` hook when a user is deactivated, with two subscribers:

- session: delete the user's core_session rows
- oauth-server: mark the user's access and refresh tokens revoked_at

* Pin that an API key's lifecycle follows its synthetic user

An API key authenticates as its own synthetic user (api_key.user_id); the
creator_id column that records the admin who minted it is attribution only and
is never consulted at auth time. So deactivating that admin does not revoke the
key — which is the intended design: keys are org-level service credentials,
visible to and revocable by any admin from the API-key page, independent of who
created them. Revoke a key by deactivating its synthetic user
(DELETE /api/api-key/:id), not the human who minted it.

No behavior change. Add a regression test that pins this: a key survives its
creator's deactivation (200) but is revoked when its own synthetic user is
deactivated (401), so the two paths cannot be conflated by a future creator_id
join. The DELETE-endpoint revocation path is already covered by api-keys-work-e2e.

* Register the credentials-revoked topic in the events hierarchy

The events system validates topics against its own hierarchy in
metabase.events.hierarchy, not Clojure's global one, so the plain
derive calls left :event/user-credentials-revoked unregistered and
publish-event! threw a 500 whenever a user (or API key's synthetic
user) was deactivated. Use events/derive! like every other subscriber.
2026-08-31 11:29:45 -07:00
Chris Vandoodewaard
596e0c0f71 Fix for LTS tag causing minor release failure (#81038)
* filter lts versions when finding latest from tags

* always skip lts tag since it isn't valid for finding latest versions

* add guard for valid version to release-log

* add tests

* fix actionlint

* clean up/fix logic in release-log

* Keep returning the major version for rolling .x tags

getMajorVersionFromRef now recognizes v0.56.x / v0.51.2.x style tags in
addition to valid version strings, so only lts and non-version tags get
an empty string back.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-31 18:28:27 +00:00
Kevin Kelleher
8c3ea6f40b Remove Explorations dimension anchored blocks (#80554)
* remove dimension anchored blocks from FE

* Remove dimension-anchored blocks from the backend

Research-plan groups are now always a metric sliced by dimensions; the
dimension-anchored shape (one dimension slicing several metrics) is gone:

- add_research_groups: drop anchor/dimension_id/metric_ids, require metric_id
- remove_from_research_plan: members lose metric_ids; dimension_ids required
- research-groups validation: metric-only, anchor dispatch removed
- blocks-tree: no :type on nodes; "By <dimension>" headings and the
  same-name disambiguation machinery deleted
- BlockSelection/ExplorationBlockNode schemas lose :type; the
  exploration_block.type column is no longer written (left in place,
  nullable)
- explorations.selmer prompt rewritten for the single group shape

Legacy dimension-anchored rows keep rendering (as metric-headed blocks);
pinned by the new blocks_test regression test.

* more FE cleanup, fix tests

* Drop exploration_block.type column

---------

Co-authored-by: John Swanson <john.swanson@metabase.com>
Co-authored-by: Nathan Voxland <nathan@metabase.com>
2026-08-31 17:14:01 +00:00
bryan
72987c24bc Validate LDAP server certificates and normalize synced attributes (#81039) 2026-08-31 10:43:37 -06:00
Oleksandr Yakushev
105262e022 Bump Toucan2 to 1.0.575 (#81449) 2026-08-31 19:22:45 +03:00
Andrei Chernykh
883ff5c9ac Remove unused webpack deps, fix rspack invalidate path (#81390) 2026-08-31 09:20:25 -07:00
Andrei Chernykh
fa7e1e598a Remove json-to-pretty-yaml (#81085) 2026-08-31 09:11:28 -07:00
Andrei Chernykh
94f0aec2e9 Replace @cypress/skip-test with a local helper (#80947)
* Replace @cypress/skip-test with a local e2e helper

* Document --spec requirement in the e2e-test skill

* Tidy skip-test helper comments and skill doc wording
2026-08-31 09:08:47 -07:00
Chris Truter
2da893377b Fix the cancellation race in process-userland-query-test (#81560)
* Wait for the query to reach the reduce step before cancelling in cancel-test

cancel-test gave the query a fixed 100ms head start before future-cancel and
assumed it would be sleeping inside *reduce* by then. Only an interrupt that
lands inside *run*'s try posts ::cancel to the canceled channel, so whenever
pre-pipeline setup took longer than 100ms the future died silently during
setup and the test timed out waiting for the cancel message.

That made the test flaky under CI load and deterministically red when run in
isolation: on a fresh JVM the first query's setup takes seconds, so the
granular-rerun step (which re-runs only the failed test) could never pass it,
pinning any PR that flaked onto it. Synchronize on a promise delivered from
*reduce* instead of sleeping.

* Block on a latch instead of sleeping in *reduce*

The 1000ms sleep was a second timing assumption: the cancel had to arrive
within it or the reduce would complete and save the execution. Await a latch
nobody opens instead — the interrupt wakes it just like the sleep, with no
window to miss. The 30s timeout only bounds the worker thread if cancellation
is genuinely broken.

* Use a never-delivered promise and drop the dead *result* call

A promise is the same CountDownLatch under the hood (interrupt propagates
identically from deref) and matches the started promise next to it. The
*result* call after the block was unreachable on the happy path — the
interrupt throws out of the deref — and pointless on the timeout path, where
the test failed 28 seconds earlier.

* Collapse the port/val channel assertions into one

A timeout or closed channel takes nil, which fails against ::cancel on its
own — no need to name the winning port. Also fixes the doubled word in the
testing string.

* fix cancellation test cleanup race

* Clarify cancellation test scope

* Strengthen cancellation metadata assertion

* Polish cancellation test formatting
2026-08-31 17:49:57 +02:00
Mihael Konjević
e815f913d1 Update Metabot data-source guidance for stale references and curation signals (#78248)
Clean up stale, contradictory, and unreachable guidance in Metabot prompts and skills

- Remove references to tools/params that never existed (`search_tables`, `search_transforms`, `get_report_details`, doc-search tool, `collection_id`/`database_id` on search, `update_dashboard` mutations, `is_library_member`, dead `source_tables` param, duplicate Slackbot tool)
- Align per-profile guidance with actual tool wiring: SQL-only profile has no notebook/metric/chart tools, Slackbot has no `read_resource`, `construct_notebook_query` schema differs by profile, SQL query-link behavior differs by tool
- Fix `read_resource`: pagination bug (server now returns a ready-to-use `next-page-uri` instead of broken `?page=N` guidance), curation-signal comparison, container/document listing
- Fix a Selmer `{% safe %}` vs `{% verbatim %}` bug that silently blanked all `{{#model_id}}` examples in the SQL profile prompt
- Document previously-missing required arguments across several tools (`create/edit/replace_sql_query`, `edit_chart`, time-clause `unit`, etc.)
- Fix `document_schema_collect`'s unreachable stop instruction and missing `database_id`
- Fix `list_available_fields` fallback for saved questions
- Add regression tests locking in the template-rendering and pagination fixes
2026-08-31 17:45:35 +02:00
Mahatthana (Kelvin) Nomsawadi
63057ee485 Key guest embed tokens per instance instead of one shared slot (#81351)
* key guest embed tokens per instance instead of one shared slot

Concurrent guest StaticQuestion/StaticDashboard embeds under one
MetabaseProvider wrote into a single Redux rawToken slot, so the
last-mounted instance's token won for all of them. Key by a stable
per-mount instance id instead.

* refactor: name the guest token key mountId

instanceId read as the Metabase instance, and collided with
EnsureSingleInstance's own instanceId. Also simplify the two reducer
cases the fix rewrites, which Immer lets us assign into directly, and
drop a !mountId guard that currentToken already covers.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CkZ5rUUDeeWN9GU2wuEUHk

* test: drop the multi-dashboard guest token spec

It passed with the whole fix reverted to master: asserting each endpoint
was called at least once is already true there, because every mount's
first render uses its own token prop and only the re-render collides. The
name also implied multiple StaticDashboards work, which they never have —
they share one global state.dashboard slot.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CkZ5rUUDeeWN9GU2wuEUHk

* test: cover a guest refresh that switches resource

Every existing refresh case reissues a token for the same resource, so
none of them notice which token the component ends up using — PR #81240
flipped that precedence and CI stayed green. Switching to a question that
takes different parameters is what makes the choice observable.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01CkZ5rUUDeeWN9GU2wuEUHk

* fix: drop a guest mount's token when it unmounts

The iframe embed route re-keys its children when the token changes, so a
parent-side token update remounts the component with a fresh mountId.
Nothing removed the old entry, so Object.keys(...)[0] in
getOrRefreshGuestSession kept picking the dead mount and every request
was rewritten with its stale token. Once that token expired, the refresh
wrote back to the same dead key, so the map never recovered.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016stkr2R8EEPxp5gbyqDjdR

* test: cover a guest remount with a new token

Mounts a guest question, re-keys it with a second token the way the
iframe route does, and asserts the query goes out with the new token.
Fails without the unmount cleanup: no request reaches the new token's
url at all.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_016stkr2R8EEPxp5gbyqDjdR

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-31 15:21:19 +00:00
github-automation-metabase
38cc09d133 Auto-update documentation for master (#81576)
Update generated docs (master)

Co-authored-by: github-actions <github-actions@github.com>
2026-08-31 11:03:40 -04:00
John Swanson
ba823a5488 Include every attribute remapping in the sandbox FieldValues fingerprint (#81040)
The per-user sandbox fingerprint (the advanced-FieldValues cache key, and
the sandbox component of data-access tokens) narrowed the hashed login
attributes to remappings whose dimension target resolved to a field of the
sandboxed table itself. But the query processor applies *every* attribute
remapping when it runs the sandboxed query, including ones targeting
columns of tables joined inside the sandbox card, or columns referenced by
name. Those remappings were silently dropped from the fingerprint, so two
users whose sandboxes differed only by such an attribute hashed to the
same field_values row and were served each other's cached values (and
could read each other's stored exploration results via the colliding
data-access token).

Fix: fingerprint every key in attribute_remappings, regardless of what
its target resolves to. This exactly mirrors the set of attributes the QP
consumes, keeps unrelated login-attribute changes from busting the cache,
and leaves hashes for own-table-only sandboxes (the common case)
unchanged. Existing colliding rows become unreachable under the new hash
and are reaped by the delete-expired-advanced-field-values sync job.

Fixes SEC-874.
2026-08-31 07:41:06 -07:00
Ben Grabow
b7d74aab6d Fix order-dependent transform permissions in tests (#81404)
* Small correctness and hardening fixes

A handful of independent, low-risk fixes bundled together — each too small to
ship on its own, each a behavior improvement that also closes a minor
hardening gap.

Reduce DB load / avoid unconditional work:
- Settings cache: a settings-last-updated cookie now triggers a cheap
  single-row staleness check and reloads only if the cache is genuinely
  behind, instead of unconditionally reloading the whole settings table.
  Exposes restore-cache-if-needed! with a :force-check? option as the shared
  "reload if actually stale" primitive the cookie path now uses.

Reduce log noise:
- CORS origin validation runs on every request's raw Origin header, so it now
  parses that client-supplied value with the silent try-parse-url rather than
  the variant that logs "Invalid URL" at ERROR — a malformed Origin no longer
  fills the operator's error log. Parsing behavior is otherwise identical, so
  no CORS allow/deny decision changes.

Correctness (case-insensitivity):
- forgot_password throttles on the lower-cased email, matching the
  case-insensitive account lookup, so User@x and user@x share one bucket
  rather than each getting a fresh allowance.

Add a missing throttle:
- PUT /api/user/:id/password throttles the old_password re-auth check, which
  previously had none, bringing it in line with the other credential
  endpoints.

* Set create queries permission explicitly for transforms tests

---------

Co-authored-by: dan sutton <dan@dpsutton.com>
2026-08-31 09:32:26 -05:00
Jeff Bruemmer
e8b8ad1a88 docs - script to generate page for supported AI providers (#81101) 2026-08-31 09:57:51 -04:00
Jeff Bruemmer
a1c217c51b docs - embedded ai chat updates (#80940)
* ai chat

* edits

* edits

* split

* revisions

Co-authored-by: Jeff Bruemmer <jeffbruemmer@gmail.com>

* revisions

* custom error image
2026-08-31 09:57:02 -04:00
Alexander Polyankin
629fd1fee0 Encrypt only settings that are secret or integrity-critical (#81506) 2026-08-31 09:37:14 -04:00
Chris Truter
f332a4e4b2 Stamp private ECR images with their Git commit (#81557) 2026-08-31 15:05:46 +02:00
Mihael Konjević
1c7ac88006 Respect sandboxing, impersonation, and routing in Metabot metadata (#80723)
* Withhold fingerprint statistics from row-restricted users in get_field_values/read_resource

Fingerprints were read from the shared Field row and refingerprinted on demand with no
restriction gating -- the same leak #436 fixed in llm/context.clj, left open here. Gate
both behind a fail-closed, per-database-batched row-restricted-table-ids check, resolving
each Field's owning table canonically rather than trusting caller-supplied metadata.

Also guard list_available_fields, viewing-context entity lookups, and typed-schemas
table/card selection against destination-database resources, and apply a missing
permission-filter-columns pass to card-details' FK targets.

* Widen LLM schema-context row-restriction handling to sandboxing and routing

row-restricted-user? only checked impersonation and failed open on a feature/license
lapse. Replace it with metabot's fail-closed row-restricted-table-ids, applied per table so
one restricted table doesn't blank out fingerprints for the whole response.

Also filter a table's own sandbox-restricted columns (previously only FK targets were),
constrain mentioned/FK-target tables to the requested database, add a database read-check,
and cap+log restricted-table field-values fetches per table.

* Cover destination-DB exclusion in typed schemas; quiet expected 404s in viewing context

Adds test coverage proving select-schema-cards/select-tables actually exclude
tables and cards backed by a destination (routed) database from typed-schema
generation -- the only guard on that path, previously unverified.

Also stops fetch-and-format logging every expected 404 (missing entity, or a
destination-db routing guard) at ERROR level; it now logs at DEBUG and still
falls back to the simple entity rendering, same as before.

* Quiet expected destination-DB 404s in get_metadata

safe-fetch was logging every fetch failure at error level, including
the routing-destination-database 404s from check-table-resource-database
/check-card-resource-database, which are an expected outcome rather
than a bug. Matches the debug-level treatment already given to the
same case in agent/user_context.clj.

* Style pass: trim design-rationale docstrings, shorten oversized fns, wrap long lines

- row-restricted-by-db: move the retry-ladder rationale out of the docstring and
  onto the try/catch lines it explains.
- permission-filter-columns: extract column-table-id/field-visible?/caller-joined?/
  referenced-field-visible?/column-visible? as top-level private fns instead of
  closures, bringing the function back under ~20 lines.
- build-schema-context: extract drop-or-enrich-fingerprints.
- Wrap a handful of lines pushed past 120 chars by the with-cache nesting and new
  test fixtures.

No behavior change; same 83 tests (315 assertions) still pass.

* Fail closed on unresolvable table IDs in row-restricted-table-ids

A table ID that couldn't be resolved to a Table row silently fell out
of the per-database restriction map and defaulted to unrestricted,
contradicting the fail-closed contract this function documents.

* Log restriction-probe failures in row-restricted-by-db

All three exception paths in row-restricted-by-db were silent, so an
impersonation/routing attribute failure left no trace of why every
fingerprint for a database fell back to the per-table restriction path.

* Handle unrecognized get_field_values data_source gracefully

mu/defn schemas aren't enforced in production, so an LLM-supplied
data_source could reach a case with no default clause and throw
uncaught, failing the whole tool call. Widen the case (and its schema)
to cover "question"/"report" like field-values already does, and give
both the permission-check case and field-values a graceful fallback
for anything else.

* Return an agent-facing 404 for a field-id with no resolvable table

check-column-table-perms! used api/check-404, which throws without
:agent-error?, so handle-agent-error rethrows it and fails the whole
tool call. This is reachable from ordinary stale result_metadata (a
dropped column, or serdes drift), not just a malicious input.

* Apply restricted-field-values cap after the eligibility filter

The per-table cap on restricted-table FieldValues fetches was applied
to raw columns before filtering to those that should have FieldValues,
so ineligible columns ahead of an eligible one in the raw list could
consume its slot in the budget and leave it without values. Filter
first, then cap -- grouping by the persisted Field's own table_id
while at it, consistent with the permission checks elsewhere in this
namespace.

* Move database read-check out of the extract-sources/generate-sql prelude

fetch-accessible-tables-with-columns required database read access
unconditionally, so /extract-sources hard-403'd even when a caller only
wanted its independent :card_ids behavior. generate-sql is the path
that needs the 403, so move the check there via build-schema-context
and leave get-tables-with-columns (extract-sources) to return an
empty result instead.

* Exclude destination-DB cards and fieldless models from answer-sources

get-metrics-and-models had no destination-database guard, so a card
backed by a destination (routed) database could still reach
list_available_data_sources -- the same gap already closed for
get_metadata. Also omit models whose :fields end up empty after
permission filtering (no view-data access to their table) instead of
listing them as data sources with nothing queryable.
2026-08-31 14:44:47 +02:00
Rodrigo López Dato
7d46650cad Don't use app DB pool to probe for initial connectivity (#81271)
Prevents app DB misconfigurations from timing out by failing immediately
2026-08-31 08:17:54 -03:00
YB
24f4aec505 Bump hive-common to 4.2.1 in the hive-like driver (#81460)
bump hive-common to 4.2.1 in the hive-like driver
2026-08-31 17:15:55 +08:00
YB
c839a31539 Pin reactor-core 3.8.7 in the Snowflake driver (#81462)
pin reactor-core 3.8.7 in the snowflake driver
2026-08-31 17:15:03 +08:00
YB
3866917fba Bump jsoup to 1.23.2 (#81457)
bump jsoup to 1.23.2 and pin it in the snowflake driver
2026-08-31 17:14:28 +08:00
YB
1866aaccd9 Bump sshd-core to 2.19.0 (#81461)
bump sshd-core to 2.19.0
2026-08-31 17:14:17 +08:00
YB
52fa5626a2 Bump httpclient5 to 5.6.3 (#81459)
bump httpclient5 to 5.6.3 and pin it in the clickhouse and databricks drivers
2026-08-31 17:14:05 +08:00
YB
ad47b4094b Bump Netty to 4.1.137.Final / 4.2.17.Final in driver deps (#81458)
bump netty to 4.1.137.final and 4.2.17.final in driver deps
2026-08-31 17:13:55 +08:00
Alexander Polyankin
d568f38f1a Encrypt plaintext values of encrypted-at-rest columns on startup (#81498) 2026-08-31 00:12:53 -04:00
Alexander Polyankin
0c54590106 Read settings without the cache while reconciling their encryption (#81491) 2026-08-30 23:02:41 -04:00
Alexander Polyankin
840faeb408 Reconcile settings encryption with the registry on every startup (#81478) 2026-08-30 21:38:46 -04:00
Alexander Polyankin
172bc22044 Name the source in strict-decrypt read failures (#81471) 2026-08-30 17:25:28 -04:00
Alexander Polyankin
c5878f2509 Encrypt legacy plaintext rows of :setter :none settings (#81464) 2026-08-30 15:25:34 -04:00
Ben Grabow
1e78c186c0 Improve log output in DWH GC job (#81447) 2026-08-29 04:05:59 +00:00
Alexander Polyankin
6b9bcaca8e Never encrypt the app DB on startup when there is existing data; add enable-encryption command (#81237) 2026-08-28 22:05:19 -04:00
John Swanson
418fbf1bf9 Treat API-key users consistently across user endpoints and attributes (#78976)
* Treat API-key users consistently across user endpoints and attributes

API keys are backed by rows in core_user with type = 'api-key'. Most
/api/user endpoints already restrict themselves to personal users, but
a few didn't, and user attributes were resolved for all user types.
Align everything on the rule that only personal users are managed via
/api/user and only personal users carry attributes:

- GET /api/user/:id and PUT /api/user/:id now 404 for non-personal
  users (API-key users and the internal user), matching the sibling
  endpoints (password, reactivate, password-reset-url, delete, modal)
  and the list endpoint's existing type = 'personal' filter. API keys
  are managed via /api/api-key instead.
- EE PUT /api/mt/user/:id/attributes now 404s for non-personal users.
- user/add-attributes only resolves attributes (tenant + jwt + login)
  for personal users; other types resolve to {}. Sandboxed queries run
  by a non-personal user therefore report a missing user attribute
  rather than reading attributes stored on the user row.

No migration: any pre-existing login_attributes on API-key rows are
left in place but no longer take effect. GET /api/user/current still
works for API-key authentication, with an unchanged response shape.

Scoped programmatic access as a first-class feature is tracked
separately in #72959.

* Provide a schema for `/api/user/current`

* Update kondo ratchet budgets

- :metabase/validate-defendpoint-has-response-schema 441 -> 440, since
  GET /api/user/current now has a response schema.
- :discouraged-var 100 -> 101 for the mt/with-temp ignore in the new
  sandboxing test: it creates a :model/User, which metadata providers
  do not support, matching the exception documented in the linter
  message and the file's existing ignores.

* CR resp - throw on missing `:type`
2026-08-28 15:41:39 -07:00
Ryan Laurie
7293988a96 dont refresh dynamic snowflake tables (#79846)
# Conflicts:
#	modules/drivers/snowflake/test/metabase/driver/snowflake_test.clj
2026-08-28 22:32:27 +00:00
Timofey Kachalov
e925a8df94 Temporarily disable Shoppy sample app tests (#81416) 2026-08-28 15:53:59 -06:00
Fraser
a0d5c5a0c7 Create the viz-core module (#80786) 2026-08-29 09:53:45 +12:00
Ryan Laurie
441cfa66ef Add Databricks Workspace Sharding (#81241)
* add env sharding for databricks

* follow the rules

* kick ci

* kick ci

* make the console output nicer
2026-08-28 15:15:46 -06:00
Timofey Kachalov
01add7e6e2 Fix per-table permission queries in db metadata endpoint (#81397) 2026-08-29 00:54:55 +04:00
appleby
e023152e90 Send finish-reason length for a Gemini MAX_TOKENS truncation (#80959)
* Send finish-reason length for a Gemini MAX_TOKENS truncation

Translate Gemini finishReason values to AI SDK v5 finish reasons and add them to the `:usage` chunk, as the other
adapters do. `MAX_TOKENS` now reports `:finish-reason "length"` instead of an in-stream error part, so the agent loop
stops cleanly and the client can offer to continue.

* Add missing image-related stop-reasons to gemini provider

The image related stop reasons should happen in practice since we only do text generation, but add them for
completeness.

https://docs.cloud.google.com/gemini-enterprise-agent-platform/reference/rest/v1/GenerateContentResponse#FinishReason

* Add stop-reasons from the Gemini Developer API as well

https://github.com/metabase/metabase/pull/80959#discussion_r3867216474
https://ai.google.dev/api/generate-content#FinishReason

* Review feedback: only add synthetic usage part for finish-reasons-without-error

* Review feedback: name the early-stop-without-error subset
2026-08-28 13:27:23 -07:00
Anderson
e9235e2983 Fix flaky remote-sync branch-switch e2e test (#80397)
* Deterministically gate remote-sync branch-switch test on its async boundaries

* Sign in before activating the token in the admin settings describe

* Wait for collection items responses before asserting synced content

* Reword test comments per writing conventions

* Trim comments and move timeouts to request/test-level options

* Remove test comments and restore waitForTask retries cap

* Fix H2 deadlock between the post-import search reindex and readers

* Additional cleanup

* Cover the in-task H2 reindex with a unit test

* Consolidate remote-sync e2e setup into a shared helper
2026-08-28 16:54:53 -03:00
appleby
5bf02e30d7 Support Anthropic partner models via the Google provider (#80133)
* Support Anthropic partner models via the Google provider

Anthropic models are served by `streamRawPredict` with an Anthropic Messages body, so route them through the new
`metabase.metabot.self.google.raw-predict` namespace, which wraps the existing claude adapter. Connecting probes the
model's own `streamRawPredict` route with an empty body: Google resolves the credential, project, location and model
from the URL before Anthropic sees the body, so an Anthropic-shaped 400 validates all four without spending a tokens.

* Title-case the Gemini model display names

To match the convention for all other providers and models.

* Translate mid-stream failures on the Google provider

`google-raw` handed back the SSE reducible unwrapped, so a failure while the agent loop consumed it escaped the
adapter untranslated and surfaced as a raw 500. Wrap it in `core/reducible-with-api-errors`, like every other adapter.

* Carry the probed model in :learned-config

We already reported `:probed-model` as sibling of `:learned-config`. Nest it inside so that it gets saved with the
learned config so we can use it for subsequent connection probes for the Google provider. This tends to be a much
better guess for what model we should use for the connection test rather than just using the first model in the fixed
models list, since there is no guarantee that model is actually present in the currently configured location.

* Probe a Google connection against the model it serves

The listing path re-probed whichever model the fixed catalog names first, so a connection at a location serving Claude
but not Gemini 3.x saved fine and then reported itself broken the moment its cache entry expired. Probe the model the
connection is known to serve instead — the one Metabot is pointed at, or the `:probed-model` its last successful probe
recorded — and fall back to the catalog's first model only when it has neither.

* Start the edit form on the model the connection was probed against

Reopening a connection while Metabot points elsewhere reset the Model picker to the type default and submitted that as
the probe target, so a Google project whose location serves Anthropic partner models but not Gemini had a no-op edit
rejected against credentials that work. Fall back to the connection's own probed-model, when the catalog still offers
it, before the type default.

* Ensure the obfuscated-value? regex matches values ending in newline

Enable "dotall" mode for the obfuscated-value? regex to support obfuscated values where one of the last two chars is a
newline. For example, the contents of JSON service account key used for Google cloud auth or similar.

https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/util/regex/Pattern.html#DOTALL

* Review feedback: validate-google-model!

* Review feedback: use proposed-model in vllm list-models

* Review feedback: ensure new-value is not an obfuscated-value? in set-single-provider-setting!

* Add comment about `model->family` dispatch

Co-authored-by: Chris Truter <crisptrutski@users.noreply.github.com>

---------

Co-authored-by: Chris Truter <crisptrutski@users.noreply.github.com>
2026-08-28 11:54:39 -07:00
John Swanson
cb7c71d1ba Allow embedding readable cards in documents without adhoc query-authoring perms (#80775)
Allow embedding readable cards in documents without query-authoring perms (UXW-5037)

Saving a document clones every embedded existing card into a document-owned
card row. The clone path ran check-run-permissions-for-query on the cloned
query, which for a native query demands create-queries=query-builder-and-native
on the whole database. A user who could view (and run) an existing native
question therefore could not save a document embedding it, losing their work
with a vague 403.

That check is an authoring gate, but the embedding user is not authoring a
query: the query text comes from an existing card row they passed a read
check on -- the client supplies only a card ID, never SQL. Running the clone
is still gated by the usual runtime permission checks (card read perms,
result-metadata view-data, block perms), which are the same checks that gate
running the source card, so cloning grants no new runtime capability. This
mirrors POST /api/card/:id/copy, which likewise clones a readable card
without an authoring check.

Split the documents-API card creation helper into create-card! (still
checked; used for client-supplied draft cards) and clone-card! (used when
cloning embedded cards and when copying a document's cards). Authoring a new
query -- via draft cards or by editing a cloned card's query through
PUT /api/card/:id -- still requires the appropriate query permissions.
2026-08-28 11:35:40 -07:00
Ben Grabow
2bfd318907 Dwh gc parallel (#81382)
* Bump timeout to 60 minutes

* Run redshift GC in parallel, with 1 worker per cluster node

* Run snowflake GC with N=8 parallelism

* Record dataset census before GC sweep

* Satisfy the linter
2026-08-28 13:27:49 -05:00
John Swanson
4c62275732 Hide all tenant groups/users from perms graph api (#74973)
* More consistently hide tenant users/groups

There were a few locations where we weren't correctly hiding the
existence of Tenant Groups such as "All Tenant Users" when the setting
was turned off. This also hides tenant *users* from the API surface.

* allow specifically showing tenant users

I realized that there was a possible regression in the last commit. We
were hiding tenant users across the board. This meant that a workflow
that was previously possible was not possible anymore:

- an admin turns off the tenant feature or disables tenants

- then the admin uses the API to reactivate some tenant users and turn
  them into internal users.

This is probably super niche anyway but it seems nicer to allow `GET
/api/user` to show these users, IF you pass the
`tenancy=external&status=all` flags.

Then you can reactivate the user and detach them from the tenant.

This is all API only so it's probably academic, but figured I'd keep the
door open.

* fix tests

* fix e2e tests

* Move tenant tests to enterprise tenant test namespaces

* Address review feedback on tenant-group hiding

- Rewrite hidden-tenant-group-ids to intersect the input IDs with all
  tenant-group PKs in memory instead of building an unbounded IN clause
- Return 404 from PUT/DELETE /api/permissions/group/:group-id for hidden
  tenant groups, matching GET /api/permissions/group/:id
- Assert GET /permissions/graph/group/:id succeeds when use-tenants is on
- Remove duplicate create-tenant-group-requires-use-tenants-test
2026-08-28 11:26:13 -07:00
John Swanson
2971a5b944 Strip client-supplied :card before hydrating in update-dashcards! (#73104)
`dashboard/update-dashcards!` calls `(params/dashcards->param-field-ids
(t2/hydrate new-dashcards :card))` to compute the field IDs referenced by
parameter mappings. `t2/hydrate` is a no-op when `:card` is already present
on a dashcard, so if the client `PUT`s `/api/dashboard/:id` with a dashcard
that includes a nested `:card` (the standard shape from `GET`), that object
is forwarded verbatim into `param-target->field-id`.

That function validates its `card` arg against `:metabase.queries.schema/card`
(added Oct 2025), which requires keywordized metadata (`:type/Category`,
`:source/table-defaults`, ...). After JSON round-trip through
`cy.request`, those values are strings, so the request 500s with
`Invalid input: {:result_metadata [{:semantic_type [...]}]}`.

`dissoc :card` before the hydrate call forces a fresh DB select with
properly-typed metadata, keeping the on-demand-DB field-value update path
unchanged.

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-08-28 11:24:38 -07:00
dpsutton
439b8e2af5 Small correctness and hardening fixes (#81374)
A handful of independent, low-risk fixes bundled together — each too small to
ship on its own, each a behavior improvement that also closes a minor
hardening gap.

Reduce DB load / avoid unconditional work:
- Settings cache: a settings-last-updated cookie now triggers a cheap
  single-row staleness check and reloads only if the cache is genuinely
  behind, instead of unconditionally reloading the whole settings table.
  Exposes restore-cache-if-needed! with a :force-check? option as the shared
  "reload if actually stale" primitive the cookie path now uses.

Reduce log noise:
- CORS origin validation runs on every request's raw Origin header, so it now
  parses that client-supplied value with the silent try-parse-url rather than
  the variant that logs "Invalid URL" at ERROR — a malformed Origin no longer
  fills the operator's error log. Parsing behavior is otherwise identical, so
  no CORS allow/deny decision changes.

Correctness (case-insensitivity):
- forgot_password throttles on the lower-cased email, matching the
  case-insensitive account lookup, so User@x and user@x share one bucket
  rather than each getting a fresh allowance.

Add a missing throttle:
- PUT /api/user/:id/password throttles the old_password re-auth check, which
  previously had none, bringing it in line with the other credential
  endpoints.
2026-08-28 13:13:31 -05:00
Ben Grabow
8861e84d3f Cache clojure cli download (#81369) 2026-08-28 12:24:22 -05:00
Ben Grabow
0cad99631a Fix flaky query executions test (#81366)
* Flush other executions before test. Divert other executions during test.

* Flush after closing the batch ingress path.

* Remove extraneous changes

* Remove more extraneous changes
2026-08-28 12:04:12 -05:00
Nathan Voxland
393086c44a Don't allow reset password for deactivated accounts (#78699) 2026-08-28 11:32:14 -05:00
Ryan Laurie
7e3ab7a682 Cleanup data warehouses nightly (#79849)
* cleanup data warehouses nightly

* rename

* don't reinvent wheels

* simplify

* more

* cleanup

* updates

* Absorb failures at the redshift cluster level and at the driver level

* Extract old dataset name pattern

* Update ratchets

* Merge MB_REDSHIFT_TEST_HOSTS and MB_REDSHIFT_TEST_HOST when both are set

* Allow ad-hoc dispatch and report on outcomes of gc sweeps

* Don't run on forks

* Update ratchets

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: Ben Grabow <ben.grabow@gmail.com>
2026-08-28 10:09:56 -05:00
Sébastien
e56d3de794 Wait for the content-translation dictionary in the SDK rerender spec (#81352) 2026-08-28 16:55:31 +02:00
github-automation-metabase
c06c3b8f16 Make isRenderedWithinViewport retry until element settles in viewport (#77401)
Make isRenderedWithinViewport retry until element settles in viewport

The command read getBoundingClientRect() once, so a caller asserting right
after a scroll-into-view action (focusing a recently moved dashboard filter)
could observe the element mid-scroll (top ~1647px vs 800px viewport) and fail.
Wrapping the geometry checks in .should() lets Cypress re-read the rect until
it lands within the viewport.
2026-08-28 16:19:42 +02:00
Nicola Mometto
190dcf1bd0 Compute longest common substring length with an iterative O(n*m) pass (#80985)
* Compute longest common substring length with an iterative O(n*m) pass

* Add perf edge-case tests for largest-common-subseq-length
2026-08-28 14:55:29 +01:00
Mihael Konjević
4fc305fa64 fix: recognize lib/*-stripped pMBQL in ->legacy-mbql, restore edit-chart's query-id (#78798)
* fix: recognize lib/*-stripped pMBQL in ->legacy-mbql, restore edit-chart's query-id

->legacy-mbql gated pMBQL->legacy conversion on :lib/type alone, so a query that
lost its :lib/* keys (e.g. round-tripped through the frontend's viewing context)
fell through unconverted. The raw pMBQL then got embedded in /question# links,
crashing the frontend with "Stage 0 does not exist". Detect pMBQL structurally
(:lib/type or :stages) and normalize against the query schema before converting.

Also add the query-id edit-chart's result was missing, so extract-charts can
capture edited charts into conversation state and chart->xml stops rendering
an empty query-id attribute.

* fix: preserve edit-chart's query in memory, don't fail turn on link conversion

edit-chart's result set :query-id without :query, so extract-charts (which
requires both to fire, then rebuilds :queries from :query alone) overwrote
the chart's real queries with [nil] on the next update-memory call.

->legacy-mbql could also throw instead of degrading: normalizing a
:lib/*-stripped query mints fresh :lib/uuids that don't match positional
aggregation/expression refs elsewhere in the query (e.g. an order-by on the
query's own aggregation), failing conversion inside the streaming transducer
and taking down the whole agent turn instead of just producing a bad link.
Falls back to the raw query on conversion failure now.

* fix: document ->legacy-mbql's conversion-failure fallback

Docstring claimed conversion always succeeds after normalize, but the
try/catch fallback added earlier can still return raw pMBQL when a
stripped query's positional refs don't resolve.

* test: mark edit-chart-result-survives-update-memory-test ^:parallel

Doesn't write shared state, same as the test above it.

* fix: thread edit-chart-tool's resolved query into edit-chart

edit-chart-tool falls back to current-queries-state when a chart's own
:queries is empty, but edit-chart only checked charts-state, so its
result carried :query-id with a nil :query in that case -- the same
[nil]-in-memory bug fixed earlier, via a different path. Pass the
caller's resolved query through as a fallback.

* fix: capture viewing-context charts' query-id, don't clobber on edit

chart-config->chart never set :query_id, so a chart seeded from viewing
context rendered query-id="" on edit and was never captured into :charts
state by extract-charts. Reuse the context-item id already shared with
:chart_id.

That capture also collided with edit-chart-tool's own memory write for
the same chart-id: extract-charts fully replaced the entry, dropping
:image_base_64/:timeline_events/:chart_config the tool had just written.
Merge onto the existing entry instead.

* fix: separate ->legacy-mbql's docstring from its bug history

Docstring for ->legacy-mbql read as the change's rationale (BOT-1604,
the :stages detection story) rather than the function's contract.
Trim the docstring to what a caller needs -- normalizes MBQL 5 to
legacy, passes through unchanged on failure -- and move the "why"
for the :stages guard down to an inline comment next to the check.
2026-08-28 15:10:46 +02:00
Stas Gavrylov
daf31c8bc3 Fix lint-eslint-pure warning noise in fresh worktrees (#81214)
Remove stale /* eslint-env node */ comments from frontend/build files

Flat config ignores eslint-env comments (ESLintEnvWarning per file, hard
errors as of ESLint v10), and they are redundant: eslint.config.mjs already
defines globals.node for frontend/build/**/*.js.
2026-08-28 16:08:27 +03:00
John Swanson
cfd6896c17 respect default time dimensions from list of dimensions (#79167)
* respect default time dimensions from list of dimensions

* Curate a default time dimension on the time-facet test fixture

Master's #79409 stopped auto-assigning a default dimension to new
metrics, so the time-facet tests' fixture card no longer gets a default
time dimension from dimension auto-sync. Since this branch makes the
curated default authoritative for the time-facet variant (no fallback to
the query's temporal breakout), curate the default explicitly on the
fixture.
2026-08-28 05:32:29 -07:00
YB
847666c6d1 [GDGT-2528] return an actionable error when an export target id does not exist (#80809)
return an actionable error when a serialization export target id does not exist
2026-08-28 20:27:13 +08:00
John Swanson
bb2b9786f3 Make register-listeners! idempotent, mirroring the queue-declaration fix (#80887)
The earlier fix (#80388) made *queue declarations* reload-safe by guarding
them with a load-time ownership claim and replace-on-reregister semantics,
but left the *listener* registry non-idempotent: register-listener! threw
"Listener already registered" whenever the channel was already present in
the root *listeners* atom.

Fix mirrors the queue side exactly: def-listener! now claims its channel's
declaration site at load time (claim-listener-declaration! — same-ns
re-claims are no-ops so reloads stay legal, cross-ns claims throw), and
activates through register-declared-listener!, which replaces any existing
registration instead of throwing. Ad-hoc batch-listen! keeps its strict
throw-on-duplicate contract (double-listen-throws-test et al.), since
runtime registrations have no load-time claim protecting them.
2026-08-28 05:01:03 -07:00
Romeo Van Snick
57ac36ff71 Match permissions URLs for databases without schemas (#81332) 2026-08-28 11:25:40 +00:00
Timofey Kachalov
8b42f49288 Normalize instance-origin matching when filtering data-app allowed_hosts (#81106) 2026-08-28 15:14:37 +04:00
YB
3ef8df323a Bump Bouncy Castle to 1.85.2 (#81287)
bump bouncy castle to 1.85.2
2026-08-28 18:44:37 +08:00
Alexander Polyankin
8b478a76ab Encrypt subscription/alert recipient details; enforce allow-list on send (#81227)
* Encrypt subscription/alert recipient details; enforce allow-list on send

Encrypt at rest the `details` column of `notification_recipient` and
`pulse_channel`, which stores external email recipients for alerts and
dashboard subscriptions, so plaintext values are rejected on the strict
read when an encryption key is configured. Register both columns in
`encrypted-string-columns` so `encrypt-db`/`decrypt-db` and key rotation
re-encrypt them, and add a v58 migration that encrypts existing rows and
decrypts them on rollback.

Also enforce `subscription-allowed-domains` at send time (previously only
on write): the notification send path calls `validate-email-handlers!`
before delivery and throws if any external recipient is not permitted by
the allow-list. The exception is re-thrown with a generic message so
recipient addresses are never written to the logs.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* Move the v58 pulse_channel encryption migration test into the v58 group

order-your-migration-tests-test requires migration tests to be grouped by
major version in ascending order; the new test had landed among the v48 tests.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-28 12:19:26 +02:00
Sébastien
ed6247eb24 Fix collapsed visualization in the dashboard new-question query builder (#81163) 2026-08-28 10:10:07 +02:00
Chris Truter
53a31166db Justify the grandfathered kondo ignores (#78168)
* Justify the :metabase/discourage-millis-duration ignores

Claude-Session: https://claude.ai/code/session_01GParLfcfdFBwFrdzUWjGJN

* Justify the :reduce-without-init ignores

Claude-Session: https://claude.ai/code/session_01GParLfcfdFBwFrdzUWjGJN

* Justify the :def-fn ignores

Claude-Session: https://claude.ai/code/session_01GParLfcfdFBwFrdzUWjGJN

* Justify the :unquote-not-syntax-quoted ignores

Claude-Session: https://claude.ai/code/session_01GParLfcfdFBwFrdzUWjGJN

* Justify the :aliased-namespace-symbol ignores

Claude-Session: https://claude.ai/code/session_01GParLfcfdFBwFrdzUWjGJN

* Justify the :equals-true ignores

Claude-Session: https://claude.ai/code/session_01GParLfcfdFBwFrdzUWjGJN

* Justify the :case-symbol-test ignores

Claude-Session: https://claude.ai/code/session_01GParLfcfdFBwFrdzUWjGJN

* Justify the :metabase/prefer-with-dynamic-fn-redefs ignores

Claude-Session: https://claude.ai/code/session_01GParLfcfdFBwFrdzUWjGJN

* Justify the :syntax ignores

Claude-Session: https://claude.ai/code/session_01GParLfcfdFBwFrdzUWjGJN

* Justify the :unused-binding ignores

Claude-Session: https://claude.ai/code/session_01GParLfcfdFBwFrdzUWjGJN

* Justify the :unused-private-var ignores

Claude-Session: https://claude.ai/code/session_01GParLfcfdFBwFrdzUWjGJN

* Justify the :unresolved-symbol ignores

Claude-Session: https://claude.ai/code/session_01GParLfcfdFBwFrdzUWjGJN

* Justify the :unused-excluded-var ignores

Claude-Session: https://claude.ai/code/session_01GParLfcfdFBwFrdzUWjGJN

* Justify the :unresolved-namespace ignores

Claude-Session: https://claude.ai/code/session_01GParLfcfdFBwFrdzUWjGJN

* Justify the :unresolved-require ignores

Claude-Session: https://claude.ai/code/session_01GParLfcfdFBwFrdzUWjGJN

* Justify the :unused-value ignores

Claude-Session: https://claude.ai/code/session_01GParLfcfdFBwFrdzUWjGJN

* Justify the :unused-alias ignores

Claude-Session: https://claude.ai/code/session_01GParLfcfdFBwFrdzUWjGJN

* Justify the :metabase/namespace-name ignores

Claude-Session: https://claude.ai/code/session_01GParLfcfdFBwFrdzUWjGJN

* Justify the :missing-docstring ignores

Claude-Session: https://claude.ai/code/session_01GParLfcfdFBwFrdzUWjGJN

* Justify the :metabase/defsetting-namespace ignores

Claude-Session: https://claude.ai/code/session_01GParLfcfdFBwFrdzUWjGJN

* Justify the :metabase/validate-deftest ignores

Claude-Session: https://claude.ai/code/session_01GParLfcfdFBwFrdzUWjGJN

* Justify the :missing-protocol-method ignores

Claude-Session: https://claude.ai/code/session_01GParLfcfdFBwFrdzUWjGJN

* Justify the :discouraged-java-method ignores

Claude-Session: https://claude.ai/code/session_01GParLfcfdFBwFrdzUWjGJN

* Justify the :clojure-lsp/unused-public-var ignores

Claude-Session: https://claude.ai/code/session_01GParLfcfdFBwFrdzUWjGJN

* Justify the :metabase/modules ignores

Claude-Session: https://claude.ai/code/session_01GParLfcfdFBwFrdzUWjGJN

* Justify the :metabase/i-like-making-cams-eyes-bleed-with-horrifically-long-tests ignores

Claude-Session: https://claude.ai/code/session_01GParLfcfdFBwFrdzUWjGJN

* Justify the :metabase/test-helpers-use-non-thread-safe-functions ignores

Claude-Session: https://claude.ai/code/session_01GParLfcfdFBwFrdzUWjGJN

* Justify the bare :clj-kondo/ignore forms

Claude-Session: https://claude.ai/code/session_01GParLfcfdFBwFrdzUWjGJN

* Justify the :discouraged-namespace ignores

Claude-Session: https://claude.ai/code/session_01GParLfcfdFBwFrdzUWjGJN

* Justify the :deprecated-namespace ignores

Claude-Session: https://claude.ai/code/session_01GParLfcfdFBwFrdzUWjGJN

* Justify the :deprecated-var ignores

Claude-Session: https://claude.ai/code/session_01GParLfcfdFBwFrdzUWjGJN

* Justify the :discouraged-var ignores

Claude-Session: https://claude.ai/code/session_01GParLfcfdFBwFrdzUWjGJN

* Correct inaccurate justification comments from review

Reword the overclaims the review round caught: 'every render path'
and 'every test-query feature' scoped to what the tests cover, the
'mutates nothing' datasource comments acknowledge lazy pool init, the
'only channel' store comments name the pending general-cached-value
migration, the ASCII-makes-default-locale-safe clauses dropped
(Turkish casing changes ASCII I), and the accidentally-justified
import-vars ignore in metabase.test gets a real comment. Contested
claims move to the uncertain list rather than guessing.

Claude-Session: https://claude.ai/code/session_01GParLfcfdFBwFrdzUWjGJN

* Use Locale/US casing directly; drop the ignores it obsoletes

The review round was right that the circular-dep comments didn't
justify locale-sensitive casing: a Turkish default locale lowercases
ASCII I to a dotless i, mangling locale codes like "ID" and hiding
"Windows" from the os.name probe. Call .toLowerCase/.toUpperCase
with Locale/US at both sites, which removes the :discouraged-var
ignores entirely instead of excusing them. The logger comment now
states the real invariant: the notice reports logger reconfiguration
itself, so it can't go through log4j.

Claude-Session: https://claude.ai/code/session_01GParLfcfdFBwFrdzUWjGJN

* Correct remaining kondo justification comments

* Correct four justification comments from CodeRabbit review

* Correct the qp.store justification: the mbql5 shim reads the store too

* Complete kondo justification coverage

* Keep the named ignore forms while justifying them

The per-linter sweep was written when these sites still used the bare
`#_:clj-kondo/ignore`, so replaying it over the naming branch put the bare
form back under each new comment. Restore the linter vectors and rebuild
the budgets: :comment-exempt lands at 10, down from the 38 the mechanism
starts with.

* Justify the ignores master added under the exempted linters

The restack picked up new :deprecated-var and :clojure-lsp/unused-public-var
ignores from master. Left unjustified they would have re-exempted both linters,
undoing what this branch is for.

* Regenerate kondo ignore budgets after restacking onto master
2026-08-28 05:59:14 +00:00
Chris Truter
72d6cfe9cd Fail fast when a test loses its rollback boundary (#80994)
Fail the test when a rollback-only scope cannot roll back

Every top-level `with-temp` runs in a rollback-only transaction. If something
inside one commits -- DDL does that implicitly on H2 and MySQL, which also
destroys the savepoint -- the rows written up to that point are durable and
leak into every later test. Warning about it hides the leak until some
unrelated test counts rows and gets the wrong answer, and the six offending
sites found so far were caught exactly that way.

Throw instead when running tests. That covers every cause -- raw SQL DDL,
HoneySQL DDL, a savepoint lost to a deadlock -- where a guard on the SQL we
build would miss the raw statements `drop-table!` sends. Production keeps
warning and discarding what is still pending: there the transaction is a real
one that has already committed, and failing the request would not undo it.
2026-08-28 05:53:46 +00:00
technomancy
f9008f7884 Disable databricks JDBC driver's auto-retry. (#81231)
It sucks!

We will need to put our own error handling in place to do Actually
Good retries for 429s, but it's not clear yet where the best place for
that would be, because we're not getting stack traces from the 429s currently.
2026-08-28 00:05:28 -05:00
Romeo Van Snick
e6e11ee362 Write the metadata mirror from one listener, not 33 endpoint hookups (#81147)
* Write the metadata mirror from one listener, not 33 endpoint hookups

* Describe the hydration listener by what it does, not what it replaced

* Point the original_fields note at the listener, not onQueryStarted

* Pin the hydration listener to Api actions, and report a failed write
2026-08-28 13:16:41 +10:00
Romeo Van Snick
41cd2ab4f7 Name the chunks that lazy routes load (#80970) 2026-08-28 11:46:56 +10:00
Ben Grabow
f73eb6d00e Filter server-side when all target schemas are exactly named (#81250)
* Filter server-side when all target schemas are exactly named

* Blacklist metacharacters instead of whitelist word characters
2026-08-27 17:04:19 -07:00
Romeo Van Snick
21024ec984 Keep MCP node_modules out of the shared vendor chunk (#81157) 2026-08-28 09:40:04 +10:00
Fraser
a7815e9354 Give query_builder a store/ folder and an enforced public API (#79965) 2026-08-28 11:26:07 +12:00
Andrei Chernykh
e819ade161 bump dompurify to 3.4.14; removed from resolutions (#81228) 2026-08-27 15:19:20 -07:00
Nathan Voxland
0163ebfd7a Don't drop column order/visibility settings when one column no longer matches (#76088) 2026-08-27 16:18:30 -05:00
Cam Saul
27852dcc4c Resolve columns from model metadata saved in ~<=55 correctly (#75771)
* Resolve columns from model metadata saved in ~<=55 correctly

* Remove annoying :lib/options in stages and joins

* Test fix 🔧

* Code cleanup

* Comments

* Fix typo

* Revert pointless changes

* Try something different??

* Test fix 🔧

* Will disabling unneeded change fix e2e tests??

* Simplified fix 🔧

* PR Feedback

* cljfmt

* Test fix 🔧
2026-08-27 13:13:48 -07:00
Nathan Voxland
9eb4ce8524 Session Management (#80243) 2026-08-27 14:35:22 -05:00
github-automation-metabase
a9337e6046 Auto-update documentation for master (#81128)
Update generated docs (master)

Co-authored-by: github-actions <github-actions@github.com>
2026-08-27 15:33:00 -04:00
John Swanson
96faa6d511 re-check read permission when listing bookmarks (#80774)
SEC-669: re-check read permission when listing bookmarks

GET /api/bookmark (bookmarks-for-user) filtered only on the target's
archived column and never re-checked read permission, so a bookmark kept
leaking a card/dashboard/collection/document/exploration's name,
description, and type after the user lost read access without the item
being archived (moved to a private collection, or a revoked/narrowed
collection grant).

Add a visible_collection_ids CTE (permissions only; archived filtering is
left to the existing where-conditions) and filter each bookmark branch by
collection visibility via visible-collection-filter-clause. Visibility is
evaluated for the passed user-id via a UserScope, so the function is
correct for any user, not only the current request's user.
2026-08-27 12:28:20 -07:00
Uladzimir Havenchyk
dff2fd94ce chore: replace lodash.orderby with inline function (#81160)
* chore: replace lodash.orderby with inline function

* drop deps

* fix eslint
2026-08-27 22:15:20 +03:00
Nathan Voxland
a25cc1f7be Improve oracle parsing (#80043) 2026-08-27 14:12:55 -05:00
Nathan Voxland
5c63c45970 Better error handling on result_metadata.settings (#80909) 2026-08-27 14:12:10 -05:00
Andrei Chernykh
cb3d067c6e Bump js-yaml to 4.3.1 (#81229) 2026-08-27 12:10:32 -07:00
Andrei Chernykh
3ac0958c50 Replace @sinonjs/fake-timers with a local Date mock (#80930) 2026-08-27 11:46:36 -07:00
Egor Grushin
05300912fb Radio component redesign (#80372)
* Redesign Radio

* Add Radio stories to loki filter

* disallow radio labelPosition

* use StoryBoard in radio stories

* add new story's snapshots

* Radio.Card: border, leftSection, migrate call sites

- card border 0.5px border-neutral-strong, none when disabled
- children disallowed, leftSection slot for icons
- EditUserStrategyModal + DataSegregationStrategyPicker on label/description

* update loki snapshots

* Icon color prop instead of css module in DataSegregationStrategyPicker

* remove extra div

* make the indicator in the radio card optional

* fixed radio size, no size prop

* radio card body via mantine text/stack

* forwardRef radio card

* radio card border: highlight when selected

* update loki snapshots

* drop size="xs" from radio call sites

* fix card growing on select, interactive card stories, optional checkbox card indicator

* skip interactive card stories in loki, update card snapshots
2026-08-27 19:35:48 +01:00
Riley Thompson
3ecdab5ea7 Test for mongo multi column aggregation on joined models (#81079)
* add test

* use test helpers

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018bfeq38ZBHxqfwJAgRaRH4

---------

Co-authored-by: Claude <noreply@anthropic.com>
2026-08-27 18:34:19 +00:00
Ben Grabow
d18a2df374 Fix flaky snowflake key sharing (#81197) 2026-08-27 17:33:41 +00:00
Chris Vandoodewaard
32ff8a7c7c paginate PR results for backport Slack reminder (#81216)
paginate PR results
2026-08-27 13:16:27 -04:00
Chris Truter
0be2972872 Make rollback-only app DB transactions actually roll back (#80065)
* Key cached session tokens on the app db

with-empty-h2-app-db! swaps in a different application database, and this cache was keyed on the username
alone. A token minted against the previous database names a session that does not exist in the new one, so
the request 401s, and the token minted inside leaks back out when the original is restored. The retry in
client-fn cleared the whole cache and tried again, which papered over it often enough to look like flake:
"Failed to authenticate X after three tries".

Key it on the app db as well, like every neighbouring cache does via memoize-for-application-db.

databases-list-can-upload-test and dismiss-spinner-test go from failing to passing; both were in the CI
failure list, the former across 12 jobs.

* Fix rollback-only app DB transaction semantics

* Reject rollback-only combinations that cannot roll back

- :nested-transaction-rule :ignore skips the savepoint :rollback-only needs, so the pair is rejected at any
  depth rather than silently committing
- a throw out of the transaction body now rolls the connection back explicitly, since restoring autocommit
  commits whatever is still open -- a requested rollback that failed was committing the work it had to discard
- the unsupported-options error names the options, and drops the "application database" framing that
  misattributed failures on other java.sql.Connections

* Restore transaction state even when the savepoint rollback throws

The callback accumulators are discarded unconditionally at the top of rollback!, so leaving the state
restore behind a throwing .rollback left the tree half-unwound: an outer scope that caught the error and
committed would run its before-commit callbacks against the failed nested scope's state.

* Create test-data Databases outside the caller's transaction

Their ids are memoized for the whole app db, so the Database has to outlive whatever scope first asked for
one. Created inside a test's rollback-only with-temp it is rolled back while the memo keeps its id, and every
later lookup hands out an id for a row that never existed.

do-outside-transaction is the same detachment run-after-commit-callbacks! already did privately.

* Don't cache a personal collection id created inside a transaction

The cache's premise is that a Personal Collection cannot be deleted, so its id never changes. A rollback
breaks that: the collection goes away and the cached id points at a row that never existed, which reads as
a 403 on every later request that resolves the user's personal collection.

* Skip the test-database cache in a transaction rather than detaching

Detaching made the Database durable but took a second connection while the caller's transaction was still
open. When that transaction holds cluster lock rows -- data_permissions and search index setup both take
them -- the second connection waits on them until the lock acquisition times out.

Bypassing the cache keeps the work on the caller's connection, and matches how the personal collection id
cache handles the same problem. do-outside-transaction goes with it, having no other callers.

* Stop the outer commit when a requested rollback failed

The full rollback only runs when this call turned autocommit off, so for a nested scope or a caller-managed
connection a failed rollback! just propagated. Code between there and the outermost scope can catch it, and
the commit branch would then commit the writes the caller asked to discard.

Mark the tree instead, and refuse to commit it. Throwing rather than quietly rolling back: the caller asked
to commit and cannot, and dropping the outer work silently trades one bug for a worse one.

* Tolerate a savepoint an outermost rollback-only can no longer roll back to

A statement in the body can commit the transaction under us -- DDL does that implicitly on H2 and MySQL --
which invalidates the savepoint. Those writes are durable by then, so failing the scope reports a problem
nobody can act on while leaving the data exactly where it was.

At the outermost scope, discard whatever is still pending and log where it happened. Nested scopes still
poison the tree and throw, since there the enclosing work is pending and must not be committed.

* Note the option of rejecting DDL inside a savepoint-bearing transaction

* Never commit a transaction whose rollback failed

Four review passes flagged the same hole from different angles. Restoring autocommit commits whatever is
still pending, and after a rollback we were relying on to discard those writes, that is exactly the work
we were told to throw away. Track it and leave autocommit off instead, letting the pool roll the
connection back on check-in.

Two narrower routes to the same place:

- rollback! now marks the tree itself, so an exception-driven rollback that fails poisons it too. Before,
  only a requested rollback did, and the error path could still reach a commit.
- the mark is rechecked after before-commit callbacks drain. A callback can catch a nested scope whose
  rollback failed, which lands after the earlier check has already passed.

Two tests changed meaning as a result: a nested scope whose rollback throws now stops the outer scope
committing, so it no longer completes and its own after-commit callbacks no longer run. That is the point
-- its writes are still there.

Also adds the regression test for personal collection id caching, models autocommit honestly in the mock
rather than pinning it true, and records what the in-transaction test-Database lookup gives up.

* Build the test-data Database before with-temp opens its transaction

Created inside a rollback-only scope it never survives, so it is rebuilt for every test, and the ids
memoized in metabase.test.data.impl outlive it. Cards then get inserted against table ids for rows that no
longer exist: FK_REPORT_CARD_REF_TABLE_ID on a fresh app db.

Materialise it before the transaction opens, where it can commit. The table and field lookup maps get the
same in-transaction bypass the Database id already had, for the case where a dataset is first asked for
inside a scope anyway -- neither is enough on its own.

Reproduce with a throwaway app db, which is what CI has and a local one does not:

  MB_DB_TYPE=h2 MB_DB_FILE=/tmp/fresh-$$ ./bin/test-agent :only '[metabase.queries.models.card-test]'

* Only pre-warm the dataset for the default driver

db-id resolves through the driver under test, so in a driver-test namespace the pre-warm reached for that
warehouse's dataset -- work a with-temp there may never need, against a warehouse that may not be up.
Driver failures went from 2 to 12 in the push that added it.

The FK problem it fixes is on the app-db side, for the default dataset, so confine it there. Best effort
even then: a dataset that cannot be built must not take an unrelated with-temp down with it.

* Evict temporary users from personal collection cache

* Evict the personal collection cache on the rollback, not on the user

Clearing the temp User's own entry misses the case that actually bites: a committed user's Personal
Collection is created lazily on its first permission check, which often lands inside somebody else's
with-temp. Nothing evicts it when that scope rolls back, and every later request for that user 403s.

Key off the with-temp boundary instead, and drop whatever it may have cached. Costs a re-lookup per user
afterwards; correct whichever user and whichever scope created the entry.

agent-api + activity-feed went from 21 failures to none.

* Skip the dataset pre-warm where the app db is deliberately empty

with-empty-h2-app-db! rebinds the app db, and the memo key includes its identifier, so the pre-warm missed
the cache and created a test-data Database inside a scope whose whole contract is emptiness.
databases-list-can-upload-test snapshots an empty Database set and saw two.

Bind *skip-dataset-prewarm?* there instead. Also drops the earlier :h2 restriction, which came from a bad
reading of two CI runs sampled at different completion stages: it could never have helped here, since those
helpers are H2, and it took the pre-warm away from driver tests that needed it.

Reproduce with a throwaway app db, which is what CI has and a local one does not:

  MB_DB_TYPE=h2 ./bin/test-agent :only '[metabase.queries.models.card-test]'

* Register the cache eviction with a unique key

metabase.test.redefs already holds `:around :default` on do-with-temp*, and methodical overwrites methods
sharing a key rather than composing them. Whichever namespace loaded last would win, silently dropping
either this eviction or the rollback-only transaction wrapper. It happened to work; it should not depend on
load order.

Also notes what a failed connection-level discard leaves behind. Only a caller-supplied connection is
exposed: on one we own, the same flag stops autocommit being restored, so the writes are never committed.
It logs rather than throws because throwing from that catch would mask the exception being unwound, and
master never attempted the discard at all, so a caller-supplied connection is no worse off than before.
Signalling it properly would mean telling the caller some other way.

* Note that session tokens are cached without regard for transactions

The user ids directly above skip the memo inside a transaction, since users created in a `with-temp` are
discarded with it. The token cache has no equivalent guard, so a session rolled back with its scope leaves a
token behind and the request fails with "Failed to authenticate X after three tries". The retry in
`client-fn` hides it more often than not.

* Note that a rollback can leave a stale personal collection id cached

"A Personal Collection cannot be deleted" does not hold for a transaction that rolls back. Tests evict on
the with-temp boundary; production has no equivalent and keeps the id for the rest of the TTL. Accepting
that for now -- it predates honoring :rollback-only, and closing it properly wants an after-rollback hook
alongside do-before-commit/do-after-commit.

* Follow the created-globally rename in the token cache TODO

* Build the query for export inside the guard, not beside it

`:query_json` already returns nil for a card whose query cannot be exported, but `lib/query` was called in the
argument position, outside `try-export-query`. A stored `dataset_query` with no stages builds a query that fails
its own output schema, so one such Card takes down every response that walks a set of Cards -- the typed-schemas
endpoint among them.

metabase.search.appdb.scoring-test alongside metabase.typed-schemas-rest.api-test goes from 13 failures to 0.

* Don't run a test request inside a rollback-only transaction

`user-request` takes a temporary Session when it is handed a User or an id rather than a `:rasta`-style keyword,
and the handler runs in-process on this thread. Now that the with-temp rolls back for real, every app db write
the request made is discarded when it returns -- the warehouse table writes survive on their own connection and
the API still answers 200, so the test sees a successful call that changed nothing.

Insert the Session and delete it in a `finally` instead. A caller already inside a transaction still gets the
same behaviour it always had; what goes away is the extra rollback scope around the request itself.

metabase-enterprise.action-v2.models.undo-test goes from 25 failures to 0, passing all 134 assertions, which
matches master.

* Mint the test users' sessions before anything opens a transaction

`authenticate!` ran about 150 times in a single `pulse.api.pulse-test` run, nearly always inside a transaction.
A session minted inside a `with-temp` is rolled back with the scope, the next request 401s, and the retry in
`client-fn` cleared the whole cache -- every user's token, not just the dead one -- so everyone re-authenticated
in-transaction and the cycle repeated. Each of those inserts bumps the user's `last_login` through the
`:model/Session` after-insert hook, which is what breaks a test that reads the creator before making its request.

Mint the four test users' sessions at initialization, where nothing has opened a transaction yet, so they are
durable. On a 401 forget only that user's token, so one temporary user's rolled-back session cannot evict them.

pulse.api.pulse-test goes from one failure to none, matching master. publish-refresh-error-event-sends-admin-email-test
passes too, where it fails standalone on master: that email only goes to admins with a `last_login`, and
crowberto's was rolled back with every login.

* Ask for the FieldValues the chain filter test needs

The full FieldValues row for `categories.name` is created lazily, and `update-field-values-for-table!` only
refreshes rows that already exist -- so a run that creates it inside a `with-temp` discards it and nothing
makes another. `select-one-pk` then returns nil and the test dies on "Not something with an ID".

Same shape as the rest of this branch: a durable row created on demand, now rolled back with the scope that
created it. Ask for the row instead of assuming an earlier test left one behind.

* Run the metric leaf queries one at a time inside a transaction

A transaction owns a single connection and `future` hands that binding to every thread it starts, so the
leaves' app db writes -- used-card stats behind a cluster lock, query rows -- interleave on one session.
Savepoints are per session: a thread rolling back to its own destroys the ones its siblings are holding, the
next release fails with "savepoint does not exist", and the transaction aborts, taking the rest of the test
with it. That is why api-arithmetic-test loses a different test on each CI run.

Only tests get here. A request runs in no transaction, where each future takes its own pooled connection and
the parallelism is worth having.

On a throwaway Postgres the namespace errors on two tests per run before this and passes three runs out of
three after.

* Commit a lock row that would otherwise roll back with the caller

A lock row is written once and read forever after, and acquisition leans on that: rival first-time inserters
block on the winner's uncommitted unique-index entry and retry once it commits. Inside a `with-temp` that
commit never comes, so the row is gone again and the next acquisition replays the race -- on MariaDB until the
lock-wait timeout expires.

Insert it on a connection of our own when the caller was already in a transaction, which is the only case
where the row would not survive. Nothing in production takes a cluster lock from inside another transaction,
so this leaves that path alone -- worth keeping that way, since lock names are dynamic in places and rows that
used to roll back with a failed transaction would otherwise persist.

Reasoning rather than measurement; the TODO on the function says so and says what to do if it does not help.

* Bound the out-of-band insert on its own connection

`set-query-timeout!` returns false on MySQL running MariaDB Connector/J, and the fallback sets
`innodb_lock_wait_timeout` on the session -- but `acquire-lock-row!` sets it on the caller's connection, not
the one the insert opens. Blocked by a rival's uncommitted row, the insert would then wait out the server
default instead of the second it was given, on exactly the databases this is meant to help.

Give it the same treatment on its own connection. Also note in the docstring that the second connection is
only taken until the row exists, which is what bounds the cost of holding two at once.

* Resolve the venues id before counting queries

The cache is fine; the query the test counts is its own `(mt/id :venues)`. Inside a transaction the test-data
id lookup deliberately skips its memo, so the call lands in the window that is supposed to see none.

* Keep the pre-warm out of app dbs that are meant to be empty

`with-empty-h2-app-db!` already opts out of the dataset pre-warm; the serialization test dbs and the
schema-migration ones never did. A `with-temp` inside them materialised the test-data Database, and an extract
then saw a Database no assertion expects -- serialization.v2.load-test/database-test wanted one and found two.

* Do not insert a lock row out of band outside tests

The claim in "Commit a lock row that would otherwise roll back with the caller" was wrong: production does take
cluster locks inside another transaction. `load-from-h2!` inserts Databases, and so takes the batch-permissions
locks, inside one big load transaction. Our fresh connection then blocked on a next-key gap lock the caller's
own SELECT ... FOR UPDATE was holding, and a thread cannot outwait itself -- it timed out, retried, and failed.
That is what broke dump-to-h2, load-from-h2 and rotate-encryption-key on MariaDB.

Gate the out-of-band insert on `config/is-test?`, which is the only place a transaction may never commit, so
production goes back to exactly what it did before. Keep a fallback for the same shape inside tests, where
`load-from-h2!` can block on itself just as readily: on a lock-wait timeout, insert on the caller's connection.

* Stop three card tests leaving rows behind

`updating-model-query-does-not-shift-metadata-overrides-test` had no cleanup at all, and
`create-card-with-type-and-dataset-test` opened a plain `t2/with-transaction` where its siblings pass
`{:rollback-only true}` -- so both committed cards with a `{}` dataset_query that every later test walking the
card table then had to survive. That leak is older than this branch; honoring the rollback is what makes the
second fix work.

`get-series-for-card-permission-test` read crowberto's personal collection with `select-one-pk`, and a nil
collection_id puts the card in the root collection, which rasta can read -- so the test quietly asserted 403
against a card that was never private. Ask for the collection instead.

* Truncate the heartbeat fixture times to milliseconds

Postgres stores microseconds, so a timestamp ending .7369995 comes back a millisecond above its own
millis-truncation and the assertion misses by one.

* Tolerate a card whose query will not parse when finding related entities

Nothing at the schema level stops a stored `dataset_query` being empty, and such a card simply has no
context-bearing forms. Without the guard one of them takes down the related-entities computation, and with it
every x-ray, for everyone else. Same treatment `card-details` already gives an unexportable query.

* Give the end-to-end schema test a Database of its own

The test asserts exactly which questions, metrics and models fall inside the test-data Database's scope, which
holds only as long as no other namespace commits a Card against that Database. Two such leaks have been fixed
on this branch already and there is at least one more; the assertion cannot be made safe by chasing them,
because any test added later can break it again.

Run it against a copy of the Database instead, so nothing else can write there.

A throwaway namespace that commits one Card on the test-data Database ahead of it reproduces the CI failure
exactly (core_test.clj:147) and passes with this change.

* Recognise the MySQL lock-wait timeout in the in-band fallback

`lock-wait-timed-out?` knew about `SQLTimeoutException` and our own `::acquisition-timeout` marker, but not
ER_LOCK_WAIT_TIMEOUT itself. The server raises that on its own schedule, so on MySQL and MariaDB -- the
databases the fallback exists for -- it could arrive as a plain `SQLException` and the fallback would not fire.
Check the code through the cause chain.

* Take the revisions with the cards

`with-model-cleanup` deletes rows directly, which skips the Card hook that would have removed the revisions
this test's POST and two PUTs create. Name Revision in the cleanup as well.

* Truncate once, and align the chain filter's temp values

The second `truncate-to` could not do anything the first had not.

* Create the test users before the related tests race for them

`user->id` skips its memo inside a transaction and creates the users there instead, so on this branch they roll
back with the scope and the next test makes them again. These tests are parallel and every one of them takes a
`with-temp` Card whose creator defaults to rasta, so several threads insert the same user at once and all but
one time out on the row lock. The namespace goes from three errors to none.

Also covers the guard in `related/definition`: a Card whose stored query will not parse contributes no
context-bearing forms, and a genuinely similar Card still outranks it.

* Cover the card whose query will not build

The guard in `card-details` had no test: a Card with a stage-less stored query answers without `:query_json`,
and the Card beside it in the same response is unaffected.

* Cover the batch path and the lock-wait code

The first version of the card test called `get-table-details` once per card, which cannot see the failure it
claims to cover -- the bug was that one bad card killed the whole `cards-details` seq the others were in. Go
through that seq instead. Removing the guard turns the test red at the same malli output error CI was showing,
which the per-card version did not.

Also cover `lock-wait-timed-out?`: MySQL's ER_LOCK_WAIT_TIMEOUT on its own and inside a cause chain, and any
other error still propagating rather than being taken for a timeout.

* Create the temp search index before the transaction, not inside it

`with-temp-index-table` runs CREATE TABLE and DROP TABLE on the ambient connection, and on H2 and MySQL that
commits the transaction around it. Six tests opened it inside a `with-temp`, so the rollback had nothing left
to take back and every row they created leaked -- a Transform, some Cards and Collections, a published Table, a
Document -- to any later test that walks the app db.

That one leaked Transform is the whole of the serialization failures: a collection-scoped export includes every
Transform in the instance, so all four tests came back with one entity more than they expected.

Take the index table before the `with-temp` instead. The nested scope reuses it, so nothing else moves.

`metabase-enterprise.search.scoring-test` also had no fixtures at all, and fails on its own: the first lazy
`initialize :db` fires mid-test and recreates the H2 database underneath a test already writing index
bookkeeping.

The 133 namespaces that run before serialization.api-test in the Enterprise job reproduce the CI failures
exactly -- 5011 assertions, 5 failures -- and pass with this, at 4714 assertions.

* Say the cluster lock comments plainly

Lead with the point rather than building up to it, and drop the clause chains. No behaviour change.

The TODO above `clear-cached-session-tokens!` was stale: it asked for the `created-globally` treatment, which
landed earlier on this branch. Point at what is actually left instead -- initialization can still first happen
inside a `with-temp`, and then the sessions roll back with it.

* Keep the non-index assertions where the app db cannot index

`with-temp-index-table` is a `when`, so wrapping a whole test in it skips the whole test on MySQL and MariaDB.
Two of the tests moved in the last commit also assert things that need no index, and those assertions went
quiet there. Add a sibling that runs the body either way, and use it for those two.

`search.appdb.scoring-test` had no initialization fixture, the same gap its enterprise counterpart had: the
first lazy `initialize` can recreate the H2 db underneath a test already writing index bookkeeping.

* Sort the fixtures require

* Download through the client that retries a 401

`downloaded-card-filenames-test` passed a raw cached token straight to `client-full-response`, so it skipped
the retry every other test gets from `client-fn`. A session rolled back with the scope that made it then came
back here as a bare 401, which is what the BigQuery job has been failing on.

`user-http-request-full-response` still returns the headers the test reads.

* Improve rollback test isolation and comments

* Do not poison the transaction tree when the savepoint is already gone

MySQL and MariaDB roll back the whole transaction to break a deadlock, discarding every savepoint with it. The
ROLLBACK TO SAVEPOINT that follows fails with "SAVEPOINT does not exist", and marking the tree rollback-required
there is backwards: the server has already discarded the writes, so nothing is pending for an enclosing scope to
commit by mistake. A rollback-only scope whose DDL committed implicitly already gets this treatment.

The refusal message named a rollback-only transaction, but the ordinary error path sets the flag too.

Also validate :nested-transaction-rule with a throw. It is a public option, and `assert` compiles away under
`*assert*` false. Sorting the unsupported keys keeps the message stable across runs.

* Keep the test request's session out of the login hooks

:model/Session's after-insert hook publishes :event/user-login, which stamps User.last_login, and
:event/user-joined for a User that has never logged in. Deleting the Session afterwards undoes neither, so every
user-http-request left both behind for whatever ran next.

Write the row instead. created_at has to come along, since the model supplied it.

* Ask whether the app db can hold the index, not whether any engine can

supports-index? is true for any active engine. With semantic search on MySQL or MariaDB, the macro that exists to
run the body without an app-db index took the app-db branch and tried to create the table anyway.

* Say something when a stored query is dropped

Both guards swallowed every exception silently, so a Card whose query failed to build for an unrelated reason
looked exactly like one that has no query. try-export-query, right next to the Metabot guard, already warns.

Related entities logs at debug: it runs for every candidate Card while ranking.

* Commit the out-of-band lock row rather than assume autocommit

The docstring said the row was committed, but nothing committed it -- the insert relied on the pooled connection
arriving in autocommit, which the pool does not promise. The caller's SELECT cannot find the row otherwise.

* Let a failed dataset pre-warm be heard

Now that the pre-warm runs for every driver, a warehouse that is down fails it on every top-level with-temp. At
debug that is invisible on a normal run and resurfaces much later as a Database that does not exist. Warn once
per message.

Also note that mt/id costs a query inside a transaction, which is what a with-call-count window has to plan for.

* Polish prewarm comments

* Mark the tree rollback-required even when the savepoint vanished

A vanished savepoint does not mean nothing is pending. DDL committing implicitly, or a server breaking a deadlock,
ends the transaction and discards the writes so far -- but anything written afterwards sits in a fresh transaction
and is still pending. Skipping the flag there let an enclosing scope swallow the rollback error and commit exactly
those writes.

Say so at the point of the catch, since the reasoning does not survive a quick read.

* Gate every app-db index helper on app-db support

with-temp-index-table and with-appdb-search-if-available-otherwise-legacy still asked supports-index?, which is
true for any active engine. With semantic search on MySQL or MariaDB they ran app-db DDL the app DB cannot take,
including from scopes nested inside the fallback body that exists to avoid exactly that.

Cover the borrowed session too: it must leave last_login empty, and delete itself afterwards.

* Cover the out-of-band lock row against a connection in a transaction

Hands the dedicated connection over with autocommit off and checks the row survives the caller's rollback. Without
the explicit commit the insert dies with the connection, and acquisition then fails on the row it just wrote.

Runs on MySQL and PostgreSQL only; H2 takes an in-process lock and writes no row.

* Pin the vanished-savepoint case against the outer commit

A savepoint the server already discarded says nothing about what was written after it. The existing rollback tests
throw generic exceptions, so nothing stopped the SQLState 3B001 / MySQL 1305 exemption from coming back.

* Pin the engine in the otherwise-legacy fallback

Where the app DB cannot hold an index, the fallback took whatever default engine was active. Semantic can be
active there, and the bodies are written for an index the app DB does not have. Run them under legacy search, as
the macro's name says. with-legacy-search moves above its first use.

* Polish rollback and search comments

* Stop two remapping scopes deadlocking on MySQL and MariaDB

A remapping writes a Dimension for a Field the whole suite shares, and holds it until its scope ends. Two threads
doing that at once deadlock on the unique index over dimension.field_id: each holds the record lock the other's
uniqueness check wants, while asking for the insert-intention gap in front of it. MySQL and MariaDB pick a victim
and roll it back, which drops its savepoints, so the rollback that follows fails on a savepoint that is gone.

Serialise remapping scopes against each other. Tests that never remap keep running in parallel alongside them.

The helper already carried a TODO saying it was not thread-safe.

Reproduced on MariaDB 12.3 and confirmed on master, so this predates the branch. custom-values-test failed nearly
every run before, and three runs in a row are clean after. Verified on H2 as well.

* Serialise every temporary Dimension, not just remapping scopes

Remapping is not the only way a test writes a Dimension for a shared Field: card-test, card/metadata-test,
field-values-test and data-studio's table-test all create them directly, in parallel, on the Orders and Products
fields. Those still raced with the remapping scopes.

Move the lock to `do-with-temp*` for :model/Dimension so every site is covered, including ones added later.
`locking` is reentrant, so a `with-temp` holding several Dimensions still works.

* Take the search index out of six more with-temp transactions

Same fix as the earlier pass over the search tests, for the ones that pass a warehouse driver: their index scope
sits inside `with-temp`, so `drop-table!` runs DDL on the ambient connection. H2 and MySQL commit the transaction
to do it, which makes the temporary Transforms durable and destroys the savepoint. The rollback that follows can
no longer take them back, and it discards toucan's compensating deletes along with everything else still pending,
so the Transforms outlive the test.

Three tests later in the same namespace count transforms and saw the strays: root-collection-items-include-
transforms-test expected one and found four.

These were missed the first time because `mt/normal-drivers-with-feature :transforms/table` skips them on H2, so
only a driver run reaches them.

Reproduced with a MariaDB warehouse: transform-test went 3 failures to 0, and the four namespaces that failed
together now match master at 2532 assertions. H2 is unchanged at 109.

* Let the failed-rollback warning reach the console

The shared Console appender only accepts FATAL, so the warning naming a rollback-only scope that could not roll
back went to logs/test-log.json and nowhere a CI run gets read. It took hours to find six tests leaking rows
because of it; the warning had been firing the whole time.

Give that logger an appender that accepts WARN. The message carries the mb-test key, so it names the test that
broke its own isolation rather than the later one that trips over the rows.

* Hoist the search index scope above with-temp in two document search tests

Both tests opened `with-appdb-search-and-legacy-search` inside `mt/with-temp`.
That scope creates and drops the index table on the ambient connection, and on H2
and MySQL the DDL commits the transaction `with-temp` meant to roll back, so the
temp Documents leaked into later tests.

Found by the throw this branch adds: both showed up as errors at connection.clj:293
in the app DB test jobs.

* Serialize the reduced-fields card test

It holds a rollback-only savepoint across two `with-temp` Cards and an API call. Run in parallel, something else
commits the transaction that savepoint lives in, so both Cards are discarded and the downstream query reports its
source Card as missing.

Only MySQL surfaces it, and only under a full suite: the test passes on its own, and six local configurations could
not reproduce it. Confirmed by running the MySQL and MariaDB driver jobs with this single change -- all four green,
against four runs where they failed.

* Materialize the test users' Personal Collections before with-temp opens

`user->personal-collection` is a get-or-create and sits on the permissions path every API request takes. A
namespace that does not initialize `:test-users-personal-collections` creates Lucky's the first time a request
calculates permissions -- which happens inside a `with-temp` -- so the transaction rolls it back. Every later
request tries to create it again, and the parallel ones time out on each other's COLLECTION table lock:

  GET /api/database expected a status code of 200, got 500.
  Timeout trying to lock table; INSERT INTO COLLECTION (..., "Lucky Pigeon's Personal Collection", ...)

That is what failed `databases-list-include-saved-questions-test` on the Mongo, Redshift and Athena jobs -- the
empty database list was the 500, not a visibility problem.

Prewarm them next to the dataset, under the same skip flag, so helpers that need an empty app DB are unaffected.
This also closes the related hole where `:test-users` itself first initializes inside `with-temp`, since that
component initializes it.

Confirmed on the Mongo driver jobs: MongoDB Latest went from failing to green.

* Update the test-user session note now that initialization is prewarmed
2026-08-27 19:05:06 +02:00
bryan
13dde0bba3 Reject unneeded connection properties in SQL-JDBC additional-options (#81097) 2026-08-27 10:29:18 -06:00
Nathan Voxland
c24f084ae6 Improve SVG handling (#80249) 2026-08-27 11:25:08 -05:00
Andrei Chernykh
e1fbadec0b Remove unused raf dependency (#80931) 2026-08-27 09:17:21 -07:00
Andrei Chernykh
ad48fed046 Remove the direct reselect usage and dependency (#81034) 2026-08-27 09:16:17 -07:00
Andrei Chernykh
7c08b5d95c Remove cypress-each (#81086) 2026-08-27 09:15:55 -07:00
Andrei Chernykh
25ed6aac2b Swap merge-refs for Mantine's mergeRefs (#81104) 2026-08-27 09:15:15 -07:00
Andrei Chernykh
5c169f142a Replace react-innertext with a local helper (#81105) 2026-08-27 09:14:44 -07:00
Chris Truter
42cf92479a Ratchet config-level kondo suppressions too (#78217)
* Ratchet config-level kondo suppressions too

:config-counts in ratchets.edn tracks, per linter, the :off switches and
:exclude entries in .clj-kondo/config.edn (top-level and per ns-group).
Only weakening counts: adding discouragements or turning a linter on is
free. Lowering works like the inline budgets; raising is a hand edit.

* Count every excluded item and :config-in-comment in the config ratchet

Map-shaped :exclude values with vector entries counted as one suppression
({compojure.core [GET DELETE POST PUT]} is 4, not 1), and the
:config-in-comment :off switch wasn't aggregated at all, so both could
grow without tripping CI. Reseeded.

* Count :config-in-call suppressions, and self-heal on config.edn

`:config-in-call` is a scoped `:linters` map like `:config-in-ns`, so a
linter switched off inside one was invisible to the ratchet. Both scopes
now fold into the same count.

The self-heal workflow only watched Clojure sources, which was right while
budgets came from inline ignores alone. Now that `.clj-kondo/config.edn`
feeds `:config-counts`, removing a suppression there can leave a budget
stale with no way to trigger the fix.

* Count scoped :off suppressions at any nesting depth

Linter scopes nest more than one level: :discouraged-java-method keys by
class and then by method. Counting only the first level meant an :off one
map further down waived a warning the ratchet never saw. No budget moves --
the repo's only two-deep entry is a :level :error discouragement.

* Regenerate kondo ignore budgets after restacking onto master
2026-08-27 17:40:39 +02:00
Kevin Kelleher
fc487f06c9 Explorations summary document (#78848)
Co-authored-by: Nathan Voxland <nathan@metabase.com>
2026-08-27 11:32:54 -04:00
github-automation-metabase
6d2c060ef1 Fix flaky document-comment split test (#77391)
* Fix flaky document-comment split test by using realClick on hover-revealed button

The test clicked the hover-revealed "new thread" comment button of the
second paragraph via Cypress's synthetic .click(). After realHover() moved
the cursor to reveal the button, the synthetic click could act on the button
while its hover transition was unwinding, so the click did not reliably
trigger the route navigation that opens the comments sidebar — leaving
getSidebar() to time out.

Switch to .realClick(), which moves the real mouse onto the button (keeping
it visible/stable) and dispatches a real click that reliably fires the link.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* Wait for document save to persist before opening comments sidebar

The split-paragraph test opened the comments sidebar immediately after the
Save button disappeared, but a successful save schedules a deferred
navigation back to /document/:id. Under network throttling that navigation
resolved after the sidebar route had opened, clobbering it, so the sidebar
never mounted and getSidebar timed out. Wait on the PUT request and the
"Document saved" toast so the post-save navigation settles first.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-27 17:28:43 +02:00
Nicola Mometto
f8ce01fcca Check the email_verified claim in the generic OIDC provider (#80269)
Google SSO already requires the id-token email to be verified; the
generic OIDC provider (and slack-connect, which derives from it) did
not look at the claim at all.

Tokens with email_verified present and not true are now rejected. An
absent claim is still accepted: it is optional per OIDC Core and some
IdPs never send it.
2026-08-27 16:16:12 +01:00
Merlin-S3NS
e433af3f90 Fix: Support Google Cloud Universe Domain in BigQuery driver (#68607)
* Fix: Support Google Cloud Universe Domain in BigQuery driver

* feat(bigquery): Add universe domain to connection properties UI

* feat(bigquery): improve universe domain helper text

* Update bigquery_cloud_sdk.clj

Indeed we are out of sync as the impersonating was removed from master branch.

* removed empty comment

* Fixing formatting
2026-08-27 10:57:23 -04:00
Nicola Mometto
57f6f37864 Match SSO group names by exact string value when syncing memberships (#80615)
Ignore non-string SSO group names when syncing group memberships
2026-08-27 15:45:51 +01:00
github-automation-metabase
2ef0e4d264 Fix flaky dashboard bulk-move empty-state test (#78457)
Wait for the question move PUT to settle before navigating to the
affected dashboard, so its empty state is asserted only after the
dashcard has actually been removed.
2026-08-27 16:44:22 +02:00
Nemanja Glumac
c090eb292a Delete redundant e2e spec (#81174) 2026-08-27 16:03:30 +02:00
Kevin Kelleher
9e329ce6fe Ensure highlighted bars are included in brush drill filter (#80025)
* ensure highlighted bars are included in brush drill filter

* fix e2e

* fix e2e again, December 2026 label was not appearing maybe due to a screen size flake
2026-08-27 13:53:32 +00:00
github-automation-metabase
0d36304bf5 Stabilize scatter tooltip test against ExplicitSize resize flake (#78458)
The 'adding non-series columns to the tooltip' scatter test hovered a
bubble immediately after render. The ExplicitSize throttle re-renders the
chart once its container is measured, moving bubbles out from under the
realHover() before the tooltip fires, so [data-testid=echarts-tooltip]
was intermittently never found (4000ms timeout).

Apply the same view-toggle stabilization the sibling tooltip test already
uses (extracted as stabilizeScatterChart) before each hover, forcing a
re-render against an already-measured container.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-27 15:29:26 +02:00
Chris Truter
dd1cb0f0ba Require justifications for linter ignores (#77820)
* Require a justification comment above inline ignores, ratcheted per linter

An ignore of a linter outside :comment-exempt needs a substantive ;;
comment on the line above or trailing on the same line (bare ;; dividers
don't count, and no attempt is made to check the comment is about the
ignore). ~18% of ignores have one today, so 35 linters start exempt.
The set only shrinks: once a linter's last uncommented ignore gains a
comment, the fixer drops its exemption and CI holds the line.

* Locate trailing justification comments in masked source

A semicolon inside a string or character literal on the ignore's line
counted as a trailing comment, so an unjustified ignore could pass.
The masker now keeps the ; that starts a comment (and blanks the char
after a backslash), so justified? finds only real comment starts.

* Share one tree scan across the ratchet tests

Each ratchet test walked and slurped the whole source tree; a delay
runs the scan once for all three.

* Invalidate the shared tree scan per test run

The namespace-level delay cached the scan for the JVM's lifetime, so a
long-lived REPL compared fresh ratchet-file contents with stale counts.
The :once fixture now resets the cache; a directly-run test var scans
fresh.

* Scope the shared tree scan to the fixture's lifetime

The atom cache survived a run, so a later directly-invoked test var
(which skips :once fixtures) reused a stale scan. The cache now holds a
delay only while the fixture is live; without it every call scans fresh.

* Require canonical syntax for kondo ignores

Keep ignore detection deliberately lexical and fail closed: every real marker must use the key-first map form, otherwise the ratchet rejects it with an actionable error. This avoids maintaining a partial Clojure reader for the two attr maps that previously placed the ignore behind another key.

Justification comments must be substantive and either directly above the ignore or trailing on its line. Authenticate comment openers in masked source so strings and code-line comments cannot pose as justifications.

* Harden kondo ignore scanning edge cases

* Use reader delimiters for kondo marker boundaries

* Match Clojure reader whitespace in kondo markers

* Reserve clj-kondo namespaced map syntax

* Harden kondo scanner diagnostics

* Rebuild the budgets and exemptions on the named-linter base

Rebased onto the ignore-naming branch, so every budget is recomputed from
the tree and :comment-exempt is reseeded with exactly the linters that
still have an uncommented ignore: 38, up from 35. The three extra are
linters that were hidden inside bare `#_:clj-kondo/ignore` forms until
they were spelled out; :all itself drops out, having no ignores left.

* Point at :comment-exempt after inserting ignores for a new linter

kondo-insert-ignores writes comment-less ignores, which the justification
ratchet rejects for non-exempt linters.

* Leave ignores preceded by a # for a human, and gate the exemption advice

A `#` immediately before the matched form is ambiguous: in `#^{...}` it is
legacy metadata that removal must take with it, in `x#^{...}` it closes a
syntax-quote gensym that removal must leave alone. Telling them apart means
reading Clojure, which this scanner deliberately does not do -- so report
the site under :skipped, as it already does for prefixless maps and
unbalanced braces, and let a human excise it.

Separately, kondo-insert-ignores no longer advises a :comment-exempt entry
unconditionally. An inserted ignore lands under whatever comment already sat
above the flagged form, so a linter whose sites are all justified would get
an exemption that no-stale-exemptions-test then rejects.

* Align the scan-test expectations

The occurrence vector's :justified? column and the counts map both drifted
out of alignment as linters were added to the fixture.

* Regenerate kondo ignore budgets after restacking onto master
2026-08-27 15:16:59 +02:00
Chris Truter
ec3b24fadd Make every kondo ignore name the linters it suppresses (#79531)
* Make every kondo ignore name the linters it suppresses

The vector-less `#_:clj-kondo/ignore` suppresses every linter on the next
form, so a site added to silence one warning quietly absorbs any other that
appears there later. Replace all 50 with explicit linter vectors.

The budgets absorb what the bare forms were hiding: :discouraged-var
106 -> 129, :unresolved-namespace 3 -> 9, :type-mismatch 2 -> 6,
:unresolved-symbol 4 -> 9, plus first entries for :consistent-alias,
:duplicate-require and :redundant-do. :all drops out entirely, so a new
bare ignore now fails the ratchet with no budget to land in.

* Use the mdb.env alias in app-db-as-data-warehouse

Var-quotes resolve namespace aliases, private vars included, so the
fully-qualified name was never needed. Dropping it retires the
:aliased-namespace-symbol ignore and the unused-alias warning the
workaround caused.

* Regenerate kondo ignore budgets after restacking onto master
2026-08-27 14:23:09 +02:00
Jakub Chodorowicz
7eba2629f2 harden host event listener access across membrane (#81036) 2026-08-27 14:02:06 +02:00
Jakub Chodorowicz
c433278e06 Gdgt 2472 loader (#80586) 2026-08-27 11:53:29 +02:00
Oleh K
11be7cb3e7 Restyle NavLink with primary and secondary variants (#80640)
* Add primary/secondary NavLink variants and sibling components (GDGT-2469)

Restyle the design-system NavLink from Figma:

- Add `primary` (brand-fill selected) and `secondary` (subtle gray selected)
  variants, with Default/Hover/Pressed/Selected states.
- Add the `icon-{primary,secondary,disabled,brand}-inverse` color tokens.
- Add `NavLinkButton` and `NavLinkBadge` sibling components for the right
  section; both invert automatically on a selected `primary` item (no prop),
  the button also has its own hover/press and stops click propagation.
- Give NavLink a `leftIcon` prop so it renders and colors the leading icon
  itself instead of styling the section slot.
- Add a two-variant state-matrix Storybook showcase (Loki-covered).

* Migrate NavLink call sites to primary/secondary variants (GDGT-2469)

- Admin nav: `admin-nav` -> `secondary`
- Entity picker: current level -> `primary`, other levels -> `secondary`;
  search results -> `primary`
- Remove the now-unused `default`/`mb-light`/`admin-nav` variant CSS

* Revert NavLink `leftIcon` prop back to `leftSection` (GDGT-2469)

Drop the polymorphic NavLink wrapper and colour the leading icon via the
`.NavLinkSection[data-position="left"]` CSS overrides again.

* Update Loki Snapshots

* Cleanup

* Update Loki Snapshots

* Add Loki reference for the NavLink Overview story (GDGT-2469)

* Update Loki Snapshots

* Address NavLink review comments (GDGT-2469)

- Migrate the remaining `default` NavLink (embedding SimpleDataPicker) to
  `primary`, restoring its selected styling
- Render NavLinkButton as a `<div role="button">` (valid inside a NavLink's
  `<a>`) with keyboard activation, instead of a `<button>`

* Update Loki Snapshots

---------

Co-authored-by: Metabase Automation <github-automation@metabase.com>
2026-08-27 11:42:14 +02:00
Oleksandr Yakushev
cad622a164 [test] Extract and reuse deferred str mechanism for testing macro (#79932) 2026-08-27 10:50:01 +03:00
Ben Grabow
92fdc53695 Only setup tracking db once per jvm (#80960)
* Only setup tracking db once per jvm

* kick ci
2026-08-27 04:53:59 +00:00
Alexander Polyankin
c3dddcfcc6 Encrypt public_uuid at rest, resolved via an indexed prefix (#80929) 2026-08-26 21:08:08 -04:00
Tyler Plude
31e8463f0f [BOT-2019] Harden Metabot SQL editor access (#80544)
* harden sql access

* remove hardcoded sql capability from document context

* make SQL permission denials terminal and visible

* make read-check denials terminal and gate document_schema_collect
2026-08-26 18:06:39 -07:00
Romeo Van Snick
afa13457ae Reset transforms-enabled before the transform permission tests (#80996)
* Reset transforms-enabled before the transform permission tests

* Clear transforms-enabled rather than setting it false
2026-08-27 10:55:52 +10:00
Denis Berezin
7692d3f479 UXW-5117 Fix Timeline event pills displayed on a wrong date when merged (#80567)
* UXW-5117 Implement timeline events stacks

* Improve performance

* Fix edge cases, improve performance, fix issues

* Review fixes

* Place chips at real data point

* Self review
2026-08-27 03:05:06 +03:00
Romeo Van Snick
0a601f07c6 Keep entity identity stable when a write changes nothing (#80976)
* Keep entity identity stable when a write changes nothing

* Skip null field writes in the tables reducer
2026-08-27 09:23:39 +10:00
Romeo Van Snick
cf3200aa96 Load the template tag's field from the API, not the metadata mirror (#80974) 2026-08-27 09:22:55 +10:00
Romeo Van Snick
f5b9b156e8 Move the data reference panes off the metadata mirror (#80973) 2026-08-27 09:22:03 +10:00
Romeo Van Snick
518f75d5f5 Read the picked table's database from the RTK cache, not the metadata mirror (#80972) 2026-08-27 09:21:43 +10:00
Kevin Kelleher
cc1d5a93d1 Preserve timelines modal stack on close (#81037)
turn flat timelines routes into a tree
2026-08-26 19:03:55 -04:00
Andrei Chernykh
3a824943f0 Remove mockdate dependency (#80941) 2026-08-26 15:17:25 -07:00
Ben Grabow
3d7eed5d4a Split postgres driver tests (#81111) 2026-08-26 16:36:55 -05:00
technomancy
cb7114ff8a Stop duplicating databricks test jobs for multi-catalog (#80957)
Stop duplicating databricks test jobs.

In https://github.com/metabase/metabase/pull/57148/changes we added
support for databricks multi-catalog feature. In this PR the existing
databricks job was duplicated, so every databricks test ran twice. The
rationale for this (and more broadly the rationale and background for
the entire feature) was never explained.

The code which looks at the multi-catalog flag looks to be tested in
the metabase.driver.databricks-test test. So running the entire driver
suite all over again just with that one flag set differently looks to
be very wasteful.

We have been putting a lot of load on databricks recently with the
extreme levels of backporting we're doing, which has led to periods
during which 99% of databricks jobs time out. The fact that we're
running twice as many tests as we need to is surely a contributing
factor to this.

It would be even better if the multi-catalog functionality were tested
inside the main test suite instead of spun off into a separate job,
but I want to focus on getting it stable first.

Also we split databricks into 3 jobs, but since the bottleneck is in
the DB itself, this was counter-productive. I've brought it back to 2
jobs like the other cloud databases.
2026-08-26 13:59:16 -07:00
Krishn
af1df1432c Document background task and run statuses (#80578) 2026-08-26 16:54:52 -04:00
Nemanja Glumac
d35b91c92c Run CI only for the base of a stack of PRs (#81098) 2026-08-26 22:13:51 +02:00
Andrei Chernykh
bceebfaee4 Remove dead React 17 compatibility (#81080)
Remove dead React 17 compat
2026-08-26 12:21:23 -07:00
Alexander Polyankin
55d7df2c9c Improve encrypted app-db column handling (#80785)
* Reject plaintext values in encrypted app-db columns via a strict encrypted read

Make the canonical encrypted read path strict: when MB_ENCRYPTION_SECRET_KEY is set,
a value that is not encrypted is rejected instead of trusted, so a value written
directly via SQL cannot stand in for a properly encrypted one. This relies on the
existing aes256-cbc-hmac-sha512 authentication of encrypted values.

- encryption/maybe-decrypt is now strict; the previous lenient behaviour is
  maybe-decrypt-accepting-plaintext. Every existing lenient caller (settings,
  secrets, key rotation, the encryption-check sentinel, migrations) uses the
  accepting-plaintext variant explicitly.
- models.interface: encrypted-json-out / transform-encrypted-json are the only
  (strict) variants. The explorations encrypted-text/EDN transforms are strict too.
- app-db.encryption: the rotation list (encrypted-columns) now also includes the
  exploration_query_result columns, so key rotation and encrypt-db cover them.
- A v63 clojure migration (EncryptEncryptedJsonColumns) encrypts any plaintext
  values left in the encrypted-json columns (e.g. the v58 credentials SQL backfill)
  so strict reads succeed after upgrade.

Secrets and settings keep the lenient path for now and will be handled in follow-up PRs.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* Use explicit arities for maybe-decrypt / maybe-decrypt-accepting-plaintext

Replace the [& args] + argument-sniffing with plain [v] / [secret-key v] arities, which
is unambiguous (the value itself can be a byte array).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* Make secrets strict; move credentials migration to v58; split decrypt by type

- Narrow the re-encryption migration to auth_identity.credentials only (the sole
  column the v58 SQL backfill wrote as plaintext) and move it to v58 so it backports
  to every affected release. Other encrypted columns are always written encrypted and
  covered by encrypt-db, so they need no migration.
- transform-secret-value is now strict (secrets reject plaintext at rest); encrypt-db's
  secret loop reads raw + lenient so the enable-encryption-later flow still works.
- Split the decrypt helpers by value type like maybe-encrypt/maybe-encrypt-bytes:
  maybe-decrypt / maybe-decrypt-bytes (strict) and their -accepting-plaintext lenient
  counterparts, with String/bytes type hints and explicit arities.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* Drop the -accepting-plaintext decrypt variants; use strict + explicit try/catch

The lenient variants silently returned plaintext, which conflates "legacy plaintext
(fine)" with "corrupt/invalid" — and only the caller knows which. Notably the
encryption-check sentinel treated a plaintext UUID as :valid when it should be :invalid.

Each caller now uses the strict maybe-decrypt / maybe-decrypt-bytes and handles the
throw explicitly: the sentinel and the startup check treat a decrypt failure as
invalid; key rotation and the secret loop tolerate plaintext (guarding with
possibly-encrypted-*?); settings and migration reads fall back to the raw value.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* Remove now-unused metabase.test require in encryption-test

Left over after dropping the lenient-decrypt tests.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* Reintroduce -accepting-plaintext decrypt variants for plaintext-tolerant callers

Bring back maybe-decrypt-accepting-plaintext / maybe-decrypt-bytes-accepting-plaintext so the
plaintext-tolerant callers (settings reads, migration reads, key rotation and the secret loop)
call them directly instead of wrapping the strict maybe-decrypt in try/catch.

The encryption-check sentinel and the startup key-check stay strict, but now express it as an
explicit possibly-encrypted-string? guard + lenient decrypt so a plaintext UUID still reads as
invalid (rather than being trusted) without a try/catch. The core app-db column transforms
(models.interface, exploration) remain strict.

Also apply review nit: maybe-blob->bytes uses cond->.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* encrypt-db: also re-encrypt secret-value BYTES columns (stored_result.result_data)

stored_result.result_data (like secret.value) is a mi/transform-secret-value byte column, read
strictly via maybe-decrypt-bytes. do-encryption only re-encrypted secret.value, so a result_data
written as plaintext before a key was set stayed plaintext, and once a key is set the strict read
throws (500 on GET /api/exploration/query/:id).

List both byte columns and loop over them. Rename encrypted-columns -> encrypted-string-columns and
add encrypted-bytes-columns, splitting the two lists by wire type (string vs bytes).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* Address review: stream re-encryption; fail instead of double-encrypting undecryptable values

- `maybe-decrypt-accepting-plaintext` / `maybe-decrypt-bytes-accepting-plaintext` now throw when a value looks
  encrypted but cannot be decrypted with the current key, instead of logging and returning it unchanged. Returning it
  let the key-rotation path re-encrypt it into `encrypt_new(encrypt_old(x))`, permanently unrecoverable. They still
  return genuinely-plaintext values as-is.
- Re-encryption streams rows via `reducible-select` (the string path and a new bytes helper) so a large column such as
  `stored_result.result_data` is not held in memory all at once, and catches the strict decrypt to clear (clearable
  columns) or abort rather than double-encrypting.
- Callers that must tolerate the throw handle it: the `encryption-check` sentinel and `check-encryption` treat a
  decrypt failure as a wrong key; the Setting after-select degrades gracefully on read; `encrypted-json-out` (migration
  reads) returns the raw value on failure.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* Fix rotate-encryption-key test for the lenient Setting read

The Setting after-select degrades gracefully on an undecryptable value (returns the raw ciphertext) rather than
throwing, so reading a wrong-key setting yields ciphertext, not a thrown exception. Assert not= plaintext instead of
thrown? for that read; the strict Database/User columns still throw.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* Encrypt api_key hashes at rest (#80902)

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-26 20:43:07 +02:00
github-automation-metabase
a135d86c9a Update translations 2026-08-26 (#81077)
* Update translation sources 2026-08-26

* Update translations

---------

Co-authored-by: github-actions <github-actions@github.com>
2026-08-26 18:41:31 +00:00
Andrei Simionescu
1f807106ab BOT-1013: Correct identifier casing when Metabot fixes SQL (#79674)
Validation transpiled with `identify=True` which quotes every identifier and
freezes its case, so a bare `subtotal` on Snowflake stopped resolving to
`SUBTOTAL`. Keep the LLM's own quoting instead, and only quote reserved words,
folded first so quoting can't change what they match.
2026-08-26 18:21:30 +00:00
Ben Grabow
245862781f Ignore flaky sync failures caused by table deletion race conditions (#81073) 2026-08-26 18:19:24 +00:00
Kevin Kelleher
acaaa73106 Use Markdown for Measure/Segment description fields (#80883)
* markdown for measure and segment descriptions

* Add unit tests that Measure/Segment descriptions render markdown
2026-08-26 17:14:10 +00:00
Ben Grabow
2e58c450be Skip extra server round-trips when loading data (#80958) 2026-08-26 12:13:54 -05:00
Ben Grabow
039a969544 Reuse the impersonation database for each impersonation deftest (#80750)
* Reuse the impersonation database for each impersonation deftest

* Remove dynamic layer of fixture
2026-08-26 16:48:24 +00:00
Ben Grabow
f5ac3e3c64 Fix flaky test caused by noise from batched query executions from other deftests (#80943)
* Eliminate noise from batched query executions from other deftests

* Update ratchets
2026-08-26 16:48:20 +00:00
Riley Thompson
44b811bdcc Use separate page-byte-budget for bigquery query execution and sync (#80849)
* save

* fix bigquery csv downloads

* remove debug
2026-08-26 16:32:51 +00:00
Maksym Yakubych
0421c77905 Normalize scalar search tool arguments (#80107) 2026-08-26 12:24:21 -03:00
Nicola Mometto
bd6f636e35 Quote ClickHouse impersonation role as a single identifier (#80820)
* Quote ClickHouse impersonation role as a single identifier

Stop splitting the role attribute on commas so the whole value is one
role identifier. This removes multi-role activation via a comma-separated
attribute.

* Escape backslashes when quoting the ClickHouse role identifier

A trailing backslash would otherwise escape the closing quote of the
role identifier. Escape backslashes before doubling interior quotes.
2026-08-26 16:17:27 +01:00
Nemanja Glumac
15ef5d5b97 Delete skipped e2e tests (#81011)
* Delete e2e tests tagged @skip

Removes 53 skipped blocks (86 test cases), the oldest of them skipped since
2020, plus the fixtures and helpers they left unreferenced. Three spec files
held nothing but skipped tests and are deleted outright.

The @skip tag itself still exists in the workflows and the matrix builder.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* Drop the @skip grep tag from the e2e workflows

No spec carries the tag anymore, so the exclusion is dead weight. With
`-@skip` gone the tagged-run expression no longer needs format() to append
it, and collapses to the input or the default tag set.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-26 16:55:15 +02:00
Phoomparin Mano
b0525d2dc4 Fix tenant collections showing up as unknown in the dashboard question picker (#80824)
* Fix tenant collection question picker

* Fix tenant collection question picker root browsing

* Add tenant collection picker hierarchy

* refactor: extract tenant collection helper module

* Fix tenant collection question picker

* refactor: cleanup unit tests

* refactor: simplify unit tests

* chore: rename synthetic root to collection

* fix: only show root collection if user has access to it

* simplify condition for shouldIncludeRoot

* fix flaky dashboard-tenant-user-question-picker.cy.spec.ts test
2026-08-26 21:51:53 +07:00
Andrei Chernykh
c2f5f3bd7a Remove unused dev dependencies (#80724)
* Remove unused dev-tool dependencies

* Add openapi-typescript back
2026-08-26 07:50:06 -07:00
Paolo Rascunà
a9f25e8645 BOT-2010: Post Metabot's Slack answer as a markdown block (#80652)
* BOT-2010: Post Metabot's Slack answer as a markdown block

Channel answers went in an `mrkdwn` `section`: no table syntax, and a
3000-char cap that cut them short. They now go in a `markdown` block at 12000.

- `final-text-blocks` emits `{:type "markdown"}`, and the answer is elided to
  `markdown-text-limit` (12000) rather than the section limit
- the prompt switches bold and strikethrough to `**text**` and `~~text~~`;
  `*one*` renders italic and `~one~` does not render at all, so the old
  dialect would have silently lost both. Link syntax is untouched --
  `<url|label>` does render inside a `markdown` block (measured)
- the test harness models Slack's real rejection for each block type
  (`invalid_blocks` for `section`, bare `msg_too_long` for `markdown`), and
  charges the markdown budget across the payload as Slack documents it.
  Without this the answer would no longer be checked by anything and the
  limit assertions would pass vacuously

Verified against the live API: a `markdown` block takes exactly 12000 chars,
Slack expands one into several as it renders -- a heading becomes a `header`,
a rule a `divider`, a table a `table` -- and that expansion counts against
the 50-block ceiling, which is why the prompt still bans headings and rules.


Co-authored-by: Paolo Rascuna <1936871+prascuna@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-26 16:40:03 +02:00
Ryan Laurie
70a3c288ed Stabilize Embedding Parameters test (#80761)
* try some stuff

* limit query
2026-08-26 08:07:11 -06:00
Stas Gavrylov
3f2ad8bd17 Upgrade Node.js to 22.23.2 (#80995)
* Upgrade Node.js to 22.23.2

* Use .nvmrc as mise Node version source
2026-08-26 16:46:12 +03:00
Chris Vandoodewaard
fd13d19cad Fix rerun notification: don't notify for PR stacks and thread rerun notifications (#81012)
* don't notify for stacks

* thread Slack notifications

* use short commit

* use run id as key

* add error handling
2026-08-26 09:45:52 -04:00
Nicola Mometto
02a1dc223b Restrict notification markdown link schemes and diff pulse recipients by email (#80597)
* Restrict markdown link URI schemes in rendered notifications

Only http/https/mailto links and images survive markdown rendering for
email/Slack notifications; other schemes and unparseable URIs are
dropped instead of being passed through (or, for malformed URIs when a
site URL is set, throwing mid-render).

* Diff pulse recipients by id or email in the subscription-permission check

Key the added-recipients diff the same way pulse-channel keys
recipients (user recipients by :id, external ones by :email) so
external-address changes are covered by the check too.

* Allow inline base64 images in notification markdown

The app's markdown renderer accepts data:image/...;base64 URIs
(DATA_IMAGE_URI_PATTERN); let notification rendering accept the same
pattern so text-card images look the same in email.

* Cross-link DATA_IMAGE_URI_PATTERN to its backend counterpart

* Share the data-image URI pattern between backend and frontend

Lift the pattern into metabase.util.markdown.image (cljc), compile it
into the frontend bundle via shadow-cljs, and re-export it as
DATA_IMAGE_URI_PATTERN so both renderers accept the same inline images
by construction.

* Apply resolve-uri to Slack images too

* Render a dropped link-ref as its text alone instead of restoring brackets
2026-08-26 12:09:26 +00:00
Kevin Kelleher
da72c9e970 Fix Trend visualization for native MongoDB queries (#80751)
remove trend viz dependency on insights
2026-08-26 07:39:10 -04:00
Sébastien
e83b3f6abe Fix flaky drill-through tests in the sdk iframe embedding spec (#80971)
Scope embed drill-through cell lookups to the table
2026-08-26 13:02:34 +02:00
Fraser
28f667591b Give every bundler the side-effect-free declarations (#80956) 2026-08-26 22:30:21 +12:00
Romeo Van Snick
5a315ad0b4 Move the action creator and embedding data picker off the metadata mirror (#80975)
* Compute the action model's write permission from the API, not the metadata mirror

* Read the embedding picker's source card from the API, not the metadata mirror
2026-08-26 20:12:41 +10:00
github-automation-metabase
a04aaf3714 Fix flaky bulk-table 'edit attributes for db' e2e (#78169)
Clicking the database row in the TablePicker before its expand handler is
wired drops the click, so the schema fetch never fires and cy.wait("@getSchema")
times out with "No request ever occurred." Gate on the expand toggle's
aria-expanded state (collapsed -> click -> expanded) so the schema request
reliably fires before selecting the database — same pattern already proven in
the sibling publish/unpublish test.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-26 12:01:39 +02:00
YB
24a9ec6182 auth-check transform source (#80328)
A transform's :query source is auth-checked against its source database but leaves out some entities named by the query. This checks those too by leveraging on QP's check-query-permissions*.
2026-08-26 09:59:55 +00:00
github-automation-metabase
49716266bf Fix flaky data-model field-description preview hovercard (#78284)
The shared verifyTablePreview helper opened the column-description
hovercard with a single one-shot realHover(). That hovercard opens on a
delayed openDelay timer, so a lone realHover can miss it: after
cy.wait("@dataset") the preview grid re-renders on a microtask and
Chrome v133+ headless hit-tests CDP mouse events differently, either of
which drops the hover and cancels the open timer. hovercard() then only
retries the query, never re-hovers, so the card stays permanently
absent for that attempt.

Replace realHover() with the re-queried synthetic mouseenter+mouseover
dispatch already proven in data-model-shared-1's local verifyTablePreview,
so the events land on the post-render DOM node.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-26 11:34:25 +02:00
Paolo Rascunà
9cd6391ce9 BOT-522: Seed the Slack agent loop with persisted conversation state (#80204)
* BOT-522: Seed the Slack agent loop with persisted conversation state

The Slack loop wrote `metabot_message.state` on every turn but always started
`run-agent-loop` with `:state {}`, so it never read back what it had persisted —
unlike the in-app path, which seeds from `conversation-state`.

This makes sure we feed the state back into the agent loop, filtering out errored messages.

Co-authored-by: Paolo Rascuna <1936871+prascuna@users.noreply.github.com>
Co-authored-by: Claude Opus 5 <noreply@anthropic.com>
2026-08-26 09:45:44 +02:00
YB
f11ceeac6e [GDGT-3088] gate slack bug reports on bug-reporting-enabled and enforce attribution to session user when non-anon (#80467)
This feature was not following the bug-reporting-enabled gate on the BE previously, and we now enforce using the session user when making a non-anonymous report.

As this is a endpoint that has been in the wild for some time, we'll first report any non-compliance first while overriding with the desired behaviour of only using the session user instead of breaking the API by returning an error
2026-08-26 14:58:41 +08:00
Romeo Van Snick
9b3874e114 Delete the entity-framework hooks (#80969) 2026-08-26 15:52:04 +10:00
Romeo Van Snick
4480309da3 Read a field's remappings through a store-owned selector (#80968) 2026-08-26 15:34:06 +10:00
Romeo Van Snick
c7690123cf Hold a dashboard's click-behavior link targets in dashboard state (#80787) 2026-08-26 12:37:40 +10:00
Romeo Van Snick
3fe2998633 Read the permissions tree's databases from the API, not the metadata mirror (#80403)
* Read the permissions tree's databases from the API, not the metadata mirror

* Record each edit's database in permissions state instead of holding subscriptions

* Take each database field from the endpoint that returns it

Two e2e failures traced to the same cause: no single endpoint returns
everything the permissions tree reads.

GET /api/database is the only endpoint that hydrates router_user_attribute
(warehouses_rest/api.clj:361 and :501). Reading the database from
getDatabaseMetadata therefore dropped it, and the "(Database routing enabled)"
breadcrumb stopped rendering.

GET /api/database/:id/metadata is the only endpoint that returns tables. The
group page's database list passes listDatabases entries, which have none, so
hasPermissionValueInSubgraph found no children and the blocked-child
confirmation never opened.

The mirror had merged both, and held them for the session. getPermissionsDatabase
now merges them explicitly, taking router_user_attribute from the list and tables
from the metadata response. The tables are kept in permissions state rather than
read back from the request's cache entry, which is dropped as soon as the admin
navigates away from that database.

databases.unit.spec.ts pins the merge with fixtures shaped like the two real
responses, which is what the previous specs could not catch: they seeded one
complete database, making the two sources indistinguishable.
2026-08-26 12:18:00 +10:00
Romeo Van Snick
7c8f7b450b Load the whitelabel settings pages lazily (#80788) 2026-08-26 11:59:21 +10:00
Alexander Polyankin
4a7f73029a Store passwords and reset tokens in auth_identity (#80718) 2026-08-25 21:52:54 -04:00
Ryan Laurie
88432c1055 Stabilize table selection in flaky segments/datamodel test (#80681)
* stabilize table selection

* wait on the network requests
2026-08-25 17:18:47 -06:00
Andrei Chernykh
b3bcce1e6b Fix timezone warning for equivalent timezones (UXW-133) (#80131)
Report the results timezone under the requested name when the two are aliases, so charts stop warning about equivalent timezones
2026-08-25 15:31:19 -07:00
github-automation-metabase
5fced6e7da Auto-update documentation for master (#80938)
Update generated docs (master)

Co-authored-by: github-actions <github-actions@github.com>
2026-08-25 21:26:11 +00:00
dpsutton
d90b61d26d use authoritative query database id from actions (#80363)
like cards, the actions table has a top level column for database
id. But we can use the canonical value on the action's query and let the
db value be for bulk lookups and as an index. But we make sure to keep
it in lockstep as we go.
2026-08-25 16:09:11 -05:00
Andrei Chernykh
6cd29dedb0 Replace legacy button CSS with Mantine buttons (#80386)
* Replace legacy button CSS with Mantine buttons

* Do not click the disabled map update button in the e2e test

* Polish admin header and add-row wrapping

* Use static view-section paddings instead of clamp
2026-08-25 14:04:03 -07:00
dpsutton
9c2ee7c41d Refuse analytics-dev DB connection/creation unless analytics-dev-mode… (#80901)
* Refuse analytics-dev DB connection/creation unless analytics-dev-mode is on

An :is-audit-dev database is a handle onto the app-db; it carries no real
connection details of its own. Reusing the app-db datasource for it is only
ever valid while analytics dev mode is enabled. Previously the connection
router only *skipped* the datasource reuse when the mode was off, silently
falling through to build a credential-less pool against the wrong host
(surfacing in CI as `FATAL: role "runner" does not exist`).

Make the invariant explicit and fail loudly at every site:
- db->pooled-connection-spec throws for an :is-audit-dev DB when the mode is off
- can-connect? throws likewise instead of reporting the DB as connectable
- create-analytics-dev-database! refuses to create the DB when the mode is off

Tests create/connect these DBs, so they now run under analytics-dev-mode=true.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BjQcjQx7NPGr3Rpf6QaG4b

* Update is-audit-dev routing test for the throw-on-invariant-violation behavior

The connection layer now throws for an :is-audit-dev database reached with
analytics-dev-mode off, rather than silently declining to route it to the app
DB. Update the test's dev-mode-off case to assert the throw.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BjQcjQx7NPGr3Rpf6QaG4b

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-25 15:47:14 -05:00
Riley Thompson
bed8a61829 External PR: db-tables as multimethod to enable driver implementation (#78842)
* clean(materialized-tables): consolidate changes for materialized tables v2

* small changes

---------

Co-authored-by: damienchambe <damien.chambe@gmail.com>
Co-authored-by: Damien Chambe <42462209+damienchambe@users.noreply.github.com>
2026-08-25 16:34:18 -04:00
Chris Vandoodewaard
5a65c04cda add -F msgcat to sort and stablize .po files (#80919)
* add -s to msgcat to sort entries by msgid

* actually sort by file
2026-08-25 16:33:18 -04:00
Denis Berezin
11e969a619 UXW-5034 New UI for database caching settings (#80034)
* UXW-5034 New UI for database caching settings

* Fix issues

* Address feedback

* Address design review fixes

* Fix e2e

* Fix wrapping description text
2026-08-25 23:30:15 +03:00
Ben Grabow
0312bafbc9 Prefix PR title with target version number (#80917)
* Prefix PR title with target version number

* Robot emoji is most important
2026-08-25 19:38:21 +00:00
github-automation-metabase
3eabd5847f Deflake dependency broken list spec (#78600)
* Deflake dependency broken list spec

visitBrokenDependencies did a bare cy.visit with no wait, so tests
immediately queried dynamically-loaded list items with only Cypress's
default 4s timeout - flaky when the breaking-dependencies API is slow.

Mirror the sibling visitUnreferencedEntities helper: intercept the
/api/ee/dependencies/graph/breaking request, wait on it, and assert the
list is visible before the test interacts with it.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* Wait for the test's own broken entities before asserting

The prior deflake waited for the page's breaking-dependencies request, but
the underlying data still raced: setup gated on a bare count
(nodes.length >= 3), which the instance's pre-existing Usage Analytics
breaking dependencies satisfy before the test's transform-table break is
analyzed. The page then rendered only Usage Analytics rows and the test's
"Test Transform Table" / question / model were absent.

Gate setup on the specific expected entities by name instead of a count,
and align the breaking helper to include personal collections (matching its
sibling waitForUnreferencedEntities) so the personal-collection question is
visible to the check.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-25 20:59:28 +02:00
Chris Vandoodewaard
b3cddb3504 Notify Slack when "Run Tests" re-runs more than 5 times (#80854)
* add workflow to notify slack on repeated reruns

* fixes

* a few more fixes

* cleanup whitespace

* update to use triggering_actor
2026-08-25 14:36:54 -04:00
Ben Grabow
b1d98f6538 Divide redshift tests first by enterprise/oss, then split by var count (#80789) 2026-08-25 18:29:11 +00:00
Anderson
adc97eaff2 Deflake dashboard title-drill anchor href assertions (#80739)
* Deflake dashboard title-drill anchor href assertions

* Park the cursor without an extra page visit
2026-08-25 17:29:31 +00:00
Ben Grabow
0a3659ea3d Fix error in Summarize test wall times (#80876) 2026-08-25 19:26:09 +02:00
Ben Grabow
4539b47457 Include full log output in profiling bundle (#80848) 2026-08-25 19:24:35 +02:00
Andrei Chernykh
6be03b850b Remove mutationobserver-shim (#80748) 2026-08-25 10:24:23 -07:00
Andrei Chernykh
38346d6268 Remove unused prod dependencies (#80663) 2026-08-25 10:23:46 -07:00
Anderson
6059647f51 Fix flaky Other pie slice drill-through e2e test (#80717)
Fix flaky Other pie slice drill e2e test and skip copy value action for grouped clicks
2026-08-25 13:53:56 -03:00
metamben
87841b3fe6 Compile current time in filters the converted timezone for Postgres (#80244)
Closes QUE2-807
2026-08-25 16:04:25 +00:00
metamben
4e60ba6fad Properly set the report timezone for ClickHouse (#80196)
* Properly set the report timezone for ClickHouse

Closes QUE2-792

* Add clickhouse to the list of tricky to stub drivers
2026-08-25 19:01:58 +03:00
metamben
36fd11b0f7 Take ClickHouse's date bucketing into account (#80110)
Closes QUE2-790
2026-08-25 19:01:46 +03:00
metamben
6ca347e9e2 Enable native pivot support for hive-like drivers (#80333)
* Enable native pivot support for hive-like drivers
2026-08-25 19:01:25 +03:00
Riley Thompson
e58b5a46fb Only rewrite temporal unit on order bys and breakouts (#80124)
* only rewrite breakouts and order bys

* remove test stuff
2026-08-25 12:01:21 -04:00
Egor Grushin
27bfc0d005 Checkbox component redesign (#80262)
* checkbox redesign

* small fix

* fix disabled checkbox visual size

* disallow checkbox labelPosition

* add new loki tests

* update loki snapshots

* fixup! update loki snapshots

* fix e2e specs relying on checkbox Icon-check/Icon-dash classes

* checkbox card border

add border-highlight token, use it for selected card

* disallow checkbox size

single 16px size; xs/sm were both 16px and md was unused

* disallow checkbox card children

* drop redundant role from checkbox icon

* checkbox card body via mantine text/stack

* forwardRef checkbox card

* drop border on disabled checkbox card

* drop disabled checkbox border ring

alpha border over alpha bg stacked into a visible ring

* hide unchecked card indicator icon

mantine hides indicator icon via color:transparent; .icon color override defeated it

* update colors loki snapshot
2026-08-25 16:23:38 +01:00
Ben Grabow
b7322989e3 Use explicit hierarchy for temporal literal classes (#79461)
The java.time classes grouped under ::->absolute-datetime and ::->time were derived in
Clojure's global hierarchy, sharing one mutable namespace with model keywords, hook traits and
every other subsystem -- and registering concrete JDK classes there is especially easy to
collide with.

Move them into a hierarchy var private to this namespace, mutated through derive! -- the same
shape as metabase.events.hierarchy, kept in-file because add-type-info is private and is the
only reader.

The prefer-method calls against Object still apply: class-to-class isa? goes through Java
assignability rather than any keyword hierarchy, so Object continues to match every temporal
class regardless of which hierarchy is in use.

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-25 09:29:38 -05:00
Riley Thompson
45516ce5cf Fix string to boolean literal coercion (#80093)
fix literal coercion
2026-08-25 10:03:43 -04:00
dpsutton
4917982a2d better development against audit db (#80349)
* better development against audit db

* Bump :discouraged-namespace kondo ratchet to 81

connection.clj now requires metabase.audit-app.core with a
:discouraged-namespace ignore (audit-db dev support), so the budget
needs +1.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01BjQcjQx7NPGr3Rpf6QaG4b

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-25 08:17:31 -05:00
Jakub Chodorowicz
a4fa8cf2ca harden the custom viz dev server url handling (#80222) 2026-08-25 14:04:21 +02:00
Fraser
b3f2191d7b Prepare visualizations for the viz-core split (#80784) 2026-08-25 23:29:47 +12:00
Chris Truter
858eee14df Add hierarchy visualization renderers (#80618)
* Add hierarchy visualization utilities

* Normalize hierarchy visualization label newlines

* Preserve ordered hierarchy traversal in visualizations

* Format hierarchy utility docstrings

* Move hierarchy visualization utilities to dev

* Move hierarchy visualization tests alongside the dev namespace

Also sort nodes unreachable from a root, so malformed hierarchies still
render in a stable order, and mark the hierarchy tests parallel.

* Keep hierarchy visualization tests discoverable by the test runner

The runner skips `dev` directories and non-`metabase.*` namespaces, so a
`dev.*` test never runs. Follow `metabase.core.modules-test` and
`metabase.core.kondo-ratchet-test`, which test dev namespaces from a
`metabase.*` test namespace, and say so in the namespace docstring.

* List hierarchy nodes without drawing a tree

`nodes` returns every tag as a flat vector, leaves-to-roots by default so a node
precedes its parents, or alphabetically on request. Ordered hierarchies break ties
by derivation order and the rest fall back to `pr-str`, both of which `hierarchy->graph`
already worked out, so there is no separate code path for the two kinds.

A test pins the topological order to `ordered-hierarchy/sorted-tags` so the dev output
cannot drift from the order the runtime uses.
2026-08-25 13:20:48 +02:00
Sébastien
5ae667c0b0 Fix flaky JWT user-session e2e in sdk iframe embed setup get-code (#80642)
* Fix flaky JWT user-session e2e in sdk iframe embed setup get-code

* Assert terms acceptance with a plain not.exist check
2026-08-25 13:08:50 +02:00
Chris Truter
a5bd647dc4 Fix ordered hierarchy ordering and validation (#80720)
* Fix ordered hierarchy ordering and validation

* Format hierarchy utility docstrings

* Mark ordered hierarchy tests parallel

* Return nil from first-common-ancestor when tags share no ancestor

Passing a tag with no ancestors as the second argument made the lookup call nil as a
predicate, so disconnected roots and tags outside the hierarchy threw an NPE instead of
returning nil.

* Reject children declared after a tag's first occurrence in any basis

The check only ran for nested vectors, so a tag introduced in one basis could pick up
children in a later one. Hoisting it into derive-basis applies the same rule to every
top-level basis.

* Ratchet down kondo ignore budgets

---------

Co-authored-by: Metabase Automation <github-automation@metabase.com>
2026-08-25 12:49:56 +02:00
Nicola Mometto
79c18e5f89 Check ChannelTemplate write permission on notification handler templates (#80469)
The notification create/update endpoints let a handler attach an existing
ChannelTemplate by id, or carry an inline template that creates, overwrites,
or deletes one, but didn't apply the permission check used when writing a
ChannelTemplate directly. Gate any such template write on
mi/can-write? :model/ChannelTemplate, mirroring the existing inline-channel
check. Seeding and the pulse->notification migration go through the model
layer directly, so they're unaffected.
2026-08-25 10:07:57 +00:00
Nemanja Glumac
4bcfa01f00 Fix kondo ratchets total ignored forms count (#80811) 2026-08-25 11:33:56 +02:00
Fraser
dd1cc22c22 Early exit the loki stress test when every changed story is loki-skipped (#80790) 2026-08-25 20:51:51 +12:00
Nicola Mometto
421f547421 Require native query permission to author native query actions (#80612)
POST /api/action and PUT /api/action/:id now require the current user to
have ad-hoc native query permission on the target database when the
submitted dataset_query is native.
2026-08-25 09:24:19 +01:00
Fraser
4071663479 Tidy module side-effects lint rule (#80734) 2026-08-25 14:12:47 +12:00
Romeo Van Snick
b9846a5b64 Load enterprise route pages through plugin route slots (#80268)
* Load the enterprise admin pages through plugin route slots

* Load the tenant collection pages through plugin route slots

* Resolve every plugin route slot in a test

* Name the chunks the plugin route slots load
2026-08-25 12:12:02 +10:00
Nemanja Glumac
adf654542a Remove ability to skip test suites upfront (#80760) 2026-08-24 17:49:51 -06:00
Fraser
e8b4febba7 Move session and subscription request types into metabase-types/api (#79346) 2026-08-25 11:27:19 +12:00
Fraser
ecdaad1ddc Prepare the visualization types for a viz-core module (#80404) 2026-08-25 11:25:00 +12:00
Alexander Polyankin
1fbd338057 Check revision revert perms against the table of the restored definition (#80553)
Check revert perms against the table of the restored definition

For Segment and Measure reverts, table_id is re-derived from the
definition on update, so check write perms against the source table of
the restored revision's definition when it has one, falling back to the
revision's stored table_id otherwise.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-24 19:05:04 -04:00
Alexander Polyankin
a408a8822c Default undeclared endpoint params to an empty map schema (#80575)
* Default undeclared endpoint params to an empty map schema

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Ignore unparsed request bodies instead of declaring them

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Pass multipart params as the request body of multipart endpoints

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Declare query and route params read by dashboard and database endpoints

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Ignore the kebab-case linter for newly declared snake_case query params

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-24 19:04:46 -04:00
Ben Grabow
2258a06f60 Don't create nested transaction which would block view of task progress (#80402) 2026-08-24 17:29:18 -05:00
github-automation-metabase
ad801f22e9 Auto-update documentation for master (#80733)
Update generated docs (master)

Co-authored-by: github-actions <github-actions@github.com>
2026-08-24 21:22:09 +00:00
Alex Yarosh
037092060e docs: remove billing page (#80722)
* remove billing

* tending to links
2026-08-24 17:00:29 -04:00
Jeff Bruemmer
93d7163cd2 docs - embedding dashboards (#79915) 2026-08-24 19:28:20 +00:00
Anderson
0361fce560 Fix flaky remote-sync conflict-modal e2e test (#80396)
* Anchor remote-sync conflict-modal test on the async conflict lifecycle

* Reword test comments per writing conventions

* Trim comments and move timeouts to request/test-level options

* Use navigation helper when navigating to the transforms page

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

* Fail fast on terminal sync task statuses

---------

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
2026-08-24 15:52:21 -03:00
Nemanja Glumac
5e53c6b689 Reduce flakiness of table-editing e2e tests (#80598) 2026-08-24 20:52:18 +02:00
Ben Grabow
6fa6eee688 Debounce tracking table writes (#80662) 2026-08-24 18:35:28 +00:00
github-automation-metabase
8339e57d2c Fix detached-DOM flake in upload table deletion e2e test (#78293)
* Fix detached-DOM flake in upload table deletion e2e test

Re-query the upload-tables-table container on each assertion instead of
caching it via within(). The table re-renders when getUploadTables
resolves, detaching the node within() captured, so a retrying query
against the stale subtree got stuck on an intermediate render.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* Appease the linter

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: Nemanja <31325167+nemanjaglumac@users.noreply.github.com>
2026-08-24 20:32:30 +02:00
Nemanja Glumac
4b8fd9848e Cover DB management permissions with targetted tests (#80594) 2026-08-24 20:25:17 +02:00
Phoomparin Mano
4852413258 Check embedding saml popup source (#80494)
* check saml popup origins

* throw when site-url does not match instance-url

* Fix SAML embedding popup validation
2026-08-24 17:39:25 +00:00
Nemanja Glumac
eb401d8b6e Skip drivers-decision analysis on force-run (#80617) 2026-08-24 19:31:26 +02:00
Chris Truter
59b8696296 Fix test-user caching across appdb swaps (#80436)
* Key cached session tokens on the app db

with-empty-h2-app-db! swaps in a different application database, and this cache was keyed on the username
alone. A token minted against the previous database names a session that does not exist in the new one, so
the request 401s, and the token minted inside leaks back out when the original is restored. The retry in
client-fn cleared the whole cache and tried again, which papered over it often enough to look like flake:
"Failed to authenticate X after three tries".

Key it on the app db as well, like every neighbouring cache does via memoize-for-application-db.

databases-list-can-upload-test and dismiss-spinner-test go from failing to passing; both were in the CI
failure list, the former across 12 jobs.

* Track globally-created test users per application database

with-empty-h2-app-db! swaps in an empty app db, where the users another database created do not exist.
`created-globally?` was a boolean, so it stayed true across the swap and user->id kept handing back ids from
the previous database. Authenticating then inserted a Session for a user that was not there:

  Failed to authenticate :crowberto after three tries: Referential integrity constraint violation:
  FK_SESSION_REF_USER_ID: PUBLIC.CORE_SESSION FOREIGN KEY(USER_ID) REFERENCES PUBLIC.CORE_USER(ID) (1)

Track the set of app dbs that have them instead. The memo beside it was already keyed this way via
memoize-for-application-db; only the flag was not.

databases-list-can-upload-test failed 8/8 before this and 0/8 after; the whole namespace now passes.

* Say what the token cache holds
2026-08-24 19:20:47 +02:00
metabase-bot[bot]
ff25772d0c [chore] Update E2E test timings with recent data (#79933)
Update E2E test timings with averaged data

Collected timing data from 7 days of test runs.
All specs with timing data were included (simple averages).

🤖 Generated automatically by update-e2e-timings workflow

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: GitHub Actions <actions@github.com>
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: iethree <30528226+iethree@users.noreply.github.com>
2026-08-24 13:13:09 -04:00
Nicola Mometto
4a47fda8d8 Reject impersonation role equal to the driver default-role sentinel (#80616)
Reject impersonation role attribute equal to the driver default-role sentinel

connection-impersonation-role now rejects a role attribute that (case-insensitively)
equals the driver's default-database-role sentinel (e.g. NONE / DEFAULT), which would
otherwise emit SET ROLE NONE and drop the connection to the base warehouse credential.
2026-08-24 17:24:16 +01:00
Alexander Polyankin
70504458f6 Strip template tags from public and embed native queries (#80574)
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-24 12:19:28 -04:00
Alexander Polyankin
54d059982c Resolve card UI parameter fields from param_fields for saved cards (#80569)
* Resolve card UI parameter fields from param_fields for saved cards

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Resolve parameters against the query for questions opened from a dashboard

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-24 12:19:27 -04:00
Alexander Polyankin
2350e6a952 Remove unused data from embed and public endpoints (#80510)
* Remove unused data from embed and public endpoints

Public and static-embed card/dashboard/document endpoints now return a
minimal placeholder dataset_query (a blank native query against the same
database) instead of selecting individual query keys. The frontend only
needs the database id here. Parameter combining and :param_fields
hydration in public-card now run before the card is trimmed since both
read template tags from the full query.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Add tests for embed card and dashboard dataset_query

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Assert strictly on dataset_query in public and embed tests

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Handle native queries in Table viz

* Fix column shadowing in HeaderCellWithColumnInfo

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Use param_fields for public question parameters

Public and static-embed card payloads carry param_fields instead of the
real query, so PublicOrEmbeddedQuestion now builds UI parameters from
them via getCardUiParametersFromParamFields, mirroring the saved-mode
dashboard path. The query-based helpers are renamed to the FromQuery /
FromParamFields scheme on both the card and dashboard sides, and the
ParameterWithTarget casts are dropped now that getParameterTargetField
accepts an optional target.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Use param_fields for embed setup card parameters

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Use param_fields for guest embed SDK question parameters

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Route card UI parameters by param_fields presence

Restores getCardUiParameters as the entry point: it delegates to
getCardUiParametersFromParamFields when the card carries param_fields
(public and static-embed payloads) and to the query-based variant
otherwise. The SDK SQL parameter surfaces use it since they serve both
guest and authenticated contexts. Also reverts the dashboard helper
renames back to getSaved/getUnsavedDashboardUiParameters.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Fix preview embed card param values

The preview-embed card values and remapping endpoints get their card via
card-for-unsigned-token -> public-card, which now replaces the query with
a blank native placeholder, so field-filter parameters could no longer be
resolved and the response schema rejected the nil result. Bind
qp.perms/*param-values-query* around the card fetch, the escape hatch
remove-card-non-public-columns already honors, matching the public
sharing values endpoints.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Add preview embed test for remapped parameter fields

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* fix

* vscode fix

* Backfill template tag parameters in param_fields UI parameters

GET /api/card/:id returns parameters as stored, unlike the public and
embed endpoints which combine them with template tags, so
getCardUiParametersFromParamFields now derives parameters via
getParametersFromCard like the query-based variant always did. Guest
embed payloads are unaffected: their parameters arrive already combined
and the blank query derives nothing.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Use getCardUiParameters dispatcher in SDK load-question

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Guard applyTemplateTagParameters by param_fields presence

Cards whose payloads carry param_fields have parameters already combined
with template tags by the backend, so re-applying from the query would
wipe them. Keying the guard on the card payload keeps it in sync with
how the card was loaded, replacing the isGuestEmbed flag checks.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Use getCardUiParameters everywhere and build test queries via Lib

Question.parameters and the query builder call sites go back to the
getCardUiParameters entry point, which now routes by param_fields
presence, leaving those files unchanged relative to master. The
template tag fallback test builds its query with
Lib.createTestJsNativeQuery instead of an inline legacy map.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Make getCardUiParameters the only entry point

The FromQuery and FromParamFields variants are private to cards.ts now;
all consumers call getCardUiParameters, which routes by param_fields
presence.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Build preview embed remapped-fields test query via lib

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Restore null fallback in useAvailableParameters

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Fix

* Preserve query type in stripped public and embed card queries

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Add placeholder aggregations to stripped MBQL queries

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Keep parameter template tags in stripped native queries and revert FE workarounds

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Export parameter-template-tag? via import-vars

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Add test for :param_fields hydration on GET /api/card/:id

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-24 12:19:27 -04:00
Andrei Chernykh
c0ed9ab9af Remove unused @types/ packages (#80568)
Remove orphaned @types stubs, move @types/js-yaml to devDeps
2026-08-24 08:50:48 -07:00
Chris Truter
6482f14a58 Respect Metabot permission mode when resolving access (#80468)
* Clear All tenant users metabot permissions when switching to group-level mode

Switching metabot permissions to group-level only wiped the All Users magic group's rows.
Under tenants the simple mode also writes to All tenant users, and since resolution takes the
most permissive value across a user's groups, a leftover :yes there overrode every group-level :no.

POST /advanced now clears both magic groups; DELETE /advanced keeps both instead of dropping the
tenant toggle. The confirmation dialog names both groups when tenants are on.

Fixes #80394

* Backfill the tenant permission cleanup and make both mode-switch dialogs tenant-aware

Instances that switched to group-level mode before the fix still carry the seeded all-yes rows
for All tenant users, so a migration clears them wherever metabot-advanced-permissions is true.

The disable dialog now says both magic groups keep their access under tenants, and both dialogs
use the "All internal users" name the permissions UI shows when tenants are on.

* Explain why the tenant-permission migration only reads the setting row

* Move the tenant-permission migration to 063 for the single backport

* Move the tenant-permission migration to 061 so it backports to every affected release

* Scope metabot permission resolution to the groups the current mode shows

Resolution took the most permissive value across every group a user belongs to regardless of
mode, so any row on a group the admin UI hides -- the All Users and All tenant users rows in
group-level mode, the seeded data-analyst rows and any API-written group in simple mode --
silently overrode every visible :no. The write-site fixes (deleting rows on POST /advanced, the
backfill migration gated on the setting row) only covered the paths that went through the
endpoint; PUT /api/setting, serdes import and PUT / on a hidden group all bypassed them.

Filter in the resolver instead: simple mode only counts Administrators, All Users and All tenant
users; group-level mode counts everything but those two default groups. Hidden rows stay in the
table and come back into force on switching modes, so POST /advanced no longer deletes them and
DELETE /advanced genuinely keeps them, which also restores the simple-mode values after a round
trip instead of leaving the default groups at all-no. With leftover rows inert the migration is
no longer needed.

* Leave the mode-switch dialog copy as it was

* Refuse the metabot permission mode switch while an env var forces the setting

The setter writes the row regardless, but the env var keeps winning on read, so DELETE /advanced would
delete every group's rows and leave the instance in group-level mode with nobody but admins allowed in.

* Flip the metabot permission mode before dropping the group-level rows

Deleting first meant a failed setting write left group-level mode in place with its permissions already gone. In the new order a failed delete only leaves rows that simple mode ignores.

* Say in the docstrings that resolution only sees the active mode's groups

* Clear the default-group rows again when switching to group-level mode

Preserving them so they returned on a switch back was a silent widening: the 061 migration seeds every default group all-yes, so a round trip through group-level mode handed everyone AI access again, including the tenant rows that caused this bug.

Both mode-switch dialogs promise removal, and nothing in the docs describes a mode remembering its old configuration, so the modes now delete the rows the other one owns, as before. Resolution stays scoped to the active mode's groups: that is what makes rows created by other write paths, and the rows already sitting on instances in the field, harmless without a migration.

* Switch the metabot permission mode in one transaction

Ordering the two writes only chose which half-applied switch an admin got: the mode changed while the rows did not, or the rows went while the mode stayed. The setting write goes last inside the transaction, since it updates the settings cache in place and a rollback would leave the new value there.

* Reload the settings cache when a mode switch rolls back

The setting write updates the cache in memory, which the rollback does not undo, so a commit failure would leave this node serving a mode the database does not have.

* Cover the settings cache in the mode-switch rollback test

The redefined setter now writes the setting for real before throwing, so the test fails if the rollback leaves the new mode in the cache.

* Extract the mode's group list to one definition

Both the resolution query and the mode-switch endpoints had their own copy of the
Administrators / All Users / All tenant users list, and read as opposites: one
selected with :in, the other deleted with :not-in. They now share
visible-groups-clause, with hidden-groups-clause defined as its complement.

* Improve Metabot permissions documentation

* Address Metabot permissions review feedback
2026-08-24 15:01:14 +00:00
Tyler Plude
3cd5fc8e1e [BOT-1899] Metabot DeepSeek direct provider support (#80054)
* initial deepseek support

* [BOT-1899] Port DeepSeek onto the LLM provider connection registry (#80100)

Wire DeepSeek into the LLM provider connection registry

DeepSeek arrived as an adapter reading its own credential settings, which is how
providers worked before the connection list. Make it a connection type like the
rest:

- `deepseek` joins `metabase.llm.provider`'s registry with the api-key and
  base-url fields the admin connection form renders itself. No key prefix:
  DeepSeek keys carry the same `sk-` an OpenAI key does, so matching on it would
  claim OpenAI keys and reject nothing.
- `llm-deepseek-api-key` / `-api-base-url` become the type's single-provider
  environment variables, reading and writing through the connection they
  configure like every other provider's.
- The adapter takes `:credentials` off the request instead of reading settings,
  so two DeepSeek connections can hold different keys.
- The frontend mirrors the new type name and gets a DeepSeek mark.

The app-db migration that folds the old per-provider settings into the
connection list is a frozen snapshot of the registry as it stood then, and stays
untouched: no released version wrote a DeepSeek setting, so there is nothing to
adopt, and a rollback drops the connection because the versions it rolls back to
cannot serve DeepSeek either. A test pins that.

Regenerated the settings docs, and listed DeepSeek among the providers you can
bring a key for.

* revert docs changes

* review feedback

---------

Co-authored-by: Maksym Yakubych <maksym@metabase.com>
Co-authored-by: Maksym Yakubych <undrfined@gmail.com>
2026-08-24 10:35:50 -04:00
Kamil Mielnik
5f8ff14492 GDGT-3141 [Flaky Test]: should render saved top level blocks (#80614) 2026-08-24 21:24:04 +07:00
Sloan Sparger
185e6d7878 [Metabot] Add prompt toggle button to the SQL editor header (#80379) 2026-08-24 11:08:59 -03:00
Stas Gavrylov
a90f1170ba GDGT-2460 Update Toast styles (#80327)
* GDGT-2460 Update Toast styles

* GDGT-2460 Port Toast to Mantine Notification

* Update Loki Snapshots

---------

Co-authored-by: Metabase Automation <github-automation@metabase.com>
2026-08-24 16:46:10 +03:00
github-automation-metabase
3af49a24f7 Auto-update documentation for master (#80555)
Update generated docs (master)

Co-authored-by: github-actions <github-actions@github.com>
2026-08-24 09:39:32 -04:00
Chris Vandoodewaard
c15af0329d update driver-test-results with missing driver tests (#80551)
* add dependency on all driver tests

* sort the list
2026-08-24 13:28:01 +00:00
Chris Vandoodewaard
19747d61b0 use CI Conductor base url from vars instead of secrets (#80552) 2026-08-24 09:23:59 -04:00
Kevin Kelleher
3235182102 Remove group prefixes from Explorations, use curated dimension display name (#79603)
* Remove group prefixes from dimension labels, use curated display-name

* fix error after merge
2026-08-24 13:14:04 +00:00
github-automation-metabase
e1ed14d77f Fix flaky native database source selectDatabase detach (#78266)
* Fix flaky native database source selectDatabase detach

The database picker popover opens automatically and re-mounts its rows as the database list finishes loading, which could detach the target row while Cypress waited for it to become actionable ("elements ... disappeared from the page"). Anchor the click in selectDatabase behind a visibility assertion so Cypress re-queries the popover chain on detach and clicks a freshly attached, settled row.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* Force-click the native database picker row to avoid detach

The database picker popover opens automatically and, as GET /api/database
resolves, its onQueryStarted hook re-writes shared metadata. That hands the
selector a fresh databases array reference and re-mounts the AccordionList rows.
The previous visibility-anchored click still entered Cypress's actionability
wait, during which the target row detached ("elements ... disappeared from the
page"). Click the row with { force: true } so Cypress fires the moment the row
is found and visible, skipping the actionability wait window in which the
re-mount can detach it.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: Uladzimir Havenchyk <125459446+uladzimirdev@users.noreply.github.com>
2026-08-24 14:18:45 +02:00
Paolo Rascunà
638d0e4cb2 BOT-1606: Truncate over-long Metabot answers instead of going silent (#80105)
* BOT-1606: Truncate over-long Metabot answers instead of going silent

`channel/final-text-blocks` put the whole answer into a single Slack `section`
block. Slack caps a section's `text.text` at 3000 characters, so any longer
answer came back as `invalid_blocks` ("must be less than 3001 characters") and
the thread simply went quiet -- no answer, no error, nothing to retry.

Elide the answer at the limit, and when that actually cuts it, follow it with a
`context` block saying so and linking to the full answer in Metabase. The notice
is deliberately kept out of the message's `:text`, which `thread->history`
replays back to the model as the assistant's own words.

The answer stays a single mrkdwn `section` block, as before. Answers that already
fit are byte-for-byte unchanged: `u.str/elide` returns its input untouched.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>

* BOT-1606: Address review comments on the truncation notice

Works through appleby's review nits on #80105:

- Docstring summary for `truncation-notice` is one sentence (continuation
  aligned to 3 spaces, matching the rest of the file).
- The notice now names the limit, so a reader can judge how much to trim:
  "This answer was longer than 3000 characters."
- Adopted the suggested "...and try again." ending.
- Added a debug log on the truncation path, recording the answer length
  against the limit.
- Moved the shared `oversized-answer` fixture into `slackbot.test-util`;
  `channel_test` and `api_test` had identical copies.
- `slack-section-text-limit` now derives from the production constant
  rather than restating it, which makes the drift test redundant.

`log/debugf` evaluates its args only once the level is enabled, so the
debug log was verified through the REPL with log capture on rather than
through the suite, which cannot reach it.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ew4fCZUQC2fu4MZ7JamMLm

* BOT-1606: Cap the visualization title so Slack accepts the message

The truncation shipped so far only guarded the answer block. The error in
BOT-1606 names `/blocks/1`, which is the visualization title block, not the
answer: `format-viz-title` embeds a `/question#<base64-query>` link, and for
a large query that base64 alone runs past Slack's 3000-character section
limit, so `chat.postMessage` rejects the whole message.

Reproduced with a native query of the size Metabot routinely writes: a
7,119-character SQL string yields a 9,770-character link and a 9,820-character
title block, and Slack returns the reported error verbatim.

A cut URL is a broken URL, so drop the link rather than truncate it and keep
the title; with no title left, `viz-output->blocks` already falls back to
"Query results". `section-text-limit` becomes public for this -- streaming
already required the channel namespace, so no new dependency.

Both this and the answer truncation log at `info` rather than `debug`:
`metabase.slackbot` inherits INFO from log4j2.xml, so a debug line there is
invisible on a default instance. Link drops get their own counter rather than
reusing `responses-truncated`, which counts responses; a long answer and a
long query link are different problems and worth telling apart.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ew4fCZUQC2fu4MZ7JamMLm

* BOT-1606: Fall back to plain text when Slack rejects the blocks

`send-channel-response` logged a failed `chat.postMessage` and stopped
there, so a user whose message Slack refused saw the "is doing science..."
status and then nothing. `send-dm-response` already retries with a
plain-text reply; do the same here, with the same wording.

A plain-text reply carries no blocks for Slack to reject, so it survives
whatever made the block message fail -- including causes we have not
anticipated and so cannot cap the way the answer and viz title are capped.

Add `responses-undeliverable`, incremented from both paths when the
fallback fails too. It counts only total delivery failure: a response the
fallback rescues is deliberately not counted, so the metric answers "how
often did a user get nothing at all", which is the alertable question.

Left the error-cleanup fallback in `send-dm-response` uncounted -- that
path is already reporting a thrown exception, and its fallback carries an
error notice rather than an answer.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ew4fCZUQC2fu4MZ7JamMLm

* BOT-1606: Cap alt_text, and stop miscounting title-only elisions

Follow-ups from a Clojure review of the branch.

Slack caps an image block's `alt_text` at 2000 characters, not the 3000 it
allows a section block, and `viz-output->blocks` passed the raw title
straight through. A title of 2001-3000 characters therefore cleared
`format-viz-title` untouched -- comfortably inside the section limit -- and
then failed `chat.postMessage` with `invalid_blocks`: the same silence this
branch exists to fix, reachable through the function it hardened. Cut the
title with `limit-chars` rather than `elide`, since alt text is plain and an
ellipsis would only eat into the budget.

`format-viz-title` also reported a dropped link whenever the rendered title
was over the limit, including when there was no link at all -- logging
`link_length=0` while claiming a drop, and incrementing `viz-links-dropped`
for something that never happened. Both cases still elide the title; only the
reporting now branches.

Docstrings: several first lines ran on into the next line, which
https://guide.clojure.style/#docstring-summary asks not to happen. Also
`format-viz-title` claimed to return nil only when given neither a title nor
a link, though it also returns nil for a link too long to keep -- as the
branch's own test asserts -- and `slack-section-text-limit` restated the
sentence from the var it aliases.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Ew4fCZUQC2fu4MZ7JamMLm

---------

Co-authored-by: Paolo Rascuna <1936871+prascuna@users.noreply.github.com>
Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-24 14:01:11 +02:00
github-automation-metabase
1081fb8c02 Fix flaky alerts toggle e2e in sdk iframe embed setup select-embed-options (#78285)
* Fix flaky alerts toggle e2e: re-query preview iframe for Alerts click

The 'toggles alerts for question when email is set up' spec cached the
embed preview iframe body via within() and chained the Alerts button
visibility assertion straight into the click. Toggling the sidebar
options re-renders the embedded question, so the cached body and the
found ActionIcon detach mid-click ('the page updated while this command
was executing'). Re-query the iframe body fresh and split the visibility
assertion from the click so Cypress retries against a stable element.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* Give re-render-dependent alerts lookups a longer timeout

Iteration 1 removed the mid-click detach by re-querying the preview
iframe body, and 49/50 burn-in runs passed. The residual failure is a
different flake: toggling a sidebar option re-renders (and re-runs the
query of) the embedded question inside the already-loaded iframe, and
that round-trip occasionally exceeds Cypress's default 4s command
timeout, so findByRole for the "Alerts" button times out with only a
"group" role present in the iframe body. Give the Alerts button and
alert-modal lookups that depend on a re-render a 15s budget so Cypress
waits the slow re-fetch+render out instead of asserting mid-render.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: Sébastien <sebastien@metabase.com>
2026-08-24 13:13:39 +02:00
github-automation-metabase
4ba63550a4 Harden embedding-hub sandbox column-update e2e flake (#78620)
The "should update existing sandboxes when changing column selection"
test raced in two ways:

- It waited on @updatePermissionsGraph with the default 5s request
  timeout, but the "Next" click first runs several sequential metadata
  fetches (list tables, list databases, permissions-graph revision)
  before issuing that PUT, so under load the request can appear later
  than 5s and the wait times out. Give it a 15s timeout.

- It asserted H.undoToast().should("not.exist") with no positive anchor,
  which can pass against an unrendered page. Anchor it on the positive
  success signal ("Select data" step marked complete) first.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: Sébastien <sebastien@metabase.com>
2026-08-24 13:00:31 +02:00
Phoomparin Mano
582d66e9c1 Allow embedding sdk target for saml popups (#80479)
* check for origins in saml popups

* log origin of login
2026-08-24 10:46:48 +00:00
Ngoc Khuat
04b84f8b77 Add connection and read timeouts to python-runner requests (#80080)
* Add connection and read timeouts to python-runner requests

* Tighten timeout docstrings

* Cancel the runner on a client timeout, retry transient log-poll timeouts

Review follow-ups on the python-runner timeouts:
- a client-side timeout on /execute now fires /cancel, so the runner
  stops working on a run nobody is waiting for
- a read timeout while polling /logs is retried instead of ending the
  poll loop for the rest of the run
- use u/seconds->ms instead of inline math
2026-08-24 16:34:27 +07:00
YB
9adb94e945 [GDGT-3085] adhere to HTTP put spec for notification API (#79821)
PUT /api/notification/:id accepted a different id from what was in the URL which diverges from normal PUT behaviour. This fix aligns it with how we've handled PUT updates in this codebase by only handling allowlisted params for the update.
2026-08-24 09:10:26 +00:00
github-automation-metabase
9139563930 Deflake SDK question data-picker target-collection test (#78105)
* Deflake SDK question data-picker target-collection test

The "change target collection to a different entity id" test blindly
pressed Escape then clicked "Pick your starting data" to open the data
picker. In the embedding SDK the DataStep always renders the data picker
and auto-opens it when no source table is selected, and that open state
settles asynchronously after the collection re-render. When the popover
auto-opened after the blind Escape, the follow-up click toggled it back
closed, so H.popover() never appeared and the Orders lookup timed out.

Wait until the popover is actually gone after Escape before reopening it
from a known-closed state, and use visibility anchors instead of exist,
removing the toggle race.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* Deflake SDK question data-picker target-collection test

The embedding data picker uses isInitiallyOpen={!table}; with questionId="new"
no source table is ever selected, so the picker auto-opens on every re-render and
stays open. The prior approach toggled it (esc to close, click to reopen), which
raced the async auto-open: sometimes the click toggled the just-opened popover
shut, sometimes esc failed to close it at all. Interact with the already-open
popover directly to remove the toggle race.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-24 10:55:14 +02:00
Fraser
dd308471eb Remove the dead push-event arms from the affected-tests stats upload (#80583)
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-24 09:37:02 +02:00
metabase-bot[bot]
5f354e3df2 [chore] Update E2E test timings with recent data (#80580)
Update E2E test timings with averaged data

Collected timing data from 7 days of test runs.
All specs with timing data were included (simple averages).

🤖 Generated automatically by update-e2e-timings workflow

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
Co-authored-by: GitHub Actions <actions@github.com>
2026-08-23 20:28:05 +02:00
Ben Grabow
fbc2d9d323 Use explicit hierarchy for metabot reaction types (#79465)
Reaction types registered by defreaction derived from :metabot/registered-action in Clojure's
global hierarchy, sharing one mutable namespace with model keywords, hook traits and every
other subsystem. Move them into a hierarchy var private to this namespace, mutated through
derive! -- the same shape as metabase.events.hierarchy, kept in-file because defreaction is
the only writer and known-reaction-types the only reader.

This also narrows the schema-rebuild watch. It was attached to #'clojure.core/global-hierarchy,
so it woke on every derive anywhere in the application and compared descendant sets to decide
whether anything relevant had changed; now it only fires for reaction registrations.

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-22 21:57:54 -05:00
Ben Grabow
c24af85666 Use explicit hierarchy for search engines (#79462)
The legacy-cookie alias :search.engine/fulltext -> :search.engine/appdb lived in Clojure's
global hierarchy, sharing one mutable namespace with model keywords, hook traits and every
other subsystem. Move it into metabase.search.hierarchy, mirroring metabase.events.hierarchy:
a defonce var holding a hierarchy map, mutated through derive!.

All thirteen engine multimethods now dispatch on that hierarchy, and known-engine? walks it
rather than the global one.

The hierarchy has a single writer inside the search module, so it exposes only derive! and
ancestors -- the operations that are actually used.

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-22 12:22:19 -05:00
Sloan Sparger
1d961d5cc5 [Metabot] Remove dead chart analysis code (#80371) 2026-08-21 22:50:30 +00:00
github-automation-metabase
df58523076 Fix flake in writable-connection model persistence e2e test (#78277)
The model persistence test clicked the global and per-database persistence
toggles without waiting for their requests to complete, then immediately
POSTed to persist a card. The card-persist endpoint returned 400
("Persisting models not enabled for database") when it raced ahead of the
per-database setting, and the per-database toggle could fail to render when
the database page booted from a stale global setting.

Intercept and wait on both persist-enable requests before proceeding.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-22 00:48:17 +02:00
github-automation-metabase
b9292b6b6c Deflake notifications unsubscribe test on modal entrance transition (#78580)
The "unsubscribe from an alert when the user has not created it" test
clicked the Unsubscribe button immediately after a bare findByText for
the confirm modal's title. That query resolves the instant the title
mounts, while the Mantine modal is still animating in and its title
transiently covers the button's click point, so cy.click() intermittently
failed with "covered by another element".

Anchor on the title being visible first so the click is deferred until
the modal's entrance transition has settled.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-21 16:08:43 -06:00
Sloan Sparger
bd86545b79 [Metabot] Remove image_base_64 context (#80364)
remove image_base_64 context
2026-08-21 17:03:48 -05:00
Sloan Sparger
92ab58c480 [Metabot] Remove explain chart button (#80355)
* remove explain chart

* update docs

* doc change
2026-08-21 17:03:48 -05:00
John Swanson
319a3664f9 Guard queue declarations by ownership, not config equality (#80388)
Re-running mq init in a REPL (dev server startup plus test init, or a
retried :mq test-init step) threw for the exploration queues:

```
  Queue :queue/exploration-plan is already registered with different config.
```

This is because of an attempt to catch cases where we were declaring
the same queue multiple times with different config. However, this was
subtly broken in two ways:

- first, there are two phases to queue registration: declaration, and
  registration. Declaration just means "write down what queue X's config
  is." Registration means actually executing that. Our check ran on
  *registration*, not on declaration. So if there were two different
  calls to `def-queue!` for the same queue, the first one would declare
  its `def-queue*`, then the second would overwrite it, and there would
  be no meaningful check left.

- second, doing registration twice would always throw, because some
  queue configs contained functions, and declaring the function twice
  resulted in non-equal results.

Instead, we want to just check that we're not *declaring* the same queue
multiple times in different namespaces. We allow declaring the same
queue twice in the same namespace for REPL convenience - technically a
loophole, but this is similar to a check we have for `defsetting`s and
it doesn't seem to have been a problem.
2026-08-21 14:41:38 -07:00
John Swanson
e964676a23 Pin exploration auto-binning to an explicit bin width (UXW-4391) (#78060)
* Pin exploration auto-binning to an explicit bin width (UXW-4391)

Exploration charts fan one metric/dim query out into several
segment-filtered variants that share an x-axis. With {:strategy :default}
binning, the QP re-derives the bin width per variant from that variant's
own filters, so a segment that range-filters the binned column (e.g.
"Highly rated products", rating >= 4) got 0.125-wide bins while its
siblings got 0.75-wide bins.

Fix: resolve the width the QP would use for the unsegmented query
(card-level filters included, per-segment filter excluded) and pin it on
the breakout as {:strategy :bin-width}. The binning middleware never
renegotiates an explicit bin width, and bin edges snap to multiples of
the width, so every variant lands on the same bin grid. Card-level range
filters on the dim still narrow the bins, since they're shared by all
variants.

- move filters->field-map + extract-bounds from the binning middleware
  into metabase.lib.binning.util (middleware delegates; extract-bounds
  now returns nil and the middleware keeps the qp.error-type throw)
- add metabase.lib.binning/default-bin-width (exported via lib.core):
  the width :default binning resolves for a column given the query's
  own filters, nicer-breakout fixed point included
- pin it in metabase.explorations.query-plan.mbql/apply-default-bucket

* Address CR

- default-bin-width now keys its filter lookup by the column ref's own
  id-or-name (like the QP binning middleware) instead of (or (:id column)
  (:name column)) with a regression test for the bug this fixed.
- Build the segment :definition test fixtures through lib instead of the
  mt/mbql-query macro
2026-08-21 14:34:57 -07:00
Cam Saul
a816155366 Clean up usages of 'pMBQL' in our documentation (#80390) 2026-08-21 21:00:00 +00:00
Kevin Kelleher
faa3018ebf Explorations toggle for contextual interestingness (#78239)
* toggle for contextual interestingness

* update toggle, language in AI usage views

* fix test
2026-08-21 20:56:19 +00:00
Anderson
3b6a98b66b Hide the empty dashcard menu on visualizer cards whose source card cannot be downloaded (#80113)
* Hide the empty dashcard menu on visualizer cards when downloads are not permitted

* Address review comments

* Type the dashcard menu's underlying-question items as an array and simplify code
2026-08-21 20:24:30 +00:00
Nemanja Glumac
d4268ac46e Remove unused merge_group CI logic (#80535) 2026-08-21 21:58:10 +02:00
Anderson
ed16a0bc37 Migrate home cards from Emotion to Mantine (#80335)
* Migrate home cards from Emotion

* Fix x-ray icon sizing
2026-08-21 16:06:16 -03:00
Nick Fitzpatrick
866b1b7bb0 add copy value click action (#79837)
* add copy value click action

* move details above filter

* move copy into it's own section

* fix import

* e2e adjustments

* Adding unit test for column settings

* Don't show copy action on PK columns
2026-08-21 15:54:06 -03:00
Sloan Sparger
f53640862e [Metabot] Handle conversation reaching max window size (#79859) 2026-08-21 18:36:21 +00:00
Chris Vandoodewaard
29afd6c0ad turn off slack messages in engineering-ci and create Linear issues instead (#80533)
* create tickets instead of sla
ck notifications

* add CI Triage label

* add pagination

* fix

* address pr review
2026-08-21 14:31:17 -04:00
Anderson
e86c35cd4d Migrate collection header caption styles from Emotion to Mantine (#80331)
Migrate CollectionCaption from Emotion to Mantine and CSS module
2026-08-21 14:21:23 -03:00
Alexander Polyankin
7e8be17997 Improve mongo value compilation (#80509)
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-21 16:56:34 +00:00
Alexander Polyankin
13cddfb68d Don't splice unvalidated database-type into JSON-field casts (#80482)
h2x/cast already guards cast targets: a plain type name is emitted raw,
anything else is quoted as an identifier. The MySQL and Postgres
json-query implementations bypassed that route and spliced the stored
field's database-type into SQL unvalidated (CONVERT(.., <raw>) and
::<raw> respectively).

Expose the plain-type-name predicate as h2x/raw-type-name? and use it:
Postgres quotes a non-plain type as an identifier (same rule as
h2x/cast); MySQL rejects it with an invalid-query error, since
CONVERT's target type cannot be a quoted identifier.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-21 12:49:23 -04:00
Alexander Polyankin
0ea74a39ff Reject implicit-join field refs in tile endpoints (#80480)
Tile endpoints resolve latField/lonField legacy refs via resolve-field;
a ref with :source-field (implicit join) now fails fast with a 400
instead of producing a broken query. The check lives in resolve-field,
which every tile endpoint (ad-hoc, card, dashcard, public, embed,
preview-embed) reaches through tiles-query.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-21 12:49:22 -04:00
Alexander Polyankin
abf7c47f3c Strip internal query-processor keys at the query boundary (#80392)
Internal query-processor and permission keys (`:qp/...`, `:query-permissions/...`,
`:impersonation/...`, `:persisted-info/...`, `:source-query/...`) are added to a
query during preprocessing and drive permission enforcement, so a client must
not be able to supply them. Previously five separate stripper middlewares
removed them one key at a time.

Replace those with a single declarative rule: a qualified map key outside the
`:lib` namespace is an internal key and gets stripped when a query is
deserialized from JSON. The rule is a Malli `:decode/api` (and
`:encode/serialize`) transformer on the query/stage/join/clause-options schemas,
run via `lib.serialize/prepare-after-deserialization` at the JSON boundaries
(REST API request decode and app-DB read) and once as a preprocessing
middleware, `qp.perms/remove-internal-keys`, gated by `qp.pipeline/*pivot?*` so
pivot sub-query keys survive their re-run.

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-08-21 12:49:22 -04:00
Sloan Sparger
4dbf593d23 [Metabot] Key conversation state by conversation id (#78759) 2026-08-21 11:35:01 -05:00
Alexander Polyankin
ede6a0ec56 Improve API schemas (#80332)
* Improve API schemas

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>

* Keywordize nested parameter option map keys

`::parameter-with-value` only keywordizes its top-level keys (via
`normalize-map-no-kebab-case`), so on the query-string parameter path -- where
the whole value arrives as a JSON string with string keys at every level -- the
nested `parameter.options` and `dimension.options` maps kept string keys. The
api decode's `strip-extra-keys` pass then dropped those undeclared string keys,
silently emptying `:options` (a case-insensitive filter would run case
sensitively, a relative date filter would lose `:include-current`, a
stage-targeted dimension would lose `:stage-number`).

Give both option schemas a `:decode/normalize` of `lib.schema.common/normalize-map`
so their keys are keywordized before the strip pass, matching how the rest of
the lib schemas decode map keys.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* Address agent-api / xrays review feedback

- /v2/query continuation-token branch now normalizes-and-validates the embedded
  query like the query_handle branch does, instead of trusting the unsigned
  token's shape; the total-row budget is read off that validated query.
- reject-native-query! normalizes the payload to MBQL 5 (best-effort) and checks
  for a native stage with lib/any-native-stage?, so native detection no longer
  depends on how the JSON was decoded (keyword vs string keys); /v1/execute and
  the query_handle path decode with plain json/decode and let normalization do
  the keywordizing. Malformed payloads still fall through to the existing shape
  checks for their clean 400s.
- Renamed validate-query -> normalize-and-validate-query (it normalizes and
  strips, not just validates) and led its docstring with what it returns.
- xrays cell-query route params decode declaratively via a ::cell-query schema
  (:decode/api base64-decodes + validates ::root.cell-query) instead of
  base64-decoding once in the schema and again in the handler.
- Tiles reject test asserts a clean 400 (status-code) rather than any Exception.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

* Update sandbox dimension-target test for keywordized option keys

The dimension-target `:options` map now keywordizes its keys (e.g. `"stage-number"`
-> `:stage-number`), so the attribute-remappings round-trip test expects the
normalized keyword form on the way back out.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-21 11:15:18 -04:00
Brad Anderson
a4eb75df3a GRO-829 Commit embedding docs (#80186) 2026-08-21 11:14:08 -04:00
Nicolò Pretto
9ad311d127 attempt to cut admin <-> sdk cycle in modules (#80146) 2026-08-21 16:54:34 +02:00
Chris Vandoodewaard
7abb55964b display CI Conductor link for failing tests (#79601)
* add permalink to quarantine entry, update compare function to return QuarantineEntry type

* print search url to make tests easy to find

* update tests

* remove a few comments

* simplify search url
2026-08-21 10:31:14 -04:00
Egor Grushin
a28a9af735 "Send now" in the question alert modal is never disabled (#80439)
Disable "Send now" when the alert has no delivery target (#79881)

Extract alertHasValidTarget from alertIsValid: the handler and channel
checks without the subscriptions one. Send now is a one-off send that
ignores the schedule, so it gates on the target only, while Done keeps
the full check.
2026-08-21 14:44:56 +01:00
Egor Grushin
24fa76cfa8 Fix the disabled Done button in the question alert modal (#80438)
Fix disabled Done button in question alert modal (#79914)

bg is a style prop, lands inline on the root and beats the :disabled
rule in Button.module.css, so the button kept its brand background while
the label switched to the dark text-disabled token. color feeds
--button-bg instead, which the disabled rule overrides.
2026-08-21 14:27:28 +01:00
Nicola Mometto
dad470d197 Add validation and permission checks for content endpoints (#80277)
* Run full query-permission checks when compiling a native form (SEC-822)

POST /api/dataset/native compiled and returned the query after checking only
database-level native perms, so a referenced source card or card template tag
was resolved without a read check. Preprocess the query once (with inline
parameter compilation enabled), run the same check-query-permissions* checks
the run path uses (surfacing a permission failure as a 403), then compile the
preprocessed query. Also trim the response to :query and :params.

* Validate link-card entity ids on write for dashboard cards (SEC-836, SEC-832)

DashboardCard validated the link-card entity id only when building the read
query; nothing checked it on write, so a non-integer id could be stored and
would then break every hydration of the dashboard. Add a write-side check in
define-before-insert and a new define-before-update, and wrap the notification
link-card renderer in try/catch so one bad card degrades to a missing part
instead of failing the whole subscription. Adds regression tests.

* Require positive-integer entity ids in dependency backfill (SEC-830)

replace-dependencies! placed to_entity_id directly in the insert, and the
dashboard click_behavior extraction forwarded targetId with no type check. Add
an explicit pos-int? check at the insert where to-add is built (a runtime
check, not an mu/defn schema, which is stripped from prod builds), and filter
targetId to positive integers during extraction so bad ids drop rather than
making the backfill job throw. Adds regression tests.

* Validate click-behavior target ids on write for dashboard cards (SEC-830)

Review follow-up: the entity ids the dependency backfill consumes come from
dashcard click_behavior targetIds, so validate them at the write boundary as
well, keeping the deep guard in replace-dependencies! as defense in depth.
Covers both the top-level click_behavior and per-column column_settings ones,
on insert and update. Adds regression tests.
2026-08-21 08:32:38 -04:00
Romeo Van Snick
72b3d9c271 Drop the two selector-level display readers of the metadata mirror (#80400) 2026-08-21 21:21:10 +10:00
Nicolò Pretto
be612d2dc6 support passing multiple fonts in embedding (#80442) 2026-08-21 13:15:28 +02:00
github-automation-metabase
3d99e1332f Wait for query run before asserting native-conversion results (#78274)
The 'converting question to a native query' e2e test asserted on
[data-testid=cell-data] immediately after clicking 'Convert this
question to a native query' (and after 'Explore results'), without
waiting for the POST /api/dataset run to settle. Under load the
assertion raced a stale/mid-flight results table and timed out.

Mirror the working convertToSql() helper: intercept POST /api/dataset
and cy.wait for it before each cell-data assertion.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-21 13:05:29 +02:00
Kevin Kelleher
5e5b740287 Fix commenting on a chart without a timeline selected in explorations (#80378)
don't send null timeline_id to the BE in a comment's context
2026-08-21 07:00:22 -04:00
Kevin Kelleher
57ca3a007d Add row count check to column cardinality cache (#80176)
add row count check to column cardinality cache
2026-08-21 07:00:00 -04:00
Romeo Van Snick
a5e4adb11a Move plan, frame-paint, and export-format helpers out of common (#80049)
* Move plan util from common into lib utils

* Move waitUntilNextFramePainted from common into lib utils

* Move export format types from common into metabase-types

* Move plan helpers into the settings module
2026-08-21 20:32:45 +10:00
YB
866c840355 gate pulse test-send behind the subscription application permission (#80136) 2026-08-21 18:32:13 +08:00
YB
d914e47f76 escape parameter & heading text when rendering notification emails (#80055)
escape parameter and heading text when rendering notification emails
2026-08-21 18:31:57 +08:00
Andrei Simionescu
537b242202 PRO-180: Add copy to clipboard for query results (#79341)
Add a copy button to the query builder's view footer, next to download.
It copies whatever is on screen: tabular results (tables, pivot grids,
or a chart toggled to the raw data view) as tab-separated text plus a
text/html table flavor so spreadsheets paste a grid, and any other
chart as a png rendered through the same pipeline as the png download.

Copies are always formatted, matching the rendered table: remapped
columns, column visibility and order, renamed titles, click-behavior
link text, and pivot grids with their headers and totals. Raw data
stays a download concern. Copying is capped at the rows loaded in the
browser, with a toast saying when only the first slice was copied.

The clipboard write starts inside the click's user activation so Safari
accepts it, cell click metadata is built only for columns whose text
needs it so wide tables serialize in linear time, and the selected-cell
copy now shares the quoting TSV serializer.
2026-08-21 10:31:18 +01:00
Ngoc Khuat
118ee5715c Cover database detail handling on serialization import (#80334)
Cover Database connection details on serialization import

Pins the two checks in load-one! for Database: an H2 engine is refused, and
low-level JDBC keys are dropped from details, write_data_details and
admin_details.
2026-08-21 16:13:09 +07:00
Chris Truter
5f4bb206a1 Treat a 403 from construct_notebook_query as agent-facing (#79983) 2026-08-21 10:36:06 +02:00
Ngoc Khuat
a6345c149b Quote table names in the MySQL rename, and cover transform target names (#80068) 2026-08-21 08:26:26 +00:00
Nicola Mometto
992d8c36e2 Add checks to document card-creation and AST reference ids (#80145)
* Harden document card-creation permission checks

Route document create/update/copy card creation through the same checks
POST /api/card applies: create-check the target collection, read-check
each card copied by document_id FK, and query-permission-check the fields
that parameter targets name.

* Guard document AST entity ids before app-DB lookups

smartLink/cardEmbed reference ids come from free-form document JSON and
may be any value. Add a shared node-entity-id accessor that yields the id
only when it is a positive integer, and use it in the raw-entity readers
(serdes export transform, export-time dependencies, and descendants) so a
malformed reference is skipped rather than passed to a Toucan query.
2026-08-21 09:23:57 +01:00
Nicola Mometto
024aa144a0 Add access and visibility checks to comments and mentions (#80142)
* Add access and type checks to comment notifications

Mentioned users are now resolved to active users whose permissions cover
reading the commented entity before being added to the notification
recipients, matching how other delivery surfaces scope their audiences.

The TipTap text-node renderer now coerces non-string :text values to
strings so they always compile as escaped text rather than as hiccup
elements.

* Scope the comment mentions listing to visible users

GET /api/comment/mentions now applies the same audience rules as
GET /api/user/recipients: non-superusers only see users in their own
tenant, further narrowed by the user-visibility setting (:none -> self,
:group -> shared-group members, :all -> everyone in the tenant). This
also resolves the endpoint's long-standing TODO about tenant handling.

same-groups-user-ids moves from the user REST namespace into the user
model so both endpoints share one implementation.
2026-08-21 09:23:37 +01:00
Nemanja Glumac
3fea6bf3fc Fix the action creator modal flake (#80282) 2026-08-21 10:11:07 +02:00
Fraser
79f3813c3e Tolerate stale self entries in the side-effect registry spec (#80401) 2026-08-21 20:10:50 +12:00
Fraser
5516e40607 Add extension points in viz for sdk behaviour (#79436) 2026-08-21 16:23:06 +12:00
Romeo Van Snick
ebe7663ba3 Read the query's database from the API, not the entities mirror (#80267)
Read the query's database from the API in the three feature-check consumers
2026-08-21 14:09:18 +10:00
Romeo Van Snick
234c695a25 Dissolve the lib-tier type cycle between metabase-types, metabase-lib, and utils (#80053)
* Move JoinConditionOperator from metabase-lib into metabase-types

* Move font family and DeepPartial types into metabase-types

* Generate mock document ids without the lib utils uuid helper

* Import JoinConditionOperator from the api barrel in metabase-lib

* Drop lib-utils re-export shims and inline docs at the moved declarations
2026-08-21 12:26:21 +10:00
Fraser
e247190827 Make metabase/ui side-effect free (#79962) 2026-08-21 14:17:50 +12:00
Tyler Plude
8661fd4524 [BOT-1930] Self hosted vLLM metabot support (#79437)
* init vllm support

* tmp improvements

* cleanups; bump max tokens floor for vllm; env shadowed cred field guards

* fix openrouter temperature

* vllm reasoning

* fixes

* cleanups

* make vllm transport errors non-retryable

* fix vllm connect diagnostics; add recorded stream fixtures

* [BOT-1930] Rebuild vLLM support on the provider connection registry (#80103)

* Rebuild vLLM support on the provider connection registry

vLLM becomes a provider type in `metabase.llm.provider` rather than a set of
`llm-vllm-*` settings read by the adapter: a required base URL and an optional
API key, no default model, and an `MB_LLM_VLLM_API_BASE_URL` group so the
environment can configure one connection. The base URL is the credential — a
server started without `--api-key` takes no key — so it alone brings a usable
connection into existence, and the admin form renders from the descriptor
instead of a bespoke component.

Two things the adapter used to reach out for now travel with the connection:

- The connect-time preflight, which exercises tool calling and structured
  output against the model that will be used, runs from `verify-credentials!`
  under a new `probe?` flag. Only writes probe; a model listing must not spend
  a generation on the operator's server.

- Whether the served model streams reasoning, which only the probe can answer,
  is reported back as `:learned-config` and stored on the connection instead of
  in a global setting, so two vLLM connections no longer overwrite each other's
  verdict. The request path reads it from the credentials it is handed.

A vLLM connect has no default model to select, so it adopts the model its probe
exercised, and an edit re-probes against the model the connection is actually
serving Metabot.

* Document connecting a vLLM server

The provider list in the AI settings docs is hand-maintained. vLLM is the one
provider an admin can misconfigure outside Metabase, so it gets the server flags
the connect-time check looks for alongside its entry.

* fix kondo

* revert docs

---------

Co-authored-by: Tyler Plude <tsplude@gmail.com>

* review comments

---------

Co-authored-by: Maksym Yakubych <maksym@metabase.com>
Co-authored-by: Maksym Yakubych <undrfined@gmail.com>
2026-08-20 22:00:58 -04:00
Fraser
e7a84b1625 Fix Mongo native preview sidebar assertions after default-limit removal (#80395) 2026-08-21 13:39:57 +12:00
github-automation-metabase
449e3f5c76 Auto-update documentation for master (#80376)
Update generated docs (master)

Co-authored-by: github-actions <github-actions@github.com>
2026-08-20 21:18:29 +00:00
Kevin Kelleher
ce55f0cdc6 Fix axis labels for timezone naive strings (#80121)
* fix axis labels for timezone naive strings

* Update Loki Snapshots

* fix lint after rebase

* don't throw in tests

---------

Co-authored-by: Metabase Automation <github-automation@metabase.com>
2026-08-20 17:11:25 -04:00
Denis Berezin
706c3862ab UXW-4718 Dashboard tab selection not persisted on page refresh (#79669)
* UXW-4718 Dashboard tab selection not persisted on page refresh

* review fixes

* Fix unit tests

* Fix unit tests
2026-08-20 23:32:07 +03:00
Anderson
723aebae08 Aggregate region and grid map tooltips when the mapped dimensions are not unique (#80027)
* Aggregate map rows sharing a region or grid cell and warn about unaggregated data

* Fix comment
2026-08-20 17:19:59 -03:00
Ben Grabow
06f7a3ca8b Bgrabow/profile tests workflow (#80258)
* Add workflow dispatch/profiling options to app-db, backend, semantic-search workflows
2026-08-20 20:12:09 +00:00
Chris Vandoodewaard
e30fb0cec1 report all test results on rerun to CI Conductor (#80326)
* upload all pass/failures for backend tests on rerun

* also for frontend tests

* add some tests

* cleanup whitespace

* copilot review

* a few more fixes from local review

* determine rerun from github context instead of input
2026-08-20 14:50:15 -04:00
Ben Grabow
9add75e67f Use content-based cache keys for m2, bun, cypress, eslint. (#80219)
* Use content-based cache keys for m2, bun, cypress, eslint.
Eagerly populate cache on push to master/release for m2, bun, cypress.
Read-write eslint cache from every branch.

* Handle multiline outputs

* Remove unneeded M2 restore on prepare-frontend

* Handle potentially multiple cyprss version matches. Update commentary.

* Validate list of alias combinations in use across the repo

* Check preresolve aliases in parallel
2026-08-20 12:38:42 -05:00
github-automation-metabase
af4fd281b4 Auto-update documentation for master (#80250)
Update generated docs (master)

Co-authored-by: github-actions <github-actions@github.com>
2026-08-20 13:27:35 -04:00
Nicolò Pretto
6f36c446e6 remove --no-package-lock from embedding host app tests (#80094)
remove --no-package-lock
2026-08-20 18:30:08 +02:00
lbrdnk
c010ae765a Reuse workflow to dockerize an image in perf test workflow (#80205)
* Reuse dockerize workflow

* Remove uberjar job from labeled workflow
2026-08-20 18:17:55 +02:00
appleby
b6edd4379c Enable Qwen 3.8 Max via OpenRouter (#79735)
* Enable Qwen 3.8 Max via OpenRouter

* Downgrade tool_choice "required" to "auto" for qwen3.8-max

Alibaba returns a 400 request error if you pass tool_choice "required" and unlike moonshot / Kimi K3, does not allow
you to disable thinking mode for Qwen 3.8.

* Add coerce-stringified-scalars to transform tool call args

Qwen 3.8 sometimes sends integer args as strings, like `{:limit "15"}`. Use the tool's declared schema to
automatically transform any simple numeric or boolean scalars.
2026-08-20 08:29:53 -07:00
Timofey Kachalov
7e3d167c05 Adjust skills to instruct using default Question components when possible (#80248) 2026-08-20 19:24:21 +04:00
Nicola Mometto
ef87a8221e Guard transform revision history per snapshot (#80088)
* Test: transform revision diffs should not include past source bodies

A transform's revision history diffs two full snapshots, so every past
:source (native SQL / Python body) and :source_database_id shows up in
the diff - even for versions that read from a database the current
viewer has no query access to. Add a test asserting the diff only
describes that the source changed, without reproducing the old source.

* Guard transform revision history per snapshot, not per current row

* extra guards in metabot tool
2026-08-20 15:16:56 +01:00
Timofey Kachalov
4c5abeb77e Add description field for data apps (#79544) 2026-08-20 17:57:34 +04:00
Sloan Sparger
fdc8caffe7 [Metabot] Handle tool-calls finish reason (#79860) 2026-08-20 14:53:51 +01:00
Stas Gavrylov
62c29ab1eb GDGT-2932: Refactor AI Analytics views to use internal routes and shared layout (#79010)
* GDGT-2932: Refactor MCP/CLI analytics to shared-layout + nested routes

Replaces the tab-query-param pages with a shared layout (header, tab
navigation, filter bar, and a single "has any data" gate) rendering
usage/events sub-routes through an Outlet, mirroring the
dependency-diagnostics pattern. New URLs:
- /monitor/ai-auditing/mcp/{usage,events}
- /monitor/ai-auditing/cli/{usage,calls}
with an index redirect from the bare section path to /usage.

Shared filter/pagination state is passed to the active leaf route via a
typed React context (following MonitorContent's existing
useMonitorSidebarContext precedent) rather than react-router's untyped
useOutletContext.

Also fixes two bugs found in cross-review: tab links were dropping the
current query string (clearing filters on every tab switch, since
LinkTab doesn't inherit location.search), and the index redirect was
gated behind the "has data" query so a bare /mcp or /cli with zero rows
never canonicalized to /usage. Bundles a parity fix for useCliHasData
(now surfaces query errors, matching useMcpHasData) so the CLI usage
view doesn't spin forever on a failed count query.

* Fix MonitorHeaderTabs to use aria-current instead of the ARIA tabs pattern

MonitorHeaderTabs rendered its options with role="tab" (via Mantine
Tabs.Tab + a Link component), but each "tab" is a real, bookmarkable
route rather than in-place content switching — the ARIA tabs pattern
implies activating a tab doesn't navigate, which isn't true here. It
also never rendered a matching tabpanel/aria-controls pairing, since
the actual content lives in a react-router <Outlet/> outside the Tabs
tree entirely.

Rewritten as plain nav links with aria-current="page" on the active
one, matching the existing AreaTab component's approach for the same
kind of route-driven navigation. Visual pill styling is preserved via
a small CSS module. Updates the two dependency-diagnostics/tasks/mcp/
cli consumers' tests and e2e specs that asserted the old role="tab".

* GDGT-2932: Review

* GDGT-2932: Keep error count queries mounted across analytics routes

* GDGT-2932: Cleanup

* Fix task tabs E2E selector

* GDGT-2932: Address PR comments

* GDGT-2932: Cleanup

* GDGT-2932: Remove LinkTab. Introduce shared AiAnalyticsSectionLayout. Fix comments
2026-08-20 16:21:00 +03:00
Stas Gavrylov
f78ab5b83f Upgrade Scalar API Reference to 1.65.1 (#80289) 2026-08-20 15:54:15 +03:00
Fraser
7cedc004a8 Fix the module side-effect lint errors in querying/expressions (#80285) 2026-08-20 23:35:31 +12:00
Fraser
d2c5d44b63 Add a lint rule that keeps side-effect-free modules side-effect free (#80047) 2026-08-20 22:22:11 +12:00
Nemanja Glumac
ee92e5d470 Reproduce 23103 using Jest instead of e2e (#80237) 2026-08-20 11:01:14 +02:00
Nicola Mometto
f0bf525611 Require write permission to send notifications and to use inline channels (#80069) 2026-08-20 09:57:40 +01:00
Romeo Van Snick
d7e2aa3d5b Check database features through the API helper, not the v1 wrapper (#80158)
* Check database features through the API helper, not the v1 wrapper

* Move the database feature checks out of common, behind a databases barrel
2026-08-20 15:46:50 +10:00
Romeo Van Snick
da126bb88c Give the remaining app routes their own chunks (#80160)
* Give the remaining app routes their own chunks

* Fetch the home page chunk while the user signs in
2026-08-20 13:54:35 +10:00
Romeo Van Snick
4711e0c845 Always invalidate remote sync on card, dashboard and document mutations (#80148) 2026-08-20 13:54:19 +10:00
appleby
6d22e0c553 Add deepseek-v4-pro-0813 to openrouter supported-models (#80018) 2026-08-19 16:55:48 -07:00
Sloan Sparger
8ed4b9d8dc [Metabot] Reasoning style updates (#80127) 2026-08-19 22:30:28 +00:00
Romeo Van Snick
f5bdbf045d Load the dependency graph and schema viewer pages lazily (#80050)
* Move the xyflow stylesheet into the graph components

* Give the schema viewer one loader for its route and its prefetch

* Load the dependency graph from the plugin slot lazily
2026-08-20 08:22:14 +10:00
bryan
9450affe98 Sign session key hashes with a server-side secret (#80046) 2026-08-19 22:04:09 +00:00
Maksym Yakubych
25ed6e5a58 Update the OpenRouter provider logo to the refreshed brand mark (#80253) 2026-08-19 21:50:55 +00:00
Maksym Yakubych
84be938a6e fix(select): don't render option groups emptied by search (#80197) 2026-08-19 21:46:36 +00:00
Maksym Yakubych
909156c65d Deflake metabot error boundary test by loading the chat module at suite setup (#80213)
* Deflake metabot error boundary test by loading the chat module at suite setup

* Preload the chat module in the shared metabot test setup

* Use the shared metabot test setup in the error boundary spec
2026-08-19 20:56:53 +00:00
Nathan Voxland
9a0e229370 Better tracking of attached data warehouse connections (#79910) 2026-08-19 15:07:30 -05:00
Andrei Chernykh
68746a6d43 Clean up leftover JS-era config, deps, and docs after the TypeScript migration (#80032)
* Clean up leftover JS-era config, deps, and docs after the TypeScript migration

* Address review: keep .jsx in resolve.extensions, drop .js from loader tests, includes-based e2e validator filter

* Keep @babel/node for a separate deps cleanup round

* Keep js/jsx in rspack loader tests
2026-08-19 12:48:52 -07:00
github-automation-metabase
dc81dff870 Fix flaky dashboard parameter-removal e2e test (#78302)
* Fix flaky dashboard parameter-removal e2e test

The "should be able to remove parameter (metabase#17933)" test asserted on
the full dashboard URL query string with cy.location("search").should("eq",
...). The order in which parameter slugs are serialized into the URL is not
deterministic, so a correct-values-but-different-order string
(?text_starts_with=G&text_ends_with= vs ?text_ends_with=&text_starts_with=G)
could never match and the retry just spun until timeout. Empty/stale-URL
timing races produced the other observed failures.

Replace the four exact-string assertions with an order-independent helper that
parses the query string via URLSearchParams and deep-equals the expected
param map. It still retries through cy .should(callback), so async URL updates
settle before the assertion resolves.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* Wait for parameter-remove button to enable before clicking

The parameter-removal step in the dashboard parameters spec clicked the
sidebar's Remove control via cy.findByText("Remove"). That query resolves to
the button's inner label <span>, not the <button> element. A span is never
"disabled", so Cypress's actionability check did not wait: it clicked the span
while the underlying button was still disabled.

The Remove button stays disabled until the dashboard's subscriptions have
loaded (the sidebar warns before archiving any subscription bound to the
filter). When that GET /api/pulse request was slow, the click landed on the
disabled button as a silent no-op, the parameter was never removed, and the
subsequent URL assertion timed out waiting for the slug to disappear.

Target the button element by role and assert it is enabled before clicking so
the click waits for the subscriptions request to settle.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* Fix linting error

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: Nemanja <31325167+nemanjaglumac@users.noreply.github.com>
2026-08-19 21:30:30 +02:00
github-automation-metabase
8107c34e1d Auto-update documentation for master (#80120)
Update generated docs (master)

Co-authored-by: github-actions <github-actions@github.com>
2026-08-19 15:22:08 -04:00
Nick Fitzpatrick
97ecbeab61 Update auto 'Show Dots' logic (#80071)
* Update auto 'Show Dots' logic

* Update Loki Snapshots

* PR feedback

---------

Co-authored-by: Metabase Automation <github-automation@metabase.com>
2026-08-19 16:09:30 -03:00
github-automation-metabase
3ea4987f1f Fix flaky revision-history dashboard test (#78280)
The test opened the info sidebar right after an ad-hoc edit-mode save that
only awaited the PUT /api/dashboard request. The trailing query_metadata
reload re-rendered the header, dropping the 'More info' click so the
sidesheet never opened. Use the H.saveDashboard() helper, which waits for the
full save-and-settle sequence before proceeding.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-19 21:07:10 +02:00
bryan
58c85c338c Only serialize Channel :details for callers who can write the channel (#80057) 2026-08-19 13:00:45 -06:00
github-automation-metabase
d056853a8c Fix flaky segment_created tracking e2e test (#78610)
* Fix getTable intercept in segment_created tracking e2e test

The segment editor's DataStep loads a table via fetchTableMetadataAndForeignKeys, which calls GET /api/table/:id/query_metadata. The test intercepted the bare GET /api/table/:id endpoint instead, so cy.wait("@getTable") always timed out because that request never fires in this flow. Point the intercept at the query_metadata endpoint the editor actually calls.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* Gate segment filter click on enabled Add-filters button

The segment editor renders a disabled "Add filters to narrow your answer"
button until onChange builds the query from fully-loaded table + FK metadata.
Waiting on the getTable response alone isn't enough — the trailing foreign-key
metadata loads race the click, so the click lands on the still-disabled button
and the filter popover never opens. Assert the button is enabled first.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-08-19 20:55:18 +02:00
Nemanja Glumac
368c50f7e4 Explicitly exclude old-migrations-test tag (#80214) 2026-08-19 20:50:00 +02:00
Chris Vandoodewaard
3c70c47538 Revert "only publish Github release for major and gold releases" (#80220)
Revert "only publish Github release for major and gold releases (#79478)"

This reverts commit 814b57b74a.
2026-08-19 18:45:08 +00:00
Nick Fitzpatrick
b872cccdde Uxw 5027 model metadata editor UI issues (#79909)
* everything except model index

* use-should-index

* remove 0.88em form label
2026-08-19 14:38:17 -03:00
Stas Gavrylov
0c5d3b3a59 GDGT-2459: Update Tooltip component (#79994)
* GDGT-2459 Update Tooltip styles

* Update Loki Snapshots

* Add Tooltip Overview Loki reference

* GDGT-2459 Add Tooltip spacing and shadow

* GDGT-2459 Use standard small Tooltip shadow

* Update Loki Snapshots

---------

Co-authored-by: Metabase Automation <github-automation@metabase.com>
2026-08-19 20:19:40 +03:00
Chris Truter
3989cb5eb3 Standardize nonparallel tests on ^:synchronized (#80064) 2026-08-19 17:15:36 +00:00
Chris Vandoodewaard
83adb8f686 make cross version tests run using Postgres (#79091)
* add sample db

* delete cross version 57 since we don't support it anymore

* update cross version tests to use postgres

* fix modal selector to work on v1.60

* fix modal selector for v60 and v63 compatibility

* add better logging

* use qa image

* use herestring to handle large output properly

* use data from WA image

* fix flake in nested model assertion

* cleanup the README

* code review fixes
2026-08-19 13:11:33 -04:00
Nick Fitzpatrick
3e9460c53e Uxw 4977 show collection that couldnt be synced (#79652)
* updating remote sync enpoint error response

* adding FE types

* Show required dependencies on sync enable

* modal version

* tests

* maz feedback

* Handle Our Analytics case

* Code review fixes

* Fixed bad fix

* Rebase and cleanup

---------

Co-authored-by: Nathan Voxland <nathan@metabase.com>
2026-08-19 13:38:03 -03:00
Chris Truter
6327ba0828 Stop LLM impersonation tests leaking cached field values (#80178) 2026-08-19 18:03:07 +02:00
Anderson
6b4af53319 Keep metric dimension rows full-width by placing the vertical scrollbar in the column gutter (#80008)
Keep metric dimension rows full-width by moving scrollbar into column gutter
2026-08-19 13:00:28 -03:00
Eric Normand
6bd66a6d5e Validate imported queries against this instance's MBQL schema (GHY-4241) (#79496)
* Validate imported queries against this instance's MBQL schema (GHY-4241)

An export decides the shape of the queries it carries, so an import can hand us
a query shape this version has no representation for. `lib/normalize` does not
always reject one: it can quietly produce something the schema rejects, which
is then stored and breaks the card on read.

After `import-mbql` normalizes an ingested query, validate the result against
`::lib.schema/query` and refuse the import if it fails. Only full queries are
checked - bare refs and the MBQL fragments inside visualization settings have no
standalone schema to validate against.

Normalization failures stay non-fatal. They fire today on content this instance
produced itself (pivot column refs in visualization settings raise
`:malli.core/invalid-schema`), so promoting them would reject legitimate
imports. Validating the successfully-normalized result catches the real problem
without that fallout.

`MB_SERIALIZATION_SKIP_SCHEMA_VALIDATION` opts out. `metabase.models.serialization`
cannot read an EE setting, so the flag reaches it through a dynamic var bound by
`load-metabase!` - the one choke point every import path funnels through.

Also validate the bundled instance analytics content against the same schema in
CI. That content re-imports on every EE boot and a failure there propagates out
of `init!` to `System/exit`, so a bundle regeneration that broke it would
crash-loop rather than degrade.

* Fix import validation documentation

* Refactor documentation for import validation settings

* update docs

* Report the schema refusal as a 400 and stop duplicating its errors (GHY-4241)

The serdes import API reads `:status` off ex-data itself rather than going
through the API layer's exception handling, so `:status-code` left it nil and
the refusal surfaced as a 500 for what is a client input error.

`u/strip-error` already renders ex-data into the message, so the truncated
`Schema errors:` tail was a second, shorter copy of `:schema-errors`.

* Drop the unreachable status code from the schema refusal (GHY-4241)

`load-one!` rewraps every exception from the load block in a fresh ex-info
carrying `path-error-data`, and the import API reads `:status` off the
outermost exception only. Neither `:status` nor `:status-code` attached here
was ever visible, so claiming one in a comment was worse than saying nothing.

* Name both causes in the refusal, and pin bundle ingest errors (GHY-4241)

`mu/defn` schemas are not instrumented in prod, so an app DB can hold MBQL the
QP tolerates but `::lib.schema/query` rejects - a stale `:join-alias`, a field
filter with no `:widget-type`. Such content exports intact and is then refused
on import, so "most likely exported by a newer Metabase" was the wrong
diagnosis for a whole class of refusals. Name both causes, and point at
continue_on_error as the per-entity escape rather than only the global one.

The bundle test proved every query imports but not that every file parses.
`ingest-list` collects unreadable files in an errors atom rather than failing,
so a malformed bundled YAML would drop out of the queries under test while
still crashing EE boot. Assert the atom is empty too.

* Move refusal rationale out of docstrings, harden a test helper (GHY-4241)

Docstrings state the contract; the reasoning behind the check, the message
wording and the sentinel moves to comments beside the code it explains.
`*skip-schema-validation?*` no longer names who binds it, which would go stale
silently. `validate-imported-query!` now says legacy MBQL 4 queries are left
alone as well, which was true but unstated.

`cause-chain-messages` used `map ex-message`, so an exception with no message
would put a nil in the vector and NPE the callers' `re-find` - failing the
test for a reason unrelated to what it asserts.

* kick ci

* Simplify the import schema check's control flow (GHY-4241)

`validate-imported-query!` returns its argument and no longer consults the
opt-out, so it is a plain step in `import-mbql`'s pipeline and the caller
decides whether to run it. That removes the sentinel `normalize-imported`
needed to keep the refusal outside its `catch`, along with the comment
explaining the sentinel.

`some->` replaces `->`, which makes `normalize-imported`'s nil guard
redundant.

* update comment
2026-08-19 15:38:28 +00:00
Michael Eby
50568b4841 docs: remove db secrets export from serialization docs (#80114) 2026-08-19 11:20:28 -04:00
Chris Vandoodewaard
272b17ffdd [Flaky Test]: should send snowplow events through admin settings (#80005)
* don't assert on toast

* dismiss toast after assertion
2026-08-19 10:57:24 -04:00
Ben Grabow
64b5ba8500 Fix flaky tests: Error rolling back after previous error: Deadlock detected. (#80126)
Retry on search reindex deadlock
2026-08-19 09:42:02 -05:00
Chris Truter
285d779b78 Use the in-process embedder for retrieval and complexity score (#78314)
* Route semantic embeddings through the provider SPI

Summary

- Register the existing ai-service, OpenAI, and Ollama implementations through the shared provider registry.
- Route semantic embedding, readiness, resolution, and preparation through the SPI while preserving the existing public adapter.
- Preserve the compatibility client model-dimensions contract by normalizing it to vector-dimensions at the provider boundary.
- Keep semantic-specific batching, metrics, and settings policy in semantic search.

Scope

This migrates consumers to the SPI. Persisted embedding-space compatibility and in-process provider selection are intentionally handled by later stack layers.

Testing

- Built-in provider behavior and existing semantic embedding adapter tests.
- Compatibility-client dimension normalization and conflict handling.

* Describe the embeddings client contract in SPI terms

The batch entry point delegates to the provider registry rather than a multimethod.

* Port complexity-test fake embedder to the provider SPI

get-embeddings-batch is a plain fn now, so the old defmethod no longer compiles
and broke every job that loads this namespace. Register a capturing provider
instead and assert on the descriptor it receives.

* Induce the dimension mismatch from the model, not the mock vector

The SPI rejects a vector whose length doesn't match the resolved model, so a dim-1 mock embedding
no longer reaches pgvector. Shrink the configured model instead, which is what an upgrade does.

* Persist immutable embedding-space identity

Summary

- Persist embedding-space IDs in semantic and library-entity index metadata.
- Backfill semantic metadata through a preserving schema migration and rebuild legacy entity vectors once when identity is unknown.
- Include immutable space identity in compatibility checks and physical table names.
- Enforce the PostgreSQL 63-byte identifier limit using UTF-8 byte length.

Scope

This establishes durable compatibility. Synchronization between entity compatibility checks and rebuilds follows in the next stack layer.

Testing

- Semantic migration preservation and backfill.
- Entity-index rebuild and compatibility behavior.
- Embedding-space table naming and non-ASCII identifier limits.

* Resolve the model in the index-cleanup test helper

record-new-index-table! now persists embedding_space_id into a NOT NULL column,
so create-test-index must build a resolved model that carries one.

* Track the index-status rename after rebase onto master

* Resolve the model-v2 variant in the reconcile tests

A bare assoc keeps the v1 embedding-space-id on a renamed model, so the rebuild wrote a meta row
whose space no longer matched what the provider resolves and nothing repopulated.

* Serialize entity index queries with rebuilds

Summary

- Coordinate library searches and reconciles with shared and exclusive PostgreSQL advisory locks.
- Keep compatibility rechecks and vector queries on the same locked connection so they cannot straddle a rebuild.
- Use non-blocking search lock acquisition so waiting searches cannot exhaust the pgvector pool.
- Preflight compatibility before embedding and return no results while a reconcile owns the index.

Scope

This PR only addresses library entity-index concurrency and degradation behavior.

Testing

- Search call ordering and locked connection reuse.
- Incompatible-index preflight and reconcile-contention degradation.

* cljfmt entity-retrieval core-test

* Follow the search-unfiltered rename in the entity-retrieval tests

Rebase fallout: the parent branch renamed `search` to `search-unfiltered`, and these call sites came across from
before the rename.

* Enable the in-process embedding provider

Summary

- Allow plugin-defined providers in semantic settings and safely encode provider names in physical index identifiers.
- Enable the bundled in-process Arctic provider with dimension readiness, query prefixing, and token metrics.
- Document the optional plugin and its glibc 2.34+ Linux or Apple Silicon macOS runtime requirement.
- Build the embedder jar in CI and run one artifact-only smoke path through the provider SPI on the OSS classpath.

Scope

This intentionally supports one pinned Arctic model. Custom model sources, MiniLM, and library overrides remain out of scope.

Testing

- Settings, prefix, token-accounting, readiness, and derived table-name regressions.
- Jar-manifest discovery, platform failure modes, batching, no-network behavior, and real ONNX inference.

* Re-hash qualified index table names over the 63-byte limit

qualify-index wraps the model table name with the metadata qualifier but did not
re-check Postgres's 63-byte identifier limit. A longer provider-encoded name plus
the qualifier could exceed it, so Postgres truncated the name on CREATE while
table-exists? still looked it up by the full name -- reporting the index table as
missing. Re-apply hash-identifier-if-exceeds-pg-limit to the qualified name.

* Hash only the table component of a qualified index name

Postgres's 63-byte limit is per identifier. Hashing the whole schema-qualified
name dropped the schema, so in app-db mode a long semantic_search.<table> became
a bare index_<sha1> created outside the isolated schema. Split off the schema and
hash only the table component.

* Cover in-process MiniLM complexity scoring

* Activate the in-process embedding provider on demand

* Stub lazy provider activation in token usage test

* Update Kondo ratchets for embedder changes

* Rely on bootstrap for in-process provider registration

* Cover the bundled complexity-score model in the artifact smoke test

The artifact job only exercised the retrieval model, so a broken or missing MiniLM
bundle -- which uses a different pooling and the three-input INT8 graph -- would have
shipped unnoticed.

* Document both bundled embedder models

* Register the in-process provider in standalone CLI mode

Provider registration happens in metabase.core.core/init!, which `--mode complexity-score`
skips entirely. A synonym axis configured for the in-process provider therefore failed with
:provider-not-registered on the CLI while working on the server.

The activation moves into metabase.embeddings.startup so both entry points run the same
routine instead of drifting apart.

* Assert the descriptor the in-process synonym embedder sends

The test claimed the embedder passes the MiniLM descriptor to the provider SPI but only
checked that it was a function, so an Arctic descriptor would have passed too.

* Pin the CLI's provider registration with a test

Nothing caught the standalone CLI skipping provider registration the first time, so assert
appdb mode registers before it scores.

* Honour :snowplow? false in the ai-service adapter

Routing single embeddings through the batch SPI dropped the option, so the health and
circuit-recovery probes started reporting their synthetic embeddings as organic token usage.

* Make the dimension-mismatch test reach pgvector

Shrinking the model with assoc kept the old embedding-space id, so resolution failed and the
query never ran -- the same path search-degrades-when-configured-model-cannot-be-resolved-test
already covers. Use a self-consistent model, stub the compatibility preflight aside, and assert
the warning that only the 22000 branch emits.

* Use dynamic redefs for the mock index's table suffix

Pre-existing on master: a plain defn redefined on one thread, so nothing here needs the root
swap. Same mock-index value either way.

* Document the tiny bundled models as a test tier

* Fix index-health-check false degraded report

row->index's :embedding-model now carries :embedding-space-id and
:embedding-spi-version, which get-configured-embedding-model doesn't
return, so the equality check in index-health-check always failed and
reported every healthy index as degraded. Compare only the keys
settings actually configure.

* Give v1 Arctic-embed models their own query prefix

model-family-query-prefixes matched every snowflake-arctic-embed
model name and prefixed queries with "query: ", which is only correct
from v1.5 onward. v1 models (including the bundled xs test-tier
model) expect the longer CQE-style instruction instead.

* Carry the plugin-name pin into embeddings.startup

The provider registration this branch moved into
embeddings.startup/ensure-in-process-provider! re-duplicated the
manifest name as its own private literal. Make it the one public
constant both the startup logic and the tests reference, instead of
reintroducing a third copy.

* Correct the Arctic Embed query-prefix cutover to v2.0

The generation split is at v2.0, not v1.5. m-v1.5 was getting "query: "
when it wants the longer instruction, and m-long matched neither pattern
so it got no prefix at all.

Replace the two mutually-exclusive patterns with an ordered first-match-wins
table. That drops the exclusivity constraint the previous shape needed and
covers every model in the family.

* Stop the query-prefix setting claiming `query: ` family-wide

The description predates the generation split and tells admins the whole
snowflake-arctic-embed family expects `query: `, which is wrong for the
bundled model.

* Anchor the Arctic Embed patterns to the model-name segment

Unanchored, they matched any name merely containing the family name, and
a false positive there is unsuppressable: `ee-embedding-query-prefix` can
replace a matched prefix but never remove one.

* Compare embedding spaces in the semantic health check

Settings can stay identical while a provider upgrade resolves the same
model into a new space, stranding the index. The space id is what
actually decides whether the stored vectors are still usable, so compare
that rather than provider/model/dimensions.

Resolution reaches the provider, so it can fail outright when the plugin
is absent or the platform is unsupported. That is its own incident, not
a model mismatch.

* Document the in-process semantic search model

* Add in-process semantic search integration test

* Drop incompatible legacy entity indexes

* Address embedder review findings

* Quote legacy index identifiers separately
2026-08-19 16:39:01 +02:00
Chris Truter
c9ee97eba1 Run LLM context queries with user-aware database access (#80149) 2026-08-19 13:31:13 +00:00
Nicolò Pretto
1da1d694ff fix(eajs): allow copying to clipboard in chrome (#80072) 2026-08-19 15:01:37 +02:00
Ben Grabow
ff8e7993d3 Internal load-namespaces tool to check for compilation errors (#80009)
* Internal load-namespaces tool to check for compilation errors

* Ignore load-namespaces in module checks

* lint load-namespaces

* Reject positional args

* Test the new utility

* Guard against nonexistent root.
Make the code more testable.
2026-08-19 07:56:18 -05:00
Nemanja Glumac
ac3cd1d211 Make mage driver-decisions honor the "force-run" (#80128) 2026-08-19 14:44:04 +02:00
Nemanja Glumac
22581bf881 Add e2e instructions for copilot (#80097) 2026-08-19 14:06:55 +02:00
Romeo Van Snick
5d77c90c36 Delete the reference loading slice (#80137)
* Give the reference edit forms their own save state

* Pass reference fetch state as props and drop it from the slice
2026-08-19 21:08:41 +10:00
Romeo Van Snick
2ca2e0f6d3 Carry the upload destination name in upload state (#80135) 2026-08-19 21:08:31 +10:00
Romeo Van Snick
a444fcd2af Preload the app bundles from the top of <head> (#80134)
* Preload the app bundles from the top of <head>

* Narrow the preload hint type with flatMap
2026-08-19 20:51:31 +10:00
Nicola Mometto
1a84c0616c remove unused transformer (#80117) 2026-08-19 09:41:16 +01:00
Romeo Van Snick
16906d4383 Load CodeMirror editors lazily so they leave the initial bundle (#79809)
* Load CodeMirror editors lazily so they leave the initial bundle

* Inline the single-use dynamic imports into the lazy calls

* Share the codemirror split chunk with the embedding SDK build

* Split the snippet, Python and public document pages by route instead of wrappers

* Dedupe modules shared by async chunks instead of naming CodeMirror

* Drop the duplicate metrics viewer route that master already added

* Keep barrel imports and mark the expression language side-effect free

* Move the action editor boundary to the new action-creator module

* Drop the codemirror cache group the SDK config no longer needs

* Drop props types exported for wrappers that route splitting replaced

* Delay the code fallback so a fast chunk load never flashes uncoloured code

* Render nothing while the code editor chunk loads

* Delay the whole expression widget instead of showing a spinner inside it

* Open the editors from routes and modals instead of loading states

* Fold the Metabot preview chunk into the message's own loading state

* Fold the query editor chunk into the transform pages' own loading state

* Prefetch the expression widget from the notebook so its popovers open ready

* Await the run error message now that the code editor loads lazily

* Hold the custom column popover shut until the expression widget arrives

* Wait for the expression editor to hold focus before typing into it

* Type into the page directly when asserting the read-only native editor

* Read the editor value only once its document stops changing
2026-08-19 16:02:49 +10:00
Nathan Voxland
dbe9a0acc1 Improve geojson and http requests (#80111) 2026-08-19 00:29:36 -05:00
Romeo Van Snick
3a0ac1ecba Move the segment fetch thunks into the reference module (#80059)
* Move the segment fetch thunks into the reference module

* Inject the settings endpoints in the api cache seed helper
2026-08-19 15:08:10 +10:00
Romeo Van Snick
2d2e90cf66 Fetch every plugin route factory when its route is matched (#79637)
* Fetch the routes-only plugin pages when their route is matched

* Fetch the remaining plugin route factories when their route is matched

* Load the AI settings pages as one chunk

* Say why these route files register no prefetch

* Derive the AI settings prefetch paths from the route paths

* Prefetch the model migration page like its siblings

* Count the python transform pages master already made lazy

* Give each AI settings page its own chunk
2026-08-19 15:05:14 +10:00
Nemanja Glumac
b7f4881ae8 Decide whether to build uberjar based on files changed (#80129) 2026-08-19 16:02:50 +12:00
Ryan Laurie
9b71465b85 Use eng stats api for data uploads (#79929) 2026-08-19 15:16:38 +12:00
Fraser
522b0458e0 Create FE Modularization skill (#80132) 2026-08-19 14:48:53 +12:00
Romeo Van Snick
70181282f3 Keep tiptap and prosemirror out of the initial bundle (#79964)
* Move useEntityData out of the tiptap SmartLink node module

* Load the Metabot chat panel lazily

* Load the public document page lazily

* Recover from a failed fetch of the Metabot chat panel

* Fetch the public document chunk at startup
2026-08-19 12:40:29 +10:00
Romeo Van Snick
1f9d8f05ba Give the remaining route subtrees their own chunks (#79738)
* Fetch the data studio, model and snippet pages when their route is matched

* Fetch the monitor and timeline pages when their route is matched

* Name the chunks the route loaders build

* Fetch the AI auditing and library pages when their route is matched
2026-08-19 12:37:47 +10:00
Romeo Van Snick
b8584138cb Resolve the segment thunks' table and database from responses, not the mirror (#80058) 2026-08-19 12:25:52 +10:00
Romeo Van Snick
4525787c27 Fetch reference pages through one loading bridge instead of two (#80056) 2026-08-19 09:35:51 +10:00
Nemanja Glumac
63f77fa7c3 Decide whether jobs run at all before hitting the test-plan (#80091) 2026-08-18 23:06:47 +00:00
Denis Berezin
4c73becf0e Fix e2e test flakes (#79791)
* Fix e2e test flakes

* Revert timeout
2026-08-19 02:04:21 +03:00
Egor Grushin
741ed577d9 Security Center: Markdown (#79737)
* GDGT-2977 Style full markdown output in shared Markdown component

- Markdown.module.css covers every CommonMark+GFM element as :where() base layer
- compact prop for line-clamped previews
- disallowHeading renders headings as paragraphs instead of unwrapping to text
- drop duplicated rules from AIMarkdown, delete AdvisoryCard.module.css
- kitchen sink fixture + stories + spec failing on unstyled elements

* GDGT-2977 Trim markdown specs to our own behavior

- drop tests that only exercise react-markdown/remark-gfm
- cover urlTransform (metabase://, data:image, unsafe protocols)
- assert headings render as p when disallowed
- merge AdvisoryCard markdown cases

* GDGT-2977 Fix markdown spec asserting against mantine style tag

- container.firstElementChild was the injected <style>, so every
  querySelector check passed vacuously
- render into a host element and select the markdown root from it
- javascript: urls collapse href to empty, which drops the link role

* addressing the PR's comments

* GDGT-2977 Match skeleton caption tooltip to legend caption

compact + lineClamp, per PR review

* fix small regression
2026-08-18 23:36:09 +01:00
Fraser
e81d02d15d Give dayjs a facade module (#79963) 2026-08-19 10:25:12 +12:00
Maksym Yakubych
9b159ccf78 Let conversation titles run on their own model (#78954)
* Let conversation titles run on their own model

Every LLM call read the one `llm-metabot-provider` setting, so naming a
conversation — a short, high-volume call — burned the same model the chat runs
on. Add an `llm-title-model` setting whose getter resolves rather than defaults:
the stored value, else the fastest model of the connection Metabot uses, else
that model itself. Provider types now carry a `:mini-model` alongside
`:default-model`, taken from each adapter's own supported-models list so the
fallback names a model the picker actually offers; Azure and the managed
provider have none and fall through.

Move model selection out of the AI providers card into its own Models section,
so per-use-case choices have somewhere to live. Deleting a connection clears a
title model pinned to it, reading the raw stored value so a merely-derived one
is left alone.

* Name a mini model for every provider type that has one

Mistral and Z.AI were the only types with no `:mini-model`, so conversation
titles on those connections fell through to the model Metabot chats on. Both
adapters whitelist exactly one model today, so their mini model is that same
model — the fall-through by another name, but spelled out where a real small
model goes when one is added.

Two tests hold the line. The registry map fails when a type gains or loses a
`:mini-model`, since a missing one reads as nil and quietly sends titles to
the full-size model. The listability test fails when a type names a model its
adapter will not offer: `list-models` returns the whitelist intersected with
the provider's catalog, so an id the whitelist omits never reaches the admin
picker, which renders it as a blank selection.

That second test caught Anthropic naming `claude-haiku-4-5` while the Claude
whitelist carried only `claude-haiku-4-5-20251001`, leaving the new title
picker blank on the commonest setup there is. The whitelist was the odd one
out — the adapter already defaults to the undated alias — so it loses the date.

* Sell the title model as the mini model it already was

Review asked whether each feature should get its own picker or whether one
cheap model should serve every quick task; the answer was one model. The
setting already resolved through the registry's `:mini-model` and nothing but
titles read it, so this is a rename — `llm-title-model` becomes
`llm-mini-model` — plus copy that presents naming conversations as the first
of the quick tasks rather than the point.

The derivation tests now pin the stored value to nil instead of assuming a
clean database; a crashed run had left a stored value behind, which the old
tests read as the derived one.

* Return Haiku's dated id, which is what the Anthropic catalog serves

Dropping the date assumed /v1/models would list the bare alias. Review
testing with a live key showed it does not: the catalog carries only
claude-haiku-4-5-20251001, so the undated whitelist key filtered Haiku out
of the picker, and the derived mini-model reference matched no option —
titles kept running on Haiku while the picker sat blank.

The alias stays where it always worked: inference-call defaults. The
whitelist and the registry go back to the catalog's id, which is also the
whitelist's convention — the 2025 models are dated, the 2026 models are not,
tracking what the catalog returns for each.

* Move a pinned mini model with the deployment its connection now serves

Editing an Azure connection's deployment already moves the Metabot
selection, because the reference bakes the deployment name in. A mini model
pinned to that connection went stale the same way, so it moves the same
way. A derived mini model is left unstored — it follows the Metabot
selection on its own.
2026-08-18 17:01:37 -03:00
Jeff Bruemmer
fbd41598bf docs - embedding intro edits (#80109)
* auth props

* edits

* Update docs/embedding/introduction.md
2026-08-18 19:47:56 +00:00
github-automation-metabase
b4eb9ba39f Auto-update documentation for master (#80030)
Update generated docs (master)

Co-authored-by: github-actions <github-actions@github.com>
2026-08-18 15:41:17 -04:00
Maksym Yakubych
3e6fe863dd BOT-1642 Show a clearer error for a second AI-managed subscription (#80017) 2026-08-18 18:53:15 +00:00
Kevin Kelleher
da492ba066 Fix cardinality cache collisions (#79856)
* use json_query as the cache key to prevent cardinality cache collisions

* fix e2e, persist default settings that depend on cardinality

* review comments
2026-08-18 13:26:55 -04:00
Anderson
b1e7ed37dd Add setting to display percentages instead of values on stacked bar charts (#79922)
* Display percentages instead of values on stacked bar charts

Adds a Stack value format setting that lets stacked bar chart segments display their percentage of the stack total.

Addresses #67702

* Handle percetanges for negative values

* Show decimals for fractional stack percentages

* Show percentage totals for stacked bars

* Improve condition readability

---------

Co-authored-by: Abhijnya K G <53806883+Abhijnya002@users.noreply.github.com>
2026-08-18 14:21:20 -03:00
Maksym Yakubych
2c98f5d2bf BOT-1989: Restore the conversation title size on the Conversation detail page (#79996) 2026-08-18 17:13:32 +00:00
Nick Fitzpatrick
15e8fd286d Update user-visibility subtext (#78147) 2026-08-18 14:08:08 -03:00
Maksym Yakubych
35a1199a35 Support multiple LLM provider connections at once (#78860)
* Invalidate the cached models list when credentials change

A credential write can change which models the provider serves, e.g. a different Bedrock region, Google location, or
Azure resource.

* Support multiple LLM provider connections at once

Metabot could only ever be connected to one AI provider, because each
provider's credentials lived in its own hardcoded settings
(llm-anthropic-api-key, llm-azure-api-key/-base-url, llm-bedrock-*, ...)
and llm-metabot-provider named the single provider in use. Adding a
provider meant editing a `case` in six namespaces plus three constant
maps on the frontend, and two keys for the same provider were impossible.

Replace that with a list of provider *connections* stored in one
`llm-providers` JSON setting, fronted by a CRUD API rather than edited as
a raw blob -- the same shape the `oidc-providers` setting already uses.
Provider types are now a pure-data registry describing each type's
credential fields, so the admin UI renders a connection form from the
server descriptor instead of a bespoke component per provider, and the
model picker lists models from every connection, grouped by connection.

Connection keys are slugs defaulting to the provider type, so existing
`llm-metabot-provider` values keep resolving unchanged. `metabase`
becomes an ordinary connection, which collapses the three-segment
`metabase/provider/model` special case into the generic rule. The
per-provider env vars keep working and each synthesizes one read-only
connection; MB_LLM_PROVIDERS puts the whole list under env control.

* Fix managed provider handling in the connection list

Five issues from reviewing the new admin UI, all around the Metabase-managed
provider:

- The managed provider's models were fetched from the proxy, so instances
  that cannot reach it showed "Couldn't load models". The proxy serves one
  benchmarked model rather than a listable catalog, so the registry now
  carries that catalog directly and nothing is fetched. It doubles as the
  allow-list `llm-metabot-provider` is validated against, replacing the
  separate copy in metabot.settings.

- The managed provider had an Edit action that opened an empty modal (or one
  offering to re-Connect something already connected). There is nothing to
  edit, so managed connections now only offer Remove.

- It could be added twice. Provider types can declare themselves singletons;
  the API rejects a second connection and the FE drops already-connected
  singletons from the Add dropdown.

- The empty state repeated the section description verbatim.

- Cards showed the raw type slug under the name ("Metabase" / "metabase").
  The provider type's label is now shown only when it differs from the
  connection's name, i.e. when the admin renamed it.

Also drops the startup step that materialized a `metabase` connection on any
proxy-configured instance, which made the managed provider look connected when
nobody had connected it. It is now materialized only where a `metabase/...`
model reference is actually written: the legacy metabot-v3 sync, and the
migration of an instance already pointed at it.

* Address review comments on the provider e2e helpers and managed setup spec

- Drop the doc comments added to e2e-metabot-helpers.ts.

- Move the mock LLM server's base URL into the connection's own config rather
  than the legacy `llm-anthropic-api-base-url` setting. Both worked, because
  the adapters fall back to that setting when the connection carries no base
  URL, but relying on the fallback left the connection describing one endpoint
  while requests went to another.

- Assert that the add-on purchase really does precede the connection POST,
  which the test claimed in its name but never checked, and add the missing
  case: a failed purchase must not create the connection.

* Stop repeating the model family in the model picker

Providers already carry the family in the model's display name, so prefixing
it with the group produced labels like "Opus · Claude Opus 4.8" and
"Anthropic · Anthropic: Claude Haiku 4.5". Show the display name on its own.

The group still comes back from the API: the backend orders each provider's
models by it, so dropping it here keeps the grouping-driven order without
showing the label twice.

* Select a default model on connect, and simplify the ad-hoc connect view

- Connecting a provider when Metabot had nothing usable to run on now points
  `llm-metabot-provider` at that connection's default model, so the first
  provider you add leaves the instance working instead of connected with no
  model selected. An existing selection that still resolves is left alone, so
  adding a second provider does not silently switch Metabot over to it. The
  "did it have a usable model" check has to run before the new connection is
  saved: the setting's default names the `anthropic` connection, which a
  freshly saved Anthropic connection would otherwise satisfy retroactively.

- The ad-hoc "connect to a model" modal no longer renders the admin list with
  an "Add a provider" button that opens a second modal. It is one connect form,
  and once a provider exists it is the model picker. Extracted
  ProviderConnectionForm so the admin modal and this view share it.

- Show a skeleton while the connection and provider-type lists load.

- Replace the add-on ordering assertion, which compared indexes into the call
  history, with a purchase that only resolves once the test releases it: the
  connection must not be created while it is in flight.

* Fix the managed-provider-limit spec for the single-form connect view

The ad-hoc connect modal no longer offers an "Add a provider" button that
opens a nested modal, so assert on the provider picker the form now renders
directly.

* Show the model picker after connecting from the ad-hoc modal

Connecting a provider in the ad-hoc view called onClose straight away, so the
modal shut before the picker it was supposed to hand over to could render.
Stay open and show the picker instead, except for a provider that serves a
single fixed model (the managed one), where there is nothing to pick.

* Split the AI provider list and setup views apart

The one component branched on an `isModal` prop to be either the admin list
(cards, add/edit/remove, model picker) or the ad-hoc connect flow, which meant
neither was composable and the modal branch read as an afterthought. Split it
into AIProviderList and AIProviderSetup, each owning its own data and state,
sharing ProviderConnectionForm, LlmModelPicker and ProviderListSkeleton.
Call sites pick the one they mean instead of passing a flag.

Also use `useDisclosure` for the add-provider modal. `editing` and `deleting`
stay on `useState` because they carry the row being acted on rather than a flag.

* Cancel the managed AI add-on from the backend, not a plugin hook

`PLUGIN_METABOT.useOnProviderRemoved` only ran when the managed connection was
removed through that one component, so removing it any other way — the API
directly, or the fallback path in the delete handler — left the customer paying
for an add-on they no longer used.

Move the cancellation into `DELETE /api/llm/providers/:key` behind a
`defenterprise`, which is where the invariant actually holds: removing the
managed connection cancels its add-on for every caller. The EE side decides
which product type to cancel from the same premium features the frontend was
reading, and keeps the rule that an instance on legacy tiered pricing with no
metered offer to move to is left alone. Extracted the Store call the
cloud-add-ons endpoints already make into `cloud-add-ons.core` so both share it.

The plugin hook and its EE implementation are gone.

Also clear fetch-mock state between AI provider spec setups. The file grew a
second `describe`, and its routes and call history leaked into whichever suite
jest packed next into the same worker.

* Address review comments on the model picker and provider API shape

- Snake_case the two kebab-case keys the provider-type endpoint put on the
  wire (docs-url, default-model), matching display_name alongside them. The
  internal registry keeps its idiomatic kebab-case keys.
- Drop the model picker's own success toast: useAdminSetting's updateSetting
  already toasts both outcomes, so picking a model fired two toasts and the
  error path only looked unhandled.
- Show SetByEnvVar under the picker when llm-metabot-provider comes from an
  env var, so the disabled Select says why.

* Remove the unused GET /api/llm/list-models endpoint

Nothing called it: no frontend, SDK, or e2e reference, only its own tests. It
listed models for whichever connection Metabot was pointed at, which
GET /api/llm/models now covers for every connection.

It is in the generated OpenAPI spec, so this is a breaking change for anyone
calling it directly. The spec is regenerated by the openapi-self-healing CI job
rather than by hand — a local run rewrites far more of the file than this change
touches.

* Pick a provider type from an icon grid instead of a dropdown

Replace ProviderTypeSelect with a ProviderTypePicker card grid, giving each
provider type an icon the backend names in the provider-type registry.

Connections now also report the env vars that configured them, so the UI can
name them rather than just saying the connection is env-managed.

* Use real provider logos, drop the stepper, lead with Metabase

- Drop the two-step "Provider / Configure" indicator. The modal swaps content
  in place rather than paging, so it rendered as a lone empty circle next to a
  floating label and conveyed no progress.

- Ship brand logos for the five bring-your-own-key providers, mirroring how
  driver logos already work: a file per provider under
  app/assets/img/llm-providers, looked up by provider type, falling back to the
  registry's icon when there is no logo (the managed provider keeps `metabot`).
  Sourced from svgl. The three monochrome marks are rewritten to currentColor so
  they survive dark mode; Azure and AWS keep their brand colour. Bedrock uses the
  AWS mark for want of a Bedrock-specific one.

- Offer the Metabase-managed provider first when the instance can actually use
  it, since it is the option to reach for before bringing a key.

- Fix the blank managed connect screen. MetabaseAIProviderSetup decided between
  "connect" and "already connected" from `llm-metabot-configured?`, which under
  multi-provider is true as soon as *any* connection works — so adding Metabase
  alongside an existing Anthropic connection rendered the connected-state card
  for a subscription that was never bought, which draws nothing. The caller now
  passes whether the managed provider itself is connected.

The provider-types order assertions became environment-dependent once ordering
keys off proxy availability (this worktree's .env sets MB_LLM_PROXY_BASE_URL), so
they now assert the set of types plus the lead position explicitly.

* Drop the provider picker heading that repeated the modal title

* Right-align the managed provider footer to match the other setup screens

* Focus the confirm button so Enter confirms instead of dismissing the modal

* Tuck the optional connection fields behind Advanced settings

The connect form led with Display name and API base URL, so the one field
that actually matters — the API key — was buried among inputs that already
have working defaults.

Show only the fields a provider type marks required, and collapse the rest
plus Display name into an Advanced settings disclosure at the bottom. The
split comes from the field descriptors rather than a hardcoded list, so
Azure (whose base URL is required) keeps both inputs up front.

Editing a connection that already customized an optional field opens the
section, so a non-default value is never hidden.

* Let the registry say which connection fields are advanced

Inferring it from `required` was wrong for Bedrock. `required` means
validation fails without a value, which is a different question from whether
an admin has to think about the field. Region has a default, so it is not
required — but it decides which models are reachable and where inference
runs, so burying it hands EU customers a silent us-east-1 default.

Add an explicit `advanced?` to the field descriptors and split on that. Only
the base URLs and Bedrock's session token carry it; region now stays up
front where it belongs.

* Cover submitting the provider connection form with the enter key

* Treat the single-provider env vars as a supported way to configure a provider

They were named and documented as a legacy compatibility shim — `legacy-env-connections`,
`migrate-legacy-provider-connections!`, and a doc line promising they "keep working".
That undersells them: configuring one provider by environment variable is the simpler
option when you do not want to hand-write the `llm-providers` JSON, and it is resolved
from the environment on every read, so editing a variable is picked up rather than being
frozen into a copy at first startup.

Rename to say what they are, and reword the docs to position the two mechanisms as
alternatives rather than old and new. The one-shot at startup only ever adopted
credentials stored in the app DB, so name it for that instead of for migrating away from
something we are keeping.

* Type the LLM provider logo lookup and move it out of the icon component

The logo map lived inline in ProviderTypeIcon as a Record<string, string>, so a new
provider type silently fell back to the generic icon instead of failing the build.

Give provider types a LlmProviderTypeName union and key the map on it, so adding a type
without deciding on a logo is a compile error. The map moves to metabot/constants.ts and
the lookup to metabot/utils/llm-provider.ts, matching how databases/ splits ENGINE_LOGO
from getEngineLogo.

* Focus the first credential field once a provider is picked

* Show the Metabase logo for the managed provider

* Only badge a provider connection when something is actually wrong

The green check was driven by `usable`, which only asks whether the required fields are
non-blank. The connect form already refuses to submit until they are, so every connection
made through the UI got a check — including one whose API key the provider rejects, right
above a "Couldn't load models" error saying so.

Drop the check and keep the warning, which still carries a real signal for connections
that arrive incomplete from MB_LLM_* or MB_LLM_PROVIDERS, and label it so it says what is
wrong rather than just showing a red triangle.

* Lighten the provider list to divider-separated rows

Each connection was a bordered Card, but the list already sits inside SettingsSection,
which is itself a bordered, padded card — so every row read as a card inside a card.

Follow DatabaseInfoSection instead: one container, rows separated by a divider. Also drop
the icon from 40 to 32, since the tile no longer has to anchor a card of its own.

* Tighten the provider list spacing and align the add button with the rows

The list and its add button sat in the same lg-gap stack as the model picker, so a control
that belongs to the list was pushed 24px away from it, as far as the next setting. Group
them in their own sm stack and keep lg for the gap to the picker.

The subtle button also carries horizontal padding, so its + sat indented from the provider
logos below it. Drop the padding, matching the Advanced settings toggle on the connect
form, so both start on the same edge.

Tighten the section header gap from lg to md via the stackProps SettingsSection already
exposes for this.

* Fetch provider models once and report failures on the provider that failed

A model-loading failure was only visible under the model picker, which reads as a problem
with the picker rather than with Anthropic. It also meant the failure was invisible
anywhere a picker was not rendered.

/api/llm/models already returns every connection in one response with a per-connection
error, and RTK Query already caches it under the llm-models tag, so the fetch is shared by
construction. Wrap it in useLlmConnectionModels, which hands back the grouped select
options and the errors keyed by connection. Any future picker goes through that hook and
gets the same cache entry and the same keying, rather than re-deriving either.

The provider row now renders its own error and the picker no longer lists them; the picker
keeps the request-level error, which is a different failure.

* Pick the provider from a pasted API key

Paste a key anywhere on the provider grid and it jumps straight to that
provider's form with the key filled in, ready to connect.

The registry already declared a `:prefix` per credential field — the backend
validates against it — so this just exposes it and reuses it for recognition.
Anthropic, OpenAI and OpenRouter carry one; nothing else is guessable.

Longest prefix wins, since OpenAI's `sk-` also matches an Anthropic
`sk-ant-` key. Text that matches nothing is left alone.

* Leave the paste-to-detect shortcut unannounced

Drop the hint under the provider grid. The shortcut stays; it is just for
people who find it. `canRecognizeApiKeys` existed only to decide whether to
render that line, so it goes too rather than sitting unused.

* Gate the managed provider usage panel on the features that fill it

The panel was shown whenever the metabot plugin was enabled, which is a
weaker condition than having usage and pricing to report. Move the check
behind a hasMetabaseManagedProviderDetails plugin hook so the enterprise
side decides from the premium features, and OSS answers false.

* Register the Mistral and Z.AI provider types in the connection registry

master added both providers to the single-provider settings architecture this branch
replaces, so rebasing dropped them from the admin UI: the adapters, the model listers and
the MB_LLM_MISTRAL_*/MB_LLM_ZAI_* settings all survived, but nothing offered either type
as something an admin could connect.

Registry entries restore that, and adding them to `single-provider-settings` is what keeps
an instance already configured through those env vars working — the same entry drives both
the env-resolved connection and the app-DB adoption at startup.

* Resolve provider connections in the LLM call tests

`parse-provider-model` stopped deriving a provider from the model string's first segment
and started resolving it against a configured connection, but this file still called it
with nothing configured, so every test that reached an adapter failed on "No LLM provider
connection named". Configuring the default connections is the fixture those tests were
always implying.

The invalid-format cases now assert the error the new resolution actually raises: an
unparseable string and an unknown connection are the same failure, because a name that is
not a connection is all "unknown provider" can mean once the registry is the source.

* Move the onboarding AI step onto the provider connection list

The setup wizard's AI step was built against the single-provider form this branch removed,
so it still imported `AIProviderConfigurationForm` and the provider enum and no longer
compiled. It now renders `AIProviderSetup`, the same connect-then-pick-a-model view the
ad-hoc modal uses, so onboarding and the admin page stay one flow rather than two.

Preselecting `metabase` goes away with the dropdown it was written for. The backend already
sorts the managed provider first in the type picker, which is what the preselection was for,
and picking it in a grid of logos is not a step the wizard needs to skip on the admin's
behalf.

* Add the Mistral logo and make a missing provider logo fail the build

LlmProviderTypeName is written by hand and had drifted: the registry gained mistral and
zai, the union did not, so the exhaustive LLM_PROVIDER_LOGOS record was exhaustive over a
stale set and both types fell through to the generic icon without a type error.

Add them to the union, which does make the record fail to compile until each is decided.
Mistral gets its mark from svgl; svgl has no Z.AI logo, so zai is an explicit null and
keeps the fallback icon until we have a real asset.

Nothing links the registry to the union, so add a backend test over the registry's type
names that names both frontend files to update.

* Thread per-connection credentials through the Mistral and Z.AI call paths

Both adapters took :credentials in list-models but ignored them in mistral-raw/zai-raw,
which read llm-mistral-api-key / llm-zai-api-key directly. So a connection's models listed
under its own key while every actual chat call went out under the global setting: a second
Mistral connection would silently answer with the first one's key, and a connection with no
global setting configured would fail outright.

Match the openrouter/claude shape — credentials first, configured settings for whatever
they do not carry — for both the key and the base URL, and cover the call path, which no
adapter had a test for.

* Give Z.AI its logo

Taken from z.ai's own logo.svg, since svgl carries no Z.AI mark. Stripped the Illustrator
export's ~10.5KB of unused .st0-.st194 declarations — only two of them were referenced —
and kept the geometry and colours exactly as shipped.

Every registered type now has a mark, so the fallback is only reachable when the backend
serves a type this union has not caught up with. Test it that way instead.

* Let instances that are only offered managed AI reach the purchase flow

The managed provider tile is enabled by `type-available?`, which asks whether
the LLM proxy URL is readable. That setting was gated on `metabase-ai-managed` or
`metabot-v3` — features granted only by the AI add-on products — while
`offer-metabase-ai-managed` comes from the starter and pro-cloud plans. Every
cloud instance eligible to buy the add-on therefore saw the tile as unavailable
and had no way to reach the purchase flow that grants the feature.

* Cover per-connection credentials on the remaining providers' call paths

Every provider tested credentials through list-models and none through the call path,
which is why Mistral and Z.AI could list models under a connection's own key while sending
every chat request under the global setting.

Claude, OpenAI and OpenRouter resolve credentials inline like Mistral did, so they get the
same explicit/blank pair. Azure and Bedrock instead forward :credentials into a shared
request helper the list-models tests already exercise, so what is worth pinning there is
the forwarding: with no settings saved, the request only goes out if the passed-in
credentials arrive.

* Pin every provider type's default model

The removed settings-put-connect-*-defaults-model tests asserted this per provider; the
connection API replaced them with one test that a first connection gets a model selected,
and provider-types-test only spot-checked anthropic and azure. A typo in mistral's or
zai's :default-model would have shipped silently.

* Alias metabase.llm.test-util as llm.tu, not lct

The letters do not spell anything in the namespace, so at a use site like
lct/default-connections there is no way to tell which namespace it came from. The repo
convention for a module's test utilities is <module>.tu — lib.tu, notification.tu.

Add it to kondo's :consistent-alias map too; it was absent, which is why the alias could
be picked freely in the first place.

* Make the whole provider header toggle the usage details

Only the chevron was clickable, so the icon and name next to it did nothing — unlike
Accordion.Control, which is what makes the entire header hit the toggle everywhere else.

Promote the header itself to the control and leave the chevron as the affordance, with
the options menu as a sibling rather than nested inside it. SetByEnvVar moves below the
header for the same reason: it carries a docs link, and a link inside a button is invalid.

Not Mantine's Accordion, because expandability is per-row here — only the managed provider
has a panel, and wrapping the rest would give them a control that opens nothing.

* Let the provider modal play its closing animation

The modal hardcoded opened and the parent mounted it conditionally, so closing unmounted
it outright and Mantine never got to run the exit transition. Opening animated because
mounting still runs the enter one.

Drive it with opened instead and keep it mounted, the way ConfirmModal a few lines below
already does. Clearing the edited connection moves to onExitTransitionEnd so the title
does not flip to "Add a provider" on the way out.

* Fix the edit modal never closing

Openness was derived from isAdding || editing != null, but closing only cleared isAdding
and left editing to be cleared after the exit transition — which could not start, because
editing still held the modal open. Editing a provider trapped it.

Track openness in its own disclosure so closing is one flag, and let editing carry only
which connection to show, cleared after the transition. Adding worked before, which is why
the existing test missed this; cover closing from edit too.

* Revert the provider modal close-animation work

Reverts 7e78358857d and 1a7c37d6412. The missing close animation is not this component's:
the Modal theme attaches enter-only CSS keyframes (popInFromBottom, fadeIn) to every modal
in the app and animation.module.css defines no exit counterpart, so driving this one with
opened bought nothing but state to keep in sync — and the first attempt at it trapped the
edit modal open.

Back to mounting it conditionally. Keeps the fetch-mock teardown from the reverted commit,
which is unrelated hygiene: without it this spec's routes leak into
MetabotAgentDataSourcePills and fail it in a combined run.

* Serve a request from its own connection's credentials, nothing else

Every adapter fell back to the single-provider `llm-*-api-key` setting when
the credentials it was handed came up blank. That made sense while the two
systems coexisted, but the env vars are themselves connections now, so the
fallback could only ever fire by lending one connection another's key — a
connection whose key an admin cleared would silently keep working on someone
else's, while `connection-usable?` reported it as broken.

Resolution now fills each field's registry default into the config, so
`:credentials` carries everything the adapter needs, including the base URL
it used to read from the settings. The adapters take credentials and nothing
else, and throw when they are missing.

Tests drive the adapters the way production does — by passing credentials —
rather than by setting a global and calling with none.

* Finish removing the settings fallback: Mistral, Z.AI, and the docs

Mistral and Z.AI landed alongside the previous commit and were copied from
the old shape, so both still reached for their `llm-*-api-key` setting when
the credentials came up blank. A half-applied invariant is worse than either
state — the next adapter gets copied from whichever one you happen to open.

The docstrings across all seven still advertised the fallback I had already
deleted, including the canonical `LLMRequestOpts` contract. Code that lies
about itself in the one place people go to read the rule is how the rule
comes back.

* Drop the editorializing line from the credentials doc

The entry should say what the field is, not argue for it.

* Reject runtime writes to the per-provider credential settings

These configure a connection only when set by an environment variable, which
llm.provider/connections resolves on every read. Writing one to the app DB landed somewhere
nothing reads: the settings API returned 200 and the request kept using whatever the
connection held. The e2e specs are the proof — one pointed llm-anthropic-api-base-url at a
mock server and would have talked to the real Anthropic instead.

Mark all sixteen :setter :none, so a write raises "you cannot set X; it is a read-only
setting" instead. Tests keep working because with-temporary-setting-values passes
:bypass-read-only?; connections are managed through /api/llm/providers.

Give each a :doc, since env-var-dox drops a read-only setting from the generated docs unless
it has one, and format-config-name then labels them environment-variable-only.

The custom setters and normalize-llm-base-url are unreachable now, so they go; base URLs on
connections were never normalized, only the setting path was.

* Disable the managed-AI Connect button instead of hiding it

An admin who had not ticked the Terms box saw no Connect button at all, so
the modal gave no sign that connecting was possible or what unlocked it.
Show it disabled: the checkbox is now visibly the thing standing in the way.

The gate moves out of `connectAction`, which keeps meaning "there is nothing
to do here" — already connected, or not an admin — and stays null in those
cases so the button remains hidden.

* Let a connection name the model it serves, so Azure is selectable

Azure's listing endpoint returns the regional catalog rather than the customer's
deployments, so list-models always came back empty and the picker had nothing to offer: you
could connect Azure and never pick a model. Master collected the deployment alongside the
credentials; the connection API dropped that and nothing replaced it.

Give the registry a :model-field naming the config key holding the model, and Azure a
required Deployment field. /api/llm/models still makes the call — it is what verifies the
credentials — but reports the configured deployment instead of the empty list. The connect
form needs no frontend change: it is descriptor-driven, so the field renders itself.

Two things this pulled in. config-complete? now demands the deployment, which is right for
"can this connection serve a request" but wrong for the adapter's auth check, so that
gets credentials-complete?, which ignores the model field. And the environment path needs
to express the deployment too, or an env-configured Azure connection reports unusable, so
llm-azure-model joins the single-provider settings.

Also give the unsupported-model error a 400: the deployment is typed by hand, so a bad
prefix is a bad request, not an outage.

* Import the provider logos instead of pointing at asset paths

The filename map plus a path-building helper came from ENGINE_LOGO, but that is the older
pattern: 57 places import an SVG as a module, and DatabaseHostnameWithProviderField's
ProviderIcon does exactly this — vendor logos colocated in the component directory, imported
and mapped by provider name.

So colocate them and import them. The bundler resolves the reference, which means a renamed
or missing file fails the build rather than 404ing at runtime, and the path string stops
being something to keep in sync by hand. The map moves next to the imports, which drops
metabot/utils/llm-provider.ts and the constants entry entirely.

The per-file src assertions go: jest maps every SVG to one stub, so what is left to check
is which of the three marks renders — the Metabase logo, a vendor image, or the fallback.

* Judge the onboarding AI step on a usable connection, not the first listed

connections[0] answered three questions it could not answer well. A listed connection is
not necessarily one that can serve a request — one configured by env var with a field
missing reports usable false — so onboarding would call itself connected, hide the skip
button, and report that provider to analytics.

Ask for the first usable connection instead. The skip button also waited on the list being
empty, which is equally true while the request is in flight, so it flashed on every load;
gate it on isLoading as well.

The completed-step title inferred skipping from a missing label, but the label comes from
the provider-types request, so a connected provider with that request still in flight read
as skipped. Pass whether a provider connected separately from what it is called.

* Match the loading skeleton to the list it stands in for, and colocate it

It still described the card-per-connection layout: two 4rem blocks with rounded corners and
a gap between them. The list has been divider-separated rows for a while now, so the
skeleton was a size and a shape that no longer appear anywhere.

Rebuild it from the row it mimics — PROVIDER_ICON_SIZE plus the row's py="sm" — with a
divider between and the button that follows, and move it into AIProviderList.tsx beside
those constants, so the next layout change has it in view rather than a file away.

Cover it too: nothing asserted the skeleton rendered at all, which is how it drifted.

* Keep the Metabase mark on the managed provider when whitelabelled

LogoIcon resolves through PLUGIN_LOGO_ICON_COMPONENTS, which the whitelabel plugin fills
with the customer's logo. That is right nearly everywhere, and wrong here: this row is
Metabase's own hosted AI service, so a whitelabelled instance was labelling it "Metabase"
— the registry string is not rebranded — beside someone else's logo.

Use DefaultLogoIcon, as WelcomePage and SdkUsageProblemBanner already do where the mark has
to be Metabase's regardless of branding.

* Stop standing in for an unknown provider with a real one

Gemini is a provider we could plausibly add, and the day we do, every test asserting it is
unknown starts asserting the opposite of what it means. Use a name nobody will ship.

Same for the Azure family placeholder, which picked gemini for a family Azure does not
serve. The genuine google/gemini-2.5-flash model references stay.

* Match on the secondary button instead of nesting a && inside a ternary

isEditing ? (onCancel && <Cancel/>) : <Back/> reads as two branches but is three, and the
one that renders nothing is the one you cannot see. The rest of this component already
picks its shape with match, so this now does too — and onCancel is narrowed by the pattern
rather than guarded separately.

* Pick the Azure model provider from a dropdown again

The rewrite collapsed master's Model provider select and Deployment name
input into one text field where the admin types `openai/` as a prefix. Split
them back apart and compose the model from the two, so the wire family is
picked rather than spelled.

`:model-field` becomes `:model-fields`, a vector composed with `/`, which is
the shape the Azure adapter already parses back out. A required field the
registry gives a `:default` now counts as filled — the form shows it
pre-selected, and resolution supplies it — so the family select does not
block Connect on a connection that simply accepted it.

* Drop two explanatory comments

Both restated what the line below already says.

* Shrink the loading skeleton to the row's content height

The skeleton painted the full 3rem row, padding included, so it read as two
heavy slabs butted against the divider. Wrap it in the row's own py="sm" and
size the bar to the provider icon instead: the row still occupies the same
height, so nothing shifts when the list arrives.

* Name the provider on the closed model picker

A model name alone does not say who serves it, so the picker gave no way to tell which
provider was selected without opening it. With several connections — two Anthropic keys,
say — that is the part you most need to see.

The option label carries the provider, since that is what a closed Select renders. The
dropdown keeps rendering the model alone through renderOption, because the group heading
above it already names the provider.

* Only treat a usable connection as one worth moving on from

Setup moved past the provider picker as soon as any connection was listed,
while the step around it counted only usable ones. A connection that exists
but cannot serve a request landed between them: the picker was replaced by a
model dropdown with nothing in it, the step still offered to skip, and there
was no way to connect anything.

That is reachable, not theoretical — the single-provider env vars synthesize
a connection as soon as one credential field is set, so MB_LLM_AZURE_API_KEY
on its own produces one Azure needs three fields to use.

* Serve the disconnect test's stream from the connection under test

The fake OpenRouter server was reached through the per-provider base-URL
setting, which no longer feeds a request now that credentials come from the
connection: the stream went to openrouter.ai and the turn finalized as an
error rather than an abort.

Disabling clj-http decompression on the LLM request also had to move from
http/post to the fn the adapters actually call, so the aborted stream no
longer races a ZLIB EOF against the cancel.

* Stop shipping an icon name the frontend never reads

The frontend keys its logos on the provider type and fails to compile for a
type it has no logo for, so the registry icon was only ever reachable for a
type the server knows and the client does not — which cannot happen when the
two ship as one artifact. Seven of the eight entries said "ai" anyway, and
the eighth said "metabot" for the managed provider, which is drawn from the
Metabase logo component before the icon is consulted.

Drop it from the registry, the response, and the type, and let
ProviderTypeIcon own the generic fallback it was already defaulting to.

* Point the setup wizard's AI e2e tests at the connection API

All three drove the single-provider flow this branch replaced: a Provider Select that is
now a grid of buttons, and PUT /api/metabot/settings, which no longer exists. The Anthropic
one also aimed the mock server via llm-anthropic-api-base-url, which stopped being writable
when those settings became read-only — it now types the base URL into the connection's own
advanced settings, which is where a connection reads it from.

The managed test additionally stubs GET /api/llm/provider-types and /api/llm/providers: the
managed type is only connectable once the LLM proxy is configured, and that has no backing
in e2e, so it is patched the same way the token features already are.

* Match the required API key label the way the unit specs do

Mantine appends a required marker to a required field's label, so the setup
spec's exact-string lookup found nothing once the API key field came from the
provider registry with :required? true. The unit specs already match on a
regex; the e2e spec was the last one on the bare string.

Also name do-with-entitlements! for the thread-unsafe settings it binds, which
Kondo flags.

* Edit the stored connection list rather than the environment-resolved one

The environment winning on read is right, but writes rebuilt the list from
connections, where an env-configured connection replaces the stored one with
the same key. Saving anything else then dropped the shadowed credentials from
llm-providers for good, so taking the env var back off did not restore them.

Editing the stored list also lets PUT report a shadowed key as env-configured
instead of 404ing, and stops the startup managed-connection write from landing
in the app DB when the whole list comes from MB_LLM_PROVIDERS -- which would
have pointed Metabot at a connection that never resolves.

* Configure an Azure deployment from the environment the way the form does

MB_LLM_AZURE_MODEL landed under a :model config key that nothing reads --
azure declares :model-fields [:model-family :deployment-name] -- so an
environment-configured Azure connection composed no model and counted as
incomplete, which hid the Metabot UI instance-wide behind
llm-metabot-configured?. Replace it with one variable per config key.

The same completeness rule dropped Azure from the startup adoption entirely,
because the credentials that existed before this branch never named a
deployment: they carried it in llm-metabot-provider. An upgraded instance was
left pointing at a connection that did not exist, with Metabot failing on every
request. A deployment names what to call rather than what authenticates the
call, so stop requiring it, and recover the pair from the model reference
during adoption so the connection can still offer it in the picker.

* Add a provider alongside the managed one instead of cancelling it

Running out of included tokens is a reason to bring your own key, not to end the
subscription. "Use a different AI provider" was wired straight to the add-on
cancellation: it charged ahead with no confirmation, offered no provider to
switch to, and left the metabase connection and llm-metabot-provider pointing at
each other afterwards, so nothing on screen changed.

Let the button open its own modal again. AIProviderSetup short-circuits to the
model picker once any connection exists, which is exactly wrong here, so let a
caller start on the connection form; the managed connection is left alone and
the model picker follows the save. Removing the connection outright is already
the list's Remove action, which cancels the add-on server-side.

* Let the single-colour provider marks follow the theme

The marks were loaded through <img>, and an SVG in an <img> is its own document:
currentColor resolves against that document's initial color, black, with no way
to reach the color the tile sets. Anthropic, OpenAI and OpenRouter therefore
painted black on a near-black tile in dark mode, and Bedrock's navy "aws"
wordmark left only the orange smile visible.

Inline those four instead, so currentColor picks up the tile's text colour --
dark on light, light on dark, which is how each brand publishes its monochrome
mark. Mistral, Z.AI and Azure keep their own colours and stay images. Bedrock's
wordmark becomes currentColor, reproducing AWS's own light and dark variants.

OpenRouter pointed at a clipPath the file never defined; harmless while it was
sandboxed in an <img>, but an id to collide with once inlined.

* Optimize the provider logos and normalize them to one size

The files came from seven different sources and showed it: viewBoxes ranged from
24x24 to 512x512, some carried fixed width/height, and each baked in its own
arbitrary padding. Rendered into the same 20px tile the marks came out anywhere
from 12px to 20px tall, so the row read as a jumble.

Run everything through SVGO (viewBox kept, dimensions and editor cruft dropped),
then re-cut each viewBox to a square centred on the mark's real ink extent. Every
mark now fills the tile's width, with padding controlled by the tile alone rather
than by whoever exported the file. Z.AI is inset 12%: its mark is itself a filled
rounded square, so at an equal bounding box it reads far heavier than the open
marks.

* Say when the provider lists fail to load

Both components defaulted the two queries to empty arrays and never read
their error, so a failed request was indistinguishable from having nothing
configured. The provider-types failure was the worse of the two: it rendered
an empty picker grid — no providers to choose, no explanation, no way on.
The connections failure is quieter but wronger, since an admin with several
providers would be told to connect their first one.

Report the error where the list or the picker would have gone, using the
same getErrorMessage the rest of this feature already uses.

* Tighten the provider section's spacing and hang the icon off the name

Sloan flagged three gaps as feeling high even where they match other sections: drop the
section's header gap from md to sm, and the gap out to the model picker from lg to md. The
row-to-button gap was already the tightest of the three and stays.

The icon was centred against the whole text block, so it sat slightly off the name and
drifted further as an error or env-var line appeared beneath it. Give the name the icon's
height and centre it there, so the two line up on one row however many follow.

* Collapse the add button's box, which was most of the spacing

Trimming gaps barely moved this because the space around "Add another provider" was not a
gap. Metabase's Button defaults to size md, so it is 42px tall; p={0} removes the padding
but not the height, leaving its ~20px label centred with about 11px of dead space above and
below it. That is the two gaps flagged around the button, and no gap value could reach them.

Let it take its label's height once it is an inline link. Rows go from py="sm" to "xs" as
well, since a 32px icon does not need 8px above and below it.

* Give the add button its height back

Collapsing it to its label bought vertical space but cost the button its shape. Keep the
tighter rows from the same change.

* Draw every provider logo on one 24x24 grid

Making each viewBox square left seven different squares -- 24, 88, 300.23, 256,
259.53, 511, 30.72 -- so the files only matched once a consumer sized them. Bake
each mark's scale and centring into its path data instead, so every file is
literally width=24 height=24 viewBox="0 0 24 24" with the mark centred on that
grid and its longest side spanning it.

Z.AI keeps its 12% inset, for the same reason as before: its mark is a filled
rounded square and reads heavier than the open marks at an equal box.

* Sit the row actions on the icon band and cut the gap to the add button

* Fit a provider's name and type inside the icon's height

* Give each provider row a little more room

* Inline the remaining provider logos instead of loading them by URL

Mistral, Z.AI and Azure rendered as broken images. Their files are valid; the
copies the bundler emitted were not. BannerPlugin is configured with no test, so
it prepends the licence header to every emitted asset -- and re-applies it on
each watch rebuild, so the served .svg started with six stacked comment blocks
before its <svg>, which no browser will parse as an image. Editing these files
repeatedly is what re-emitted them and made it visible.

Inline all seven the way the other four already were: SVGR turns them into
modules, so nothing reaches the asset pipeline and one import style covers the
set. Azure's gradients were on ids a/b/c, which are too generic to share a
document with, so they are namespaced now.

The banner covers every other emitted asset too, so any .svg re-emitted during a
dev session hits this; that is worth fixing in the build config separately.

* Call the managed provider Metabase AI service and tighten the add-provider modal

Drops the redundant 'Selected provider' subtitle and 'About Metabase AI service'
heading, puts the free-token and pricing lines in their own callout, and swaps the
row's ellipsis button for a neutral ActionIcon.

* Pin the base URL the credential-adoption tests read

* Mock the provider endpoints the onboarding AI modal calls

* Give the explorations e2e helper a provider connection instead of read-only settings

* Make Moonshot AI a provider type you connect to

* Regenerate the settings docs

* Answer the review on the model listing endpoint

- Drop the per-provider :group heuristics. The picker groups by connection
  name and never reads the field, so it was computed on every admin page load
  for nothing.
- Key the model cache on a hash of the connection's config rather than on the
  config itself, so a credential is not held in a process-wide cache, and a
  rotated one gets its own entry instead of the old list.
- Take the model a connection composes from its own config into account when
  Metabot's selection has to move: Azure has no default model, so it was never
  a fallback, and editing its deployment left the selection naming one that no
  longer exists.

* Migrate the per-provider credential settings instead of adopting them at startup

The startup adoption left the settings it copied from behind, frozen: nothing
writes to them any more and they are read-only, so an instance rolled back to
code that still reads them would run on whatever was last stored there rather
than on what is configured. A reversible migration fixes both ends — it clears
the settings on the way up, and writes the connection list back into them (and
rewrites a model reference older code cannot resolve) on the way down.

Also pulls the copy of `trimmed-string` the two LLM namespaces shared into
`metabase.util`.

* Wait for the model list before opening the picker in its spec

* Make Google Gemini a provider type you connect to

Carries the Gemini Enterprise Agent Platform provider over to the connection
list: a registry entry with the same form every other provider gets, credentials
resolved from the connection rather than from the `llm-google-*` settings (which
become environment-only like the rest), and the connection naming the model it
serves — the platform has no listing endpoint worth trusting, so connecting
validates the model with a free countTokens probe, the way Azure validates its
deployment.

* Cover the Google credentials in the settings migration

* Name the Gemini models Metabot works best with

* Use Moonshot AI's own mark, not Kimi's

The file was Kimi's rounded-square K — Kimi is Moonshot's chatbot, not the
company we connect to. Icon sets ship the two separately and it is an easy
one to pick wrong.

Replaced with the MoonshotAI mark, kept in the same shape as the other
single-colour logos here so it takes the theme's text colour.

* Give Google the form the upstream PR built for it

Three field kinds the registry could not express before, so the connection form
can offer what the settings page did:

- a fixed model list, replacing the free-text field and the paragraph of advice
  about which IDs work;
- an authentication method to pick, rendered as a segmented control;
- a file to upload for the service account key, read into the config the way
  every other credential is typed into it.

A field can now hang off another one's value (`show_when`), which is what makes
the credential follow the method — and a field the form hides is cleared on
save, so switching methods drops the credential it replaced.

* Let Gemini's models come from the shared picker

A connection only names its own model when nothing else can name it — Azure,
whose deployments its listing endpoint does not return, and which serves one of
them. Gemini's models are a known list, so pinning one per connection put a
second model picker inside the form and hid the other model from the one below
it. The list becomes the type's fixed catalog instead, the way the managed
provider's is, and both models show up per connection in the model picker.

A fixed catalog no longer skips the provider call: that is what verifies the
credentials, so it is made against the catalog's first model and the catalog is
what comes back. The managed provider still answers from the registry alone —
there is nothing to call, and instances that cannot reach the proxy would fail.

* Answer the migration review notes

Rename the frozen table's :credentials to :required-keys — they are the keys a
provider needs to count as configured, and "credentials" made the optional ones
sound like something else.

Stop the downgrade encrypting every value it writes. write-setting! ran
maybe-encrypt unconditionally, so base URLs, regions and the model reference —
settings declared :encryption :no — came out of a rollback holding ciphertext.
Reads decrypt opportunistically so nothing broke, but a setting should hold what
its declaration says it holds. Only the :sensitive? settings are encrypted now,
and a test pins the raw storage both ways.

The Google row is also renamed to Google Gemini Enterprise alongside the
registry, to keep the adopted connection's display name in step.

* Close the review's holes in the provider registry and its API

Redact the Google service account key. secret-field-keys covered only
:password fields, and the key is a :file upload, so GET /api/llm/providers
returned the whole credential — private key included — in plaintext. Fields can
now be marked :secret? regardless of input type, which also makes the masked
echo-back flow cover the key on edit.

Require what Google actually requires. Every field was individually optional
because either credential will do, so an empty config counted as complete —
usable: true on a connection that can serve nothing. Provider types now declare
alternative credential groups (:required-any): a service account key on its own,
or an OAuth token together with the project ID it bills to. Completeness and
validation both honor the groups.

Treat blank credentials as absent. The form clears the field it hides when the
authentication method changes, but the empty string it sent was stored and
passed to the adapter, which fed "" to the service-account parser — the
"no JSON input found" from the review. Blank values are dropped on save, and
the adapter trims what reaches it so an env-supplied blank cannot shadow the
other credential or the project ID a key carries.

Reserve the metabase connection key. Any type could claim it, splitting
managed-model-ref? from managed-type? — a bring-your-own-key connection whose
requests would be tagged as proxied in metabot_message and confuse the managed
free-tier limit. Only the managed type may hold the key now, a squatter blocks
managed connection with a clear message instead of colliding, and the unused
proxied-model-ref? is gone.

Also: per-field :validate hooks in the registry (Google's project ID and
location get the setting-specific validation the old defsettings had), select
values are checked against their options, with-entitlements takes a kwargs map,
and the cond-> in self.clj is realigned.

* Pick the Google model in the connection form

Connecting a Google provider validates the credentials with a countTokens probe
that needs a model, but the form collected none, so the probe ran against a
hardcoded default the chosen location may not serve — a confusing rejection the
admin had no control over, and no guarantee the model they wanted works at all.

Provider types now ship their fixed catalog and alternative credential groups to
the frontend. A type with a catalog gets a model picker in its connection form,
the probe runs against the picked model, and Metabot starts on it. The Connect
button also honors the credential groups, so it no longer offers to connect a
Google provider with nothing filled in.

* Quiet the kondo warnings CI caught

u/lower-case-en over str/lower-case in the reserved-key check, and the
validate-config! additions split into their own deftests instead of growing the
original past the one-concern-per-test lint.

* Report the provider Metabot landed on, not the first usable connection

The setup step resolved its connected provider with find(usable) over the
connection list, which is insertion order. Connect two providers during setup
and pick the second one's model, and the step still reported the first — in its
title and in what submitAiConfig records. Resolve the connection from the
llm-metabot-provider reference instead, the way the pre-connection-list code
compared against the saved value.

* Spell the field-level secret flag :sensitive?

Same word as the defsetting option it mirrors, so a grep for :sensitive?
surfaces the registry's secret fields alongside the settings.

* Give the LLM settings migration its own test file, and a managed round trip

Twice now a reviewer could not find the migration's coverage, because the tests
sat in the shared custom_migrations_test and referenced the migration only by
its changeset id. They live in a file mirroring the migration's path now, with a
docstring naming the change class that connects the two.

The round trip crisptrutski asked about also surfaced what he predicted: the
managed connection is not in the migration's provider table, so every rollback
of a managed-AI instance logged a false 'no equivalent setting: metabase'
warning. It holds no credentials and its model reference survives the rollback,
so it is dropped silently now, and a new test walks the managed round trip.

* Let the environment shadow connections field by field, and settings write through

Answers crisptrutski's review of the environment and settings story.

The MB_LLM_* variables now shadow a stored connection's config per field, the
way an env var shadows any other setting, instead of swapping the whole
connection out. A lone MB_LLM_ANTHROPIC_API_BASE_URL reaches the stored
connection's base URL rather than doing nothing; everything the environment
does not supply stays editable, and env_fields tells the form exactly which
inputs to disable. A standalone env connection still only comes into existence
when a credential variable is set — which is why Azure's base URL is no longer
marked as one: alone it used to synthesize an unusable connection that shadowed
the stored credentials wholesale. A metabase/ reference pinned by
MB_LLM_METABOT_PROVIDER synthesizes the managed connection it names, so that
reference resolves without an app-DB row.

The per-provider settings are a view over the connection list rather than
read-only. :setter :none broke config.yml provisioning outright — the
provisioner calls setting/set! on every entry and nothing catches the throw, so
the instance failed to start — and orphaned generate-sql and semantic search,
which still read llm-anthropic-api-key and llm-openai-api-key directly after
the migration deleted the rows underneath them. Getters resolve the connection
field with the environment and registry defaults layered in; setters write
through to the connection, creating it on first write and keeping the old
setters' field validation. Both docs files are regenerated: the config
template carries the settings again.

Also from the review: deleting the managed connection requires superuser — it
cancels the Store subscription, and everything else that can cancel add-ons is
superuser-only — and the confirmation dialog says so; the automatic
llm-metabot-provider writes (first connection, edit follow-up, delete
fallback) are skipped when the env var pins the selection, restoring what
check-not-env-shadowed! used to guarantee; the edit form starts the model
picker on the model the connection is actually serving and a changed pick
follows through to the selection for fixed-catalog types; and redact masks
every field of a provider type the registry does not recognize, instead of
none of them.

* Reconcile the restack onto bot-1875-gemini-models-fe

Mechanical conflict resolutions during the rebase left a few files at the wrong
side of the divergence; this restores the reviewed merge result: the shared
tool-function conversion in the Claude and OpenAI adapters, the settings
endpoints stripped from the relocated metabot API slice, and
gemini-3.7-flash — new on the Gemini branch — joining the fixed catalog.

* Restore the stop-reason propagation the restack dropped from the adapters

* Strip trailing slashes off base URLs when a connection resolves

* Slug-proof the reserved key, follow the effective config, and seed the models cache

* Count a blank-config connection as dropped on rollback

* Warn that deleting the anthropic or openai connection turns off the feature reading it

* Regenerate the environment variable docs against current master

* Drop the env-var doc section master removed in the backend hardening

* Update src/metabase/llm/settings.clj

Co-authored-by: Chris Truter <crisptrutski@users.noreply.github.com>

* Mark the dev rollback subqueries so the app-DB honeysql guard allows them

* Gate the settings-access delete test on EE, where advanced permissions exist

* Wait for the AI setup buttons to render before clicking them

---------

Co-authored-by: Mike Appleby <86076+appleby@users.noreply.github.com>
Co-authored-by: Chris Truter <crisptrutski@users.noreply.github.com>
2026-08-18 13:42:53 -03:00
Anderson
6ab7bfb2c6 Add tracking events for collection filtering, selection, pinning, and move interactions (#79926)
* Add collection interaction analytics

* Code cleanup

* Address review comments
2026-08-18 15:37:24 +00:00
Nicola Mometto
50a3a1177d Align hardening with x.63 backport (#80066) 2026-08-18 16:27:27 +01:00
Denis Berezin
461830362b UXW-3641 Remove emotion from EntityItem (#79848)
* UXW-3641 Remove emotion from EntityItem

* Review fixes
2026-08-18 18:19:44 +03:00
Chris Truter
2550ef763e Add embedding provider SPI and Arctic embedder plugin (#78310)
* Add a versioned embedding provider SPI

Summary

- Add a runtime registry for embedding providers with readiness, model resolution, preparation, and batch embedding.
- Define immutable embedding-space descriptors and legacy deterministic identities.
- Validate provider results, dimensions, counts, and finite numeric vector components.
- Make SPI version 1 a compile-time constant; provider artifacts must embed the literal version they were built against.

Scope

This defines the neutral provider contract only. It does not migrate semantic-search consumers or ship a provider plugin.

Testing

- Registration and version compatibility.
- Identity stability and revision round trips.
- Registry snapshot consistency and malformed provider output.

* Rename shadowing local in provider/prepare!

The local bound from :prepare! shadowed the prepare! var (eastwood local-shadows-var).

* Add the Arctic embedder plugin

Summary

- Build a separate runtime plugin containing the pinned Snowflake Arctic embedding model and DJL/ONNX dependencies.
- Bundle arm64 and AVX2 exports, lazy-load native inference, and cap local batches.
- Register literal embedding SPI version 1 and derive immutable space identity from the exact model/runtime bundle.
- Fail readiness closed for unsupported platforms, musl, and glibc older than 2.34.
- Disable DJL network telemetry and revision-address bundle URLs so model upgrades cannot reuse stale cached content.

Scope

This PR ships and registers the provider but does not yet select it from semantic-search settings. Consumer integration follows upstack.

Testing

- Model bundle and plugin uberjar build tests.
- Catalog, classloader, platform-readiness, identity, cache-key, and batching coverage.
- Artifact-only real inference with zero outbound network attempts.

* Follow prune-provided-libs! rename in the embedder plugin build

* Merge nested let in embedder-plugin artifact test

Kondo flagged the inner let as redundant; fold both binding vectors into one.

* Deref the now-delayed core provided-libs in the embedder build

* Bundle MiniLM for in-process complexity scoring

* Activate the embedder plugin in its artifact smoke test

* Activate lazy embedding providers on demand

* Use plugin initializer in artifact smoke test

* Make lazy provider activation best effort

* Log lazy embedding provider activation failures

* Declare the embeddings plugin dependency

* Keep embeddings provider internal

* Activate the in-process embedder during bootstrap

* Fix embedder validation and optional plugin startup

* Declare the embedder plugin as a module

The deps graph only scanned src, enterprise/backend/src, and modules/drivers, so the plugin's
namespaces belonged to no module and anyone linting them got six unresolved-dependency
warnings. Scanning modules/embedder/src too lets the generator record what the plugin actually
takes from the host.

* Move embedder model caching into the weekly cache generator

Review feedback on #78310:
- Drop the redundant persist-credentials: false checkout options.
- Stop writing the model cache from the CI job. The weekly cache-generator
  workflow is the single cache writer; the build job now restores only.
  The downloader is content-addressed (SHA-256 verified, refetches deltas),
  so a stale weekly cache still protects against HuggingFace rate limits
  without affecting correctness.

* Bundle snowflake-arctic-embed-xs instead of Arctic-L

The bundled models are a test tier: they exercise the packaging, DJL
runtime, tokenizer, and pooling machinery without shipping the 1.1 GB
Arctic-L artifacts. xs keeps the same family, query-prefix scheme, and
cls pooling as Arctic-L at 23 MB per architecture. A release-tier build
with the full model comes later, when the plugin is published for
customers or offline use.

At ~90 MB of pinned downloads there is nothing worth caching, so the
cache-generator wiring is reverted and the CI job downloads directly.

* Fail loudly when a catalog entry lacks this architecture's export

resolved-model computed the embedding-space-id from
get-in spec [:architectures arch :sha256] without checking it was
present. A model missing this architecture's export would silently
bake a nil into the identity hash instead of failing, producing a
syntactically valid but bogus embedding-space-id.

* Pin the embedder plugin manifest name to one constant

"Metabase In-Process Embedder" was duplicated in core.clj (the
registered?/load-plugin! lookup key) and the artifact test. A rename
in modules/embedder/resources/metabase/embedder/metabase-plugin.yaml
without updating both call sites would silently disable the plugin,
since registered? just returns false for a name it doesn't recognize.

* Downgrade the hashed-table-name log line to debug

Hashing fires deterministically for every identifier derived from a
long provider/model pairing (e.g. "in-process" + the bundled xs
model), so it was logging a warning on every lookup rather than once
at creation.

* Cover the missing-architecture catalog guard

The error path added alongside the guard had no test, so the earlier
silent nil-hashing behaviour could come back unnoticed.

* Assert the reason on the missing-architecture guard

The message alone leaves `:reason :architecture-not-bundled` untested,
which is the part callers actually branch on.

* Drop the hashed-table-name log line

It fires from a pure name-derivation helper on every lookup. The table
creation it hints at is already logged at info by the caller, and the
parameters behind the hash are in index_metadata.

* Extract the missing-architecture check out of the smoke test

The guard's assertions pushed the smoke test to 155 lines, past the
150-line deftest limit, so Clj-Kondo failed. Pull it into a helper the
way the platform-support checks already are.
2026-08-18 17:11:24 +02:00
Ramiro Nuñez Dosio
c78c9fed48 Update README with new image URL and bug reporting info (#80073)
* Update README with new image URL and bug reporting info

Updated the image URL for the Metabase product screenshot and added a bug reporting guide.

* put metabase-product-screenshot-updated.png to the docs

* fix link in the readme

---------

Co-authored-by: Timur Mashara <timur@metabase.com>
2026-08-18 15:43:18 +02:00
Oleh K
1821975d0c Use Breadcrumb component in Detail View (#79892)
* Use Breadcrumb component in Detail View (GDGT-2596)

Detail View had its own Breadcrumb, duplicating the shared one introduced
in #75114. Point TableNav, ModelNav and CollectionBreadcrumb at
metabase/common/components/Breadcrumb and delete the local copy.

The shared component hardcoded showTooltip={false}, which would have lost
the full-text tooltip Detail View shows on truncated crumbs, so make it a
prop. It defaults to false, leaving every other consumer unchanged.

Crumbs now take the shared component's sizing (0.875em, bold) instead of
inheriting 14px regular; the separator is sized to match so the row stays
consistent. Colour and icons are unchanged.

* Use URL helpers for the Detail View breadcrumb links

TableNav built the database and schema URLs by hand. Extract databaseSlug
from browseDatabase so browseSchemaBySlug can reuse it, then build both
links from the helpers. Both now carry the database slug rather than only
the id.

* Style official collections in the Detail View breadcrumbs

Collection crumbs hardcoded icon="folder", so an official collection
rendered like a regular one. Use CollectionBadge, which resolves the icon
from the collection's authority level, the same way the model page does.

Drop the text-secondary override too: it made Detail View darker than
every other breadcrumb in the app bar.

* Align Detail View breadcrumbs with the rest of the app bar

The detail view nav carried a -13px left margin, putting its first crumb
13px closer to the logo than the collection breadcrumbs shown on every
other page. Drop it so both start at the same offset.

* Match the Detail View breadcrumb separator to the app bar

Its color, font size and line height all differed from the separator the
collection breadcrumbs render. Use the same values, and Box rather than
Text so it inherits the line height instead of setting its own.

* Update the database breadcrumb href expectation

The database crumb now goes through Urls.browseDatabase, which appends
the slug, so the link is /browse/databases/1-sample-database rather than
/browse/databases/1.
2026-08-18 15:39:42 +02:00
Nemanja Glumac
812e970d41 Remove the reduntant skip input from bundle-size step (#80070) 2026-08-18 14:35:31 +02:00
Oleh K
836c398dc7 Make query builder breadcrumb text the same size (#79889)
* Make query builder breadcrumb text the same size (GDGT-2609)

The database and schema crumbs rendered smaller than the rest of the
breadcrumb. HeadBreadcrumbs spread {...rest} after className, so a caller
forwarding className -- even as undefined -- wiped the computed Container
and headVariant classes, and those crumbs fell back to Breadcrumb's
0.875em. Merge the incoming className instead of letting it clobber.

Size the head-variant dividers and the leading icon to match the crumbs
too, so the whole row reads as one line of text.

* Address review comment

Keep the props spread last and exclude className from it, rather than
reordering the spread ahead of className.
2026-08-18 14:35:03 +02:00
Chris Truter
548bae6986 Adopt bare library index tables in dedicated store only (#79986) 2026-08-18 13:00:20 +02:00
Chris Truter
2e45128a8e Drop departed members from the Metabot team (#80031) 2026-08-18 12:22:46 +02:00
lbrdnk
f768659552 Unify build logic in PR env and AI benchmarks (#78534)
* Stub the evals trigger

* use ref arg

* dummy to trigger build

* Clean up

* Use appropriate token

* Simplify pr message

* Use .evals_ref for default ref

* Comment cleanup

* Adjust ref

* Use evals branch

* Use general automation token

* readme for .evals_branch

* Use main of evals for label trigger

* Revert "dummy to trigger build"

This reverts commit e6502c6ff076a47d94eb829b516fc45b37cd7680.

* whitespace

* Address review remarks

* Use ai benchmark naming so we can trigger from pr

* Address review comments

* Remove now redundant branch pinning

* Review remarks

* Enable passing commit to uberjar from other workflows

* Unify ai-benchmark and pr-env build logic

* linter

* checkout action

* separate build step

* Use wip branch

* adjust job output

* Make image building manually triggerable

* tmp comment

* Address review remarks on the build extraction

- ai-benchmark's `image` regained the label guard `uberjar` used to carry; without
  it any label on any same-repo PR built ee+oss and pushed to ECR.
- New `resolve` job turns the dispatch `pr`/`ref` inputs into one full sha, and
  feeds it to both the image build and the eval-run dispatch. `pr` was ignored
  before, so `pr: N` benchmarked the launch branch while reporting against the PR;
  `ref: master` looked for an artifact named after a branch.
- prepare-uberjar-artifact takes a `commit` so the upload key matches what
  check-existing-artifacts/fetch-artifact look up. Without it a build for an
  explicitly passed commit uploaded under the event sha and then failed to
  retrieve itself.
- uberjar's build checkout honours an explicit commit, but stays on the event ref
  otherwise so PR builds keep compiling the merge ref.
- Concurrency group includes the calling workflow, so a re-label on one caller no
  longer evicts the other's queued run.
- ECR existence check targets the pushed registry explicitly and no longer hides
  real errors behind "not found".
- Scoped `secrets: inherit` down to the two secrets dockerize needs, added
  read-only default permissions, dropped the dead `jar xf`, restored the comment
  explaining `finalize`, and reset EVALS_BRANCH to main.

* Point smoke evals back at the evals-docker-registry branch

Temporary while metabase/evals#32 is unmerged — the ECR image logic is only on
that branch. TODO comment retained so this cannot merge as-is.

* Align ai-benchmark pr/ref precedence with evals eval-run

eval-run.yml resolves both inputs with `ref` overriding the PR head; this
resolved `pr` first, so the same two inputs meant opposite things either side of
the dispatch. Flip precedence and the run-name to match, and point the `ref`
description at eval-run's containment rule instead of claiming pr wins.

* Cleanup the uberjar worfklow

* Smoke should be triggered on !cancelled()

* Reset pointer to evals branch
2026-08-18 12:14:46 +02:00
bryan
7b9b376765 Harden JSON-encoded parameter-values request schema (#80035) 2026-08-18 09:52:00 +01:00
Romeo Van Snick
3933c11183 Register visualization definitions eagerly, load chart components on demand (#79745)
* Give List, Map, ObjectDetail and PivotTable their own definition file

* Let a visualization register a loader for its component

* Load every chart component on demand

* Load the chart chunk while the query is still running

* Delete the echarts lazy boundary the chart split made redundant

* Dedupe modules shared by the SDK's async chunks (#79748)

The chunked SDK entry's splitChunks filter only matched chunks whose
name starts with "embedding-sdk-chunk", so the unnamed chunks created by
import() were excluded from splitChunks entirely. With every chart now
loaded through import(), each echarts-based chart chunk bundled its own
copy of echarts, zrender and the shared viz code, growing the reachable
SDK total from 3.3MB to 6.2MB gzipped.

Include async chunks in the filter and add an asyncCommons cache group
(minChunks: 2) so shared modules move into a common async chunk. The
vendors group keeps its own name-based filter so async modules are not
merged into the eagerly loaded vendor chunks. Initial payload is
unchanged; the legacy monolith and the bootstrap stay excluded.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>

* Lower the size floor for the SDK's shared async chunks

* Load chart components before a story renders

* Retry a chart chunk that fails to download

* Keep one loading state while a chart chunk loads

* Delete the leaflet and pivot-table lazy boundaries the chart split made redundant

* Say why onInit is late now that the renderer is not lazy

* Register the charts a test renders before it runs

---------

Co-authored-by: Nicolò Pretto <info@npretto.com>
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-08-18 11:21:10 +10:00
Fraser
8dbbb58c57 Create current-user module (#79357) 2026-08-18 12:58:58 +12:00
Romeo Van Snick
e7de47b608 Module boundaries follow-ups: storybook element order, dead window-bridge rule (#79803)
* Order the storybook config element before embedding-sdk-shared

* Drop the dead window-bridge whitelist rule
2026-08-18 10:25:04 +10:00
Anderson
f6e9cd0a58 Adapt the collection bulk action bar to pinned, unpinned, and mixed selections (#79857)
* Adapt the collection bulk action bar to pinned, unpinned, and mixed selections

* Align the bulk action bar per-state actions with the Figma spec

* Show the bulk action overflow for unpinned selections and fix its trigger styling

* Move bulk action logic into UnarchivedBulkActions and address review feedback

* Center the bulk action overflow trigger icon via a label class

* Make BulkActionButton code nicer

* Address review comments
2026-08-17 23:38:59 +00:00
Romeo Van Snick
c883033bb6 Make the provider props store payload opaque (#79801) 2026-08-18 09:37:11 +10:00
Cam Saul
34863099c0 Migrate MongoDB to MBQL 5 (#77673)
* [MongoDB] remove `:metadata/key-constraints` driver feature flag (incorrectly set)

* Migrate MongoDB to MBQL 5 [WIP]

* cljfmt

* Test fix 🔧

* Test fixes 🔧

* Test fixes 🔧

* Test fixes 🔧

* value.clj => value.cljs

* value.cljs => value.cljc 🤦

* 🔧

* Let's not deprecate too many things in this PR

* Fix more stuff? 🔧

* Test fixes 🔧

* Revert SQL driver changes

* Test fixes 🔧

* cljfmt

* Test fix 🔧

* Kondo (partial)

* Test fixes 🔧

* cljfmt

* kondo

* Address PR feedback 🔧

* Update ratchets 🔧

* 🔧

* 🔧

* Test fix 🔧

* Update ratchets.edn
2026-08-17 15:34:42 -07:00
Ryan Laurie
fbfa5c9c40 Use ubuntu slim image for 59 little jobs (#80028)
use ubuntu slim image for 59 little jobs
2026-08-17 22:18:37 +00:00
Denis Berezin
7cd842e414 UXW-5013 Support adding a metric to recent items (#79661)
* UXW-5013 Support adding a metric to recent items

Co-authored-by: Ruchir D <111691121+Ruchir-D@users.noreply.github.com>

* Code review fixes

---------

Co-authored-by: Ruchir D <111691121+Ruchir-D@users.noreply.github.com>
Co-authored-by: Nathan Voxland <nathan@metabase.com>
2026-08-18 01:09:23 +03:00
Nemanja Glumac
3fdbcf9ac6 Delete minimal-tests workflow (#80029) 2026-08-17 23:40:16 +02:00
github-automation-metabase
e791ef41da Auto-update documentation for master (#79919)
Update generated docs (master)

Co-authored-by: github-actions <github-actions@github.com>
2026-08-17 19:48:45 +00:00
github-automation-metabase
68496eb7a0 Auto-update documentation for master (#79847)
Update generated docs (master)

Co-authored-by: github-actions <github-actions@github.com>
2026-08-17 15:48:30 -04:00
Nicola Mometto
af35f7f0af Backend hardening (#80003)
Co-authored-by: Alexander Polyankin <alexander.polyankin@metabase.com>
Co-authored-by: Alexander Lesnenko <alxnddr@users.noreply.github.com>
Co-authored-by: Ben Grabow <ben.grabow@gmail.com>
Co-authored-by: Bryan Maass <bryan.maass@gmail.com>
Co-authored-by: Dan Sutton <dan@dpsutton.com>
Co-authored-by: Eric Normand <ericwnormand@gmail.com>
Co-authored-by: Nemanja Glumac <31325167+nemanjaglumac@users.noreply.github.com>
Co-authored-by: Timothy Dean <timothy@timothydean.dev>
Co-authored-by: Tyler Plude <tsplude@gmail.com>
2026-08-17 13:44:13 -06:00
technomancy
c7166aaa15 Only run latest app db variants on PRs (#78755)
* Don't test MySQL/MariaDB AppDB on anything but latest outside release/master.

* generate matrix up front

# Conflicts:
#	.github/workflows/app-db.yml

* bugfix

* parameterize it all

* make things more uniform

---------

Co-authored-by: Ryan Laurie <iethree@gmail.com>
2026-08-17 13:40:56 -06:00
Jeff Bruemmer
8f7a033678 docs - map tile notes (#80006)
* map tile notes

* edit

* image
2026-08-17 19:35:23 +00:00
Ben Grabow
6d4769584e Use an isolated executor pool for test isolation (#79913)
* Use an isolated executor pool for test isolation

* Fix another test

* Fix some other likely flaky tests

* Consistently use the mock executor in the tests that need isolated behavior.
2026-08-17 14:10:21 -05:00
Chris Vandoodewaard
a68d9424ca disable CodeQL overlay DB cache (#79987)
* disable cache

* cleanup codeql cleanup workflow
2026-08-17 14:35:46 -04:00
github-automation-metabase
7582bb77ec Update translations 2026-08-17 (#79988)
* Update translation sources 2026-08-17

* Update translations

---------

Co-authored-by: github-actions <github-actions@github.com>
2026-08-17 17:42:59 +00:00
Ben Grabow
a0d8a1758b Check via .getDataset instead of .listDatasets when all datasets are exactly named (#79921)
* Check via .getDataset instead of .listDatasets when all datasets are exactly named

* Use perf/every?

* Handle some corner case differences between .listDatasets and .getDataset method behaviors
2026-08-17 11:40:08 -05:00
Kamil Mielnik
7470cf2485 GDGT-2646 Refresh leads to custom viz reverting to standard viz (#79888) 2026-08-17 20:28:55 +07:00
Michael Eby
c1fc823ce5 docs: callout for AI Analytics Week (#79918) 2026-08-17 09:18:22 -04:00
Chris Vandoodewaard
b0ba105d0c add file, not line number to .po files (#79723)
add file, not line number
2026-08-17 09:03:55 -04:00
Nick Fitzpatrick
e49a6d6754 Uxw 4937 combine account password and security tabs (#79677)
* Moving Account Security Panel

* tests

* adjustments

* update docs

* Product Feedback, rebasing adjustments

* fix unit test

* adjust e2e
2026-08-17 09:18:28 -03:00
Stas Gavrylov
6b311219dc Fix duplicated rows on the Erroring questions page (#79520)
The `latest_qe` CTE joined `query_execution` to its per-card max
`started_at`, which returns every execution tied at that timestamp
rather than one. A card whose two most recent runs landed in the same
clock tick therefore fanned out into two identical rows on
`/monitor/errors` — same card_id, duplicate row keys in the table, and
an inflated `total_count`. Rank the tied executions and keep one.

Also give the ORDER BY a unique tiebreaker: no sort column is unique,
so tied cards were ordered arbitrarily and could repeat on one page of
LIMIT/OFFSET results while going missing from another.
2026-08-17 15:07:21 +03:00
Oleh K
8129fff836 Match SelectButton styling to Select (#79879)
* Update SelectButton styling to match Select (#GDGT-2705)

SelectButton diverged from the new Mantine Select: bolder text, a smaller
lighter chevron, a taller radius and, on long values, wrapping to two
centered lines instead of truncating.

Match the md Select input on every measurable property — 40px height, 4px
radius, regular weight, left aligned, 16px chevron in text-primary, and
Select's disabled tokens — and truncate long values with an ellipsis. The
clear affordance now sits alongside the chevron rather than replacing it,
matching Select's layout.

Migrate the component from Emotion to CSS modules while here.

Also fixes three Select issues surfaced by comparing the two side by side:

- long values cut off mid-glyph instead of ellipsizing
- with a clear button, the value ran underneath it, because the right-hand
  padding was pinned to a flat 40px while Mantine widens that section to
  60px (md) / 41px (xs)
- the disabled right section painted an opaque background over the field's
  translucent disabled fill, showing a square-cornered box on any
  non-white surface

* Remove comment

* Address review comments

- use !! instead of a null check, onClear is never null
- drop size={16} on both icons, it is Icon's default
- drop overflow: hidden from .SelectInput; the input already computes
  overflow: clip, so the declaration never applied and the ellipsis works
  without it
- cover sm, lg and xl in the clear-button padding fix, not just md and xs
2026-08-17 13:01:49 +02:00
Romeo Van Snick
0b0e6c0f4b Delete the unread collections entity slice (#79870)
* Stop hydrating the collections entity slice

* Delete the unread collections entity slice

* Drop the orphaned createMockEntitiesState import

* Wait for the collection query in the TableCollection link test

* Await the collection tree in the SavedEntityPicker tests
2026-08-17 20:55:14 +10:00
Ngoc Khuat
2366d9fc6b Don't let a failed advisory matching query override the version check (#79466)
* security center: don't let a failed matching query override the version check

an advisory whose matching query names a table the instance doesn't have yet
fails at parse time, and we mapped that to :error. the notification task treats
:error the same as :active, so instances that the version range had already
ruled out got notified anyway. that's how SC-2026-015 reached 1.58.

affected means in-range AND matched, so an undeterminable query result shouldn't
outrank a version check that already said no. same as SQL giving FALSE AND NULL
= FALSE. in-range instances with a query we genuinely couldn't run still report
:error.

* security center: split evaluate-advisory!-test to stay under the kondo length limit
2026-08-17 09:53:42 +00:00
Romeo Van Snick
3a065165fb Read database, table, and field display data from RTK Query (#79810)
* Read database and field display data from RTK Query, not state.entities

* Read table and database breadcrumb data from RTK Query, not state.entities

* Delete the legacy useTableQuery and useDatabaseQuery entity hooks

* Delete the legacy useDatabaseListQuery entity hook

* Keep FileUploadStatus on the mirror-backed table hook
2026-08-17 18:39:07 +10:00
Romeo Van Snick
c9c8b101cd Import only the metadata actions the reference module uses (#79869)
* Drop the dead metadata action spreads in the reference module

* Import only the metadata actions the reference module uses
2026-08-17 13:52:33 +10:00
Fraser
fe94806a72 Re-tier metabot to platform P4 and detail-view to P2 (#79866) 2026-08-17 12:40:31 +12:00
Fraser
a9ad0ee017 Replace the custom-homepage cache patch with tag invalidation (#79867) 2026-08-17 10:38:23 +12:00
metamben
47e50180d6 Return nil when cached query is canceled (like non-cached queries) (#79625)
closes QUE2-106
2026-08-16 15:33:32 +03:00
Romeo Van Snick
45dfb5a837 Make the theme editor an app-tier module (#79802) 2026-08-15 09:21:36 +10:00
Egor Grushin
eb009eb8f9 Require selecting an alert schedule time (#79623)
* Refactoring Schedule, force a user to pick an hour in alerts and subscriptions
2026-08-14 23:54:58 +01:00
Michael Eby
f258c5de52 docs: update outdated starter pricing (#79890) 2026-08-14 17:04:45 -04:00
appleby
fb3f08713d Gemini Enterprise Agent Platform: FE changes (#79558)
* Add Gemini Enterprise Agent Platform provider settings

* Invalidate the cached models list when credentials change

A credential write can change which models the provider serves, e.g. a different Bedrock region, Google location, or
Azure resource.

* Give the FileInput placeholder and clear button a visible color

The theme resolves these to transparent making them invisible withouth the override.

* Review feedback: whitelist recommended models

* Fix useUpdateMetabotSettingsMutation import

* Add gemini-3.7-flash to list of recommended models
2026-08-14 12:31:07 -07:00
appleby
c6e544cb1c Gemini Agent Platform: BE support Gemini models (#78193)
* Add llm-google-* settings for the Gemini Enterprise Agent Platform

The location, project ID and model become path segments of every request, so each is validated as URL-safe.

* Wire the google provider into Metabot provider settings

* Add Google Gemini provider via streamGenerateContent API

Add new provider supporting Gemini models via the Gemini Enterprise Agent Platform

- New ns `metabase.metabot.self.google`. Handles generic provider concerns like
  - contructing appropriate endpoint urls for the given model and location
  - validating caller-provided credentials via a countToken call
  - credentials handling
  - validating config
  - remapping upstream errors with improved error messages
  - toplevel request entrypoint
- New ns `metabase.metabot.self.google.stream-generate-content`
  - handles wire format and aisdk chunk tranlation for Google's streamGenerateContent API

* Wire Google credentials into the admin API

Optional credential settings that are set by an env var no longer block connect or disconnect.

* Skip the provider setting write when shadowed by an env var

* Drop the unused llm-bedrock-configured? setting

Nothing read it: the frontend never referenced it, and its last backend caller went away when
configured-provider-credentials switched to provider-credentials-complete? for the bedrock branch.

* Extract the shared tool->function conversion into schema/tool-function

The mu/defn doc-stripping + filter-schema-by-features + JSON Schema transform boilerplate was copy-pasted across the
claude, openai, chat-completions, and google adapters.

* Review feedback: allow settings to be cleared even if env shadowed

There was a mismatch where check-not-env-shadowed! allowed nil values but set-setting-unless-env-shadowed! did
not. Update set-setting-unless-env-shadowed! to preform nil writes so that a disconnect fully clears the appdb
settings even if some are env shadowed.
2026-08-14 12:31:07 -07:00
technomancy
1ca1c69b3f Track datasets created in with-dynamic-table. (#79862)
Update snowflake's sql.tx/qualified-name-components to not ignore db-name.
2026-08-14 11:43:40 -07:00
Chris Vandoodewaard
6c7ddff080 add workflow to run security scans daily (#79843)
* add workflow to run security scanners

* add newline

* add slack notification on failure
2026-08-14 14:29:21 -04:00
Chris Vandoodewaard
0d1f7d911c used cache deps for Mage (#79903) 2026-08-14 17:35:42 +00:00
Andrei Simionescu
0e70b3eb71 BOT-1956: Read the Python library source from :source (#79573)
Change `get_transform_python_library_details` to read from `:source` instead
of `:content` to match what the API sends. The code is wrapped in a Markdown
fence longer than any backtick run inside it, prefixed with a line telling
the model to treat it as data, and cut off at 100k characters with a
truncation marker when the library is bigger than that.
2026-08-14 18:22:52 +01:00
Andrei Chernykh
0c9e3642c9 Convert enterprise embedding dataselector to ts (#79789)
* Convert enterprise embedding DataSelector to TypeScript

* Replace default exports with named exports in the embedding data picker
2026-08-14 10:00:49 -07:00
Ben Grabow
e3708068c3 Count only the query executions under test (#79726) 2026-08-14 11:37:09 -05:00
Nathan Voxland
5dbc8db1d2 Only default warehouse-allowed-networks to external-only on prod (#79672) 2026-08-14 11:17:55 -05:00
Andrei Chernykh
cab11e6bcc chore: Convert dashboard click drill to ts (#79626)
* Rename dashboard-click-drill and its unit spec to TypeScript

* Convert dashboard-click-drill to TypeScript

* Address review feedback: discriminate click-behavior types and replace non-null assertions with checkNotNull

* Deduplicate base intersections in click-behavior union types
2026-08-14 09:02:00 -07:00
Kevin Kelleher
f0f11536f6 Avoid rerendering visualization on every SQL editor keystroke (#79825)
* Avoid rerendering visualization on every SQL editor keystroke

* fix unnecessary `card` assignment

Co-authored-by: Denis Berezin <denis.berezin@metabase.com>
2026-08-14 15:41:27 +00:00
Riley Thompson
33ac781b25 Snowflake passphrase protected private keys (#79542)
* update tests

* passphrase protected keys

* clean up

* improve tests
2026-08-14 15:36:29 +00:00
Michael Eby
4ba5c162e5 docs: add metric dimensions page (#79772)
* docs: add metric dimensions page

* Optimized 3 images, saved 262.3 KB (53.0% smaller)

* Edits from Jeff

* more consolidation

---------

Co-authored-by: Metabase Automation <github-automation@metabase.com>
2026-08-14 11:05:06 -04:00
Ben Grabow
e29527e5b3 Assert only on password reset email count (#79721)
* Assert only on password reset email count

* Initialize :db :web-server :test-users once for support access grant session tests
2026-08-14 08:52:55 -05:00
Chris Vandoodewaard
c980d85154 print out basic summary for release workflow (#79844) 2026-08-14 08:55:16 -04:00
Chris Vandoodewaard
19899d290d cache Babashka, also guard cache generation (#79841)
* cache Babashka, also guard cache generation

* fix linting

* also cache whitespace-linter deps
2026-08-14 08:54:13 -04:00
Kamil Mielnik
22e69fce8b GDGT-3076 Toast notifications are truncated for unavailable visualizations (#79766) 2026-08-14 09:45:18 +00:00
Oleh K
0a42bfbac2 Keep the remove-table button in the row when table names are long (#79760)
* Keep remove-table button in the row when table names are long

The table selector laid its label button and remove button out in a Group
that wraps by default. The label button is a flex item, so it kept the
default min-width: auto and refused to shrink below the width of its
longest line. A long database or schema name made it claim the whole row
and pushed the remove button onto a line of its own, at the left edge.

Stop the group wrapping, let the button shrink, and truncate the label
lines instead. The lines use max-width rather than width so a short line
keeps the left alignment the Stack gives it -- Button centers its label,
so a full-width line would be centered.

Also space the two label lines apart slightly.

* Space the remove button with margin instead of padding

Padding right sat inside the ActionIcon, so its hover background ran past
the icon and the glyph sat off centre. Margin keeps the same gap from the
row edge with a symmetric 28x28 hit area.

* Use Ellipsified for the table selector label lines

Manual truncation clipped the text with no way to read the full name.
Ellipsified brings the overflow styles and a tooltip that appears only
when the text is actually cut.

Dropping the Stack's align=start matters here: with flex-start each line
sized to its max-content width, so it never overflowed itself and the
truncation check never fired -- the button label clipped the text
instead, without an ellipsis. Stretched lines re-expose the button's
centered text-align, hence ta=left.

* Drop no-op layout props from the table selector

The button root class duplicated miw={0}, which already lands as an
inline min-width. The Stack's w/miw/justify did nothing: it stretches to
the button label by default, the label already carries min-width 0, and
its height is content-driven. ActionIcon has min-width equal to its
natural size, so it cannot shrink and flex="0 0 auto" changed nothing.

Verified by removing each and re-measuring at 800/1440/2560px.

* Drop redundant truncation styles and the empty-state Ellipsified

Mantine's button label already sets overflow hidden, and Ellipsified
carries its own min-width 0, so both declarations restated what was
already there. The css module is back to its state before this branch.

"Select a table..." is a fixed short string that never truncates, so it
goes back to a plain Box.
2026-08-14 10:04:29 +02:00
Anderson
32a179075c Add Escape and Delete shortcuts for collection item selection (#79670)
* Add collection selection keyboard shortcuts

* Address review comments
2026-08-14 00:32:36 -03:00
Fraser
acaeecd506 Delete dead ai-sql-fixer types, move revision diff guards into querying (#79865) 2026-08-14 13:24:19 +12:00
Fraser
fbb89ab47a Delete dead SandboxedPortal and unused formatting barrel exports (#79864) 2026-08-14 13:24:07 +12:00
Romeo Van Snick
8f06a28894 Compare a PR's bundle size against the base ref its uberjar was merged with (#79858) 2026-08-14 11:23:49 +10:00
Fraser
5f6f2ba892 Move card-embed editor extensions into documents (#79695) 2026-08-14 12:39:37 +12:00
Ben Grabow
c5e7d8024a Fix flaky trigger metadata sync test (#79771)
* Isolate async task execution from other tests and ensure task is cleaned up

* Use dynamic redefs
2026-08-13 17:20:02 -05:00
Andrei Chernykh
e0342c82dd Bump react-router from 7.18.1 to 7.18.2: CVE-2026-22030 (#79838) 2026-08-13 14:53:25 -07:00
Maz Ameli
662e74ba16 Add Data Studio guide page and reorganize sidebar navigation (#76707)
* Add Data Studio guide page and reorganize sidebar navigation (#76707)

* adjustments

* transform tabs, e2e adjustments

* oss test

* redirect first timers to the guide page and clean things up

* PR Feedback

* OSS copy, re-adding tests

---------

Co-authored-by: Nick Fitzpatrick <nickfitz.582@gmail.com>
2026-08-13 17:32:21 -03:00
Ryan Laurie
87dc99836a Auto-update documentation for master (#79792)
Update generated docs (master)

Co-authored-by: github-actions <github-actions@github.com>
2026-08-13 19:22:26 +00:00
Alex Yarosh
f5e7923fb5 docs: yet more AI providers (#79395)
* Revise AI provider details in settings documentation

Updated AI provider list to include Mistral and Z.AI models.

* Update docs/ai/settings.md

Co-authored-by: Michael Eby <38187276+michaeleby1@users.noreply.github.com>

---------

Co-authored-by: Michael Eby <38187276+michaeleby1@users.noreply.github.com>
2026-08-13 18:23:39 +00:00
Riley Thompson
0218df7cd7 Offset window function support for clickhouse (#79541)
* backwards compatible version

* clean up

* remove check
2026-08-13 18:06:33 +00:00
Andrei Simionescu
28d47ffafe BOT-1956: Render MBQL transform sources as portable-repr JSON for Metabot (#79575)
Notebook-built transform sources now reach Metabot as the same portable JSON that `construct_notebook_query` consumes, with tables and fields by name, while native SQL still passes through verbatim. Card entity IDs inside an exported query now come from the permission-checked content store, so a source card the reader can't open renders no query at all instead of falling back to an EDN dump.
2026-08-13 18:25:29 +01:00
Michael Eby
f9ac58f586 docs: add Monitor docs section (#79577)
* docs: add Monitor docs section

* update inbound links for profiling-metabase move

* tiny edits

* docs - CLI analytics (#79551)

* edits from jeff

---------

Co-authored-by: Jeff Bruemmer <jeff.bruemmer@gmail.com>
2026-08-13 12:58:41 -04:00
Nick Fitzpatrick
93fb2a5515 Chart Settings Popover horizontal margin (#79786) 2026-08-13 13:58:07 -03:00
Phoomparin Mano
633781cc4e Replace flaky embed code e2e test with jest tests (#79818)
* replace e2e with unit tests

* Update frontend/src/metabase/embedding/embedding-iframe-sdk-setup/components/tests/SdkIframeEmbedSetup.unit.spec.tsx

Co-authored-by: Nicolò Pretto <info@npretto.com>

* remove embed-snippet unit test

---------

Co-authored-by: Nicolò Pretto <info@npretto.com>
2026-08-13 16:30:57 +00:00
YB
98ea8d0a0a [GDGT-3087] mount /api/email routes with auth middleware (#79807)
mount /api/email routes with +auth middleware
2026-08-14 00:23:24 +08:00
Denis Berezin
5efdec98b5 UXW-4961 Convert data-grid to TS (#79788)
* UXW-4961 Convert data-grid to TS

* review fixes
2026-08-13 19:19:37 +03:00
Chris Vandoodewaard
f40f61f6ee add Mage deps to the cache (#79787)
resolve mage deps
2026-08-13 08:08:28 -04:00
Fraser
4724b7bde4 Split viz registry from the index file (#79682) 2026-08-13 23:16:30 +12:00
Fraser
9bed0e2f99 Move the query-action plug to querying and re-tier actions to platform (#79428) 2026-08-13 22:50:14 +12:00
Fraser
1be7ee6d1b Move metabot's endpoints into the metabot module (#79563) 2026-08-13 22:39:12 +12:00
Romeo Van Snick
21600b34b2 Make the metabot state channel payload opaque (#79800)
* Make the metabot state channel payload opaque

* Make MetabotStateChannel generic over the state type
2026-08-13 20:09:59 +10:00
Romeo Van Snick
1f6a8476dc Move the SDK bundle window declaration next to its exports type (#79799) 2026-08-13 20:04:13 +10:00
Romeo Van Snick
aa1d39ebc4 Move SDK storybook themes into embedding-sdk-shared (#79796) 2026-08-13 20:03:51 +10:00
Fraser
644d271c6d Sever visualizer, custom-viz and data-grid edges (#79355)
* Invert visualizer click-object formatting via a Visualization prop

Visualization no longer imports formatVisualizerClickObject from the
visualizer module; DashCardVisualization supplies a transformClickObject
callback instead, so the dashboard side owns the visualizer coupling.
2026-08-13 21:51:41 +12:00
Oleksandr Yakushev
8a83354b64 [perf] Optimize Malli validator cache (#79274) 2026-08-13 08:56:22 +00:00
Fraser
59646dd4b0 Move query-endpoints into querying (#79564) 2026-08-13 20:49:27 +12:00
Fraser
b249fe1b3d Move admin and single-consumer endpoints out of api (#79354) 2026-08-13 20:48:53 +12:00
Romeo Van Snick
a021efac20 Give the transforms, Data Studio, monitor and account pages their own chunks (#79701)
* Give the transforms and Data Studio pages their own chunks

* Give the monitor and account pages their own chunks

* Load the transform pages as one chunk
2026-08-13 15:49:38 +10:00
Romeo Van Snick
7a8ce63393 Give the chart-rendering feature pages their own chunks (#79700)
* Give the chart-rendering feature pages their own chunks

* Load the metric pages as one chunk

* Fetch the Data Studio Library metric pages when their route is matched

* Load the metric pages and their Data Studio wrappers as one chunk

* Say why the metric wrappers share the core chunk
2026-08-13 15:04:30 +10:00
Romeo Van Snick
917c65d41f Remove the unused ?source SVG imports from the icon map (#79741) 2026-08-13 15:01:13 +10:00
Romeo Van Snick
7d228d6fbe Move builtin auth plugin registration into the auth module (#79798) 2026-08-13 13:09:08 +10:00
Romeo Van Snick
fb8cf2d724 Move NewItemMenu integration spec next to NewModals (#79797)
* Move NewItemMenu+NewModals integration spec next to NewModals

* Drop the stale NewItemMenu spec pattern from module boundaries
2026-08-13 13:09:04 +10:00
Romeo Van Snick
a5268784d3 Move customVizColumnTypes into enterprise custom_viz (#79795) 2026-08-13 13:07:35 +10:00
Romeo Van Snick
033ca3a319 Give the dashboard its own chunk (#79645)
* Split the app shell's dashboard selectors into their own module

* Declare the dashboard card actions beside their type constants

* Keep the dashboard reducer off the parameter and data-fetching actions

* Split the tab thunks off the tab reducer

* Fetch the embed setup modals when one is opened

* Give the dashboard its own chunk

* Keep the query builder URL sync from replacing a pending navigation

* Keep the table picker's automatic selection off a pending navigation

* Read the pending navigation from the router, not from a render

* Wait for the code-split embed modal before probing for its terms card

* Drop the note restating what import type already says

* Outrank the grid placeholder style the dashboard chunk now loads later
2026-08-13 13:05:25 +10:00
Anderson
e406a40c47 Reveal column descriptions on hover in the Detail visualization (#78875)
* Show column descriptions in the Detail visualization via an info icon tooltip

* Reveal the Detail column description icon on hover instead of always

* Reserve the description icon's width so hovering never shifts the Detail table

* Address review comments

* Remove delay showing info icon
2026-08-12 23:56:09 -03:00
Anderson
c9f16511fa Allow selecting collection items with shift+click and a Select menu (#79663)
* Add a shift-pressed hook and shift+click selection for rows and pinned cards

* Add a Select entry to the collection item overflow menu

* Cover shift+click and the Select menu entry with an e2e test

* Keep shift+click on row actions from selecting the row

* Simplify collection item selection callbacks

* Address collection selection review feedback

* Scope pinned card queries now that pinned items are listed as rows

A pinned item renders both as a card and as a table row, so unscoped link
queries by item name now match twice. Scope them to the pinned section and
wait for the pinned query before asserting.

* Address review comments
2026-08-12 22:57:14 -03:00
Nemanja Glumac
5147989def Run a configured-skip driver when its own files change (#79793)
Drop the quarantine-conflict flag: a driver marked `skip` in ci-test-config
whose own `modules/drivers/*` files changed now simply runs, instead of
spinning up a runner that fails immediately and demands a `ci:run-<driver>`
label. Changes to another driver's files, or to shared code, leave the skip
in place.

Rename the decision logic's "quarantine" vocabulary to "skip", matching the
config's own `status: skip`. "Quarantine" now refers only to ci-conductor's
suite-level gating rules.

Co-authored-by: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-08-12 23:34:15 +00:00
Fraser
c917cb51a5 Reduce UI imports from viz-core (#79684) 2026-08-13 10:30:07 +12:00
Fraser
d7a8cb8f84 Resolve settings widgets by name (#79683) 2026-08-13 10:29:31 +12:00
Anderson
32d8cbe5d8 Allow pinned collection items to be selected alongside table rows (#79614)
* Make useListSelect key-safe and pinned cards selectable

* Cover shared pinned and table selection with tests

Adds a CollectionContent selection harness and end-to-end coverage for
selecting the same item from its pinned card and its table row, and points
the pinned item menu helper at the card element so it still resolves once
the card becomes a selection target rather than a link.

* Swap the pinned card icon for a checkbox on hover in select mode

* Reset pinned card hover state outside select mode

* Target projected metric dataset requests in e2e

* Simplify pinned selection and select-all handling

* Simplify pinned selection inputs

* Share one selection entry between pinned cards and table rows

Pinned items now appear in the collection contents list (#79679), so the
pinned grid and the table render the same logical item twice. Both read and
write the single useListSelect entry keyed by id plus model, and select-all
covers the listed page once instead of composing a separate pinned set.

* Simplify selected pinned card styling
2026-08-12 19:17:34 -03:00
Nemanja Glumac
b4366d39b7 Consolidate driver ci labels under ci:run-<driver> (#79668)
* consolidate driver CI labels under ci:run-<driver>

break-quarantine-<driver> and ci:run-<driver> were two spellings of the
same override: ci:run-* is checked at Priority 3, ahead of the quarantine
check, so it already forces a quarantined driver to run.

Drop the break-quarantine-* family and point the quarantine-conflict hint,
the mage help, and the workflow error messages at ci:run-<driver>.

* rename ci:all-cloud-drivers to ci:run-all-cloud-drivers

Every other driver force-run label is spelled ci:run-*.


Co-authored-by: Chris Vandoodewaard <chris.vandoodewaard@metabase.com>
2026-08-12 22:38:11 +02:00
Sloan Sparger
d678585e39 [Metabot] Handle expired sessions (#79742)
fix
2026-08-12 12:51:04 -05:00
Sloan Sparger
cb5adad43b [Metabot] Better scrolling on historical convo load (#79734) 2026-08-12 17:49:21 +00:00
Sloan Sparger
ab6756d28f [Metabot] Hide Metabot copy action for textless responses (#79727) 2026-08-12 12:48:26 -05:00
Chris Vandoodewaard
7b8de67c1c only run milestone workflows in metabase/metabase (#79767)
* guard all milestone workflows so they only run in metabase/metabase

* add guards/notes for other workflows doing milestone things

* format

* typo

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

* another typo

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

---------

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
2026-08-12 16:26:10 +00:00
Ben Grabow
b59cd74dc8 Fix flaky cleanup of poll thread (#79729) 2026-08-12 10:59:27 -05:00
Andrei Chernykh
b0826c98f3 Convert app.js and app-main.js entry points to TypeScript (#79724)
* Convert app.js and app-main.js entry points to TypeScript

* Throw instead of logging when the root element is missing
2026-08-12 08:55:03 -07:00
Andrei Chernykh
893c614bed Convert metabase-lib/v1 parameter-values utils to TypeScript (#79555)
* Convert metabase-lib/v1 parameter-values utils to TypeScript

* Address review feedback: keep falsy values in conjunct, flatten test describes
2026-08-12 08:54:03 -07:00
Andrei Chernykh
6580d35948 chore: Convert schema.js to TypeScript (#79685)
* Convert schema.js to TypeScript

* Shorten comments

* Remove dead CacheConfigSchema

* Replace db_id cast with checkNotNull
2026-08-12 08:50:33 -07:00
Chris Vandoodewaard
3e231408dd add repo to release notification (#79770) 2026-08-12 11:37:16 -04:00
Sloan Sparger
a33d96bbd3 [Metabot] Handle content-filter finish reason (#79336)
handle content-filter finish reason
2026-08-12 10:15:31 -05:00
Sloan Sparger
7514efdd2a [Metabot] Handle length finish reason (#79335)
* support length finish reason at the api level

* add length stop reason ui

* TEMP COMMIT

* sure up new providers

* remove trailing whitespace
2026-08-12 10:15:31 -05:00
Jeff Bruemmer
b8e6d94a47 docs - impersonation notes (#79768) 2026-08-12 14:17:57 +00:00
Oleh K
1944ddd2c7 Stop the alert run-status icon from shrinking (#79747)
* Stop the alert run-status icon from shrinking

The warning icon sits in a flex row next to the run's error message, and
with flex-shrink at its default of 1 a long message squeezed it down to a
few pixels wide while its height stayed at 16px.

* Use FixedSizeIcon for the alert run-status icon
2026-08-12 14:22:24 +02:00
Andrei Simionescu
c30815f910 BOT-1921: Document additional Metabot environment variables (#79662)
Ten Metabot settings were marked :doc false, excluding them from
environment-variables.md. Remove the flag and write real descriptions
so MB_METABOT_NAME, MB_METABOT_ICON, MB_METABOT_SHOW_ILLUSTRATIONS,
the three system prompt settings, and the four EE usage-limit/
permissions settings show up in the generated docs.
2026-08-12 10:57:08 +01:00
Romeo Van Snick
08beefc835 Give the admin section its own chunks (#79643)
* Give the admin section its own chunks

* Load the admin pages as two chunks

* Fetch the tenant people and group pages when their route is matched

* Fetch the permissions pages when their route is matched

* Export AdminApp and DataPermissionsPage by name

* Say why the tenant wrappers get their own chunk
2026-08-12 13:57:40 +10:00
8019 changed files with 1705977 additions and 1458276 deletions

View File

@@ -81,7 +81,7 @@ Everything else in the module is **internal** and not allowed to be referenced f
`dev/src/dev/modularization_help.clj` — `potemkin-ns!` helper that generates `.core` re-export boilerplate from a target namespace.
`test/metabase/core/modules_test.clj` — runs on config changes; validates structure, team assignments, API and model boundaries.
`dev/test/metabase/core/modules_test.clj` — runs on config changes; validates structure, team assignments, API and model boundaries.
### API Design Inside a Module
@@ -119,7 +119,7 @@ When the linter complains, the answer is **always refactoring**, never suppressi
- `dev/src/dev/module_score.clj` — quality scoring
- `dev/src/dev/modularization_help.clj` — Potemkin re-export helper
- `dev/src/dev/model_boundary_config.clj` + `dev/src/dev/model_tracking.clj` — model-level enforcement
- `test/metabase/core/modules_test.clj` — config validation tests
- `dev/test/metabase/core/modules_test.clj` — config validation tests
- `src/metabase/core/init.clj` — OSS module init aggregation
- `enterprise/backend/src/metabase_enterprise/core/init.clj` — EE module init aggregation
- `src/metabase/models/resolution.clj` — `:model/X` keyword → namespace map
@@ -198,6 +198,6 @@ Use the `clojure-eval` skill (preferred) or `clj-nrepl-eval` to drive the dev to
(dev.module-score/scores (dev.module-score/deps) (dev.module-score/config))
```
For tests of the config itself, use `./bin/test-agent :only '[metabase.core.modules-test]'`. After editing Clojure files, run `clj-paren-repair`. After editing `config.edn`, re-run the modules-test.
For tests of the config itself, use `./bin/mage project-tests modules`. After editing Clojure files, run `clj-paren-repair`. After editing `config.edn`, re-run the modules-test.
**Update your agent memory** as you discover idioms: which modules use `:friends` and why, which models are most-imported (suggesting they belong in their own module), which settings are accessed cross-module via `(setting/get …)` instead of `:uses` deps, and which refactors the team is actively running.

View File

@@ -304,12 +304,13 @@ Tag response Malli `:map` schemas with `{:closed true}` so the generated OpenAPI
**Linter Suppressions:**
The right shape is a **reader-discard map** placed directly above the form being silenced, listing the rule keywords explicitly:
The right shape is a **reader-discard map** placed directly above the form being silenced, listing the
rule keywords explicitly and including the required explanation:
```clojure
#_{:clj-kondo/ignore [:metabase/validate-defendpoint-route-uses-kebab-case
:metabase/validate-defendpoint-has-response-schema]}
(api.macros/defendpoint :post "/api_key" ...)
;; Loaded by name from the plugin registry.
#_{:clj-kondo/ignore [:clojure-lsp/unused-public-var]}
(defn plugin-entrypoint ...)
```
For a single require entry, hang it as metadata on that entry:
@@ -320,7 +321,12 @@ For a single require entry, hang it as metadata on that entry:
[metabase.query-processor.store :as qp.store])
```
Common Metabase-specific rules you'll see: `:metabase/modules`, `:metabase/validate-defendpoint-route-uses-kebab-case`, `:metabase/validate-defendpoint-has-response-schema`, `:metabase/prefer-with-dynamic-fn-redefs`, `:deprecated-namespace`, `:discouraged-namespace`. Don't use the keyword form (`#_:clj-kondo/ignore`); always the map form so it's grep-able by which rule(s) are suppressed.
Use the map form, not the keyword form (`#_:clj-kondo/ignore`), so searches can identify the suppressed
rules. Keep `:clj-kondo/ignore` as the map's first key; the ratchet scanner rejects other orderings.
Fix the warning when possible. Adding a suppression is a last resort and requires approval. If one is
necessary, add an explanatory `;;` comment directly above it or at the end of the same line. CI enforces
these requirements with `./bin/mage kondo-ratchets`.
**Configurable Options:**

View File

@@ -149,8 +149,7 @@ ms/NonBlankString ;; Non-empty string
ms/BooleanValue ;; String "true"/"false" or boolean
ms/MaybeBooleanValue ;; BooleanValue or nil
ms/TemporalString ;; ISO-8601 date/time string (for REQUEST params only!)
ms/Map ;; Any map
ms/JSONString ;; JSON-encoded string
ms/OpaqueJSONObject ;; JSON object whose keys are not ours to declare; string-keyed
ms/PositiveNum ;; Positive number
ms/IntGreaterThanOrEqualToZero ;; 0 or positive
```

View File

@@ -111,7 +111,12 @@ liability it usually is.
### Miscellaneous
- [ ] Example data is bird-themed when possible
- [ ] Kondo linter suppressions use proper format (not `#_:clj-kondo/ignore` keyword form)
- [ ] Kondo suppressions use a reader-discard map, not `#_:clj-kondo/ignore`, with
`:clj-kondo/ignore` as the first key
- [ ] Each new suppression is approved and has a `;;` comment explaining why the warning cannot be fixed
- [ ] Any ratchet budget increase is explained in the PR
- [ ] PRs that remove ignores leave ratchet budgets unchanged; the shrink workflow records reductions on
`master`
## Pattern matching table

View File

@@ -123,5 +123,12 @@ breakage keeps happening, *that* is the signal a comment was warranted.
- Spaces on a line with nothing after it is not allowed
- After changing module boundaries (adding/removing/renaming a `src` namespace, a cross-module `require`
or `:model/X` reference, or a new module), run `./bin/mage fix-modules-config` to regenerate
`.clj-kondo/config/modules/config.edn` and keep `metabase.core.modules-test` green. No-op when nothing
drifted; see "Module Boundaries" in the project `CLAUDE.md`.
`.clj-kondo/config/modules/config.edn`, then run `./bin/mage project-tests modules`. The fixer is a no-op when
nothing drifted; see "Module Boundaries" in the project `CLAUDE.md`.
- Fix kondo warnings instead of suppressing them. Add a suppression only as a last resort, with approval
and a `;;` comment explaining why it is necessary.
- Do not lower budgets in `.clj-kondo/ratchets.edn` after removing ignores. The shrink workflow records
reductions on `master`.
- If `.clj-kondo/ratchets.edn` conflicts during a merge, rebase, or restack, run
`./bin/merge-kondo-ratchets`. It preserves one-sided changes, chooses the policy that allows fewer
suppressions when both sides change the same entry, and stops when the conflict needs a human decision.

View File

@@ -37,14 +37,16 @@ First check if snapshots exist:
ls e2e/snapshots/default.sql 2>/dev/null && echo "snapshots exist" || echo "snapshots missing"
```
Always pass the spec path via `--spec`. The runner feeds its arguments to Cypress's CLI parser (`cypress.cli.parseRunArguments`), which silently drops bare positional paths and then runs the entire suite. A leading `run` argument is harmless, but the path itself must follow `--spec`. Sanity-check that the first `Running:` line says `(1 of 1)`.
If snapshots exist, skip regeneration for speed:
```bash
MB_EDITION=oss CYPRESS_VIDEO=false CYPRESS_RETRIES=0 CYPRESS_GUI=false GENERATE_SNAPSHOTS=false bun test-cypress $ARGUMENTS
MB_EDITION=oss CYPRESS_VIDEO=false CYPRESS_RETRIES=0 CYPRESS_GUI=false GENERATE_SNAPSHOTS=false bun test-cypress --spec path/to/spec.cy.spec.js
```
If snapshots are missing (first run), let the runner generate them:
```bash
MB_EDITION=oss CYPRESS_VIDEO=false CYPRESS_RETRIES=0 CYPRESS_GUI=false bun test-cypress $ARGUMENTS
MB_EDITION=oss CYPRESS_VIDEO=false CYPRESS_RETRIES=0 CYPRESS_GUI=false bun test-cypress --spec path/to/spec.cy.spec.js
```
When running enterprise tests, replace `MB_EDITION=oss` with `MB_EDITION=ee` in the commands above.
@@ -67,9 +69,11 @@ GREP="test name here" MB_EDITION=oss bun test-cypress --spec path/to/spec.js
When the user asks to verify a test is not flaky:
```bash
MB_EDITION=oss bin/e2e-stress-test $ARGUMENTS
MB_EDITION=oss bin/e2e-stress-test --spec path/to/spec.cy.spec.js
```
(The stress script forwards its arguments to `bun test-cypress`, so the same `--spec` rule applies.)
Set `E2E_STRESS_RUNS=N` for more iterations (default: 5). Stops on first failure and prints screenshot paths. Read those screenshots to analyze the failure.
## Analyzing failures

View File

@@ -171,7 +171,7 @@ Create `ComponentName.module.css` alongside the component file:
/* Use design system tokens — NEVER raw color/spacing values */
.root {
border: 1px solid var(--mb-color-border-neutral);
border-radius: var(--mantine-radius-md);
border-radius: var(--mantine-radius-sm);
background-color: var(--mb-color-background_page-primary);
}
@@ -246,7 +246,8 @@ Remove the old styled file entirely. Remove all imports of it from other files.
**Spacing** (`p`, `px`, `py`, `pt`, `pb`, `pl`, `pr`, `m`, `mx`, `my`, `mt`, `mb`, `ml`, `mr`):
- `"xs"` = 4px, `"sm"` = 8px, `"md"` = 16px, `"lg"` = 24px, `"xl"` = 32px
- `"xxxs"` = 0.125rem, `"xxs"` = 0.25rem, `"xs"` = 0.375rem, `"sm"` = 0.5rem, `"md"` = 0.75rem, `"lg"` = 1rem, `"xl"` = 1.5rem, `"xxl"` = 2rem, `"xxxl"` = 2.5rem
- Use numeric `0` for zero spacing.
- Custom: `rem(48)` for non-standard values (import `rem` from `metabase/ui`)
**Dimensions** (`w`, `h`, `maw`, `mah`, `miw`, `mih`):
@@ -289,11 +290,16 @@ Remove the old styled file entirely. Remove all imports of it from other files.
**Mantine spacing** — `var(--mantine-spacing-<size>)`:
- `--mantine-spacing-xs` (4px), `--mantine-spacing-sm` (8px), `--mantine-spacing-md` (16px), `--mantine-spacing-lg` (24px), `--mantine-spacing-xl` (32px)
- `--mantine-spacing-xxxs` (0.125rem), `--mantine-spacing-xxs` (0.25rem), `--mantine-spacing-xs` (0.375rem), `--mantine-spacing-sm` (0.5rem), `--mantine-spacing-md` (0.75rem), `--mantine-spacing-lg` (1rem), `--mantine-spacing-xl` (1.5rem), `--mantine-spacing-xxl` (2rem), `--mantine-spacing-xxxl` (2.5rem)
**Mantine radius** — `var(--mantine-radius-<size>)`:
- `--mantine-radius-xs` (4px), `--mantine-radius-sm` (6px), `--mantine-radius-md` (8px), `--mantine-radius-xl` (40px)
- `--mantine-radius-xxxs` (0.125rem), `--mantine-radius-xxs` (0.25rem), `--mantine-radius-xs` (0.375rem), `--mantine-radius-sm` (0.5rem), `--mantine-radius-md` (0.75rem), `--mantine-radius-lg` (1rem), `--mantine-radius-xl` (1.5rem)
**Mantine shadows (elevation)** — `var(--mantine-shadow-<size>)`:
- `--mantine-shadow-xs`, `--mantine-shadow-xs_outline`, `--mantine-shadow-sm`, `--mantine-shadow-sm_outline`, `--mantine-shadow-lg_outline`
- Light and dark modes use different shadow values (defined in `frontend/src/metabase/ui/theme.ts`)
**Mantine font sizes** — `var(--mantine-font-size-<size>)`:
@@ -313,24 +319,36 @@ When migrating, **never carry over hardcoded `rem`/`px` values** from the origin
**Spacing** — snap to the nearest Mantine spacing token:
| Hardcoded value | Nearest token | Style prop | CSS variable |
| --------------------------------- | ------------- | ------------ | ------------------------------ |
| `0.125rem` (2px) | `2px` | `2` (number) | `2px` (keep literal, no token) |
| `0.2rem` (3.2px), `0.25rem` (4px) | **xs** (4px) | `"xs"` | `var(--mantine-spacing-xs)` |
| `0.5rem` (8px) | **sm** (8px) | `"sm"` | `var(--mantine-spacing-sm)` |
| `0.75rem` (12px) | between sm/md | `rem(12)` | `0.75rem` (no exact token) |
| `1rem` (16px) | **md** (16px) | `"md"` | `var(--mantine-spacing-md)` |
| `1.5rem` (24px) | **lg** (24px) | `"lg"` | `var(--mantine-spacing-lg)` |
| `2rem` (32px) | **xl** (32px) | `"xl"` | `var(--mantine-spacing-xl)` |
| Hardcoded value | Nearest token | Style prop | CSS variable |
| --------------------------------- | ------------- | ---------- | ------------------------------- |
| `0` (0px) | — | `0` | `0` |
| `0.125rem` (2px) | **xxxs** | `"xxxs"` | `var(--mantine-spacing-xxxs)` |
| `0.2rem` (3.2px), `0.25rem` (4px) | **xxs** | `"xxs"` | `var(--mantine-spacing-xxs)` |
| `0.375rem` (6px) | **xs** | `"xs"` | `var(--mantine-spacing-xs)` |
| `0.5rem` (8px) | **sm** | `"sm"` | `var(--mantine-spacing-sm)` |
| `0.75rem` (12px) | **md** | `"md"` | `var(--mantine-spacing-md)` |
| `1rem` (16px) | **lg** | `"lg"` | `var(--mantine-spacing-lg)` |
| `1.5rem` (24px) | **xl** | `"xl"` | `var(--mantine-spacing-xl)` |
| `2rem` (32px) | **xxl** | `"xxl"` | `var(--mantine-spacing-xxl)` |
| `2.5rem` (40px) | **xxxl** | `"xxxl"` | `var(--mantine-spacing-xxxl)` |
Values between steps: keep the literal (e.g. `rem(10)`), don't round to a token.
**Border radius** — snap to the nearest Mantine radius token:
| Hardcoded value | Nearest token | CSS variable |
| ---------------- | ----------------------------- | -------------------------- |
| `0.25rem` (4px) | **xs** (4px) | `var(--mantine-radius-xs)` |
| `0.375rem` (6px) | **sm** (6px) | `var(--mantine-radius-sm)` |
| `0.5rem` (8px) | **md** (8px) | `var(--mantine-radius-md)` |
| `1rem`+ (16px+) | **xl** (40px) or keep literal | `var(--mantine-radius-xl)` |
| Hardcoded value | Nearest token | CSS variable |
| ---------------- | ------------- | ----------------------------- |
| `0` (0px) | — | `0` |
| `0.125rem` (2px) | **xxxs** | `var(--mantine-radius-xxxs)` |
| `0.25rem` (4px) | **xxs** | `var(--mantine-radius-xxs)` |
| `0.375rem` (6px) | **xs** | `var(--mantine-radius-xs)` |
| `0.5rem` (8px) | **sm** | `var(--mantine-radius-sm)` |
| `0.75rem` (12px) | **md** | `var(--mantine-radius-md)` |
| `1rem` (16px) | **lg** | `var(--mantine-radius-lg)` |
| `1.5rem` (24px) | **xl** | `var(--mantine-radius-xl)` |
Fully-round pills/badges (radius ≥ half the element height): keep a literal
such as `9999px`.
**Font sizes** — snap to the nearest Mantine font size token:

View File

@@ -0,0 +1,248 @@
---
name: fe-modularization
description: Deciding where frontend code lives — tier model, move mechanics, extension points, side effects, naming, and the traps. Use when moving code between modules, carving new modules, fixing boundary violations, adding a barrel or an endpoint, or reviewing module-shape decisions.
---
# Frontend modularization
The module is the unit of blast radius: dependency direction, test selection,
bundle cones, and review scope all follow module boundaries. Every decision
here serves one goal: **make the file locations tell the truth about who owns
what and who may depend on whom.**
## Hard rules (check these before anything else)
- NEVER add an `export … from` re-export at an old path, and NEVER `export *`
from a barrel. Move the code, codemod every call site, delete the old path,
all in the same PR.
- NEVER import past a module's `index.ts` when that module has
`enforcePublicApi: true`, and never past `metabase/ui`'s index at all. If
the barrel is heavy, the fix is making the module side-effect free (below),
not a deep import.
- NEVER rewrite a consumer to a lower-level idiom to make the linter pass. If
the fix makes the consumer worse, the plan is wrong.
- NEVER give a new module `enforceSharedTiers: false`; new modules ship
enforced with `enforcePublicApi: true` and an explicit `index.ts`.
- NEVER move code without the consumer-tier check (procedure step 2).
- ALWAYS delete a module's `enforceSharedTiers: false` line in the PR that
takes it to zero violations.
- ALWAYS measure `bun run module-boundaries` before and after, and report the
numbers.
- ALWAYS import `dayjs` from `metabase/dayjs`, routing from `metabase/router`,
Mantine from `metabase/ui`, react-redux hooks from `metabase/redux`; the
raw specifiers are lint-forbidden.
## Files that are ground truth
| what | where |
|---|---|
| module elements, tiers, `enforceSharedTiers`, `enforcePublicApi` | `frontend/lint/module-boundaries.mjs` |
| shared sub-tiers and levels, cluster rules | `frontend/lint/shared-tiers.mjs` |
| standalone boundaries lint (all violations, incl. grandfathered) | `bun run module-boundaries` (config `eslint.config.module-boundaries.mjs`) |
| PR lint (only enforced modules fail CI) | `bun run lint-eslint-pure` |
| side-effect-free directories and their exceptions | `frontend/build/shared/rspack/side-effect-free-modules.js` (`SIDE_EFFECT_FREE_PATHS`, `SIDE_EFFECT_PATHS`) |
| the lint rules that enforce that promise | `metabase/no-module-side-effects`, `metabase/no-base-api-access` in `frontend/lint/eslint-plugin-metabase/rules/` |
| public-api enforcement | `metabase/enforce-module-public-api` rule, driven by `getPublicApiModules()` |
## The model
Tiers: `lib < basic < shared < feature < app`. Imports point downward, never
sideways at feature tier (features may not import features; app and EE may
import anything). The shared tier is subdivided in `shared-tiers.mjs` into
shared-utils (U0…), shared-platform (P0…), and shared-domain, each ordered
into levels. A module imports only *strictly lower* levels of its sub-tier
plus the sub-tiers below; same-level peers are deliberately forbidden, which
is what makes cycles structurally impossible. A domain may hold two seats
when consumers demand it: a low core and a high surface (metabase-lib below
questions below query_builder; viz-core below visualizations).
Enforcement is per module: `enforceSharedTiers: false` on an element exempts
it from the level rules (counted by `bun run module-boundaries`, invisible to
PR lint). Modules with `enforcePublicApi: true` may only be imported from
outside via `metabase/<module>`, and import relatively inside.
## Deciding where code lives (apply in order; first decisive test wins)
1. **Who owns the concept?** Code lives with the module that owns its
concept, not the module that renders or calls it. A mode encoding dashboard
click behaviour is dashboard code even if viz executes it. Metabot
conversation state is metabot state even though the store registers it.
2. **Consumer-tier check.** The destination must sit at or below the file's
*lowest* consumer. A single consumer below the proposed home vetoes the
move; report it, don't force it.
3. **Only four legitimate fixes** for a bad edge: move the code to its
terminal home; invert through a designed extension point (a prop, an
injected component, a contract type owned by the socket); fix the tier
placement when the declared level is wrong; delete a thin wrapper (a rename
with no derivation isn't an abstraction — deleting it *is* the migration).
4. **A bridge lives above the lower endpoint.** Code that needs both sides of
a boundary belongs in or above the higher module.
5. **"Genuinely shared" is proven by consumers.** A shared address needs two
or more consumers the tier rules can't serve another way. One consumer
pretending to be shared is a feature module at the wrong address.
## Extension points
The socket's owner defines the contract; every plug lives with its extender.
Visualization owns the `mode` prop and click interfaces, each surface supplies
its mode; the editor owns its extension contract, metabot supplies tiptap
extensions; querying owns `TemplateTagsSidebarProps`, parameters implements
it.
- Prefer plain props/injection at composition sites. `PLUGIN_*` registries are
for edition gating; single-reader slots move out to their reading module;
slots with many readers live in the module that owns the concept (every
slot the whitelabel plugin fills lives in `whitelabel`), tier permitting.
Keep contracts type-light so implementations can load lazily.
- Identical injection at every callsite is acceptable until a fourth consumer
or second slot appears; then the composition deserves its own module above
both parts. Don't pre-build the wrapper.
## Store shape
A module that has redux state owns it:
- `store/` is private: reducer, plain creators/action types, and selectors,
typed against the module's own state (`QueryBuilderStoreState`), never the
global `State`. Thunks live in `actions/` and import `store/`, never the
reverse.
- The barrel is the state API: selectors for reads, creators/thunks for
writes.
- Store roots (`reducers-main`, `reducers-public`, the SDK store) import each
slice from its module barrel and derive their own state type; no slice
registry, no `declare module` merging.
- Cross-module writes: a callback prop when a composition point exists;
otherwise dispatch the owner's exported creator; an event only when the
emitter must not know its listeners. Raw `dispatch({ type: "…" })` strings
are banned. A reducer or listener matching another module's *internal*
action is the coupling to remove.
- Slices that mirror one endpoint get deleted (the RTK cache is the state); a
fold over many sources with one writer (the metadata store) is kept as a
module-private slice behind the barrel.
## Endpoints
Endpoints migrate to their owning module via `Api.injectEndpoints` from the
module's `api/` file (settings, metabot, transforms precedents); `metabase/api`
trends toward the client only. There is one `Api` object per backend because
tag invalidation only works within one instance. Consumers reach endpoints
only through the owner's exports (`useGetCardQuery`, `cardApi.endpoints.…`),
never by name through the base object; `metabase/no-base-api-access` allows
injection only in `metabase/api` and `**/api/**` / `**/api.ts`, and reaching by
name only in `metabase/api` and test support (`invalidateTags` /
`resetApiState` are fine anywhere). Each endpoint move carries its
metadata-store hookup: the owner calls `entitiesFetched` from its own
`onQueryStarted`.
## Import-time side effects
Directories in `SIDE_EFFECT_FREE_PATHS` are marked `sideEffects: false` for
rspack, so importing one export from their barrel no longer drags the whole
barrel into a bundle. The price: nothing in those directories may do work at
import time, or production silently drops it. `metabase/no-module-side-effects`
enforces this over every listed directory (module-scope calls, writes to
imported objects or globals, bare imports, control flow at import; escape
hatches are `/* #__PURE__ */` and the rule's pure-callee list). Files that
must run at import are listed in `SIDE_EFFECT_PATHS` (files or directories).
- **A library the app configures gets a facade module** owning the vendor
import, the registrations, and the types, with the raw specifier
lint-forbidden outside it: `metabase/router`, `metabase/ui`,
`metabase/redux`, `metabase/dayjs`. Facades are the effect, so they never
enter `SIDE_EFFECT_FREE_PATHS`. Never re-register a vendor plugin locally
(`dayjs.extend`, `echarts` `use`).
- **A patch a component needs is an explicit registration module,
bare-imported by the provider that needs it** and listed in
`SIDE_EFFECT_PATHS` (Mantine's `Popover.Dropdown` replacement, imported by
`ThemeProvider`).
- **Effects with no value to import** (global CSS, polyfills, the CSP nonce,
EE plugin bootstrap) live in the entry's side-effects file and nowhere else.
- **Registries are filled from the composition root at boot**
(`initializePlugins`, `registerVisualizations`), never by a module
registering itself at import.
- **RTK injection stays at import**; when a module with an `api/` folder is
declared side-effect free, list `<module>/api/` in `SIDE_EFFECT_PATHS`.
## Naming
The feature keeps the plain product-surface name; a shared carve is named for
what the shared part actually is: the concept when the concept is the shared
thing (`settings`, `current-user`, `whitelabel`, `dayjs`), or a qualified
capability when the plain noun is taken (`search-ui`, `metrics-ui`,
`viz-core`, `data-studio-ui`). Never two modules distinguished only by tier
prefix; never generic `-shared` / `-feature` suffixes.
## Procedure for a move
1. **Enumerate consumers honestly** (hook-name greps miss the last three):
```
grep -rn "metabase/<module>" frontend/src enterprise/frontend/src frontend/test e2e
grep -rn "jest.mock(\"metabase/<module>" frontend enterprise/frontend
grep -rn "addMatcher(.*<endpoint>" frontend/src enterprise/frontend/src
```
plus sibling files importing the moved file relatively. Classify each by
module and tier from `module-boundaries.mjs` / `shared-tiers.mjs`.
2. **Consumer-tier check**: destination at or below the lowest consumer. If
not, stop and report the blocking consumer.
3. **Measure before**: `bun run module-boundaries 2>&1 | tail -1` on the base
(write the number down).
4. **Move**: `git mv`; codemod every importer to `metabase/<module>` (outside)
or a relative path (inside); add named exports to the destination barrel
for every symbol an outside consumer needs (each must have a real
consumer). Delete the old path. If the module didn't exist: add its element
in `module-boundaries.mjs` (ordered before any element it's carved from,
first match wins), its level in `shared-tiers.mjs`, `enforcePublicApi:
true`, an `index.ts`. If the move empties a module's violations, delete
its `enforceSharedTiers: false` line. If the module has an `api/` folder
and is side-effect free, list `<module>/api/` in `SIDE_EFFECT_PATHS`.
5. **Verify** (all of these, report the numbers):
```
grep -rn "<old path>" frontend enterprise/frontend e2e # must be empty
bunx eslint --no-warn-ignored <touched files>
bun run lint-eslint-pure # enforce-module-public-api included
bun run type-check-pure
bun run test-unit-keep-cljs <touched folders' specs>
bun run module-boundaries 2>&1 | tail -1 # after; no violation may name the new files
bun run build-release:static-viz # only if viz/static-viz/ui/dayjs touched; hard 3.5 MiB budget
```
6. **Report**: count before/after (state count-neutral explicitly), the edges
removed by file, flags/rules deleted, barrel exports added, anything you
skipped and why, and any consumer you found that vetoed part of the move.
## Traps (each has bitten at least once)
- **Late binding.** A bare function reference in a `createSelector` input
array, a component identity captured for comparison, a `PLUGIN_*` object
read at module scope: all capture at import time and dodge jest spies, EE
overrides, and lazy loading. Read at call time (`(_state) => fn()`), or
inject.
- **Plans go stale.** Verify every recipe against current code before
executing; things get merged, renamed, or turn out never to have existed.
Skip-and-report beats force.
- **The linter's blind spots**: `export … from` re-exports, bare-specifier
packages (custom-viz), pre-seeded caches that never register tags. A grep
for the old path is the stronger claim than a green lint run.
- **Path-keyed baselines reset on rename**: a generated per-file ledger
silently loses a file's history when it moves.
- **A heavy barrel is a bundle hazard until its module is side-effect free.**
One constant imported from the `metabase/ui` barrel pulled Mantine into the
static-viz bundle and broke its budget; the fix was `SIDE_EFFECT_FREE_PATHS`,
never a deep import.
- **Type augmentation is program-wide.** `declare module "dayjs"` (and
similar) makes plugin types available to any file in the same tsconfig, so
a passing type-check never proves the setup ran; only importing the facade
does.
- **Environment before diagnosis**: after a dependency-touching merge,
`bun install` before declaring a failure real; worktrees share staleness
through the node_modules symlink, and a stale `target/cljs_dev` makes
`type-check-pure` fail on `metabase-lib/metric/core.ts` (rebuild cljs in the
worktree).
## PR shape
One logical change per PR; the body names the specific edges removed (files,
imports, before/after count) and gives each move's ownership reason in plain
language a reviewer outside the effort can follow, without campaign labels.
Stack only for semantic dependency or same-hot-file serialisation, and say
so. Consider codeowner surface when chunking. Open as a draft until measured
and green.

View File

@@ -31,6 +31,11 @@ Phases 1, 2, 5 and 6 are shared. The middle two differ in **order**: update mode
- **The component's intended API** — variants, sizes, and states the design system supports for this component. This defines the axes of your showcase (Phase 3).
3. Decide the mode (see **Two modes** above): search for an existing component — in `metabase/ui` or as a legacy component elsewhere. Found → **update**; nothing equivalent anywhere → **create**. Confirm with the user when unsure.
4. **Verify a Figma desktop MCP is connected before doing the work** — this skill depends on it for exact tokens in Phase 4 (and styling can't proceed accurately without it). Do a quick read against the issue's node (e.g. `get_metadata`/`get_variable_defs`); if it errors with "nothing selected" or the server isn't connected, prompt the user to enable it (Switch to Dev Mode → MCP section in the right sidebar) and select the relevant layer before continuing.
5. **Figma Desktop MCP environments only:** open the issue's exact page with [`figma-open`](./figma-open) before MCP reads. Do not run this helper when Desktop MCP is unavailable.
```bash
.claude/skills/metabase-ui-component-from-figma/figma-open "<figma-url-with-node-id>"
```
A URL with `node-id` needs no token. Bare page-name and `--list` lookups require an already-configured `FIGMA_TOKEN`.
## Phase 2 — Understand the component
@@ -205,7 +210,7 @@ Per `docs/developers-guide/frontend.md` ("Colors"): every color must be a **sema
The same discipline applies to **dimensional** values — radius, spacing/padding/gap, elevation/shadow, and typography (font size, line-height, weight). Prefer the codebase's existing scale variable over a literal: `--mantine-radius-*`, `--mantine-spacing-*`, `--mantine-shadow-*`, and the Mantine font tokens.
But Figma's scales don't always line up with the codebase's. When a Figma value **has no matching step** in the corresponding scale — e.g. Figma `radius/md = 12px` while `--mantine-radius-md` is `8px`, or a Figma `xxxs` spacing step with no Mantine equivalent — **don't silently bake in a literal.** Flag it to the user the same way you flag primitive colors: name the property, the Figma value, and the nearest codebase token, so it can be resolved with design / the scale owners (align the value, or add a scale step). Only fall back to a literal if the user confirms it's an accepted one-off, and leave a short comment in the code explaining why.
But Figma's scales don't always line up with the codebase's. When a Figma value **has no matching step** in the corresponding scale — e.g. Figma `radius/md = 16px` while `--mantine-radius-md` is `0.75rem`, or a Figma spacing step that has no Mantine equivalent — **don't silently bake in a literal.** Flag it to the user the same way you flag primitive colors: name the property, the Figma value, and the nearest codebase token, so it can be resolved with design / the scale owners (align the value, or add a scale step). Only fall back to a literal if the user confirms it's an accepted one-off, and leave a short comment in the code explaining why. The codebase scales are defined in `frontend/src/metabase/ui/theme.ts` (`SPACING_SCALE`, `RADIUS_SCALE`, `LIGHT_SHADOWS`/`DARK_SHADOWS`).
### Mantine implementation notes (reference)
@@ -240,5 +245,6 @@ Only after sign-off:
- [ ] Storybook showcase matrix built from the component's full state space (theme excluded — global toggle drives light/dark), single panel, hover/pressed forced via `storybook-addon-pseudo-states`, controls scoped per story; lint + type-check pass. (Update mode: built before styling, **component styles untouched**. Create mode: built after the component is implemented in Phase 4.)
- [ ] Figma desktop MCP available; exact tokens extracted and mapped to semantic `--mb-color-*` (NO `color-mix`, NO primitives) and to existing scale vars for radius/spacing/elevation/type — any color *or* dimensional value with no matching token/scale step flagged to the user, not baked in as a literal.
- [ ] Component styled; stylelint + eslint(+CSS modules) + type-check pass.
- [ ] Loki coverage registered: `storiesFilter` matches exact story display names; targeted `loki update` generated references; reference PNGs and Playwright screenshots visually inspected; targeted `loki test` passes; `.loki/reference/*.png` included in the commit.
- [ ] Iterated with the user until satisfied.
- [ ] Committed (when asked); call sites migrated/verified (update) or export wired (create); findings doc handed back.

View File

@@ -0,0 +1,68 @@
#!/usr/bin/env bash
# figma-open — open a Figma file (or a specific page) in the Figma desktop app
#
# Usage:
# figma-open <url-or-file-key> open the file
# figma-open <url-or-file-key> <node-id> open at a node/page id (e.g. 12-3 or 12:3)
# figma-open <url-or-file-key> --list list pages with their ids
# figma-open <url-or-file-key> "Page name" open a page by name
#
# Page lookup by name/--list needs a Figma personal access token:
# export FIGMA_TOKEN=figd_... or put it in ~/.config/figma/token
set -euo pipefail
arg="${1:-}"
[[ -n "$arg" ]] || { awk 'NR==1 && /^#!/ {next} /^#/ {sub(/^# ?/,""); print; next} {exit}' "$0"; exit 1; }
token="${FIGMA_TOKEN:-}"
[[ -f "$HOME/.config/figma/token" ]] && token="$(<"$HOME/.config/figma/token")"
# Extract the file key from any Figma URL form, or use the arg as a bare key.
key="$arg"
case "$arg" in
*figma.com*|figma://*)
key="$(printf '%s' "$arg" | sed -E 's#https?://([a-z]+\.)?figma\.com##; s#^([a-z0-9-]+\.)?figma\.com##; s#^figma://##; s#^/?(file|design|proto|board)/##; s#^/##; s#/.*##; s#\?.*##')"
;;
esac
req="${2:-}"
# If no page arg was given but the URL carries a node-id, use it.
url_node="$(printf '%s' "$arg" | sed -nE 's/.*[?&]node-id=([0-9]+([-:][0-9]+)*).*/\1/p')"
open_fig() { # $1 = optional node id
if [[ -n "${1:-}" ]]; then
open "figma://file/${key}?node-id=${1//:/-}"
else
open "figma://file/${key}"
fi
}
# No page requested — open the file (or the node the URL points at).
[[ -z "$req" ]] && { open_fig "${url_node:-}"; exit 0; }
# Explicit node id (page ids work: pages are top-level nodes).
if [[ "$req" =~ ^[0-9]+[:-][0-9]+$ ]]; then
open_fig "$req"
exit 0
fi
# Everything else needs the REST API.
[[ -n "$token" ]] || { echo "error: page lookup needs FIGMA_TOKEN (env or ~/.config/figma/token)" >&2; exit 1; }
pages_json="$(curl -sf -H "X-Figma-Token: ${token}" "https://api.figma.com/v1/files/${key}?depth=1")" \
|| { echo "error: could not fetch file ${key} (bad key, no access, or bad token)" >&2; exit 1; }
if [[ "$req" == "--list" || "$req" == "-l" ]]; then
printf '%s\n' "$pages_json" | jq -r '.document.children[] | "\(.id // .guid)\t\(.name)"' | column -t -s $'\t'
exit 0
fi
# Page by name (case-insensitive, exact match first, then substring).
node_id="$(printf '%s' "$pages_json" | jq -r --arg n "$req" \
'first(.document.children[] | select((.name // "") | ascii_downcase == ($n | ascii_downcase)) | .id // .guid) //
first(.document.children[] | select((.name // "") | ascii_downcase | contains($n | ascii_downcase)) | .id // .guid) //
empty')"
[[ -n "$node_id" ]] || { echo "error: no page matching \"$req\" in file ${key}" >&2; exit 1; }
open_fig "$node_id"

View File

@@ -17,10 +17,10 @@ Adherence to `typescript-write` is the **highest-priority** review dimension: ra
Review in this priority order:
1. **Violations of [`typescript-write`](../typescript-write/SKILL.md) provisions** — no-`any`, type tightening, type modeling, null/undefined handling, naming, structure, comments. Highest priority; block on the no-`any` rule.
1. **Violations of [`typescript-write`](../typescript-write/SKILL.md) provisions** — no-`any`, type tightening, type modeling, function signatures, null/undefined handling, naming, structure, comments. Highest priority; block on the no-`any` rule. Apply conditional guidance in context: explain the unsupported type guarantee or concrete readability problem, rather than treating every preference as a blanket ban.
2. Compliance with `frontend/CLAUDE.md`.
3. Readability and maintainability.
4. Appropriate test coverage.
4. Appropriate test coverage. For internal typed callers, avoid requesting tests solely for inputs the type system excludes. External API data, deserialised values, storage and JavaScript callers can violate annotations: test runtime validation and nontrivial assumptions at those boundaries. Types do not replace behavioural, security or data-integrity tests.
## Blind spots — act as the missing reviewer
@@ -31,3 +31,4 @@ These rarely surface in team reviews, so this skill should raise them. They are
- **Security.** Evaluate potential security issues in new code.
- **Bundle size.** Flag new large dependencies, default imports from icon or util libs, and heavy modules imported at route-load time.
- **Analytics.** User-facing flows should emit tracking events. If a PR adds a new flow (button, modal, navigation) without a tracking event, ask whether one is expected.
- **Public API surface** (embedding SDK). Consumers should be able to use public signatures and name types they need to import. Export those types deliberately and document public behaviour, including `@deprecated` for deprecated APIs; a referenced structural type does not automatically need its own named export.

View File

@@ -20,20 +20,27 @@ description: Write TypeScript and JavaScript code following Metabase coding stan
- **Avoid type casts and loose `unknown`** — fix the signature instead.
- **If a function only needs one field of a wide object, accept that field** — not the wide object. The cast often disappears once the signature is right.
- **Reach for `Partial<T>`, `Pick<T, K>`, `Record<K, V>`, and generics** before reaching for a cast.
- **Match dictionary keys to the data.** Use a finite key union when the keys are known. Open dictionaries can use an index signature, `Record<string, T>`, or `Map`; index signatures still constrain values, and changing their spelling to `Record<string, T>` does not make missing-key access safe.
- **Prefer making props/components generic** (`<T>`) when a value flows through unchanged and the caller knows the type.
- **Prefer `unknown` over loose typing** and narrow before use — an `unknown` value forces a guard at the point of use.
- **`satisfies` for object literals** that must conform without widening (config objects, lookup maps, discriminated literals) — better than `: T` (widens) or `as T` (unsafe).
- **Avoid non-null assertions (`!`)**. Prefer a guard, early return, or `?.`. Use `!` only when non-nullness is provably true and localized, with a comment.
- **Guard indexed lookups that may miss.** Arrays and dictionaries can return `undefined` even when the inferred type omits it. Use an iteration form that preserves the key/value relationship, and only assert `keyof` when the runtime keys are known to belong to the declared type.
- **No redundant runtime coercion** — don't wrap already-typed values in `Number()` / `String()` / `Boolean()`.
- **Type guards belong in `frontend/src/metabase-types/guards/`**. Do not redefine them locally.
- **A cast you can't avoid needs a real justification comment.** The `metabase/no-unjustified-type-casts` rule accepts any preceding comment — state the actual reason the cast is safe. NEVER write the legacy `// Unjustified type cast. FIXME` placeholder; it exists only on casts that predated the rule, and copying it sneaks an unjustified cast past the linter. If you can't articulate why the cast is correct, the cast is wrong — fix the types.
- **Keep unavoidable assertions local.** Isolate a repeated or complex assertion behind a helper when that makes its invariant easier to enforce. Test nontrivial runtime assumptions that justify it; a trivial assertion does not automatically need a new helper or test. Do not weaken a public signature just to silence implementation errors.
## Type modeling
- **Reuse existing types; don't re-declare them.** Use canonical IDs and domain entity types from `metabase-types/api` (`FieldId`, `TableId`, `ConcreteTableId`, `SchemaName`, …) and key data structures by them (`new Map<ConcreteTableId, …>()`). Don't duplicate generated/API types — compose or derive (`Pick`, `Omit`, indexed access `SomeType["field"]`, `ReturnType`).
- **Use generics to allow TypeScript to infer correct types** when creating functions and components that need to be reusable and type-safe. Don't hesitate to introduce complex generics if they allow to derive types automatically instead of manual narrowing.
- **Generics must make promises the implementation can keep.** A caller-selected `get<T>(): T` must not disguise an unchecked assertion about external data. Return `unknown` and validate, or accept a validator that establishes `T`. A factory such as `function empty<T>(): T[] { return []; }` is valid; judge the implementation, not how often `T` appears in the signature.
- **Prefer an honest type over false precision.** Use generics when they express a real relationship. If a complex type cannot model the behaviour accurately, choose a simpler type or `unknown` with narrowing instead of asserting an unsupported guarantee.
- **Model the actual data contract; keep types narrow.** Optional `field?: T` for a key that may be absent, `field: T | undefined` only when the key is always present but the value may be undefined, `| null` for explicit API nulls. Prefer domain unions over broad `string` / `number` / loose `Record`.
- **Refer to API implementation** when defining or refining types to ensure they match the actual data structure. When considering a type cast, first consider if the type should be refined to match the actual data structure.
- **Optionality must reflect absence.** Keep required fields required and optional fields optional. Normalise input when the application has a meaningful default, not merely to remove a type error. Preserve the actual wire shape in API types.
- **Represent related absence together when modelling internal state.** If several fields exist or disappear together, consider a nullable containing object or a discriminated union. Do not reshape a raw API declaration unless the data actually has that shape.
- **Prefer explicit special states when designing a format.** Use nullability or named union variants when sentinel values such as `-1` hide meaning. Preserve established protocol sentinel values unless the behaviour is deliberately changed, or normalise them at an explicit boundary.
- **Discriminated unions for variant state, with exhaustive checks.** Model "one of N shapes" as a union with a literal discriminant rather than a bag of optional fields, and exhaust it with ts-pattern's `.exhaustive()` so adding a variant becomes a compile error:
```ts
import { match } from "ts-pattern";
@@ -45,20 +52,30 @@ description: Write TypeScript and JavaScript code following Metabase coding stan
.exhaustive(); // Compile-time guarantee all cases handled
```
- **Derive union types from constants** (`as const` + `typeof`/`keyof`) so the type and the values can't drift.
- **`readonly` / immutability where mutation isn't intended** — component props, shared constants, exported config. Prefer `readonly T[]` / `ReadonlyArray<T>` for inputs you don't mutate.
- **`readonly` / immutability where mutation isn't intended** — component props, shared constants, exported config, and unmutated parameters. Prefer `readonly T[]` / `ReadonlyArray<T>` for inputs you don't mutate. Functions that mutate caller-owned data should make that behaviour explicit.
- **Construct complete, well-typed objects where practical.** Prefer an object expression when it avoids partially initialised state or assertions. Incremental construction is fine when it is clearer and maintains the type's invariants.
- **Treat `metabase-lib` opaque types as black boxes.** Use `metabase-lib` functions to work with types such as `Lib.Query`, rather than casting into their internal representation.
- **Type async and error states explicitly** (a discriminated union or the data-layer's typed result) — never leave loading/error/empty implicit.
## Function signatures
- **Make public contracts explicit where it improves stability and clarity.** Annotate parameters and return types at shared boundaries when useful; let local values infer. Use `satisfies` or an annotation when a declaration needs an explicit shape check.
- **Accept the inputs the operation supports and return the most precise honest result.** Narrow avoidable uncertainty inside the function, but preserve meaningful nullability and union variants in its return type.
- **Use named options when positional arguments are easy to confuse.** Consecutive arguments with the same type are a useful warning sign, not an automatic requirement to rewrite a clear API.
- **Use `async`/`await` when it clarifies control flow or error handling.** Returning an existing promise directly is also valid; a Promise return type alone does not require adding `async`.
## Null and undefined
- **Narrow at the source**. If a value is optional only in a corner case, don't thread `undefined` through every layer — guard at the producer.
- **Sensible defaults for optional values**. Use `?.` and `??` at the consumer.
- **Lists should be filtered** before being used in a map or other iteration.
- **Narrow nullable list elements when the operation requires present values.** Filter with a type guard when missing entries should be discarded; preserve them when their absence or position carries meaning.
- **Avoid non-strict null comparisons** (`X != null`) when `X` can never be `null` — use a strict check or narrow the type. Use `checkNotNull` where necessary.
- **Check actual nullability against API implementation**. Find the API endpoint implementation and check if the field can actually be null.
## Naming
- **Names describe the entity, not the mechanism**. A name must reflect what the value holds.
- **Use domain vocabulary and include units where useful** (`timeoutMs`, `widthPx`, `temperatureC`). Prefer a more specific name when `Info`, `Data`, or `Entity` obscures the meaning, while keeping established terminology when it is clear.
- **Align sibling concepts**: keep verb conventions consistent across a related API.
- **No names that encode implementation history** rather than current meaning. Suffixes like `Base`, `New`, `Old`, `Initial` need a real semantic distinction, otherwise drop them.
- **Avoid cryptic identifiers** (`v`, `n`, `$n`) for domain values; short names are fine only in tiny conventional contexts (loop index `i`, coordinates `x`/`y`, generic params `T`/`K`/`V`).
@@ -75,10 +92,6 @@ description: Write TypeScript and JavaScript code following Metabase coding stan
- **No comments by default**. Well-named identifiers carry the `what`.
- **Comments should be concise**. Add a short, concise comment only when the `why` is non-obvious: a workaround, a hidden invariant, a subtle ordering constraint, a clever reduction. Never document the actual implementation, focus on the intent and the why.
## TypeScript Migration
**When touching existing JavaScript files, propose to convert them to TypeScript first**. Create a separate PR for the conversion, then implement the changes.
## Verify before done
- **Run the project type-check** when finished (see the shared TypeScript commands above).

View File

@@ -72,6 +72,7 @@
:metabase/namespace-name {:level :warning}
:metabase/no-jsqlparser-imports {:level :warning}
:metabase/prefer-with-dynamic-fn-redefs {:level :warning}
:metabase/t2-query-namespace {:level :warning}
:metabase/toucan-model-ns {:level :warning}
:metabase/require-shape-checker {:level :warning}
:metabase/tests-must-live-in-known-modules {:level :warning}
@@ -180,7 +181,7 @@
clojure.core.async/take!
clojure.core.async/to-chan!
clojure.core.async/to-chan!!
;; only writes .clj-kondo/ratchets.edn, from a :once fixture that finishes before the parallel tests
;; writes the ratchet files from a :once fixture that finishes before the parallel tests
dev.kondo-ratchet/fix!
metabase.ai-tracing.core/record!
metabase.api.macros.defendpoint.tools-manifest/assert-optional-fields-nullable!
@@ -191,6 +192,8 @@
metabase.channel.render.pdf.font/load-fonts!
metabase.warehouses.models.database/assert-not-h2!
metabase.driver.sql-jdbc.execute/execute-prepared-statement!
;; only inspects a details map and throws; the `!` is for the throw, not for a mutation
metabase.driver/validate-db-details!
metabase.mcp.usage/record-mcp-session!
metabase.mcp.usage/record-mcp-session-end!
metabase.mcp.usage/record-mcp-tool-call!
@@ -403,6 +406,7 @@
metabase.channel.render.core channel.render
metabase.cloud-migration.core cloud-migration
metabase.eid-translation.core eid-translation
metabase.llm.test-util llm.tu
metabase.login-history.core login-history
metabase.model-persistence.core model-persistence
metabase.notification.core notification
@@ -466,6 +470,7 @@
metabase-enterprise.serialization.metadata-file-import.wire-format-test/with-tiny-fixture! clojure.core/fn
metabase-enterprise.serialization.test-util/with-dbs clojure.core/fn
metabase-enterprise.serialization.test-util/with-random-dump-dir clojure.core/let
metabase-enterprise.tenants.pulse-api-test/with-tenant-pulse-fixture! clojure.core/fn
metabase-enterprise.workspaces.test-util/with-resources! clojure.core/let
metabase-enterprise.workspaces.test-util/with-workspaces! clojure.core/let
metabase.actions.test-util/with-actions clojure.core/let
@@ -495,6 +500,7 @@
metabase.notification.test-util/with-card-notification clojure.core/let
metabase.notification.test-util/with-system-event-notification! clojure.core/let
metabase.notification.test-util/with-temp-notification clojure.core/let
metabase.oauth-server.test-util/with-oauth-client clojure.core/fn
metabase.osi.ai-context.api-test/with-test-entry clojure.core/let
metabase.premium-features.core/defenterprise-schema clj-kondo.lint-as/def-catch-all
metabase.premium-features.defenterprise/defenterprise-schema clj-kondo.lint-as/def-catch-all
@@ -628,6 +634,45 @@
metabase.lib.schema.mbql-clause/define-tuple-mbql-clause hooks.metabase.lib.schema.mbql-clause/define-mbql-clause
methodical.core/defmethod hooks.metabase.toucan.table-name/lint-defmethod
methodical.macros/defmethod hooks.metabase.toucan.table-name/lint-defmethod
metabase.app-db.core/query hooks.metabase.toucan.db-ns/lint-query-call
metabase.app-db.core/streaming-reducible-query hooks.metabase.toucan.db-ns/lint-query-call
metabase.app-db.core/select-or-insert! hooks.metabase.toucan.db-ns/lint-query-call
metabase.app-db.core/update-or-insert! hooks.metabase.toucan.db-ns/lint-query-call
metabase.app-db.core/current-timestamp-string hooks.metabase.toucan.db-ns/lint-query-call
metabase.app-db.query/query hooks.metabase.toucan.db-ns/lint-query-call
metabase.app-db.query/streaming-reducible-query hooks.metabase.toucan.db-ns/lint-query-call
metabase.app-db.query/select-or-insert! hooks.metabase.toucan.db-ns/lint-query-call
metabase.app-db.query/update-or-insert! hooks.metabase.toucan.db-ns/lint-query-call
metabase.app-db.query/current-timestamp-string hooks.metabase.toucan.db-ns/lint-query-call
toucan2.core/count hooks.metabase.toucan.db-ns/lint-query-call
toucan2.core/delete! hooks.metabase.toucan.db-ns/lint-query-call
toucan2.core/exists? hooks.metabase.toucan.db-ns/lint-query-call
toucan2.core/insert! hooks.metabase.toucan.db-ns/lint-query-call
toucan2.core/insert-returning-instance! hooks.metabase.toucan.db-ns/lint-query-call
toucan2.core/insert-returning-instances! hooks.metabase.toucan.db-ns/lint-query-call
toucan2.core/insert-returning-pk! hooks.metabase.toucan.db-ns/lint-query-call
toucan2.core/insert-returning-pks! hooks.metabase.toucan.db-ns/lint-query-call
toucan2.core/query hooks.metabase.toucan.db-ns/lint-query-call
toucan2.core/query-one hooks.metabase.toucan.db-ns/lint-query-call
toucan2.core/reducible-query hooks.metabase.toucan.db-ns/lint-query-call
toucan2.core/reducible-select hooks.metabase.toucan.db-ns/lint-query-call
toucan2.core/reducible-update hooks.metabase.toucan.db-ns/lint-query-call
toucan2.core/reducible-update-returning-pks hooks.metabase.toucan.db-ns/lint-query-call
toucan2.core/save! hooks.metabase.toucan.db-ns/lint-query-call
toucan2.core/select hooks.metabase.toucan.db-ns/lint-query-call
toucan2.core/select-fn->fn hooks.metabase.toucan.db-ns/lint-query-call
toucan2.core/select-fn->pk hooks.metabase.toucan.db-ns/lint-query-call
toucan2.core/select-fn-reducible hooks.metabase.toucan.db-ns/lint-query-call
toucan2.core/select-fn-set hooks.metabase.toucan.db-ns/lint-query-call
toucan2.core/select-fn-vec hooks.metabase.toucan.db-ns/lint-query-call
toucan2.core/select-one hooks.metabase.toucan.db-ns/lint-query-call
toucan2.core/select-one-fn hooks.metabase.toucan.db-ns/lint-query-call
toucan2.core/select-one-pk hooks.metabase.toucan.db-ns/lint-query-call
toucan2.core/select-pk->fn hooks.metabase.toucan.db-ns/lint-query-call
toucan2.core/select-pks-set hooks.metabase.toucan.db-ns/lint-query-call
toucan2.core/select-pks-vec hooks.metabase.toucan.db-ns/lint-query-call
toucan2.core/update! hooks.metabase.toucan.db-ns/lint-query-call
toucan2.core/update-returning-pks! hooks.metabase.toucan.db-ns/lint-query-call
metabase.lib.test-util.macros/$ids hooks.metabase.test.data/$ids
metabase.lib.test-util.macros/mbql-query hooks.metabase.test.data/mbql-query
metabase.lib.test-util.macros/mbql-5-query hooks.metabase.test.data/mbql-query
@@ -799,7 +844,7 @@
:name test-namespaces}
{:pattern "^(?!.*-test(?:\\..*)?$)(?!.*test-util)(?!^metabase\\.test.*).*$"
:name source-namespaces}
{:pattern "(?:(?:^metabase\\.cmd.*)|(?:^build.*)|(?:^metabuild-common.*)|(?:^release.*)|(?:^i18n.*)|(?:^lint-migrations-file$))|(?:^mage.*)"
{:pattern "(?:(?:^metabase\\.cmd.*)|(?:^build.*)|(?:^metabuild-common.*)|(?:^release.*)|(?:^i18n.*)|(?:^lint-migrations-file$))|(?:^mage.*)|(?:^load-namespaces.*)|(?:^dev\\..*)"
:name printable-namespaces}
{:pattern "^metabase\\.(?:(?:lib)|(?:legacy-mbql))\\..*"
:name metabase-lib}
@@ -836,7 +881,13 @@
{:pattern "^metabase(?:((?:-enterprise\\.sandbox)?\\.query-processor)|(?:\\.driver\\.sql(?!server)(?!ite))).*-test$"
:name general-qp-and-driver-test-namespaces}
{:pattern "(?:^mage.*)"
:name mage-namespaces}]
:name mage-namespaces}
;;
;; the app-db module is the application database layer itself (connections, migrations, encryption), so it gets to
;; run Toucan 2 queries anywhere.
;;
{:pattern "^metabase\\.app-db\\..*"
:name app-db-namespaces}]
:config-in-ns
{test-namespaces
@@ -846,6 +897,7 @@
:private-call {:level :off}
:metabase/defsetting-must-specify-export {:level :off}
:metabase/defsetting-namespace {:level :off}
:metabase/t2-query-namespace {:level :off}
:metabase/test-helpers-use-non-thread-safe-functions {:level :warning} ; more config in `.clj-kondo/config/test-helpers/config.edn`
:discouraged-var
@@ -853,6 +905,9 @@
metabase.lib.convert/->legacy-MBQL {:level :off}
metabase.lib.core/->legacy-MBQL {:level :off}}}}
app-db-namespaces
{:linters {:metabase/t2-query-namespace {:level :off}}}
;; .cljc tests run in both Clojure and ClojureScript — `with-dynamic-fn-redefs` is JVM-only,
;; so leave these alone.
metabase.lib.aggregation-test

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,6 @@
;; Budgets for escape hatches in config.edn. Counts may fall but not exceed these values.
;; Leave reductions to the post-merge shrink workflow; explain increases in the PR.
{:api-any 1
:friend-edges 22
:model-imports-bypass 2
:uses-any 4}

View File

@@ -58,6 +58,7 @@
metabase.app-db.core/finish-db-setup!
metabase.app-db.core/migrate!
metabase.app-db.core/setup-db!
metabase.app-db.encryption-test-util/do-with-encrypted-app-db!
metabase.app-db.schema-migrations-test.impl/run-migrations-in-range!
metabase.app-db.setup/migrate!
metabase.app-db.setup/setup-db!

View File

@@ -1,48 +1,81 @@
;; Per-linter budgets for inline `:clj-kondo/ignore` forms.
;; metabase.core.kondo-ratchet-test fails when the budgets drift from the actual counts.
;; `./bin/mage fix-kondo-ratchets` lowers budgets to match the tree; local test runs do it
;; automatically. Raising a budget, or adding one for a new linter (`--seed`), is a hand edit
;; to defend in your PR.
;; Budgets for kondo suppressions: inline `:clj-kondo/ignore` forms per linter (:ignore-counts), and
;; config-level waivers in .clj-kondo/config.edn (:config-counts -- :off switches and :exclude entries).
;; Each :ignore-counts value is a non-negative integer budget, or :unlimited for no ceiling.
;; Checks fail when a count exceeds its numeric budget; unused budget is allowed.
;; Any ignore outside :comment-exempt needs an explanatory comment directly above or trailing on its line.
;; `./bin/mage kondo-ratchets-shrink` lowers budgets unless `--seed` explicitly adds or raises one.
;; The workflow runs it on master, so feature branches do not need to record reductions.
;; Raising or adding a budget (`--seed` for inline ignores, a manual edit otherwise) or widening the
;; exemptions must be explained in the PR.
;; :all is the vector-less ignore form, which suppresses every linter on the next form.
{:ignore-counts {:aliased-namespace-symbol 3
:all 49
:case-symbol-test 1
:clojure-lsp/unused-public-var 9
:def-fn 1
:deprecated-namespace 95
:deprecated-var 79
:discouraged-java-method 3
:discouraged-namespace 79
:discouraged-var 107
:equals-true 1
:main-without-gen-class 1
:metabase/defsetting-namespace 2
:metabase/disallow-hardcoded-driver-names-in-tests 34
:metabase/discourage-millis-duration 1
:metabase/i-like-making-cams-eyes-bleed-with-horrifically-long-tests 13
:metabase/modules 7
:metabase/namespace-name 4
:metabase/prefer-with-dynamic-fn-redefs 28
:metabase/test-helpers-use-non-thread-safe-functions 17
:metabase/validate-defendpoint-has-response-schema 441
:metabase/validate-defendpoint-query-params-use-kebab-case 47
:metabase/validate-defendpoint-route-uses-kebab-case 44
:metabase/validate-deftest 9
:missing-docstring 10
:missing-protocol-method 3
:non-arg-vec-return-type-hint 1
:reduce-without-init 3
:redundant-fn-wrapper 1
:syntax 2
:uninitialized-var 1
:unquote-not-syntax-quoted 1
:unresolved-namespace 3
:unresolved-require 1
:unresolved-symbol 4
:unsorted-required-namespaces 1
:unused-alias 1
:unused-binding 9
:unused-excluded-var 2
:unused-namespace 1
:unused-private-var 8
:unused-value 1}}
{:ignore-counts {:aliased-namespace-symbol 3
:case-symbol-test 1
:clojure-lsp/unused-public-var 9
:consistent-alias 2
:def-fn 1
:deprecated-namespace 95
:deprecated-var 86
:discouraged-java-method 4
:discouraged-namespace 71
:discouraged-var 130
:duplicate-require 1
:equals-true 1
:main-without-gen-class 1
:metabase/defsetting-namespace 1
:metabase/disallow-hardcoded-driver-names-in-tests 34
:metabase/discourage-millis-duration 1
:metabase/i-like-making-cams-eyes-bleed-with-horrifically-long-tests 13
:metabase/modules 23
:metabase/namespace-name 4
:metabase/prefer-with-dynamic-fn-redefs 28
:metabase/test-helpers-use-non-thread-safe-functions 18
:metabase/validate-defendpoint-has-response-schema 427
:metabase/validate-defendpoint-query-params-use-kebab-case 48
:metabase/validate-defendpoint-route-uses-kebab-case 44
:metabase/validate-deftest 10
:missing-docstring 12
:missing-protocol-method 3
:non-arg-vec-return-type-hint 1
:reduce-without-init 3
:redundant-do 1
:syntax 2
:type-mismatch 8
:uninitialized-var 1
:unquote-not-syntax-quoted 1
:unresolved-namespace 3
:unresolved-symbol 11
:unsorted-required-namespaces :unlimited
:unused-alias 2
:unused-binding 9
:unused-excluded-var 2
:unused-namespace 2
:unused-private-var 8
:unused-value 1}
:config-counts {:constant-condition 1
:deprecated-namespace 7
:deprecated-var 16
:discouraged-namespace 14
:discouraged-var 14
:inline-def 1
:main-without-gen-class 1
:metabase/defsetting-must-specify-export 1
:metabase/defsetting-namespace 1
:metabase/prefer-with-dynamic-fn-redefs 3
:metabase/t2-query-namespace 2
:missing-docstring 1
:private-call 1
:redundant-ignore 1
:redundant-primitive-coercion 1
:refer-all 1
:type-mismatch 1
:unexpected-recur 1
:unresolved-symbol 19
:unresolved-var 1
:unused-referred-var 4}
:comment-exempt #{:deprecated-namespace
:discouraged-namespace
:discouraged-var
:metabase/modules
:metabase/validate-defendpoint-has-response-schema
:metabase/validate-defendpoint-query-params-use-kebab-case
:metabase/validate-defendpoint-route-uses-kebab-case}}

View File

@@ -71,10 +71,28 @@
(some-> (ns-form-node->ns-symb-node ns-form-node)
hooks/sexpr))
(defn- lint-test-parallel-metadata [ns-form-node]
(when-let [ns-symb-node (ns-form-node->ns-symb-node ns-form-node)]
(let [ns-metadata (meta (hooks/sexpr ns-symb-node))]
(cond
(:synchronous ns-metadata)
(hooks/reg-finding!
(assoc (meta ns-symb-node)
:message (str "Use `^:synchronized` to mark this namespace explicitly non-parallel; "
"`^:synchronous` is ignored by Hawk. [:metabase/validate-deftest]")
:type :metabase/validate-deftest))
(and (contains? ns-metadata :parallel)
(false? (:parallel ns-metadata)))
(hooks/reg-finding!
(assoc (meta ns-symb-node)
:message "Use `^:synchronized` instead of `^{:parallel false}`. [:metabase/validate-deftest]"
:type :metabase/validate-deftest))))))
(defn- lint-modules [ns-form-node config]
(let [ns-symb (ns-form-node->ns-symb ns-form-node)]
(when-not (modules/ignored-namespace? config ns-symb)
(when-let [current-module (modules/module ns-symb)]
(when-let [current-module (modules/module config ns-symb)]
(let [required-namespace-symb-nodes (-> ns-form-node
ns-form-node->require-node
require-node->namespace-symb-nodes)]
@@ -140,6 +158,7 @@
lint-requires-on-new-lines
(lint-modules (modules/config x))
lint-namespace-name
lint-test-parallel-metadata
lint-jsqlparser-imports)
x)

View File

@@ -11,15 +11,32 @@
(every? simple-symbol? required-namespaces)]}
(when-not (modules/ignored-namespace? config current-ns)
;; ignore namespaces outside of the module system
(when-let [current-module (modules/module current-ns)]
(when-let [current-module (modules/module config current-ns)]
(doseq [required-namespace required-namespaces]
;; ignore namespaces outside of the module system.
(when (modules/module required-namespace)
(when (modules/module config required-namespace)
(when-let [error (modules/usage-error config current-module required-namespace)]
(hooks/reg-finding! (assoc (meta node)
:message error
:type :metabase/modules))))))))
(defn- lint-dynamic-require* [node current-ns config]
(when (and (not (modules/ignored-namespace? config current-ns))
(modules/module config current-ns))
(hooks/reg-finding! (assoc (meta node)
:message "Module dependency cannot be statically determined from a dynamic require"
:type :metabase/modules))))
(defn- quoted-require? [node]
(or (= (hooks/tag node) :quote)
(and (= (hooks/tag node) :list)
(let [[x] (:children node)]
(and (hooks/token-node? x)
(= (hooks/sexpr x) 'quote))))))
(defn- keyword-node? [node]
(keyword? (hooks/sexpr node)))
(defn- unwrap-require [node]
(case (hooks/tag node)
;; some.namespace of some.namespace/some-var
@@ -42,7 +59,11 @@
;; something like [some.namespace :as whatever]
:vector
(recur (first (:children node)))))
(recur (first (:children node)))
;; anything else -- e.g. a runtime expression like `(requiring-resolve (:failing-test-var opts))` --
;; has no statically-known namespace
nil))
(comment
(unwrap-require (-> "(requiring-resolve 'metabase.notification.payload.execute/execute-dashboard)"
@@ -51,20 +72,24 @@
second)))
(defn- lint-require* [node current-ns config]
(let [[_require & args] (:children node)
required-namespaces (->> (keep unwrap-require args)
;; `require` runs through `cc/load-libs` which allows
;; #{:as :reload :reload-all :require :use :verbose :refer :as-alias}
;; as args. If you use a REPL tool that applies clj-kondo linting (e.g., Clojure MCP)
;; you may wish to `:reload` or `:reload-all` a namespace. So we shouldn't assume all
;; args are keywords:
(remove keyword?))]
(lint* node current-ns config required-namespaces)))
(let [[_require & args] (:children node)
;; Keywords such as `:reload` and `:reload-all` are options, not namespace dependencies.
namespace-nodes (remove keyword-node? args)
static-nodes (filter quoted-require? namespace-nodes)
required-namespaces (->> (keep unwrap-require static-nodes)
(filter simple-symbol?))]
(lint* node current-ns config required-namespaces)
(when (or (not= (count static-nodes) (count namespace-nodes))
(not= (count required-namespaces) (count static-nodes)))
(lint-dynamic-require* node current-ns config))))
(defn- lint-requiring-resolve* [node current-ns config]
(let [[_requiring-resolve symb-node] (:children node)
required-namespace (unwrap-require symb-node)]
(lint* node current-ns config [required-namespace])))
(if (and (quoted-require? symb-node)
(simple-symbol? required-namespace))
(lint* node current-ns config [required-namespace])
(lint-dynamic-require* node current-ns config))))
(defn lint-require [x]
(lint-require* (:node x) (:ns x) (modules/config x))

View File

@@ -28,11 +28,11 @@
(walk form)))
(defn- deftest-check-parallel
"1. Check if test is marked ^:parallel / ^:synchronized correctly.
"1. Check if test is marked `^:parallel` / `^:synchronized` correctly.
2. Make sure disallowed forms are not used in ^:parallel tests.
3. Disallow ^:parallel tests in namespaces marked ^:synchronous -- the
ns marker is the author's blanket promise that nothing inside runs
in parallel, so an individual ^:parallel deftest contradicts it."
3. Disallow `^:parallel` tests in namespaces marked `^:synchronized` --
the ns marker is the author's blanket promise that nothing inside runs
in parallel, so an individual `^:parallel` deftest contradicts it."
[{[_ test-name & body] :children, :as _node} ns-sym config]
(let [test-metadata (:meta test-name)
metadata-sexprs (map hooks/sexpr test-metadata)
@@ -44,28 +44,48 @@
(completing merge)
{}
metadata-sexprs)
parallel? (:parallel combined-metadata)
synchronized? (:synchronized combined-metadata)
ns-synchronous? (boolean (:synchronous (meta ns-sym)))]
parallel? (true? (:parallel combined-metadata))
synchronized? (true? (:synchronized combined-metadata))
explicitly-nonparallel? (or synchronized?
(and (contains? combined-metadata :parallel)
(false? (:parallel combined-metadata))))
ns-metadata (meta ns-sym)
ns-explicitly-nonparallel? (or (true? (:synchronized ns-metadata))
(and (contains? ns-metadata :parallel)
(false? (:parallel ns-metadata))))]
(when (and (contains? combined-metadata :parallel)
(false? (:parallel combined-metadata)))
(hooks/reg-finding! (assoc (meta test-name)
:message (str "Use `^:synchronized` instead of `^{:parallel false}`. "
"[:metabase/validate-deftest]")
:type :metabase/validate-deftest)))
(when (:sequential combined-metadata)
(hooks/reg-finding! (assoc (meta test-name)
:message (str "Use `^:synchronized` to mark this test explicitly non-parallel; "
"`^:sequential` is ignored by Hawk. "
"[:metabase/validate-deftest]")
:type :metabase/validate-deftest)))
(when (and parallel? synchronized?)
(hooks/reg-finding! (assoc (meta test-name)
:message "Test should not be marked both ^:parallel and ^:synchronized"
:message "Test should not be marked both `^:parallel` and `^:synchronized`"
:type :metabase/validate-deftest)))
(when (and parallel? ns-synchronous?)
(when (and parallel? ns-explicitly-nonparallel?)
(hooks/reg-finding!
(assoc (meta test-name)
:message (str "Test should not be marked ^:parallel in a namespace marked ^:synchronous -- "
:message (str "Test should not be marked `^:parallel` in a namespace marked "
"`^:synchronized` -- "
"the ns marker promises no parallel execution. "
"Drop ^:parallel from the deftest, or drop ^:synchronous from the ns. "
"Drop `^:parallel` from the deftest, or drop `^:synchronized` from the ns. "
"[:metabase/validate-deftest]")
:type :metabase/validate-deftest)))
;; only when the custom `:metabase/deftest-not-marked-parallel-or-synchronized` is enabled: complain if tests are
;; not explicitly marked `^:parallel` or `^:synchronized`. This is mostly to encourage people to mark everything
;; `^:parallel` in places like `metabase.lib` tests unless there is a really good reason not to.
(when-not (or parallel? synchronized?)
;; Only when the custom `:metabase/deftest-not-marked-parallel-or-synchronized` is enabled:
;; complain if tests are not explicitly marked `^:parallel` or `^:synchronized`. This is
;; mostly to encourage people to mark everything `^:parallel` in places like `metabase.lib`
;; tests unless there is a really good reason not to.
(when-not (or parallel? explicitly-nonparallel?)
(hooks/reg-finding!
(assoc (meta test-name)
:message "Test should be marked either ^:parallel or ^:synchronized"
:message "Test should be marked either `^:parallel` or `^:synchronized`"
:type :metabase/deftest-not-marked-parallel-or-synchronized)))
(when parallel?
(doseq [form body]
@@ -151,8 +171,10 @@
(str/starts-with? (name ns-symb) prefix))
["build-drivers."
"build."
"hooks." ; clj-kondo hook tests, outside the module system
"i18n." ; bin/i18n
"lint-migrations-file-test"
"load-namespaces." ; bin/load-namespaces
"mage."
"main-test" ; bin/release-list
"metabase.deps-edn-test"
@@ -172,7 +194,7 @@
(not (contains? @warned-namespaces ns-symb)))
(swap! warned-namespaces conj ns-symb)
(let [known-modules (set (keys (:metabase/modules (modules/config input))))
current-module (modules/module ns-symb)]
current-module (modules/module (modules/config input) ns-symb)]
(when (or (not current-module)
(not (contains? known-modules current-module)))
(hooks/reg-finding! (assoc (meta node)
@@ -232,18 +254,20 @@
(defn use-fixtures
"Flag `:parallel/unsafe` forms inside fixtures. Skipped when the surrounding
namespace is marked `^:synchronous` -- the ns marker is the author's
namespace is marked `^:synchronized` -- the ns marker is the author's
explicit opt-in to a single-threaded test ns where destructive setup is
safe. Without that opt-in, kondo can't know whether sibling deftests will
be `^:parallel`, so the conservative default is to flag.
Sister to [[deftest-check-parallel]]: the deftest hook rejects `^:parallel`
tests inside a `^:synchronous` ns, so the two checks together form a
coherent opt-in: either the whole ns is synchronous (fixtures can be
tests inside a `^:synchronized` ns, so the two checks together form a
coherent opt-in: either the whole ns is explicitly non-parallel (fixtures can be
anything; no parallel tests allowed) or it isn't (fixtures must be
parallel-safe)."
[{:keys [node config], ns-sym :ns, :as input}]
(when-not (:synchronous (meta ns-sym))
(when-not (or (true? (:synchronized (meta ns-sym)))
(and (contains? (meta ns-sym) :parallel)
(false? (:parallel (meta ns-sym)))))
(let [linter-config (get-in config [:linters :metabase/validate-deftest])]
(doseq [form (rest (:children node))]
(warn-about-disallowed-parallel-forms form linter-config))))

View File

@@ -1,4 +1,8 @@
(ns hooks.common.modules
"Resolves namespaces to modules and enforces module boundaries.
The Kondo linter, config generator, and CI tooling share this namespace so
they apply the same rules."
(:require
[clojure.string :as str]))
@@ -12,25 +16,130 @@
(merge (get-in config [:linters :metabase/modules])
(select-keys config [:metabase/modules])))
(defn module
;;;; Module tree. These functions take the `:metabase/modules` map, or the prefix map built from it.
;;;;
;;;; Dots express nesting: `lib.schema` is a child of `lib`. A declared
;;;; `enterprise/X` module is also a child of OSS module `X`. A namespace
;;;; belongs to the module with the most specific matching `:ns-prefix`.
(defn default-ns-prefix
"Namespace prefix a module owns unless it sets `:ns-prefix`: `metabase.lib.schema` for `lib.schema`,
`metabase-enterprise.foo` for `enterprise/foo`."
[module]
(str (if (= "enterprise" (namespace module)) "metabase-enterprise." "metabase.") (name module)))
(defn module-ns-prefix
"Namespace prefix `module` owns: its `:ns-prefix`, else [[default-ns-prefix]]."
[modules module]
(or (get-in modules [module :ns-prefix])
(default-ns-prefix module)))
(defn build-prefix->module
"Map each declared namespace prefix to its module, for [[declared-module]]."
[modules]
(into {}
(map (fn [module] [(module-ns-prefix modules module) module]))
(keys modules)))
(defn declared-module
"Resolve `ns-symb` to its declared module, or `nil`.
Chooses the most specific dotted prefix and ignores a trailing `-test`."
[prefix->module ns-symb]
(loop [candidate (str/replace (str ns-symb) #"-test$" "")]
(or (get prefix->module candidate)
(when-let [dot (str/last-index-of candidate ".")]
(recur (subs candidate 0 dot))))))
(defn resolve-module
"E.g.
(module 'metabase.qp.middleware.wow) => 'qp
(module 'metabase-enterprise.whatever.core) => enterprise/whatever"
[ns-symb]
(resolve-module prefix->module 'metabase.qp.middleware.wow) => 'qp
(resolve-module prefix->module 'metabase-enterprise.whatever.core) => enterprise/whatever
An unmatched Metabase namespace resolves to its first segment so the linter can report an undeclared module."
[prefix->module ns-symb]
{:pre [(simple-symbol? ns-symb)]}
;; treat something like `metabase.driver-test` (for a module that hasn't fully been updated to use `.core`
;; namespaces) as being in the `driver` module
(let [ns-symb (if (str/ends-with? (name ns-symb) "-test")
(symbol (str/replace (name ns-symb) #"-test$" ""))
ns-symb)]
(or (some->> (re-find #"^metabase-enterprise\.([^.]+)" (str ns-symb))
(or (declared-module prefix->module ns-symb)
(some->> (re-find #"^metabase-enterprise\.([^.]+)" (str ns-symb))
second
(symbol "enterprise"))
(some-> (re-find #"^metabase\.([^.]+)" (str ns-symb))
second
symbol))))
(defn parent-module
"The direct parent of `module`, or `nil` when it is top-level."
[modules module]
(let [module-name (name module)]
(if-let [dot (str/last-index-of module-name ".")]
(symbol (namespace module) (subs module-name 0 dot))
(when (= "enterprise" (namespace module))
(let [oss (symbol module-name)]
(when (contains? modules oss)
oss))))))
(defn descendant-of?
"Whether `module` is `ancestor` or one of its descendants."
[modules module ancestor]
(boolean (some #{ancestor} (take-while some? (iterate #(parent-module modules %) module)))))
(defn- exports-child?
[modules parent child]
(or (contains? (set (get-in modules [parent :module-exports])) child)
;; OSS module `X` implicitly exports its `enterprise/X` companion.
(and (not= (namespace parent) (namespace child))
(contains? modules child))))
(defn- blocking-export
"The first missing export from `module` toward the root.
Returns `{:ancestor parent, :child child}`, or `nil` when every link is
exported."
[modules module]
(loop [child module]
(when-let [ancestor (parent-module modules child)]
(if (exports-child? modules ancestor child)
(recur ancestor)
{:ancestor ancestor, :child child}))))
(defn namability-error
"Explain why `caller` may not refer to `target` in `:uses`, or return `nil` if it may.
A nested module is private to the nearest ancestor with a missing export.
Exporting every link makes it public."
[modules caller target]
(when-let [{:keys [ancestor child]} (blocking-export modules target)]
(when-not (descendant-of? modules caller ancestor)
(format (str "Module %s is nested and not exported by its ancestors; %s may not use it. Add %s to %s's "
":module-exports, or move the caller into the %s subtree. [:metabase/modules %s :module-exports]")
target caller child ancestor ancestor ancestor))))
;;;; Lint rules. These functions take the full linter config.
(defonce ^:private prefix->module-cache
(atom nil))
(defn- prefix->module
"[[build-prefix->module]] for `config`, cached because Kondo hands every hook call the same `:metabase/modules` map."
[config]
(let [modules (:metabase/modules config)
cached @prefix->module-cache]
(if (identical? modules (:modules cached))
(:prefix->module cached)
(:prefix->module (reset! prefix->module-cache {:modules modules
:prefix->module (build-prefix->module modules)})))))
(defn module
"Resolve `ns-symb` to its module under `config`; see [[resolve-module]]."
[config ns-symb]
(resolve-module (prefix->module config) ns-symb))
(defn- module-api-namespaces
"Set of API namespace symbols for a given module. `:any` means you can use anything, there are no API namespaces for
this module (yet). If unspecified, the default is just the `<module>.core` namespace."
@@ -44,9 +153,7 @@
module-config
:else
(let [ns-prefix (if (= (namespace module) "enterprise")
(str "metabase-enterprise." (name module))
(name module))]
(let [ns-prefix (module-ns-prefix (:metabase/modules config) module)]
#{(symbol (str ns-prefix ".api"))
(symbol (str ns-prefix ".core"))
(symbol (str ns-prefix ".init"))}))))
@@ -68,15 +175,17 @@
(contains? (set allowed-modules) required-module))))
(defn- allowed-module-namespace? [config current-module ns-symb]
(let [module (module ns-symb)
(let [module (module config ns-symb)
module-api-namespaces (module-api-namespaces config module)
module-friends (module-friends config module)]
(or (empty? module-api-namespaces)
(or (nil? module-api-namespaces)
(contains? module-api-namespaces ns-symb)
(contains? module-friends current-module))))
(contains? module-friends current-module)
;; a child may use its ancestors' internals; a parent still goes through its child's `:api`
(descendant-of? (:metabase/modules config) current-module module))))
(defn- rest-module? [module]
(str/ends-with? module "-rest"))
(re-find #"[.-]rest$" (str module)))
(defn- routes-module? [module]
(str/ends-with? module "-routes"))
@@ -89,7 +198,7 @@
error type if there is one, otherwise `nil` if there are no errors."
[config current-module required-namespace]
;; ignore stuff not in a module i.e. non-Metabase stuff.
(when-let [required-module (module required-namespace)]
(when-let [required-module (module config required-namespace)]
(when-not (= current-module required-module)
(cond
(not (allowed-module? config current-module required-module))
@@ -113,4 +222,8 @@
required-module
current-module
required-module
(symbol (str/replace required-module #"-rest$" "")))))))
(symbol (str/replace required-module #"[.-]rest$" "")))
;; Config tests check explicit `:uses`; wildcard callers are checked here.
(= :any (allowed-modules config current-module))
(namability-error (:metabase/modules config) current-module required-module)))))

View File

@@ -4,9 +4,9 @@
[hooks.common :as common]))
(defn lint-defsetting-namespace [node context]
(when-not (re-matches #"^metabase(?:-enterprise)?\.[^\.]+\.settings$" (name (:ns context)))
(when-not (re-matches #"^metabase(?:-enterprise)?\.([^\.]+\.)+settings$" (name (:ns context)))
(hooks/reg-finding! (assoc (meta node)
:message "All defsettings should live in metabase[-enterprise].<module>.settings namespaces"
:message "All defsettings should live in a namespace ending in .settings under metabase[-enterprise]"
:type :metabase/defsetting-namespace))))
;;; TODO -- move this into a Kondo config file in `.clj-kondo/config/`
@@ -286,6 +286,7 @@
(update context :node update-node)))
(comment
(require '[clojure.pprint])
(defn- defsetting* [form]
(hooks/sexpr
(:node
@@ -293,7 +294,6 @@
{:node
(hooks/parse-string
(with-out-str
#_{:clj-kondo/ignore [:unresolved-namespace]}
(clojure.pprint/pprint
form)))}))))

View File

@@ -0,0 +1,45 @@
(ns hooks.metabase.toucan.db-ns
"Lint that application database query calls -- Toucan 2's `t2/select`, `t2/query`, `t2/insert!`, `t2/update!`,
`t2/delete!` and friends, plus the `metabase.app-db.core` wrappers around them such as `mdb/query` and
`mdb/update-or-insert!` -- live in a module's `db` namespace, i.e. `metabase[-enterprise].<module>.db` (or `metabase.driver.<driver>.db` for
driver modules). Every other namespace in a module goes through those functions instead of talking to the
application database directly.
Registered as an `:analyze-call` hook on each of those functions in `.clj-kondo/config.edn`. The hook
returns its input unchanged so Kondo's normal analysis of the call (arity, var usage) still runs."
(:require
[clj-kondo.hooks-api :as hooks]
[hooks.common.modules :as modules]))
(def ^:private driver-db-namespace
"Matches `metabase.driver.<driver>.db`; individual drivers are not modules."
#"^metabase\.driver\.[^.]+\.db$")
(defn- db-namespace? [config ns-sym]
(let [ns-str (name ns-sym)]
(boolean
;; Resolve ownership first: a nested `.db` name alone does not make a module.
(or (when-let [module (modules/module config ns-sym)]
(= ns-str (str (modules/module-ns-prefix (:metabase/modules config) module) ".db")))
(re-matches driver-db-namespace ns-str)))))
(defn- test-file?
"Whether `filename` is in a test source tree. Test namespaces are exempt through the `test-namespaces` group in
`config.edn`, but helper namespaces like `metabase.sso.test-helpers` don't match that group's pattern."
[filename]
(boolean (and filename (re-find #"(?:^|/)test/" filename))))
(defn lint-query-call
"Register a `:metabase/t2-query-namespace` finding when a Toucan 2 query call appears outside a `<module>.db`
namespace."
[{:keys [node ns filename] :as input}]
(when (and ns
(not (db-namespace? (modules/config input) ns))
(not (test-file? filename)))
(let [fn-node (first (:children node))]
(hooks/reg-finding!
(assoc (meta fn-node)
:message (format "Application database query calls like `%s` must live in metabase[-enterprise].<module>.db (or metabase.driver.<driver>.db) namespaces"
(hooks/sexpr fn-node))
:type :metabase/t2-query-namespace))))
input)

View File

@@ -19,6 +19,19 @@
(defn- lint-modules [form config]
(lint-ns form (assoc-in config [:linters :metabase/modules :level] :warning)))
(deftest ^:parallel explicit-nonparallel-namespace-metadata-test
(let [config {:linters {:metabase/validate-deftest {:level :warning}}}]
(testing "Hawk's supported namespace marker passes"
(is (empty? (lint-ns '(ns ^:synchronized example.test) config))))
(testing "the verbose Hawk spelling is not accepted as Metabase style"
(is (=? [{:type :metabase/validate-deftest
:message #(re-find #"Use `\^:synchronized` instead" %)}]
(lint-ns '(ns ^{:parallel false} example.test) config))))
(testing "the legacy marker explains that Hawk ignores it"
(is (=? [{:type :metabase/validate-deftest
:message #(re-find #"`\^:synchronous` is ignored by Hawk" %)}]
(lint-ns '(ns ^:synchronous example.test) config))))))
(deftest ^:parallel module-checker-allowed-modules-test
(are [task-namespace] (=? [{:message "Module task should not be used in the api module. [:metabase/modules api :uses]"
:type :metabase/modules}]
@@ -43,6 +56,16 @@
'{:metabase/modules {api {:uses #{search}}
search {:api #{metabase.search.core}}}}))))
(deftest ^:parallel module-checker-empty-api-test
(is (=? [{:message "Namespace metabase.embeddings.core is not an allowed external API namespace for the embeddings module. [:metabase/modules embeddings :api]"
:type :metabase/modules}]
(lint-modules
'(ns metabase.metabot.core
(:require
[metabase.embeddings.core :as embeddings]))
'{:metabase/modules {metabot {:uses #{embeddings}}
embeddings {:api #{}}}}))))
(deftest ^:parallel module-checker-friends-test
(is (= []
(lint-modules

View File

@@ -0,0 +1,65 @@
(ns hooks.clojure.core.require-test
(:require
[clj-kondo.hooks-api :as hooks]
[clj-kondo.impl.utils]
[clojure.test :refer :all]
[hooks.clojure.core.require]))
(def ^:private config
'{:linters {:metabase/modules {:level :warning}}
:metabase/modules {search {:uses #{}}
task {:api #{metabase.task.core}}}})
(defn- lint [hook form current-ns]
(binding [clj-kondo.impl.utils/*ctx* {:config config
:ignores (atom nil)
:findings (atom [])
:namespaces (atom {})}]
(hook {:node (hooks/parse-string (pr-str form))
:ns current-ns
:config config})
@(:findings clj-kondo.impl.utils/*ctx*)))
(defn- lint-require [form current-ns]
(lint hooks.clojure.core.require/lint-require form current-ns))
(defn- lint-requiring-resolve [form current-ns]
(lint hooks.clojure.core.require/lint-requiring-resolve form current-ns))
(def ^:private dynamic-require-finding
{:message "Module dependency cannot be statically determined from a dynamic require"
:type :metabase/modules})
(def ^:private cross-module-finding
{:message "Module task should not be used in the search module. [:metabase/modules search :uses]"
:type :metabase/modules})
(deftest ^:parallel dynamic-requiring-resolve-test
(testing "outside the module system"
(is (= [] (lint-requiring-resolve '(requiring-resolve (:failing-test-var opts)) 'dev))))
(testing "inside a module"
(are [form] (=? [dynamic-require-finding]
(lint-requiring-resolve form 'metabase.search.core))
'(requiring-resolve (:failing-test-var opts))
'(requiring-resolve @some-atom)
'(requiring-resolve some-local)
'(requiring-resolve "not-a-symbol"))))
(deftest ^:parallel dynamic-require-test
(testing "outside the module system"
(is (= [] (lint-require '(require some-local) 'dev))))
(testing "inside a module"
(is (=? [dynamic-require-finding]
(lint-require '(require some-local) 'metabase.search.core)))))
(deftest ^:parallel static-requiring-resolve-still-linted-test
(is (=? [cross-module-finding]
(lint-requiring-resolve '(requiring-resolve 'metabase.task.impl/go)
'metabase.search.core))
"a statically-known cross-module violation is still reported"))
(deftest ^:parallel static-require-still-linted-test
(is (=? [cross-module-finding]
(lint-require '(require 'metabase.task.impl :reload)
'metabase.search.core))
"a statically-known cross-module violation is still reported while keyword flags are ignored"))

View File

@@ -21,6 +21,54 @@
#{:athena}}}}})
(mapv :message @(:findings clj-kondo.impl.utils/*ctx*))))
(defn- parallel-metadata-findings
([form]
(parallel-metadata-findings form 'example.test))
([form ns-sym]
(let [linters {:metabase/deftest-not-marked-parallel-or-synchronized {:level :warning}
:metabase/validate-deftest {:level :warning}}]
(binding [clj-kondo.impl.utils/*ctx* {:config {:linters linters}
:ignores (atom nil)
:findings (atom [])
:namespaces (atom {})}]
(hooks.clojure.test/deftest {:node (api/parse-string form)
:lang :clj
:ns ns-sym
:config {:linters {:metabase/validate-deftest {}}}})
@(:findings clj-kondo.impl.utils/*ctx*)))))
(deftest ^:parallel explicit-nonparallel-metadata-test
(testing "Hawk's supported test markers satisfy the explicit metadata linter"
(are [metadata] (empty? (parallel-metadata-findings
(format "(deftest %s example-test (is true))" metadata)))
"^:parallel"
"^:synchronized"))
(testing "an unmarked test still gets the opt-in linter's guidance"
(is (=? [{:type :metabase/deftest-not-marked-parallel-or-synchronized
:message "Test should be marked either `^:parallel` or `^:synchronized`"}]
(parallel-metadata-findings "(deftest example-test (is true))"))))
(testing "the unsupported marker explains that Hawk ignores it"
(is (some #(and (= (:type %) :metabase/validate-deftest)
(re-find #"ignored by Hawk" (:message %)))
(parallel-metadata-findings
"(deftest ^:sequential example-test (is true))"))))
(testing "the verbose Hawk spelling is not accepted as Metabase style"
(is (some #(and (= (:type %) :metabase/validate-deftest)
(re-find #"Use `\^:synchronized` instead" (:message %)))
(parallel-metadata-findings
"(deftest ^{:parallel false} example-test (is true))"))))
(testing "a test cannot request both execution modes"
(is (some #(and (= (:type %) :metabase/validate-deftest)
(re-find #"both `\^:parallel` and `\^:synchronized`" (:message %)))
(parallel-metadata-findings
"(deftest ^:parallel ^:synchronized example-test (is true))"))))
(testing "a namespace-level non-parallel promise rejects parallel tests"
(is (=? [{:type :metabase/validate-deftest
:message #(re-find #"namespace marked.*`\^:synchronized`" %)}]
(parallel-metadata-findings
"(deftest ^:parallel example-test (is true))"
(with-meta 'example.test {:synchronized true}))))))
(deftest ^:parallel disallow-hardcoded-driver-names-in-tests-test
(is (= []
(deftest-warnings

View File

@@ -5,6 +5,6 @@
(deftest ^:parallel module-test
(are [symb expected] (= expected
(hooks.common.modules/module symb))
(hooks.common.modules/module {} symb))
'metabase.qp.middleware.wow 'qp
'metabase-enterprise.whatever.core 'enterprise/whatever))

View File

@@ -0,0 +1,73 @@
(ns hooks.metabase.toucan.db-ns-test
(:require
[clj-kondo.hooks-api :as hooks]
[clj-kondo.impl.utils]
[clojure.test :refer :all]
[hooks.metabase.toucan.db-ns :as toucan.db-ns]))
(defn- lint-query-call [form ns-sym & [filename modules]]
(binding [clj-kondo.impl.utils/*ctx* {:config {:linters {:metabase/t2-query-namespace {:level :warning}}}
:ignores (atom nil)
:findings (atom [])
:namespaces (atom {})}]
(let [input {:node (hooks/parse-string (pr-str form))
:ns ns-sym
:filename (or filename "src/metabase/foo/bar.clj")
:config {:metabase/modules modules}}
output (toucan.db-ns/lint-query-call input)]
(is (identical? (:node input) (:node output))
"the hook must return the node unchanged so Kondo's normal analysis still runs")
@(:findings clj-kondo.impl.utils/*ctx*))))
(deftest ^:parallel t2-query-must-live-in-db-namespace-test
(testing "a query call outside a db namespace is flagged"
(is (=? [{:type :metabase/t2-query-namespace
:message #".*`t2/select-one`.*"}]
(lint-query-call '(t2/select-one :model/Card :id 1) 'metabase.queries.models.card))))
(testing "metabase.<module>.db is allowed"
(is (empty? (lint-query-call '(t2/select-one :model/Card :id 1) 'metabase.queries.db))))
(testing "metabase-enterprise.<module>.db is allowed"
(is (empty? (lint-query-call '(t2/select-one :model/Card :id 1) 'metabase-enterprise.sandbox.db))))
(testing "metabase.driver.<driver>.db is allowed for driver modules"
(is (empty? (lint-query-call '(t2/select-one :model/Database :id 1) 'metabase.driver.bigquery-cloud-sdk.db))))
(testing "a nested db namespace is not a module db namespace"
(is (=? [{:type :metabase/t2-query-namespace}]
(lint-query-call '(t2/query {:select [:*]}) 'metabase.queries.models.db))))
(testing "a namespace merely ending in db is not a module db namespace"
(is (=? [{:type :metabase/t2-query-namespace}]
(lint-query-call '(t2/delete! :model/Card :id 1) 'metabase.queries.dashboards-db))))
(testing "files in a test source tree are exempt even when the namespace name doesn't look like a test"
(is (empty? (lint-query-call '(t2/update! :model/User 1 {:sso_source nil}) 'metabase.sso.test-helpers
"test/metabase/sso/test_helpers.clj")))
(is (empty? (lint-query-call '(t2/select :model/Card) 'metabase-enterprise.remote-sync.test-helpers
"/repo/enterprise/backend/test/metabase_enterprise/remote_sync/test_helpers.clj"))))
(testing "app-db wrappers around Toucan 2 are reported the same way"
(is (=? [{:type :metabase/t2-query-namespace
:message #".*`mdb/update-or-insert!`.*"}]
(lint-query-call '(mdb/update-or-insert! :model/Foo {:id 1}) 'metabase.foo.models.foo))))
(testing "fully-qualified calls are reported by their written name"
(is (=? [{:type :metabase/t2-query-namespace
:message #".*`toucan2.core/insert!`.*"}]
(lint-query-call '(toucan2.core/insert! :model/Card {}) 'metabase.queries.models.card)))))
(deftest ^:parallel t2-query-namespace-follows-the-module-tree-test
(let [modules '{queries {}
metabot {}
metabot.llm {}
lib.be {:ns-prefix "metabase.lib-be"}
enterprise/sandbox {}}]
(testing "a nested module owns its own db namespace"
(is (empty? (lint-query-call '(t2/select :model/Card) 'metabase.metabot.llm.db nil modules))))
(testing "the parent's db namespace stays its own"
(is (empty? (lint-query-call '(t2/select :model/Card) 'metabase.metabot.db nil modules))))
(testing "a module with an explicit :ns-prefix is resolved through it, not its dotted name"
(is (empty? (lint-query-call '(t2/select :model/Card) 'metabase.lib-be.db nil modules)))
(is (=? [{:type :metabase/t2-query-namespace}]
(lint-query-call '(t2/select :model/Card) 'metabase.lib.be.db nil modules))))
(testing "a db namespace under a directory naming no module is still a finding"
(is (=? [{:type :metabase/t2-query-namespace}]
(lint-query-call '(t2/query {:select [:*]}) 'metabase.queries.models.db nil modules)))
(is (=? [{:type :metabase/t2-query-namespace}]
(lint-query-call '(t2/query {:select [:*]}) 'metabase.metabot.llm.models.db nil modules))))
(testing "enterprise modules resolve through the metabase-enterprise root"
(is (empty? (lint-query-call '(t2/select :model/Card) 'metabase-enterprise.sandbox.db nil modules))))))

View File

@@ -12,6 +12,7 @@
"enterprise/backend"
"bin/build"
"bin/lint-migrations-file"
"bin/load-namespaces"
"bin/release-list"
#_"mage/src"
#_"mage/test"

View File

@@ -16,7 +16,7 @@ skip =
frontend/src/metabase/querying/expressions/tokenizer/lezer.js,
frontend/src/metabase/query_builder/components/NativeQueryEditor/CodeMirrorEditor/language.ts,
frontend/src/metabase/static-viz/constants/char-sizes.ts,
frontend/src/metabase/visualizations/lib/mapping_codes.ts,
frontend/src/metabase/viz-core/lib/mapping_codes.ts,
frontend/*/mocks/*,
modules/drivers/mongo/src/metabase/driver/mongo/operators.clj,
src/metabase/analyze/classifiers/name.clj,

15
.github/CODEOWNERS vendored
View File

@@ -42,6 +42,9 @@ docs/api.json # auto-generated
docs/configuring-metabase/environment-variables.md # auto-generated
docs/configuring-metabase/config-template.md # auto-generated
docs/installation-and-operation/commands.md # auto-generated
docs/ai/providers.md # auto-generated
docs/embedding/sdk/api # auto-generated
docs/embedding/eajs/snippets # auto-generated
# @metabase/devexp
.github @metabase/devexp
@@ -52,3 +55,15 @@ src/metabase/analytics/prometheus.clj @metabase/cloud-ops
# @metabase/metabot-frontend
enterprise/frontend/src/metabase-enterprise/metabot @metabase/metabot-frontend
frontend/src/metabase/metabot @metabase/metabot-frontend
# @metabase/core-frontend-gadget
bin/custom-viz @metabase/core-frontend-gadget
docs/developers-guide/custom-visualizations.md @metabase/core-frontend-gadget
enterprise/frontend/src/custom-viz @metabase/core-frontend-gadget
enterprise/frontend/src/metabase-enterprise/api/custom-viz-plugin.ts @metabase/core-frontend-gadget
enterprise/frontend/src/metabase-enterprise/custom_viz @metabase/core-frontend-gadget
frontend/src/metabase-types/api/custom-viz-plugin.ts @metabase/core-frontend-gadget
frontend/src/metabase/plugins/oss/custom-viz.ts @metabase/core-frontend-gadget
frontend/src/metabase/visualizations/custom-visualizations @metabase/core-frontend-gadget
frontend/test/__support__/custom-viz-fixtures @metabase/core-frontend-gadget
.github/workflows/release-custom-viz.yml @metabase/devexp @metabase/core-frontend-gadget

View File

@@ -8,6 +8,12 @@ paths:
# GitHub added parallel steps (`parallel`, `background`, `wait`, `wait-all`,
# `cancel`) in June 2026, and actionlint 1.7.12 does not know the schema yet:
# https://github.blog/changelog/2026-06-25-actions-steps-can-now-be-run-in-parallel/
.github/workflows/backend.yml:
ignore:
- 'step must run script with "run" section or run action with "uses" section'
.github/workflows/lint.yml:
ignore:
- 'step must run script with "run" section or run action with "uses" section'
.github/workflows/pr.checks.yml:
ignore:
- 'step must run script with "run" section or run action with "uses" section'

View File

@@ -3,17 +3,15 @@ description: |
Measures app + embedding SDK bundle sizes from the current and base-ref
uberjars (reusing the builds that already ran) plus their bundle-stats
artifacts, and flags gzipped size changes beyond the threshold for the main
app's initial bundle and the chunked SDK's reachable total. Skips when the
base-ref artifacts aren't available rather than rebuilding from source (which
would compare across pipelines).
app's initial bundle and the chunked SDK's reachable total. The base ref is
read back off the current uberjar so that both sides differ only by the PR.
Skips when the base-ref artifacts aren't available rather than rebuilding from
source (which would compare across pipelines).
inputs:
edition:
description: 'Metabase edition (ee or oss)'
required: true
base-ref-commit:
description: 'Commit SHA of the base ref.'
required: true
threshold-percent:
description: 'Percent threshold for bundle size change'
required: true
@@ -41,12 +39,35 @@ runs:
commit: ${{ github.event.pull_request.head.sha || github.sha }}
edition: ${{ inputs.edition }}
extract-path: temp/current-uberjar
- name: Resolve the base ref the current uberjar was built against
id: base-ref
shell: bash
env:
GH_TOKEN: ${{ github.token }}
run: |
set -uo pipefail
# The uberjar job checks out refs/pull/<n>/merge (the PR head already
# merged into the base branch tip) but names its artifact after head.sha,
# so the comparable base ref is that merge's first parent. Reading it back
# off the jar describes the artifact actually being measured. Using
# pull_request.base.sha instead compares against a stale snapshot of the
# base branch, reporting everything that landed in between as this PR's
# own bundle delta.
unzip -o -j temp/current-uberjar/metabase.jar version.properties -d temp/current-version >/dev/null
built=$(sed -n 's/^hash=//p' temp/current-version/version.properties)
base=$(gh api "/repos/${GITHUB_REPOSITORY}/commits/${built}" \
--jq 'if (.parents | length) == 2 then .parents[0].sha else empty end' 2>/dev/null) || base=""
echo "sha=${base}" >> "$GITHUB_OUTPUT"
echo "The current uberjar was built from ${built}; its base ref is ${base:-unknown}"
- name: Download base-ref uberjar
id: base-jar
if: steps.base-ref.outputs.sha != ''
continue-on-error: true
uses: ./.github/actions/fetch-artifact
with:
commit: ${{ inputs.base-ref-commit }}
commit: ${{ steps.base-ref.outputs.sha }}
edition: ${{ inputs.edition }}
extract-path: temp/base-uberjar
- name: Measure and compare bundle sizes
@@ -56,7 +77,7 @@ runs:
GH_TOKEN: ${{ github.token }}
EDITION: ${{ inputs.edition }}
HEAD_SHA: ${{ github.event.pull_request.head.sha || github.sha }}
BASE_SHA: ${{ inputs.base-ref-commit }}
BASE_SHA: ${{ steps.base-ref.outputs.sha }}
THRESHOLD: ${{ inputs.threshold-percent }}
MEASURE_BUNDLES: app,embedding-sdk-legacy,embedding-sdk-chunked
# The gated bundles, as "<bundle>/<kind>". Each one's step outputs are
@@ -79,6 +100,7 @@ runs:
# The base ref needs an already-built uberjar. Rebuilding it from source
# would compare across two build pipelines (the bug this check used to
# have), so skip instead when it — or its stats — isn't available.
[ -n "${BASE_SHA}" ] || skip "no comparable base ref for the current uberjar"
[ -f temp/base-uberjar/metabase.jar ] || skip "base-ref uberjar not found for ${BASE_SHA}"
extract_js() { # $1=jar $2=dest-root

View File

@@ -0,0 +1,61 @@
name: Collect profile
description: >-
Attach a flamegraph and per-test wall times to a job whose tests ran under clj-async-profiler.
Does nothing when the run was not profiled.
inputs:
profiled:
required: true
description: >-
"true" when the test step ran under the profiler. Passed in rather than read from the
environment so the decision stays recorded by the step that made it.
artifact-name:
required: true
description: Name for the uploaded artifact. Must be unique across the jobs of one run.
runs:
using: "composite"
steps:
# Unlike a JUnit failure report, these run on a green build too — a suite that passes slowly is
# exactly what profiling is for.
#
# `awk 'NR<=25'` rather than `head -25`: the runner ignores SIGPIPE, so `head` exiting early
# leaves `sort` with an EPIPE write error and `pipefail` fails the step. `|| true` covers `grep`
# finding no junit files.
- name: Summarize test wall times
if: ${{ inputs.profiled == 'true' }}
continue-on-error: true
shell: bash
run: |
{
echo "### Slowest test namespaces (seconds)"
echo '```'
grep -h '<testsuite' target/junit/*.xml 2>/dev/null \
| sed -E 's|.*<testsuite name="([^"]*)" time="([^"]*)".*|\2 \1|' \
| sort -rn | awk 'NR<=25' || true
echo '```'
echo "### Slowest tests (seconds)"
echo '```'
grep -h '<testcase' target/junit/*.xml 2>/dev/null \
| sed -E 's|.*classname="([^"]*)" name="([^"]*)" time="([^"]*)".*|\3 \1/\2|' \
| sort -rn | awk 'NR<=25' || true
echo '```'
} >> "$GITHUB_STEP_SUMMARY"
# Only the rendered flamegraph is kept: the raw collapsed stacks it was built from run to
# hundreds of MB on a long suite, and are reproducible locally from the same test selection.
#
# The info-level test log rides along on a green profiled run too. The failure-only log artifact
# the test jobs upload is not written when nothing failed, which is exactly the run being profiled.
- name: Upload profile
if: ${{ inputs.profiled == 'true' }}
continue-on-error: true
uses: actions/upload-artifact@v7
with:
name: ${{ inputs.artifact-name }}
path: |
target/clj-async-profiler/results/*flamegraph.html
target/junit/*.xml
logs/test-log.json
retention-days: 14
if-no-files-found: warn

View File

@@ -25,6 +25,8 @@ runs:
COMMIT: ${{ inputs.backport-commit }}
shell: bash
run: | # bash
source "${{ github.action_path }}/kondo-ratchets.sh"
git config --global user.email "metabase-bot@metabase.com"
git config --global user.name "Metabase bot"
@@ -34,7 +36,7 @@ runs:
git checkout ${TARGET_BRANCH}
git fetch --all
git checkout -b ${BACKPORT_BRANCH}
git cherry-pick ${COMMIT} || true
cherry_pick_backport "${COMMIT}"
CONFLICT_LIST=$(git ls-files -u)
@@ -46,10 +48,7 @@ runs:
echo "has-conflicts=true" >> "$GITHUB_OUTPUT"
# Add a shell script for resolving conflicts
echo "git reset HEAD~1" > ./backport.sh
echo "rm ./backport.sh" >> ./backport.sh
echo "git cherry-pick ${COMMIT}" >> ./backport.sh
echo "echo 'Resolve conflicts and force push this branch.\n\nTo backport translations run: bin/i18n/merge-translations <release-branch>'" >> ./backport.sh
write_backport_script "${COMMIT}"
chmod +x ./backport.sh
git add ./backport.sh
git commit -m "Add backport resolution script"
@@ -73,7 +72,7 @@ runs:
git push -u origin ${BACKPORT_BRANCH}
PR_ARGS=(--base "${TARGET_BRANCH}" --head "${BACKPORT_BRANCH}" --label "was-backported" --assignee "${{ github.event.pull_request.user.login }}" --title "🤖 backported \"${ORIGINAL_TITLE}\"" --body "${PR_BODY}")
PR_ARGS=(--base "${TARGET_BRANCH}" --head "${BACKPORT_BRANCH}" --label "was-backported" --assignee "${{ github.event.pull_request.user.login }}" --title "🤖 v${TARGET_VERSION} backported \"${ORIGINAL_TITLE}\"" --body "${PR_BODY}")
if [ "$CONFLICTS" -gt 0 ]; then
PR_ARGS+=(--draft)
fi
@@ -86,19 +85,15 @@ runs:
git checkout ${{ github.sha }}
- name: Auto approve backport PR
- name: Approve and Merge the PR
if: ${{ steps.create_backport_pull_request.outputs.has-conflicts == 'false' }}
uses: juliangruber/approve-pull-request-action@68fcc9a5a73b5641cadf757cf99d73720dcb05d0 # v2.1.0
with:
github-token: ${{ inputs.github-token-2 }}
number: ${{ steps.create_backport_pull_request.outputs.backport_pr_number }}
- name: Enable Pull Request Automerge
if: ${{ steps.create_backport_pull_request.outputs.has-conflicts == 'false' }}
run: gh pr merge --squash --auto "$PR_NUMBER"
run: |
gh pr review --approve "$PR_NUMBER"
gh pr merge --squash --auto "$PR_NUMBER"
shell: bash
env:
GH_TOKEN: ${{ inputs.github-token }}
# uses a different token than the token that created the PR so we can approve and merge it
GH_TOKEN: ${{ inputs.github-token-2 }}
PR_NUMBER: ${{ steps.create_backport_pull_request.outputs.backport_pr_number }}
- uses: ./.github/actions/notify-pull-request

View File

@@ -0,0 +1,375 @@
#!/usr/bin/env bash
set -euo pipefail
action_dir=$(cd "$(dirname "$0")" && pwd)
cut_release_workflow="$action_dir/../../workflows/cut-release-branch.yml"
# shellcheck source=.github/actions/create-backport/kondo-ratchets.sh
source "$action_dir/kondo-ratchets.sh"
# Any editor launch fails the run, so a continuation that waits on an editor cannot pass.
export GIT_EDITOR=false
test_root=
trap '[ -z "$test_root" ] || rm -rf -- "$test_root"' EXIT
trap 'exit 129' HUP
trap 'exit 130' INT
trap 'exit 143' TERM
test_root=$(mktemp -d)
active_ratchets='{:ignore-counts {:example 1}}'
disabled_ratchets=';; Kondo ignore ratchets apply only to master; this release branch opts out.
;; The test and fixer recognize this explicit opt-out.
{:disabled true}'
# Coverage:
#
# Target state Incoming change Other conflict Expected result
# ----------------- -------------------- --------------- ------------------------------------------
# active ratchets unrelated file none leave ratchets unchanged
# active ratchets ratchets none install the release opt-out
# disabled ratchets ratchets none keep the opt-out; finish with an empty commit
# divergent ratchets ratchets none resolve ratchets and finish the cherry-pick
# divergent ratchets ratchets (on a pty) none finish without opening an editor
# active ratchets unrelated file app.txt leave the conflict for manual resolution
# divergent ratchets ratchets + app.txt app.txt resolve only ratchets
# release cut ratchets none cut and backport commit the same opt-out
# n/a cut-release workflow n/a the workflow calls the shared writer
# any invalid commit n/a propagate the cherry-pick failure
# divergent ratchets generated backport.sh app.txt resolve only ratchets through the manual script
#
# Known gaps: an older target with no ratchets file, and an incoming commit that
# deletes the ratchets file.
test_unrelated_backport_preserves_target_ratchets() (
local repo="$test_root/unrelated"
init_repo "$repo"
local commit
commit=$(feature_commit "$repo" change_app)
git -C "$repo" checkout -q release
cd "$repo"
cherry_pick_backport "$commit"
assert_eq feature "$(cat app.txt)" "the unrelated change was not cherry-picked"
assert_ratchets "$active_ratchets"
assert_cherry_pick_completed
assert_worktree_clean
)
test_clean_ratchet_backport_installs_release_opt_out() (
local repo="$test_root/clean-ratchet"
init_repo "$repo"
local commit
commit=$(feature_commit "$repo" change_ratchets)
git -C "$repo" checkout -q release
cd "$repo"
cherry_pick_backport "$commit"
assert_ratchets_disabled
assert_cherry_pick_completed
assert_worktree_clean
)
test_disabled_release_absorbs_ratchet_only_backport() (
local repo="$test_root/disabled-release"
init_repo "$repo"
local commit
commit=$(feature_commit "$repo" change_ratchets)
git -C "$repo" checkout -q release
commit_release_change "$repo" disable_release_ratchets "Disable release ratchets"
cd "$repo"
cherry_pick_backport "$commit"
assert_ratchets_disabled
assert_cherry_pick_completed
assert_empty_commit
assert_worktree_clean
)
test_ratchet_only_conflict_is_resolved() (
local repo="$test_root/ratchet-conflict"
init_repo "$repo"
local commit
commit=$(conflicting_ratchet_commit "$repo")
cd "$repo"
cherry_pick_backport "$commit"
assert_ratchets_disabled
assert_cherry_pick_completed
assert_worktree_clean
)
test_continuation_never_opens_an_editor() (
local repo="$test_root/editor"
init_repo "$repo"
local commit
commit=$(conflicting_ratchet_commit "$repo")
cd "$repo"
# Git only opens an editor for the continuation when stdin is a terminal, so run it on a pty. The
# exported GIT_EDITOR=false turns any editor launch into a failure. The single quotes are deliberate:
# $1 and $2 are for the inner bash, not this shell.
# shellcheck disable=SC2016
python3 -c 'import os, pty, sys; sys.exit(os.waitstatus_to_exitcode(pty.spawn(sys.argv[1:])))' \
bash -c 'source "$1/kondo-ratchets.sh" && cherry_pick_backport "$2"' bash "$action_dir" "$commit" >/dev/null ||
fail "the cherry-pick continuation opened an editor"
assert_ratchets_disabled
assert_cherry_pick_completed
)
test_non_ratchet_conflict_remains_manual() (
local repo="$test_root/non-ratchet-conflict"
init_repo "$repo"
local commit
commit=$(feature_commit "$repo" change_app)
git -C "$repo" checkout -q release
commit_release_change "$repo" change_release_app "Change release app"
cd "$repo"
cherry_pick_backport "$commit"
assert_ratchets "$active_ratchets"
assert_only_conflicts app.txt
assert_cherry_pick_pending
)
test_mixed_conflict_resolves_only_ratchets() (
local repo="$test_root/mixed-conflict"
init_repo "$repo"
local commit
commit=$(feature_commit "$repo" change_app_and_ratchets)
git -C "$repo" checkout -q release
commit_release_change "$repo" change_release_app_and_ratchets "Change release app and ratchets"
cd "$repo"
cherry_pick_backport "$commit"
assert_ratchets_disabled
assert_only_conflicts app.txt
assert_cherry_pick_pending
)
test_release_cut_and_backport_commit_the_same_opt_out() (
local cut_repo="$test_root/release-cut"
init_repo "$cut_repo"
cd "$cut_repo"
git checkout -qb release-x.99.x
write_disabled_ratchets
git add --sparse .clj-kondo/ratchets.edn
git commit -q --allow-empty --no-verify -m "Cut release-x.99.x branch"
git show HEAD:.clj-kondo/ratchets.edn > "$test_root/release-cut.edn"
local backport_repo="$test_root/release-cut-backport"
init_repo "$backport_repo"
local commit
commit=$(feature_commit "$backport_repo" change_ratchets)
git -C "$backport_repo" checkout -q release
cd "$backport_repo"
cherry_pick_backport "$commit"
git show HEAD:.clj-kondo/ratchets.edn > "$test_root/backport.edn"
cmp -s "$test_root/release-cut.edn" "$test_root/backport.edn" ||
fail "the release cut and the backport committed different opt-out files"
assert_eq "$disabled_ratchets" "$(cat "$test_root/release-cut.edn")" \
"the release cut did not install the expected opt-out"
)
test_cut_release_workflow_uses_the_shared_writer() (
grep -Fq 'source .github/actions/create-backport/kondo-ratchets.sh' "$cut_release_workflow" ||
fail "the cut-release workflow does not source kondo-ratchets.sh"
grep -Fq 'write_disabled_ratchets' "$cut_release_workflow" ||
fail "the cut-release workflow does not call write_disabled_ratchets"
! grep -Fq ':disabled' "$cut_release_workflow" ||
fail "the cut-release workflow carries its own copy of the opt-out"
)
test_invalid_commit_failure_is_propagated() (
local repo="$test_root/invalid"
init_repo "$repo"
cd "$repo"
if cherry_pick_backport deadbeef; then
fail "an invalid commit succeeded"
fi
)
test_generated_script_resolves_ratchets_end_to_end() (
local repo="$test_root/generated-script"
init_repo "$repo"
local commit
commit=$(feature_commit "$repo" change_app_and_ratchets)
git -C "$repo" checkout -q release
commit_release_change "$repo" change_release_app_and_ratchets "Change release app and ratchets"
cd "$repo"
cherry_pick_backport "$commit"
git cherry-pick --abort
local release_commit
release_commit=$(git rev-parse HEAD)
write_backport_script "$commit"
chmod +x backport.sh
git add backport.sh
git commit -qm "Add manual backport script"
bash -n backport.sh
grep -Fq 'write_disabled_ratchets ()' backport.sh || fail "the generated script omitted write_disabled_ratchets"
./backport.sh
assert_ratchets_disabled
assert_only_conflicts app.txt
assert_cherry_pick_pending
assert_eq "$release_commit" "$(git rev-parse HEAD)" "the generated script did not return HEAD to the release commit"
[ ! -e backport.sh ] || fail "the generated script did not remove itself"
! git ls-files --error-unmatch backport.sh >/dev/null 2>&1 || fail "the generated script is still tracked"
! git status --porcelain | grep -q backport.sh || fail "the generated script left a status entry"
)
# Test harness
fail() {
echo "FAIL: $*" >&2
exit 1
}
assert_eq() {
local expected=$1
local actual=$2
local message=$3
[ "$expected" = "$actual" ] || fail "$message (expected '$expected', got '$actual')"
}
assert_ratchets() {
assert_eq "$1" "$(cat .clj-kondo/ratchets.edn)" "unexpected ratchet state"
}
assert_ratchets_disabled() {
assert_ratchets "$disabled_ratchets"
}
assert_cherry_pick_completed() {
! git rev-parse -q --verify CHERRY_PICK_HEAD >/dev/null || fail "the cherry-pick is still pending"
}
assert_cherry_pick_pending() {
git rev-parse -q --verify CHERRY_PICK_HEAD >/dev/null || fail "the cherry-pick state was lost"
}
assert_only_conflicts() {
local expected
local actual
expected=$(printf '%s\n' "$@" | sort)
actual=$(git diff --name-only --diff-filter=U | sort)
assert_eq "$expected" "$actual" "unexpected unresolved files"
}
assert_empty_commit() {
git diff --quiet HEAD^ HEAD || fail "the backport commit was not empty"
}
assert_worktree_clean() {
[ -z "$(git status --porcelain)" ] || fail "the backport left worktree changes"
}
init_repo() {
local repo=$1
git init -q -b release "$repo"
git -C "$repo" config user.email test@example.com
git -C "$repo" config user.name "Backport test"
printf 'base\n' > "$repo/app.txt"
mkdir -p "$repo/.clj-kondo"
printf '%s\n' "$active_ratchets" > "$repo/.clj-kondo/ratchets.edn"
git -C "$repo" add .
git -C "$repo" commit -qm "Base"
}
feature_commit() {
local repo=$1
shift
git -C "$repo" checkout -qb feature
"$@" "$repo"
git -C "$repo" add .
git -C "$repo" commit -qm "Feature"
git -C "$repo" rev-parse HEAD
}
# Sets up a release branch whose ratchets conflict with the feature commit, and prints that commit.
conflicting_ratchet_commit() {
local repo=$1
local commit
commit=$(feature_commit "$repo" change_ratchets)
git -C "$repo" checkout -q release
commit_release_change "$repo" change_release_ratchets "Change release ratchets"
echo "$commit"
}
change_app() {
printf 'feature\n' > "$1/app.txt"
}
change_ratchets() {
printf '{:ignore-counts {:example 2}}\n' > "$1/.clj-kondo/ratchets.edn"
}
change_app_and_ratchets() {
change_app "$1"
change_ratchets "$1"
}
change_release_app() {
printf 'release\n' > "$1/app.txt"
}
change_release_ratchets() {
printf '{:ignore-counts {:release 1}}\n' > "$1/.clj-kondo/ratchets.edn"
}
change_release_app_and_ratchets() {
change_release_app "$1"
change_release_ratchets "$1"
}
# Setup writes the opt-out through the shared writer; the only copy is the expected text at the top.
disable_release_ratchets() {
(cd "$1" && write_disabled_ratchets)
}
commit_release_change() {
local repo=$1
local change=$2
local message=$3
"$change" "$repo"
git -C "$repo" add .
git -C "$repo" commit -qm "$message"
}
run_test() {
local description=$1
local test=${description// /_}
test=${test//-/_}
test="test_$test"
declare -F "$test" >/dev/null || fail "missing test function: $test"
printf 'TEST: %s\n' "$description"
"$test"
printf 'PASS: %s\n' "$description"
}
run_test "unrelated backport preserves target ratchets"
run_test "clean ratchet backport installs release opt-out"
run_test "disabled release absorbs ratchet-only backport"
run_test "ratchet-only conflict is resolved"
run_test "continuation never opens an editor"
run_test "non-ratchet conflict remains manual"
run_test "mixed conflict resolves only ratchets"
run_test "release cut and backport commit the same opt-out"
run_test "cut-release workflow uses the shared writer"
run_test "invalid commit failure is propagated"
run_test "generated script resolves ratchets end-to-end"

View File

@@ -0,0 +1,74 @@
#!/usr/bin/env bash
set -euo pipefail
# The only place that knows what a release branch's opt-out looks like. The cut-release workflow, the
# backport helper, and the tests all go through this function.
write_disabled_ratchets() {
mkdir -p .clj-kondo
printf '%s\n' \
';; Kondo ignore ratchets apply only to master; this release branch opts out.' \
';; The test and fixer recognize this explicit opt-out.' \
'{:disabled true}' \
> .clj-kondo/ratchets.edn
}
disable_ratchets() {
local commit=$1
local file=.clj-kondo/ratchets.edn
[ -n "$(git diff-tree --root --no-commit-id --name-only -r "$commit" -- "$file")" ] || return 0
echo "$file: disabling kondo ratchets on the release branch"
write_disabled_ratchets
git add -- "$file"
if ! git rev-parse -q --verify CHERRY_PICK_HEAD >/dev/null; then
if ! git diff --cached --quiet HEAD; then
git commit --amend --no-edit
fi
return 0
fi
if [ -z "$(git ls-files -u)" ]; then
echo "$file was the only conflict, finishing the cherry-pick"
if git diff --cached --quiet HEAD; then
echo "nothing left to apply, committing the backport empty"
git commit --allow-empty --no-edit
else
# GIT_EDITOR outranks core.editor, VISUAL, and EDITOR, so the continuation can never wait on
# an editor; the repository's own editor configuration is left alone.
GIT_EDITOR=true git cherry-pick --continue
fi
fi
}
cherry_pick_backport() {
local commit=$1
local status=0
git cherry-pick "$commit" || status=$?
if [ "$status" -ne 0 ] && ! git rev-parse -q --verify CHERRY_PICK_HEAD >/dev/null; then
echo "cherry-pick failed without entering a resolvable conflict state" >&2
return "$status"
fi
disable_ratchets "$commit"
if [ "$status" -ne 0 ] &&
git rev-parse -q --verify CHERRY_PICK_HEAD >/dev/null &&
[ -z "$(git ls-files -u)" ]; then
echo "cherry-pick stopped without a file conflict to resolve" >&2
return "$status"
fi
}
write_backport_script() {
local commit=$1
{
echo "#!/usr/bin/env bash"
echo "set -euo pipefail"
echo "git reset HEAD~1"
echo "rm ./backport.sh"
declare -f write_disabled_ratchets disable_ratchets cherry_pick_backport
printf 'cherry_pick_backport %q\n' "$commit"
printf '%s\n' "printf 'Resolve conflicts and force push this branch.\\n\\nTo backport translations run: bin/i18n/merge-translations <release-branch>\\n'"
} > ./backport.sh
}

View File

@@ -93,8 +93,8 @@ runs:
if ${{ inputs.maildev }}; then
echo -e "${Y}checking maildev container..." &&
while ! nc -z localhost 1080; do sleep 1; done &&
while ! nc -z localhost 1025; do sleep 1; done &&
while ! nc -z localhost 1180; do sleep 1; done &&
while ! nc -z localhost 1125; do sleep 1; done &&
echo -e "${G}Maildev is up and running!"
echo -e "${Y}checking maildev-ssl container..." &&

View File

@@ -20,6 +20,15 @@ inputs:
description: Directory path where the jar should be extracted (defaults to current directory)
required: false
default: "."
download:
description: Default is true. Set to false to only look the artifact up and report `fetch-hit`.
required: false
default: "true"
outputs:
fetch-hit:
description: Boolean indicating if an artifact was successfully found and downloaded.
value: ${{ steps.find_release_artifact.outputs.fetch-hit }}
runs:
using: "composite"
@@ -28,11 +37,12 @@ runs:
id: find_release_artifact
uses: actions/github-script@v9
with:
result-encoding: string
script: | # js
const fs = require('fs');
const isRelease = "${{ inputs.release }}" === "true";
const failOnMiss = "${{ inputs.fail-on-fetch-miss }}" !== "false";
const shouldDownload = "${{ inputs.download }}" !== "false";
const prefix = isRelease ? "metabase-release" : "metabase";
const artifactName = `${prefix}-${{ inputs.edition }}-${{ inputs.commit }}-uberjar`;
console.log(`Looking for artifact: ${artifactName}`);
@@ -44,12 +54,18 @@ runs:
per_page: 1,
});
if (!artifacts.data?.artifacts?.[0]?.id) {
core.setFailed(`No artifacts found for ${artifactName}`);
return;
const artifact_id = artifacts.data?.artifacts?.[0]?.id;
if (!artifact_id) {
core.setOutput('fetch-hit', 'false');
} else {
core.setOutput('fetch-hit', 'true');
}
const artifact_id = artifacts.data.artifacts[0].id;
if (!shouldDownload) {
console.log(`skipping download (download: false)`);
return;
}
let download;
const maxAttempts = 3;
@@ -74,6 +90,7 @@ runs:
fs.writeFileSync(`${process.env.GITHUB_WORKSPACE}/mb.zip`, Buffer.from(download.data));
- name: Extract and rename JAR
if: ${{ steps.find_release_artifact.outputs.fetch-hit == 'true' && inputs.download != 'false' }}
shell: bash
run: | # bash
OUTPUT_NAME="${{ inputs.output-name }}"
@@ -119,12 +136,14 @@ runs:
fi
- name: Verify that this is a valid JAR file
if: ${{ steps.find_release_artifact.outputs.fetch-hit == 'true' && inputs.download != 'false' }}
shell: bash
run: |
echo "Verifying JAR at: $JAR_PATH"
file --mime-type "$JAR_PATH"
- name: Reveal its version.properties
if: ${{ steps.find_release_artifact.outputs.fetch-hit == 'true' && inputs.download != 'false' }}
shell: bash
run: |
echo "Extracting version.properties from: $JAR_PATH"

View File

@@ -1,45 +0,0 @@
name: Get cache keys
description: |
Get deterministic cache keys for Maven and Node.js caches based on the centrally controlled cache prefix,
and the suffix based on the runner OS and the current week of the year.
outputs:
m2-cache-key:
description: "The cache key for the Maven cache."
value: ${{ steps.keys-factory.outputs.m2-cache-key }}
m2-restore-key:
description: "The fallback restore key prefix for the Maven cache."
value: ${{ steps.keys-factory.outputs.m2-restore-key }}
node-cache-key:
description: "The cache key for the Node.js cache."
value: ${{ steps.keys-factory.outputs.node-cache-key }}
node-restore-key:
description: "The fallback restore key prefix for the Node.js cache."
value: ${{ steps.keys-factory.outputs.node-restore-key }}
eslint-cache-key:
description: "The cache key for Eslint cache"
value: ${{ steps.keys-factory.outputs.eslint-cache-key }}
cypress-cache-key:
description: "The cache key for Cypress cache"
value: ${{ steps.keys-factory.outputs.cypress-cache-key }}
runs:
using: "composite"
steps:
- name: Generate and output cache keys
id: keys-factory
run: |
M2_CACHE_PREFIX='M2'
NODE_CACHE_PREFIX='node-modules'
ESLINT_CACHE_PREFIX='eslint'
CYPRESS_CACHE_PREFIX='cypress'
WEEK_OF_YEAR=$(/bin/date "+%G-%V")
CACHE_SUFFIX="${{ runner.os }}-$WEEK_OF_YEAR"
echo "m2-cache-key=$M2_CACHE_PREFIX-$CACHE_SUFFIX" >> "$GITHUB_OUTPUT"
echo "m2-restore-key=$M2_CACHE_PREFIX-" >> "$GITHUB_OUTPUT"
echo "node-cache-key=$NODE_CACHE_PREFIX-$CACHE_SUFFIX" >> "$GITHUB_OUTPUT"
echo "node-restore-key=$NODE_CACHE_PREFIX-" >> "$GITHUB_OUTPUT"
echo "eslint-cache-key=$ESLINT_CACHE_PREFIX-$CACHE_SUFFIX" >> "$GITHUB_OUTPUT"
echo "cypress-cache-key=$CYPRESS_CACHE_PREFIX-$CACHE_SUFFIX" >> "$GITHUB_OUTPUT"
shell: bash

View File

@@ -1,7 +1,15 @@
name: Get Docker Info
description: Determines Docker repository and tag based on branch and edition
description: Determines the registry, repository, and tag a container image is pushed to.
inputs:
repo:
description: Registry and repo, e.g. "metabase/metabase". Overrides branch derived repo.
required: false
default: ''
tag:
description: Docker tag, e.g. v1.87.2. Overrides a branch derived tag.
required: false
default: ''
branch:
description: Branch name (defaults to current branch)
required: false
@@ -25,9 +33,6 @@ outputs:
full_image:
description: Full Docker image name (repo:tag)
value: ${{ steps.docker-info.outputs.full_image }}
editions:
description: JSON array of editions to build
value: ${{ steps.docker-info.outputs.editions }}
runs:
using: "composite"
@@ -41,34 +46,22 @@ runs:
const edition = '${{ inputs.edition }}';
const owner = '${{ inputs.owner }}';
console.log(`Determining Docker info for branch: ${branch}, edition: ${edition}`);
let repo, tag, editions;
if (branch === 'master') {
// Master builds both editions with specific repos
editions = ['ee', 'oss'];
tag = 'latest';
if (edition === 'ee') {
repo = `${owner}/metabase-enterprise-head`;
} else {
repo = `${owner}/metabase-head`;
}
} else {
// All other branches only build EE to metabase-dev
editions = ['ee'];
tag = branch.replaceAll('/', '-'); // slashes make docker sad
repo = `${owner}/metabase-dev`;
let tag = '${{ inputs.tag}}';
if (!tag) {
tag = branch === 'master' ? 'latest' : `${branch.replaceAll('/', '-')}-${edition}`;
}
const fullImage = `${repo}:${tag}`;
let repo = '${{ inputs.repo }}';
if (!repo) {
if (branch === 'master') {
repo = edition === 'ee' ? `${owner}/metabase-enterprise-head` : `${owner}/metabase-head`;
} else {
repo = `${owner}/metabase-dev`;
}
}
// Set outputs
core.setOutput('repo', repo);
core.setOutput('tag', tag);
core.setOutput('full_image', fullImage);
core.setOutput('editions', JSON.stringify(editions));
core.setOutput('full_image', `${repo}:${tag}`);
console.log(`Docker image: ${fullImage}`);
console.log(`Editions: ${JSON.stringify(editions)}`);
console.log(`Resolved: repo = ${repo}, tag = ${tag}`);

View File

@@ -5,9 +5,6 @@ inputs:
java-version:
required: true
default: "25"
clojure-version:
required: true
default: "1.12.0.1488"
runs:
using: "composite"
@@ -17,12 +14,40 @@ runs:
with:
java-version: ${{ inputs.java-version }}
distribution: "temurin"
- name: Cache spec
id: cache-spec
shell: bash
run: .github/scripts/cache-keys.sh | tee -a "$GITHUB_OUTPUT"
- name: Restore Clojure CLI
uses: actions/cache/restore@v5
with:
path: ${{ steps.cache-spec.outputs.clojure-path }}
key: ${{ steps.cache-spec.outputs.clojure-key }}
- name: Install Clojure CLI
shell: bash
env:
CLOJURE_PREFIX: ${{ steps.cache-spec.outputs.clojure-path }}
CLOJURE_VERSION: ${{ steps.cache-spec.outputs.clojure-version }}
run: |
set -uo pipefail
echo "$CLOJURE_PREFIX/bin" >> "$GITHUB_PATH"
export PATH="$CLOJURE_PREFIX/bin:$PATH"
# Whether the prefix already holds the right install is decided by running it, not by the
# cache-hit flag. The installer bakes the prefix into the clj/clojure shims, so a tree restored
# under a different $HOME points at a directory that is not there; and on a runner that is not
# ephemeral, a previous version's prefix outlives the cache entry that stopped matching it.
if clojure --version | grep -qF "$CLOJURE_VERSION"; then
clojure --version
exit 0
fi
cd "$RUNNER_TEMP"
for attempt in 1 2 3; do
curl --retry 3 --retry-delay 5 --fail -O https://download.clojure.org/install/linux-install-${{ inputs.clojure-version }}.sh \
&& sudo bash ./linux-install-${{ inputs.clojure-version }}.sh \
curl --retry 3 --retry-delay 5 --fail -O "https://download.clojure.org/install/linux-install-$CLOJURE_VERSION.sh" \
&& bash "./linux-install-$CLOJURE_VERSION.sh" --prefix "$CLOJURE_PREFIX" \
&& break
echo "::warning::Clojure install attempt $attempt failed, retrying in 10s..."
sleep 10
@@ -32,10 +57,6 @@ runs:
exit 1
fi
- name: Get M2 cache key
uses: ./.github/actions/get-cache-keys
id: get-cache-keys
- name: Install uv (for Python package installation)
uses: astral-sh/setup-uv@08807647e7069bb48b6ef5acd8ec9567f424441b # v8.1.0
with:
@@ -46,9 +67,6 @@ runs:
- name: Restore M2 cache
uses: actions/cache/restore@v5
with:
path: |
~/.m2
~/.gitlibs
key: ${{ steps.get-cache-keys.outputs.m2-cache-key }}
restore-keys: |
${{ steps.get-cache-keys.outputs.m2-restore-key }}
path: ${{ steps.cache-spec.outputs.m2-path }}
key: ${{ steps.cache-spec.outputs.m2-key }}
restore-keys: ${{ steps.cache-spec.outputs.m2-restore-key }}

View File

@@ -25,15 +25,17 @@ runs:
chrome-version: 144
id: setup-chrome
- name: Get cache keys
uses: ./.github/actions/get-cache-keys
id: get-cache-keys
- name: Cache spec
id: cache-spec
shell: bash
run: .github/scripts/cache-keys.sh | tee -a "$GITHUB_OUTPUT"
- name: Get Cypress cache
- name: Restore Cypress binary
uses: actions/cache/restore@v5
with:
path: ~/.cache/Cypress
key: ${{ steps.get-cache-keys.outputs.cypress-cache-key }}
path: ${{ steps.cache-spec.outputs.cypress-path }}
key: ${{ steps.cache-spec.outputs.cypress-key }}
restore-keys: ${{ steps.cache-spec.outputs.cypress-restore-key }}
- name: Ensure that Cypress executable is ready
run: |

View File

@@ -16,50 +16,38 @@ runs:
with:
node-version: ${{ inputs.node-version }}
- name: Get cache keys
uses: ./.github/actions/get-cache-keys
id: get-cache-keys
- name: Restore M2 cache
uses: actions/cache/restore@v5
with:
path: |
~/.m2
~/.gitlibs
key: ${{ steps.get-cache-keys.outputs.m2-cache-key }}
restore-keys: |
${{ steps.get-cache-keys.outputs.m2-restore-key }}
- name: Get bun cache directory
id: bun-cache
run: |
BUN_CACHE_DIR=$(bun pm cache)
echo "Bun cache directory: $BUN_CACHE_DIR"
echo "dir=$BUN_CACHE_DIR" >> "$GITHUB_OUTPUT"
- name: Cache spec
id: cache-spec
shell: bash
run: .github/scripts/cache-keys.sh | tee -a "$GITHUB_OUTPUT"
- name: Restore node_modules cache
# The spec names the store path rather than discovering it, so that a job can restore the cache
# before bun exists. Exported job-wide rather than per-step because every later bun invocation has
# to resolve against the same store. Confirm bun agreed: if the variable stopped taking effect, bun
# would fill its default directory and the cache would silently save an empty tree.
- name: Point bun at the cached store
shell: bash
env:
STORE: ${{ steps.cache-spec.outputs.bun-store-path }}
run: |
echo "BUN_INSTALL_CACHE_DIR=$STORE" >> "$GITHUB_ENV"
ACTUAL=$(BUN_INSTALL_CACHE_DIR="$STORE" bun pm cache)
if [ "$ACTUAL" != "$STORE" ]; then
echo "::error::bun reports its store at $ACTUAL, not $STORE; BUN_INSTALL_CACHE_DIR is not taking effect"
exit 1
fi
- name: Restore bun store
uses: actions/cache/restore@v5
id: node-modules-cache
with:
path: |
${{ steps.bun-cache.outputs.dir }}
node_modules
key: ${{ steps.get-cache-keys.outputs.node-cache-key }}
restore-keys: |
${{ steps.get-cache-keys.outputs.node-restore-key }}
path: ${{ steps.cache-spec.outputs.bun-store-path }}
key: ${{ steps.cache-spec.outputs.bun-store-key }}
restore-keys: ${{ steps.cache-spec.outputs.bun-store-restore-key }}
# postinstall lifecycle hook can be dangerous in CI so we only run it locally (see package.json)
# If a job wants to patch packages, it does so explicitly in the CI. This setting is opt-out.
# For example, we never want to cache node_modules with patches already applied so cache-generator.yml skips that step.
- name: Clean install
# Remove the restored node_modules before installing. The os-week cache can
# carry a stale tree (for example a different React major), and
# `--frozen-lockfile` alone does not prune it. Rebuilding from the cached bun
# store gives an exact, lockfile-correct node_modules with no extra download.
run: |
rm -rf node_modules
bun install --frozen-lockfile
- name: Install front-end dependencies
run: bun install --frozen-lockfile
shell: bash
- name: Patch frontend dependencies
if: inputs.apply-patches == 'true'

View File

@@ -14,21 +14,6 @@ inputs:
staging-mb-all-features-token:
description: "Staging MB all features token"
required: true
shoppy-iam-role:
description: "Shoppy IAM role for AWS credentials"
required: true
shoppy-metabase-app-db-s3-bucket:
description: "S3 bucket for Shoppy app DB dump"
required: true
shoppy-metabase-app-db-s3-key:
description: "S3 key for Shoppy app DB dump"
required: true
shoppy-metabase-app-db-user:
description: "Shoppy Metabase app DB user"
required: true
shoppy-metabase-app-db-database:
description: "Shoppy Metabase app DB database"
required: true
metastore-dev-server-url:
description: "Metastore dev server URL"
required: true
@@ -93,20 +78,6 @@ runs:
echo "sample_app_branch_exists=false" >> "$GITHUB_OUTPUT"
fi
- name: Configure AWS credentials
if: ${{ steps.check-sample-app-branch.outputs.sample_app_branch_exists == 'true' }}
uses: aws-actions/configure-aws-credentials@d979d5b3a71173a29b74b5b88418bfda9437d885
with:
role-to-assume: ${{ inputs.shoppy-iam-role }}
role-session-name: GitHub_to_AWS_via_FederatedOIDC
aws-region: us-east-1
- name: Download Shoppy's App DB PostgreSQL dump from S3
if: ${{ steps.check-sample-app-branch.outputs.sample_app_branch_exists == 'true' }}
shell: bash
run: |
aws s3 cp s3://${{ inputs.shoppy-metabase-app-db-s3-bucket }}/${{ inputs.shoppy-metabase-app-db-s3-key }} ./e2e/tmp/db_dumps/shoppy_metabase_app_db_dump.sql
- name: Prepare and launch Shoppy containers
if: ${{ steps.check-sample-app-branch.outputs.sample_app_branch_exists == 'true' }}
shell: bash
@@ -115,8 +86,6 @@ runs:
SAMPLE_APP_ENVIRONMENT: ${{ inputs.sample-app-environment }}
CYPRESS_MB_ALL_FEATURES_TOKEN: ${{ inputs.staging-mb-all-features-token }}
METASTORE_DEV_SERVER_URL: ${{ inputs.metastore-dev-server-url }}
METABASE_APP_DB_USER: ${{ inputs.shoppy-metabase-app-db-user }}
METABASE_APP_DB: ${{ inputs.shoppy-metabase-app-db-database }}
SHOPPY_DATADOG_APPLICATION_ID: ${{ inputs.shoppy-datadog-application-id }}
SHOPPY_DATADOG_CLIENT_TOKEN: ${{ inputs.shoppy-datadog-client-token }}
SHOPPY_DATADOG_SITE: "us5.datadoghq.com"

View File

@@ -25,6 +25,7 @@ runs:
TARGET_BRANCH: ${{ github.event.pull_request.base.ref || github.ref_name }}
CI_CONDUCTOR_TEST_SUITE: ${{ inputs.test-suite }}
ADAPTER: ${{ inputs.adapter }}
IS_RERUN: ${{ github.run_attempt != '1' }}
# Keep the path constrained to known entrypoints.
run: |
case "$ADAPTER" in

View File

@@ -20,8 +20,30 @@ inputs:
required: false
default: "ee"
description: Edition to test (oss or ee)
quarantine-engine:
runner-index:
required: false
description: >-
The index of this runner among those sharing a partitioned suite. See
`be-tests-bigquery-cloud-sdk-ee` in `.github/workflows/drivers.yml` for an example.
runner-count:
required: false
description: >-
How many runners share the suite. Recommended to set to `strategy.job-total` rather
than a literal so that it doesn't need updating if the `runner-index` matrix changes.
jvms-per-runner:
required: false
default: "1"
description: >-
Concurrent JVMs per runner. Recommended to raise above 1 for drivers whose tests
spend a lot of time waiting on a remote warehouse.
heap-per-jvm:
required: false
default: "4g"
description: >-
`-Xmx` per JVM, applied only when `jvms-per-runner` is more than 1 (otherwise the
the `:ci` alias's `-Xmx12g` is used). To size it: reserve ~1G for the OS and ~2G
of non-heap per JVM, then divide what's left. On a 16G runner that's ~4G each for
two JVMs.
granular-rerun:
required: false
default: "true"
@@ -100,21 +122,50 @@ runs:
# Otherwise run exactly as before. Quote the file so the whole `[ns/var ...]`
# vector reaches clojure -X as a single argument.
run: |
ALIASES="dev:ci:${{ inputs.edition }}:${{ inputs.edition }}-dev:drivers:drivers-dev:test"
BASE="clojure -X:dev:ci:${{ inputs.edition }}:${{ inputs.edition }}-dev:drivers:drivers-dev:test"
if [ "${{ inputs.granular-rerun }}" = "true" ] && [ "${{ github.run_attempt }}" != "1" ] && [ -s target/failed-tests ]; then
# `:profile-tests` overrides `:test`'s exec-fn, so it has to come last. See dev.profile-tests.
# The `profiled` output is what the collection steps below key off, so that the decision is
# recorded by the step that acts on it rather than re-derived from the environment.
if [ "$PROFILE_TESTS" = "true" ]; then
echo "Profiling this run; a flamegraph will be attached to the job."
echo "profiled=true" >> "$GITHUB_OUTPUT"
BASE="$BASE:profile-tests"
fi
# An explicit selection wins over the rerun narrowing below: it was asked for by hand, on this
# attempt. Names may be separated by commas or spaces; hawk wants them as one vector argument.
if [ -n "$ONLY_TESTS" ]; then
ONLY="[$(echo "$ONLY_TESTS" | tr ',' ' ')]"
echo "Running only: $ONLY"
$BASE :only "$ONLY"
elif [ "${{ inputs.granular-rerun }}" = "true" ] && [ "${{ github.run_attempt }}" != "1" ] && [ -s target/failed-tests ]; then
echo "Granular rerun of previously-failed tests: $(cat target/failed-tests)"
$BASE :only "$(cat target/failed-tests)"
clojure -X:"$ALIASES" :only "$(cat target/failed-tests)"
elif [ -n "$TEST_RUNNER_INDEX" ]; then
CLOJURE_ALIASES="$ALIASES" ./.github/scripts/run-backend-test-jvms.sh ${{ inputs.test-args }}
else
$BASE ${{ inputs.test-args }}
clojure -X:"$ALIASES" ${{ inputs.test-args }}
fi
shell: bash
id: run-test
env:
TEST_RUNNER_INDEX: ${{ inputs.runner-index }}
TEST_RUNNER_COUNT: ${{ inputs.runner-count }}
TEST_JVMS_PER_RUNNER: ${{ inputs.jvms-per-runner }}
TEST_HEAP_PER_JVM: ${{ inputs.heap-per-jvm }}
# Keep this step continue-on-error because the quarantine gate below controls whether it
# ultimately fails.
continue-on-error: true
- name: Collect profile
if: ${{ !cancelled() }}
uses: ./.github/actions/collect-profile
with:
profiled: ${{ steps.run-test.outputs.profiled }}
artifact-name: ${{ format('profile-{0}{1}', inputs.junit-name, inputs.artifact-suffix && format('-{0}', inputs.artifact-suffix) || '') }}
- name: Report failed tests to ci-conductor
if: ${{ !cancelled() && steps.run-test.outcome == 'failure' }}
if: ${{ !cancelled() && ( steps.run-test.outcome == 'failure' || github.run_attempt != '1' ) }}
# This step should NEVER fail the job!
continue-on-error: true
uses: ./.github/actions/report-failures-to-ci-conductor
@@ -165,7 +216,9 @@ runs:
uses: actions/upload-artifact@v7
with:
name: ${{ format('test-logs-{0}{1}', github.job, inputs.artifact-suffix && format('-{0}', inputs.artifact-suffix) || '') }}
path: logs/test-log.json
# Glob: a single-JVM run writes `logs/test-log.json`; a multi-JVM run merges one
# `logs/test-log-p<index>.json` per JVM.
path: logs/test-log*.json
retention-days: 1
# Failing to upload the artifact should never affect the outcome of the whole test run.
continue-on-error: true
@@ -178,4 +231,4 @@ runs:
with:
adapter: backend
test-suite: ${{ inputs.junit-name }}
enforce-quarantine: ${{ inputs.quarantine-engine == 'ci-conductor' }}
enforce-quarantine: "true"

View File

@@ -1,41 +0,0 @@
name: Update cache
description: |
Update a GitHub Actions cache based on a provided path and key.
If a cache entry already exists for the given key, it is first removed.
This ensures immutability of cache entries, and prevents runtime errors.
inputs:
path:
description: "The path(s) to cache, separated by newlines."
required: true
key:
description: "The cache key to use."
required: true
runs:
using: "composite"
steps:
- name: Check if the cache entry exists
id: cache-lookup
uses: actions/cache/restore@v5
with:
path: ${{ inputs.path }}
key: ${{ inputs.key }}
lookup-only: true # Important bit: the action will not fetch anything, just check for the cache existence.
- name: Delete the cache entry if it exists
if: ${{ steps.cache-lookup.outputs.cache-hit == 'true' }}
run: |
echo "Cache entry found for key '${{ inputs.key }}'. Deleting it to ensure immutability."
gh api \
--method DELETE \
-H "Accept: application/vnd.github+json" \
-H "X-GitHub-Api-Version: 2022-11-28" \
/repos/${{ github.repository }}/actions/caches?key=${{ inputs.key }}
env:
GH_TOKEN: ${{ github.token }}
shell: bash
- name: Save the new cache entry
uses: actions/cache/save@v5
with:
path: ${{ inputs.path }}
key: ${{ inputs.key }}

View File

@@ -7,9 +7,8 @@ default: &default
- "locales/**"
- "bin/**/!(*.md)"
actionlint:
- added|modified: ".github/workflows/*.yml"
- added|modified: ".github/workflows/*.yaml"
workflows:
- added|modified: ".github/workflows/*.{yml,yaml}"
shared_sources: &shared_sources
- "src/**/*.cljc"
@@ -65,6 +64,9 @@ frontend_specs: &frontend_specs
- "frontend/**/*.unit.*"
- "enterprise/frontend/**/*.unit.*"
- ".github/**/*.unit.spec.*"
# file-paths.unit.spec.ts asserts what this file's own patterns match, so a change to it has to
# run the specs that guard it.
- ".github/file-paths.yaml"
- "jest.config.js"
- "jest.tz.unit.conf.json"
@@ -113,11 +115,15 @@ backend_sources: &backend_sources
- "src/**"
- "modules/drivers/{*,*/{*,!(test)/**}}"
- "resources/**"
- ".clj-kondo/**"
# Ratchet files drive project_ratchet_checks alone, so automation PRs that lower budgets
# run the Project tests job by themselves. Patterns are OR-ed, so a separate "!..." entry would match
# every other path instead of excluding this one.
- ".clj-kondo/**/!(ratchets.edn)"
backend_specs: &backend_specs
- *shared_specs
- "test/**"
- "dev/test/**"
- "enterprise/backend/test/**"
- "test_modules/**"
- "modules/drivers/*/test/**"
@@ -130,6 +136,48 @@ backend_all: &backend_all
- *backend_sources
- *backend_specs
# Project checks have narrower triggers than the backend matrix.
# Changes to their shared CI entry points exercise every suite; otherwise each
# suite follows only the files that can affect its result.
project_tests_infra: &project_tests_infra
- ".github/actions/prepare-backend/**"
- ".github/file-paths.yaml"
- ".github/workflows/backend.yml"
- ".github/workflows/run-tests.yml"
- "bb.edn"
- "bin/mage"
- "bin/mage.bb"
- "mage/src/mage/color.clj"
- "mage/src/mage/project_tests.clj"
- "mage/src/mage/shell.clj"
- "mage/src/mage/util.clj"
project_backend_checks:
- *project_tests_infra
- "{src,test,enterprise,dev,bin,mage}/**/*.{clj,cljc,cljs}"
- "modules/**/*.clj"
- "modules/**/*.cljc"
- "modules/**/*.cljs"
- "**deps.edn"
- ".clj-kondo/{src,test}/**/*.{clj,cljc,cljs}"
- "{resources,test_resources,test_config}/**/*.{clj,cljc,cljs}"
- ".clj-kondo/config.edn"
- ".clj-kondo/config/modules/config.edn"
- ".github/team.json"
- "dev/resources/dev/modules_config_test/**"
# Only the ratchet check reads the budgets, so a diff that touches nothing else runs that suite alone.
project_ratchet_checks:
- ".clj-kondo/ratchets.edn"
- ".clj-kondo/config/modules/ratchets.edn"
project_migration_checks:
- *project_tests_infra
- "bin/lint-migrations-file/**"
- "resources/migrations/**/*.{yaml,yml}"
- "src/metabase/app_db/custom_migrations.clj"
- "src/metabase/app_db/custom_migrations/**"
sources: &sources
- *shared_sources
- *frontend_sources
@@ -222,6 +270,28 @@ cljs:
- ".github/workflows/cljs.yml"
- "shadow-cljs.edn"
embedder_plugin:
- ".github/actions/prepare-backend/**"
- ".github/file-paths.yaml"
- ".github/workflows/build-scripts.yml"
- "bin/build-embedder-plugin.sh"
- "bin/build/src/build/embedder_model.clj"
- "bin/build/src/build/plugin_uberjar.clj"
- "bin/build/src/build_embedder_plugin.clj"
- "deps.edn"
- "modules/embedder/**"
- "enterprise/backend/src/metabase_enterprise/data_complexity_score/complexity_embedders.clj"
- "enterprise/backend/src/metabase_enterprise/data_complexity_score/settings.clj"
- "enterprise/backend/src/metabase_enterprise/data_complexity_score/synonym_source.clj"
- "enterprise/backend/src/metabase_enterprise/semantic_search/embedding.clj"
- "enterprise/backend/src/metabase_enterprise/semantic_search/settings.clj"
- "enterprise/backend/test/metabase_enterprise/semantic_search/appdb_pgvector_mode_test.clj"
- "enterprise/backend/test/metabase_enterprise/semantic_search/embedding_test.clj"
- "src/metabase/embeddings/provider.clj"
- "src/metabase/embeddings/startup.clj"
- "src/metabase/plugins/**"
- "test/metabase/embeddings/embedder_plugin_artifact_test.clj"
serialization_baseline:
- ".github/workflows/serialization.yml"
- "test_resources/serialization_baseline/**"

View File

@@ -0,0 +1,12 @@
---
applyTo: "e2e/**/*.cy.spec.{js,ts}"
---
# Cypress E2E Spec Review
When reviewing Cypress E2E specs, apply the guidelines in these files:
- `.claude/skills/_shared/cypress-conventions.md`
- `.claude/skills/e2e-test-review/SKILL.md`
These are in addition to the TypeScript/JavaScript instructions, which also match these files.

View File

@@ -1,152 +0,0 @@
/* eslint-disable import/no-commonjs */
// Prepares the rows the bundle-size stats logger uploads to stats.metabase.com.
//
// For each measured (bundle, kind) it computes the delta — raw, gzipped and
// brotli (as-served) bytes plus percent — against the previously *plotted* data
// point (restored from a rolling cache), so the deltas can be charted directly.
// It also decides whether this commit is worth recording at all: a point is kept
// when the as-served size moved by at least MIN_DELTA_PERCENT, or when a new
// bundle/kind appears. Only master builds run through here — releases form
// non-linear lines whose deltas are meaningless, so they're not recorded (their
// historical sizes are backfilled separately).
//
// buildStatsRows is pure (data in, data out) so it can be unit-tested; main()
// is the thin I/O wrapper that reads env/files and writes the rows, cache and
// step outputs.
const fs = require("fs");
const path = require("path");
const deltaPercent = (current, base) =>
base ? Math.round(((current - base) * 10000) / base) / 100 : "";
/**
* Turn the current measurements + the last plotted point into upload rows, the
* slim cache rows for the next diff, and the keep/skip decision.
*
* The significance threshold tracks the as-served size: brotli where the build
* ships a precompressed .br, otherwise gzip. Current measurements always carry
* brotliBytes (estimated when no .br shipped), but a cached base point recorded
* before brotli logging may not, so the delta still falls back to gzip per row.
*/
function buildStatsRows({ measurements, previous, threshold, date, commit, commitMessage, version }) {
const previousOf = (bundle, kind) => previous.find(row => row.bundle === bundle && row.kind === kind);
let maxServedDeltaPercent = 0;
let hasNewSeries = false;
const rows = measurements.map(measurement => {
const base = previousOf(measurement.bundle, measurement.kind);
const hasBrotli = measurement.brotliBytes != null && base?.brotliBytes != null;
const gzipDeltaPercent = deltaPercent(measurement.gzipBytes, base?.gzipBytes);
const brotliDeltaPercent = hasBrotli ? deltaPercent(measurement.brotliBytes, base.brotliBytes) : "";
if (!base) {
hasNewSeries = true;
} else {
const servedDeltaPercent = hasBrotli ? brotliDeltaPercent : gzipDeltaPercent;
maxServedDeltaPercent = Math.max(maxServedDeltaPercent, Math.abs(servedDeltaPercent));
}
return {
"Date": date,
"Version": version,
"Commit": commit,
"Bundle": measurement.bundle,
"Kind": measurement.kind, // "initial" or "total"
// The stats table carries a free-text Description column; append-csv
// requires every table column to be present. Populate it with the commit
// subject so the chart's points are self-describing.
"Description": commitMessage,
"Raw bytes": measurement.rawBytes,
"Gzip bytes": measurement.gzipBytes,
"Brotli bytes": measurement.brotliBytes, // as-served (shipped .br, else estimated)
"File count": measurement.fileCount,
"Raw bytes delta": base ? measurement.rawBytes - base.rawBytes : "",
"Gzip bytes delta": base ? measurement.gzipBytes - base.gzipBytes : "",
"Brotli bytes delta": hasBrotli ? measurement.brotliBytes - base.brotliBytes : "",
"Raw delta %": deltaPercent(measurement.rawBytes, base?.rawBytes),
"Gzip delta %": gzipDeltaPercent,
"Brotli delta %": brotliDeltaPercent,
};
});
const firstPoint = previous.length === 0;
const significant = firstPoint || hasNewSeries || maxServedDeltaPercent >= threshold;
// Slim rows the next run diffs against. The workflow only persists this to the
// cache when we actually push, so the cached reference always stays the last
// *plotted* point (cumulative drift is caught).
const cacheRows = measurements.map(({ bundle, kind, rawBytes, gzipBytes, brotliBytes }) => ({
bundle,
kind,
rawBytes,
gzipBytes,
brotliBytes,
}));
const reason = firstPoint
? "first point"
: hasNewSeries
? "new bundle/kind series"
: `max served Δ ${maxServedDeltaPercent.toFixed(2)}% (threshold ${threshold}%)`;
return { rows, cacheRows, significant, reason, maxServedDeltaPercent, firstPoint, hasNewSeries };
}
module.exports = { buildStatsRows };
const readJson = filePath => (filePath && fs.existsSync(filePath) ? JSON.parse(fs.readFileSync(filePath, "utf8")) : null);
const writeJson = (filePath, value) => {
fs.mkdirSync(path.dirname(filePath), { recursive: true });
fs.writeFileSync(filePath, JSON.stringify(value));
};
const setOutput = (env, name, value) => {
if (env.GITHUB_OUTPUT) {
fs.appendFileSync(env.GITHUB_OUTPUT, `${name}=${value}\n`);
}
};
// version.properties (extracted from the uberjar) carries the build's tag.
// Non-release (master) builds report tag=vUNKNOWN, so leave Version empty there.
function readVersion(versionPropsPath) {
const raw =
versionPropsPath && fs.existsSync(versionPropsPath)
? (fs.readFileSync(versionPropsPath, "utf8").match(/^tag=(.*)$/m)?.[1]?.trim() ?? "")
: "";
return raw === "vUNKNOWN" ? "" : raw;
}
function main() {
const env = process.env;
const measurements = readJson(env.CURRENT);
if (!Array.isArray(measurements) || measurements.length === 0) {
console.error(`::error::No bundle measurements found at ${env.CURRENT}`);
process.exit(1);
}
const result = buildStatsRows({
measurements,
// The last plotted point, as slim rows: [{ bundle, kind, rawBytes, gzipBytes, brotliBytes }].
previous: readJson(env.LAST) || [],
threshold: Number(env.MIN_DELTA_PERCENT ?? 1),
date: new Date().toISOString().slice(0, 10), // YYYY-MM-DD
commit: (env.HEAD_SHA || "").slice(0, 12),
commitMessage: (env.COMMIT_MESSAGE || "").split("\n")[0], // subject line only
version: readVersion(env.VERSION_PROPS),
});
writeJson(env.ROWS_OUT, result.rows);
writeJson(env.CACHE_OUT, result.cacheRows);
console.log(`${result.significant ? "RECORD" : "SKIP"} — ${result.reason}`);
setOutput(env, "significant", result.significant ? "true" : "false");
setOutput(
env,
"max_delta_percent",
result.firstPoint || result.hasNewSeries ? "" : result.maxServedDeltaPercent.toFixed(2),
);
}
if (require.main === module) {
main();
}

View File

@@ -0,0 +1,225 @@
// Prepares the rows the bundle-size stats logger imports into eng-stats-importer.
//
// For each measured (bundle, kind) it computes the delta — raw, gzipped and
// brotli (as-served) bytes plus percent — against the previously *plotted* data
// point (restored from a rolling cache), so the deltas can be charted directly.
// It also decides whether this commit is worth recording at all: a point is kept
// when the as-served size moved by at least MIN_DELTA_PERCENT, or when a new
// bundle/kind appears. Only master builds run through here — releases form
// non-linear lines whose deltas are meaningless, so they're not recorded (their
// historical sizes are backfilled separately).
//
// buildStatsRows is pure (data in, data out) so it can be unit-tested; main()
// is the thin I/O wrapper that reads env/files and writes the rows, cache and
// step outputs.
import {
appendFileSync,
existsSync,
mkdirSync,
readFileSync,
writeFileSync,
} from "node:fs";
import { dirname } from "node:path";
/** One measurement emitted by measure-bundle-sizes. */
export interface Measurement {
bundle: string;
kind: "initial" | "total";
rawBytes: number;
gzipBytes: number;
brotliBytes: number;
fileCount: number;
}
/**
* The slim row cached between runs, holding the last *plotted* point.
* `brotliBytes` is optional because a point cached before brotli logging
* landed does not carry it — see buildStatsRows' per-row gzip fallback.
*/
export type CacheRow = Pick<Measurement, "bundle" | "kind" | "rawBytes" | "gzipBytes"> & {
brotliBytes?: number;
};
export interface BuildStatsRowsInput {
measurements: Measurement[];
previous: CacheRow[];
threshold: number;
date: string;
commit: string;
commitMessage: string;
version: string;
}
/** An upload row, keyed by the importer's column display names. */
export type StatsRow = Record<string, string | number | null>;
export interface BuildStatsRowsResult {
rows: StatsRow[];
cacheRows: CacheRow[];
significant: boolean;
reason: string;
maxServedDeltaPercent: number;
firstPoint: boolean;
hasNewSeries: boolean;
}
// null, not "", for an absent delta: the stats importer coerces values
// strictly and rejects "" for a numeric column.
const deltaPercent = (current: number, base: number | undefined | null): number | null =>
base ? Math.round(((current - base) * 10000) / base) / 100 : null;
/**
* Turn the current measurements + the last plotted point into upload rows, the
* slim cache rows for the next diff, and the keep/skip decision.
*
* The significance threshold tracks the as-served size: brotli where the build
* ships a precompressed .br, otherwise gzip. Current measurements always carry
* brotliBytes (estimated when no .br shipped), but a cached base point recorded
* before brotli logging may not, so the delta still falls back to gzip per row.
*/
export function buildStatsRows({
measurements,
previous,
threshold,
date,
commit,
commitMessage,
version,
}: BuildStatsRowsInput): BuildStatsRowsResult {
const previousOf = (bundle: string, kind: string) =>
previous.find((row) => row.bundle === bundle && row.kind === kind);
let maxServedDeltaPercent = 0;
let hasNewSeries = false;
const rows = measurements.map((measurement): StatsRow => {
const base = previousOf(measurement.bundle, measurement.kind);
// Non-null only when BOTH sides carry brotli: a point cached before brotli
// logging landed has none, and that row falls back to the gzip delta.
const baseBrotli =
measurement.brotliBytes != null && base?.brotliBytes != null ? base.brotliBytes : null;
const gzipDeltaPercent = deltaPercent(measurement.gzipBytes, base?.gzipBytes);
const brotliDeltaPercent =
baseBrotli != null ? deltaPercent(measurement.brotliBytes, baseBrotli) : null;
if (!base) {
hasNewSeries = true;
} else {
const servedDeltaPercent = baseBrotli != null ? brotliDeltaPercent : gzipDeltaPercent;
maxServedDeltaPercent = Math.max(maxServedDeltaPercent, Math.abs(servedDeltaPercent ?? 0));
}
return {
Date: date,
Version: version,
Commit: commit,
Bundle: measurement.bundle,
Kind: measurement.kind, // "initial" or "total"
// The stats table carries a free-text Description column. Populate it
// with the commit subject so the chart's points are self-describing.
Description: commitMessage,
"Raw bytes": measurement.rawBytes,
"Gzip bytes": measurement.gzipBytes,
"Brotli bytes": measurement.brotliBytes, // as-served (shipped .br, else estimated)
"File count": measurement.fileCount,
"Raw bytes delta": base ? measurement.rawBytes - base.rawBytes : null,
"Gzip bytes delta": base ? measurement.gzipBytes - base.gzipBytes : null,
"Brotli bytes delta": baseBrotli != null ? measurement.brotliBytes - baseBrotli : null,
"Raw delta %": deltaPercent(measurement.rawBytes, base?.rawBytes),
"Gzip delta %": gzipDeltaPercent,
"Brotli delta %": brotliDeltaPercent,
};
});
const firstPoint = previous.length === 0;
const significant = firstPoint || hasNewSeries || maxServedDeltaPercent >= threshold;
// Slim rows the next run diffs against. The workflow only persists this to the
// cache when we actually push, so the cached reference always stays the last
// *plotted* point (cumulative drift is caught).
const cacheRows = measurements.map(
({ bundle, kind, rawBytes, gzipBytes, brotliBytes }): CacheRow => ({
bundle,
kind,
rawBytes,
gzipBytes,
brotliBytes,
}),
);
const reason = firstPoint
? "first point"
: hasNewSeries
? "new bundle/kind series"
: `max served Δ ${maxServedDeltaPercent.toFixed(2)}% (threshold ${threshold}%)`;
return {
rows,
cacheRows,
significant,
reason,
maxServedDeltaPercent,
firstPoint,
hasNewSeries,
};
}
const readJson = <T,>(filePath: string | undefined): T | null =>
filePath && existsSync(filePath) ? (JSON.parse(readFileSync(filePath, "utf8")) as T) : null;
const writeJson = (filePath: string, value: unknown) => {
mkdirSync(dirname(filePath), { recursive: true });
writeFileSync(filePath, JSON.stringify(value));
};
const setOutput = (name: string, value: string) => {
if (process.env.GITHUB_OUTPUT) {
appendFileSync(process.env.GITHUB_OUTPUT, `${name}=${value}\n`);
}
};
// version.properties (extracted from the uberjar) carries the build's tag.
// Non-release (master) builds report tag=vUNKNOWN, so leave Version empty there.
function readVersion(versionPropsPath: string | undefined): string {
const raw =
versionPropsPath && existsSync(versionPropsPath)
? (readFileSync(versionPropsPath, "utf8").match(/^tag=(.*)$/m)?.[1]?.trim() ?? "")
: "";
return raw === "vUNKNOWN" ? "" : raw;
}
export function main() {
const env = process.env;
const measurements = readJson<Measurement[]>(env.CURRENT);
if (!Array.isArray(measurements) || measurements.length === 0) {
console.error(`::error::No bundle measurements found at ${env.CURRENT}`);
process.exit(1);
}
const result = buildStatsRows({
measurements,
// The last plotted point, as slim rows: [{ bundle, kind, rawBytes, gzipBytes, brotliBytes }].
previous: readJson<CacheRow[]>(env.LAST) || [],
threshold: Number(env.MIN_DELTA_PERCENT ?? 1),
date: new Date().toISOString().slice(0, 10), // YYYY-MM-DD
commit: (env.HEAD_SHA || "").slice(0, 12),
commitMessage: (env.COMMIT_MESSAGE || "").split("\n")[0], // subject line only
version: readVersion(env.VERSION_PROPS),
});
writeJson(env.ROWS_OUT!, result.rows);
writeJson(env.CACHE_OUT!, result.cacheRows);
console.log(`${result.significant ? "RECORD" : "SKIP"} — ${result.reason}`);
setOutput("significant", result.significant ? "true" : "false");
setOutput(
"max_delta_percent",
result.firstPoint || result.hasNewSeries ? "" : result.maxServedDeltaPercent.toFixed(2),
);
}
// Only run the I/O wrapper when invoked directly, so importing buildStatsRows
// (from the spec) has no side effects.
if ((import.meta as ImportMeta & { main?: boolean }).main) {
main();
}

View File

@@ -1,7 +1,16 @@
const { buildStatsRows } = require("./bundle-size-stats-prepare");
import {
buildStatsRows,
type CacheRow,
type Measurement,
} from "./bundle-size-stats-prepare";
const meta = { date: "2026-06-30", commit: "abc123", commitMessage: "Fix the thing (#123)", version: "" };
const measurement = (over = {}) => ({
const meta = {
date: "2026-06-30",
commit: "abc123",
commitMessage: "Fix the thing (#123)",
version: "",
};
const measurement = (over: Partial<Measurement> = {}): Measurement => ({
bundle: "embedding-sdk-chunked",
kind: "total",
rawBytes: 1000,
@@ -23,8 +32,8 @@ describe("buildStatsRows", () => {
expect(result.firstPoint).toBe(true);
expect(result.significant).toBe(true);
expect(result.reason).toBe("first point");
expect(result.rows[0]["Gzip bytes delta"]).toBe("");
expect(result.rows[0]["Brotli delta %"]).toBe("");
expect(result.rows[0]["Gzip bytes delta"]).toBeNull();
expect(result.rows[0]["Brotli delta %"]).toBeNull();
expect(result.rows[0]["Description"]).toBe("Fix the thing (#123)");
expect(result.cacheRows[0]).toEqual({
bundle: "embedding-sdk-chunked",
@@ -49,7 +58,15 @@ describe("buildStatsRows", () => {
});
it("gates significance on the brotli (as-served) delta when both sides have it", () => {
const previous = [{ bundle: "embedding-sdk-chunked", kind: "total", rawBytes: 1000, gzipBytes: 400, brotliBytes: 300 }];
const previous: CacheRow[] = [
{
bundle: "embedding-sdk-chunked",
kind: "total",
rawBytes: 1000,
gzipBytes: 400,
brotliBytes: 300,
},
];
const big = buildStatsRows({
...meta,
@@ -75,13 +92,14 @@ describe("buildStatsRows", () => {
const result = buildStatsRows({
...meta,
measurements: [measurement({ gzipBytes: 440, brotliBytes: 300 })], // gzip +10%
// No brotliBytes: this point was cached before brotli logging landed.
previous: [{ bundle: "embedding-sdk-chunked", kind: "total", rawBytes: 1000, gzipBytes: 400 }],
threshold: 1,
});
expect(result.maxServedDeltaPercent).toBeCloseTo(10);
expect(result.significant).toBe(true);
expect(result.rows[0]["Brotli bytes delta"]).toBe(""); // no base brotli to diff against
expect(result.rows[0]["Brotli bytes delta"]).toBeNull(); // no base brotli to diff against
expect(result.rows[0]["Gzip delta %"]).toBeCloseTo(10);
});
});

162
.github/scripts/cache-keys.sh vendored Executable file
View File

@@ -0,0 +1,162 @@
#!/usr/bin/env bash
# Single definition of every CI dependency cache: what it holds, what identifies it, what it falls back to.
#
# A GitHub cache entry is identified by its key, a hash of the declared path list, and the ref that saved
# it. A step declaring a different path list than the one a cache was saved with computes a different
# identity and can never match it, whatever its key says. So paths and keys are emitted together here and
# every cache step takes both from this script.
#
# Emits `name=value` lines in $GITHUB_OUTPUT format:
#
# .github/scripts/cache-keys.sh >> "$GITHUB_OUTPUT"
#
# Run it with no redirect to see the whole scheme, or pass one name to print a single value:
#
# .github/scripts/cache-keys.sh
# .github/scripts/cache-keys.sh m2-key
#
# Hashes are computed here rather than with GitHub's hashFiles() so that a local run and a CI run of the
# same commit produce the same keys, and so that an empty match can fail loudly - a hashFiles() call that
# matches nothing silently yields "", collapsing the key onto its own restore prefix and pointing every
# dependency set at one entry.
set -euo pipefail
cd "$(git rev-parse --show-toplevel)"
OS="${RUNNER_OS:-$(uname -s)}"
[ "$OS" = "Darwin" ] && OS="macOS"
sha256() {
if command -v sha256sum >/dev/null 2>&1; then
sha256sum | cut -d' ' -f1
else
shasum -a 256 | cut -d' ' -f1
fi
}
# Digest of a set of files: hash each one, then hash the concatenation, so the result depends on every
# file's contents and on which files exist.
digest() {
local f
if [ "$#" -eq 0 ]; then
echo "::error::cache-keys.sh: no files matched; refusing to emit a key that would collide across dependency sets" >&2
exit 1
fi
for f in "$@"; do
[ -f "$f" ] || { echo "::error::cache-keys.sh: $f does not exist" >&2; exit 1; }
sha256 < "$f"
done | sha256
}
shopt -s nullglob
DEPS_FILES=(deps.edn
bin/lint-migrations-file/deps.edn
bin/load-namespaces/deps.edn
modules/drivers/deps.edn
modules/drivers/*/deps.edn)
shopt -u nullglob
DEPS_HASH="$(digest "${DEPS_FILES[@]}")"
LOCK_HASH="$(digest bun.lock)"
# The Cypress binary depends on the Cypress version alone, so keying it on the whole lockfile would
# throw away a 200MB download every time any frontend dependency moved.
#
# Reading a version out of a lockfile with a regex is only safe while exactly one line matches. Insist
# on that rather than taking the first of several: a second match means the format moved under us, and
# picking one at random would key the binary under a version it is not.
CYPRESS_VERSIONS="$(sed -n 's/.*"cypress": \["cypress@\([^"]*\)".*/\1/p' bun.lock)"
CYPRESS_MATCHES="$(printf '%s\n' "$CYPRESS_VERSIONS" | grep -c . || true)"
if [ "$CYPRESS_MATCHES" != "1" ]; then
echo "::error::cache-keys.sh: expected exactly one resolved cypress version in bun.lock, found $CYPRESS_MATCHES" >&2
exit 1
fi
CYPRESS_VERSION="$CYPRESS_VERSIONS"
# The Clojure CLI version CI installs. It lives here rather than in prepare-backend so that the version
# and the key that identifies its cache entry cannot drift apart.
CLOJURE_VERSION="1.12.0.1488"
# An incremental lint cache is only ever an accelerator, so it keys on the commit and always falls back
# to the newest entry on the prefix. The exact key never pre-exists, which keeps the entry current.
ESLINT_SHA="${GITHUB_SHA:-$(git rev-parse HEAD)}"
emit_multiline() {
local name="$1"; shift
printf '%s<<CACHE_KEYS_EOF\n' "$name"
printf '%s\n' "$@"
printf 'CACHE_KEYS_EOF\n'
}
# Paths under the home directory are emitted absolute rather than as `~/...`. actions/cache would expand
# a tilde, but a shell assigning one of these to a variable would not, and would go on to create a
# directory named `~`. Paths inside the checkout stay relative; actions/cache resolves those against the
# workspace.
spec() {
emit_multiline m2-path "$HOME/.m2" "$HOME/.gitlibs" "$HOME/.deps.clj" 'bin/bb'
echo "m2-key=M2-$OS-$DEPS_HASH"
echo "m2-restore-key=M2-$OS-"
# Pinned rather than discovered via `bun pm cache` so that the path is known before bun is installed;
# prepare-frontend exports BUN_INSTALL_CACHE_DIR to match and fails if bun disagrees.
echo "bun-store-path=$HOME/.bun/install/cache"
echo "bun-store-key=bun-store-$OS-$LOCK_HASH"
echo "bun-store-restore-key=bun-store-$OS-"
# No restore-key: an entry from another version installs a working `clojure` of the wrong version, and
# the freshness check in prepare-backend - running the binary - would accept it.
#
# The installer bakes this prefix into the clj/clojure shims, so the tree only works when restored to
# the same absolute path it was built at; prepare-backend reinstalls when it is not.
echo "clojure-path=$HOME/.clojure-cli"
echo "clojure-key=clojure-cli-$OS-$CLOJURE_VERSION"
echo "clojure-version=$CLOJURE_VERSION"
echo "cypress-path=$HOME/.cache/Cypress"
echo "cypress-key=cypress-$OS-$CYPRESS_VERSION"
echo "cypress-restore-key=cypress-$OS-"
echo "eslint-path=.eslintcache"
echo "eslint-key=eslint-$OS-$ESLINT_SHA"
echo "eslint-restore-key=eslint-$OS-"
}
# Print one output's value, including the multiline form, and fail on a name that does not exist. A
# caller that silently received "" would go on to build a key with a hole in it.
query() {
local want="$1" line delim found=0 in_block=0
while IFS= read -r line; do
if [ "$in_block" = 1 ]; then
if [ "$line" = "$delim" ]; then
in_block=0
else
printf '%s\n' "$line"
fi
continue
fi
case "$line" in
"$want="*)
printf '%s\n' "${line#*=}"
found=1
;;
"$want<<"*)
delim="${line#*<<}"
in_block=1
found=1
;;
esac
done <<EOF
$(spec)
EOF
if [ "$found" = 0 ]; then
echo "::error::cache-keys.sh: no output named '$want'" >&2
exit 1
fi
}
if [ "$#" -eq 0 ]; then
spec
else
query "$1"
fi

80
.github/scripts/cache-keys.unit.spec.ts vendored Normal file
View File

@@ -0,0 +1,80 @@
import { execFileSync } from "child_process";
import { join } from "path";
const SCRIPT = join(__dirname, "cache-keys.sh");
const CACHES = ["m2", "bun-store", "cypress", "eslint"];
// stderr is inherited by default, so the deliberate-failure case below would print a literal
// `::error::` line - which GitHub Actions reads as an annotation directive, making a passing run
// annotate itself with an error.
const run = (args: string[] = [], env: NodeJS.ProcessEnv = {}, quiet = false) =>
execFileSync(SCRIPT, args, {
encoding: "utf8",
stdio: quiet ? ["ignore", "pipe", "ignore"] : "pipe",
env: { ...process.env, RUNNER_OS: "Linux", GITHUB_SHA: "abc123", ...env },
});
const get = (name: string, env: NodeJS.ProcessEnv = {}) =>
run([name], env).trimEnd();
describe("cache-keys.sh", () => {
it("is deterministic for a given tree", () => {
expect(run()).toEqual(run());
});
it("emits every cache's path, key and restore key", () => {
for (const cache of CACHES) {
expect(get(`${cache}-path`)).not.toEqual("");
expect(get(`${cache}-key`)).not.toEqual("");
expect(get(`${cache}-restore-key`)).not.toEqual("");
}
});
// Silently returning "" for a name that does not exist is how a caller ends up building a key with a
// hole in it.
it("fails on an unknown output name", () => {
expect(() => run(["no-such-output"], {}, true)).toThrow();
});
// A key equal to its own restore prefix points every dependency set at one entry, and nothing reports
// it. This is the failure the script exists to prevent.
it("never emits a key equal to its own restore prefix", () => {
for (const cache of CACHES) {
const key = get(`${cache}-key`);
const prefix = get(`${cache}-restore-key`);
expect(key.startsWith(prefix)).toBe(true);
expect(key.length).toBeGreaterThan(prefix.length);
}
});
it("scopes every key to the runner OS", () => {
for (const cache of CACHES) {
expect(get(`${cache}-key`, { RUNNER_OS: "Linux" })).not.toEqual(
get(`${cache}-key`, { RUNNER_OS: "macOS" }),
);
}
});
// Home paths must be absolute: actions/cache expands a tilde but a shell assigning one to a variable
// does not, and would create a directory literally named `~`.
it("emits absolute paths for home directory locations", () => {
expect(get("bun-store-path").startsWith("/")).toBe(true);
expect(get("cypress-path").startsWith("/")).toBe(true);
for (const line of get("m2-path").split("\n")) {
expect(line.startsWith("~")).toBe(false);
}
});
// The Cypress binary depends on the Cypress version alone, so an unrelated dependency bump must not
// invalidate a 200MB download.
it("keys the Cypress binary on the resolved version, not the lockfile", () => {
expect(get("cypress-key")).toMatch(/^cypress-Linux-\d+\.\d+\.\d+/);
});
it("keys the ESLint cache on the commit", () => {
expect(get("eslint-key", { GITHUB_SHA: "deadbeef" })).toEqual(
"eslint-Linux-deadbeef",
);
});
});

71
.github/scripts/check-job-timeouts.sh vendored Executable file
View File

@@ -0,0 +1,71 @@
#!/usr/bin/env bash
# Fails when a job in .github/workflows/ does not set `timeout-minutes`.
#
# Without it a job inherits GitHub's 6-hour default, so a hung job burns six hours of runner time -
# and holds up everything queued behind it - before anyone notices. actionlint cannot check this: its
# rule set is compiled in and .github/actionlint.yaml only takes `self-hosted-runner`,
# `config-variables`, and `paths` (which suppresses findings rather than adding them). Hence this
# script.
#
# The rule is per job: a `timeout-minutes` on a step does not satisfy it, and steps are not required
# to carry one of their own.
#
# Jobs that call a reusable workflow (`uses:` at the job level) are skipped - GitHub rejects
# `timeout-minutes` there. The called workflow's own jobs are checked when it lives in this repo.
#
# .github/scripts/check-job-timeouts.sh [workflow-file ...]
#
# With no arguments it checks every workflow; CI passes the files that changed, like actionlint does.
set -euo pipefail
# Arguments are used as given, so the paths in the annotations match what the caller passed. Without
# them the full scan has to run from the repo root.
if [ $# -gt 0 ]; then
workflows=("$@")
else
cd "$(git rev-parse --show-toplevel)"
shopt -s nullglob
workflows=(.github/workflows/*.yml .github/workflows/*.yaml)
if [ ${#workflows[@]} -eq 0 ]; then
echo "::error::check-job-timeouts.sh: no workflow files found under .github/workflows/" >&2
exit 1
fi
fi
status=0
for file in "${workflows[@]}"; do
# `awk NF` drops the blank line yq emits when a file has nothing to report.
missing="$(
# --header-preprocess=false: yq otherwise slurps any leading comment block before parsing, which
# shifts every line number it reports by the size of that block.
yq --header-preprocess=false '
.jobs
| to_entries
| .[]
| select(((.value | has("timeout-minutes")) or (.value | has("uses"))) | not)
| [(.key | line), .key]
| @tsv
' "$file" | awk NF
)"
[ -n "$missing" ] || continue
while IFS=$'\t' read -r line job; do
echo "::error file=${file},line=${line}::Job \"${job}\" does not set a job-level timeout-minutes" >&2
done <<< "$missing"
status=1
done
if [ "$status" -ne 0 ]; then
echo >&2
echo "Every job must set an explicit timeout-minutes; without one it inherits GitHub's 6-hour default." >&2
echo "Pick a value with headroom over the job's normal runtime." >&2
exit 1
fi
echo "All jobs in the ${#workflows[@]} workflow file(s) checked set timeout-minutes."

109
.github/scripts/check-preresolve-aliases.sh vendored Executable file
View File

@@ -0,0 +1,109 @@
#!/usr/bin/env bash
# Fails when a Clojure classpath used by CI is not pre-resolved by cache-warm.
#
# tools.deps selects dependency versions globally per classpath, so two alias combinations can resolve
# the same transitive library to different versions. A combination the warm job never resolved is
# therefore not merely absent from the cache - the cache holds *a* version of those libraries, just not
# the one this classpath wants, and the job fetches its delta straight from Maven Central on every run.
# That is the intermittent-403 failure of DEV-2094, and it is invisible: the build still passes.
#
# Nothing about a missing combination shows up at runtime, so this check is the only thing standing
# between a newly added alias combination and a permanently half-cold cache.
#
# .github/scripts/check-preresolve-aliases.sh
set -euo pipefail
cd "$(git rev-parse --show-toplevel)"
WARM=.github/workflows/cache-warm.yml
# Invocations deliberately left out of the warm job. Each needs a reason, because the default answer is
# to add the combination to the list instead.
WAIVED="$(
cat <<'EOF'
:deps
:outdated
EOF
)"
# :deps - tools.deps built-in used by write-poms.sh; contributes no dependencies of its own.
# :outdated - scheduled dependency-bump workflow only; a cold resolve there costs nothing anyone waits on.
# Dependency roots and alias combinations the warm job pre-resolves.
declared="$({
sed -n '/^[[:space:]]*combos=(/,/^ *)/p' "$WARM" \
| grep -oE '":[^"]*"' \
| tr -d '"' \
| sed 's#^#.|#'
sed -n '/^[[:space:]]*nested_combos=(/,/^ *)/p' "$WARM" \
| grep -oE '"[^"]+\|:[^"]+"' \
| tr -d '"'
} | sort -u)"
if [ -z "$declared" ]; then
echo "::error::check-preresolve-aliases.sh: found no pre-resolved classpaths in $WARM" >&2
exit 1
fi
# Expressions we know how to expand. An unrecognised one has to stop the check rather than be skipped:
# silently ignoring it is how a whole matrix of combinations would go unchecked.
unknown="$(grep -rhoE '\$\{\{[^}]*\}\}' --include='*' \
--exclude='*.png' --exclude='*.jpg' .github/ 2>/dev/null \
| sort -u | grep -v 'edition' || true)"
scan() { # scan <edition>: dependency root and aliases used by .github Clojure invocations
grep -rhE 'clojure[[:space:]]+(-P[[:space:]]+)?-[XMATP]?:' \
--include='*' --exclude='*.png' --exclude='*.jpg' .github/ 2>/dev/null \
| sed "s/\\\${{[^}]*edition[^}]*}}/$1/g" \
| grep -oE 'clojure[[:space:]]+(-P[[:space:]]+)?-[XMATP]?:[A-Za-z0-9:_./-]+' \
| grep -oE ':[A-Za-z0-9:_./-]+' \
| sed -e 's/:$//' -e 's#^#.|#'
}
scan_project_tests() { # scan_project_tests <function> <dependency-root>
# Mage shell commands are vectors split across lines, so flatten each function body before
# extracting its alias.
sed -n "/(defn- $1 /,/^(defn/p" mage/src/mage/project_tests.clj \
| tr '\n' ' ' \
| grep -oE '"clojure"[[:space:]]+("-P"[[:space:]]+)?"-[XMATP]?:[A-Za-z0-9:_./-]+' \
| grep -oE ':[A-Za-z0-9:_./-]+' \
| sed -e 's/:$//' -e "s#^#$2|#"
}
# Check each scan separately. One scan still finding commands would otherwise conceal that another has
# stopped matching, which silently drops everything it used to cover.
require_scan() { # require_scan <what> <result>
[ -n "$2" ] && return
echo "::error::check-preresolve-aliases.sh: found no Clojure invocation in $1; the scan pattern no longer matches" >&2
exit 1
}
workflow_checks=$( { scan ee; scan oss; } || true)
clojure_checks=$(scan_project_tests run-clojure-checks! . || true)
migration_checks=$(scan_project_tests run-migration-checks! bin/lint-migrations-file || true)
require_scan ".github/" "$workflow_checks"
require_scan "run-clojure-checks! (mage/src/mage/project_tests.clj)" "$clojure_checks"
require_scan "run-migration-checks! (mage/src/mage/project_tests.clj)" "$migration_checks"
scanned="$(printf '%s\n' "$workflow_checks" "$clojure_checks" "$migration_checks" | sort -u)"
found="$( {
printf '%s\n' "$scanned"
# build-scripts.yml runs this classpath from its own dependency root.
printf '%s\n' 'bin/load-namespaces|:test'
} | sort -u )"
covered="$( {
printf '%s\n' "$declared"
printf '%s\n' "$WAIVED" | sed 's#^#.|#'
} | sort -u)"
missing="$(comm -23 <(printf '%s\n' "$found") <(printf '%s\n' "$covered") || true)"
if [ -n "$missing" ]; then
echo "::error::Clojure classpaths used by CI that cache-warm does not pre-resolve:" >&2
printf '%s\n' "$missing" | sed 's/^/ /' >&2
echo >&2
echo "Add each to the matching root or nested combo list in $WARM, or waive it here with a reason." >&2
echo "Leaving it uncovered means those jobs re-fetch their version deltas from Maven on every run." >&2
exit 1
fi
echo "All $(printf '%s\n' "$found" | grep -c .) Clojure classpaths used by CI are pre-resolved."

View File

@@ -24,11 +24,17 @@ const STORY_GLOBS = [
"enterprise/frontend/**/*.stories.{js,jsx,ts,tsx}",
];
// `git ls-files -- frontend enterprise/frontend` already prints just over a
// megabyte of paths, and node's default maxBuffer is exactly 1 MiB: past that
// the spawn dies with ENOBUFS. Give the listings room to grow.
const LS_FILES_MAX_BUFFER = 64 * 1024 * 1024;
// Returns the tracked files under `roots` that match `globs`. The `dot: true`
// option means files inside dot-directories such as `.storybook` are included.
function listFiles(roots: string[], globs: string[]): string[] {
const tracked = execFileSync("git", ["ls-files", "--", ...roots], {
encoding: "utf8",
maxBuffer: LS_FILES_MAX_BUFFER,
})
.split("\n")
.map((line) => line.trim())

View File

@@ -1,91 +0,0 @@
/**
* jsonData must be in the format:
* [
* { column1: value1, column2: value2, ... },
* { column1: value3, column2: value4, ... },
* ...
* ]
*/
function jsonToCsvFormData(jsonData) {
const formData = new FormData();
const csvHeader = Object.keys(jsonData[0]).join(',') + '\n';
const csvContent = jsonData.map(row =>
Object.values(row).map(value => `"${String(value).replace(/"/g, '""')}"`).join(',')
).join('\n');
const blob = new Blob([csvHeader + csvContent], { type: 'text/csv' });
formData.append('file', blob, 'data.csv');
return formData;
}
// Transient failures worth retrying: throttling and server-side errors. A 4xx
// (bad request, auth) won't succeed on retry, so those fail fast.
const RETRYABLE_STATUS = new Set([429, 500, 502, 503, 504]);
class UploadError extends Error {
constructor(message, { retryable }) {
super(message);
this.retryable = retryable;
}
}
async function attemptUpload(url, jsonData, timeoutMs) {
let response;
try {
response = await fetch(url, {
method: 'POST',
headers: {
"x-api-key": process.env.API_KEY
},
// Rebuilt per attempt: a consumed request body can't be reused.
body: jsonToCsvFormData(jsonData),
// Without this the request can hang indefinitely on a stalled server,
// eating the whole job timeout. An abort surfaces below as a retryable
// network error, so it retries with backoff instead.
signal: AbortSignal.timeout(timeoutMs)
});
} catch (networkError) {
throw new UploadError(networkError.message, { retryable: true });
}
if (response.ok) {
return;
}
const body = await response.text().catch(() => '');
throw new UploadError(
`Upload failed: ${response.status} ${response.statusText} ${body}`.trim(),
{ retryable: RETRYABLE_STATUS.has(response.status) }
);
}
const sleep = ms => new Promise(resolve => setTimeout(resolve, ms));
/**
* Uploads jsonData as CSV, retrying transient API errors with exponential
* backoff. `retries` is the number of extra attempts after the first (so the
* default 2 means up to 3 tries). `timeoutMs` is a per-attempt total deadline
* (default 60s) that aborts a stalled request. Throws the last error once
* attempts are exhausted or the error is non-retryable.
*/
async function uploadCsvToMb({ baseUrl, tableId, jsonData, mode = 'append', retries = 2, retryDelayMs = 1000, timeoutMs = 60_000 }) {
const operation = mode === 'replace' ? 'replace-csv' : 'append-csv';
const url = `${baseUrl}/api/table/${tableId}/${operation}`;
for (let attempt = 0; ; attempt++) {
try {
await attemptUpload(url, jsonData, timeoutMs);
return { success: true };
} catch (error) {
if (!error.retryable || attempt >= retries) {
throw error;
}
const delay = retryDelayMs * 2 ** attempt;
console.warn(`Upload attempt ${attempt + 1} failed (${error.message}); retrying in ${delay}ms`);
await sleep(delay);
}
}
}
module.exports = { uploadCsvToMb };

View File

@@ -1,50 +0,0 @@
const { uploadCsvToMb } = require("./csv-to-mb");
const ok = () => ({ ok: true });
const fail = status => ({ ok: false, status, statusText: "err", text: async () => "" });
const upload = (over = {}) =>
uploadCsvToMb({
baseUrl: "https://stats.example.com",
tableId: 1,
jsonData: [{ a: 1 }],
retryDelayMs: 1,
...over,
});
describe("uploadCsvToMb retries", () => {
afterEach(() => {
delete global.fetch;
});
it("retries transient server errors then succeeds", async () => {
global.fetch = jest.fn().mockResolvedValueOnce(fail(503)).mockResolvedValueOnce(fail(500)).mockResolvedValueOnce(ok());
await expect(upload({ retries: 2 })).resolves.toEqual({ success: true });
expect(global.fetch).toHaveBeenCalledTimes(3);
});
it("retries network errors", async () => {
global.fetch = jest
.fn()
.mockRejectedValueOnce(new Error("ECONNRESET"))
.mockResolvedValueOnce(ok());
await expect(upload({ retries: 2 })).resolves.toEqual({ success: true });
expect(global.fetch).toHaveBeenCalledTimes(2);
});
it("gives up after exhausting retries and throws the last error", async () => {
global.fetch = jest.fn().mockResolvedValue(fail(500));
await expect(upload({ retries: 2 })).rejects.toThrow("Upload failed: 500");
expect(global.fetch).toHaveBeenCalledTimes(3); // 1 initial + 2 retries
});
it("does not retry a non-transient 4xx", async () => {
global.fetch = jest.fn().mockResolvedValue(fail(400));
await expect(upload({ retries: 2 })).rejects.toThrow("Upload failed: 400");
expect(global.fetch).toHaveBeenCalledTimes(1);
});
});

66
.github/scripts/file-paths.unit.spec.ts vendored Normal file
View File

@@ -0,0 +1,66 @@
import { readFileSync } from "fs";
import { join } from "path";
import { load } from "js-yaml";
import { isMatch } from "micromatch";
const FILTERS = join(__dirname, "..", "file-paths.yaml");
type Filter = string | Filter[] | { [changeType: string]: Filter };
// A filter is a list of patterns, and an entry may name the change types it applies to as
// { "added|modified": pattern }. Either way the patterns are what matters here.
const patterns = (value: Filter): string[] => {
if (typeof value === "string") return [value];
if (Array.isArray(value)) return value.flatMap(patterns);
return Object.values(value).flatMap(patterns);
};
describe("file-paths.yaml", () => {
const filters = load(readFileSync(FILTERS, "utf8")) as Record<string, Filter>;
// dorny/paths-filter matches with picomatch, which micromatch wraps, so this asks the same
// question CI asks of a changed path.
const matches = (name: string, path: string) =>
patterns(filters[name]).some((pattern) =>
isMatch(path, pattern, { dot: true }),
);
// dorny/paths-filter ORs the patterns in a filter, so a "!..." entry does not subtract from the
// other entries - it matches every path they don't, turning the filter permanently on. Excluding
// a path means writing the exclusion inside one pattern, the way backend_sources keeps
// ratchet files out with ".clj-kondo/**/!(ratchets.edn)".
it("never excludes a path with a standalone negation", () => {
const negated = Object.entries(filters).flatMap(([name, filter]) =>
patterns(filter)
.filter((pattern) => pattern.startsWith("!"))
.map((pattern) => `${name}: ${pattern}`),
);
expect(negated).toEqual([]);
});
it.each(["backend_sources", "backend_all"])(
"%s skips a ratchets-only change and still follows the rest of .clj-kondo",
(name) => {
expect(matches(name, ".clj-kondo/ratchets.edn")).toBe(false);
expect(
matches(name, ".clj-kondo/config/modules/ratchets.edn"),
).toBe(false);
expect(matches(name, ".clj-kondo/config.edn")).toBe(true);
expect(matches(name, ".clj-kondo/config/modules/config.edn")).toBe(true);
},
);
it("runs the ratchet check on the ratchets file", () => {
expect(matches("project_ratchet_checks", ".clj-kondo/ratchets.edn")).toBe(
true,
);
expect(
matches(
"project_ratchet_checks",
".clj-kondo/config/modules/ratchets.edn",
),
).toBe(true);
});
});

View File

@@ -1,40 +0,0 @@
async function findLinearIssue({ githubIssueUrl, linearApiKey }) {
const response = await fetch("https://api.linear.app/graphql", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: linearApiKey,
},
body: JSON.stringify({
query: `
query {
attachmentsForURL(url: "${githubIssueUrl}") {
nodes {
issue { identifier }
}
}
}
`,
}),
});
const data = await response.json();
if (!response.ok) {
return { success: false, message: `Linear API error: ${response.status}` };
}
if (!data.data?.attachmentsForURL?.nodes?.length) {
return {
success: false,
message: `No Linear issue linked to ${githubIssueUrl}`,
};
}
return {
success: true,
issue: data.data.attachmentsForURL.nodes[0].issue.identifier,
};
}
module.exports = { findLinearIssue };

109
.github/scripts/linear-issues.js vendored Normal file
View File

@@ -0,0 +1,109 @@
async function findLinearIssue({ githubIssueUrl, linearApiKey }) {
const response = await fetch("https://api.linear.app/graphql", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: linearApiKey,
},
body: JSON.stringify({
query: `
query {
attachmentsForURL(url: "${githubIssueUrl}") {
nodes {
issue { identifier }
}
}
}
`,
}),
});
const data = await response.json();
if (!response.ok) {
return { success: false, message: `Linear API error: ${response.status}` };
}
if (!data.data?.attachmentsForURL?.nodes?.length) {
return {
success: false,
message: `No Linear issue linked to ${githubIssueUrl}`,
};
}
return {
success: true,
issue: data.data.attachmentsForURL.nodes[0].issue.identifier,
};
}
async function createLinearIssue({
teamId,
title,
description,
projectId,
labelIds,
linearApiKey,
}) {
const response = await fetch("https://api.linear.app/graphql", {
method: "POST",
headers: {
"Content-Type": "application/json",
Authorization: linearApiKey,
},
body: JSON.stringify({
query: `
mutation CreateIssue($input: IssueCreateInput!) {
issueCreate(input: $input) {
success
issue {
id
identifier
title
url
}
}
}
`,
variables: {
input: {
teamId,
title,
...(description ? { description } : {}),
...(projectId ? { projectId } : {}),
...(labelIds?.length ? { labelIds } : {}),
},
},
}),
});
if (!response.ok) {
return { success: false, message: `Linear API error: ${response.status}` };
}
const data = await response.json();
if (data.errors?.length) {
return {
success: false,
message: `Linear API error: ${data.errors.map((e) => e.message).join(", ")}`,
};
}
if (!data.data?.issueCreate?.success) {
return {
success: false,
message: `Failed to create Linear issue "${title}"`,
};
}
return {
success: true,
issue: data.data.issueCreate.issue,
};
}
module.exports = {
findLinearIssue,
createLinearIssue,
};

160
.github/scripts/run-backend-test-jvms.sh vendored Executable file
View File

@@ -0,0 +1,160 @@
#!/usr/bin/env bash
#
# Run this runner's share of a partitioned backend test suite as one or more concurrent
# JVMs. The caller says how many runners share the suite and how many JVMs each gets.
#
# WHY MULTIPLE JVMS PER RUNNER
# ----------------------------
# Driver tests spend most of their wall time waiting on the remote warehouse, and they
# can't use the idle CPU by using more threads because some tests mutate global state.
# A second JVM gets that isolation for free.
#
# Two paths are NOT safe to share:
# * `target/junit` — hawk deletes the whole directory at `:begin-test-run`, so a JVM
# starting late would wipe an earlier one's results.
# * `logs/test-log.json` — the log4j2 File appender truncates it on open.
# So each JVM runs in its own hardlinked copy of the checkout (inodes, not disk) and
# outputs are merged back into the workspace afterwards.
#
# INPUTS (environment)
# --------------------
# CLOJURE_ALIASES alias string for `clojure -X`, e.g. dev:ci:ee:ee-dev:drivers:drivers-dev:test
# TEST_RUNNER_INDEX index of this runner among those sharing the suite
# TEST_RUNNER_COUNT how many runners share the suite
# TEST_JVMS_PER_RUNNER concurrent JVMs per runner (default 1)
# TEST_HEAP_PER_JVM -Xmx per JVM, applied only when running more than one
#
# Exits non-zero if any JVM fails.
set -uo pipefail
: "${CLOJURE_ALIASES:?CLOJURE_ALIASES is required}"
: "${TEST_RUNNER_INDEX:?TEST_RUNNER_INDEX is required}"
: "${TEST_RUNNER_COUNT:?TEST_RUNNER_COUNT is required}"
TEST_ARGS=("$@")
TEST_JVMS_PER_RUNNER="${TEST_JVMS_PER_RUNNER:-1}"
TEST_HEAP_PER_JVM="${TEST_HEAP_PER_JVM:-4g}"
die() {
echo "::error::run-backend-test-jvms.sh: $1"
exit 1
}
[[ "$TEST_RUNNER_INDEX" =~ ^[0-9]+$ ]] || die "TEST_RUNNER_INDEX must be a non-negative integer, got '$TEST_RUNNER_INDEX'"
[[ "$TEST_RUNNER_COUNT" =~ ^[0-9]+$ ]] || die "TEST_RUNNER_COUNT must be a positive integer, got '$TEST_RUNNER_COUNT'"
[[ "$TEST_JVMS_PER_RUNNER" =~ ^[0-9]+$ ]] || die "TEST_JVMS_PER_RUNNER must be a positive integer, got '$TEST_JVMS_PER_RUNNER'"
[ "$TEST_RUNNER_COUNT" -ge 1 ] || die "TEST_RUNNER_COUNT must be at least 1"
[ "$TEST_JVMS_PER_RUNNER" -ge 1 ] || die "TEST_JVMS_PER_RUNNER must be at least 1"
[ "$TEST_RUNNER_INDEX" -lt "$TEST_RUNNER_COUNT" ] ||
die "runner index $TEST_RUNNER_INDEX is out of range for $TEST_RUNNER_COUNT runner(s) — a matrix entry was added without raising runner-count"
# Partition indexes are split across runners rather than handed out in contiguous
# blocks. E.g. with 2 runners and 2 JVMs the first runner gets partition 0 and 2, and
# the second runner gets partitions 1 and 3. Hawk partitions in namespace order, so
# neighbouring partitions have similar runtimes — contiguous blocks would group the slow
# ones together onto one runner.
PARTITION_TOTAL=$((TEST_RUNNER_COUNT * TEST_JVMS_PER_RUNNER))
INDEXES=()
for ((k = 0; k < TEST_JVMS_PER_RUNNER; k++)); do
INDEXES+=($((TEST_RUNNER_INDEX + k * TEST_RUNNER_COUNT)))
done
# One JVM: run directly in the workspace with no heap override, exactly as a
# partitioned run behaved before this script existed.
if [ "$TEST_JVMS_PER_RUNNER" -eq 1 ]; then
echo "Running partition ${INDEXES[0]} of $PARTITION_TOTAL"
exec clojure -X:"$CLOJURE_ALIASES" "${TEST_ARGS[@]}" \
:partition/total "$PARTITION_TOTAL" \
:partition/index "${INDEXES[0]}"
fi
WORKSPACE="$PWD"
# Sibling of the checkout: same filesystem (so `cp -al` can hardlink) but outside the
# repo, so one JVM's directory never gets copied into another's.
JVM_DIRS_ROOT="$(dirname "$WORKSPACE")/backend-test-jvms"
STATUS_DIR="$JVM_DIRS_ROOT/status"
# Merge every JVM's results into the workspace the rest of the job reads from.
#
# Each partition's junit XML goes into its own subdirectory: `mb_hawk_var_less_errors.xml`
# has a fixed name, so a flat copy would silently overwrite it. Nesting is safe because
# both consumers (dorny/test-reporter and ci-conductor's backend adapter) walk
# `target/junit` recursively and match on filename suffix.
#
# Runs from an EXIT trap so a cancelled or timed-out job still publishes whatever
# finished.
# shellcheck disable=SC2329 # invoked by the EXIT trap below, which shellcheck can't see.
merge_outputs() {
mkdir -p "$WORKSPACE/target/junit" "$WORKSPACE/logs"
local idx jvm_dir
for idx in "${INDEXES[@]}"; do
jvm_dir="$JVM_DIRS_ROOT/partition-$idx"
if [ -d "$jvm_dir/target/junit" ]; then
mkdir -p "$WORKSPACE/target/junit/p$idx"
cp -a "$jvm_dir/target/junit/." "$WORKSPACE/target/junit/p$idx/" || true
fi
# `logs/test-log*.json` is what the action uploads on failure.
if [ -f "$jvm_dir/logs/test-log.json" ]; then
cp -a "$jvm_dir/logs/test-log.json" "$WORKSPACE/logs/test-log-p$idx.json" || true
fi
done
}
trap merge_outputs EXIT
trap 'exit 143' TERM
trap 'exit 130' INT
# Hardlinked copy of the checkout. Skips the paths a run writes to (`target`, `logs`, `.cpcache`)
# and the two most expensive trees nothing on the test classpath reads (`.git`, `node_modules`).
prepare_jvm_dir() {
local jvm_dir="$1" entry
rm -rf "$jvm_dir"
mkdir -p "$jvm_dir"
for entry in "$WORKSPACE"/* "$WORKSPACE"/.[!.]*; do
[ -e "$entry" ] || continue
case "$(basename "$entry")" in
.git | node_modules | target | logs | .cpcache) continue ;;
esac
# Fall back to a real copy if the filesystem refuses the hardlink.
cp -al "$entry" "$jvm_dir/" 2>/dev/null || cp -a "$entry" "$jvm_dir/"
done
}
# Prefix output with the partition index so interleaved JVM logs stay readable.
run_partition() {
local idx="$1" jvm_dir="$2" rc line
(
cd "$jvm_dir" || exit 1
# `-J` options land after the aliases' `:jvm-opts`, overriding the `:ci` alias's
# `-Xms12g -Xmx12g`. Xms stays small so JVMs sharing a runner grow into memory on
# demand rather than each committing its ceiling up front.
exec clojure -J-Xms512m -J-Xmx"$TEST_HEAP_PER_JVM" -X:"$CLOJURE_ALIASES" \
"${TEST_ARGS[@]}" \
:partition/total "$PARTITION_TOTAL" \
:partition/index "$idx"
) 2>&1 | while IFS= read -r line || [ -n "$line" ]; do printf '[p%s] %s\n' "$idx" "$line"; done
rc="${PIPESTATUS[0]}"
echo "$rc" > "$STATUS_DIR/p$idx"
}
rm -rf "$JVM_DIRS_ROOT"
mkdir -p "$STATUS_DIR"
echo "Runner $TEST_RUNNER_INDEX of $TEST_RUNNER_COUNT: running $TEST_JVMS_PER_RUNNER concurrent JVMs for partition(s) ${INDEXES[*]} of $PARTITION_TOTAL (-Xmx$TEST_HEAP_PER_JVM each)"
for idx in "${INDEXES[@]}"; do
prepare_jvm_dir "$JVM_DIRS_ROOT/partition-$idx"
done
for idx in "${INDEXES[@]}"; do
run_partition "$idx" "$JVM_DIRS_ROOT/partition-$idx" &
done
wait
overall=0
for idx in "${INDEXES[@]}"; do
rc="$(cat "$STATUS_DIR/p$idx" 2>/dev/null || echo 1)"
echo "partition $idx exited $rc"
[ "$rc" -eq 0 ] || overall=1
done
exit "$overall"

140
.github/scripts/stats-import.ts vendored Normal file
View File

@@ -0,0 +1,140 @@
// Pushes stats rows to eng-stats-importer, which writes them to Postgres.
//
// The importer's origin comes from ENG_STATS_URL and its key from API_KEY, both
// repository secrets — this repo is public, so neither is hardcoded here. Visit
// the importer to see the tables and mint keys.
// Transient failures worth retrying: throttling and server-side errors. A 4xx
// (bad request, auth, unknown table) won't succeed on retry, so those fail fast.
const RETRYABLE_STATUS = new Set([429, 500, 502, 503, 504]);
/**
* One row, keyed by column. Values are `unknown` rather than a scalar union
* because a `json` column takes arbitrary nested data.
*/
export type StatsRow = Record<string, unknown>;
export interface ImportStatsOptions {
/** Table name as it appears in `/api/import/{table}`, e.g. `emotion_files`. */
table: string;
rows: StatsRow[];
/** Importer origin. Defaults to ENG_STATS_URL. */
baseUrl?: string;
/** Extra attempts after the first, so the default 2 means up to 3 tries. */
retries?: number;
retryDelayMs?: number;
/** Per-attempt total deadline; aborts a stalled request. */
timeoutMs?: number;
}
export interface ImportStatsResult {
success: true;
inserted?: number;
/** Payload keys with no matching column, when `ignoreUnknown` is in play. */
ignoredKeys?: string[];
}
class ImportError extends Error {
retryable: boolean;
constructor(message: string, { retryable }: { retryable: boolean }) {
super(message);
this.retryable = retryable;
}
}
async function attemptImport(
url: string,
rows: StatsRow[],
timeoutMs: number,
): Promise<ImportStatsResult> {
let response: Response;
try {
response = await fetch(url, {
method: "PUT",
headers: {
"x-api-key": process.env.API_KEY ?? "",
"content-type": "application/json",
},
body: JSON.stringify(rows),
// Without this the request can hang indefinitely on a stalled server,
// eating the whole job timeout. An abort surfaces below as a retryable
// network error, so it retries with backoff instead.
signal: AbortSignal.timeout(timeoutMs),
});
} catch (networkError) {
const message =
networkError instanceof Error ? networkError.message : String(networkError);
throw new ImportError(message, { retryable: true });
}
if (!response.ok) {
// Failures carry an `{ error }` body naming the offending row and column,
// which is the only way to tell a type mismatch from a typo'd key.
const body = await response.text().catch(() => "");
throw new ImportError(
`Import failed: ${response.status} ${response.statusText} ${body}`.trim(),
{ retryable: RETRYABLE_STATUS.has(response.status) },
);
}
// Best-effort: the row count is for logging, so a body that doesn't parse
// shouldn't turn a successful import into a failure.
const result = (await response.json().catch(() => ({}))) as {
inserted?: number;
ignoredKeys?: string[];
};
return { success: true, inserted: result.inserted, ignoredKeys: result.ignoredKeys };
}
const sleep = (ms: number) => new Promise((resolve) => setTimeout(resolve, ms));
/**
* Imports `rows` into the `table` table, retrying transient API errors with
* exponential backoff.
*
* Keys are matched leniently against the table's columns -- `Emotion Files`,
* `emotionFiles` and `emotion_files` all land in `emotion_files` -- but values
* are matched strictly, and a key matching no column is an error rather than a
* silent drop. Rows are appended; the importer has no replace mode.
*
* Throws the last error once attempts are exhausted or the error is
* non-retryable.
*/
export async function importStats({
table,
rows,
baseUrl = process.env.ENG_STATS_URL,
retries = 2,
retryDelayMs = 1000,
timeoutMs = 60_000,
}: ImportStatsOptions): Promise<ImportStatsResult> {
// The importer accepts an empty payload, but there's no point spending a
// request (and a rate-limit slot) to insert nothing.
if (rows.length === 0) {
return { success: true, inserted: 0 };
}
if (!baseUrl) {
throw new Error("ENG_STATS_URL is not set, so there is no importer to push to");
}
// Tolerate a trailing slash: the origin comes from a hand-entered secret.
const url = `${baseUrl.replace(/\/+$/, "")}/api/import/${table}`;
for (let attempt = 0; ; attempt++) {
try {
return await attemptImport(url, rows, timeoutMs);
} catch (error) {
const importError = error as ImportError;
if (!importError.retryable || attempt >= retries) {
throw error;
}
const delay = retryDelayMs * 2 ** attempt;
console.warn(
`Import attempt ${attempt + 1} failed (${importError.message}); retrying in ${delay}ms`,
);
await sleep(delay);
}
}
}

View File

@@ -0,0 +1,160 @@
import { importStats } from "./stats-import";
const ok = (body: unknown = { inserted: 1 }) => ({ ok: true, json: async () => body });
const fail = (status: number) => ({
ok: false,
status,
statusText: "err",
text: async () => "",
});
const load = (over: Record<string, unknown> = {}) =>
importStats({
baseUrl: "https://stats.example.com",
table: "emotion_files",
rows: [{ a: 1 }],
retryDelayMs: 1,
...over,
});
describe("importStats requests", () => {
afterEach(() => {
// @ts-expect-error -- removing the stub the tests installed
delete global.fetch;
delete process.env.API_KEY;
delete process.env.ENG_STATS_URL;
});
it("defaults the origin to ENG_STATS_URL", async () => {
const fetchMock = jest.fn().mockResolvedValue(ok());
global.fetch = fetchMock;
process.env.ENG_STATS_URL = "https://importer.example.com";
await load({ baseUrl: undefined });
expect(fetchMock.mock.calls[0][0]).toBe(
"https://importer.example.com/api/import/emotion_files",
);
});
it("tolerates a trailing slash on the origin", async () => {
const fetchMock = jest.fn().mockResolvedValue(ok());
global.fetch = fetchMock;
await load({ baseUrl: "https://importer.example.com/" });
expect(fetchMock.mock.calls[0][0]).toBe(
"https://importer.example.com/api/import/emotion_files",
);
});
it("fails loudly when no origin is configured", async () => {
const fetchMock = jest.fn();
global.fetch = fetchMock;
await expect(load({ baseUrl: undefined })).rejects.toThrow("ENG_STATS_URL is not set");
expect(fetchMock).not.toHaveBeenCalled();
});
it("PUTs the rows as JSON to the table's import endpoint", async () => {
const fetchMock = jest.fn().mockResolvedValue(ok());
global.fetch = fetchMock;
process.env.API_KEY = "secret";
await expect(load({ rows: [{ a: 1 }, { a: 2 }] })).resolves.toEqual({
success: true,
inserted: 1,
ignoredKeys: undefined,
});
const [url, options] = fetchMock.mock.calls[0];
expect(url).toBe("https://stats.example.com/api/import/emotion_files");
expect(options.method).toBe("PUT");
expect(options.headers).toMatchObject({
"x-api-key": "secret",
"content-type": "application/json",
});
expect(JSON.parse(options.body)).toEqual([{ a: 1 }, { a: 2 }]);
});
it("skips the request entirely when there are no rows", async () => {
const fetchMock = jest.fn();
global.fetch = fetchMock;
await expect(load({ rows: [] })).resolves.toEqual({ success: true, inserted: 0 });
expect(fetchMock).not.toHaveBeenCalled();
});
it("succeeds even if the response body does not parse", async () => {
global.fetch = jest.fn().mockResolvedValue({
ok: true,
json: async () => {
throw new Error("not json");
},
});
await expect(load()).resolves.toMatchObject({ success: true });
});
});
describe("importStats retries", () => {
afterEach(() => {
// @ts-expect-error -- removing the stub the tests installed
delete global.fetch;
});
it("retries transient server errors then succeeds", async () => {
const fetchMock = jest
.fn()
.mockResolvedValueOnce(fail(503))
.mockResolvedValueOnce(fail(500))
.mockResolvedValueOnce(ok());
global.fetch = fetchMock;
await expect(load({ retries: 2 })).resolves.toMatchObject({ success: true });
expect(fetchMock).toHaveBeenCalledTimes(3);
});
it("retries throttling", async () => {
const fetchMock = jest.fn().mockResolvedValueOnce(fail(429)).mockResolvedValueOnce(ok());
global.fetch = fetchMock;
await expect(load({ retries: 2 })).resolves.toMatchObject({ success: true });
expect(fetchMock).toHaveBeenCalledTimes(2);
});
it("retries network errors", async () => {
const fetchMock = jest
.fn()
.mockRejectedValueOnce(new Error("ECONNRESET"))
.mockResolvedValueOnce(ok());
global.fetch = fetchMock;
await expect(load({ retries: 2 })).resolves.toMatchObject({ success: true });
expect(fetchMock).toHaveBeenCalledTimes(2);
});
it("gives up after exhausting retries and throws the last error", async () => {
const fetchMock = jest.fn().mockResolvedValue(fail(500));
global.fetch = fetchMock;
await expect(load({ retries: 2 })).rejects.toThrow("Import failed: 500");
expect(fetchMock).toHaveBeenCalledTimes(3); // 1 initial + 2 retries
});
it("does not retry a non-transient 4xx", async () => {
const fetchMock = jest.fn().mockResolvedValue(fail(400));
global.fetch = fetchMock;
await expect(load({ retries: 2 })).rejects.toThrow("Import failed: 400");
expect(fetchMock).toHaveBeenCalledTimes(1);
});
it("does not retry an unknown table", async () => {
const fetchMock = jest.fn().mockResolvedValue(fail(404));
global.fetch = fetchMock;
await expect(load({ retries: 2 })).rejects.toThrow("Import failed: 404");
expect(fetchMock).toHaveBeenCalledTimes(1);
});
});

View File

@@ -1,11 +1,11 @@
// Appends the test-plan stats row produced by create-test-plan.ts to the
// "FE Affected Tests" table on stats.metabase.com.
// Reads STATS_JSON, TRIGGERED_BY, PR_NUMBER, HEAD_SHA, BASE_SHA, API_KEY from env.
// "FE Affected Tests" table in eng-stats-importer.
// Reads STATS_JSON, PR_NUMBER, HEAD_SHA, BASE_SHA, API_KEY from env.
const { uploadCsvToMb } = require("./csv-to-mb.js");
import type { TestPlanStats } from "./affected-tests";
import { importStats } from "./stats-import";
// "FE Affected Tests" uploaded table on stats.metabase.com.
const TABLE_ID = 81818;
const TABLE = "fe_affected_tests";
async function main() {
// create-test-plan doesn't always produce stats (e.g. on release branches
@@ -16,13 +16,13 @@ async function main() {
return;
}
const s = JSON.parse(raw);
const s = JSON.parse(raw) as TestPlanStats;
console.log("stats", s);
const row = {
Date: new Date().toISOString(),
// "pr_update" or "merge_to_master". ("Trigger" is a reserved SQL word.)
"Triggered By": process.env.TRIGGERED_BY,
// ("Trigger" is a reserved SQL word.)
"Triggered By": "pr_update",
PR: Number(process.env.PR_NUMBER),
"Head SHA": process.env.HEAD_SHA,
"Base SHA": process.env.BASE_SHA,
@@ -43,17 +43,15 @@ async function main() {
"Loki Stories All": s.loki_stories_all,
"Loki Stories To Run (Rules)": s.loki_stories_to_run_rules,
"Loki Stories To Run (Usage)": s.loki_stories_to_run_usage,
"E2E Specs All": s.e2e_specs_all,
"E2E Specs To Run (Rules)": s.e2e_specs_to_run_rules,
"E2E Specs To Run (Usage)": s.e2e_specs_to_run_usage,
// Spelled as the column name rather than a display name: the importer
// splits a digit-then-capital run, so "E2E Specs All" would normalize to
// `e2_e_specs_all` instead of `e2e_specs_all`.
e2e_specs_all: s.e2e_specs_all,
e2e_specs_to_run_rules: s.e2e_specs_to_run_rules,
e2e_specs_to_run_usage: s.e2e_specs_to_run_usage,
};
await uploadCsvToMb({
baseUrl: "https://stats.metabase.com",
tableId: TABLE_ID,
jsonData: [row],
mode: "append",
});
await importStats({ table: TABLE, rows: [row] });
console.log("Data uploaded successfully");
}

View File

@@ -0,0 +1,97 @@
// Appends the measured load times to the "Bundle Load Times" table in
// eng-stats-importer. Reads ROWS (the JSON matrix.js prints) and API_KEY from
// env, and stamps each row with the commit it came from.
import { readFileSync } from "node:fs";
import { importStats } from "./stats-import";
/** One condition, as `frontend/test/bench/matrix.ts` reports it. */
interface Condition {
network: string;
networkMbps: number;
latencyMs: number;
cpu: string;
cpuThrottle: number;
coldMs: number;
warmMs: number;
steadyMs: number;
coldSpreadPercent: number;
coldTtfbMs: number;
coldFirstPaintMs: number;
coldAppMountedMs: number;
coldLargestPaintMs: number;
coldPageReadyMs: number;
warmPageReadyMs: number;
scripts: number;
scriptKb: number;
runs: number;
}
interface CommitStamp {
sha: string;
subject: string;
}
type LoadTimeRow = Record<string, string | number>;
function buildRows(
conditions: Condition[],
{ sha, subject }: CommitStamp,
): LoadTimeRow[] {
return conditions.map((condition) => ({
Date: new Date().toISOString().slice(0, 10),
// Truncated the same way the bundle-size table does, so the two join.
Commit: sha.slice(0, 12),
// The stats table carries a free-text Description column. Populate it with
// the commit subject so the chart's points are self-describing.
Description: subject.split("\n")[0],
Network: condition.network,
"Network mbps": condition.networkMbps,
"Latency ms": condition.latencyMs,
CPU: condition.cpu,
"CPU throttle": condition.cpuThrottle,
"Cold ms": condition.coldMs,
"Warm ms": condition.warmMs,
"Steady ms": condition.steadyMs,
"Cold spread %": condition.coldSpreadPercent,
// The cold load broken up. A zero means the browser or the route never
// reported that one, rather than that it happened at time zero.
"Cold ttfb ms": condition.coldTtfbMs,
"Cold first paint ms": condition.coldFirstPaintMs,
"Cold app mounted ms": condition.coldAppMountedMs,
"Cold largest paint ms": condition.coldLargestPaintMs,
"Cold page ready ms": condition.coldPageReadyMs,
"Warm page ready ms": condition.warmPageReadyMs,
Scripts: condition.scripts,
"Script kb": condition.scriptKb,
Runs: condition.runs,
}));
}
async function main() {
const path = process.env.ROWS || "artifacts/load-times.json";
// matrix.js wrote this file, and Condition is the shape it prints.
const conditions = JSON.parse(readFileSync(path, "utf8")) as Condition[];
const rows = buildRows(conditions, {
sha: process.env.HEAD_SHA || "",
subject: process.env.COMMIT_MESSAGE || "",
});
console.table(rows);
try {
await importStats({ table: "bundle_load_times", rows });
console.log("Load times uploaded successfully");
} catch (error) {
// Stats logging is best-effort. A point lost to an unreachable importer is
// worth less than a red build on master, and the next commit plots another.
const message = error instanceof Error ? error.message : String(error);
console.log(
`::warning::Load-time upload failed after retries; leaving run green: ${message}`,
);
}
}
main();

View File

@@ -0,0 +1,38 @@
// Appends the measured bundle sizes (with deltas) to the "Bundle Sizes" table
// in eng-stats-importer. Reads ROWS (a JSON file of rows) and API_KEY from env,
// and reports whether the import landed via the `uploaded` step output.
import { appendFileSync, readFileSync } from "node:fs";
import { importStats, type StatsRow } from "./stats-import";
/** `core.setOutput` without the github-script runtime. */
function setOutput(name: string, value: string) {
const file = process.env.GITHUB_OUTPUT;
if (file) {
appendFileSync(file, `${name}=${value}\n`);
}
}
async function main() {
const rowsPath = process.env.ROWS || "artifacts/upload-rows.json";
const rows = JSON.parse(readFileSync(rowsPath, "utf8")) as StatsRow[];
console.table(rows);
try {
await importStats({ table: "bundle_sizes", rows });
console.log("Bundle sizes uploaded successfully");
setOutput("uploaded", "true");
} catch (error) {
// Stats logging is best-effort: if the importer is still unreachable after
// the client's retries, keep the run green. The last-plotted cache is only
// saved on a successful upload, so this point is re-attempted on the next
// master build and nothing is silently dropped.
const message = error instanceof Error ? error.message : String(error);
console.log(`::warning::Bundle-size upload failed after retries; leaving run green: ${message}`);
setOutput("uploaded", "false");
}
}
main();

25
.github/scripts/upload-emotion-stats.ts vendored Normal file
View File

@@ -0,0 +1,25 @@
// Appends the weekly @emotion/* importer count to the "Emotion Files" table in
// eng-stats-importer. Reads EMOTION_FILES and API_KEY from env.
import { importStats } from "./stats-import";
async function main() {
console.log("EMOTION_FILES", Number(process.env.EMOTION_FILES));
// Keys must match the target table's columns (the importer normalizes both
// sides, so casing/spacing is forgiving).
const rows = [
{
Date: new Date().toISOString().slice(0, 10), // YYYY-MM-DD
"Emotion Files": Number(process.env.EMOTION_FILES),
},
];
await importStats({ table: "emotion_stats", rows });
console.log("Data uploaded successfully");
}
main().catch((error) => {
console.error("Error uploading data:", error);
process.exit(1);
});

View File

@@ -0,0 +1,30 @@
// Appends the weekly module-boundary counts to the "Module Boundaries" table in
// eng-stats-importer. Reads NAMED_MODULES, ENFORCED_MODULES, UNMODULED,
// VIOLATIONS and API_KEY from env.
import { importStats } from "./stats-import";
async function main() {
console.log("NAMED_MODULES", Number(process.env.NAMED_MODULES));
console.log("ENFORCED_MODULES", Number(process.env.ENFORCED_MODULES));
console.log("UNMODULED", Number(process.env.UNMODULED));
console.log("VIOLATIONS", Number(process.env.VIOLATIONS));
const rows = [
{
Date: new Date().toISOString().slice(0, 10), // YYYY-MM-DD
Modules: Number(process.env.NAMED_MODULES),
"Enforced modules": Number(process.env.ENFORCED_MODULES),
"Unmoduled folders": Number(process.env.UNMODULED),
Violations: Number(process.env.VIOLATIONS),
},
];
await importStats({ table: "module_boundaries", rows });
console.log("Data uploaded successfully");
}
main().catch((error) => {
console.error("Error uploading data:", error);
process.exit(1);
});

11
.github/team.json vendored
View File

@@ -56,17 +56,15 @@
"label": ".Team/Metabot",
"members": [
"appleby",
"noahmoss",
"retro",
"sloansparger",
"somtom",
"tsplude",
"lbrdnk",
"piranha",
"crisptrutski",
"undrfined",
"andreis",
"prascuna"
"prascuna",
"krever"
]
},
{
@@ -113,7 +111,10 @@
"uladzimirdev",
"egorgrushin",
"metatyb",
"olehk-mb"
"olehk-mb",
"annatomka",
"brybacki",
"BillyBobFry"
]
},
{

View File

@@ -1,5 +1,5 @@
name: AI Benchmark
run-name: "dispatch evals · ${{ github.event_name == 'pull_request' && format('smoke PR#{0}', github.event.pull_request.number) || (inputs.pr != '' && format('PR#{0}', inputs.pr) || (inputs.ref != '' && inputs.ref || 'master')) }}"
run-name: "Evals · ${{ github.event_name == 'pull_request' && github.event.label.name || format('manual · {0}', inputs.scope) }} · ${{ github.event.pull_request.number || inputs.pr || inputs.ref || github.sha }}"
on:
pull_request:
@@ -11,14 +11,23 @@ on:
required: false
default: ""
ref:
description: "Metabase ref"
description: "Metabase branch, tag or sha (resolved to a full sha; overrides the PR head, and must sit on the PR's branch when both are given)"
required: false
default: ""
scope:
description: "Scope"
required: true
type: choice
options: [smoke, full, "all (EXPENSIVE)"]
options:
- smoke
- full
- embarrassing-plain
- embarrassing-human
- embarrassing-all
- goldens-plain
- goldens-human
- goldens-all
- "all (EXPENSIVE)"
default: smoke
sample:
description: "Sample (0 = full suite)"
@@ -29,99 +38,202 @@ on:
default: main
concurrency:
group: evals-dispatch-${{ (github.event.label.name == 'evals/smoke' && github.event.pull_request.number) || github.run_id }}
group: evals-dispatch-${{ github.event_name == 'pull_request' && format('{0}-{1}', github.event.pull_request.number, github.event.label.name) || github.run_id }}
cancel-in-progress: true
jobs:
unsupported:
prepare:
if: >-
github.event_name == 'pull_request'
&& github.event.label.name == 'evals/smoke'
&& github.event.pull_request.head.repo.full_name != github.repository
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
(github.event_name == 'pull_request'
&& github.event.pull_request.head.repo.full_name == github.repository
&& startsWith(github.event.label.name, 'evals:'))
|| github.event_name == 'workflow_dispatch'
runs-on: ${{ vars.SLIM_RUNNER_KEY }}
timeout-minutes: 5
outputs:
pr: ${{ steps.prepare.outputs.pr }}
ref: ${{ steps.prepare.outputs.ref }}
scope: ${{ steps.prepare.outputs.scope }}
sample: ${{ steps.prepare.outputs.sample }}
label: ${{ steps.prepare.outputs.label }}
evals_branch: ${{ steps.prepare.outputs.evals_branch }}
steps:
- run: |
echo "::error::evals/smoke only runs on same-repo PRs; this PR's head is on a fork"
exit 1
- name: Prepare
id: prepare
env:
EVENT_NAME: ${{ github.event_name }}
LABEL_PR: ${{ github.event.pull_request.number }}
LABEL: ${{ github.event.label.name }}
INPUT_PR: ${{ inputs.pr }}
INPUT_REF: ${{ inputs.ref }}
INPUT_SCOPE: ${{ inputs.scope }}
INPUT_SAMPLE: ${{ inputs.sample }}
INPUT_EVALS_BRANCH: ${{ inputs.evals_branch }}
run: |
set -euo pipefail
# The two paths are mutually exclusive, and `on:` admits no other trigger.
if [[ "$EVENT_NAME" == 'pull_request' ]]; then
SCOPE="${LABEL#evals:}"
case "$SCOPE" in
embarrassing-plain|embarrassing-human|embarrassing-all|goldens-plain|goldens-human|goldens-all)
SAMPLE='0' ;;
smoke|full)
SAMPLE='5' ;;
*)
echo "::error::'${LABEL}' is not a known evals trigger label; add its scope here and to the workflow's \`scope\` options, or remove the label"
exit 1 ;;
esac
PR="$LABEL_PR"; REF=''; EVALS_BRANCH='main'
else
PR="$INPUT_PR"; REF="$INPUT_REF"; SCOPE="$INPUT_SCOPE"
SAMPLE="${INPUT_SAMPLE:-5}"; EVALS_BRANCH="$INPUT_EVALS_BRANCH"
LABEL='' # nothing to consume: a manual dispatch was not triggered by a label
fi
# None of these is ever multi-line; a newline would forge extra output entries.
for v in PR REF SCOPE SAMPLE LABEL EVALS_BRANCH; do
if [[ "${!v}" == *$'\n'* ]]; then
echo "::error::${v} must be a single line"
exit 1
fi
done
{
echo "pr=$PR"
echo "ref=$REF"
echo "scope=$SCOPE"
echo "sample=$SAMPLE"
echo "label=$LABEL"
echo "evals_branch=$EVALS_BRANCH"
} >> "$GITHUB_OUTPUT"
announce:
if: >-
github.event_name == 'pull_request'
&& github.event.label.name == 'evals/smoke'
&& github.event.pull_request.head.repo.full_name == github.repository
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
needs: prepare
if: github.event_name == 'pull_request'
runs-on: ${{ vars.SLIM_RUNNER_KEY }}
timeout-minutes: 5
outputs:
comment_id: ${{ steps.post.outputs.comment_id }}
steps:
- name: Comment (building)
id: post
env:
SCOPE: ${{ needs.prepare.outputs.scope }}
uses: actions/github-script@v9
with:
github-token: ${{ secrets.METABASE_AUTOMATION_USER_TOKEN }}
script: |
const runUrl = `${context.serverUrl}/${context.repo.owner}/${context.repo.repo}/actions/runs/${context.runId}`;
const body = `🤖 **Evals smoke** — ⏳ building the image… ([logs](${runUrl}))`;
const prefix = `🤖 **Evals (${process.env.SCOPE})**`;
const body = `${prefix} — ⏳ building the image… ([logs](${runUrl}))`;
const { owner, repo } = context.repo;
const issue_number = context.payload.pull_request.number;
// Drop earlier verdicts first: they describe shas that are no longer head, and a stale
// green one reads as this PR passing. The prefix survives eval-run's rewrites.
// Drop this scope's earlier verdicts first: they describe shas that are no longer head,
// and a stale green one reads as this PR passing. Only this scope's, though — a sibling
// scope's comment is a live report on a run still going.
const existing = await github.paginate(github.rest.issues.listComments, { owner, repo, issue_number });
for (const c of existing.filter(c => c.body.startsWith('🤖 **Evals'))) {
// The second form is what the single `evals/smoke` trigger wrote before the labels were
// split per scope; nothing writes it any more, so this clause is only here to tidy PRs
// that predate the split and can go once none are open.
const stale = c => c.body.startsWith(prefix) || c.body.startsWith('🤖 **Evals smoke**');
for (const c of existing.filter(stale)) {
await github.rest.issues.deleteComment({ owner, repo, comment_id: c.id }).catch(() => {});
}
const { data } = await github.rest.issues.createComment({ owner, repo, issue_number, body });
core.setOutput('comment_id', String(data.id));
uberjar:
needs: [announce]
if: >-
github.event_name == 'pull_request'
&& github.event.label.name == 'evals/smoke'
&& github.event.pull_request.head.repo.full_name == github.repository
uses: ./.github/workflows/uberjar.yml
secrets: inherit
smoke:
needs: [announce, uberjar]
if: >-
github.event_name == 'pull_request'
&& github.event.label.name == 'evals/smoke'
&& github.event.pull_request.head.repo.full_name == github.repository
resolve:
needs: prepare
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
timeout-minutes: 5
env:
COMMENT_ID: ${{ needs.announce.outputs.comment_id }}
permissions:
contents: read
pull-requests: read
outputs:
sha: ${{ steps.sha.outputs.sha }}
steps:
- name: Dispatch smoke eval-run
- name: Resolve pr/ref to a full commit sha
id: sha
env:
GH_TOKEN: ${{ github.token }}
PR: ${{ needs.prepare.outputs.pr }}
REF: ${{ needs.prepare.outputs.ref }}
DEFAULT_SHA: ${{ github.sha }}
run: |
set -euo pipefail
# `ref` wins over `pr`, matching evals' eval-run.yml, which this dispatches into — same two
# inputs with opposite precedence in chained workflows would be a trap. eval-run also
# rejects a ref that doesn't sit on the PR's branch; that check stays there rather than
# being duplicated here.
if [[ -n "$REF" ]]; then
# `ref` accepts a branch or tag; fetch-artifact and the image tag need a full sha.
SHA=$(gh api "repos/${GITHUB_REPOSITORY}/commits/${REF}" --jq .sha)
echo "ref ${REF} -> ${SHA}"
elif [[ -n "$PR" ]]; then
SHA=$(gh api "repos/${GITHUB_REPOSITORY}/pulls/${PR}" --jq .head.sha)
echo "PR #${PR} head -> ${SHA}"
else
SHA="$DEFAULT_SHA"
echo "neither pr nor ref given; using this run's commit -> ${SHA}"
fi
if [[ ! "$SHA" =~ ^[0-9a-f]{40}$ ]]; then
echo "::error::could not resolve a full commit sha (got '${SHA}')"
exit 1
fi
echo "sha=${SHA}" >> "$GITHUB_OUTPUT"
image:
needs: resolve
uses: ./.github/workflows/build-private-ee-docker-image.yml
secrets:
PR_ENV_IAM_ROLE: ${{ secrets.PR_ENV_IAM_ROLE }}
PR_ENV_AWS_ACCOUNT_ID: ${{ secrets.PR_ENV_AWS_ACCOUNT_ID }}
with:
commit: ${{ needs.resolve.outputs.sha }}
dispatch:
needs: [prepare, announce, resolve, image]
if: >-
!cancelled()
&& needs.prepare.result == 'success'
&& (needs.announce.result == 'success' || needs.announce.result == 'skipped')
&& needs.resolve.result == 'success'
&& needs.image.result == 'success'
timeout-minutes: 5
runs-on: ${{ vars.SLIM_RUNNER_KEY }}
steps:
- name: Dispatch eval-run
env:
GH_TOKEN: ${{ secrets.METABASE_AUTOMATION_USER_TOKEN }}
PR: ${{ github.event.pull_request.number }}
HEAD_SHA: ${{ github.event.pull_request.head.sha }}
EVALS_BRANCH: main
EVALS_BRANCH: ${{ needs.prepare.outputs.evals_branch }}
PR: ${{ needs.prepare.outputs.pr }}
SHA: ${{ needs.resolve.outputs.sha }}
SCOPE: ${{ needs.prepare.outputs.scope }}
SAMPLE: ${{ needs.prepare.outputs.sample }}
LABEL: ${{ needs.prepare.outputs.label }}
COMMENT_ID: ${{ needs.announce.outputs.comment_id }}
run: |
# `label` is the one eval-run consumes once it has taken the run over; empty on a manual
# dispatch, where there is nothing to consume.
gh api repos/metabase/evals/actions/workflows/eval-run.yml/dispatches \
-f ref="$EVALS_BRANCH" \
-f "inputs[pr]=$PR" \
-f "inputs[ref]=$HEAD_SHA" \
-f "inputs[scope]=smoke" \
-f "inputs[ref]=$SHA" \
-f "inputs[scope]=$SCOPE" \
-f "inputs[surfaces]=all" \
-f "inputs[sample]=5" \
-f "inputs[sample]=$SAMPLE" \
-f "inputs[label]=$LABEL" \
-f "inputs[evals_branch]=$EVALS_BRANCH" \
-f "inputs[comment_id]=$COMMENT_ID"
finalize:
# If the build or dispatch fell over, eval-run never took over the comment — leave a
# failure verdict instead of a comment stuck at "building the image…".
needs: [announce, uberjar, smoke]
if: always() && needs.announce.result == 'success' && needs.smoke.result != 'success'
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
needs: [prepare, announce, resolve, image, dispatch]
if: always() && needs.announce.result == 'success' && needs.dispatch.result != 'success'
runs-on: ${{ vars.SLIM_RUNNER_KEY }}
timeout-minutes: 5
env:
COMMENT_ID: ${{ needs.announce.outputs.comment_id }}
SMOKE_RESULT: ${{ needs.smoke.result }}
UBERJAR_RESULT: ${{ needs.uberjar.result }}
SCOPE: ${{ needs.prepare.outputs.scope }}
LABEL: ${{ needs.prepare.outputs.label }}
NEEDS_JSON: ${{ toJSON(needs) }}
steps:
- name: Comment (build/dispatch failed)
uses: actions/github-script@v9
@@ -129,11 +241,12 @@ jobs:
github-token: ${{ secrets.METABASE_AUTOMATION_USER_TOKEN }}
script: |
const runUrl = `${context.serverUrl}/${context.repo.owner}/${context.repo.repo}/actions/runs/${context.runId}`;
// A concurrency-cancelled retrigger lands here too; don't stamp it as an infra failure.
const cancelled = [process.env.SMOKE_RESULT, process.env.UBERJAR_RESULT].includes('cancelled');
const cancelled = Object.values(JSON.parse(process.env.NEEDS_JSON))
.some(j => j.result === 'cancelled');
const prefix = `🤖 **Evals (${process.env.SCOPE})**`;
const body = cancelled
? `🤖 **Evals smoke** — ⚪ cancelled before evals started ([logs](${runUrl}))`
: `🤖 **Evals smoke** — ❌ build or dispatch failed before evals started ([logs](${runUrl}))`;
? `${prefix} — ⚪ cancelled before evals started ([logs](${runUrl}))`
: `${prefix} — ❌ build or dispatch failed before evals started ([logs](${runUrl}))`;
// The replacement run deletes this comment on its way in, so a concurrency cancel can
// land here with nothing to patch. Losing the stamp is fine; failing the job isn't.
await github.rest.issues.updateComment({
@@ -146,27 +259,5 @@ jobs:
await github.rest.issues.removeLabel({
owner: context.repo.owner, repo: context.repo.repo,
issue_number: context.payload.pull_request.number,
name: 'evals/smoke',
name: process.env.LABEL,
}).catch(() => {});
dispatch:
if: github.event_name == 'workflow_dispatch'
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
timeout-minutes: 5
steps:
- name: Dispatch eval-run
env:
GH_TOKEN: ${{ secrets.METABASE_AUTOMATION_USER_TOKEN }}
EVALS_BRANCH: ${{ github.event.inputs.evals_branch }}
PR: ${{ inputs.pr }}
REF: ${{ inputs.ref }}
SCOPE: ${{ inputs.scope }}
SAMPLE: ${{ inputs.sample }}
run: |
gh api repos/metabase/evals/actions/workflows/eval-run.yml/dispatches \
-f ref="$EVALS_BRANCH" \
-f "inputs[pr]=$PR" \
-f "inputs[ref]=$REF" \
-f "inputs[scope]=$SCOPE" \
-f "inputs[sample]=${SAMPLE:-5}" \
-f "inputs[evals_branch]=$EVALS_BRANCH"

View File

@@ -6,6 +6,34 @@ on:
skip:
type: boolean
default: false
force-run:
description: Run the full suite regardless of the diff (master / release branches).
type: boolean
default: false
# Run one app-DB job on demand, against the ref you dispatch on, optionally under a profiler.
# Everything else about the job -- services, matrix legs, test args, quarantine gating -- is
# whatever the normal CI run uses, because it is the same job.
workflow_dispatch:
inputs:
app-db:
description: 'Which app-DB job to run. Only this one runs; the others are skipped.'
type: choice
required: true
options:
- mariadb
- mysql
- postgres
tests:
description: 'Optional: run only these tests, comma- or space-separated, e.g. metabase.db.custom-migrations-test/some-test. Bare namespaces work too. Blank runs the job''s usual set.'
type: string
required: false
default: ''
profile:
description: 'Profile the test run and attach a flamegraph to the job. Adds sampling overhead.'
type: boolean
required: false
default: false
concurrency:
group: ${{ github.workflow }}-${{ github.head_ref && github.ref || github.run_id }}-app-db
@@ -15,28 +43,105 @@ concurrency:
# ci-conductor (secrets: inherit is already set on the app-db call in
# run-tests.yml). See DEV-2224.
env:
CI_CONDUCTOR_BASE_URL: ${{ secrets.CI_CONDUCTOR_BASE_URL }}
CI_CONDUCTOR_BASE_URL: ${{ vars.CI_CONDUCTOR_BASE_URL }}
CI_CONDUCTOR_WEBHOOK_SECRET: ${{ secrets.CI_CONDUCTOR_WEBHOOK_SECRET }}
# Both read by the test-driver action, which is what actually runs the tests. Set here rather than
# passed as inputs to each job so that turning either on is one line, not one line per job.
# Empty (and so off) on workflow_call, where neither input exists.
#
# ONLY_TESTS replaces the job's own test selection, so every matrix leg of the chosen job runs the
# whole list -- each app DB has three.
PROFILE_TESTS: ${{ inputs.profile }}
ONLY_TESTS: ${{ inputs.tests }}
jobs:
be-tests-mariadb:
app-db-matrix:
if: ${{ !inputs.skip }}
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
timeout-minutes: 5
name: Determine app DB versions
outputs:
mariadb: ${{ steps.versions.outputs.mariadb }}
mysql: ${{ steps.versions.outputs.mysql }}
postgres: ${{ steps.versions.outputs.postgres }}
steps:
- name: Select versions to test
id: versions
uses: actions/github-script@v9
env:
RUN_ALL: ${{ inputs.force-run }}
with:
script: | # js
const runAll = process.env.RUN_ALL === 'true';
const versions = {
mariadb: [
{
name: 'MariaDB 10.6',
image: 'metabase/mariadb:10.6',
'junit-name': 'be-tests-mariadb-10-6-ee',
env: { 'enable-ssl-tests': 'false' },
latest: false
},
{
name: 'MariaDB Latest',
image: 'mariadb:latest',
'junit-name': 'be-tests-mariadb-latest-ee',
env: { 'enable-ssl-tests': 'false' },
latest: true
},
],
mysql: [
{
name: 'MySQL 8.0',
image: 'mysql:8.0',
'junit-name': 'be-tests-mysql-8-0-ee',
env: { 'enable-ssl-tests': 'false', 'enable-aws-iam-tests': 'false' },
latest: false
},
{
name: 'MySQL 9',
image: 'mysql:9',
'junit-name': 'be-tests-mysql-9-ee',
env: { 'enable-ssl-tests': 'true', 'enable-aws-iam-tests': 'true' },
// treating 9.0 as latest until we introduce mysql 26+ support
latest: true
},
],
postgres: [
{
name: 'Postgres 14.x',
'junit-name': 'be-tests-postgres-ee',
image: 'postgres:14-alpine',
env: { 'enable-ssl-tests': 'false', 'enable-aws-iam-tests': 'false' },
latest: false,
},
{
name: 'Postgres Latest',
'junit-name': 'be-tests-postgres-latest-ee',
image: 'postgres:latest',
env: { 'enable-ssl-tests': 'true', 'enable-aws-iam-tests': 'true' },
latest: true,
},
],
};
for (const [db, dbVersions] of Object.entries(versions)) {
const selected = runAll ? dbVersions : dbVersions.filter((version) => version.latest);
core.info(`${db}: ${selected.map((version) => version.name).join(', ')}`);
core.setOutput(db, JSON.stringify(selected));
}
be-tests-mariadb:
needs: app-db-matrix
if: ${{ !inputs.skip && (inputs.app-db == '' || inputs.app-db == 'mariadb') }}
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
timeout-minutes: 40
strategy:
fail-fast: false
matrix:
version:
- name: MariaDB 10.6
junit-name: be-tests-mariadb-10-6-ee
image: metabase/mariadb:10.6 # https://github.com/metabase/metabase-mariadb-docker-image
env:
enable-ssl-tests: 'false'
- name: MariaDB Latest
junit-name: be-tests-mariadb-latest-ee
image: mariadb:latest
env:
enable-ssl-tests: 'false'
version: ${{ fromJSON(needs.app-db-matrix.outputs.mariadb) }}
job:
- name: Enterprise Tests
build-static-viz: false
@@ -70,21 +175,9 @@ jobs:
MARIADB_ALLOW_EMPTY_ROOT_PASSWORD: true
MARIADB_DATABASE: mb_test
env:
# Only run old migrations tests on pushes to master or release branches. All other branches should skip tests
# with the tag `mb/old-migrations-test`. `__ADDITIONAL_EXCLUDED_TAG__` is not used anywhere outside of splicing
# it in to the command below.
__ADDITIONAL_EXCLUDED_TAG__: >-
${{
(
github.event_name == 'push' &&
(
github.ref_name == 'master' ||
startsWith(github.ref_name, 'release-x')
) &&
''
) ||
':mb/old-migrations-test'
}}
# __ADDITIONAL_EXCLUDED_TAG__: ${{ !inputs.force-run && ':mb/old-migrations-test' || '' }}
# GDGT-3126: re-enable and properly fix old migrations tests
__ADDITIONAL_EXCLUDED_TAG__: ':mb/old-migrations-test'
# actual serious env vars below
CI: 'true'
DRIVERS: mysql
@@ -124,37 +217,16 @@ jobs:
test-args: >-
${{ matrix.job.test-args }}
:exclude-tags '[ ${{ matrix.job.exclude-tag }} ${{ env.__ADDITIONAL_EXCLUDED_TAG__ }}]'
quarantine-engine: ${{ vars.QUARANTINE_ENGINE }}
be-tests-mysql:
if: ${{ !inputs.skip }}
needs: app-db-matrix
if: ${{ !inputs.skip && (inputs.app-db == '' || inputs.app-db == 'mysql') }}
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
timeout-minutes: 40
strategy:
fail-fast: false
matrix:
version:
- name: MySQL 8.0
junit-name: be-tests-mysql-8-0-ee
image: mysql:8.0
env:
enable-ssl-tests: 'false'
enable-aws-iam-tests: 'false'
- name: MySQL 9
junit-name: be-tests-mysql-9-ee
image: mysql:9
env:
enable-ssl-tests: 'true'
enable-aws-iam-tests: 'true'
# `mysql:latest` now resolves to MySQL 26.x, which fails in a way that floods the log
# until the runner cancels the job. A cancelled job can't be soft-failed with
# continue-on-error, so the leg is disabled until 26.x is supported.
# - name: MySQL Latest
# junit-name: be-tests-mysql-latest-ee
# image: mysql:latest
# env:
# enable-ssl-tests: 'false'
# enable-aws-iam-tests: 'false'
version: ${{ fromJSON(needs.app-db-matrix.outputs.mysql) }}
job:
- name: Enterprise Tests
build-static-viz: false
@@ -188,21 +260,9 @@ jobs:
MYSQL_ALLOW_EMPTY_PASSWORD: true
MYSQL_DATABASE: mb_test
env:
# Only run old migrations tests on pushes to master or release branches. All other branches should skip tests
# with the tag `mb/old-migrations-test`. `__ADDITIONAL_EXCLUDED_TAG__` is not used anywhere outside of splicing
# it in to the command below.
__ADDITIONAL_EXCLUDED_TAG__: >-
${{
(
github.event_name == 'push' &&
(
github.ref_name == 'master' ||
startsWith(github.ref_name, 'release-x')
) &&
''
) ||
':mb/old-migrations-test'
}}
# __ADDITIONAL_EXCLUDED_TAG__: ${{ !inputs.force-run && ':mb/old-migrations-test' || '' }}
# GDGT-3126: re-enable and properly fix old migrations tests
__ADDITIONAL_EXCLUDED_TAG__: ':mb/old-migrations-test'
# actual serious env vars below
CI: 'true'
DRIVERS: mysql
@@ -250,28 +310,16 @@ jobs:
test-args: >-
${{ matrix.job.test-args }}
:exclude-tags '[ ${{ matrix.job.exclude-tag }} ${{ env.__ADDITIONAL_EXCLUDED_TAG__ }}]'
quarantine-engine: ${{ vars.QUARANTINE_ENGINE }}
be-tests-postgres:
if: ${{ !inputs.skip }}
needs: app-db-matrix
if: ${{ !inputs.skip && (inputs.app-db == '' || inputs.app-db == 'postgres') }}
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
timeout-minutes: 40
strategy:
fail-fast: false
matrix:
version:
- name: Postgres 14.x
junit-name: postgres-ee
docker-image: postgres:14-alpine
env:
enable-ssl-tests: 'false'
enable-aws-iam-tests: 'false'
- name: Postgres Latest
junit-name: postgres-latest-ee
docker-image: postgres:latest
env:
enable-ssl-tests: 'true'
enable-aws-iam-tests: 'true'
version: ${{ fromJSON(needs.app-db-matrix.outputs.postgres) }}
job:
- name: Enterprise Tests
build-static-viz: false
@@ -282,7 +330,6 @@ jobs:
build-static-viz: true
test-args: >-
:only '"test"'
:exclude-tags [:mb/driver-tests]
:partition/total 2
:partition/index 0
exclude-tag: ':mb/driver-tests :mb/transforms-python-test'
@@ -295,21 +342,9 @@ jobs:
exclude-tag: ':mb/driver-tests :mb/transforms-python-test'
name: "${{ matrix.version.name }} ${{ matrix.job.name }}"
env:
# Only run old migrations tests on pushes to master or release branches. All other branches should skip tests
# with the tag `mb/old-migrations-test`. `__ADDITIONAL_EXCLUDED_TAG__` is not used anywhere outside of splicing
# it in to the command below.
__ADDITIONAL_EXCLUDED_TAG__: >-
${{
(
github.event_name == 'push' &&
(
github.ref_name == 'master' ||
startsWith(github.ref_name, 'release-x')
) &&
''
) ||
':mb/old-migrations-test'
}}
# __ADDITIONAL_EXCLUDED_TAG__: ${{ !inputs.force-run && ':mb/old-migrations-test' || '' }}
# GDGT-3126: re-enable and properly fix old migrations tests
__ADDITIONAL_EXCLUDED_TAG__: ':mb/old-migrations-test'
# actual serious env vars below
CI: 'true'
DRIVERS: postgres
@@ -332,7 +367,7 @@ jobs:
AWS_SECRET_ACCESS_KEY: ${{ secrets.AWS_AURORA_IAM_SECRET_ACCESS_KEY }}
services:
postgres:
image: ${{ matrix.version.docker-image }}
image: ${{ matrix.version.image }}
ports:
- "5432:5432"
env:
@@ -346,19 +381,19 @@ jobs:
uses: ./.github/actions/test-driver
with:
build-static-viz: ${{ matrix.job.build-static-viz }}
junit-name: 'be-tests-${{ matrix.version.junit-name }}'
junit-name: ${{ matrix.version.junit-name }}
artifact-suffix: ${{ matrix.job.name }}
test-args: >-
${{ matrix.job.test-args }}
:exclude-tags '[ ${{ matrix.job.exclude-tag }} ${{ env.__ADDITIONAL_EXCLUDED_TAG__ }}]'
quarantine-engine: ${{ vars.QUARANTINE_ENGINE }}
app-db-tests-result:
needs:
- app-db-matrix
- be-tests-mariadb
- be-tests-mysql
- be-tests-postgres
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
runs-on: ${{ vars.SLIM_RUNNER_KEY }}
timeout-minutes: 5
name: app-db-tests-result
if: always() && !cancelled()

View File

@@ -7,7 +7,8 @@ on:
jobs:
update_pr:
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
runs-on: ${{ vars.SLIM_RUNNER_KEY }}
timeout-minutes: 5
steps:
- uses: tibdex/github-app-token@3beb63f4bd073e61482598c45c71c1019b59b73a # v2.1.0

View File

@@ -17,7 +17,8 @@ on:
jobs:
setup-oss:
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
runs-on: ${{ vars.SLIM_RUNNER_KEY }}
timeout-minutes: 5
outputs:
modules: ${{ steps.get-modules.outputs.modules }}
steps:
@@ -64,7 +65,8 @@ jobs:
flags: back-end
setup-ee:
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
runs-on: ${{ vars.SLIM_RUNNER_KEY }}
timeout-minutes: 5
outputs:
modules: ${{ steps.get-modules.outputs.modules }}
steps:

View File

@@ -6,6 +6,38 @@ on:
skip:
type: boolean
default: false
force-run:
description: Run the full suite regardless of the diff (master / release branches).
type: boolean
default: false
run-project-backend-checks:
description: Run project-level backend checks.
type: boolean
default: false
run-project-migration-checks:
description: Run project-level migration checks.
type: boolean
default: false
run-project-ratchet-checks:
description: Run the ratchet check for a diff that touches nothing but the ratchets file.
type: boolean
default: false
# Run the backend test suite on demand, against the ref you dispatch on, optionally under a
# profiler. Everything else about the jobs -- matrix legs, tag filters, quarantine gating -- is
# whatever the normal CI run uses, because they are the same jobs.
workflow_dispatch:
inputs:
tests:
description: 'Optional: run only these tests, comma- or space-separated, e.g. metabase.query-processor-test/some-test. Bare namespaces work too. Blank runs each leg''s usual set.'
type: string
required: false
default: ''
profile:
description: 'Profile the test run and attach a flamegraph to the job. Adds sampling overhead.'
type: boolean
required: false
default: false
concurrency:
group: ${{ github.workflow }}-${{ github.head_ref && github.ref || github.run_id }}-backend
@@ -15,10 +47,106 @@ concurrency:
# (secrets: inherit is already set on the backend call in run-tests.yml).
# See DEV-2224.
env:
CI_CONDUCTOR_BASE_URL: ${{ secrets.CI_CONDUCTOR_BASE_URL }}
CI_CONDUCTOR_BASE_URL: ${{ vars.CI_CONDUCTOR_BASE_URL }}
CI_CONDUCTOR_WEBHOOK_SECRET: ${{ secrets.CI_CONDUCTOR_WEBHOOK_SECRET }}
# Both read by the be-tests run step below. Set here rather than passed per job so that turning
# either on is one line. Empty (and so off) on workflow_call, where neither input exists.
#
# ONLY_TESTS replaces the leg's own test selection, so every matrix leg runs the whole list: the
# partition args no longer apply, and legs that hold none of the named tests run nothing.
PROFILE_TESTS: ${{ inputs.profile }}
ONLY_TESTS: ${{ inputs.tests }}
jobs:
project-checks:
name: 'Project tests: Suites'
if: >-
${{ inputs.force-run ||
inputs.run-project-backend-checks ||
inputs.run-project-migration-checks ||
inputs.run-project-ratchet-checks }}
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
timeout-minutes: 15
steps:
- uses: actions/checkout@v6
- name: Prepare back-end environment
uses: ./.github/actions/prepare-backend
# Bootstrap the shared Mage runtime before concurrent commands try to install it themselves.
- name: Prepare Mage
run: ./bin/mage
- parallel:
- name: Run backend checks
if: ${{ inputs.force-run || inputs.run-project-backend-checks }}
run: ./bin/mage project-tests backend
- name: Run migration checks
if: ${{ inputs.force-run || inputs.run-project-migration-checks }}
run: ./bin/mage project-tests migrations
# Babashka, not a JVM test run, so it is cheap enough to run alongside the backend checks.
# It still needs the JDK prepare-backend installs, to resolve clj-kondo on a cold cache.
- name: Run ratchet checks
if: ${{ inputs.force-run || inputs.run-project-backend-checks || inputs.run-project-ratchet-checks }}
run: ./bin/mage kondo-ratchets
project-tests:
name: Project tests
needs: project-checks
if: ${{ always() && !cancelled() }}
runs-on: ${{ vars.SLIM_RUNNER_KEY }}
timeout-minutes: 5
steps:
- name: Check Project tests status
uses: actions/github-script@v9
env:
needs: ${{ toJson(needs) }}
with:
script: | # js
const needs = JSON.parse(process.env.needs);
const jobs = Object.entries(needs).map(
([jobName, jobValues]) => ({
name: jobName,
result: jobValues.result
}));
if (jobs.every(job => job.result === 'skipped' || job.result === 'success')) {
console.log('');
console.log(' |>>> |>>> |>>>');
console.log(' | | |');
console.log(' _ _|_ _ _ _|_ _ _ _|_ _');
console.log(' | |_| |_| |______| |_| |_| |______| |_| |_| |');
console.log(' | | | | | |');
console.log(' | [] [] | | [] [] | | [] [] |');
console.log(' | |______| |______| |');
console.log(' | ___ |');
console.log(' |___________________| |___________________|');
console.log(' |___|');
console.log('');
console.log('Everything is up to code and structurally sound.');
process.exit(0);
}
console.log('');
console.log(' .-===========-.____');
console.log(' /_______________\\ \\____');
console.log(' | .-----------. | \\___');
console.log(' | | x x | | \\__');
console.log(' | | ~ | | _\\_');
console.log(" | `-----------' | /___\\");
console.log(' | o o |');
console.log(" `-----------------'");
console.log(' /=============\\');
console.log(' / O O O O O O O \\');
console.log(' \\_______________/');
console.log('');
console.log('One or more project checks are off the blueprint. Hard hats required.');
jobs.forEach((job) => {
if (job.result !== 'success' && job.result !== 'skipped') {
console.log(`${job.name} - ${job.result}`);
}
});
process.exit(1);
be-linter-clj-kondo:
if: ${{ !inputs.skip }}
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
@@ -45,7 +173,7 @@ jobs:
be-linter-eastwood-test:
# Master / release safety net: lint every backend test namespace.
if: ${{ !inputs.skip && github.event_name == 'push' && (github.ref_name == 'master' || startsWith(github.ref_name, 'release-x')) }}
if: ${{ !inputs.skip && inputs.force-run }}
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
timeout-minutes: 45
name: Eastwood (tests only)
@@ -53,12 +181,12 @@ jobs:
- uses: actions/checkout@v6
- name: Prepare back-end environment
uses: ./.github/actions/prepare-backend
- run: clojure -X:dev:ee:ee-dev:drivers:drivers-dev:test:eastwood/test
- run: clojure -X:dev:dev/test:ee:ee-dev:drivers:drivers-dev:test:eastwood/test
name: Run Eastwood linter on our backend tests
be-linter-eastwood-test-changed:
# PR / merge queue: lint only the test namespaces touched by the diff.
if: ${{ !inputs.skip && (github.event_name == 'pull_request' || github.event_name == 'merge_group') }}
# Lint only the test namespaces touched by the diff.
if: ${{ !inputs.skip && !inputs.force-run && github.event_name == 'pull_request' }}
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
timeout-minutes: 15
name: Eastwood (changed tests only)
@@ -72,8 +200,8 @@ jobs:
- name: Compute changed test namespaces
id: changed
env:
BASE_SHA: ${{ github.event.pull_request.base.sha || github.event.merge_group.base_sha }}
HEAD_SHA: ${{ github.event.pull_request.head.sha || github.event.merge_group.head_sha || github.sha }}
BASE_SHA: ${{ github.event.pull_request.base.sha }}
HEAD_SHA: ${{ github.event.pull_request.head.sha || github.sha }}
run: |
set -euo pipefail
@@ -81,13 +209,14 @@ jobs:
# last synced don't widen our scope. Falls back to BASE_SHA if older than fetched depth.
git fetch --no-tags --depth=200 origin "$BASE_SHA"
DIFF_BASE=$(git merge-base "$BASE_SHA" "$HEAD_SHA" 2>/dev/null || echo "$BASE_SHA")
# Test roots we lint: core, EE, and each driver module's test tree.
# Test roots we lint: core, EE, dev/test, and each driver module's test tree.
# :eastwood/test derives matching :source-paths from the classpath, so any
# namespace we name here is reachable. Include renames (R) so a test that
# was just renamed still gets linted under its new name.
FILES=$(git diff --name-only --diff-filter=AMR "$DIFF_BASE" "$HEAD_SHA" \
-- 'test/**/*.clj' 'test/**/*.cljc' \
'enterprise/backend/test/**/*.clj' 'enterprise/backend/test/**/*.cljc' \
'dev/test/**/*.clj' 'dev/test/**/*.cljc' \
'modules/drivers/**/test/**/*.clj' 'modules/drivers/**/test/**/*.cljc')
if [ -z "$FILES" ]; then
@@ -103,7 +232,14 @@ jobs:
exit 1
fi
NS=$(sed -E 's#^(test/|enterprise/backend/test/|modules/drivers/[^/]+/test/)##; s#\.cljc?$##; s#/#.#g; s#_#-#g' <<<"$FILES" \
# Convert each test path to a Clojure namespace: strip its known test root and
# extension, then translate path separators and underscores. Keep these roots
# aligned with FILES above and the Eastwood classpath aliases below.
NS=$(sed -E \
-e 's#^(test/|enterprise/backend/test/|dev/test/|modules/drivers/[^/]+/test/)##' \
-e 's#\.cljc?$##' \
-e 's#/#.#g' \
-e 's#_#-#g' <<<"$FILES" \
| sort -u \
| paste -sd' ' -)
echo "Changed test namespaces: $NS"
@@ -112,7 +248,7 @@ jobs:
if: steps.changed.outputs.namespaces != ''
env:
NAMESPACES: ${{ steps.changed.outputs.namespaces }}
run: clojure -X:dev:ee:ee-dev:drivers:drivers-dev:test:eastwood/test :namespaces "[$NAMESPACES]"
run: clojure -X:dev:dev/test:ee:ee-dev:drivers:drivers-dev:test:eastwood/test :namespaces "[$NAMESPACES]"
be-tests:
if: ${{ !inputs.skip }}
@@ -158,21 +294,9 @@ jobs:
:partition/index 1
name: "Java ${{ matrix.java-version }} ${{ matrix.job.name }}"
env:
# Only run old migrations tests on pushes to master or release branches. All other branches should skip tests
# with the tag `mb/old-migrations-test`. `__ADDITIONAL_EXCLUDED_TAG__` is not used anywhere outside of splicing
# it in to the command below.
__ADDITIONAL_EXCLUDED_TAG__: >-
${{
(
github.event_name == 'push' &&
(
github.ref_name == 'master' ||
startsWith(github.ref_name, 'release-x')
) &&
''
) ||
':mb/old-migrations-test'
}}
# __ADDITIONAL_EXCLUDED_TAG__: ${{ !inputs.force-run && ':mb/old-migrations-test' || '' }}
# GDGT-3126: re-enable and properly fix old migrations tests
__ADDITIONAL_EXCLUDED_TAG__: ':mb/old-migrations-test'
steps:
- uses: actions/checkout@v6
- name: Prepare front-end environment
@@ -230,7 +354,21 @@ jobs:
# whole `[ns/var ...]` vector reaches clojure -X as a single argument.
run: |
BASE="clojure -X:dev:ci:test:${{ matrix.job.edition }}:${{ matrix.job.edition }}-dev"
if [ "${{ github.run_attempt }}" != "1" ] && [ -s target/failed-tests ]; then
# `:profile-tests` overrides `:test`'s exec-fn, so it has to come last. See dev.profile-tests.
# The `profiled` output is what the collection steps below key off, so that the decision is
# recorded by the step that acts on it rather than re-derived from the environment.
if [ "$PROFILE_TESTS" = "true" ]; then
echo "Profiling this run; a flamegraph will be attached to the job."
echo "profiled=true" >> "$GITHUB_OUTPUT"
BASE="$BASE:profile-tests"
fi
# An explicit selection wins over the rerun narrowing below: it was asked for by hand, on this
# attempt. Names may be separated by commas or spaces; hawk wants them as one vector argument.
if [ -n "$ONLY_TESTS" ]; then
ONLY="[$(echo "$ONLY_TESTS" | tr ',' ' ')]"
echo "Running only: $ONLY"
$BASE :only "$ONLY"
elif [ "${{ github.run_attempt }}" != "1" ] && [ -s target/failed-tests ]; then
echo "Granular rerun of previously-failed tests: $(cat target/failed-tests)"
$BASE :only "$(cat target/failed-tests)"
else
@@ -239,8 +377,15 @@ jobs:
# Keep this step continue-on-error because the quarantine logic controls whether it ultimately fails.
continue-on-error: true
- name: Collect profile
if: ${{ !cancelled() }}
uses: ./.github/actions/collect-profile
with:
profiled: ${{ steps.run-java-tests.outputs.profiled }}
artifact-name: profile-be-tests-java-${{ matrix.java-version }}-${{ matrix.job.test-group-name }}
- name: Report failed tests to ci-conductor
if: ${{ !cancelled() && steps.run-java-tests.outcome == 'failure' }}
if: ${{ !cancelled() && ( steps.run-java-tests.outcome == 'failure' || github.run_attempt != '1' ) }}
# This step should NEVER fail the job!
continue-on-error: true
uses: ./.github/actions/report-failures-to-ci-conductor
@@ -316,7 +461,7 @@ jobs:
uses: ./.github/actions/prepare-backend
# TODO -- we should probably also check WITHOUT ee -- do a check with only OSS namespaces on the classpath
- name: Check namespaces
run: clojure -M:ee:drivers:check
run: clojure -M:ee:drivers:load-namespaces
be-cljfmt:
if: ${{ !inputs.skip }}
@@ -332,6 +477,7 @@ jobs:
be-tests-result:
needs:
- project-tests
- be-linter-eastwood
- be-linter-eastwood-test
- be-linter-eastwood-test-changed
@@ -340,7 +486,7 @@ jobs:
- be-check
- be-tests
if: always() && !cancelled()
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
runs-on: ${{ vars.SLIM_RUNNER_KEY }}
timeout-minutes: 5
env:
needs: ${{ toJson(needs) }}

View File

@@ -12,7 +12,8 @@ concurrency:
jobs:
flags:
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
runs-on: ${{ vars.SLIM_RUNNER_KEY }}
timeout-minutes: 5
outputs:
has_backport_label: ${{ steps.c.outputs.value }}
steps:
@@ -27,7 +28,7 @@ jobs:
files-changed:
name: Check which files changed
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
runs-on: ${{ vars.SLIM_RUNNER_KEY }}
timeout-minutes: 3
outputs:
docs: ${{ steps.changes.outputs.docs }}
@@ -44,7 +45,7 @@ jobs:
needs: [ files-changed, flags ]
if: ${{ !cancelled() }}
name: Decide whether to backport or not
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
runs-on: ${{ vars.SLIM_RUNNER_KEY }}
timeout-minutes: 5
permissions: {}
steps:
@@ -59,7 +60,7 @@ jobs:
priority-backport-reminder:
name: Remind about backporting P0 + P1 fixes
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
runs-on: ${{ vars.SLIM_RUNNER_KEY }}
timeout-minutes: 5
needs: [flags]
permissions:

View File

@@ -1,14 +0,0 @@
name: Block Master Branch PRs
on:
pull_request:
types: [opened, synchronize]
jobs:
check-source-branch:
if: github.head_ref == 'master'
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
steps:
- name: Block master branch PRs
run: |
echo "PRs from \`master\` branches are not allowed, please use a new branch name for your PR."
exit 1

View File

@@ -0,0 +1,142 @@
name: Build & push private Metabase Docker image
# Builds the ee uberjar for a commit and pushes it to the private ECR repo, tagged with that
# commit's full SHA. Callers get the tag back as an output.
#
# The tag is per-commit rather than per-PR, so a PR leaves one image behind per pushed commit.
# Nothing in this repo prunes them — retention is whatever lifecycle policy the ECR repo carries.
on:
workflow_dispatch:
inputs:
commit:
description: Full sha of commit to build, optional
workflow_call:
inputs:
commit:
description: Full sha of commit to build, optional
type: string
secrets:
PR_ENV_IAM_ROLE:
description: Role assumed via OIDC to reach ECR
required: true
PR_ENV_AWS_ACCOUNT_ID:
description: Account hosting the private ECR registry
required: true
outputs:
tag:
description: "Image tag (the commit SHA)"
value: ${{ jobs.dockerize.outputs.tag }}
# Keyed on the calling workflow as well as the commit: pr-env and ai-benchmark both land here, and
# a shared group lets a re-label on one evict the other's queued run (`cancel-in-progress: false`
# still drops a *pending* run when a third queues). Before the extraction the two paths were
# independent; this keeps them that way.
concurrency:
group: build-private-ee-docker-image-${{ github.workflow }}-${{ inputs.commit || github.event.pull_request.head.sha || github.sha }}
cancel-in-progress: false
permissions:
contents: read
actions: read # fetch-artifact reads the artifact API
jobs:
build:
if: github.event_name == 'workflow_dispatch' || github.event.pull_request.head.repo.full_name == github.repository
uses: ./.github/workflows/uberjar.yml
with:
# Pass through only an *explicit* commit and let uberjar apply its own event fallback.
# Resolving head.sha here instead would pin the PR path's checkout to the head commit, while
# run-tests' uberjar keeps building the merge ref — both upload under the same
# `metabase-ee-<head.sha>-uberjar` name, so whichever raced first would decide what the tag
# actually contains.
commit: ${{ inputs.commit }}
dockerize:
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
needs: [build]
if: needs.build.result == 'success'
timeout-minutes: 60
permissions:
id-token: write
contents: read
actions: read
outputs:
tag: ${{ steps.meta.outputs.tag }}
steps:
# Deliberately the workflow's own revision, not `inputs.commit`: this checkout is where
# `./.github/actions/fetch-artifact` below comes from, and pinning it to the target commit
# would run that commit's copy of the action instead of this one. Nothing else in this job
# reads the tree.
- name: Checkout source code
uses: actions/checkout@v6
- name: Configure AWS credentials
uses: aws-actions/configure-aws-credentials@d979d5b3a71173a29b74b5b88418bfda9437d885 # v6.1.1
with:
role-to-assume: ${{ secrets.PR_ENV_IAM_ROLE }}
role-session-name: GitHub_to_AWS_via_FederatedOIDC
aws-region: us-east-1
- name: Login to Amazon ECR
uses: aws-actions/amazon-ecr-login@183a1442edf41672e66566b7fc560e297a290896 # v2
with:
registries: "${{ secrets.PR_ENV_AWS_ACCOUNT_ID }}"
- name: Compute image tag
id: meta
env:
SHA: ${{ inputs.commit || github.event.pull_request.head.sha || github.sha }}
run: echo "tag=${SHA}" >> "$GITHUB_OUTPUT"
- name: Check whether image already exists
id: exists
env:
TAG: ${{ steps.meta.outputs.tag }}
# Same registry the push below targets — the assumed role's default registry is not
# necessarily this account, and querying the wrong one always reports "not found".
REGISTRY_ID: ${{ secrets.PR_ENV_AWS_ACCOUNT_ID }}
run: |
set +e
OUT=$(aws ecr describe-images \
--registry-id "${REGISTRY_ID}" \
--repository-name metabase-enterprise \
--image-ids imageTag="${TAG}" 2>&1)
STATUS=$?
set -e
if [[ "${STATUS}" -eq 0 ]]; then
echo "Image already present for ${TAG}; reusing it."
echo "found=true" >> "$GITHUB_OUTPUT"
elif grep -q 'ImageNotFoundException' <<< "${OUT}"; then
echo "No image for ${TAG}; building."
echo "found=false" >> "$GITHUB_OUTPUT"
else
# Anything else (missing ecr:DescribeImages, wrong registry, throttling) is
# indistinguishable from "not found" if we swallow it, and we'd rebuild forever
# without ever saying why. Rebuilding is still the safe answer, so warn and go on.
echo "${OUT}" >&2
echo "::warning::Could not determine whether ${TAG} exists in ECR (exit ${STATUS}); building unconditionally."
echo "found=false" >> "$GITHUB_OUTPUT"
fi
- name: Retrieve uberjar artifact for ee
if: steps.exists.outputs.found == 'false'
uses: ./.github/actions/fetch-artifact
with:
commit: ${{ steps.meta.outputs.tag }}
edition: ee
extract-path: "target/uberjar"
output-name: "metabase.jar"
- name: Move uberjar to bin/docker
if: steps.exists.outputs.found == 'false'
run: mv target/uberjar/metabase.jar bin/docker/metabase.jar
- name: Build container
if: steps.exists.outputs.found == 'false'
uses: docker/build-push-action@f9f3042f7e2789586610d6e8b85c8f03e5195baf # v7.2.0
with:
context: bin/docker/
platforms: linux/amd64
network: host
build-args: |
GIT_COMMIT_SHA=${{ steps.meta.outputs.tag }}
tags: ${{ secrets.PR_ENV_AWS_ACCOUNT_ID }}.dkr.ecr.us-east-1.amazonaws.com/metabase-enterprise:${{ steps.meta.outputs.tag }}
push: true

View File

@@ -9,8 +9,77 @@ on:
jobs:
files-changed:
name: Check which files changed
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
timeout-minutes: 3
permissions:
contents: read
outputs:
embedder_plugin: ${{ steps.changes.outputs.embedder_plugin }}
steps:
- uses: actions/checkout@v6
- name: Test which files changed
uses: dorny/paths-filter@fbd0ab8f3e69293af611ebaee6363fc25e6d187d # v4.0.1
id: changes
with:
token: ${{ github.token }}
filters: .github/file-paths.yaml
test-embedder-plugin:
needs: files-changed
if: needs.files-changed.outputs.embedder_plugin == 'true'
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
timeout-minutes: 20
permissions:
contents: read
services:
postgres:
image: pgvector/pgvector:pg17
env:
POSTGRES_USER: mb_test
POSTGRES_DB: mb_test
POSTGRES_HOST_AUTH_METHOD: trust
ports:
- 5432:5432
steps:
- uses: actions/checkout@v6
- name: Prepare back-end environment
uses: ./.github/actions/prepare-backend
- name: Build embedder plugin
run: ./bin/build-embedder-plugin.sh
- name: Verify packaged plugin resources
run: |
jar tf modules/embedder/target/metabase-embedder-plugin.jar | grep -Fx metabase/embedder/metabase-plugin.yaml
jar tf modules/embedder/target/metabase-embedder-plugin.jar | grep -Fx metabase/embedder-model-catalog.edn
jar tf modules/embedder/target/metabase-embedder-plugin.jar | grep -Fx metabase-embedder/snowflake-arctic-embed-xs-d8c86521100d3556476a063fc2342036d45c106f-arm64.zip
jar tf modules/embedder/target/metabase-embedder-plugin.jar | grep -Fx metabase-embedder/snowflake-arctic-embed-xs-d8c86521100d3556476a063fc2342036d45c106f-avx2.zip
jar tf modules/embedder/target/metabase-embedder-plugin.jar | grep -Fx metabase-embedder/all-minilm-l6-v2-1110a243fdf4706b3f48f1d95db1a4f5529b4d41-arm64.zip
jar tf modules/embedder/target/metabase-embedder-plugin.jar | grep -Fx metabase-embedder/all-minilm-l6-v2-1110a243fdf4706b3f48f1d95db1a4f5529b4d41-avx2.zip
- name: Run artifact-only plugin smoke test
env:
MB_EMBEDDER_ARTIFACT_TEST: "true"
MB_PLUGINS_DIR: modules/embedder/target
run: >-
./bin/test-agent --oss :only
'[metabase.embeddings.embedder-plugin-artifact-test]'
- name: Run in-process semantic-search round trip
env:
MB_DB_TYPE: postgres
MB_DB_PORT: 5432
MB_DB_HOST: localhost
MB_DB_DBNAME: mb_test
MB_DB_USER: mb_test
MB_APPDB_PGVECTOR_MODE_TEST: "true"
MB_IN_PROCESS_EMBEDDER_SEMANTIC_SEARCH_TEST: "true"
MB_PLUGINS_DIR: modules/embedder/target
run: >-
./bin/test-agent --drivers=postgres :only
'[metabase-enterprise.semantic-search.appdb-pgvector-mode-test/appdb-pgvector-in-process-embedder-round-trip-test]'
test-build-scripts:
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
timeout-minutes: 40
steps:
- uses: actions/checkout@v6
- name: Prepare back-end environment
@@ -20,7 +89,7 @@ jobs:
- name: Run build and release script tests
run: clojure -X:dev:drivers:build:build-dev:build-test:ci
timeout-minutes: 15
- name: Run Liquibase migrations linter tests
- name: Run load-namespaces tests
run: clojure -M:test
working-directory: bin/lint-migrations-file
working-directory: bin/load-namespaces
timeout-minutes: 15

View File

@@ -2,27 +2,56 @@ name: Bundle Size Stats
# Reuses the uberjar built on every master merge: downloads the jar (for the
# emitted JS) plus the bundle-stats and embedding-sdk artifacts, measures
# initial/total bundle sizes, and appends them to stats.metabase.com.
# initial/total bundle sizes, and appends them to eng-stats-importer.
# Triggered by "Run tests", which is the workflow that builds the uberjar on a
# master merge.
on:
workflow_run:
workflows: ["Build Uberjar"]
workflows: ["Run tests"]
types: [completed]
# Master only: releases form non-linear lines whose deltas are meaningless,
# so their sizes are backfilled separately rather than logged here.
branches: [master]
workflow_call:
inputs:
commit:
description: "Commit SHA to measure."
type: string
required: false
default: ""
concurrency:
group: bundle-size-stats-${{ github.event.workflow_run.head_sha }}
group: bundle-size-stats-${{ inputs.commit || github.event.workflow_run.head_sha }}
cancel-in-progress: true
jobs:
# "Run tests" concludes `failure` on master more often than `success`, from
# jobs that have nothing to do with the jar, so its conclusion is not a usable
# gate. The artifact is one: the uberjar job publishes it, and a docs-only
# merge that skipped that job publishes none.
uberjar-built:
if: ${{ github.repository == 'metabase/metabase' }}
runs-on: ${{ vars.SLIM_RUNNER_KEY }}
timeout-minutes: 5
outputs:
found: ${{ steps.probe.outputs.fetch-hit }}
steps:
- uses: actions/checkout@v6
- id: probe
uses: ./.github/actions/fetch-artifact
with:
commit: ${{ inputs.commit || github.event.workflow_run.head_sha }}
edition: ee
download: false
bundle-size-stats:
if: ${{ github.event.workflow_run.conclusion == 'success' && github.repository == 'metabase/metabase' }}
needs: [uberjar-built]
if: ${{ needs.uberjar-built.outputs.found == 'true' }}
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
timeout-minutes: 15
env:
HEAD_SHA: ${{ github.event.workflow_run.head_sha }}
HEAD_SHA: ${{ inputs.commit || github.event.workflow_run.head_sha }}
# Only record a data point when a bundle's as-served size (brotli where the
# build ships .br, else gzip) moved by at least this percent vs the last
# plotted point, keeping the chart to real changes.
@@ -31,11 +60,12 @@ jobs:
- name: Check out the code
uses: actions/checkout@v6
with:
ref: ${{ github.event.workflow_run.head_sha }}
ref: ${{ env.HEAD_SHA }}
- uses: ./.github/actions/prepare-node-bun
- name: Download EE uberjar
uses: ./.github/actions/fetch-artifact
with:
commit: ${{ github.event.workflow_run.head_sha }}
commit: ${{ env.HEAD_SHA }}
edition: ee
extract-path: temp/uberjar
- name: Extract front-end bundles from uberjar
@@ -104,42 +134,15 @@ jobs:
# Passed via env (not interpolated into the shell) so the commit
# message can't inject commands; the script keeps only the subject.
COMMIT_MESSAGE: ${{ github.event.workflow_run.head_commit.message }}
run: node ./.github/scripts/bundle-size-stats-prepare.js
- name: Upload sizes (with deltas) to Stats
run: bun ./.github/scripts/bundle-size-stats-prepare.ts
- name: Import sizes (with deltas) into Stats
id: upload
if: steps.prepare.outputs.significant == 'true'
uses: actions/github-script@v9
if: ${{ steps.prepare.outputs.significant == 'true' && inputs.commit == '' }}
env:
API_KEY: ${{ secrets.STATS_API_KEY }}
with:
script: | # js
const fs = require("fs");
const { uploadCsvToMb } = require("${{ github.workspace }}/.github/scripts/csv-to-mb.js");
const data = JSON.parse(
fs.readFileSync("${{ github.workspace }}/artifacts/upload-rows.json", "utf8"),
);
console.table(data);
try {
await uploadCsvToMb({
baseUrl: "https://stats.metabase.com",
tableId: 79702,
jsonData: data,
mode: "append",
});
console.log("Bundle sizes uploaded successfully");
core.setOutput("uploaded", "true");
} catch (error) {
// Stats logging is best-effort: if stats.metabase.com is still
// unreachable after the client's retries, keep the run green. The
// last-plotted cache is only saved on a successful upload (below),
// so this point is re-attempted on the next master build and
// nothing is silently dropped.
core.warning(`Bundle-size upload failed after retries; leaving run green: ${error.message}`);
core.setOutput("uploaded", "false");
}
ROWS: artifacts/upload-rows.json
ENG_STATS_URL: ${{ secrets.ENG_STATS_URL }}
API_KEY: ${{ secrets.ENG_STATS_API_KEY }}
run: bun .github/scripts/upload-bundle-size-stats.ts
- name: Remember this as the last plotted point
if: steps.upload.outputs.uploaded == 'true'
uses: actions/cache/save@v4

View File

@@ -7,11 +7,6 @@ name: Bundle Size
on:
workflow_call:
inputs:
skip:
description: Whether to skip the check (e.g. no front-end sources changed, or the uberjar failed to build).
required: true
type: boolean
concurrency:
group: bundle-size-${{ github.workflow }}-${{ github.head_ref && github.ref || github.run_id }}
@@ -20,7 +15,6 @@ concurrency:
jobs:
bundle-size-check:
name: "Bundle size check"
if: ${{ !inputs.skip }}
continue-on-error: true
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
timeout-minutes: 20
@@ -32,7 +26,6 @@ jobs:
id: compare
with:
edition: ee
base-ref-commit: ${{ github.event.pull_request.base.sha }}
threshold-percent: ${{ env.BUNDLE_SIZE_THRESHOLD_PERCENT }}
- name: Comment on PR if app bundle size has increased

View File

@@ -1,83 +0,0 @@
# CodeQL's overlay analysis saves a ~400MB "base database" cache on every master run, keyed by commit SHA.
#
# Only the newest entry is ever restored: CodeQL looks its cache up by key *prefix* and takes the most recent match,
# so everything behind it is dead weight. This job keeps the newest few and deletes the rest.
name: CodeQL Cache Cleanup
on:
schedule:
- cron: "0 4 * * *" # daily at 04:00 UTC
workflow_dispatch:
inputs:
keep:
description: "How many of the newest CodeQL caches to keep"
required: false
default: "2"
dry-run:
description: "List what would be deleted without deleting it"
type: boolean
required: false
default: false
concurrency:
group: cache-cleanup-codeql
cancel-in-progress: false
permissions:
actions: write # required to delete cache entries
contents: read
jobs:
cleanup:
# don't run the schedule on forks
if: ${{ github.event_name != 'schedule' || github.repository == 'metabase/metabase' }}
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
timeout-minutes: 10
env:
GH_TOKEN: ${{ github.token }}
KEEP: ${{ github.event.inputs.keep || '2' }}
DRY_RUN: ${{ github.event.inputs.dry-run || 'false' }}
PREFIX: codeql-overlay-base-database-
steps:
- name: Delete superseded CodeQL caches
shell: bash
run: |
set -euo pipefail
# created_at is ISO-8601, so a reverse lexicographic sort is newest-first.
gh api --paginate "/repos/${GITHUB_REPOSITORY}/actions/caches?per_page=100" \
--jq ".actions_caches[] | select(.key | startswith(\"${PREFIX}\")) | \"\(.created_at)\t\(.id)\t\(.size_in_bytes)\t\(.key)\"" \
| sort -r > all.tsv || true
found=$(wc -l < all.tsv | tr -d ' ')
echo "Found $found cache(s) matching '${PREFIX}'; keeping the newest $KEEP."
if [ "$found" -eq 0 ]; then
echo "Nothing to do." >> "$GITHUB_STEP_SUMMARY"
exit 0
fi
tail -n +$((KEEP + 1)) all.tsv > doomed.tsv || true
doomed=$(wc -l < doomed.tsv | tr -d ' ')
freed=0
while IFS=$'\t' read -r created id size key; do
[ -z "${id:-}" ] && continue
echo " deleting $key ($((size / 1000000))MB, created $created)"
if [ "$DRY_RUN" = "true" ]; then
echo " (dry run — not deleted)"
else
# A cache can vanish between listing and deleting (concurrent eviction); don't fail the job over it.
gh api --method DELETE "/repos/${GITHUB_REPOSITORY}/actions/caches/${id}" >/dev/null \
|| echo " (already gone, skipping)"
fi
freed=$((freed + size))
done < doomed.tsv
{
echo "### CodeQL cache cleanup"
echo ""
echo "- matched: **$found**"
echo "- kept (newest): **$KEEP**"
echo "- deleted: **$doomed**"
echo "- reclaimed: **$((freed / 1000000)) MB**${DRY_RUN:+ (dry run: $DRY_RUN)}"
} >> "$GITHUB_STEP_SUMMARY"

View File

@@ -1,173 +0,0 @@
# This workflow is the single source of truth for generating and updating various caches used by our CI pipeline.
# It sets the fresh cache each Monday but provides a manual trigger to update it on-demand.
#
# All other jobs only restore from this cache; *they never update it*!
# They should always use `actions/cache/restore@vX` because `actions/cache@vX` would attempt to save the cache.
#
# Our agreed-upon strategy is to use a deterministic cache key based on the week of the year.
# Jobs can utilize the prior week's cache if the current week's cache is not found.
#
#
# PRINCIPLES:
# - The cache is never wrong!
# - Caches are immutable once created.
# - Caches are for speeding up builds, not for correctness.
# - It is faster to download a large cache than to re-resolve missing dependencies.
#
#
# DESIGN:
#
# 1. Prepare
# - A job first prepares the local environment (e.g., installs JDK, Clojure, Node.js, etc.)
# - This fetches the dependencies from the cache (if it exists) and warms up the local cache for this workflow.
# 2. Resolve
# - The next step pre-resolves all dependencies, ensuring that the local cache is fully populated and up-to-date.
# 3. Update
# - The final step saves the local cache back to GitHub Actions cache with a deterministic key.
# - If a cache entry already exists for that key, it is deleted first to ensure immutability.
#
name: Cache Generator
on:
schedule:
- cron: "0 3 * * 1" # Mondays at 03:00 UTC
workflow_dispatch: # manually update the cache
concurrency:
group: cache-generator
cancel-in-progress: true
jobs:
get-cache-keys:
if: ${{ github.event_name != 'schedule' || github.repository == 'metabase/metabase' }}
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
steps:
- uses: actions/checkout@v6
- name: Get cache keys
uses: ./.github/actions/get-cache-keys
id: get-cache-keys
outputs:
m2-cache-key: ${{ steps.get-cache-keys.outputs.m2-cache-key }}
node-cache-key: ${{ steps.get-cache-keys.outputs.node-cache-key }}
eslint-cache-key: ${{ steps.get-cache-keys.outputs.eslint-cache-key }}
cypress-cache-key: ${{ steps.get-cache-keys.outputs.cypress-cache-key }}
generate-caches:
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
timeout-minutes: 30
needs: get-cache-keys
env:
M2_CACHE_KEY: ${{ needs.get-cache-keys.outputs.m2-cache-key }}
NODE_CACHE_KEY: ${{ needs.get-cache-keys.outputs.node-cache-key }}
CYPRESS_CACHE_KEY: ${{ needs.get-cache-keys.outputs.cypress-cache-key }}
ESLINT_CACHE_KEY: ${{ needs.get-cache-keys.outputs.eslint-cache-key }}
steps:
- uses: actions/checkout@v6
# Backend preparation and cache
- name: Prepare backend
uses: ./.github/actions/prepare-backend
# Pre-resolve every Clojure dependency classpath CI actually uses, so the
# saved cache is a SUPERSET of what each job resolves at runtime.
#
# Why a single `-P` is not enough: tools.deps selects dependency *versions*
# globally per classpath, so different alias combinations can resolve the
# same transitive lib to different versions (e.g. `org.clojure/data.json`
# 2.4.0 vs 2.5.x, `org.ow2.asm/asm` 9.2 vs newer). Resolving only one combo
# leaves the others to fetch their version-deltas straight from Maven
# Central / Clojars on every run -> intermittent 403s. See DEV-2094.
#
# Keep this list in sync with the `clojure` invocations across .github/.
# Each entry notes its consumer. We resolve the FULL alias strings (not a
# hand-reduced set) on purpose: if a currently dep-less alias later gains a
# dependency, this still covers it instead of silently drifting back into a
# cache gap.
- name: Pre-resolve Clojure dependencies
shell: bash
run: |
set -euo pipefail
combos=(
":build:dev:ee:ee-dev:drivers:drivers-dev:cljs" # build + uberjar (combined classpath)
":cljs" # shadow-cljs (build:cljs); resolves :cljs alone -> covers asm:9.2
":dev:ee:ee-dev:drivers:drivers-dev:test:eastwood" # backend.yml (eastwood + eastwood/test)
":dev:ci:ee:ee-dev:drivers:drivers-dev:test" # test-driver.yml (ee) -> covers data.json:2.4.0
":dev:ci:oss:oss-dev:drivers:drivers-dev:test" # test-driver.yml (oss)
":dev:ci:test:ee:ee-dev" # backend.yml matrix (ee)
":dev:ci:test:oss:oss-dev" # backend.yml matrix (oss)
":dev:ci:ee:ee-dev:test:cloverage" # backend-cloverage.yml
":dev:drivers:drivers-dev:test" # reset-cloud-test-dataset.yml
":dev:drivers:build:build-dev:build-test:ci" # build-scripts.yml
":ee:drivers:check" # backend.yml (check; git dep athos/clj-check)
":ee:doc" # docs-generate-base.yml
":kondo" # resolve-backport-conflicts.yml (replace-deps)
":run:ee" # cross-branch-migration-test
":dev:ee:migrate" # cross-branch-migration-test
)
for combo in "${combos[@]}"; do
echo "::group::clojure -P -A${combo}"
clojure -P -A"${combo}"
echo "::endgroup::"
done
- name: Update M2 cache
uses: ./.github/actions/update-cache
with:
path: |
~/.m2
~/.gitlibs
key: ${{ env.M2_CACHE_KEY }}
# Frontend preparation and caches
# `prepare-frontend` action (1) prepares Node.js and (2) fetches the node_modules cache if it exists.
# It then (3) runs `bun install --frozen-lockfile` which ensures the local cache is fully populated.
# IMPORTANT: Caching node_modules after patches are already applied will break any PR that attempts to either:
# - upgrade a patched library
# - change a patch
# Hence why we explicitly exclude patches from the cache (controlled by the `apply-patches` action input).
- name: Install front-end dependencies
uses: ./.github/actions/prepare-frontend
with:
apply-patches: "false"
- name: Get bun cache directory
id: bun-cache
run: |
BUN_CACHE_DIR=$(bun pm cache)
echo "Bun cache directory: $BUN_CACHE_DIR"
echo "dir=$BUN_CACHE_DIR" >> "$GITHUB_OUTPUT"
- name: Ensure that Cypress executable is ready
run: |
bun run cypress install
bun run cypress cache path
bun run cypress cache list
bun run cypress verify
shell: bash
- name: Update node_modules cache
uses: ./.github/actions/update-cache
with:
path: |
${{ steps.bun-cache.outputs.dir }}
node_modules
key: ${{ env.NODE_CACHE_KEY }}
- name: Update Cypress cache
uses: ./.github/actions/update-cache
with:
path: ~/.cache/Cypress
key: ${{ env.CYPRESS_CACHE_KEY }}
# ESLint cache (requires both backend and frontend)
- name: Compile CLJS
run: bun run build-pure:cljs
- name: Run ESLint to populate cache
run: bun run lint-eslint-pure
- name: Update eslint cache
uses: ./.github/actions/update-cache
with:
path: ${{ github.workspace}}/.eslintcache
key: ${{ env.ESLINT_CACHE_KEY }}

204
.github/workflows/cache-warm.yml vendored Normal file
View File

@@ -0,0 +1,204 @@
# Writes the shared dependency caches. Every other job restores them and none of them writes.
#
# A single writer rather than the usual let-every-job-save arrangement, because a pull request here fans
# out to roughly 200 jobs, ~75 of which install Cypress. Letting each of those save would have them all
# build a 200MB archive and race for one reservation on every lockfile change, and all pull the Cypress
# binary at once on a version bump.
#
# The ESLint cache is the exception and saves from the lint job itself: it is under a megabyte and only a
# couple of jobs write it, so there is no herd to avoid.
#
# A cache is readable from the ref that saved it, from that ref's pull requests, and - for every ref -
# from the default branch. Warming on push to each merge target therefore serves the pull requests aimed
# at it, and master's copy backs up every ref that has none of its own.
#
# Keys are content-derived (see .github/scripts/cache-keys.sh), so a push whose dependencies already have
# an entry does nothing but four lookups. There is no cron: nothing here is keyed by date.
#
#
# PRINCIPLES:
# - The cache is never wrong!
# - Caches are immutable once created.
# - Caches are for speeding up builds, not for correctness.
# - It is faster to download a large cache than to re-resolve missing dependencies.
name: Cache Warm
on:
push:
branches:
- master
- "release-x.*.x"
workflow_dispatch:
concurrency:
group: cache-warm-${{ github.ref }}
# Pushes to master land a median of 27 minutes apart and a full resolve takes longer, so cancelling in
# progress would abort most warms before they save and a ref could stay cold indefinitely. Queueing
# costs one wait instead: the queued run finds every key present and exits in about a minute.
cancel-in-progress: false
jobs:
warm:
# Forks read the upstream default branch's caches and cannot usefully write their own, so warming
# there would burn a runner for nothing.
if: ${{ github.repository == 'metabase/metabase' }}
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
timeout-minutes: 30
steps:
- uses: actions/checkout@v6
- name: Cache spec
id: cache-spec
run: .github/scripts/cache-keys.sh | tee -a "$GITHUB_OUTPUT"
# `lookup-only` with no restore-keys asks whether this exact dependency set is already cached.
# Paths come from the spec, the same ones the save below declares - a lookup that named different
# paths would compute a different cache identity and report a miss every time.
- name: Look up M2 cache
id: m2-lookup
uses: actions/cache/restore@v5
with:
path: ${{ steps.cache-spec.outputs.m2-path }}
key: ${{ steps.cache-spec.outputs.m2-key }}
lookup-only: true
- name: Look up bun store
id: bun-lookup
uses: actions/cache/restore@v5
with:
path: ${{ steps.cache-spec.outputs.bun-store-path }}
key: ${{ steps.cache-spec.outputs.bun-store-key }}
lookup-only: true
- name: Look up Clojure CLI
id: clojure-lookup
uses: actions/cache/restore@v5
with:
path: ${{ steps.cache-spec.outputs.clojure-path }}
key: ${{ steps.cache-spec.outputs.clojure-key }}
lookup-only: true
- name: Look up Cypress binary
id: cypress-lookup
uses: actions/cache/restore@v5
with:
path: ${{ steps.cache-spec.outputs.cypress-path }}
key: ${{ steps.cache-spec.outputs.cypress-key }}
lookup-only: true
# Also runs when only the Clojure CLI entry is missing: installing it is what there is to save,
# and the pre-resolve below needs it either way.
- name: Prepare backend
if: steps.m2-lookup.outputs.cache-hit != 'true' || steps.clojure-lookup.outputs.cache-hit != 'true'
uses: ./.github/actions/prepare-backend
- name: Save Clojure CLI
if: steps.clojure-lookup.outputs.cache-hit != 'true'
uses: actions/cache/save@v5
with:
path: ${{ steps.cache-spec.outputs.clojure-path }}
key: ${{ steps.cache-spec.outputs.clojure-key }}
# Pre-resolve every Clojure dependency classpath CI actually uses, so the saved cache is a SUPERSET
# of what each job resolves at runtime.
#
# Why a single `-P` is not enough: tools.deps selects dependency *versions* globally per classpath,
# so different alias combinations can resolve the same transitive lib to different versions (e.g.
# `org.clojure/data.json` 2.4.0 vs 2.5.x, `org.ow2.asm/asm` 9.2 vs newer). Resolving only one combo
# leaves the others to fetch their version-deltas straight from Maven Central / Clojars on every
# run -> intermittent 403s. See DEV-2094.
#
# Keep this list in sync with the `clojure` invocations across .github/. Each entry notes its
# consumer. We resolve the FULL alias strings (not a hand-reduced set) on purpose: if a currently
# dep-less alias later gains a dependency, this still covers it instead of silently drifting back
# into a cache gap.
- name: Pre-resolve Clojure dependencies
if: steps.m2-lookup.outputs.cache-hit != 'true'
shell: bash
run: |
set -euo pipefail
combos=(
":build:dev:ee:ee-dev:drivers:drivers-dev:cljs" # build + uberjar (combined classpath)
":cljs" # shadow-cljs (build:cljs); resolves :cljs alone -> covers asm:9.2
":dev:ee:ee-dev:drivers:drivers-dev:test:eastwood" # backend.yml (eastwood)
":dev:dev/test:ee:ee-dev:drivers:drivers-dev:test:eastwood/test" # backend.yml (eastwood tests)
":dev:dev/test:ee:ee-dev:drivers:drivers-dev:test:ci" # run-tests.yml (project tests)
":dev:ci:ee:ee-dev:drivers:drivers-dev:test" # test-driver.yml (ee) -> covers data.json:2.4.0
":dev:ci:oss:oss-dev:drivers:drivers-dev:test" # test-driver.yml (oss)
":dev:ci:test:ee:ee-dev" # backend.yml matrix (ee)
":dev:ci:test:oss:oss-dev" # backend.yml matrix (oss)
":dev:ci:ee:ee-dev:test:cloverage" # backend-cloverage.yml
":dev:drivers:drivers-dev:test" # reset-cloud-test-dataset.yml
":dev:drivers:build:build-dev:build-test:ci" # build-scripts.yml
":test" # build-scripts.yml (bin/build unit tests)
":ee:drivers:load-namespaces" # backend.yml (load-namespaces)
":ee:doc" # docs-generate-base.yml
":kondo" # resolve-backport-conflicts.yml (replace-deps)
":run:ee" # cross-branch-migration-test
":dev:ee:migrate" # cross-branch-migration-test
":whitespace-linter" # whitespace linter
)
for combo in "${combos[@]}"; do
echo "::group::clojure -P -A${combo}"
clojure -P -A"${combo}"
echo "::endgroup::"
done
# These commands use nested tools.deps projects; resolving the same alias from the
# repository root does not warm their dependencies.
nested_combos=(
"bin/lint-migrations-file|:test" # project migration checks
"bin/load-namespaces|:test" # build-scripts.yml
)
for spec in "${nested_combos[@]}"; do
project=${spec%%|*}
combo=${spec#*|}
echo "::group::${project}: clojure -P -M${combo}"
(cd "$project" && clojure -P -M"${combo}")
echo "::endgroup::"
done
echo "::group::./bin/mage"
./bin/mage
echo "::endgroup::"
- name: Save M2 cache
if: steps.m2-lookup.outputs.cache-hit != 'true'
uses: actions/cache/save@v5
with:
path: ${{ steps.cache-spec.outputs.m2-path }}
key: ${{ steps.cache-spec.outputs.m2-key }}
# `prepare-frontend` installs bun, points it at the store path, and runs a frozen-lockfile install,
# which is what fills the store. Patches are deliberately not applied: a store cached with patches
# already in place breaks any pull request that changes or upgrades a patched dependency.
#
# This also runs when only the Cypress cache is missing, because `bun run cypress install` below
# needs the node_modules this step creates. Narrowing the condition to the bun store alone would
# leave that step with no Cypress binary to run.
- name: Install front-end dependencies
if: steps.bun-lookup.outputs.cache-hit != 'true' || steps.cypress-lookup.outputs.cache-hit != 'true'
uses: ./.github/actions/prepare-frontend
with:
apply-patches: "false"
- name: Save bun store
if: steps.bun-lookup.outputs.cache-hit != 'true'
uses: actions/cache/save@v5
with:
path: ${{ steps.cache-spec.outputs.bun-store-path }}
key: ${{ steps.cache-spec.outputs.bun-store-key }}
- name: Ensure that Cypress executable is ready
if: steps.cypress-lookup.outputs.cache-hit != 'true'
shell: bash
run: |
bun run cypress install
bun run cypress cache path
bun run cypress cache list
bun run cypress verify
- name: Save Cypress binary
if: steps.cypress-lookup.outputs.cache-hit != 'true'
uses: actions/cache/save@v5
with:
path: ${{ steps.cache-spec.outputs.cypress-path }}
key: ${{ steps.cache-spec.outputs.cypress-key }}

View File

@@ -1,21 +0,0 @@
name: Prevent backport.sh from being merged
on:
pull_request:
types: [opened, synchronize, reopened]
merge_group:
jobs:
check-backport-script:
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
steps:
- name: Checkout code
uses: actions/checkout@v6
- name: Check for backport.sh file
run: |
if [ -f "./backport.sh" ]; then
echo "backport.sh file exists. Please remove it before merging."
exit 1
else
echo "All good."
fi

View File

@@ -14,7 +14,7 @@ concurrency:
jobs:
files-changed:
name: Check which files changed
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
runs-on: ${{ vars.SLIM_RUNNER_KEY }}
timeout-minutes: 3
outputs:
frontend_all: ${{ steps.changes.outputs.frontend_all }}

View File

@@ -14,7 +14,7 @@ concurrency:
jobs:
files-changed:
name: Check which files changed
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
runs-on: ${{ vars.SLIM_RUNNER_KEY }}
timeout-minutes: 3
outputs:
cljs: ${{ steps.changes.outputs.cljs }}

View File

@@ -1,5 +1,5 @@
name: Containerize Uberjar
run-name: Containerize ${{ inputs.tag }} Uberjar
run-name: Containerize ${{ inputs.edition }} ${{ inputs.tag }} Uberjar
on:
workflow_call:
@@ -9,9 +9,10 @@ on:
type: string
required: true
repo:
description: owner and repo like "metabase/metabase"
description: Docker owner and repo, e.g. "metabase/metabase".
type: string
tag:
description: Docker tag, e.g. v1.87.2.
type: string
commit:
type: string
@@ -30,10 +31,10 @@ on:
- oss
required: true
repo:
description: docker owner and repo like "metabase/metabase"
description: Docker owner and repo, e.g. "metabase/metabase".
type: string
tag:
description: usually a version like v1.87.2
description: Docker tag, e.g. v1.87.2.
type: string
commit:
description: the full commit hash
@@ -45,10 +46,14 @@ on:
jobs:
containerize:
name: containerize (${{ inputs.edition }})
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
timeout-minutes: 15
outputs:
platforms: ${{ steps.platforms.outputs.result }}
repo: ${{ steps.image.outputs.repo }}
tag: ${{ steps.image.outputs.tag }}
full_image: ${{ steps.image.outputs.full_image }}
steps:
- uses: actions/checkout@v6
with:
@@ -65,6 +70,13 @@ jobs:
release: ${{ inputs.release }}
- name: Prepare release scripts
uses: ./.github/actions/prepare-release-scripts
- name: Resolve image repo and tag
id: image
uses: ./.github/actions/get-docker-info
with:
repo: ${{ inputs.repo }}
tag: ${{ inputs.tag }}
edition: ${{ inputs.edition }}
- name: Get platforms
id: platforms
uses: actions/github-script@v9
@@ -72,7 +84,7 @@ jobs:
result-encoding: string
script: | # js
const { getBuildRequirements, isValidVersionString} = require('${{ github.workspace }}/release/dist/index.cjs');
const version = "${{ inputs.tag }}".split('-')[0];
const version = "${{ steps.image.outputs.tag }}".split('-')[0];
if (!isValidVersionString(version)) {
return "linux/amd64,linux/arm64";
@@ -100,7 +112,7 @@ jobs:
context: bin/docker/.
platforms: ${{ steps.platforms.outputs.result }}
network: host
tags: ${{ inputs.repo }}:${{ inputs.tag }}
tags: ${{ steps.image.outputs.full_image }}
no-cache: true
push: true
build-args: ${{ inputs.build-args }}
@@ -108,16 +120,26 @@ jobs:
# we need to do this to get the nice fallback behavior of the legacy manifest file
- name: Build container (x86 only)
if: contains(steps.platforms.outputs.result, 'arm') == false
env:
BUILD_ARGS: ${{ inputs.build-args }}
FULL_IMAGE: ${{ steps.image.outputs.full_image }}
run: | # bash
args=()
while IFS= read -r line; do
[ -n "$line" ] && args+=(--build-arg "$line")
done <<< "$BUILD_ARGS"
docker build \
-t ${{ inputs.repo }}:${{ inputs.tag }} \
-t "$FULL_IMAGE" \
"${args[@]}" \
--network=host \
--push \
bin/docker/.
verify-docker-pull:
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
needs: containerize
name: verify-docker-pull (${{ inputs.edition }})
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
timeout-minutes: 15
steps:
- name: Login to Docker Hub
@@ -126,18 +148,19 @@ jobs:
username: ${{ inputs.release && secrets.DOCKERHUB_RELEASE_USERNAME || secrets.DOCKERHUB_USERNAME }}
password: ${{ inputs.release && secrets.DOCKERHUB_RELEASE_TOKEN || secrets.DOCKERHUB_TOKEN }}
- name: Pull the container image
run: docker pull ${{ inputs.repo }}:${{ inputs.tag }}
run: docker pull ${{ needs.containerize.outputs.full_image }}
- name: Launch container
run: docker run --rm -dp 3000:3000 ${{ inputs.repo }}:${{ inputs.tag }}
run: docker run --rm -dp 3000:3000 ${{ needs.containerize.outputs.full_image }}
timeout-minutes: 5
- name: Wait for Metabase to start
run: while ! curl -s 'http://localhost:3000/api/health' | grep '{"status":"ok"}'; do sleep 1; done
timeout-minutes: 5
verify-docker-pull-arm:
runs-on: arm-ubuntu-24-2core
needs: containerize
if: contains(needs.containerize.outputs.platforms, 'linux/arm64')
name: verify-docker-pull-arm (${{ inputs.edition }})
runs-on: arm-ubuntu-24-2core
timeout-minutes: 15
steps:
- name: Login to Docker Hub
@@ -146,10 +169,41 @@ jobs:
username: ${{ inputs.release && secrets.DOCKERHUB_RELEASE_USERNAME || secrets.DOCKERHUB_USERNAME }}
password: ${{ inputs.release && secrets.DOCKERHUB_RELEASE_TOKEN || secrets.DOCKERHUB_TOKEN }}
- name: Pull the container image
run: docker pull ${{ inputs.repo }}:${{ inputs.tag }}
run: docker pull ${{ needs.containerize.outputs.full_image }}
- name: Launch container
run: docker run --rm -dp 3000:3000 ${{ inputs.repo }}:${{ inputs.tag }}
run: docker run --rm -dp 3000:3000 ${{ needs.containerize.outputs.full_image }}
timeout-minutes: 5
- name: Wait for Metabase to start
run: while ! curl -s 'http://localhost:3000/api/health' | grep '{"status":"ok"}'; do sleep 1; done
timeout-minutes: 5
post-docker-info-comment:
needs: [containerize, verify-docker-pull, verify-docker-pull-arm]
# Only post a comment if all the steps pass and this is a PR.
if: |
!cancelled() &&
!failure() &&
!inputs.release &&
github.event_name == 'pull_request'
name: post-docker-info-comment (${{ inputs.edition }})
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
timeout-minutes: 5
steps:
- name: Post PR comment
uses: marocchino/sticky-pull-request-comment@0ea0beb66eb9baf113663a64ec522f60e49231c0 # v3.0.4
with:
header: docker-build-status-${{ inputs.edition }}
message: |
✅ Docker build completed for commit ${{ inputs.commit || github.event.pull_request.head.sha || github.sha }}
The uberjar has been built and containerized successfully.
**Branch:** `${{ github.head_ref || github.ref_name }}`
**Docker Image:** `${{ needs.containerize.outputs.full_image }}`
**Docker Hub:** [View on Docker Hub](https://hub.docker.com/r/${{ needs.containerize.outputs.repo }}/tags?name=${{ needs.containerize.outputs.tag }})
**Triggered by:** @${{ github.actor }}
Pull the image:
```bash
docker pull ${{ needs.containerize.outputs.full_image }}
```

View File

@@ -1,129 +0,0 @@
name: Containerize Uberjar
on:
workflow_call:
workflow_dispatch:
inputs:
commit:
description: the full commit hash to containerize (defaults to the triggering commit)
type: string
jobs:
get-container-info:
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
timeout-minutes: 5
name: Get container info
outputs:
editions: ${{ steps.ee-info.outputs.editions }}
ee: ${{ toJson(fromJson(steps.build-matrix.outputs.result).ee) }}
oss: ${{ toJson(fromJson(steps.build-matrix.outputs.result).oss) }}
steps:
- name: Check out the code
uses: actions/checkout@v6
- name: Get EE Docker info
id: ee-info
uses: ./.github/actions/get-docker-info
with:
edition: ee
- name: Get OSS Docker info
id: oss-info
uses: ./.github/actions/get-docker-info
with:
edition: oss
- name: Build matrix info
id: build-matrix
uses: actions/github-script@v9
with:
script: | # js
const editions = JSON.parse('${{ steps.ee-info.outputs.editions }}');
const result = {
editions: editions,
ee: {
repo: '${{ steps.ee-info.outputs.repo }}',
tag: '${{ steps.ee-info.outputs.tag }}'
},
oss: {
repo: '${{ steps.oss-info.outputs.repo }}',
tag: '${{ steps.oss-info.outputs.tag }}'
}
};
console.log('Build matrix:', result);
return result;
containerize:
needs: [get-container-info]
if: needs.get-container-info.result == 'success'
strategy:
matrix:
edition: ${{ fromJson(needs.get-container-info.outputs.editions) }}
uses: ./.github/workflows/containerize-jar.yml
secrets: inherit
with:
edition: ${{ matrix.edition }}
commit: ${{ github.event.inputs.commit || github.event.pull_request.head.sha || github.sha }}
repo: ${{ fromJson(needs.get-container-info.outputs[matrix.edition]).repo }}
tag: ${{ fromJson(needs.get-container-info.outputs[matrix.edition]).tag }}
release: false
build-args: |
GIT_COMMIT_SHA=${{ github.event.inputs.commit || github.event.pull_request.head.sha || github.sha }}
run-trivy:
needs: [get-container-info, containerize]
strategy:
matrix:
edition: ${{ fromJson(needs.get-container-info.outputs.editions) }}
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
name: Run Trivy vulnerability scanner
steps:
- name: Check out the code
uses: actions/checkout@v6
with:
ref: ${{ github.event.inputs.commit || github.event.pull_request.head.sha || github.sha }}
- name: Run Trivy vulnerability scanner
uses: aquasecurity/trivy-action@ed142fd0673e97e23eac54620cfb913e5ce36c25 # v0.36.0
env:
TRIVY_OFFLINE_SCAN: true
repo: ${{ fromJson(needs.get-container-info.outputs[matrix.edition]).repo }}
tag: ${{ fromJson(needs.get-container-info.outputs[matrix.edition]).tag }}
with:
image-ref: docker.io/${{ env.repo }}:${{ env.tag }}
format: sarif
output: trivy-results.sarif
- name: Upload Trivy scan results to GitHub Security tab
uses: github/codeql-action/upload-sarif@v3
with:
sarif_file: "trivy-results.sarif"
post-comment:
needs: [get-container-info, containerize]
if: github.event_name == 'pull_request'
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
name: Post PR comment
steps:
- name: Check out the code
uses: actions/checkout@v6
- name: Get Docker info for comment
id: docker-info
uses: ./.github/actions/get-docker-info
with:
branch: ${{ github.head_ref || github.ref_name }}
edition: ee
- name: Post PR comment
uses: marocchino/sticky-pull-request-comment@0ea0beb66eb9baf113663a64ec522f60e49231c0 # v3.0.4
with:
header: docker-build-status
message: |
✅ Docker build completed for commit ${{ github.event.pull_request.head.sha || github.sha }}
The uberjar has been built and containerized successfully.
**Branch:** `${{ github.head_ref || github.ref_name }}`
**Docker Image:** `${{ steps.docker-info.outputs.full_image }}`
**Docker Hub:** [View on Docker Hub](https://hub.docker.com/r/${{ steps.docker-info.outputs.repo }}/tags?name=${{ steps.docker-info.outputs.tag }})
**Triggered by:** @${{ github.actor }}
Pull the image:
```bash
docker pull ${{ steps.docker-info.outputs.full_image }}
```

View File

@@ -27,7 +27,8 @@ jobs:
# Generate matrix for scheduled/PR runs
generate-matrix:
if: github.event_name != 'workflow_dispatch' && github.repository == 'metabase/metabase'
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
runs-on: ${{ vars.SLIM_RUNNER_KEY }}
timeout-minutes: 5
outputs:
matrix: ${{ steps.set-matrix.outputs.matrix }}
steps:
@@ -97,9 +98,12 @@ jobs:
- name: Show logs on failure
if: failure()
run: |
cd cross-version
docker compose logs metabase || true
docker compose logs postgres || true
for f in cross-version/logs/*.log; do
[ -e "$f" ] || continue
echo "::group::$f"
cat "$f"
echo "::endgroup::"
done
# Notify Slack on nightly failures
notify-on-failure:
@@ -221,6 +225,9 @@ jobs:
- name: Show logs on failure
if: failure()
run: |
cd cross-version
docker compose logs metabase || true
docker compose logs postgres || true
for f in cross-version/logs/*.log; do
[ -e "$f" ] || continue
echo "::group::$f"
cat "$f"
echo "::endgroup::"
done

View File

@@ -59,6 +59,12 @@ jobs:
# Pushing the new branch triggers set-milestone.yml, which does the
# full milestone backfill and then dispatches release-notes-preview
# to upload the markdown to #writing.
#
# Kondo ignore ratchets apply only to master. The cut commit replaces the
# budgets with an explicit opt-out so future budget changes are not applied
# to the release branch. Keeping the opt-out in the canonical file avoids
# introducing a separate marker that could drift out of sync, and the
# backport helper writes the same opt-out so both paths stay identical.
- name: Cut the branch
id: cut
run: |
@@ -66,6 +72,9 @@ jobs:
git config user.name github-actions
git config user.email github-actions@github.com
git checkout -b "$BRANCH"
source .github/actions/create-backport/kondo-ratchets.sh
write_disabled_ratchets
git add --sparse .clj-kondo/ratchets.edn
git commit --allow-empty --no-verify -m "Cut $BRANCH branch"
git push -u origin "$BRANCH"
echo "sha=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT"

View File

@@ -1,88 +0,0 @@
name: Disabled Drivers Slack Notification
on:
workflow_dispatch:
schedule:
- cron: "0 9 * * 1" # every Monday at 9:00 UTC
jobs:
notify-disabled-drivers:
if: ${{ github.event_name != 'schedule' || github.repository == 'metabase/metabase' }}
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
timeout-minutes: 5
steps:
- uses: actions/setup-node@v6.4.0
with:
node-version: lts/Jod
- name: Install Slack SDK
run: npm install @slack/web-api
- name: Check disabled drivers and notify Slack
uses: actions/github-script@v9
env:
SLACK_BOT_TOKEN: ${{ secrets.SLACK_BOT_TOKEN }}
with:
script: |
const { WebClient } = require('@slack/web-api');
// Fetch the config
const response = await fetch('https://raw.githubusercontent.com/metabase/ci-test-config/refs/heads/master/ci-test-config.json');
const config = await response.json();
const drivers = config.drivers || [];
const lastUpdated = config.metadata?.last_updated || 'unknown';
const reason = config.metadata?.reason || 'No reason provided';
// "skip" is the only status CI reads: the driver is not run at all. A driver that
// runs but must not gate is expressed as a suite-level rule in CI Conductor, which
// reports it in its own UI.
const skipped = drivers.filter(d => d.status === 'skip').map(d => d.name);
if (skipped.length === 0) {
console.log('No drivers are disabled. Skipping Slack notification.');
return;
}
const list = (names) => names.map(d => `\`${d}\``).join(' ');
const lines = [`:no_entry: *Disabled (not run):* ${list(skipped)}`];
if (!process.env.SLACK_BOT_TOKEN) {
throw new Error('SLACK_BOT_TOKEN is required');
}
const slack = new WebClient(process.env.SLACK_BOT_TOKEN);
await slack.chat.postMessage({
channel: 'engineering-ci',
text: 'CI Driver Status Report',
blocks: [
{
type: 'section',
text: {
type: 'mrkdwn',
text: `*CI Driver Status*\n${lines.join('\n')}`
},
accessory: {
type: 'button',
text: {
type: 'plain_text',
text: 'View Config',
emoji: true
},
url: 'https://github.com/metabase/ci-test-config/blob/master/ci-test-config.json'
}
},
{
type: 'context',
elements: [
{
type: 'mrkdwn',
text: `${reason} · :clock1: *${lastUpdated}*`
}
]
}
]
});
console.log('Slack notification sent successfully');

View File

@@ -33,6 +33,9 @@ jobs:
- name: Prepare backend environment
uses: ./.github/actions/prepare-backend
- name: Prepare frontend environment
uses: ./.github/actions/prepare-frontend
- name: Set up Babashka
uses: turtlequeue/setup-babashka@d78ec6570aea3b614bc695cafcceb82eb45c2af9 # v1.8.0
with:
@@ -72,9 +75,36 @@ jobs:
clojure -M:ee:doc command-documentation
continue-on-error: false
- name: Generate AI provider documentation
id: generate_ai_provider_docs
# The generator only exists on branches that ship the multi-provider registry (master / 64+), but
# this reusable workflow always runs from master, so skip the step on release branches without it.
if: hashFiles('src/metabase/cmd/ai_provider_dox.clj') != ''
run: |
set -e # Exit on any error
echo "Generating AI provider documentation..."
clojure -M:ee:doc ai-providers-documentation
continue-on-error: false
- name: Generate usage analytics documentation
run: ./bin/generate-usage-analytics-docs.bb
- name: Generate embedding SDK documentation
id: generate_embedding_sdk_docs
run: |
set -e # Exit on any error
echo "Generating embedding SDK documentation..."
bun run embedding-sdk:docs:generate
continue-on-error: false
- name: Generate embedding EAJS documentation
id: generate_embedding_eajs_docs
run: |
set -e # Exit on any error
echo "Generating embedding EAJS documentation..."
bun run embedding-eajs:docs:generate
continue-on-error: false
- name: Check for changes
id: check_changes
run: |
@@ -145,7 +175,10 @@ jobs:
- \`clojure -M:ee:doc config-template\`
- \`clojure -M:ee:doc api-documentation\`
- \`clojure -M:ee:doc command-documentation\`
- \`clojure -M:ee:doc ai-providers-documentation\`
- \`./bin/generate-usage-analytics-docs.bb\`
- \`bun run embedding-sdk:docs:generate\`
- \`bun run embedding-eajs:docs:generate\`
Please review the changes and merge if they look correct." \
--label "Type:Documentation" \

View File

@@ -32,3 +32,9 @@ jobs:
fail: true
args: docs --config ./.lychee/config.toml --offline
format: markdown
# lychee can't read the YAML nav, so this script renders it as markdown first. lychee is on PATH
# from the step above.
- name: Check nav.yml links
if: ${{ !cancelled() }}
run: docs/util/check-links.sh nav

View File

@@ -770,7 +770,7 @@ jobs:
login-to-ecr:
if: inputs.driver == 'Vertica'
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
runs-on: ${{ vars.SLIM_RUNNER_KEY }}
timeout-minutes: 15
permissions:
id-token: write

View File

@@ -6,6 +6,49 @@ on:
skip:
type: boolean
default: false
force-run:
description: Run the full suite regardless of the diff (master / release branches, ci:run-all label).
type: boolean
default: false
# Run one driver job on demand, against the ref you dispatch on, optionally under a profiler.
# Everything else about the job -- credentials, services, test args, quarantine gating -- is
# whatever the normal CI run uses, because it is the same job.
workflow_dispatch:
inputs:
driver:
description: 'Which driver job to run. Only this one runs; the usual decision rules are bypassed.'
type: choice
required: true
options:
- athena
- bigquery
- clickhouse
- databricks
- druid-jdbc
- h2
- mongo
- mongo-sharded-cluster
- mongo-ssl
- mysql-mariadb
- oracle
- postgres
- presto-jdbc
- redshift
- snowflake
- sparksql
- sqlite
- sqlserver
- vertica
tests:
description: 'Optional: run only these tests, comma- or space-separated, e.g. metabase.driver.bigquery-cloud-sdk-test/sync-test. Bare namespaces work too. Blank runs the job''s usual set.'
type: string
required: false
default: ''
profile:
description: 'Profile the test run and attach a flamegraph to the job. Adds sampling overhead.'
type: boolean
required: false
default: false
concurrency:
group: ${{ github.workflow }}-${{ github.head_ref && github.ref || github.run_id }}-drivers
@@ -15,14 +58,23 @@ concurrency:
# ci-conductor (secrets: inherit is already set on the drivers call in
# run-tests.yml). See DEV-2224.
env:
CI_CONDUCTOR_BASE_URL: ${{ secrets.CI_CONDUCTOR_BASE_URL }}
CI_CONDUCTOR_BASE_URL: ${{ vars.CI_CONDUCTOR_BASE_URL }}
CI_CONDUCTOR_WEBHOOK_SECRET: ${{ secrets.CI_CONDUCTOR_WEBHOOK_SECRET }}
# Both read by the test-driver action, which is what actually runs the tests. Set here rather than
# passed as inputs to each job so that turning either on is one line, not one line per driver.
# Empty (and so off) on workflow_call, where neither input exists.
#
# ONLY_TESTS replaces the job's own test selection, so every matrix leg of the chosen driver runs
# the whole list -- BigQuery, for instance, has three legs.
PROFILE_TESTS: ${{ inputs.profile }}
ONLY_TESTS: ${{ inputs.tests }}
jobs:
# This job determines which driver tests should run based on PR context.
# All decision logic is consolidated in mage driver-decisions.
determine-driver-skips:
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
timeout-minutes: 10
outputs:
# All driver run decisions (from mage driver-decisions)
h2-should-run: ${{ steps.driver-decisions.outputs.h2-should-run }}
@@ -45,29 +97,11 @@ jobs:
sqlite-should-run: ${{ steps.driver-decisions.outputs.sqlite-should-run }}
sqlserver-should-run: ${{ steps.driver-decisions.outputs.sqlserver-should-run }}
vertica-should-run: ${{ steps.driver-decisions.outputs.vertica-should-run }}
# Per-driver quarantine conflict flags (set when driver is quarantined but has file changes)
athena-quarantine-conflict: ${{ steps.driver-decisions.outputs.athena-quarantine-conflict }}
bigquery-quarantine-conflict: ${{ steps.driver-decisions.outputs.bigquery-quarantine-conflict }}
clickhouse-quarantine-conflict: ${{ steps.driver-decisions.outputs.clickhouse-quarantine-conflict }}
databricks-quarantine-conflict: ${{ steps.driver-decisions.outputs.databricks-quarantine-conflict }}
druid-quarantine-conflict: ${{ steps.driver-decisions.outputs.druid-quarantine-conflict }}
druid-jdbc-quarantine-conflict: ${{ steps.driver-decisions.outputs.druid-jdbc-quarantine-conflict }}
mongo-quarantine-conflict: ${{ steps.driver-decisions.outputs.mongo-quarantine-conflict }}
mongo-ssl-quarantine-conflict: ${{ steps.driver-decisions.outputs.mongo-ssl-quarantine-conflict }}
mongo-sharded-cluster-quarantine-conflict: ${{ steps.driver-decisions.outputs.mongo-sharded-cluster-quarantine-conflict }}
mysql-mariadb-quarantine-conflict: ${{ steps.driver-decisions.outputs.mysql-mariadb-quarantine-conflict }}
oracle-quarantine-conflict: ${{ steps.driver-decisions.outputs.oracle-quarantine-conflict }}
postgres-quarantine-conflict: ${{ steps.driver-decisions.outputs.postgres-quarantine-conflict }}
presto-jdbc-quarantine-conflict: ${{ steps.driver-decisions.outputs.presto-jdbc-quarantine-conflict }}
redshift-quarantine-conflict: ${{ steps.driver-decisions.outputs.redshift-quarantine-conflict }}
snowflake-quarantine-conflict: ${{ steps.driver-decisions.outputs.snowflake-quarantine-conflict }}
sparksql-quarantine-conflict: ${{ steps.driver-decisions.outputs.sparksql-quarantine-conflict }}
sqlite-quarantine-conflict: ${{ steps.driver-decisions.outputs.sqlite-quarantine-conflict }}
sqlserver-quarantine-conflict: ${{ steps.driver-decisions.outputs.sqlserver-quarantine-conflict }}
vertica-quarantine-conflict: ${{ steps.driver-decisions.outputs.vertica-quarantine-conflict }}
steps:
- name: Checkout repository
uses: actions/checkout@v6
- name: Prepare back-end environment
uses: ./.github/actions/prepare-backend
- name: Fetch base branch
if: github.event_name == 'pull_request' && github.event.pull_request.base.ref != ''
run: |
@@ -80,9 +114,10 @@ jobs:
# branch context, labels, and file changes to decide what runs.
MAGE_ARGS=(
--git-ref="${BASE_REF}"
--is-master-or-release="${IS_MASTER_OR_RELEASE}"
--force-run="${FORCE_RUN}"
--pr-labels="${{ join(github.event.pull_request.labels.*.name, ',') }}"
--skip="${{ inputs.skip }}"
--only-driver="${ONLY_DRIVER}"
)
echo "Running:"
echo "./bin/mage -driver-decisions ${MAGE_ARGS[*]}"
@@ -96,12 +131,13 @@ jobs:
./bin/mage -driver-decisions "${MAGE_ARGS[@]}" --github-output-only >> "$GITHUB_OUTPUT"
env:
BASE_REF: ${{ github.event.pull_request.base.ref || github.ref_name }}
IS_MASTER_OR_RELEASE: ${{ github.ref_name == 'master' || startsWith(github.ref_name, 'release-x') }}
FORCE_RUN: ${{ inputs.force-run }}
ONLY_DRIVER: ${{ inputs.driver }}
shell: bash
be-tests-athena-ee:
needs: determine-driver-skips
if: ${{ needs.determine-driver-skips.outputs.athena-should-run == 'true' || needs.determine-driver-skips.outputs.athena-quarantine-conflict == 'true' }}
if: ${{ needs.determine-driver-skips.outputs.athena-should-run == 'true' }}
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
timeout-minutes: 40
env:
@@ -118,16 +154,6 @@ jobs:
MB_ATHENA_TEST_WITHOUT_GET_TABLE_METADATA_SECRET_KEY: ${{ secrets.MB_ATHENA_TEST_WITHOUT_GET_TABLE_METADATA_SECRET_KEY }}
name: Athena
steps:
- name: Fail on quarantine conflict
if: ${{ needs.determine-driver-skips.outputs.athena-quarantine-conflict == 'true' }}
run: |
echo "::error::Athena driver is quarantined but you changed files in modules/drivers/athena/"
echo ""
echo "Your changes will NOT be tested because the driver is currently quarantined."
echo "To run Athena tests, add the label: break-quarantine-athena"
echo ""
echo "If you merge without testing, you risk breaking the Athena driver!"
exit 1
- uses: actions/checkout@v6
- name: Test Athena driver
id: test-driver
@@ -137,35 +163,16 @@ jobs:
test-args: >-
:only-tags [:mb/driver-tests]
:exclude-tags [:mb/transforms-python-test]
quarantine-engine: ${{ vars.QUARANTINE_ENGINE }}
be-tests-bigquery-cloud-sdk-ee:
needs: determine-driver-skips
if: ${{ needs.determine-driver-skips.outputs.bigquery-should-run == 'true' || needs.determine-driver-skips.outputs.bigquery-quarantine-conflict == 'true' }}
if: ${{ needs.determine-driver-skips.outputs.bigquery-should-run == 'true' }}
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
timeout-minutes: 70
timeout-minutes: 40
strategy:
fail-fast: false
matrix:
job:
- name: Driver Tests Part 1
test-args: >-
:only-tags [:mb/driver-tests]
:exclude-tags [:mb/transforms-python-test]
:fail-fast? true
:partition/total 2
:partition/index 0
- name: Driver Tests Part 2
test-args: >-
:only-tags [:mb/driver-tests]
:exclude-tags [:mb/transforms-python-test]
:fail-fast? true
:partition/total 2
:partition/index 1
- name: Transforms Python Tests
test-args: >-
:only-tags [:mb/transforms-python-test]
needs-python-runner: true
runner-index: [0, 1]
env:
CI: 'true'
DRIVERS: bigquery-cloud-sdk
@@ -176,21 +183,43 @@ jobs:
MB_BIGQUERY_TEST_REFRESH_TOKEN: ${{ secrets.MB_BIGQUERY_TEST_REFRESH_TOKEN }}
MB_BIGQUERY_CLOUD_SDK_TEST_SERVICE_ACCOUNT_JSON: ${{ secrets.MB_BIGQUERY_CLOUD_SDK_TEST_SERVICE_ACCOUNT_JSON }}
MB_BIGQUERY_CLOUD_SDK_TEST_SERVICE_ACCOUNT_JSON_ROUTING: ${{ secrets.MB_BIGQUERY_CLOUD_SDK_TEST_SERVICE_ACCOUNT_JSON_ROUTING }}
name: BigQuery ${{ matrix.job.name }}
name: BigQuery Driver Tests ${{ matrix.runner-index }}
steps:
- uses: actions/checkout@v6
- name: Test BigQuery Cloud SDK driver
id: test-driver
uses: ./.github/actions/test-driver
with:
junit-name: 'be-tests-bigquery-cloud-sdk-ee'
test-args: >-
:only-tags [:mb/driver-tests]
:exclude-tags [:mb/transforms-python-test]
:fail-fast? true
runner-index: ${{ matrix.runner-index }}
runner-count: ${{ strategy.job-total }}
jvms-per-runner: '2'
heap-per-jvm: '4g'
artifact-suffix: runner-${{ matrix.runner-index }}
be-tests-bigquery-transforms-python-ee:
needs: determine-driver-skips
if: ${{ needs.determine-driver-skips.outputs.bigquery-should-run == 'true' }}
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
timeout-minutes: 30
env:
CI: 'true'
DRIVERS: bigquery-cloud-sdk
MB_BIGQUERY_TEST_PROJECT_ID: ${{ secrets.BIGQUERY_TEST_PROJECT_ID }}
MB_BIGQUERY_TEST_CLIENT_ID: ${{ secrets.MB_BIGQUERY_TEST_CLIENT_ID }}
MB_BIGQUERY_TEST_CLIENT_SECRET: ${{ secrets.MB_BIGQUERY_TEST_CLIENT_SECRET }}
MB_BIGQUERY_TEST_ACCESS_TOKEN: ${{ secrets.MB_BIGQUERY_TEST_ACCESS_TOKEN }}
MB_BIGQUERY_TEST_REFRESH_TOKEN: ${{ secrets.MB_BIGQUERY_TEST_REFRESH_TOKEN }}
MB_BIGQUERY_CLOUD_SDK_TEST_SERVICE_ACCOUNT_JSON: ${{ secrets.MB_BIGQUERY_CLOUD_SDK_TEST_SERVICE_ACCOUNT_JSON }}
MB_BIGQUERY_CLOUD_SDK_TEST_SERVICE_ACCOUNT_JSON_ROUTING: ${{ secrets.MB_BIGQUERY_CLOUD_SDK_TEST_SERVICE_ACCOUNT_JSON_ROUTING }}
name: BigQuery Transforms Python Tests
steps:
- name: Fail on quarantine conflict
if: ${{ needs.determine-driver-skips.outputs.bigquery-quarantine-conflict == 'true' }}
run: |
echo "::error::BigQuery driver is quarantined but you changed files in modules/drivers/bigquery-cloud-sdk/"
echo ""
echo "Your changes will NOT be tested because the driver is currently quarantined."
echo "To run BigQuery tests, add the label: break-quarantine-bigquery"
echo ""
echo "If you merge without testing, you risk breaking the BigQuery driver!"
exit 1
- uses: actions/checkout@v6
- name: Setup python-runner
if: ${{ matrix.job.needs-python-runner == true }}
uses: ./.github/actions/setup-python-runner
with:
metabase-automation-token: ${{ secrets.METABASE_AUTOMATION_USER_TOKEN }}
@@ -198,20 +227,21 @@ jobs:
id: test-driver
uses: ./.github/actions/test-driver
with:
# This is the same as the cloud-sdk job above to preserve quarantine history in ci-conductor.
junit-name: 'be-tests-bigquery-cloud-sdk-ee'
test-args: ${{ matrix.job.test-args }}
artifact-suffix: ${{ matrix.job.name }}
quarantine-engine: ${{ vars.QUARANTINE_ENGINE }}
test-args: >-
:only-tags [:mb/transforms-python-test]
artifact-suffix: transforms-python
- name: Cleanup python-runner
if: ${{ always() && matrix.job.needs-python-runner == true }}
if: ${{ always() }}
uses: ./.github/actions/cleanup-python-runner
with:
upload-logs: ${{ steps.test-driver.outcome == 'failure' }}
logs-artifact-suffix: ${{ matrix.job.name }}
logs-artifact-suffix: transforms-python
be-tests-clickhouse-ee:
needs: determine-driver-skips
if: ${{ needs.determine-driver-skips.outputs.clickhouse-should-run == 'true' || needs.determine-driver-skips.outputs.clickhouse-quarantine-conflict == 'true' }}
if: ${{ needs.determine-driver-skips.outputs.clickhouse-should-run == 'true' }}
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
timeout-minutes: 40
strategy:
@@ -235,16 +265,6 @@ jobs:
MB_CLICKHOUSE_TEST_NGINX_PORT: 8127
name: Clickhouse ${{ matrix.job.name }}
steps:
- name: Fail on quarantine conflict
if: ${{ needs.determine-driver-skips.outputs.clickhouse-quarantine-conflict == 'true' }}
run: |
echo "::error::ClickHouse driver is quarantined but you changed files in modules/drivers/clickhouse/"
echo ""
echo "Your changes will NOT be tested because the driver is currently quarantined."
echo "To run ClickHouse tests, add the label: break-quarantine-clickhouse"
echo ""
echo "If you merge without testing, you risk breaking the ClickHouse driver!"
exit 1
- uses: actions/checkout@v6
- name: Setup python-runner
if: ${{ matrix.job.needs-python-runner == true }}
@@ -274,7 +294,6 @@ jobs:
junit-name: 'be-tests-clickhouse-ee'
test-args: ${{ matrix.job.test-args }}
artifact-suffix: ${{ matrix.job.name }}
quarantine-engine: ${{ vars.QUARANTINE_ENGINE }}
- name: Cleanup python-runner
if: ${{ always() && matrix.job.needs-python-runner == true }}
uses: ./.github/actions/cleanup-python-runner
@@ -284,7 +303,7 @@ jobs:
be-tests-druid-jdbc-ee:
needs: determine-driver-skips
if: ${{ needs.determine-driver-skips.outputs.druid-jdbc-should-run == 'true' || needs.determine-driver-skips.outputs.druid-jdbc-quarantine-conflict == 'true' }}
if: ${{ needs.determine-driver-skips.outputs.druid-jdbc-should-run == 'true' }}
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
timeout-minutes: 40
env:
@@ -299,16 +318,6 @@ jobs:
CLUSTER_SIZE: nano-quickstart
name: Druid (JDBC)
steps:
- name: Fail on quarantine conflict
if: ${{ needs.determine-driver-skips.outputs.druid-jdbc-quarantine-conflict == 'true' }}
run: |
echo "::error::Druid JDBC driver is quarantined but you changed files in modules/drivers/druid-jdbc/"
echo ""
echo "Your changes will NOT be tested because the driver is currently quarantined."
echo "To run Druid JDBC tests, add the label: break-quarantine-druid-jdbc"
echo ""
echo "If you merge without testing, you risk breaking the Druid JDBC driver!"
exit 1
- uses: actions/checkout@v6
- name: Test Druid JDBC driver
id: test-driver
@@ -318,11 +327,10 @@ jobs:
test-args: >-
:only-tags [:mb/driver-tests]
:exclude-tags [:mb/transforms-python-test]
quarantine-engine: ${{ vars.QUARANTINE_ENGINE }}
be-tests-databricks-ee:
needs: determine-driver-skips
if: ${{ needs.determine-driver-skips.outputs.databricks-should-run == 'true' || needs.determine-driver-skips.outputs.databricks-quarantine-conflict == 'true' }}
if: ${{ needs.determine-driver-skips.outputs.databricks-should-run == 'true' }}
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
timeout-minutes: 50
strategy:
@@ -334,44 +342,45 @@ jobs:
:only-tags [:mb/driver-tests]
:exclude-tags [:mb/transforms-python-test]
:fail-fast? true
:partition/total 3
:partition/total 2
:partition/index 0
- name: Driver Tests Part 2
test-args: >-
:only-tags [:mb/driver-tests]
:exclude-tags [:mb/transforms-python-test]
:fail-fast? true
:partition/total 3
:partition/total 2
:partition/index 1
- name: Driver Tests Part 3
test-args: >-
:only-tags [:mb/driver-tests]
:exclude-tags [:mb/transforms-python-test]
:fail-fast? true
:partition/total 3
:partition/index 2
env:
CI: 'true'
DRIVERS: databricks
MB_DATABRICKS_TEST_HOST: ${{ secrets.MB_DATABRICKS_JDBC_TEST_HOST }}
MB_DATABRICKS_TEST_HTTP_PATH: ${{ secrets.MB_DATABRICKS_JDBC_TEST_HTTP_PATH }}
MB_DATABRICKS_TEST_TOKEN: ${{ secrets.MB_DATABRICKS_JDBC_TEST_TOKEN }}
MB_DATABRICKS_TEST_CATALOG: 'metabase_ci'
MB_DATABRICKS_TEST_CATALOG_ROUTING: 'metabase_routing_catalog'
MB_DATABRICKS_TEST_CLIENT_ID: ${{ secrets.MB_DATABRICKS_JDBC_TEST_CLIENT_ID }}
MB_DATABRICKS_TEST_OAUTH_SECRET: ${{ secrets.MB_DATABRICKS_JDBC_TEST_OAUTH_SECRET }}
name: Databricks
steps:
- name: Fail on quarantine conflict
if: ${{ needs.determine-driver-skips.outputs.databricks-quarantine-conflict == 'true' }}
run: |
echo "::error::Databricks driver is quarantined but you changed files in modules/drivers/databricks/"
echo ""
echo "Your changes will NOT be tested because the driver is currently quarantined."
echo "To run Databricks tests, add the label: break-quarantine-databricks"
echo ""
echo "If you merge without testing, you risk breaking the Databricks driver!"
exit 1
- name: Select Databricks workspace
shell: bash
env:
TOTAL_SHARDS: '2'
HOST_0: ${{ secrets.MB_DATABRICKS_JDBC_TEST_HOST }}
TOKEN_0: ${{ secrets.MB_DATABRICKS_JDBC_TEST_TOKEN }}
HTTP_PATH_0: ${{ secrets.MB_DATABRICKS_JDBC_TEST_HTTP_PATH }}
HOST_1: ${{ secrets.MB_DATABRICKS_JDBC_TEST_HOST_2 }}
TOKEN_1: ${{ secrets.MB_DATABRICKS_JDBC_TEST_TOKEN_2 }}
HTTP_PATH_1: ${{ secrets.MB_DATABRICKS_JDBC_TEST_HTTP_PATH_2 }}
run: | # sh
shard=$(( GITHUB_RUN_NUMBER % TOTAL_SHARDS ))
echo "Using Databricks workspace shard $(( shard + 1 )) of $TOTAL_SHARDS"
for name in HOST HTTP_PATH TOKEN; do
var="${name}_${shard}"
if [ -z "${!var}" ]; then
echo "::error::Secret $var is empty - is the shard $shard Databricks workspace configured?"
exit 1
fi
echo "MB_DATABRICKS_TEST_${name}=${!var}" >> "$GITHUB_ENV"
done
- uses: actions/checkout@v6
- name: Test Databricks driver
id: test-driver
@@ -380,70 +389,6 @@ jobs:
junit-name: 'be-tests-databricks-ee'
artifact-suffix: ${{ matrix.job.name }}
test-args: ${{ matrix.job.test-args }}
quarantine-engine: ${{ vars.QUARANTINE_ENGINE }}
be-tests-databricks-multi-catalog-ee:
needs: determine-driver-skips
if: ${{ needs.determine-driver-skips.outputs.databricks-should-run == 'true' || needs.determine-driver-skips.outputs.databricks-quarantine-conflict == 'true' }}
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
timeout-minutes: 50
strategy:
fail-fast: false
matrix:
job:
- name: Driver Tests Part 1
test-args: >-
:only-tags [:mb/driver-tests]
:exclude-tags [:mb/transforms-python-test]
:fail-fast? true
:partition/total 3
:partition/index 0
- name: Driver Tests Part 2
test-args: >-
:only-tags [:mb/driver-tests]
:exclude-tags [:mb/transforms-python-test]
:fail-fast? true
:partition/total 3
:partition/index 1
- name: Driver Tests Part 3
test-args: >-
:only-tags [:mb/driver-tests]
:exclude-tags [:mb/transforms-python-test]
:fail-fast? true
:partition/total 3
:partition/index 2
env:
CI: 'true'
DRIVERS: databricks
MB_DATABRICKS_TEST_MULTI_LEVEL_SCHEMA: true
MB_DATABRICKS_TEST_HOST: ${{ secrets.MB_DATABRICKS_JDBC_TEST_HOST }}
MB_DATABRICKS_TEST_HTTP_PATH: ${{ secrets.MB_DATABRICKS_JDBC_TEST_HTTP_PATH }}
MB_DATABRICKS_TEST_TOKEN: ${{ secrets.MB_DATABRICKS_JDBC_TEST_TOKEN }}
MB_DATABRICKS_TEST_CATALOG: 'metabase_ci'
MB_DATABRICKS_TEST_CATALOG_ROUTING: 'metabase_routing_catalog'
MB_DATABRICKS_TEST_CLIENT_ID: ${{ secrets.MB_DATABRICKS_JDBC_TEST_CLIENT_ID }}
MB_DATABRICKS_TEST_OAUTH_SECRET: ${{ secrets.MB_DATABRICKS_JDBC_TEST_OAUTH_SECRET }}
name: Databricks (Multi-Catalog)
steps:
- name: Fail on quarantine conflict
if: ${{ needs.determine-driver-skips.outputs.databricks-quarantine-conflict == 'true' }}
run: |
echo "::error::Databricks driver is quarantined but you changed files in modules/drivers/databricks/"
echo ""
echo "Your changes will NOT be tested because the driver is currently quarantined."
echo "To run Databricks tests, add the label: break-quarantine-databricks"
echo ""
echo "If you merge without testing, you risk breaking the Databricks driver!"
exit 1
- uses: actions/checkout@v6
- name: Test Databricks driver with multi-catalog
id: test-driver
uses: ./.github/actions/test-driver
with:
junit-name: 'be-tests-databricks-multi-catalog-ee'
artifact-suffix: ${{ matrix.job.name }}
test-args: ${{ matrix.job.test-args }}
quarantine-engine: ${{ vars.QUARANTINE_ENGINE }}
be-tests-h2:
needs: determine-driver-skips
@@ -463,7 +408,6 @@ jobs:
test-args: >-
:only-tags [:mb/driver-tests]
:exclude-tags [:mb/transforms-python-test]
quarantine-engine: ${{ vars.QUARANTINE_ENGINE }}
be-tests-h2-oss:
needs: determine-driver-skips
@@ -484,7 +428,6 @@ jobs:
test-args: >-
:only-tags [:mb/driver-tests]
:exclude-tags [:mb/transforms-python-test]
quarantine-engine: ${{ vars.QUARANTINE_ENGINE }}
be-tests-mysql-mariadb:
needs: determine-driver-skips
@@ -549,21 +492,9 @@ jobs:
MYSQL_ALLOW_EMPTY_PASSWORD: true
MYSQL_DATABASE: mb_test
env:
# Only run old migrations tests on pushes to master or release branches. All other branches should skip tests
# with the tag `mb/old-migrations-test`. `__ADDITIONAL_EXCLUDED_TAG__` is not used anywhere outside of splicing
# it in to the command below.
__ADDITIONAL_EXCLUDED_TAG__: >-
${{
(
github.event_name == 'push' &&
(
github.ref_name == 'master' ||
startsWith(github.ref_name, 'release-x')
) &&
''
) ||
':mb/old-migrations-test'
}}
# __ADDITIONAL_EXCLUDED_TAG__: ${{ !inputs.force-run && ':mb/old-migrations-test' || '' }}
# GDGT-3126: re-enable and properly fix old migrations tests
__ADDITIONAL_EXCLUDED_TAG__: ':mb/old-migrations-test'
# actual serious env vars below
CI: 'true'
DRIVERS: mysql
@@ -615,7 +546,6 @@ jobs:
test-args: >-
${{ matrix.job.test-args }}
:exclude-tags '[ ${{ matrix.job.exclude-tag }} ${{ env.__ADDITIONAL_EXCLUDED_TAG__ }}]'
quarantine-engine: ${{ vars.QUARANTINE_ENGINE }}
- name: Cleanup python-runner
if: always()
uses: ./.github/actions/cleanup-python-runner
@@ -625,7 +555,7 @@ jobs:
be-tests-mongo:
needs: determine-driver-skips
if: ${{ needs.determine-driver-skips.outputs.mongo-should-run == 'true' || needs.determine-driver-skips.outputs.mongo-quarantine-conflict == 'true' }}
if: ${{ needs.determine-driver-skips.outputs.mongo-should-run == 'true' }}
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
timeout-minutes: 40
strategy:
@@ -662,16 +592,6 @@ jobs:
MONGO_INITDB_ROOT_PASSWORD: metasample123
name: ${{ matrix.version.name }} ${{ matrix.job.name }}
steps:
- name: Fail on quarantine conflict
if: ${{ needs.determine-driver-skips.outputs.mongo-quarantine-conflict == 'true' }}
run: |
echo "::error::MongoDB driver is quarantined but you changed files in modules/drivers/mongo/"
echo ""
echo "Your changes will NOT be tested because the driver is currently quarantined."
echo "To run MongoDB tests, add the label: break-quarantine-mongo"
echo ""
echo "If you merge without testing, you risk breaking the MongoDB driver!"
exit 1
- uses: actions/checkout@v6
- name: Setup python-runner
if: ${{ matrix.job.needs-python-runner == true }}
@@ -685,7 +605,6 @@ jobs:
junit-name: ${{ matrix.version.junit-name }}
test-args: ${{ matrix.job.test-args }}
artifact-suffix: ${{ matrix.version.name }}-${{ matrix.job.name }}
quarantine-engine: ${{ vars.QUARANTINE_ENGINE }}
- name: Cleanup python-runner
if: ${{ always() && matrix.job.needs-python-runner == true }}
uses: ./.github/actions/cleanup-python-runner
@@ -695,7 +614,7 @@ jobs:
be-tests-mongo-ssl:
needs: determine-driver-skips
if: ${{ needs.determine-driver-skips.outputs.mongo-ssl-should-run == 'true' || needs.determine-driver-skips.outputs.mongo-ssl-quarantine-conflict == 'true' }}
if: ${{ needs.determine-driver-skips.outputs.mongo-ssl-should-run == 'true' }}
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
timeout-minutes: 40
strategy:
@@ -713,16 +632,6 @@ jobs:
MB_TEST_MONGO_REQUIRES_SSL: true
name: "${{ matrix.version.name }} (SSL)"
steps:
- name: Fail on quarantine conflict
if: ${{ needs.determine-driver-skips.outputs.mongo-ssl-quarantine-conflict == 'true' }}
run: |
echo "::error::MongoDB SSL driver is quarantined but you changed files in modules/drivers/mongo/"
echo ""
echo "Your changes will NOT be tested because the driver is currently quarantined."
echo "To run MongoDB SSL tests, add the label: break-quarantine-mongo-ssl"
echo ""
echo "If you merge without testing, you risk breaking the MongoDB SSL driver!"
exit 1
- uses: actions/checkout@v6
- name: Spin up Mongo docker container
run: >-
@@ -757,11 +666,10 @@ jobs:
test-args: >-
:exclude-tags '[:mongo-sharded-cluster-tests :mb/transforms-python-test]'
:only-tags [:mb/driver-tests]
quarantine-engine: ${{ vars.QUARANTINE_ENGINE }}
be-tests-mongo-sharded-cluster-ee:
needs: determine-driver-skips
if: ${{ needs.determine-driver-skips.outputs.mongo-sharded-cluster-should-run == 'true' || needs.determine-driver-skips.outputs.mongo-sharded-cluster-quarantine-conflict == 'true' }}
if: ${{ needs.determine-driver-skips.outputs.mongo-sharded-cluster-should-run == 'true' }}
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
timeout-minutes: 40
env:
@@ -774,16 +682,6 @@ jobs:
- "27017:17017"
name: MongoDB Sharded Cluster
steps:
- name: Fail on quarantine conflict
if: ${{ needs.determine-driver-skips.outputs.mongo-sharded-cluster-quarantine-conflict == 'true' }}
run: |
echo "::error::MongoDB Sharded Cluster driver is quarantined but you changed files in modules/drivers/mongo/"
echo ""
echo "Your changes will NOT be tested because the driver is currently quarantined."
echo "To run MongoDB Sharded Cluster tests, add the label: break-quarantine-mongo-sharded-cluster"
echo ""
echo "If you merge without testing, you risk breaking the MongoDB Sharded Cluster driver!"
exit 1
- uses: actions/checkout@v6
- name: Test MongoDB driver (Sharded cluster)
id: test-driver
@@ -792,11 +690,10 @@ jobs:
junit-name: 'be-tests-mongo-sharded-cluster-ee'
test-args: >-
:only metabase.driver.mongo.sharded-cluster-test
quarantine-engine: ${{ vars.QUARANTINE_ENGINE }}
be-tests-oracle:
needs: determine-driver-skips
if: ${{ needs.determine-driver-skips.outputs.oracle-should-run == 'true' || needs.determine-driver-skips.outputs.oracle-quarantine-conflict == 'true' }}
if: ${{ needs.determine-driver-skips.outputs.oracle-should-run == 'true' }}
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
timeout-minutes: 40
strategy:
@@ -847,16 +744,6 @@ jobs:
- "1521:${{ matrix.version.port }}"
name: ${{ matrix.version.name }}
steps:
- name: Fail on quarantine conflict
if: ${{ needs.determine-driver-skips.outputs.oracle-quarantine-conflict == 'true' }}
run: |
echo "::error::Oracle driver is quarantined but you changed files in modules/drivers/oracle/"
echo ""
echo "Your changes will NOT be tested because the driver is currently quarantined."
echo "To run Oracle tests, add the label: break-quarantine-oracle"
echo ""
echo "If you merge without testing, you risk breaking the Oracle driver!"
exit 1
- uses: actions/checkout@v6
- name: Test ${{ matrix.version.name }}
id: test-driver
@@ -867,7 +754,6 @@ jobs:
test-args: >-
:only-tags [:mb/driver-tests]
:exclude-tags [:mb/transforms-python-test]
quarantine-engine: ${{ vars.QUARANTINE_ENGINE }}
be-tests-postgres:
needs: determine-driver-skips
@@ -891,9 +777,20 @@ jobs:
enable-ssl-tests: 'true'
enable-aws-iam-tests: 'true'
job:
- name: Driver Tests
# Split because the unpartitioned Driver Tests job was running ~40 minutes of tests against
# `timeout-minutes: 50` (checkout and prepare-backend take the rest), and Postgres Latest was
# timing out.
- name: Driver Tests Part 1
test-args: >-
:only-tags [:mb/driver-tests]
:partition/total 2
:partition/index 0
exclude-tag: ':mb/transforms-python-test'
- name: Driver Tests Part 2
test-args: >-
:only-tags [:mb/driver-tests]
:partition/total 2
:partition/index 1
exclude-tag: ':mb/transforms-python-test'
- name: Transforms Python Tests
test-args: >-
@@ -901,21 +798,9 @@ jobs:
needs-python-runner: true
name: "${{ matrix.version.name }} ${{ matrix.job.name }}"
env:
# Only run old migrations tests on pushes to master or release branches. All other branches should skip tests
# with the tag `mb/old-migrations-test`. `__ADDITIONAL_EXCLUDED_TAG__` is not used anywhere outside of splicing
# it in to the command below.
__ADDITIONAL_EXCLUDED_TAG__: >-
${{
(
github.event_name == 'push' &&
(
github.ref_name == 'master' ||
startsWith(github.ref_name, 'release-x')
) &&
''
) ||
':mb/old-migrations-test'
}}
# __ADDITIONAL_EXCLUDED_TAG__: ${{ !inputs.force-run && ':mb/old-migrations-test' || '' }}
# GDGT-3126: re-enable and properly fix old migrations tests
__ADDITIONAL_EXCLUDED_TAG__: ':mb/old-migrations-test'
# actual serious env vars below
CI: 'true'
DRIVERS: postgres
@@ -961,7 +846,6 @@ jobs:
test-args: >-
${{ matrix.job.test-args }}
:exclude-tags '[ ${{ matrix.job.exclude-tag }} ${{ env.__ADDITIONAL_EXCLUDED_TAG__ }}]'
quarantine-engine: ${{ vars.QUARANTINE_ENGINE }}
- name: Cleanup python-runner
if: always()
uses: ./.github/actions/cleanup-python-runner
@@ -971,7 +855,7 @@ jobs:
be-tests-presto-jdbc-ee:
needs: determine-driver-skips
if: ${{ needs.determine-driver-skips.outputs.presto-jdbc-should-run == 'true' || needs.determine-driver-skips.outputs.presto-jdbc-quarantine-conflict == 'true' }}
if: ${{ needs.determine-driver-skips.outputs.presto-jdbc-should-run == 'true' }}
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
timeout-minutes: 40
env:
@@ -994,16 +878,6 @@ jobs:
env:
JAVA_TOOL_OPTIONS: "-Xmx2g"
steps:
- name: Fail on quarantine conflict
if: ${{ needs.determine-driver-skips.outputs.presto-jdbc-quarantine-conflict == 'true' }}
run: |
echo "::error::Presto JDBC driver is quarantined but you changed files in modules/drivers/presto-jdbc/"
echo ""
echo "Your changes will NOT be tested because the driver is currently quarantined."
echo "To run Presto JDBC tests, add the label: break-quarantine-presto-jdbc"
echo ""
echo "If you merge without testing, you risk breaking the Presto JDBC driver!"
exit 1
- uses: actions/checkout@v6
- uses: ./.github/actions/await-port
with:
@@ -1038,11 +912,10 @@ jobs:
test-args: >-
:only-tags [:mb/driver-tests]
:exclude-tags [:mb/transforms-python-test]
quarantine-engine: ${{ vars.QUARANTINE_ENGINE }}
be-tests-redshift-ee:
needs: determine-driver-skips
if: ${{ needs.determine-driver-skips.outputs.redshift-should-run == 'true' || needs.determine-driver-skips.outputs.redshift-quarantine-conflict == 'true' }}
if: ${{ needs.determine-driver-skips.outputs.redshift-should-run == 'true' }}
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
timeout-minutes: 50
strategy:
@@ -1054,17 +927,44 @@ jobs:
test-args: >-
:only-tags [:mb/upload-tests]
:fail-fast? true
- name: Redshift (Excluding Upload Tests) Part 1
# `:partition/*` balances on test-var count, so it cannot break up a block of namespaces that is
# cheap in vars and expensive in seconds. The `metabase-enterprise.*` driver tests are exactly that:
# ~10% of the vars and ~40% of the wall clock, and they sort ahead of `metabase.*`, so a plain 2-way
# split hands one job the whole block and times out. Splitting on the namespace pattern first puts
# them in their own pair of jobs, and each pair then partitions by count within a comparable cost.
# The two patterns are exhaustive over the default `:namespace-pattern` -- every namespace lands in
# exactly one of them -- so nothing stops running when a namespace is added.
- name: Redshift EE (Excluding Upload Tests) Part 1
skip: false
test-args: >-
:namespace-pattern '"^metabase-enterprise[.].*"'
:only-tags [:mb/driver-tests]
:exclude-tags '[:mb/upload-tests :mb/transforms-python-test]'
:fail-fast? true
:partition/total 2
:partition/index 0
- name: Redshift (Excluding Upload Tests) Part 2
- name: Redshift EE (Excluding Upload Tests) Part 2
skip: false
test-args: >-
:namespace-pattern '"^metabase-enterprise[.].*"'
:only-tags [:mb/driver-tests]
:exclude-tags '[:mb/upload-tests :mb/transforms-python-test]'
:fail-fast? true
:partition/total 2
:partition/index 1
- name: Redshift OSS (Excluding Upload Tests) Part 1
skip: false
test-args: >-
:namespace-pattern '"^(?:metabase[.]|hooks[.]).*"'
:only-tags [:mb/driver-tests]
:exclude-tags '[:mb/upload-tests :mb/transforms-python-test]'
:fail-fast? true
:partition/total 2
:partition/index 0
- name: Redshift OSS (Excluding Upload Tests) Part 2
skip: false
test-args: >-
:namespace-pattern '"^(?:metabase[.]|hooks[.]).*"'
:only-tags [:mb/driver-tests]
:exclude-tags '[:mb/upload-tests :mb/transforms-python-test]'
:fail-fast? true
@@ -1087,16 +987,6 @@ jobs:
MB_REDSHIFT_TEST_PASSWORD: ${{ secrets.MB_REDSHIFT_TEST_PASSWORD }}
name: ${{ matrix.job.name }}
steps:
- name: Fail on quarantine conflict
if: ${{ needs.determine-driver-skips.outputs.redshift-quarantine-conflict == 'true' }}
run: |
echo "::error::Redshift driver is quarantined but you changed files in modules/drivers/redshift/"
echo ""
echo "Your changes will NOT be tested because the driver is currently quarantined."
echo "To run Redshift tests, add the label: break-quarantine-redshift"
echo ""
echo "If you merge without testing, you risk breaking the Redshift driver!"
exit 1
- uses: actions/checkout@v6
- name: Setup python-runner
if: ${{ matrix.job.needs-python-runner == true }}
@@ -1112,7 +1002,6 @@ jobs:
test-args: >-
${{ matrix.job.test-args }}
artifact-suffix: ${{ matrix.job.name }}
quarantine-engine: ${{ vars.QUARANTINE_ENGINE }}
- name: Cleanup python-runner
if: ${{ always() && matrix.job.needs-python-runner == true }}
uses: ./.github/actions/cleanup-python-runner
@@ -1122,7 +1011,7 @@ jobs:
be-tests-snowflake-ee:
needs: determine-driver-skips
if: ${{ needs.determine-driver-skips.outputs.snowflake-should-run == 'true' || needs.determine-driver-skips.outputs.snowflake-quarantine-conflict == 'true' }}
if: ${{ needs.determine-driver-skips.outputs.snowflake-should-run == 'true' }}
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
timeout-minutes: 70
strategy:
@@ -1162,16 +1051,6 @@ jobs:
MB_SNOWFLAKE_TEST_RSA_ROLE_TEST_DB: RSA_ROLE_TEST_DB
name: Snowflake ${{ matrix.job.name }}
steps:
- name: Fail on quarantine conflict
if: ${{ needs.determine-driver-skips.outputs.snowflake-quarantine-conflict == 'true' }}
run: |
echo "::error::Snowflake driver is quarantined but you changed files in modules/drivers/snowflake/"
echo ""
echo "Your changes will NOT be tested because the driver is currently quarantined."
echo "To run Snowflake tests, add the label: break-quarantine-snowflake"
echo ""
echo "If you merge without testing, you risk breaking the Snowflake driver!"
exit 1
- uses: actions/checkout@v6
- name: Setup python-runner
if: ${{ matrix.job.needs-python-runner == true }}
@@ -1185,7 +1064,6 @@ jobs:
junit-name: 'be-tests-snowflake-ee'
test-args: ${{ matrix.job.test-args }}
artifact-suffix: ${{ matrix.job.name }}
quarantine-engine: ${{ vars.QUARANTINE_ENGINE }}
- name: Cleanup python-runner
if: ${{ always() && matrix.job.needs-python-runner == true }}
uses: ./.github/actions/cleanup-python-runner
@@ -1195,7 +1073,7 @@ jobs:
be-tests-sparksql-ee:
needs: determine-driver-skips
if: ${{ needs.determine-driver-skips.outputs.sparksql-should-run == 'true' || needs.determine-driver-skips.outputs.sparksql-quarantine-conflict == 'true' }}
if: ${{ needs.determine-driver-skips.outputs.sparksql-should-run == 'true' }}
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
timeout-minutes: 40
env:
@@ -1208,16 +1086,6 @@ jobs:
- "10000:10000"
name: Spark SQL
steps:
- name: Fail on quarantine conflict
if: ${{ needs.determine-driver-skips.outputs.sparksql-quarantine-conflict == 'true' }}
run: |
echo "::error::SparkSQL driver is quarantined but you changed files in modules/drivers/sparksql/"
echo ""
echo "Your changes will NOT be tested because the driver is currently quarantined."
echo "To run SparkSQL tests, add the label: break-quarantine-sparksql"
echo ""
echo "If you merge without testing, you risk breaking the SparkSQL driver!"
exit 1
- uses: actions/checkout@v6
- name: Test Spark driver
id: test-driver
@@ -1227,11 +1095,10 @@ jobs:
test-args: >-
:only-tags [:mb/driver-tests]
:exclude-tags [:mb/transforms-python-test]
quarantine-engine: ${{ vars.QUARANTINE_ENGINE }}
be-tests-sqlite-ee:
needs: determine-driver-skips
if: ${{ needs.determine-driver-skips.outputs.sqlite-should-run == 'true' || needs.determine-driver-skips.outputs.sqlite-quarantine-conflict == 'true' }}
if: ${{ needs.determine-driver-skips.outputs.sqlite-should-run == 'true' }}
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
timeout-minutes: 40
env:
@@ -1239,16 +1106,6 @@ jobs:
DRIVERS: sqlite
name: SQLite
steps:
- name: Fail on quarantine conflict
if: ${{ needs.determine-driver-skips.outputs.sqlite-quarantine-conflict == 'true' }}
run: |
echo "::error::SQLite driver is quarantined but you changed files that affect it"
echo ""
echo "Your changes will NOT be tested because the driver is currently quarantined."
echo "To run SQLite tests, add the label: break-quarantine-sqlite"
echo ""
echo "If you merge without testing, you risk breaking the SQLite driver!"
exit 1
- uses: actions/checkout@v6
- name: Test SQLite driver
id: test-driver
@@ -1258,11 +1115,10 @@ jobs:
test-args: >-
:only-tags [:mb/driver-tests]
:exclude-tags [:mb/transforms-python-test]
quarantine-engine: ${{ vars.QUARANTINE_ENGINE }}
be-tests-sqlserver:
needs: determine-driver-skips
if: ${{ needs.determine-driver-skips.outputs.sqlserver-should-run == 'true' || needs.determine-driver-skips.outputs.sqlserver-quarantine-conflict == 'true' }}
if: ${{ needs.determine-driver-skips.outputs.sqlserver-should-run == 'true' }}
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
timeout-minutes: 30
strategy:
@@ -1301,16 +1157,6 @@ jobs:
MSSQL_MEMORY_LIMIT_MB: 1024
name: ${{ matrix.version.name }} ${{ matrix.job.name }}
steps:
- name: Fail on quarantine conflict
if: ${{ needs.determine-driver-skips.outputs.sqlserver-quarantine-conflict == 'true' }}
run: |
echo "::error::SQL Server driver is quarantined but you changed files in modules/drivers/sqlserver/"
echo ""
echo "Your changes will NOT be tested because the driver is currently quarantined."
echo "To run SQL Server tests, add the label: break-quarantine-sqlserver"
echo ""
echo "If you merge without testing, you risk breaking the SQL Server driver!"
exit 1
- uses: actions/checkout@v6
- name: Setup python-runner
if: ${{ matrix.job.needs-python-runner == true }}
@@ -1324,7 +1170,6 @@ jobs:
junit-name: ${{ matrix.version.junit-name }}
test-args: ${{ matrix.job.test-args }}
artifact-suffix: ${{ matrix.version.name }}-${{ matrix.job.name }}
quarantine-engine: ${{ vars.QUARANTINE_ENGINE }}
- name: Cleanup python-runner
if: ${{ always() && matrix.job.needs-python-runner == true }}
uses: ./.github/actions/cleanup-python-runner
@@ -1362,8 +1207,8 @@ jobs:
login-to-ecr:
needs: determine-driver-skips
if: ${{ needs.determine-driver-skips.outputs.vertica-should-run == 'true' || needs.determine-driver-skips.outputs.vertica-quarantine-conflict == 'true' }}
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
if: ${{ needs.determine-driver-skips.outputs.vertica-should-run == 'true' }}
runs-on: ${{ vars.SLIM_RUNNER_KEY }}
timeout-minutes: 15
permissions:
id-token: write
@@ -1394,7 +1239,7 @@ jobs:
be-tests-vertica-ee:
needs: [determine-driver-skips, login-to-ecr]
if: ${{ needs.determine-driver-skips.outputs.vertica-should-run == 'true' || needs.determine-driver-skips.outputs.vertica-quarantine-conflict == 'true' }}
if: ${{ needs.determine-driver-skips.outputs.vertica-should-run == 'true' }}
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
timeout-minutes: 40
env:
@@ -1410,16 +1255,6 @@ jobs:
password: ${{ needs.login-to-ecr.outputs.docker_password }}
name: Vertica
steps:
- name: Fail on quarantine conflict
if: ${{ needs.determine-driver-skips.outputs.vertica-quarantine-conflict == 'true' }}
run: |
echo "::error::Vertica driver is quarantined but you changed files in modules/drivers/vertica/"
echo ""
echo "Your changes will NOT be tested because the driver is currently quarantined."
echo "To run Vertica tests, add the label: break-quarantine-vertica"
echo ""
echo "If you merge without testing, you risk breaking the Vertica driver!"
exit 1
- uses: actions/checkout@v6
- name: Make plugins directory
run: mkdir plugins
@@ -1431,34 +1266,34 @@ jobs:
test-args: >-
:only-tags [:mb/driver-tests]
:exclude-tags [:mb/transforms-python-test]
quarantine-engine: ${{ vars.QUARANTINE_ENGINE }}
drivers-tests-result:
needs:
- determine-driver-skips
# if you add a driver job, you must add it to this list for it to be a required check
- be-tests-h2
- be-tests-athena-ee
- be-tests-snowflake-ee
- be-tests-bigquery-cloud-sdk-ee
- be-tests-bigquery-transforms-python-ee
- be-tests-clickhouse-ee
- be-tests-databricks-ee
- be-tests-druid-jdbc-ee
- be-tests-mysql-mariadb
- be-tests-h2
- be-tests-h2-oss
- be-tests-mongo
- be-tests-mongo-ssl
- be-tests-mongo-sharded-cluster-ee
- be-tests-mongo-ssl
- be-tests-mysql-mariadb
- be-tests-oracle
- be-tests-postgres
- be-tests-presto-jdbc-ee
- be-tests-redshift-ee
- be-tests-snowflake-ee
- be-tests-sparksql-ee
- be-tests-sqlite-ee
- be-tests-sqlserver
- be-tests-vertica-ee
# - be-tests-starburst-ee
# TODO(rileythomp, 2025-08-20): Re-enable vertica tests once the docker image is updated
# - be-tests-vertica-ee
- be-tests-clickhouse-ee
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
runs-on: ${{ vars.SLIM_RUNNER_KEY }}
timeout-minutes: 5
name: drivers-tests-result
if: always() && !cancelled()

View File

@@ -66,7 +66,8 @@ jobs:
# one place (SHARDS below); the matrix is generated from it.
setup:
name: Build shard matrix
runs-on: ubuntu-22.04
runs-on: ${{ vars.SLIM_RUNNER_KEY }}
timeout-minutes: 5
outputs:
matrix: ${{ steps.gen.outputs.matrix }}
count: ${{ steps.gen.outputs.count }}

View File

@@ -97,7 +97,7 @@ jobs:
CYPRESS_BROWSER: ${{ steps.cypress-prep.outputs.chrome-path }}
run: |
node e2e/runner/run_cypress_ci.js e2e \
--expose grepTags="-@mongo+-@python+-@OSS+-@skip"
--expose grepTags="-@mongo+-@python+-@OSS"
# Don't let a single failing/flaky spec abort the shard — we still want
# coverage from the specs that did run.
continue-on-error: true

Some files were not shown because too many files have changed in this diff Show More