Compare commits

...

1146 Commits

Author SHA1 Message Date
Nicola Mometto
3ae1585c7e bump 2026-07-17 09:40:23 +01:00
Nicola Mometto
b0b11dca91 test seccomp 2026-07-17 09:39:53 +01:00
Oleh K
8984233763 Align transform job header to fix tab layout shift (#77803)
* Fix layout shift when switching tabs on the transform job page

The job Overview and Run history pages each rendered their own header:
Overview used an editable name input plus a `...` menu, while Run history
used a static title with no menu. The differing heights shifted the tab
row, so the clicked tab jumped when switching between the two.

Extract a shared JobHeader component (and a useJobHeaderState hook for the
readOnly/name-change logic) rendered identically by both pages, mirroring
the MetricHeader pattern. Run history now also shows the `...` menu and the
editable name, and Metabot is consistent across both tabs.

* Unify JobPage header logic with useJobHeaderState

JobPage duplicated the readOnly computation and name-change handler that
now live in useJobHeaderState. Source them from the hook instead; keep the
local useTransformPermissions call only for the page-level loading gate.

* Use strict undefined comparisons in job header code

Address review: job/jobId are never null, so compare with undefined
strictly and derive jobId from job.id in the JobHeader render.
2026-07-17 08:51:59 +02:00
Egor Grushin
8ab2269f04 GDGT-2767 Replace deprecated MaybeLink (#77908)
* Replace deprecated MaybeLink

* refactor
2026-07-17 03:12:48 +01:00
Kevin Kelleher
4385d33640 Fix failing test introduced by #77981 (#78000)
fix test
2026-07-17 01:03:20 +00:00
bryan
64588d02fb test(mfa): auth-mechanism matrix + lockout-corner coverage (#77624) 2026-07-16 22:11:37 +00:00
github-automation-metabase
20b1d51e6b Auto-update documentation for master (#77997)
Update generated docs (master)

Co-authored-by: github-actions <github-actions@github.com>
2026-07-16 17:41:49 -04:00
Michael Eby
838d5a7a50 docs: add data isolation content (#77876)
* docs: add data isolation content

* Optimized 4 images, saved 70.0 KB (15.8% smaller)

* Fix links

* Edits from Alex

---------

Co-authored-by: Metabase Automation <github-automation@metabase.com>
2026-07-16 16:47:42 -04:00
dpsutton
5fb83b02e7 Fix MCP OAuth consent flow when Metabase is hosted under a subpath (#77765)
Fixes GIT-10551: connecting an MCP client to a Metabase instance served
under a subpath (site-url like https://example.com/metabase behind a
prefix-stripping reverse proxy) failed at the consent step.

The OAuth flow already derives every advertised URL from site-url —
discovery metadata, authorization/token/registration endpoints, and the
WWW-Authenticate resource_metadata header are all subpath-correct. But
three browser-facing pieces assumed Metabase lives at the domain root:

1. The consent form posted to root-relative /oauth/authorize/decision,
   so the browser sent the POST outside the subpath and the proxy
   returned 404 (the reported bug). The form action is now the absolute
   site-url-based URL, via the same absolute-url helper the page already
   uses for the logo. The bundled @font-face URLs on the page get the
   same treatment.

2. The CSRF cookie was scoped to Path=/oauth/authorize. Under a subpath
   the consent page lives at /metabase/oauth/authorize, so the browser
   would never send the cookie back and the decision POST would fail
   CSRF validation even with the form action fixed. The cookie path now
   carries the path component of site-url.

3. The logged-out flow: the backend bounces to the login page with a
   basename-relative redirect target (the server sits behind the
   prefix-stripping proxy and never sees the subpath). The frontend
   guard resolved that target against the bare origin, losing the
   subpath on the full-page redirect back to /oauth/authorize. The
   guard now normalizes targets through the router basename in both
   directions: paths without an explicit origin get the basename joined
   (browser-real href), and pathnames get it stripped (router path, so
   the backend-only-path prefix check still matches).

Why this is safe:

- Root deployments are bit-for-bit unchanged. site-url has no path
  component there, so the cookie path is still /oauth/authorize, the
  form action still targets /oauth/authorize/decision, and with an
  empty basename the guard resolves every input shape (relative path,
  bare path, absolute URL) to exactly the URLs it produced before.
- Under a subpath, the only outputs that change are ones that were
  previously unroutable (404 through the proxy or a path the SPA
  router would double-prefix).
- The server never sees the subpath, so no routes, parameters, or
  validation logic change; every fix is to a browser-visible artifact
  derived from site-url.

Tests pin both halves: existing root-deployment assertions are
untouched and still pass, and new tests cover the subpath form action,
cookie path, login redirect target, and the full consent -> decision
round-trip with a subpath site-url. Also verified live against a local
prefix-stripping Caddy proxy with a real MCP client flow (DCR, consent,
PKCE token exchange, tool calls).

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-16 15:06:24 -05:00
Rodrigo López Dato
31b35fb452 Automatically focus new Key field when adding user attributes (#77715)
* Automatically focus new Key field when adding user attributes

* Only focus new entry if no error
2026-07-16 16:55:13 -03:00
Anderson
f82bdbdd52 Restore table color range saturation for single conditional formatting rules (#77981)
Restore color range saturation for single rules
2026-07-16 16:41:02 -03:00
Alexander Polyankin
2819934fdc Unify image-buffer pool (#77836)
* Rewrite image-buffer pool on dirigiste (same pool as the GraalVM contexts)

Replace the hand-rolled ConcurrentLinkedDeque pool, stats counters, sweeper
daemon, and logging with the dirigiste Pool already used for static-viz
contexts, with the same semantics: 0-3 pooled int[] arrays of the fixed
oversized size, held exclusively per render, idle arrays dropped after ~10
minutes. acquire blocks until an array is free when the requested size fits;
larger requests get a fresh unpooled BufferedImage.

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

* Extract the dirigiste pool factory into metabase.util.pool

create-pool was duplicated verbatim between the static-viz graal renderer
(channel.render.js.common) and the sqlglot graal runner (sql-parsing.common),
and image-buffer had just picked up a third use. Move it to metabase.util.pool
and use it from all three; the pool behavior tests move from
sql-parsing.common-test to util.pool-test with it.

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

* Add prometheus counters for image-buffer pool usage

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

* Rename image-buffer metrics to metabase-notification namespace

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-16 15:40:38 -04:00
Timofey Kachalov
ce264b2c85 Update SDK version to 0.64.0-alpha (#77978) 2026-07-16 18:33:44 +00:00
lbrdnk
07f62f33c3 Log suggested prompts generation exception on debug only (#77962)
Log exception on debug only
2026-07-16 18:15:54 +00:00
Andrei Chernykh
adf574b57b Convert Scalar visualization from a class to a function component (#77774) 2026-07-16 11:00:04 -07:00
da
43d61f4514 Update Jetty dependencies to version 12.1.11 (#77860)
https://github.com/jetty/jetty.project/releases

check 12.1.7...12.1.11
2026-07-16 14:08:59 -03:00
Andrei Chernykh
12ce1e67e7 Migrate nav search and search result components from Emotion to Mantine (#77332)
* Migrate nav search and search result components from Emotion to Mantine

* Address review feedback: close button label, valid footer markup, footer role and hover transition

* Restore search dropdown footer ref by returning a ref callback from useListKeyboardNavigation
2026-07-16 17:03:22 +00:00
Rodrigo López Dato
89abda4d66 Browse directly from RCLS settings to saved questions (#77614)
* Browse directly from settings to RCLS saved questions

* Move styles to separate file
2026-07-16 14:02:39 -03:00
Anderson
911fe173f2 Fix margins when printing documents with charts (#74234)
* Improve page/container margins when printing document

* do not call flushSync while printing

* Revert "do not call flushSync while printing"

This reverts commit 37c6fe2b50.

* Resize ECharts synchronously for print layout changes

* Refactor ECharts print resize tests

* Clean up
2026-07-16 13:18:49 -03:00
Ethan McCue
8705016252 Fix gauge breaking in static-viz (#77724)
Fix gauge color crashing

Co-authored-by: Kevin Kelleher <16599994+kevinkelleher12@users.noreply.github.com>
2026-07-16 13:46:56 +00:00
Chris Truter
fc7d1ec13b Make default-source-table-entry deterministic and field-safe (#77725) 2026-07-16 13:09:07 +00:00
da
6108e0182e Accept JWT in the body or in parameters according to the method (#75656)
* Follow up to https://github.com/metabase/metabase/pull/72798#discussion_r3234347346

* Apply suggestions from code review

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

* Update docs/people-and-groups/authenticating-with-jwt.md

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

---------

Co-authored-by: Jeff Bruemmer <jeffbruemmer@gmail.com>
Co-authored-by: Jeff Bruemmer <jeff.bruemmer@gmail.com>
2026-07-16 13:01:48 +00:00
Kamil Mielnik
479d7ff67b GDGT-1570 Transform has changes after bluring source table input and still has changes after cancelling them (#77712) 2026-07-16 18:20:13 +07:00
Nicola Mometto
3e6612f075 fix incremental transforms on clickhouse (#77921)
* remove compile-with-inline for clickhouse, no longer needed since the driver got fixed

* re-enable full tests

* fix: for max behavior on clickhouse

* fix: insert for clickhouse

* add temporal reg test
2026-07-16 12:04:46 +01:00
Kamil Mielnik
ce8a99bf08 GDGT-2648 Action menu is too wide when editing a dashboard (#77795) 2026-07-16 17:43:14 +07:00
Nicola Mometto
ed3aa72e65 humanize the alert management error when recipient input is wrong (#77852)
* fix: better human readable validation

* tests
2026-07-16 10:34:25 +00:00
Romeo Van Snick
4081105624 Migrate expression parser and NotebookStepPreview to TypeScript (#77914)
* Generate expression parser as TypeScript

Add --typeScript to lezer-generator so the parser emits typed output; convert lezer.js to lezer.ts.

* Migrate NotebookStepPreview to TypeScript

* Reuse QuestionResultLoaderChildrenProps for VisualizationPreview props
2026-07-16 19:04:36 +10:00
Nicola Mometto
37d96787a1 Better human validation of notification schemas (#77922)
* fix: tighten schema

* 400 rather than 500
2026-07-16 08:57:22 +00:00
Fraser
e823ccc4d7 Move source-location utils to their sole consumer, metabot (#77676) 2026-07-16 20:33:45 +12:00
Romeo Van Snick
4674a3610f Compose route guards as element wrappers (#77686)
* Add element prop support to facade Route

* Compose route guards as element wrappers

* Memoize the element bridge by component type and render off the injected route

* Clarify that index routes accept component or element

* Test that the element bridge reuses shared components across sibling routes
2026-07-16 17:32:12 +10:00
Tyler Plude
1f0d8d6b34 [BOT-1840] Drop visualizer bespoke search index cols (#77684)
* drop temporal dim related search index cols

* revert manual changes to generated docs

* pr feedback; bump up overfetch in visualizer

* rm stale test
2026-07-15 22:02:32 -07:00
Chris Truter
5616e61f7a Allow obsolete semantic search kill-switch (#77903) 2026-07-15 21:58:06 -07:00
Romeo Van Snick
3aa548b966 Migrate DataSelector to TypeScript (#76861)
* Migrate DataSelector SavedEntityPicker to TypeScript

* Align DataSelector picker prop types with actual usage

* Migrate DataSelector to TypeScript and adapt consumers

* Migrate DataSelector unit tests to TypeScript

* Remove unused DataSelector props

* Add TODO for DataSelector api/metabase-lib structural-type cleanup

* Remove unused hasBackButton/onBack from DataSelectorSchemaPicker

* Use setState updater form in setStateWithComputedState

* Guard currentUser instead of faking a zero user id

* Avoid passing a null database to SchemaAndTableDataSelector

* Convert SavedQuestionHeaderButton unit spec to TypeScript

* Justify or remove DataSelector type casts for no-unjustified-type-casts
2026-07-16 14:03:33 +10:00
Timothy S. Dean
cb49c63e0c Better destination-db errors (#77890)
Different endpoints dealing with destination databases handled checks differently, causing confusing error messages depending on code path. This consolidates and standardizes both the messages and the HTTP code.
2026-07-15 20:27:53 -07:00
Romeo Van Snick
99661b47e3 Bundle-size stats: lower record threshold to 0.5% (#77780) 2026-07-16 09:06:44 +10:00
Fraser
98daa6fbf8 Move OnboardingStepper into embedding-hub 2026-07-16 10:19:05 +12:00
Alexander Polyankin
30e4219082 Remove redundant table id from segment and measure API (#77716)
* Remove table_id from measures and segments

* Clear stale Card table_id when the query loses its source table

populate-query-fields only wrote table_id when the derived value was
truthy, so converting an MBQL question to native SQL (or pointing it at
a native model) left table_id referencing the old table. Make it
unconditional, the same fix #68080 applied to source_card_id.

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

* Address review: validate derived table on segment/measure updates

- PUT /api/segment/:id and PUT /api/measure/:id now derive the table from an
  updated definition: table-less definitions are rejected (consistent with
  POST), and if the definition implicitly moves the entity to another table,
  the user must also pass the create permission check for the new table
  (write-check alone only covered the old table).
- Drop the dead :table_id insert arg in POST /api/measure — before-insert
  already derives it from the definition.

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

* Derive segment/measure perms from the definition, not table_id

Per review: instead of API-handler checks against a separately derived table
id, the mi/can-read?, mi/can-write?, and mi/can-create? implementations for
:model/Segment and :model/Measure now derive the source table from the
definition via lib/primary-source-table-id (same admin-or-analyst check as
before, rejecting definitions with no source table), and the API handlers no
longer deal with table ids at all — table_id only remains in what we return
to the client.

Segment definitions are now normalized to MBQL5 at the API boundary (like
measures already were), so the perms and model hooks always see full queries.
Updating a definition re-runs the create check with the new definition, since
the write-check only covers the existing one.

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

* Fix remote-sync segment permission tests for definition-derived perms

The three remote-sync segment tests used empty {} definitions and relied on
table_id/hydrated :table for the permission checks. Perms now derive the
source table from the definition, so give the segments a real MBQL5
definition on the venues table. Also coerce the can-manage helpers to
booleans so callers asserting false? keep working.

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

* Strip stray :aggregation from MBQL4 segment fragments at the API boundary

The model migration always dropped :aggregation from legacy segment
fragments (segments cannot have one). When definition normalization moved to
the API layer, that behavior was lost, so fragments with a stray aggregation
(which several Cypress specs post) started failing schema validation on
insert.

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

* Reject invalid segment definitions instead of stripping :aggregation

Per review: don't silently fix up segment definitions with a stray
:aggregation — validate the normalized definition against the segment schema
at the API boundary and return a 400. Remove the aggregation key from the
Cypress specs that were posting it (it was always dropped by the old model
migration, so those specs never exercised it anyway).

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

* Simplify: keep table_id derivation at the API, revert the perms refactor

Restore the segment/measure permission methods, search filtering, and the
associated tests to their previous table_id-based behavior. The PR keeps to
its core change: the segment/measure APIs no longer accept table_id — it is
derived from the definition and used for the permission checks (including
re-checking the newly derived table when an update moves the entity).

Also update compare-to-the-rest-15655-test for the card change in this PR:
a wrong table_id can no longer be persisted (it is always derived from the
query), so the comparison dashboard for a nil-table card is built from the
field-distribution path now.

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

* Only clear a stale card table_id when the query itself changes

populate-query-fields' unconditional :table_id meant any card update
(rename, archive, collection move) would wipe table_id whenever the
derivation came back nil — e.g. when the query's source card had been
hard-deleted. Gate the nil-overwrite on :dataset_query actually being in
t2/changes; inserts and query edits still clear stale values.

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-15 18:01:40 -04:00
github-automation-metabase
eed6ef7980 Auto-update documentation for master (#77899)
Update generated docs (master)

Co-authored-by: github-actions <github-actions@github.com>
2026-07-15 18:01:11 -04:00
Timofey Kachalov
b21e9dcba1 Fix lost plural translations for strings that also have a msgctxt (#77700) 2026-07-15 21:11:18 +00:00
Nathan Voxland
8771f8eb73 Persistent queue improvements (#77779)
* Persistent queue: concurrent batches, per-queue error handler, config

Generic improvements to the mq persistent-queue subsystem, extracted from the
explorations work so they can land independently:

- max-concurrent-batches: a queue can process multiple batches in parallel,
  bounded by a (optionally dynamic) limit (metabase.mq.queue.concurrency).
- on-error: per-queue handler invoked when a message exhausts its retries,
  so callers can record terminal failures instead of silently dropping them.
- Reworked polling, quartz scheduling, and registry for the above.
- Expanded mq/README.md and tests (concurrency, on-error, quartz affinity).

* Fix Eastwood reflection warnings on Scheduler.checkExists in quartz-test

`Scheduler.checkExists` is overloaded (JobKey vs TriggerKey), so the un-hinted
`nudge-key` made the three call sites reflective. Import `JobKey` and hint the
local; CI's Eastwood step fails the build on reflection warnings.

* Code fixes
2026-07-15 15:20:33 -05:00
Jeff Bruemmer
e5a9978cac docs - 63 temp workflow (#77722)
* 63 temp workflow

* format
2026-07-15 16:15:48 -04:00
Ben Grabow
039504f1e9 Add linear issue link (#77853) 2026-07-15 15:12:57 -05:00
Andrei Chernykh
09e0cf1718 Migrate remaining ModalContent Emotion styles to Mantine and fix dead EmbedModal header overrides (#77324)
* Migrate remaining ModalContent Emotion styles to Mantine and fix dead EmbedModal header overrides

* Make the modal header back button keyboard-accessible with a descriptive label
2026-07-15 11:14:15 -07:00
Ben Grabow
ba4c6a87c3 Update table-level permissions targeting sample DB to use the correct schema on upgrade (#77843)
Update table-level permissions targeting sample DB to use the correct schema
2026-07-15 12:54:25 -05:00
Alexander Polyankin
1921483a0d Revert data_permissions migration (#77864)
* data_permissions migration fix

* fix
2026-07-15 13:28:16 -04:00
Tyler Plude
0f97c3e87b [BOT-1833] Fix semantic search orphan table cleanup (#77499)
* fix orphan semantic search index table cleanup

* Harden orphan index cleanup: schema-scope the scan, skip views, isolate drops

The orphan scan now only considers base tables (a view in the DROP TABLE
batch would abort every nightly cleanup) and, in dedicated-pgvector mode,
only current_schema() — where the unqualified DROP actually resolves;
previously it scanned all schemas and logged drops that never happened.
Stale/orphan tables are dropped one statement at a time with per-table
error handling so a single undroppable table (e.g. one with a dependent
view) cannot permanently block stale, tombstone, and repair cleanup.

Also anchors index-table-name-pattern (\A/\z) so it stays substring-proof
independent of re-matches, documents that legacy pre-BOT-337
index_table_* names must keep matching, and derives the force-reset test
case from model-table-name/model-table-suffix instead of a literal.

* Count actual index-table drops and reap legacy index_table_ stragglers

drop-index-table! now reports :dropped/:missing/:failed — dropping without
IF EXISTS so a vacuous drop (metadata row whose table is already gone)
does not count — and cleanup logs dropped-of-found. The name pattern
gains an index_table_<anything> alternative: the prefix belongs
exclusively to the pre-BOT-337 era, whose digit-less stragglers were
otherwise unreachable.

---------

Co-authored-by: Chris Truter <chris@metabase.com>
2026-07-15 09:40:46 -07:00
appleby
62cdfb57c2 Do not duplicate user context between system prompt and last user message (#77496)
* Do not duplicate user context between system prompt and last user message

In #71045 we moved most of the user context out of internal.selmer system prompt and injected it into the last user
message. However, other system prompts still injected user context into the system prompt, so we wound up formatting
and including it twice. If the `:user_is_viewing` context happens to be large (many related tables / fields), then the
memory and token cost can be significant (#76493).

This commit removes everything from system prompts that was already being injected into the last user message, namely:

- `current_time`
- `first_day_of_week`
- `current_user_info`
- `viewing_context`

It also moves `recent_views` into the last user message (not previously included there).

In addition to saving input tokens and memory, this should also help with caching on providers like openai that do
automatic prefix caching, since we now always inject the current date/time near the end of the prompt.

This also means all system prompts can drop the `<<<METABOT_CACHE_BREAKPOINT>>>` since they no longer have any dynamic
content after the breakpoint.

* Add :slackbot and :document-generate-content to profiles-excluding-recent-views

Their system prompt never included recent_views, so preserve the behavior now that we inject recent_views in the last
user message.
2026-07-15 16:27:20 +00:00
Maksym Yakubych
ba9e327dd0 fix: metabot ai settings (#77637) 2026-07-15 11:20:54 -05:00
Eric Normand
8706236c94 Add test that workspace isolation init never leaks generated passwords (#77721)
A failed CREATE USER used to surface the generated workspace password
verbatim in the JDBC exception message, which provisioning then logged
(GHY-3660). Scrubbing landed in #74657; this adds a regression test that
reproduces the failure for real: init-workspace-isolation! runs over a
connection authenticated as a low-privilege workspace user (granted
database-level CREATE on postgres/redshift so execution reaches the
password-bearing CREATE USER), and every piece of text a logger could
print from the thrown exception - stack trace, Throwable->map, causes,
suppressed, ex-data, and SQLException nextException links - must not
contain the password. A postgres-only assertion requires the redaction
marker in the echoed statement so the test cannot pass vacuously.
2026-07-15 10:18:13 -06:00
Ben Grabow
5598559520 Disable unsupported actions on driver change (#77838) 2026-07-15 11:04:16 -05:00
Ben Grabow
8d47578032 Compile transforms with nested union all layer to prevent inheriting IDENTITY property (#77539)
* Compile transforms with nested union all layer to prevent inheriting IDENTITY property
2026-07-15 10:35:01 -05:00
Timofey Kachalov
7cc5a515f1 Update log4j-* versions (#77808) 2026-07-15 19:10:30 +04:00
Alexander Polyankin
bf028c04dd Treat a blank MB_CONFIG_FILE_PATH as unset (#77821)
JDK 25 changed the empty file path to resolve to the current directory
(File("").exists() is now true), so a long-standing MB_CONFIG_FILE_PATH=''
made the config-from-file loader try to parse the current directory as YAML
and fail at boot. Ignore blank values like metabase.config.core/config-str
does everywhere else, and don't count them as config-text-file being enabled
in anonymous stats.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-15 10:19:28 -04:00
Benoit Vinay
b2d652c6ab Search MB documentation link incorrectly has underline on hover (#77701)
Fix for underline
2026-07-15 16:12:23 +02:00
Sébastien
e29d97eb9e Fill available space in the dashboard new-question query builder (#77270) 2026-07-15 15:56:53 +02:00
Kamil Mielnik
83215dcacd GDGT-2400 Custom viz plugin can overflow its own container (#77695) 2026-07-15 13:44:06 +00:00
Kamil Mielnik
f0a65273fb GDGT-2649 New action modal has redundant vertical scrollbar (#77809) 2026-07-15 13:35:42 +00:00
Egor Grushin
0d59548a1e Gdgt 2586 replace deprecated loadingspinner component (#77638)
* initial migration

* initial migration

* remove deadcode loaders

* one more site is migrated. remove dead code

* make data-testid="loading-indicator" to be by default for Loader component

* fix unit test
2026-07-15 14:11:08 +01:00
github-automation-metabase
16a8399a5c Auto-update documentation for master (#77760)
Update generated docs (master)

Co-authored-by: github-actions <github-actions@github.com>
2026-07-15 09:10:37 -04:00
Nicola Mometto
45940c8ff1 fix: index manager driver added metabdata (#77807) 2026-07-15 12:35:34 +00:00
Kevin Kelleher
88474b9d2a Fix type error introduced by #77131 (#77817)
fix type error
2026-07-15 12:19:52 +00:00
Oleh K
bb8b550a21 Omit negative values from treemap instead of producing wrong percentages (#77601)
* Omit negative values from treemap instead of producing wrong percentages

Treemaps summed metric values as signed totals and divided by that signed
total, so rows of 30 and -50 rendered a surviving leaf as -150%. Negative
tiles also have no positive area, so ECharts dropped them with no warning.

Mirror the pie chart: omit negative values (with a warning) during
aggregation, or fall back to absolute values when every value is negative.
With all node values non-negative the downstream percentage math is correct.

Fixes GDGT-2760

* Tighten null check and document per-row negative filtering
2026-07-15 13:57:05 +02:00
Alexander Polyankin
373b755b50 Bump mise JDK and docs to temurin 25 to match CI (#77769)
* Bump mise JDK to temurin 25 to match CI

CI defaults to Java 25 (.github/actions/prepare-backend and the backend
workflow matrix), but mise.toml still pinned temurin 21.

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

* Update remaining Java 21 leftovers to 25

The e2e matrix builder and docs still referenced JDK 21, while CI,
Docker images, and release requirements for v60+ are on Java 25.

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-15 07:50:30 -04:00
Kevin Kelleher
03a8afdba8 Truncate categorical axis labels rather than not showing them (#77131)
* truncate categorical axis labels

* Update Loki Snapshots

---------

Co-authored-by: Metabase Automation <github-automation@metabase.com>
2026-07-15 07:30:44 -04:00
Ngoc Khuat
aaa84da26f Move index manager driver changelog entry to 0.64.0 (#77710)
move index manager driver changelog entry from 0.63.0 to 0.64.0
2026-07-15 09:27:36 +00:00
Arik Aronov
611ef3690b Set enablePutGet as a Snowflake connection property (#77731)
* assoc in connection-details->spec

* Drop unused empty? refer

* fix in check-manager-of-group function name
2026-07-15 12:05:23 +03:00
github-automation-metabase
559301b57b Fix flaky MBQL to SQL transform conversion e2e test (#77699)
* Pin MBQL transform source schema in transforms e2e spec

The many_schemas Postgres fixture creates an "Animals" table in every
schema (Schema A through Schema Z). createMbqlTransform resolved its
source table via getTableId by name only, so Array.find returned an
arbitrary schema's "Animals" depending on /api/table ordering. The
"convert an MBQL transform to a SQL transform" test asserts the compiled
SQL contains "Schema A", so a non-Schema-A match made it flake.

Add an optional sourceSchema to createMbqlTransform and pin the spec's
source to Schema A so the resolved table and its SQL are deterministic.

* Wait for MBQL->SQL transform save to settle before clicking Run tab

The Run tab only exists in read-only view mode; after clicking Save the
test must wait for the update PUT and the navigation off /edit, otherwise
it races the still-in-flight save and times out looking for the Run tab.

* only pin source schema for the default source table

---------

Co-authored-by: Ngoc Khuat <qn.khuat@gmail.com>
2026-07-15 15:21:14 +07:00
Romeo Van Snick
803f470a7c Replace IndexRoute/IndexRedirect/Redirect with index routes and Navigate (#77591)
* Add index-route support and redirect() to the metabase/router facade

* Adapt ModalRoute and DataPermissionsPage to the function-based Route

* Replace IndexRoute/IndexRedirect/Redirect with index routes and redirect()

* Convert createEntityIdRedirect to a facade-hook wrapper component

* Update route test scaffolding for index routes and redirect()

* Build the Route shim via createRoutes instead of augmenting RouteUtils

* Point the guards spec at the relocated Route export

* Stabilize transforms permission navigation in e2e specs

* Freeze redirect() target at mount to fix chained index-redirect race

---------

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
2026-07-15 14:43:41 +10:00
Alexander Polyankin
cb41874c74 Revert "Bound concurrent query-cache writes" (#77781)
Revert "Bound concurrent query-cache writes (#77738)"

This reverts commit a77339d049.
2026-07-14 23:36:46 -04:00
Alexander Polyankin
1a8a17229a Don't GZIP sync-flush per object when serializing QP cache entries (#77786)
* Don't GZIP sync-flush per object when serializing QP cache entries

Sync-flushing after every cached row meant one native Deflater call in a
JNI critical region per row; on JDK <= 21 (no G1 region pinning, JEP 423)
that stalls GC via the GCLocker under concurrent cache writes. Let the
deflater buffer normally instead, and have result-fn finish the stream
(draining the deflater and writing the GZIP trailer) before returning the
bytes. Old cache entries (unterminated gzip) still deserialize since the
reader already treats EOFException as end-of-stream.

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

* Don't flush the JSON download writer per row

Each per-row flush cascaded into a sync-flush of the gzipped HTTP response:
one native Deflater call in a JNI critical region per exported row (GCLocker
stalls on JDK <= 21) plus one TCP packet per row (#34795, fixed for the :api
writer but not :json downloads) and a worse compression ratio. Let the
BufferedWriter push rows through as it fills, like the CSV writer does;
finish! still flushes the tail.

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-14 23:32:58 -04:00
Romeo Van Snick
972c96b58d Convert modal routes to a modalRoute factory and delete getParentPath (#77372)
* Resolve relative navigation in the router facade's useNavigate

* Add modalRoute factory for modals declared as child routes

* Convert modal routes to the modalRoute factory and delete getParentPath

* Keep navigate's identity stable when v3 rebuilds the matched routes

* Measure matched route pathnames with v3's matchPattern

* Address review: splat note and test, parsePath docstring grammar
2026-07-15 11:36:35 +10:00
Alexander Polyankin
4c9497c75c Add missing FKs (#77713) 2026-07-14 21:16:40 -04:00
technomancy
4e5bb2daa8 Isolate snowflake DB names in CI aggressively (#77669)
Make Snowflake CI runs use a randomly-generated, isolated DB names.

Something is still randomly calling `destroy-db!` on the test-data
dataset and wrecking things for CI runs:

```
(pprint (jdbc/query (no-db-connection-spec)
                    ["SELECT query_text, end_time
                        FROM SNOWFLAKE.ACCOUNT_USAGE.QUERY_HISTORY
                       WHERE query_text LIKE '%_c1bae%'
                         AND (query_text LIKE '%DROP%' OR query_text LIKE '%drop%')
                       ORDER BY end_time DESC limit 128"]))
[...]
"DROP DATABASE \"sha_rel_c1baee7db240aa419104c2d925a07a4d4faeeb24_test-data\";"
```

This particular query (without `IF EXISTS`) only exists on master in
the `destroy-db!` method. However, this method already has protection
against being run on the `test-data` dataset and will throw an
exception if this is tried! And the main call to `destroy-db!` is
gated behind a feature check for `:test/dynamic-dataset-loading`. So
there's nowhere this could be coming from on master.

Rather than trying to track it down, I think it's better to just treat
all snowflake DBs as isolated and disposable. Update `qualified-db-name`
to just prefix the DB name with a random prefix, and use the
`after-run` hook to drop it when done. This also allows us to get rid
of the janky and weird locking system, because no two jobs should ever
try to hit the same DB.
2026-07-14 21:05:52 -04:00
Alexander Polyankin
9cd10f877b Always include inactive tables in dependencies API responses (#77714) 2026-07-14 20:00:12 -04:00
Egor Grushin
9a5a4e2587 GDGT-2833 Add per-version download link to Security Center advisories (#77677)
* Add per-version download link to Security Center advisories

Thread optional download_jar_url through backend schema/fetch and render
a Download link next to each fixed version in AdvisoryCard.

* fix aligning

* Read instance version via useSetting; simplify affected-version lookup

* rollback a redundant change

* addressing PRs comments

* use sequence to nil-coerce download_jar_urls

* addressing the PR's comments

* add download-click analytics

* fix test: add download_jar_urls to Advisory factory

* add e2e test
2026-07-15 00:13:03 +01:00
Egor Grushin
7b3ed42a61 GDGT-2585 Replace deprecated Input component (#77559)
* initial migration

* fix link input size

* remove dead files

* Use Input.ClearButton for textinput clear icon

Replace hand-rolled Tooltip+ActionIcon+Icon clear pattern w/ Mantine
Input.ClearButton across 5 sites; c=text-secondary + rightSectionPointerEvents=all.
Comment why LinkViz needs pointer-events on both root+input.

* fix unit test

* Update loki refs for parameter search Input->TextInput

* Use Input.ClearButton in PermissionsEditorContent; rm blank line in SearchBar styled

* addressing the PR's comments
2026-07-14 22:49:55 +01:00
Sloan Sparger
bf26412ac5 [Metabot] Backend driven conversation state (#76939)
* validate client sent parent_message_id

* implement more restrictive retry logic

* move history to the backend

* migate state from conversation to message records

* client nows generates message ids to shrink case of client not knowing id of written message record on aborted requests

* pr feedback

* [Metabot] Implement conversation branches in usage analytics (#77542)

* implement branches in usage analtyics

* sol pass at making code terser / cleaner

* handle error messages correctly + allow branching after assistant message

* pr feedback

* fix test failures

* remove migration logicalFilePath
2026-07-14 16:22:06 -05:00
Egor Grushin
12835e1889 GDGT-2580 Replace deprecated FormErrorMessage component (#77497)
* initial migration

* initial migration

* Fix WritebackParameter missing name/slug in scaffold
2026-07-14 22:09:33 +01:00
Chris Truter
d65b0f5661 Remove the semantic search kill switch (#77570) 2026-07-14 20:51:41 +00:00
Alexander Polyankin
a77339d049 Bound concurrent query-cache writes (#77738) 2026-07-14 16:16:11 -04:00
Alexander Polyankin
fcd561b654 Replace timeout-prone permissions-collapse migration with aggregate-first query (#77727) 2026-07-14 15:39:15 -04:00
Alexander Polyankin
d3a8d67430 Skip static-viz bundle size budget in dev builds (#77741)
Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-14 15:06:17 -04:00
Chris Vandoodewaard
bd6c7a3ef6 Lint Github Actions Workflows with actionlint (#77698)
* add actionlint workflow

* install actionlint with mage

* pass flags to actionlint

* fix options

* don't use mage

* install actionlint locally with mise, update workflow to use install script
2026-07-14 14:43:38 -04:00
Alexander Polyankin
973bddf906 Bump Docker runtime images to Temurin 25 JRE (#77730) 2026-07-14 13:40:54 -04:00
Nick Fitzpatrick
ace59d6c1c Show all connected parameters when setting up a subscription (#77626) 2026-07-14 21:40:27 +05:30
Eric Normand
5246357b5c Gate write share actions (embed publish, public link) on write access (#72752, GHY-3814) (#77528)
* Hide write-only share actions when entity is not writable (#72752)

The Question and Dashboard sharing menus, and the public-link popover,
offered write actions to any admin regardless of write access. On a
read-only remote-synced instance a card/dashboard in a synced collection
is not writable (can_write=false), so these actions 403'd or authored
state that doesn't stick — the "updating embed fails on read-only
instance" symptom in #72752.

Gate the write actions on can_write, matching how the normal edit
affordances already disappear when the entity can't be written:
- Embed (publish): hidden when not writable.
- Create a public link: hidden when not writable; an existing public link
  stays visible so it can still be viewed/copied (those are reads).
- Remove public link: hidden when not writable.

* Disable embed Publish instead of hiding the option on read-only entities (#72752)

Keep the Embed sharing option visible for a read-only remote-synced
card/dashboard, but disable the Publish/Unpublish buttons in the embed
modal with a tooltip explaining the entity is synced and read-only.
This reverts the earlier hiding of the Embed menu item; the public-link
gating (hide create / remove, keep an existing link viewable) is
unchanged.

* Translate the read-only embed tooltip per resource type (#72752)

Interpolating resourceType left the noun untranslated and prevented the
rest of the sentence from agreeing with its gender.
2026-07-14 10:57:58 -05:00
Mihael Konjević
2ca895407f Bot 1729 eval tracing (#77169)
* Add ai-tracing: eval-time trace capture for the Metabot agent

Introduce a new `ai-tracing` module that captures complete, per-run agent
traces during benchmark/eval runs and exports them to an external eval
backend (Confident AI) over OTLP — separate from production observability.

- Capture is gated by a per-run dynamic binding (`*capture*`), orthogonal to
  MB_TRACING_*, so it never fires on organic traffic. Enabled via the
  env-only MB_AI_EVAL_CAPTURE setting; the API path emits the trace as an
  `eval_trace` data part and exports it.
- Captures the full agent.turn -> llm.call -> tool.* tree with prompts,
  completions, tool args/results, durations, and concurrent-tool nesting
  (conveyed across the agent's virtual threads).
- OTLP export uses a dedicated TracerProvider (SimpleSpanProcessor +
  force-flush, never the production one), replaying the in-memory tree
  post-hoc. The domain -> Confident `confident.*` semconv mapping lives in a
  single chokepoint (`node->semconv-attrs`); vendor/schema swaps are one edit.
- Wires capture into run-agent-loop, loop-step, call-llm, and run-tool.
- Trace-level input/output (user question + final answer) set on the root.
- Export failures are logged loudly instead of swallowed.
- Tests cover the gate, nesting, enrichment, timing, concurrency, the
  semconv mapping, and a metadata-size regression guard.

* Make ai-tracing export more idiomatic; refresh stale docs

- export.clj: replace node->semconv-attrs's nested cond-> of repeated
  type checks + json/encode with :ai/keys destructuring and a flat
  medley/assoc-some table; compose final-llm-output as transducers;
  extract event->attributes; tidy parse-headers (for-comprehension),
  build-provider! (doto), and ensure-provider! (fresh? helper).
- core.clj: drop the stale "seam not wired" comment block and the
  outdated ns docstring (it referenced the abandoned gen_ai/OpenInference
  schema and "single namespace" framing); describe the shipped export.

No behavior change; 14 tests / 56 assertions still pass.

* Replace ai-tracing OTLP export with per-session JSONL log files

Switch the eval-trace collection method from OpenTelemetry/OTLP export to a
dedicated file-based logger, and extend instrumentation to the MCP server and
agent-api in addition to the Metabot agent loop.

- Rip out all OTLP/Confident code (export.clj, the OTLP settings, the OTel
  provider/semconv mapping, the eval_trace SSE part).
- New metabase.ai-tracing.log sink: each span streams one JSON line on a
  dedicated logger, routed per session to its own <session-id>.jsonl by a
  Log4j2 RoutingAppender keyed on mb-eval-session-id. Pure JSONL (%m%n), full
  payloads, no size limits.
- Session model = OTel trace-id analog: *session-id* minted at a fresh
  capture's root, or supplied by the caller, conveyed across virtual threads
  by bound-fn*. Nodes carry :id/:parent-id for tree reconstruction.
- Generic with-eval-session entrypoint (gated by MB_AI_EVAL_CAPTURE, inherits
  when nested) reused by run-agent-loop, MCP dispatch-request (keyed on the
  Mcp-Session-Id so a conversation lands in one file), and agent-api routes.
- MB_AI_EVAL_CAPTURE is the single on/off switch; the logger sits at info and
  writes nothing unless a capture is active.
- run-agent-loop emits a tiny eval_session SSE part so the HTTP harness can
  locate the session file.

Verified end-to-end: real agent run writes a per-session JSONL file with the
correct span tree (parent chain, full structured + normal tool output);
sessions route to separate files. 14 tests / 51 assertions pass.

* ai-tracing: capture full request/response context and add trace read API

Enrich eval spans so a captured trace is a self-contained record of a run:

- agent-api: record HTTP request body, user id, and the response status/body
  via a wrapping respond fn that fires inside the span.
- mcp: record JSON-RPC params, user id, scopes, and the materialized result.
- metabot agent: thread an optional eval-session-id through run-agent-loop so
  the harness can name and read back the per-session trace file; record the
  full request (messages/context/state), turn-level token usage, finish reason,
  and final agent state (link registry / generated entities). Surface the loop
  finish-reason out of loop-step instead of only logging it.
- log: guard span serialization so a non-encodable attribute can never break a
  traced run.

Add metabase.ai-tracing.api: a superuser-only GET /api/eval-trace/:session-id
that returns the captured JSONL, mounted only when MB_AI_EVAL_CAPTURE is on.
Filenames are validated against path traversal. Wire the module into routes and
the kondo module config.

* ai-tracing: preserve OpenAPI spec on agent-api routes; harden trace sink

The eval-tracing wrapper turned agent-api `routes` into a plain fn, which no
longer implemented OpenAPISpec — full-API spec generation (openapi.json,
endpoint-dox, the openapi-all-routes test) threw when the walk reached
/api/agent. Wrap it in `handler-with-open-api-spec`, delegating the spec to the
underlying ns-handler.

Also: narrow the trace-sink catch to Exception so Errors/InterruptedException
propagate; stream the trace file instead of slurping it into heap; and correct
the "single nil-check" docstring claim.

* ai-tracing: validate eval-session-id at mint time to prevent path traversal

The trace read endpoint sanitized the session-id before touching disk, but the
write path fed the raw, caller-supplied eval_session_id straight into the
RoutingAppender's `<session-id>.jsonl` file name — a value like `../../foo` on
an eval instance escaped the trace dir (arbitrary .jsonl write).

Hoist the safety regex to a single `safe-session-id-re` in ai-tracing.core and
add `checked-session-id`, which mints a uuid when none is supplied and throws on
an unsafe supplied id. `with-eval-session` now validates every caller-supplied
id before it can reach the log-file path; ai-tracing.api references the shared
regex so read/write validation can't drift.

* ai-tracing: gate span-macro arg construction on capture-active?

The span macros expanded to an eval-span* call, so span-name and attrs
were built on every invocation and discarded on the nil-check when no
capture was live. Hoist the capture-active? guard into a `spanning`
helper macro (and an inlined variant in with-tool-call, whose name
derives from attrs) so organic traffic never builds the span name string
or attrs map — it pays only the *capture* nil-check plus one thunk
closure. with-tool-call now evaluates attrs exactly once, and only when
capturing.

* ai-tracing: test cross-module span nesting; make agent tests capture-agnostic

Add eval-tracing-nesting-test: drives the real run-agent-loop under
capture-reducible with only the LLM + search backend mocked, and asserts
the emitted span tree nests agent.turn -> llm.call -> tool.search. This
covers the wiring the ai-tracing docstrings promise — the turn/llm spans
opened in metabot.agent.core, the tool span in metabot.self.core, and
*parent* conveyed across bound-fn* into the virtual-thread tool executor
— which the ai-tracing unit tests exercised only at the primitive level.

Also pin eval-capture off for the namespace via a fixture. run-agent-loop
appends an eval_session data part to the stream whenever capture is active,
so every exact-match assertion on its output broke under MB_AI_EVAL_CAPTURE
(which dedicated eval instances set). The fixture keeps those assertions on
the production stream shape; the new test forces capture independently.

* ai-tracing: key MCP eval session on UUID correlator; complete finish-reason

Key the MCP eval-trace session on the session id's UUID prefix rather than
the full <uuid>.<base64> id: the prefix is stable across the conversation and
always filesystem/URL-safe, so a base64 payload that require-valid-session
accepts but safe-session-id-re rejects (e.g. `=` padding) can no longer make
checked-session-id throw ahead of the JSON-RPC try/catch and 500 the request.

Record :finish-reason on the empty-response and reduced (early-termination)
loop terminations too, so the turn span's :ai/finish-reason is populated on
every path, not just natural completion.

* ai-tracing: harden trace sink serialization and error capture

- emit!: fall back to a JSON-safe copy when an attribute value isn't
  encodable, so one bad value no longer drops the span (and, for a root
  span, orphans its children).
- span error events now carry the exception class and ex-data, not just
  the message.
- rename JSONL :start-ns/:end-ns to :start-epoch-ns/:end-epoch-ns (they
  hold wall-clock epoch nanos, not System/nanoTime).
- test the api trace-file path-traversal guard directly.

* ai-tracing: bound session ids, gate user-input build, snapshot finish-node

- Cap supplied eval-session-id at 200 chars on the API schemas and in
  checked-session-id, so a supplied id can't produce a filename that fails
  creation and silently drops the trace (charset was already enforced).
- Compute the turn span's :ai/user-input inside the capture-gated attrs map
  instead of unconditionally on every run-agent-loop call.
- finish-node takes a single consistent snapshot of the node atom.

* ai-tracing: enforce session-id cap+charset at API boundaries

Route the 200-char cap through ait/max-session-id-length everywhere (read
endpoint, run-agent-loop opts, POST /api/metabot params) instead of
hardcoding the literal, and bound the previously-unbounded read-endpoint
:session-id path segment.

Validate the charset via safe-session-id-re in the Malli schemas so a bad
eval-session-id 400s at the boundary rather than throwing deep in
checked-session-id and surfacing as a generic agent error. Anchor
safe-session-id-re with \A/\z so it stays exact under both re-matches (mint/
read checks) and re-find (Malli :re) — unanchored, :re accepted any string
containing a safe run (e.g. ../../etc/passwd).

* ai-tracing: key MCP eval trace on a harness-supplied session id

Let an eval harness name and later fetch an MCP conversation's trace. The MCP
endpoint honors an `x-eval-session-id` header — `dispatch-request` keys
`with-eval-session` on it (validated through `checked-session-id`, the single
source of truth for the safe-id contract), falling back to the `Mcp-Session-Id`
correlator when absent. This is the MCP analogue of metabot's `eval_session_id`,
needed because the client owns the `Mcp-Session-Id` and never exposes it.

Also record the resolved query on the construct-query endpoints as `ai/query`
(inert unless capturing): the MCP `construct_query` tool returns only an opaque
handle, so this is the only place a harness can recover the agent's query off
the trace to grade it.

* ai-tracing: address review — guard :reduced append, cover the read API

- run-agent-loop: on a :reduced stop (client disconnect / cancellation) the
  reducing fn has already terminated, so don't step it again to append the
  eval-session pointer or debug part — that violates the transducer contract.
  Fold both trailing appends into one capture-gated cond-> that no-ops on
  :reduced (also fixes the latent debug-branch case). The harness reads the
  JSONL file, not the stream, so a skipped pointer on disconnect costs nothing.
- agent-api: record :http/user-id in the respond closure, where +auth has bound
  *current-user-id* — it is unbound when the span opens, so direct HTTP callers
  previously recorded nil.
- ai-tracing.api: add endpoint integration tests — capture-gated 404,
  superuser-gated 403, missing-trace 404, and existing-trace 200.
- log: mark node->entry ^:private; document that trace-file retention is the
  operator's responsibility (append-only, no rollover, re-runs accumulate).
- mcp: extract the dispatch lambda (line length) and note the fresh-file-per-
  request fallback when neither session id is present. Mark pure tests ^:parallel.

* ai-tracing: drop dead exports, document capture id, harden json-safe

- Remove the `sanitize-sql` re-export and `event!`: neither has a
  non-test caller. Dropping `sanitize-sql` also removes ai-tracing's only
  dependency on the `tracing` module (trimmed from `:uses`). The sites that
  put a query in a span record the raw value on purpose (a scorer wants the
  real SQL/MBQL), so the sanitizer was advertising an inconsistency the
  design doesn't want.
- Document that `capturing`/`capture-reducible` is return-value-based: a
  session id supplied to an inner `with-eval-session` is ignored because
  capture is already active, so no `<id>.jsonl` is written on that path.
- `json-safe` now stringifies non-scalar map keys too, so the fallback can
  never itself throw and orphan the root span it exists to save. Covered by
  a vector-keyed-map regression test.

* ai-tracing: address review — gate pointers, bound json-safe, drop indirection

Correctness:
- capturing/capture-reducible no longer mint a session id, so the in-process
  path is truly file-less (read :trace) instead of writing a stray <uuid>.jsonl
- gate the trailing eval_session pointer on a non-nil *session-id* so the
  file-less path doesn't emit a pointer to a <nil>.jsonl
- add *retain-tree* so the in-memory span tree is only built when a caller
  reads it back (capturing); the file-routed path no longer pins heap for the
  whole run
- depth-bound json-safe so a deep/cyclic attr degrades to a string instead of a
  StackOverflowError escaping emit!'s catch
- agent-api trace wrapper: only record a plain-data :http/response (skip a
  streaming/opaque body rather than stringifying it); fix the stale comment

Cleanup:
- drop the eval-capture-enabled? indirection; entrypoints and tests consult the
  ai-eval-capture setting directly
- with-eval-session: inline supplied-id, ^:once, generic 404 gate message
- extract mcp dispatch-method to de-nest the JSON-RPC case
- remove the dead ai-tracing.core/event! kondo entry
- keep eval JSONL spans out of the shared test log (log4j2-test.xml)

Tests: cover the agent-api trace wrapper, the file-less no-pointer/no-file
behaviour, and drive the log-sink assertions through with-eval-session.

* ai-tracing: fix route sort order and wire settings through init

Two structural test failures on the branch:

- Move the `/eval-trace` route into sorted position in the route-map
  (keep-routes-sorted-test reads the file and asserts the keys are sorted).
- Add `metabase.ai-tracing.init` (requiring the settings ns), require it from
  `metabase.core.init`, and add it to the module's `:api` — so
  settings-namespaces-should-be-required-by-init-namespaces-test passes and the
  `MB_AI_EVAL_CAPTURE` setting is registered deterministically at startup rather
  than only when some instrumented namespace happens to load `ai-tracing.core`.

* ai-tracing: store span wall-clock timestamps as epoch millis, not nanos

Review: the epoch fields were nanos synthesized from currentTimeMillis (ms-
granular anyway), and precise sub-ms duration already lives in :dur-ms — so nanos
bought nothing. Rename :start-epoch-nanos/:end-epoch-nanos → :start-epoch-ms/
:end-epoch-ms (and the JSONL keys :start-epoch-ns/:end-epoch-ns → :start-epoch-ms/
:end-epoch-ms). End is still start + the monotonic duration (rounded to ms), so it
never reads a second, possibly backward-jumping wall clock.
2026-07-14 17:30:50 +02:00
Nick Fitzpatrick
85485ed925 Fix flaky bulk-move dashboard-questions e2e test (#76165)
visitDashboard waits on every dashcard query with cy.wait's default 5s
per-alias window; with 20+ cards the tail queries stagger behind the HTTP/1
concurrency limit and miss it (the dashcardQuery### "no request occurred"
flake). Add a dashcardTimeout option to visitDashboard and use it for the
large-dashboard visits in this test, so the downstream card assertions can
stay at their default timeouts. Also give the 20-request bulk move a longer
window, since its tail lags under CPU constraint.
2026-07-14 20:54:53 +05:30
github-automation-metabase
8d3584593a Auto-update documentation for master (#77657)
Update generated docs (master)

Co-authored-by: github-actions <github-actions@github.com>
2026-07-14 10:09:10 -04:00
Kamil Mielnik
6547e398ee GDGT-2748 Broken Security Center layout in error state (#77704) 2026-07-14 20:39:51 +07:00
Chris Vandoodewaard
a6b0d2c7d6 Clean up stale step condition in backend.yml (#77605)
* remove dead condition, update to match other checks

* just use always
2026-07-14 09:08:06 -04:00
Chris Truter
4d04a9743c MCP notes on archiving questions and dashboards (#77569) 2026-07-14 14:34:05 +02:00
Nemanja Glumac
7712c474dd Run master's ci-conductor sources on release branches (#77625)
The ci-conductor scripts are shared CI infrastructure: every supported
release branch runs them, and they keep evolving on master. A copy
committed to a branch goes stale, and syncing six branches by hand on
every change does not scale.

Add a prepare-ci-conductor action that overlays release/ci-conductor and
e2e/support/ci_conductor.ts from master, so a release branch runs the
current scripts while its workflow wiring stays branch-historical.
Anything headed for master uses its own sources, so a PR can still test
its own changes.

quarantine-gate and report-failures-to-ci-conductor delegate their bun
setup to it. prepare-cypress calls it too, because e2e/support/config.js
imports the reporter at Cypress bundle time and it has to be in place
before the run starts.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-14 14:32:43 +02:00
metamben
dbedcbfbd4 Grouping set pivot (#76560)
* Implement schema, lib helpers, viz-settings + query -> query

* Implement grouping-set compilation

* Implement query nesting to support breakouts with parameters

For example, when selecting nested JSON fields in postgres,
the generated SQL query contains prepared query parameter
placeholders and the engine cannot determine that all copies
are the same expression.
2026-07-14 11:05:24 +00:00
Alexander Polyankin
25eebabf11 2FA E2E tests (#77671)
* 2fa e2e

* tests
2026-07-14 06:40:21 -04:00
Timur Mashara
30daa26a7b GRO-554 update storage upsell (#76052)
* GRO-554 update storage upsell

* combine 2 enabling storage modals

* redesign csv tab + storage upsell

* update gdrive panel upsell / small tweaks on supported DBs for upload

* move StoragePurchaseModal + StorageSetupProvider to ee

* revert unnecesary test change

* remove etl-connections alongside dwh-rent on storage delete; add check for collecting analytics in upsell
2026-07-14 10:36:01 +02:00
Oleh K
ebea514c84 Keep dominant treemap share honest instead of rounding to 100% (#77602)
* Keep dominant treemap share honest instead of rounding to 100%

The treemap percent formatter used a fixed 2 decimal places, so a dominant
leaf's share rounded up to a misleading 100.00% (e.g. 100000 vs 1 rendered
as 100.00% instead of 99.999%).

Mirror the pie chart: derive the decimal count from every node share via
computeMaxDecimalsForValues, so a tiny sibling forces enough precision to
keep the dominant share honest. Floored at the existing two decimals so
ordinary treemaps are unchanged, and a genuine whole still shows a clean 100%.

Fixes GDGT-2761

* Pass tree to test setup via SetupOpts object
2026-07-14 10:15:29 +02:00
github-automation-metabase
622629ef6c Update translations 2026-07-14 (#77689)
* Update translation sources 2026-07-14

* Update translations

---------

Co-authored-by: github-actions <github-actions@github.com>
2026-07-14 07:04:45 +00:00
Fraser
d60573c199 Move single-consumer code to its consumer 2026-07-14 16:44:14 +12:00
Romeo Van Snick
71e305b6ab Dynamic/plugin route conformance (#77586)
* Add dynamic/plugin route conformance harness

* Add dynamic/plugin route conformance spec
2026-07-14 13:05:39 +10:00
Alexander Polyankin
e7211002cf Static viz imports optimization (#77658) 2026-07-13 22:40:54 -04:00
Romeo Van Snick
cf56c33cdd Delete react-router-redux and redux-auth-wrapper (#77590)
* Delete react-router-redux and redux-auth-wrapper

* Dedupe redux to a single v5 copy

Removing the @types packages dropped a transitive redux@3 pin that kept a
typeless redux at the top level and masked a redux@4-vs-RTK-v5 type conflict.
Force a single redux@5 so types stay consistent.

* Migrate remaining react-router-redux references

Drop the now-dead eslint import bans for the deleted package, remove the
obsolete redux-action cast in auth logout, and reword stale comments. Keep the
metabase/router provenance docs that name the package as their reference point.
2026-07-14 09:53:16 +10:00
Anderson
8eea1fc50b Convert visualization settings components and specs to TypeScript (#76759)
* Convert visualizations/components/settings/* to TypeScript (GDGT-1799)

* Remove castings

* Preserve null chart field values in field picker

* Address review
2026-07-13 20:23:26 -03:00
dpsutton
a420372ba0 Revert "update workflow triggers" (#77666)
Revert "update workflow triggers (#77662)"

This reverts commit bc0d27253e.
2026-07-13 17:57:21 -05:00
Fraser
0b7aa11b15 Remove querying e2e repros already covered by existing Lib/QP tests 2026-07-14 10:57:06 +12:00
dpsutton
bc0d27253e update workflow triggers (#77662) 2026-07-13 17:21:14 -05:00
Cam Saul
e3791b88e8 Change :template-tags from a map to a list (#77133)
* First pass for updating Lib

* Update metabase.lib.query.test-spec

* All Lib + Lib BE tests are passing

* Fix remaining tests in Lib + QP

* Update Lib JS template tag functions

* cljfmt

* Another round of test fixes 🔧

* Leave NativeQuerySnippet :template-tags alone for now; test fixes 🔧

* cljfmt

* kondo

* Test fixes 🔧

* FE test fix? 🔧

* Another round of test fixes 🔧

* Test fix 🔧

* Test fixes 🔧

* Test fix 🔧

* Test fixes 🔧

* PR feedback

* PR feedback

* 🔧

* Test fix 🔧
2026-07-13 14:14:16 -07:00
Michael Eby
6c25c78740 docs: pdfs in subscriptions (#77610)
* docs: pdfs in subscriptions

* Edit from Jeff
2026-07-13 17:08:04 -04:00
Nathan Voxland
b3cfb8d510 Persistent Queue (#76352) 2026-07-13 16:05:07 -05:00
Tyler Plude
2765c8d027 [GIT-74954] Fix search reindex hang on metric reference cycles (#77556)
Co-authored-by: mbql-backend-expert <agent@metabase.com>
Co-authored-by: Chris Truter <crisptrutski@users.noreply.github.com>
2026-07-13 20:50:43 +00:00
Jeff Bruemmer
dad63b3da3 docs - supported AI providers (#77603)
* supported AI providers

* overview

* models
2026-07-13 16:24:59 -04:00
Chris Truter
8ef62d8612 Support pgvector on the app DB with minimal config (#77371) 2026-07-13 20:20:24 +00:00
github-automation-metabase
e2e10c2867 Auto-update documentation for master (#77545)
Update generated docs (master)

Co-authored-by: github-actions <github-actions@github.com>
2026-07-13 16:20:15 -04:00
Nick Fitzpatrick
ee29a82916 remount EditorBubbleMenu on hide (#77575) 2026-07-14 01:30:18 +05:30
Tyler Plude
ffdd62caaa Disable harbormaster metabot feedback & add appdb MCP feedback (#76932)
* disable metabot feedback harbormaster; add appdb persistence for mcp feedback

* fix kondo

* re-add metabot enabled check; fix migration

* update to v64
2026-07-13 12:59:27 -07:00
Nick Fitzpatrick
6e6bca18d0 Make getState generic for createThunkAction (#77615) 2026-07-14 01:26:49 +05:30
technomancy
5a6a2d84e2 Use qualified db names for locks in snowflake. (#77548)
* Use qualified db names for locks in snowflake.

We're seeing some timeouts in Snowflake on CI. There are a few reasons
for this, but part of it is that we are locking a lot waiting for
access to the datasets. These locks are currently based on unqualified
database names, not hashed and branch-qualified, so they lock more
often than they need to. Using the qualified names spreads things out
a bit.

In order to do this, we need to change the `dataset-lock` method to
take the whole dataset (to hash it) not just the dataset's database-name.

* Fix upload test to not assume table set is stable.

The purpose of this test is to ensure that the created table is gone,
but the assertion it makes is far too wide. This breaks in snowflake
where we have other tests randomly creating tables in the shared cloud
DB across jobs.
2026-07-13 11:44:02 -07:00
Alexander Polyankin
669dc959ff Remove unused code (#77613)
* Remove unused code

* Remove unused code
2026-07-13 14:38:16 -04:00
Ethan McCue
3554cc36fb onboarding: add Github username to team, add Github -> Slack ID mapping (#77608)
Update JSON files
2026-07-13 14:31:21 -04:00
Andrei Chernykh
5340d25eea Convert enterprise auth session middleware to TypeScript (#77399)
* Convert enterprise auth session middleware to TypeScript

* Fix sessionMiddlware -> sessionMiddleware typo

* Justify getState type cast in application permissions reducer
2026-07-13 10:42:03 -07:00
Arik Aronov
7a39244afe Show redirect destination on the OAuth consent page (#77578)
redirect dest in concent page + test for 3 cases
2026-07-13 20:02:33 +03:00
Chris Truter
f9dce94f95 Omit empty optional fields when serializing a transform index request (#77594) 2026-07-13 16:26:53 +00:00
Riley Thompson
2d7ed54076 Finish mbql5 compilation for more drivers (#76549)
* mysql mbql5

* clickhouse mbql5

* starburst mbql5

* sqlite mbql5

* presto-jdbc mbql5

* druid-jdbc mbql5

* vertica mbql5

* athena mbql5

* hive-like mbql5

* fix databricks
2026-07-13 12:20:57 -04:00
bryan
f4d3f69010 Native 2FA: EE scaffold, TOTP core, two-step login, recovery codes (#77449) 2026-07-13 16:15:58 +00:00
Andrei Chernykh
88c9058a51 Convert snippets and application_permissions plugin modules to TypeScript (#77398)
* Rename snippets and application_permissions plugin modules to TS extensions

* Convert snippets and application_permissions plugin modules to TypeScript
2026-07-13 08:44:34 -07:00
Kamil Mielnik
bd2df5059b GDGT-2770 RFC 147. Require justification for type casts (#77168) 2026-07-13 22:06:32 +07:00
Ngoc Khuat
4a12356ec8 Add Snowplow tracking for Index Manager (#77600) 2026-07-13 22:03:52 +07:00
Chris Truter
8e13d485ec Allow MCP to create text cards and headings on dashboards (#77362) 2026-07-13 14:55:37 +02:00
Chris Truter
4d849db7f8 Force a full rebuild when a transform index request is :failed (#77593) 2026-07-13 18:29:38 +07:00
Nicolò Pretto
5a024bd2ff chore(modules): fix embedding violations and start enforcing most of the modules (#77517)
* [pr-3] Move SDK error types to embedding-sdk-shared

* [pr-3] Move SDK auth-config types to embedding-sdk-shared

* remove un-useful usage of SdkCollectionId to remove import of sdk code in core app

we don't really need that type and they both end up being `number | string`

* [pr-3] Move PLUGIN_NOTIFICATIONS_SDK to the core app plugins

I don't particularly like this: this is one of those "plugins" used
both to activate enterprise code and to inject behavior from the SDK
into the core app. We don't have an alternative at the moment, so this
is the change with the smallest blast radius. The plugin was already
used in the core app, so this just moves it to the right place.

* [pr-3] Move onEditQuestion from the SDK dashboard context to DashboardContext

DashCardMenuItems (feature/dashboard) reached into the SDK bundle's
SdkDashboardContext just for the onEditQuestion override.
I moved the onEditQuestion to the DashboardContext instead, as
it's used in the core app dashboard.

* [pr-3] Remove CommonSdkStoryWrapper from SimpleDataPicker stories

It was not needed

* [pr-3] Move useLazySelector to the SDK package

The hook exists to read the lazy-loaded bundle's redux store from the
npm package, so the package is its natural home. Its only bundle-side
consumer, useInitDataInternal, already receives the redux store as a
parameter and now subscribes to it directly instead of going through
the window props-store singleton.

* [pr-3] Introduce SdkSharedStoreState

Some core app code currently needs to read _one_ piece of information
from the SDK redux state, I moved that piece of info into a new type
called `SdkSharedState` which I documented as being something we
should avoid adding to in the future.

* [pr-3] Promote embedding-sdk-bundle to the app tier

Promotes the sdk bundle to app tier, it needs a special rule for the
bridge
module that we'll hopefully clean up in the future

* [pr-4] Promote embedding-iframe-sdk to the app tier

EAJS becomes app tier, but we need to whitelist the theme preview from
importing it

* [pr-5] Move DashboardSharingEmbeddingModal to the dashboard module

The modal is dashboard UI living under metabase/embedding, giving the
embedding module an outgoing edge into dashboard (it imports
metabase/dashboard/selectors). Move it next to its domain so the next
commit can enforce the embedding module's outgoing boundaries.

* [pr-5] Move UserForm and group helpers to the common module

UserForm is used by the new "invite people to view" modal
(InviteToViewModal, which lives in metabase/embedding, shared tier),
so it moves out of feature/admin down to metabase/common together with
GroupsMultiSelect and the group utilities it depends on. Import paths
updated, no logic changes.

* [pr-5] Move DashCardMenuItem to the embedding-sdk plugins contract

It's imported by shared/embedding-sdk but it lived in feature/dashboard,
moved it down to remove violation that will be enforced on one of the next
commits.

* [pr-5] Enforce outgoing boundaries for shared/embedding and shared/embedding-sdk
2026-07-13 12:56:31 +02:00
Ngoc Khuat
fe4a72d76f Record model views in the view log (#77091) 2026-07-13 09:11:59 +00:00
Nicolò Pretto
31e79dc02d create new embedding modules - first pr (#77263)
* [pr-1] Define embedding modules

Defines the embedding modules without promoting them yet: modules whose
back-edges still need cleanup stay at their current tier (shared, outgoing
unenforced). Each module is then promoted to app in its own follow-up PR,
together with the fixes its back-edges require.

* [pr-1] Promote embedding-sdk-package to the app tier

The npm package is an entrypoint and should be able to import from
anything, and nothing should import from it.
I raised it up as app tier

* [pr-1] Promote embedding-sdk-ee to the app tier

This should probably be "embedding-features" in the future, but for now
I'm moving it to app to be above enterprise (which it imports from) and
to prohibit other things from importing from it

* [pr-2] Move LegacyStaticEmbeddingModalProps to the plugins contract

Module `embedding-iframe-sdk-setup` will be moved to app tier, so we move
`LegacyStaticEmbeddingModalProps` to the oss plugin file to avoid an import
going up to app

* [pr-2] Promote embedding-iframe-sdk-setup to the app tier

`embedding-iframe-sdk-setup` imports EAJS, which is app tier
so this also needs to be brought up to app tier
TBD how we want to structure this, but it kinda makes sense that some
parts of the core app are above EAJS as they use it (we also use it
to render theme previews in the admin settings for themes)
2026-07-13 09:28:59 +02:00
Chris Truter
64dfbf0bb3 Dedup the modules config.edn writer (#77571) 2026-07-13 08:32:30 +02:00
Romeo Van Snick
9a6f10f9dc Replace redux-auth-wrapper with guard components (#77259)
* Replace redux-auth-wrapper guards with facade guard components

* Convert admin route guards to facade guard components

* Full-page redirect for absolute post-login redirect targets

* Normalize post-login redirect target to an absolute URL

* Convert transforms route guard to facade guard component
2026-07-13 15:44:24 +10:00
Romeo Van Snick
1ad3f2b114 Move onEnter/onChange/onLeave to components and effects (#77264)
* Move root route onEnter/onChange/onLeave into components and effects

* Replace data-studio index onEnter redirect with a component

* Address review: settle LoadCurrentUser on rejection, drop test any-cast

* Point test Route import at the metabase/router facade

* Freeze has-user-setup on entry so the setup wizard is not interrupted

* Colocate route lifecycle components with the modules that own them

* Drop onEnter/onChange/onLeave from the facade's Route props
2026-07-13 14:47:04 +10:00
Tyler Plude
98424e1a61 [BOT-1807] Add metabot treemap chart support (#77568)
* add treemap chart support

* fix fe lint
2026-07-12 21:31:42 -07:00
Romeo Van Snick
4d47327087 Fix forbidden react-router-redux import in transforms route-guards (#77581)
Use metabase/router routerActions in transforms route-guards
2026-07-13 12:33:32 +10:00
Romeo Van Snick
29993aa6db Typescript 7 (#73979)
* Update to typescript 7.0 (beta)

* Switch to tsgo in scripts

* Remove NODE_OPTIONS from typecheck script

* Use typescript 7 instead of native-preview, but keep 6 around for lint

* Use typescipt 7.0.2

* Use real typescript 6.0.3 for eslint, run tsc 7 by explicit path

* Fix type errors surfaced by typescript 7
2026-07-13 08:41:36 +10:00
Alexander Polyankin
733e1c6f3e Change defaults for graalvm (#77573) 2026-07-11 18:22:31 -04:00
Alexander Polyankin
97f82c0792 mb-sql-parsing-mode=python (#77558)
* refactor(sql-parsing): protocol + graal split, render.js-style context pool

Mirror the static-viz renderer structure (channel/render/js) for the sqlglot
parser:

- protocol.clj: strongly-typed SqlParser protocol for the sql_tools operations
- graal.clj (replaces pool.clj): GraalPy implementation on a 0..2 dirigiste
  pool; contexts share one refcounted Engine and one bootstrap Source, created
  with the first context and closed with the last, so an idle pool releases
  all native memory (replacing the old TTL/min-size-1 leak mitigation);
  timed-out contexts are interrupted and disposed instead of released
- common.clj: create-pool copied as-is from render.js.common (replaces the
  PythonEval protocol); the future external-python impl will share it
- core.clj: public API unchanged; keeps JVM-side pre/post-processing
  (VALUES stripping, field/error conversion) and delegates through the
  protocol

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

* tune(sql-parsing, static-viz): 0..3 pooled graal contexts, 10-minute idle reap

:idle-minutes is now an explicit create-pool option in both pool factories
(no default): graal pools (sqlglot + static-viz) keep idle workers for up to
10 minutes, the node renderer pool stays at 1.

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

* feat(sql-parsing): native CPython parser, mirroring the static-viz node renderer

- python.clj: :python SqlParser running sqlglot in a pool of external CPython
  child processes speaking newline-delimited JSON over stdin/stdout
  (sql_tools_cli.py); in dev the child imports straight from
  resources/python-sources, from the jar the sources are written to a fresh
  temp zip per spawn (zipimport) and deleted with the process; single-process
  pool (0..1, 1-minute idle reap), timeout kills a wedged process, one retry
  when an acquired process turns out dead, call-level Python errors release
  the healthy process back
- settings.clj + parser.clj: sql-parsing-mode setting (:graalvm default |
  :python) and the mode-selection namespace, like static-viz-mode/renderer
- common.clj: python-sources locations + dev sqlglot install move here from
  graal.clj (shared by both transports), plus make-parser building the
  protocol reify over a transport call fn (marshalling written once)
- fix latent nil-schema bug in validate-query arg encoding: (json/encode
  (or schema "{}")) double-encoded, making Python treat the string "{}"
  as a strict-mode schema; encode an empty map instead

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

* fix(sql-parsing): transport-agnostic parse errors; 10-minute idle for process pools

Both parser transports now throw the same ex-info for Python-side failures
(common/call-failed-ex: :sql-parsing/error + extracted Python error type) —
graal wraps PolyglotException, the CPython transport wraps its ok:false
responses — and core exposes parse-error? so callers stop catching
PolyglotException (sql-tools.sqlglot updated; a python-mode instance
previously bypassed its parse-error fallbacks entirely).

Also raise the external-process pools (sql-parsing python, static-viz node)
to a 10-minute idle reap, matching the graal context pools.

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

* test(sql-parsing): un-nest testing blocks

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

* build(docker): install python3 for the :python sql-parsing mode

Both images already carry nodejs for the :node static-viz renderer; add
python3 (~45MB on alpine) so MB_SQL_PARSING_MODE=python works out of the box.

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

* build(docker): default sql-parsing to python and static-viz to node in the entrypoint

The image ships python3 and node, so prefer the external-process backends
(lighter and faster than in-process GraalVM) unless MB_SQL_PARSING_MODE /
MB_STATIC_VIZ_MODE are set explicitly, following the MB_JETTY_HOST pattern.

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

* tune(static-viz): keep the node process pool at a 1-minute idle reap

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

* fix(sql-parsing): wire settings into module init

metabase.core.init-test requires every .settings namespace to be reachable
from an init namespace; add metabase.sql-parsing.init and register it.

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-11 16:16:44 -04:00
Chris Truter
6188ef843f Resolve the default search engine from capability precedence (#77418)
* Resolve the default search engine from capability precedence

The search-engine setting's :appdb default meant the engine precedence
list never chose semantic, no matter how many of its dependencies were
met. Engine selection now works in three layers:

- supported-engine? is a pure capability check (app-db type, premium
  features, infrastructure) and no longer reads the search-engine
  setting.
- The default engine is the configured override when servable,
  otherwise the first supported engine in the precedence
  (semantic > appdb > in-place). Unknown configured values warn once
  and degrade instead of breaking all of search.
- Indexes are maintained for the default engine, the engines it
  declares as dependencies (semantic mixes in appdb results), and any
  engines opted in via the new additional-search-engines setting.

Reading the search-engine setting now resolves the engine that
actually serves search, so the admin UI needs no changes; the raw
override is available via configured-search-engine.

An explicitly passed per-request search_engine that cannot serve now
returns a 400 naming the cause (unknown / not supported / not enabled)
instead of silently falling back; legacy engine cookies keep the
fallback. The engine-active prometheus metric now reports active-set
membership rather than capability.

MB_SEMANTIC_SEARCH_ENABLED remains a kill switch, folded into the one
canonical semantic availability predicate (so repair/cleanup tasks now
respect it too); it will be removed once Cloud stops setting it.

Part of BOT-1832

* Tighten search engine docstrings and comments

* Validate cookie-carried search engines before use

A stale engine cookie naming an unmaintained index (e.g. appdb on an
in-place-default instance) now degrades to the default engine instead
of querying a missing index. The in-place exemption in engine-active?
uses = rather than isa?, so derived engines don't inherit a free pass.

Updates the prometheus search-engine-metrics-test to the new
engine-active semantics.

Part of BOT-1832

* Serve per-request engines through validated query-params; gate semantic writers on activity

Review follow-ups from roborev job 2600 and the workflow review:

- The engine middleware now reads and writes :query-params - the
  :params injection had been dead since the api.macros migration, so
  engine cookies had no effect on the served engine. Cookie values are
  validated (stale/unknown degrade to the default), and param values
  are normalized: blank means absent, the qualified form the API
  returns in :engine is accepted, and the legacy fulltext name maps to
  appdb at the boundary so activity checks use exact matches.
- engine-status in search.engine is the one classification of whether
  an engine can serve (:ok/:unknown/:unsupported/:inactive); the API
  layer maps it to 400s and no longer re-encodes engine invariants.
- Semantic fallback (EE core and the metabot search tool) prefers
  engines with a maintained index over merely supported ones, so an
  in-place default with additional-search-engines=semantic mixes with
  the warm appdb index instead of in-place.
- The semantic indexer and index-repair tasks gate on the new
  semantic-search-active? instead of availability, so a supported but
  inactive semantic index no longer accrues hourly embedding spend.
- active-engines guards the pre-init nil default and only
  capability-checks dependency entries.

Part of BOT-1832

* Canonicalize legacy engine names at every boundary; tolerate repeated engine params

search.engine/canonical-engine resolves legacy names (fulltext -> appdb)
for configured values, additional-search-engines, and request
params/cookies alike, so active-engine membership compares exactly.

A repeated search_engine query param parses as a vector; the middleware
now passes it through for schema validation to reject with a 400
instead of throwing.

Part of BOT-1832

* Review cleanups: single evaluation of engine resolution values

Bind configured-engine, the parsed param engine, and active-engines
once per expression instead of re-evaluating (Copilot); remove blank
lines inside the check-engine-serves! case form (CodeRabbit).

Part of BOT-1832

* Engine-active metric means can-serve; harden param parsing and dependency filtering

engine-active shares engine-status's definition: in-place is always
active while it exists, indexed engines while their index is
maintained. Fixes the prometheus test assertion that compared a metric
to itself.

param->engine strips the search.engine/ prefix rather than splitting on
slashes, so junk values 400 with the full value named instead of
validating their last segment, and degenerate values like // cannot
produce an empty or nil keyword.

active-engines filters dependency engines through known-engine? before
supported-engine?, matching the startup-ordering guard in
supported-engines.

Part of BOT-1832

* Reject malformed explicit engine values instead of treating them as absent

A non-blank search_engine that strips to a blank suffix (e.g.
search.engine/) parses to an unknown engine and 400s naming the raw
value; only genuinely blank values fall through to the cookie/default.

Part of BOT-1832

* Clarify the unknown-engine filter comment in supported-engines

* Fix review findings: runtime kill switch, csv hygiene, cookie unpinning, shared fallback

- Semantic Quartz jobs are scheduled when the instance is capable
  (pgvector + feature) and check availability/activity per execution,
  so the kill switch works at runtime again instead of gating job
  scheduling at boot.
- semantic-search-active? is plain active-set membership; the HNSW
  build gates on it like every other index writer.
- additional-search-engines values are trimmed, blanks dropped, and
  qualified/legacy names canonicalized (prefix handling now lives in
  canonical-engine, the one boundary fn).
- An explicit blank search_engine clears the engine cookie (the unpin
  mechanism this branch had removed) instead of being ignored.
- fallback-engine lives in search.engine; the EE semantic core and the
  metabot search tool share it.
- The runtime-activation backfill note moved from the
  additional-search-engines description to a comment.

Part of BOT-1832

* Initialize the semantic index from repair when none is active

Semantic can become active at runtime (kill switch re-enabled, or added
to additional-search-engines) without init! ever having run; the hourly
repair task now initializes and backfills in that case instead of
no-oping until a manual /re-init.

Also renames warn-once to warn-once! per the side-effect convention and
adds end-to-end coverage for the pinned-cookie and blank-unpin paths.

Part of BOT-1832

* Cover the repair-initializes path; unpin test asserts the resolved default

The blank-unpin api test compared against a hard-coded appdb default,
which does not hold on MySQL/MariaDB app dbs. New repair test starts
from a blank pgvector db and asserts repair-index! creates an active
index and gates the documents.

Part of BOT-1832

* Trigger search index init when additional engines are set at runtime

Registers the (previously dangling) init-job-key as a durable,
trigger-less quartz job wrapping the search init, and the
additional-search-engines setter fires it when it exists. In tests the
scheduler is not running, so the setter stays side-effect free there;
env-var configuration is covered by the startup init.

Part of BOT-1832

* Rename the engine cookie and cover the pin/unpin round trip

metabase.SEARCH_ENGINE becomes metabase.SEARCH_ENGINE_OVERRIDE, so the
population of long-lived cookies written before engine validation
existed stays inert.

The round-trip test covers pinning via an explicit param, serving from
the cookie, and clearing it with a blank param.

Part of BOT-1832

* Order semantic capability gates cheapest first

The license check short-circuits before the pgvector URL check, whose
slot becomes a DB probe under BOT-1796.

Part of BOT-1832

* Only trigger search init when the setting change activates an engine

Semantic init re-gates every searchable document, so an unconditional
trigger made any write to additional-search-engines cost a full app-db
sweep. The setter now diffs active-engines across the set and triggers
only for newly activated engines.

Part of BOT-1832

* Defer the engine-activation trigger to after commit

The activation diff and quartz trigger run via do-after-commit in a
future (extracted to trigger-init-for-newly-active-engines!), observing
the final committed settings state - a surrounding set-many! may
include the setting that makes the engine supported - without I/O on
the transaction's thread.

The cookie round-trip test uses the in-process client so the handler
runs inside the fixture's engine and index bindings.

Part of BOT-1832

* Review nits: log async trigger failures, quote the cookie regex, fix a docstring

The post-commit init trigger logs exceptions instead of dropping them
in the future; the cookie test quotes the cookie name before building
its regex; build-hnsw-index-async! says active, matching its gate.

Part of BOT-1832

* Schedule semantic jobs on the boot-static gate; indexer initializes missing indexes

Job scheduling happens once at startup, so it now gates on the only
boot-static input: whether a pgvector DB is configured. The runtime
gates (license, kill switch, engine activity) are checked per
execution, so applying a license or re-enabling the kill switch at
runtime no longer strands semantic as an unindexed default until
restart.

The indexer's 20-second tick initializes the index when it is missing,
so every runtime activation path (license, kill switch, setter on a
stale cluster node) converges within seconds instead of waiting for the
hourly repair or a restart.

Also: the blank-param unpin deletes the engine cookie (max-age 0)
instead of writing an empty 20-year one; the activation trigger helper
lives in search.task.search-index with static requires; the setter test
uses poll-until for the async positive case and a direct synchronous
call for the negative.

Part of BOT-1832

* Runtime self-heal initializes all active engines and the HNSW index

The indexer's missing-index branch runs the generic search init, which
covers newly active dependencies, and applies the same HNSW-strategy
safety net as task registration.

Part of BOT-1832

* Ensure the HNSW index on the indexer's active path

An index-backed strategy configured while semantic was inactive misses
the setter's build event; the indexer tick now fires the async build
when the active index lacks its HNSW index. The pg_indexes existence
check is self-limiting: CONCURRENTLY registers the index when the build
starts.

Part of BOT-1832

* Fix engine tests on app dbs without appdb search support

Explicitly requesting an unservable engine now 400s instead of silently
falling back, so tests must not hard-code appdb: the data-studio search
tests iterate only supported engines, the cookie staleness test pins
in-place (servable everywhere), and the not-enabled case runs only
where appdb is supported.

Also realigns warn-once! call args (cljfmt).

Part of BOT-1832

* Keep semantic active under the search test fixtures

active-engines now derives from the default engine, so fixtures that
pin default-engine were silently deactivating semantic: semantic
queries in the metabot search tool fell through to the term engine.
Both fixtures pin active-engines to the set the old derivation gave
them - appdb plus semantic when supported, or semantic alone for
legacy search.

Part of BOT-1832

* Rename with-new-search-* test fixtures to with-appdb-search-*

The appdb engine predates semantic search; new no longer disambiguates.

Part of BOT-1832

* Update the last supported-implies-active consumers

The metabot semantic-search feature predicate gates tool schemas on
engine-status :ok rather than capability, so semantic_queries is only
advertised when a semantic index is actually maintained.

The metric collector runs only when semantic is active, and index
cleanup no-ops until the bookkeeping tables exist: available but never
initialized is now a steady state, and both jobs would otherwise warn
or throw about missing tables on every run. Cleanup still runs while
merely available so an opted-out instance's leftover indexes get
dropped.

Part of BOT-1832

---------

Co-authored-by: Tyler Plude <tsplude@gmail.com>
2026-07-10 20:16:56 -07:00
Romeo Van Snick
544a0c2ba8 Migrate query_builder/analytics to TypeScript (#76934)
* Migrate query_builder/analytics to TypeScript

* Type Card.creationType and drop analytics cast

Address review: type Card.creationType as a union instead of a plain
string, narrow Question.creationType(), and make the new_question_saved
type field optional/nullable to match the Snowplow schema. Removes the
cast in the analytics tracker.

* Drop as const in load-question via Card annotation
2026-07-11 09:33:43 +10:00
Romeo Van Snick
836e12b526 Re-own react-router-redux behind the metabase/router facade (#77142)
* Re-own react-router-redux mechanisms behind the metabase/router facade

* Wire store, app and store types onto the re-owned router facade

* Re-point react-router-redux call sites onto metabase/router

* Update router tests and harness for the re-owned facade

* Ban react-router-redux imports outside metabase/router

* Model routing state's null location contract instead of casting

* Flatten CallHistoryMethodAction into per-method history action types

* Match history actions with ts-pattern in routerMiddleware

* Preserve explicit null location in createMockRoutingState
2026-07-11 09:33:29 +10:00
Ben Grabow
ba83271710 Auto-fix modules config.edn (#77541)
* Auto-fix modules config.edn

* Extract generic nrepl integration wrapper

* Remind claude to use this

* Demo the module config fixer with some tests
2026-07-10 17:20:33 -05:00
dpsutton
6b855cbe81 feat(dev): browser-based email template previewer (#77546)
Adds `bun run email-dev`: a small Bun server + static page that renders
the Handlebars email templates in src/metabase/channel/email/ with
editable sample data, so designers and copywriters can iterate on email
copy and layout without running Metabase or sending real emails.

- live-reloads when a .hbs file changes on disk (1s polling)
- Fields/JSON panels to fill in template values; edits persist in
  localStorage per browser
- Desktop/Narrow/Phone width toggles and Copy HTML
- sample-contexts.js mirrors the real send-time contexts (traced from
  messages.clj and the notification handlers)
- mirrors the jknack custom helpers (equals, format-date, now, initials,
  card-url, dashboard-url, trash-url) in handlebars.js

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-10 17:09:04 -05:00
Andrei Chernykh
b8673198cd Migrate Link, ListItem, and LoadingSpinner from Emotion to Mantine + CSS modules (#77323)
* Migrate Link, ListItem, and LoadingSpinner from Emotion to Mantine + CSS modules

* Fix TableList disabled-state assertions by exposing data-disabled instead of relying on Emotion-injected styles
2026-07-10 13:47:48 -07:00
lbrdnk
87f0514519 Mention archival and soft deletion in MCP metric update API (#77525)
* Mention archival and soft deletion in MCP metric update api

* Update src/metabase/agent_api/api.clj

Co-authored-by: Chris Truter <crisptrutski@users.noreply.github.com>

* Update src/metabase/agent_api/api.clj

Co-authored-by: Chris Truter <crisptrutski@users.noreply.github.com>

* Extend update-metric-archive-test

---------

Co-authored-by: Chris Truter <crisptrutski@users.noreply.github.com>
2026-07-10 22:43:57 +02:00
Nemanja Glumac
dea12ca75c Wire the test-driver action to work with the Quarantine switch (#77476) 2026-07-10 21:12:56 +02:00
Nemanja Glumac
71863190b1 Wire the quarantine switch into the embedding e2e workflows (#77518) 2026-07-10 19:07:34 +02:00
Eric Normand
5a4f82063e Name the referring entity in remote sync not-found errors (#77430)
* Name the referring entity in remote sync not-found errors

When an import references content that doesn't exist on this instance, the
error named only the missing entity's raw serdes id. It now also names the
entity holding the dangling reference, and backtick-quotes names and ids so
leading and trailing whitespace is visible.

`load-one!` takes the referrer as an explicit parameter rather than carrying
it on the load context: `load-deps!` reduces over sibling deps and each
recursive `load-one!` returns its own context, so a context key would leave
later siblings labelled with the deepest child's referrer.

Message construction lives in `missing-reference-message` so the format can
change without touching the throw sites.

* Attach the referrer by catch-and-rethrow instead of threading it

Replaces the extra `load-one!`/`load-deps!` parameter with a try/catch around
the dependency load. The nearest enclosing `load-one!` unwinds first, so it is
the frame that attaches itself as the referrer; outer frames see the key
already present and rethrow unchanged. The original exception is kept as the
cause, preserving the stack trace of the detection site.

Adds an end-to-end assertion in bare-import-test that a real import of a Card
referencing a missing Database carries the Card as `:referrer`, which the
hand-built ex-info unit tests could not cover.

* Key the database-not-found error off ex-data, and name the referring card

`source-error-message` detected this case by matching "database not found"
against the cause's message text, then interpolated that raw internal string
into the user-facing error:

  Import failed: A referenced database does not exist on this instance.
  table id present, but database not found: [clickhouse nil some_table]

`import-table-fk` now tags the throw with `:error ::database-not-found` and
`:db-name`, and the render walks the whole cause chain looking for that key
rather than checking only the immediate cause. `::load-failure` carries the
referring entity, so both missing-content paths now render through
`missing-reference-message`:

  Import failed: Card `Some card` (`abc123`) references Database (`clickhouse`),
  which does not exist on this instance. ...

Also fixes `:database-names` in that ex-data, which selected names from
:model/Table rather than :model/Database. It has no consumers.

The end-to-end test uses a result_metadata `:table_id`, since that is the path
that actually reaches `import-table-fk` with an undeclared database:
`result-metadata-deps` derives deps only from `:field_ref`, and a Card's own
top-level `table_id` is recomputed from `dataset_query` by
`populate-query-fields` on insert.

* Backtick-quote file paths in remote sync ingest-error messages

GHY-3992 asks for content names to be quoted so leading and trailing
whitespace is visible. The ::not-found path already did this; the
ingest-errors branch still joined raw paths, and the message already uses
": " between path and reason and "; " between entries, so a path containing
punctuation or trailing space was ambiguous to read.

No fallback is added for a nil :file. All three ingest-error producers
(ingest.clj file-hierarchy!, ingestable.clj read and parse failures) always
set it, and only YamlIngestion and IngestableSnapshot produce a non-empty
ingest-errors; the other Ingestables delegate.

Splits source-error-message-entity-not-found-test into three deftests, one
per error branch, which kondo requires now that each has grown assertions.

* Render load-failure errors with the entity name, reason, and stripped keys

::load-failure fell through to the generic "Failed to reload from git
repository: <ex-message>" fallback, showing a NanoID and burying the
stripped-keys note. It now reads:

  Import failed: could not save Card `Orders by Month` (`abc123`).
  NOT NULL constraint failed: report_card.display.

and, when the entity was part of a dependency loop, adds "It may have been
saved without: `dashcards`, `parameters`." — a partial row for it survived
the import, which the user previously had no way to learn.

Renames the ::load-failure ex-data key `:referrer` to `:entity`. It names the
entity that failed to load, which is a referrer only relative to the missing
database in the ::database-not-found case; that branch now reads `:entity` and
passes it as the referrer. ::not-found keeps `:referrer`, where it really is
the parent.

The new branch is ordered after the tenant-collection and database-not-found
branches, both of which match on causes that a ::load-failure wraps.

::circular is left on the fallback. Rendering its cycle needs an ordered
expansion chain — `expanding` is a set — and it only fires when the
key-stripping recovery has already failed.

* Address CodeRabbit review

- Remove a duplicated `testing` block in impl_test.clj. It was byte-identical
  to the one above it, introduced when the deftest was split. Replaced with a
  doseq covering trailing, leading, and no surrounding whitespace.
- Mark `missing-reference-message` and `load-failure-message` private; neither
  is used outside impl.clj.
- Capture the exception once in bare-import-test's not-found case instead of
  running the same failing import twice, and flatten the resulting nested let.
2026-07-10 16:24:16 +00:00
Riley Thompson
9197dc9057 Fix path in location-connection-properties (#77322)
fix path
2026-07-10 14:53:47 +00:00
Sébastien
0b9e1c0be4 Show the SQL editor when useMetabot opens a native question (#77370) 2026-07-10 16:18:42 +02:00
github-automation-metabase
46d217cf64 Auto-update documentation for master (#77469) 2026-07-10 09:23:39 -04:00
Chris Truter
f9ecaf7f92 Fix weak assertion in create-table-from-schema!-test (#77520) 2026-07-10 13:13:42 +00:00
Chris Truter
ae56aaf2b2 Fix the shadow-cljs warning from lib.core's macro re-export (#77521) 2026-07-10 13:08:42 +00:00
Egor Grushin
ab9a3e191a GDGT-2766 GDGT-2766 Migrates deprecated FormTextInput and FormInput components (#77161)
* GDGT-2766 GDGT-2766 Migrates deprecated FormTextInput and FormInput components

* GDGT-2780-2766 DRY FormInputWidget

* GDGT-2780-2766 fix lost margin

* replace with new FormField

* fix marging

* rollback be.visible to exist in action e2e specs

* replace HTML_INPUT_TYPES map with inline ts-match

* fix margin
2026-07-10 13:54:37 +01:00
Sébastien
9f42bcf323 Apply global dashboardCardMenu plugin from MetabaseProvider to dashboards (#77500) 2026-07-10 14:28:51 +02:00
Chris Truter
130888462d Fix the metabot semantic-search tests not runing in CI (#77519) 2026-07-10 11:18:03 +00:00
Ngoc Khuat
32a869b1e6 Index manager (#75848) 2026-07-10 11:05:07 +00:00
Alexander Polyankin
f7f8697947 Add tests for the node static-viz renderer (#77508) 2026-07-10 03:41:13 -04:00
Timothy S. Dean
960d036afd Bump js-yaml to 4.3.0 (#77459)
Bump js-yaml to 4.3.0
2026-07-10 00:49:07 -06:00
da
60e1b995d3 Add CSV uploads to Snowflake (#77239)
Co-authored-by: Chris Truter <chris@metabase.com>
2026-07-10 04:18:36 +00:00
Sébastien
15195d006a fix(sdk-bundle): restore back button after "Edit question" in embedded dashboards (#77389) 2026-07-10 06:14:14 +02:00
appleby
5bd7fa6247 Support OpenRouter (#77139)
* Fix metabase.metabot.api/openrouter-model-group

Fallback to parsing the id if the display_name has no ":"-separated prefix.

* Add a default OpenRouter model so connect-without-model works

Without an entry in default-llm-metabot-model-by-provider, a PUT /api/metabot/settings that connects openrouter with
only an API key would save the key but silently fail to switch llm-metabot-provider.

* Use real dotted OpenRouter model IDs in defaults and docs

OpenRouter model IDs use dots in version numbers, e.g. anthropic/claude-haiku-4.5. The hyphenated
anthropic/claude-haiku-4-5 referenced by the default args and docstrings does not exist.

* FE: enable openrouter provider in metabot admin UI config

* Whitelist openrouter models

Filter openrouter list-models down to the same curated Anthropic and OpenAI model set the direct providers support,
instead of returning the full ~340-model catalog.

* Throw an exception if callers pass :ai-proxy true for openrouter

Similar to bedrock and openai, supporting this would require work on the ai-service side, and we already reject
non-anthropic providers in validate-metabase-managed-provider!

* Remove explicit credentials check in list-all-models

We want to allow callers to omit the creds and fallback to the configured api key from settings. core/resolve-auth
still handles the auth check and will throw if no credentials are provided or configured.

* Support prompt caching for openrouter

Report `:cacheCreationTokens` and `:cacheReadTokens` in the `:usage`.

For anthropic models, add the `:cache_control` breakpoint on the system message to enable caching (openai caching is
automatic).

* Apply code review suggestion in AIProviderSettingsSection.unit.spec.tsx

Co-authored-by: Maksym Yakubych <undrfined@gmail.com>

* Add gpt-5.6 and drop gpt-5 from openrouter supported-models

See also #77450

* Apply code review suggestion in fe tests

Co-authored-by: Maksym Yakubych <undrfined@gmail.com>

---------

Co-authored-by: Maksym Yakubych <undrfined@gmail.com>
2026-07-10 00:47:30 +00:00
Alexander Polyankin
6eff4789f0 Static viz node renderer (#77419) 2026-07-09 20:16:11 -04:00
Egor Grushin
fe6bc8a408 Gdgt 2587 2581 replace deprecated numericinput components (#77117)
* GDGT-2587 GDGT-2581 migrate deprecated components

* GDGT-2587 GDGT-2581 get rid of deprecated components

* GDGT-2581 fix tests

* fix tests

* GDGT-2584 DRY FormNumberInputWidget

* GDGT-2587-2581 fix floats + cover the change with a test

* GDGT-2587-2581 fix a test

* GDGT-2587-2581 addressing PR's comments

* GDGT-2587-2581 small UX improvement

* GDGT-2587-2581 stronger assertions in model-actions test

* GDGT-2587-2581 remove spreading

* GDGT-2587-2581 scrollIntoView before visibility asserts

* GDGT-2587-2581 assert exist not visible for constraint errors
2026-07-10 01:00:25 +01:00
Timothy S. Dean
117020fc2e Pin linkify-it to 5.0.2 (#77457)
Pin linkify-it to 5.0.2
2026-07-09 17:06:06 -06:00
Egor Grushin
b9bba24cfd GDGT-2584 migrate FormTextArea (#77089)
* GDGT-2584 migrate FormTextArea

* GDGT-2584 remove unused code

* GDGT-2581 fix error labeling

* GDGT-2584 DRYed FormTextareaWidget

* GDGT-2584 make textarea resizeable for the snippet form

* GDGT-2584 restore actions

* GDGT-2584 fix margin

* GDGT-2584 fix margins
2026-07-09 23:27:35 +01:00
appleby
a817ed88a6 Add gpt-5.6 to openai supported-models (#77450)
* Add gpt-5.6 to openai supported-models

* Drop gpt-5 from openai supported-models
2026-07-09 22:21:36 +00:00
Eric Normand
0a3932e9cf Move remote-sync branch switching into Settings with destructive-action guard rails (GHY-4019) (#77286)
* Move remote-sync branch switching into Settings with guard rails (GHY-4019)

Branch switching ran a full import that hard-deletes any synced-collection
content absent from the target branch, and it lived as a routine app-bar
dropdown item. A forced switch could permanently delete never-pushed content.

Backend:
- spec: detect collection-scoped deletion conflicts (Cards/metrics, Dashboards,
  Documents, Timelines), not just the transform family; wire into get-conflicts
- import: expose force_deletion on POST /import so a forced version/dirty
  override no longer silently forces deletions
- async-import dirty guard now returns the dirty objects (what would be lost)
- PUT /settings rejects a read-write branch switch (must use the guarded import);
  read-only changes and first-time config still allowed

Frontend:
- remove the Switch branch affordance from the app-bar sync controls (branch
  name stays as a read-only label; push/pull intact); drop the switch-branch
  conflict variant
- add a guarded branch switcher to the read-write Settings panel: destructive
  warning copy, hard block when there are unsaved changes (lists them, no force
  path), destructive confirm when clean, stale-tab handling

* Refine Settings branch switcher: choice modal, admin gating, direct clean switch

Follow-up to the branch-switching rework, from review feedback:

- Offer a choice modal (push / new branch / discard) when switching with
  unsaved changes, instead of a hard block — restores the switch-branch
  conflict variant, now driven from the Settings panel BranchSwitcher.
- Drop the destructive confirmation on a clean switch: with everything pushed
  the switch is reversible, so it runs directly.
- Show a red "N unsaved change(s)" label beside the dropdown when dirty.
- Gate the switcher on superuser: non-admins (e.g. settings managers) see the
  section with an "admin required" message instead of a control they can't use;
  the section no longer depends on the admin-only branch setting being readable.
- Match the section subtitle styling to the other settings sections.
- Strengthen the import superuser test to cover a branch switch.

* Update remote-sync E2E for Settings-panel branch switching

Branch switching moved from the app bar to the Settings panel, so the
branching specs and helpers drive it there now:

- Replace the app-bar switch helpers with Settings-panel ones
  (visitRemoteSyncSettings, getSettingsBranchSwitcher,
  createBranchViaSettings, switchBranchViaSettings).
- Rewrite the branching tests to create/switch branches on the Settings
  page, navigating back to the app for content changes.
- Switching with unsaved changes opens the choice modal (wait for the
  unsaved-changes indicator first); a clean switch goes directly.
- Snowplow triggered_from: app-bar -> admin-settings.

* cljfmt

* Address review: guard-bypass fix, anti-join, shared removal predicate

- api: block blanking the branch in read-write mode too, so it can't be used to
  reset the branch-switch guard and then switch freely; regression test added.
- spec: compute collection deletion conflicts with a SQL anti-join + count/limit
  instead of loading every candidate and an exists? per row, so it scales when a
  switch would drop a large synced collection.
- Extract spec/removal-where-clauses as the single definition of what an import
  reconcile removes for a model; remove-unsynced! and the deletion-conflict check
  both build their WHERE from it (removes the duplicate build-entity-id-where-clause).
- Add a parity test asserting the conflict warning is exactly the unsynced subset
  of what remove-unsynced! removes.
- Nits: be.visible for the dirty-warning indicator; wrap a long test string.

* Build the deletion-conflict WHERE with a thread-first instead of nested into/conj

* Give check-deletion-conflicts the same anti-join as the collection check

Was doing a t2/exists? per candidate (and materializing every candidate).
Now counts via one SQL anti-join, sharing removal-where-clauses and the new
model-id-column / unsynced-anti-join helpers with check-collection-deletion-conflicts.
Adds a direct spec-level test for it.

* Build collection deletion conflicts with cond-> instead of if/into

* Cover NativeQuerySnippet in the deletion-conflict warning

Generalize check-collection-deletion-conflicts -> check-content-deletion-conflicts:
warn before an import deletes any unsynced entity-id content, not just collection-
scoped models. This pulls in NativeQuerySnippet (global, no collection scope), which
otherwise fell through both conflict checks and could be silently deleted on a forced
import/branch switch. Collection stays excluded (structural; its contents are covered).
Adds a snippet test case.

* Address branch-switch review: drop force_deletion param, refetch dirty at switch, add tests

- Remove the unused force_deletion param from POST /import (schema, destructure,
  and async-import! call); internal force-deletion? threading is unchanged.
- BranchSwitcher refetches dirty state at switch time so a stale settings-page
  snapshot can't route a switch down the wrong (delete-without-warning) path.
- Add BranchSwitcher unit tests: non-admin message, dirty count label,
  clean direct switch, and the choose-what-to-do modal on the dirty path.

* Left-align the branch value in the settings switcher for consistency with other selects

* Show a 'Using <env var>' note when the sync branch is pinned by an env var

* Fix branch-switcher e2e: scroll the switcher into view, drop spurious branch-switched event

The Sync branch section sits below the fold at the default viewport, and Cypress treats an element
clipped by a scrollable ancestor as hidden, so the switcher assertions failed (surfaced by
testing-library as a misleading "Unable to find an element"). Scroll to it before asserting.

BranchSwitcher also reported a branch switch when creating a branch, emitting a spurious
remote_sync_branch_switched alongside the branch picker's remote_sync_branch_created. Creating a
branch forks the current one without a reconcile, so only the creation is reported now.
2026-07-09 22:15:44 +00:00
Nemanja Glumac
44dc41a7fa Introduce the Quarantine Control Knob (#77417)
Introduces a `QUARANTINE_ENGINE` variable that acts as a control knob. Either Trunk enforces a quarantine or CI conductor does. So far wired only in three places:
1. fe
2. be
3. e2e
2026-07-09 21:34:00 +00:00
Ben Grabow
f0ef171d25 Ghy-4069 minimal migration approach (#77297)
* Upgrade H2 -> SQLite sample DB by mutating database :driver
2026-07-09 16:29:28 -05:00
Chris Vandoodewaard
5373a65352 Revert "Update translations 2026-07-07" (#77456)
Revert "Update translations 2026-07-07 (#77151)"

This reverts commit 5f56057bfe.
2026-07-09 21:27:36 +00:00
Chris Vandoodewaard
a169d4ab75 remove experimental linear-release-sync workflow (#77302)
* remove experimental linear-release-sync workflow

* remove linear-release-lifecycle job from release workflow

* also cleanup helper functions
2026-07-09 16:47:05 -04:00
Timofey Kachalov
31a0379d5d Update jackson.* dependencies to 2.21.5 (#77427) 2026-07-09 23:55:33 +04:00
Eric Normand
950f453535 Preserve native model column types during serialization (GHY-4043) (#77405)
* Preserve native model column types during serialization (GHY-4043)

export-result-metadata checked (model? card) before the native branch, so
native models were routed through lib/model-preserved-keys — a metadata-merge
soft-key set that omits :base_type/:effective_type. On a read-only Remote Sync
target the column types could not be re-derived without executing the SQL, so
computed columns (e.g. STRING_AGG(...) AS names) fell back to type/* and their
filter UI collapsed to Is empty / Not empty.

Reorder the cond so native cards — models included — go through the branch that
preserves structural type info; only MBQL models, whose types are re-derivable
from the query at import, use the soft-key set.

* Update native-model extract test for preserved column types

extract-result-metadata-native-model-test asserted the old behavior — that a
native model dropped :base_type on export. Update it to expect structural type
info to survive, matching the GHY-4043 fix. Drop the now-unused clojure.set
require.
2026-07-09 19:31:44 +00:00
Kevin Kelleher
7a20b77fbd Add enable/disable setting for Transforms in Data Studio (#75710)
* transform enable/disable setting

* fix test, change approach for self hosted

* fix tests

* fix tests, self review

* add tests

* fix ci

* fix lint

* address review comments

* address review comments

* fix ci

* changelog 63 -> 64

* fix lint, test

* another lint
2026-07-09 19:29:55 +00:00
Maksym Yakubych
7d1f271280 fix: move data complexity lower on the stats page (#77003)
Closes [BOT-1797: Move data complexity lower on the stats page](https://linear.app/metabase/issue/BOT-1797/move-data-complexity-lower-on-the-stats-page)

### Description

Move data complexity lower on the stats page, decrease font size and copy length.

### How to verify

1. Go to Admin settings -> AI.
2. Scroll down to the data complexity section.

### Demo

<img width="1840" height="1120" alt="image" src="https://github.com/user-attachments/assets/627935fd-e9d2-40d6-8c1c-7b2a52c35394" />

### Checklist

- [x] Tests have been added/updated to cover changes in this PR
- [x] If adding new Loki tests: they pass [stress testing](https://github.com/metabase/metabase/actions/workflows/loki-stress-test-flake-fix.yml)
2026-07-09 16:14:13 -03:00
appleby
a9b9b7bb59 Ensure openai reports :cacheReadTokens in :usage (#77341)
* Ensure openai reports `:cacheReadTokens` in `:usage`

Add `openai-usage->aisdk-usage` to convert openai usage format to aisdk format and report `:cacheReadTokens`.

* Add undocumented :cache_write_tokens as well
2026-07-09 19:08:11 +00:00
Eric Normand
368ed03818 Preserve MySQL role name case when expanding role grants (#77415)
`parse-grant` lowercased role names parsed out of `SHOW GRANTS FOR <user>`.
Those names are fed back into `SHOW GRANTS FOR <user> USING <roles>`, and
MySQL 8 treats backticked role identifiers as case-sensitive, so any role
with uppercase characters made the follow-up query fail with error 3530 and
took the whole metadata sync step down with it.

Lowercasing is still correct for the privilege types in the sibling
`:privileges` branch; it was never right for role identifiers.

Also add the missing space before `USING` in the follow-up query, which
only parsed because the user identifier ends in a backtick.
2026-07-09 13:42:32 -05:00
Alexander Polyankin
ffbddbbc6f Static-viz: dispose ECharts instances (OOM fix) + faster SVG dominant-baseline patch (#77412)
* Static-viz: dispose ECharts SSR instances + faster SVG dominant-baseline patch

Two isolated, output-preserving fixes to the static-viz render path:

- Dispose the ECharts/zrender SSR instance after renderToSVGString() in every
  chart component. These instances were never released, leaking ~MBs per render
  and OOMing a long-lived renderer process; memory is flat after.

- Replace patchDominantBaseline's full hast parse+serialize round-trip over the
  whole SVG with a targeted string transform (like the sibling
  transformSvgForOutline), cutting a large share of big-chart render time with
  byte-identical output.

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

* Update BoxPlotChart.tsx

* Update ComboChart.tsx

* Update PieChart.tsx

* Update SankeyChart.tsx

* Update ScatterPlot.tsx

* Update TreemapChart.tsx

* Update WaterfallChart.tsx

* Drop hast deps entirely; svg test uses DOMParser

The SVG dominant-baseline patch no longer uses hast, and its test was the last
user of hast-util-from-html. Rewrite the test with the jsdom DOMParser and
remove hast-util-from-html and hast-util-to-html from the deps.

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

* Fix formatting in ComboChart.tsx

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

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-07-09 14:27:18 -04:00
Chris Truter
c6a0c72b01 Enforce the 50 MB CSV upload limit on the backend (#77363) 2026-07-09 17:54:36 +00:00
Alexander Polyankin
22725a83b9 Extract a StaticVizRenderer protocol for static-viz rendering (#77315) 2026-07-09 11:26:13 -04:00
Kamil Mielnik
a9e1b0edf7 GDGT-2454 Badge (#74714) 2026-07-09 21:47:43 +07:00
Sloan Sparger
6912a50e85 [Metabot] Chat internal format improvements (#77301)
* [Metabot] Migrate BE to v2 message format (#75672)

* migrate codebase to writing v2 format

* move to camelCase to match upstream schema changes

* improvements

* improvements

* correction

* metadata corrections

* handle string outputs correctly

* put add error code to message metadata in finish message

* self-review pass

* record step start to db

* correct issue in claude provider that sent too long of message ids

* record text state to open up future ability to write in progress work

* increase malli usage

* limit client streamed output for tool calls

* emit cache token usage correctly

* ensure started before error is emited

* update migration version

* [Metabot] FE read new message format (#76429)

* initial impl

* self review

* update e2e tests

* copilot feedback

* pr feedback

* fix lint

* feedback - test helper ergonomics

* misc. fixes to metabot chat improvements integration branch (#77321)

* fixes due to stale branches, correct data- prefix not getting recorded, remove unused code

* clean up debug visuals

* ci fixes

* fix couple more tests

* pr feedback
2026-07-09 09:39:59 -05:00
github-automation-metabase
5f56057bfe Update translations 2026-07-07 (#77151)
* Update translation sources 2026-07-07

* Update translations

---------

Co-authored-by: github-actions <github-actions@github.com>
Co-authored-by: Ryan Laurie <30528226+iethree@users.noreply.github.com>
Co-authored-by: Chris Vandoodewaard <chris.vandoodewaard@metabase.com>
2026-07-09 14:35:20 +00:00
Nicola Mometto
e5bd3a34eb fix: enumerate cols to fix sql server (#77373)
* fix: enumerate cols to fix sql server

* fix sqlserver boolean coercion properly
2026-07-09 14:06:15 +00:00
Chris Truter
6097aa447b Publish / unpublish tables trigger hooks properly (#77374) 2026-07-09 12:22:58 +00:00
Mahatthana (Kelvin) Nomsawadi
ff2b145e37 Forward query edits from viz settings in SDK QuestionSettings (#77262)
* test: add repro for SDK viz-settings column edits being dropped

Reproduces EMB-2057 — in modular embedding (embed.js), removing a
column via Visualization settings > Add or remove columns silently
no-ops. Fails against the current QuestionSettings.tsx onChange,
which drops the second question argument carrying the query edit.

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

* fix: forward query edits from viz settings in SDK QuestionSettings

QuestionSettings.tsx's onChange dropped the second `question`
argument that ChartSettings forwards for query-level edits (e.g.
add/remove columns), applying only the settings to the stale closure
question and never re-running the query. Column-removal edits landed
in the query object but the table kept rendering the old result.

Forward `nextQuestion` when present and re-run only in that case, so
pure viz-settings-only edits (no query change) keep their existing
no-run behavior.

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

* Fix code format

* move test to where it belongs

---------

Co-authored-by: Claude Sonnet 5 <noreply@anthropic.com>
2026-07-09 08:47:59 +01:00
Alexander Polyankin
21f2c65b15 Collapse uniform blocked view-data table permissions to db-level rows (#77130) 2026-07-08 21:44:07 -04:00
technomancy
1c90ab2c31 Split databricks CI jobs in 2 parts. (#77312)
Currently they are timing out with some regularity in CI. We've done
this same thing to bigquery and redshift already.

Not only will this get us pass/fail results more quickly; it also
reduces the scope of failures so retries don't have to redo as much
wasted work.
2026-07-09 01:32:33 +00:00
Denis Berezin
82b65c8496 UXW-4481 Timeline Events new UI (#76381)
* UXW-4481 Timeline Events new UI

* Add full implementation (without new icons)

* Update icons

* Self review

* Self review

* Review fixes

* Add focused list of events in sidebar

* Clean-up

* Fix hover color

* Fix unit test

* Better sidebar logic

* Fix e2e

* Review fixes

* Review fixes

* Fix e2e

* Fixes

* Review fix

---------

Co-authored-by: Andrei Chernykh <andrei.chernykh@metabase.com>
2026-07-09 03:59:30 +03:00
Egor Grushin
da4e98d389 GDGT-2576 migrate Toggle (#77063)
* GDGT-2576 migrate Toggle

* GDGT-2576 tests fix

* GDGT-2576 remove unused code + fix test

* GDGT-2576 fix failing tests

* GDGT-2576 drop unused onChange from FormToggle
2026-07-09 01:34:59 +01:00
Fraser
4701e5f8dc Remove querying e2e tests made redundant by backend test parity 2026-07-09 12:12:05 +12:00
Andrei Chernykh
18f5a74df7 Reject replacing a dashcard's card with a question internal to another dashboard (#77236) 2026-07-08 15:20:08 -07:00
Michael Eby
339d2c91b9 docs: add page for treemap visualizations (#77185)
* docs: add page for treemap visualizations

* Optimized 1 images, saved 237.8 KB (44.8% smaller)

* fix broken link

* Edits from Jeff

* Edits from Robert

* Edits from Jeff 2

---------

Co-authored-by: Metabase Automation <github-automation@metabase.com>
2026-07-08 16:21:36 -04:00
Ben Grabow
51e50d157c Avoid loading any H2 classes until/unless the H2 lib is on the classpath (#76842)
* Avoid loading any H2 classes until/unless the H2 lib is on the classpath
2026-07-08 14:15:03 -05:00
technomancy
c16d08579d Stop running metabase-enterprise.transforms-inspector-test in cloud DBs (#77231)
Stop running metabase-enterprise.transforms-inspector-test in cloud DBs.

These tests create new tables in the default schema, which is fine for
most drivers, but not for cloud DBs like snowflake and bigquery, because
concurrent CI jobs share the same jobs, which means this will cause test
failures in other unrelated tests which list tables, such as
metabase-enterprise.impersonation.driver-test/resilient-connection-options-test

We need to get these tests to stop creating tables in the default schema,
then we can drop the requirement for the :test/dynamic-dataset-loading feature.
2026-07-08 17:47:57 +00:00
Phoomparin Mano
07c824b6fb fix(sdk): derive dark mode color scheme based on sdk theme colors (#77269)
* add css variables for styled components

* commit loki snapshot change

* add resolved theme mocks

* use real theme color values
2026-07-08 16:24:19 +00:00
Nicola Mometto
6aa06eaa23 Fix notification seed legacy template paths (#77268)
* Fix notification seed crashing on pre-existing template rows

* add regression test
2026-07-08 16:58:49 +01:00
Andrei Chernykh
7876a74202 Uxw 4531 replace the group picker dropdown with a multiselect (#76648)
* Replace the group picker in the user form with a multiselect

* Port the tenant group-picker e2e steps to the new multiselect

* Add group-manager controls and a section separator to the multiselect, with chevron and Backspace fixes

* Fix external-default group ordering in the multiselect dropdown, with manager-flag and divider tests

* Update frontend/src/metabase/admin/people/components/GroupsMultiSelect/GroupsMultiSelect.tsx

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>

* Update remove-button test assertions for the group-specific aria-label

---------

Co-authored-by: coderabbitai[bot] <136622811+coderabbitai[bot]@users.noreply.github.com>
2026-07-08 08:35:46 -07:00
dpsutton
c09cdbf49c Serialize static-viz GraalJS context creation (GHY-4077) (#77225)
* Serialize static-viz GraalJS context creation (GHY-4077)

Even with the shared-Source code cache (#77180), evaluating the bundle
in a fresh context churns through ~500 MB of allocation. That memory is
transient — allocated and discarded during the eval, with only ~10 MB
retained per extra live context — but it all still has to pass through
the heap. The dirigiste pool grows during render bursts, and nothing
stopped 2-3 context creations from running concurrently: ~1-1.5 GB of
allocation churn stacked on top of in-flight renders, which on a 2 GB
heap outruns the collector and drives GC thrash / OOM.

Serialize creation on a private monitor so at most one generate runs at
a time; waiting acquires just queue on the pool. Also jitter the
10-minute expiry timestamps (+/- 3 min) so pool members created in the
same burst don't all expire and regenerate in the same window.

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

* Document static-viz pool memory model in namespace docstring

Capture what the OOM investigation measured so the pool's design
choices stay legible: engine + parsed sources ~220 MB retained (paid
once); fresh-context eval ~500 MB of collectable churn with only
~16 MB retained per live context (first-in-JVM cold parse ~1.2 GB);
renders ~1 MB/row transient. Also spell out why creation is serialized
on a monitor rather than time-throttled: bursts genuinely need
multiple contexts, so the pool still grows — just one creation at a
time.

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-08 10:12:58 -05:00
Michael Eby
23825aec8e docs: add mcp + cli webinar callouts (#77191)
* docs: add mcp + cli webinar callouts

* Edit from Jeff
2026-07-08 10:29:39 -04:00
Chris Vandoodewaard
eca47dd2dc DEV-2270: add .bun-version file, configure setup-bun to use version file (#77208)
* add .bun-version file, configure setup-bun to use version file

* use package.json as the source of truth for the version of bun installed
2026-07-08 10:23:09 -04:00
Ngoc Khuat
8a7b431057 Fix redshift transform job dependency-detection flake (#77095) 2026-07-08 14:59:08 +01:00
Fraser
384f6fb9b7 Make test stats upload more robust (#77258)
* Make test stats upload more robust

* Fix trailing whitespace

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-07-08 13:47:04 +00:00
github-automation-metabase
b7fa7d73d2 Auto-update documentation for master (#77222)
Update generated docs (master)

Co-authored-by: github-actions <github-actions@github.com>
2026-07-08 09:28:53 -04:00
github-automation-metabase
9d523b4604 Auto-update documentation for master (#77036)
Update generated docs (master)

Co-authored-by: github-actions <github-actions@github.com>
2026-07-08 09:27:54 -04:00
Sébastien
951be524ec Fix embed preview stuck loader when reopening with a saved theme (#77150) 2026-07-08 15:06:28 +02:00
Ngoc Khuat
c518575acc run the incremental transform suite against all drivers (coverage probe) (#76793) 2026-07-08 11:56:27 +00:00
Ngoc Khuat
206ba7ee99 Don't fail dashboard subscriptions when a filter's default is an empty list (#77158) 2026-07-08 11:43:49 +00:00
Sébastien
e78a7c57e6 MCP Usage Analytics: storage, instrumentation, audit view, and admin page (MVP) (#76403) 2026-07-08 12:15:21 +02:00
Sergii Vozniuk
892974e74e Fix rendering of tenant avatars (#77075)
* Fix rendering of tenant avatars
* Remove unused Avatar code, cleanup initials logic, more explicit types
* Fix type used in isUser
* Stricter types to avoid initial bug in the future
2026-07-08 11:58:50 +02:00
Nemanja Glumac
1bec6455d3 Wire embedding tests to ci-conductor (#77184)
* Wire embedding tests to ci-conductor reporting

* Add ci-conductor quarantine gate to embedding Cypress jobs


Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-08 11:19:26 +02:00
Chris Truter
0149067bd7 execute_question: improve error codes (#77156) 2026-07-08 07:46:17 +00:00
Romeo Van Snick
54a2825522 Convert route-prop reference containers onto the metabase/router facade (#77067)
* Add withRouteProps facade shim for the router migration

* Convert DatabaseListContainer to a function component on facade hooks

* Put route-prop reference containers on withRouteProps

* Require route props in withRouteProps generic constraint

* Convert ScrollToTop from withRouter to useLocation hook form

* Fix merge fallout: rename RouteProps shim and repoint react-router imports
2026-07-08 16:23:09 +10:00
Romeo Van Snick
ca6033b698 Convert query_builder test loose ends to TypeScript (#76938)
* Convert query_builder test loose ends to TypeScript

* Rename ChartSettingsSidebar tests to match their assertions
2026-07-08 14:22:49 +10:00
Fraser
f6be96587f Delete dead frontend code (#77253) 2026-07-08 16:02:20 +12:00
Fraser
1bc18a3626 Consolidate reference-only components into reference/ (#77254) 2026-07-08 16:01:57 +12:00
Fraser
837a454620 Consolidate app banners into AppBanner (#77255) 2026-07-08 16:01:43 +12:00
Fraser
3127b4e8c3 Consolidate question-timeline UI into query_builder (#77256) 2026-07-08 16:01:26 +12:00
Romeo Van Snick
56879decb0 Migrate direct react-router usage onto the metabase/router facade + eslint ban (#77068)
* Facade re-exports full react-router surface via a single leaf seam

* Re-point all react-router imports onto the metabase/router facade

* Ban react-router imports outside the metabase/router facade (eslint)

* Migrate InviteToViewModal Link import onto metabase/router facade
2026-07-08 12:53:05 +10:00
Alexander Polyankin
d81c75451c Minify the static-viz bundle (#77234) 2026-07-08 02:18:57 +00:00
Alexander Polyankin
b48d367c21 Log only the error message for failed queries (#77223) 2026-07-07 21:38:18 -04:00
Denis Berezin
5c6e3e71fe UXW-4235 Transforms nav item permissions (#76705) 2026-07-08 01:29:14 +03:00
Alexander Polyankin
5e05b04e53 Pool error fix (#77212) 2026-07-07 17:00:26 -04:00
Timothy S. Dean
5a39e1adf8 Update version-helpers.ts for v63 (#77211)
Update version-helpers.ts for v63
2026-07-07 14:39:58 -06:00
Eric Normand
ff5e3b6973 Validate serialization dependencies before export (GHY-4010) (#76763)
* Add serialization-dependencies multimethod + Card impl (GHY-4010)

Foundation for export-time dependency validation. serialization-dependencies
runs on a raw appdb entity and returns its references tagged :content (must be
in the export) or :data (database/table/field that must exist in the appdb).
Unlike the load-time `dependencies` multimethod, it operates pre-serialization
and includes tables/fields, which import otherwise creates on the fly.

The Card impl derives content deps from `descendants` (so the two can't drift)
and adds data-model deps from the query via the lib walkers. Not yet wired into
the export pipeline.

* Replace escape analysis with general dependency validation (GHY-4010)

extract-subtrees now runs a dry-run pass (collect-dependencies) that shares the
real export's extract queries but neither serializes nor writes. For every entity
that will be extracted it derives serialization-dependencies and checks them:
content references must be in the visited/extracted set (or be analytics cards),
and data-model references (database/table/field) must exist in the appdb. Any
unsatisfied reference aborts the export (unless continue-on-error), before any
archive is produced.

This generalizes part A's Card-only, collection-id escape analysis: it now also
catches non-Card content escapees and dangling data-model references (a deleted
table/field that would otherwise serialize to a malformed [nil nil nil] ref).

Adds a Dashboard serialization-dependencies impl. Tests not yet updated.

* Update serialization tests for dependency validation (GHY-4010)

The dependency-validation warnings replace the old "Failed to export
Dashboard/Cards ... outside requested collections" messages with a uniform
"<entity> references <model> <id> which is not included in the export /
is missing from the source database" form, so the escape tests now assert
on the new wording. Adds dependency-validation-missing-data-ref-test, which
covers the new data-model case: a card referencing a deleted field aborts the
export (and continue-on-error still exports the rest).

* Fold dependency collection over a monoid, with batched queries (GHY-4010)

Replaces the nested reduce in collect-dependencies with a {:visited :deps}
monoid: entity-deps maps one entity to its contribution, merge-deps is the
associative combine (0/1/2-arity, usable directly as a transduce reducing fn),
and collect-dependencies folds every entity into the whole via a single
transduce. content-id-batches yields [model id-batch] pairs so each extract
query's :in :id clause stays bounded (query-batch-size 1000), and the data-dep
existence check is batched the same way. Behavior is unchanged.

* Flatten dependency collection into four transducer stages (GHY-4010)

entity-deps now reads its model off the entity (extract-query returns modeled
rows) instead of taking it as an argument, so collect-dependencies becomes a
flat pipeline: filter content models, resize into id batches, mapcat each batch
through extract-query into an entity stream, then map entity-deps — no eduction
nested inside the mapcat. Behavior unchanged.

* Move dependency validation into its own namespace (GHY-4010)

Extract the export-time dependency-satisfaction check out of
serialization.v2.extract into serialization.v2.dependency-validation. extract
now just calls dependency-validation/validate-dependencies! and keeps ownership
of the analytics-card set, which it passes in. The moved code carries this
session's cleanups (map-kv-vals for the existence lookup, set-based :deps).

Tests move to a matching dependency-validation-test namespace; the escape
assertion embedded in selective-serialization-basic-test stays with extract as
an extraction-level integration check.

* Address review: drop :kind, transients, cover segment/measure (GHY-4010)

Alex's PR comments on the raw dependency validation:

- serialization-dependencies no longer tags deps with :kind; it returns plain
  {:model :id} and the validator classifies each by model (serdes.models
  content vs data-model), since serdes already knows which is which.
- collect-dependencies accumulates into transient sets — an export can walk a
  lot of entities.
- Card serialization-dependencies now covers every reference in the query,
  including :segment and :measure (both data-model, existence-checked), via the
  lib walkers, closing the gap the field/table/card-only version had.

Refs embedded in parameter_mappings / visualization_settings / result_metadata
still aren't covered, and the raw serialization walker still duplicates the
serialized *-deps knowledge; both are tracked for the follow-up unification.

* Cover result_metadata and visualization_settings field refs (GHY-4010)

serialization-dependencies "Card" now gathers Field references from every
routine-backed source, not just the query:

- query: lib walkers (fields, tables, segments, measures, template-tag fields)
- result_metadata: each column's :id
- visualization_settings: the JSON-encoded column-setting keys, parsed with
  mb.viz/db->norm (the same routine the dependency-analysis project uses)

New test covers a field referenced only in visualization_settings. Field refs
buried in parameter_mappings / parameters value-fields are bare [:field ...]
clauses the lib walkers reject; those remain for the dep-walker unification.

* Rename `dependencies` multimethod to `deserialization-dependencies`

Makes the load-time dep multimethod parallel with the export-time
`serialization-dependencies`. `dependencies` runs on the serialized/ingested
form for load ordering and omits tables/fields (import synthesizes them);
`serialization-dependencies` runs on the raw entity and includes them. The
name now says which is which.

Mechanical rename of the defmulti + default + 19 impls across 18 models + 3
callers (load, metabot, remote-sync) + tests + doc-links. No behavior change.

* Address CodeRabbit: batch analytics lookup, fix test targeting (GHY-4010)

- analytics-card-ids batches the card-id :in via a partition-all transducer, so
  a large closure doesn't exceed database parameter limits (matches the batching
  already used in dependency collection).
- escape-report-test's ":parameters" case targeted coll2 (re-testing the
  source-table card); target coll3 so it actually exercises the parameter card.
- Correct the continue-on-error test wording: it suppresses the abort but does
  not skip the affected card at export (the malformed card is skipped on import).

* Unify serialization/deserialization dependency walkers (GHY-4010)

Make the mbql-deps walker family format-aware so a single traversal handles
both raw (numeric ids, export/serialization) and serialized (portable refs,
load/deserialization) forms, gated by *serialization?* / raw-ref-id?. Card and
Dashboard now share one deps helper across both dependency multimethods.

Implement serialization-dependencies for the remaining content models
(Action, Collection, Document, NativeQuerySnippet, Timeline), computing deps
from the raw entity: Action fetches its query_action child row; Collection
derives its parent from the raw :location path.

Refine export-time validation: a content reference to a deleted entity is not a
failure (export can't emit a portable id for a missing row, so fk-elide drops
it), and structural Collection references are ignored (a selective export may
omit the containing collection tree).

Tests: mbql-deps format-parity test, direct per-model serialization-dependencies
coverage, and the full baseline load->extract round-trip over every model.

* Trim duplicated dependency docstrings and consolidate abort tests (GHY-4010)

Dedupe the "content refs must be in export / data-model refs must exist"
explanation that appeared in four docstrings, and collapse the three
near-identical "delete a data-model ref -> export aborts" tests into one
parameterized test over Field/Segment/viz-settings references.

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

* Share query-batch-size constant; use pos-int? for raw ref ids (GHY-4010)

Hoist the `:in`-clause batch size into a single serdes/query-batch-size
constant instead of a private def plus a bare 1000 literal in extract, and
tighten raw-ref-id? to pos-int? (entity ids are always positive).

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

* Replace transient accumulator with a named merge-entity-deps monoid (GHY-4010)

The set-building is not the hot path (batched DB queries and the mbql walk
dominate), so drop the transients for a plain `merge-with into` monoid,
extracted as `merge-entity-deps` — the same idiom as u/traverse and
remote-sync's merge-incremental-export-plans.

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

* Fold partition-all into the existing-ids transducer (GHY-4010)

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

* Fold distinct into the existing-ids transducer too (GHY-4010)

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

* Use peek and set-as-predicate in dependency validation (GHY-4010)

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

* SPIKE: thread allow-int-ids? param instead of *serialization?* dyn var (GHY-4010)

Replaces the *serialization?* dynamic var with an explicit allow-int-ids?
parameter threaded through the mbql walkers (mbql-deps/-map/-vector,
parameters-deps, visualization-settings-deps, viz-link-card-deps) and the
shared model helpers (card-deps, dashboard-deps, serdes-deps-dashcard,
result-metadata-deps). The name states the behavior: integer ids count as
references only when set (raw appdb entities), never on the serialized/load
form where a stray numeric must be ignored.

The parameter is mandatory everywhere — no default arities. Load-side callers
(measure/segment/transform/action deserialization impls) pass false; the three
serialization-dependencies impls pass true.

Spike to compare against the dyn-var approach; drop if we prefer that.

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

* Fix cljfmt: align card-deps destructuring continuation lines (GHY-4010)

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-07 20:22:39 +00:00
Alexander Polyankin
486296ff36 Graalvm pool with staticly parsed sources (#77180) 2026-07-07 15:27:15 -04:00
Nick Fitzpatrick
7f6472209d Move only show attachments toggle for email subscriptions (#77022)
* Move  only show attachments toggle for email subscriptions

* fix e2e test
2026-07-08 00:52:14 +05:30
Timothy S. Dean
f57fdc8258 Bump postgresql 42.7.11 -> 42.7.12 (#77181) 2026-07-07 12:36:22 -06:00
Chris Truter
705bda8519 feat(search): publish analytics for every search context (#76613) 2026-07-07 20:17:51 +02:00
appleby
a91da664b9 Do not compute related-tables or metrics in get-report-details (#76945)
Don't compute related-tables or metrics in get-report-details

`get-report-details` drops `:related_tables` and `:metrics` via a `select-keys`, so don't ask `card-details` for them.
2026-07-07 17:57:21 +00:00
Nicola Mometto
631e2c157f write-through cache for transform deps in ee only (#77079)
* write-through cache for transform deps in ee only

* kondo
2026-07-07 17:32:25 +01:00
Timofey Kachalov
01fa952fa7 Update httpcore5, httpcore5-h2 and httpclient5 versions (#77109) 2026-07-07 20:00:34 +04:00
Timothy S. Dean
d9ea875545 Bump handlebars 4.3.1 -> 4.5.3 (#77134)
* Bump handlebars 4.3.1 -> 4.5.3
* Add license for jnack/handlebars
2026-07-07 14:27:21 +00:00
Oleh K
3512caf5ee refactor: Migrate feedback, components, misc, upsell, illustration & admin color tokens (#76871)
* Migrate remaining color tokens to new names (GDGT-2535)

Migrate the remaining legacy design-system color tokens to their new
names per the GDGT-2517 migration guide:

- feedback: error/danger -> feedback-negative, success ->
  feedback-positive, warning/gold -> feedback-warning
- misc/core: info -> core-info, white -> core-white, shadow ->
  shadow-default, overlay -> modal-overlay, focus -> input-focus,
  metabase-brand -> core-metabase_brand
- admin: admin-navbar* -> navbar-admin*
- upsell/illustration: per guide
- remove unused bronze/copper/silver

Covers all reference forms: CSS `var(--mb-color-*)`, `color()`/helper
calls, Mantine `c`/`bg`/`color`/`iconColor` props (string and ternary),
object-literal `color:`/`iconColor:` keys, `ColorName` return values,
arrays, and `Record<_, ColorName>` value maps. Tightens `Undo.toastColor`
from `string` to `ColorName` so future token removals fail at compile
time. Maps the `Alert` component's semantic `color` prop to feedback
tokens internally so its call sites stay unchanged.

Also sweeps up brand/filter/summarize consumer stragglers left over from
the earlier (merged) migration. SDK/whitelabel input keys, the
derive-theme alias definitions, and static-viz's local palette are left
on their existing names by design.

* Migrate missed success-secondary props in StepperWithCards

The .module.css was migrated to feedback-positive-selected but the two
inline c="success-secondary" props (Done check icon + label) were missed.

* Update Loki Snapshots

* Fix toastColor type widening in metabot toast-prop helpers

Undo.toastColor tightened to ColorName in this branch; the two get*ToastProps
helpers returned object literals where toastColor widened to string (missing
as const, unlike their iconColor/dismissIconColor siblings).

* Update TransformListPage sync-color spec to migrated feedback token names

utils.ts color map was migrated (success/warning/danger -> feedback-*) but
the spec assertions still expected the old names.

* Update SDK theme + treemap specs for feedback/misc token mirrors

- get-embedding-theme: SDK mapping now fans text-white->core-white and
  focus->input-focus, so the expected override gains those keys.
- treemap option: getColor("white") became getColor("core-white"); add
  core-white to the test's MOCK_COLORS palette.

* Update Loki Snapshots

* Update toast color-attr assertions to migrated feedback token names

* Cleanup

* Migrate remaining color tokens in Button and Table stories

* Add explainer comment for colors naming convention

---------

Co-authored-by: Metabase Automation <github-automation@metabase.com>
2026-07-07 15:34:02 +02:00
Kamil Mielnik
63716689ad GDGT-2771 Remove redundant type casts (#77078) 2026-07-07 19:39:25 +07:00
Oleh K
a7e7e5ac5b fix: Toaster crash on long-running questions from color-mix tokens (#77152)
* fix: Toaster crash on long-running questions from color-mix tokens

The Toaster's styled-components computed colors at render time with the
JS `color` library (via the deprecated lighten()/alpha() helpers). One
of the tokens they parsed, `background_page-tertiary-inverse`, is now
defined as a color-mix() value, which the `color` library can't parse —
so it threw "Unable to parse color from string" and crashed.

Replace those runtime helper calls with CSS color-mix on the variables
directly, so the mixing happens in CSS where color-mix()/var() resolve.

* Adjust dismiss color
2026-07-07 11:43:43 +02:00
Nemanja Glumac
6b5c699c22 Make e2e modal selector slightly more accessible (#76975) 2026-07-07 09:39:39 +02:00
Romeo Van Snick
2a8bbb797c Add v7 conformance tests for the metabase/router facade (#77064)
* Add react-router v7 as a test-only aliased devDependency

* Add differential conformance harness for the router facade

* Add v7 conformance test for useLocation

* Add v7 conformance test for useParams

* Add v7 conformance test for useNavigate

* Add v7 conformance test for useSearchParams

* Add v7 conformance test for Navigate

* Add v7 conformance test for useSearchParams defaultInit

* Pin react-router v7 to 7.18.1 for conformance

* Add type-level conformance tests against react-router v7

* Guarantee cleanup between facade and v7 renders in runBoth
2026-07-07 15:28:44 +10:00
Romeo Van Snick
c16bdc6c32 Migrate DatasetEditor DatasetNotebook and DatasetFieldMetadataSidebar to TypeScript (#76971) 2026-07-07 15:28:20 +10:00
Romeo Van Snick
c1e5037657 Migrate query builder View components and tests to TypeScript (#76972)
* Migrate ChartSettingsSidebar unit test to TypeScript

* Migrate DatasetMetadataStrengthIndicator unit test to TypeScript

* Migrate QuestionDataSource unit test to TypeScript

* Migrate ViewTitleHeader unit test to TypeScript

* Correct onSave return type to Promise<void> and relax Toaster className

* Migrate query builder View components to TypeScript

* Preserve collection type on move and tighten timeline callback types

* Remove dead onCloseQuestionInfo prop from structured sidebar
2026-07-07 15:27:41 +10:00
Fraser
aae7c76e84 Integrate e2e coverage into module graph (#74621) 2026-07-07 16:39:30 +12:00
Tyler Plude
c8ede8c5c5 Pin maildev to 2.2.1 (#77143)
pin maildev to 2.2.1
2026-07-06 18:56:25 -07:00
YB
1b244fdd43 pin @babel/core to 7.29.7 (#77044) 2026-07-07 09:36:03 +08:00
Alexander Polyankin
c109d4fbc6 Add backend test parity for MBQL lib / QP behaviors covered only by e2e tests (#77062) 2026-07-06 20:35:33 -04:00
appleby
16eefb159d Remove enhanced-database-tables and provide columnless tables in metabot context :used_tables (#76944)
`enhance-context-with-schema` resolved each `:user_is_viewing` item's used tables and then ran them through
`table-utils/enhanced-database-tables`, which fetched and formatted the full visible-columns set for every used table, including all implicitly-joinable columns from related tables. That work was discarded anyway since columns were recalculated via `entity-details/get-table-details` when rendering the context. On large, highly-connected schemas this could load thousands of columns into the request metadata cache and exhausted the heap (metabase#76493).

`:used_tables` entries now carry only `{:id :type :name :database_schema :description}`. name/schema/description are kept for the `simple-entity` error fallback. `enhanced-database-tables` had no other callers, so it is removed.
2026-07-06 15:58:03 -07:00
Braden Shepherdson
931afd85c5 [PDFs] Support emoji (#77034)
Fixes UXW-4704.

Support emoji in PDF rendering - in card titles, text cards, and the dashboard title.

These are monochrome only, since monochrome emoji are regular font glyphs. Colour emoji requires unusual bitmap-backed font support, and the PDFBox engine doesn't support that. It could be done, but it would require rendering the emoji glyphs to PNGs, then embedding those in the PDF. It's not worth the effort or including a bulky bitmap emoji font for a cosmetic feature.

This includes the Noto Emoji font in the JAR, and adds the Open Font License notice file covering all the PDF fonts.
2026-07-06 20:55:13 +00:00
Tyler Plude
79002d4666 [BOT-1442] Fix metabot silently producing non-runnable MBQL (#76133)
* fix Metabot construct_notebook_query silently producing non-runnable queries

* trim overly verbose docstring

* pr feedback
2026-07-06 20:07:24 +00:00
Romeo Van Snick
a7b48d8ca8 Convert remaining NativeQueryEditor js files to TypeScript (#76948) 2026-07-07 06:07:07 +10:00
Eric Normand
843ddfa348 Fix transforms-root breadcrumb link in remote-sync changes list (GHY-3901) (#77113)
The "Transforms" group header in the push/pull changes list is backed by a
virtual collection with the sentinel id -1 (TRANSFORMS_ROOT_ID). Every -1 case
is special-cased in displayGroups.ts except the header breadcrumb, so the
sentinel flowed into collectionUrl({ id: -1 }) and produced a dead
/collection/-1-transforms link (a hyphen at the start of the last path segment).

Link the transforms-root segment to the transforms list (/data-studio/transforms)
instead. Covers both the virtual-root group and the transforms-namespace prefix
on sub-collections, since the guard sits at the single render site.
2026-07-06 19:39:13 +00:00
appleby
b7262df217 Whitelist anthropic and bedrock models (#76768)
* Whitelist bedrock models

* Whitelist anthropic models

* Add claude-fable-5 to supported-models for bedrock and claude providers

* Include a display_name for all supported-models

* Filter to available-model? in bedrock's list-models
2026-07-06 19:14:32 +00:00
Eric Normand
8bb5162d89 Fix snippet template-tag id churn in serdes round-trip (GHY-4067) (#77112)
Snippet template-tag ids were regenerated on every serdes import: YAML
ingest keywordizes the tag-name keys, so the NativeQuerySnippet load hook
could not match them to preserve the existing :id and minted a fresh UUID
instead. In a remote-sync import/export loop this produced a spurious id
diff for every snippet with variables on every cycle.

Normalize :template_tags on import in make-spec so the tag-name keys are
strings before the model hooks run; export is unchanged. Add a round-trip
regression test asserting template-tag ids survive export/import.
2026-07-06 19:09:51 +00:00
Eric Normand
0605e0352f [GHY-3974] Fix Usage Analytics breaking after upgrade (two failure modes) (#76551)
* [GHY-3974] Add failing tests for Usage Analytics upgrade failure modes

Two invariant tests covering the audit-DB upgrade breakage, asserted
through ensure-audit-db-installed! so they're independent of the fix
mechanism and leave the generic sync path untouched:

- Mode A (audit-db-self-heals-duplicate-rows-from-stale-schema-test):
  an interrupted host-adjust + schema sync duplicates a v_* view row and
  retires the original, breaking customer content. ensure-audit-db-installed!
  must reconcile back to one active row per view and keep dependent content
  on an active table.

- Mode B (checksum-not-advanced-until-host-adjust-completes-test):
  last-analytics-checksum must not advance if adjust-audit-db-to-host! is
  interrupted, so the next boot re-runs the load and the host-adjust.

Both fail on master.

* [GHY-3974] Fix Usage Analytics upgrade failure modes

Mode B (checksum committed before host-adjust): in maybe-load-analytics-content!
advance last-analytics-checksum only after adjust-audit-db-to-host! completes,
so an interrupted host-adjust leaves the checksum behind and the next boot
re-runs the load + adjust. Also force a reload, regardless of the checksum, when
audit tables are stuck at the postgres "source" schema on a non-postgres host
(audit-db-in-source-state?) so already-corrupted instances self-heal.

Mode A (schema-renamed view duplicated + retired by sync): add
reconcile-audit-db-duplicates!, run on every ensure-audit-db-installed! so
already-corrupted instances (whose checksum already matches, skipping the load)
still recover. For each duplicate same-name group in the audit DB it keeps the
row dependent content points at, repoints stray report_card.table_id refs to it,
normalizes it to the host-canonical name/schema, and deletes the orphans. Schema
is derived from the host engine, not the surviving row, so a duplicate left at
the postgres source schema (Mode B masking Mode A) is corrected too. Scoped
entirely to the audit DB; the generic sync path is untouched.

Both audit-test regression tests pass on h2 and postgres.

* [GHY-3974] Serialize audit DB load/adjust/sync across nodes (1b)

with-duplicate-ops-prevented is per-process only, so on a rolling upgrade
two pods could run the audit load/adjust/sync concurrently and produce the
half-applied schema states behind both failure modes. Wrap the
load+adjust+sync+reconcile in an app-DB cluster lock (metabase_cluster_lock)
so only one node runs it at a time. If another node already holds the lock it
is doing the same work, so skip rather than fail the boot.

The sync must run inside the lock to be serialized, so maybe-sync-audit-db!
now runs synchronously instead of in a background future: on a transactional
appdb a sync on another thread would escape the lock's transaction and
deadlock against its uncommitted metabase_table writes.

Full audit-app namespace passes on h2 (in-process RW lock) and postgres
(transaction + SELECT FOR UPDATE), 52 assertions each.

* [GHY-3974] Filter audit view lookups in SQL, not in memory

audit-view-table and the Mode A heal assertion were selecting every active
audit table and filtering by lower(name) in Clojure. Push the predicate into
the query with a lower(name) where clause.

* Better comments

* [GHY-3974] Don't force a reload for an inactive public orphan (MySQL fix)

audit-db-in-source-state? treated any `public`-schema audit table on a
non-postgres host as the interrupted-host-adjust state and forced a reload.
But a Mode A duplicate leaves an *inactive* `public` orphan, and on MySQL
(canonical schema NULL) forcing a reload made adjust-audit-db-to-source!
move the active NULL row to `public`, colliding with the orphan on the
(db_id, schema, name) unique index (Duplicate entry '…-public-v_content').

Only active rows signal the genuine stuck source state; inactive public rows
are retired orphans handled by reconcile-audit-db-duplicates!. Restrict the
check to active rows. Surfaced by the MySQL/MariaDB app-db CI run of
audit-db-self-heals-duplicate-rows-from-stale-schema-test.

* [GHY-3974] Update modules config: audit-app no longer uses config

Removing the metabase.config.core require from the audit-app module (the
unused config dep dropped when the sync future was removed) leaves config
out of enterprise/audit-app :uses. Fixes modules-config-up-to-date-test.

* [GHY-3974] Only swallow lock-contention failures for our own audit lock

A different cluster lock's acquisition failure raised from inside the locked
body (e.g. the permissions lock taken when serdes inserts a Database) also
carries :lock-names; it must propagate rather than be swallowed as audit
contention and silently abandon the load.

* [GHY-3974] Bail faster on audit lock contention

Drop the lock-acquisition timeout to 5s and retries to 2, so a node that loses
the boot-time audit lock skips in ~17s instead of ~150s. The work is idempotent
and the lock holder is doing it, so a losing node need not win; keeping a couple
retries still lets a node pick up the work if the holder crashes mid-load.

* [GHY-3974] Serialize audit DB install/adjust under the cluster lock too

The install-time adjust-audit-db-to-host! + schema sync (the ::installed and
::updated branches of maybe-install-audit-db!) previously ran outside the
cluster lock, so two nodes detecting an engine mismatch could adjust and sync
concurrently against a half-adjusted schema. Move install inside the lock so the
whole install+adjust+load+sync+reconcile is serialized across nodes; a node that
acquires the lock after the installer commits sees the DB already exists and
no-ops instead of colliding on the audit DB primary key.

* [GHY-3974] Harden reconcile-audit-db-duplicates! and Mode B test

- Sort rows by id before grouping so survivor selection (including the
  referenced? tiebreak) is deterministic regardless of appdb row order.
- Clear is_defective_duplicate on the survivor so it re-enters idx_unique_table
  (a flagged row has a NULL unique_table_helper and is excluded from the index).
- Comment why orphans are deleted before the survivor is re-canonicalized.
- Mode B test: move cleanup into a finally and reinstall the audit DB so an
  unexpected throw can't leave sibling tests without an audit DB.

* [GHY-3974] Make reconcile lossless: move content off orphans before deleting

The previous reconcile did (t2/update! :model/Card {:table_id orphan} {:table_id survivor})
then deleted the orphan. That update is a no-op — Card's before-update populate-query-fields
re-derives table_id from the unchanged dataset_query — and report_card.table_id is ON DELETE
CASCADE, so deleting the orphan destroyed any customer card whose query pointed at it. This
happens in real Mode A: bundled audit cards reference the retired row (making it the survivor)
while a customer question built during the corrupted window references the freshly-synced active
row (the deleted orphan).

Now repoint-cards-to-survivor! rewrites each referencing card's dataset_query (source-table)
and result_metadata, remapping field ids onto the survivor's same-named fields, before the
orphan is deleted. Handles both pMBQL and legacy field refs.

Adds audit-db-reconcile-preserves-content-on-the-deleted-duplicate-test, which asserts the card
survives and its field refs resolve to active fields on the survivor (fails on the old code).

* [GHY-3974] Use lib field-ref helpers instead of hand-indexing refs

repoint-refs now reads/writes the field id via lib/field-ref-id and
lib/with-field-ref-id rather than indexing the ref vector by position. Expose
with-field-ref-id from metabase.lib.core (the setter alongside the already-public
field-ref-id getter) so it's reachable through the lib module's public API.

* [GHY-3974] Use lib clause predicate / field-ref-id for remaining MBQL access

Replace the hand-rolled field-ref? predicate with lib/clause-of-type?, and the
positional field-id extraction in the test with lib/field-ref-id.

* better docstring

* [GHY-3974] Order reconcile rows in the query instead of in memory

Address review: let the DB sort (:order-by [[:id :asc]]) rather than sort-by; group-by
preserves the order within each group, keeping the survivor tiebreak deterministic.

* [GHY-3974] Move query id-remap into lib; handle result-metadata thoroughly

Review (@metamben): the ref manipulation should live in lib and be general-purpose,
and queries vs result metadata shouldn't share one generic walker.

- Add metabase.lib.walk.util/replace-field-ids and replace-table-ids (general, built on
  lib.walk): field refs everywhere via walk-clauses (filters/aggregations/breakouts/joins/
  nested stages), :source-field/:fk-field-id opts, native :template-tags :dimension refs, and
  :source-table per stage/join. Exposed via metabase.lib.core.
- audit-app repoint-cards-to-survivor! now rewrites dataset_query via the lib helpers, and
  handles result_metadata separately (non-generic): :id, :fk_target_field_id, and :field_ref
  covering both legacy ([:field id opts]) and pMBQL ([:field opts id]) shapes.
- Test asserts legacy result_metadata :field_ref is remapped onto the survivor.

Covers review threads: field-ref manipulation in lib (#383), FK/source-field refs (#418),
legacy result-metadata refs (#392).

* [GHY-3974] Batch the reconcile referenced? check into one query

Address review: instead of a t2/exists? per row in a duplicate group, fetch the set of
card-referenced table_ids for the whole group in a single query and test membership.

* [GHY-3974] Review cleanups: cond-> in replace-field-ids; update-existing in result-metadata remap

- lib replace-field-ids: use cond-> for the template-tags/:dimension updates instead of if/else.
- audit remap-result-metadata: use m/update-existing with an identity-for-unmapped fn instead of
  a cond-> with duplicate lookups; drop the redundant pos-int? guard in remap-result-metadata-ref
  (field-id-remap is always a map, so it already returns nil for names/nil).
2026-07-06 19:07:41 +00:00
Aleksandr Lesnenko
fc54b654f4 disable coderabbit PR summaries (#77114)
* disable PR summaries

* disable coderabbit yapping when skipped
2026-07-06 19:03:17 +00:00
Braden Shepherdson
2a8b0fdefe [PDFs] If a Visualizer card has a name override, use it (#77033)
Fixes UXW-4705.

Also refactors the duplicated logic from two other places in the
subscriptions rendering into a new `render.util` helper.
2026-07-06 18:39:19 +00:00
Aleksandr Lesnenko
851cb65a11 coderabbit config (#77111) 2026-07-06 18:24:09 +00:00
Chris Vandoodewaard
62e3bb098e onboarding: add Github username to team, add Github -> Slack ID mapping (#77110)
Add Github ID to DevEx team, map Github ID to Slack ID
2026-07-06 18:22:08 +00:00
Nick Fitzpatrick
6bf214f2c2 update Echarts to 6.1.0 (#75139)
* echarts 6.1.0

* adjusting BE test
2026-07-06 23:44:56 +05:30
Nick Fitzpatrick
77eb75ecd0 improving Pivot table and and object detail PDF renders (#76728)
* improving Pivot table and and object detail PDF renders

* pivot table improvements
2026-07-06 23:41:59 +05:30
Nick Fitzpatrick
2080e7c13f Handle PDF uploads to slack user DMs (#76787) 2026-07-06 23:22:46 +05:30
Braden Shepherdson
78e968bd69 Use a much larger maximum nesting limit while parsing YAML (#76528)
Fixes UXW-3770.

The default limit of 50 levels of nesting is too small for deeply nested
MBQL expressions, such as a `replace(replace(replace(...)))` tower.

This PR raises the limit to 10k, and includes a test that 500 levels
parses fine. 10k works at my REPL but I don't want to commit a test like
that in case other JVMs hit a `StackOverflowError`. Rejecting the import
is a better UX than crashing Metabase!
2026-07-06 13:07:47 -04:00
Braden Shepherdson
636276120b Make /api/cache/invalidate endpoint return 400 for missing filters (#76364)
Fixes UXW-4108.

When no `database`, `dashboard` or `question` parameter is supplied, the
endpoint does not invalidate anything. It previously returned a 404 in
that case, indicating that nothing was found to invalidate.

But since no attempt to invalidate anything is made without at least one
of those parameters, the 404 was misleading. Instead, this malformed
request should return a 400, which it now does.

No impact to the Metabase FE, which only ever calls this endpoint with
the parameters supplied.
2026-07-06 13:07:34 -04:00
Tyler Plude
b0682e0144 [BOT-1776] Show cache read tokens in usage analytics (#76847)
show cache read tokens in usage analytics
2026-07-06 09:34:15 -07:00
Braden Shepherdson
4682a713c8 [PDFs] Regression test: hide "no results" cards per the setting (#77032)
Regression test for UXW-4706, which was fixed in #76918.
2026-07-06 12:29:28 -04:00
Andrei Chernykh
eae64a014a Invite someone to view a dashboard or question (#76444)
* Add an Invite someone to view this action to dashboard and question share menus (#76209)

* Add an Invite someone to view this action to dashboard and question Share menus

* Update admin create-user e2e to reveal the temporary password via the new toggle

* Add a shareable item link to the invite modal's no-email states

* Remove the stale password-toggle aria-label and reword the temp-password invite copy

* Land invited users on the shared dashboard or question after signup (#76505)

* Land invited users on the shared dashboard or question after signup

* Scope the invite email to the shared dashboard or question

* Code cleanup

* Polish the invite email's join button spacing, label, and padding

* Remove stale TODO about synchronous invite email

* Add tests for invite someone to view (unit + e2e) (#76589)

* Add unit and e2e tests for the invite-to-view feature

* Fix the invite-to-view e2e signup button and no-access selectors

---------

Co-authored-by: Nathan Voxland <nathan@metabase.com>

* Add user_invited and invite_to_view_opened analytics events (#76646)

* Add user_invited and invite_to_view_opened analytics events

* Reword the external-invite tracking comment in NewUserModal

* Type isEmailAlreadyInUse's error with a guard instead of a cast

* Return an error_code for the duplicate-email 400 and key isEmailAlreadyInUse off it

* Move invite-events analytics into common/analytics and assert events fire once

---------

Co-authored-by: Nathan Voxland <nathan@metabase.com>
2026-07-06 08:39:46 -07:00
Braden Shepherdson
2c6e6b806d [pdf] Remove branding for white-labeling customers (#76426)
Fixes UXW-4575.

The "Made with Metabase" branding is skipped for customers with white-labeling enabled.
2026-07-06 15:07:02 +00:00
Braden Shepherdson
2f98715cbc [PDFs] Respect the explicit text alignment setting for Markdown cards (#77031)
Fixes UXW-4703.
2026-07-06 10:45:54 -04:00
Brad Anderson
69c3756253 GRO-536 replace ad hoc metaplow functions with @metabase/track alpha (#76618) 2026-07-06 10:10:06 -04:00
Sébastien
344861dd67 Link to usage conditions in the theme preview acceptance prompt (#77072) 2026-07-06 15:38:21 +02:00
Jakub Chodorowicz
3487a7801f GDGT-2750: Treemap renders incorrectly in PDF export (#76996)
* fix treemap wrong size in grid driven pdfs

* add missing loki screenshot
2026-07-06 15:19:43 +02:00
Kevin Kelleher
1fbea58471 Fix tooltips showing incorrect date ranges for native queries (#76295)
* don't format native query weekly dates as ranges in tooltips

* delete e2e test for 25007
2026-07-06 07:41:05 -04:00
Oleh K
605c237a1a Allow map tile server host in img-src CSP (#76967)
* fix(custom-viz): allow map tile server host in img-src CSP

When Custom Visualizations are enabled, csp-img-enabled is forced on,
switching img-src from a permissive wildcard to a restricted allowlist.
Map tiles (OpenStreetMap by default, or a custom map-tile-server-url)
were never added to that allowlist, so map visualizations broke.

Automatically add the configured tile server's origin to img-src,
mirroring how custom font files are added to font-src. The {s} subdomain
placeholder becomes a * wildcard and the {z}/{x}/{y} path is dropped.

* docs: note map tile server is always allowed under restricted image domains

* Missing update to setting description

* Update comment

* Fix whitespace
2026-07-06 08:06:46 +02:00
Romeo Van Snick
b2d81611cc Build the metabase/router facade for react-router v7 (#76859)
* Rename router useRouter to kebab-case use-router

* Add router facade shared types and path/search utils

* Add useNavigate facade hook

* Add useLocation facade hook

* Add useParams facade hook

* Add useSearchParams facade hook

* Add Navigate facade component

* Add Outlet facade shim

* Add Link facade re-export

* Reference react-router v7 docs from each facade helper

* Lock facade tests to react-router v7 behaviour

* Import useRouter from the metabase/router barrel

* Sort metabase/router barrel exports

* Test useNavigate splits query from a string destination with state

* Test setSearchParams clears the query when called with no argument

* Use router/<name> pattern for facade test describe blocks

* Link react-router v7 API reference from facade types

* Use react-router's official descriptions for facade type comments

* Use useMount instead of a bare useEffect in Navigate

* Expand inline JSDoc in router utils to multiline

* Implement useNavigate over v3 history instead of redux dispatch

* Navigate via react-router's router API instead of history directly

* Re-navigate on prop change in Navigate to match v7

* Default useLocation state to null and note v3 helper limitations

* Pass Navigate state by reference and clone search-param updater arg

* Expose v3 splat param under v7's * key in useParams

* Drop the existing hash in setSearchParams to match v7

* Churn useNavigate identity per navigation to match v7

* Support defaultInit in useSearchParams to match v7

* Match v7's URLSearchParamsInit pair-tuple type

* Match v7's useParams generic signature
2026-07-06 09:08:31 +10:00
Alexander Polyankin
af81edb346 Revert "Enable streaming results for app db queries with postgres" (#77048)
Revert "Enable streaming results for app db queries with postgres (#76645)"

This reverts commit 49cc599892.
2026-07-05 04:55:18 -04:00
Denis Berezin
dc91702b6b UXW-4658 Fix viz settings dropdown broken styles (#76845) 2026-07-04 01:47:49 +03:00
Braden Shepherdson
b8d634be90 [PDFs] Reuse query results and PNG rendering memory pools for PDFs (#76918)
The work done in #76355 and #76504 to fix some OOMs while generating
subscriptions modified the core rendering pipeline (static viz charts to
PNGs) concurrently with the work happening on PDFs.

This adapts the PDF generation to reuse both in-memory and on-disk query
results, and to use the whole-dashboard budget of results in memory before
spilling to disk. Cleans up all temporary files when finished.
2026-07-03 16:01:30 -04:00
Nathan Voxland
471df8492b Add request info to 'Request canceled before finishing' log line (#77023) 2026-07-03 14:20:45 -05:00
technomancy
e0ad467236 Take existing tables into account when determining already-loaded bigquery (#76936)
Take existing tables into account when determining already-loaded bigquery.

We no longer have bigquery tables that constantly think that they need
to be recreated, but we have fallen a little too far in the other
direction; datasets that get their DB created but fail midway thru
will still be treated as loaded.

In snowflake we have a way of checking this down to the individual row
counts and counting as not-already-loaded if there's a mismatch. I
don't see a way to do this in bigquery, but we can at least check that
all the tables exist. If we get a failed partial load that gets all
the tables created but fails the rows that will still require manual
intervention.

Also stop using (config/current-major-version) when qualifying dataset
names; turns out this is not at all reliable in CI. This unfortunately
means that we don't actually have cross-major-version isolation; the
best we can do is isolate master/release from all other branches,
which is still an improvement over what we have now.
2026-07-03 17:26:34 +00:00
Timofey Kachalov
eac68e3fe9 Update c3p0 version (#77000) 2026-07-03 20:30:28 +04:00
Alexander Polyankin
d141f2f00e jdbc-data-warehouse-connection-pool-max-pending-checkouts (#77004) 2026-07-03 16:19:41 +00:00
metamben
5c0455b3ec Stop pretending the cache is up to date (#76898)
Closes GIT-10454
2026-07-03 18:38:33 +03:00
Mihael Konjević
a9ceb5f20d Drop unsupported get-day-of-week week-modes in repair (#76766)
`get-day-of-week` accepts a positional week-mode, and the ::week-mode
schema admits :iso, :us, and :instance (shared with get-week). But only
the default (no-mode) and :iso forms have a lowering in lib.filter.desugar
— :us and :instance desugar to a nil temporal-extract unit and 500 at SQL
compile time (observed: an LLM emitting "instance" for "day of week on
weekends"). Drop the unsupported mode, leaving the start-of-week-aware
default. :iso and the bare form are untouched.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-03 17:13:57 +02:00
Mihael Konjević
df0986902c Sharpen Metabot data-source discovery and construct guidance (#76767)
Prompt-snippet updates, independent of any code change:
- discovery: search to choose a source, navigate to drill in (don't skip
  the curated layer just because a raw table name is recognizable)
- data-sources: a source the user explicitly names is authoritative
- grounding: when several columns plausibly match, read descriptions and
  sample values rather than picking by name resemblance
- construct_notebook_query: a "translating the request" section (constraint
  vs breakout, apply every constraint, absolute vs relative dates)

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-03 17:13:47 +02:00
Timofey Kachalov
9b3fe8e0ea Pin jackson-databind for databrocks/redshift/snowflake drivers (#76980) 2026-07-03 19:06:40 +04:00
Chris Truter
7ed335db9c Decouple library-retrieval and semantic-search features (#76872) 2026-07-03 15:31:06 +02:00
Timofey Kachalov
b83ac24d1e Update esbuild to 0.28.1 (#76908) 2026-07-03 17:16:51 +04:00
Alexander Polyankin
c32c55c589 MB_JDBC_DATA_WAREHOUSE_CONNECTION_POOL_CHECKOUT_TIMEOUT_MS (#76941)
* MAX_JDBC_DATA_WAREHOUSE_CONNECTION_POOL_CHECKOUT_TIMEOUT_MS

* use same dox

* fix

* fix

* fixes
2026-07-03 12:44:44 +00:00
Benoit Vinay
84b27f02a5 utm query params for docs search (#76674)
* utm query params for docs search

* Misc

* Copy updates
2026-07-03 14:39:22 +02:00
Timofey Kachalov
863d48e920 Pin jackson-databind for bigquery-cloud-sdk (#76899) 2026-07-03 09:09:46 -03:00
lbrdnk
06d3dd8cb4 Support creation and and update of a metric through mcp (#76809)
* Support creation and metric update through mcp

* kondo
2026-07-03 12:46:33 +02:00
Oleh K
bfdce241fe Make custom-viz dev-mode hot reload reliable (#76739)
* fix(custom-viz): make dev hot-reload resilient to transient failures

When the dev server is mid-rebuild its bundle endpoint can transiently
fail, and rapid edits / overlapping reloads could leave the viz showing a
stale bundle or a spurious "unavailable" toast.

- Backend: fetch-dev-bundle returns nil on upstream failure (mirroring
  fetch-dev-manifest) so the endpoint serves its existing retryable 503
  instead of a hard 500.
- Frontend: retry the dev bundle fetch on transient 5xx (fail fast on
  4xx), and tag each load with a monotonic sequence so a slower/older
  overlapping load can't overwrite a newer applied bundle or fire a stale
  toast (latest-wins).

* fix(custom-viz): render the freshest bundle after overlapping dev reloads

Overlapping dev reloads (rapid edits) could apply the newest bundle to the
visualizations registry but leave the chart rendering an older one: the
visualization only re-reads the registry when it remounts on the loading
toggle, and a plain boolean cleared after the first load resolved.

- Refcount in-flight loads so `loading` stays true until the last settles,
  so the single remount reads the freshest registered bundle.
- Stop retrying a load once a newer one has started (it would be discarded
  by the latest-wins guard anyway, and would keep `loading` held).

* fix(e2e): restore custom-viz dev plugin source between retries

The development-mode custom-viz test mutates the scaffolded plugin
source in place ("Above threshold" -> "Way above!") to verify hot
reload, but never reverts it. Since `before` does not re-run on a
Cypress retry, a retried attempt started from the mutated file and the
opening "Above threshold" assertion timed out against stale state.

Capture the pristine source in `before` (after the clean re-scaffold)
and rewrite it in `afterEach` so each attempt starts from the default.

* fix(e2e): use frozen lockfile for custom-viz SDK bun install

Skip lockfile resolution during the dev-mode `before` hook so the
install step is deterministic and faster, reducing the chance of the
120s setup timeout.

* fix(e2e): start custom-viz dev server per test, not per suite

The dev-mode test stops the dev server as its final assertion (revert to
default), but the server was started once in `before`. Since `before`
does not re-run on a Cypress retry or during burn-in, every run after the
first hit a dead server and failed at "verify the dev plugin is
registered".

Move the server start to `beforeEach` and the stop to `afterEach` (the
stop task is idempotent), keeping the heavy build/scaffold/install in
`before`.

* chore(custom-viz): trim verbose comments per review

* refactor(custom-viz): reuse retry util for dev bundle fetch

* fix(custom-viz): use > not >= in superseded check

The == case is impossible (loadAppliedSeq is only set to a load's own seq
on success, which returns before the catch; seqs are unique), so >= and >
are equivalent here. > matches the sibling loadStartedSeq check and reads
as "a strictly newer load exists".

* fix(custom-viz): only the latest-started load registers its bundle

The apply-guard bailed only when a newer load had already applied; bail
when a newer load has merely started too (applying implies starting, so
this subsumes the old check). Reuses isLatest(), consistent with the
retry loop and the superseded check.

* refactor(custom-viz): name load-sequence maps by plugin id

* test(custom-viz): scaffold dev plugin per attempt instead of capturing source

Move the plugin scaffold (init + npm i) into beforeEach so each attempt
starts from a pristine source, dropping the pristineSrc capture/restore.
The expensive SDK build stays one-time in before.
2026-07-03 12:37:31 +02:00
Timofey Kachalov
3777617772 Update @hey-api/openapi-ts (#76897) 2026-07-03 14:17:57 +04:00
Sébastien
06ed290471 Fix crash when editing column settings in the embedding SDK (#76795)
* fix crash when editing column settings in embedding SDK

* add e2e test for editing native question column title in embedding SDK
2026-07-03 11:51:23 +02:00
Oleksandr Yakushev
7afc643c0c [lint] Implement Kondo hooks for metabase.util.match macros (#73986) 2026-07-03 12:31:46 +03:00
Mahatthana (Kelvin) Nomsawadi
960b9fa2d1 Gate SDK query builder controls on create-queries permission (#76862)
* fix(embedding-sdk): gate query builder controls on create-queries permission

Filter/Summarize/Breakout dropdowns and the notebook editor toggle rendered
regardless of query permissions, showing non-working controls for users
without create-queries access. Mirrors main app's FilterHeaderButton/
QuestionSummarizeWidget/QuestionNotebookButton gating (isEditable, !isNative,
!isArchived) via a new shouldRenderQueryBuilderEditingControl.

Fixes EMB-1963

* test(embedding-sdk): unit test shouldRenderQueryBuilderEditingControl

Covers editable/native/archived/no-question cases, plus the missing
create-queries case by building a query against metadata with the source
table excluded (mirrors what the backend does when that permission is
missing) rather than mocking metabase-lib.

* fix(embedding-sdk): hide decorative icon from ToolbarButton accessible name

Icon set role="img" aria-label="<name> icon" unconditionally, so a button's
accessible name became "filter icon Filter" instead of just "Filter",
breaking cy.button()/getByRole name lookups.

* test(embedding-sdk): e2e test for query builder permission gating

Confirms Filter/Summarize/notebook editor toggle are hidden for a user
without create-queries permission on the underlying table, and shown for
one with it, using existing readonly/readonlynosql fixture users whose
default group permissions already match each scenario.

Fixes EMB-1963

* docs(embedding-sdk): tighten comments, scope test fixtures per-test

Bullet the three omitted main-app gating conditions instead of run-on
prose, shorten the missing-permission test comment, and move each
question fixture into the test that uses it instead of module-level
constants shared across unrelated tests.

* fix(embedding-sdk): guard BreakoutDropdown on missing question

Matches the !question || !shouldRenderQueryBuilderEditingControl(question)
pattern used by FilterDropdown and EditorButton.
2026-07-03 10:20:30 +01:00
Oleksandr Yakushev
6c81e71958 [schema] Validation performance improvements (#64815) 2026-07-03 12:19:46 +03:00
Chris Truter
caf298bc5a Support OSI ai_context string shorthand (#76865) 2026-07-03 09:43:46 +02:00
Chris Truter
71c929d0d9 Metabot catalog to include all curated entities (#76863) 2026-07-03 09:42:14 +02:00
Romeo Van Snick
34296d1975 Reuse dashboard save response and make dashboard e2e saves deterministic (#76507)
* Let fetchDashboard accept a prefetched dashboard

(cherry picked from commit 63425d8754777a96f023c3be6028c5a45b4607d5)

* Use save response to refresh dashboard instead of refetching

(cherry picked from commit 8f5aff044beb8290f9c63f7ebb041ffbe8c2b392)

* Test save reuses response without refetching the dashboard

(cherry picked from commit a90b2885f7ac19ed472bed1018a88fa29fee60be)

* Update e2e save helper for dropped post-save dashboard refetch

(cherry picked from commit 41bba584ae41640903c06fcd76022a1569d6f087)

* Update e2e dashboard reload expectations for save-response reuse

(cherry picked from commit 97fabf4f8df7d0c1345ea33a6136a1c3ba76933f)

* Wait on dashboard UI instead of phantom reload when returning from drill

(cherry picked from commit 19181e1345af6af1fe46f323c3b0362a5286e1b4)

* Add waitForDashcardsToLoad e2e helper and use it in #32444 test

(cherry picked from commit fa3a0e989f2166f50af10a0294fcda9bfef968d9)

* Settle saveDashboard on dashcards loaded instead of fixed sleep

(cherry picked from commit b7a2e157b6db12a2f4f8ab10b7c19f68437b94ed)

* Drop redundant saveDashboard waitMs args now that it settles deterministically

(cherry picked from commit e8827b06955f581dde739491d3aef2bee5f90be9)

* Drop redundant post-save sleep now covered by saveDashboard settle

(cherry picked from commit c3ae1c65997165fffc0fa1c394d1d2765b4fb2b8)

* Drop tombstone comments per review

* Make waitForDashcardsToLoad tolerant of dashboards without a grid

* Anchor dashcard settle on dashboard body to avoid early return

* Revert broad saveDashboard auto-settle; keep save-reuse and opt-in waitForDashcardsToLoad

* Settle saveDashboard on dashcards loaded + grid layout stable; drop waitMs sleeps

* Wait for filter widgets to settle after save (parameter panel re-render)

* Make editDashboard resilient to a dropped Edit click after save

* Make editDashboard retry work inside cy.within (use cy.document not cy.get body)
2026-07-03 08:37:10 +10:00
Romeo Van Snick
4dcb2a7f86 Add routing behavior lock-down tests (#76322)
* Add routing behavior lock-down tests

* Add updateUrl navigation producer lock-down tests

* Add table-route preservation lock-down tests for updateUrl

* Add locationChanged read-seam lock-down tests

* Add dashboard URL-query sync lock-down tests

* Restore console spies in routing lock-down tests

* Fix import order lint in dashboard url-query test

* Fix parameterValues type in dashboard url-query test
2026-07-03 07:56:20 +10:00
github-automation-metabase
f19e78d9fc Auto-update documentation for master (#76924)
Update generated docs (master)

Co-authored-by: github-actions <github-actions@github.com>
2026-07-02 17:37:52 -04:00
metamben
44570e07cd Convert all ASCII chars in var names not allowed by mongo to _ (#76761)
Closes QUE2-704
2026-07-03 00:33:36 +03:00
github-automation-metabase
b4b8e57722 Restore 30s timeout on findByText (#76021)
* auto stress test

* better options

* fix(e2e): restore 30s timeout on findByText for impersonated permission test

The timeout was removed in a8cc638d2f when updating the error message text.
The impersonated write path takes 15-20s, far exceeding the default 4s timeout,
causing consistent test failures (quarantined for 33 days).

---------

Co-authored-by: Ryan Laurie <iethree@gmail.com>
Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
Co-authored-by: Ryan Laurie <30528226+iethree@users.noreply.github.com>
2026-07-02 19:18:59 +00:00
Michael Eby
1fe4641c3e docs: new dimension picker in metrics explorer (#76552)
* docs: new dimension picker in metrics explorer

* Optimized 4 images, saved 493.5 KB (52.8% smaller)

* Edits from Alex

---------

Co-authored-by: Metabase Automation <github-automation@metabase.com>
2026-07-02 14:48:50 -04:00
github-automation-metabase
bc91754508 Stabilize flaky pivot-table dashboard filter spec (#76747)
* Fix flaky pivot-table dashboard filter spec: wait for dashcard load before opening question

The "does not use extra filtering stage for pivot tables" spec clicked the pivot
dashcard's legend title immediately after exiting edit mode. The title's
navigation handler is only wired once the card series has reloaded, so an early
click was a no-op and the /api/dataset/pivot request never fired, timing out
cy.wait("@datasetPivot"). Wait for the dashcard to finish loading (visible title
+ no loading indicator) before clicking.

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

* Give pivot-table dashboard filter spec a throttle-tolerant pivot wait

Clicking the pivot dashcard title navigates to an ad-hoc QB that must boot
the route, load table metadata, and only then issue /api/dataset/pivot. Under
network throttling that chain can exceed cy.wait's default 5s timeout, so the
wait occasionally fails even though the request does fire moments later. Wait
on the @datasetPivot alias with a throttle-tolerant timeout.

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-07-02 12:41:18 -06:00
Ryan Laurie
2828ecaa8b Fix Linear Release Sync Again (#76909)
* add catch logic

* do it right this time
2026-07-02 12:14:08 -06:00
Ryan Laurie
8c937d249b Don't fail builds on linear release issue tracking (#76889)
don't ever fail a build for this
2026-07-02 18:56:31 +02:00
Riley Thompson
b27f04d153 Use report timezone if breakout field has datetime effective type (#76697)
use report timezone if bucketed field as temporal effective type
2026-07-02 11:10:59 -04:00
Egor Grushin
8d56144be1 GDGT-2589 Make H.popover() to select the Select component from "metabase/ui" (#76737)
* GDGT-2589 Make H.popover() to select the Select component from "metabase/ui"

* GDGT-2589 fix attributes drilling
2026-07-02 15:52:37 +01:00
Ben Grabow
2833fa63b2 Exclude audit db when coalescing default perms (#76608)
* Exclude audit-db when selecting lowest permission level for group
2026-07-02 09:25:20 -05:00
Nemanja Glumac
7098c5576a Add a unified, dry-run ci-conductor quarantine gate (#76752)
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-02 15:14:29 +02:00
Nicola Mometto
03b9522551 Incremental transforms merge (#76663)
* WIP: support for merge strategy via delete + insert

* PoC FE

* fix

* overridable method

* support for py

* refactor

* FE

* changelog

* FE fixes

* validate UK

* chore

* update FE

* tests

* remove compile-merge multi

* FE tests

* remove feature

* move component to its own file

* chore: test composite keys

* fix: override for sqlserver
2026-07-02 13:09:19 +00:00
Nick Fitzpatrick
eec1d1b0d5 Add only published filter to data studio table picker (#76521) 2026-07-02 18:28:32 +05:30
Alex Yarosh
a3596d04cf docs - password complexity (#76776)
* Revise password complexity guidelines in documentation

Updated password complexity requirements and options.

* Update docs/people-and-groups/changing-password-complexity.md

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

* Apply suggestions from code review

---------

Co-authored-by: Jeff Bruemmer <jeff.bruemmer@gmail.com>
2026-07-02 12:35:51 +00:00
github-automation-metabase
68f276b5a1 Auto-update documentation for master (#76849)
Update generated docs (master)

Co-authored-by: github-actions <github-actions@github.com>
2026-07-02 08:31:35 -04:00
Jakub Chodorowicz
2e2aae3f62 GDGT-2527: Make new treemaps full width by default (#76804)
change the default size of treemap to full grid with
2026-07-02 14:08:52 +02:00
Mahatthana (Kelvin) Nomsawadi
2e33d53027 fix(sdk): open SQL editor when Metabot navigates to native hash URL (#76738)
* fix(embedding-sdk): open SQL editor when Metabot navigates to native hash URL

When Metabot sends navigate_to with /question#<native_hash>, SdkAdHocQuestion
was returning questionId=null (no numeric slug), so isNewQuestion=false and the
SQL editor never opened. Now detects dataset_query.type==='native' and returns
'new-native', which makes SdkQuestionProvider set isNewQuestion=true and
useNewQuestionEditorSync open the editor.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Dwi9BjxKNSJsztkkVrsU8d

* test(sdk): use real embedding Metabot stream for SQL editor test

Replaces hand-rolled mock payload with a navigate_to event captured
verbatim from an actual embedding Metabot response, so the test
fixture matches real wire format (db id adjusted to match env).

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

* refactor(sdk): call resolveQuestionId inline instead of in useMemo

It's a cheap derivation, not worth complicating the memo for.

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

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-02 12:01:36 +01:00
Oleh K
132a7e674a refactor: Migrate icon tokens (disabled/secondary swap) (#76792)
* GDGT-2534 Migrate icon tokens (disabled/secondary swap + text aliases)

Per design, the icon tokens are corrected: `icon-disabled` and
`icon-secondary` swap meaning, and all four icon tokens become runtime
aliases of their text counterparts.

- Swap consumers: `icon-disabled` <-> `icon-secondary` call sites.
- Redefine in both themes:
  - icon-primary  -> var(--mb-color-text-primary)   (value unchanged)
  - icon-secondary -> var(--mb-color-text-secondary)
  - icon-disabled  -> var(--mb-color-text-disabled)
  - icon-brand    -> var(--mb-color-text-brand)      (brand[40] -> brand[50])

Token names are unchanged, so there's nothing to remove at cleanup. Icon
tokens aren't SDK public theme keys and aren't used in static-viz, so the
var() aliases are safe everywhere.

* Update Loki Snapshots

---------

Co-authored-by: Metabase Automation <github-automation@metabase.com>
2026-07-02 13:00:13 +02:00
Romeo Van Snick
a1a4a037fd Consolidate basename into a dedicated module (#76852)
* refactor: add basename module for app-wide basename state

* refactor: move basename off ApiClient into the basename module

* refactor: make setBasename tolerate nullish input

* refactor: drop redundant basename guard in sdk init

* test: capture original basename per-test in setupBasename

* fix: strip basename only as a prefix in getDatasetDownloadUrl
2026-07-02 19:20:12 +10:00
Romeo Van Snick
914130d706 Bundle-size stats: emit Description column (fixes 422 on upload) (#76860)
Bundle-size stats: emit Description column populated with the commit subject
2026-07-02 06:06:23 +00:00
Romeo Van Snick
2ed2645f5b Fix bundle-size extract: drop non-existent embedding-sdk.js pattern (#76857)
Fix bundle-size extract: drop non-existent embedding-sdk.js pattern (unzip exit 11)
2026-07-02 14:41:56 +10:00
Fraser
e73f7ecf1b Update affected test stats (#76855) 2026-07-02 16:36:02 +12:00
Romeo Van Snick
91bdbd3f21 Bundle-size: apples-for-apples PR check + delta-aware stats logger (#76409)
* Measure SDK/app bundle sizes from both uberjars, apples-to-apples

* Always report brotli bundle size, estimating when no .br is shipped

* Bundle-size stats: upload per-bundle deltas, skip unchanged commits

* Bundle-size stats: always record releases, gate/report on brotli delta

* Scope app to app-main and SDK totals to reachable code via the chunk graph

* Fall back to whole app/dist when stats lack reachableAssets

* Stats logger: record master only, drop release tags from the live series

* Measure SDK async chunks as loadable; split legacy initial/total

* Point bundle-size logger at table 79702

* Skip SDK bundle-size gate when base ref predates reachable-chunk stats

* Split bundle-size scripts into pure cores + I/O wrappers, add unit tests

* Bundle-size: extract legacy embedding-sdk.js fallback; fix stale as-served comments

* Retry stats upload with backoff; keep bundle-size run green if it still fails
2026-07-02 13:27:43 +10:00
appleby
9160419f64 BOT-1723 Support OpenAI models (#76499)
* Add default-openai-llm-metabot-model gpt-4.1-mini

* Filter openai list-models by supported-models

OpenAI's /vi/models endpoint returns ~140 models, many of which are not relevant (text embeddings, audio/video models)
or else deprecated. Filter this down to a whitelisted set of known supported models.

* Add grouping for openai models in provider-models-response

* Throw an exception if callers pass `:ai-proxy true` for openai

Similar to bedrock and azure, supporting this would require some work on the ai-service side, and we already reject
non-anthropic in validate-metabase-managed-provider!

* FE: enable openai provider in metabot admin UI config

* Drop gpt-4.1-mini from supported-models and change default to gpt-5.4

* Replace gpt-4.1 with gpt-5 in supported-models

* Bump metabase.metabot.example-question-generator/max-tokens to 4096 for gpt-5

GPT-5 produces a lot of reasoning tokens and sometimes exceeded the old limit.

* Remove reference to gpt-4.1-mini in docstring example

* Remove references to gpt-4.1 and gpt-4.1-mini in FE unit tests
2026-07-01 20:03:03 -07:00
Ryan Laurie
0cdbb874ac Add Linear Release tracking (#76711)
* Add Linear Release tracking

* use uniform helper

* fix typos 🤦‍♀️

* get linear release version
2026-07-01 18:16:21 +00:00
Eric Normand
6cc57802d4 Skip empty remote-sync commits after a no-op export (GHY-3934) (#76753)
* Skip empty remote-sync commits after a no-op export (GHY-3934)

A dirty RemoteSyncObject row whose serialized content already matches the
repo stages a net-zero tree change, so finishing the commit produced an
empty commit that still got pushed. GHY-3933's content-hash gating catches
the no-op-update-event case, but not the others: a full-export fallback
that re-serializes byte-identical content, a rename/delete whose old path
isn't known yet, a dedup name collision, or path/hybrid models.

Add an `empty-commit?` query to the CommitBuilder protocol (git layer
answers whether the staged tree equals the parent's; it does not decide
policy). full-export!/incremental-export! branch on it: when empty, abort
the commit, leave the version unadvanced, and report push-skipped — while
still reconciling RemoteSyncObject state so the stale dirty flags that
triggered the no-op are cleared.

* Docstring

* Unify remote-sync export commit lifecycle and skip empty merges

Extract commit-staged! — the open/stage/empty-commit?/finish-or-abort
lifecycle — and route full, incremental, and merge exports through it.
merge-and-store! moves from source.clj into impl.clj (next to the other
export paths) so it shares commit-staged! instead of duplicating the
lifecycle via replace-all-files!; source.clj keeps the merge computation
(compute-merge, preview-merge).

commit-staged! returns the :remote-sync/empty-commit sentinel when the
staged tree matches the parent, so the merge path no longer pushes an
empty commit either. An empty merge folds in any remote changes and
advances to the remote tip, reporting "pulled" (or "push-skipped" when
nothing changed on either side) rather than a misleading "merged, pushed 0".

* Inline merge-and-store! into export-merged!

The intermediate {:status ...} map that export-merged! re-dispatched via
case added nothing: inline the merge computation and commit so the merge
path reads like full-export!/incremental-export! — compute, commit-staged!,
reconcile, outcome.

Move the test seam down from merge-and-store! to source/compute-merge: the
export! tests stub the pure merge function and exercise the real commit
staging, and the three dedicated merge-and-store! unit tests are dropped as
redundant with merge-test (algorithm) and the commit-staged!/export coverage.

* Better docstrings

* Test empty-commit? against a real git repo

Exercise empty-commit? through the real JGit commit builder (not a mock):
identical re-stage and delete-of-absent-path read empty, real edits and new
files don't, aborted no-op checks leave the branch untouched, and the
memoized tree still yields a correct commit when finish-commit! follows.
2026-07-01 18:06:55 +00:00
Oleksandr Yakushev
f8cb4ca1bf Bump kixi.stats to 0.5.9 (#76789) 2026-07-01 15:01:44 -03:00
appleby
d3ee87fab5 Claude Sonnet 5 support (#76756) 2026-07-01 10:33:30 -07:00
Eric Normand
2d635fadf9 Drop metabase_version from serialization (GHY-4013) (#76760)
Serdes stamped every non-Setting entity (and the Card column) with the
instance build version on extract. Since the value differs between
instances, it produced spurious uncommitted changes during remote sync.

Compatibility is now governed by the versioned representation spec
(:card_schema + upgrade-card-schema-to), so the per-entity version stamp
no longer carries useful information. Stop serializing it:

- extract: remove the metabase_version stamp
- Card serdes spec: move :metabase_version from :copy to :skip
- load: remove the now-dead version-mismatch warning machinery

Legacy baseline fixtures still carry the field, exercising that older
exports import cleanly now that it's skipped.
2026-07-01 16:10:32 +00:00
lbrdnk
5c475f1d06 Add endpoint for execution of saved questions (#76720)
* Add endpoint for native query construction in expected format

* Add model import

* Add endpoint for execution of saved questions
2026-07-01 16:54:25 +02:00
lbrdnk
fe2715ef6b Add endpoint for native query construction in expected format (#76717)
* Add endpoint for native query construction in expected format

* Add model import

* Review remarks

* Endopint version
2026-07-01 15:20:39 +02:00
Sébastien
3d8b6293b8 Fix date-dependent test in ConversationFilters date dropdown (#76803)
fix date-dependent ConversationFilters date dropdown test
2026-07-01 18:46:40 +05:30
Nemanja Glumac
b4f0b23363 Reuse the ci-conductor contract types and utils in e2e reporting (#76746)
Replace e2e's local ConductorTest with the shared NormalizedTest wire shape
(plus a transient screenshotPath) and import toNumber from the module, so the
report path and the quarantine path can't drift on a test's identity. The
transport stays forked: e2e posts mid-run from Cypress's after:spec hook on
node-fetch, with screenshots and a dry-run mode the module's post-run transport
doesn't cover.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-07-01 13:13:29 +00:00
github-automation-metabase
34cc99da9a Auto-update documentation for master (#76764)
Update generated docs (master)

Co-authored-by: github-actions <github-actions@github.com>
2026-06-30 23:37:34 -04:00
Mahatthana (Kelvin) Nomsawadi
1f99507ef5 fix(sdk): controlled parameters prop leaks into drill-through target dashboard (#76716)
* fix(sdk): strip controlled parameters from drill-through target dashboard

When InteractiveDashboard renders a drill-through target via
SdkInternalNavigationProvider, the full dashboardProps spread included
the host's controlled `parameters` and `onParametersChange` props.
getEffectiveParameterValues makes the controlled prop win over
initialParameters, so click-behavior filter values were silently
discarded and the target dashboard opened with empty filters.

Introduce getDrillThroughDashboardProps to explicitly strip controller
props before forwarding to the drill-through target. Display props
(withDownloads, withTitle, etc.) pass through unchanged. The target
is seeded from click-behavior initialParameters as intended.

Fixes EMB-1946.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Fwn7CNjPBZAg4KLVMaV7HW

* fix(sdk): also strip initialParameters from drill-through target props

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Fwn7CNjPBZAg4KLVMaV7HW

* test(sdk): clean up EMB-1946 e2e test

Rename Dashboard A/B to Origin/Target for readability, fix parameter id,
remove cy.intercept/cy.wait in favour of visible UI assertions only, and
rename the describe block to cover all three stripped props.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Fwn7CNjPBZAg4KLVMaV7HW

* test(sdk): remove describe.only from EMB-1946 test

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Fwn7CNjPBZAg4KLVMaV7HW

* fix(sdk): address review feedback on getDrillThroughDashboardProps

- shorten comment to focus on why (root-scoped props override drill-through target)
- tighten return type to Omit<> reflecting the stripped keys

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Fwn7CNjPBZAg4KLVMaV7HW

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-07-01 10:22:19 +07:00
appleby
d5fea3a9a0 Limit metabot related-tables to bound context size (#76588)
* Limit metabot FK related-tables to bound context size

When bulding metabot's context we expand one related-table entry per FK column and fetch and format the full column
set for each related table. On a large, highly-connected schema this fetches a large number of columns into the
metadata cache, exhausting the heap (metabase#76493).

We now limit the number of related-tables we attempt to fetch to metabase.metabot.tools.entity-details/max-related-tables

* Report truncated related tables to the LLM

When the related-table list in the metabot context gets truncated due to exceeding the limit, leave a note in the
context that truncation occurred. For tables that were dropped, include them in a lighter weight list with only
id/name/related-by (also capped), so the LLM knows more related tables exist and can look any of them up individually.

`entity-details/related-tables` now returns the detailed list plus a total count and a list of truncated items; the
result surfaces related_tables_truncated / related_tables_total / related_table_refs (+ related_table_refs_truncated),
and llm-shape renders a <related-tables-truncated> note with the truncated items.

* Rename max-related-table-{,truncated-}refs and add table descriptions

* Don't :include-implicitly-joinable? when looking up FKs for metabot related-tables

Otherwise we fetch and cache the full column set for every FK-target table when looking up realted-tables for
metabot's context. Instead, just do a bulk metadata lookup on the FK target columns only so we don't blow up the
metadata cache for tables with a huge number of columns.

* Cleanup docstrings and formatting in related-tables->xml

* Exclude tables in :related_tables from :related_table_refs

The refs list doesn't need to duplicate the tables from :related_tables. This way, the LLM potentially gets more
info about truncated tables, since we also cap the :related_table_refs list.

* Drop :related_tables_truncated and :related_table_refs_truncated

They can be inferred from :related_tables_total and the size of two lists.

* Use render-llm-template for related-tables->xml and related-table-ref->xml

* Fold related-tables-result into related-tables

* Reduce max-related-tables from 20 to 10

* Make metabase.metabot.tools.entity-details/related-tables private

* Fix docstring typo

* Ensure that :related_tables_total = :realted_tables + :related_table_refs

Don't exclude entries from :related_table_refs just because the table id appears in :realted_tables. We specifically
want to allow duplicate table-ids as long as the (table-id, fk) pairs are distinct to preserve the total = related +
refs invariant.

* Cleanup realted-tables

* Return field id from fk-related-table-groups

To avoid having to call lib.metadata/field in the caller for each fk just to extract the :name.

* Include the field id in related-tables :related_by to distinguish fk fields with the same :name

* Simplify handling for related-tables without fields

- rename max-related-tables to max-related-tables-with-fields
- rename max-related-table-truncated-refs to max-related-tables
- rename :related_table_refs to :related_tables_without_fields
- return up to max-related-tables-with-fields (10) in :related_tables
- return up to 40 tables in :related_tables_without_fields
  - 40 = 50 - 10 = max-related-tables - max-related-tables-with-fields
- always use table-details to format related-tables, just pass :with-fields? false once max-related-tables-with-fields
  is exceeded

* Don't say roster

* Only include :related_tables_without_fields if the caller requested fields

If the caller did not pass `with-fields? true`, then there is no distinction between :related_tables and
:related_tables_without_fields, so don't include it.

* Fix docstring
2026-06-30 17:47:51 -07:00
YB
15c5b59fe7 [GDGT-2688] refactor find-stale-query to core multimethod (#76649)
Makes find-stale-query easier to extend in core models.
2026-07-01 08:40:25 +08:00
technomancy
eeaf08ce0a Adjust dataset name qualification for snowflake and bigquery. (#76706)
Adjust dataset hashing for snowflake and bigquery.

We are frequently seeing some rogue process dropping the test-data
database which is shared across all tests, causing a good deal of
instability. We have not been able to track down what code is doing
this. Changing the way we calculate database names based on dataset
will help us find the culprit and also help isolate branches for
stability.

When we are on master or a release branch, splice the current major
version into the qualified database name. When we aren't, use "sha__"
as a prefix instead of "sha_", which will keep backport branches from
affecting dev branches going forward and help us identify whether it's
backports or not that are causing the database drops we're seeing.

Stop checking the tracking table to determine whether the dataset is
loaded. The dataset will be tracked regardless, so this should not
factor into the question of whether it needs to be created.

Unrelated change: update get-or-create/create-database! to print when
it encounters a failure and deletes the database it was trying to
create. This should never happen for snowflake/bigquery because they
are flagged as not supporting dynamic dataset loading, but it's still
better to have this printed visibly instead of the error logs which
are hidden.
2026-06-30 22:45:36 +00:00
Alexander Polyankin
5fb4c98d45 Fix transform table deletion in workspaces (#76754)
* fix table deletion

* FE fix

* FE fixes
2026-06-30 18:24:50 -04:00
Jeff Bruemmer
7a7e1d4ae3 docs - notes on custom viz (#76703) 2026-06-30 17:52:54 -04:00
Nemanja Glumac
f3370e8c87 Report frontend jest test failures to ci conductor (#76666)
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-30 20:48:03 +00:00
Riley Thompson
5d84f2ea39 Upgrade databricks jdbc driver (#75037)
* upgrade snowflake and databricks jdbc drivers

* remove arrow, disable thrift client

* bump snowflake

* skip snowflake upgrade
2026-06-30 20:01:46 +00:00
Chris Truter
78382c9a96 Retrieve Library Entities tool using OSI metadata (#76394) 2026-06-30 15:15:53 -04:00
Anderson
b113cf9527 Fix shift-scroll behavior in the data picker browse all state (#76537)
Fix shift-scroll in data picker
2026-06-30 16:02:32 -03:00
Anderson
15adc01a45 Consolidate duplicated ColumnSettings types into single definition (#76713)
* Consolidate ColumnSettings types into single definition in metabase-types/api

* Collapse OptionsType into ColumnSettings
2026-06-30 16:01:45 -03:00
Eric Normand
008bf29ce0 Fail serialization export when cards escape requested collections (#75176) (#76741)
* Fail serialization export when cards escape requested collections (#75176)

When a dashboard or card in the requested collections referenced a card
saved outside them, escape analysis logged a warning but the extract
stream was silently emptied. The CLI still printed "Export complete!" and
exited 0, and the API returned HTTP 200 with an archive containing only
export.log, so automated pipelines could not detect the empty export.

The default export now aborts loudly: the eager extract phase throws, so
the CLI exits non-zero and the API returns a 4xx before streaming begins
(the status can't change once the tar.gz starts). continue-on-error is
unchanged - it still proceeds, skipping the escaped entities, and the
escape warnings still land in export.log.

* Unify escape reporting and abort into handle-escapees!

The escape warning report and the abort throw were two adjacent branches
over the same data. Fold them into one handle-escapees! function: it logs
the per-entity report and, unless continue-on-error? is set, throws to
abort. Behavior and the thrown message/status are unchanged.

* Better docstrings
2026-06-30 18:44:44 +00:00
Riley Thompson
8e47d62c2c Don't error when table has a foreign key reference to an inaccessible table (#76740)
* use promise allSettled

* Add e2e test
2026-06-30 14:38:17 -04:00
Nick Fitzpatrick
d53658dc3b Allow field identifiers to grow in Data Studio Table page (#76287)
* Allow field identifiers to grow in Data Studio Table page

* Move Data type section below Field name

* Maz and Anderson feedback
2026-06-30 23:37:40 +05:30
Anderson
b52b11e11a Remove wrong disabled styles on chart settings Data fields (#76744) 2026-06-30 14:48:11 -03:00
Eric Normand
585f612d74 Track remote-sync dirty state by serialized content hash (GHY-3933) (#76098)
* Track remote-sync dirty state by serialized content hash (GHY-3933)

The remote-sync "yellow dot" was driven purely by update events: any
:event/<model>-update flipped the RemoteSyncObject row to "update",
regardless of whether the entity's serialized form actually changed. So
editing a non-serialized field (e.g. a transform's schedule) or any no-op
re-save marked the entity dirty, and the subsequent push produced a commit
with no files.

Record a content_hash (SHA-256 of the entity's serialized YAML, taken from
the live DB entity) on each RemoteSyncObject at every sync point — full
export, incremental export, and import. On an update event, the consumer
recomputes the hash and keeps the row "synced" when it matches the recorded
baseline; a null baseline is treated as dirty so new content still exports
once. A reverted edit that returns to the synced content clears the stale
dirty flag.

Works for all tracked model types (entity-id, hybrid, and path identities).

* Add export/import integration tests for content-hash dirty detection

Beyond the consumer-level per-type tests (which seed the baseline hash
directly), add end-to-end tests that exercise the baseline-recording paths:

- export integration: run a real export! to a mock source, then fire a no-op
  update and assert it stays synced — covers the incremental export
  synced-loop hash recording for Card, Dashboard, Document, Timeline,
  Collection, TransformTag, and PythonLibrary.
- import integration: run a real import! from a mock source (the "right after
  a pull" scenario), then fire a no-op update — covers record-content-hashes!
  on the import path for Transform and TransformTag.

* Better comments in migration

* Batch record-content-hashes! to one extraction and update per model

Instead of re-extracting and updating each RemoteSyncObject one entity at a
time, group rows by model type and: run a single extract-query (keeping each
instance's local id so it correlates to its row), serialize each in-process,
and write all hashes with a single CASE update. This works for every identity
flavor — including the extract-query overrides (Collection, NativeQuerySnippet),
hybrids, and path models (Table/Field) that have no entity_id — since
correlation is by the instance's primary key, not entity_id.

Adds a unit test asserting the batched result matches per-row row->content-hash
across entity-id, override, hybrid, and path models.

* Chunk record-content-hashes! into batches of 500

Bound the IN-list and CASE expression sizes: partition each model type's rows
into chunks of content-hash-batch-size (500) and run one extract-query + one
CASE update per chunk, so very large synced sets don't produce a single
oversized statement. Adds a test (with a small batch size) covering rows that
span multiple chunks.

* Use t2/query CASE update for cross-driver portability

Switch the batched content_hash write from t2/update! (with a honeysql value)
to the t2/query {:update :set :where} form used by
queries.models.query/update-rolling-average-execution-times! — the established
cross-driver (H2/Postgres/MySQL) pattern for a single atomic CASE update.

* Use t2/update! for the batched content_hash CASE update

RemoteSyncObject has no transforms or update hooks, so t2/update! passes the
honeysql CASE expression straight through to the same dialect-aware compilation
as t2/query — equally portable across H2/Postgres/MySQL — while reading more
idiomatically with its conditions/changes maps.

* Make record-content-hashes! no-arg, selecting all rows itself

Both callers passed the same select-all of RemoteSyncObject rows, so move that
query into the function. It is always invoked after every row is synced.

* Run record-content-hashes! under serdes/with-cache

Extraction resolves foreign keys (collections, databases, users, …) while
serializing each entity. Wrapping the pass in serdes/with-cache memoizes those
resolvers so shared references are looked up once instead of once per entity.
The full-export caller was already inside a cache; the import caller was not.

* Record export/import metadata in one serialize + one batched write

Collapses the post-export/import RemoteSyncObject bookkeeping. Previously a full
export serialized the whole synced set twice (store! to write files, then
record-content-hashes! to re-serialize for hashes) and wrote each row up to
three times (blanket status, per-row file_path, batched content_hash); import
was similar.

Now:
- source/store-and-record! drives serialization from extract-query so it keeps
  each entity's primary key, writing files and returning {:model_type :model_id
  :path :content_hash} — so file_path and content_hash come from the single
  serialization store! already does, for every model type (including path
  models with no entity_id).
- record-exported-metadata! writes file_path and content_hash for all models in
  one batched CASE update per chunk (not per model, not per row), matched by
  primary key.
- import-content-metadata re-serializes the loaded entities once (import has no
  store!), overriding file_path with the actual repo path for entity-id models;
  used by both full and incremental import.

Extraction (extract-one) runs inside the extract-query reduction so the JDBC
ResultSet stays open. Replaces record-exported-paths! and record-content-hashes!.

* Batch the incremental export RSO updates

The incremental export fast-path wrote each synced row with its own t2/update!.
Replace with one batched CASE update per chunk (status/status_changed_at
constant, file_path/content_hash per-row CASE), keyed by the RSO :id the synced
plan already carries — no extra select. Fewer round-trips on the fast path.

* Fold import metadata into the insert (one batched insert per row)

Import previously wrote each RemoteSyncObject row twice: sync-objects! inserted
status/name, then record-exported-metadata! updated file_path/content_hash.
Compute the metadata before the insert and merge it into the insert maps
(merge-content-metadata), so the whole import reconcile is one delete-all + one
batched insert (full import) / one delete + one insert (incremental). Drops the
follow-up update pass and leaves record-exported-metadata! export-only.

* Make full export one RSO write per row

record-exported-metadata! now reconciles the whole table in one write per row:
one select of all rows, then chunked updates that set status for every row in
the chunk and file_path/content_hash for the exported ones (CASE with ELSE
keep-existing). full-export! drops the separate blanket status update. Each row
is written once; removed/delete rows just get their status reset.

* Chunk the import pipeline and export IN clauses

Bound the work that could exceed DB param limits / memory on large syncs:
- insert-with-metadata! processes the import in chunks of content-hash-batch-size
  (extract + hash + enrich + insert per chunk, under one shared serdes cache),
  so insert/IN params and the maps held at once stay bounded — replaces the
  whole-table merge + unbounded insert. Used by full and incremental import.
- store-and-record! chunks each model's extract-query IN (restores bounding the
  refactor had dropped from record-content-hashes!).
Removes the now-unused sync-objects!.

* Flatten store-and-record! into one transduction pipeline

Replace the nested mapcat>mapcat>map with a single (into [] (comp ...) targets):
expand each model into bounded [model-type id-chunk] work items, then stream
each chunk's extract-query through a serialize helper via an eduction — so
extract-one still runs while the ResultSet is open, with no intermediate
per-chunk sequence realized.

* Flatten import-content-metadata to a single transduction

Mirror store-and-record!: pull the per-instance work into a serialize helper and
stream each model's extract-query through it via an eduction instead of an inner
(into [] (keep ...)), so the whole function is one transduction over the model
groups with no intermediate per-model sequence realized. extract-one still runs
inside the extract-query reduction (ResultSet open).

* Fix events_test references to the removed sync-objects!

The export/import refactor removed sync-objects!, but events_test still called it
(2-arg form) to set up a synced baseline before firing move-out events, failing
clj-kondo (unresolved var) and the enterprise test load. Replace with a local
mark-synced! helper that does the same via spec/sync-all-entities!. Also refresh
two stale comments referencing removed functions.

* Use empty? instead of not

* kick ci

* Remove no-op (filter identity) from export root-targets

query-export-roots is consumed by mapcat (so nil returns contribute nothing) and
the [model-type id] tuples it produces are never nil, so the filter could never
remove anything. (PR review #76098)

* export-targets returns {} instead of nil

Removes a nil-as-empty signal: export-targets always returns a map, so callers
test emptiness (full-export! already uses empty?; extract-entities-for-export
uses not-empty) rather than nil. (PR review #76098)

* refactor

* Refactor!

* commment

* Stream full-export serialization; fix disabled-files deref

- store-and-record! feeds write-files! a lazy tee'd eduction so the full
  serialized content is never held at once; only the lightweight per-entity
  entries accumulate (GHY-3933 / PR review #11).
- Fix export!: pass @disabled-files (was the raw delay) to export-incremental!,
  which reduces it via into.
- Fix resolve-status: return "synced" (was "synched").

* Stream the incremental export in two passes (bound memory)

The incremental plan used to serialize every dirty entity and hold all their YAML
in :upserts. Split it so the dirty set's content is never all in memory:

- Pass 1 (incremental-plan / incremental-updates-for-row / dep-writes): validate
  the batch is syncable and compute each write's target path — using the new
  source/entity->path, which renders no YAML. Produces a content-free plan of
  {:writes [{:id :model_type :model_id :file_path}] :delete-paths :removed-ids}.
- Pass 2 (export-incremental!): stream-re-serialize each write's content (via
  source/entity->content), using the pass-1 path, and feed it lazily to
  apply-changes!; tee the per-row synced metadata. One entity's content is live
  at a time.

stream-extract is a single comp'd eduction over the model groups (not a nested
eduction over the reduce-only extract-query) so it survives reduce- or
seq-consumption. entity->file-spec is now path+content composed.

* Batch the incremental pass-1 extraction (one query per model, not per row)

incremental-updates-for-row used to extract its entity itself, so incremental-plan
did one DB read per dirty row. Move extraction up into incremental-plan: batch-
extract the create/update rows on entity-id models via stream-extract (one query
per model/chunk), computing each row's path + existing-repo-file info once, then
run incremental-updates-for-row as a pure decision over the precomputed info.

removed/delete and non-entity-id rows need no extraction; a create/update row
whose entity is gone gets no info and is unsyncable; an extraction error sends the
whole batch to a full export (which self-heals). Paths are still computed with the
shared storage context (rows before deps) so dedup stays consistent.

* Simplify stream-extract: one key->row lookup, no tuple threading

Compute the [model-type model-id]->row lookup once instead of threading a per-model
id->row through the work-item tuple. Same two-mapcat structure (which keeps the
reduce-only extract-query on the reduce path); just less to read.

* Full export drops tracking rows for entity-id entities that left the set

Reconcile the removed-row handling between the two export paths. The incremental
path deletes the RemoteSyncObject row for a removed/delete entity; full export
left it as a synced row pointing at a file the wholesale re-serialize had already
dropped. Full export now deletes those rows too — but only for entity-id entities
that genuinely left (removed/delete status AND not in this export). Path/hybrid
removed rows (which can't go incremental) and removed rows whose entity is still
exported are still kept and reconciled to synced, as before.

* remove unnecessary function

* Rework export onto a streaming git commit-builder + chunk model

Reshape the export path around two ideas the reviewer asked for: an incremental
git commit API, and a uniform chunk-based extract pipeline shared by full and
incremental export.

Git protocol: add a stateful CommitBuilder (open-commit / stage-upsert! /
stage-delete! / finish-commit! / abort-commit!). The caller stages one file at a
time and the blob is inserted immediately, so the writer never receives or holds a
whole collection — streaming is structural, not a fragile single-pass contract.
write-files!/apply-changes! are kept, re-expressed on top of the builder. All
SourceSnapshot implementers (git, mocks, read-only views) implement it.

Export core: a chunk is [model-name rows<=500]; ->chunks (pure) groups+partitions
and extract-chunk runs one query per chunk. full-export! and incremental-export!
share stage-and-commit!, which doseq-stages each chunk's entities and accumulates
the synced metadata locally. After the push, set-version! + the RSO writes
(mark-synced! / record-exported-metadata! / removed deletes) run in one
transaction so the version can't advance past stale RSO state. Incremental still
validates first (incremental-plan) and aborts to a full export when unsyncable.

Supersedes the store-and-record! helper and the reduce-once write hardening (now
moot — no collection is passed to git).

* Tighten docstrings on the reworked export functions

One-line intent + args/return; move the how (batched CASE, select-all, streaming,
dedup, validation rules) into body comments where it matters. Fix the open-commit
docstring that still referenced the old :replace-dirs option.

* Batch enable-snippet-tracking! into one insert

Was one t2/insert! per snippets-namespace collection and per snippet (N+M
inserts); build the rows and do a single batched insert instead.

* Fix snippets export test for the removed-row reconciliation

A full export now drops the tracking row for an entity-id entity that left the
synced set (archived snippet, 'delete' status, not in export-targets) instead of
marking it synced — matching the incremental path. Update the assertion to expect
the row to be deleted.

* BEtter names

* Consistent capped chunking + shared path-free? predicate

- ->sized-chunks (group by model + cap at content-hash-batch-size) is now used by
  stage-and-commit!, incremental-plan, and dep-writes, so every extract-chunk gets
  a bounded chunk (the ≤500 cap was missing from the first two).
- dep-writes validates one chunk at a time and short-circuits on the first
  colliding chunk, instead of realizing all decisions then scanning.
- path-free? is a pure predicate over the {:eid :file-exists? :file-eid} info,
  shared by dep-chunk-writes (via repo-file-info) and incremental-updates-for-row's
  create/rename branches — one collision check instead of three copies.

* docs and names

* Calculate the incremental plan one chunk at a time

incremental-export-plan now folds the create/update rows over ->sized-chunks
(chunk->updates per chunk), short-circuiting on the first unsyncable chunk like
dep-writes and stage-and-commit! do — instead of building an id->info map for all
rows and then deciding in a separate pass. Rows that need no entity (removed/delete,
non-entity-id, bad status) are decided up front. A gone entity is detected by the
found-vs-requested count; an extraction error falls back to a full export. Reuses
repo-file-info + path-free?.

* lots of doc improvements, some refactoring

* More renames

* Row is now map

* Chunk-as-map, deps return plans, and a pure plan combiner

- A chunk is {:model_type :rows}; export-closure/untracked deps speak
  {:model_type :model_id} maps throughout.
- dep validation returns plan fragments ({:writes [...]}) merged like every other
  fragment; row/chunk/dependency all produce plans combined by one function.
- Split merge-incremental-export-plans into a pure combiner (safe for direct
  calls, e.g. the deps merge) and a -reducer wrapper that adds the reduced
  short-circuit at fold sites — fixing a bug where the direct deps merge returned
  a Reduced and broke the fall-back path.
- Move the chunk-plan try/catch into chunk->plan where the throwing happens.

* REfactor

* Nice!

* Go!

* Guard no-source export at the API call; add exportable-entity-chunks

- async-export! refuses up front (HTTP 400) when remote sync isn't configured,
  instead of a nil-snapshot check inside the async task (which never fired) or a
  cryptic clone error. export! no longer guards its snapshot.
- spec/exportable-entity-chunks: exportable-entities in chunk form.

* Decompose stage-writes into stage-write/chunk-stage-writes

Split per-entity staging (stage-write) and per-chunk staging (chunk-stage-writes)
out of stage-writes; synced metadata flows out as return values.

* Go for it!

* Self-contained exportable-chunks; tighten docstrings

- exportable-chunks reads its own export set and full-export!/delete-departed-entities!
  flow over chunks; delete-departed derives the exported set from the chunk rows.
- Tighten prose-heavy docstrings to intent + Returns shape (content-metadata trio,
  untracked-content-deps, incremental-export-plan, dep plan, row->content-hash).

* Refactor!

* Go for it!

* Retire the legacy write API (write-files!/apply-changes!, store!)

The CommitBuilder (open-commit → replace-all!/stage-upsert!/stage-delete! →
finish-commit!) is now the sole SourceSnapshot write path:

- merge-and-store! (the export-merged! path) writes via the commit builder
  (replace-all-files!) instead of write-files!.
- Removed the dead store! and its tests/mocks.
- Removed write-files! and apply-changes! entirely — protocol methods, git
  impls + helpers (and the now-unused with-staged), and the read-only stubs.
- Test fixtures (git_test, test_helpers_test) seed via local commit-builder
  helpers, so they still exercise the same wholesale/incremental write paths.

* Untrack content_hash_bench.clj (committed by mistake)

* cljfmt: re-align test helper call sites

* Review fixes: drop unused fn, log skipped serialization, document commit lifecycle

- Remove the unused spec/exportable-entity-chunks.
- Log a warning when an entity fails to serialize for its content hash (was a
  silent catch in import-content-metadata).
- Document the CommitBuilder resource/lifecycle contract (caller must finish/abort).

* Align RSO txn ordering (delete then update); use u/index-by in merge-content-metadata

- incremental-export! now deletes departed rows before updating RSO metadata,
  matching full-export!'s order (the ops are disjoint within the txn, so this is
  a consistency change, not a behavior change).
- merge-content-metadata uses u/index-by instead of an into/map/juxt build.

* Inline expand-nested-collections

* Bgrabow/ghy 3933 suggestions (#76640)

PR feedback

---------

Co-authored-by: Ben Grabow <ben.grabow@metabase.com>
2026-06-30 15:15:36 +00:00
Alexander Polyankin
f1375bb764 Make bigquery throw when there is a next page that we cannot fetch (#76709)
bigquery page fix
2026-06-30 08:38:36 -04:00
Romeo Van Snick
6269865946 Make all API client request middleware declared statically (#75779)
* Move OnBeforeRequest* types into the api client middleware module

The `OnBeforeRequestHandler` / `OnBeforeRequestHandlerConfig` types lived in
`metabase/plugins/oss/api` but describe the request-manipulation middleware,
which lives under `metabase/api/client`. Relocate the type definitions to
`metabase/api/client/middleware` and re-export them from the `metabase/api/client`
barrel, so the middleware contract is fully contained in its own module. Pure
move plus import updates; no behavior change.

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

* Make the request middleware a single static plugin-slot list

The request-manipulation pipeline was split across two mechanisms: a hardcoded
list of `PLUGIN_*` slots in `middleware.ts`, plus a dynamic
`api.beforeRequestHandlers` array that three features pushed onto at runtime
(the embed-preview rewrite, the React-SDK embed referrer, and the iframe embed
referrer). That made the full set of handlers — and their order — impossible to
see in one place.

Promote the three dynamic handlers to plugin slots and drop the dynamic array,
so `middleware.ts` lists the entire ordered pipeline statically:

- `PLUGIN_API.onBeforeRequestHandlers.rewriteEmbedPreviewUrl`
- `PLUGIN_EMBEDDING_SDK.onBeforeRequestHandlers.reactSdkEmbedReferrer`
- `PLUGIN_EMBEDDING_IFRAME_SDK.onBeforeRequestHandlers.embedReferrer` (new
  `onBeforeRequestHandlers` section on that plugin)

The owning features now install their handler into the slot instead of pushing.
`ApiClient` loses its `beforeRequestHandlers` field; `apiRequestManipulationMiddleware`
reads the static list and delegates to an exported `runBeforeRequestHandlers`
(kept pure so the merge/ordering semantics stay unit-testable). Slot resets on
plugin `reinitialize` now cover these handlers too, and the dead
`overrideRequestsForStaticEmbeds` slot is removed.

Because the slot positions are fixed, the public/static preview-rewrite no
longer depends on render-vs-effect registration timing.

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

* Move the embedded-app header to a plugin handler

`client.ts` imported `isEmbeddingSdk` from `metabase/embedding-sdk/config` to
decide whether to send the `X-Metabase-Embedded` header — the last SDK import in
the api HTTP client. Move that logic into a `PLUGIN_API.onBeforeRequestHandlers`
slot (`setEmbeddedHeader`) whose default implementation does the
`isWithinIframe() && !isEmbeddingSdk()` check, and add it to the static pipeline
in `middleware.ts`. The plugin layer may import SDK config; `metabase/api/client`
no longer does.

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

* Route param-remapping endpoints through the embed middleware

`api/card.ts` and `api/dashboard.ts` built the parameter-value remapping URL via
`PLUGIN_API.getRemapped*Url` — the last reason these endpoint files imported
`metabase/plugins`. Switch them to the same `:tag` template + params convention
the sibling `values`/`search` endpoints already use, so the existing embed
override middleware (which already has remapping transforms) does the rewrite.

Embed requests pass `entityIdentifier` instead of the real id, mirroring
`parameters/actions` — non-embed fills `:cardId`/`:dashId`, embed swaps to
`:entityIdentifier` and the guest handler injects the token. `substituteUrlTags`
encodes tag values, matching the getter's prior `encodeURIComponent`.

NOTE: verify the embedding e2e suite (guest/public/static parameter remapping)
before merge — this changes outward-facing embed request URLs and is not covered
by unit tests.

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

* Remove the now-unused remapping-URL plugin getters

With the card/dashboard endpoints routed through the embed override middleware,
nothing reads `PLUGIN_API.getRemappedCardParameterValueUrl` /
`getRemappedDashboardParameterValueUrl` anymore. Drop the getters from the
plugin default and delete `setupRemappingUrls` (and its calls in the guest /
public-static embed setup), which only existed to override them.

`metabase/api/card.ts` and `metabase/api/dashboard.ts` no longer import
`metabase/plugins`.

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

* Move embedding auth/client request headers off the api client

The api client carried embedding-only request state (apiKey, sessionToken,
requestClient) and emitted the embedding request headers (X-Api-Key /
X-Metabase-Session / X-Metabase-Client / -Version / -Embedded-Preview). Move
these off the generic client into embedding request-header plugin handlers built
as closure factories: setApiKeyHeader / setSessionTokenHeader installed onto the
setEmbeddingRequestAuthHeaders slot as the active auth strategy, and
setRequestClientHeaders installed onto its own slot per embed mode. The embedding
setup sites install the handlers they need, each closing over its value, so no
embedding state or header logic remains in metabase/api and there is no shared
mutable module state.

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

* Send the SSO session token on the initial embed requests

In the SSO/SAML/JWT path the session-token header was only installed by the
request-pipeline refresh handler, which runs after the auth-header step, so the
user/settings requests fired during init went out without X-Metabase-Session
(the bootstrap path already installed it eagerly). Install the strategy eagerly
right after the initial session refresh, sharing one refresh-and-install helper
with the pipeline handler.

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

* Simplify RequestClientInfo type

* Split the embed-preview header off the request-client handler

X-Metabase-Embedded-Preview signals preview mode (IFRAMED_IN_SELF), which is
orthogonal to which client is embedding. It was riding inside
setRequestClientHeaders, where the IFRAMED_IN_SELF branch was unreachable from
the static and full-app install sites (they skip installing the handler in
preview). Move it to its own setEmbedPreviewHeader slot, installed only by the
public and SDK flows so static/full-app previews keep not emitting it.

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

* Set the SSO session header from the refresh handler itself

getOrRefreshSessionHandler re-installed setEmbeddingRequestAuthHeaders with the
fresh token, but that was too late for the triggering request: the handler list
is snapshotted per request, and setEmbeddingRequestAuthHeaders runs earlier in
the pipeline, so the request that detected expiry still went out with the stale
token. Have the handler return the session header itself instead — it runs after
the static auth-header slot, so the refreshed token applies to the same request
(mirroring getOrRefreshGuestSessionHandler).

Drop the three dynamic setSessionTokenHeader installs (SSO + bootstrap) in favour
of the returning handler; keep setSessionTokenHeader for MCP's static token via a
shared sessionTokenHeaders helper. Widen the getOrRefreshSessionHandler slot type
to allow returning a header config.

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

* Type request handlers with OnBeforeRequestHandler

Replace the repeated inline `async (): Promise<Partial<OnBeforeRequestHandlerConfig> | void>`
annotations (and the local EmbeddingRequestHandler alias) with the existing
OnBeforeRequestHandler type. The plugin no-op defaults collapse to a shared
`noop` handler, and the embedding-request-auth factories and the two embed-
referrer handlers gain their parameter and return types from the annotation.

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

* Skip null querystring params, not just undefined

appendQueryParameters only skipped undefined, so a param explicitly set to
null was serialized as the literal string "null" (e.g. ?cursor=null). Skip
nullish values so an absent param drops out of the querystring entirely.

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

* Drop the cardId/entityIdentifier switch into the embed override

The param-value/remapping endpoints chose between cardId/dashId and
entityIdentifier at six call sites to keep the unused id out of the request.
Pass both unconditionally instead: the embed override now drops the real
cardId/dashId from the params bag when it rewrites the path to
:entityIdentifier, so the real id never leaks to an embed endpoint, and a null
entityIdentifier falls out of the normal-app querystring via the nullish skip.

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

* Settle the JWT popover test's auth flow to stop a cross-test leak

The 'usage problem popover' test rendered the auth flow but never awaited it,
so its user/current + session/properties requests were still in flight when the
next test (the SSO subpath test) ran, tripping the strict unmocked-routes
afterEach. Await the user request after the synchronous assertion so the flow
settles within the test.

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

* Omit null entityIdentifier from parameter-value requests

The parameter-value dropdowns key their cache on stableStringify(request).
Always including entityIdentifier (null when not embedding) changed that key
from {dashId, paramId} to {dashId, entityIdentifier: null, paramId} — stable-
Stringify keeps null — so every cache lookup missed and the dropdown rendered
empty (caught by the PublicOrEmbeddedDashboardView Loki stories). Only include
entityIdentifier when it exists; cardId/dashId stay unconditional (the embed
override still strips them). Add actions tests pinning the cache-key shape.

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

* Use camelCase ids in the remapped-parameter request types

The getRemapped{Card,Dashboard}ParameterValue requests used snake_case
(card_id/dashboard_id/parameter_id) while the url tags and the embed override
use camelCase (:cardId/:dashId/:paramId), so each query function had to remap
the keys. Align the request types (and their callers) to camelCase like the
sibling values/search endpoints, so the query is a plain passthrough. Rewriting
the url template to snake_case instead would have pushed mixed casing into the
shared override (its embed-url outputs and the cardId/dashId strip), so the
request types are the right place to converge.

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-06-30 19:03:11 +10:00
Oleh K
aa2e7326e0 Migrate bubble Radio usages to pills and remove the deprecated Radio (#76668)
* Migrate bubble Radio usages off the deprecated component

Replace the two `bubble`-variant usages of the deprecated
`metabase/common/components/Radio`:

- EntityViewSwitch (Groups/Databases view switch) -> Mantine `Tabs`
  `variant="pills"`. Drops the accent7 color scheme for the standard brand.
- FormFieldEditor "Field type" -> a horizontal Mantine `Radio.Group`. It's a
  single-select choice, so a radio group fits better than tabs.

Centralize the pills active style in the shared `metabase/ui` Tabs so
`variant="pills"` renders our soft "selected" pill out of the box.

Update the EntityViewSwitch e2e selectors (label/radio -> tab). The Field type
tests are unchanged: Mantine `Radio.Group` keeps the radio/radiogroup roles.

Part of GDGT-2588 (PR 3 of 3).

* Replace data studio hand-rolled tabs with Mantine pill tabs

PaneHeaderTabs (the data-studio entity-header navigation) was a hand-rolled
Group of Button-as-Link pills. Render it with the shared Mantine `Tabs`
`variant="pills"` instead, deriving the active tab from the existing
`isSelected` logic. Tabs keep real `<Link>` anchors (cmd/middle-click, href)
via a small cast, since Mantine's `Tabs.Tab` isn't polymorphic.

Drops the unused `withBackground` prop and refines the shared pills styling.

* Remove the deprecated common/components/Radio component

All usages have been migrated to metabase/ui (Radio, Tabs, SegmentedControl)
across the normal/underlined/bubble variants, so the deprecated component is
now unused. Delete it along with its stories and spec.

* Document pills variant in Tabs stories and docs

Add Pills (and Pills + icons) stories plus a variant control, and document the
pills variant and the listBorder prop in Tabs.mdx.

* Fix tests for the Tabs/Radio migration

- TransformHeader and JobRunListPage specs: PaneHeaderTabs are now role="tab",
  not "link".
- FormFieldEditor: give the "Field type" Radio.Group a real label (via the
  Subtitle) so the radiogroup has an accessible name again — Mantine doesn't
  name it from a sibling label + aria-label. Fixes the actions e2e specs that
  query the radiogroup by name, and add a positive assertion for it.

* Simplify comment
2026-06-30 10:14:41 +02:00
Mahatthana (Kelvin) Nomsawadi
b58a926cea feat(sdk): migrate analytics events to simple_event schema (#76337)
* feat: convert SDK analytics events to use trackSimpleEvent

Replace the custom Snowplow "sdk" tracker approach with trackSimpleEvent
so SDK analytics go through both Snowplow (simple_event schema) and
Metaplow automatically — no custom schema registration or Metaplow
migration needed.

Two events via trackSimpleEvent:
- embedding_sdk_initialized: fires once per JS load from ComponentProvider
- embedding_sdk_component_rendered: fires per component mount via
  triggered_from (component name) and event_detail (JSON with sdk_version,
  auth_method, locale_used, and component-specific properties)

Removes: snowplow.ts (custom tracker), sdkTrackerReady Redux state
(no longer needed — trackSimpleEvent needs no async init). Dedup for
component events switches to instance-based (useRef + nextInstanceId)
from entity-based, matching the reference branch design.

setSdkTrackingContext() is called synchronously during ComponentProvider
render so child component effects can read auth_method on the first commit
without needing a Redux gate.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: pass live store getState to Snowplow instance-context plugin

getSdkStore() calls configureStore() each invocation — no memoization —
so the plugin's lazy getSdkStore().getState() was always reading from a
fresh empty store, leaving analytics-uuid, version, and token_features
undefined on every event. Fix: pass store.getState from useSdkStore()
(the actual ComponentProvider store) to initSdkTracker, which threads it
into the plugin closure so it reads the live state at event-send time.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VagN42CYBMhd1MHSDhbxTJ

* test: guard tracker-before-event ordering with an integration test

Uses real tracker.ts, snowplow.ts, component-events.ts (only
@snowplow/browser-tracker mocked) to assert that newTracker is called
before the first trackSelfDescribingEvent across a parent+child tree.

Falsifiability verified: reverting initSdkTracker to useEffect causes
the assertion to fail (invocationCallOrder 9 > 6), confirming the test
is exercising real render/effect ordering, not just mocked call counts.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01VagN42CYBMhd1MHSDhbxTJ

* fix: address review findings for simple_event schema migration

- Cache sdkMetaplowEnabled at init instead of storing the full store ref
- Unexport trackSdkEvent; only trackSdkSimpleEvent is public
- Move SdkComponentName back to component-events.ts (SDK-only type)
- Remove triggered_from from SDK event types; component goes in event_detail
- Nest event_detail as { component, properties, global } envelope
- Restore field order auth_method/sdk_version/locale_used in global block
- Add sdkTrackerReady Redux flag; gates per-mount events until tracker is up
- Initialize SDK Snowplow tracker synchronously to prevent first-event drop
- Read metaplow gate from Redux store, not Settings singleton

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_018HWtepijYZu4qkYB3XAgwT

* fix: tighten trackSdkSimpleEvent to EmbeddingSdkEvent union type

Narrows the parameter from the open SimpleEventSchema to the closed
EmbeddingSdkEvent union so only known SDK events are accepted at
call sites. Updates two Metaplow gate tests to supply the now-required
event_detail field and runs Prettier on format-checked files.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Jux5AAEEsYVNUNSUEK8zBF

* refactor: remove implementation-detail tests and unnecessary diffs

- Delete reducer.unit.spec.ts (Redux plumbing; behavior covered by events
  and tracker specs)
- Delete ComponentProvider test 1 (call arity check); update tests 2 & 3
  to use toHaveBeenCalledWith instead of magic index access
- Extract parseEventDetail/findEventByComponent helpers in e2e spec to
  eliminate repeated try-catch JSON.parse blocks
- Restore setSdkTrackerReady position in reducer.ts to append after
  setInitialDashboardTabId (matches master, removes unnecessary diff)
- Restore JSDoc on sdkTrackerReady in types.ts

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Jux5AAEEsYVNUNSUEK8zBF

* refactor: simplify event_detail assertions in events spec

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Jux5AAEEsYVNUNSUEK8zBF

* refactor: move SDK event types and schema URI out of metabase-types

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Jux5AAEEsYVNUNSUEK8zBF

* fix: pass metaplow-url and analytics-uuid explicitly to trackMetaplowEvent

Convert trackMetaplowEvent to object-style signature with metaplowUrl and
analyticsUuid params that default to Settings.get. The SDK caches both
values from the Redux store at initSdkTracker time and passes them
explicitly, bypassing the Settings singleton which is absent in a
customer's page.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Jux5AAEEsYVNUNSUEK8zBF

* refactor: convert all metaplow.ts functions to object-style params

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01Jux5AAEEsYVNUNSUEK8zBF

* refactor: revert core app metaplow to positional params

Settings.setAll already runs in SDK auth flow, so trackMetaplowEvent and
trackMetaplowPageView can read metaplow-url and analytics-uuid via Settings.get
directly. No need to change the core app function signatures for SDK's sake.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01NQTnAAmpqsWDQqNymVmnck

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-30 06:43:00 +01:00
Nick Fitzpatrick
c9f621e291 Add tables and snippets to useSetCollection (#76670)
* Add tables and snippets to useSetCollection

* remove table from Movable Models
2026-06-30 11:09:18 +05:30
Romeo Van Snick
fa01d45f28 Move content-translation facade out of metabase/i18n (#76140)
* Move content-translation facade out of metabase/i18n

* Fix missed i18n->content-translation references and import order
2026-06-30 15:38:22 +10:00
Egor Grushin
4193c0298d Gdgt 2589 replace deprecated select component (#76651)
* GDGT-2589 initial migration

* GDGT-2589 fix get json

* GDGT-2589 fix get json

* GDGT-2589 fix logs

* GDGT-2589 get rid of formselect from /common/

* GDGT-2589 fix size of new action form widget select

* GDGT-2589 fix test

* GDGT-2589 fix comboboxWidths

* GDGT-2589 make ClickMappingsTargetWithoutSource to look like master's version

* GDGT-2589 make ClickMappingsTargetWithoutSource to look like master's version

* GDGT-2589 update static embed

* GDGT-2589 update xray schema selector

* GDGT-2589 update xray schema tests

* GDGT-2589 move menu to combobox

* GDGT-2589 fix tests

* GDGT-2589 fix assertions

* GDGT-2589 fix e2e tests

* GDGT-2589 fixed AI slope

* GDGT-2589 fixed leftovers tests
2026-06-30 06:32:52 +01:00
github-automation-metabase
4fd6ffc3a4 Auto-update documentation for master (#76704)
Update generated docs (master)

Co-authored-by: github-actions <github-actions@github.com>
2026-06-29 23:05:27 -04:00
Nemanja Glumac
fd95704a9c Report backend & driver test failures to ci-conductor (#76439)
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-30 00:25:49 +02:00
lbrdnk
aff92695a5 Make more entities discoverable through mcp search (#76616) 2026-06-29 23:04:56 +02:00
Alexander Polyankin
6aa80c5a79 Granular permissions for workspaces (#76698) 2026-06-29 16:30:12 -04:00
Alexander Polyankin
c446d690c4 Fix setting writable and admin db details (#76696) 2026-06-29 16:01:12 -04:00
Nemanja Glumac
b114036f85 Stop running auto-stress-tests on any label (#76638)
* Gate auto-stress-test to only the flaky-test-fix label event
2026-06-29 20:48:59 +02:00
Braden Shepherdson
0161c22652 [PDFs] Resolve large results in temp files; surface "too large" errors (#76605)
Fixes UXW-4614.

There are effectively three "sizes" of query results for rendering
dashboard subscriptions. The PDF renderer had so far only supported the
smallest of them ("fits in memory").

The QP always *streams* query results, but the subscriptions sink
collects them in memory up to a threshold, then spills them to a temp
file and streams the rest there.

If the temp files get too large, we don't risk an OOM by reading them and
trying to render the dashcard. The files are discarded and the card's
results are marked `:too-large? true`.

This PR makes the PDF renderer correctly read from temp files, and
properly surfaces a "results too large" message just like the FE if the
results are too big to render in one chart.
2026-06-29 14:37:44 -04:00
Alexander Polyankin
fe80ebe382 Perms graph reduce (#76678) 2026-06-29 14:33:39 -04:00
Braden Shepherdson
a926f047be Visualizer: Preserve the results_timezone if the source has one (#76446)
Fixes UXW-4040.

The timezone being dropped caused it to default to UTC, causing the
bug. With the `results_timezone` preserved the correct timezone is used
to render the x-axis and tooltip labels, achieving correct results.
2026-06-29 14:11:19 -04:00
Maz Ameli
b098b29d46 Restyle the user-joined invite email with the modern card template (#75452)
Migrate the "{user} accepted their Metabase invite" admin notification
email from the legacy _header/_footer layout to the newer card-style
template (_dashsub_alert_header) already used by the new-device login
and transform-failure emails. Updates the sender to build the nested
context map the new template expects.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-29 18:02:38 +00:00
technomancy
64a6e18e21 Make Snowflake data loaded checks look at row count. (#76647)
* Make Snowflake data loaded checks look at row count.

We have some unidentified process that destroys the test-data dataset
and causes failures such as this:

https://github.com/metabase/metabase/actions/runs/28206004397/job/83561786972#step:5:381

Sometimes the database exists but the tables have double or triple the
expected number of rows.

First change: refuse to destroy the test-data database. This should
just never happen. If this ends up throwing, it should allow us to
identify where the deletions are coming from. (Unless the culprit is
someone calling DROP DATABASE directly.) Of course, we really should
be blocking *all* deletions of static datasets, but this is by far the
most commonly-used, and we don't have a good predicate for identifying
static datasets anyway.

Second change: don't consider a dataset loaded if it's been
double-loaded or triple-loaded. Previously we would just look at
whether the dataset's database existed and ignore the tables inside
it, but now we'll be able to see when it's been double-loaded and
treat this the same as if it had not been created at all.

Third change: when creating a database, ensure it gets dropped first
before creating. Without this, the previous change would just cause
the datasets to get loaded increasingly many times. This actually
reverts a change made previously in #74464, but we have a lot more
data now about what's happening, and making create-db into a no-op
when it already exists has turned out to be counterproductive because
of the double-loading issue.

* Remove parallel from database-local-settings-test

This fails in CI sometimes with the following error:

    clojure.lang.ExceptionInfo: Error rolling back after previous error: (conn=362) Deadlock found when trying to get lock; try restarting transaction

This indicates it is probably not safe to do in parallel with other tests.
2026-06-29 10:57:38 -07:00
github-automation-metabase
4fe4c864d6 Auto-update documentation for master (#76636)
Update generated docs (master)

Co-authored-by: github-actions <github-actions@github.com>
2026-06-29 12:23:01 -04:00
Oleh K
8f5eb11fba refactor: Migrate text and syntax tokens (#76508)
* GDGT-2533 Migrate text and syntax tokens

Sweep all consumer references from the legacy text/syntax tokens to their
new names (added in the foundation PR):

- text-tertiary -> text-disabled (and -inverse) — value shifts from solid
  orion to orion-alpha (intended recolor)
- text-hover -> text-brand-hover (value unchanged)
- syntax-parameters(-active) -> text-syntax-parameter(-active)
- saturated-{blue,green,yellow,red,purple} -> core-{blue,green,yellow,red,
  purple}-saturated (value unchanged)

`text-tertiary` and `text-hover` are also SDK public theme keys, so the
SDK_TO_MAIN_APP_COLORS_MAPPING right-hand sides gain the new internal names
as second targets and the public keys are left unchanged.

Per design review, the five saturated colors are renamed to
`core-{color}-saturated` palette primitives rather than `text-syntax-{role}`;
this PR adds those token definitions, removes the superseded text-syntax-*
ones, and keeps the legacy saturated-* definitions emitting until cleanup.
`text-secondary-opaque` is left untouched (open design question).

* Formatting

* Update Loki Snapshots

* Keep public SDK theme key text-tertiary in embedding examples/tests

text-tertiary is an embedder-facing SDK theme key (MetabaseColors), not an
internal token. The blanket sweep wrongly renamed it to the internal
text-disabled in three embedding spots that live outside the type-check
scope (e2e specs + the CLI scaffold snippet). Revert those to the public
text-tertiary; the SDK maps it internally via SDK_TO_MAIN_APP_COLORS_MAPPING.

---------

Co-authored-by: Metabase Automation <github-automation@metabase.com>
2026-06-29 16:36:18 +02:00
Anderson
14f1989888 Preserve dashboard table column settings for stale SQL question metadata (#76434)
* Fix dashcard table column settings merge

* Preserve dashcard-only table columns
2026-06-29 11:05:36 -03:00
Alexander Polyankin
49cc599892 Enable streaming results for app db queries with postgres (#76645) 2026-06-29 09:41:26 -04:00
Braden Shepherdson
3507005944 Move bshepherdson from QPlat to UX West on Github; remove edpaget (#76532) 2026-06-29 15:26:59 +02:00
Alexander Polyankin
bffea3f481 Simple shared image buffers for rendering (#76504) 2026-06-29 13:24:27 +00:00
Oleh K
f00423cbd5 Migrate underlined Radio usages to Mantine Tabs (#76535)
* Migrate underlined Radio usages to Mantine Tabs

Replace the `underlined`-variant usages of the deprecated
`metabase/common/components/Radio` with Mantine `Tabs` from `metabase/ui`:
AccountHeader, the admin PermissionsTabs, and the BaseChartSettings section
picker. Mantine's default tab styling already matches the old underlined look
(neutral list divider + brand active underline).

Add a thin `metabase/ui` Tabs wrapper (replacing the bare Mantine re-export)
with a typed `listBorder?: boolean` prop. When `false` it suppresses the tab
list's own divider (default variant only), so a full-width divider can instead
be drawn on a parent container — avoiding full-width hacks and absolute
positioning. The active tab's underline is unaffected.

Adopt that pattern everywhere the list divider is customized, and migrate the
tabs that previously hid the divider with one-off CSS to use it, deleting their
CSS modules:
- PeopleListingApp, TenantsListingApp, SourceReplacementModal (were
  `::before { display: none }`)
- AccountHeader and BaseChartSettings now draw the divider on a parent

Also tidy the permissions header layout (parent-drawn divider, toolbar back in
normal flow) and convert a leftover utility-class `div` to a `Box`.

Update BaseChartSettings tests from radio `toBeChecked()` assertions to tab
`aria-selected`.

Part of GDGT-2588 (PR 2 of 3).

* Update tests for radio -> tab structure

Fix tests that queried the migrated tab bars as radios:
- section picker (Scalar, viz-charts e2e): role="radio" -> "tab",
  toBeChecked() -> aria-selected
- permissions tabs (CollectionPermissionsPage, admin-permissions e2e,
  command-palette e2e, transforms e2e): role="radio"/"radiogroup" and
  label-based selectors -> role="tab"

* Fix data-permissions e2e for radio -> tab structure

The "data permissions > warns about leaving with unsaved changes" test
selected the Collections permissions tab via a label selector; the tab is
now a role="tab" button.

* Reflect listBorder in Tabs stories; show focus outline

- Add the `listBorder` prop to the Tabs Storybook stories (boolean control +
  a dedicated "Without list border" story).
- Show a keyboard focus outline on tabs via `:focus-visible` instead of
  suppressing it, for accessibility.
2026-06-29 14:40:53 +02:00
Jeff Bruemmer
cd9114d94b docs - update SQL query example (#76665) 2026-06-29 08:25:40 -04:00
Jakub Chodorowicz
fdb82ddafc GDGT-2665: Wrong colors in dark mode in getTextColorForBackground function (#76592) 2026-06-29 14:24:54 +02:00
Benoit Vinay
67f4a32538 Fix for docs link (#76660)
Docs link fixed
2026-06-29 08:13:48 -04:00
Romeo Van Snick
f7ea88f395 Fix flaky usage-auditing e2e: anchor seed today in instance timezone (#76657)
Anchor usage-auditing seed today in instance timezone, not UTC
2026-06-29 20:26:03 +10:00
Fraser
3ddd960cbc Add dep-cruiser for creating module graph (#76598) 2026-06-29 22:24:46 +12:00
Ryan Laurie
c14043d64e ignore info status on master and release branches (#76641) 2026-06-29 11:30:23 +02:00
Nemanja Glumac
00050453bb Remove duplicated custom viz e2e helper (#76637) 2026-06-29 10:27:36 +02:00
Nicolò Pretto
1fc3f75419 chore: update codeowners file for embedding folders (#76614) 2026-06-29 09:51:36 +02:00
Nicolò Pretto
2d6f530c2b chore(storybook): exclude embedding sdk stories from main app storybook (#76610) 2026-06-29 09:35:31 +02:00
Nemanja Glumac
1290678ca7 Consolidate dashboard sidebar-switch repros (#76639)
Consolidate dashboard sidebar-switch repros, drop flaky 27356 block

Fold the parameterized -> non-parameterized sidebar-switch coverage into
the better-asserted 26230 sticky-positioning test by making its switch
target a param-less bookmarked dashboard, and remove the redundant,
weakly-asserting flaky block.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-29 06:13:15 +02:00
metabase-bot[bot]
2621d3d6b5 [chore] Update E2E test timings with recent data (#76652)
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-06-28 18:32:07 +00:00
Anderson
8a61a434ec Fix weekly line chart zero-fill across DST (#76376)
* Fix DST weekly zero fill in line charts

* Clean up DST zero-fill fix

* Address review comments
2026-06-27 21:01:57 +00:00
Romeo Van Snick
4f088825ca Remove @ts-nocheck from metabase-lib Question (#76506)
* Add transient creationType field to UnsavedCard type

* Type STRUCTURED_QUERY_TEMPLATE and allow null source-table

* Declare dev-only __lib_query/__lib_metadata/Lib window globals

* Accept null/undefined collection in collection type guards

* Remove @ts-nocheck from metabase-lib Question
2026-06-27 10:39:19 +10:00
Ben Grabow
fe593bdcf1 Copy old sample DB permissions to new sample DB on upgrade (#76561)
* Apply outgoing sample DB permissions to new sample DB
2026-06-26 18:17:30 -05:00
Chris Truter
6509e9818c HNSW benchmark utils + additional diagnostics (#75755) 2026-06-26 23:26:45 +02:00
Nemanja Glumac
ccfc78c97a Fix the flaky "trash" e2e test (#76634)
Open the navbar inside assertTrashSelectedInNavigationSidebar

Routes like a dashboard or question collapse the navbar, so the assertion
needs it open first. Two of the four call sites opened it manually while the
other two relied on the route not collapsing it. Fold the open into the
assertion helper so every call site is covered uniformly, and drop the now
redundant standalone calls. openNavigationSidebar is idempotent and self-heals
against a pending collapse, so calling it unconditionally is safe.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-26 23:25:01 +02:00
github-automation-metabase
362883f829 Auto-update documentation for master (#76566)
Update generated docs (master)

Co-authored-by: github-actions <github-actions@github.com>
2026-06-26 17:21:02 -04:00
Anderson
7be4c69df7 Fix input styles in chart visualization settings (#76308) 2026-06-26 18:09:44 -03:00
Nemanja Glumac
fca0657ffc Make openNavigationSidebar self-heal against a pending navbar collapse (#76631)
Navigating to a dashboard/question collapses the navbar, and that collapse
can land a beat after the page content renders. The previous helper took a
single non-retrying snapshot of the sidebar's open state, so it could read a
lingering-open navbar, skip the toggle click, then watch it collapse out from
under the be.visible assertion. Re-check after acting and re-open if it
collapsed, bounded to a few attempts.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-26 22:46:04 +02:00
Michael Eby
b0b035f0d0 docs: replace drill-through links (#76622)
* docs: replace drill-through links

* add relative links
2026-06-26 16:41:15 -04:00
Jeff Bruemmer
f941dc5964 docs - mcp edits (#76627) 2026-06-26 19:37:32 +00:00
Nemanja Glumac
f5015de183 Add ExplicitSize test for measuring a child that renders content after mount (#76559)
* Add ExplicitSize test for measuring a child that renders content after mount

PivotTable returns null on its first render, so ExplicitSize has nothing
to measure at mount. The regression was that once it rendered content,
its size was never recalculated without a resize event, leaving the
child stuck at null dimensions. Cover that contract directly at the unit
layer rather than through a flaky e2e viz-switch repro.

* Delete e2e repro for 51926

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-26 14:37:19 -03:00
Chris Truter
a6da15a4b1 feat(search): publish analytics for every search context (#75443) 2026-06-26 17:09:41 +00:00
Jeff Bruemmer
342b6fcb79 Update tool description for read_resource (#76609)
Co-authored-by: Chris Truter <chris@metabase.com>
2026-06-26 16:19:09 +00:00
Anderson
0d432c97f1 Fix dashboard question breadcrumb layout (#76345) 2026-06-26 12:01:09 -03:00
Nick Fitzpatrick
e533c75f9a Fix flaky Pro-cloud email settings e2e test (#76168)
The test forced email-configured?=true with a response-modifying intercept
on GET /api/session/properties; a reload aborting an in-flight refetch made
the callback throw "Socket closed before finished writing response". Set
email-smtp-host server-side instead so email-configured? is genuinely true.
2026-06-26 13:55:11 +02:00
Uladzimir Havenchyk
0368561d80 fix: do not fire custom viz track event when no necessary (#76562)
* fix: do not fire custom viz track event when no necessary

* do not put track event on plugin
2026-06-26 11:37:36 +00:00
Chris Truter
4fe7e43256 Metabot should verify it has the right entity using metadata (#76438) 2026-06-26 09:54:00 +00:00
Nicolò Pretto
7ce7ce034f chore(sdk): clean up old sdk files when starting build-hot (#76538)
* chore(sdk): clean the dist folder when starting build-hot

* chore(sdk): skip writing the hot-update files to disk
2026-06-26 11:46:21 +02:00
Stas Gavrylov
aa0fe0bdd6 GDGT-2676/2677: Migrate Dependency Diagnostics & Admin Tools UI source code under Monitor space (#76416)
* Add monitor dir in metabase-enterprise

* GDGT-2676: Migrate Dependency Diagnostics under Monitor space

* GDGT-2677: Migrate Admin -> Tools under Monitor space

* GDGT-2676: Fix paths

* GDGT-2676: Create separate high-level directories for migrated features

---------

Co-authored-by: Kamil Mielnik <kamil@kamilmielnik.com>
2026-06-26 12:01:05 +03:00
github-automation-metabase
fb78326577 Fix flaky data-studio bulk "edit attributes for db" e2e test (#76407)
After publishing, the active-path effect in useExpandedState auto-expands
the database. The test then clicked the (already-expanded, active) database
row, which only toggles expansion and collapses it again — so the schema
fetch never re-fired and the table rows disappeared, causing the getSchema
wait timeout and the missing [data-type="table"] failures.

Re-open Data Studio for a clean, collapsed tree before expanding the
database, matching the reliable pattern the sibling tests already use.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-26 15:34:04 +07:00
Mahatthana (Kelvin) Nomsawadi
720bb19d79 fix: bump dompurify, js-yaml, markdown-it; pin form-data (#76533)
* fix: bump dompurify, echarts, js-yaml, markdown-it; pin form-data

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EBYTJTjQQY4qo5EBCt5YwH

* fix: revert echarts bump; keep dompurify, js-yaml, markdown-it, form-data fixes

* fix: restore echarts 6.0.0 patch, remove 6.1.0 patch

* fix: regenerate release/bun.lock

* fix: pin form-data to 4.0.6 in root resolutions

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EBYTJTjQQY4qo5EBCt5YwH

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-26 08:13:06 +01:00
Mahatthana (Kelvin) Nomsawadi
6df842cd19 fix: pin opentelemetry-api to 1.62.0 (#76531)
* fix: pin opentelemetry-api to 1.62.0

* fix: move io.opentelemetry pin to correct alphabetical position in deps.edn

* fix: correct OTel comment attribution, fix stale sdk-testing comment, bump bigquery netty to 4.2.15

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EBYTJTjQQY4qo5EBCt5YwH

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-26 08:12:57 +01:00
Mahatthana (Kelvin) Nomsawadi
63919edccc fix: bump netty to 4.1.135.Final (athena) and 4.2.15.Final (hive-like) (#76530)
* fix: bump netty to 4.1.135.Final (athena) and 4.2.15.Final (hive-like)

* fix: correct stale version in athena netty comment

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EBYTJTjQQY4qo5EBCt5YwH

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-26 08:12:46 +01:00
Mahatthana (Kelvin) Nomsawadi
31034d8487 fix: bump jackson-databind to 2.21.4 (#76529)
* fix: bump jackson-databind to 2.21.4 and handlebars to 4.5.2

* fix: bypass handlebars 4.4+ root-classpath loader check

* fix: revert handlebars bump; keep only jackson-databind 2.21.4

* fix: bump jackson-core to 2.21.4 to match jackson-databind

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01EBYTJTjQQY4qo5EBCt5YwH

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-26 08:12:32 +01:00
technomancy
9de4197be8 Update bigquery remark test to put the remark at the end. (#76567)
This behavior was changed in 3617b2c (#76462) but the test was
overlooked because of quarantine.
2026-06-25 23:03:46 +00:00
Sloan Sparger
a7ff8b0c55 [Metabot] Do not render images in markdown (#76280)
* SEC-505 prevent Metabot frontend from loading external images

* lint fix
2026-06-25 17:49:11 -05:00
Eric Normand
a87f3e0def Make workspaces deletable from any database state (GHY-3954) (#76350)
* Make workspaces deletable from any database state (GHY-3954)

delete-workspace! only deprovisioned :provisioned rows, but the model-level
guard rejects any non-:unprovisioned row. A WorkspaceDatabase stuck in
:provisioning or :deprovisioning (crash mid-flight, or a failed warehouse
teardown) made the workspace permanently undeletable with a 409.

delete-workspace! now drives every active row through a best-effort,
delete-only teardown (force-teardown-for-delete!) that works from any state:
it reconstructs the iso schema/user names deterministically from the row id,
drops them idempotently, always clears app-DB TableRemapping rows so query
routing is never left dangling, and forces the row to :unprovisioned. When the
warehouse is unreachable the workspace is still deleted; the 200 response then
carries :orphaned_resources and a :message naming the inert schema/user left
behind and why.

Recovering a stuck row without deleting (startup reconciliation / admin
force-unstick) remains GHY-3550.

* Surface orphaned warehouse resources in logs and the delete UI

Log a per-row warning (with the exception) when warehouse teardown fails
during delete, plus a consolidated warning carrying the full human-readable
orphan summary.

On the frontend, type the delete response (DeleteWorkspaceResponse) and, when
the workspace was deleted but warehouse cleanup partly failed, show a warning
toast naming the leftover schema/user objects and why they couldn't be removed
— the response is otherwise silently discarded since delete returns 200.

* Gate workspace delete on pending databases with an ignore-pending flag

A database still :provisioning/:deprovisioning may have warehouse work in
flight, so delete-workspace! now refuses by default (409, :pending_databases
lists them) rather than tearing such rows down. The new ignore-pending? arg
(ignore-pending query param, default false) leaves those databases' warehouse
resources untouched and removes only their app-DB rows. :provisioned rows are
still torn down, and the orphaned-resources reporting for unreachable warehouses
is unchanged.

On the frontend, the delete modal fetches the workspace's databases, and when
any are pending it swaps in a warning that lists them by name and confirms with
ignore-pending=true.

* Mock get-workspace in WorkspaceItem delete-modal test

The delete modal now fetches the hydrated workspace when opened, so the
'opens the delete modal' test hit an unmocked GET /api/ee/workspace-manager/:id.
2026-06-25 17:05:54 -05:00
Anderson
cfa17c66be Fix MySQL utf8mb3 app DB Library root migration (#76540)
Fix MySQL utf8mb3 library root migration
2026-06-25 18:34:52 -03:00
technomancy
8c9d598724 Check dynamic dataset in do-with-dataset-definition/with-transform-cleanup (#76543)
Check dynamic dataset in do-with-dataset-definition/with-transform-cleanup!

Monitoring failures for bigquery/snowflake on master, we're seeing
these are still trying to do creation/deletion of datasets and
occasionally failing on bigquery and snowflake.

These are specific to the tests for transforms and actions.

Long term we want to make it so this can work reliably. Short term we
just need the tests to fail less when blocking releases and allow us
to unquarantine sooner.
2026-06-25 14:24:46 -07:00
Nemanja Glumac
c0965b27dc Run e2e "smart test selection" on PRs only (#76539) 2026-06-25 23:11:51 +02:00
Nemanja Glumac
a61f013de4 Consolidate metabot usage-auditing e2e flake fixes (#76490)
* Consolidate usage-auditing row-chart drill-through e2e flake fixes

clickRowChartBarForLabel coordinate-clicked the chart container at a blind
labelRect.right + 30 offset, which intermittently landed on empty SVG so the
drill-through never fired (cy.wait("@conversations") timed out) or a near-miss
drilled a neighboring group. Two things conspired: the page only waits for the
audit metadata so the chart's dataset query + render could still be in flight,
and row charts measure their size asynchronously (ExplicitSize, throttled) and
first render with zero-width bars — assertChartRendered passes in both states.

Anchor on assertChartRendered, then click the measured (non-zero-width) bar
whose vertical band contains the label's midpoint, asserting exactly one match.
Cypress re-resolves the element's center at click time and retries for
actionability, so the click can't miss.

selectUserFilter anchored on `url includes "user="`, a no-op after a
drill-through since the URL already carries the drilled user, so it didn't gate
on the filter actually switching. Anchor on the select's value instead,
mirroring selectDateFilter.

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

* Use graphics-symbol role query for row-chart bar drill

Swap the ad-hoc `[aria-roledescription="bar"]` attribute selector in
clickRowChartBarForLabel for the a11y query cy.findAllByRole("graphics-symbol"),
matching the conventions' preference for role queries over CSS attribute
selectors in spec files. Functionally equivalent — both resolve the same ECharts
row-chart bars within the scoped chart card.

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

* Give the chart-render assertion a budget for the ECharts mount

The usage-stats page waits only for the audit metadata before rendering; each of
its six charts then fires its own adhoc /api/dataset query and mounts ECharts
independently. getChartCard resolves as soon as the chart title paints (a
Skeleton placeholder), but the [data-testid="chart-container"] only mounts once
that card's data query returns. With all six mounting at once under CI CPU
contention, the container mount routinely overran Cypress's default 4s budget,
surfacing as "Unable to find an element by [data-testid=chart-container]".

Give the chart-container readiness assertion a 12s budget (CHART_RENDER_TIMEOUT)
so it waits out the ECharts mount instead of racing it. This hardens every chart
assertion in the spec, including the assertChartRendered anchor the drill-through
helpers rely on.

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-06-25 15:22:35 -05:00
Riley Thompson
a8f6bc947f Sync starburst and presto-jdbc column comments (#76440)
* sync trino and presto column comments

* starburst comment tests

* add presto test
2026-06-25 15:54:38 -04:00
Nathan Voxland
3c58b8226f Add UTF-8 BOM to CSV downloads (#76028) 2026-06-25 14:29:05 -05:00
Riley Thompson
37b72f94e4 Upgrade clickhouse jdbc driver to 0.9.8 (#73404)
* upgrade clickhouse to 0.9.8 and add relevant test

* fix test

* add boolean settings test

* format rows in test
2026-06-25 19:24:02 +00:00
Nathan Voxland
bd049b7d08 Throttle heavy log4j calls (#76482) 2026-06-25 13:40:06 -05:00
Riley Thompson
3617b2ce8b Put remarks at end of query instead of start (#76462)
* put remarks at end

* only keep fix for bigquery and starburst
2026-06-25 14:29:50 -04:00
technomancy
af705d639f Broaden the test disabling from #76502 (#76541)
Just missed a couple here.
2026-06-25 18:18:20 +00:00
Chris Truter
746a65d593 Support HNSW iterative-scan + cross-test each strategy (#75722) 2026-06-25 11:23:05 -04:00
Nick Fitzpatrick
0c145ac68b Searchable document content (#75841) 2026-06-25 09:44:23 -05:00
Eric Normand
a242d43788 Fix model filter dropdown lost on serdes sync (GHY-3946) (#76349)
* Fix model filter dropdown lost on serdes sync (GHY-3946)

A dashboard/model filter mapped to an MBQL model column rendered as a
text-search box instead of a value dropdown after the content was synced
via serdes (git sync).

Root cause: a model's result_metadata is serialized with overrides only
(display_name, semantic_type, ...); the structural :id that links each
column to its underlying Field is dropped on export and never restored on
import, because populate-result-metadata stores passed-in metadata
verbatim during deserialization. Without that link the column can't
resolve has_field_values, so the widget falls back to text search.

Fix: add a generic serdes load-finalize! lifecycle hook that runs after
every entity is loaded (when the referenced Tables/Fields are present),
and implement it for Card to re-derive an MBQL model's result_metadata
field links from its query while preserving the serialized overrides.
This keeps the serialized form unchanged (no :id in the YAML) and avoids
the load-ordering fragility of re-inferring at insert time.

* Drive model metadata restore through model-preserved-keys

Rework the Card load-finalize! to mirror the export: recompute the fresh
columns from the query, then overlay the serialized overrides using the
same lib/model-preserved-keys set (with this model's native flag) that the
export uses to decide what to keep. This replaces the opaque
infer-metadata-with-model-overrides call and removes the separate native
guard — native-ness now flows through model-preserved-keys, so native
models (whose infer-metadata yields nil) keep their already-complete
serialized metadata untouched.

* Remove comments on native models in card.clj

Removed comments about native models and infer-metadata.

* Switch to serializing model result_metadata :id as a portable ref

Carry each model column's :id through serdes as a portable field
reference (via *export-field-fk*), instead of recomputing it on load.
serdes already knows how to remap it on import (import-result-metadata),
and its FK resolution handles load ordering. This drops the load-finalize!
hook (and its serialization/load plumbing) in favor of a one-key change to
the model result_metadata keep-set.

* Re-derive model result_metadata :id on deserialization

Instead of serializing the model column :id (reverted), restore it on
import: when deserializing a model, populate-result-metadata re-derives
the result_metadata from the query (recovering each column's :id link to
its underlying Field) and blends the serialized overrides on top. This
assumes the referenced Fields are already present on the destination; if
they aren't resolvable, it falls back to the passed-in metadata.
2026-06-25 14:20:30 +00:00
Nemanja Glumac
eaf53de036 Ignore tagged tests in e2e smart runs (#76513)
Ignore tagged tests in e2e "smart runs"
2026-06-25 07:25:51 -06:00
Aleksandr Lesnenko
e4f821e593 indicate dirty transforms nodes (#76301)
* indicate dirty transforms nodes

* feedback
2026-06-25 08:58:15 -04:00
Ngoc Khuat
7ae5004486 Fix task_run.notification_id backfill migration on MySQL (#76509) 2026-06-25 12:43:48 +00:00
Nemanja Glumac
9a255e1059 Require an honest e2e-vs-unit-test breakdown in e2e-test-review reports (#76514)
Add a mandatory closing section to the e2e-test-review skill that classifies
each it() block as load-bearing e2e, narrowable, or a unit/component-test
candidate, grounded in which layers the test actually exercises. Wire it into
the review process and final-check steps so every report includes it.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-25 13:45:33 +02:00
github-automation-metabase
984b85591c Fix flaky transforms collections expand by clicking the Expand control (#76375)
The 'should create collections and save transforms to them' e2e test
created a nested transform collection and then clicked the parent row's
name to expand it. The row only toggles when row.getCanExpand() is true,
i.e. once the post-create collection-tree refetch has landed and
re-rendered with the new child. Clicking the name before that re-render
was a no-op, leaving 'Q4 Reports' hidden until the 4s findByText timed
out — a race that surfaced on faster (unthrottled) runs.

Waiting on the GET /api/collection/tree refetch wasn't enough: the
re-render can lag the network response. Instead, wait for the row's
Expand control, which the TreeTable only renders once the row is
actually expandable, and click that. Its presence is the deterministic
signal the child has landed, and it only ever expands (never toggles a
collapse), removing both the readiness race and the toggle ambiguity.

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-25 12:56:28 +02:00
Nicola Mometto
1ed83cde4b reduce compute load of transform planning (#76406)
* feat: cache table_dependencies, reduce read surface during get-plan

* feat: migrations

* for get-cycles too

* backfill migration

* tests

* fix

* write through on cache miss

* fix test

* ensure load source

* fix

* fix
2026-06-25 11:17:17 +01:00
Oleh K
30811cfc49 Migrate normal-variant Radio usages to metabase/ui Radio (#76405)
* Replace deprecated Radio with metabase/ui Radio (normal variant)

Migrate the four `normal`-variant usages of the deprecated
`metabase/common/components/Radio` to Mantine's `Radio.Group` + `Radio`
from `metabase/ui`:

- query_builder LimitPopover
- ActionCreator FieldSettingsPopover (input type)
- ValuesSourceTypeModal (parameter value source)
- enterprise EditSandboxingModal

Mantine's `Radio.Group` only handles string values, so the two non-string
cases are adapted at the radio boundary:

- EditSandboxingModal: boolean options -> "column"/"saved-question"
- ValuesSourceTypeModal: the null source type ("From connected fields")
  -> a sentinel string via serialize/deserialize helpers, keeping
  `ValuesSourceType` (incl. null) as the domain type everywhere else

Part of GDGT-2588 (PR 1 of 3).

* Adjust visual alignment
2026-06-25 11:34:13 +02:00
Oleh K
7e10ccb938 Preserve search relevance order for command palette actions (#76146)
* Preserve search relevance order for command palette actions (#76055)

The command palette re-sorted basic action results by a static
BASIC_ACTION_ORDER array, discarding the relevance order kbar's
useMatches already computes via Fuse.js. Since basic actions only
render when there is a search term, this static sort never served as a
useful default ordering and only buried the best match (e.g. typing
"New c" pushed "New collection" below "New question").

Drop the static re-sort so kbar's relevance order is preserved, and
remove the now-unused BASIC_ACTION_ORDER constant and processSection
sortOrder parameter.

* Update e2e test

* Make command palette nav test independent of action relevance order

* Try fixing e2e

* Fix test

* Tie-break command palette actions by default order via kbar priority

Rather than dropping the default action order entirely, encode it as a
small kbar `priority` so it only orders actions whose relevance scores
are equal. Typing "New" still surfaces "New question" first, while a
stronger match like "New c" surfaces "New collection" (metabase#76055).

Adds unit coverage for both cases and restores the concrete navigation
assertions in the palette specs.

* Rank palette actions by relevance with registration-order tie-break

Type a query and the command palette now orders basic actions by kbar's
search relevance, falling back to registration order only to break ties
between equally-relevant matches (via a tiny per-action priority). This
fixes 'New c' burying 'New collection' while keeping 'New question' first
for the bare 'New' query.

Also drop the redundant 'new embed' and 'new SQL' keywords: each merely
duplicated words already in the action's name, but distorted Fuse scoring
for short prefixes (ranking 'New embed'/'New SQL query' above the plain
create actions for 'New'). They remain findable by name.

* Restore PageDown-based palette nav assertions with updated order
2026-06-25 11:33:52 +02:00
Romeo Van Snick
922fcf102e Move data studio to feature tier (#75846)
* Extract data-studio's cross-module surface into common/data-studio

* Move data-studio FE module to the feature tier
2026-06-25 16:08:05 +10:00
Romeo Van Snick
1df9e07651 Remove @ts-nocheck from metabase-lib Field (#76320)
* Widen isDimension/isMetric and formatField parameter types

* Fold Base into Field and remove @ts-nocheck

* Type the Field constructor input and keep runtime-only fields on the class

* Use the API field directly in MappedFieldPicker; document Field hydration

* Move Field instance fields onto the class; drop vestigial JSDoc type comments

* Remove _comesFromEndpoint reference in clojurescript

* Take a NormalizedField in the Field constructor (removes constructor casts and lies)

* Move comment
2026-06-25 11:36:37 +10:00
technomancy
40d2f6caba Disable known-bad bigquery tests. (#76502)
Also: mark an unrelated test as requiring dynamic dataset creation.

Also: fix an unrelated bug in calculating which dataset tables already exist.
2026-06-24 19:41:35 -04:00
Romeo Van Snick
cd59e7adb5 Remove metabase/redux/question-reducer (#76134)
* Drop dead SOFT_RELOAD_CARD branch from questions reducer

* Hydrate questions slice via RTK endpoints, remove INJECT reducer

* Hydrate metadata store from entity mutation endpoints

* Revert "Hydrate metadata store from entity mutation endpoints"

This reverts commit fc20ae580a.
2026-06-25 08:39:34 +10:00
Ryan Laurie
362621fc4b Dont quarantine drivers on master or release branches (#76468)
dont quarantine drivers on master or release branches
2026-06-24 16:07:21 -06:00
github-automation-metabase
a55fd162cf Fix flaky data-studio bulk "syncing multiple tables" e2e test (#76492)
* Fix flaky data-studio bulk "syncing multiple tables" e2e test

The "syncing multiple tables" test restores the postgres-writable snapshot
in its body but, unlike every sibling test in this spec, never re-signs in
afterward. Visiting Data Studio could then land in an unauthenticated state
where the TablePicker never issues the GET .../schema/public request, so
`cy.wait("@getSchema")` timed out after 5s with "No request ever occurred".

Add `cy.signInAsAdmin()` after the restore — the same deterministic
re-authentication the reliable sibling tests already perform — so the
database expands and the schema request fires before the wait.

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

* Fix flaky "syncing multiple tables" e2e test: read table IDs deterministically

The test derived the expected table IDs from the intercepted `@getSchema`
UI response. Under stress that response body is occasionally a truthy
non-array (e.g. an error map), so `tables.find` threw
`TypeError: tables.find is not a function`. Read the table list from a
direct `cy.request` instead, which deterministically returns the array,
and keep `cy.wait("@getSchema")` purely as a UI-readiness wait.

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-06-24 21:45:58 +00:00
github-automation-metabase
38c9fa8e6b Harden flaky read-only column resize e2e with bounded drag retry (#76483)
* Fix flaky resize-column-width e2e test with real-events drag

The read-only column-resize test hand-rolled a synthetic mousedown/
mousemove/mouseup sequence plus a magic cy.wait(10). The TanStack resize
handle re-renders while the table measures itself, so the synthetic
events intermittently landed on a stale node and the drag was lost (or
only partly applied), leaving the column width unchanged.

Drive the drag with cypress-real-events (CDP-level input) and re-query
the resize handle for every event so each one targets the live node,
matching the proven pattern in notebook-native-preview-sidebar. Drop the
numeric wait in favor of the existing retrying assertion.

* Harden flaky read-only column resize e2e with bounded drag retry

The synthetic TanStack column-resize drag in saved.cy.spec.js was
occasionally lost or only partially applied because the resize handle
re-renders while the data grid measures/auto-sizes itself, so the
width assertion would time out (e.g. expected 72 to be at least 82).

A prior cypress-real-events rewrite did not resize the 4px, hover-only
handle at all. Revert to the proven synthetic drag and re-run it until
the column has actually widened (bounded, gte-checked, idempotent), so
a dropped drag becomes a non-event instead of a failure.

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-06-24 23:44:33 +02:00
github-automation-metabase
18da9c7f40 Stabilize pivot dashcard drill flake in dashboard-filters-misc (#76491)
* Stabilize pivot dashcard drill flake in dashboard-filters-misc

The 'does not use extra filtering stage for pivot tables' test drilled into
the pivot dashcard via its legend caption immediately after a raw
cy.button("Save").click(), without waiting for the dashboard to leave edit
mode. The drill only navigates in view mode, so when the click landed during
the save/edit-to-view transition it did nothing and /api/dataset/pivot never
fired, timing out cy.wait("@datasetPivot").

Use H.saveDashboard(), which waits for the save PUT, dashboard reload, and the
edit bar to disappear (view mode) before proceeding, so the drill reliably
triggers the pivot request.

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

* Exit dashboard edit mode without awaiting a save PUT in pivot filter test

The 'does not use extra filtering stage for pivot tables' test only inspects
parameter mapping options (verifyDashcardMappingOptions opens the picker and
clicks away); it never creates a mapping, so the dashboard stays clean and
clicking Save issues no PUT /api/dashboard/*. The prior H.saveDashboard() call
waited unconditionally on the saveDashboardCards request, which only fired on
the runs where the dashboard happened to be dirty, timing out otherwise.

Pass awaitRequest: false so saveDashboard clicks save and waits for the edit bar
to disappear (view mode) without awaiting a PUT that may never occur. This still
guarantees the following legend-caption drill runs in view mode, where it
reliably triggers the pivot dataset query.

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-06-24 21:41:25 +00:00
github-automation-metabase
7804a2b24f Fix flaky metabot usage-auditing by-day drill-through e2e (#76425)
The usage-auditing seed timestamps the "today" conversations at
`today - {15min, 30min, 2h}` where `today` is the current instant in
UTC. When the e2e suite runs shortly after UTC midnight, those events
roll into the previous UTC day, while the reported `:date` (the UTC
calendar day) advances to the new day. The "Conversations by day"
chart's last dot is then yesterday, so drilling navigates to
`date=<yesterday>` and the assertion `search` includes `date=<today>`
times out (e.g. `'?date=2026-05-25' to include 'date=2026-05-26'`).

Anchor `today` at noon UTC so every seeded "today" event stays firmly
inside the current UTC day regardless of run time. Relative offsets and
all per-hour relationships between the seeded conversations are
preserved.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-24 23:32:01 +02:00
github-automation-metabase
c06ca48e21 Fix click-behavior tab-fallback e2e flake: await target dashboard load before save (#76487)
Fix click-behavior tab-fallback flake: await target dashboard load before save

The "fall back to the first tab" test saved the dashboard immediately after
opening the click behavior sidebar, gated only by a negative assertion that
the tab selector is absent. That assertion passes trivially before the target
dashboard's fetch resolves, so the save raced ahead of the `migrateDeletedTab`
effect that falls the invalid tabId back to the first tab — the only thing
that dirties the dashboard. With no change registered, the PUT never fired and
`cy.wait("@saveDashboard-saveDashboardCards")` timed out.

Anchor on a positive signal (the click-mappings heading, rendered once the
target dashboard has loaded) before asserting the tab selector is absent, so
the migration has run and the dashboard is dirty by the time we save.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-24 23:21:48 +02:00
Uladzimir Havenchyk
41c638c12a fix: make no results text neutral (#76175)
* fix: make no results text neutral

* update screenshots

* update screenshot
2026-06-25 00:11:19 +03:00
github-automation-metabase
f9fbba15e0 Fix flaky bulk publish/unpublish e2e test (#76488)
The "allows publishing and unpublishing multiple tables" test clicked the database row to expand it and then waited on the schema fetch. The picker tree is still mounting when the databases request resolves, so the click on the row landed before its expand handler was wired and was dropped — the GET .../schema/public?include_hidden=true request that populates the tables never fired, timing out cy.wait("@getSchema") with "No request ever occurred" (and downstream, the [data-type=table] rows never rendered).

Click the database's dedicated expand toggle once it has rendered in its collapsed state (aria-expanded=false), then assert it reaches the expanded state. The pre-click assertion anchors on a positive readiness signal so the toggle is fully interactive before we click it, making the schema fetch fire deterministically.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-24 23:10:12 +02:00
github-automation-metabase
e15ce8caae Fix flaky test: should not reload dashboard cards not connected to a filter (metabase#32444) (#76484)
* Fix flaky dashboard filter card-reload e2e test

The "should not reload dashboard cards not connected to a filter" test
re-aliases the dashcard query intercept after saving the dashboard, then
asserts exactly one filter-triggered card query fires. Saving exits edit
mode and reloads both dashcards, but the test waited for only one of those
two post-save queries. The unwaited second query, slow under network
throttling, arrived after the intercept was re-registered on the same URL
and got counted as a filter-triggered query, so the assertion saw 2 instead
of 1.

Wait for both post-save card queries (total of four) to settle before
re-aliasing, so only the genuine filter-triggered query is counted.

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

* Settle dashboard reload by loading state, not query count

The flaky dashboard filter card-reload test re-aliased the card-query
intercept right after saving, then asserted only one filter-triggered
query fired. A post-save reload query could still be in flight and get
captured by the new intercept, inflating the count.

The previous attempt waited for a fixed number (4) of post-save queries,
but how many fire is not deterministic — cached card results may be
reused, so the total varied (3 vs 4) and the wait failed.

Wait instead for both dashcards' loading indicators to clear before
re-aliasing, which drains the post-save reload regardless of how many
queries it issued.

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-06-24 20:41:59 +00:00
Nemanja Glumac
8dfc0fc7c5 Consolidate unreferenced-entities e2e flake fixes into one guard (#76466)
The dependency graph is recomputed asynchronously on entity create/update,
so waitForBackfillComplete (global one-time flag) doesn't guarantee freshly
seeded entities have surfaced in the unreferenced list. Visiting too early
renders an incomplete list and findByText times out.

Replace the per-test ad-hoc waits with a single waitForUnreferencedAnalysis
helper that polls the unreferenced endpoint until every seeded entity (table
included, via the slower DB-sync path) is present. Apply it to all ten
presence-asserting tests, including five that shared the same race but were
never individually patched. The lone absence-asserting test keeps the global
backfill wait, since presence can't be polled for entities that should be
absent.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-24 14:26:25 -06:00
Alexander Polyankin
f573bc8dba Fix BigQuery OOM with information_schema queries (#76459) 2026-06-24 20:03:05 +00:00
Michael Eby
1701a63d4e docs: add page for dashboard heading and text cards (#76353)
* docs: add page for dashboard heading and text cards

* Optimized 6 images, saved 251.7 KB (49.2% smaller)

* Remove broken links

* Edits from Jeff

---------

Co-authored-by: Metabase Automation <github-automation@metabase.com>
2026-06-24 15:54:55 -04:00
Michael Eby
71895bbeff docs: add markdown page (#76019)
* docs: add markdown page

* Optimized 1 images, saved 4.5 KB (29.3% smaller)

* Edits from Jeff

* Edits from Jeff 2

---------

Co-authored-by: Metabase Automation <github-automation@metabase.com>
2026-06-24 15:54:44 -04:00
Alexander Polyankin
91db3c07f9 Fix perms OOM (#76463) 2026-06-24 19:53:08 +00:00
Ben Grabow
0c81b6fc95 Ghy 3975 fix dependency analysis on upgrade (#76442)
* Revert to returning unimported fk when importing fk fails

* Only ask for dashboard_id, for perf and to avoid pulling in problematic dangling refs in visualizer settings
2026-06-24 19:42:41 +00:00
github-automation-metabase
b096963652 Fix flaky test: data studio Undos allows to undo every action (#75996) 2026-06-24 21:38:27 +02:00
technomancy
a6c8c638b6 Mark bigquery as not supporting workspaces yet. (#76445)
Mark transform-schema-created-if-needed-test as requiring dynamic
dataset loading feature.
2026-06-24 18:47:58 +00:00
Alexander Polyankin
375861d545 Bigquery sync-fields less memory (#76441) 2026-06-24 17:40:00 +00:00
Nick Fitzpatrick
5c471b3e4d remove color prop from Based On Icons, center with flex (#76253) 2026-06-24 21:39:57 +05:30
Jakub Chodorowicz
65a4459af7 Gdgt 2498 integration treemap (#76346) 2026-06-24 16:54:30 +02:00
lbrdnk
d992491063 Ignore components of cors urls (#76192)
* Ignore components of cors urls

* Review remarks
2026-06-24 16:17:26 +02:00
Chris Truter
6ca4f480ff Create HNSW index only when explicitly using it (#76387)
* Create HNSW semantic-search index just-in-time, only when configured

The semantic-search index table always got an HNSW index on its embedding
column, regardless of whether anything used it. HNSW indexes are expensive
(build time, memory, disk), and a cluster hosting thousands of instances paid
that cost for every one even though ~99% are fast enough with an exact scan.

Flip the default vector-search strategy to :brute-force (exact, no index) and
only build the HNSW index when an instance is actually configured for :hnsw:

- create-index-table-if-not-exists! builds the HNSW index only when the
  configured strategy is :hnsw (covers env-var config and restarts). Extracted
  into idempotent create-hnsw-index-if-not-exists! (supports CONCURRENTLY).
- Setting the strategy to :hnsw at runtime triggers an async background build
  on the active index table (via core/build-hnsw-index-async!), so the settings
  call returns promptly.
- A query that requests :hnsw (e.g. a per-request override) when no HNSW index
  exists now fails fast with a clear error, rather than silently doing a slow
  exact scan.

* Add clj-kondo ignore marker to index-relfilenode test helper

Matches the sibling pgvector test helpers; suppresses
:metabase/test-helpers-use-non-thread-safe-functions.

* Build HNSW index only on the transition into :hnsw; test trigger and build

The setter previously kicked off a background build on every set to :hnsw,
including the restore that with-temporary-setting-values does. Gate it on the
actual transition (old != :hnsw) so redundant sets don't spawn stray builds.

Tests, split so neither relies on a real (flaky) future:
- index-test asserts the setter *triggers* a build only on the transition into
  :hnsw (spying on the async build).
- pgvector-api-test asserts ensure-active-hnsw-index! actually *builds* a missing
  index, and is a genuine noop when the index already exists (stable relfilenode)
  or when there is no active index.

* Build HNSW index via event instead of requiring-resolve; add startup safety net

* Test the indexer task's startup HNSW safety net
2026-06-24 16:00:22 +02:00
Romeo Van Snick
bb27b7a1c5 Fix MCP embed bundle loading async chunks from wrong origin (#76411) 2026-06-24 14:32:13 +02:00
Chris Truter
b934ac131d Add operator knobs for the pgvector connection pool (#75651) 2026-06-24 11:51:52 +00:00
github-automation-metabase
ecfa59f5fb Fix flaky bulk-table attribute-edit e2e test (#76408)
The "allows to edit attributes for tables" test clicked the database to
expand it and then immediately queried for table rows, without waiting
for the schema/tables to load. The tree picker is populated by an async
GET .../schema/public request, so the `[data-type="table"]` rows were
sometimes not yet rendered when the assertion ran, timing out after
4000ms.

Add `cy.wait("@getSchema")` after expanding the database — the same
deterministic wait the sibling tests in this spec already use — so the
tables are guaranteed to be present before selection.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-24 11:50:35 +00:00
Chris Truter
b57bcab6f0 Address minor tech debt in Search code (#76240) 2026-06-24 13:46:59 +02:00
github-automation-metabase
ff8b438987 Fix flaky auto-wiring foreign-keys e2e test (#76379)
The two auto-wire suggestion toasts (Orders Question + Reviews Question)
stack and briefly overlap while the undo list re-measures heights and
animates them into their final positions. During that window a sibling
toast can cover the precisely-scoped Auto-connect button, so cy.click()
fails its actionability check with "covered by another element".

Force the two Auto-connect clicks past the transient obstruction; the
target buttons are already uniquely scoped via
.contains(...).closest("toast-undo").

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-24 11:17:45 +02:00
github-automation-metabase
3b340f98e5 Deflake maps zoom/pan settle detection (#76383)
The "preserve zoom and pan after resize" test reads the first leaflet
marker position before and after a 1px viewport resize and asserts the
two are within 5px. The settle helper only required two consecutive
should() retries to land within 0.5px. Cypress retries faster than the
browser repaints, so two reads can fall in the same animation frame and
return an identical getBoundingClientRect() mid-animation, a false settle
that captured the after-zoom baseline before leaflet finished animating,
producing the historical 8-29px gaps.

Anchor the settle on elapsed wall-clock time (performance.now) instead of
read-count: require the marker to hold within 0.5px of an anchor for at
least 200ms before sampling, which a single-frame coincidence cannot
satisfy.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-24 11:09:54 +02:00
github-automation-metabase
807236db31 Fix flaky embedding data-picker join-step e2e test (#76380)
The picker resolves its initial path asynchronously before auto-navigating
into the data source's collection: a card-metadata fetch plus one
listCollectionItems request per collection level. On a throttled CI runner
that serial chain outlasts Cypress's default 4 s command timeout, so the
clickPickerItem lookup gives up while the picker is still showing the root
collections — the dominant "cannot find menuitem 'QA Postgres12 Orders
Model'" failure.

Give the picker-item lookup a generous timeout so it waits for the path to
finish resolving, and assert visibility before clicking. Also drop the stale
comment referencing a force-click that was already removed.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-24 16:07:35 +07:00
Oleh K
6dd944131e refactor: Migrate background-* tokens to background_page-* / background_surface-* (#76049)
* GDGT-2532 Migrate background-* tokens to background_page / background_surface

Sweep all consumer references from the legacy `background-*` semantic
tokens to their `background_page-*` / `background_surface-*` counterparts
(added in the foundation PR):

- Page:    background-primary/secondary/tertiary (+ -inverse), -highlight
           (-> -highlighted), -filter  ->  background_page-*
- Surface: background-disabled (+ -inverse), -hover, -selected, -brand
           (-> -brand-subtle), -success, -warning (+ -secondary -> -strong),
           -error (+ -secondary -> -subtle)  ->  background_surface-*
- Replaces: background-info -> background_page-tertiary;
            background-success-secondary -> feedback-positive-selected

SDK public theme keys (background, background-secondary, -hover, -disabled,
-error, -light) are part of the embedder-facing contract and are left
unchanged; the SDK_TO_MAIN_APP_COLORS_MAPPING right-hand sides gain the new
internal names as second targets so SDK/whitelabel overrides reach consumers
that now read the new tokens. Alert.config.tsx's `background-${color}`
synthesis is replaced with an explicit lookup map.

Drive-by fixes (pre-existing, surfaced by the sweep):
- EmbedFrame.module.css: fix `-inverseer` typo (undefined var since #65855).
- Bare `var(--mb-color-background)` was never a real token (rendered
  transparent at 8 sites); point each at the correct token by role and
  remove the dead `--mb-color-background` definition in LogoBadge that was
  silencing find-never-defined-css-variables.

* Use surface background tokens for Switch component

The Switch is a control (a surface on the page), so its track/thumb
backgrounds should use `background_surface-*` rather than `background_page-*`.
Disabled states now use the purpose-built `background_surface-disabled`;
the enabled off-track uses `background_surface-secondary`.

* Remove redundant comment

* Use text-secondary for RowChart axis text

The axis tick + title text was borrowing `background_page-tertiary-inverse`
(a background token) for its color. That token recolors as part of the
background migration, which shifted the axis text. Point it at the proper
`text-secondary` token instead — also consistent with the goal label.

* Update Loki Snapshots

* Formatting

* Update Loki Snapshots

* Update dark-mode body background assertion for recolored page-secondary

The body background uses `background_page-secondary`, which this migration
intentionally recolors in dark mode (color-mix off the page primary). Update
`assertDarkMode` from rgb(5, 14, 21) to rgb(5, 17, 25) (#051119) to match.
Light mode is unchanged.

* Assert dark-mode body background as color(srgb ...) computed value

The body background is a color-mix(in srgb, ...), which browsers serialize
in computed style as color(srgb ...). Assert the exact computed value
instead of an approximated rgb().

* Formatting

---------

Co-authored-by: Metabase Automation <github-automation@metabase.com>
2026-06-24 10:31:02 +02:00
Romeo Van Snick
dbf7e231fe Fix document boundaries (#75311) 2026-06-24 17:10:59 +12:00
Alexander Polyankin
1062bfb0a4 Fix BigQuery getQueryResults pagination (#76396) 2026-06-23 23:52:01 -04:00
Romeo Van Snick
d2ffdf5e3f Remove legacy API client (#76241)
* Migrate SDK execute-action to api.request

* Use updateSetting RTK hook in test render helper

* Remove legacy API client

* Flatten ApiClient request dispatch into a single _send

* Call updateSetting hook inside the test store provider

* Use RTK query for executeAction in embedding SDK bundle
2026-06-24 12:48:25 +10:00
Anderson
05e9b21565 Fix y-axis currency symbol clipping in compact view (#76138)
* Fix compact currency tick label padding

* Update loki snapshots

* Address review
2026-06-24 02:40:47 +00:00
Alexander Polyankin
b2b2786712 Fix bigquery nested fields sync (#76389) 2026-06-23 21:33:21 -04:00
Romeo Van Snick
f9fe257031 Allow full async lazy-loading Embedding SDK chunks (#75985)
* Fix embedding SDK on-demand chunk loading via runtime publicPath

The backend-hosted embedding SDK bundle shipped with output.publicPath: ""
and never set a runtime publicPath, so any dynamic import()/React.lazy chunk
URL resolved against the host app's origin (where SDK chunks don't exist) and
failed with ChunkLoadError.

Set webpack's runtime publicPath to the Metabase-hosted asset directory
(app/embedding-sdk/) so on-demand chunks load correctly:

- sdk-public-path.ts resolves the asset base and assigns __webpack_public_path__;
  it is the first import in the entry so it runs before any import().
- The chunked bootstrap exposes the base on
  window.METABASE_EMBEDDING_SDK_ASSET_BASE_URL (the entry runs asynchronously,
  so document.currentScript is unreliable there).
- The legacy monolithic bundle has no bootstrap, so the resolver falls back to
  document.currentScript.src, which is valid during its synchronous evaluation.

The backend already serves any app/embedding-sdk/chunks/*.js generically, so no
backend change is needed.

* Load jspdf and html2canvas lazily in the embedding SDK bundle

These export-only dependencies (~180KB brotli) were force-imported eagerly in
sdk-specific-imports.ts to work around the broken on-demand chunk loading. Now
that the runtime publicPath is set, drop the eager imports so they load on
demand (PDF / image export) instead of weighing down the SDK's critical path.

* Load pivot table grid lazily in the embedding SDK bundle

* Load map renderer lazily in the embedding SDK bundle

* Count async SDK chunks toward total bundle size now that they are loadable
2026-06-24 11:09:43 +10:00
Chris Truter
6c69992d5b Surface curation signals to Metabot in search results (#75511) 2026-06-24 00:27:26 +00:00
Chris Truter
edf5b0ae2e Consolidate "curation" filtering for Metabot (#75510) 2026-06-24 01:53:51 +02:00
github-automation-metabase
a05d864d9d Fix flaky dashboard back-navigation e2e test (#76382)
The "back to the dashboard button when navigating to a question" test
clicked "Edit question" from a dashcard and immediately clicked the
"Back to <dashboard>" button without waiting for the notebook editor to
finish loading. Clicking back before the query builder settles produces
a racy back-navigation that can briefly leave the dashboard without a
mounted app bar, so the later `appBar()` lookup ("Navigation bar")
intermittently fails while the dashboard header text is already visible.

Wait for the notebook editor's "Visualize" button to be visible before
clicking back, mirroring the sibling native-editor test and the
dashboard.cy.spec navigate-to-notebook test.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-23 22:22:41 +00:00
Sloan Sparger
774531880a [Metabot] Add v1 to v2 migration fns (#75662)
* adds migration for v1 message schema to v2

* output adjustment

* flip migration output keys to camelcase

* match on v1 malli schemas, improve tests

* copilot feedback

* pr feedback

* test fixes
2026-06-23 17:12:27 -05:00
Alex Yarosh
875ee94fc9 docs: Add note about public links and database routing (#76152)
Add note about public links and database routing

Clarified that public links do not function with database routing.
2026-06-23 17:56:09 -04:00
github-automation-metabase
e33b302372 Fix flaky usage-auditing chart drill-through e2e (#76377)
The "drills through from the conversations by hour/day chart" tests
interact with the timeseries chart immediately after visiting the usage
stats page, which only waits for the audit metadata request. The chart's
dataset query and ECharts render can still be in flight, so
cartesianChartCircle() races the render and intermittently times out
looking for [data-testid="chart-container"].

Anchor clickLastTimeseriesChartDot on assertChartRendered so the chart is
fully rendered (container visible with an svg child) before drilling.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-23 21:53:01 +00:00
github-automation-metabase
a0d9a2614e Deflake model entity-qualified-id drill-through e2e test (#76373)
The test clicked a result cell immediately after saving a new model,
racing the table that renders/animates in after the redirect to the
model view (Cypress reported the cell as still animating). Wait for the
model create (POST /api/card) and its query (POST /api/dataset) to
resolve and assert the table is visible before clicking the cell, so the
click no longer depends on animation timing.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-23 23:46:44 +02:00
github-automation-metabase
0c6374742f Fix flaky dashcard-duplicate parameters e2e test (#76374)
The "should duplicate filters and mappings when duplicating a dashcard"
test began interacting with the dashboard parameters (clicking the
"Count" pill) immediately after entering edit mode. Entering edit mode
re-mounts the dashcards and re-runs the card query, so the parameter
header was still re-rendering asynchronously when the click fired,
detaching the target element mid-click ("cy.click() failed because the
page updated while this command was executing").

Gate the first interaction on the dashcard's chart being visible so the
page has settled before editing parameters.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-23 21:35:34 +00:00
technomancy
6fe0c5b57e Don't destroy database during creation failure for cloud DBs. (#76363)
Mark bigquery as not supporting dynamic test loading, because it's a
cloud DB.
2026-06-23 20:57:31 +00:00
dpsutton
6701de190d Notification temp storage across dashboard (#76355) 2026-06-23 16:54:59 -04:00
Alexander Polyankin
9315930aa7 Improve memory usage of sync-tables-and-database! (#76330) 2026-06-23 16:54:04 -04:00
github-automation-metabase
9901a4384d Fix flaky notifications unsubscribe e2e test (#76362)
The "unsubscribe from an alert when the user has not created it" test
scoped its post-unsubscribe negative assertion inside the
notifications-list container and never waited for the unsubscribe
request. Since admin was the only recipient and not the creator,
unsubscribing empties the list and the notifications-list container
unmounts into the empty state. When the refetch won the race,
findByTestId("notifications-list") timed out.

Wait deterministically on the unsubscribe POST, anchor on the success
toast, then assert the notifications-list is gone (the real
post-condition) instead of querying inside a container that disappears.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-23 22:14:48 +02:00
Ben Grabow
1d050aec9c Bgrabow/monitor memoization cache size (#75967)
* Monitor number of cache entries in unbounded memoization caches

* Refresh metrics every 10 minutes instead of 1 minute
2026-06-23 18:32:31 +00:00
Eric Normand
fdd669322d Log the reason for full remote-sync export/import fallback (GHY-3935) (#76348)
When export! or import! falls back from the incremental fast-path to a
full re-serialize/reload, log which guard forced it so operators can see
why a full sync ran:

- export: forced overwrite, or a pending change can't be applied incrementally
- import: forced, local changes pending, first import, or changes not
  incrementally loadable

Bind import dirty? as a delay so the fast-path check and the reason
derivation share one query without forcing it on the no-op/merge paths.
2026-06-23 18:13:31 +00:00
Andrei Chernykh
c96ad1f49a Fix @tenant.slug tooltip to read 'system defined' on the create tenant user from (#76321)
Fix @tenant.slug tooltip to read 'system defined' on the create tenant user form
2026-06-23 11:01:28 -07:00
appleby
00f5a7c258 Add agent-lib repair pass to fixup invalid lib/type for join clauses (#76309)
* Add metabase.agent-lib.representations.repair/rewrite-lib-type-aliases*

Rewrite the hallucinated lib/type mbql.join/join to the corrected mbql/join. The LLM was observed making this error in BOT-1657.

Similar to the existing rewrite passes:

- rewrite-operator-name-aliases*
- rewrite-temporal-bucket-aliases*
- rewrite-direction-aliases*

* Fill in a missing lib/type for join clauses

We already did this for stages and the top-level query.

* Validate lib/type for ::join clause in metabase.agent-lib.representations/validate-query

* Mark all deftests ^:parallel in metabase.agent-lib.representations-test
2026-06-23 16:03:14 +00:00
Denis Berezin
98e9faea89 UXW-3457 Fix select to overflow viz settings popover (#76297)
Co-authored-by: @syedfardeenjeelani
2026-06-23 18:04:11 +03:00
Kevin Kelleher
025cda0388 Fix non-unique key props in SectionLayoutPreview (#76250)
fix non-unique key props
2026-06-23 10:51:30 -04:00
Riley Thompson
74aa95064b Validate sqlserver additional options when connecting (#76293)
validate sqlserver optios when connecting
2026-06-23 13:48:41 +00:00
github-automation-metabase
daa7c3d33c Auto-update documentation for master (#76303)
Update generated docs (master)

Co-authored-by: github-actions <github-actions@github.com>
2026-06-23 09:01:23 -04:00
Kevin Kelleher
49c604047d Fix bars overlapping in time series with only two bars (#76246)
* account for extra padding in bar width

* add loki test

* Update Loki Snapshots

---------

Co-authored-by: Metabase Automation <github-automation@metabase.com>
2026-06-23 07:10:03 -04:00
Nicola Mometto
0a0589299c Restrict glossary permissions (#76275)
* restrict permissions for glossary

* disable on UI

* adjust FE code + removed hover effect if the row is readOnly

* rename FieldId to GlossaryField

* address comments

---------

Co-authored-by: Egor Grushin <egor@metabase.com>
2026-06-23 10:05:54 +00:00
YB
403107f13f [GDGT-376] [GDGT-2624] fix serdes import oom (#75786)
Serializing the **import** of a very large data model (~1M+ fields) can OOM. The entire retained-memory cost of an import is the **ingest index**, built up-front before any entity loads (a flat memory plateau through the whole load phase).

Fixes:
1. **Drop the dead structures.** The cache value becomes the `File` directly (`{stripped-path File}`); delete `:from-ids` and its `medley` require, removing the second `ingest-list` pass.

2. **Intern path segments while building the index.** Each `{:model … :id …}` segment and its strings are canonicalized through a shared interner so index keys share their `[db schema table]` prefix structure. Value equality is unchanged, so cache lookups and `:seen`-set comparisons behave identically. Interning goes through a new `metabase.util.memoize/fast-interner` - a thread-safe `ConcurrentHashMap`-backed interner that stores the *canonical* value as the key (so the retained object is the string-pooled copy, not the parsed input).
2026-06-23 16:57:30 +08:00
Nemanja Glumac
dc80345e66 Drop the fix-flaky-test command (#76299) 2026-06-23 09:54:20 +02:00
Uladzimir Havenchyk
6787014a55 chore: drop deprecated Button (#76296) 2026-06-23 07:46:09 +00:00
Romeo Van Snick
3d5661eb54 Lazy load echarts module (#75220)
* Lazy load Echarts renderer

* Load Echarts as the vizualisation loads

* Use correct fallback for echarts renderer

* Fix placeholders for some skeletons

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

* Eagerly load echarts in sdk bundle

* Reenable brush after chart loads

---------

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
2026-06-23 16:24:56 +10:00
Alexander Polyankin
5ec0d46be4 Push sync limit to drivers (#76307)
* Push sync limit to drivers

* fix

* fix

* fix
2026-06-22 19:49:21 -04:00
Romeo Van Snick
e5b06223a1 Lazy load leaflet (#75222)
* Lazy load Leaflet

* Eagerly import map renderer in SDK bundle to fix lazy-loaded leaflet

The lazy `import()` of MapRenderer never resolves in the embedding SDK
bundle, which can't fetch on-demand chunks at runtime. Pull it into the
preloaded SDK bundle via sdk-specific-imports so the dynamic import
resolves from an already-loaded chunk, while the main app keeps its lazy
leaflet chunk.

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-06-23 09:32:04 +10:00
Eric Normand
a60bd4f293 Surface essential-step sync failures instead of reporting initial sync complete (GHY-3943) (#76286)
* Surface essential-step sync failures instead of reporting initial sync complete (GHY-3943)

When an essential metadata sync step (sync-tables, sync-fields) failed
non-transiently mid-initial-sync, the error was logged and swallowed,
and the database's initial_sync_status was still set to "complete".
This left tables with zero fields while reporting success -- e.g. on
MariaDB <10.2, whose information_schema lacks generation_expression, so
describe-fields throws and no fields are synced, yet the query builder
reports 'Table has no Fields associated with it'.

Mark sync-tables and sync-fields as essential steps. Initial sync is now
reported as aborted (not complete) when an essential step fails for any
reason, in addition to the existing transient-error abort path. Non-
essential step failures (indexes, FKs) and per-table failures still
report complete, preserving graceful degradation. The status setters
no-op once a database is already complete, so re-syncs of healthy
databases are unaffected.

* Better factoring

* Remove unused metabase.util require in sync-metadata

The cond-based sync-db-metadata!* no longer uses u/prog1, so the alias
is unused; drop it to satisfy clj-kondo.
2026-06-22 17:04:54 -05:00
Ben Grabow
ebb8e4838b Replace H2 with SQLite for sample data 2026-06-22 21:50:25 +00:00
Braden Shepherdson
57991c5b67 [subs] Generate PDFs for dashboard subscriptions on the BE (#75205)
The PDFs are laid out on either A4 or US Letter paper, portrait orientation, following the size and positioning of cards on the dashboard itself.

This is a nearly complete rendering of the dashboard, akin to what you see in the brower:
- Directly building a PDF in memory with Apache PDFBox, a low-level Java library.
- All chart types supported by static viz
    - Recently expanded to include maps and pivot tables!
- Markdown rendering, including code blocks, clickable links etc.
- Unicode support (Europe, Cyrillic, Greek, Hebrew, Arabic, Hindi, CJK and others) including RTL
- iframe cards have their target (e.g. a YouTube video) rendered as a link
- Dashboard is run as the requesting user, and can have parameter values supplied
- Parameters on dashboard and individual cards are shown with their values.
- Solid API endpoint that allows for parameter values and directly responds with the PDF.
- Reusing query results when sending charts via email or Slack along with a PDF.

---------

Co-authored-by: Nick Fitzpatrick <nick@metabase.com>
2026-06-22 16:40:28 -04:00
Uladzimir Havenchyk
09726c60c7 chore: migrate to FormSubmitButton from metabase/forms (#75709)
* chore: migrate to FormSubmitButton from metabase/forms

* address code review
2026-06-22 23:28:58 +03:00
bryan
fdf5e72f54 dev.module-viz: interactive modules graph visualizer (#75256) 2026-06-22 20:21:49 +00:00
Andrei Chernykh
0c9ca2b55d Fix middle-click on search results (#76123)
* Make the whole search result row a real link so middle/ctrl-click opens a new tab, and migrate its styles to Mantine

* Block navigation on inactive results, fix click-tracking attribution, and harden the title color override
2026-06-22 11:55:42 -07:00
Alexander Polyankin
ea63bc4889 Fix OOM with BigQuery and Redshift sync (#76276) 2026-06-22 14:23:48 -04:00
Egor Grushin
ab33899be5 GIT-5689 get rid of tippy.js (#76247)
* GIT-5689 get rid of tippy.js

* GIT-5689 additional clean ups
2026-06-22 19:19:43 +01:00
Uladzimir Havenchyk
657d0ec515 fix: handle click on cancel button and make title bigger (#76148) 2026-06-22 21:15:17 +03:00
Denis Berezin
1b5aefd862 UXW-4466 fix Y-axis auto position (#76183)
* UXW-4466 fix Y-axis auto position

* Fix failing e2e

* Fix failing e2e
2026-06-22 21:05:34 +03:00
Nick Fitzpatrick
e809dd2715 Fix library tree auto-expand race leaving Data/Metrics collapsed (#76167) 2026-06-22 23:33:07 +05:30
Nick Fitzpatrick
4318830e5e Stabilize flaky datetime cell-edit table-editing e2e test (#76158)
remove randomness from table edit date test
2026-06-22 23:32:19 +05:30
Eric Normand
6bfb3cc0ae Enforce remote-sync dependency guard on card bulk-move (GHY-3791) (#76278)
* Enforce remote-sync dependency guard on card bulk-move (GHY-3791)

The bulk-move endpoint (POST /api/card/collections) was the only mutation
path that hand-rolled the remote-sync dependency guard instead of using
check-for-remote-sync-update. It checked the stale pre-update card objects
(so moving a root-level card into a synced collection slipped through) and
never checked dependents (so bulk-moving a depended-on synced card out of
the sync set was allowed, unlike the single-card PUT path).

Use check-for-remote-sync-update so the post-update state is re-selected
and both directions are checked inside the existing transaction.

Also add an edit-time test for adding a non-synced dashcard via dashboard
PUT, closing a pre-existing coverage gap.

* Unnecessary comment
2026-06-22 17:00:08 +00:00
Ben Grabow
63a2dbfdf4 Empty nodes yields empty traversal instead of error (#76262) 2026-06-22 16:50:11 +00:00
Riley Thompson
52833fb7bb Use table of LHS join column in query builder (#76038)
* use table of the lhs column

* apply suggestion
2026-06-22 16:41:04 +00:00
metamben
630fc8df93 Preserve nulls in day-of-week calculation (#76180)
Closes QUE2-687
2026-06-22 16:21:01 +00:00
Alexander Polyankin
59637becb1 Fix postgres test (#76277) 2026-06-22 11:58:18 -04:00
Riley Thompson
db9803f9b8 Remove mbql5 experiments (#75127)
* remove postgres-mbql5

* remove mbql5 experiment

* fix postgres, add testing code

* fix and clean up

* include h2 test

* ignore native queries

* add function to compare compilation results

* fix tests

* remove old mbql5 references

* move redshift to mbql5

* redshift compilation test

* examples

* save changes

* fix bad merge
2026-06-22 11:21:28 -04:00
Riley Thompson
cea403df68 Dont override lib temporal types if driver type is text (#75663)
* dont override lib temporal types if driver type is text

* make test driver agnostic

* fix tests

* add sqlite test

* rename unreliable-driver-type? to prefer-lib-type?

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

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
2026-06-22 11:03:17 -04:00
Nathan Voxland
16080fabce Fix appdb reindex misdirecting writes to the live index (#76199) 2026-06-22 09:56:06 -05:00
Alexander Polyankin
b342ae4aa7 Fix OOM with json/decode (#76221) 2026-06-22 10:41:55 -04:00
Alexander Polyankin
4392d6aff4 Fix OOM with sync metadata for postgres/redshift (#76218) 2026-06-22 10:41:42 -04:00
metamben
67f5557d3b Skip sandboxing during metric expansion (#76125)
Closes QUE2-681
2026-06-22 17:20:41 +03:00
Anderson
e1e1fef04b Fix conditional formatting range matching (#76137) 2026-06-22 10:53:42 -03:00
Anderson
36329b87e1 Fix download permission warning for blocked groups (#76075) 2026-06-22 10:53:31 -03:00
Ngoc Khuat
a65b91edee GDGT-2332: Retry cluster-lock writes on transient deadlocks (#75172) 2026-06-22 13:46:18 +00:00
Egor Grushin
e3ce080ee8 Gdgt 2590 replace deprecated tooltip component (#76117)
* GDGT-2590 remove tippy completely

* GDGT-2590 replace tippy Tooltip with Tooltip from metabase/ui.

* GDGT-2590 fix tests

* GDGT-2590 fix js test

* GDGT-2590 fix fade animation

* GDGT-2590 fix the gap in stacked tooltip

* GDGT-2590 remove the useState+useEffect hack

* GDGT-2590 remove redundant comment
2026-06-22 14:11:55 +01:00
Romeo Van Snick
4b32e29e29 Move collections frontend module to the feature tier (#75986)
* Move shared collection utilities to metabase/common/collections

Relocate the tier-agnostic collection helpers (utils, constants, types,
hooks, schemas, getExpandedCollectionsById, analytics) from
metabase/collections into metabase/common/collections so they remain in
the shared tier once metabase/collections becomes a feature module.
Update all importers to the new path.

* Move shared collection components to metabase/common/collections

Relocate the collection components and containers that are consumed by
other feature and shared modules (FormCollectionPicker,
FormCollectionAndDashboardPicker, CreateCollectionModal,
FormAuthorityLevelFieldContainer, CreateCollectionForm, PinnedItemCard,
ActionMenu, PinDropZone, CollectionRowMenu, QuestionMoveConfirmModal)
into metabase/common/collections. Extract the shared collection-content
column types into metabase/common/collections/columns. Update importers.

* Move metabase/collections to the feature tier

With all cross-module collection utilities and shared components now
living in metabase/common/collections, metabase/collections only holds
the collection browsing/landing experience. Promote it from the shared
tier to the feature tier so it can no longer be imported by shared or
other feature modules.

* Import SortableColumnHeader directly to avoid barrel cycle resolving undefined
2026-06-22 22:48:40 +10:00
Chris Truter
813d41e755 Respect explicit null collection_id in MCP creation (#75727) 2026-06-22 12:02:40 +00:00
Romeo Van Snick
1b0e9e91d4 Fix silent data corruption when a query errors mid-stream (#75586)
* Abort instead of sending json blob to client in streaming responses

* Stop trying to parse 202 as JSON

* Handle error in response.blob

* Stream an error event when metabot fails mid-stream in text/event-stream

* Clean up handleResponse

* Add e2e test for failing download

* Fix typo in handleResponse comment

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

* Revert completion flag when aborting the connection fails

If the Jetty .abort throws, the optimistically-set *completed?* flag would
otherwise stay true, causing do-f-async's finally to skip .complete and leave
the async request hanging until Jetty's timeout fires.

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

* Add frontend tests for mid-stream download error handling

Covers readDownloadBlob mapping a blob() rejection to the localized
download-interrupted error, and handleResponse rejecting (rather than silently
resolving) when a streamed success body fails to read mid-stream — the behavior
that replaced the old 202 error-blob sniffing.

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

* Fix flaky metabot disconnect test under forced chunked encoding

closing-connection-native-agent-test closed the response body stream to
simulate a client disconnect. Now that streaming responses force
Transfer-Encoding: chunked (for mid-stream abort detection on downloads),
closing the body makes clj-http drain the chunked response to completion —
which the server sees as a normal finish, not a disconnect, so the turn
finalized as :finished? true.

Close the underlying http-client instead, which aborts the connection and is
detected by the server's cancel loop — matching the existing pattern in
streaming_response_test. Adds user-real-request-full-response to expose the
:http-client from a real streaming request.

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

* Add special error case for interrupted responses

* Render the new stream error differently than just a network error

* Remove stale _status in BE response

* Remove all references to _status

* Be more explicit about HTTP/2 in comment

Co-authored-by: Chris Truter <crisptrutski@users.noreply.github.com>

* Disambiguate singular "Year" granularity label to fix i18n template build

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: Chris Truter <crisptrutski@users.noreply.github.com>
2026-06-22 20:52:07 +10:00
Romeo Van Snick
26dc779def Disambiguate singular "Year" granularity label to fix i18n template build (#76231) 2026-06-22 10:51:07 +00:00
Chris Truter
632949fe3d Add search debug API to explain why an entity is missing from results (#75132)
## Summary

Adds a superuser-only **`GET /api/search/debug`** that answers "I searched for X but my card/dashboard/table didn't show up — why?". It takes a normal `/api/search` request plus `expected_result_type` and `expected_result_id`, walks the search pipeline against whatever engine the request resolves to, and returns `{type, details}` for the **first** stage that drops the entity.

| `type` | meaning |
|---|---|
| `not-searchable` | the spec says don't index it (no spec, or its `:where` excludes it) |
| `missing-from-index` | the spec would index it, but it's absent from the active index (stale/failed ingestion) |
| `filtered` | in the index but cut by a structural filter or permissions — `details.excluded-by` says which |
| `not-matching` | passes filters but doesn't match the fulltext/semantic query (semantic includes the 0.7 cosine cutoff) |
| `matched` / `ranked-out` | passes every stage; returned, or ranked below the limit |

## How it works

A new `search.engine/diagnose` multimethod, dispatched per engine — appdb impl in OSS, semantic impl in EE. Shared orchestration in `debug.clj` handles the engine-independent stages (`not-searchable`, terminal `matched`/`ranked-out`); each engine impl handles `missing-from-index` / `filtered` / `not-matching`.

The appdb impl reuses the normal `results` filter chain but **drops the fulltext predicate** — the blank-search-term seam — to separate "filtered" from "not-matching", and probes filters cumulatively to attribute which one excluded the row.

## Notes

- `indexed-entity` is rejected (400) — compound id doesn't fit `PositiveInt`.
- `not-searchable` reflects current spec/DB truth, so it wins over a stale lingering index row.

## Testing

`metabase.search.debug-test` (appdb) and `metabase-enterprise.semantic-search.debug-test` (pgvector, auto-skips without `MB_PGVECTOR_DB_URL`) — one case per result type. Green in a clean JVM.
2026-06-22 11:56:27 +02:00
Ngoc Khuat
0869369208 Admin notifications group by notification id not card id (#75928) 2026-06-22 09:23:04 +00:00
Oleh K
18eeb58dc2 refactor: Sweep border-* tokens to border-neutral-* (#75611)
* Sweep `border-*` tokens to `border-neutral-*` (GDGT-2531)

Renames all internal consumers of the legacy border semantic tokens to
their `border-neutral-*` counterparts (added by the foundation PR):

- `--mb-color-border`           → `--mb-color-border-neutral`
- `--mb-color-border-strong`    → `--mb-color-border-neutral-strong`
- `--mb-color-border-stronger`  → `--mb-color-border-neutral-strongest`
- `--mb-color-border-subtle`    → `--mb-color-border-neutral-subtle`

Sweep covers `var(--mb-color-…)` references in CSS modules and
styled-components, `color()`/`alpha()`/`darken()`/`getColor()`/
`renderingContext.getColor()`/`theme.fn.themeColor()` helper calls,
`theme.colors.border`/`theme.colors.border[0]` accesses, Mantine
`c`/`bg`/`color` props, and a couple of single-site palette lookups.
All four are pure renames — `border-neutral*` resolve to the same
primitives as the legacy tokens in both light and dark modes.

`border` is an SDK v1 theme input key (`MetabaseColors.border`), so
`SDK_TO_MAIN_APP_COLORS_MAPPING.border` now maps to both `["border",
"border-neutral"]`. Without it, an SDK consumer setting
`theme.colors.border = "#hex"` would update only the legacy
`--mb-color-border`; the new `--mb-color-border-neutral` that the swept
code reads would stay at its default. The dual-map covers both SDK v1
paths — the global `colors` object via `getEmbeddingColorPalette` and the
Mantine override via `getEmbeddingThemeOverride`. Unlike
`brand`/`filter`/`summarize`, `border` isn't a whitelabel
(`application-colors`) key, so no whitelabel-passthrough mirror is needed.

Also flips the four `border` references in the emotion-migrate skill to
their `border-neutral` equivalents, matching the per-sweep convention.

The SDK contract surfaces (`embedding-color-palette.ts` left-side input
key, `dynamic-css-vars-config.ts`, `dynamic-sdk-color-defaults.ts`,
`MetabaseTheme.ts`, `apply-theme-preset.ts`) stay on the legacy `border`
name.

* Realign table in SKILL.md
2026-06-22 11:14:18 +02:00
Oleh K
e78aaa2c44 Fix run query button icon being too small on large screens (#76223)
Remove the large-breakpoint padding override on the run button so the icon keeps its intended size across viewport widths.
2026-06-22 11:06:00 +02:00
Oleh K
dc878ea1e5 Add transform job run history page (#76017)
* GDGT-2632 Build frontend for job run history page

Add a "Run history" tab to the individual transform job page
(/data-studio/transforms/jobs/:jobId/runs) showing a paginated,
sortable, status-filterable list of past job runs, with a resizable
right sidebar to drill into the transform runs that made up a run.

- Types/API: TransformJobRun + TransformRunForJobRun, listTransformJobRuns
  and listJobRunTransformRuns endpoints, transformJobRuns URL helper
- Page: JobRunListPage (table, status filter, pagination, polling) and
  JobRunSidebar (job-run info + transform-run items with View transform)
- Tabs: JobTabs (Overview / Run history) wired into JobEditor + routes
- Promote shared sidebar pieces to metabase/transforms/components
  (SidebarResizableBox, SidebarInfoRow, ErrorSection, TimezoneIndicator)
  so both the runs page and job-run page use them instead of
  cross-importing between pages
- ErrorSection gains showTitle option; colors use the new token names

* GDGT-2632 Add run-method and start-time filters to job run history

The base endpoint now supports filtering job runs by run-method and
start-time, so wire them through and surface them in the UI.

- RTKQ/URL: add run-method + start-time to ListTransformJobRunsRequest,
  the transformJobRuns URL helper, and the page param parser
- UI: Trigger Select (manual/cron) and Started Select with relative
  presets reusing TaskRunDatePicker's labels/values
- Tests: cover each filter interaction and URL-driven params; fix an
  async sidebar assertion

* GDGT-2632 Extract TransformRunList to avoid nested ternary

Address PR review: replace the loading/empty/list nested ternary in the
job run sidebar with a small TransformRunList component using early
returns.

* GDGT-2632 Poll sidebar transform runs while a run is in progress

Address PR review: the job run list polls and updates a run's status, but
the sidebar's transform runs are a separate cache entry that never
refetched, so they went stale after the run finished. Poll the sidebar's
transform runs while the run or any of its transforms is still in
progress.

Lets the shared setup*Endpoint helpers accept a response getter so the
test can drive a run from in-progress to finished while the sidebar
stays open.
2026-06-22 09:11:34 +02:00
Nick Fitzpatrick
abeb35e2e6 Fix flaky impersonation caching e2e test (#76162)
After switching to the impersonated user and reloading, the test asserted
query-builder-main before the reloaded query returned; under load the page
outlasted the default 4s timeout (seen in CI at impersonated.cy.spec.js:143).
Wait on the @query response before asserting the error UI.
2026-06-22 07:40:12 +05:30
Nick Fitzpatrick
9eb4bd1407 Fix flake in should preserve correct order of columns after column removal via sidebar (metabase#13455) (#76083) 2026-06-22 07:39:51 +05:30
Nick Fitzpatrick
a56c304e9e Fix flaky document revision-history toast assertion (#76164)
The revert-error check used a singular toast-undo lookup, but the two earlier
"Document saved" undo toasts could still be visible, so it matched multiple
elements and timed out with an ambiguity error. Dismiss each save toast right
after asserting it so they don't stack into the later lookup, keeping the
simple singular assertions.
2026-06-22 07:35:59 +05:30
Nick Fitzpatrick
7c823b037d Fix flaky remote-sync read-only tenant collection test (#76161)
The test created a shared tenant collection right after enabling read-only
sync, racing the auto-triggered import. Both creations bump the implicit
collection-permission revision via a non-atomic max(id)+1 insert, so they
collided on the primary key and returned a 500. Now await the import first.
2026-06-22 07:35:45 +05:30
Nick Fitzpatrick
e2ad12e6bd Fix flaky maps zoom/pan-after-resize e2e test (#76159)
The test compared a pin marker's position before and after a 1px viewport
resize, but read both positions on fixed cy.wait() timers that race leaflet's
~250ms zoom/resize animation. On a slow machine the pre-resize read landed
mid-animation, drifting past the 5px tolerance. Read each position only once it
settles (poll until two consecutive reads agree) instead of waiting a fixed
time; the closeTo tolerance assertions are unchanged.
2026-06-22 07:35:25 +05:30
Nick Fitzpatrick
42446b8240 Stabilize data-studio bulk "edit attributes for db" e2e test (#76085)
The test selected the database, published it, then clicked the database
row to expand it. While a node is selected, the row click only toggles
expansion, which races the post-publish re-render and could collapse the
database so its tables never rendered. Deselect before expanding, then
wait on the schema request before asserting on the table rows.
2026-06-22 07:27:54 +05:30
Fraser
fd771cbb26 Move home to feature tier (#75213) 2026-06-22 13:34:45 +12:00
Fraser
0ef9a1f2a3 Move account to feature tier (#75211) 2026-06-22 13:29:21 +12:00
Romeo Van Snick
45d21618a2 Lazy load react-virtualized (#75680)
* Lazy load react-virtualized

* Force pivot table eager in SDK bundle to fix on-demand chunk failure

The SDK bundle can't fetch on-demand webpack chunks at runtime, so the
lazily-imported react-virtualized-backed pivot table never rendered,
failing the SDK component tests. Importing PivotTableInner from
sdk-specific-imports.ts inlines it eagerly only in the SDK bundle while
keeping the main app lazy.

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-06-22 11:27:18 +10:00
bryan
7766803a0c Bump bun to 1.3.14 (#76037)
* Bump bun to 1.3.14

* Update bun version in actions

---------

Co-authored-by: Fraser <fraser@metabase.com>
2026-06-22 12:01:29 +12:00
Romeo Van Snick
4bb017ab46 Bundle sizes stats fix (#76220)
* Show error when response fails

* Upload bundle sizes to the correct stats table

* Leave Version empty for unknown build tags
2026-06-22 09:38:38 +10:00
Alexander Polyankin
4df92d8239 Do not fingerprint MongoDB binary blobs (#76214) 2026-06-21 11:17:41 -04:00
Romeo Van Snick
dfecbd6799 Convert metabase/redux/metadata.js to TypeScript and remove some deprecated handlers (#76048)
Type redux/metadata, merge metadata-typed, and split out remapping/revision thunks
2026-06-21 15:09:37 +10:00
Romeo Van Snick
9fd9561b4c Bundle size stats (#76043)
* Emit frontend bundle stats from production build

* Track bundle sizes over time in stats.metabase.com

* Fix formatting

* Remove unused lint rule

* Reuse measure-bundle-sizes.js in the SDK bundle size check
2026-06-21 15:08:36 +10:00
Romeo Van Snick
2c8318d72a Remove enterprise legacy services (#76132)
* Convert enterprise services.ts to RTK query hooks

* Convert application permissions API to RTK query hooks
2026-06-21 15:08:07 +10:00
Egor Grushin
3153af0735 Gdgt 2575 replace deprecated modal component (#75563)
* GDGT-2615 fix PopoverWithRef

* GDGT-2615 migration step 2. (checks 1–6 are passed)

* GDGT-2615 migration step 3 put comments

* GDGT-2615 fix comments

* GDGT-2615 fix test

* GDGT-2615 move tippy-leftovers to tooltip folder

* GDGT-2575 hook mantine's modal to RENDERED_POPOVERS and get rid of deprecated Modal

* GDGT-2615 fix import import "metabase/common/components/Tooltip/tippy.module.css";

* GDGT-2575 extra comment

* GDGT-2575 restore pie_chart.cy.spec.js to master

* GDGT-2575 remove RENDERED_POPOVERS stack

* GDGT-2575 fix closing order

* GDGT-2575 simplify a code

* GDGT-2575 restore working state + added comments + keep code simplification

* GDGT-2575 fix animations

* GDGT-2575 change test description

* GDGT-2575 remove legacy modal selector from H.modal()

* GDGT-2575 fix autofocus in CreateActionForm

* GDGT-2575 remove legacy test

* GDGT-2575 fix Cancel button in NewEventModal

* GDGT-2575 fix autofocus

* GDGT-2575 fix cancel buttons

* GDGT-2575 make wide to be 95% instead of 85%

* GDGT-2575 force rerender to be sync

* GDGT-2575 fix SDK test

* GDGT-2575 addressed #75637 PR's comment leftovers

* GDGT-2575 removed missed unused import

* GDGT-2575 rename store to context

* GDGT-2575 move OverlayStackProvider to the app and sdk roots

* GDGT-2575 fix codemirror editor tooltip inside transformed parent

* GDGT-2590 fix unit tests

* GDGT-2590 fix loki tests
2026-06-20 16:15:11 +01:00
Alexander Polyankin
6992729d5e Limit max sync / scan / fingerprint fields (#76189) 2026-06-19 20:05:50 -04:00
Chris Truter
0bc758804b Add search_curated tool for NLQ (#75237)
* Add semantic_layer_index table and the semantic-layer-search OSS module

The semantic layer is a hand-curated library of saved search prompts, each
mapped to the entities that answer it (canonical = one directly-answering
entity, sources = a set to combine), plus agent-facing usage_instructions.

- migration: single createTable for semantic_layer_index (search_prompt,
  usage_instructions, entities JSON, type, verified, entity_id, timestamps)
- :model/SemanticLayerIndex with validation (non-empty entities; canonical =>
  exactly one) and serdes spec (polymorphic entity refs export as portable
  Card entity_ids / Table paths, mirroring export-viz-link-card)
- write hooks only nudge the enterprise background sync (request-sync!
  defenterprise shim, no-op in OSS) - no embedding or pgvector work on the
  write path
- superuser CRUD API at /api/semantic-layer-search
- module config: new semantic-layer-search module entry

* Add the semantic_layer_search Metabot tool and wire it into the nlq profile

The tool matches the user's request by vector similarity against the curated
semantic layer instead of ranking the whole instance:

- over-fetches raw per-prompt hits, dedupes to distinct entity sets (several
  prompts map to one entity), and returns a small best-first list
- hydrates matched entity refs into the enriched search-result shape via a new
  public tools.search/entity-refs->search-results (portable_entity_id,
  database names, fully-qualified names, metric base tables), so the agent can
  build a query without an extra read_resource round-trip
- surfaces raw cosine similarity and flags low-confidence matches (< 0.45)
  with a leading <note> + confidence="weak", so a miss reads as a miss
- the nlq profile uses it in place of nlq-search-tool

* Add the enterprise pgvector mirror with asynchronous reconciliation

Replaces the hackathon design (embedding-service + pgvector writes inside the
appdb write path via Toucan hooks, best-effort and silently drifting) with a
self-healing background sync:

- reconcile! diffs the whole authoritative appdb table against the mirror by
  content hash every run: stale rows are re-embedded (batched), orphans
  deleted, unchanged rows cost nothing. Any missed write - pgvector downtime,
  a crashed node, an import that bypassed the hooks - is repaired on the next
  run with no operator action.
- index-table/ensure-tables! owns the pgvector DDL: vectors table + HNSW
  index + a single-row meta table recording the embedding model identity and
  schema version. A model/dims change (or version bump) drops and recreates
  the vectors table; the next reconcile re-embeds everything. That
  drop-and-rebuild is the whole model-change story - the source table is
  small and always available.
- task.sync runs reconcile! on a 30s Quartz schedule (cluster-singleton,
  DisallowConcurrentExecution); appdb write hooks trigger-now! the job so
  curator edits are searchable within seconds, with trigger coalescing as
  free debounce.
- core/search serves the tool's similarity query (cosine distance + flat
  canonical/verified boosts, regular-search-shaped score breakdown); [] when
  pgvector is unconfigured or the mirror table does not exist yet.

End-to-end test drives CRUD API -> reconcile -> pgvector -> tool against an
isolated mirror with the 4-dim mock embedding model.

* Wire SemanticLayerIndex into serialization export/import

- exported-models + extract/model-set (with a :no-semantic-layer-index
  opt-out, like sibling models) + ingest legal-top-level-paths
  (semantic_layer_index/, matching the model's storage-path label)
- round-trip coverage: in-memory ref transformation and a real on-disk
  export/import (the two layers that have silently dropped models before),
  excused from the shared baseline fixture it covers itself

* Simplify the semantic layer to a single entity per entry

Drop the sources/canonical distinction: every entry now maps one saved prompt
to exactly ONE entity. Simplifications that follow:

- appdb table: `entities` JSON array + `type` column become a single
  `entity` JSON object; the canonical-arity validation hooks disappear
- pgvector mirror: `canonical` column gone; scoring is similarity (1.0) +
  verified boost (0.1) only
- tool: dedupe key is the single entity, matches lose the kind attribute,
  flatten-data loses match_group, and total_count now trivially equals the
  per-entity row count
- API: no type field/filter

Also folds in the roborev branch-review findings (job 1915):

- serdes entity-ref vocabulary now covers ALL the entity models the tool
  hydrates (question was missing -> export threw; card was hydrated nowhere),
  with an export-viz-link-card-style fallback for unmapped model strings
  instead of aborting the export, and round-trip coverage for every card
  flavor (card/model/metric/question) plus table
- the sync job uses task/defjob (log context + tracing span) instead of a
  raw deftype re-implementing half of it

The remaining two findings (PUT canonical revalidation, total_count vs
flattened rows) are moot now that canonical/sources is gone.

* Address Copilot PR feedback: card->question normalization, XML escaping, finite embeddings

- entity refs with :model "card" now hydrate (normalized to the agent-facing
  "question" type via a new public tools.search/ref-model->entity-type, used
  for both hydration grouping and the tool's lookup key)
- curator-entered saved_search_prompt / usage_instructions are XML-escaped in
  the tool output
- format-embedding rejects NaN/Infinity (they satisfy number? but produce SQL
  literals pgvector chokes on)

* Fix nlq-profile tests for the renamed tool + roborev follow-up nits

CI: the pre-existing profile/tool tests asserted the nlq profile exposes a
tool named "search"; it is now "semantic_layer_search". embedding_next
deliberately keeps the general nlq-search tool (switching embedding customers
to a curated-only layer that starts empty was not in scope), so the
matches-nlq invariant test now asserts the tool sets are identical modulo
that one substitution.

roborev (jobs 1916/1917):
- reuse llm-shape/escape-xml (now public) instead of a second, narrower copy
- format-embedding error message covers non-numbers too ("invalid value")
- API EntityRef :model is now an enum of the known entity types, so garbage
  refs are rejected at the boundary; the serdes :else passthrough (for rows
  predating a model string's removal) gets a test
- migration header notes the in-place changeset edit for anyone who ran the
  earlier branch revision

* Relax the entity-ref response schema to tolerate retired model strings

The write-side enum stays (garbage refs still 400 on POST/PUT), but GET
responses accept any :model string: rows can predate a model string's
retirement — serdes already tolerates those — and under dev/test response
validation a single legacy row would otherwise 400 the whole list endpoint.
(roborev job 1918)

* Drop the in-place-edit note from the migration header

The earlier revision never ran anywhere that survives (and the table name is
new on this branch anyway), so there is no checksum-mismatch audience to warn.

* Fix CI: migration 062->063, ASCII minus, mage driver-test override

* Lint with-isolated-mirror as fn, not let (single-symbol binding)

* Address Copilot round 2: rank by blended score in SQL, PUT patch semantics, smaller nits

- search: the SQL LIMIT now orders by distance minus the verified boost
  (equivalent to the blended score), so a verified row whose boost lifts it
  into the top N is no longer cut by the raw-distance limit; covered by a
  ranking test that fails against the old ordering
- PUT: presence of a key (contains?), not nil-ness, decides what changes, so
  an explicit null clears usage_instructions; entity/verified reject null in
  the schema since the columns are non-nullable
- EntityRef write schema: id must be a positive int
- entity-refs->search-results: drop the per-card (set verified) rebuild;
  select-fn-set already returns a set
- tool instructions prose names the match/note elements without literal
  angle-bracket tags, keeping the instructions element well-formed

* Drop the unused HNSW index from the mirror table

The blended ORDER BY (distance minus the verified boost) can't be served by
an HNSW index, so since the ranking fix the index was built and maintained
but never used on the read path. An exact scan is intentional and
microseconds at curated-table scale; documented at the ranking expression
and in the index-table namespace docstring. (roborev job 1923)

* Tighten docstrings: contracts first, one sentence per line

- mirror/search shim now documents its return shape (the caller contract the
  metabot tool builds on)
- upsert-batch! claimed to return the rows; it returns the count
- format-embedding states the contract (throws on non-finite elements); the
  pgvector-chokes rationale moves to an inline comment at the check
- stale plural in the module docstring (entries map to ONE entity now)
- multi-sentence paragraphs reflowed to one sentence per line

* Bump mirror schema-version so existing tables shed the orphaned HNSW index

Dropping the index creation left tables built under version 1 carrying a
maintained-but-unused index until some other rebuild trigger. The version
bump forces the one-time drop-and-rebuild on first sync. (roborev job 1924)

* Test that a schema-version mismatch alone triggers the mirror rebuild

The version bump is the rebuild trigger the previous commit leans on; cover
it directly (stale-write the meta row, assert :rebuilt + emptied vectors
table) so dropping schema_version from the meta comparison can't regress
silently. (roborev job 1926)

* Assert the mirror rebuild self-terminates

After the rebuild cases, a follow-up ensure-tables! must return :ok — i.e.
write-meta! healed the meta row. Without this, breaking schema_version
handling in write-meta! would silently rebuild on every sync and the tests
would still pass. (roborev job 1927)

* Rename semantic-layer-search -> curated-search; tool 'search_curated', augment not replace

Drops the overloaded 'semantic layer' term (it collides with the BI metrics
layer and with 'semantic search' = embedding IR). New vocabulary throughout:

- appdb table semantic_layer_index -> curated_search_entries
  (model :model/CuratedSearchEntry); pgvector mirror -> curated_search_index
  (now the only thing called an 'index')
- modules curated-search / enterprise/curated-search; API /api/curated-search;
  serdes model CuratedSearchEntry, dir curated_search_entries
- tool var curated-search-tool, :tool-name "search_curated" (verb-first like
  the other tools; distinct from the general 'search' so the two can coexist)

Behavior: the nlq profile now offers BOTH the general search and the curated
search tool, rather than replacing one with the other. The curated tool is
gated on the :semantic-search feature (via a :feature-semantic-search
capability derived in profiles/feature-capabilities) and its description tells
the agent to prefer it, using general search as fallback/complement.

Also tightened two over-long inline comment blocks in EE core.

* Fix alphabetical ordering after the curated-search rename

The in-place sed rename left three sorted lists with curated-search/
CuratedSearchEntry in the old 's' slot:
- api_routes route-map (fails keep-routes-sorted-test) + its keep-me
- models/resolution model->namespace map
Move them to their 'c' slots. (roborev job 2041)

* Filter curated-search hydration by current-user read permissions

entity-refs->search-results fetched Tables/Cards via direct t2/select with no
permission check, so an admin-curated entry pointing at a restricted entity
could leak its name/description/db/portable_entity_id to a user who can't
access it. Filter both fetches with mi/can-read? (mirrors the transform
filter already in this pipeline). (Copilot PR review)

* Address claude-code branch review: permission-filter before take-n, locale-safe XML

- build-matches: hydrate (and thus permission-filter) the whole deduped
  candidate set, then take n — taking n first let unreadable top hits shrink
  the result below n while readable matches sat just past the cut. The
  preceding permission fix made this reachable.
- match->xml: use String/format with Locale/ROOT so %.3f always renders a '.'
  decimal separator (clojure.core/format uses the default locale; a
  comma-decimal site locale produced score="0,950").
Both covered by new regression tests. (roborev job 2042)

* Address claude-fable-5 branch review

- core_test e2e: bind a superuser around the tool calls — the permission
  filter (mi/can-read?) needs *current-user-id*, so the test was returning []
  and would fail wherever it actually runs.
- semantic-search.yml: add the curated_search EE test dir to each job's :only,
  so the pgvector-gated tests (reconcile, rebuild, e2e) actually run in CI
  instead of silently no-opping — which is why the broken e2e went unnoticed.
- dedupe-by-entity: normalize the model so a "card" and a "question" entry
  for the same Card collapse to one (both hydrate to one record).
- ordering: move CuratedSearchEntry / curated-search to their alphabetical
  slots in exported-models, mage driver-affecting-overrides, and the kondo
  lint-as map (+ column alignment).
(roborev job 2048)

* Address claude-fable-5 review: schedule sync independent of feature flag, harden hydration + prompt

- sync task: schedule the Quartz job whenever pgvector is configured (boot-fixed),
  not gated on the semantic-search feature. The job body already self-gates, so
  this keeps the periodic safety net + the write-path trigger's target job alive
  when a license is enabled after startup (otherwise the mirror silently never
  syncs while the tool is offered). New pgvector-configured? predicate.
- card-refs->results: emit one record per ref so a card registered under two
  type strings no longer collapses (last-type-wins) and drops a match.
- API: search_prompt is NonBlankString on POST/PUT — reject blank prompts
  (meaningless embedding + degraded serdes slug).
All covered by new tests. (roborev job 2110)
2026-06-20 00:07:54 +02:00
github-automation-metabase
8b90dc2110 Auto-update documentation for master (#76193)
Update generated docs (master)

Co-authored-by: github-actions <github-actions@github.com>
2026-06-19 17:31:48 -04:00
Mihael Konjević
b907ae761d Make SQL guardrail skills always-on (#76176)
* Make SQL guardrail skills always-on

The on-demand skills system demoted read_resource and the SQL
create/edit/replace guidance from always-present system-prompt content to
catalog-only skills the agent had to load itself. With the guardrails gone
from the prompt, the SQL profile would loop read_resource calls (no
"drill, don't re-search"/"honor truncation" rules) and fire redundant
edit_sql_query calls instead of one replace_sql_query (no edit-vs-replace
guidance).

Mark read-resource, create-sql-query, edit-sql-query, and replace-sql-query
as always-on so their bodies are inlined into the prompt prefix again, while
keeping the bulky rarely-used skills on-demand. Harden load_skill
registration to fire when the manifest has any catalog or always-on skills,
so the dialect-preload invariant no longer depends on read-resource sitting
in the catalog.

* Make ask-for-sql-clarification always-on to restore SQL termination

The :sql profile is :required-tool-call?, which maps to Anthropic
tool_choice {:type "any"} — the model is forced to emit a tool call on
every turn and can never stop on free text. The agent loop only terminates
on max-iterations or a tool result carrying :final-response?. Among the SQL
profile's tools, ask_for_sql_clarification is the only one that sets it, so
it is the model's de facto termination signal.

The skills commit (ec842e1) moved the clarification guidance from the
always-inlined tool instructions to a catalog-only on-demand skill. Its
content was unchanged, but it was no longer present in the prompt, so the
model lost awareness of its terminal/handoff role and instead spun on
read_resource until hitting max-iterations (observed: a single edit_sql_query
followed by 19 redundant read_resource calls).

Mark the skill always-on so its guidance is inlined again, restoring the
pre-commit behavior. Together with the other SQL guardrail skills, the
:sql profile's catalog is now empty (all guidance inline, as before);
load_skill stays registered via the manifest's always-on entries so dialect
preload keeps working.

* Exclude always-on skills from the loadable/advertised skill set

Always-on skill bodies are already inlined in the system prompt, so the
model must neither see them in the catalog nor be able to load_skill them.
The catalog already removed them, but record-loadable-skill-ids! still
recorded every visible skill, leaving always-on ids loadable — so the agent
could burn an iteration re-fetching a skill it already has inline.

Record only the on-demand (non-always-on) skills as loadable, and build the
catalog from that same set.

* Make always-on a per-profile decision instead of a skill-global flag

A skill's always-on/on-demand status was a boolean on the skill itself, so it
applied to every profile exposing the matching tool. That is wrong: the SQL
profile wants its SQL skills inlined on every turn, but the internal profile
(which shares read_resource/create/edit/replace_sql_query) wants them
on-demand to keep its prompt prefix lean.

Move the decision to the profile: a profile lists :always-on-skills (skill
ids) whose bodies are inlined; every other relevant skill stays on-demand in
the catalog. build-skill-manifest now partitions on the profile's set rather
than the skill's flag. The skill-level :always-on frontmatter is removed, and
register-profile! validates that :always-on-skills resolve to real skills.

The :sql profile inlines read-resource + the create/edit/replace/clarification
SQL skills; no other profile opts in, restoring their pre-skills on-demand
behavior. Adds tests for the per-profile split and for always-on bodies
actually appearing in the rendered system prompt.

* Don't render the load_skill catalog header when the catalog is empty

Selmer treats an empty vector as truthy, so a profile whose skills are all
always-on (empty catalog) still rendered the "# Available skills … load the
skill(s) you need with load_skill" header with nothing listed — nudging the
model into pointless load_skill calls. Pass the catalog through not-empty so
an empty catalog is nil (falsy) and the header is omitted.

* Let a profile mark tools terminal; end :sql turn after a successful write

Under :required-tool-call? the model is forced to emit a tool call every
turn and can only stop on max-iterations or a :final-response? result. After
a clean edit_sql_query the SQL profile had no terminal tool to reach for, so
it spun on read_resource to max-iterations (e.g. 1 edit + 19 redundant reads).

Add a per-profile :terminal-tools set: a *successful* call to one of these
tools ends the turn. Success is detected by the presence of :structured-output
(the query/chart tools attach it only on success, returning just an error
:output otherwise), so a failed edit still lets the model self-correct.
Terminality is per-profile — the same write tools stay non-terminal in
profiles like :internal that need multi-step flows.

The :sql profile marks create/edit/replace_sql_query terminal. register-profile!
validates that :terminal-tools refer to tools the profile exposes.

* Replace tool-level :final-response? with per-profile :terminal-tools

Terminality was expressed two ways: the new per-profile :terminal-tools and
the older tool-level :final-response? flag (set by ask_for_sql_clarification
and the document_construct_*_chart tools). Two mechanisms for one concept —
and, like always-on on skills, the tool-level flag couldn't vary by profile.

Consolidate on :terminal-tools. Both tools already pair their terminal result
with :structured-output (failures return only :output), so success-gated
:terminal-tools is behaviour-preserving:
- :sql adds ask_for_sql_clarification to its terminal set.
- :document-generate-content marks document_construct_model_chart and
  document_construct_sql_chart terminal (schema collection stays preparatory).

Remove :final-response? from the tools and drop has-final-response? from the
loop. No frontend/persistence consumer read the flag.
2026-06-19 23:28:14 +02:00
Uladzimir Havenchyk
3f54ca2ce3 chore: replace more deprecated buttons with mantine buttons (#76051)
* chore: replace more deprecated buttons with mantine buttons

* cleanup

* fix button size

* fixup

* fixup

* fixup

* fixup

* fixup

* fixup

* chore: replace more deprecated buttons with mantine buttons

* fixup

* apply suggestion

* fix test
2026-06-19 21:05:54 +00:00
appleby
951e37d922 Normalize row charts before sending to metabot in chart configs (#76102)
* Normalize row charts before sending to metabot in chart configs

* Validate chart configs in analyze-chart-tool
2026-06-19 13:08:35 -07:00
Riley Thompson
93954e82de Exclude remapped columns from saved question return columns (#75931)
exclude remapped columns from saved quesiton return columns
2026-06-19 15:59:43 -04:00
Riley Thompson
ff472d84da Re-enable test and clean up fixmes (#75963)
* re-enable data-editing-requires-describe-features-test

* remove trivial fixmes

* set nested-field-columns to false for mariadb

* check for not maria db
2026-06-19 15:59:26 -04:00
Eric Normand
f5e0129bf6 Show success confirmation when remote sync import/export completes (GHY-3747) (#76099)
* Show success confirmation when remote sync import/export completes (GHY-3747)

Remote sync import/export can take a while, so the progress modal now stays
open on success showing a confirmation message and a Close button, instead of
silently auto-dismissing.

The task carries a general-purpose `message` column (reusable beyond success)
populated from the sync result on completion and exposed via GET /current-task.
The modal renders the server message, falling back to generic copy when none is
provided.

* Store sync result as structured outcome, render copy on the client (GHY-3747)

Instead of storing customer-facing copy in remote_sync_task, store a structured
outcome map (e.g. {:kind "pulled" :count 12 :branch "main"}) and let the UI map
it to a localized message. This keeps copy out of the database and renders it in
the viewer's locale rather than freezing the worker thread's locale at write time.

- Migration: remote_sync_task.message -> outcome (JSON)
- complete-sync-task! takes an outcome map (multi-arity); :outcome JSON transform
- impl success paths return :outcome data; drop the tru strings
- Frontend: RemoteSyncOutcome union, modal maps kind -> copy, falling back to
  generic per-task-type copy when the shape isn't recognized

* Drop the no-auto-dismiss middleware test (GHY-3747)

It asserted the absence of the removed auto-dismiss behavior and needed a
subscribe:false workaround to avoid an invalidation refetch loop. The success
state (renders with a Close button, no auto-dismiss) is covered by the
SyncProgressModal component tests.

* Refactor.

* get rid of silly comment

* Test per-kind fallbacks for malformed sync outcomes (GHY-3747)

Cover the kind-specific fallback branches in getSuccessMessage when a known
outcome kind is missing its fields, including the combined pull-and-push copy
for a malformed merged outcome.
2026-06-19 19:33:58 +00:00
Riley Thompson
c95bba80cb Use scanner over regex in make-nestable-sql (#75970)
* use scanner over regex in make-nestable-sql

* clean up
2026-06-19 14:38:57 -04:00
lbrdnk
748eeb1ce7 Fix agent api /query pagination (#76013)
* Fix results pagination

* Adjust description
2026-06-19 20:35:59 +02:00
Anderson
22b1e3d54c Fix native time grouping ordinal labels (#76047)
* Fix native time grouping ordinal labels

* Address review
2026-06-19 15:20:12 -03:00
Sloan Sparger
94dc98834e [Metabot] Add metabot message validation schemas (#75546)
* add malli schemas for ai-sdk v4 + v5/v6 message formats

* add disposable v4 validation endpoint

* add fn to handle historically invalid v4 messages, remove endpoint, add comment form for validation

* split spec version up into files

* automated clean up pass

* v4 naming improvements, v5+ snake case conversion, small correctness changes

* remove ai sdk v4 format given our internal implementation was so incorrect, move to v1 + v2 file names

* tighten types a bit

* remove code comments

* flip v2 schema keys to spec-faithful camelcase

* clean up

* add helpers

* copilot feedback

* impl PR feedback

* second round pr feedback
2026-06-19 18:04:45 +00:00
Denis Berezin
da6c396006 UXW-3079 Add date format settings for Trend viz (#76130)
* UXW-3079 Add date format settings for Trend viz

* Fix CI

* Review suggestions
2026-06-19 20:52:31 +03:00
lbrdnk
07853910a8 Enable searching for models through agent api (#76076) 2026-06-19 19:41:36 +02:00
Sloan Sparger
3fc052ed12 [Metabot] Don't send query in user is viewing context for questions without a data source (#75569)
* ensure there is a data source before registering query context

* disambiguate validation error message

* add extra test
2026-06-19 17:35:59 +00:00
Jeff Bruemmer
bc5719510d docs - rephrase SSO note (#76181)
rephrase
2026-06-19 13:16:20 -04:00
Mahatthana (Kelvin) Nomsawadi
3e09ab817b docs: add embedding telemetry transparency section (#76069) 2026-06-19 11:54:13 -04:00
Phoomparin Mano
03ed418f80 Fix sensible visualization options in MCP Apps visualization selector (#75876)
* fix visualization selector showing illegal visualizations

* reset the stored default display when loading a new query

* refactor: cleanup logic to capture default display

* update unit test name to be clearer

* add unit test to captureDefaultDisplay

* update prompt in MCP resource to not mention display types or viz settings

* do not accept stale query results after query changes
2026-06-19 15:53:53 +00:00
Anderson
4cc540400e Fix pie chart Other slice drill-through (#75938)
* Fix pie chart Other slice drill-through

* Limit grouped pie drill-through actions

* Add e2e test to account for the Other slice drill through options

* Address metamben's
2026-06-19 15:29:38 +00:00
Copilot
69a279d4ad docs: add driver removal steps and required driver exception (#75870) 2026-06-19 11:05:05 -04:00
Nicolò Pretto
598fc88b68 feat(sdk): Custom visualizations in the Embedding SDK (#75920)
* Add custom-viz plugin support to the embedding SDK

Wire the SDK to load EE custom-visualization bundles. The core loader gains a
`sandboxMode` so the SDK can run plugins in an `about:blank` sandbox, fetches
bundles through the authenticated `api.fetch` client, and exposes
`unregisterCustomVizDisplay` / a `loadCustomVizPluginForDisplay` slot so a saved
`custom:*` question keeps its display instead of resetting to a built-in viz.

No allowlist yet: any installed custom-viz plugin loads.

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

* Gate SDK custom-viz behind allowedCustomVisualizations

Add the `allowedCustomVisualizations` MetabaseProvider prop and gate every
custom-viz plugin slot (load, auto-load, list, icon) on it: only listed plugin
identifiers load, and a display dropped from the allowlist is unregistered so
the question falls back to a built-in visualization.

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

* Add initialVisualization prop to SDK questions

Let host apps override the saved display when a question loads via an
`initialVisualization` prop on InteractiveQuestion/StaticQuestion. Accepts
built-in chart types and `custom:*` displays; the custom plugin is loaded
concurrently with the query and the prop falls back to the saved display when
the requested one isn't available or allowed.

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

* Show custom visualizations in the SDK chart-type picker

Eagerly load the allowed custom-viz plugins so their displays register in the
global visualizations map and appear in the chart-type dropdown, mirroring the
main-app ChartTypeSidebar. Lets users switch a question to a custom viz from
the picker.

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

* Support loading icons via blobs in the sdk

* Update enterprise/frontend/src/embedding-sdk-ee/custom-viz/initialize.ts

Co-authored-by: Kamil Mielnik <kamil@kamilmielnik.com>

* Update enterprise/frontend/src/embedding-sdk-ee/custom-viz/initialize.ts

Co-authored-by: Kamil Mielnik <kamil@kamilmielnik.com>

* Update enterprise/frontend/src/metabase-enterprise/custom_viz/sandbox/distortions-dom-read.ts

Co-authored-by: Kamil Mielnik <kamil@kamilmielnik.com>

* fix icon in collection browser

* use more specific types instead of "number"

* drop call site from code comment

* remove describeNode (unused) and unused imports

* change `allowedCustomVisualizations` to require `custom:` prefix

* warn the host app dev when they pass down plugins that we don't find in the instance

* temporarily disable initialVisualization

* update e2e after the removal of console.error

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: Kamil Mielnik <kamil@kamilmielnik.com>
2026-06-19 16:49:57 +02:00
Nick Fitzpatrick
9228b95e0b Fix flaky template-tags transform test by waiting on the save request (#76157)
The undo-toast assertions ran immediately after clicking Save, racing the
PUT /api/transform/* round-trip. Wait on the existing @updateTransform intercept after each Save
2026-06-19 19:36:33 +05:30
Copilot
23c363b9af docs: document auth method switching behavior for existing accounts (#75900) 2026-06-19 09:51:40 -04:00
Alexander Polyankin
e615ca6f97 Fix memory leak with notifications and GraalVM (#76145)
* Fix memory leak with table notifications

* fix
2026-06-19 09:32:19 -04:00
Uladzimir Havenchyk
a57898c7c3 chore: replace more deprecated buttons with mantine buttons (#75903)
* chore: replace more deprecated buttons with mantine buttons

* cleanup

* fix button size

* fixup

* fixup

* fixup

* fixup

* fixup

* fixup

* apply suggestion

* fixup
2026-06-19 12:42:52 +00:00
Sébastien
7dc9d844b3 Fix flaky editable-dashboard create-question e2e test (#76011) 2026-06-19 13:48:22 +02:00
Romeo Van Snick
8948318340 Convert mode.js to TypeScript (#76135) 2026-06-19 20:52:00 +10:00
Oleh K
f399a41952 Fix find-never-defined-css-variables for multi-line and whitespace var() usages (#76054)
* GDGT-2642 Fix find-never-defined-css-variables for multi-line and fallback var()

The CSS-variable lint only matched contiguous `var(--x)`, so any whitespace,
newline, or fallback between `var(`, the name, and `)` silently defeated
detection. Tighten the usage regex to `var(\s*(--name)\s*[,)])` so it catches:

  - multi-line:        var(\n  --foo\n)
  - inner whitespace:  var( --foo )
  - fallback syntax:   var(--foo, red)

Requiring a trailing `)`/`,` also skips dynamic `var(--mb-color-${x})` template
usages we can't statically validate. A `var(--x, fallback)` is treated as safe
unless `--x` is one of our `--mb-*` design-system primitives, which must always
be defined (a fallback would silently mask a typo or a dropped backport).

Add unit tests covering the bare, whitespace, multi-line, fallback, nested,
mb-with-fallback, and dynamic-interpolation cases.

The tightened lint surfaced several latent bugs, now fixed:
  - EmbedFrame: `--mb-color-background-tertiary-inverseer` typo -> `-inverse`
  - ThemeEditor PreviewPanel: nonexistent `--mb-radius-md` -> `--mantine-radius-md`
  - Switch: `--mb-color-accent-3` typo -> `--mb-color-accent3` (invisible error border)
  - Select: removed dead `.Select` rule and `--select-item-*` declarations that
    referenced variables never defined by Mantine or our theme

Also pruned the knownIssues whitelist from 10 entries down to 2 (only the
genuinely Mantine-provided `--button-bg` and runtime-generated
`--mantine-color-accent-gray-light-filled` remain).

* Clarify why --mantine-color-accent-gray-light-filled is allow-listed

getMantineThemeColors registers the color; Mantine derives the -filled variant
var from it at runtime, so it's absent from the static styles.css we scan.

* Add test for mb-* fallback wrapper with nested bare var

Mirror of the non-mb-wrapper case: an mb-* var carrying the fallback is still
validated, and the nested bare var is too, so both are extracted.

* Remove comment
2026-06-19 12:22:58 +02:00
Nick Fitzpatrick
194821f222 Apply column formatting to static viz map legend, add render to side (#76024)
* Apply column formatting to static viz map legend, add render to side

* PR Feedback
2026-06-19 14:27:28 +05:30
Nicola Mometto
fe44abd20a More generic error message on transform timeout (#76071)
chore: don't leak impl detail on error message
2026-06-19 08:49:53 +00:00
Fraser
24ca0fe913 Error for files that aren't in modules and enforce remaining modules (#76126) 2026-06-19 13:59:48 +12:00
Alexander Polyankin
1c12b1931d BigQuery - sample-table with adaptive page size (#76068) 2026-06-18 23:41:36 +00:00
Timothy S. Dean
28d0a1c5a5 Drain stale dependency entities oldest-first to prevent starvation (#76118)
The dependency entity-check job re-analyzes stale entities in batches. Among entities that are equally stale, the order they're selected in is arbitrary. When the stale backlog is larger than one batch, the same subset can keep getting picked while others are repeatedly passed over — so some stale entities can go unprocessed run after run.

### Solution

Select stale entities oldest-analyzed-first. Each entity that's just been analyzed moves to the back of the line, so the job round-robins through the whole backlog and every stale entity is reached.
2026-06-18 17:23:27 -06:00
Timothy S. Dean
c6be4cae58 Clear the stale flag for entities whose database can't be resolved (#76119)
The dependency entity-check job analyzes each stale entity and records a finding, which clears its stale flag.

If an entity's database can't be resolved — and there's no prior error that already explains why — analysis silently does nothing. The stale flag is never cleared, so the entity is re-selected and re-analyzed on every run, forever.

### Solution

Record a terminal error finding for that case, which clears the stale flag and explains why the entity couldn't be analyzed. If its database later becomes resolvable, the entity is analyzed normally again.
2026-06-18 17:23:00 -06:00
Ryan Laurie
0ccaefe55c Auto Stress Test (#76034)
* auto stress test

* better options

* double test

* variable burn

* less ai comment

* less ai comment
2026-06-18 23:18:40 +00:00
Nemanja Glumac
ac0c1c3d3e Add ci-conductor (dry run) quarantine gate for e2e tests (#76014) 2026-06-18 23:56:34 +02:00
github-automation-metabase
366f27d2f0 Auto-update documentation for master (#76120)
Update generated docs (master)

Co-authored-by: github-actions <github-actions@github.com>
2026-06-18 21:50:47 +00:00
dpsutton
a57027861f Fix OOM in table-sync permission setup by SELECTing DISTINCT (#76077) (#76100)
When the sync-and-analyze job creates new tables, `set-default-table-permissions!`
calls `load-perm-context`, which loaded *every* table-level `data_permissions`
row for the database to figure out, per (group, perm-type, schema), the set of
distinct permission values already in use. The result set grew with the table
count, so on databases with very many tables it materialized millions of rows
(2.5M+ `org.postgresql.core.Tuple` / `toucan2.instance.Instance` in the heap
dump that prompted this) and OOM'd the JVM on a scheduler thread.

`schema-vals-idx` only ever needs the *distinct* (group_id, perm_type,
schema_name, perm_value) tuples — it reduces the rows into a set keyed by
(group, perm-type, schema), so duplicate rows were already being collapsed in
memory. Pushing that DISTINCT into SQL makes the loaded set bounded by
groups × perm-types × schemas × values instead of growing with table count.

Rows loaded by the introspection query (measured; one perm-type, one schema):

    groups  tables   before (groups×tables)   after (DISTINCT)
      5       10              100                    20
      5      100            1,000                    20
      5    1,000           10,000                    20   <- flat across tables
     10      100            2,000                    40
     50      100           10,000                   200   <- linear in groups

Before, the result scaled with the table count (the thing that blew up); after,
it is flat across table count and grows only linearly with the number of groups.
The produced `schema-vals-idx` is byte-identical because it accumulates into a
set — verified in a regression test.

Not scoping the query to the synced tables' schemas (a further reduction):
a `schema_name IN (...)` filter would add NULL/casing correctness risk, and the
DISTINCT collapse alone removes the geometric blowup that caused the OOM.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-18 16:18:41 -05:00
Oreon Lothamer
7d485d539d run PR-Env-Stats-Dump on already labeled PRs (#76095) 2026-06-18 11:13:38 -10:00
dpsutton
718c730aa9 downgrade apache sshd-core (#76104)
Why? Because 3.0.0-M2 leaks connections.

 Revert mina-sshd 3.0.0-M2 → 2.16 to stop SSH channel leak OOMs

  3.0.0-M2 leaks one KexListener per SSH port-forward channel, never
  removed on channel close. Each Metabase DB query over an SSH tunnel
  opens and closes a `direct-tcpip` channel, so the listener list grows
  unbounded for the life of the (long-lived) SSH connection.

  Heap dump from a crashed prod instance (highway):
  - 1 SSH connection, but 67,221 closed TcpipClientChannel /
    Nio2Session / socket-channel objects retained.
  - KexFilter.listeners (a session-scoped CopyOnWriteArrayList) retained
    572 MB ≈ 38% of heap — full of AbstractChannel$$Lambda instances,
    each capturing one closed channel.

  Root cause in mina-sshd 3.x (dev_3.0 branch):
  - AbstractChannel.init() registers an anonymous KexListener on the
    session for every channel and never removes it on close.
  - AbstractSession.removeKexListener() is also broken: it calls
    addKexListener() instead of remove (copy-paste bug), so even a
    correct removal attempt adds a duplicate.

  The 2.x lineage has no KexFilter / addKexListener / per-channel KEX
  listener — the filter-chain mechanism is entirely new in 3.x — so the
  leak cannot occur on 2.16.
2026-06-18 14:01:00 -07:00
Alexander Polyankin
ddbb6d05e5 BigQuery - ignore tables and fields with long names that we cannot insert into the app db (#76074) 2026-06-18 20:41:51 +00:00
Andrei Chernykh
b04009322f Fix user provisioning getting disabled when adding a group mapping (#75829)
* Fix user provisioning getting disabled when adding a group mapping

* Improve group mappings widget layout and add autosave toasts

* Migrate GroupMappingsWidget off Emotion to Mantine and drop deprecated exports

* Migrate GroupSelect off legacy Select to Mantine Combobox and trim widget CSS to style props

* Show Changes saved toast on JWT settings save and add group field placeholders for SAML and LDAP

* Fix group-mappings e2e helper for the Combobox dropdown

* Consolidate redundant OIDC group-sync and tooltip unit tests

* Give group-select options an explicit aria-label for a stable accessible name

* Scope group-mapping consistency e2e assertions to the table to avoid the portaled dropdown

* Use Text instead of Box for the delete-mapping modal heading and subtitle

* Refactor delete-mapping modal to use Mantine Modal from metabase/ui

* Migrate deprecated Button and Radio to metabase/ui in the group mappings widget
2026-06-18 12:14:43 -07:00
Nick Fitzpatrick
6d294e5f4d Further pdf export improvements (#76016)
* use cssText

* include font props on <text>, <tspan>, and <textPath> nodes

* re-apply SVG transform after cssText copy in html2canvas patch

Chrome's getComputedStyle().cssText is empty, so the cssText copy wiped the Leaflet grid SVG's transform and offset its serialized bounds, re-breaking the #68751 PDF-export grid fix. Re-apply transform/transform-origin/transform-box after the cssText copy; Firefox keeps the bulk-copy perf win. Re-enable the GridMapPdfExport loki test with its baseline reference.

* resolve vars in svg props

* fix hidden row chart axis labels

* gauge value positioning

* fix gauge chart labels

* re-skip grid map loki test
2026-06-18 23:54:41 +05:30
Nathan Voxland
4181df4429 Include dashId in downloaded diagnostics (#75803)
* Include dashId in downloaded diagnostics

* e2e test

---------

Co-authored-by: Nick Fitzpatrick <nickfitz.582@gmail.com>
2026-06-18 23:50:40 +05:30
Eric Normand
c70f62de5c Incremental remote-sync import: load only changed entities on pull (GHY-3779) (#75897)
* Add git changed-files primitive for incremental remote-sync import

changed-files diffs two commit trees with jgit's ANY_DIFF filter,
returning {:added :modified :deleted} path sets. jgit prunes unchanged
subtrees during the walk, so cost is proportional to the number of
changed entries rather than the size of the tree. Returns nil when the
base commit is unresolvable or orphaned (force-push/rebase), signalling
callers to fall back to a full import.

This is the change-detection primitive for making import/pull cost
proportional to what changed (GHY-3779).

* Add differential equivalence harness for incremental import

Establishes the full reload (load-snapshot!) as the oracle for incremental
import: a correct incremental import must leave the app DB, RemoteSyncObject
table, transforms setting, and version pointer in exactly the state a full
import would. Rather than assert hand-computed expectations, the harness runs
both paths against the same change and asserts identical resulting state.

import! provides the seam: :force? true always takes the full path (oracle),
:force? false is the path under test (full today, incremental once GHY-3779
lands). The state vector is pk-independent so delete+recreate doesn't produce
false diffs. Covers no-op / edit / add / delete card scenarios; the
rename/move/delete-collection/transform cases come with the incremental path.

GHY-3779.

* Incremental import fast-path: load only changed entities on pull

On a subsequent (non-first, non-forced, non-dirty) import, load only the
entities whose files changed since the last imported version instead of
deserializing and upserting the entire snapshot.

- Diffable protocol + source.p/changed-files wrapper: git diffs two commit
  trees; the in-memory versioned test source diffs its trees; everything else
  returns nil (no diff available) and falls back to full.
- incremental-load-snapshot!: loads only added/modified files (deps resolve
  from the app DB), deletes only genuinely-removed entities, and reconciles
  just the affected RemoteSyncObject rows. Renames are matched by entity_id, so
  a leaf rename updates in place rather than delete+recreate. Skips the full
  backfill and reindex that the whole-snapshot load runs.
- import! tries the fast-path and falls back to the full load-snapshot! for
  anything structural: first import, force/dirty (only full truly discards
  local drift), an unresolvable base (force-push/rebase), a deleted file with
  no recorded path, or a changed Collection/feature model (v1 scope). Also
  hoists the no-op version-skip ahead of conflict detection so an unchanged
  pull reads nothing.

The differential harness now drives the fast-path behind force? false and
proves it equals the full oracle for no-op / edit / add / delete / rename of
leaf content. (The harness caught a real rename bug during development.)

GHY-3779.

* Update search index per-entity on incremental import

The incremental load skips the whole-appdb reindex, so keep the search index
consistent at a cost proportional to the change: after the reconcile commits,
search/delete! the genuinely-removed entities and search/update! the loaded
(added/modified) ones. Adds search to the enterprise/remote-sync module :uses.

Covered by a test asserting only the changed entity is re-indexed, not the
whole synced set.

GHY-3779.

* Extend differential harness with fast-path assertions and fallback scenarios

run-differential! now reports which path the under-test import took, so every
scenario asserts the v1 scope boundary explicitly:
- leaf changes (no-op / edit / multi-edit / add / delete / rename) run
  :incremental and match the full oracle;
- structural changes (collection rename, collection delete with contents) fall
  back to :fallback (the full import) and still match the oracle.

GHY-3779.

* Improvements

* Drop redundant search/update! on incremental import; rely on serdes load hooks

Serdes load already re-indexes added/modified entities: its t2 insert!/update!
fire the :hook/search-index after-insert/after-update hooks, which call
search/update!. So the explicit per-entity search/update! in the incremental
path was redundant double-work — remove it. Deletes have no such hook, so the
explicit search/delete! for removed entities stays.

Tests: replace the live appdb search-index integration test (its index-tracking
state is order-sensitive across tests in a shared JVM, causing flakiness) with a
stable call-level assertion that search/delete! is invoked with the removed
entity's id. The differential harness + update call-spy continue to cover the
rest. Disable index maintenance in the non-search scenarios so their async
ingestion can't interfere.

GHY-3779.

* Flatten import! decision tree and fix incremental/merge fallback bugs

Refactor the remote-sync import path into flat cond-based decision trees
that read top-to-bottom, and fix correctness/perf issues surfaced along
the way:

- import! / incremental-import-plan / import-merged!: replace nested ifs
  with flat conds (one predicate -> one action per clause).
- incremental-import-plan: guard the diff call so a first import (nil
  last-version) returns the fallback sentinel instead of NPEing on a real
  git source (resolve(nil)).
- import! and import-merged!: compute the expensive conflict scan and
  3-way merge lazily (delay), so no-op pulls and the nil-base / force /
  merge paths don't pay for a full-tree read, and the nil-base merge
  returns its :conflict result instead of throwing.
- Consolidate the repeated full-reload success result via a local
  full-import! closure; route finalize! and the result through the bound
  snapshot-version.
- Make incremental-load-snapshot! private; inline handle-import-exception
  into import!'s catch; refactor prog1 calls to do/let.
- Add a first-import-no-force test (incremental fast-path must not run on
  a first import) and fix the path-detection spy to compare against the
  current sentinel var.

Pre-existing conflict-fixture failures in impl_test are unaffected.

* Batch per-entity deletes and search-index removals in incremental import

incremental-load-snapshot! removed entities (and their search-index
entries) one row at a time. Batch both by model type:

- entity deletes: one (t2/delete! model-key :id [:in ids]) per model
  instead of per row. Toucan2 fires before-delete per matched row even
  for an :in delete, and the Card/Dashboard before-delete cascades are
  row-independent, so behavior is preserved. Still inside the existing
  reconcile transaction.
- search-index removal: one search/delete! per model type (it already
  takes a collection of ids).

The remaining per-row lookups (deleted file_path -> RemoteSyncObject,
RemoteSyncObject -> entity_id) are left as-is; they're bounded by the
number of deletions in a single pull.

* Tag remaining incremental-import N+1 queries with comments

Note the two per-row lookups left un-batched in the incremental import
path (deleted file_path -> RemoteSyncObject, and RemoteSyncObject ->
entity_id) and why: both are bounded by the number of deletions in a
single pull, and batching either has real downsides (long file_path IN
clauses; per-model-key IN grouping).

* Reorder import! so the incremental path skips the conflict scan

After merging GHY-3900, blocking-conflicts was computed before the
incremental fast-path, re-introducing a full-tree get-conflicts scan on
every changed pull and undercutting the constant-time incremental win.

Reorder import!'s cond so the incremental clause sits ahead of the
conflict gate: an incremental load touches only changed files and can't
wholesale-delete unsynced transforms, so it needs no conflict scan and
forces only the cheap O(changes) diff. The conflict gate and full reload
fall to the bottom, so every full-reload path (forced, dirty, first
import, structural) is still gated. force? keeps no standalone branch —
it stays off the incremental path and flows through the gate so
force-deletion? semantics hold.

Also defer the get-conflicts scan behind an inner delay so it runs only
when a gate is open (a forced import with force-deletion? true skips it),
and inline the now single-use full-import! body into :else.

* refactor
2026-06-18 17:04:02 +00:00
lbrdnk
928e9098e2 Add pagination to read_resource (#74966)
* Add pagination to read_resource tool

* kondo

* Review remarks
2026-06-18 18:31:43 +02:00
Nathan Voxland
73cd4c7c1e Pass scopes through the oidc check function (#75416) 2026-06-18 11:20:38 -05:00
Sébastien
5ac6536012 test(sdk-bundle): Fix flaky e2e test (data picker) (#76057) 2026-06-18 17:42:28 +02:00
Nemanja Glumac
42e75a07ba (chore): Point ci-conductor reporter at a base-URL secret (#76067)
Replace the CI_CONDUCTOR_WEBHOOK_URL secret (which held the webhooks base)
with CI_CONDUCTOR_BASE_URL holding the bare origin, and have the reporter
build ${base}/webhooks/failed-tests. This lets each consumer append its own
path.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-18 17:39:17 +02:00
Anderson
11de545b4b Fix public pivot table downloads (#76023) 2026-06-18 11:52:24 -03:00
Anderson
8894b2a7eb Fix conditional formatting for mini bar cells (#76025) 2026-06-18 11:51:37 -03:00
Anderson
6ea899e4b0 Fix progress Goal input styles / Convert ChartSettingFieldPicker to typescript (#75916)
* Fix progress goal input chevron alignment

* Convert components to typescript and css modules / Remove ghost dropdown caret

* Convert test file to ts

* Address Nick's comment
2026-06-18 11:49:54 -03:00
Nemanja Glumac
f35c54150c Harden the flaky text fix command (#76005) 2026-06-18 15:53:00 +02:00
github-automation-metabase
8cfe03b28c Auto-update documentation for master (#76036)
Update generated docs (master)

Co-authored-by: github-actions <github-actions@github.com>
2026-06-18 09:14:18 -04:00
lbrdnk
9331d39f46 Stamp types on integer id field clauses in resolve-query (#75998)
Stamp types on field clauses after resolve

lib.normalize does not inject type info from the metadata provider.
Add annotate-field-types pass in resolve-query to fill this gap for
all [:field opts integer-id] clauses missing :base-type.
2026-06-18 14:35:31 +02:00
Maz Ameli
3f26fa8e53 Fix capitalization of "View schema" table action label (#76035)
Change "View Schema" to "View schema" in the data model table actions
menu and update the affected unit and e2e tests.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-18 11:44:58 +00:00
Nicola Mometto
f0fc22bb27 Add BE endpoints for job run history (#75926)
* feat: link transform runs with their parent job

* feat: allow storing job-run-id

* add endpoints

* tests

* fix

* missing remark

* fix: add to schema

* fix schema

* fmt

* kondo

* fix test

* allow filtering by start-time and run-method

* tests

* chore: use read-check

* backfill job run ids

* chore: don't alias

* perf of the migration

* realias, add mysql/h2 versions, remove rollback

* chore

* prefilter on run_method
2026-06-18 12:02:25 +01:00
Fraser
8e2c0cc178 Remove legacy SettingsApi service (#76046) 2026-06-18 21:12:32 +12:00
Oleh K
94144e3411 Add KeyboardShortcut component and restyle Kbd (#75895)
* WIP: restyle Kbd from Figma + disabled state and showcase

Restyle the Kbd component to the GDGT-2473 Figma spec: flat surface
fill, no border/shadow, 4px radius, Lato Medium 12px. Add a thin
metabase/ui wrapper exposing a `disabled` boolean prop, a CSS `:hover`
state, and a Storybook showcase matrix.

* Add sequential shortcut examples to Kbd showcase

* Add KeyboardShortcut component, simplify Kbd, migrate palette

Per design discussion: drop Kbd's hover/disabled states (Kbd is now just a
restyled building block), add a KeyboardShortcut component that composes Kbd —
simultaneous keys adjacent (no "+"), sequential steps joined by a localized
"then", with a canonical modifier order and symbol/casing normalization. Migrate
the command-palette shortcuts modal to it (replacing its local renderer) and
list multiple shortcuts comma-separated.

* Add KeyboardShortcut Overview story to Loki visual regression tests

* Render Shift as a word in KeyboardShortcut, not a symbol

Per design: drop the SHIFTKEY (⇧) mapping so Shift always renders as the word.

* Extract KeyboardShortcut key parsing to utils with unit tests

Move formatKey/parseShortcut into a colocated utils.ts and cover them with unit
tests (each formatKey branch + chord/sequence/modifier-ordering for parseShortcut).
2026-06-18 08:59:18 +02:00
Romeo Van Snick
66a53ed09b Move SessionApi to RTK query hooks (#76045)
* Add session RTK Query mutations

* Migrate auth thunks to session RTK mutations and remove SessionApi
2026-06-18 15:40:55 +10:00
Romeo Van Snick
21a319ed95 Remove simple services API's (#75866)
* Move `FrontendErrorsApi` to RTK hooks and update callers

Replace the legacy `FrontendErrorsApi.report` service with a
`reportFrontendError` RTK Query mutation. The two callers are class-based
error boundaries (`componentDidCatch` requires a class), so each gets a thin
functional wrapper that calls `useReportFrontendErrorMutation` and passes a
bound `onReportError` callback down to the inner class component.

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

* Move `UserApi` to RTK hooks and update callers

Add `getCurrentUser` and `updateUserModalQbnewb` endpoints to the user RTK
API (`UserApi.list` was already covered by `listUserRecipients`) and remove
`UserApi` from services.js.

Component callers use the hooks directly (`UserNameDisplay` via
`useListUserRecipientsQuery`); thunk and imperative callers dispatch through
`runRtkEndpoint`, matching the existing redux/api migration pattern.

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

* Move `SetupApi` to RTK hooks and update callers

Replace the legacy `SetupApi.create` service with a `createSetup` RTK Query
mutation. The sole caller is the `submitUser` setup thunk, which dispatches it
through `runRtkEndpoint` so its existing try/catch error handling is preserved.

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

* Move `PersistedModelsApi` to RTK hooks and update callers

The `persistApi` already had matching `enablePersist`/`disablePersist`/
`setRefreshSchedule` mutations, but they were unused and `setRefreshSchedule`
pointed at the wrong URL (`set-refresh/schedule` instead of the backend's
`set-refresh-schedule`). Fix that URL and wire `ModelPersistenceConfiguration`
onto the hooks, using `.unwrap()` so the existing error-toast handling still
fires on failure. Remove `PersistedModelsApi` from services.js.

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

* Move `PermissionsApi` to RTK hooks and update callers

Add the data-permissions graph endpoints (`getPermissionsGraph`,
`getGroupPermissionsGraph`, `getDatabasePermissionsGraph`,
`updatePermissionsGraph`) to `permissionApi`. All callers are thunks or
imperative hook callbacks, so they dispatch through `runRtkEndpoint` (which
preserves the legacy fetch-every-time behavior and cleans up the query
subscription). Remove `PermissionsApi` from services.js.

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

* Move `ParameterApi` to RTK hooks and update callers

The `parametersApi` already had matching `getParameterValues`/
`searchParameterValues` query endpoints. Route the `fetchParameterValues`
thunk's `loadParameterValues` through `runRtkEndpoint` and remove
`ParameterApi` from services.js.

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

* Move `StoreApi` to RTK hooks and update callers

Add a `getTokenStatus` query to `premiumFeaturesApi` (the token-status GET
that lived in `StoreApi`) and route `useLicense`'s status fetch through
`runRtkEndpoint`, preserving its 404-specific error handling. Remove
`StoreApi` from services.js.

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

* Move `RevisionsApi` to RTK hooks and update callers

The legacy `RevisionsApi.get` (`GET /api/revision/:entity/:id`) and the
existing `listRevisions` query (`GET /api/revision?entity=&id=`) both resolve
to the same backend `revisions+details` after a read-check, so route the two
revision-fetching thunks through `runRtkEndpoint` + `listRevisions`. Remove
`RevisionsApi` from services.js.

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

* Move `ModerationReviewApi` to RTK hooks and update callers

Route the moderation `verifyItem`/`removeReview` helpers through
`runRtkEndpoint` + the existing `editItemVerification` mutation (taking a
`dispatch` argument), and rework their unit tests to assert the real request
against a store-backed `fetchMock` instead of a mocked service. Remove
`ModerationReviewApi` from services.js.

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

* Move `CollectionsApi` to RTK hooks and update callers

Add `getCollectionPermissionsGraph`/`updateCollectionPermissionsGraph` to
`collectionApi` (the `graph`/`updateGraph` endpoints; `get` already existed as
`getCollection`). Route the collection-permission load/save thunks and the
error-page collection fetch through `runRtkEndpoint`. Remove `CollectionsApi`
from services.js.

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

* Move `GTAPApi` to RTK hooks and update callers

Add a `validateGroupTableAccessPolicy` mutation to `groupTableAccessPolicyApi`
for the GTAP `validate` endpoint. The `attributes` endpoint already existed as
`userApi.listUserAttributes`, so reuse it: `useUserAttributes` becomes a thin
`useListUserAttributesQuery` wrapper, and the enterprise `fetchUserAttributes`
thunk dispatches it via `runRtkEndpoint`. (`GTAPApi.list` had no callers.)
Remove `GTAPApi` from services.js.

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

* Move `PulseUnsubscribeApi` to RTK hooks and update callers

Add a `pulseApi` with `unsubscribeFromPulse`/`undoUnsubscribeFromPulse`
mutations (the unauthenticated, hash-based email unsubscribe endpoints) plus
shared `UnsubscribeRequest`/`UnsubscribeResponse` types, and route the pulse
branch of the unsubscribe page through them. Remove `PulseUnsubscribeApi` from
services.js. (Notification branch migrated separately.)

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

* Move `NotificationUnsubscribeApi` to RTK hooks and update callers

Add `unsubscribeFromNotificationByEmail`/`undoUnsubscribeFromNotificationByEmail`
mutations to `notificationApi` (distinct from the existing authenticated
by-id `unsubscribeFromNotification`) and migrate the notification branch of the
unsubscribe page onto them. Remove `NotificationUnsubscribeApi` from
services.js.

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

* Move `EmbedApi` to RTK hooks and update callers

Add `getEmbedCard`/`getEmbedDashboard` query endpoints to `embedApi` (the base
embed card/dashboard fetches) and route the embed dashboard load and the
public/embedded question loader through `runRtkEndpoint`. Remove `EmbedApi`
from services.js.

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

* Move `PublicApi` to RTK hooks and update callers

Add the base public endpoints to `publicApi` — `getPublicAction`,
`getPublicCard`, `getPublicDashboard`, `getPublicDocument`,
`executePublicAction`, `executePublicDashcardAction`, and
`prefetchPublicDashcardValues` — and route all callers (public dashboard/card/
document/action loaders, action execution, and dashcard prefetch) through
`runRtkEndpoint`. Remove `PublicApi` from services.js.

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

* Ignore promise return value

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

* Fix formatting

* Remove unused code

* Remove mention of EmbedApi

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
2026-06-18 14:19:15 +10:00
Fraser
8460bb5470 Fix unit test violations (#75919) 2026-06-18 16:10:47 +12:00
Alexander Polyankin
b0c6b77bfa Avoid duplicate app db requests in public and embedded cards and dashboards (#76026)
* In-memory entity cache for public/embed paths

* now cards

* fix

* fix

* fixes

* fix

* fix

* fix

* fix

* fix

* fix

* fix

* ffix tests

* fix
2026-06-17 16:08:21 -07:00
technomancy
28b1a1507e Improve dataset creation for Bigquery (#76031)
* Stop deleting datasets for now in bigquery.

* Don't assume the database existing means all tables exist.
2026-06-17 22:50:56 +00:00
Nathan Voxland
4b3ee24236 Store SAML relay state in db (#75887) 2026-06-17 16:54:43 -05:00
Cam Saul
391f7141bf Add Kondo linter to check for empty testing forms (#76029)
* Add Kondo linter to check for empty `testing` forms

* Kondo

* Apply suggestion from @bgrabow

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

* Apply suggestion from @camsaul

---------

Co-authored-by: Ben Grabow <ben.grabow@metabase.com>
2026-06-17 14:32:10 -07:00
github-automation-metabase
94efd72ec4 Auto-update documentation for master (#75972)
Update generated docs (master)

Co-authored-by: github-actions <github-actions@github.com>
2026-06-17 19:54:19 +00:00
Eric Normand
82544e9255 Warn that force push deletes remote-only files (GHY-3917) (#76012)
Force-pushing to a diverged remote silently deleted files that existed
only on the remote branch (content created elsewhere); the confirmation
only said it would "overwrite the remote branch."

- Compute the force-push blast radius (deleted + overwritten entities) in
  the export preflight, reusing the trial merge's already-loaded trees,
  and return it as force_push_casualties.
- Surface it in the conflict modal: a ForcePushWarning with counts and an
  expandable file list shown when force-push is selected.
- Sharpen the force-push option label and split the options into safe
  (history-preserving) and destructive groups.
- Fix history-rewritten detection: commit-sha now verifies the resolved
  object exists, so an orphaned merge base resolves to nil instead of
  throwing MissingObjectException; compute casualties without a base there.
2026-06-17 14:42:31 -05:00
Nick Fitzpatrick
e61954d29b Show empty state in Admin Table Metadata Table Picker (#75927) 2026-06-18 00:32:39 +05:30
Braden Shepherdson
358be53b46 Propagate parent collection :type only for Library types (#76020)
Fixes UXW-4520.

Previously this propagated all `:type`s other than `"trash"`, which
accidentally copied the magic `"tenant-specific-root-collection"` and
broke creating subcollections for tenants.

This flips the logic from "block only trash" to "allow only library",
which fixes this issue and should be more future-proof.
2026-06-17 18:57:38 +00:00
Anderson
d07294ea21 Fix metrics explorer e2e flakes (#75564)
* Improve metrics explorer e2e tests and try to resolve flakes (attempt 2)

* Make sure expressions data points are clickable on metrics viewer charts

* Continue work on making metrics explorer tests more reliable

* Disable devtools in chrome by default when in headless mode

* Additional anti-flakiness improvements

* Adjust useFormulaEditor.ts to recover metric identities when they are dropped while editing

* Use UI state assertion instead of wait @dataset when formula input is run / Other improvements in metrics-explorer.cy

* Remove test that is vastly covered by the other tests

* Fix metric expression name identity recovery

* Keep 'Responsive viewer controls' test order

* Add metrics picker measure coverage
2026-06-17 15:52:03 -03:00
Mihael Konjević
665fed1d4f Fix metabot construct-query bugs: string-filter options + skill gaps (#76015)
Repair layer:
- New pass merges a trailing options-map into position-1 on the N-ary
  string-search filters (contains / does-not-contain / starts-with /
  ends-with). LLMs append the case-sensitivity options as a trailing element
  (e.g. ["contains" {} <field> "@gmail.com" {"case-sensitive" false}]); because
  these clauses are variadic the fixed-arity merge-trailing-options pass skips
  them, and the stray trailing map made lib.normalize fail with a missing
  lib/uuid "Invalid output" error. A string-search value is never a map, so the
  trailing map is unambiguously misplaced options. Reuses merge-trailing-options
  and is idempotent. Tests cover each head, multi-value, keys-win, nested-in-and
  postwalk, no-ops, and idempotency.

Skills (construct-notebook-query-advanced):
- Document that a `distinct` aggregation outputs a column named `count`, so
  cross-stage HAVING filters reference `["field" {} "count"]`, not "distinct".
- Add guidance for breaking out a metric by a dimension on another table via an
  explicit join (an implicit FK reference against a metric is rejected by the QP
  with a 400).
2026-06-17 20:11:28 +02:00
Nathan Voxland
7bd450f1de Force an analyze on pending index table (#75816)
Force an analyze on pending index before promoting it so metrics are correct and queries fast
2026-06-17 11:27:14 -05:00
Timofey Kachalov
1a9b0c7520 feat(sdk): Add use-action hook for SDK (#75327) 2026-06-17 19:01:33 +04:00
Mihael Konjević
4ff0c08a4b Add @retro slack id mapping (#76009) 2026-06-17 16:25:35 +02:00
Nicola Mometto
c6a4c1bb0e Zombie transform reaper (#75194)
* feat: add transform_run heartbeat migration

* custom message on timeout

* reap stale runs

* test

* heartbeat job runs too

* extract in a run-tracking module

* kondo

* mage

* fix: dissoc internal fields

* fix tests

* chore

* style

* factor out system

* ensure jobs don't hang forever

* use future timeouts

* don't hammer with heartbeats

* refactor

* further handle cases

* simplify impl

* get rid of macro for run tracking

* simplify

* external heartbeat

* cancel in flight

* fix

* move migration to 63

* remove dead kondo config

* add indices for locking run performance

* dissoc tracking run fields on dependencies api

* fix: transform prep needs to be within try/catch

* fix: just use future-cancel

* feat: share heartbeat+reconcile

* feat: add last_heartbeat to job_run

* present run

* cancel in flight on abonrmal exit

* ioc

* simplify

* note

* tighten docstrings

* fix kondo

* fix tests

* nil safe

* whitespace from merge

* handle review comments

* just dissoc last_heartbeat on hydration

* fixes

* use minutes->ms
2026-06-17 15:19:56 +01:00
Mahatthana (Kelvin) Nomsawadi
3012ea0cb4 fix(test): fix flaky embedded dashboard tab view_count assertions (#75889)
fix(test): fix flaky embedded dashboard tab test

The test was asserting view_count values that go through a 20-second
async batch queue, causing near-100% failure in stress runs:

- visitDashboard (beforeEach) fires card queries, submitting increments
  to the batch queue before the embed query runs
- When both increments flush in the same batch cycle, view_count jumps
  from 1 to 3, permanently skipping the expected value of 2
- === 2 is never true in burns 2-30, so retryRequest always times out

Drop the view_count assertions entirely. Backend tests already cover the
increment mechanism (card-read-view-count-test,
embedded-dashboard-card-query-view-log-test,
increment-view-counts!*-test). The intercept spy assertions
(calledOnce / not.have.been.called) fully cover the test's stated
behavior: only cards on the active tab are queried.

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-17 15:14:26 +01:00
Rodrigo López Dato
80520be19e Expose Mcp-Session-Id header for CORS requests (#75838) 2026-06-17 10:49:58 -03:00
Nemanja Glumac
462255ca5e ci(drivers): Don't let cancelled or timed-out info drivers block PRs (#75992)
ci(drivers): don't let cancelled or timed-out info drivers block PRs

The drivers-tests-result gate passes only when every needed job is
success or skipped. An info driver's job is forced green by the upload
step's continue-on-error, but that only neutralizes a step that runs and
fails normally. When an info job is cancelled (fail-fast, manual cancel)
or times out, the controlling step never completes, so the job's result
is cancelled/failure and the gate fails the required check, blocking PRs.

Feed each driver's configured status into the result job and drop info
drivers from the pass/fail check entirely, so their result never gates
regardless of cancelled/timed-out/failure. Empty or unknown status falls
back to required, so the gate can only stop gating an explicitly-info
driver, never weaken a required one.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-17 15:48:07 +02:00
dpsutton
e86ae3f02b fix(mysql): don't pass getCatalog() as the sync catalog filter (#75929) (#75971)
Table enumeration broke for PlanetScale databases configured with replica
(or any `<db>@replica`-targeted) credentials starting in 0.62.

Root cause
----------
`active-tables :mysql` was changed to pass `(.getCatalog conn)` as the
catalog filter to `DatabaseMetaData.getTables`. `getCatalog()` is backed by
`SELECT DATABASE()`, which on a Vitess/PlanetScale replica connection returns
the routing-qualified name `<db>@replica`. The driver compiles a non-nil
catalog into `WHERE TABLE_SCHEMA = '<db>@replica'`, but `information_schema`
stores the bare `TABLE_SCHEMA = '<db>'`, so the filter matches nothing and
sync sees an empty database. Primary credentials return the bare name, which
is why the same sync worked on primary but not replica creds.

The `@replica` suffix is a Vitess routing directive, not part of the schema
name, so it can never equal a real `TABLE_SCHEMA`. There is no clean catalog
to recover at runtime: getCatalog/DATABASE()/SCHEMA() are all contaminated,
and setCatalog is a no-op on Vitess.

Fix
---
1. Revert `active-tables :mysql` to pass `nil` for the catalog. The MariaDB
   driver's `nullCatalogMeansCurrent=true` default already scopes a nil
   catalog to the connection's current (bound) database — it does NOT
   enumerate every DB the user can read. This delegates "current database"
   resolution to the driver instead of reconstructing a filter string, and
   correctly returns the bound DB's tables on both primary and replica
   PlanetScale connections.

2. Pin `nullCatalogMeansCurrent=true` explicitly in `default-connection-args`
   so the contract is documented and a future driver bump (Connector/J 8.x
   defaults it to `false`) can't silently widen sync to sibling databases.

The original change aimed to stop workspace MySQL users (GRANT SELECT on the
canonical DB + ownership of an iso DB) from leaking the iso DB into sync. That
leak does not occur with the shipped driver: `nullCatalogMeansCurrent=true`
already scopes `nil` to the bound DB. This is corroborated by the test suite
running many databases on one MySQL server with exact-set table assertions —
a true over-enumeration would have failed those deterministically. Verified
directly against live PlanetScale (replica: nil -> 3 tables, getCatalog -> 0;
primary: 3) and a local multi-DB MySQL server (scoped to the bound DB, no leak).

Why no test
-----------
This regression is not reproducible without Vitess, so no local test has teeth.
The bug only manifests when `getCatalog()` returns a value that differs from the
`information_schema` TABLE_SCHEMA — i.e. PlanetScale's `<db>@replica`. On stock
MySQL `getCatalog()` returns the bare bound-DB name, so any local test would
scope correctly and stay green even if `(.getCatalog conn)` were reintroduced.
A behavioral cross-DB test passes whether or not the bug is present; a unit test
asserting the `nullCatalogMeansCurrent` pin is orthogonal to the catalog
argument and likewise passes with the bug reintroduced. Both would give false
confidence. A faithful test requires a live Vitess/PlanetScale instance, which
isn't available in CI. The inline code comments document the trap, the
mechanism, and the verified reproduction as the durable regression guard.

Here's a repro with the following containers:

```
docker run -d --name mysql-local -e MYSQL_ROOT_PASSWORD=mysecretpassword -e MYSQL_ROOT_HOST='%' -p 3306:3306 mysql:8

docker run -d --name vitess-local \
    -p 33574:33574 \
    -p 33575:33575 \
    -p 33577:33577 \
    -e PORT=33574 \
    -e KEYSPACES=stuff,unsharded \
    -e NUM_SHARDS=2,1 \
    -e MYSQL_BIND_HOST=0.0.0.0 \
    -e VTCOMBO_BIND_HOST=0.0.0.0 \
    vitess/vttestserver:mysql80
```

```clojure
(letfn [(probe [label uri]
          (with-open [conn (jdbc/get-connection {:connection-uri uri})]
            (let [cnt (fn [cat] (with-open [rs (.getTables (.getMetaData conn) cat nil "%"
                                                           (into-array String ["TABLE"]))]
                                  (count (jdbc/result-set-seq rs))))]
              {:label label
               :getCatalog (.getCatalog conn)
               :nil-filter (cnt nil)
               :getCatalog-filter (cnt (.getCatalog conn))})))]
  (mapv (fn [[db conn-s]] (probe db conn-s))
        [["MySQL"           "jdbc:mysql://127.0.0.1:3306/stuff?user=root&password=mysecretpassword"]
         ["Vitess"          "jdbc:mysql://127.0.0.1:33577/stuff?user=root&password="]
         ["Vitess @replica" "jdbc:mysql://127.0.0.1:33577/stuff@replica?user=root&password="]]))
[{:label "MySQL",
  :getCatalog "stuff",
  :nil-filter 3,
  :getCatalog-filter 3}
 {:label "Vitess",
  :getCatalog "stuff",
  :nil-filter 3,
  :getCatalog-filter 3}
 {:label "Vitess @replica",
  :getCatalog "stuff@replica",
  :nil-filter 3,
  :getCatalog-filter 0}]
```
2026-06-17 09:12:06 -04:00
Alexander Polyankin
bc6bc90b7e Fix memory leak with GraalVM (#75982)
* Fix memory leak with GraalVM

* fix
2026-06-17 08:56:07 -04:00
Phoomparin Mano
be2fb45f22 Rename switch for MCP inline charts in admin settings (#75859)
* update copy for mcp apps admin settings

* add aria label

* fix failing type checks
2026-06-17 11:34:22 +00:00
Nemanja Glumac
f3d2ef76b2 Add a pre-flight check to the Claude e2e flake fix (#75991) 2026-06-17 11:42:58 +02:00
Mahatthana (Kelvin) Nomsawadi
1ca82c0c89 feat(sdk-bundle): Modular embedding SDK insights collection (#75785)
* Add public Snowplow proxy endpoint for SDK telemetry (#74967)

* Add public Snowplow proxy endpoint for SDK telemetry

Server half of the CSP-bypass transport (EMB-1758). The Embedding SDK
runs in the customer's page where a strict connect-src CSP blocks a
direct POST to the Snowplow collector; the SDK POSTs the tp2 payload to
the instance instead (already allowlisted) and this endpoint forwards it
server-side, where no browser CSP applies.

Public/anonymous by construction: mounted with +public-exceptions, no
+auth. The browser-tracker can't carry a Metabase session cross-origin,
and the collector it fronts is itself public. Forwards status + body
verbatim so the tracker's retry outbox keeps working; 5s timeouts; 502
on an unreachable collector.

Payload-blind passthrough: no knowledge of the event schema. The
existing embedded_analytics_js schema is used only as a test vehicle;
the SDK's real collection schema is separate (Half 2).

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

* fix: remove unused analytics.settings require in proxy_api_test

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* refactor: move proxy endpoint to analytics.api.proxy sub-namespace

- Rename proxy_api → analytics/api/proxy (follows <module>.api.* convention)
- Reference directly from routes.clj (matches metabot pattern)
- Drop inline route comment (docstring covers it)
- Drop log/infof on success path; keep log/errorf on failure
- Drop 502 body (tracker ignores it; server log already captures cause)
- Remove proxy-api from kondo :api set; add analytics.api.proxy instead

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Clean up AI comments

* fix: clean up proxy test — drop ticket ref, remove unused atom

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: proxy test and impl cleanup

- Add :body nil to 502 response so Ring treats it as a response map
- Overload with-collector macro to support no-atom form
- Relay body in relays-collector-status-verbatim-test
- Drop redundant header case checks (clj-http normalizes to lowercase)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: use sp.metabase.com instead of "configured collector" in proxy comments

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* Add SDK telemetry transport through the instance proxy (#74968)

* Add public Snowplow proxy endpoint for SDK telemetry

Server half of the CSP-bypass transport (EMB-1758). The Embedding SDK
runs in the customer's page where a strict connect-src CSP blocks a
direct POST to the Snowplow collector; the SDK POSTs the tp2 payload to
the instance instead (already allowlisted) and this endpoint forwards it
server-side, where no browser CSP applies.

Public/anonymous by construction: mounted with +public-exceptions, no
+auth. The browser-tracker can't carry a Metabase session cross-origin,
and the collector it fronts is itself public. Forwards status + body
verbatim so the tracker's retry outbox keeps working; 5s timeouts; 502
on an unreachable collector.

Payload-blind passthrough: no knowledge of the event schema. The
existing embedded_analytics_js schema is used only as a test vehicle;
the SDK's real collection schema is separate (Half 2).

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

* fix: remove unused analytics.settings require in proxy_api_test

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* refactor: move proxy endpoint to analytics.api.proxy sub-namespace

- Rename proxy_api → analytics/api/proxy (follows <module>.api.* convention)
- Reference directly from routes.clj (matches metabot pattern)
- Drop inline route comment (docstring covers it)
- Drop log/infof on success path; keep log/errorf on failure
- Drop 502 body (tracker ignores it; server log already captures cause)
- Remove proxy-api from kondo :api set; add analytics.api.proxy instead

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Clean up AI comments

* fix: clean up proxy test — drop ticket ref, remove unused atom

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: proxy test and impl cleanup

- Add :body nil to 502 response so Ring treats it as a response map
- Overload with-collector macro to support no-atom form
- Relay body in relays-collector-status-verbatim-test
- Drop redundant header case checks (clj-http normalizes to lowercase)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: use sp.metabase.com instead of "configured collector" in proxy comments

* Add SDK telemetry transport through the instance proxy

Client half of the CSP-bypass transport (EMB-1760). Stands up the
Embedding SDK's Snowplow tracker pointed at the instance proxy
(/api/analytics-proxy, EMB-1758) instead of the collector directly, so
telemetry works inside a strict-CSP customer app — connect-src matches
host not path, so the already-allowlisted instance origin passes.

Transport only, schema-agnostic: initSdkTracker stands up a named "sdk"
tracker (post, credentials omit, keepalive, bufferSize 1, no storage,
server anonymisation); trackSdkEvent sends any self-describing event;
isSdkTrackingEnabled gates on the instance's anonymous-tracking settings.
It does NOT decide what the SDK collects, on which schema, or wire
emission into the component lifecycle — that is the collection work
(EMB-1786) on a new SDK-specific schema. The existing
embedded_analytics_js schema is used only as a temporary test vehicle.

Bumps @snowplow/browser-tracker to v4 (for keepalive + credentials:omit).
Shared dep: pin encodeBase64:true on the main-app tracker to preserve its
exact v3 wire format, and adjust the main-app event.ts data cast for v4's
narrower self-describing-event typing — both no-ops for existing events.

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

* Note SDK analytics exports unused until EMB-1786

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

* Trim SDK tracker config and tests

Remove the trivial isSdkTrackingEnabled helper, drop keepalive and
bufferSize (speculative / web default), make contexts and encodeBase64
explicit, and clarify the credentials comment. Trim the spec to the
config flags that fail silently plus tracker-isolation routing.

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

* fix: downgrade @snowplow/browser-tracker v4 → v3.24.6 to fix CI OOM crash

v4.8.1 increased the package weight enough to OOM the CI runner during
e2e-group-28-ee (question-reproductions/reproductions.cy.spec.ts, issue 56416),
crashing Chrome on every run. v3.24.6 is the latest v3 patch and behaves
identically for all current usage (same wire format, same API surface).

Reverts the two v4 accommodations: encodeBase64: true (v4 flipped the POST
default; v3 default is already true) and the Record<string, unknown> type cast
(v4 narrowed SelfDescribingJson; v3 accepts the broader union without a cast).

Also removes credentials: "omit" from the SDK tracker (v4-only option; v3
does not send credentialed cross-origin requests by default).

* fix: remove credentials assertion from snowplow spec — v3 uses XHR not fetch

v3.24.6 uses XMLHttpRequest (not fetch), which has no credentials config.
XHR defaults to withCredentials=false, equivalent to credentials:"omit".
The assertion was added for the v4 fetch-based tracker and doesn't apply to v3.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: upgrade @snowplow/browser-tracker 3.1.6→3.2.0, add withCredentials:false

3.1.6 hardcodes `xhr.withCredentials = true` — no config option. This
causes CORS failures against the proxy endpoint which uses
`Access-Control-Allow-Origin: *` (wildcard CORS rejects any credentialed
request).

3.2.0 added `withCredentials?: boolean` (defaults true). Pinning to
exactly 3.2.0 keeps the bundle at 35 KB — smaller than 3.1.6 (38 KB)
and well below the 3.24.6 bundle (46 KB) that caused the Chrome renderer
OOM in e2e-group-28-ee.

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* Add per-mount SDK component usage events (#75402)

* Add per-mount SDK component usage events

Fire one Snowplow event per public SDK component mount (Option B from
the EMB-1785 tech plan) plus a global-only beacon at provider init,
through the instance proxy transport from EMB-1760.

- New forked schema com.metabase/embedding_sdk/jsonschema/1-0-0
- useTrackSdkComponentMount hook: first-mount-wins dedup, opt-out gate
- All 7 public SDK components wired with their dimension props
- Instance-context plugin + authMethod/sdkVersion globals
- sdkTrackerReady flag fixes child-before-parent init race

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

* Add e2e for SDK per-mount component events

Cypress component spec asserting the per-mount event + global init
beacon reach /api/analytics-proxy with the embedding_sdk schema, and
that the opt-out gate (anon-tracking-enabled=false) suppresses both.

Not yet executed locally (needs the SDK component Cypress harness);
verified by CI.

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

* refactor: rename sdk-component-events → events, object params for initSdkTracker, fix format

- Rename analytics/sdk-component-events.ts → analytics/events.ts (mirrors
  core app's analytics/snowplow.ts + analytics/event.ts split)
- Export EMBEDDING_SDK_SCHEMA from events.ts; remove duplicate definition
  in ComponentProvider.tsx
- Convert initSdkTracker positional params to a named-object signature
- Fix oxfmt formatting in e2e spec and snowplow unit spec

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat: CreateDashboardModal tracking, type-safe properties, analytics refactor

- Add CreateDashboardModal to SdkComponentName + iglu schema
- Wire useTrackSdkComponentMount in CreateDashboardModalInner
- Add SdkComponentProperties mapped type for per-component compile-time validation
- Make useTrackSdkComponentMount generic over SdkComponentName
- Move useSdkTrackerInit + deriveAuthMethod to analytics/tracker-init.ts
- Make store a required param in initSdkTracker, remove getSdkStore fallback
- Remove dead null guard in createSdkInstanceContextPlugin, add invariant comment
- Named return value wasJustInitialized in initSdkTracker
- Convert module-scope functions to function keyword
- Fix serialization: value == null catches undefined
- Fix Boolean() casts, improve eslint-disable comment, fix screaming-case comments
- Fix withDownloads default in StaticDashboard to satisfy strict boolean type
- Tests: instance context test, CreateDashboardModal presence test, CreateQuestion delegation e2e test

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: format analytics-component-events spec

* refactor: rename analytics files, type-safe snowplow exports

- events.ts → component-events.ts (more descriptive name)
- tracker-init.ts → tracker.ts, useSdkTrackerInit → useInitSdkTracker
- Export SdkAuthMethod union type from snowplow.ts
- Add WasJustInitialized named type alias for initSdkTracker return
- Simplify initSdkTracker early-return logic (no wasJustInitialized temp var)
- Add comment on createSdkInstanceContextPlugin explaining userId omission
- All consumers updated to new module paths and hook name

* refactor: centralize defaults, drop inapplicable tracked properties

- Add SDK_COMPONENT_DEFAULT_PROPERTIES (mirrors modular embedding's
  DEFAULT_VALUES pattern); hook accepts Partial<> and merges defaults
- Split StaticDashboardProperties (4 fields) from DashboardProperties
  (5 fields); StaticDashboard omits enable_entity_navigation entirely
- Replace PresenceProperties with EmptyProperties = Record<never, never>
  for CollectionBrowser and CreateDashboardModal; drop { used: true }
  (trivially always true, no analytical signal)
- Remove ?? false / ?? "auto" fallbacks from call sites — hook fills
  gaps via SDK_COMPONENT_DEFAULT_PROPERTIES spread merge

* fix: filter undefined before default merge, fix StaticQuestion with_title default

Spread-merge does not distinguish between omitted and undefined: passing
{ with_downloads: undefined } silently overrides the default false.
Filter out undefined values before merging so SDK_COMPONENT_DEFAULT_PROPERTIES
fills genuine gaps, not fields that were explicitly passed as undefined.

Also corrects StaticQuestion.with_title default from true → false to match
the actual component default (title = false, hidden for backwards-compat).

* feat: gate component-mount events to npm SDK only, not iframe embed

Uses isEmbeddingSdk() && !isEmbeddingEajs() — same pattern already used
in ComponentProvider. Iframe embed has its own analytics path; per-mount
component events are intended for npm SDK usage tracking only.

* refactor: drop redundant tracking-only prop defaults in dashboard components

EditableDashboard and InteractiveDashboard destructured withTitle/withDownloads
etc. with defaults solely to pass to useTrackSdkComponentMount. The hook now
handles defaults via SDK_COMPONENT_DEFAULT_PROPERTIES, so the defaults at
the destructuring site are redundant. StaticDashboard keeps its defaults
because withDownloads is also used for the dashcardMenu render.

* fix: filter undefined before default merge, fix StaticQuestion with_title default

Spread-merge does not distinguish between omitted and undefined: passing
{ with_downloads: undefined } silently overrides the default false.
Filter out undefined values before merging so SDK_COMPONENT_DEFAULT_PROPERTIES
fills genuine gaps, not fields that were explicitly passed as undefined.

Also corrects StaticQuestion.with_title default from true → false to match
the actual component default (title = false, hidden for backwards-compat).

* refactor: drop redundant tracking-only prop defaults in StaticDashboard

withTitle and withSubscriptions are only used in the tracking hook call;
withDownloads is also used in dashcardMenu but undefined is falsy so the
= false default has no behavioral effect. All flow through {...normalizedProps}
to SdkDashboard. Hook fills defaults via SDK_COMPONENT_DEFAULT_PROPERTIES.

* refactor: destructure InteractiveQuestion props directly instead of type casts

* refactor: drop component enum from embedding_sdk schema

TypeScript enforces valid component names at compile time via SdkComponentName.
Enum in the schema would require a version bump every time a new component is added.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: pass destructured props through to SdkQuestion in InteractiveQuestion, fix stale test assertion

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* refactor: replace store mock in events spec with real store via renderWithProviders

Use renderWithProviders + sdkReducers + setupSdkState instead of jest.mock on
embedding-sdk-bundle/store. State controls (trackingEnabled, sdkTrackerReady) are now
explicit initial state rather than per-call mock return values.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: resolve TS errors in snowplow.unit.spec

Pass sdk: createMockSdkState() to createMockState so the SdkStoreState
overload is selected instead of State. Replace bare {} with
createMockTokenFeatures() for the token-features setting.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: resolve TS errors in snowplow.unit.spec

Pass sdk: createMockSdkState() to createMockState so the SdkStoreState
overload is selected instead of State. Replace bare {} with
createMockTokenFeatures() for the token-features setting.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* test: add length assertions and multi-component test to analytics spec

- Assert capturedEvents.length in every test so event count is explicit
- Add test: two StaticQuestion mounts fire 3 events (2 component + 1 beacon)
- Fix stale comments: encodeBase64 wording and 3.1.6→3.2.0 upgrade reason

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: correct test 2 length assertion and replace dedup-colliding test 3

Test 2: beacon fires once per JS context (module-level singleton); it
already fired in test 1, so assert length 1 not 2.

Test 3: two StaticQuestion mounts with the same questionId share a dedup
key and only fire one event. Replace with InteractiveQuestion +
CollectionBrowser (distinct keys) and assert length 2.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* test: add iframe embed gate test to events spec

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* test: move iframe embed gate assertion to e2e component spec

Replaces the mocked unit test with a real assertion in the existing
analytics-component-events Cypress spec, where the module singleton is
live and no mocking is needed.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: restrict trackSchemaEvent to main-app tracker to prevent double-firing

In the SDK iframe embed context both the main-app tracker ("sp") and the
SDK tracker ("sdk") are in the Snowplow registry. trackSelfDescribingEvent
with no tracker names fires on all registered trackers, so events like
dashboard_pdf_exported were emitted twice — once via "sp" (browser UA)
and once via the SDK proxy ("sdk", Apache-HttpClient UA).

Passing ["sp"] mirrors the existing pattern in trackSdkEvent which already
restricts to ["sdk"]. In pure SDK contexts where "sp" is never registered
the call becomes a no-op, which is also correct.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: skip SDK tracker init in iframe embed context

The SDK tracker ("sdk") should only initialize when running as the npm
SDK package. In the iframe embed context (isEmbeddingEajs) the tracker
was being registered unnecessarily — its per-mount events are already
blocked by useTrackSdkComponentMount, and the init beacon it was firing
had no test coverage or analytical purpose in that context.

Guarding at the useInitSdkTracker level makes the "sdk" tracker
structurally absent from the Snowplow registry in EAJS, complementing
the ["sp"] restriction in trackSchemaEvent as defense in depth.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* test: move EAJS gate test to iframe embedding e2e suite, fix lint

Removes the EAJS gate test from the SDK component spec (wrong layer —
component tests use a simulated environment, not the real iframe embed
entry point) and adds it to the sdk-iframe-embedding e2e suite where
the full EAJS stack runs.

Also removes unused StaticQuestion import that caused the fe-lint failure.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: default anon-tracking to false until settings load

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: format analytics-component-events spec

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: tighten SdkAuthMethod types and refactor event spec to renderHookWithProviders

- Remove SdkAuthMethod | "" — authMethod is now required in initSdkTracker
  and getSdkAuthMethod returns SdkAuthMethod | undefined (undefined only before
  init, which the sdkTrackerReady gate prevents in practice)
- Update snowplow spec: "returns undefined" replaces "returns empty string"
- Replace TestComponent wrapper in events spec with renderHookWithProviders
  per review comment r3402348453
- Default useIsTrackingEnabled to false so opted-out users are not tracked
  during the settings-load window (review comment r3402504036)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* refactor: extract getSdkPackageVersion shared helper from getBuildInfo

Replaces 4 inline getBuildInfo("...PACKAGE_BUILD_INFO").version ?? null
calls with a single getSdkPackageVersion() util in get-build-info.ts.
SdkDebugInfo.tsx is left unchanged — it uses the full BuildInfo object.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: update test mocks from getBuildInfo to getSdkPackageVersion

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: wait for both analytics-proxy POSTs in component event e2e tests

Snowplow serializes sends via executingQueue: event 2 is only dispatched
after event 1's XHR response arrives, producing two separate requests.
Waiting for only one request left the count assertion flaky in CI.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: stub analytics proxy to respond immediately in component event tests

The Snowplow queue serializes events: event N+1 fires only after event N's XHR
response arrives. In CI, the real analytics proxy can take 10+ seconds to respond,
which blocks the queue and causes subsequent events to miss the 10s cy.wait timeout.

Replace request.continue() with request.reply({ statusCode: 200 }) so the proxy
stubs return immediately. This also prevents ghost events from failed test retries
from blocking the queue during subsequent tests.

Also adds visual waits (cy.findByText("Product ID").should("be.visible")) before
the proxy waits in tests 1 and 3 as a settings-load race guard, mirroring the
existing pattern in test 4.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: run Snowplow Micro in component test CI and revert proxy stub

Snowplow Micro was not started in component test CI (snowplow: false), so
the backend's analytics proxy hit a connection-refused on localhost:9090 and
returned 502. This blocked the Snowplow queue and caused event wait timeouts.

Enable Snowplow Micro in both component test jobs and revert request.reply()
back to request.continue() so the full proxy chain runs as in production.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-17 09:48:12 +01:00
Mahatthana (Kelvin) Nomsawadi
5db67937ad feat(sdk-bundle): Modular embedding SDK insights collection (#75785)
* Add public Snowplow proxy endpoint for SDK telemetry (#74967)

* Add public Snowplow proxy endpoint for SDK telemetry

Server half of the CSP-bypass transport (EMB-1758). The Embedding SDK
runs in the customer's page where a strict connect-src CSP blocks a
direct POST to the Snowplow collector; the SDK POSTs the tp2 payload to
the instance instead (already allowlisted) and this endpoint forwards it
server-side, where no browser CSP applies.

Public/anonymous by construction: mounted with +public-exceptions, no
+auth. The browser-tracker can't carry a Metabase session cross-origin,
and the collector it fronts is itself public. Forwards status + body
verbatim so the tracker's retry outbox keeps working; 5s timeouts; 502
on an unreachable collector.

Payload-blind passthrough: no knowledge of the event schema. The
existing embedded_analytics_js schema is used only as a test vehicle;
the SDK's real collection schema is separate (Half 2).

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

* fix: remove unused analytics.settings require in proxy_api_test

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* refactor: move proxy endpoint to analytics.api.proxy sub-namespace

- Rename proxy_api → analytics/api/proxy (follows <module>.api.* convention)
- Reference directly from routes.clj (matches metabot pattern)
- Drop inline route comment (docstring covers it)
- Drop log/infof on success path; keep log/errorf on failure
- Drop 502 body (tracker ignores it; server log already captures cause)
- Remove proxy-api from kondo :api set; add analytics.api.proxy instead

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Clean up AI comments

* fix: clean up proxy test — drop ticket ref, remove unused atom

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: proxy test and impl cleanup

- Add :body nil to 502 response so Ring treats it as a response map
- Overload with-collector macro to support no-atom form
- Relay body in relays-collector-status-verbatim-test
- Drop redundant header case checks (clj-http normalizes to lowercase)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: use sp.metabase.com instead of "configured collector" in proxy comments

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* Add SDK telemetry transport through the instance proxy (#74968)

* Add public Snowplow proxy endpoint for SDK telemetry

Server half of the CSP-bypass transport (EMB-1758). The Embedding SDK
runs in the customer's page where a strict connect-src CSP blocks a
direct POST to the Snowplow collector; the SDK POSTs the tp2 payload to
the instance instead (already allowlisted) and this endpoint forwards it
server-side, where no browser CSP applies.

Public/anonymous by construction: mounted with +public-exceptions, no
+auth. The browser-tracker can't carry a Metabase session cross-origin,
and the collector it fronts is itself public. Forwards status + body
verbatim so the tracker's retry outbox keeps working; 5s timeouts; 502
on an unreachable collector.

Payload-blind passthrough: no knowledge of the event schema. The
existing embedded_analytics_js schema is used only as a test vehicle;
the SDK's real collection schema is separate (Half 2).

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

* fix: remove unused analytics.settings require in proxy_api_test

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* refactor: move proxy endpoint to analytics.api.proxy sub-namespace

- Rename proxy_api → analytics/api/proxy (follows <module>.api.* convention)
- Reference directly from routes.clj (matches metabot pattern)
- Drop inline route comment (docstring covers it)
- Drop log/infof on success path; keep log/errorf on failure
- Drop 502 body (tracker ignores it; server log already captures cause)
- Remove proxy-api from kondo :api set; add analytics.api.proxy instead

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Clean up AI comments

* fix: clean up proxy test — drop ticket ref, remove unused atom

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: proxy test and impl cleanup

- Add :body nil to 502 response so Ring treats it as a response map
- Overload with-collector macro to support no-atom form
- Relay body in relays-collector-status-verbatim-test
- Drop redundant header case checks (clj-http normalizes to lowercase)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: use sp.metabase.com instead of "configured collector" in proxy comments

* Add SDK telemetry transport through the instance proxy

Client half of the CSP-bypass transport (EMB-1760). Stands up the
Embedding SDK's Snowplow tracker pointed at the instance proxy
(/api/analytics-proxy, EMB-1758) instead of the collector directly, so
telemetry works inside a strict-CSP customer app — connect-src matches
host not path, so the already-allowlisted instance origin passes.

Transport only, schema-agnostic: initSdkTracker stands up a named "sdk"
tracker (post, credentials omit, keepalive, bufferSize 1, no storage,
server anonymisation); trackSdkEvent sends any self-describing event;
isSdkTrackingEnabled gates on the instance's anonymous-tracking settings.
It does NOT decide what the SDK collects, on which schema, or wire
emission into the component lifecycle — that is the collection work
(EMB-1786) on a new SDK-specific schema. The existing
embedded_analytics_js schema is used only as a temporary test vehicle.

Bumps @snowplow/browser-tracker to v4 (for keepalive + credentials:omit).
Shared dep: pin encodeBase64:true on the main-app tracker to preserve its
exact v3 wire format, and adjust the main-app event.ts data cast for v4's
narrower self-describing-event typing — both no-ops for existing events.

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

* Note SDK analytics exports unused until EMB-1786

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

* Trim SDK tracker config and tests

Remove the trivial isSdkTrackingEnabled helper, drop keepalive and
bufferSize (speculative / web default), make contexts and encodeBase64
explicit, and clarify the credentials comment. Trim the spec to the
config flags that fail silently plus tracker-isolation routing.

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

* fix: downgrade @snowplow/browser-tracker v4 → v3.24.6 to fix CI OOM crash

v4.8.1 increased the package weight enough to OOM the CI runner during
e2e-group-28-ee (question-reproductions/reproductions.cy.spec.ts, issue 56416),
crashing Chrome on every run. v3.24.6 is the latest v3 patch and behaves
identically for all current usage (same wire format, same API surface).

Reverts the two v4 accommodations: encodeBase64: true (v4 flipped the POST
default; v3 default is already true) and the Record<string, unknown> type cast
(v4 narrowed SelfDescribingJson; v3 accepts the broader union without a cast).

Also removes credentials: "omit" from the SDK tracker (v4-only option; v3
does not send credentialed cross-origin requests by default).

* fix: remove credentials assertion from snowplow spec — v3 uses XHR not fetch

v3.24.6 uses XMLHttpRequest (not fetch), which has no credentials config.
XHR defaults to withCredentials=false, equivalent to credentials:"omit".
The assertion was added for the v4 fetch-based tracker and doesn't apply to v3.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: upgrade @snowplow/browser-tracker 3.1.6→3.2.0, add withCredentials:false

3.1.6 hardcodes `xhr.withCredentials = true` — no config option. This
causes CORS failures against the proxy endpoint which uses
`Access-Control-Allow-Origin: *` (wildcard CORS rejects any credentialed
request).

3.2.0 added `withCredentials?: boolean` (defaults true). Pinning to
exactly 3.2.0 keeps the bundle at 35 KB — smaller than 3.1.6 (38 KB)
and well below the 3.24.6 bundle (46 KB) that caused the Chrome renderer
OOM in e2e-group-28-ee.

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>

* Add per-mount SDK component usage events (#75402)

* Add per-mount SDK component usage events

Fire one Snowplow event per public SDK component mount (Option B from
the EMB-1785 tech plan) plus a global-only beacon at provider init,
through the instance proxy transport from EMB-1760.

- New forked schema com.metabase/embedding_sdk/jsonschema/1-0-0
- useTrackSdkComponentMount hook: first-mount-wins dedup, opt-out gate
- All 7 public SDK components wired with their dimension props
- Instance-context plugin + authMethod/sdkVersion globals
- sdkTrackerReady flag fixes child-before-parent init race

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

* Add e2e for SDK per-mount component events

Cypress component spec asserting the per-mount event + global init
beacon reach /api/analytics-proxy with the embedding_sdk schema, and
that the opt-out gate (anon-tracking-enabled=false) suppresses both.

Not yet executed locally (needs the SDK component Cypress harness);
verified by CI.

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

* refactor: rename sdk-component-events → events, object params for initSdkTracker, fix format

- Rename analytics/sdk-component-events.ts → analytics/events.ts (mirrors
  core app's analytics/snowplow.ts + analytics/event.ts split)
- Export EMBEDDING_SDK_SCHEMA from events.ts; remove duplicate definition
  in ComponentProvider.tsx
- Convert initSdkTracker positional params to a named-object signature
- Fix oxfmt formatting in e2e spec and snowplow unit spec

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat: CreateDashboardModal tracking, type-safe properties, analytics refactor

- Add CreateDashboardModal to SdkComponentName + iglu schema
- Wire useTrackSdkComponentMount in CreateDashboardModalInner
- Add SdkComponentProperties mapped type for per-component compile-time validation
- Make useTrackSdkComponentMount generic over SdkComponentName
- Move useSdkTrackerInit + deriveAuthMethod to analytics/tracker-init.ts
- Make store a required param in initSdkTracker, remove getSdkStore fallback
- Remove dead null guard in createSdkInstanceContextPlugin, add invariant comment
- Named return value wasJustInitialized in initSdkTracker
- Convert module-scope functions to function keyword
- Fix serialization: value == null catches undefined
- Fix Boolean() casts, improve eslint-disable comment, fix screaming-case comments
- Fix withDownloads default in StaticDashboard to satisfy strict boolean type
- Tests: instance context test, CreateDashboardModal presence test, CreateQuestion delegation e2e test

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: format analytics-component-events spec

* refactor: rename analytics files, type-safe snowplow exports

- events.ts → component-events.ts (more descriptive name)
- tracker-init.ts → tracker.ts, useSdkTrackerInit → useInitSdkTracker
- Export SdkAuthMethod union type from snowplow.ts
- Add WasJustInitialized named type alias for initSdkTracker return
- Simplify initSdkTracker early-return logic (no wasJustInitialized temp var)
- Add comment on createSdkInstanceContextPlugin explaining userId omission
- All consumers updated to new module paths and hook name

* refactor: centralize defaults, drop inapplicable tracked properties

- Add SDK_COMPONENT_DEFAULT_PROPERTIES (mirrors modular embedding's
  DEFAULT_VALUES pattern); hook accepts Partial<> and merges defaults
- Split StaticDashboardProperties (4 fields) from DashboardProperties
  (5 fields); StaticDashboard omits enable_entity_navigation entirely
- Replace PresenceProperties with EmptyProperties = Record<never, never>
  for CollectionBrowser and CreateDashboardModal; drop { used: true }
  (trivially always true, no analytical signal)
- Remove ?? false / ?? "auto" fallbacks from call sites — hook fills
  gaps via SDK_COMPONENT_DEFAULT_PROPERTIES spread merge

* fix: filter undefined before default merge, fix StaticQuestion with_title default

Spread-merge does not distinguish between omitted and undefined: passing
{ with_downloads: undefined } silently overrides the default false.
Filter out undefined values before merging so SDK_COMPONENT_DEFAULT_PROPERTIES
fills genuine gaps, not fields that were explicitly passed as undefined.

Also corrects StaticQuestion.with_title default from true → false to match
the actual component default (title = false, hidden for backwards-compat).

* feat: gate component-mount events to npm SDK only, not iframe embed

Uses isEmbeddingSdk() && !isEmbeddingEajs() — same pattern already used
in ComponentProvider. Iframe embed has its own analytics path; per-mount
component events are intended for npm SDK usage tracking only.

* refactor: drop redundant tracking-only prop defaults in dashboard components

EditableDashboard and InteractiveDashboard destructured withTitle/withDownloads
etc. with defaults solely to pass to useTrackSdkComponentMount. The hook now
handles defaults via SDK_COMPONENT_DEFAULT_PROPERTIES, so the defaults at
the destructuring site are redundant. StaticDashboard keeps its defaults
because withDownloads is also used for the dashcardMenu render.

* fix: filter undefined before default merge, fix StaticQuestion with_title default

Spread-merge does not distinguish between omitted and undefined: passing
{ with_downloads: undefined } silently overrides the default false.
Filter out undefined values before merging so SDK_COMPONENT_DEFAULT_PROPERTIES
fills genuine gaps, not fields that were explicitly passed as undefined.

Also corrects StaticQuestion.with_title default from true → false to match
the actual component default (title = false, hidden for backwards-compat).

* refactor: drop redundant tracking-only prop defaults in StaticDashboard

withTitle and withSubscriptions are only used in the tracking hook call;
withDownloads is also used in dashcardMenu but undefined is falsy so the
= false default has no behavioral effect. All flow through {...normalizedProps}
to SdkDashboard. Hook fills defaults via SDK_COMPONENT_DEFAULT_PROPERTIES.

* refactor: destructure InteractiveQuestion props directly instead of type casts

* refactor: drop component enum from embedding_sdk schema

TypeScript enforces valid component names at compile time via SdkComponentName.
Enum in the schema would require a version bump every time a new component is added.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: pass destructured props through to SdkQuestion in InteractiveQuestion, fix stale test assertion

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* refactor: replace store mock in events spec with real store via renderWithProviders

Use renderWithProviders + sdkReducers + setupSdkState instead of jest.mock on
embedding-sdk-bundle/store. State controls (trackingEnabled, sdkTrackerReady) are now
explicit initial state rather than per-call mock return values.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: resolve TS errors in snowplow.unit.spec

Pass sdk: createMockSdkState() to createMockState so the SdkStoreState
overload is selected instead of State. Replace bare {} with
createMockTokenFeatures() for the token-features setting.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: resolve TS errors in snowplow.unit.spec

Pass sdk: createMockSdkState() to createMockState so the SdkStoreState
overload is selected instead of State. Replace bare {} with
createMockTokenFeatures() for the token-features setting.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* test: add length assertions and multi-component test to analytics spec

- Assert capturedEvents.length in every test so event count is explicit
- Add test: two StaticQuestion mounts fire 3 events (2 component + 1 beacon)
- Fix stale comments: encodeBase64 wording and 3.1.6→3.2.0 upgrade reason

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: correct test 2 length assertion and replace dedup-colliding test 3

Test 2: beacon fires once per JS context (module-level singleton); it
already fired in test 1, so assert length 1 not 2.

Test 3: two StaticQuestion mounts with the same questionId share a dedup
key and only fire one event. Replace with InteractiveQuestion +
CollectionBrowser (distinct keys) and assert length 2.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* test: add iframe embed gate test to events spec

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* test: move iframe embed gate assertion to e2e component spec

Replaces the mocked unit test with a real assertion in the existing
analytics-component-events Cypress spec, where the module singleton is
live and no mocking is needed.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: restrict trackSchemaEvent to main-app tracker to prevent double-firing

In the SDK iframe embed context both the main-app tracker ("sp") and the
SDK tracker ("sdk") are in the Snowplow registry. trackSelfDescribingEvent
with no tracker names fires on all registered trackers, so events like
dashboard_pdf_exported were emitted twice — once via "sp" (browser UA)
and once via the SDK proxy ("sdk", Apache-HttpClient UA).

Passing ["sp"] mirrors the existing pattern in trackSdkEvent which already
restricts to ["sdk"]. In pure SDK contexts where "sp" is never registered
the call becomes a no-op, which is also correct.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: skip SDK tracker init in iframe embed context

The SDK tracker ("sdk") should only initialize when running as the npm
SDK package. In the iframe embed context (isEmbeddingEajs) the tracker
was being registered unnecessarily — its per-mount events are already
blocked by useTrackSdkComponentMount, and the init beacon it was firing
had no test coverage or analytical purpose in that context.

Guarding at the useInitSdkTracker level makes the "sdk" tracker
structurally absent from the Snowplow registry in EAJS, complementing
the ["sp"] restriction in trackSchemaEvent as defense in depth.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* test: move EAJS gate test to iframe embedding e2e suite, fix lint

Removes the EAJS gate test from the SDK component spec (wrong layer —
component tests use a simulated environment, not the real iframe embed
entry point) and adds it to the sdk-iframe-embedding e2e suite where
the full EAJS stack runs.

Also removes unused StaticQuestion import that caused the fe-lint failure.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: default anon-tracking to false until settings load

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: format analytics-component-events spec

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: tighten SdkAuthMethod types and refactor event spec to renderHookWithProviders

- Remove SdkAuthMethod | "" — authMethod is now required in initSdkTracker
  and getSdkAuthMethod returns SdkAuthMethod | undefined (undefined only before
  init, which the sdkTrackerReady gate prevents in practice)
- Update snowplow spec: "returns undefined" replaces "returns empty string"
- Replace TestComponent wrapper in events spec with renderHookWithProviders
  per review comment r3402348453
- Default useIsTrackingEnabled to false so opted-out users are not tracked
  during the settings-load window (review comment r3402504036)

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* refactor: extract getSdkPackageVersion shared helper from getBuildInfo

Replaces 4 inline getBuildInfo("...PACKAGE_BUILD_INFO").version ?? null
calls with a single getSdkPackageVersion() util in get-build-info.ts.
SdkDebugInfo.tsx is left unchanged — it uses the full BuildInfo object.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: update test mocks from getBuildInfo to getSdkPackageVersion

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: wait for both analytics-proxy POSTs in component event e2e tests

Snowplow serializes sends via executingQueue: event 2 is only dispatched
after event 1's XHR response arrives, producing two separate requests.
Waiting for only one request left the count assertion flaky in CI.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: stub analytics proxy to respond immediately in component event tests

The Snowplow queue serializes events: event N+1 fires only after event N's XHR
response arrives. In CI, the real analytics proxy can take 10+ seconds to respond,
which blocks the queue and causes subsequent events to miss the 10s cy.wait timeout.

Replace request.continue() with request.reply({ statusCode: 200 }) so the proxy
stubs return immediately. This also prevents ghost events from failed test retries
from blocking the queue during subsequent tests.

Also adds visual waits (cy.findByText("Product ID").should("be.visible")) before
the proxy waits in tests 1 and 3 as a settings-load race guard, mirroring the
existing pattern in test 4.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: run Snowplow Micro in component test CI and revert proxy stub

Snowplow Micro was not started in component test CI (snowplow: false), so
the backend's analytics proxy hit a connection-refused on localhost:9090 and
returned 502. This blocked the Snowplow queue and caused event wait timeouts.

Enable Snowplow Micro in both component test jobs and revert request.reply()
back to request.continue() so the full proxy chain runs as in production.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-17 09:47:57 +01:00
Alexander Polyankin
9c204243f0 Fix dependencies cycles handling (#75978) 2026-06-17 01:16:57 +00:00
Denis Berezin
cb574d0ac1 UXW-4342 Fix document crash after removing a chart (#75641)
* UXW-4342 Fix document crash after removing a chart

* Fix typecheck

* Review fixes

* Fix unit tests
2026-06-17 03:39:36 +03:00
Eric Normand
7b274b46ac Don't delete local transforms when remote has none (GHY-3900) (#75898)
Enabling remote-sync-transforms triggered an import; when the remote
contained no transforms, the imported entity-id set was empty, so
remove-unsynced! built no WHERE clause and fell through to a bare
full-table (t2/delete! :model/Transform), wiping locally-created
transforms.

Gate the unconditional full-table delete so it never fires for
all-or-nothing models (those marked :all-on-setting-disable). An empty
import set means the feature was just toggled on, or the remote tracks
none yet -- not that every local entity should be destroyed.
2026-06-16 22:52:21 +00:00
Kevin Kelleher
449527b9fa Handle null x-axis values in time series charts (#75962)
* properly sort nulls for timeseries axis

* Update Loki Snapshots

---------

Co-authored-by: Metabase Automation <github-automation@metabase.com>
2026-06-16 22:02:54 +00:00
Alexander Polyankin
32c871a46e Introduce multi-process stale-while-revalidate behavior with query caching (#75949)
* Cache empty query results

* Introduce stale-while-revalidate behavior with query caching

* fix author

* fix

* fix

* fix

* fix

* fix

* fix migrations

* fix

* fix

* review comments

* fix

* fix mysql

* fix

* fix
2026-06-16 16:38:39 -04:00
Tyler Plude
eca496d66e [BOT-1662] Support for Microsoft Azure BYOK (#75768)
* Azure BYOK support (squashed BOT-1662)

* cleanups

* fix test

* pr feedback
2026-06-16 13:29:12 -07:00
metamben
b0e21b07d6 Set row limit based on last aggregation or join (#75899)
* Set row limit based on last aggregation or join

Closes QUE2-190

* Fix tests
2026-06-16 22:58:22 +03:00
metamben
5a71626691 Take the metric's name into account when replacing references (#75910)
Closes QUE2-159
2026-06-16 22:58:11 +03:00
metamben
a5287f0238 Add test showing that bucketed breakouts truncate properly (#75811)
* Add test showing that bucketed breakouts truncate properly
* Make mongo's ->rvalue for expressions honor temporal bucketing

Closes QUE2-234
2026-06-16 19:57:31 +00:00
Alexander Polyankin
e025170e85 Fix lib-related N+1 issues with DB calls in parameters (#75888)
* remove duplications

* dedup

* fix

* add tests

* fix

* bulk load

* fix

* fixes

* tests

* fixes

* fix

* fixes

* fix

* fix

* fixes

* fix

* fix /values

* fix

* fix

* fix index usage
2026-06-16 15:03:33 -04:00
Nick Fitzpatrick
656540b069 Oauth client event mark ran v63 (#75950)
* Guard v63 oauth_client_event migration against v62 backport

The oauth_client_event migration was backported to v62. Without these
preconditions, a v62 -> v63 upgrade re-runs CREATE TABLE and fails because
the table already exists. Add MARK_RAN preconditions keyed on the paired
v62 changesets, plus empty rollbacks so a v63 -> v62 downgrade keeps the
objects the still-recorded v62 changesets own. Mirrors #72651.

* Add guarded v62 oauth_client_event backport to master

Master must carry the v62 backport file (identical to release-x.62.x) so
that on a fresh v63 install the 062 changeset sorts first and owns the
table, and v63.* mark-ran. Without it, a fresh-v63 -> downgrade-to-v62
path fails: migrate-down removes the v63 changelog row but the empty
rollback keeps the table, so the v62 jar then re-runs CREATE TABLE on an
existing table. Both files coexisting matches #72651's 060/061 layout.

* Adding comment to rollback props
2026-06-17 00:32:10 +05:30
Riley Thompson
1846972a9e Allow single non-select statements for admins on impersonated DBs (#75902) 2026-06-16 21:00:58 +02:00
Riley Thompson
ba3ba7cdc0 Prefer adding field to join with same join alias (#75917) 2026-06-16 20:55:40 +02:00
Copilot
ba5883cd44 Add CFP Franc (XPF) to currency list (#75906)
Add CFP Franc (XPF) to currency list (fixes #42129)

Co-authored-by: copilot-swe-agent[bot] <198982749+Copilot@users.noreply.github.com>
2026-06-16 20:42:34 +02:00
technomancy
95f1ed9b8d Disable multithreading for tests under snowflake and bigquery. (#75948) 2026-06-16 11:14:07 -07:00
Alexander Polyankin
6bc02506d7 Cache empty query results (#75946) 2026-06-16 11:08:28 -07:00
Oreon Lothamer
890a48bc56 PR-Env-Stats-Dump creates PR env with stats db (#75367)
* PR-Env-Stats-Dump creates PR env with stats db
2026-06-16 07:51:20 -10:00
Timofey Kachalov
ffe60b4f05 Do not show the sdk-disabled usage problem on localhost (#75930) 2026-06-16 20:34:13 +04:00
appleby
3c173a9fcc Fix translation of aisdk error parts (#75913)
* Handle response.failed in openai->aisdk-chunks-xf

Bedrock was sending this due to server error for GPT models in certain regions.

* Handle response.incomplete in openai->aisdk-chunks-xf

* Ensure :error parts are correctly translated in aisdk-chunks->part

Providers return aisdk v5 format :errorText, anything consuming internal-format parts expects :error instead. Make
sure to do the translation in aisdk-chunks->part. This was causing us to drop streaming errors and fail to report them
in the UI or persist them to MetabotMessage, so they never got surfaced in the AI usage analytics Conversations view.

* Log LLM provider in-stream errors in report-aisdk-errors-xf
2026-06-16 09:25:51 -07:00
Andrei Chernykh
3d290b8530 Convert QueryVisualization components to TypeScript (#75684) 2026-06-16 09:21:22 -07:00
github-automation-metabase
195fff76b2 Auto-update documentation for master (#75907)
Update generated docs (master)

Co-authored-by: github-actions <github-actions@github.com>
2026-06-16 12:19:07 -04:00
metamben
2cdb98f44a Add missing dimensions in underlying-records drill-thru (#75048) 2026-06-16 18:55:25 +03:00
Riley Thompson
ca7f3468ab Use desired column alias when merging model metadata (#75884)
* use desired column alias

* remove legacy conversion in test

* fix kondo
2026-06-16 11:00:55 -04:00
Eric Normand
6cc41b5ad9 Surface YAML parse reason in remote-sync ingestion errors (#75896)
* Surface YAML parse reason in remote-sync ingestion errors

When a pull/ingestion failed on an unreadable or unparseable file, the
error only named the file ("Failed to read N file(s) during ingestion:
<path>"), giving no clue why. The underlying cause was preserved in the
exception chain but never rendered.

- ingestable.clj: read- and parse-failure ex-infos now carry a concise,
  machine-readable :reason in ex-data. For YAML errors the reason is the
  SnakeYAML problem plus its 1-based line/column (its message's first line
  is a generic context wrapper, so first-line alone is unhelpful).
- impl.clj source-error-message: render one line per failed file with its
  :reason, so the sync-error modal explains the failure.

* Render ingestion error as a single line

The modal shows the error in a plain <Text> that collapses newlines, so
the per-file bullet list rendered as a run-on line. Join files with '; '
on one line instead. The machine-readable :file/:reason stay in ex-data
for a structured display later.
2026-06-16 09:49:46 -05:00
Nick Fitzpatrick
89ec6adf08 Maps support static viz (#75387)
* Maps static viz

* adjustments

* linting error

* CI failures

* Sasha Feedback. Removing some duplication

* BE cleanup

* first pass

* second pass

* eastwood linter

* review bot - first pass

* bot review pass 2

* PR feedback
2026-06-16 20:18:56 +05:30
Nick Fitzpatrick
f8822cdd9c Object Detail static viz support (#75386)
* Object Detail static viz support

* adjustments

* braden-bot review
2026-06-16 18:20:01 +05:30
Nick Fitzpatrick
90d86d090c add documents to search on link dashcards (#75892) 2026-06-16 16:56:50 +05:30
Romeo Van Snick
c3590b13b0 Move DashboardApi to RTK hooks and update all callers (#75677)
* Add dashboard parameter-values RTK endpoints

Add getDashboardParameterValues and searchDashboardParameterValues query
endpoints to dashboardApi, mirroring the existing cardApi equivalents, and
forward dashboard_load_id through the getDashboard query. Introduces the
DashboardParameterValuesRequest and SearchDashboardParameterValuesRequest
types in preparation for replacing the legacy DashboardApi client.

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

* Migrate DashboardApi callers to RTK and remove it

Replace the legacy DashboardApi client with the RTK dashboardApi endpoints:
get -> getDashboard, parameterValues/parameterSearch -> the new dashboard
parameter-values queries. Imperative thunk callers dispatch the endpoints
via runRtkEndpoint / initiate, matching the existing cardApi patterns. Drops
the obsolete DashboardApi jest mocks and removes DashboardApi from services.

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

* Avoid mutating frozen RTK Query dashboard result in fetchDashboard

The `else` branch of `fetchDashboard` now reads the dashboard through the
`getDashboard` RTK Query endpoint, whose responses are deeply frozen. The
virtual-card merge mutated the dashcards in place, throwing "Cannot assign to
read only property" and breaking dashboard rendering. Rebuild the dashcards
immutably instead.

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

* Wire abort signal through runRtkEndpoint in fetchDashboard

`runRtkEndpoint` now accepts an optional `signal` that it wires to RTK Query's
`.abort()`, so imperative callers can cancel in-flight requests. Pass
`fetchDashboardCancellation.signal` to the `getDashboard` call so starting a
new dashboard fetch cancels the previous one again, as it did before the
migration off `DashboardApi.get`.

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

* Clean up RTK Query subscriptions in error-page entity fetch

`getEntityDetails` dispatched `initiate(...).unwrap()` for cards and dashboards
without ever unsubscribing, leaving long-lived subscriptions in the store.
Route both through `runRtkEndpoint`, which unsubscribes in a `finally`.

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-06-16 21:12:21 +10:00
Kamil Mielnik
ad68687351 GDGT-2631 Fix name input border cut off on hover (#75923) 2026-06-16 11:06:28 +00:00
Uladzimir Havenchyk
1e99cb10aa chore: replace easy deprecated Button call sites with metabase/ui Button (#75790)
* chore: replace easy deprecated Button call sites with metabase/ui Button

* chore: simplify migrated button call sites

- Scope EditBar button styling to ButtonsContainer so it can't leak into
  the title/center slots, and raise its specificity above the metabase/ui
  variant hover rules; collapse the subtle/filled selector pair to
  button[data-variant]
- DatabaseSectionField: use the size="compact-sm" prop pattern of its
  sibling section fields and drop its CSS module
- DisconnectButton: size via the ActionIcon size prop instead of CSS
  dimension resets; drop declarations the subtle variant already provides
- Replace single-rule filterButton class with m="sm"; remove no-op CSS
  (createTabButton padding, SnippetButton brand color)
- Dedupe the repeated inline action types in the card reducer

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

* chore: migrate ActionButton to metabase/ui Button

ActionButton now renders the Mantine Button; the success/failed states
use variant="filled" with the success/error theme colors instead of the
legacy ButtonsS classes. Consumer flags map 1:1 (primary -> filled,
danger -> filled error, success borderless -> filled success), and the
edit-bar save buttons use size="sm" to match their migrated cancel
buttons. With no legacy buttons left inside EditBar, its ButtonsS
selectors are gone too.

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

* fix: keep "Show error details" as an inline text link after Button migration

The deprecated onlyText Button rendered as an inline text link (~90x13);
variant="subtle" alone kept Mantine's default md box (146x40), enlarging
the control and shifting the error-modal layout. Restore the inline look
with the size="xs" h="1rem" p={0} idiom.

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

---------

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-06-16 13:39:14 +03:00
Nicola Mometto
00ec2a1dea Generate athena pom on publish (#75925) 2026-06-16 12:35:04 +02:00
Nemanja Glumac
c8350535e7 Design the autonomous e2e flake fixer (#75909)
Replace the human push-approval gate with a branch-existence dedup check:
the branch name is derived solely from the Linear ref
(automated-e2e-flake-fix-<TEAM_SLUG>-<ISSUE_NUMBER>), and an existing remote
branch means a run is already in flight — otherwise it's a go, no approval.
The command stays identity-agnostic, so a human locally and an automated
trigger run the same path.

Also: prefer Linear MCP with a REST/GraphQL fallback for headless runs,
drop the poll cadence to 15 minutes, and lead the Linear audit-trail
comment with total time spent and tokens used.

* Add claude-e2e-flake-fix workflow for autonomous e2e flake fixing

Runs /fix-flaky-test headlessly as the Metabase Automation user, triggered
by workflow_dispatch or repository_dispatch (e.g. from ci-conductor) with a
Linear issue ref. ci-conductor only dispatches; the agent runs here, in CI.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-16 09:56:33 +02:00
appleby
9f71763026 AWS Bedrock support (#75685)
* openai s/:max_tokens/:max_output_tokens/

Prevents errors like the following when using openai provider

  Provider API request failed: provider=openai status=400 body={:error {:message "Unknown parameter: 'max_tokens'.", :type "invalid_request_error", :param "max_tokens", :code "unknown_parameter"}}

* openai: do not attempt to set temperature on models that do not support it

for example, gpt-5 and the o-series models

* openai: ignore reasoning chunks in openai->aisdk-chunks-xf

* bedrock: raise max-tokens for suggested prompts generator

* BOT-1663 Metabot support for AWS Bedrock provider

* Drop custom SigV4 implementation in bedrock provider and use AwsV4HttpSigner instead

* vibed admin UI changes for configuring bedrock provider and creds

* Validate bedrock creds before save and unify creds handling with api-key providers

- fix metabot.settings/configured-provider-api-key to return a creds map not api key
- modify provider-models-response and list-models to take a creds map rather than api key
- update various other places that expected api-key only
- ensure bedrock provider supports "Disconnect" button in admin UI
- drop Fable models for now

* admin UI change to support bedrock disconnect via :credentials nil

* BE: rename api-key errors -> credentials

* FE: rename api-key errors -> credentials

* Reject ai-proxy requests early in bedrock provider

Supporting this would require some work on the ai-service proxy side, so reject it with a clear error message for now,
but also update the bedrock provider to use core/resolve-auth and core/request so that it's easy to add support in the
future if we decide to.

* feat: admin ui for amazon bedrock (#75805)

* Fix docstrings

* Fix race in extraction-metrics-test

* review feedback: fix clearing of session token and region

* Ensure that a Disconnect in the admin UI clears the AWS region as well

---------

Co-authored-by: Maksym Yakubych <undrfined@gmail.com>
2026-06-15 16:03:20 -07:00
metamben
88fd6b6d90 Add test showing that day-of-week is not a temporal on the next stage (#75821)
Closes QUE2-249
2026-06-15 22:55:37 +00:00
Kevin Kelleher
f9aa7966d3 Fix axis labels being cut off when rotated 45 degrees (#75815)
* fix axis labels being cutoff when rotated 45 degrees

* add png, split stories into files

* try to fix default export error, add comment
2026-06-15 17:42:30 -04:00
Nemanja Glumac
4c586296a9 Pass build_jar to stress-test workflow in /fix-flaky-test (#75891)
The e2e-stress-test-flake-fix workflow gained a build_jar input that
builds the uberjar from the branch instead of downloading a prebuilt
ancestor JAR. Teach the command to set it: build whenever any commit on
the branch touches source (backend or frontend), keeping it on for later
test-only attempts; skip the build only when every commit is test-only.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-15 23:39:01 +02:00
mendral-app[bot]
08e62e754d Use env var indirection in team-issues-slack-notification (#70291)
Co-authored-by: mendral-app[bot] <233154221+mendral-app[bot]@users.noreply.github.com>
2026-06-15 23:34:45 +02:00
da
f3d28fd439 Update row and column security information for databases (#75885)
* Update row and column security information for databases

Clarified that both MongoDB and Druid support only row-level security and do not support column-level security.

* Update docs/permissions/row-and-column-security.md

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

---------

Co-authored-by: Jeff Bruemmer <jeff.bruemmer@gmail.com>
2026-06-15 18:16:38 -03:00
thackervishal
d7a5482a8a DOC-fix bug in keycloak page + minor improvements (#75813) 2026-06-15 16:51:03 -04:00
Stas Gavrylov
0f5bed6ad7 GDGT-2579: Replace deprecated EntityMenu internals with Mantine Menu (#75637)
* Refactor EntityMenu to use Menu inside

* GDGT-2579: Remove unused EntityMenu paths. Cleanup

* GDGT-2579: Use Menu directly instead of EntityMenu

* GDGT-2579: Cleanup following comments

* wip

* Fix detail view actions menu hotkeys

* GDGT-2579: Remove legacy wrappers

* GDGT-2579: Cleanup

* GDGT-2579: Get rid of EntityMenuTrigger component

* GDGT-2579: Cleanup

* GDGT-2579: Fix tests

* GDGT-2579: Address review comments

* GDGT-2579: Apply PR comments

* GDGT-2579: Update 'disabled' handling logic
2026-06-15 21:45:42 +01:00
Andrei Chernykh
e49ba02621 Hide public link options from non-admins and when public sharing is disabled (#75681)
* Hide public link options from non-admins and when public sharing is disabled

* Update public link copy tooltip

* Redesign sharing menus with Copy link and Embed header actions for admins and a public link copy for non-admins

* Hoist repeated card action types in the QB reducer to fix a TS2589 instantiation-depth error

* Make sharing menus regular menus with an always-available app link copy and a separate public link copy for non-admins

* Clean up sharing menu leftovers: dead props, unused testid, repeated test setup, and explicit resource branches in e2e

* Update stale Loki reference for the dark-theme embed download story

* Revert "Update stale Loki reference for the dark-theme embed download story"

This reverts commit a3b9c8f70c.

* Update permissions e2e for the always-present non-admin copy button

* Drop unused onCopied prop from CopyLinkMenuItem; use createMockDashboardTab in its spec
2026-06-15 12:32:19 -07:00
metabase-bot[bot]
e5d0ac1636 [chore] Update E2E test timings with recent data (#75840)
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-06-15 21:09:48 +02:00
technomancy
0a858152c1 Fix a very foolish mistake around percentages for health inspector. (#75890)
Add a test that catches this.
2026-06-15 18:36:59 +00:00
Nemanja Glumac
f1fd89c939 Allow info level driver runs (#75648)
* mage: read driver skip/info status from ci-test-config

Replace the legacy `ignored.drivers` quarantine list with the new top-level
`drivers` array in ci-test-config.json, where each entry carries a status:

  skip      -- do not run the driver (quarantined; break-quarantine-<driver> overrides)
  info      -- run the driver, but its result must not gate (data collection only)
  required  -- not listed: runs and gates as usual (the default)



Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-15 20:28:37 +02:00
Nick Fitzpatrick
dd1ec20321 Add support for pivot table static viz (#75337)
* Add support for pivot table static viz

* review feedback

* Move pivot postprocess into the pivot module

* deduplicate formatters

* formatting

* fix CI
2026-06-15 23:40:56 +05:30
technomancy
b0da250e69 Temporarily remove belize test and create-replace-table test in snowflake (#75830)
Temporarily comment out problematic tests.

These tests are quarantined, so they don't affect pass/fail
status. However, by examining CI logs, it appears that it's very
common for seemingly-unrelated failures to happen immediately
following one of these failures. Let's see if this still happens when
they don't run at all!
2026-06-15 11:03:51 -07:00
Andrei Chernykh
c1c9bb4f1c Convert SnippetSidebar to TypeScript (#75659)
* Convert SnippetSidebar to TypeScript

* Replace ComponentType<any> in snippet sidebar row renderers with a typed plugin contract
2026-06-15 09:02:50 -07:00
Alex Yarosh
a3176eb0ca docs: erd (#75647)
* erd

* Optimized 1 images, saved 134.0 KB (43.4% smaller)

* link sprinkling

* Apply suggestions from code review

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

* Apply suggestions from code review

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

---------

Co-authored-by: Metabase Automation <github-automation@metabase.com>
Co-authored-by: Jeff Bruemmer <jeff.bruemmer@gmail.com>
Co-authored-by: Michael Eby <38187276+michaeleby1@users.noreply.github.com>
2026-06-15 11:12:03 -04:00
github-automation-metabase
3fbfb979e8 fix(test): resolve flaky TablePicker visibility layer test (#75721)
* fix(test): resolve flaky TablePicker visibility layer test

Consolidate all virtualizer-dependent assertions into a single waitFor
block with a 5000ms timeout. The virtualizer's async layout cycle
(containerRef → measureElement → render rows) can exceed the default
1000ms timeout under CI load, causing intermittent failures.

Fixes UXW-4469

* fix: use single assertion in waitFor to satisfy eslint rule

* Properly mocking ResizeObserver

* Don't click the table row

---------

Co-authored-by: Nick Fitzpatrick <nickfitz.582@gmail.com>
2026-06-15 20:41:33 +05:30
Alex Yarosh
33d8adc109 docs: collections in the library (#75448)
* collections in the library

* Optimized 3 images, saved 123.3 KB (51.4% smaller)

* Apply suggestions from code review

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

* edits from jeff

---------

Co-authored-by: Metabase Automation <github-automation@metabase.com>
Co-authored-by: Jeff Bruemmer <jeff.bruemmer@gmail.com>
2026-06-15 11:10:05 -04:00
Riley Thompson
5af51e630d Check custom aggregations don't contain unaggregated refs (#75797)
* add test to prove fixed

* check for unaggregated refs

* fix typo and test
2026-06-15 14:36:44 +00:00
Egor Grushin
f44a41ead4 GDGT-2615 Replace deprecated TippyPopover component (#75668)
* GDGT-2615 fix PopoverWithRef

* GDGT-2615 migration step 2. (checks 1–6 are passed)

* GDGT-2615 migration step 3 put comments

* GDGT-2615 fix comments

* GDGT-2615 fix test

* GDGT-2615 fix test

* GDGT-2615 fix test

* GDGT-2615 fix test

* GDGT-2615 fix test

* GDGT-2615 fix test

* GDGT-2615 fix test

* GDGT-2615 move tippy-leftovers to tooltip folder

* GDGT-2615 fix import import "metabase/common/components/Tooltip/tippy.module.css";

* GDGT-2615 fix SDK tests

* GDGT-2615 address the PR's comments

* GDGT-2615 fix test

* GDGT-2615 fix a regression

* GDGT-2615 fix a regression

* GDGT-2615 addressed the review's comments

* GDGT-2615 addressed the review's comments
2026-06-15 13:46:50 +01:00
Oleh K
348c513d47 Restyle Chip component according to Figma spec (#74769)
* Rework Chip story and add reusable Storybook showcase helpers

Turn the Chip story into an overview showcase (sizes section plus a column
per variant with all interactive states, hover/pressed via
storybook-addon-pseudo-states) and extract the layout into a reusable
metabase/ui/stories/showcase module: StoryShowcase, StorySection, StoryRow,
StoryCode, and StoryJsx (a small JSX syntax highlighter).

* WIP: restyle Chip to Figma spec with semantic tokens

Restyle the Chip to match the updated Figma spec (GDGT-2483) using
semantic --mb-color-* tokens throughout — light/filled variants, sm/md
sizes, and the full state matrix (default / hover / pressed / selected /
hover-selected / disabled / disabled-selected). Sizes are wired via a
Mantine vars resolver; per-state styling is keyed off data-variant on
the root and data-checked/data-disabled on the label. Adds data-force-*
hooks so the showcase can render hover and pressed states statically.

Migrates the two existing call sites (BaseSMTPConnectionForm,
WebhookForm) from the invalid variant="brand" to variant="filled".

* wip: chip

* Align Chip colors with updated Figma semantic tokens

Switch to the post-refactor (GDGT-2517) role-based tokens design now binds in
Figma: neutral background_surface-secondary(-hover/-pressed) for unchecked
states, background_surface-brand-subtle + text-brand-strong for selected light,
background_surface-brand-strong for selected filled, and the corresponding
-hover variants. Also renames background-disabled/text-tertiary to
background_surface-disabled/text-disabled.

* Add Chip Overview story to Loki visual regression tests

* Format

* Add Loki reference for Chip Overview story

* Remove redundant comments from Chip restyle

* Cleanup

* Address review comment

* Cleanup
2026-06-15 11:47:28 +00:00
Sébastien
e860f98a43 Fix Guest embed options staying disabled until SSO terms are accepted (#75794) 2026-06-15 12:54:38 +02:00
Fraser
5fabe396ab Fix selectors/app module-boundary violations (#75777) 2026-06-15 21:14:36 +12:00
Sébastien
b55bed1cc1 Fix history.back 404 when Metabase is under a sub-path in interactive embedding (#75700) 2026-06-15 10:42:42 +02:00
Nicola Mometto
04bfeb20f6 deleted database handling for transforms (#74829)
* wip

* wip: fe

* tests

* tests

* serialize as tombstone

* mark dead transforms as stale

* fix tests

* fix

* fix migration

* move check

* fix FE when no dbs are available

* fix e2e test

* handle nil database in validation

* fix for broken dependency surfacing

* fix comment

* lenient for serdes

* fix: don't display while loading

* refactor

* handle migration comments

* move migration to 60

* handle N+1 in batched-hydrate for source-readable? by providing a per-model cache

* refactor

* random ids
2026-06-15 09:34:54 +01:00
Romeo Van Snick
94487e88fe Move AutoApi to RTK hooks and update callers (#75774)
* Add getXrayDashboard RTK endpoint to automagic-dashboards API

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

* Migrate AutoApi callers to RTK hooks and remove AutoApi

Use the getXrayDashboard RTK endpoint instead of the legacy AutoApi.dashboard
service: the embedding-hub x-ray picker uses the useLazyGetXrayDashboardQuery
hook, and the transient dashboard fetch dispatches the endpoint via
runRtkEndpoint alongside the existing query-metadata fetch.

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

* Remove :tag* raw-substitution special case from substituteUrlTags

AutoApi.dashboard was the only route using a multi-segment :tag* placeholder,
and it now builds its URL directly through the RTK endpoint. With no remaining
callers, drop the raw-substitution branch so every URL tag is URL-encoded.

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

* Propagate abort signal through runRtkEndpoint for transient x-ray fetch

The transient-dashboard branch lost abort support when AutoApi.dashboard moved
to runRtkEndpoint: rapid dashboard navigation could leave stale in-flight
requests and apply late state updates. Thread an optional AbortSignal through
runRtkEndpoint that calls the RTK Query action's abort(), and pass
fetchDashboardCancellation.signal to both transient x-ray fetches.

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

* Guard getXrayDashboard against path-traversal in user-controlled subPath

The transient x-ray subPath comes from the /auto/dashboard/* route (splat +
location hash), so it is user-controlled and embedded raw into the request URL.
Reject '.'/'..' path segments in the getXrayDashboard query so a crafted URL
cannot walk out of the automagic-dashboards route into another same-origin
endpoint. Validating in the API query keeps the check at the source for every
caller.

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-06-15 15:55:23 +10:00
Romeo Van Snick
f635373830 Move ActivityApi into metabase/api and update callers (#75773)
* Add getMostRecentlyViewedDashboard RTK endpoint

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

* Migrate AddToDashSelectDashModal off ActivityApi to RTK hook

Replace the useAsync-based useMostRecentlyViewedDashboard wrapper with the
useGetMostRecentlyViewedDashboardQuery RTK hook and drop ActivityApi from
services.js.

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

* Test getMostRecentlyViewedDashboard tag invalidation

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

* Use findRequests in activity API spec (review feedback)

Replace the fetchMock.callHistory.calls(...) call counters with the shared
findRequests helper, per review. The helpers become async (findRequests flushes
call history and returns the matching requests), so the waitFor callbacks await
them.

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-06-15 15:23:22 +10:00
Fraser
c8535a0013 Fix VisualizationResult violations (#75671) 2026-06-15 14:39:46 +12:00
YB
58d6210131 [GDGT-376] [GDGT-2623] fix serdes export oom and n+1 table lookups (#75595)
* fix serdes export oom and n+1 table lookups: tally :seen as a frequency map and cache table-fk resolution

* formatting

* narrow table and database selects in export-table-fk resolver

* use export-resolver for database lookup

* use u/safe-inc and rename export report :seen to :entity-counts

* add comment on intentionally not routing field lookups through cached resolver
2026-06-15 10:10:56 +08:00
Romeo Van Snick
9cdd481113 Move metrics to feature tier (#75776)
* Extract shared metric primitives to common/metrics

Move the FilterPicker and TemporalBucketPicker components, the metric
dimension/date utilities, and the core metric types out of
metabase/metrics into the shared-tier metabase/common/metrics. These are
the only pieces of metrics that shared-tier consumers (metrics-viewer,
urls) depend on. Relocating them lets metrics become a feature-tier
module in a follow-up without creating shared -> feature import
violations.

Pure relocation: no behavior changes, only file moves and import path
updates.

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

* Move metrics module to the feature tier

With the shared metric primitives now living in common/metrics, nothing
in the shared tier reaches into metabase/metrics anymore. Reclassify it
as a feature module so the boundary linter enforces that it can only be
consumed by other feature modules (enterprise, public) and the app
shell.

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-06-15 11:57:17 +10:00
Romeo Van Snick
97c046ec87 Move metabase/metrics-viewer to the feature tier (#75775)
* Extract metrics-viewer URL-state codec into shared common/metrics-viewer

The metrics-viewer URL-state codec is the contract shared between code
that builds deep-links into the viewer (shared `urls`/`metrics`) and the
viewer itself. Extract it into a new shared module so the viewer can move
to the feature tier without shared modules importing across the boundary.

- common/metrics-viewer/compact-schema.ts: moved verbatim from the feature
- common/metrics-viewer/types.ts: relocated MetricsViewerDisplayType,
  MetricsViewerDimensionBreakoutType, DimensionFilterValue
- common/metrics-viewer/url-state.ts: serialized types, compact schemas,
  encodeState/decodeState (pure, no metabase-lib runtime dependency)

The metabase-lib-bound live-state conversion stays in the feature's
url-serialization.ts, which now imports the codec from common and
re-exports it; viewer-state.ts and dimension-filters.ts re-export the
relocated types so internal call sites are unchanged. urls/metrics.ts now
imports the codec from common.

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

* Move metrics-viewer FE module to feature tier

Reclassify metrics-viewer from the shared tier to the feature tier now
that the shared URL-state codec it exposed lives in common/metrics-viewer.
No shared module imports the viewer across the boundary anymore, so the
move introduces no new module-boundary violations.

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-06-15 08:49:38 +10:00
Maksym Yakubych
91628d34bf feat: inline charts (#75550) 2026-06-13 03:52:20 +00:00
Alexander Polyankin
e6670cff35 Fix flaky with-query-execution! test helper delivering stale batched executions (#75831) 2026-06-13 01:28:29 +00:00
Maksym Yakubych
55682e2e8c feat: full screen ai exploration page (#75502)
Closes [BOT-1667: Full-screen AI Exploration page](https://linear.app/metabase/issue/BOT-1667/full-screen-ai-exploration-page)

### Description

It's a full-screen AI Exploration page. Now, instead of opening the sidebar to display the chat with Metabot, it will be on its own page. 

### How to verify

1. Press New, then AI exploration.
2. Send a message to Metabot.

### Demo

_Upload a demo video or before/after screenshots if sensible or remove the section_

### Checklist

- [x] Tests have been added/updated to cover changes in this PR
- [x] If adding new Loki tests: they pass [stress testing](https://github.com/metabase/metabase/actions/workflows/loki-stress-test-flake-fix.yml)
2026-06-12 20:31:59 -03:00
Stas Gavrylov
eacd80a882 GDGT-2617 Hide Security Center setup prompt from non-admins (#75690)
* Hide Security Center setup prompt from non-admins (GDGT-2617)

The SecurityCenterPromoCard rendered for all users in the navbar promo slot,
but links to the admin-only /admin/security-center route, so non-admins hit a
permission error on click. Gate the card on getUserIsAdmin and skip its
admin-only RTK Query requests for non-admins.

* GDGT-2617: Refactor tests

* GDGT-2617 small adjustment

---------

Co-authored-by: Egor Grushin <egor@metabase.com>
2026-06-12 23:59:57 +01:00
Alexander Polyankin
5d1dd5c032 Improve app db connection pool usage with public dashboards (#75770) 2026-06-12 21:17:45 +00:00
Anderson
938ce52bb0 Make metric viewer controls responsive (#75250)
* Add responsive metric viewer controls

* Add dedicated css module files / break down components / Clean up props / Simplify test approach

* Address review comments
2026-06-12 17:14:34 -03:00
thackervishal
9e1b5779f9 docs: update session expiration page. (#74936)
* docs: update session expiration page. Restructures around how MAX_SESSION_AGE, MB_SESSION_TIMEOUT, and MB_SESSION_COOKIES interact
* Updates based on PR feedback

Co-authored-by: Alex Yarosh
2026-06-12 14:21:10 -04:00
technomancy
38fba4025f Avoid recreating datasets in snowflake (#75682)
* Fix describe-database-test in two namespaces to use sets.

This shouldn't be asserting about the full set of tables, just that at
least these tables exist.

* Stop deleting old datasets snowflake driver.

Turn off dynamic dataset loading support.

This is just too unreliable given the race conditions we see in cloud databases.

* Fix some other describe-database tests to assert subset of table names.
2026-06-12 11:19:02 -07:00
Chris Truter
23269606df Guarantee correctness for the search permissions fast path (#73037)
* Guarantee correctness for the search permissions fast path

Semantic search's read filter has a fast path for models whose read permission is a pure function of their denormalized `:collection_id`. Membership in that fast path was a hardcoded map, trusted by hand to stay in sync with each model's actual `mi/can-read?` — a silent-drift hazard: change a model's read perms and the map keeps routing it through the fast path with stale semantics.

Make the declaration authoritative. A model opts in with `define-collection-based-visibility!`, the single source of truth:

- t2-model form: installs `mi/can-read?` as a delegate to the shared `perms/can-read-via-parent-collection?` AND registers the model, in one call — so a model can't be in the fast-path set unless its `can-read?` is genuinely collection-id-only.
- search-model (string) form: registers a search-model whose index-row `:collection_id` is denormalized from a parent at index time (e.g. "indexed-entity" from its parent Card), with a required `:denormalized-from`.

Semantic search derives its fast-path set from these registries (running `search/specifications` first so the model namespaces load before the registries are read; wrapped in a `delay`). The fast path then calls the same helper the slow path installs, so the two can't diverge.

Guards: an identity-check test fails if anyone re-`defmethod`s `mi/can-read?` over a registered model; a contract test structurally traces each `:denormalized-from` claim through the spec's join-equality graph; a cold-start regression pins the specs-before-registry load order.

* Structurally verify keyword-form-derived fast-path search models

The :denormalized-from contract test only covered string-form
registrations. Keyword-form-derived siblings (card/dataset/metric/
dashboard) were swept into the collection-id-only fast path purely
because their spec's :model is a registered t2-model, with no check
that the index row's :collection_id is the entity's own collection.

Add a contract test asserting that, for each keyword-form-derived
search-model, tracing :collection-id through join equalities reaches
the spec's own registered t2-model -- so a future sibling sourcing
:collection-id from a join fails the test instead of silently gaining
incorrect read semantics.

* Guard against vacuous pass in keyword-form fast-path trace test

Add an (is (seq registered-t2-models)) assertion so the test fails
directly if the t2-model registry is ever empty, rather than silently
no-op'ing when the :when filter matches nothing.
2026-06-12 10:23:43 -07:00
thackervishal
8649b4126b DOC - one word fix in models intro (#74609)
* one word fix in models intro
* Update docs/data-modeling/models.md

Co-authored-by: Jeff Bruemmer <jeff.bruemmer@gmail.com>
2026-06-12 13:21:23 -04:00
Uladzimir Havenchyk
3e1f4bd247 fix: add optimistic updates for comments api in documents with many cards (#75763)
* fix: invalidate in-flight queries

* cleanup test

* use different approach

* update comment

* update comments
2026-06-12 16:59:47 +00:00
Riley Thompson
25a108bfb0 Fix quick filter on binned columns (#75767)
apply binning to column in quick filter drill thru
2026-06-12 12:55:34 -04:00
Riley Thompson
a989608ef6 Preserve column selection on joined tables in drill through (#75617)
* only use fields from join in drill thru

* improve and add test
2026-06-12 12:54:56 -04:00
Riley Thompson
498c7e3552 Fix self join column remapping (#75339)
* skip if same join alias

* add test
2026-06-12 12:48:16 -04:00
Eric Normand
a37645a74a Fix restoring items from a remote-synced collection (#75766)
The remote-synced dependents check in check-for-remote-sync-update fired
on any change to :archived, so restoring (true->false) an item in a
remote-synced collection threw "Used by remote synced content." — the
item's own containing collection is reported as a dependent. Guard the
check so it only runs when archiving (false->true), where blocking on
real dependents is the intended behavior.

Fixes GHY-3821
2026-06-12 11:12:22 -05:00
Tyler Plude
70da910602 [BOT-1685] Fix UX of Metabot inline SQL search (#75772)
* Scope inline SQL @-mention search to the selected database via table_db_id

* Recreate the Metabot prompt tiptap editor on database change so @-mention scoping doesn't use a stale onlyDatabaseId
2026-06-12 08:26:50 -07:00
Eric Normand
0376648dc8 GHY-3726 merge non-conflicting remote changes on export instead of blocking (#75050)
* GHY-3726 merge non-conflicting remote changes on export instead of blocking

When the remote branch had advanced past the last synced version, export
hard-failed ("Cannot export changes that will overwrite new changes in the
branch") even when local and remote touched different entities, deadlocking
push and pull.

Export now performs a 3-way merge keyed on serdes identity (model + id)
rather than on-disk path -- paths are derived from entity/collection names,
so a path-keyed merge would corrupt on renames/moves (duplicate entity_ids,
false conflicts). Non-conflicting remote changes are merged in, the merge
commit fast-forwards onto the remote tip, and the merged result is loaded
back into the local app DB (the pull half). Genuine same-entity conflicts
return a :conflict result; force still overwrites; an orphaned merge base
(force-push/rebase) surfaces as a conflict.

- merge.clj: entity-identity three-way-merge + conflict-label
- source.clj: serialize-specs, merge-and-store!
- git.clj/protocol.clj: snapshot-at
- impl.clj: export! merge/reconcile path, factored load-snapshot!

* GHY-3726 make merge an explicit user choice (preflight) instead of auto-merging

Reworks the push UX so merging is a deliberate option rather than something that
happens silently on push.

Backend:
- Gate the 3-way merge behind an explicit :merge? flag. A diverged export with
  neither force nor merge now returns :conflict (the UI decides how to proceed)
  rather than auto-merging.
- Add impl/preview-export-merge + source/preview-merge: a dry-run that reports
  {has_changes, clean, conflicts, summary, reason} without writing.
- New GET /export-preflight endpoint; :merge param on POST /export.

Frontend:
- Push now runs the preflight first. If the remote has advanced it opens the
  conflict modal offering Merge (when clean), Force push, Create new branch, and
  Cancel; a genuine conflict drops Merge and lists the conflicting entities.
- Merge action calls export with merge=true; commit message threads through.
- Invalidate all content tags after any successful sync (a merged export changes
  local data), and stop mapping export-task conflicts to the "setup" modal.

* GHY-3726 add local-only merge to the pull path

Pull now offers the same Merge affordance as push, but merges into local only
(the push is left for later) so a coworker's branch changes can be brought in
without discarding un-pushed local edits.

Backend:
- import! gains a :merge? flag → import-merged!: a local-only 3-way merge that
  loads the merged result into the app DB without writing to the remote.
  Remote-originated changes end up synced; un-pushed local changes are preserved
  as dirty (captured before the load and restored after, including pending
  deletions). Sets last-version to the remote tip so the branch is no longer
  behind. Genuine conflicts and an orphaned base return :conflict.
- source/compute-merge made public; source/specs->snapshot builds an in-memory
  snapshot so merged content can be loaded without going through git.
- :merge param on POST /import.

Frontend:
- Pull with un-pushed local changes runs the export preflight, then opens the
  conflict modal: clean → Merge (local) / Force push / New branch / Discard;
  conflict → drops Merge and lists the conflicting entities. Read-only keeps
  Discard-only. Merge on the pull variant calls import(merge=true).

* GHY-3726 run export preflight on push click for a single-modal flow

Previously, pushing when the remote had advanced showed two modals: the commit
form, then (after submit) the merge/conflict modal. Now the export preflight
runs when the user clicks Push, so we open the correct modal directly:
- remote unchanged -> commit-message modal (plain push)
- remote ahead     -> merge/conflict modal straight away

The commit-message field moves into the conflict modal's push variant (merge /
force / new branch all push), so there's a single modal in every case.

* GHY-3726 show entity name (not entity_id) in merge conflict labels

conflict-label now parses the entity's name from the serialized content and
shows e.g. "Card A (collections/.../card_a.yaml)" instead of the raw serdes
"Card <entity_id>". Falls back to model + id when the content has no name.

* GHY-3726 fix CI: implement snapshot-at on remaining Source mocks, mock export-preflight, stabilize merge API tests

After merging master:
- Add snapshot-at to the Source mocks that lacked it (api_test missing-branch /
  failing sources, wrapping_source_test) so clj-kondo's protocol-method check passes.
- Mock the new /export-preflight (and /export) endpoints in the shared remote-sync
  test server-mocks, fixing GitSyncControls unit test's unmocked-request failure.
- Stub load-snapshot! in the export/import merge API tests: the heavy app-DB
  reconcile load inside the async task is slow/racy on the MySQL/MariaDB app-db
  matrix; merge correctness is covered synchronously by impl-test.

* GHY-3726 reject branch-mismatch on export/preflight (multi-tab CAS guard)

Make branch a required param on POST /export and GET /export-preflight and
reject the request (409 with branch_mismatch + current_branch) when it
disagrees with the authoritative remote-sync-branch setting, so a stale tab
can't push to or preview the wrong branch after another session switched
branches. Thread the validated branch into preview-export-merge. Also fixes
a pre-existing dropped body schema on /export (misplaced ]).

Frontend surfaces the mismatch as a 'this view is out of date' modal with a
Refresh action on both push and pull, instead of swallowing the preflight
error.

* GHY-3726 reject branch-mismatch on import via expected_branch token

/import handles both pull (branch == current) and branch switch (branch is a
different target), so a single branch param can't double as the CAS
assertion like it does on export. Add an optional expected_branch param =
the branch the client believes is currently active; reject (409
branch_mismatch) when it disagrees with the remote-sync-branch setting.
Optional so scheduled auto-import and the admin-settings pull degrade safely.

Frontend sends expected_branch=currentBranch from the app-bar pull/switch and
the conflict-modal merge-import/discard flows.

* GHY-3726 make import expected_branch required

The CAS token is only a real guarantee if every endpoint caller must send it;
an optional token leaves the same opt-in hole we're closing, and is
inconsistent with export's required branch. The scheduled auto-import calls
impl/async-import! directly (not this endpoint), so only FE callers hit
/import and all of them have a current branch to assert. Wire the remaining
caller (admin-settings PullChangesButton) and guard currentBranch on switch.

* GHY-3726 surface branch-mismatch as refresh modal across all sync flows

Route every GitSyncControls catch (push preflight, dirty-pull preflight,
non-dirty pull, branch switch) through a shared showBranchMismatchIfPresent
helper that opens the 'this view is out of date' modal on a 409
branch_mismatch, instead of swallowing it or showing a generic toast.

* GHY-3726 make merge version/status bookkeeping atomic with the reconcile

load-snapshot! gains an optional :finalize! thunk that runs inside its existing
transaction (after remove-unsynced!/sync-objects!). Callers move their
version/status bookkeeping into it so it commits atomically with the
object-table reconcile, or rolls back together.

Closes two crash windows:
- import-merged! could permanently lose captured dirty markers if it died
  between the load (which marks everything synced) and restore-dirty-objects!
  (a retry's capture would then find nothing). Restore now commits with
  sync-objects! or not at all.
- export-merged! now advances the version only after the reconcile load, so a
  crash leaves it at the old base and a retry re-merges (the push is
  idempotent) instead of pointing past un-reconciled local state.

load-metabase! stays outside the transaction (unchanged).

* GHY-3726 fail loudly when a pushed merge commit can't be reconciled locally

export-merged! previously skipped the local reconcile (via when-let) if
snapshot-at returned nil for the just-written commit, yet still advanced the
version and marked everything synced — silently leaving local without the
folded-in remote changes. Throw instead: export!'s catch fails the task, the
version stays at the old base (set-version! is in the reconcile's finalize),
and a retry re-merges and reconciles. The push is idempotent.

* GHY-3726 test: pull merge folds remote change while keeping local deletion dirty

Combined round-trip covering the disjoint-change invariant: one merge applies an
unrelated remote change (folded in, synced) while a pending local deletion is
preserved as dirty via restore-dirty-objects!' re-insert branch, and the version
advances to the remote tip.

* GHY-3726 throw on duplicate entity_id within a merge side

index-by-key warned and silently overwrote when two specs on the same side
shared a serdes identity (same model + entity_id at two paths), dropping one
file — silent corruption. Throw instead so a duplicate entity_id surfaces.
Path-fallback keys (non-serdes files, unique paths) still only warn.

* GHY-3726 show busy state during preflight and toast when mergeability check fails

- Push and dirty-pull both await the export preflight (which re-serializes the
  library and reads remote trees); track it with isCheckingPreflight and fold
  it into the branch control's isLoading so the control shows a spinner and
  disables meanwhile, instead of looking idle.
- A dirty pull whose preflight fails for a non-branch-mismatch reason now toasts
  'Couldn't check whether your changes can be merged...' before opening the pull
  modal (without the merge option), rather than silently degrading.

Test asserts the toast via the undo store (the toaster isn't mounted in this
test harness).

* GHY-3726 fix two branch/merge bugs found in review

- Branch switch dropped .unwrap() on importChanges, so the CAS 409 resolved
  silently instead of throwing: no refresh modal and trackBranchSwitched fired
  as success. Add .unwrap() so it routes to the refresh modal. (review Issue 1)
- A dirty-but-up-to-date merge pull reported a spurious 'remote history was
  rewritten' conflict: async-import! left base-snapshot nil when the remote
  hadn't advanced, which import-merged! treated as an orphaned base. Resolve
  base to the remote tip when not diverged and no-op the merge (keep local
  dirty). Genuine orphaned-base/no-prior-sync still conflict. (review Issue 2)

Tests: clean-switch-rejected refresh modal; import merge no-op when the remote
hasn't advanced (drives async-import! base resolution, review Issue 3). Also
de-flaked two pre-existing race-prone pull tests by waiting for the dirty state
to settle before clicking.

* GHY-3726 review cleanup: atomicity, conflict surfacing, labels, logging

- Plain/force export now advances the version and marks objects synced inside a
  transaction (store! push stays outside), matching the merge path. (Issue 4)
- Export tasks that end in :conflict now toast 'the remote branch changed
  before your push finished...' instead of being silently swallowed by the
  listener middleware (covers the preflight->execute race). (Issue 5)
- conflict-label no longer destructures a [::by-path path] key into garbage
  model/id; uses the filename. (Issue 7)
- merge_test deftests marked ^:parallel. (Issue 9)
- entity-identity parse-failure log raised debug->warn so a malformed
  serialized file is visible. (Note B)
- Documented same?'s conservative cross-side-rename conflict edge. (Note A)

* GHY-3726 test async-{import,export}! base-snapshot resolution via a versioned fake Source

Per review: deeper coverage of the async-*! wrappers without a hand-built
:base-snapshot or stubbed compute-merge. Adds test-helpers/versioned-source (a
Source with a controllable current version + version->files map; snapshot-at
returns nil for an unreachable/orphaned base). Six tests drive the real base
resolution and real 3-way merge end-to-end (load-snapshot! stubbed-with-finalize
to skip the slow app-DB reconcile): not-diverged no-op keeps local dirty,
diverged resolves base and folds in a remote-only entity, base unreachable ->
conflict, no prior sync -> conflict; plus the export mirrors. This is the test
shape that would have caught the dirty-but-up-to-date false conflict directly.

* GHY-3726 rename SyncConflictModal mutation-wrappers.ts to hooks.ts

Per review (alxnddr): repo convention is hooks.ts. Pure rename + import update.

* GHY-3726 surface export-conflict toast via useToast in GitSyncControls

Per review (alxnddr): prefer useToast over addUndo. useToast is a hook and can't
run in the listener middleware, and the shared useSyncStatus hook mounts twice
(StatusListing + GitSyncControls) so it would double-toast. Move the toast to
GitSyncControls (single mount, already has sendToast, observes the task): on an
export task in conflict it toasts once via useToast then clears the task, which
also fixes the latent poll/refetch re-fire of the old middleware addUndo. The
middleware now just dismisses the modal for export conflicts. Drops the undo
reducer from the middleware spec; toast assertion moves to the GitSyncControls
spec.

* GHY-3726 test: force export overwrites upstream changes (full re-serialize)

A force export must drop files the remote diverged with — something the
incremental fast-path (which preserves every untouched file) cannot do. This
test shows the same upstream file is preserved by an incremental export but
removed by a force export, pinning force? = full re-serialize and guarding
against regressing to an incremental force.

* GHY-3726 implement apply-changes! on remaining SourceSnapshot mocks

The master merge added apply-changes! to the SourceSnapshot protocol; three of
my implementations didn't implement it, which clj-kondo flags (and CI fails on):
- source/specs->snapshot (in-memory read-only merge snapshot) -> throws
- source_test entities->snapshot -> records upserts like write-files!
- test_helpers versioned mock snapshot -> applies upserts/deletes, preserves the rest

* Send expected_branch in e2e read-write import helper

The /import endpoint requires expected_branch (CAS guard against stale
multi-tab clients). configureGitAndPullChanges' read-write path posted an
empty body, failing validation. Send expected_branch: "main" to match the
branch configureGit sets.

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

* Flatten nested conds in export!

The undiverged export path was an inner cond nested inside the outer
dispatch cond. Hoist its inputs (disabled-files, dirty-rows, plan) into
the let — gated so incremental-plan stays lazy on the force/merge paths —
and lift its three branches into the single top-level cond. No behavior
change.

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

* Update out-of-date push e2e test for preflight-first flow

The push redesign runs the export preflight on push-click and, when the
remote has advanced, opens the conflict modal directly instead of the
"Push to Git" commit-message modal. Update the out-of-date push test to
assert the conflict modal ("The remote branch has new changes…") and pick
"Create a new branch and push changes there" there, matching the new UX.
The stale two-step assertion was masked until the expected_branch helper
fix let setup succeed.

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

* Match either push conflict-modal title in out-of-date push e2e test

The 3-way merge in this scenario comes back as a conflict, not a clean
merge (the local re-serialization of the synced set isn't byte-identical
to base, so the remote-renamed question reads as changed on both sides),
so the modal title is "Some of your changes conflict with the remote
branch…" rather than "The remote branch has new changes…". Match on
/remote branch/, common to both push-variant titles, so the test passes
regardless of merge cleanliness.

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-06-12 10:03:34 -05:00
Timothy S. Dean
e11255220d Fix: core.async/timeout combined with core.async/go prevented fat dynamic var GC (#75769)
* This has to be the strangest Clojure footgun I've seen in many years.

* Kondo-ignore in the test file what the src file ignores
2026-06-12 11:00:53 -04:00
Oleh K
376db5fb43 refactor: Sweep brand/filter/summarize tokens to core-* (#75332)
* GDGT-2529: Add new color tokens alongside existing ones

Foundation for the GDGT-2517 color token refactor. Adds new and
renamed semantic tokens without changing any existing emission or
call sites. After this PR, both old and new CSS variable names
resolve to the same values; migration sweeps will move consumers
to the new names, and the cleanup PR will remove the old.

* GDGT-2529: Move kept tokens from Legacy to New section

These 14 tokens are not being renamed (text-primary, text-brand,
border-brand, tooltip-*, switch-off, etc.) and have no equivalent
in the New section. Moving them into the New group prevents
readers from assuming they're discontinued when they encounter
the Legacy section's 'Prefer using new ones' comment.

* Update Loki Snapshots

* Rearrange and aort new colors keys alphabetically

* Add explanation to core-brand/filter/summarize copy

* Update Loki Snapshots

* Split light/dark themes into `deprecatedColors` and `actualColors`

Per review feedback on #75227 — replaces the `// Legacy colors` and `// New`
section comments with named top-level constants so the intent shows up in
the import graph rather than as inline prose.

* Sweep `brand`/`filter`/`summarize` to `core-*` (GDGT-2530)

Renames all consumer-side references to the legacy semantic tokens to
their `core-` counterparts added by the foundation PR:

- `--mb-color-brand` → `--mb-color-core-brand` (and `-hover`)
- `--mb-color-filter` → `--mb-color-core-filter`
- `--mb-color-summarize` → `--mb-color-core-summarize`

Sweep covers: `var(--mb-color-…)` references in CSS/styled-components,
`color()`/`alpha()`/`lighten()`/`darken()`/`getColor()` helper calls,
Mantine `color`/`c`/`bg`/`iconColor`/`colorScheme`/`primaryColor`
props, type unions, default destructure values, ternary/fallback
expressions in JSX, static color-name lists, plus three doc files
(emotion-migrate skill, custom-viz template README, mantine-styles
contract test).

Both old and new CSS variables continue to emit during the migration,
and the SDK/whitelabel input keys (`theme.colors.brand`,
`application-colors.brand`) are unchanged; the rename is internal.

* Re-align emotion-migrate SKILL.md tables after the brand → core-brand edits

* Fix two visual regressions from the brand → core-brand sweep

- SDK v1 `theme.colors.brand` (and `filter`/`summarize`) now writes
  to both the legacy and the new core-* internal token via
  `SDK_TO_MAIN_APP_COLORS_MAPPING`, so consumers that have already
  migrated to `var(--mb-color-core-brand)` pick up SDK overrides
  the same way legacy consumers do. The v2 path was already covered
  by the mirror in `derive-theme.ts`; this PR patches the v1 path.

- `<Alert color="core-brand">` lost its tinted background because
  `Alert.config.tsx` was synthesizing the background-color token name
  via `background-${props.color}`, which produced the non-existent
  `background-core-brand`. Added an explicit `core-brand → background-brand`
  case so the tint resolves correctly while the `background-*` family
  is still on the legacy namespace.

* Revert sweep over CssVarsDeclarationPlugin test assertions

The sweep accidentally flipped two `toContain("--mb-color-brand: ;")`
assertions to `core-brand`, but the test's synthetic TS fixtures still
define `type ColorKey = "brand" | …` — the plugin parses those literally
and emits `--mb-color-brand`, so the assertions need to track the fixture,
not the production rename.

* Mirror `brand`/`filter`/`summarize` to `core-*` in embedding palette

The SDK v1 path rebuilds the global `colors` map via
`setGlobalEmbeddingColors` → `getEmbeddingColorPalette` on every theme
or whitelabel change, which bypasses the mirror in `derive-theme.ts`.
Whitelabel `application-colors` comes in via `appPalette` directly
keyed by the legacy `brand`/`filter`/`summarize` names, so before this
fix only the legacy CSS vars picked up the whitelabel override and the
new `core-*` keys silently fell back to their built-in defaults.

Mirror them at the end of the merge so consumers reading
`var(--mb-color-core-brand)` get the right color regardless of where
in the merge chain the brand value came from.

* Try to fix missing core-* variables

* Remove manual patch of core-* colors in getEmbeddingColorPalette

---------

Co-authored-by: Metabase Automation <github-automation@metabase.com>
2026-06-12 15:57:59 +02:00
Riley Thompson
b25f53509f Fix param values from joined source card (#75751)
* fix param values from joined source card

* Update test/metabase/parameters/custom_values_test.clj

Co-authored-by: metamben <103100869+metamben@users.noreply.github.com>

---------

Co-authored-by: metamben <103100869+metamben@users.noreply.github.com>
2026-06-12 09:39:45 -04:00
Oleh K
5b36ecb251 Add Storybook showcase helpers and a Figma component skill (#75693)
* Add reusable Storybook showcase components

Storybook-only presentational primitives for building component showcase
stories: StoryShowcase (bordered panel + title), StorySection, StoryRow,
and StoryJsx (monospace JSX with light, theme-aware syntax highlighting via
tokenizeJsx). Live in metabase/ui/stories/showcase so they stay out of the
metabase/ui barrel.

* Add metabase-ui-component-from-figma skill

Project skill codifying the workflow for restyling/implementing a metabase/ui
component from a Figma spec: check out the issue, map usage/blast radius, build
the Storybook showcase first, style from exact semantic tokens, iterate, then
commit and migrate call sites. Registered in frontend/CLAUDE.md.

* Handle closing tags and text children in StoryJsx tokenizer

Track whether we're inside a tag vs. element content so text children render as
plain text, and stop clearing the tag-name expectation on `/` so the name in a
closing tag (e.g. `</Kbd>`) is recognized as a tag. Handles `<Kbd>⌘</Kbd>`.

* Refine component-from-figma skill per review feedback

Raise the abstraction (drop Chip-specific anecdotes and one-time setup
rationale), split into update-existing vs create-new modes with the
showcase/styling order flipped for new components, derive the showcase matrix
from the component's full state space (theme excluded — it's global, not a
prop), and add a scoped test-first step (custom-interactive components only, not
thin Mantine wrappers).

* Address skill review feedback: trim duplication, add story example

Trim the Phase 1 mode-decision step and Phase 2 path reiteration, add an upfront
Figma desktop MCP availability check, mention playwright-mcp as an alternative
browser MCP, and embed an illustrative finalized matrix story.

* Flag non-color token scale mismatches in component-from-figma skill

Extend the discrepancy guardrail beyond colors: radius/spacing/elevation/type
values that have no matching step in the codebase's scales (e.g. Figma radius
md=12px vs --mantine-radius-md=8px) should be flagged to the user, not silently
baked in as literals.

* Fix typo
2026-06-12 14:09:20 +02:00
Braden Shepherdson
5f7c893f98 Add admin endpoints for OAuth clients and tokens (#74933)
* Add admin endpoints for OAuth clients and tokens

This allows auditing of the outstanding OAuth clients and tokens created
by users on an instance to enable MCP server access for external agents
like Claude Code.

* Add migrations for `decision` and `decided_at` columns; update API endpoints

* Adding unit tests for the new endpoint and adjusting checks on other tests

* Overhaul the approach: now a separate audit log table

Note that the migration was dropped but since it only added columns,
there's no real problem.

* FE - Authorizations page

* e2e tests

* Design Feedback

* Adding redirect-uri column, making the page wider

* column tweaking

* BE lint fixes

* fix be tests

* add fk index to oauth_client_event

---------

Co-authored-by: Nick Fitzpatrick <nickfitz.582@gmail.com>
2026-06-12 17:17:52 +05:30
Stas Gavrylov
19cd3a9b25 GDGT-2597 Order Schema Viewer fields to match the table metadata view (#75716)
GDGT-2597: Order Schema Viewer fields to match the table metadata view

The `/api/ee/erd` endpoint fetched a table's fields with no `:order-by`, so
columns came back in raw DB order. Sort them by `field-order-rule`
([position asc, lower(name) asc]) — the same ordering the `:fields` hydration
applies — so the Schema Viewer's field list matches
`/api/table/:id/query_metadata` instead of appearing unsorted.

Reuse the shared `field-order-rule` constant (declaring the warehouse-schema
module dependency) so the two surfaces can't drift.
2026-06-12 14:25:33 +03:00
Stas Gavrylov
d7c289b747 GDGT-2598: Schema Viewer shows the database name for schema-less DBs (MongoDB, MySQL, …) (#75616)
* GDGT-2598: Make SchemaPickerInput display DB name for schemaless DBs

* Fix metadataUrl generation for Schema Viewer's  info panel header

* GDGT-2598: Cleanup

* GDGT-2598: Address PR comments
2026-06-12 12:23:17 +03:00
Romeo Van Snick
bf0ac23a9f Move embedding-specific rewrites to metabase/embedding (#75582)
* Inline publicBase

* Inline internalBase

* Add middleware for rewriting /api/embed to /api/embed_preview where needed

* Remove getEmbedBase helper and inline /api/embed everywhere

* Tighten the prefix regexp

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

* Fix e2e tests

* Register embed-preview rewrite from render, not module load

The module-load registration polluted the shared api client in unrelated
unit tests (the SDK JWT subpath test saw a stray unmocked
/api/session/properties). Register it synchronously from usePublicEndpoints
instead: render runs parent-first while effects run child-first, so this
still lands before the child dashboard fetcher's effect and fixes the embed
preview race, but only when an embed page actually renders.

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

* Guard based on isEmbed

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

* Simplify unit test

---------

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: Mahatthana (Kelvin) Nomsawadi <me@bboykelvin.dev>
2026-06-12 14:52:05 +10:00
Alexander Polyankin
c2c7a41a53 Workspace UI revamped (#75687) 2026-06-11 20:33:37 -04:00
github-automation-metabase
73e2bfc4db Auto-update documentation for master (#75764)
Update generated docs (master)

Co-authored-by: github-actions <github-actions@github.com>
2026-06-11 17:35:26 -06:00
Romeo Van Snick
eff532c50f Move search to feature tier (#75613)
* Relocate non-UI search core to metabase/utils/search (lib tier)

Moves the search filter types, SearchFilterKeys constants, analytics
helpers, and URL/location utils out of metabase/search into the lib-tier
metabase/utils/search so non-feature modules (api, palette, plugins,
entity pickers) can keep importing them once search becomes a feature
module. Pure relocation + import-path rewrites; no behavior change.

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

* Move shared date filter components to metabase/querying

SearchFilterDateDisplay and SearchFilterDatePicker are generic
querying-date UI (built on metabase/querying + metabase/ui), reused by
the transforms run-filter bar. Move them into
metabase/querying/filters/components so non-search modules can keep
using them once search becomes a feature module.

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

* Move shared search-result components to metabase/common/components

SearchResult, SearchResultLink, and InfoText are presentational
components reused by the global nav search bar (and via it, dashboard
LinkViz), the command palette, and entity pickers. Move the cluster
into metabase/common/components so these non-search consumers no longer
import from the search module.

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

* Move search FE module to the feature tier

Reclassify metabase/search from a shared module to a feature module in
the module-boundaries config. Shared/lib modules can no longer import
from search; the reusable primitives previously living under search were
relocated to their natural homes (metabase/utils/search,
metabase/querying, metabase/common/components) in the preceding commits.

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

* Move search core from utils to metabase/common/search (shared tier)

metabase/utils should stay product-agnostic, but the search filter
types, SearchFilterKeys constants, analytics helpers, and URL/location
utils are Metabase search-domain code. Move them from
metabase/utils/search into metabase/common/search, the shared
Metabase-domain layer (mirroring the querying <-> query_builder split
and sitting alongside the SearchResult components already in
metabase/common/components). Pure relocation + import-path rewrites; no
behavior change.

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-06-12 09:18:54 +10:00
Romeo Van Snick
c0136115c0 Move ActionApi into RTK hooks and clean up callers (#75679)
* Add RTK Query endpoints for action execution and prefetch

Add executeAction, prefetchActionValues, executeDashcardAction, and
prefetchDashcardValues endpoints to actionApi, plus the request/result
types they need. These replace the legacy ActionsApi helpers in
metabase/services; callers migrate in follow-up commits.

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

* Migrate ActionsApi callers to RTK action endpoints

Replace the legacy ActionsApi.execute/prefetchValues/executeDashcardAction/
prefetchDashcardValues calls with the RTK endpoints:

- Thunks dispatch the endpoints' initiate() (executeAction, executeRowAction).
- Imperative prefetches in components go through the runRtkEndpoint helper.
- DeleteObjectModal uses the useExecuteActionMutation hook.
- Public-dashboard branches keep using PublicApi for now.

The ActionExecuteModal test builds fetchInitialValues via useDispatch +
runRtkEndpoint, mirroring the real callers.

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

* Remove ActionsApi from metabase/services

All callers now use the RTK action endpoints, so drop the legacy
ActionsApi helper.

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

* Fix CI failures and address review feedback

- Use runRtkEndpoint in the executeAction/executeRowAction thunks instead of
  dispatching initiate().unwrap() directly. The codebase Dispatch type returns
  `unknown`, so the direct form failed type-check (TS2571); runRtkEndpoint is the
  blessed thunk helper and returns the result.
- DeleteObjectModal: coalesce a missing objectId to null so the execute params
  satisfy ParametersForActionExecution (TS2322).
- ActionVizForm unit test: render with renderWithProviders so the new
  useDispatch/RTK prefetch path has a store.
- Add keepUnusedDataFor: 0 to the prefetch queries (Copilot review): they are
  imperative fetch-and-discard calls with row/dashcard-specific params that
  rarely repeat, so retaining cache entries adds memory for no benefit.

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-06-12 09:18:06 +10:00
metamben
e31c5c451a Add test verifying model persistence with duplicate column names (#75675)
Closes QUE2-182
2026-06-11 22:56:16 +00:00
Eric Normand
aff4a39ab7 Fix circular dependency error for cards with self-referencing parameters (#75731)
* Fix circular dependency error for cards with self-referencing parameters

A card whose parameter sources dropdown values from the card itself (or
from another card whose parameter points back) declares itself as a
serdes dependency. The circular-dependency strip keys for Card did not
include :parameters, so the load retry hit the same self-dependency and
aborted with "Circular dependency on Card <entity_id>".

Add :parameters to the strip keys for Card and Dashboard. The existing
two-pass mechanism then handles it: the circular retry inserts the
entity without parameters, and the outer pass restores them once the
row exists for FK resolution.

Also fix xform-one: coercion re-added stripped keys as explicit nils,
which violated the NOT NULL constraint on report_dashboard.parameters
during stripped updates.

* Address review: strip-mechanism hardening and test cleanup

- Fix the model->circular-dependency-keys docstring: it promised
  vector-path stripping with :* that no consumer ever implemented;
  document the actual top-level-keys contract and the two-pass restore.
- When a load fails for an entity that was stripped to break a
  dependency loop, say so in the error: with continue-on-error the
  stripped row survives the import, and the message now names the keys
  the entity may be missing.
- Exclude stripped keys from the :copy spec in xform-one, so the strip
  contract holds for all spec-processing steps, not just :transform
  and :coerce keys.
- Share one card-sourced-param helper across the three new tests and
  assert both cards' parameters in the mutual-reference test.
2026-06-11 17:22:33 -05:00
Anderson
bf2544ff7d Display column labels below split map charts (#74774)
* Show column labels below split map charts

* Clarify metric dimension item index fields
2026-06-11 18:49:16 -03:00
Anderson
af5aa9e59f Add metric labels to dimension picker selects / Add expr metric occurrence counts (#75292)
* Add metric labels to dimension picker selects + add metric expression occurance counts

* Expand accordions on search / Fix accordion bg color

* Replace ExpressionSubToken.count with ExpressionSubToken.occurrenceCount / Fix unit test
2026-06-11 18:48:08 -03:00
John Swanson
984e06d3a1 Analyze query executions for metadata (#72726)
* Track metric-api executions as QueryExecution rows

Tag metric-plan MBQL queries from /api/metric/dataset and
/api/metric/breakout-values with :executed-by and :context :metric so
process-userland-query writes a QueryExecution row; extend the ::context
enum with :metric to match.

* Usage-metadata: infer implicit dimensions, segments, and metrics from query executions

A new Quartz task extracts facts from each day's QueryExecution rows and
writes daily rollups to four source-keyed tables (SourceDimensionDaily,
SourceMetricDaily, SourceSegmentDaily, SourceDimensionProfileDaily). An
insights layer queries the rollups to surface the most common ad-hoc
aggregations, filters, and breakouts.

Deviation from the original plan: dimension "interestingness"
(single-value, all-null, low-cardinality) was meant to come from cached
"count by <dim>" queries. We read it from the field's existing
Field.fingerprint instead (see
metabase.usage-metadata.models.source-dimension-profile-daily).

* Usage-metadata: treat queries as opaque via metabase.lib

Replaces direct (:stages ...) / (:source-table ...) reads and raw :field
clause pattern-matching in usage_metadata.extract with the kondo-allow-listed
metabase.lib public API (metabase.lib.core + metabase.lib.util.match).

- select-root-owner: uses lib/primary-source-table-id + lib/primary-source-card-id
- extract-usage-facts: uses lib/stage-count
- clause-field-refs: uses lib.util.match/match-many instead of clojure.walk/postwalk
- atomic-filter-clauses: uses lib/clause-of-type?
- field-ref detection: lib/clause-of-type? + lib/field-ref-id, dropping the
  hand-rolled field-ref? / field-ref-info helpers

Also drops the :join-alias fallback and its Field.table_id DB lookup
(*field->table-id* cache + binding wrapper in batch.clj), since
lib/find-matching-column already resolves joined columns via the :table-id
on the returned column metadata.

* random ids, no rollbacks on migration

* Stream the Query-table read in usage-metadata batch

The reducible-select over :model/Query filtered by query_hash could
buffer a large slice of the query table in driver memory on Postgres.
Wrap it in mdb/streaming-reducible so the JDBC fetch actually streams
via a server-side cursor.

* CR response

* update module config

* CR response

* oops, fix stale references in tests

* fix migration version

* address self-review

I was taking one final look at this before merging and noticed a couple
small issues that I wanted to clean up before I merged.

The big one was aggregation types I hadn't thought about, e.g.
`[:- [:metric A] [:metric B]]` is a supported custom expression.

Take a query like this:
```
{
  "lib/type":"mbql/query",
  "stages":[{
    "lib/type":"mbql.stage/mbql",
    "source-table":210,
    "aggregation":[
      [
        "-",
        {"lib/uuid":"bd30ecfd-f921-4e52-a253-2b3d348d63d4","name":"foo","display-name":"foo"},
        ["metric",{"lib/uuid":"27c99d2b-d951-4024-ab21-729cac76b54a","effective-type":"type/Integer"},94],
        ["metric",{"lib/uuid":"084c85de-68ab-456c-a451-a3dbce2be844","effective-type":"type/Integer"},95]
      ]
    ]
  }],
  "database":2
}
```

This would have resulted in a `NOT NULL` crash because we couldn't
extract the source (card or table) from an aggregation like this.

The fix is just to ignore these cases. This does have tradeoffs: it
means we're explicitly going to undercount some usages. However,
handling them "correctly" would require actually resolving the metric
reference during extraction, which we want to avoid for reasons of
efficiency and correctness (the metric may have changed since the query
was run).

Since these are fairly niche queries, I think this is probably okay?

I also added batching to the INSERTs to avoid errors on very large
numbers of parameters, and added a safety harness around calling
`lib-be/normalize-query` in case that throws.

* don't use deprecated `mt/mbql-query`

* Usage-metadata: composite segment candidates (#72982)

* Usage-metadata: mine composite segment candidates from stage filter baskets

Adds a composite rollup sibling to `source_segment_daily`: one row per stage's
top-level filter basket (the implicit `:and` of all top-level filters), keyed
on the canonicalized whole-clause and carrying the sorted array of atom
fingerprints. Storage stays `O(queries)` -- no powerset expansion at write
time.

Read path runs Apriori FIM (size-capped 2..5, absolute + relative support
floors, closed itemsets only) over a rolling window of composite rollups for a
given owner and returns reconstructed `[:and ...]` candidates that recur
across baskets with different tails. Itemsets whose atom-set matches an
existing saved `:model/Segment` definition are filtered out.

* kondo

* seq->vec before normalization

* rm `:count` from `implicit-composite-segments`, document vals

`count` and `support` were the same thing by two different names; I
removed `count` because in this domain `support` and `support-ratio`
are more meaningful.

I also added better descriptions of all the return values, because I had
to refresh my memory on them when I was looking back at this code :)

* fixup migration

* bad john, no raw mbql manipulation

* more CR response

* vectorize lazyseqs as part of normalization

* don't break everything, though

* fix tests for mysql/mariadb

* Move `atomic-filters` and `referenced-columns` to lib

Two new Lib helpers, both re-exported from lib.core:

- `lib.filter/atomic-filters` — stage helper that flattens top-level `:and`'s
  into a list of atomic boolean filter clauses. Mirrors `lib/filters`'s
  return shape.

- `lib.fe-util/referenced-columns` — walks the expression-parts AST and
  returns the `:metadata/column` leaves of a clause. Runtime-gates the
  input via `lib.util/clause?` / `column-metadata?`. Lives in `fe-util` rather
  than next to returned-columns because the impl is built on
  expression-parts and the natural placement would create a cycle —
  noted in the docstring.

`usage-metadata/extract.clj`'s segment, composite and metric fact builders
now compose these helpers. Drops `atomic-filter-clauses`, `participants-from-parts`,
and the `column-metadata?` predicate.

* Move `referenced-columns` out of `lib.fe-util` into its own namespace

* move migrations to 063

* cljfmt
2026-06-11 14:44:15 -07:00
Ben Grabow
8c0e64ac1f Log connection pool destruction at INFO for flaky-test diagnosis (#75754)
Destroying a c3p0 pool closes its checked-out connections, which kills
any in-flight query on another thread with errors like SQL Server's
"The result set is closed" (DEV-2161). These destroy/invalidate events
were only logged at DEBUG, so CI test-log artifacts (which capture
INFO+) could not show whether a pool destroy coincided with a flaky
query failure.

Log destroy-pool! and invalidate-pool-for-db! at INFO so the next
occurrence is diagnosable from the CI artifact alone. In tests these
log lines automatically carry the running test's name via the logging
context, attributing each pool destruction to its trigger.

Co-authored-by: Claude Fable 5 <noreply@anthropic.com>
2026-06-11 16:25:51 -05:00
metamben
55f798f532 Add test demonstrating that #33698 has been fixed (#75555)
Closes QUE2-189
2026-06-12 00:13:22 +03:00
metamben
9ab9b085d4 Fall back on effective-type for time fields (#75442)
Closes QUE2-650
2026-06-12 00:13:09 +03:00
technomancy
f6423a79b5 Use *driver* to test h2/postgres with and without mbql5 (#75729)
Consider this atonement for my crimes of having used with-redefs.
2026-06-11 20:56:53 +00:00
Anderson
daef67027c Fix filter not respected when downloading visualizer-affected card from dashboard (#75720)
Fix filtered dashboard card xlsx downloads
2026-06-11 16:02:10 -03:00
Eric Normand
87e4ecf563 Audit-log background and startup remote-sync imports (#75730)
* Audit-log background and startup remote-sync imports

Auto-imports (Quartz job) and startup imports now publish
:event/remote-sync-import with :user-id nil and :details {:auto true},
so the activity log records every pull on read-only instances.

Also fixes the manual paths: the :on-success callbacks in api.clj were
single-arity but run-async! invokes them with [task-id result], so the
ArityException was silently swallowed and manual sync events were never
recorded either.

Fixes #73335

* Guard audit publish in auto-import; test manual import audit row

publish-event! rethrows handler exceptions, so an audit-log failure
would have marked an already-successful auto-import as failed in task
history. Wrap it in try/catch like run-async! does for :on-success.

Also adds a regression test asserting manual POST /import writes a
remote-sync-import audit row attributed to the user with no :auto flag,
locking in the callback arity fix.
2026-06-11 18:49:51 +00:00
Andrei Chernykh
525aca564b Fix extra divider in metric menu for non-admin users (#75667)
Fix extra divider in metric menu for non-admin users without usage analytics access
2026-06-11 11:25:08 -07:00
metamben
f02742f0a9 Return nested fields from sandboxed queries (#75358)
* Return nested fields from sandboxed queries

Closes QUE2-651
2026-06-11 18:12:06 +00:00
Timothy S. Dean
80646be599 Fix Athena sync failing on partitioned Iceberg tables (#75666)
Syncing a partitioned Iceberg table left it with no fields at all.

When the driver can't get field metadata over JDBC it runs `DESCRIBE` instead (#43980, #58441). `DESCRIBE` output ends with a partition section that re-lists the partition columns. For Hive tables
they reappear with their real types and were already deduplicated; for Iceberg tables they reappear with the partition transform (e.g. `identity`) where the type should be. The parser treated
those rows as real columns, couldn't map `identity` to a base type, and the insert for *all* of the table's fields failed on the null base type.

Fix:

- Stop parsing `DESCRIBE` output at the partition section — it never contains new columns. (Section markers verified against Hive's `TextDescTableFormatter`, where this format comes from; link in
the code.)
- Also drop any row that repeats an earlier column name, in case the marker text ever changes.
- Unknown database types now fall back to `:type/*` instead of failing the sync, same as the JDBC path.
2026-06-11 11:54:57 -06:00
Ben Grabow
9ea5f3c265 Omit case-sensitive option when DB doesn't support it (#75665)
* Omit case-sensitive option when DB doesn't support it

* Accept database as setup opt and construct state in setup
2026-06-11 17:36:30 +00:00
github-automation-metabase
306ce29098 Auto-update documentation for master (#75673)
Update generated docs (master)

Co-authored-by: github-actions <github-actions@github.com>
2026-06-11 13:28:31 -04:00
Chris Truter
a9f80db7fd Prefix semantic search queries with query: for Arctic embedding models (#75718) 2026-06-11 17:19:21 +00:00
Rodrigo López Dato
4015a7408e Add JVM hardware info to diagnostic details (#75561)
Include the number of CPUs, max JVM memory, and total physical host
memory in the bug-reporting diagnostic info, under the system-info
section. The max JVM figure matches the "Maximum memory available to
JVM" line printed at startup; the total host memory shows how much
the machine actually has, making it easier to diagnose performance
problems from a bug report.
2026-06-11 16:49:53 +00:00
Anderson
ce69cec459 Fix schema breadcrumb after table route refresh (#75428) 2026-06-11 13:27:29 -03:00
Anderson
8c750b74fb Fix stale dashboard breadcrumb after rename (#75432)
* Fix stale dashboard breadcrumb after rename

* Fix dashboard breadcrumb context leaks
2026-06-11 13:27:26 -03:00
Gabriel Moreno
f234679608 Fix library e2e empty state flaky test (#75429)
* fix: wait for library to be created

* fix: formatting
2026-06-11 11:43:36 -04:00
Chris Truter
92c67e8c62 Fix inconsistent db defaults for data_layer / data_authority (#75689) 2026-06-11 15:14:50 +00:00
Nathan Voxland
4d1d85814c Tidy query preprocessing, dataset streaming, and permission helpers (#75551)
* Tidy persisted-info handling in query preprocessing and SQL QP

Resolve the persisted-cache source SQL from the metadata provider in the SQL
QP, and clear any stale :persisted-info/native keys during preprocessing.

* Add docstrings to query-permission helpers and simplify related tests

* Normalize query maps before permission checks on card save and revert

* Build dataset-streaming :info server-side and tidy pivot query setup

* Fixed mbql and formatting
2026-06-11 09:38:32 -05:00
Chris Truter
1bb1a3848a Weaken verified and official-collection search weights (#75676) 2026-06-11 16:14:02 +02:00
Riley Thompson
6cb272064f Fix replacement with field filter alias (#75644)
* fix field filter alias

* trigger ci
2026-06-11 13:26:36 +00:00
Brad Anderson
a866b4827c GRO-388 mimic Snowplow.setUserId with metaplow (#75565) 2026-06-11 09:18:44 -04:00
Nicola Mometto
de9f9979c0 Transform scheduler freshness (#75309)
* wip: transform freshness

* fix: don't consider inactive jobs

* fix: don't include unscheduled transforms, use appdb now

* fix npe

* just compute next scheduled run

* test

* chore: return scheduled/dependency from API

* notes on freshness

* handle review comments
2026-06-11 12:28:30 +00:00
Uladzimir Havenchyk
f77ee419cc fix(documents): add proper rendering optimizations of the cards (#70832)
- do not render cards which are not visible at the viewport and close to it, use placeholders instead
- fetch data only when browser is ready to provide the best user experience
- prepare document for printing by rendering all cards in background, so no placeholders are rendered instead of cards
2026-06-11 11:20:42 +00:00
Fraser
f702f1aa45 Fix setup module violation (#75692) 2026-06-11 13:34:53 +03:00
Fraser
e8adb6a17e Fix EmbeddingTheme violations (#75683) 2026-06-11 20:13:00 +12:00
Fraser
5a2357c36f Fix pdf download violations (#75459) 2026-06-11 20:03:42 +12:00
Uladzimir Havenchyk
08fd155739 fix: wait for all databases to be loaded and fix sources of flakinesses (#75173)
* test: attempt to fix flaky test

* fix: only auto-select database in DataSelector when exactly one is available

The segments "Filter by table" picker (and every other multi-database
DataSelector) auto-selected the first database and drilled into its tables,
skipping the database list. This was a regression from #64406, which changed
the skipSteps guard from `=== 1` to `>= 1` while adding disabled-database
filtering. Restore the `=== 1` invariant on the filtered enabled databases.

This was the root cause of the metabase#52411 e2e flake: opening the picker
intermittently drilled into Sample Database (alphabetically first, single
schema) instead of showing the list, depending on metadata-load timing. With
the fix the list is always shown, so the test drops the drill-recovery and
keeps only force-click for the unrelated re-render detach.

- Unit regression test: with multiple databases, none is auto-selected.
- e2e: simplified back to force-click.

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

* fix: don't auto-select a database while the picker list is still loading

The earlier === 1 fix addressed the fully-loaded multi-database case, but the
segments picker still drilled into Sample Database intermittently: the picker's
`databases` list is built by hydrating queried database ids through the
metadata store and dropping those not yet hydrated, so mid-load it can
transiently contain only the first database. skipSteps then treated that as
"the only available database" and auto-selected it.

Gate the auto-select on `databasesLoaded` (every queried database hydrated, or
`databases` passed directly), so a transient partial list can't trigger it.
Together with the === 1 guard this fixes both the metabase#52411 flake and the
fully-loaded multi-DB regression at the source.

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

* fix(AccordionList): key rows by section identity, not list position

AccordionList rendered each row with `key={index}`, a flat position into a
list that changes length/order as async sections resolve. In the legacy
DataSelector picker, the "Saved Questions" section appears/disappears as the
`/api/database?saved=true` and `/api/search` requests settle, shifting every
later section's index and remounting it. That detached "Writable Postgres12"
mid-click and made metabase#52411 flaky (worse under CI network throttling).

Key rows by `section.key`/`section.name` instead, falling back to the index
when a section has no stable identity. Each row now keeps its React instance
across these updates, fixing the detach at its source for every AccordionList
consumer (data selector, notebook data source, filter pickers, etc.).

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

* test: drop force-click now that AccordionList keys are stable (52411)

The re-render detach that force-click worked around is fixed at its source by
keying AccordionList rows on section identity (prev commit). "Writable
Postgres12" no longer remounts when the saved-questions/search requests settle,
so a plain click is safe.

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

* move db loading logic to initializeQB

* fix(AccordionList): key rows by section identity, not list position

The metabase#52411 stress test (50x, qa_db, network throttling) still
failed 21/50 with the initializeQB preload alone: every failure detached
on the first database click ("Writable Postgres12") in the DataSelector
popover. That test runs on /admin/datamodel/segments, which never calls
initializeQB — so the preload can't help it. The real cause is the
database AccordionList re-rendering as databases hydrate into metadata
incrementally: with key={index}, shifting list entries remount the row
mid-click and Cypress loses it.

Key rows by section.key/section.name instead, falling back to the index
when a section has no stable identity, so each row keeps its React
instance across these updates. Restores the fix from the earlier branch
state with a corrected comment (the churn is the database list itself,
not a Saved Questions section). The initializeQB preload is kept as an
orthogonal improvement for the QB data selector.

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

* Revert "fix(AccordionList): key rows by section identity, not list position"

This reverts commit 0f79b29ca2.

* restore automatic db selection when only 1 db is available

* fix: don't auto-select a database while the picker list is still loading

The === 1 guard alone still let the segments "Filter by table" picker drill
into Sample Database intermittently (metabase#52411): the DataSelector connect
builds `databases` by hydrating queried database ids through the metadata store
and dropping those not yet hydrated, so mid-load the list can transiently hold
only the first database. skipSteps then treated that single entry as "the only
available database" and auto-selected it, advancing into its schema/tables and
unmounting the list mid-click.

Gate the DATABASE_STEP auto-select on `databasesLoaded` (every queried database
hydrated, or `databases` passed directly), so a transient partial list can't
trigger it. Together with the === 1 guard this fixes the flake at its source for
the segments page and every other DataSelector consumer.

Confirmed via CI stress runs that the initializeQB preload could not fix this:
the segments page never calls initializeQB, and === 1 alone leaves the
transient-single race. Adds a unit regression test.

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

* improve comments

* cleanup

* fixup

* rename function

* cleanup test

* cleanup test

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-11 09:30:35 +03:00
Eric Normand
db96fadd29 GHY-3725 incremental export fast-path for remote sync (#75057)
* GHY-3725 incremental export fast-path for remote sync

Export previously re-serialized the entire synced content set on every push,
regardless of what changed, so a single in-place edit cost as much as a full
export (O(total synced entities)).

Add an incremental fast-path: when every pending dirty change is an in-place
content update of an entity-id model whose serialized path already exists in
the repo holding that same entity, serialize and write only the changed
entities and preserve everything else. Any other case (create, rename, delete,
collection rename, path/hybrid models, mixed batches) falls back to the
existing full export, which reconciles the whole tree correctly.

- source protocol: new apply-changes! (write/overwrite + delete, preserve rest)
- git: apply-changes! copies existing tree entries by object id, inserts only
  changed blobs
- spec: extract-dirty-entities-for-export serializes only the dirty rows
- impl: safe-incremental-upserts gate (verified via a real YAML parse of the
  existing file's entity_id); export! chooses incremental vs full and marks
  only processed rows synced
- RemoteSyncObject: dirty-rows helper
- MockSource: apply-changes! for tests

Measured ~constant (~4ms) regardless of synced-set size vs linear full export
(39x-353x faster for one edited card at 50-500 entities).

* GHY-3725 extend incremental export to renames and deletes

Persist each entity's last-exported file path on the RemoteSyncObject row so
the incremental fast-path can resolve old paths for renames and deletes
(previously these fell back to a full export).

- migration: add remote_sync_object.file_path (nullable)
- source: store!/->file-spec capture {model_type entity_id path} during the
  write pass (path computed once to avoid advancing the slug generator)
- impl: incremental-plan now handles update (in-place + rename: write new +
  delete old path), delete/removed (delete stored path + drop row), and falls
  back to full when file_path is absent (post-import; self-heals on next full
  export) or a name-collision is detected; record-exported-paths! persists
  file_path after every full export (export-only population)

Benchmark: in-place edit, rename, and delete are all ~constant (2-6ms)
regardless of synced-set size vs linear full export (215/650/1650ms at
50/200/500 entities).

* GHY-3725 fix incremental export dropping cross-scope dependencies

The incremental fast-path wrote only the changed entities, so an in-place edit
that newly referenced remote-sync content outside the synced set (e.g. a card
based on a card in another collection) omitted that dependency's file — a full
export pulls it via serdes/descendants, so this was a regression introduced by
incremental updates.

Guard incremental updates with a dependency-closure check: compute the entity's
transitive serdes/descendants + serdes/required closure and fall back to a full
export when any referenced remote-sync content model isn't tracked by a
RemoteSyncObject row. References to already-synced content (which has a row and
is in the repo) stay incremental; non-content deps (databases, resolved by
reference at import) are ignored.

Tests: an update/create that adds a cross-scope reference exports the dependency;
an update referencing a card in another synced collection stays incremental.

* GHY-3725 make creates incremental in remote-sync export

Creates previously forced a full export. Handle them on the incremental
fast-path: write the new entity's file (no old path to delete), guarded by the
same checks as updates — the target path must be free or already hold this
entity (dedup-collision guard), the dependency closure must already be in the
repo (else fall back to full so serdes/descendants pulls it), and all upsert
paths in a batch must be distinct.

Create and in-place update are kept distinct: an update with no stored file_path
to a new path is an unresolvable rename and still falls back to full, whereas a
create to a free path is written directly.

Tests: create is incremental and records file_path while preserving other files;
a create whose path collides with a different entity falls back to full; a create
referencing un-synced content falls back (dependency guard).

* GHY-3725 pull dependency closure incrementally instead of falling back

When an incremental create/update references remote-sync content not yet in the
repo (e.g. a synced card based on a card in a non-synced collection), we now
serialize and write that dependency alongside the change instead of falling back
to a full export. The set written is the change's transitive
serdes/descendants+required closure restricted to untracked content models — the
same subset a full export would emit for the change — so the repo ends up
consistent while everything else is preserved.

- untracked-content-deps returns the untracked content entities in the closure
- incremental-plan accumulates them per row and dep-upserts serializes them
  (reusing the storage context so paths dedupe consistently)
- a path collision while pulling a dep still falls back to full; pulled deps get
  no RemoteSyncObject row, matching full-export behavior

Tests: an update/create that adds a cross-collection reference now stays
incremental and exports the dependency.

* GHY-3725 fix CI: migration dir, kondo, task-leak, transform cleanup

- migration: move file_path changeset to migrations/063 (next dev version)
  and bump id to v63; 062 is the released version (check-migration-versions).
- incremental_export_test: add (fixtures/initialize :db) + clean-remote-sync-state
  fixtures so RemoteSyncTask rows don't leak into later tests (was causing
  "A running task exists" failures in settings-test/snippets-test); replace the
  deprecated mt/mbql-query with explicit query maps (kondo).
- source_test / wrapping_source_test: implement apply-changes! on the
  SourceSnapshot mocks now that it's part of the protocol (kondo
  missing-protocol-method warnings).
- impl: incremental export now falls back to a full export when the repo still
  holds files for content types disabled by settings (transforms /
  python-libraries / snippets), since only a full export reconciles those away.

* Whitespace

* GHY-3725 address review feedback

- dirty-objects is now implemented in terms of dirty-rows (no duplicated query);
  trim caller details from the dirty-rows docstring.
- store! returns {:version :entries} instead of taking a path-atom argument, so
  the exported-path tracking is a return value rather than a threaded side
  effect; ->file-spec's serialization is shared via entity->file-spec.
- rename extract-dirty-entities-for-export -> extract-entities-for-rows (it just
  groups rows by model type and serdes-extracts them; also used for dependency
  rows, not only dirty ones) and trim caller details from its docstring.
2026-06-11 05:31:59 +00:00
Nemanja Glumac
f0ab65ee4f Allow e2e stress-test workflow to build the jar when needed (#75669) 2026-06-11 07:30:21 +02:00
Alexander Polyankin
9c76f5c629 Show upstream archived on inactive dependencies (#73186) 2026-06-11 02:58:27 +00:00
Anderson
79b7c2a604 Clean up metrics viewer token action menu (#75206)
Clean up metric token action menu
2026-06-10 19:32:27 -03:00
Eric Normand
ecbbbd0543 Add regression test: native SQL card flagging itself as broken (GHY-3682) (#75674)
Add regression test for native SQL card flagging itself as broken (GHY-3682)

Editing a native SQL card to use an explicit column list (instead of
SELECT *) previously caused /check-card to report the card being edited
as broken, surfacing the "these changes will break some other things"
popup for the card itself. The underlying native validation was fixed in
639c8deb; this adds an endpoint-level regression test covering the
reported symptom: a native source card plus a downstream consumer, edited
to explicit valid columns, must return success with no broken cards.
2026-06-10 22:24:54 +00:00
Romeo Van Snick
e95194e698 Remove legacy GET in leaflet map (#75577)
* Switch LeafletTilePinMap to use api.request instead of legacy GET

* Await data url read before calling done

* Wait for the tile image to actually load

* Move image loading to asyn helper

* Enable retry

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-06-11 08:24:22 +10:00
Romeo Van Snick
2a1b4e0163 Remove legacy POST in internal-analytics (#75578)
Remove legacy GET in internal-analytics
2026-06-11 08:23:32 +10:00
Romeo Van Snick
02d7cbdded Convert PulseApi to RTK hooks (#75583)
* Convert pulse api to RTK hooks

* Use actual response type

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

* Fix formatting

---------

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
2026-06-11 08:23:16 +10:00
Kevin Kelleher
84ed39b816 Use dashboard filters in Visualizer data (#75498)
use datasets in visualizer initial state as primary rather than fallback
2026-06-10 18:06:40 -04:00
Eric Normand
8083e6e3aa Abort initial sync status when metadata fetch fails (#75660)
When `describe-database` throws during the metadata-fetch stage (e.g.
Athena credentials lacking `glue:GetDatabases`), the exception was raised
before `initial_sync_status` was ever updated, leaving the database stuck
at "incomplete" and the UI perpetually showing "Syncing tables…".

Wrap the fetch so a throw marks the initial sync aborted before
re-throwing, so the status flips to "aborted" and the UI surfaces the
failure. This is general to any driver, not just Athena.

Fixes GHY-3534.
2026-06-10 20:08:05 +00:00
Eric Normand
b47b12cf6b Stop retrying permanently-failed fingerprinting every sync (#75640)
* Stop retrying permanently-failed fingerprinting every sync

When fingerprinting a field failed, `fingerprint_version` was never
advanced, so `fields-to-fingerprint` re-selected the field via
`fingerprint_version < latest` and retried it on every subsequent sync —
indefinitely. For an effectively-permanent failure (slow view timeout,
permission denied, unsupported type, coercion/dispatch error) this is pure
waste, and amplifies GHY-3266 by leaking a long-running query each sync.

Advance `fingerprint_version` to the latest on failure so the field is not
re-selected, EXCEPT for transient connection/environment errors (DB
unreachable, pool exhausted, SSL handshake), which are left untouched so the
next sync retries them — matching the existing abandon-sync behavior.

Covers both failure paths: the whole-table sampling-query throwable and the
per-field fingerprinter throwable.

* Use public do-not-retry-exception? instead of a single-use wrapper

* Clarify do-not-retry-exception? branch in fingerprint failure handling

* Rename do-not-retry-exception? to transient-exception? with a private hierarchy

Move the exception classification into a private hierarchy populated through a
new public register-transient-exception fn (replacing the global derive), and
rename the keyword to ::transient-exception and the predicate to
transient-exception?. The predicate's truthy meaning now matches its name.
2026-06-10 18:38:09 +00:00
technomancy
e7262aa5b3 Update driver stress test workflow to pass in necessary snowflake env. (#75574)
* Update driver stress test workflow to pass in necessary snowflake env.

Seems bad that this has to be duplicated a bunch of places.

* Unset CDPATH to avoid failures in dev-install.
2026-06-10 11:11:11 -07:00
thackervishal
d24c2551d7 DOC - fixing 2 incorrect links and adding a line about arrays in json unfolding (#74610) 2026-06-10 14:00:35 -04:00
Alex Yarosh
9ac9602d26 docs: alert management (#75478)
* alert management

* Optimized 2 images, saved 245.6 KB (51.8% smaller)

* Apply suggestions from code review

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-06-10 17:56:09 +00:00
John Swanson
05a70000b5 Fix metric viewer for metrics based on native sql cards (#72404)
metrics based on native sql support
2026-06-10 10:26:49 -07:00
John Swanson
7d8738db7e UXW-4443: Re-encrypt additional columns during key rotation (#75536)
* UXW-4443: Re-encrypt additional columns during key rotation

There were 6 columns that we weren't correctly rotating during key
rotation. This is a mechanical change to add them to the list of things
we rotate. The "Right Way" to fix this would probably be closer to
UXW-4444 (a refactor that mechanically prevents this from happening
again) but this triage makes sense for now.

[UXW-4443: Re-encrypt additional encrypted columns during key rotation](https://linear.app/metabase/issue/UXW-4443/re-encrypt-additional-encrypted-columns-during-key-rotation)

* fix test
2026-06-10 10:25:44 -07:00
Chris Truter
6d7cbe822c Make app DB authoritative for table existence in table-candidates (#75588) 2026-06-10 18:51:37 +02:00
Timothy S. Dean
f2afce5817 Fix dropped admin email on persist-refresh failures in dev/test (#75342)
The `:event/persisted-model-refresh-error` event schema required `:trigger` to be an org.quartz.Trigger instance, but in dev mode the producer was hardcoding it to the strings `"Scheduled"` or `"Manual".

The schema mismatch had no effect in production, but in dev and test runs `mu/validate-throw` rejected the payload; the resulting exception was swallowed by the try/catch in `publish-refresh-error-event!`. I only noticed because I happened to write a test that exercised the path.

Fix: the real Quartz Trigger was available on the JobExecutionContext that `refresh-job-fn!` receives, so we use it.
2026-06-10 10:16:24 -06:00
Anderson
357cc76125 Fix UI error handling when archiving a collection fails (#75431)
Fix silent archive failures
2026-06-10 13:07:44 -03:00
Aleksandr Lesnenko
31f7b5d27e cli oauth (#75451)
Co-authored-by: Bryan Maass <bryan.maass@gmail.com>
2026-06-10 09:37:04 -06:00
Stas Gavrylov
a1d5e4b071 Fix flaky schema-viewer writable-Postgres test (#75094)
* Fix flaky schema-viewer writable-Postgres test by re-triggering DB sync

The writable-Postgres beforeEach used a single fire-and-forget
resyncDatabase whose wait only required *any* table to exist. sync_schema
submits to a single-threaded task pool (a slow predecessor task blocks the
queue) and is subject to duplicate-op suppression (a sync already in flight
makes ours a no-op), so the newly-created sv_test/sv_extra schemas were
intermittently never discovered and the hook timed out with zero tables.

Replace it with a re-triggering poll that re-POSTs sync_schema periodically
and waits until every required table reaches initial_sync_status=complete,
which also guarantees fields and FKs are synced.

* Refactor resyncDatabase to support waiting for multiple tables to complete sync

* Add /sync_schema issue link
2026-06-10 18:24:54 +03:00
Chris Truter
7ff2080a85 Further MCP improvements for HTTPS detection (#75531) 2026-06-10 09:16:00 -06:00
Alex Yarosh
155bac70a7 docs: metric updates (#75581)
* metric updates

* Optimized 2 images, saved 246.3 KB (49.0% smaller)

* Update docs/data-modeling/metrics.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-06-10 15:15:41 +00:00
Anderson
ddd34b2742 Fix MySQL/MariaDB collation mismatch failure in v62 legacy_library_root_entity_ids migrations (#75496)
* Fix MySQL collation in Library root migrations

* Change approach: fix existing sql directly and replace changeset ids

* Update unit tests

* Include filepath in the DELETE WHERE clause / Replace only changed changesets' ids
2026-06-10 11:57:31 -03:00
Nathan Voxland
edaf5a64f7 Switch appdb-index-size to be a real db check (#75284) 2026-06-10 09:51:41 -05:00
Maksym Yakubych
862fc7a2eb feat: make slackbot use the default internal metabot id (#74727)
Closes [BOT-1581: Slackbot `metabot` record can not be configured in the admin UI](https://linear.app/metabase/issue/BOT-1581/slackbot-metabot-record-can-not-be-configured-in-the-admin-ui)

### Description

Smartbot was using its own separate Metabot i, which made it unconfigurable via admin settings. Now it uses the same internal id as the Metabot inside the app.

### Checklist

- [x] Tests have been added/updated to cover changes in this PR
- [x] If adding new Loki tests: they pass [stress testing](https://github.com/metabase/metabase/actions/workflows/loki-stress-test-flake-fix.yml)
2026-06-10 11:51:24 -03:00
Ngoc Khuat
c13ba1bcc8 Count webhook channels in alert management (#75379) 2026-06-10 14:18:38 +00:00
Alex Yarosh
442c7ee351 docs: mcp updates (#75580)
* mcp updates

* Optimized 1 images, saved 80.5 KB (48.3% smaller)

* Apply suggestions from code review

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

* Apply suggestions from code review

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-06-10 13:47:14 +00:00
Chris Truter
75ea90c029 Tolerate legacy search weight overrides (#75614)
* fix(search): tolerate legacy flat weight overrides (#BOT-1677)

`/api/search` 500'd on stats with `Don't know how to create ISeq from:
java.lang.Double`. `normalize-override-keys` (added in #75388) reduces over
the persisted `experimental-search-weight-overrides` setting assuming every
value is a per-context weight map. Pre-#50338 the setting was a flat
`{scorer weight}` map, and stats still has one persisted -- so a bare Double
landed where a map was expected and `merge` blew up.

Flat overrides used to apply to every context, so fold their bare weights into
the `:default` base (where an explicit `:default` context override still wins),
rather than crashing or silently dropping them.

* Tighten normalize-override-keys docstring; move rationale inline
2026-06-10 08:58:36 -04:00
Oleh K
09c574b988 Render transform job details before the transform plan loads (#75499)
* GDGT-2595 Render job details before transform plan loads

The transform plan endpoint (`/api/transform-job/:id/transforms`) can take
10+ seconds to compute, which previously blocked the entire job details page
behind a full-screen spinner.

Make only the transform plan non-blocking: the page now renders as soon as the
job and databases queries resolve, and the transform list loads independently
in TransformsSection (which owns its own loading/error states). While the plan
loads, editing stays locked and the run button shows a "Checking permissions…"
state instead of a misleading "no permission" message.

* Address PR review feedback

- Reorder getRunButtonInfo so an in-progress run takes precedence over the
  loading state, dropping the negative status guard
- Pass the transform plan loading flag directly into the run button
- Rewrite JobPage spec to use fake timers + a mock delay instead of a custom
  deferred helper
2026-06-10 14:03:01 +02:00
Romeo Van Snick
403ceceffc Move metabase/browse to feature tier (#75377)
* Make metabase/browser a feature

* Move metrics analytics to metrics module

* Move shared test setups to metabase-types
2026-06-10 22:00:39 +10:00
Romeo Van Snick
b6b6c0f6b9 Move metabase/setup to feature tier (#75584)
* Make setup a feature

* Move getIsHosted and getTokenFeature to metabase/selectors/settings
2026-06-10 21:56:12 +10:00
Chris Truter
f0c53fd0de Look up load_skill ids by string instead of keywordizing (#75587) 2026-06-10 18:52:34 +07:00
Roman Abdulmanov
2b40d21357 Removed deprecated header (#75594) 2026-06-10 08:34:07 -03:00
Uladzimir Havenchyk
e54f13d3ea docs: update the link to custom viz docs (#75603) 2026-06-10 11:31:57 +00:00
Nemanja Glumac
b79f6cdd50 Fix timeline events intermittently not rendered (#75566)
* Show timeline events when timelines load after the question

The query builder dispatched showTimelinesForCollection from an effect
gated only on bookmarks loading, with no dependency on the fetched
timelines. When GET /api/timeline?include=events resolved after the
question and bookmarks had loaded, the effect had already run once with
an empty timeline list and never re-ran, so the events were never pushed
into the chart's visible set and no marker rendered. The race surfaced
most often on ad-hoc native questions, whose load path tends to lose it.

Gate the effect on the timelines being loaded and re-run it when they
arrive, restoring the guarantee that was lost when the Timelines.loadList
HOC was removed.

Add a deterministic Jest regression test that forces the late-timelines
load order (fails without this fix, passes with it), and make the e2e
native-query timeline test deterministic via a monthly aggregation and a
wait on the timelines request.

* Point timeline-events regression test at the product bug

The test guards against the timeline-events load-order regression, so its
description should reference the product bug rather than the flaky-test
ticket it surfaced through.

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-10 13:08:26 +02:00
Nicola Mometto
dacc0adad0 Send daily digest for failing transform jobs (#75472)
* stop sending JIT job failure emails

* send daily digest instead

* add test

* cleanup

* keep disabled

* don't use cutoff, use daily range

* fix tests
2026-06-10 11:14:51 +01:00
Mahatthana (Kelvin) Nomsawadi
27fcd32d5d chore: after gold SDK release checklist on master (#75487)
* chore: bump SDK version to 0.63.0-alpha on master

* chore: add lifecycle comments to tag-latest job
2026-06-10 08:36:12 +01:00
Chris Truter
4246d2979a Fix test flake related to search analytics (#75576) 2026-06-10 08:24:29 +02:00
Fraser
114d345f86 Fix plugins violations (#75076) 2026-06-10 15:37:36 +12:00
YB
1142b7e95f [GDGT-2539] enforce run transform result schema (#75376)
Adds a malli schema to driver/run-transform! and the python equivalent that would throw in dev/test and no-ops in prod (to prevent any performance cost from running malli there).

The schema enforces that the map minimally includes the rows-affected key, which is consumed by instrumentation.
2026-06-10 09:57:29 +08:00
github-automation-metabase
f1211ebc0a Auto-update documentation for master (#75568)
Update generated docs (master)

Co-authored-by: github-actions <github-actions@github.com>
2026-06-09 20:45:36 -04:00
Andrei Chernykh
f8873d9ae9 Migrate copy components off EmotionCSS and replace CopyWidget with CopyTextInput (#75425)
Migrate copy components off Emotion and replace CopyWidget with CopyTextInput
2026-06-09 16:43:04 -07:00
Romeo Van Snick
5dc0b835b0 Clean up API client options and remove XHR calls (#74368)
* Remove XHR code path from api client

* Remove fetch: true option in api calles

* Remove fetch option from api as it is now the default

* Remove unused json option for api

* Make retry options internal

* Remove bodyParamName hack

* Remove superfluous hasBody parameter

* Split out request and legacy _makeMethod so we can be more explicit about boty

* Clean up the retry loop

* Move headers to getClientHeaders

* Remove raw option by extending the url template syntax

* Move locale to global variable

* Remove DEFAULT_OPTIONS

* Pull retry into separate module

* Remove _makeRequestWithRetries

* Use async-await for making requests

* Pull out responseStatus helper

* Simplify _buildHeaders

* Remove cast

* Fold _dispatch into _makeRequest

* Use correct type for body

* Use type of transformed response

* Avoid cast on method

* Add appendSearchParams helper

* Remove method arg to substitute-url

* Add buildUrl method

* Move appendQueryparams into branch

* Simplify options parsing

* Add test for undefined params

* Remove unneeded Request instantiation

* Pull out getResponseBody helper

* Parse the relative path correctly

* Use explicit Request so findRequests works

* Remove query wrapper in favor af a thin baseQuery wrapper

* Remove the reliance on fetch-then-abort semantics from XHR

* Make internal methods private

* Split up ApiClient

* Move substituteUrlTags into client utils

* Remove weird self = this

* Move apiRequestManipulationMiddleware into separate file

* Move errors into separate file

* Move CSRF machinery into separate file

* Add telativePath helper

* Only read header when we need it

* Small code cleanups

* Remove unused query.ts

* Remove unused fetch option

* Add types for event map

* Switch to numeric event names

* Remove unused options from transformResponse

* Remove old function-style transformer option

* Remove lengthy comment that was obvious

* Move up status emit

* Flatten branch

* Remove unused fields from ResponseErrorInfo

* Use EventEmitter for response errors

* Make retry cancellable

* Cancel retries too

* Pass url directly

* Simplify OnBeforeRequestHandlerConfig

* Centralize request options resolution

* Centralize error handling and retrying in _dispatch

* Clarify the response body parser

* Return empty body as null instead of the empty string

* Trust the server's content type

* Move types to shared types file

* Avoid parsing/cloning/buffering responses when it's not needed

* Replace transformResponse with rawResponse

* Statically determine the response type when possible

* Remove incorrect comment

* Make ai-streaming go through api client too

* Update override-requests spec for flat headers API

After rebasing onto master, the overrideRequests tests (added on master)
still used the old nested `options: { hasBody }` shape. This branch
flattened OnBeforeRequestHandlerConfig to an optional `headers`, dropping
`options`/`hasBody`, so the tests no longer type-check. Drop the obsolete
fields; the tests only assert on url/method.

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

* Return content type in server mocks

* Make sure headers exist

* Add note about 202 respone handling containing a bug

* Avoid manually parsing JSON responses

* Make aiStreamingRequest return the same shape as APIClient.request

* Remove unserializable error tpye

* Standardize on AbortError

* Import RequestMethod from metabase/api/client

* Do not export non-legacy helpers from legacy-client

* Simplify middleware handler init

* Make internal methods private

* Remove rename

* Move all legacy client machinery into legacy-client

* Fix embed URL :token substitution from legacy POST/PUT bodies

* Expose request body to middleware so embed :token resolves on api.request

Guest-embed saved-card queries (run-query.ts) dispatch through RTK with the
embed `token` in the request body. `api.request` only handed `params` to the
onBeforeRequest middleware, so the embed override could rewrite the URL to
/api/embed/card/:token/query but never fill :token — the request went to
/api/embed/card//query and the question never loaded. The previous commit fixed
only the legacy GET/POST helpers; this does the same for api.request, which is
the path the RTK query endpoints actually use (card/pivot/dashcard queries).

Merge the body into the middleware data (params win on clash), then re-split
leftovers: param-origin keys to the querystring, the rest to the JSON body.
Keys consumed by URL :tag substitution (the embed token) land in neither.

Fixes the guest-embed SDK component tests and e2e guest-embed/token-refresh
flows (pivot + map-tile failures were downstream of the question not loading).

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

* Pass body as a separate argument in middleware

* Fix tests

* Disambiguate network errors from parse errors

* Await visualizer modal save before closing to fix dashcard series race

The visualizer "Save" handlers dispatched the async replace/add thunks
without awaiting them and closed the modal immediately. Those thunks
commit the new card series to the dashcard only after fetching the
referenced cards, so closing early let a subsequent dashboard save run
against the not-yet-updated dashcard and drop the new series.

The blocking XHR transport hid this race; with fetch (dispatched on the
next microtask) it surfaced consistently, e.g. metrics-dashboard.cy
"should be able to combine scalar metrics on a dashcard" where the
dashboard save found no changes, issued no PUT, and the orphaned series
query 404'd ("Some columns are missing").

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

* Fix import

* Enable retry and RTK query endpoints

* Retry RTK queries on 503

* Avoid losing status on unparsable responses

* Fix test

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-06-10 07:43:32 +10:00
Fraser
70604b58c1 Move Metabot QB and Sidebar into query builder (#74740) 2026-06-10 09:39:58 +12:00
Andrei Chernykh
6fba249a18 Migrate moderation components from Emotion to Mantine (#75447)
* Migrate moderation components from Emotion to Mantine

* Remove orphaned ModerationReviewBanner and QuestionModerationSection

* Rename ModerationReviewBanner to ModerationReviewText and use mt prop for icon margin
2026-06-09 14:05:08 -07:00
Alexander Polyankin
4855069483 Fix regexp QP perf issue (#75548)
* fix perf with qp regex

* test
2026-06-09 13:31:43 -07:00
Mihael Konjević
ec842e146c On-demand skills system for Metabot (#75249)
Co-authored-by: Chris Truter <chris@metabase.com>
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-09 20:25:36 +00:00
Chris Truter
92d89811b3 feat(search): retune ranking — boost exact, make library opt-in (#75396) 2026-06-09 22:23:29 +02:00
Timothy S. Dean
e67f0a194a Connection credentials != intent: remove behavioral switches based on connection-type (#75346)
Principles:
1. All database operations should use the default (read) credentials, unless the programmer explicitly upgrades to write credentials.
2. Upgrading to write credentials should not implicitly upgrade downstream code (write-connection should also be able to read, and read operations shouldn't change to write -- or be expected to).

Scenario:
- Refreshing a cached model performs three data-warehouse operations, two of which *require* writes. Its body was wrapped in `with-write-connection`.
- Separately, the impersonation native-query validator was changed to require a different statement type based on which credentials were active. This broke impersonated native-model caching, as the validator rejected the model's SELECT for not being a write.
- `with-default-connection` was introduced to locally downgrade back to read credentials, to patch this up.

Because we don't ever want to accidentally escalate credentials, the system should be rock-solid simple to reason about, and downstream code changing its behavior based on which credentials happen to be active "because it can" is *not that*.
2026-06-09 14:10:54 -06:00
Cam Saul
d5f19b8634 Remove the long-deprecated describe-table-fks method (#75267)
* Remove the long-deprecated `describe-table-fks` method

* Fix typo

* Kondo lint fixes 🔧

* Fix self-require

* Fix accidental use of `driver` alias in `metabase.driver`

* Fix compilation

* Remove unused namespace

* Test fix 🔧

* Test fixes 🔧

* PR feedback & cleanup

* Test fix 🔧

* Test fix 🔧

* Make sure implementations of `describe-fks` support missing options

* Fix docstring

* Snowflake test fix 🔧

* Snowflake test fix 🔧
2026-06-09 13:09:21 -07:00
Alexander Polyankin
c45ee5937e [main] Change missing template tag warning to trace (#75530)
* Change missing template tag warning to trace

* fix
2026-06-09 13:07:16 -07:00
github-automation-metabase
d305bd7b1b fix(e2e): wait for collection API response in cross-version verify tests (#74773)
fix(e2e): wait for collection API response before asserting on entries in cross-version tests

The cross-version verify specs were flaky because cy.findAllByTestId('collection-entry-name')
would fire before the collection items API response was received, hitting the default 4000ms
Cypress retry limit under CI load.

Instead of increasing timeouts, this adds a helper that intercepts the GET /api/collection/root/items
request and waits for it to complete before asserting. This ensures the collection table is fully
rendered before any entry lookups.
2026-06-09 19:22:03 +00:00
Nick Fitzpatrick
95fa251fa6 Uxw 4224 simplify actions and tabs in table details sidebar in data (#75202)
* update TableSection button layout, remove icons from tabs

* move Schema Viewer menu item

* Design Feedback

* e2e and unit test adjustments

* Hide Shame
2026-06-10 00:51:05 +05:30
Sloan Sparger
d80908dbd8 [Metabot] Remove unused metabot REPL (#75518) 2026-06-09 19:18:08 +00:00
Chris Truter
ad23a60790 feat(search): split weight profiles and normalize search contexts (#75388) 2026-06-09 20:51:45 +02:00
Nemanja Glumac
eae3a57f82 Support single-backport escape hatch (#75503) 2026-06-09 20:50:06 +02:00
Chris Truter
701ae37562 Don't resolve inactive tables in portable FK resolution (#75397) 2026-06-09 18:31:32 +00:00
Andrei Chernykh
e81e4c8c9d Show clearer permission state on inaccessible metric pages (#75068)
* Show clearer permission state on inaccessible metric pages

* Update read-only metric e2e test to assert the new permission screen

* Detect metric view permission from the query result, not can_run_adhoc_query

* Lighten MetricPageCard doc comment

* Restore read-only metric test: read-only users can view, editing restricted

* Extract setupForbiddenCardEndpoints test helper for forbidden card mocks
2026-06-09 11:16:22 -07:00
Chris Truter
685421c95a Support query_handle consistently across MCP tools (#75403) 2026-06-09 19:16:27 +02:00
Chris Truter
1cd718fd8e Missed spots with deprecating /mcp route (#75500) 2026-06-09 17:16:07 +00:00
Anderson
a1144c0aa4 Metrics Viewer Dimension Picking Experience Improvements (#74618)
* Metrics viewer: move column picker to viewer controls and remove tabs (#74545)

* Add column picker to metrics viewer controls

* Remove column tabs

* Remove unnecessary mock / Avoid complex relative imports

* Metrics viewer: add column labels visibility toggle (#74562)

* Add metrics viewer column labels menu

* simplify imports

* Implement sidebar dimension picker for metrics viewer (#74627)

* Implement metrics viewer sidebar dimension picker

* Improve sidebar dimension picker accessibility

* Tighten sidebar dimension picker types

* Update metrics viewer dimension icons

* Use available css variables instead of defining raw colors

* Break down/refactor DimensionPickerSidebar

* Implement a few other style improvements / refactoring

* Use accordions to group tables and columns on the sidebar

* Allow accordions to be expanded/collapsed more freely / Fix test

* Avoid some prop drilling / additional clean up

* Fix same-category column select not working

* Address remaining review comments

* Update metrics viewer control styles (#74653)

* Implement metrics viewer sidebar dimension picker

* Improve sidebar dimension picker accessibility

* Tighten sidebar dimension picker types

* Update metrics viewer dimension icons

* Use available css variables instead of defining raw colors

* Break down/refactor DimensionPickerSidebar

* Implement a few other style improvements / refactoring

* Use accordions to group tables and columns on the sidebar

* Allow accordions to be expanded/collapsed more freely / Fix test

* Update metrics viewer control styles

* Fix metrics viewer control hover styles

* Fix a couple bugs on the metrics viewer dimension sidebar state (#74732)

* Fix metrics viewer dimension sidebar state

* Improve getDimensionItemKey

* Refactor metrics viewer code to remove "tab" naming (tabs do not exist anymore) (#74729)

* Refactor metrics viewer dimension breakout naming

* Address remaining 'tab' references

* Make metrics viewer column labels static (#74735)

* Refactor metrics viewer dimension breakout naming

* Make metrics viewer column labels static

* Align column label spacing with designs

* Fix issues with the Metrics Viewer dimension picking sidebar column selection (#74882)

* Fix metrics viewer sidebar field lists

* Fix a couple more issues, clean up

* Show disabled metric pills (#74870)

* Fix metrics viewer sidebar field lists

* Fix a couple more issues, clean up

* Show disabled metric pills

* Code clean up

* Add "No breakout" option to the dimension picking sidebar (#74932)

* Fix metrics viewer sidebar field lists

* Fix a couple more issues, clean up

* Add metrics viewer no breakout option

* Code clean up

* Narrow down useMemo dependencies in MetricsViewerDimensionBreakoutContent

* Update e2e tests for the Metrics Viewer (#74939)

* Fix metrics viewer sidebar field lists

* Fix a couple more issues, clean up

* Add metrics viewer dimension picker e2e tests

* Fix a few tests and restore removed tests

* Do another round of test fixes

* Stabilize metrics viewer E2E coverage

* Address review comment

* Address issues with the new dimension picking UI (#74996)

* Fix sidebar dimension category grouping

* Fix dimension picker See all mapping

* Prevent unmatched See all dimension autofill

* Disable expression pills without mapped dimensions

* Fix blank chart viewer container when all values in a series are 0

* Fix expression pill disabled state / Fix a couple bugs on dimension matching

* Fix bug on metric expression column matching on the sidebar

* Shows expression circle icon on sidebar / Fix accordions not showing up for metrics selected more than once in the formula input

* Show list of columns under category rows instead of column Select element for single-metric view

* Center controls without taking ellipsis menu into consideration

* code clean up

* Fix metrics viewer type checks

* Address review comment

* Refactor metrics-viewer components to resolve over-propping / code clean-up (#75161)

* Refactor metrics-viewer components to use context, reducing over-propping

* Additional refactoring: reorganize hooks, move utility functions, clean up

* Address review comments

* Address most of Kevin's comments

* Fix tests for new hooks and fix ts check

* Fix issues when switching dimension categories / Keep column labels state as we select different dimensions

* Avoid url to grow indefinitely when selecting dimensions

* Fix failing e2e test

* Address review comments

* Fix remaining failing e2e tests
2026-06-09 14:15:02 -03:00
Ryan Laurie
74ca24eb58 Update Backport Reminder (#75504)
* auto pass backport label check for non docs prs

* update backport reminder

* can't change the name

* test docs change

* remove docs change

* ok fine nemanja

* add concurrency limit
2026-06-09 17:04:37 +00:00
Chris Truter
8c71b27b77 Report where MCP saves questions; default to personal collection (#75491) 2026-06-09 17:00:16 +00:00
Chris Truter
fb3416c0c1 feat(search): add a search context enum, default it to api (#75385) 2026-06-09 16:48:11 +00:00
Aleksandr Lesnenko
b7bdfdce6e add admin transforms redirect routes (#75497) 2026-06-09 12:32:54 -04:00
Maksym Yakubych
f88e12ec68 feat: add copy button to metabot code snippets (#74720)
Closes [BOT-1571: Add copy button to Metabot code snippets](https://linear.app/metabase/issue/BOT-1571/add-copy-button-to-metabot-code-snippets)

### Description

Adds a button to copy and embed code snippets.

### How to verify

1. Open Metabot sidebar.
2. Type `Create plain markdown code block without using tools. Write SELECT from accounts repeated 100 times`
3. Send message.

### Demo

![image.png](https://app.graphite.com/user-attachments/assets/eebb4810-fd75-4d55-8607-3339009904e7.png)



### Checklist

- [x] Tests have been added/updated to cover changes in this PR
- [x] If adding new Loki tests: they pass [stress testing](https://github.com/metabase/metabase/actions/workflows/loki-stress-test-flake-fix.yml)
2026-06-09 12:12:24 -03:00
bryan
2aeb340822 GHY-3709 fix Redshift workspace destroy on foreign-grantor default privs (#74919)
* GHY-3709 fix Redshift workspace destroy on foreign-grantor default privs

Workspace destroy was failing with "user cannot be dropped because some
objects depend on it / privileges for default privileges on new relations
belonging to user <grantor> in schema <input-schema>". Two underlying
problems:

1. Destroy-side discovery used `svv_relation_privileges` which only surfaces
   actual relation grants -- not `pg_default_acl` entries. Schemas whose only
   reference to the iso-user was a default-priv row got skipped, leaving the
   row in place. `DROP USER` then failed.

2. Even when the schema was discovered, the REVOKE was issued without
   `FOR USER <grantor>`. `pg_default_acl` rows are keyed by grantor, not
   grantee -- so the no-`FOR USER` form only targets rows owned by
   `current_user`. Rows owned by another role (`stats_admin` in prod) were
   never revoked.

Fix:
- `default-acl-grants-for-user` queries `pg_default_acl` directly and emits
  `(grantor, schema)` pairs referencing the iso-user. Uses
  `array_to_string(defaclacl, ',')` since Redshift refuses `aclitem` casts
  and lacks `aclexplode`.
- Destroy iterates pairs and emits
  `ALTER DEFAULT PRIVILEGES FOR USER "<grantor>" IN SCHEMA "<schema>"
  REVOKE ALL ON TABLES FROM "<iso-user>"`.

Prevention (Redshift-side mirror of #74909):
- Grant-time pre-flight `assert-can-alter-default-privileges!` rejects
  schemas whose relation-owners or pre-existing default-priv grantors cannot
  be impersonated by `current_user`. Redshift has no working
  `pg_has_role(...)` overload on RA3, so impersonation collapses to
  "owner == current_user OR current_user is superuser". Verified live in
  REPL.

Added test skeleton for the foreign-grantor case; body to follow.

* Add driver-level tests for GHY-3709 preconditions and destroy

Redshift (modules/drivers/redshift/test/metabase/driver/redshift_test.clj):
- workspace-precondition-alter-default-privileges-test: mirrors PG's
  precondition test. Creates a non-superuser tenant role and a foreign-
  owned table; asserts the pre-flight raises with status 412 and clears
  after reassignment.
- workspace-precondition-foreign-default-acl-grantor-test: seeds a
  pre-existing pg_default_acl row owned by a foreign grantor and asserts
  the pre-flight catches it -- this is the prevention half of GHY-3709.

PostgreSQL (test/metabase/driver/postgres_test.clj):
- workspace-destroy-survives-foreign-grantor-default-priv-test: regression
  guard. PG sidesteps GHY-3709 because destroy uses DROP OWNED BY, which
  removes default-priv ACL entries where the iso-user is the grantee
  regardless of grantor. The test seeds a foreign-grantor default-priv
  row targeting the iso-user, runs destroy, and asserts the iso-user is
  gone.

Driver:
- Promote `assert-can-alter-default-privileges!` in the Redshift driver
  from private to public so the test ns can call it directly, matching
  the PG driver's visibility on the equivalent fn.

Removed the placeholder skeleton in driver_isolation_test.clj that the
prior commit added -- the Redshift coverage now lives in the
driver-specific test ns next to the existing precondition tests.

All three tests verified live against a real Redshift and Postgres cluster
via REPL before commit.

* Address roborev: stronger test cleanup + randomized PG workspace id

- Redshift tests: add `DROP OWNED BY` for each foreign-grantor role before
  `DROP USER` in the finally blocks. The whole point of these tests is the
  case where DROP USER would fail on lingering pg_default_acl entries, so
  cleanup needs belt-and-suspenders to prevent role accumulation if the
  destroy assertion or the test itself ever regresses.
- PG destroy regression test: switch workspace id from hardcoded
  0xdeadbeef to `(rand-int Integer/MAX_VALUE)`, matching the random-
  suffix convention used by surrounding tests in the same file.

Both still pass live.

* Rename current-user-superuser? -> current-user-usesuper?

Mirror the Redshift catalog column (pg_user.usesuper) rather than the
ambiguous "superuser" label, which already has a load-bearing meaning
elsewhere (cluster admin role).

* Address roborev branch-level findings

- LIKE escape in `default-acl-grants-for-user`: iso-user names always contain
  `_`, which LIKE treats as wildcard, so the unescaped pattern could match
  sibling users' default-priv rows. Added `escape-like-pattern` and `ESCAPE`
  clause. Pipe (`|`) chosen as escape char because Redshift's parser rejects
  `ESCAPE '\\'` as an unterminated string literal.

- `current_user` column-keyword fragility: replaced
  `(:current_user (jdbc/query "SELECT current_user"))` with an aliased
  `SELECT current_user AS me` and `(:me row)`. Removes dependence on the
  JDBC adapter's identifier mangling for a reserved word.

- Widen `relkind` set in `relation-owners-in-schema` from `('r','v')` to
  `('r','v','m','p','f')` to cover materialized views, partitioned tables,
  and foreign tables -- the same scope ALTER DEFAULT PRIVILEGES ... ON TABLES
  affects. Spectrum externals live in svv_external_tables and remain
  excluded; comment added.

- Split destroy batch: the per-grantor default-priv REVOKEs now run as
  individual statements with per-statement try/catch and warn-level logging.
  Previously, a single bad ALTER (e.g. row pointing at a manually-dropped
  schema) would abort the whole batch and leave the iso-user undroppable.

- Test cleanup: `try-execute!` now logs at warn level instead of silently
  swallowing. CI re-runs against transient cleanup failures will now leave
  a trace instead of accumulating orphan roles invisibly.

All four new fns + both new tests verified live against Redshift after the
changes.

* Address roborev: LIKE first-element bug + PG cleanup logging

- Critical bug fix in `default-acl-grants-for-user`: verified live that
  Redshift's `array_to_string(aclitem[])` strips enclosing braces, so the
  output of a row with a single grantee is `name=privs/grantor` -- with no
  leading delimiter. The prior LIKE alternation (`,name=%` OR `{name=%`) only
  matched mid-array entries; single-grantee rows (the common case) were
  silently skipped. Without this, GHY-3709 would have been "fixed" only for
  multi-grantee rows and would have recurred on every typical workspace
  destroy.

  Replaced with a single LIKE that prepends `,` to the haystack:
  `(',' || array_to_string(d.defaclacl, ',')) LIKE ',name=%' ESCAPE '|'`.
  Both single- and multi-grantee rows now match. Verified live with a real
  single-grantee fixture; sibling-with-underscore-substring still does NOT
  match (escape still effective).

- PG cleanup logging: replaced `(catch Throwable _ nil)` in the destroy
  test's finally block with `(catch Throwable t (log/warnf ...))`. CI re-runs
  now surface orphan iso-users instead of masking them behind a downstream
  schema-drop failure.

All tests still green live.

* Update Redshift precondition tests for new error message

Master's PR refactor of raise-unmemberable-default-priv-owners! changed
the error message from one containing 'ALTER DEFAULT PRIVILEGES' to
'not a member of N role(s)'. Update both Redshift precondition tests'
thrown-with-msg? regexes to match, mirroring the PG counterpart at
test/metabase/driver/postgres_test.clj:2557.

* Add Redshift destroy-survives-foreign-grantor integration test

Mirrors the PG counterpart workspace-destroy-survives-foreign-grantor-default-priv-test.
Reproduces GHY-3709 end-to-end: provisions an iso-user, seeds a pg_default_acl
row owned by a foreign role (CREATEUSER + AUTHORIZATION pattern), runs the
real destroy-workspace-isolation!, and asserts DROP USER succeeds.

This is the destroy-path coverage that was missing — the existing
precondition tests only exercise assert-can-alter-default-privileges! at
grant time. This test catches a transaction-aborted regression on the
destroy side if the per-statement REVOKE loop ever poisons its enclosing
JDBC transaction (PG SQLSTATE 25P02).

* Address @ericnormand: autocommit per-grantor REVOKE before destroy tx

Redshift has no SAVEPOINT and aborts the entire transaction on the first
error. The previous shape ran per-grantor REVOKEs inside the destroy
`with-db-transaction`; on any error the tx was poisoned and the
following batch (relation REVOKEs, DROP SCHEMA, DROP USER) silently
rolled back. The catch-and-log was a no-op for cleanup intent.

Fix: split the per-grantor REVOKE loop out into its own auto-commit
phase (jdbc/execute! on the pooled spec, no enclosing tx) BEFORE opening
the destroy transaction. Each REVOKE either commits or fails
independently; one stale row no longer poisons DROP USER.

The main batch stays transactional -- relation REVOKEs + iso-schema
REVOKE + DROP SCHEMA + DROP USER is the cleanup we want atomic.
2026-06-09 09:02:29 -06:00
Nemanja Glumac
6f932522d6 Auto minor releases for every supported major version (#75251)
Auto minor releases for every supported major version.

Schedule-minor now releases a minor for every supported major line, not
just the current one, so the branches we backport into don't go stale.

It reads the supported majors from `major_version_support` in
_version-info.json_ via `getSupportedMajors` — the same source the
auto-backport workflow uses to pick its targets — and dispatches
release-auto.yml once per supported major.

Patch scheduling is left untouched for this first pass.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-09 16:18:21 +02:00
Nemanja Glumac
530bae6edc Fix flaky test: warn about unsaved changes when navigating away while save modal is open (#75482)
Wait for Mantine's focus trap to move focus inside the leave-confirm modal
before pressing Escape, so the realPress keydown lands on the focus-trapped
content where the closeOnEscape handler lives instead of being lost during the
open transition.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-09 14:01:15 +00:00
Nemanja Glumac
5183ebbc86 Auto-backport to supported releases (#74969)
* Derive auto-backport targets from version-info.json release_lines

The `backport` label now fans out to every supported major line, read from
version-info.json: a line is a target iff its eol is todayor later
(lts is display-only and ignored here). Targets fan out via a
fail-fast:false matrix so one cherry-pick conflict can't block the others.

double-/triple-backport keep their original CURRENT_VERSION-based depth
behavior, verbatim, in a separate legacy job at the end of the file as a
short-term manual escape hatch.

* Extract supported-majors logic into a unit-tested release helper

auto-backport.yml builds the release scripts via prepare-release-scripts
and calls the helper, so the "which majors are supported" rule has one tested
implementation instead of being duplicated inline.

Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-09 15:16:31 +02:00
Chris Truter
c81156251c Fix formatDurationLong rounding at unit boundaries (#75474)
## Summary

Fixes a rounding edge in `formatDurationLong`.

The seconds branch formatted via `(durationMs / 1_000).toFixed(1)`, which could round-up to the boundary value we just checked, e.g.

```
formatDurationLong(59_999) // → "60.0s" 
formatDurationLong(60_001) // → "1m 0s" 
```

## Fix

Round the duration to the tenth-of-a-second *before* choosing a branch, so values at th boundary promote to the next unit. The same class of bug existed at the hour boundary, which this also fixes.

## Origin

Introduced in #75102 (`[GDGT-2503] add sorting by duration to transform runs list`)

## Tests

Added boundary cases to `time.unit.spec.ts`; full suite passes and `type-check-pure` is clean.
2026-06-09 14:40:44 +02:00
Timofey Kachalov
df165c37d3 Fix broken parameters api snippets (#75475) 2026-06-09 16:39:04 +04:00
Kamil Mielnik
b324b2bbc8 GDGT-2504 Replace deprecated Badge component (#75114) 2026-06-09 12:19:13 +00:00
Chris Truter
e7ae478c43 Setting to remove recent views from Metabot context (#75470)
Co-authored-by: Mike Appleby <86076+appleby@users.noreply.github.com>
2026-06-09 11:55:05 +00:00
Stas Gavrylov
94ce9b37df Rename App to AppComponent to resolve import conflict with app.js (#75473) 2026-06-09 11:52:41 +00:00
Stas Gavrylov
f716e395a4 Migrate app routes to TypeScript (#75323)
* Migrate app routes to TypeScript

* Cleanup
2026-06-09 13:56:53 +03:00
Nicolò Maria Mezzopera
301179ef9b Add frontend skill patterns from FE PR review feedback (#72689)
* Add frontend skill patterns from Gadget PR review feedback

Codify recurring review feedback from the last 2 months of Gadget
frontend PRs into shared skill patterns so Claude can apply and enforce
them while writing and reviewing TypeScript code.

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

* Add error/loading, Mantine, i18n, security, bundle-size patterns

Extend frontend skill patterns with themes surfaced by aggregating PR
review feedback across all 29 frontend engineers over the last 3 months.

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

* Address PR review feedback: restructure skills, remove duplication

- Inline typescript-patterns into typescript-write, delete shared file
- Merge testing-patterns into e2e-test-create, delete shared file
- Move Mantine/i18n guidance to frontend/CLAUDE.md
- Remove duplicate review checklist from typescript-review
- Remove too-specific examples (custom viz, metabase-lib)
- Remove Cypress line from react-redux-patterns
- Add non-strict null comparison rule (egorgrushin)

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

* Address second round of PR feedback and fix incongruences

- Revert unstructured blob in e2e-test-create; surgically insert helpers
  into Phase 0, intercept guidance into Phase 3, Cypress.env into
  "What NOT to do"
- Remove redundant "Before you submit" checklist from typescript-write
- Fix frontend/CLAUDE.md tech stack line (CSS Modules > Emotion → Mantine > CSS Modules)
- Add etc. to style props list, remove translation-branch-in-tests line
- Deduplicate "do not derive loading from data" in react-redux-patterns
- Add "check helpers first" preamble to Intercepts example

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

* Update Claude skills and guidelines

* Address PR comments

* Updates following PR comments

* Address feedback

* Fix path typo
2026-06-09 13:29:54 +03:00
Ben Grabow
5b2a4365f1 When tables are created in a batch, assign IDs deterministically (#75365)
* When tables are created in a batch, assign IDs deterministically

* Update IDs to match new sort order

* Use a specific table ID instead of assuming that n+1 is valid.

* This test creates a transform targeting the sorted-first schema/table. Update the assertion to expect Schema A, which now sorts first.

* Reorder to match new entity sort order

* Parameterize a hard-coded table id
2026-06-09 05:25:35 +00:00
Nick Fitzpatrick
be3475c670 Send expandedIds when clicking on a table collection in table view of Data Studio (#75404) 2026-06-09 09:22:07 +05:30
Nick Fitzpatrick
6a3b4bd207 Don't move already published tables (#74977)
Don't move alraedy published tables
2026-06-09 09:20:48 +05:30
Nick Fitzpatrick
49b7aa0f57 Unpublish fk linked tables with archiving a collection with published tables (#75046) 2026-06-09 09:20:20 +05:30
Maz Ameli
792592ff00 Restyle the new-device login email with the modern card template (#75246)
Restyle new-device login email with the modern card template

Rewrite login_from_new_device.hbs to mirror transform_failed.hbs (shared
_dashsub_alert_header.hbs partial, centered logo, rounded card, footer),
reshape the context passed by send-login-from-new-device-email! to supply
the namespaced context/payload vars the shared markup expects, and switch
to send-email-with-logo! so custom logos embed via cid. Also simplify the
body copy (no Metabase hyperlink, single greeting paragraph) and update
the session test assertions to match.

Co-authored-by: Cursor <cursoragent@cursor.com>
2026-06-08 17:33:22 -07:00
Alex Yarosh
6f5582f62c docs: Update docs autogen workflow (#75449)
Update default target branch for documentation release
2026-06-09 00:14:58 +00:00
Andrei Chernykh
640d666809 Migrate EmptyState component off Emotion to a CSS module (#75420) 2026-06-08 17:09:51 -07:00
github-automation-metabase
992b2195ea Auto-update documentation for master (#75438)
Update generated docs (master)

Co-authored-by: github-actions <github-actions@github.com>
2026-06-08 20:02:28 -04:00
Egor Grushin
787d9a65be GDGT-2555 Replace deprecated CheckBox with metabase/ui Checkbox (#75372)
* GDGT-2555 Replace deprecated CheckBox with metabase/ui Checkbox

Migrate all remaining usages of the custom common/components/CheckBox to
the Mantine-based Checkbox from metabase/ui, and delete the deprecated
component.

Migrated call sites:
- EntityItem / ItemsTable collection table (per-row select, select-all header)
- ActionCreator FormFieldEditor "Show field" checkbox
- Timeline questions sidebar (TimelineCard, EventCard)
- Enterprise audit table (AuditTableVisualization)

* adjust the checkbox's label color and size

* fix tests

* fix test with a new checkbox
2026-06-09 00:10:57 +01:00
Alexander Polyankin
e839894faa Make workspace db updates in a transaction (#75413) 2026-06-08 23:03:50 +00:00
Chris Truter
e319703c94 Make defaulted defendpoint params Optional in OpenAPI (#75406) 2026-06-08 22:18:23 +00:00
Nemanja Glumac
a866620984 Pilot: self-healing e2e tests (/fix-flaky-test command) (#75434)
Add /fix-flaky-test pilot command for self-healing e2e tests

A bounded, human-supervised loop that diagnoses a quarantined flaky e2e
test, proposes a fix on a branch, and verifies it with CI stress runs
(burn_in=50, fail_fast, network throttling on/off). Pilot, not autonomous:
a human approves before any push and the resulting PRs never auto-merge.
2026-06-09 00:13:13 +02:00
Nathan Voxland
afa196ae00 Fix password-disable when using OIDC (#75361) 2026-06-08 17:02:17 -05:00
metamben
d7b6f616a9 Honor report-timezone in native field filters (#75029)
Closes QUE2-609
2026-06-09 00:59:06 +03:00
Nemanja Glumac
7c0b9e43e2 Fix flaky homepage x-ray save test (#75424)
The "Save this" button on automatic (x-ray) dashboards rendered enabled as
soon as the header was visible, regardless of whether the dashboard had
finished loading. Clicking it before `dashboard` was populated fired a
false `x-ray_saved` analytics event and no-opped `save()`, so no
`POST /api/dashboard/save` request was ever sent.

* Disable the button until `dashboard` is loaded.

* Assert x-ray save via the saved-state UI, not the request alias

cy.wait("@saveDashboard") flaked with 'No request ever occurred' because
it depends on catching the POST in a timing window. Assert the real
user-observable outcome instead: after clicking 'Save this', the header
switches to a 'Saved' button + 'See it' link. Cypress retries that until
the save lands, which (with the disabled-until-loaded guard) is robust.

* Wait for x-ray dashboard readiness (param URL sync) before saving

the dashboard isn't in the store yet. useDashboardUrlQuery syncs the dashboard
params into the URL query string once it's loaded, so a populated location.search
is a reliable readiness signal. Clicking Save before then loses the save.

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 23:30:25 +02:00
Andrei Chernykh
295d050934 Convert sandboxes ParameterTargetWidget and container to TS (#75330)
* Convert sandboxes ParameterTargetWidget and container to TS

* Fix typecheck: bridge loose ValueType to ParameterTarget at the widget boundary

* De-flake TablePicker tree-view test by waiting for the first table

* Drop HOC cast and default export, tidy ColumnPicker widget bridge

* Replace sandbox DimensionRef with ParameterTarget and drop the casts
2026-06-08 14:18:27 -07:00
Fraser
e3f84bfc43 Fix AIProvider config violations (#74888) 2026-06-09 09:15:40 +12:00
Nemanja Glumac
6134f7a7ca Pre-resolve all CI alias combos in cache generator (#75258)
The cache generator resolved only one classpath
(`:build:dev:ee:ee-dev:drivers:drivers-dev:cljs`), but CI jobs run other
alias combinations. Because tools.deps selects dependency versions
globally per classpath, those combos resolve some transitive libs to
versions the generator never cached (e.g. data.json 2.4.0 from the test
classpath, asm 9.2 from shadow-cljs's `:cljs`-only classpath). Those
deltas were fetched Maven Central / Clojars direct on every run, which
intermittently 403s from GitHub's shared runner IPs.

Resolve every distinct alias combination CI uses (one `clojure -P` per
combo) so the saved cache is a superset of what every job needs, and
jobs stop hitting upstream registries for these deltas.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 22:46:59 +02:00
technomancy
943ce3d2b2 Health inspector (#74681)
* WIP health inspector.

* Table and routes for health inspector.

* Add API routes for health inspector.

* Address review suggestions.

* Add delay in between validating each query.
* Check for empty results before trying to divide by zero.
* Formatting

* Address review suggestions.

* Rename *delay* -> *delay-ms*
* Fix migration comment
* Parameterize limit
* Select newest runs first
* Switch to counting valid queries using reduce instead of map

* Move health inspector migration to version 63.

* Add a setting and jitter to health inspector reporting job.

Lower thread priority.

* Move settings into separate ns; sleep as long as validation took.

* Add an init namespace; needed to pass metabase.core.init-test.

* Don't rerun health inspector job on misfire or allow concurrent execution.

* Delete unused delay-ms var.

For some reason the linter didn't catch that this was unused! That's
an annoying bug.

Also use `int` instead of `integer` for health in the DB schema.
2026-06-08 13:40:53 -07:00
technomancy
649b0e2b00 Mark snowflake as not having :transforms/accurate-rows-affected. (#75421)
Similarly to bigquery and redshift, the :rows-affected of the result
is incorrect when doing CTAS operations. We need to mark it as such so
that it will use the fallback COUNT-based approach to get the real number.
2026-06-08 13:32:26 -07:00
Romeo Van Snick
84a31f735c Move metabase/auth to the feature tier (#75375)
* Move auth redux actions into shared redux/auth slice

The session/auth actions (login, logout, refreshSession, etc.) are
app-wide concerns used by nav, metabot, and enterprise auth — not part
of the auth feature UI. Co-locate them with the existing auth reducer in
metabase/redux/auth, matching the convention used by other redux slices
(e.g. redux/user). The LoginData payload type moves alongside the login
thunk.

This removes all cross-module imports of metabase/auth/actions, which is
a prerequisite for moving auth to the feature tier (shared/feature
modules may not import from a feature module).

Pure refactor: no behavior change.

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

* Move auth to feature tier

auth is a user-facing feature (login/logout pages, password reset, auth
provider buttons), not shared infrastructure. Reclassify it from the
shared tier to the feature tier in the module-boundary lint config.

All session/auth redux actions previously imported across modules now
live in the shared metabase/redux/auth slice, so no shared or feature
module imports from metabase/auth anymore. The strict module-boundaries
lint adds zero new violations.

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-06-09 06:30:22 +10:00
Andrei Chernykh
3d0713ce21 Update API keys admin page UI (#75170)
* Modernize API keys admin page with standard empty state, table, and modals

* Polish API keys table layout and modal styling per design

* Add row-menu hover affordance and fix secret-key padding and dark-mode colors

* Fix admin-route and settings tests for new API keys copy

* Add row-click-to-edit, ActionIcon copy button, and align Create/Edit API key modals with the designs

* Align Regenerate API key modal with the shared modal style and mark Key name required on Edit

* Make the API keys e2e group selector case-insensitive after the group label rename

* Remove the shadow from the API key info-note Paper and add a TODO for the future Alert
2026-06-08 13:21:09 -07:00
Alexander Polyankin
70bb44ec4d Limit schemas in workspaces (#75405)
limit schemas in workspaces
2026-06-08 16:17:24 -04:00
Alexander Polyankin
f3dcaa059f Filter out stub databases (#75401)
filter out stub databases
2026-06-08 16:17:16 -04:00
Egor Grushin
6edffa6fb4 GDGT-1784 add a loader to the lens tab (#75151)
* GDGT-1784 add a loader to the lens tab to indicate loading while the tab is active

* fix the indicator for fast lenses

* fix test

* Extract renderIndicator into Indicator component

Co-Authored-By: Egor Grushin <egor@metabase.com>
2026-06-08 21:07:35 +01:00
technomancy
0f23c635f7 Split bigquery driver tests into 2 parts like redshift. (#75366)
They time out otherwise. Might be necessary to do 3 parts honestly.
2026-06-08 11:18:13 -07:00
Riley Thompson
650a933a6f Update transitively dependent cards when card database changes (#75268)
* update dependent cards with new db id

* address feedback
2026-06-08 17:47:35 +00:00
Ryan Laurie
b756e6a1ad Update frontend dev guide (#75419)
update dev guide
2026-06-08 11:06:08 -06:00
Eric Normand
ae5ac5a2ba Re-clone remote sync repo if its temp dir was deleted (GHY-3815) (#75414)
* Re-clone remote sync repo if its temp dir was deleted (GHY-3815)

get-jgit cached Git instances keyed by repo path without checking that
the underlying directory still existed. If $TMPDIR/metabase-git was
deleted, the stale cached instance lost its origin remote and every
remote sync operation failed with 'origin: not found' until restart.
Only return the cached instance when its directory still exists;
otherwise re-clone.

* Type-hint local-path to avoid reflection in git test
2026-06-08 17:02:52 +00:00
John Swanson
aa27de3c3d Fix /api/database/:id/schemas when tables have a NULL schema (#74988)
For databases whose tables have Table.schema = NULL  table-level
`:perms/create-queries` grants were being silently
ignored. The endpoint returned an empty 200 even when the user had
query-builder permission on individual tables.

`schema-permission-for-user` was normalizing its `schema-name` argument
from nil to "" before filtering data_permissions rows. But we weren't
normalizing the other side of the `=` - the
`data_permissions.schema_name`. When this was stored as `NULL`, the
comparison failed.

Note that for mysql, both `:model/Table` and `:model/DataPermissions`
store `NULL` for the schema, triggering this bug - we want the schema
permissions for `NULL` but end up checking the schema permissions for
`""`. There aren't any data permissions for that schema name, so we fall
back to the least permissive permission value and `can-read-schema?`
returned false.

`NULL` and `""` schemas can be treated as functionally equivalent - in
general a single database will *either* have `NULL` or `""` values, so I
think it would be safe to just remove the coercion from both sides of
the equality here (like `(= schema-arg schema-from-data-perm)`), but it
should also be safe to just add coercion to *both* sides of the equation
(like `(= (or schema-arg "") (or schema-from-data-perm ""))`), which is
what I've done here.
2026-06-08 16:28:11 +00:00
Anderson
5bf39260ba Fix picker search fired twice on metrics viewer page load (#75290)
Fix duplicate metric picker search
2026-06-08 13:23:11 -03:00
Andrei Chernykh
04b98c1501 Show value preview for metrics defined on a model (#75169) 2026-06-08 09:03:18 -07:00
Jeff Bruemmer
e6132a0ac6 docs - parameter dropdown labels (#75338) 2026-06-08 11:27:11 -04:00
Oleh K
53baf39e82 Add new color tokens alongside existing ones (#75227)
* GDGT-2529: Add new color tokens alongside existing ones

Foundation for the GDGT-2517 color token refactor. Adds new and
renamed semantic tokens without changing any existing emission or
call sites. After this PR, both old and new CSS variable names
resolve to the same values; migration sweeps will move consumers
to the new names, and the cleanup PR will remove the old.

* GDGT-2529: Move kept tokens from Legacy to New section

These 14 tokens are not being renamed (text-primary, text-brand,
border-brand, tooltip-*, switch-off, etc.) and have no equivalent
in the New section. Moving them into the New group prevents
readers from assuming they're discontinued when they encounter
the Legacy section's 'Prefer using new ones' comment.

* Update Loki Snapshots

* Rearrange and aort new colors keys alphabetically

* Add explanation to core-brand/filter/summarize copy

* Update Loki Snapshots

* Split light/dark themes into `deprecatedColors` and `actualColors`

Per review feedback on #75227 — replaces the `// Legacy colors` and `// New`
section comments with named top-level constants so the intent shows up in
the import graph rather than as inline prose.

---------

Co-authored-by: Metabase Automation <github-automation@metabase.com>
2026-06-08 17:23:21 +02:00
Riley Thompson
984d24be26 Handle null timestamps for druid (#75350)
* fix druid nil timestamp

* remove let block

* use when-let
2026-06-08 14:56:28 +00:00
Oleh K
6bfd5cefd6 Enable JUnit hook-failure rewriting for all e2e tests (#75380) 2026-06-08 16:44:46 +02:00
Chris Truter
dd08672815 Run the Data Complexity Score job weekly instead of daily (#75059) 2026-06-08 12:11:46 +00:00
Egor Grushin
7ee95ea5d8 Fix tooltips rendering under popovers and menus (#75373)
Mantine assigns Tooltip, Popover and Menu the same "popover" z-index
tier (300), so a tooltip tied with them and the winner was decided by
portal DOM order. Once tooltips moved into the fixed PortalContainer
near the top of <body>, later-mounted overlays began painting over
them. Bumping the tooltip z-index to popover+1 keeps it in its tier
while always rendering above same-tier overlays, independent of DOM
order.
2026-06-08 12:07:07 +01:00
Nicola Mometto
514ec567ba Relax schema in security center (#75382)
security center: relax semver schema
2026-06-08 10:56:18 +00:00
Mahatthana (Kelvin) Nomsawadi
0eeccf9ae5 feat: add embedding-devs Slack group to github-slack-map (#75384)
Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-08 11:54:26 +01:00
Nemanja Glumac
c33fe8afee Make representations repair idempotent for unwrapped boolean wrappers (#75304)
Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-08 11:32:42 +02:00
Fraser
a5f3bdb2e2 Fix notifications violations (#75075) 2026-06-08 21:19:05 +12:00
github-automation-metabase
b8bfd206e7 fix: update misleading copy on transforms upsell page (#74938)
- Replace 'No writable database connection' with 'No compatible database
  connection' since the validation checks database compatibility (not
  sample, not audit, supports transforms feature), not write permissions
- Update the permissioned description to show 'Analysts and Admins' for
  all Pro plans, not just pro-self-hosted
- Update body text in NoWritableDatabasesEmptyState to accurately
  describe the requirement

Fixes GRO-421

Co-authored-by: Benoit Vinay <ben@benoitvinay.com>
2026-06-08 09:15:47 +02:00
Fraser
25a4905945 Move models to feature tier (#75212) 2026-06-08 16:13:08 +12:00
Timothy S. Dean
b1b5d4906b Optimize chain filter inner field projections (#75209)
Chain filter built each join's inner stage with no explicit `:fields` projection, leaving `add-implicit-clauses` to fill it in, which on wide tables meant *every single column*. This PR narrows each join's inner projection to exactly the columns the rest of the query references through it.

## Approach

- `with-join-source-fields` sets `:fields` on a join's source subquery; `nil` or empty reverts to implicit-all prior behavior. Modeled after `with-join-fields`, which governs what the join exposes outward to its containing stage.
- `joined-thing` is a re-export of the existing `lib.join` function, surfaced for callers that need to ask whether a join was built against a Table or a Card.

`tighten-join-projections` runs as the terminal pass in `chain-filter-mbql-query`.

Ordering matters. The pass runs after `add-required-filters-if-needed` so that middleware-injected refs (BigQuery partition filters on joined tables, most relevantly) are present in the query before projections are computed. A regression test pins exactly that.
2026-06-07 19:07:00 -06:00
metabase-bot[bot]
c32e5bdaf8 [chore] Update E2E test timings with recent data (#75369)
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-06-07 22:43:32 +02:00
Nick Fitzpatrick
c610661092 Hide collection CTA if user doesn't have publish permisisons (#75275) 2026-06-07 09:19:31 +05:30
github-automation-metabase
b47463a1c9 Auto-update documentation for master (#75359)
Update generated docs (master)

Co-authored-by: github-actions <github-actions@github.com>
2026-06-05 17:37:45 -04:00
Riley Thompson
d202231950 Remove failed bigquery fix attempt (#75344)
remove failed fix
2026-06-05 16:57:42 -04:00
Jeff Bruemmer
8674434557 docs - workspace framing (#75351)
Revise workspaces documentation for clarity
2026-06-05 16:30:25 -04:00
Jeff Bruemmer
a623d06a21 docs - custom viz (#75153) 2026-06-05 20:08:18 +00:00
Andrei Chernykh
6cd06168df refactor(embedding): Convert SavedEntityPicker to TypeScript (#75061)
* Convert SavedEntityPicker to TypeScript

* Pass collectionId to SavedEntityList and drop the tree-node cast

* Gate SavedEntityPicker on currentUser and document children override
2026-06-05 11:36:04 -07:00
Cam Saul
b9fd9c4f3d Add test for #68701 (already fixed) (#75291)
* Add test for #68701 (already fixed)

* cljfmt
2026-06-05 11:24:20 -07:00
Cam Saul
a4f27fd2fc Fix zoom in drill for auto binned lat/lon (#75063)
* Fix zoom in drill for auto binned lat/lon

* Test fix 🔧
2026-06-05 11:24:15 -07:00
technomancy
aa55ae49d3 Add locks around Snowflake dataset creation (#74876)
* Make with-temp-test-data use a randomized dataset name.

This isn't a problem on most DBs, but on cloud DBs where everything is
shared, we have to use a random name unless the dataset is immutable
and never deleted.

* Add dataset-lock implementation for Snowflake.

* Use existing random-name helper for temp-test-dataset names.

* Memoize snowflake locks table creation and use connection pooling.

* Fix stale lock check; apparently the difference can be negative.

* Actually use a separate readlock.

* WIP add debugging info for snowflake locks

* Turn readLock into a no-op for snowflake.

A proper readLock here would almost certainly blow out the timeout
budget. The current implementation is just to check that there isn't
an existing writeLock happening, but it doesn't prevent a new
writeLock from happening, and it's very unreliable, with Snowflake
randomly reporting that the table just disappeared briefly.

Disabling it is bad, but it would still leave us with the writeLock
protecting against the worst of the unreliability.

* Retry when Snowflake tells us the table that definitely exists doesn't exist.

* Grant access to locks table; get rid of retry stuff.

This was caused by an errant use of with-redefs that swapped out the
user accessing the locks table randomly based on parallelism.
2026-06-05 10:06:14 -07:00
Nemanja Glumac
728296f25b Send Cypress failure screenshots to ci-conductor (#75283)
* Send Cypress failure screenshots to ci-conductor (DEV-2000)

Attach each failed test's first failure screenshot to the failed-tests
payload so ci-conductor can upload it to S3 and link it to the run.

- Capture in the after:screenshot hook, the only place Cypress exposes
  testFailure + testAttemptIndex; keep exactly the first failure shot per
  test (testFailure && testAttemptIndex === 0), excluding retries and
  manual cy.screenshot() at the source.
- Drain the per-spec buffer in after:spec and match each failing test to
  its shot by normalized title↔filename containment (after:screenshot
  gives a path but no title; name is null for auto-failure shots).
- Read + base64-inline the file at send time as a data URI; ci-conductor
  stores null when absent.

Best-effort throughout: every step is wrapped, logs on failure, and can
never throw into or interrupt the test run.

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

* Resolve failure screenshots in after:spec, drop the after:screenshot hook (DEV-2000)

The after:screenshot hook was only there for `testFailure` /
`testAttemptIndex`, but both can be recovered from the filename, and
`results.screenshots[].path` in after:spec is the same path the hook
reported. So everything we need lives in after:spec.

Match each failed test to its screenshot by anchoring the normalized
title on the failure marker:

  normalize(basename).startsWith(normalize(title.join("")) + "failed")

Normalizing both sides to [a-z0-9] cancels every Cypress sanitization
rule (">", " -- ", "/", ...) — no reconstruction. Anchoring on "failed"
excludes manual cy.screenshot() shots (which carry no "(failed)") and is
collision-proof against prefix titles; the shortest matching basename is
the first attempt (no "(attempt N)" suffix).

Removes the recordedFailureScreenshots accumulator, recordFailureScreenshot,
takeRecordedScreenshotPaths, and the after:screenshot wiring in config.js —
one hook, no cross-hook state, and strictly more precise matching.

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-06-05 11:00:20 -06:00
Nemanja Glumac
3d13cfe575 Update the org-level CURRENT_VERSION variable (#75288) 2026-06-05 18:30:18 +02:00
Andrei Chernykh
89969fff33 Convert metabase/hoc files to TypeScript (#75070)
* Convert metabase/hoc files to TypeScript

* Use createMockLocation instead of casting in ModalRoute test
2026-06-05 09:02:17 -07:00
Andrei Chernykh
9b6d1ea98e Migrate NewModelOption to TS and move hover styling to CSS (#75130)
* Migrate NewModelOption to TS and move hover styling to CSS

* Use Mantine components and rem in NewModelOption
2026-06-05 09:01:47 -07:00
Andrei Chernykh
d34785dc6e Migrate snippets CollectionRow from JSX to TS (#75138) 2026-06-05 09:01:26 -07:00
Andrei Chernykh
008feef331 Migrate QuestionModerationSection to TS and drop dead unverify path (#75134) 2026-06-05 09:01:05 -07:00
Andrei Chernykh
3378023d91 Migrate ErrorOverview and mode in tools/ from JS to TypeScript (#75072)
* Migrate ErrorOverview and mode in tools/ from JS to TypeScript

* Coerce cardId to number in handleReloadSelected

* Update enterprise/frontend/src/metabase-enterprise/tools/mode.ts

Co-authored-by: Anderson <ands.alves.nunes@gmail.com>

---------

Co-authored-by: Anderson <ands.alves.nunes@gmail.com>
2026-06-05 09:00:44 -07:00
Andrei Chernykh
49251fcf79 Migrate subscriptions sidebar pulse card from Emotion to Mantine (#74999)
Migrate subscriptions sidebar pulse card from Emotion to Mantine and CSS module
2026-06-05 08:58:03 -07:00
Andrei Chernykh
0de49b9ef7 Migrate database engine warning and section field from Emotion to Mantine (#74997)
Migrate database engine warning and section field from Emotion to Mantine and CSS module
2026-06-05 08:57:00 -07:00
Mahatthana (Kelvin) Nomsawadi
43b804d390 feat: add embedding-sdk-tag-latest workflow for npm dist-tag (#75245)
* feat: add embedding-sdk-tag-latest workflow for npm dist-tag

Adds a standalone reusable workflow that sets the `latest` dist-tag on
a published @metabase/embedding-sdk-react version using a classic npm
token (NPM_RELEASE_TOKEN). Trusted publishing (OIDC) cannot set
dist-tags, so this lives in a separate workflow.

Wires the new workflow into release-embedding-sdk.yml as a `tag-latest`
job (disabled via `if: false`). Remove that line when the release branch
becomes gold. Also removes the old commented-out inline dist-tag step.

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: quote GITHUB_STEP_SUMMARY in embedding-sdk-tag-latest workflow

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* Cleanup step by not explicitly create .npmrc and rely on setup-node instead

* ci: use secrets: inherit for npm token in sdk tag-latest workflow

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* ci: use DEFAULT_RUNNER_KEY in sdk tag-latest workflow

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix: add concurrency guard, permissions, and shell injection prevention to tag-latest workflow

- Add concurrency group `npm-dist-tag-latest` (cancel-in-progress: false) to prevent parallel runs from racing
- Add `permissions: {}` for least-privilege (workflow doesn't use GITHUB_TOKEN)
- Hoist version to job-level env var `VERSION` to prevent shell injection via inputs.version
- Add verify step to confirm version exists on npm before tagging
- Quote package spec in npm commands

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-05 16:53:58 +01:00
Nemanja Glumac
6d37c69bbd GHY-3805: Make check-card dependency response order deterministic (#75300)
`broken-cards-response` built `:bad_cards`/`:bad_transforms` from
`(keys card)` and an `IN` query with no `:order-by`, so the response
order was nondeterministic. This flaked
check-card-hydrates-dashboard-and-document-test, which matches
`:bad_cards` positionally via `=?`.

Achieve the deterministic ordering by sorting `created_at` anchored by `id`.
---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: Ben Grabow <ben.grabow@metabase.com>
2026-06-05 17:28:22 +02:00
Nick Fitzpatrick
6a679c2eed Add Data Layer column to table, fix update on undo (#75135)
* Add Data Layer column to table, fix update on undo

* covering undo case in e2e
2026-06-05 20:46:33 +05:30
Jeff Bruemmer
f8a9f7fc47 docs - workspaces (#75274) 2026-06-05 14:54:05 +00:00
Jeff Bruemmer
7273730111 workspace modal copy (#74982) 2026-06-05 10:50:56 -04:00
Nathan Voxland
786417140b Clear setup-token after use (#75198) 2026-06-05 09:29:26 -05:00
Uladzimir Havenchyk
215adbd598 chore: replace more deprecated buttons with mantine button (#75179)
* chore: replace more deprecated buttons with mantine button

* update colors

* fix hover state and button size

* address review

* fix segment form button usage

* use same color
2026-06-05 17:08:44 +03:00
Braden Shepherdson
9393fa8c9b [perms] Break up large SELECTs to avoid the 65K SQL parameter limit (#75032)
Fixes UXW-4107.

SQL queries (at least in Postgres) only allow 65,535 `?` parameters. If
you have a huge set of collections being selected while updating
permissions, Metabase was generating a query with
`WHERE id IN (?, ?, ?, ...)` with more than that many parameters.

With this change, the queries are broken up into chunks of 20k ids
each and the results combined in memory.
2026-06-05 10:04:54 -04:00
Braden Shepherdson
f7acc044e4 [perms] Cap perms for audit collection at :read, don't throw on :write (#74240)
Fixes UXW-3396.

Trying to set `:write` perms for a collection including the magic Audit
collections while setting `Include Subfolders` was throwing a 400.

The cause was that it tried to set `:write` perms for the Audit collection,
which threw an error. This change updates it to treat `:write` as `:read`,
so that the permissions update can succeed.

The FE handles `Include Subfolders` by fetching the tree of
subcollections, and it doesn't handle the Audit collection specially.
2026-06-05 10:04:43 -04:00
Chris Truter
bb6fe57d3f Add Prometheus metric for search result counts (#75186) 2026-06-05 09:28:36 -04:00
Mahatthana (Kelvin) Nomsawadi
5f4211360d fix: pin commons-configuration2 2.15.1 in Databricks driver (#75228)
databricks-jdbc-thin 3.3.1 transitively pulls commons-configuration2
2.11.0 which has CVE-2026-45205 (Uncontrolled Recursion, Medium).
Fixed in 2.15.0; 2.15.1 is the latest patch on that line.

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-05 14:26:18 +01:00
Mahatthana (Kelvin) Nomsawadi
876f2c4e1c fix: pin netty 4.1.135.Final in Snowflake driver (#75229)
AWS SDK (transitive via snowflake-jdbc-thin) pulls io.netty 4.1.126.Final
which has SNYK-JAVA-IONETTY-16438930 (Data Amplification, High) and
SNYK-JAVA-IONETTY-16438322 (Resource Exhaustion, High). Both fixed in
4.1.133.Final.

Pin netty-codec, netty-handler, and netty-transport-classes-epoll to
4.1.135.Final to ensure the full netty family is on a consistent version.

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
2026-06-05 14:26:15 +01:00
github-automation-metabase
6db984ab33 Auto-update documentation for master (#75289)
Update generated docs (master)

Co-authored-by: github-actions <github-actions@github.com>
2026-06-05 09:18:24 -04:00
Ngoc Khuat
af6ea737a3 Honor continue_on_error and full_stacktrace on serialization export (#75122) 2026-06-05 19:15:36 +07:00
Nick Fitzpatrick
7a3ea4c788 allow collection creation when publishing tables (#75261) 2026-06-05 17:32:32 +05:30
Nick Fitzpatrick
d9f40d41ad Remove Our Analytics from library snippet header (#75266) 2026-06-05 17:31:57 +05:30
Ngoc Khuat
6884aea553 Alerts management: failing tab includes abandoned + query failures (#75189)
* Alerts management: failing tab includes abandoned + query failures

The failing tab filtered on last_send (channel delivery) only, so alerts
that never reached delivery — query errors, or runs abandoned on instance
restart — showed as "not failing" even though nobody got the alert.

last_check is the whole-run rollup (success/failed/abandoned), already a
superset of last_send. Add a last_check_status filter and point the failing
tab at it. The explicit "last send attempt" filter still filters delivery
only, so check vs send stay distinct.

* Failing tab: sort by last_check and explain abandoned runs

the failing tab filters on last_check but still sorted by last_send, so abandoned and query-fail alerts (which have no last_send) sank to the bottom, the exact ones it's meant to surface. default the tab to sort by last_check.

abandoned runs have no task_history message, so they showed as failing with a blank reason. synthesize an explanation instead.

* small nitpick

---------

Co-authored-by: Egor Grushin <egor@metabase.com>
2026-06-05 17:43:20 +07:00
Kamil Mielnik
81cc40f669 GDGT-2339 Frontend crashes when notification payload is null (#75107) 2026-06-05 10:14:18 +00:00
Nicola Mometto
3d6b88a2a1 prevent removing table tag from existing incremental transforms (#75101)
* fix: stronger validation, reject updates that would break table incrementality

* fix test

* add tests

* add FE confirmation modal

* update kondo config

* handle FE review comments
2026-06-05 10:10:12 +01:00
Romeo Van Snick
a5630332e5 Fix native editor module boundaries (#75168)
* Remove legacy NativeQueryEditor shim

* Make native-editor toggle buttons fully controlled

* Route native-editor parameter reorder through setDatasetQuery

* Move NativeQueryEditor into the shared querying module

* Move createRawSeries to the shared visualizations lib

* Move TagEditorSidebar into the shared querying module

* Compose template-tag query mutations in transform sidebar

Switching a variable's type fires setTemplateTag and setTemplateTagConfig
back-to-back in one handler. Both derived from the same render-captured
props, so the second onChangeQuery clobbered the first and the type change
was lost — breaking the transform variable editor (TableMappingSelect never
rendered, saves produced no toast).

Track the latest query in a ref and compose each mutation on top of it so
sequential updates no longer overwrite each other. Fixes the failing
transforms template-tags and transforms-incremental e2e specs.

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-06-05 15:04:20 +10:00
Ngoc Khuat
5528bf4740 GDGT-304: Fix unthreadsafe number parsing in csv upload (#75119) 2026-06-05 04:51:37 +00:00
YB
72d014454f [GDGT-2370] add efficiency tracking histogram for incremental transforms (#74651)
Add :metabase-transforms/incremental-rows - a histogram surfacing the efficiency of incremental SQL transforms by emitting two observations per run: rows available in the source (lo, hi] checkpoint window vs. rows actually written to the target.

The :full-incremental-run label separates the first-run / config-change population (where the pair measures whole-table scans) from steady-state windowed runs.

Both numbers derive from a single scan: get-source-range-params now adds count to the existing max-watermark aggregation.

There's some existing gaps which we have mitigated as follows:

Python transforms didn't populate :rows-affected in driver/run-transform!'s return shape, so we are deriving that count from the generated output file from the python runner (number of rows equal number of lines in the file - except for the edge case where no rows were generated)

For full incremental transforms (which translate to CREATE TABLE statements), the drivers for Redshift / BigQuery do not return the number of rows that were in the created tables (they follow this spec https://docs.oracle.com/en/java/javase/21/docs/api/java.sql/java/sql/Statement.html#executeUpdate(java.lang.String)) ; we skip emitting metrics for these 2 drivers in full incremental transforms.
2026-06-05 10:25:05 +08:00
YB
a451945286 [GDGT-2548] chore: use shared constant to set empty cell placeholder values in tables/detail fields (#75223)
replace uses of em-dash empty value placeholder in fields and table cells with shared constant
2026-06-05 10:24:06 +08:00
Cam Saul
4eb1408f48 Remove legacy :druid driver / migrate to :druid-jdbc (#75143)
* Remove legacy `:druid` driver / migrate to `:druid-jdbc`

* Add no-op migration rollback

* Update e2e tests

* Remove additional places mentioning removed Druid driver

* Kondo

* Update modules config
2026-06-04 17:28:37 -07:00
Riley Thompson
6945a211ba Use unicode regex for bigquery alias (#75123)
* use unicode regex for bigquery alias

* trigger ci

* fix workspace e2e test
2026-06-04 23:57:43 +00:00
technomancy
a21f6ab613 Disable bigquery from workspace-full-e2e-test so we can unquarantine (#75254)
Temporarily disable bigquery from workspace-full-e2e-test so we can un-quarantine.
2026-06-04 15:21:05 -07:00
Eric Normand
40af443aaa GHY-3804 require superuser for remote-sync current-task endpoints (#75276)
The /current-task and /current-task/cancel endpoints were protected only
by +auth, letting any authenticated user read sync task details and cancel
active sync operations. Add api/check-superuser to both, matching the rest
of the remote-sync API.
2026-06-04 21:08:20 +00:00
thackervishal
bf4bb7ab10 one word typo fix (#75279) 2026-06-04 16:43:48 -04:00
Eric Normand
18899f65e9 GHY-3801 preserve result_metadata for native cards on serdes export (#75259)
* GHY-3801 preserve result_metadata for native cards on serdes export

Native (non-model) cards can't have their result_metadata re-derived at
import time the way MBQL cards can: query->expected-cols computes MBQL
columns statically from synced metadata, but a native query is opaque SQL
that can only be introspected by executing it. GHY-3339 dropped
result_metadata from all non-model exports on the assumption that import
re-derives it; that holds for MBQL but leaves native source cards with
nil metadata, which breaks downstream GUI questions that join them
("Error adding alias info to join...").

Export the full result_metadata for native non-model cards (mirroring the
pre-GHY-3339 transforms that import-result-metadata already inverts),
while keeping the lean model export and the MBQL non-model skip.

* Whitelist exported keys + assert column names (PR review)

- export-result-metadata: switch the native branch from a blacklist
  (dissoc :fingerprint) to an explicit keep-keys whitelist, so internal
  :lib/* and other computed keys aren't serialized — the bloat GHY-3339
  set out to remove. Keeps the structural type info native needs plus the
  display soft-keys and FK transforms.
- e2e test: assert the imported native card's result_metadata column names
  match the source, not just that metadata is non-empty.
2026-06-04 20:28:19 +00:00
Jeff Bruemmer
b9113d6741 docs - CLI page and revisions on agent-driven workflow (#74976) 2026-06-04 20:10:16 +00:00
Egor Grushin
5efc5f7963 GDGT-2365 fix z-index in PythonEditor (#75052)
* GDGT-2365 fix z-index in PythonEditor

* GDGT-2365 add a repro

* addressing the PR's comments

* addressing the PR's comments

* Update e2e/test/scenarios/data-studio/transforms/reproductions.cy.spec.ts

Co-authored-by: Kamil Mielnik <kamil@kamilmielnik.com>

* Addressing PR's comments

---------

Co-authored-by: Kamil Mielnik <kamil@kamilmielnik.com>
2026-06-04 20:59:41 +01:00
Michael Eby
d5aabfebe4 docs: update homepage settings (#75154)
* docs: update homepage settings

* fix broken link

* edits from jeff and alex
2026-06-04 15:29:13 -04:00
Michael Eby
2626b192f5 docs: update metabase store UI paths (#75136)
* docs: update metabase store UI paths

* fix links

* edits from jeff
2026-06-04 15:28:53 -04:00
Michael Eby
947662623a docs: add drill-through page (#74922)
* docs: add drill-through page

* fix broken links

* edits from alex

* add note about drag to select
2026-06-04 15:28:33 -04:00
Nemanja Glumac
bc3401f4b5 Fix job_id resolution: gh rejects --slurp with --jq (#75260)
#75185 switched the lookup to `gh api --paginate --slurp ... --jq`, but gh
refuses `--slurp` together with `--jq` ("the --slurp option is not supported
with --jq") and exits immediately. The usage error was swallowed by
2>/dev/null, so every attempt produced empty output and JOB_ID was never
written to $GITHUB_ENV — making job_id always null in ci-conductor reports
(it was only ever populated before #75185 when the job landed on page 1).

Slurp with gh and run the filter through a standalone jq instead. The slurped
shape is an array of page objects, which the existing `[.[].jobs[] | ...]`
filter already handles. Verified against a live in-progress run.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-04 21:27:31 +02:00
Eric Normand
706c4c444b GHY-3802 capture extract-phase logs in serialization export.log (#75255)
* GHY-3802 capture extract-phase logs in serialization export.log

The serialization export endpoint hoisted `extract/extract` out of the
`for-ns` log-capture block so invalid-input errors could still set a
non-200 HTTP status. But escape-analysis warnings (content referencing
entities outside the requested collections) are emitted eagerly during
`extract`, so they were logged outside the capture and never reached
`export.log` — leaving customers with a valid archive and an empty log.

Capture the eager extract logs into the same buffer that becomes
`export.log`, and write that buffer after the storage appender has closed
(and flushed). Add a regression test asserting the escape warning lands in
`export.log`.

* kick ci

* Rename serialization-log-nses to serialization-logger-prefixes

These are log4j2 logger-name prefixes, not loaded namespaces. Clarify the
name and docstring so it's obvious each prefix captures every logger nested
under it.
2026-06-04 19:12:26 +00:00
Egor Grushin
cf2ba4502c GDGT-2558 move alerts management from EE to OSS (#75247)
* GDGT-2558 move alerts management from EE to OSS

* fix build error

* fix: missing feature

---------

Co-authored-by: Nicola Mometto <nicola.mometto@metabase.com>
2026-06-04 20:11:00 +01:00
Egor Grushin
2a053bc762 fix flaky test https://app.trunk.io/metabase/flaky-tests/repo/56d8e0a… (#75253)
fix flaky test https://app.trunk.io/metabase/flaky-tests/repo/56d8e0ad-ae87-4941-a147-3082557f1178/test/44ef37ca-1d2c-5e0f-9e51-a9c64654159d
2026-06-04 19:21:41 +01:00
github-automation-metabase
a001486d53 Auto-update documentation for master (#75207)
Update generated docs (master)

Co-authored-by: github-actions <github-actions@github.com>
2026-06-04 13:36:51 -04:00
Filipe Silva
416633f7bc fix: retry message on gsheets transient failure (#75092)
Fix CLO-5546
2026-06-04 15:44:31 +01:00
Benoit Vinay
3eb882a625 Added new strong-enough password type (#75104)
* Added new `strong-enough` password type

* Revert password policy to default normal

* Numbers only test added

* Misc
2026-06-04 16:41:44 +02:00
Mia Miu
5f8ef77462 docs: standardize upload setup link labels (#75178) 2026-06-04 10:27:49 -04:00
Romeo Van Snick
38783c0797 Wait for loading databases (#75216)
* Wait for databases to load in entity picker

* Add unit test for loading databases

* Make allLoading composable in withSavedDatabasesPrefetch

OR the wrapper's own database-loading state with any incoming allLoading
prop instead of overwriting it, matching withAvailableModels. Addresses
PR review feedback; behavior is unchanged today since this is the
outermost wrapper, but it keeps the loading signal composable.

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

* Fix types

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-04 20:49:33 +10:00
Andrei Chernykh
6864d60bea Fix flaky caching test in data studio metrics e2e (#75199)
* Fix flaky data studio metrics e2e by updating the caching test for the modal and hardening library clicks

* Scope the cache strategy option lookup to the open dropdown

* Harden library readiness and absence checks in the metrics e2e spec

* Drop redundant navigation logs in the metrics e2e spec

* Fix archive metric test left on the wrong page after dropping the re-visit

* Retry the whole metricItem chain so a slow library render does not flake the click

* Wait for the library list fetch before interacting with its rows

* Navigate metric pages by id and verify list changes via API to avoid the lazy library tree

* Remove the now-unused metricItem library helper
2026-06-04 12:33:42 +02:00
Romeo Van Snick
1d04c71315 Clean table urls (#75079)
* Add Urls.table() builder for clean /table/:slug links

* Route /table/:slug to the QueryBuilder as an ad-hoc question

* Keep /table/:slug URL while the table question is unedited

* Point table links at Urls.table for clean /table/:slug hrefs

* Scope clean /table URL to the table route; update e2e

* Address PR review: restrict clean /table URLs to concrete tables

- Urls.table now accepts only ConcreteTableId; callers that may hold a
  virtual id (Saved Questions virtual DB, card__<id>) fall back to the
  ad-hoc question / tableRowsQuery URL: TableBrowser, detail-view nav,
  search results, notebook data picker, and metric source-table links.
- updateUrl's /table-route check is now basename-aware so the canonical
  URL behavior works under subpath deployments.
- Drop the virtual-id (card__1) URL test that enshrined an unroutable URL.

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

* Fix CI: keep ad-hoc URL for modelToUrl table links

modelToUrl serves collection/search/library contexts where a user may
only have indirect (published-table) access; the /table/:slug route needs
direct table metadata and 403s for those users (broke the data-studio
table-collection-permissions e2e). Revert that one call site to
tableRowsQuery. Update the InfoText unit test for the search-result table
link, which uses Urls.table directly.

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-06-04 20:16:28 +10:00
Roman Abdulmanov
e0bbcb044f Check webhook secret exists (#75226) 2026-06-04 22:00:15 +12:00
Chris Truter
814398c835 Add semantic-distance scorer for semantic search (#75128) 2026-06-04 10:27:03 +02:00
Phoomparin Mano
eaead01536 Add url to create dashboard and create question tool (#74748)
* create dashboard tool should return the dashboard url

* add unit test on returning dashboard id

* add channel to module config

* fix cljfmt and kondo

* add url to questions
2026-06-04 07:27:55 +00:00
Stas Gavrylov
58a170bf01 GDGT-2525 Introduce PortalContainer for Tooltip component (#75103)
* Set document.body as default target for Tooltip component

* Update selector to 'body' to allow dynamic capturing

* Introduce PortalContainer component as Tooltip target instead of document.body

* Update rendering of PortalContainer, fix tests

* Fix portal rendering in tests

* Make main app portal render in document.body

* Fix storybook provider
2026-06-04 10:12:28 +03:00
Oleh K
b757d6b6bf Add timeout and diagnostic logging to the JUnit hook-rewrite CI step (#75201)
* Bound JUnit hook-rewrite CI step with a timeout and add diagnostic logging

The 'Rewrite JUnit hook failures' step hung for ~30 minutes with no output,
consuming the job's wall-clock budget and cancelling the whole run.
continue-on-error only ignores a non-zero exit, not a hang, so add a
1-minute step timeout so a stall fails just the step.

Also add staged logging (shell marker before bun, then before arg parsing,
after readdir, and per file) so a future stall localizes to a phase instead
of being a black box.

* Remove comment
2026-06-04 08:24:37 +02:00
YB
31fb67c270 [GDGT-2503] add sorting by duration to transform runs list (#75102)
Adds the duration column and make it sortable for the list of transform runs we have in admin view.
2026-06-04 13:19:29 +08:00
Fraser
6f6e012c63 Revert reducers module tier change (#75218) 2026-06-04 16:50:21 +12:00
Fraser
790f4d71ad Reclassify entry-point composition files as app tier (#75073) 2026-06-04 13:47:39 +12:00
Chris Truter
c1ede1fea3 Audit driver/enterprise tests for with-dynamic-fn-redefs (#73940)
Stacked on top of #73140.

Drops the `prefer-with-dynamic-fn-redefs-unaudited` regex from `.clj-kondo/config.edn` so the linter applies to enterprise tests and driver tests too. Converts the ~262 sites it had been silencing across:

- 59 files in `enterprise/backend/test`
- 8 files in `modules/drivers/*/test`

All flagged sites had unambiguously fn-shaped RHSs and defn-style LHSs, so the conversion is mechanical. Four enterprise files needed import adjustments — two had no `metabase.test` alias (added `:as mt`), two already aliased `metabase.test.util :as mt` (added `:as dynamic-redefs` on `metabase.test.util.dynamic-redefs` to avoid the clash).

A second commit reverts 14 SSO-test sites back to `with-redefs` (with inline `#_{:clj-kondo/ignore [...]}` markers) — JWT/SAML/LDAP/OIDC tests hit `/auth/sso` which is served by Jetty workers that don't inherit `*local-redefs*`, so the dynamic redef is invisible to the request handler.

Tested locally: all 919 enterprise tests pass (5649 assertions, 0 failures, 0 errors). Driver tests not run locally — they need DB connections and are expected to be exercised by CI.
2026-06-04 01:24:38 +02:00
Andrei Chernykh
bace1da06a Migrate ArchiveCollectionModal from JSX to TS functional component (#75126)
* Migrate ArchiveCollectionModal from JSX to TS functional component

* Widen ArchiveModal modelId to number | null and pass null for non-numeric collections
2026-06-03 15:08:41 -07:00
Gabriel Moreno
b328d6a4b9 Enable all admin users to activate trial up to pro (#75056)
* refactor: enable non-store admins to go through upsells

* refactor: enable non-store admins to buy transforms

* fix: restore assertions
2026-06-03 14:25:25 -04:00
Chris Truter
729d5a3bbc Support MCP server URL aliases (#75025) 2026-06-03 19:55:48 +02:00
Nathan Voxland
d571a78d1f Default appdb checkoutTimeout to 30s (#75051)
Change c3p0 checkoutTimeout to 30s to avoid forever-waits for connections
2026-06-03 12:20:52 -05:00
Andrei Chernykh
2b4386c784 Migrate License billing info from Emotion to Mantine and CSS modules (#74990) 2026-06-03 08:33:16 -07:00
Ben Grabow
a943448e90 Improve error messages for unsupported H2 functions (#75149)
* Improve error messages for unsupported H2 functions

* regenerate sample db
2026-06-03 10:28:10 -05:00
Nemanja Glumac
d7a4cf2291 Fix job_id resolution on best effort basis (#75185)
Hit the REST jobs API, now with `--paginate --slurp` so the filter sees
every page: a full run has ~185 jobs sharing one run_id, exceeding the
100-per-page cap, so the original single-page lookup silently missed
shards past page 1 and returned null (the original DEV-2117 bug).
Also require status == in_progress and no completed_at so a reused
runner can't match a job it already finished.


Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-03 17:25:23 +02:00
Ngoc Khuat
fdd0b23683 Throttle emails once per message instead of per batch (#75183) 2026-06-03 14:44:34 +00:00
Jakub Chodorowicz
d4be5e5c3f sandbox custom react components (#73941)
* WIP: sandbox custom react components

* improve typing of widget mount

* simplify widget mount module

* refactor widget mount

* refactor widget mount

# Conflicts:
#	enterprise/frontend/src/metabase-enterprise/custom_viz/widget-mount.unit.spec.ts

* refactor viz def settings sanitizer

* improve types

* cleanup naming

* adjust readme and docs

* adjust docs

* use single generic mount to render viz and settings

* improve types

* simplify render in defineConfig

* extract use-plugin-mount

* store test custom viz plugin sources

* fix missing locale in custom viz fixture

* check string setting widgets with allowlist

* add custom viz security custom settings widget security test case

* simplify widget mount stamping to plain property

* use isObject helper, skip non-object values

* add comment explaining rendering flow in usePluginMount

* add performMount and props to explicit deps

* remove obsolete archive with custom plugin

* update test fixture of calendar heatmap

* add react settings widget sandboxing e2e test

* bump sdk version

* revert .only test annotation

* improve test name
2026-06-03 16:14:50 +02:00
github-automation-metabase
2ecf813278 fix: only show trial warning banner when 7 or fewer days remain (#74971)
* fix: only show trial warning banner when 7 or fewer days remain

Previously, the trial banner was shown immediately when starting a new
trial instance, which is overly aggressive. Now the banner only appears
when there are 7 or fewer days left in the trial period.

Closes GRO-452

* fix: update AppBanner integration test for 7-day threshold

Adjust the test to use a date within 7 days of expiry, and add a new
test verifying the banner is hidden when more than 7 days remain.
2026-06-03 13:43:14 +00:00
github-automation-metabase
4c598ca711 Auto-update documentation for master (#75158)
Update generated docs (master)

Co-authored-by: github-actions <github-actions@github.com>
2026-06-03 09:20:15 -04:00
Chris Truter
53f0305835 Add brute-force vector search strategy for semantic search (#75160) 2026-06-03 15:02:53 +02:00
Nicola Mometto
7fc7f35959 fix: use any-transform-enable to gate transform hydration (#75097)
* fix: use any-transform-enable to gate transform hydration

* add test
2026-06-03 11:50:47 +01:00
Kamil Mielnik
96dbeb455a GDGT-1844 Opening a non existant transform from Data Structure folder breaks the ui (#75035) 2026-06-03 16:54:32 +07:00
Kamil Mielnik
40228fc378 Fix "Promise was collected" error in Storybook play functions (#75109) 2026-06-03 16:53:42 +07:00
Uladzimir Havenchyk
d36a73b068 replace deprecated buttons with buttons from ui kit (#75023)
* chore: replace deprecated buttons with mantine button

* more deprecated buttons

* typo
2026-06-03 12:19:39 +03:00
Ngoc Khuat
6b0ea3600e GDGT-2233: Match colliding upload columns by display name on append/replace (#75090) 2026-06-03 08:52:21 +00:00
Uladzimir Havenchyk
346170cf3f chore: rework ChoroplethMap to function component and convert test to ts (#74483)
* chore: convert Map visualization to typescript

* addd missing props to viz definition type

* more tweaks

* more tweaks

* fix typecheck

* fixup

* convert ChoroplethMap to ts

* convert to functional component

* use display name

* oops

* fix comments

* code review

* chore: rework ChoroplethMap and convert test to ts
2026-06-03 11:44:58 +03:00
Romeo Van Snick
13c0db3b5e Typescript 6 (#74140)
* Update to typescript 7.0 (beta)

* Update moduleResolution to bundler

* Switch to tsgo in scripts

* Remove unneeded ts-expect-error

* Add aliases for sdk framework imports

* Add aliases for node_modules types

* Resolve csstype to 3.2.3

* Resolve codemirror types since the package does not export .d.ts files

* Be more precise in SegmentedControl type

* Fix types in CssVarsDeclarationPlugin

* Use correct type for keys in WeakMap

* Use declare context instead of context! to narrow context type

* Import from top-level mantine package

* Remove unused card prop

* Add missing props

* Fix import

* Be more precise in SegmentedControl type

* Convert CardRenderer to TypeScript

* Remove unused @ts-expect-error

* Remove infinite type instantiations

* Do not use declare in type

* Set module to preserve for bundlers

* Add types for tinykeys

* Switch to TypeScript 6.0.3

* Switch back to tsc

* Resolve ts config path directly

* Update @microsoft/api-extractor

* Fix Modal types

* Remove redundant ext-apps ambient module shim

Under the old moduleResolution 'node', the package exports field was
ignored, so @modelcontextprotocol/ext-apps/react could not be resolved
to its real types and this ambient shim re-exported them from the deep
dist path.

With moduleResolution 'bundler', the subpath now resolves natively via
the exports map, while that same exports map blocks the deep dist import
the shim relied on. The shim therefore resolved to nothing and shadowed
the real module, breaking fe-type-check. Deleting it lets the native
types take over.

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

* Remove deprecated baseUrl from next-15 host app tsconfigs

next build runs a full type-check using the repo's TypeScript (now 6.0),
which hard-errors (TS5101) on the deprecated baseUrl option. Both
next-15 production-bundle e2e jobs failed on it.

baseUrl is unnecessary here: the apps only use @/* path mappings and
real package imports, and under moduleResolution 'bundler' paths
resolve relative to the tsconfig location without baseUrl. This also
matches the modern create-next-app scaffold, which no longer emits it.

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

* Potential fix for pull request finding

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

* Remove ts 7 from this branch

* Upgrade typescript-eslint to a version compatible with TS6

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
2026-06-03 17:08:05 +10:00
Andrei Chernykh
fdfbd63fc2 Migrate Group managers UI from Emotion to Mantine and CSS modules (#74993)
* Migrate Group Managers user type components from Emotion to Mantine and CSS modules

* Tidy group detail empty state, member count placement, and admin pane padding

* Update people e2e test for new empty-group copy
2026-06-02 22:14:58 -07:00
Andrei Chernykh
d70174060f Migrate audit table from Emotion to Mantine and CSS modules (#75028) 2026-06-02 22:14:25 -07:00
Fraser
85bf5cfbd8 Fix parameters violations (#75074) 2026-06-03 16:53:32 +12:00
Romeo Van Snick
8d534b519e Move question query runner out of services.js and into metabase/querying (#75016)
* Add RTK query hooks for dashboard card and pivot queries

* Run saved-card queries via RTK in runQuestionQuery

* Add public/embed card and dashcard endpoints

* Add query-endpoints helpers to metabase/api

* Run dashcard queries via RTK in dashboard data-fetching

* Switch to RTK hook in ErrorOverview

* Remove unused pivot-related endpoints from services.js

* Move shouldUsePivotEndpoint into metabase/api/query-endpoints

* Move dispatchQueryEndpoint into metabase/api/query-endpoints

* Move run-query helpers from services.js to metabase/querying/run-query

* Convert run-query to ts

* Use AbortError in query endpoints too

* Remove lazy imports

* Make cardId and token mutually exclusive

* Remove one more dynamic import

* Disambiguate saved-card RTK cache keys with _refetchDeps to fix SDK query abort race

* Avoid Lib database() throw for internal queries in shouldUsePivotEndpoint
2026-06-03 11:34:19 +10:00
Chris Truter
594f46f9ff Fix MCP OAuth discovery behind a TLS-terminating proxy (#75110)
* Fix MCP OAuth discovery behind a TLS-terminating proxy

When Metabase runs behind a proxy that terminates TLS, every OAuth
discovery URL we advertise (issuer, authorize/token/registration
endpoints, protected-resource metadata) is built from the Site URL
setting. If Site URL is stored as http:// the client reaches us over
https but is told to talk to an http:// authorization server, and
rejects the mismatch. Three independent gaps made this hard to recover
from (BOT-1617):

- The OAuth provider config was cached at startup, so correcting Site
  URL had no effect until a restart. Key the cache on Site URL so it
  rebuilds when the setting changes.

- First-boot Site URL auto-seeding read the *-host headers but never
  X-Forwarded-Proto, defaulting to http://. Prepend the forwarded
  scheme (taking the first hop of a comma-separated chain).

- A client probing the bare /.well-known/oauth-protected-resource path
  fell through to the SPA's HTML catch-all, tripping a JSON parse error.
  Serve the metadata at the bare path too.

* Tighten the new docstrings

- Drop the dev-facing "alias of…" note from the bare protected-resource
  endpoint's docstring; defendpoint docstrings render verbatim into the
  OpenAPI docs, and the rationale already lives in the comment above it.
- One sentence per line in forwarded-scheme.

* Match X-Forwarded-Proto case-insensitively

X-Forwarded-Proto may legally be upper/mixed case (e.g. HTTPS). URL
schemes are case-insensitive (RFC 3986), but normalize-site-url's "http"
prefix check is not, so an upper-case scheme would be treated as
scheme-less and mangled into http://HTTPS://… and dropped. Lowercase the
extracted scheme. An unexpected scheme still passes through to fail
normalization, rather than being whitelisted away.

* Guard scheme-prepending against scheme-bearing host headers

Address roborev finding (job 1872): the X-Forwarded-Proto seeding
assumed the *-host headers are scheme-less. A scheme-bearing host header
plus X-Forwarded-Proto would have produced https://https://… → rejected
by normalize-site-url → site-url never seeded, looping on every request.
Only prepend when the host has no scheme; a scheme-bearing host passes
through untouched.

Also tighten the forwarded-scheme docstring to the caller contract
(comma-chain handling moved to an inline comment, covered by a test) and
make the *-host test drive the header from its own label so the case
name can't drift from the header actually set.
2026-06-03 01:24:39 +00:00
Eric Normand
4f60b9d657 Speed up field-values sync via UNION DISTINCT (GHY-3074) (#74533)
* Speed up field-values sync via UNION DISTINCT (GHY-3074)

Replace per-field SELECT DISTINCT queries with a single batched UNION ALL
covering every list-eligible field on a table. Each arm of the UNION runs
its own DISTINCT subquery with the same LIMIT and CAST AS VARCHAR for
type-safe transport. Decoding back to native Clojure values uses the field's
known base_type.

Per-column accuracy is preserved (each column gets up to 1000 distinct
values; has_more_values reflects per-column truncation, not a blanket
table-row sample cap).

Wires the union path through three call sites: scheduled sync, on-demand DB
field-values refresh, and the enterprise data-editor invalidation queue.
Non-SQL drivers (e.g. Mongo) fall back to the per-field path.

* Chunk batched-get-latest-full-field-values IN clause

Wide tables can have thousands of list-eligible fields. A single
`SELECT … WHERE field_id IN (?,?,?…)` with that many parameters can
exceed driver parameter limits (Oracle: 1000, SQL Server: 2100).

Partition the field-id list into batches of 500 and union the results.
Same pattern already used by batch-invalidate-field-values! and
update-field-values-for-on-demand-dbs!.

* Track probed-fields and queries-made in update-field-values task_details

Adds two counters to the sync stats map:
- :probed   number of fields we attempted to fetch distinct values for
- :queries  number of warehouse queries actually issued

On the SQL UNION path these surface the wasted-query ratio that motivated
this PR — a sync run with `{updated:312, probed:5000, queries:100}` shows
that 4688 fields were probed only to confirm "nothing changed", consuming
1 query per ~50 fields instead of 5000 individual queries.

On the non-SQL fallback `:probed` equals `:queries` equals field count
(one DISTINCT per field).

* Fix UNION arm SQL to be driver-portable

The previous shape built `CAST(value AS VARCHAR)` and `LIMIT N` directly in
HoneySQL, which broke on Oracle (needs VARCHAR2(n) + FETCH FIRST), SQL
Server (TOP n), MySQL/MariaDB (CHAR not VARCHAR), and Spark SQL (STRING).

Replace with two driver-aware primitives Metabase already has:

- `sql.qp/cast-to-text` MBQL clause — drivers override to emit their
  native text type (Oracle's VARCHAR2(4000), SQL Server's VARCHAR(MAX),
  Spark SQL's STRING, etc.).
- `sql.qp/apply-top-level-clause :limit` — drivers translate to their
  dialect (Oracle WHERE rownum, SQL Server SELECT TOP N, default LIMIT).

Restructure the arm from a nested SELECT-from-SELECT-DISTINCT to a flat
single-level SELECT with GROUP BY for DISTINCT semantics. GROUP BY
composes cleanly with every driver's :limit transform (notably SQL
Server's TOP N rewrite, which reads from :select and wouldn't have seen
:select-distinct).

Restore the `(isa? driver :sql)` gate so non-SQL drivers (Mongo et al)
fall back to per-field — same blast-radius as master, no regression.

Drops the varchar-type and supports-union-distinct? multimethods I added
in the previous attempt; the per-driver dialect concerns are now handled
by sql.qp's existing extension points.

* Fix UNION arm structure: nest table identifier and parenthesize LIMIT

Two HoneySQL-level bugs from the previous commit, caught by running the
suite in the branch worktree (the earlier "passing" runs were against a
stale REPL in a different worktree):

1. The table identifier went into :from unwrapped, so HoneySQL parsed the
   identifier's own [::identifier :table [...]] vector as a
   [table alias extra] spec. Wrap it as [[expr]] — the same nesting the
   QP's own :source-table handler uses.

2. UNION arms each carried their own LIMIT: `SELECT … LIMIT N UNION ALL
   SELECT … LIMIT N` is illegal SQL (the LIMIT binds to the whole union).
   Nest each limited query as a subquery — `SELECT * FROM (<limited>)` —
   so the LIMIT is parenthesized and the outer arms union cleanly.

Also stop asserting exact :probed/:queries values in the whole-database
sync tests — those counters depend on how many fields across the entire
database have active FieldValues, which is global state these tests
don't pin down. Compare only the create/update/delete/error counts.

* Drop the constant tag from GROUP BY

Postgres rejects a non-integer constant in GROUP BY ("non-integer
constant in GROUP BY") — in Postgres a bare integer in GROUP BY means a
positional column reference, so it disallows other constant literals
there entirely.

A constant in the SELECT list never needs a GROUP BY entry on any
engine, so GROUP BY only the cast expression. The field-name tag stays a
plain SELECT-list literal.

Verified locally against both H2 and Postgres.

* Gate union-distinct tests to SQL drivers

union-distinct-values builds and runs SQL, so the tests that call it
directly only apply to SQL drivers. Previously the integration and
batching tests used a bare mt/dataset, so in a Mongo (or other non-SQL)
CI job they ran against that driver and threw.

Add a sql-test-drivers helper (normal drivers that derive from :sql) and
wrap every direct-call test in mt/test-drivers over it. Non-SQL drivers
exercise the per-field fallback via sync-fields-grouped-by-table!-test,
which works on any driver and is left ungated.

* Add MySQL ::cast-to-text override (CHAR, not TEXT)

MySQL/MariaDB `CAST` does not accept `TEXT` as a target type — its string
cast target is `CHAR`. The `:sql` default for `sql.qp/cast-to-text`
casts to `text`, which is valid on Postgres/H2/Snowflake/Redshift but a
syntax error on MySQL.

This was never caught before because `cast-to-text`'s only other use is
UUID text-comparison, and MySQL has no native UUID type — so the broken
MySQL default was never exercised until the union-distinct field-values
path started casting every column to text.

Override mirrors MySQL's existing `:text` handler, which already casts
to CHAR, and the per-driver override idiom used by Athena, Vertica,
SQL Server, Oracle, etc. MariaDB inherits it via the driver hierarchy.

Verified locally on H2 and Postgres; MySQL relies on CI (local MySQL
test env has an unrelated dataset-teardown failure).

* Add BigQuery ::cast-to-text override (STRING, not TEXT)

BigQuery's string type is STRING; it has no TEXT type, so the :sql
default for sql.qp/cast-to-text (CAST(expr AS text)) is a syntax error.
Same class of bug as the MySQL fix in the previous commit — the default
happens to be valid on Postgres/H2/Snowflake/Redshift but not here.

Override mirrors BigQuery's existing :text handler, which already casts
to STRING.

Verified locally against BigQuery (union-distinct cross-driver and
parity tests).

* kick ci

* Fix docstring continuation indentation

Per the Clojure style guide, docstring continuation lines align with the
opening double-quote (2 spaces), not the first text character (3). Apply
to the docstrings added/modified in this PR.

* Fix docstring indentation in data_editing.clj

* kick ci

* Remove blank line from defn

* Better comment

* Use a private var instead of defn

* Inline union-distinct into models.field-values

The union-distinct namespace was a strategy module being orchestrated
from inside itself, forcing models.field-values to use requiring-resolve
to break the cycle. Merging the 13 forms into models.field-values puts
the orchestration alongside persist-field-values!/limit-values/etc.,
deletes the cycle break, and shrinks the warehouse-schema :api set.

* Rock a comment

* Use transducer for union-distinct batching

* Indentation

* Push empty-input handling into the per-table sync fns

* Use ->map delta helper in per-field sync accounting

* Improvements

* Better comments

* Move both FieldValues caps into persist-field-values!

persist-field-values! now takes raw values from the warehouse, counts them
against *distinct-limit* to detect the row-cap, runs limit-values for the
char-cap, and combines both signals. This removes the QP-level
limit-max-char-len-rff (duplicate of limit-values), drops the
:has_more_values key from distinct-values's return, and updates the
parameter widget caller in parameters.field-values to do its own capping.

Sync code no longer reaches into *distinct-limit* or runs limit-values
manually — both cap concerns are now owned by the warehouse-schema layer.

* Move FieldValues sync orchestration to sync module

The warehouse-schema layer now exposes only run-distinct-batch (the
single-batch UNION ALL primitive) and the persistence primitives. The
batching loop, SQL-vs-non-SQL dispatch, retry semantics, on-demand
refresh, and grouped-by-table orchestration all live in sync.field-values
where they belong.

Removed from warehouse-schema/models/field-values:
- union-distinct-values (batching loop)
- persist-bulk-results! (per-field persist over a batch)
- sql-driver-for-table? (sync-level dispatch concern)
- sync-fields-grouped-by-table! (orchestrator)
- update-field-values-for-on-demand-dbs! (sync workflow)
- table-ids->table-id->is-on-demand? (helper for the above)

Added to sync.field-values:
- fetch-distinct-for-table (batching loop with per-batch try/catch)
- sync-fields-for-table! (unified SQL/non-SQL persister, replaces the
  separate update-field-values-for-table-{union,per-field}! pair)
- sync-fields-grouped-by-table! (moved)
- update-field-values-for-on-demand-dbs! (moved)

Per-batch failures now keep trying through other batches: a recoverable
error (e.g. SQL syntax / query too long) marks the batch's fields as
errors and the loop continues; a non-recoverable error (ConnectException
etc.) propagates out via with-error-handling and aborts the sync.

Updated call sites:
- enterprise/action-v2/data-editing now requires sync.field-values
- queries.models.card and dashboards.models.dashboard call the sync
  version of update-field-values-for-on-demand-dbs!
- dashboards module no longer needs warehouse-schema in its :uses

Updated kondo config to add sync.field-values to sync module's :api set
and to add sync as a :uses for queries and enterprise/action-v2.

* Unify distinct-limit constants and persist code path

- Replaced *absolute-max-distinct-values-limit* with *distinct-limit*
  (both were 1000) and kept the richer docstring.
- Added fetch-distinct-per-field for the non-SQL branch — wraps
  distinct-values per field and returns the same shape as
  fetch-distinct-for-table. Non-SQL drivers now get the same
  :failed-fields semantics: one field's fetch throwing no longer
  cascades into nuking the rest.
- sync-fields-for-table! is now driver-agnostic at the persist layer:
  one reduce, one result->delta, one with-error-handling per persist.
  Branching is contained to the fetch step.

* Drop warehouse-schema from action-v2; push FV-eligibility filter into sync

sync-fields-grouped-by-table! now filters to FV-eligible fields via
field-should-have-field-values? before dispatching. Both callers
(data-editor's batch-invalidate-field-values! and
update-field-values-for-on-demand-dbs!) used to do this filter
themselves; the same logic now lives in one place.

This drops action-v2's only remaining use of warehouse-schema, so it
also disappears from action-v2's kondo :uses.

Also dropped my ^:sync test-metadata typo — it was a no-op tag I
invented; the established convention is ^:synchronized (and these
tests don't mutate global state anyway, so neither applies).

* Add ^:synchronized to FieldValues-writing sync tests

* Gate UNION-DISTINCT path on :nested-queries feature

sync-fields-for-table! used to dispatch to the UNION batch path purely
on (isa? driver-hierarchy :sql). The query structure wraps each arm in
a subquery in FROM, which requires :nested-queries support. All current
SQL drivers declare it (the SQL base class adds it to the default set),
so this is purely defensive — but if a future SQL driver doesn't, it'll
fall back to the per-field path instead of throwing at execution time.

Renamed sql-driver? to can-batch-distinct? to reflect what we actually
require.

* Decode :type/Float and :type/Decimal in UNION results

Auditing decode-value's coverage vs the per-field MBQL path revealed
two real divergences: :type/Float columns were landing as strings via
the UNION path but as Doubles via the per-field path, and same for
:type/Decimal -> BigDecimal vs string. Both round-trip through
:model/FieldValues.values as JSON; a numeric column would JSON-encode
as a number on one path and a string on the other.

Other types we don't decode (Date, DateTime, Time, UUID, IPAddress)
are already JSON-encoded as strings by mi/transform-json, so the
existing string passthrough matches the per-field path's stored
representation — no decoding needed. Added a comment to that effect.

Also hardened Integer's bigint fallback against truly unparseable
input (it threw a second NumberFormatException uncaught for
non-numeric strings) so all numeric branches now fall through to a
string passthrough on malformed input.

decode-value-test extended to cover the full type matrix:
- nil across multiple base-types
- Boolean case-insensitivity (TRUE / True / true / etc)
- Long, BigInteger, BigInteger-via-:type/Integer overflow
- Float, Decimal, Decimal-derived (Currency), Float-derived (Coordinate)
- Malformed numeric input on each numeric branch
- Non-decoded types (Date / DateTime / Time / UUID / IPAddress)

run-distinct-batch-matches-per-field-test extended to include
products.rating (Float) so the parity check would catch a numeric
divergence on every SQL driver in the matrix.

* Fall back to per-field path for tables that require a filter

Partitioned BigQuery tables reject queries without a partition-column
filter. The per-field MBQL path goes through
metadata-from-qp/table-query which has
add-required-filters-if-needed baked into its middleware; the new
run-distinct-batch runs as a native query and bypasses that
middleware, so it would fail on these tables.

can-batch-distinct? now also checks (:database_require_filter table)
and returns false for require-filter tables, dispatching them to the
per-field path which still works.

Tests:
- Unit test on can-batch-distinct? using mt/with-temp tables with the
  flag flipped both ways.
- BigQuery driver test that:
  * Verifies the dispatcher returns false for fv_partitioned_table.
  * Calls sync-fields-grouped-by-table! on the partitioned table and
    asserts that the distinct values ("coffee" / "tea" / "matcha")
    still land in :model/FieldValues correctly via the fallback.

* Route nested-JSON child fields (:parent_id set) to the per-field path

A reviewer caught that two fields can share a name in the same table
when they have different :parent_id values — the unique constraint is
(table_id, parent_id, name), and JSON-column unfolding produces child
fields whose parent JSON column is the disambiguator.

run-distinct-batch had two problems for such fields:

1. by-name collision: (into {} (map (juxt :name identity)) fields)
   keeps only the last same-named field, so the other gets pre-seeded
   :values [] and persist-field-values! would DELETE its existing
   FieldValues row.

2. cast-to-text-honeysql passes (:name field) raw with no parent
   qualification, so the SQL references the wrong column for any
   nested-JSON child.

Both bugs go away by routing :parent_id fields through the per-field
path, which goes through the QP — the QP builds the column reference
correctly (including any parent traversal) and per-field has no
by-name lookup.

sync-fields-for-table! now splits incoming fields by :parent_id:
plain fields go to fetch-distinct-for-table (batch), nested fields go
to fetch-distinct-per-field. merge-fetch-results combines the two
shapes. A table that fails can-batch-distinct? still routes everything
through per-field as before.

Unit test creates two JSON-parent fields with same-named children,
mocks both fetchers, and verifies the dispatcher routes correctly.

* Split run-distinct-batch out into its own namespace to break a cycle

CI surfaced a cyclic load dependency:

    chain-filter → ... → actions → driver-api → sql.qp → field-values →
    field → params.field-values → chain-filter

The new edges from this PR were field-values requiring sql.qp and
query-processor. sql.qp transitively loads actions → ... → eventually
back to field-values via the field/params chain. Local REPL didn't hit
it because everything's already cached; cold-load on CI does.

Fix: move the UNION ALL helpers (build-arm, build-union, run-distinct-batch,
decode-value, table-honeysql, cast-to-text-honeysql, *batch-size*) to a new
namespace, metabase.warehouse-schema.field-values.distinct-batch, which is
the one that imports sql.qp + query-processor. It requires field-values
(for *distinct-limit*). field-values itself no longer requires sql.qp
or query-processor, so the cycle is broken.

Added the new namespace to warehouse-schema's :api set in the kondo
config. sync.field-values and the relevant test files now require the
new namespace alongside field-values.

* Lazy-resolve sync.field-values from card and dashboard to break cycle

Eastwood caught a queries.core <-> queries.models.card cycle. The path:

  queries.models.card → sync.field-values → distinct-batch → sql.qp →
  driver-api → actions.core → actions.execution → query-processor.card →
  queries.core → queries.models.card

queries.models.card's direct (:require [metabase.sync.field-values …]) was
the new edge in this PR. card.clj and dashboard.clj only call
update-field-values-for-on-demand-dbs! at runtime (not at load time), so
requiring-resolve is the standard way to break the static cycle without
changing runtime behaviour. The kondo :uses sync entries on queries and
dashboards modules stay — the dep is still real, just lazy-bound.

* limit-values: keep NULL distinct values

The original PR's limit-values had a (nil? (first values)) -> skip
branch, which made sense when only the UNION batch path called it.
When this branch (in commit de4a6fb7b6) made every persist go through
limit-values, the silent null-stripping started affecting the per-field
MBQL path too — and that path is what backs cached FieldValues for any
field with has_field_values=:auto-list or :list.

The CI regression: parameters.chain-filter-test/nil-values-test creates
a dataset where :myfield contains nil, "", and "value". sync analyses
the field as :auto-list, get-or-create-full-field-values! runs the
QP query (which correctly returns [nil] [""] ["value"]), then
persist-field-values! runs limit-values on those raw values and drops
the [nil] before storing. chain-filter then sees a cached row missing
nil and returns the truncated set.

Fixed by removing the nil-skip clause. nil sorts cleanly into a
sorted-set (it goes first), and parameter widgets care about it as a
"no value set" entry. Updated the unit test to reflect the new
expected behavior.
2026-06-02 22:49:37 +00:00
Fraser
b3e5ae05d1 Fix nav violations (#74738) 2026-06-03 10:10:49 +12:00
Romeo Van Snick
13724dfa7e Migrate ViewNativeQueryEditor to composable NativeQueryEditor (#75080) 2026-06-03 08:10:23 +10:00
Romeo Van Snick
2c3adc56bd Migrate DatasetQueryEditor to composable NativeQueryEditor (#75078) 2026-06-03 08:02:56 +10:00
Romeo Van Snick
3a28d03ece Migrate QueryEditorBody to composable NativeQueryEditor (#75077) 2026-06-03 08:02:53 +10:00
Riley Thompson
71e66269c2 Optimize temporal expressions the same as filters (#74875)
* optimize expressions

* rename for accuracy

* group into one middleware

* include a between filter in test

* rename filter to clause

* improve check for day bucketing, add tests

* fix kondo and a test

* fix test and kondo

* fix test for drivers
2026-06-02 22:00:52 +00:00
technomancy
cdd4c01727 Increase warn time for long tests from 3 seconds to 60 seconds. (#75155)
While in theory it's helpful to know about which tests are "slow", in
practice an awful lot of them are, and no one is working to address
the slow tests, so there is no need to clutter up the CI logs with
information no one is using.

Instead, let's warn when tests go longer than a minute.
2026-06-02 14:58:22 -07:00
Nemanja Glumac
cbe349cac9 Fix set -e abort in e2e-prepare-containers when last service is disabled (#75150)
PR #75096 extracted the docker compose service list into a SERVICES="..."
variable assignment built from command substitutions. Under GitHub Actions'
default bash -e, a variable assignment inherits the exit status of its last
command substitution, so when the last-listed service (snowplow) is disabled,
[ false = true ] && echo ... returns 1, the assignment returns 1, and errexit
aborts the Start Containers step before the retry loop runs. This broke jobs
with snowplow=false (e.g. SDK component tests); e2e-group jobs passed only
because they run snowplow=true.

Build SERVICES as a bash array via standalone test && append statements
(exempt from errexit) and expand with "${SERVICES[@]}", which also fixes the
unquoted-word-splitting on $SERVICES.

DEV-2099

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-02 22:14:37 +02:00
Nathan Voxland
6f3b45b576 Expand Clojure style guide with helpers and idioms (#75124) 2026-06-02 14:55:58 -05:00
bryan
3831a896ca Token scanner: skip image/archive/binary files (#75141) 2026-06-02 21:39:49 +02:00
Timur Mashara
5fb636f09b remove transforms gem from left navigation (#75098) 2026-06-02 21:38:20 +02:00
Anderson
5f0665db9b Fix legacy Library entity ID migration collisions (#74795)
* Fix legacy Library entity ID migration collisions

* Update unit tests
2026-06-02 16:12:34 -03:00
Andrei Chernykh
f74bbbe901 Migrate LogoIcon from JSX class component to TS functional component (#75121) 2026-06-02 12:09:24 -07:00
Nathan Voxland
0d4997a4f3 Improve fingerprint performance (#74683) 2026-06-02 13:16:50 -05:00
Nemanja Glumac
3599d9f885 Send cypress test failures info to ci conductor (#74872)
* Report e2e test failures to ci-conductor (DEV-1999)

Send Cypress failures to the ci-conductor service mid-run, from the
`after:spec` Node hook, so failures can be tied back to the CI run (and
through it the PR / release branch) before the job completes.

- e2e/support/ci_conductor.ts: build the payload and POST it; self-guards
  on a missing webhook URL and never throws into the test run. `job_id`
  lives behind a single seam (sends null for now).
- e2e/support/config.js: call the reporter from `after:spec` (CI only).
- .github/workflows/e2e-test.yml: pass the webhook URL (secret) and REPO_ID.

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

* Dry-run mode for ci-conductor reporting (DEV-1999)

Add a CI_CONDUCTOR_DRY_RUN toggle that logs the payload instead of POSTing,
so we can validate env resolution and payload shape against real CI failures
before sending any data. Enabled in e2e-test.yml for now; remove that env to
start sending for real.

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

* Guarantee ci-conductor reporting can never break the e2e run (DEV-1999)

Wrap the whole report at the after:spec call site in try/catch as a hard
backstop, so a throw from extractFailedTests or anything downstream can't
escape into the run (and the video cleanup still runs). Also widen the
reporter's own try/catch to cover payload build + the dry-run log, not just
the fetch. Errors are logged and swallowed.

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

* Treat the ci-conductor secret as the webhooks base URL (DEV-1999)

The secret now holds the webhooks base (".../webhooks") and the reporter
appends "/failed-tests", so the same secret can serve other webhook endpoints
later and the CI_CONDUCTOR_WEBHOOK_URL name stays accurate. A trailing slash on
the base is tolerated.

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

* Authenticate ci-conductor requests with x-internal-secret (DEV-1999)

The conductor's failed-tests endpoint requires an x-internal-secret header.
Send it from CI_CONDUCTOR_WEBHOOK_SECRET (a GitHub secret passed via
`secrets: inherit`); the header is omitted when the secret is unset, so local
runs are unaffected. The secret value is never logged.

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

* Resolve job_id via composite action and send it to ci-conductor (DEV-1999)

GitHub doesn't expose the current job's numeric `workflow_jobs.id` to a
running job. Add a small composite action `./.github/actions/resolve-job-id`
that resolves it once via the Actions API (matched by run_id+run_attempt+
runner_name; picks the latest-started for sequentially-reused runners) and
exports it as $JOB_ID for any later step in the job to read.

Wire it into the e2e job and have the reporter read JOB_ID, so failed-tests
posts now carry the numeric job_id. Best-effort: a failed lookup just warns
and proceeds, and the reporter falls back to null (the column is nullable).

DEV-2036 tracks an optional server-side alternative (resolve job_id from
runner_id on workflow_jobs) for the longer term.

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

* Retry resolve-job-id lookup to absorb Actions API consistency lag (DEV-1999)

The jobs API is eventually consistent — after a runner picks up a job it can
take a few seconds for runner_name to appear. Doing the lookup early in the
job races with that, so many jobs got "Could not resolve current job id"
warnings while others got lucky. Add a 5x3s retry loop (~12s max wait); the
lookup is cheap and this stays well within job-start budget.

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

* Enrich ci-conductor payload + report flaky tests too (DEV-1999)

Forward more signal so conductor has what it needs to classify and analyze:

  - Top-level: add run_attempt (GITHUB_RUN_ATTEMPT) and retries (the resolved
    Cypress runMode ceiling, surfaced from setupNodeEvents into the env so the
    reporter can include it without a workflow change).
  - Per test: add duration (ms) and attempts (raw {state} array from Cypress,
    forwarded as-is); collapse the old message/stack pair into a single
    `message` carrying the full displayError blob (Cypress only exposes one).
  - Filter widening: include any test with ≥1 failed attempt, so flaky tests
    (failed then passed) now reach conductor alongside broken ones. Healthy
    tests stay omitted, so a clean spec still triggers zero POSTs.

For flaky tests Cypress doesn't keep displayError after the final attempt
passes, so message arrives as null — the failure pattern is still readable
from the attempts array, which is enough for conductor to classify.

The conductor schema isn't final; extra fields are silently ignored on its
side, so this is forward-safe.

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

* Send ci-conductor failed-tests for real (DEV-1999)

Drop the dry-run flag so the reporter POSTs to the conductor instead of just
logging the payload. The dry-run logic stays in the code (gated on the env)
in case we want to flip it back on for debugging a future change.

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

* update schema

* Resolve the job_id just before we run tests

* Fix the docstring

---------

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
Co-authored-by: Ryan Laurie <iethree@gmail.com>
2026-06-02 10:42:34 -06:00
github-automation-metabase
8335330b40 fix: add retry logic to docker login and compose up without third-party actions (#75096)
* fix: add retry logic to docker login and compose up without third-party actions

Replace docker/login-action with a bash retry loop (3 attempts, 15s backoff)
and wrap docker compose up with a retry loop (3 attempts, 30s backoff with
compose down cleanup between retries).

Follows the existing retry pattern from .github/actions/prepare-backend/action.yml.
No third-party retry actions introduced.

Fixes transient Docker Hub connectivity errors that have been causing
~2-4 failures/day for 83+ days.

* fix: pass docker credentials via env vars instead of direct interpolation

- Use env: block to pass username/password as runtime variables
- Prevents special characters from breaking shell interpretation
- Drop unnecessary 2>&1 redirect on docker login
2026-06-02 18:19:03 +02:00
Oleh K
59f0e1214a Replace deprecated Card with Mantine Card (#75020)
* Replace deprecated Card with Mantine Card in BillingInfo

Drops the empty `BillingInfoCard` styled wrapper and renders the Mantine
`Card` directly in BillingInfoTable. The legacy `flat` prop becomes
`withBorder radius="md"` plus Mantine's default no-shadow.

* Replace deprecated Card with Mantine Card in PinnedItemCard

Drops the empty `ItemCard` styled wrapper and renders the Mantine `Card`
directly inside the PinnedItemCard component. `flat` becomes
`withBorder radius="md"` plus Mantine's default no-shadow.

* Match deprecated Card defaults on migrated sites

The Metabase theme's `Paper.config` sets `defaultProps: { shadow: "md" }`,
which Mantine `Card` inherits. Both BillingInfo and PinnedItemCard used
the deprecated `flat` prop (no shadow), so explicitly disable the
inherited shadow via `shadow="none"`.

Also restore the implicit vertical spacing the deprecated card was
contributing via `line-height: 24px`: a small margin-top on PinnedItem's
description and a bit more padding-bottom on its body.

* Replace deprecated Card with Mantine Card in PulsesListSidebar

Swaps the underlying Card import in `PulseCard` to Mantine and moves the
no-shadow / border / radius / no-padding props onto the consumer's
PulseCard render. Drops the no-longer-needed `flat` prop.

* Replace deprecated Card with Mantine Card in LoginHistory

Inline usage in `LoginHistoryItem`. Swaps the Card import to Mantine
and converts the deprecated card's `className + style + p={0}` combo
to native Mantine spacing props (`px="20px" py="sm" my="md"`) plus
`radius="md" withBorder`. Mantine's default `shadow="md"` replaces
the heavier deprecated default.

Mixing `p={0}` with a CS.p* className silently drops the className's
padding — Mantine's own padding wins on specificity — so converting to
Mantine props is the only way to keep the original spacing.

* Replace deprecated Card with Mantine Card in ListItem

Data-reference list item renders Mantine `Card` with native spacing
props (`p="lg" mb="md" w="680px"`) and `radius="md" withBorder`
instead of stacking `hoverable + className(CS.p3, CS.mb2, CS.bgWhite,
CS.rounded, CS.bordered) + style={{width}}` on the deprecated card.
Drops the `hoverable` shadow-on-hover effect — the parent
`<ListItemLink>` already provides hover feedback.

* Replace deprecated Card with Mantine Card in SuggestionsSidebar

X-ray sidebar item card swaps to Mantine `Card` with native spacing
(`p="md"`) and `radius="md" withBorder` instead of the deprecated
`hoverable + className(CS.p2)` combo.

Side effect: the parent Link's hover text-color (`AutomaticDashboardApp.module.css`
.ItemLink :hover) no longer propagates into the card body — Mantine
Paper sets an explicit `color` that blocks the cascade. Not worth
preserving for this view.

* Replace deprecated Card with Mantine Card in BulkActionBar

Swaps `Card` import in `ToastCard` styled wrapper to Mantine and inlines
the `dark` look (dark background, inverse text) so the consumer no
longer needs the deprecated `dark` prop. Also pins
`flex-direction: row` explicitly — Mantine Card defaults to column,
which silently flipped the toast layout vertical.

* Replace deprecated Card with Mantine Card in UndoListing

Converts the `ToastCard` styled wrapper to a function component built on
Mantine `Card`. Maps the legacy `dark` and `noBorder` props to native
Mantine props (`bg`/`c`/`withBorder`) so the consumer's API stays
identical — emotion's `styled()` would have leaked these props to the
DOM as HTML attributes after the swap.

* Remove deprecated Card component

All 8 call sites now use Mantine `Card` (`metabase/ui`). The
`metabase/common/components/Card` directory has no remaining consumers
in either OSS or enterprise code.

* Fix Mantine Card prop types after deprecated Card removal

`styled(MantineCard)` strips Mantine's polymorphic call signature,
which makes consumer props like `onClick`, `color`, `children`, and
`ref` invisible to TypeScript. Two patterns to restore them:

- `BulkActionBar.styled.tsx` ToastCard has no custom props, so cast
  the styled wrapper to `typeof Card` (the same pattern `CardContentSide`
  uses in `UndoListing.styled.tsx`). Drop the now-pointless
  `<Box component={ToastCard}>` wrapper in the consumer — Box wasn't
  adding anything since ToastCard already extends Mantine Card.
- `PulsesListSidebar.styled.tsx` PulseCard needs the custom
  `canEdit` prop, so type the cast as
  `ComponentType<CardProps & ComponentPropsWithoutRef<"div"> & { canEdit }>`.
- `UndoListing.styled.tsx` ToastCard is a function component; extend
  `CardProps & ComponentPropsWithoutRef<"div">` so the consumer's HTML
  attributes type-check.

* Address PR review comments

- LoginHistory: `px="md"` for spacing-token consistency.
- ListItem: `c="inherit"` so the parent `ListItemLink`'s hover color
  propagates into the card body again; explicit `lh="1.5rem"` on the
  title and an `mt` on the subtitle to restore the spacing the
  deprecated card's inherited `line-height: 24px` was providing.
- UndoListing: inline the former `ToastCard` function component at its
  one usage site so `.styled.tsx` only contains styled components.
  Convert the inline-style padding/margin/maxWidth to Mantine
  `px`/`py`/`mt`/`maw` props and simplify the `overflowX` conditional.
- SuggestionsSidebar: `c="inherit"` so the parent `Link`'s hover color
  reaches the card title.

* Don't use rems in lh

* Don't use px in py

* Minor formatting
2026-06-02 18:03:40 +02:00
Nemanja Glumac
072cd1691b DEV-2088: Skip milestone check when there's no prior release to compare (#75085)
The trigger-milestone-check job crashed when cutting the first build of a
new major (e.g. v0.62.0-beta): getLastReleaseTag only looks within the same
major, finds no prior stable tag, and the resulting `undefined` base ref was
fed into the compare API (`compare/undefined...<sha>`), 404ing the job.

Bail early for patches (which share their parent minor's milestone) and
pre-releases (by convention a major's `.0` is always cut as a beta/RC, so a
pre-release is always the first build of a new major with no same-major
baseline). A `!lastTag` guard remains after getLastReleaseTag as a safety net
in case that convention is ever broken.

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-02 17:58:04 +02:00
Egor Grushin
96fc55c8a6 GDGT-2213 Update incremental transform label to "Only process new data" (#75049)
* GDGT-2213 Update incremental transform label to "Only process new data"

* fix failing test
2026-06-02 15:45:42 +01:00
Stas Gavrylov
586dfd96f8 GDGT-2519: Surface hidden tables in Schema Viewer ERD (#75031)
* GDGT-2519: Surface hidden tables in ERD

* GDGT-2519: Add visual mark to hidden table nodes on canvas

* GDGT-2519: Remove 'details-only' and 'normal' from TableVisibilityType
2026-06-02 17:31:31 +03:00
Andrei Chernykh
d971c1216d Migrate public link copy panel from Emotion to Mantine and CSS module (#74998) 2026-06-02 07:15:31 -07:00
Andrei Chernykh
4c2b33b3dc Migrate error components from Emotion to Mantine and CSS modules (#74986) 2026-06-02 07:14:53 -07:00
Andrei Chernykh
cf6eb54cf3 Migrate Object Detail from Emotion to Mantine and CSS modules (#74985) 2026-06-02 07:13:00 -07:00
Ngoc Khuat
0c1e95acdd Fix XLSX exports dropping the currency symbol for non-currency columns (#75026) 2026-06-02 14:12:27 +00:00
Andrei Chernykh
067993f50e Migrate New Model Options from Emotion to Mantine and CSS modules (#74984) 2026-06-02 07:12:24 -07:00
Kevin Kelleher
4c9c985255 Fix failing Update Loki Snapshots workflow (#75106)
* no-verify for loki automation commit

* temp change to test loki update

* Update Loki Snapshots

* revert test changes

---------

Co-authored-by: Metabase Automation <github-automation@metabase.com>
2026-06-02 10:12:04 -04:00
Ngoc Khuat
026b8fcff7 Send transform job-failure emails to all admins in one message (#74751)
* Send transform job-failure emails to all admins in one message

notify-job-failure looped over every admin and published one
:event/transform-failed per admin, producing N separate single-recipient
emails per failure. On instances with many admins this spammed the email
throttler (email-max-recipients-per-second) with N rapid sends, causing
retry storms, and made N SES calls where one would do.

Add a dedicated :event/transform-job-failed event + seeded notification
that targets the admin group and sends a single bcc email, mirroring the
slack-token-error pattern. notify-job-failure now publishes one event.

The per-transform notify-transform-failures path (last editor/creator) is
unchanged.

* Strengthen job-failure test and clean up review nits

- Add an assertion that the email's :bcc field covers the whole admin
  group, proving the send was consolidated rather than fanned out one
  per admin. The previous assertions could not distinguish the two.
- Switch test data to bird-themed emails.
- Point the docstring reference at the seed-notification! var rather
  than the bare namespace.

* Fix cljfmt formatting in notification seed
2026-06-02 20:43:01 +07:00
Ryan Laurie
2cc52e7e9f Convert SearchApp To Typescript (#73740)
* change filename

* convert SearchApp to ts

* simplify

* even better

* fix undefined case
2026-06-02 07:38:34 -06:00
Egor Grushin
af1305dca7 Gdgt 2429 unsaved changes warning does not work while save transform (#75054)
* GDGT-2429 run unsaved changes warning for a new transform if the saving modal is opened and the navigation attempt happen

* GDGT-2429 add tests

* GDGT-2429 extend the test

* GDGT-2429 added "pressing Esc should close the warning, not the saving modal" step to the test
2026-06-02 14:34:47 +01:00
Egor Grushin
a3992af871 GDGT-2516 add snowplow events to the Alerts Management feature. (#75045) 2026-06-02 14:14:45 +01:00
Ngoc Khuat
1ed1a67138 Split oversized email recipient lists to avoid SMTP provider rejection (#74825) 2026-06-02 20:11:39 +07:00
Fraser
116c9343a4 Fix list-view violations (#74877) 2026-06-02 20:30:34 +12:00
Ngoc Khuat
6d926642dd Allow editing MySQL tables when partial_revokes is enabled (#74573) 2026-06-02 08:18:32 +00:00
YB
44847f1ac2 [GDGT-2421] field metadata sandboxing (#74902)
Row & column security already trims columns in query results; this extends the same trimming to the read-only field listings (Data Reference / table metadata) so a sandboxed group sees a consistent column set everywhere. This is a QoL change for sandboxed viewers, OSS/non-sandboxed users and admins are unaffected.
2026-06-02 16:12:05 +08:00
Stas Gavrylov
df4e8ecfa4 GDGT-2515: Fix FK field name crop in Schema Viewer info popup (#75017)
* GDGT-2515: Fix FK field name crop in Schema Viewer info popup

* GDGT-2515: Fix InfoPanel container height

* GDGT-2515: Cleanup legacy styling
2026-06-02 09:46:41 +03:00
Romeo Van Snick
ed34beed0a Replace transformResponse with a rawResponse boolean option (#75003)
* Replace transformResponse with a rawResponse boolean option

The only thing any caller actually used `transformResponse` for in the
legacy client was the `({ response }) => response` escape hatch — "give
me the raw `Response` so I can `.blob()` / `.arrayBuffer()` it" (binary
downloads, map tiles). Replace the whole callback shape with a single
`rawResponse: boolean` option that says exactly that.

Migrations:
- `dataset.ts` `downloadDataset` (both POST and GET branches):
  `transformResponse: ({ response }) => response` → `rawResponse: true`
- `LeafletTilePinMap.tsx`: same swap.
- `query.ts` (RTK baseQuery passthrough): forward `rawResponse` instead.

Side cleanups enabled by removing `transformResponse`:
- Drop the function-form overload on `MethodCreator` (no callers).
- Drop `DEFAULT_OPTIONS.transformResponse`.
- `rawResponse: true` implies the fetch path — XHR has no `Response`
  object, so callers no longer need to pair it with `fetch: true`.

* Always drop Content-Type for formData (not just fetch path)

The previous `options.formData && options.fetch` gate was needed when
`options.fetch` was the only way the formData callers reached the
fetch transport. With `rawResponse: true` now auto-routing through
fetch, those callers no longer pass `fetch: true` — so the gate fails
to fire and the request goes out as `Content-Type: application/json`
with a multipart body. BE rejects with 400.

Fix: gate on `options.formData` alone. XHR's `send(formData)` works
the same way — the browser sets the right Content-Type.

* Strip JSON Content-Type for form-encoded rawResponse downloads

Dropping `fetch: true` from `downloadDataset` (relying on `rawResponse`
to imply the fetch path) regressed the Content-Type handling: the gate
that strips our default `application/json` header keyed off
`options.fetch` alone, so form-encoded download POSTs kept the JSON
header and the backend rejected them with a 400.

Gate the header deletion on the same condition the dispatcher uses to
choose fetch (`isTest || fetch || rawResponse`).

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

* Fix URLSearchParam body

---------

Co-authored-by: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
2026-06-02 14:42:12 +10:00
Nick Fitzpatrick
399290e672 Fix hide when no values for pivot table dashcards (#74851)
* Fix hide when no values for pivot table dashcards

* adding e2e

* fixing test
2026-06-02 09:30:21 +05:30
Nick Fitzpatrick
972bfeda54 Don't invalidate entities on logging activity (#74981)
* Don't invalidate entities on logging activity

* e2e adjustment
2026-06-02 09:29:58 +05:30
Romeo Van Snick
84e629c461 Migrate query action editor (#75015)
* Add composable NativeQueryEditor with backward-compatible shim

* Migrate the QueryActionEditor to new QueryEditor style

* Address PR review comments on native query editor slots

- Pass snippetCollections through the Sidebar slot so the snippets button
  hides correctly when there are no snippets and the root collection isn't
  writable
- Guard the RunButton slot early when run handlers aren't wired up, avoiding
  unnecessary template-tag validation on every render
- Use Children.toArray to collect slot children so React assigns stable keys

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-06-02 13:41:14 +10:00
Romeo Van Snick
d1fc4802ed Migrate NativeQueryModal to composable NativeQueryEditor (#75021) 2026-06-02 13:40:30 +10:00
Andrei Chernykh
f6105b3cf2 Convert DefaultParametersSection and GroupMappingsWidget specs to TS (#75060)
Convert DefaultParametersSection and GroupMappingsWidget specs to TypeScript
2026-06-01 19:01:04 -07:00
Cam Saul
64abdf6d9f Stop using temporary fork of cljfmt (#75062) 2026-06-01 17:25:54 -07:00
Cam Saul
23f1fb4380 Finish migrating parameters QP/driver code to MBQL 5 (#74467)
* Finish migrating parameters to MBQL 5

* PR feedback (part 1)

* Rework the qp.parameters.values namespace

* Kondo

* Test fixes 🔧

* Test fixes 🔧

* Update docstrings

* Test fix 🔧

* MongoDB test fixes 🔧

* cljfmt

* Revert schema changes to Card query

* Test fix 🔧

* 🔧

* PR feedback 🔧

* Kondo 🔧

* Fix crazy keyboard
2026-06-01 16:52:29 -07:00
Romeo Van Snick
4f4134ebe9 Accept FormData / URLSearchParams as the request body directly (#75005)
* Accept FormData / URLSearchParams as the request body directly

The legacy client previously required uploads to be passed through a
`body: { formData }, formData: true, fetch: true` triple — a wrapper
object, a flag duplicating what `instanceof` could check, and a flag
forcing the fetch transport. Teach the client to detect FormData and
URLSearchParams bodies natively:

- `legacy-client.ts`: in `_makeMethod`, when `rawData` is a `FormData`
  or `URLSearchParams`, use it as the body unchanged. Delete the
  default `Content-Type: application/json` so the browser sets the
  right value (multipart boundary or urlencoded charset). XHR's
  `xhr.send(formData)` honors this too — no transport coupling needed.

- `query.ts` (RTK baseQuery): forward FormData / URLSearchParams bodies
  unspread. The previous `{ ...args?.body, ...args?.params }` spread
  yields an empty object for FormData (keys aren't enumerable) and
  would erase the upload.

- Migrated callers: `table.ts` (append-csv, replace-csv) and
  `advanced-config.ts` now send `body: formData`. The legacy wrapper
  shape still works for any caller that hasn't migrated yet.

Pre-existing `formData: true` opt-in is kept as a fallback for now;
removing it is left for a follow-up after the remaining unmigrated
caller (if any turns up) is converted.

* Pull out helper to check for FormData

* Just use FormData instead of FormData and URLSearchParams
2026-06-02 09:22:13 +10:00
github-automation-metabase
2545ec3374 Auto-update documentation for master (#75058)
Update generated docs (master)

Co-authored-by: github-actions <github-actions@github.com>
2026-06-01 18:09:36 -04:00
Edward Paget
06f43840ce Unblock remote sync when configured branch is deleted upstream (#72885)
fix: unblock remote sync when configured branch is deleted upstream (#72778)

When the configured `remote-sync-branch` has been deleted on the remote,
any operation that snapshots the source throws `Invalid branch: X`.
The most visible symptom is that `GET /has-remote-changes` 500s,
blocking the branch-switching UI the user needs to recover.

- `git/fetch!` now passes `.setRemoveDeletedRefs true` so deleted
  remote branches are pruned locally (deterministic signal).
- `git/snapshot*` throws a typed ex-info
  (`{:error-type :missing-branch, :branch ...}`) so callers can
  discriminate.
- `impl/has-remote-changes?` catches `:missing-branch` and returns
  `{:has-changes? false, :branch-missing? true, ...}` instead of
  propagating. The branch-missing result is intentionally not cached.
- `HasRemoteChangesResponse` gains an optional `:branch_missing`
  field; the API handler includes it when set.

Refactored `has-remote-changes?` into small helpers
(`cache-valid?`, `snapshot-or-missing-branch`, `branch-missing-result`,
`fresh-result!`) to flatten the previously nested conditional flow.

Other callers (`async-import!`, `async-export!`) still surface the
typed error — those are explicit user actions where failing loudly is
correct behavior.
2026-06-01 21:21:37 +00:00
Andrei Chernykh
987b137a2d Migrate action form and implicit action icon from Emotion to Mantine (#75036) 2026-06-01 14:11:18 -07:00
Andrei Chernykh
dfdd6542be Migrate impersonation modal and warning from Emotion to Mantine (#75034) 2026-06-01 14:10:54 -07:00
Andrei Chernykh
5d0322cada Migrate move card toast from Emotion to Mantine and CSS module (#74995) 2026-06-01 14:09:52 -07:00
Uladzimir Havenchyk
2c6bb89a55 deps(custom-viz): use safe version of vite (#75053)
* deps(custom-viz): use safe version of vite

* bump custom viz
2026-06-02 00:08:37 +03:00
Eric Normand
d30920ac1a GHY-3727 add network timeout to remote sync git operations (#75047)
Remote sync pull/push could hang indefinitely (stuck at progress 0 during
import fetch/clone, and 0.3 during export push) because JGit transport
commands had no socket timeout. A stalled connection blocked the sync's
virtual thread forever, and neither the cancel flag (only observed in
update-progress!) nor the diehard interrupt (blocking socket I/O ignores
Thread.interrupt) could unblock it.

Apply .setTimeout to every remote git command via call-remote-command,
driven by a new remote-sync-git-timeout-seconds setting (default 60s), so a
stalled operation throws and flows into the existing error-handling path.
2026-06-01 16:06:23 -05:00
Nathan Voxland
c434e744b7 Add 62 to version-helpers.ts (#75040) 2026-06-01 14:37:19 -05:00
Ben Grabow
50061eab17 Bgrabow/better ci report for e2e tests (#75038)
* Capture output from E2E tests

* Capture output from E2E tests

* Revert back to cheshire
2026-06-01 13:43:05 -05:00
Eric Normand
16593d046c GHY-3754 Order serdes export by created_at for stable filename de-dup (#74992)
Same-named entities in the same folder were assigned their filename
de-dup suffix (`foo.yaml` vs `foo_2.yaml`) by the order rows happened to
arrive from the DB, which has no stable ordering. Across re-exports the
order shifted, so two distinct entities swapped files and their
entity_id/created_at/contents appeared to churn — producing large
phantom git-sync diffs.

Order top-level content extraction by created_at, then entity_id as a
deterministic tiebreaker. created_at is monotonic with creation, so the
oldest sibling keeps the unsuffixed file and adding a new same-named
entity appends a `_2` rather than displacing the existing file — an
append-only property a random entity_id would not have. Applied to the
default extract-query-collections path and the Collection and
NativeQuerySnippet overrides via the shared serdes/stable-storage-order.

Nested fetches (e.g. a Dashboard's DashboardCards) are embedded as lists
inside the parent's file rather than written to their own files, so they
keep their natural order and are explicitly excluded from the ordering.

Adds a regression test and updates the serialization baseline fixture to
the new deterministic ordering.
2026-06-01 13:13:35 -05:00
Nemanja Glumac
11377bdea4 Increase timeout for Eastwood test job to 45 minutes (#75041) 2026-06-01 19:50:35 +02:00
Chris Truter
fa9e51914a Replace abandoned verify-pr-label-action with inline gh check (#74953) 2026-06-01 17:41:03 +00:00
Nick Fitzpatrick
85b80747bc Set oauth dynamic registration to false when MCP is disabled (#74923) 2026-06-01 23:03:17 +05:30
Timur Mashara
981e3ed6f6 add tmashara (me) to slack and gh team map (#75027)
add tmashara to slack and gh team map
2026-06-01 19:00:05 +02:00
Andrei Chernykh
16d2f6509e Replace caching strategy picker radios with a dropdown (#74948)
* Replace caching strategy picker radios with a dropdown

* Migrate caching strategy specs from radios to the dropdown

* Address dropdown review feedback and migrate MetricToolbar caching spec

* Migrate caching e2e specs from radios to the dropdown

* Fix impersonated caching e2e: drop stray Default click that toggled the dropdown

* Size the caching modal to its content instead of a fixed height
2026-06-01 09:43:10 -07:00
Riley Thompson
33beb183c2 Add missing honeysql util methods for mbql5 drivers (#75024)
* add missing methods

* match h2 mbql5
2026-06-01 09:58:01 -06:00
Nathan Voxland
75e8f1854d Short-circut permission group membership queries when there is no user (#73245) 2026-06-01 10:51:06 -05:00
metabase-bot[bot]
a05cff3858 [chore] Update E2E test timings with recent data (#75006)
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-06-01 15:19:00 +00:00
metamben
ac5737c926 Prevent writing queries failing the schema checks in the DB (#74884)
Closes QUE2-622
2026-06-01 17:18:46 +03:00
github-automation-metabase
903a9a17c1 Auto-update documentation for master (#74991)
Update generated docs (master)

Co-authored-by: github-actions <github-actions@github.com>
2026-06-01 09:07:32 -04:00
Uladzimir Havenchyk
4cccd299ad chore: replace getAssetUrl with inline images (#74960)
* chore: replace getAssetUrl with inline images

* backend work

* small tightening

* address review

* inline component

---------

Co-authored-by: Nicola Mometto <nicola.mometto@metabase.com>
2026-06-01 15:38:58 +03:00
Nick Fitzpatrick
bb34d6b233 match Viz and dashcard radius (#74843)
* match Viz and dashcard radius

* Updating loki snapshots
2026-06-01 17:58:24 +05:30
Romeo Van Snick
323dca5e46 Entity copy form (#75002)
* Move EntityCopyModal to common and rename it

* Make CopyModal a normal export

* Fix module boundaries for CopyModal

* Throw instead of returning undefined when cloning without underlying question

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-06-01 21:52:20 +10:00
Oleh K
f2f40a73cf Partial rollout of JUnit hook-failure rewriting for select e2e specs (#74958) 2026-06-01 13:13:18 +02:00
Romeo Van Snick
eb6901f096 Refactor NativeQueryEditor to be more composable (#75014)
* Add composable NativeQueryEditor with backward-compatible shim

* Mock query editor sub components

* Address PR review comments on native query editor slots

- Pass snippetCollections through the Sidebar slot so the snippets button
  hides correctly when there are no snippets and the root collection isn't
  writable
- Guard the RunButton slot early when run handlers aren't wired up, avoiding
  unnecessary template-tag validation on every 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>
2026-06-01 20:03:12 +10:00
Romeo Van Snick
0750570270 Use RTK hook for settings in AppThemeProvider (#75013) 2026-06-01 19:44:08 +10:00
Romeo Van Snick
8562bc7d9f Use AbortError to signal request cancellation (#75001)
* Standardize on AbortError for request cancellation

Replace the bespoke `{ isCancelled: true }` shape that the API client threw
on abort with the standard `DOMException` AbortError that `fetch()` already
emits on cancellation. Both transports (`_makeRequestWithXhr` and
`_makeRequestWithFetch`) now reject with AbortError, and an `isAbortError`
helper next to `NetworkError` makes the check ergonomic.

Why:
- Matches the web platform (AbortController contract): `fetch` natively
  throws AbortError, no need to wrap.
- One shape, one check: callers don't have to know which transport ran.
- Better stack traces than a plain object literal.

Consumers migrated from `error.isCancelled`/`isCancelledRequestError` to
`isAbortError(error)` in `services.js`, `query_builder/actions/querying`,
dashboard `context`/`data-fetching`/`types`, and the SDK
`use-load-question` hook.

* Make isAbortError a typed guard and expose AbortError

Define `AbortError` as a named type (`Error & { name: "AbortError" }`)
next to `isAbortError`, and let the guard narrow with it. Reach for
the named type in `CancelledFetchDashboardResult` instead of the
inline `{ name: "AbortError" }` shape.

Pure type refinement — no runtime change.
2026-06-01 19:23:07 +10:00
Romeo Van Snick
a7254d757d Harden e2e tests against timing flakiness (#75004)
Defensive Cypress hardening across ~16 specs and 5 helper files,
preempting a class of timing-sensitive flakes that the upcoming
XHR→fetch transport switch is expected to surface.

The pattern across every file is the same:

- Split chained `.within(() => …)` calls when the parent subject can
  become detached mid-async (pinned items run their query on hover,
  Mantine comboboxes mount async, etc.). Re-query the parent so
  Cypress can retry on detach.

- Add small `clickPullOption` / `clickPushOption` / `clickSwitchBranchOption`
  helpers around the git-sync menu — Mantine combobox state can drop a
  synthetic `.click()` if invoked before the dropdown's handlers are
  wired. `realClick` + a "did the menu close?" verify + retry once.

- Expose a `data-testid="mini-picker-list-loader"` on
  `MiniPickerListLoader` so e2e specs can `cy.findByTestId` the
  loading skeleton instead of relying on text that hasn't rendered yet.

- Add an `expectMultipartBody` assertion in `uploads.unit.spec.js`
  that pins down "table.ts hands FormData through unwrapped, the
  multipart Content-Type is set by the browser" — locks in current
  behavior so the upcoming client refactor can't silently break it.

No production-code behavior changes (the MiniPicker `data-testid` is a
test-only attribute). All extracted from the
`remove-xhr-option-in-api` branch's preflight work.
2026-06-01 19:22:56 +10:00
Mihael Konjević
d5d356d3ec Fix agent portable-FK resolution when two tables share a name across schemas (#74931) 2026-06-01 09:22:39 +00:00
Romeo Van Snick
5ef9224d27 Remove requests reducer (#74994)
* Remove only reader of state.requests

* Remove requests reducer and redux slice
2026-06-01 19:22:36 +10:00
Romeo Van Snick
6bdfe920d4 Table API field order shape (#74890)
* Accept {"field_order": [1,2,3]} in table api as wel as [1,2,3]

* Pass {field_order: [1,2,3]} in table api RTK

* Remove bodyParamName option from the API client

The `bodyParamName` option let a caller say "wrap the data under this
key before stringifying" — a workaround for the `PUT
/api/table/:id/fields/order` endpoint that demanded a top-level array.
Now that the endpoint accepts a normal wrapped `{field_order: [...]}`
body, the previous commit migrated the only caller and the option has
no remaining users.

Drop it from `RequestOptions`, from the body-construction path in
`legacy-client`, and from the RTK Query `apiQuery` baseQuery
passthrough.
2026-06-01 19:22:20 +10:00
Oleksandr Yakushev
837cce9552 [perf] Optimize metabase.search.spec for wide tables (#74706) 2026-06-01 12:04:21 +03:00
Jakub Chodorowicz
102682e36f restrict CSP for img (#74347)
* restrict CSP for img and font

* adjust comment indentation

* wip: introduce csp-img-allowed-hosts and csp-img-enabled settings

* change text info style and placement

* adjust cypress tests

* improve coercion on custom viz setter

* copy improvement

* copy change

* cleanup tests

* refactor hosts parsing logic

* remove docs link

* fix OSS csp-img-enabled setting

* revert the default for img csp to include data and self

* update test comment

* link to custom visualization when it's not possible to turn off csp img

* adjust help links to take into account if custom visualizations are available

* remove reduntand gap

* use alert for security warning of custom viz

* always show security risk notice on setup page for custom viz

* fix formatting

* fix cypress test

* pr feecback: refactor security handles

* improve tech docs

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

---------

Co-authored-by: Jeff Bruemmer <jeffbruemmer@gmail.com>
2026-06-01 09:41:46 +02:00
Chris Truter
8be8d22aa4 Seed suggested prompts for each enabled built-in Metabot (#74951) 2026-05-31 17:25:35 +02:00
Oleksandr Yakushev
bcac56435a [perf] Implement efficient insertion in add-pivot-grouping (#74325) 2026-05-31 11:43:46 +03:00
Oleksandr Yakushev
f5d44c019c [match] Use metabase.util.match macros directly instead of driver-api aliases (#73987) 2026-05-31 10:54:25 +03:00
Alexander Polyankin
8fa3fa576f Improve workspace error messages (#74944)
* fix

* fix messages

* fix

* fixes

* fix

* fix: dedupe snowflake quote-schema/quote-field, update postgres test regex

- snowflake.clj had quote-schema/quote-field defined twice (lines 79-80
  and 1068-1069), which clj-kondo flagged as redefined-vars. Drop the
  duplicate copies near init-workspace-isolation!.
- postgres-test workspace-precondition-alter-default-privileges-test
  was asserting the error message contained "ALTER DEFAULT PRIVILEGES",
  but that phrase was removed from raise-unmemberable-default-priv-owners!
  in the recent error-message rewrite. Match the new message instead.

* fix
2026-05-29 17:31:46 -04:00
Eric Normand
706edecd2b GHY-3372 Update parameter values_source_config.card_id during source swap (#74935)
When a card-to-card source replacement runs, dashboards and cards whose
parameters use the old card as a dropdown source were left pointing at
the old card. The dependency graph correctly switched to the new card,
but parameter dropdowns silently kept the old one, leaving the system
inconsistent.

card-swap-source! and dashboard-swap-source! now also rewrite
:parameters values_source_config.card_id for card-to-card swaps. The
existing before-update hooks on Card and Dashboard propagate the change
to the parameter_card join table. Card-to-table swaps are intentionally
left untouched.

Restores walk-parameter-source-card-ids (removed in b12429ac04) and
extends the previously dashboard-only behaviour to cards too.
2026-05-29 16:07:36 -05:00
Eric Normand
7cf846f5d2 GHY-3728 Strip transient lib markers from serdes MBQL export (#74980)
* GHY-3728 Strip transient lib markers from serdes MBQL export

A Card's dataset_query can be stored in the app DB as either legacy MBQL
or MBQL 5. When a legacy query is read back, normalize-query converts it
to MBQL 5 and adds transient runtime markers (:lib.convert/converted? and
:lib/transformation-added-base-type). export-mbql did not strip these, so
whether a query happened to be stored as legacy or MBQL 5 leaked into the
serialized output, producing spurious git-sync diffs.

Run lib/prepare-for-serialization on full queries during export — the same
normalization applied before persisting a query to the app DB. This is
idempotent for already-clean queries, so it introduces no new churn, and
makes a query export identically regardless of its stored format.

* Remove comment
2026-05-29 20:46:46 +00:00
Ngoc Khuat
761a8527ad Admin page for managing notifications and alerts (#72909)
* Add admin page for managing notifications and alerts

Resolves GDGT-2315/2316/2317/2318/2322.

EE admin page at /admin/tools/notifications (gated on :audit-app) for
listing, filtering, and bulk-managing card-type notifications. List shows
ID, card, creator, recipients, schedule, channel, last sent, and a
computed health state (healthy / orphaned_card / orphaned_creator /
failing). Bulk archive, unarchive, and change-owner are available via
POST /api/ee/admin/notifications/bulk. Per-notification detail page at
/admin/tools/notifications/:id shows the hydrated notification plus its
recent send history from task_history.

Model change: creator_id is no longer blocked from updates on
:model/Notification. It is editable only through the new
superuser-gated admin bulk endpoint.

* Fix detail endpoint passing payload_type as string

The payload_type column has a toucan transform that validates values against
the keyword enum notification-types. Passing the raw string "notification/card"
through t2/select-one's kv-args bypassed decoding and failed the enum check,
returning 500 on GET /api/ee/admin/notifications/:id. Pass the keyword instead.

The list endpoint is unaffected because it uses raw honey-sql to build the
WHERE clause, which bypasses the transform entirely.

* Align admin pages with SettingsPageWrapper convention

Wrap list and detail pages in SettingsPageWrapper + SettingsSection to
match the TasksTabs / PeopleListingApp convention. Promote the list page
title to order={1}. Move pagination onto the same row as filters with
justify=space-between, mirroring TaskListPage.

* Fix module boundary config for notification-admin

- Export :model/TaskHistory from task-history module so other modules can
  reference it (our health/detail endpoints query task_history rows).
- Drop models / premium-features / task-history from notification-admin
  :uses; we don't require any namespace from those modules, only a model
  (covered by :model-imports).
- Drop unused :model/NotificationCard from :model-imports.

* Simplify and bound the notifications admin hot paths

Backend:
- health.clj / api.clj bound the task_history scans used for health and
  send-history by a 90-day window and row-count cap. Previously each list
  refresh pulled every notification-send row ever written; on long-running
  instances this was a latent DB bomb.
- Use metabase.util/index-by in place of hand-rolled (into {} (map juxt)).
- bulk-update! dispatches on a keyword instead of string literals.
- Drop a few noisy comments and shorten over-long docstrings.

Frontend:
- Narrow NotificationSendHistoryEntry.status to a typed union so StatusBadge
  is no longer stringly-typed.
- Memoize NotificationRow and pass stable callbacks keyed by id so toggling
  a checkbox at 50 rows doesn't re-render every row.
- bulkNotificationAction invalidates only the admin list tag plus the
  specific row ids it mutated, not the global notification list.
- Replace the local formatDurationMs duplicate with the shared
  formatDuration helper.

* Paginate send history; address review feedback

Backend:
- Split send history out of GET /:id into a dedicated paginated
  GET /:id/send-history?limit&offset endpoint. Detail load stays lean
  and subsequent pages don't refetch the whole notification.
- Bulk endpoint now restricts updates to payload_type = :notification/card
  so an admin can't archive/unarchive/change-owner a system-event
  notification via a stray id.
- health.clj's task_history walker now also checks
  task_details[:original-info :notification_id], so rows rewritten by
  do-with-task-history on failure are correctly picked up.
- Update notification models-test: creator_id updates are now expected to
  succeed, matching the relaxed before-update invariant documented on the
  earlier commit.

Frontend:
- Add useAdminNotificationSendHistoryQuery hook and a paginated
  SendHistorySection on the detail page.
- ChangeOwnerModal: compute the localized title up front instead of
  nesting a t template inside another t — breaks i18n extraction
  otherwise.

* Drive health off TaskRun; link send history out to Tasks > Runs

Notification sends use task_history under the hood, but the parent
notification-send row is marked :success even when an individual
channel-send child fails (exceptions are caught per handler in
metabase.notification.send). The correct aggregation already lives on
:model/TaskRun, whose status is rolled up from ALL children by
complete-task-run!. Switch health.clj to read from TaskRun via the
existing task_history.run_id link so channel failures actually surface.

A side effect: TaskRun's :abandoned status is now a first-class health
state. Add it to the enum, the filter dropdown, and the badge colors.

Since the Tasks > Runs admin page already paginates + filters these,
drop our bespoke GET /:id/send-history endpoint and RTK hook. The
detail page now links out to
/admin/tools/tasks/runs?run-type=alert&entity-type=card&entity-id=<card>
for the full run history.

Tests: reseed TaskHistory rows via TaskRun so health + last_sent_at
exercise the new path. Drop the two send-history endpoint tests. Add
a regression test asserting the run-level status wins over the
parent task_history status.

* Flatten EE notifications route and fold in simplify fixes

Admin notifications endpoints move from /api/ee/admin/notifications
to /api/ee/notifications. Drops the nested-map workaround in
ee-routes-map (the reason it existed was only to thread a single
feature-gated child under /admin — no other /admin/* routes live
there, and the admin intent is already encoded in the ns name
notification-admin, premium-handler gating, and superuser check).

Also folds in a few review items while touching these files:
- Switch the task_history scan in health.clj from ended_at to
  started_at — only started_at is indexed on task_history; a 90-day
  filter + DESC sort on the unindexed ended_at column would seq-scan.
- Refresh the compute-for-rows docstring to include :abandoned.
- Add Urls.adminToolsTasksRunsFor({runType, entityType, entityId})
  using TaskRunType / TaskRunEntityType. SendHistorySection uses
  that helper instead of hand-concatenating a query string — a typo
  now fails at compile time.

* Declare :model/TaskRun export on task-history and import on notification-admin

The module-boundaries check expects every cross-module :model/ reference
to be declared as an :model-export on the owning module and a
:model-import on the consumer. Our health.clj now reads :model/TaskRun,
so register both entries to match.

* Paginate notifications admin list in SQL when no health filter

Previous implementation fetched every matching notification into
memory, computed health for all, filtered/sorted in Clojure, then
sliced to the requested page. Fine at dev-seed scale but O(N) on
every list refresh at instance scale.

Split the list endpoint into two paths:

- No health filter (the common case): push limit/offset + sort into
  SQL. Sort by notification.updated_at desc (indexed). Compute health
  for only the page. O(page size) per request.
- Health filter set (firefighter mode): materialize the full matching
  set, compute health, filter/sort in Clojure, paginate. O(matching
  rows) — kept because :failing / :abandoned / :orphaned_* are
  post-query computed and we can't easily push them into SQL.

Also normalize the response shape to match Metabase's convention for
paginated list endpoints: {:data :total :limit :offset} (was just
{:data :total}). Consistent with /api/user, /api/persisted-info,
/api/comment, etc.

* Drop last_sent_at sort; use updated_at desc everywhere

sort-by-last-sent-desc was only still used in the health-filtered
path. Neither path needs it — a stable updated_at desc ordering is
fine. Hoists the ORDER BY into base-list-query via ordered-list-query
so both paths share it, removes the in-memory sort fn.

* Fold notification-admin list paths into one function

The two paths for with/without a :health filter shared their entire
tail (hydrate + shape response). Collapse into page+total that
returns {:rows :total} and a single list-notifications that handles
hydrate + {:data :total :limit :offset}. Internal branch is still
there (health is post-query computed; can't push into SQL without
schema work) but caller-visible surface is one function.

* Derive health from TaskRun directly; drop task_history scan

Notifications for alerts have a 1:1 mapping from notification →
payload_id → notification_card.card_id, and each alert-type TaskRun
is keyed by (run_type=:alert, entity_type=:card, entity_id=<card-id>).
That means we can derive health by querying :model/TaskRun directly
by card_id — no need to walk task_history to bridge notification_id
to run_id.

Trade-off: health is now per-card, not per-notification. If two
admins set up alerts on the same card, they share the TaskRun
status. In practice rare, and it matches what admins see on
Admin > Tools > Runs filtered by the same card.

Drops the task_history-related constants and the whole in-memory
JSON walk. Tests updated to seed distinct cards per notification
where the per-card approximation would otherwise cross-contaminate.
health-uses-task-run-not-parent-task-history-test removed — the
distinction it tested no longer exists (we never read task_history).

* Push health filtering into SQL; delete notification-admin.health ns

All five health states are now pure SQL filters. A windowed subquery
(ROW_NUMBER() OVER PARTITION BY entity_id ORDER BY started_at DESC)
gives us the latest alert-type TaskRun per card within the lookback
window, joined against LEFT JOINs on notification_card, report_card,
and core_user. health-where turns the requested state into a WHERE
clause with precedence baked in (orphaned_card > orphaned_creator >
failing > abandoned > healthy).

Side effect: health.clj is entirely redundant. The four helper queries
(nid->card, card->archived, inactive-creator-ids, latest-run-by-card)
duplicated what the SQL JOINs already do. Delete the file; replace
compute-for-rows with a 15-line enrich-row helper that reads the
extra columns we now project (__card_id / __card_archived /
__creator_active / __run_status / __run_ended_at) and assocs :health
+ :last_sent_at.

Both the list and detail endpoints share list-query now. No more
two-path split, no more O(N) materialization for the health-filtered
case. Cross-DB: window functions are supported on H2, Postgres 8.4+,
MySQL 8.0+, MariaDB 10.2+.

clj-kondo modules: drop :model/TaskHistory and :model/TaskRun from
both the task-history :model-exports and our :model-imports — we no
longer reference either directly (the SQL uses raw table names).

* Collapse notification-admin health classifier to one SQL CASE

* Drop __ column prefix; shrink notification-admin row coercion

* Debounce recipient_email filter to stop firing a query per keystroke

* Move notifications-admin pagination into a footer under the table

* Align notifications-admin pages with admin/tools design language

List page:
- drop Select labels, use "Filter by X" placeholders like Tasks/Runs
- one-line rows: Ellipsified on Card and Creator, nowrap on Last sent
- merge Channel column into Recipients as inline icon + count
- absolute Last sent timestamp with relative-time tooltip
- fix click dead-zone: only the card Link stops row-click propagation
- use CS.cursorPointer utility instead of inline style
- shorter health labels ("Orphaned", "No owner") + override Badge
  label overflow so labels aren't clipped by sub-pixel rendering
- add info tooltip next to page title

Detail page:
- card name is the page title, with Alert #N as a subtitle
- drop the redundant "Alert" badge
- muted back link matching TaskRunDetailsPage
- h3 section titles, bold inline labels, no Divider rules
- two-column Grid: Details left, Recipients right
- inline list of the last 5 alert runs with status badges
- drop the duplicate Change owner button next to the creator row

Schedule formatter:
- guard schedule_hour with Number.isFinite so bad crons don't render
  "Check daily at NaN"

adminToolsTasksRunsFor:
- optional startedAt so the Runs page entity picker populates when
  linked from the notification detail page

* Test notifications-admin refactor and tighten back-link

- schedule formatter: regression tests for NaN schedule_hour on daily,
  weekly, and monthly
- adminToolsTasksRunsFor URL builder: covers optional startedAt
- list page: row renders, short health labels, filter placeholders, row
  click navigation, empty state
- detail page: card-name title, no redundant Alert badge, single Change
  owner action, sections, recipients, inline send-history runs, back
  link returns to the list

Supporting changes:
- BackLink is now a react-router Link (matches TaskRunDetailsPage), so
  the "back" action doesn't need a dispatch(push(...)) callback
- Ellipsified: use Mantine's maw shorthand instead of style={{maxWidth}}
- TextInput onChange: explicitly type the event to keep tsc happy
- Add createMockAdminNotificationListItem and admin endpoint mocks

* Drop trailing blank line in notification-admin api test

* Fix missing 'abandoned' in HEALTH_VALUES and clean review nits

HEALTH_VALUES dropped 'abandoned', so ?health=abandoned didn't survive
the use-url-state mount-time reserialize — UI let you pick it but the
filter silently evaporated on reload or share. Use 'as const satisfies'
so future mismatches between the literal list and NotificationHealth
are a compile error.

Also: Mantine style props in place of inline flex styles in InfoRow,
drop the redundant 'skip'-guarded arg in ChangeOwnerModal's user query,
and drop the redundant ChangeEvent annotation on the email input.

* Filter recipient_email in SQL; drop raw-value scan and IN splice

The previous implementation read every raw-value notification_recipient
into memory, matched details.value in Clojure, then spliced the matching
notification ids into the outer query as IN (...). That scales poorly
and risks hitting bind-param caps on large instances.

Replace it with an EXISTS correlated on notification.id that joins
notification_handler + notification_recipient + core_user in SQL. The
filter now matches only user recipients by core_user.email; raw-value
(external) recipients are intentionally out of scope — their email
lives inside a JSON column and narrowing it portably would require
either a LIKE on the serialized text or a per-DB JSON operator, neither
of which is worth the abstraction for this one filter. Admins can find
external recipients via channel filters.

* Resolve handler/recipient tables via t2/table-name

Satisfies the :model-imports declaration in modules/config.edn — the
linter sees the :model/NotificationHandler and :model/NotificationRecipient
keywords referenced in source, and the table names stay in sync with the
model defs instead of being duplicated as raw keywords.

* Publish notification-update event on admin bulk actions

Extract publish-notification-update! in the notification API so the
admin bulk endpoint and the self-service PUT endpoint share the same
post-update side effects: recipient emails on :active transitions and
an :event/notification-update audit entry per notification. Without
this the superuser bulk archive / unarchive / change-owner path left
no audit trail.

* Address review feedback on notifications admin PR

* Rename status→active and health→status; add sort and raw-value recipient match

The new admin design surfaces the computed health values as the user-facing
"Status" column, so rename the API/response field accordingly and free the
old `?status=` enum to become a plain `?active=` boolean. Extend
`recipient-email-exists` to match raw-value (external) recipients via a
portable LIKE on the JSON-encoded `details` column — the previous
helper deliberately skipped them. Add `?sort_column` + `?sort_direction`
(malli-enum whitelist), restructure the channel filter as an EXISTS
subquery so we can drop SELECT DISTINCT and sort by any expression, and
fix typo'd `metabase/utils/urls`/`metabase/utils/redux` imports that were
blocking unit tests.

* Match raw-value recipient emails in Clojure, not via JSON-text LIKE

Replace the `recipient-email-exists` helper (which cast `notification_recipient.details`
to text and substring-LIKE-d on the JSON serialization) with a two-path lookup:
- user recipients matched in SQL via indexed `core_user.email`
- raw-value recipients loaded into memory and matched with a Clojure equality
  check on the deserialized `:details.value`

Bounded by the raw-value recipient count, which is admin-search-cadence small
in practice. Removes the dialect-specific cast and the substring false-positive
surface; main query becomes a clean `WHERE notification.id IN (…)`.

* Simplify recipient-email lookup and url-state parsers

- Use metabase.util/lower-case-en (locale-safe) instead of clojure.string/lower-case
- Fold the three-query recipient-email resolution to two: drop handler-ids-with-user-email
  (folded into the final notification-id select) and the separate handler→notification-id
  resolution step
- Drop dead (or … #{}) wrappers around t2/select-fn-set (already returns #{})
- Replace the #{-1} sentinel for empty-handler-set with [:= 1 0]
- Project only :notification_handler_id + :details in the raw-value scan
- Collapse four near-identical parse* enum helpers into one parseEnum<T>
- Extract serializeActive helper instead of nested ternaries inline

* Add ?query= fuzzy substring search

Substring ILIKE OR'd across card name, creator first/last/email, user-recipient
email (correlated EXISTS), and raw-value-recipient email (pre-resolved handler IDs
from the existing in-memory scan, parameterised over a predicate so equality and
substring callers share the helper).

Param name and shape mirror the convention from /api/user (?query=) and
/api/card/:id/series — substring %lower.col% LIKE with u/lower-case-en on input.
?q= remains reserved for the search-index-backed engine.

* Test ?query= matches slack channel name on raw-value recipients

The in-memory raw-value scan never gated on channel_type — it matches details.value
across email, slack, and webhook handlers alike. Add a slack-channel test pinning
that behaviour so a future channel_type filter on the scan can't silently shrink
search coverage. Also tighten handler-ids-with-raw-value-matching's docstring to
spell out the per-channel value shape.

* GDGT-2305 edit

* Reshape notification-admin response for the new design iteration

- Replace `:status` enum + `:last_sent_at` timestamp with `:last_check`
  and `:last_sent` run-summaries `{at, error, status}`. `:last_check` is
  the latest terminal task_run; `:last_sent` is the latest successful
  delivery. Both pull `error` text from task_history's `:message` via a
  one-shot post-page query, no JSON SQL.
- Drop the `?status=` filter and the `?query=` recipient branches; recipients
  stay as the structured `?recipient_email=` filter.
- Add `?last_sent_status=failing|successful` (latest run outcome) and
  `?owner_active=true|false` (owner is_active).
- Rename the API surface `creator_id` -> `owner_id`, `creator_name` sort key
  -> `owner_name`, hydrated `:creator` -> `:owner`. The DB column
  `notification.creator_id` and internal hydrate stay; the rename is at the
  response/request boundary only.
- Replace `:status`-driven and recipient-fuzzy tests with new run-summary
  shape tests and a non-match assertion for ?query=. Use `=?` to keep them
  short.

* Splice owner.is_active onto the admin response

The hydrated :owner (formerly :creator) map is missing :is_active
because metabase.users.models.user/default-user-columns omits it. Project
core_user.is_active from the existing JOIN and merge it onto the owner
map so the FE can render the deactivated-owner icon.

* GDGT-2305 edit

* GDGT-2305 edit

* GDGT-2305 edit

* GDGT-2305 edit

* GDGT-2305 edit

* GDGT-2305 edit

* GDGT-2305 edit

* GDGT-2305 edit

* GDGT-2305 edit

* GDGT-2305 edit

* GDGT-2305 edit

* GDGT-2305 edit

* GDGT-2305 fix sorting

* GDGT-2305 add edit question alert modal

* GDGT-2305 add edit question alert modal

* GDGT-2305 add a copy link button

* GDGT-2305 coloring

* GDGT-2305 rename archive to the delete, remove undelete

* GDGT-2305 remove undelete tests

* remove icon temporary

* remove icon temporary

* restore the icon

* edit

* fix a blinking checkbox

* fix column's name

* small spacing adjustments

* render tabs conditionally based on the whole set, not only the first page

* clean up

* clean up

* clean up

* rollback

* rollback comment regions removing

* added the UserPicker

* remove tests, better write them from scratch

* fix z indices

* inline helpers

* fix stupid lines

* Align notifications-admin API with the alerts management design

- Add ownerless and multi-value channel filters
- Add id/last_check sort columns; default sort to last_send
- last_send now reflects actual channel-send delivery attempts
- Detail endpoint returns per-notification check_history and send_history
  (send entries roll up all channels of a tick)
- Allow superusers to reassign the owner via PUT /api/notification/:id

* Drop the unused bulk unarchive action

The alerts management UI has no restore affordance — "Delete" is a soft
archive with no un-delete — so the bulk unarchive action had no caller.

* apply BE changes

* apply BE changes

* fixes

* fixes

* fixes

* fixes

* Fix CI failures on notifications-admin

- Remove duplicate getTasksRoutes import in admin/routes.tsx (fixes
  fe-type-check, verify-i18n, and the build break)
- Add is_active to createMockUserInfo (UserInfo now requires it)
- Declare :model/TaskHistory in task-history :model-exports and
  enterprise/notification-admin :model-imports (fixes model-boundaries-test)
- Mock GET /api/user in CreateOrEditQuestionAlertModal spec — the new
  NotificationOwner UserPicker fetches users
- cljfmt-format notification_admin api.clj and api_test.clj

* Use creator (not owner) on the notifications-admin API surface

The /ee/notifications endpoints exposed creator_id/creator as owner_id/owner,
diverging from the public /api/notification endpoints which use creator. FE
feedback flagged the inconsistency. Keep creator end-to-end on the wire
(query params, response keys, sort column, and the change-creator bulk action)
to match the public API; owner stays a frontend-only term, translated at the
RTK Query boundary in api/notification.ts.

* Simplify FE: use creator in the data layer, Owner only as a label

Drops the owner<->creator translation layer added at the API-client boundary
(wire types, converters, transformResponse, param/bulk mappers, mock wire
conversion). The admin FE now uses creator_id/creator/creator_active/
creatorless/creator_name and the change-creator action directly, matching the
wire. "Owner" survives only as UI labels, the Ownerless tab, and component
names (ChangeOwnerModal, NotificationOwner). The ?creatorless= URL param
replaces ?ownerless=. NotificationOwner no longer needs an AdminNotification
type guard since both notification shapes now expose creator_id/creator.

* small changes

* addressing the PR's comments

* addressing the PR's comments

* Address review comments on notifications-admin

- creator_id (owner) reassignment is now gated to a single blessed path:
  add `*allow-creator-id-change?*` + `reassigning-creator` to the model and
  have the admin bulk endpoint bind it. The model before-update rejects any
  other creator_id change (incl. unauthenticated/system and superuser-via-PUT).
- public PUT /api/notification/:id rejects creator_id changes with a 400 (was
  a silent strip); echoing back the unchanged value still works.
- escape %/_/\ in the ?query= LIKE wildcard
- error-by-run-id includes abandoned runs and picks the latest row per run via
  SQL ROW_NUMBER instead of an in-memory reduce
- has_failure: boolean CASE read back through bit->boolean (drops the dialect
  cast); list-where-clauses extracted + reduced onto the query
- handler-ids lookup uses reducible-select; guard empty ids in bulk-update!
- exclude orphaned card notifications (payload_id IS NULL) from the list

* Fix cljfmt indentation in notification models_test

* Improve the code and UserPicker UX

* addressed channels column's width if there are either three channels or the count is large

* fix magic numbers for avatar

* fix NotificationRunSummary rendering

* fix the slack icon background when it's dark theme here

* close the details sidebar if the notification is removed/archived

* clear adminNotification tags after editing a notification using a single `updateNotification` action

* invalidate admin notification tags when a new notification is created

* add unit testing

* Simplify creator_id reassignment to superuser-only PUT

Walk back the dynamic-var-gated "only the admin bulk endpoint can change
creator_id" path. The design needs the edit modal to change ownership,
which goes through PUT /api/notification/:id — bronsa's review feedback
was about privilege escalation, not single-path enforcement, and is fully
addressed by superuser gating.

- model `before-update` rejects creator_id changes unless `(mi/superuser?)`;
  unauthenticated/system writes fall through and get rejected too
- public PUT accepts creator_id (via the spec's `:compare-cols`); non-superuser
  attempts get 403 from `mi/can-update?`, model is the backstop
- drop `*allow-creator-id-change?*`/`reassigning-creator` from the model
- drop the `reassigning-creator` wrap from the admin bulk endpoint
- tests: bulk-update via `:id [:in …]` triggers before-update; cover
  superuser-can-reassign and non-superuser-403 from the public PUT

* Notifications admin detail endpoint: surface failing ticks and stream rows

The detail endpoint silently dropped failing ticks from check_history and
send_history, so last_check / last_send came back nil for notifications the
list endpoint correctly marked as failing.

Root cause: `metabase.task_history/do-with-task-history` wraps the caller's
task_details on exception as `{:status :failed :message … :original-info <orig>}`,
so on failure the caller's `notification_id` / `channel_type` move under
`:original-info`. The per-notification filter only looked at the top level.

- `task-details-key` helper checks both shapes; applied to the per-notification
  filter (`matches-notification?`) and `->channel-entry`'s channel_type lookup
- `error-by-run-id` no longer filters by task; an ORDER-BY tiebreaker prefers
  the outer `notification-send` error and falls back to the latest by `ended_at`
  so a channel-only failure still surfaces its error string in `last_check`
- `task-history-rows-for-card` returns a reducible; helpers use
  `(take result-limit)` in the transducer so the JDBC cursor short-circuits
  once we've collected enough matches — common case (one notification per card)
  fetches ~10 rows instead of 500
- realise rows inside the transducer before the reducible closes
- regression tests: failure-wrapped task_details, channel-only failure error
  surfacing on the list endpoint, and outer-error preference on the tiebreaker

* Drop blank lines inside cond in sqlserver to satisfy cljfmt :remove-blank-lines-in-forms?

* make UserPicker UX even better + tests for it

* distinct ownerless and creator_active filters

* Notifications admin list endpoint: populate last_send.error

last_send.error was hardcoded nil at the list level — the Failing tab tooltip
had nowhere to read the channel-send error message from, even though the
notification's status correctly showed :failing.

- expose `lr.run_id` from latest-send-tick-per-card as `:ls_id`
- decorate-runs collects failed ls_ids and looks them up via
  `error-by-run-id task-channel-send …`
- error-by-run-id takes a `task-name` arg now: when non-nil, restricts the
  windowed lookup to that task (last_send wants channel-send specifically);
  when nil, keeps the tiebreaker (last_check, check_history)
- regression test: list endpoint last_send.error returns the channel-send
  task_details.message when the latest send-tick failed

* Simplify error-by-run-id ORDER BY + detail endpoint hydration

- error-by-run-id: always use CASE+ended_at as the partition ORDER BY; the
  CASE is a no-op when task-name restricts the WHERE to one task, so the
  conditional branch on task-name dropped.
- get-notification-detail: drop the decorate-runs call. base-list-query with
  `:skip-run-joins?` doesn't project lc_*/ls_* columns, so decorate-runs was
  a no-op pass (assoc'd nil into last_check/last_send which we overwrite
  immediately from the per-notification histories).

* removed (deactivated) label

* request users of any status in the notification's owner select

* small ux fixes

* Notifications admin include today (#74963)

* add includeToday param

* add Today toggle to the TaskRunDatePicker

* chores

* try to keep selected entity id and type if we are changing only includeToday

* add the tests

* addressing the PR's comments

* fix console error

* fix e2e tests due to TaskRunPicker changes

---------

Co-authored-by: Egor Grushin <egor@metabase.com>
2026-05-29 21:37:12 +01:00
Romeo Van Snick
b6fe71475d Fix deletion of tenant collections (#74536)
* Fix typo

* Make notifying with toast optional in useDeleteItem

* Don't hide unsuccesful bulk archives

* Add repro for 74461

* Fix wording
2026-05-30 06:33:10 +10:00
Romeo Van Snick
41d9fa501d Harden tests against XHR vs fetch timing differences (#74897)
* Fix flakes in cache test

* Fix flake in admin remote-sync test

* Fix snippet flake

* Fix geojson e2e test

* Return content type in server mocks

* Return content type in server mocks

* Fix unit test

* Address review: backwards-compatible lastReqBody, drop redundant within

lastReqBody (and the inline copy in AIQuestionAnalysisButton) assumed the
client calls `fetch(new Request(url, init))` and read the body via
`request.clone().text()`. On master/this branch the client still calls
`fetch(url, init)`, so the first arg is a URL string and `.clone()` throws —
breaking every consumer (history/context/errors/use-metabot + the button
spec). Read both shapes so it's actually backwards-compatible, and route the
button spec through the shared `lastReqBody` to drop the duplicate.

Also collapse the single-element `H.modal().within()` in remote-sync to a
simple chain.

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-05-30 06:33:01 +10:00
Eric Normand
94f3c633ce GHY-3266 cancel slow data-warehouse queries via *canceled-chan* timer (#74776)
* GHY-3266 cancel slow data-warehouse queries when *query-timeout-ms* elapses

Statement.setQueryTimeout (added in #74xxx) handles the per-driver path,
but some drivers don't reliably issue a server-side cancel — most
notably the MariaDB connector for MySQL, where the c3p0
unreturnedConnectionTimeout closes the JDBC connection without sending
KILL QUERY, leaving the slow query running on the server. The
fingerprint sync then retries the same view every cycle, accumulating
runaway queries.

This adds a cross-driver backstop: do-with-canceled-chan now schedules a
go-block that puts ::timeout on *canceled-chan* after *query-timeout-ms*.
The existing wire-up-canceled-chan-to-cancel-Statement! then calls
Statement.cancel(), which for MariaDB issues KILL QUERY over a side
connection. Works for any driver with a working .cancel() impl, not just
JDBC.

* Don't consume from *canceled-chan* in the timeout-cancel timer

The first version of schedule-query-timeout-cancel! used
`(alts! [canceled-chan timeout-ch])` so the go-block would early-exit
when the query completed. That broke mongo's
kill-an-in-flight-query-test: the test binds `*canceled-chan*` to a
regular `(a/chan)` (not a promise-chan) and puts a cancel sentinel on
it; the driver listener takes from the chan to abort the in-flight
query. On a regular chan, `alts!` consumes the value, so the timer
go-block raced the driver listener and ate the cancel signal — the
mongo cursor was never aborted.

Replace the read on `*canceled-chan*` with a dedicated `done-ch` we
own. `do-with-canceled-chan` closes it in a `finally`, so the go-block
still exits promptly on completion. The timer never reads from the
caller-supplied channel — it only puts `::timeout` to it after the
timeout elapses, which is safe for both promise-chan and regular chan
callers.

Regression test added.

* Address review feedback on canceled-chan timer

- setup.clj: signal the timer via put! on done-ch rather than close!, so
  the intent ("the query is done") reads more naturally than
  close-as-signal on a promise-chan. Use identical? for the port check.

- setup_test.clj: simplify a deliberately-clever 300ms wait pattern to a
  plain Thread/sleep + deliver. Bound the @taken deref with a 2s
  timeout sentinel so a regression in the timer can't hang CI.

- mysql_test.clj: add a driver test that demonstrates end-to-end
  cancellation against MySQL — bind *query-timeout-ms* to 2s, run
  SELECT SLEEP(60), assert the query throws and completes far short of
  the natural 60s. Timing is the load-bearing assertion; the QP's
  output-schema middleware wraps the underlying SQLException so we
  don't pattern-match on the exception message.

* Refactor
2026-05-29 19:30:10 +00:00
Nemanja Glumac
fb4d33bb38 Fix auto-release rewinding to an older commit (#74768)
The auto-release flow could cut a higher version number from an older commit than the previous release. The fix is a single-function body change in hasCommitBeenReleased. Compare the last release tag's commit to the release branch tip and check membership of the candidate in the returned commits list.

The membership-against-branch-tip framing is deliberate: it enforces "release tags only come from release-x.NN.x" by construction. A candidate that's ahead of lastTagSha but not on the release branch is correctly rejected by the gate.
2026-05-29 11:51:17 -06:00
Timothy S. Dean
680c6ec1a0 Lock config-managed workspaces against runtime edits (#74929)
When a Metabase instance loads its workspace from `config.yml` at boot, that workspace is meant to be managed by the deployment config, not edited at runtime. Nothing stops an admin today from overwriting the config through the workspace-instance API. This leaves the instance state out of sync with the config file that would load on the next restart.

My approach was to treat a workspace as read-only when it's set at boot. This could be a `:workspace` section in `config.yml` or an `MB_INSTANCE_WORKSPACE` env var.

- `workspace-locked-by-config?` is true when the boot process loaded a workspace or the env var is set. The current lock state is not persisted.
- `/api/ee/workspace-instance/current` rejects `POST` and `DELETE` when the workspace is locked. `GET` returns `can_write`.

If you legitimately want to move from locked to unlocked, then remove your boot-time config, restart the instance, and then you can proceed to use the admin API calls.
2026-05-29 11:35:22 -06:00
Ben Grabow
51df60fa51 Add --attempt option to mage ci-report (#74975)
* Add --attempt option

* Support negative relative attempt index
2026-05-29 16:17:32 +00:00
Stas Gavrylov
0b10c75bdb GDGT-1582: Schema Viewer (Entity Relationship Diagram) (#71351)
* GDGT-1582: Add ERD endpoint

* GDGT-1582: First iteration of ERD

* GDGT-1582: Add e2e tests for ERD feature

* GDGT-1582: Fix lint errors

* GDGT-1582: Update backend to support models' ERD

* GDGT-1582: Add search picker. Add models support

* GDGT-1582: Update e2e tests

* wip

* GDGT-1582: Make db type always lowercase

* Add marching ants animation for edges

* Add table icon colors to nodes

* Add Search Input

* Improve entity picking behavior

* GDGT-1582: Add fields sorting

* GDGT-1582: Remove outdated ERD link

* Update schema viewer button icon

* Fix e2e tests

* Replace ERD abbreviature with SchemaViewer

* Refactoring

* Reorganize code

* Update Schema Viewer to support schema picker UI

* Rebuild table picker. Add hops input

* GDGT-1582: Fix tables list fetching

* GDGT-1582: Adjust selectors styling

* GDGT-1582: Fix hops handling on the BE, improve error message output

* GDGD-1582: Add support for expanding FK fields

* GDGT-1582: Add placeholder for table input when no tables are selected

* GDGT-1582: Adjust styling for Hops input

* GDGT-1582: Add schema viewing persistence

* GDGT-1582: Add share link to schema viewer

* GDGT-1582: update e2e tests

* GDGT-1582: Extend /erd to support foreign schema tables

* Update schema viewer icon to network

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

* Fix table ids caching

* GDGT-1582: Adjust border styling

* GDGT-1582: Replace number input for hops with a slider

* GDGT-1582: Implement cardinality labels for edges

* GDGT-1582: Refactor

* GDGT-1582: Add table details link and warning on selecting all tables

* GDGT-1582: Improve table selector UX

- Sort visible (but not selected) tables below selected tables
- Add fixed height to list items to prevent layout shift
- Keep dropdown open when canceling select all confirmation
- Close dropdown when confirming select all

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

* GDGT-1582: Add collapse/expand and double-click focus to table nodes

- Add collapse/expand button for nodes with more than 10 fields
- Shows first 5 fields when collapsed
- Double-click node to focus/zoom to it
- Double-click again to zoom out to fit all nodes

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

* Remove unused active-fields-for-table function

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

* REVERTME: Ignore DB deletion to alow staging environment to work

* REVERTME: Fix kondo warning

* GDGT-1582: Update styling of edges and cardinality marks.

* GDGT-1582: Add zoomed-out mode for schema viewer

* GDGT-1582: Add tooltip to compact nodes showing connected tables

Shows table name and list of connected tables with direction/cardinality icons.

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

* GDGT-1582: Show 20 fields by default and add field count to tooltip

- Change default collapsed field count from 5 to 20
- Start table nodes collapsed by default
- Add field count text under table name in compact mode tooltip

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

* GDGT-1582: Add zoom-to-table on FK field click

When clicking on a foreign key field whose target table is already
visible on the canvas, zoom to that table instead of doing nothing.

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

* GDGT-1582: Fix table selector dropdown close on outside click

Use capturing mousedown listener to close dropdown before ReactFlow
intercepts the event.

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

* GDGT-1582: Update nodes positioning logic to rearrange in compact view

* GDGT-1582: Improve field zoom transition

* GDGT-1582: Fix positioning inconcistency

* GDGT-1582: Fix tooltip not showing on bottom nodes

* GDGT-1582: Add compact mode toggle button

* GDGT-1582: Update zooming logic

* GDGT-1582: Move button to expand all node fields

* GDGT-1582: Address feedback

* GDGT-1582: Update tests

* GDGT-1582: Update compact mode initialization logic. Remove node collapsing logic

* GDGT-1582: Fix the bug with incorrect number of selected tables displayed

* GDGT-1582: Fix nodes positioning flash

* GDGT-1582: Add AppSwitcher to Schema Viewer route

* GDGT-1582: Implement saving of last selected database to user preferences

* GDGT-1582: Fix table selector bugs. Expose table names

* fix test

* GDGT-1582: Add proper handling for empty schema names

* GDGT-1582: Fix table picker list items width

* Rewrite ERD endpoint: unified pipeline + lazy BFS (#70580)

* Fix nodes rendering on hops change

* GDGT-1582: Addressing design feedback

* wip

* Minor styling fixes

* wip

* Fix eslint

* Fix hops to allow unwrapping FK fields

* fixes

* Fix fk field focus

* Update Node search input

* Implement focus node menu

* Adjust styling

* Add node selection popup

* wip

* Add ?include=schemas param to /database. Remove unit tests

* Add db and schema display in popup. Fix fields list scroll

* Remove old proxy middleware

* Fix CI

* Update table nodes design

* Make search input clear on focus

* Adjust styling. Remove context menu. Add focus node button

* Cleanup

* Add spinner while external FK table is loading

* Cleanup. Fix stuck schem picker when DB is missing

* Update table fields design

* Add Upsell page for Schema Viewer

* SchemaViewer refactoring

* Reorganize code in folders

* More refactoring

* Simplify ERD backend expansion

* Consolidate/delete schema viewer hooks

* More refactoring. Delay /erd fetch until last preferences are restored

* More code reorganization

* Optimize node layout algorithms with caching and better positioning strategies

* Hooks refactoring. Fix stale prefs value

* Refactor zoom logic. Replace FitToCanvas and FitToNewNodes with reducer

* Refactor edges selection. Cleanup

* Optimize nodes rendering

* Optimize viewport zoom logic

* Extract applyLayout functionality

* Update focus node positioning algorithm

* Add minimap nodes shading via SchemaViewerMinimap component

* Move SchemaViewer out of dependencies feature

* Optimize layout functions

* Unit tests for layout functions

* Fix Urls import path

* Add Schema Viewer Upsell page graphics

* E2E and unit tests for Schema Viewer

* Fix table node border color

* Add dark mode support for Minimap

* Replace :dependencies feature token usage with proper :schema-viewer token. Minor tests refactoring

* Further cleanup

* Rename erd.core to erd.impl

core.clj is reserved for Potemkin re-exports of a module's external surface;
this module has no external consumers, so the implementation lives in impl.clj.

* wip

* Replace edges selection z-index setting with CSS solution. More cleanup

* Comments cleanup

* Extract GraphInfoPanel. Fix focus field zoom. Add schema to external table names

* Fix formatting

* Fix cljfmt

* Adjust height of Node panel popup. Remove focus node disabling logic.

* Fix schema selection input closing on outside click

* Register :schema-viewer feature in stats and token-features

Fix backend CI failures:
- Move enterprise/erd block to correct alphabetical position in module
  config and drop non-existent erd.core from :api set
- Add :schema-viewer to snowplow features data
- Add :schema-viewer to expected token-features map in session test

* Address ERD impl.clj review nits

- Make build-erd-field/node/edges/response private (only used in impl.clj)
- Rename readable-tables binding to readable-target-table-ids (it holds IDs)
- Use positional docstring for table-perm-columns instead of ^{:doc}

* GDGT-1582: Addressing review comments

* Extend useUserKeyValue typings to properly infer result value

* GDGT-1582: Addressing review comments

* GDGT-1582: Make table details redirect to Schema Viewer zoom on table

* GDGT-1582: Fix ref fields misalignment in InfoPanelField

* GDGT-1582: Resolve e2e tests comments

* GDGT-1582: Add table description and owner information to table nodes

* GDGT-1582: Rewrite SchemaPickerInput to use Minipicker. Extend MiniPicker to support schema browsing

* GDGT-1582: Cleanup hooks

* GDGT-1582: Update input focus hotkey to 'f'

* GDGT-1582: Replace display_name with name in InfoPanel title

* GDGT-1582: Refactor zoomToNodes

* GDGT-1582: Cleanup flow-graph util

* GDGT-1582: Refactor layout util by splitting to multiple files and introducing PlacementCanvas abstraction

* GDGT-1582: Fix e2e tests

* Fix TS errors

* GDGT-1582: Fix hotkey unit test

* Fix cljfmt

* GDGT-1582: Resolve PR comments

* GDGT-1582: Enable hidden and sensitive fields on /erd

* GDGT-1582: Refactor SchemaViewerEdge + update styling.

* GDGT-1582: Revert extracting GraphInfoPanel to shared. Create own components for Schema Viewer

* GDGT-1582: Make /erd return all fields

* GDGT-1582: Refactor selectedFieldIds computation logic. Cleanup

* GDGT-1582: Fix schema viewer staleness when table metadata is updated

* GDGT-1582: Cleanup

* GDGT-1582: Use lib in flow-graph utils

* GDGT-1582: Replace display_name with name if popup fields

* GDGT-1582: Refactor unit testing mocks

* GDGT-1582: Comments cleanup

* GDGT-1582: Fix fields wrapping in table node info popup

* GDGT-1582: Minor UI fixes. Fix e2e

* GDGT-1582: Fix BE test. Fix field name overflow

---------

Co-authored-by: Claude Opus 4.5 <noreply@anthropic.com>
Co-authored-by: Nicolò Maria Mezzopera <nicolo.mezzopera@metabase.com>
Co-authored-by: Ngoc Khuat <qn.khuat@gmail.com>
2026-05-29 15:46:26 +00:00
Alexander Polyankin
e50a365f3f Fix pivot setting comparison when migrating from refs (#74972)
* Fix pivot setting comparison when migrating from refs

* fix

* fix
2026-05-29 15:11:47 +00:00
Timothy S. Dean
dc017f71a7 Don't email admin users who haven't accepted invite (#74883)
If someone has been invited as an admin to a Metabase instance, but has not yet accepted that invitation, that person should not get spammed with admin notification emails.

`last_login` = `nil` is our canonical mechanism for determining that a user has not yet accepted an invitation. Acquiring emails for admins should ensure this field is not `nil`.
2026-05-29 08:27:29 -06:00
Romeo Van Snick
c3f9cac18f Return 204 No Content from CSV append/replace endpoints (#74945)
* Return 204 No Content from CSV append/replace endpoints

The `update-csv!` helper hand-rolled a `{:status 200 :body nil}`
response map, which slips through the `wrap-response-if-needed` middleware
(see metabase.api.common.internal): the protocol only rewrites a returned
`nil` to a 204 — a map that already carries `:status` and `:body` is
passed through unchanged. The result was the only FE-facing endpoint in
the codebase that returned a 200 with a literally empty body, which an
HTTP client has to special-case (empty body but a JSON content-type means
`response.json()` throws).

Switch to the existing `api/generic-204-no-content` helper so the
response semantically matches what it always was — a side-effecting
operation with nothing meaningful to return — and so a future move to
`response.json()` in the FE client doesn't have to carry an
empty-body-200 special case.

The FE callers (`appendTableCsv` and `replaceTableCsv` in
frontend/src/metabase/api/table.ts) are typed `void` and the consumer in
frontend/src/metabase/redux/uploads.ts uses `response || modelId`, so
neither the old `null` body nor the new empty 204 changes observable
behavior.

* Fix pre-existing cljfmt violation in transforms timeout_test

CI runs `cljfmt-all --force-check` over every Clojure file, and
test/metabase/transforms/timeout_test.clj currently has blank lines
inside nested `testing` forms that cljfmt rejects. The violation lives
on master, so it fails the Cljfmt check for every open PR (this one
included). Apply the mechanical reformat so this branch's Cljfmt job
can pass.

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-05-29 22:01:02 +10:00
Romeo Van Snick
54a770c486 Return empty body as null instead of the empty string (#74895)
* Return empty body as null instead of the empty string

When the BE responded with no body (e.g. `204 No Content`), the legacy
API client surfaced the missing body as the empty string `""`. Callers
then had to disambiguate "I got an empty string back" from "I got the
parsed JSON value that happens to be the empty string", which forced
per-endpoint `transformResponse` workarounds.

Surface empty bodies as `null` instead — the natural "no value" sentinel
in JS, and what RTK Query callers tend to type their response shapes
with already.

Client change:
- Both transport paths (XHR + fetch) coerce an empty body text to `null`
  before any JSON-parse attempt (skipping the parse for empty bodies
  rather than letting it throw and swallow).

Consumer changes (the only two places affected by the new shape):
- `groupTableAccessPolicyApi.getGroupTableAccessPolicy` drops its
  `transformResponse(response: GroupTableAccessPolicy | "" | null)`
  workaround that was coalescing `""` → `null`. The endpoint already
  typed its return as `GroupTableAccessPolicy | null`; the new client
  behaviour just hands it that shape directly.
- `useUserKeyValue` no longer relies on the `""` falsy-ness to fall
  through to `defaultValue` — `null` would `??`-coalesce correctly here
  too, but the comment is updated. The downstream consumer that did
  break is `UserHasSeen`: it had a `useUserAcknowledgement(id, true)`
  default of `true` because the old `""` empty body looked acknowledged
  *and* loading looked acknowledged *and* unacknowledged-key looked
  acknowledged. With the new `null` shape, switch the default to
  `false` and gate on `isLoading || acked` so a previously-dismissed
  banner does not flash before the real state is known. Adds a unit
  test covering the freshly-installed-user case (`null` response).

* Add unit coverage for empty-body → null

Lock in the new behaviour so a future change cannot silently restore
the empty-string return value. Three new specs against the fetch
transport (which is what Jest uses via `isTest`):

- An empty 204 body resolves to `null`.
- An empty 200 body resolves to `null` (not just 204 — any empty body).
- A non-empty JSON body still parses to its decoded value, so the
  empty-text short-circuit does not regress the happy path.

The XHR path mirrors the same `responseText === ""` check; co-locating
both transports under one mock would require a dedicated XHR fake which
this spec does not currently set up. The fetch-path coverage is what
ships in production for any caller running through the test suite.

* Fix unit test
2026-05-29 21:52:42 +10:00
github-automation-metabase
3ca8008471 Auto-update documentation for master (#74942)
Update generated docs (master)

Co-authored-by: github-actions <github-actions@github.com>
2026-05-29 07:47:37 -04:00
Romeo Van Snick
2ed4929758 Remove entity framework 🎈 (#74896)
* Move entityCompatibleQuery to metabase/api/utils/entity-compatible-query.ts

* Move entityTypeForObject / entityTypeForModel into metabase/redux/store/entities

* Move UseQuery rtk type to metabase/api/types

* Wire entity slice reducers directly in metabase/redux/entities

* Drop enhanceRequestsReducer wrapper

* Delete the entity framework

* Rename entityCompatibleQuery to runRtkEndpoint

* Remove dead _list index signature from EntitiesState

* Rename hydrateLegacyEntities to hydrateMetadataStore

* Add tests for new reducer

* Fix comment

* Remove unused Metadata methods

* Fix lint
2026-05-29 20:52:50 +10:00
Chris Truter
d587fb7ffe Boost library-collection items in search ranking (#74806)
* Boost library-collection items in search ranking

- Add :library scorer to the semantic engine (was appdb-only); extract the
  shared expression into metabase.search.scoring/library-score-expr so both
  engines use one implementation.
- Add root_collection_type column to the semantic index schema + ingestion
  path, with a corresponding dynamic-schema migration (v4) to alter existing
  index tables. Existing rows are NULL until re-ingested.
- Rebalance default weights: :library 200 in :default (was unset; only set
  under :metabot at 100); drop the :metabot :library override so it inherits
  the default. 200 comfortably outranks :official-collection 80 + :verified
  80 without dominating all other scorers.

* Bring :data-layer scorer over to semantic and DRY the helpers

- Extract data-layer-score-expr into metabase.search.scoring alongside
  library-score-expr so both engines share one implementation. Refactor
  appdb base-scorers to call the helper.
- Wire :data-layer into semantic base-scorers using the helper (column
  was already in the schema/ingestion from the previous commit).
- Add semantic data-layer-test mirroring the appdb version's per-tier
  weight checks.
- Migration 3 docstring: correct attribution — :library reads
  root_collection_type (added in migration 4), not collection_type.

* Lift curation-tier weights to :default and backfill root_collection_type

- Move :official-collection 80, :verified 80, and the :data-layer per-tier
  weights from :metabot up to :default. Library at 200 stays the dominant
  tier. The :metabot block was the only consumer of these magnitudes, so
  with them lifted the block is empty and removed.
- Extend migration 4 with an in-place backfill: pull root_collection_type
  from the gate's stored document JSON when present, else use the row's
  own collection_type if it's already a library root type. Nested items
  without a refreshed gate doc remain NULL until natural re-ingestion.
- Update metabot-weights-test to assert the new contract (:metabot
  inherits :default verbatim, no overrides).

* Document migration-4 backfill assumptions

Spell out why the `collection_type IN (library...)` fallback is sufficient
today (library-typed collections can't have sub-collections, so any row
with that direct-parent type is at the root) and flag what would need to
change if that ever becomes false. Also note that only the library root
types matter for the fallback — other root types stay NULL because the
`:library` scorer doesn't care about them.

* Drop metabot-weights-test now that :metabot inherits :default with no overrides

* Trim scoring helpers and tighten library-test predicate

- Drop the column-reference parameter from library-score-expr and
  data-layer-score-expr — both columns are unambiguous in every scorer
  subquery, so callers don't need to thread engine-specific qualifiers.
- DRY data-layer-score-expr's per-tier rows via a data-layer-tiers vec
  and a small tier-clauses helper.
- Use a distinctive 'lib-tree' token in the appdb library-test row names
  and check via str/includes?, so the predicate reads off the result
  instead of relying on hand-counted ids or a too-short 'lib' prefix.

* Factor data-layer magnitude up, mirror semantic library-test predicate

- Lift the data-layer magnitude into the top-level :data-layer weight (33)
  and reduce per-tier weights to pure ratios (1 / 0.3 / 0.03). Final tier
  contribution stays at 33, so the magnitude now sits naturally alongside
  :library 200, :official-collection 80, :verified 80 in the config.
- Rewrite data-layer-score-expr as a literal :case vector with a small
  tier-weight closure — clearer than the previous into/concat/mapcat chain.
- Tighten the helper docstrings: caller contracts only, implementation
  rationale moved to inline ;; comments.
- Mirror the appdb library-test's `lib-tree` substring predicate in the
  semantic library-test, and add a tier-ordering case to the semantic
  data-layer-test to match the appdb pair-test for parity.
- Update the appdb data-layer-test tier-ordering case to use the new
  :default magnitudes (was the old :metabot magnitudes).

* Fix semantic data-layer-test tier-ordering case

The tier-ordering case was reading off the per-tier sub-tests' 4-row index,
which includes a "table no layer" row. That row matches the "table" query
(tsvector filter, score-independent), so the assertion would yield [2 3 4 1]
instead of [2 3 4]. Wrap the ordering case in its own 3-row index, mirroring
the appdb counterpart.

* Bump semantic index version to 4 and update affected migration tests

Three existing tests broke because they pinned the previous schema state:
- schema-version-match-default-version-test asserts default-index :version
  equals dynamic-schema-version (now 4) — bumped default-index to 4.
- expected-db-schema-after-migration-test enumerates the index table's
  columns — added :root_collection_type to the expected set.
- init-semantic-search!-test failed due to the version mismatch propagating
  through metadata; resolves once default-index :version matches.

Also drop a couple of unnecessary rationale comments from the appdb and
semantic library-test fixtures — the row data speaks for itself.

* Tidy library-test row alignment in appdb and semantic

* Add migration-4 backfill integration test

Covers the four backfill branches end-to-end against a real pgvector instance:
(1) gate document JSON carries root_collection_type — pulled from there;
(2) gate doc absent but collection_type IS a library root — pulled from
    collection_type; (3) neither — stays NULL; (4) row already populated —
    untouched. The test rolls metadata.index_version back to 3 to force
    migration 4 to re-run against pre-seeded rows.

Also rename the tier-ordering test fixtures from "production table" to
"foo table" — the word wasn't pulling its weight.

* Fix migration-4 backfill test: use mock embedding model and read keys

The test needs the 4-dim mock model in scope so the placeholder embedding
matches the index column dimensions — switch to :mode :mock-initialized.
That also redefines the index-metadata table names, so resolve gate/meta
table names dynamically instead of hardcoding. Read result rows via
as-unqualified-maps so model_id and root_collection_type are accessible
without knowing the dynamic table-name qualifier.

Verified by running against a local pgvector container — 24 tests / 60
assertions pass across scoring-test and migration-test.

* Drop dead with-redefs from migration-4-backfill-test

semantic.core/init! doesn't call semantic.pgvector-api/index-documents! —
the redef was a defensive no-op carried over from sibling tests. Drop it
on this code path since the index_table only ever contains the four rows
inserted by the test itself.

* Annotate data-layer per-tier ratios with effective products

* Sentence-per-line comments in config curation block

* Migration 4 backfill: switch correlated subquery to two set-based UPDATEs

Copilot flagged the per-row correlated subquery into the gate table as slow
on large indexes. Split into two set-based UPDATEs:
  1. UPDATE..FROM join against the gate table (gate-sourced backfill)
  2. UPDATE against collection_type (library-root fallback)

Behaviour-preserving — confirmed by re-running migration-4-backfill-test
against a local pgvector instance.

* Update official-collection-tests ordering for new :official-collection weight

The legacy in-place scoring test asserted [d c b a] for the EE case, relying
on :official-collection at weight 1 being small enough that text matches
still dominated. With the weight lifted to 80 in :default, an official item
now overpowers text matches — d (official) rises to the top.

Test name and intent ("should bump up the value of items in official
collections") is preserved; the assertion just reflects the stronger bump.
Verified: 16 assertions pass.

* Split official-collection-tests into two deftests

The CI kondo run flagged this as containing several logically separate
testing forms. The two testing blocks (official-collection bump vs
verified-items bump) are independent concerns and the split is a clear
readability win.

Renamed to be more specific and use the standard `-test` suffix.

* Drop dead index-documents! redef from migration-lock-coordination-test

The init! code path (init-semantic-search! + gate-updates!) never reaches
index-documents!, so stubbing it in migration-lock-coordination-test's
with-redefs-fn was dead — same as the sibling init!-only tests. Remove it,
keeping the load-bearing maybe-migrate!/write-successful-migration! redefs,
and drop the now-unused semantic.pgvector-api require.

* Clarify ascending-sort mechanics in official-collection comment

The comment said d 'rises to the top' but d appears last in the asserted
vector because sort-by is ascending (highest score last). Reword to make
the ascending-sort placement explicit and avoid a reader misreading it as
a contradiction.

* Revert :data-layer to :metabot-only; keep library/official/verified in :default

The :data-layer scorer is a *structural* signal — every visible warehouse table
has `data_layer "final"` set from `visibility_type`. With :data-layer in
:default, the +33 boost applied to every visible table flipped orderings across
every search surface (search bar, entity picker, document mentions, smart-link
suggestions, etc.) and broke a number of e2e specs that pin specific top results.

Move :data-layer back to :metabot-only with a TODO documenting how to bring it
across in the future (update the e2e snapshot fixture or relax the brittle
assertions). The user-curated tiers (:library, :official-collection, :verified)
stay in :default — they don't break anything because nothing in the snapshot is
flagged with them.

Updated the tier-ordering test labels in appdb and semantic scoring tests to
say ":metabot magnitudes" instead of ":default magnitudes". The tests themselves
use explicit weight overrides so they pass either way.

* Migration 4 backfill: walk Library tree from appdb instead of trusting collection_type

Library sub-collections shipped in #73179 and changed the assumption that every indexed row
with a library `collection_type` is at the root of its own tree. The old heuristic
(`SET root_collection_type = collection_type WHERE collection_type IN library-types`)
fills the column for sub-collections but with the wrong root — a card under
Library/Data/Sub-Data gets `library-data` instead of `library`.

Replace step 3 with an appdb lookup that builds `collection-id → root-collection-type`
for every Library-typed collection (root + sub) and applies one UPDATE per distinct
root type. Library content rules guarantee the whole forest is covered by selecting
collections where `:type` is one of the library types — sub-collections inherit the
parent's type, so a single appdb query catches every depth.

Gate-doc backfill (step 2) still runs first and takes precedence; the appdb walk only
fills rows the gate doc missed (e.g. gate rows written before the spec field existed).

Catch + log on the appdb query so test setups that exercise pgvector before the appdb
schema is up don't fail — production semantic-search init always runs after appdb migration.

Test now stands up library/library-data/nested library-data/library-metrics via
mt/with-temp and asserts every nested case resolves to "library" while a non-library
collection's row stays NULL.

* Migration 4 backfill: walk the Library forest from roots instead of parsing locations

Filter the appdb query by `:location "/"` so we get only the library-typed *root*
collections, then fetch each root's descendants via `:location [:like "/<id>/%"]`.
We know the type for every descendant directly from its root — no path parsing.

Slightly more queries (1 + N for N roots, typically 1–3), but the code is straightforward
and stops conflating "the row is a library type" with "the row is the root of its tree".

* Tighten migration-4 docstrings; relocate implementer notes to inline comments

* Use u/for-map for the Library-forest mapping

* Trim diary comments in migration 4

* Whitespace from outer space
2026-05-29 06:11:39 -04:00
Sébastien
f3d99fc440 Fix flaky guest-embed happy path checkbox visibility (#74952) 2026-05-29 11:48:22 +02:00
Romeo Van Snick
7e79fbb727 Select schema if it is missing (#74586)
* Select schema if it is missing

* Also consider state.schema

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>

* test: run mongo native setup in beforeEach so burn/retries re-set up

The stress workflow (and CI retries) re-run each it via @cypress/grep burn,
which generates N separate tests. A before() hook only sets up the first one;
with testIsolation the page resets for the rest, so iterations 2..N fail with
'never found [data-testid=native-query-editor] .cm-content'. Using beforeEach
re-establishes the editor state for every iteration.

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

---------

Co-authored-by: Copilot Autofix powered by AI <175728472+Copilot@users.noreply.github.com>
Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-29 18:53:18 +10:00
Uladzimir Havenchyk
01c49647f7 test: cleanup jest warnings from querying folder (#74753)
* test: cleanup jest warnings from query_builder folder

* test: cleanup jest warnings from querying folder

* fix last warnings

* cleanup

* cleanup and speed up joinstep
2026-05-29 11:13:03 +03:00
Uladzimir Havenchyk
e74ebaa14a chore: drop deprecated ButtonGroup (#74904)
* chore: drop deprecated ButtonGroup

* adjust ci

* Revert "adjust ci"

This reverts commit 7333dc3af8.

* Reapply "adjust ci"

This reverts commit 2ac27c8b69.
2026-05-29 11:12:12 +03:00
YB
44c2c839aa [GDGT-2078] add observability to transform cancelations (#73157)
The transform cancellation subsystem has no Prometheus metrics, no tracing spans, and only trace-level logging. We want better observability over both the user-initiated cancel path and the Quartz sweep that force-cancels stuck runs.

We are adding the following:

* Prometheus counter metabase-transforms/cancelation-requests with label {status} fired once per call to mark-cancel-started-run!
* Prometheus counter metabase-transforms/cancelation-completed with label {outcome}
* Prometheus histogram metabase-transforms/cancelation-latency-ms with label {outcome}, measuring request-time to completion
* Span task.transform.cancel in the :tasks group, with attributes run/id and transform/id
* New audit event :event/transform-run-canceled derived under ::transform-event, published from record-completion! with the full TransformRun row as the object
* Log-level change from trace to info on request, successful cancel, and force-cancel paths
* Also fixed a potential race in cancel-old-canceling-runs! by using a transaction lock on selected rows to be deleted.

* cancel old canceling runs in a transaction

* refactor review comments; properly return cancelled row data to be consumed by audit event log
2026-05-29 06:53:40 +00:00
Andrei Chernykh
1d39f46f11 Metics Homepage: Right side panel (UXW-4238) (#74809)
* Restructure metric About-tab right rail into Source and Relationships subsections (UXW-4238)

* Pluralize verb in '<N> charts use this metric' and tighten relationship-row construction (UXW-4238)

* Combine Last-updated label and relative time into one ttag template

* Inline relationship-row construction

* Use if/else over nested ternaries for relationship rows

* Render Source and Relationships rows declaratively, drop MetadataRow data type

* Polish right-rail metadata rows: white circle icon containers, larger About heading, plain verb phrase

* Detach right rail from chart card and lift sub-section cards above the page

* Connect metadata rows with a vertical line, use dependencies icon, loosen gaps

* Match Figma spec for the right rail and polish per code review

* Gate Dependencies tab and Relationships subsection by admin/analyst role (UXW-4174) and fix ttag extraction

* Test setup via real plugin init and dependency graph endpoint; switch rem() to Mantine size tokens

* Drop caching url from DescriptionSection spec to match the post-rebase MetricUrls type

* Refine right-rail metadata rows: dependent icon, hover color, spacing, and component split

* Seed dependencies token feature into the test store via renderWithProviders

* Update MetricAbout test anchor to the new Source heading
2026-05-28 21:35:09 -07:00
Fraser
6061e2f604 Fix DatePicker css import (#74947) 2026-05-29 15:54:24 +12:00
Fraser
982040aa43 Reclassify schema as shared tier (#74946) 2026-05-29 15:54:14 +12:00
Anderson
482d1dbea5 Fix Sankey click data for extra columns (#74283)
* Fix Sankey click data for extra columns

* Fix error: getting property of undefined on hover

* Address Nick's comment
2026-05-29 03:52:34 +00:00
Romeo Van Snick
2b88cdbb34 Convert the onResponseError to use EventEmitter event on API client and add event types (#74894)
* Use EventEmitter for response errors

`LegacyApi` already extends `EventEmitter` (and uses it for the
status-code events 401/403/etc), but the response-error notification
was a separate parallel mechanism: a public `onResponseError` callback
that the embedding SDK assigned at boot. Two ways for callers to
subscribe to client events on the same object.

Switch to the existing event channel:
- Remove the `onResponseError` field from `LegacyApi`.
- Replace the two `if (this.onResponseError) this.onResponseError(...)`
  guards (XHR path + fetch path) with `this.emit("responseError", info)`.
- Migrate the one external assignment (`api.onResponseError = handler`
  in the SDK init hook) to `api.on("responseError", handler)`. Dedupe by
  handler identity (matching the existing `beforeRequestHandlers`
  pattern with `reactSdkEmbedReferrerHandler`), so other listeners on
  the same event do not prevent the SDK from registering its own.
- Drop the now-unused `ResponseErrorInfo` type alias.

No behaviour change. Just one notification mechanism instead of two.

* Add stricter typing for api client events
2026-05-29 13:31:21 +10:00
Romeo Van Snick
ba93b7ebfb Replace raw option with :tag* URL template syntax (#74891)
The legacy API client supports `:tag` placeholders in URL templates that
get URL-encoded substitutions from request data. For one endpoint
(`/api/automagic-dashboards/:subPath`) the value is a multi-segment path
that must NOT be URL-encoded — slashes have to survive. The opt-out was
a per-call `raw: { subPath: true }` option, plumbed through
RequestOptions just for that one case.

Replace it with a single-character syntax extension: a trailing `*` on
the placeholder. `:tag` encodes (current behavior); `:tag*` substitutes
raw. The decision lives on the URL template, where it belongs, not in a
sibling options object.

Done in this commit:
- New `substituteUrlTags(url, data, method)` helper with its own unit
  spec covering both `:tag` (encoded) and `:tag*` (raw) cases.
- Legacy client uses the helper, drops the inline regex loop.
- `raw: Record<string, boolean>` removed from `RequestOptions` and
  `DEFAULT_OPTIONS`.
- The one caller (`AutoApi.dashboard`) migrates from
  `GET(url, { raw: { subPath: true } })` to `GET("/api/.../:subPath*")`.
2026-05-29 12:30:56 +10:00
Anderson
c63b8ad8b8 Fix stacked chart total labels for combo charts (#74247)
* Fix stacked chart total labels for combo charts

Closes https://linear.app/metabase/issue/UXW-3433/stacked-bar-chart-with-lines-bars-shows-zero-on-horizontal-axis

### Description

Limit stacked-total label placeholders to the series that are actually part of a stack, so line-only points in combo charts do not create stray zero labels.

### How to verify

1. Create a combo chart with stacked bars and a line where one x-axis bucket only has a line value.

2. Enable stacked total labels.

3. Confirm no zero label is rendered for the line-only bucket.

### Checklist

- [x] Tests have been added/updated to cover changes in this PR

* Update loki snapshot
2026-05-28 23:06:33 -03:00
YB
74494aff22 [GDGT-2079] add observability to transform timeout system (#73539)
Add Prometheus instrumentation and an audit event for transform-run and job-run timeouts, and replace the existing non-atomic sweep with a transaction so the emitted metrics can't drift from the rows actually transitioned to :timeout.

Changes:

* Counter :metabase-transforms/timeouts-total {type} - incremented per timed-out run; type is "transform" or "job".
* Histogram :metabase-transforms/timeout-detection-latency-ms {type} - how late the sweeper detected each timeout. Bounded by the 10-min sweep interval
* Audit event :event/transform-run-timeout - fires for both the single-run timeout-run! path and the sweeper path. Payload reflects the post-update :timeout row state.
* Tracing span task.transform.timeout-check {transform.timeout/type} on both Quartz jobs.

---
The transform-side sweeper previously caught and logged all exceptions inside timeout-transform-runs! (log/error from this namespace, then swallow). This wrapper is removed, as a wrapper inside tracing/with-span would have hidden - clj-otel's internal add-exception! only fires if the throw reaches it.

Recovery semantics are unchanged - Quartz catches the throw at the job-execution boundary, logs it at WARN with a JobExecutionException stack trace, and the next 10-minute trigger fires normally. The only functional change is observability: the failure now also populates the task.transform.timeout-check span with status=error.
The job-side sweeper previously used non-atomic UPDATE … RETURNING pks + post-SELECT. The new path is one transaction with SELECT … FOR UPDATE + UPDATE -> this is portable across H2/MySQL/Postgres.

Also fixed a test-isolation bug in metabase.transforms.jobs-test/timeout-old-runs-{notifies,does-not-notify}-*-test - the tests assumed :crowberto was already inserted by suite ordering, so they failed when run alone with :only. Tests now explicitly (mt/fetch-user :crowberto).
2026-05-29 09:45:15 +08:00
Romeo Van Snick
48446fa1aa Replace cancelDeferred with AbortSignal and honor the signal everywhere (#74889)
* Use AbortController in data-fetching instead of deferred

* Use signal instead of cancelDeferred

* Remove unused controller option from legacy-client

* Remove deferred arg

* Pass missing signal

* Handle already-cancelled signal

* Use abortcontroller to abort in test

* Allow delay cancellation

* Remove race in aborting a delay promise

* Cancel retry-backoff waits with the request signal

The retry loop in `_makeRequestWithRetries` was the last place where an
aborted request still finished its wait. `delay()` already accepts an
`AbortSignal`; pass `options.signal` through so an abort interrupts the
backoff sleep immediately instead of running it to completion before the
next attempt (which would only then see the aborted signal).

* Avoid another retry when cancelling

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-05-29 11:08:13 +10:00
Fraser
0a5e7eec56 Decouple ObjectDetail from QB (#72845) 2026-05-29 12:24:07 +12:00
Mihael Konjević
0b269fb4b4 Merge misplaced trailing options-map on fixed-arity MBQL clauses (#74926)
LLMs sometimes place a clause's options at the END of a fixed-arity
tuple clause instead of position 1, e.g.

  ["time-interval" {} <expr> -1 "month" {"include-current" true}]

`time-interval` is a strict 5-tuple, so the extra element fails Malli
with a generic tuple-shape error and the construct_notebook_query tool
rejects the query. The trailing map is unambiguously misplaced options
(no fixed-arity tuple clause legitimately has a map-typed last arg).

Add a generic repair pass `merge-trailing-options*` that detects this
across every fixed-arity tuple clause registered with
`metabase.lib.schema.mbql-clause` — the expected-element-count table is
derived once at namespace load from `tag-registry`, so new fixed-arity
clauses get coverage automatically. Variadic `:catn`/`:repeat` clauses
(`and`, `or`, `case`, `coalesce`, `=`, `in`, …) are excluded — their
arity isn't fixed, so a trailing map there could be a legitimate arg.

When the pattern matches, merge the trailing map into position-1 options
(trailing keys win on conflict, since the trailing map is where the LLM
deliberately wrote content) and drop the trailing element. Idempotent by
construction.

Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-28 17:27:29 -04:00
technomancy
0726c32209 Check for VolumeOperationAllowedLocalPaths connecting to databricks. (#74375)
* Check for VolumeOperationAllowedLocalPaths connecting to databricks.

* Move additional options check to validate-db-details! method.

* Review suggestions: check a few other cases.
2026-05-28 19:02:33 +00:00
Andrei Chernykh
ed8e23b76f Move Explore button into the chart card (UXW-4237) (#74810)
* Move Explore button into the chart card (UXW-4237)

* Address review: drop dead mock, move zIndex to CSS module

* Drop now-redundant Group wrapper around single Menu

* CSS cleanup: drop dead border-radius, move position:relative into class

* Fix metric-page e2e: explore link is now on the chart card, not the header

* Bump Explore button overlay spacing to xl (32px)

* Drop module mocks in MetricAbout spec; use real card metadata + endpoint stubs

* Use size=xs on Explore button for closer-to-design height
2026-05-28 12:02:08 -07:00
appleby
d4238abb10 BOT-1524 Save tables used in a metabot conversation (#74254)
* BOT-1524 Save data sources used in a metabot conversation

* Handle implicit joins

* Simplify query-tables-and-cards with lib/all-referenced-entity-ids

* Cleanup native-tables parsing, remove uneeded macaw-tables

* Use lib more. banish mbql destructuring and raw mbql in tests

* Remove MetabotUsedTable from module config model-exports since nothing external uses it

* banish deprecated mt/mbql-query in tests

* Clean up docstrings in used_tables.clj

* Calm down with "MBQL 5" references

* Improve description for metabot_used_table

* Push seq down into when

* whitespace cleanups

* Use with-temp rather than t2/insert! and t2/delete! in used table tests

* Small formatting cleanup in persistence tests

* Use t2/with-transaction :rollback-only true rather than mt/with-model-cleanup in persistence tests

* Cleanup finalize-records-used-tables-test

* Formatting cleanup in ->transform-sql-parts and ->transform-python-parts

* More persistent test cleanups

* Remove private mp defn for metadata provider

* Rename provider to mp

* Formatting cleanups in used tables tests

* Pass in metadata-provider to extract-used-tables defaulting to lib-be/application-database-metadata-provider

And update the tests to take advantage of not need real cards in the app db and mark tests ^:parallel

* Use mt/with-dynamic-fn-redefs and mark tests ^:parallel

* Remove explicit ^:sequential

* Improve testing description strings

* Improve combined tool calls used tables test

* Only visit cards shared between tool calls once in extract-used-tables

* Fix trailing whitespace

* Fix lint warning about with-redefs

* Fix race in app-mention-triggers-response-test

* Add prometheus metrics for used table extraction duration and failures

* Move used tables extraction to background thread

* review feedback: remove macaw mentions

* review feedback: composed transducer rather than lazy seq

* review feedback: add some debug logs with more context

* review feedback: add bounded queue and increase threads to 4 for the used tables extraction executor

* Add 15s timeout via u/with-timeout for used tables extraction

* Add separate worker and waiter executors to ensure work remains bounded

Don't use u/with-timeout which runs the extraction on the shared future thread pool. Instead, create a separate worker
pool to ensure worker threads remain bounded even if they are stuck in cpu-bound state where they ignore thread
cancellations.

* Rename extract-used-tables-with-timing to extract-used-tables-with-timing!

* Allow idle threads to be reclaimed after 5 minutes

* Add test for extraction timeout and improve test for queue saturation
2026-05-28 14:35:06 -04:00
Cam Saul
7fa844b5bb Revert formatting-breaking commits (#74921)
* Revert "Use existing commit for cljfmt (#74885)"

This reverts commit d4d8c53d83.

* Revert "Fix cljfmt formatting  (#74892)"

This reverts commit ef186e4a60.
2026-05-28 11:25:03 -07:00
Timothy S. Dean
b355eb27f9 Gate workspace config section on :workspaces feature (#74864)
Loading the `:workspace` config-file section (at boot or at runtime via `POST /api/ee/advanced-config/`) only required the `:config-text-file` feature. They should both require `:workspaces`.
2026-05-28 11:51:51 -06:00
Mihael Konjević
9382445c5c Reduce and converge Metabot system prompts on objective-based style (#74758)
* Reduce and converge Metabot system prompts on objective-based style

Converge the embedding and internal system prompts onto the lean,
objective-based style of the NLQ prompt, and collapse the duplicated
verification/grounding guidance into a single source of truth.

- New shared includes (grounding, data-sources, mbql-shape, communication,
  discovery) lifted from the NLQ prompt; nlq/embedding/internal now compose
  them. Retire critical-constraints, verification-triggers, samples-vs-results,
  disclosure-protocol, and anti-patterns (the verification rule was restated
  ~6x; now once).
- internal.selmer 447->107 lines, embedding-next.selmer 419->79; permission
  gating kept but expressed through stable <!-- gate:X -->/<!-- denial:X -->
  anchors so wording can change without breaking tests.
- Verification reframed from "verify EVERY literal, no exceptions" to
  "verify literals whose format you can't predict" to stop wasteful
  sample reads; narration/clarification contradictions resolved.
- Discovery reframed navigate-first: read_resource is a first-class peer of
  search. Fold the four near-identical search prompt files into the discovery
  include; move search parameter guidance into Malli field descriptions and
  enrich the tool docstrings.
- De-duplicate the SQL read-only contract: canonical in create_sql_query.md,
  pointer in edit/replace, one-liner in internal.
- prompt_gating_test asserts on the new anchors instead of prose.

* Address PR review on Metabot prompt converge

- Include grounding/data-sources/discovery in the SQL profile so it gets
  the same discovery and verification guidance as the other profiles
  after the per-tool search prompts were retired.
- Drop the literal tool-name reference in grounding.selmer so the snippet
  is not coupled to specific tool names; discovery.selmer keeps the
  names since it is specifically about distinguishing them.
- Move shared snippets under shared/prompt_snippets/ to mark the
  directory as a contract: files placed there must be safe to embed in
  the cacheable prefix.
- Add prompt-cache tests asserting no Selmer directives appear in
  shared/prompt_snippets/ and that the cacheable prefix of every system
  template is stable across per-request values (current_time, user
  info, viewing context, recent views).

* Tune SQL profile to address regressions found in benchmark runs

- Add an SQL-specific "Searching effectively" section to the SQL
  profile so the agent gets concrete multi-concept and
  semantic/keyword search examples that used to live in the deleted
  sql_search.md.
- Replace the previous "Handle Uncertainty" framing (which described
  ask_for_sql_clarification as "your only way to send text") with an
  explicit tool-routing table. SQL bodies go through
  create_sql_query/edit_sql_query/replace_sql_query;
  ask_for_sql_clarification is reserved for short clarifying
  questions about structural ambiguity only.
- Rewrite ask_for_sql_clarification.md from the ground up: scope to
  short clarifying questions, explicit denylist for SQL bodies and for
  questions discovery can answer, and a one-sentence constraint on
  the question argument.
- Reinforce the routing in the profile's Remember section so the
  cache-prefix tail nails the rule.
- Bump SQL profile max-iterations from 10 to 20 so the agent has
  budget for the longer discovery patterns the new prompt encourages.

* Silence reflection warning in prompt_cache_test

Add (set! *warn-on-reflection* true) so the type hint on ^java.io.File
in snippet-files is checked by the compiler instead of producing a
clj-kondo warning.
2026-05-28 19:41:00 +02:00
Uladzimir Havenchyk
6954909b94 deps: use safe version of js-cookie (#74778)
* deps: use safe version of js-cookie

* pin
2026-05-28 17:37:16 +00:00
Nick Fitzpatrick
b4ebd35fcd Test connection button for Remote Sync (#74665)
* Test connection button for Remote Sync

* remove branch and mode from connection test
2026-05-28 23:05:31 +05:30
Nick Fitzpatrick
dca533be70 Fix Field Filter when there are no search results (#74832) 2026-05-28 23:03:23 +05:30
Phoomparin Mano
ef1d510edc Do not return MCP Apps tools for clients without UI capability (#74743)
* do not return mcp apps tools for clients without ui capability

* use a stronger shape for mcp ui capability detection

* tidy up session.clj session helpers

* add extended session id validation

* mcp ui tools should declare required client extensions

* remove rollback for varchar length extension

* update argument order

* parse uuid with parse-uuid utility

* log when capability payload is blank

* log when capability payload cannot be decoded

* warn if the mcp session id is too long

* document preserving slash with json/decode+kw

* use with-dynamic-fn-redefs for unit test

* remove unused supported-extensions option

* check scope matches first

* re-add non-null constraint after varchar(254) change

* disable mcp apps ui support if capability payload version mismatches

* allow known/older version for capability payload

* fix cljfmt lint
2026-05-28 13:11:32 -04:00
Alexander Polyankin
f6de634363 check pg grant statements rights (#74909)
* check pg grant statements rights

* tests

* fix

* redshift

* fix

* fix

* fix

* fix
2026-05-28 11:56:31 -04:00
Mahatthana (Kelvin) Nomsawadi
4e0dfc2136 bump qs (#74898)
deps: bump qs ^6.14.2 -> 6.15.2

Fixes Snyk medium-severity advisory SNYK-JS-QS-16721866
(CVE-2026-8723, NULL pointer dereference in stringify with
arrayFormat=comma + encodeValuesOnly when arrays contain
null/undefined).
2026-05-28 15:30:52 +00:00
Eric Normand
dd9d119b4c GHY-3701 force let-user-control-scheduling false in workspace config (#74913)
GHY-3701 force let-user-control-scheduling false for non-stub config entries

build-workspace-config emits :details only — not the schedule cron
columns. infer-db-schedules asserts cache_field_values_schedule and
metadata_sync_schedule are populated whenever :let-user-control-scheduling
is true, so a source DB that opted in would blow up the round-trip on
import. Override the key to false in database-entry so the receiving
side takes the auto-schedule branch. Stubs are unaffected — they emit
:details {} and already fall through to the auto-schedule branch.
2026-05-28 15:26:45 +00:00
Alexander Polyankin
db65e87b13 Workspace setup entry point from zero state (#74887)
* setup changes

* fix

* e2e fixes

* fix

* fix

* fix
2026-05-28 15:01:09 +00:00
Romeo Van Snick
ef186e4a60 Fix cljfmt formatting (#74892)
Fix formatting
2026-05-28 17:14:57 +03:00
Braden Shepherdson
72eb2f945c [perms] Fix N+1 query in sandboxing when updating perms (#74734)
Even when sandboxing is not used, 1 read was being generated for each
group X table whose permissions were impacted by the update. In a sample
query from a user, that was 28 groups X 382 tables =  10,696 reads.

This change includes a unit test that synthesizes this same scale and
makes the same request. It did reproduce the same 10,700+ requests the
user was seeing initially, but with these changes to how sandboxes are
checked (one query per database) it now only makes 87 queries. That's
still a lot but not unreasonable for a complex request.
2026-05-28 09:57:54 -04:00
Sébastien
900e1abd5a Fix embedModalEnableEmbedding race with pending React remount (#74815) 2026-05-28 15:50:42 +02:00
Chris Truter
0fe9d30bea Distinguish empty Metabot prompt regeneration from errors (#74406)
* Distinguish empty Metabot prompt regeneration from errors

When an admin clicks "Regenerate suggested prompts" today, three different
outcomes look the same: the LLM crashed, the metabot's library is empty
(no models/metrics to summarise), or the LLM ran but produced no
questions. All three previously returned `204 No Content` and the UI had
no way to tell them apart.

This commit makes `generate-sample-prompts` return a structured outcome
the API endpoint surfaces as JSON:

  {:status :generated  :prompt-count N}             - happy path
  {:status :empty :reason :no-library-content}      - nothing to summarise
  {:status :empty :reason :ai-produced-no-prompts}  - LLM returned 0 questions
  {:status :empty :reason :managed-free-limit-reached}
                                                    - managed AI cap reached

The empty-library and managed-free-limit cases skip the LLM call entirely
so we don't burn tokens generating nothing. The endpoint now returns
`200 OK` with the structured body in place of `204 No Content`; the
response schema is declared so docs and TypeScript signature generation
pick it up.

Errors (LLM 5xx, network, etc.) still surface as exceptions and turn
into 4xx/5xx responses — those remain distinct from the `:empty` cases.

Frontend follow-up needed: the admin panel's regenerate-button toast
should branch on `:status` and `:reason` to render a friendly empty-state
message instead of a silent success. Not in this PR (backend-only).

* Make regenerate-prompts response a discriminated union

Collapse the previous `{:status :empty :reason :x}` shape into a single-tag
union `{:status :x}` so callers can switch on one field, and rename
`:prompt-count` to `:prompt_count` to match wire conventions.

* Handle each regenerate-prompts status in admin UI

Surface the new no-library-content, ai-produced-no-prompts, and
managed-free-limit-reached statuses with their own toast copy instead of
collapsing them into a generic error.

* Tighten regenerate-prompts response and tests

- Drop :managed-free-limit-reached from the discriminated union; the 402
  fires before generate-sample-prompts is ever called, so the case is
  unreachable from this endpoint.
- Match exhaustively in the admin UI via ts-pattern so future status
  additions are a compile error.
- Add admin-UI unit tests for the no-library-content,
  ai-produced-no-prompts, and happy-path branches.
- In the backend test, assert that :prompt_count in the response equals
  the actual MetabotPrompt row count (not just the mock's promise).
- Realize the per-source prompt seqs into vectors so we don't re-run
  ->prompt between counting and inserting.
- "summarise" → "summarize".

* Close TOCTOU race on managed-AI lock in regenerate-prompts

`generate-sample-prompts` now calls `check-metabase-managed-free-limit!`
itself instead of soft-returning `{:status :managed-free-limit-reached}`.
That makes the response union genuinely closed: there's no longer a window
where the endpoint's pre-check passes, the function-level check then sees
the lock flipped, and a status not in the Malli `:multi` schema slips
through (which would have surfaced as a 500 from defendpoint validation).

`update-metabot` still wants best-effort behavior — a settings PUT
shouldn't 402 just because prompt regeneration was raced by the lock —
so wrap its `generate-sample-prompts` call in a try/catch that swallows
the locked-account exception and re-throws everything else.

Add a test for that race-tolerance path, asserting both that the locked
402 is swallowed and that a non-locked ex-info still propagates.

* Tighten happy-path regenerate test anchor

The previous `waitFor(negative-assertion)` succeeded immediately because
no toast renders synchronously on click — by the time the mutation
settled, the assertion had already passed, so a regression where the
happy-path branch wrongly fell through to an empty-state toast could
slip past.

Anchor on the button's idle text instead: "Regenerate suggested prompts"
only re-renders after `isRegenerating` flips back to false, which is the
same render where any mistaken toast would have appeared. Now the
negative assertions run only after the mutation has actually resolved.

* docstrings: trim design-rationale from generate-sample-prompts + endpoint

Both docstrings carried multi-paragraph design rationale ("single discriminator
so the frontend can switch on one field", "closed union so the regenerate
endpoint can declare an exact response schema", "no TOCTOU race between
checks"). All of that is implementer-context for someone who'd refactor the
design, not caller-contract material the IDE-hovering caller needs.

Slim each docstring to the caller contract: what's returned, when 402 fires,
and what callers who want best-effort behaviour should do about the
managed-free-limit race. The schema declaration above the endpoint already
shows the exact response shape.

* Tighten regenerate-prompts response schema

Two narrower invariants in the discriminated union:

- `{:closed true}` on each variant so the OpenAPI / TS output is an
  exact union instead of permitting `additionalProperties`.
- `:prompt_count` is `pos-int?`, not `nat-int?`. The `:generated`
  variant is only returned when total > 0 — the zero case branches
  to `:ai-produced-no-prompts`. Encoding that in the schema removes
  an impossible state from the contract.

Inline comment points the next reader at the function that decides
which branch is returned.

* Pre-guard managed-AI lock in startup prompt task

After 4831cc9a74c made `generate-sample-prompts` always call
`check-metabase-managed-free-limit!`, locked-instance startups would
fail the call and surface as `log/errorf` from the generic catch in
`maybe-generate-suggested-prompts!`. That's noise — the locked state
isn't a failure, just a "not now."

Add a `metabot.usage/managed-free-limit-reached?` branch to the cond so
the task logs a clean info-level skip when the cap is hit, mirroring
the existing "Metabot is disabled" skip. The catch still backstops real
exceptions.

The existing locked-provider test already pins the outcome (no prompts
persisted, generator never called); the new path just changes how the
skip is logged.

* Wrap PUT regenerate in a transaction so a failed regen keeps prompts

* Test that PUT prompt regen rolls back the delete on failure

* Sync OpenAPI specs with regenerate endpoint docstring

* Plainer regenerate-prompts docstring in API docs

* Regenerate OpenAPI specs to include regenerate-prompts response union

The earlier sync commit (9ab0fc923d) updated only the endpoint
description, leaving `responses.2XX` as the generic placeholder. Copilot
review on #74406 flagged that generated clients still wouldn't see the
discriminated union this PR introduces.

Run `bun run generate-openapi` and `clojure -M:ee:doc api-documentation`
so both `resources/openapi/openapi.json` and `docs/api.json` carry the
full `oneOf` schema for the 2XX response (`generated` /
`no-library-content` / `ai-produced-no-prompts`). The regen also flushes
unrelated component drift (workspace schemas, etc.) that the nightly
auto-update workflow had not yet caught up to.

* Drop unrelated EE endpoint drift from docs/api.json

* Drop stray blank lines flagged by cljfmt

The earlier merge commit (`8684854bc85`) was made with `--no-verify`
because husky's pre-commit cljfmt was getting SIGKILL'd mid-merge.
CI caught two stray trailing blank lines inside `let`/`with-redefs`
bodies the merge introduced — apply `bin/mage cljfmt-files` to them.

* Use mt/with-dynamic-fn-redefs for the new function-mocking sites

Copilot review on #74406 flagged four new mocks that use
`clojure.core/with-redefs` to redefine defn-style vars (the project
clj-kondo hook prefers `metabase.test/with-dynamic-fn-redefs` because
it's thread-safe).

Switch the four sites I added in this PR:
- metabot-put-skips/recovers tests for managed-AI lock
- metabot-prompt-regenerate-empty-states-test (no-library-content and
  ai-produced-no-prompts branches)

Leaving the two pre-existing `with-redefs` sites in this file (the
ones not flagged by the reviewer) untouched — those weren't introduced
by this PR.

* nits

---------

Co-authored-by: Sloan Sparger <sloansparger@gmail.com>
2026-05-28 07:52:01 -05:00
Sébastien
84cfb80f6a Update test to reflect label change (#74906) 2026-05-28 14:44:28 +02:00
Ngoc Khuat
fabf312a17 Log resolved email recipients when sending an email (#74816) 2026-05-28 09:21:09 +00:00
Fraser
ccef44cf5c Move NoDatabasesEmptyState into common (#74813) 2026-05-28 20:55:41 +12:00
Uladzimir Havenchyk
07ba1d3459 test: cleanup jest warnings from query_builder folder (#74640)
* test: cleanup jest warnings from query_builder folder

* fix question download widget test

* proper fixes
2026-05-28 11:15:53 +03:00
Ngoc Khuat
52bd3beefd Only re-validate incremental checkpoint field when source changes (#74752) 2026-05-28 15:02:37 +07:00
Romeo Van Snick
5325f240e9 Remove Question entity (#74652)
* Migrate question entity-framework hooks off the Questions entity

* Migrate read-only Question consumers off the Questions entity

* Migrate dashboard card actions off the Questions entity

* Migrate query-builder card actions off the Questions entity

* Remove the questions entity

* Do not drop dashcard sizes in api call

* Handle errors in card query

* Add error/loading state to action creator modal

* Avoid refetching when forbidden

* Avoid stale cards in card mutations
2026-05-28 13:17:56 +10:00
Romeo Van Snick
d4d8c53d83 Use existing commit for cljfmt (#74885) 2026-05-28 12:45:02 +10:00
Phoomparin Mano
a0f8e76a88 Hide feedback buttons for MCP Apps when not on cloud (#74742)
hide mcp feedback buttons if not enabled
2026-05-28 00:28:12 +00:00
github-automation-metabase
ce339dfb19 Update translations 2026-05-26 (#74744)
* Update translation sources 2026-05-26

* Update translations

---------

Co-authored-by: github-actions <github-actions@github.com>
2026-05-27 22:57:39 +00:00
bryan
0537620660 Fix Redshift iso-user leak in test cleanup (#74867) 2026-05-27 16:51:31 -06:00
Ryan Laurie
d29198d4fa Auto-add issues only to open milestones (#74871)
only auto-add issues to open milestones
2026-05-27 22:43:23 +00:00
github-automation-metabase
aabdd5ceb7 Auto-update documentation for master (#74874)
Update generated docs (master)

Co-authored-by: github-actions <github-actions@github.com>
2026-05-27 17:50:43 -04:00
Fraser
bae37c4861 Move setIsNativeEditorOpen into shared (#74807) 2026-05-28 09:38:54 +12:00
Eric Normand
f6bf515793 GHY-3687 Handle is_sample database (#74839)
* GHY-3687 expose sample-database-name from sample-data.core

* GHY-3687 workspace-manager /config emits sample-database entry

* GHY-3687 advanced-config loader handles is_sample

* GHY-3687 add sample-data to driver-affecting-overrides

sample-data is fixture/loader infrastructure, not driver logic. With
enterprise/workspaces (a trigger) now depending on sample-data, the
module would otherwise nudge modules-triggering-drivers from 41 to 42.
2026-05-27 21:12:32 +00:00
bryan
29d703e9d2 MCP: read_resource, write tools, execute_sql (#74458) 2026-05-27 14:34:57 -06:00
Jeff Bruemmer
67745bd3c2 docs - adds dedicated AI privacy page (#74669) 2026-05-27 20:13:57 +00:00
Andrei Chernykh
520fece1d0 feat: Move Caching tab into the overflow menu (UXW-4236) (#74563)
* Move Caching tab into the overflow menu (UXW-3839)

* Refactor caching strategy form and migrate styled-components (UXW-3839) (#74666)

* Open metric caching settings in a modal (UXW-4236) (#74682)

* Remove legacy metric caching page (UXW-4236) (#74691)

* Remove legacy metric caching page (UXW-4236)

* Address review feedback (UXW-4236)

* remove a comment

* Migrate StrategyFormLauncher to CSS module (UXW-4236)

* Merge duplicate @media query in StrategyFormLauncher.module.css (UXW-4236)

* Address review feedback (UXW-3839)

* Use UnstyledButton instead of Anchor for cache strategy trigger (UXW-3839)

* Trim verbose code comments (UXW-3839)

* Address review feedback: rem units, flex alignment, Cancel discard prompt (UXW-3839)

* Fixed-height caching modal and consistent Cancel behavior (UXW-3839)

* Restore Radio description prop and forward description clicks to input (UXW-3839)

* Make strategy radio descriptions clickable via second label (UXW-3839)

* Address review: Radio description prop, modal CSS module, S import name (UXW-3839)

* Tighten Caching modal typography, spacing, and inline-style cleanup (UXW-3839)

* Restore pointer cursor on strategy option label (UXW-3839)
2026-05-27 13:06:42 -07:00
Eric Normand
601be9c2de GHY-3686 Add stub databases (#74789)
* GHY-3686 add is_stub column to metabase_database

Boolean column, NOT NULL, default false. Marks placeholder databases
created during deserialization so they can be excluded from sync and
connection-test paths. Cleared when real details are supplied and the
main connection test passes.

* GHY-3686 serdes :copy + :defaults for is_stub

Round-trip serialization preserves is_stub when true, and elides it
from the exported map when false (matching the column default).

* GHY-3686 reject is_stub in REST API, clear on successful main-conn test

POST /api/database and PUT /api/database/:id throw 400 when :is_stub
appears in the body — setting it is reserved for the advanced-config
code path. PUT clears :is_stub to false when :details or :engine change
and the main connection test passes; write_data_details / admin_details
changes do not clear it.

* GHY-3686 skip stub databases in sync scheduler and job

sync-and-analyze-database! short-circuits when the database is a stub,
mirroring the audit-db guard. check-and-schedule-tasks-for-db! refuses
to register Quartz triggers for stubs.

* GHY-3686 advanced-config loader accepts is_stub

Config-file entries with `is_stub: true` skip the connection-test
gate and the post-insert sync trigger. Spec now optionally accepts
:is_stub as a boolean.

* GHY-3686 inject stub entries into workspace-manager /config

build-workspace-config now appends stub entries to :config.databases
for every database in the instance that isn't already provisioned for
the workspace. Sample (handled by GHY-3687), audit, and routing-target
databases are excluded.

* GHY-3686 chunk workspace-db-ids into 500-row NOT-IN clauses

Avoid feeding an unbounded sequence into a single SQL IN clause —
Oracle's IN cap is 1000 and other drivers have their own parameter
limits. partition-all yields zero chunks (and so no NOT-IN clauses)
when the workspace has no databases, which is the prior behavior.

* GHY-3686 chunk workspace DB lookup IN clause to 500-row batches

Same reasoning as the NOT-IN in stub-databases: a workspace with many
provisioned databases would otherwise hit driver IN-clause limits.
Empty workspace_db_ids yields zero queries (no chunks), matching the
prior empty-case behavior.

* GHY-3686 add :is_stub to table-test db-details fixture

The new is_stub column on metabase_database now appears in API
responses inside the embedded :db map; table-test fixtures asserting
exact :db shapes need to list it. Same pattern as the other is_*
flags in this fixture.

* GHY-3686 stub config entries no-op when a real DB already exists

The round-trip workflow (build-workspace-config -> YAML -> initialize!)
emits stub entries for every non-workspace DB in the instance. When that
config is applied back to the same instance, the stub entries collide
by name+engine with the real databases — without this guard the loader
would update them with :details {} and :is_stub true, breaking working
connections (surfaced as "FATAL: role <user> does not exist" in workspace
e2e tests).

Stubs only ever create rows; they never overwrite existing ones.

* GHY-3686 revert workspace DB IN/NOT-IN chunking

Restoring the single-clause IN and NOT-IN queries in
build-workspace-config and stub-databases. A workspace will not
realistically accumulate enough database refs to hit driver parameter
limits.
2026-05-27 19:59:53 +00:00
Nemanja Glumac
aa84834af4 Upgrade various GitHub actions (#74850)
* Pin nowactions/envsubst comment to v1.0.1

SHA unchanged; the # v1 comment now reflects the exact release.

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

* Pin trunk-io/analytics-uploader to v2.0.9

Was floating on @main (unpinned); pin to an immutable SHA.

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

* Upgrade anthropics/claude-code-action to v1.0.133

Pin the exact v1.x release instead of the floating v1 major.

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

* Upgrade crowdin/github-action to v2.16.2

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

* Upgrade hoverkraft-tech/compose-action to v2.6.0

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

* Upgrade lycheeverse/lychee-action to v2.8.0

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

* Upgrade aquasecurity/trivy-action to v0.36.0

Also adds the missing version comment to the pin.

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

* Upgrade tailscale/github-action to v4.1.2

Drop-in: all inputs unchanged (version is explicitly pinned to 1.50.1). v4 moves the action to the Node 24 runtime.

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

* Upgrade azure actions (k8s-set-context, setup-helm) to v5.0.0

Drop-in: inputs unchanged (cluster-type still defaults to generic; setup-helm version still defaults to latest). Both move to the Node 24 runtime.

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

* Upgrade codecov/codecov-action to v6.0.1

Drop-in: token/files/flags inputs unchanged. v6.0.1 includes the VULN-1652 template-injection fix and the Node 24 runtime.

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

* Upgrade tj-actions/changed-files to v47.0.6

Drop-in: files input and consumed outputs unchanged. SHA is the GPG-signed v47.0.6 tag, a clean release post-dating the March 2025 incident; SHA pinning stays as the durable protection.

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

* Upgrade marocchino/sticky-pull-request-comment to v3.0.4

Drop-in: header/message/recreate inputs unchanged. v3 moves to the Node 24 runtime.

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

* Upgrade chromaui/action to v17.0.1

Drop-in despite the major jump: token/projectToken inputs survive and the removed inputs (allowConsoleErrors, only, etc.) were unused. v17 moves to the Node 24 runtime.

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

* Upgrade snyk/actions/setup to v1.0.0

Drop-in: we pass no inputs to setup; v1.0.0 is purely additive (new optional os input).

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

* Upgrade slackapi/slack-github-action to v3.0.3

Migrate the v2+ input model: the incoming-webhook URL moves from the SLACK_WEBHOOK_URL/SLACK_WEBHOOK_TYPE env vars into the webhook/webhook-type inputs; payloads are unchanged. Consolidates the previous v1.23.0 and v1.26.0 pins onto one v3.0.3 SHA. errors stays at the default (false), preserving v1 behavior. v3 runs on Node 24.

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

* Pin anthropics/claude-code-base-action to v0.0.63

Was floating on @beta (unpinned); pin to the immutable SHA @beta currently resolves to. No behavior change today.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-27 18:32:13 +00:00
bryan
7b466c9b86 Add clj-surgeon config (#74855) 2026-05-27 18:23:43 +00:00
Nick Fitzpatrick
1203790a23 Pass column settings when formatting pivot column headers (#74628) 2026-05-27 23:43:28 +05:30
metamben
00e329ce7e Report synchronous bigquery errors as client errors (#74684)
* Report synchronous bigquery errors as client errors

Closes QUE2-487

* Add missing type hint
2026-05-27 19:12:11 +03:00
metamben
94757c098c Handle nil subtotal nodes (#74605)
Closes #71220
Closes QUE2-460
2026-05-27 19:02:42 +03:00
lbrdnk
8ca87a3ff3 Make default embedding service base url match AI service (#74756)
* Set the default of embedding service base to ai service

* components

* test

* Apply suggestion from @crisptrutski

Co-authored-by: Chris Truter <crisptrutski@users.noreply.github.com>

* review remarks

* review remarks

* test and trim

---------

Co-authored-by: Chris Truter <crisptrutski@users.noreply.github.com>
2026-05-27 17:54:26 +02:00
Alex Yarosh
ecdb062426 docs - you no longer have to be store admin (#74837)
Refine Metabase AI settings documentation

Removed redundant information about the Metabase AI add-on visibility and the requirement for admin email matching. Clarified the process for enabling and disconnecting the Metabase AI Service.
2026-05-27 11:53:09 -04:00
Chris Truter
ae19823c53 Remove worktrunk config from git (#74838) 2026-05-27 15:37:23 +00:00
Riley Thompson
aa971184b0 Don't strip values from impersonation validation (#74440)
* dont strip values from impersonation validation

* add test

* strip values for graalpy, but return original values

* add tests that strip multi statement queries
2026-05-27 14:56:38 +00:00
Chris Truter
2520cb43c2 Bound pr-str when logging LLM errors (#74796) 2026-05-27 16:45:06 +02:00
8193 changed files with 724394 additions and 481905 deletions

View File

@@ -22,7 +22,6 @@ You understand Metabase's driver architecture built on Clojure multimethods with
:bigquery-cloud-sdk, :databricks, :clickhouse, :athena, :sparksql,
:presto-jdbc / :starburst, :vertica, :sqlite, :h2
:mongo (non-SQL, custom protocol)
:druid (non-SQL, REST-based)
```
Key driver extension points you know intimately:

View File

@@ -1 +0,0 @@
Fix flakey test $ARGUMENTS

View File

@@ -44,6 +44,22 @@ This guide covers Clojure and ClojureScript coding conventions for Metabase. See
- Lines ≤ 120 characters
- No blank non-comment lines within definition forms (except pairwise `let`/`cond`)
**Java interop: type-hint parameters in the arglist; prefer `ex-*` helpers:**
```clojure
;; bad — reflection warning, calls Throwable methods directly
(defn root-cause [e]
(if-let [cause (.getCause e)] (recur cause) e))
;; good
(defn- root-cause [^Throwable e]
(if-let [cause (ex-cause e)]
(recur cause)
e))
```
Use `ex-cause`/`ex-message`/`ex-data`/`ex-info` rather than `.getCause`/`.getMessage`/`(.getData ^ExceptionInfo …)` where possible.
## Style Conventions
**Keywords and Metadata:**
@@ -51,6 +67,37 @@ This guide covers Clojure and ClojureScript coding conventions for Metabase. See
- Prefer namespaced keywords for internal use: `:query-type/normal` not `:normal`
- Tag variables with `:arglists` metadata if they're functions but wouldn't otherwise have it
**Time/date: `java-time.api :as t` and `u.date`, not `java.time.*` direct interop:**
```clojure
;; bad — Claude default, requires java.time interop
(:import (java.time LocalDate))
... (LocalDate/now) ...
;; good
(:require
[java-time.api :as t]
[metabase.util.date-2 :as u.date])
... (t/local-date) ...
... (u.date/parse "2024-01-01") ...
```
Only `(:import java.time.X)` when interop with a Java method genuinely needs the class.
**Check non-emptiness with `seq`, not `count`:**
```clojure
;; bad — `count` realizes the whole seq into memory just to test emptiness
(let [prompts (map build-prompt items)]
(when (pos? (count prompts))
(t2/insert! :model/Prompt prompts)))
;; good — `seq` realizes one cell; `insert!` streams the rest
(let [prompts (map build-prompt items)]
(when (seq prompts)
(t2/insert! :model/Prompt prompts)))
```
## Tests
**Organization:**
@@ -62,6 +109,33 @@ This guide covers Clojure and ClojureScript coding conventions for Metabase. See
- Mark pure function tests `^:parallel`
**Redefining `defn`-vars under test:**
Use `mt/with-dynamic-fn-redefs` instead of `with-redefs` when stubbing `defn`/`defn-` vars — plain `with-redefs` is not parallel-test-safe and a clj-kondo hook (`:metabase/prefer-with-dynamic-fn-redefs`, see `.clj-kondo/config.edn`) will warn. `with-redefs` is still fine for `def` / dynamic var rebinding.
```clojure
;; bad — flagged by the linter, not safe under :parallel tests
(with-redefs [my.ns/some-fn (fn [_] :stub)] (do-test))
;; good
(mt/with-dynamic-fn-redefs [my.ns/some-fn (fn [_] :stub)] (do-test))
```
**Async tests: no bare `Thread/sleep` — use `deref` with a timeout sentinel:**
A fixed sleep is the #1 source of CI flake. Tests should fail fast and loud when a contract is violated, not hang or sleep through the bug.
```clojure
;; bad — flaky on slow CI, silent on actual failure
(Thread/sleep 300)
(is (= :expected @seen))
;; good — fails fast with a clear message
(let [v (deref some-promise 1000 ::timeout)]
(is (not= ::timeout v) "promise never delivered")
(is (= :expected v)))
```
## Modules
**OSS Modules:**
@@ -86,6 +160,45 @@ This guide covers Clojure and ClojureScript coding conventions for Metabase. See
- Do not cheat module linters with `:clj-kondo/ignore [:metabase/modules]`
**Enterprise/OSS split: use `defenterprise`, not protocols or runtime feature checks:**
The OSS namespace defines the fallback body and names the EE namespace; the EE namespace overrides with the same fn name and a `:feature` clause naming the premium-features flag that gates the override. Both files use the same docstring shape — describe behavior on both sides.
```clojure
;; src/metabase/remote_sync/core.clj (OSS)
(defenterprise collection-editable?
"Returns whether remote-synced collections are editable.
Always true on OSS; EE consults the remote-sync settings."
metabase-enterprise.remote-sync.core
[_collection]
true)
;; enterprise/backend/src/metabase_enterprise/remote_sync/core.clj (EE)
(defenterprise collection-editable?
"EE override — respects the synced-collections-editable? setting."
:feature :remote-sync
[collection]
(or (synced-collections-editable?) (not (synced? collection))))
```
`defenterprise-schema` is the malli-schema variant. Required from `[metabase.premium-features.core :refer [defenterprise defenterprise-schema]]`. The OSS body is what runs when the feature flag is off — never write `(when (premium/has-feature? ...) ...)` in user code; let `defenterprise` route.
**Security gates fail *open* under `:feature` — use `:feature :none` and check manually.** The router (`dynamic-ee-oss-fn`) calls the EE body only when both the EE namespace is loaded *and* the token currently grants the feature; otherwise it falls back to the OSS body. For a permissive default (`collection-editable?` → `true`) that's fine. But for a *restriction* — sandboxing, impersonation, row-level filtering — the OSS fallback is the unrestricted answer, so a temporarily lost/expired token silently downgrades a sandboxed user to full access. **Fail open.** When the EE override is what *decides whether to restrict*, gate it with `:feature :none` (which always routes to the EE body once EE code is loaded) and check the feature explicitly inside, so token loss fails *closed*:
```clojure
;; enterprise/.../sandbox/api/util.clj — the gate that detects whether a user is sandboxed
(defenterprise enforced-sandboxes-for-user
"..."
;; :none so we can decide whether sandboxing is *configured* even when the feature
;; isn't currently available — letting us BLOCK requests that would otherwise be
;; sandboxed, instead of returning the permissive OSS fallback. Fail closed.
:feature :none
[user-id]
...)
```
Reach for this only for the detection/enforcement decision point. Downstream functions that merely *act* on an already-made decision can keep their normal `:feature :sandboxes` gate.
## REST API Endpoints
**Required Elements:**
@@ -94,6 +207,20 @@ This guide covers Clojure and ClojureScript coding conventions for Metabase. See
- All endpoints need Malli schemas for parameters (detailed and complete)
- All new REST API endpoints MUST HAVE TESTS
**Endpoint shape: `api.macros/defendpoint`, four positional arglist:**
```clojure
(api.macros/defendpoint :get "/:key/callback"
"OIDC callback for a specific provider."
[{provider-key :key} :- [:map [:key ProviderKey]]
_query-params
_body
request]
(oidc-integration/sso-callback provider-key request))
```
The arglist is **always 4 positional bindings** in this order: `route-params`, `query-params`, `body`, `request`. Use `_`-prefixed names for unused ones. Each one gets a Malli schema via `:- <schema>` (omit when `_`). The HTTP verb is a keyword (`:get`/`:post`/`:put`/`:delete`), not a symbol. Required as `[metabase.api.macros :as api.macros]`.
**Naming Conventions:**
- Query parameters use kebab-case
@@ -105,6 +232,20 @@ This guide covers Clojure and ClojureScript coding conventions for Metabase. See
- `GET` endpoints should not have side effects (except analytics)
- `defendpoint` forms should be small wrappers around Toucan model code
**Closed response maps:**
Tag response Malli `:map` schemas with `{:closed true}` so the generated OpenAPI / TypeScript types reject extra keys. Open maps emit `additionalProperties: true`, which produces weak frontend types and makes discriminated unions ineffective. Tighten domain types in the same pass (`pos-int?` rather than `:int` when zero branches elsewhere).
```clojure
;; weak
{:status 200 :body [:map [:status [:= :generated]] [:prompt_count :int]]}
;; tight
{:status 200 :body [:map {:closed true}
[:status [:= :generated]]
[:prompt_count pos-int?]]}
```
## MBQL (Metabase Query Language)
**Restrictions:**
@@ -144,10 +285,215 @@ This guide covers Clojure and ClojureScript coding conventions for Metabase. See
**Linter Suppressions:**
- Use proper format for kondo suppressions
- No `#_:clj-kondo/ignore` (keyword form)
The right shape is a **reader-discard map** placed directly above the form being silenced, listing the rule keywords explicitly:
```clojure
#_{:clj-kondo/ignore [:metabase/validate-defendpoint-route-uses-kebab-case
:metabase/validate-defendpoint-has-response-schema]}
(api.macros/defendpoint :post "/api_key" ...)
```
For a single require entry, hang it as metadata on that entry:
```clojure
(:require
^{:clj-kondo/ignore [:deprecated-namespace :discouraged-namespace]}
[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.
**Configurable Options:**
- Don't define configurable options that can only be set with environment variables
- Use `:internal` `defsetting` instead
## Metabase Helpers — Quick Reference
Metabase and its libraries have **many** helper functions to make code more readable. Don't hand-roll things that already exist! Reach for the right helper *the first time*.
Organized by **problem you're solving**, not by namespace.
## "I wrote this — use that instead" cheat sheet
*Authors: prefer the right column. Reviewers: flag the left column in PRs.*
| You wrote | Reach for | When NOT to |
| -------------------------------------------------------------------- | ------------------------------------ | ----------------------------------------------------------------- |
| `(vec (keep f xs))` | `(u/keepv f xs)` | — |
| `(let [x (...)] (side-effect!) x)` | `(u/prog1 (...) (side-effect!))` | — (`<>` anaphor binds the result) |
| `(into {} (map (juxt k identity)) xs)` | `(u/index-by k xs)` | — |
| `(into {} (map (juxt k vf)) xs)` | `(u/index-by k vf xs)` | — |
| `#(compare %2 %1)` | `u/reverse-compare` | — |
| `(:col (t2/select-one [Model :col] …))` | `(t2/select-one-fn :col Model …)` | — |
| `(or (:k m) default)` | `(:k m default)` | **The value can be present-but-nil** (hydrated DB null, etc.) |
| `(let [x (...)] (if x then else))` | `(if-let [x (...)] then else)` | — |
| `(filter #(= :a (:type %)) coll)` + same for `:b` … | `(group-by :type coll)` then dispatch | — |
| `(->> xs (map f) (remove g) (mapv h))` | `(into [] (comp (map f) (remove g) (map h)) xs)` | when readability of the threading wins |
| nested `let` / `if` / `if-let` | `b/cond` with `:let` | a 2-level nest may be clearer as-is |
| `(let [{:keys [k]} arg] …)` as first form of body | destructure in the arg list | when the destructure also references something computed in `let` |
| `(or (:k m) (get m (name k)))` per field | normalize once: `(update-keys m keyword)` then plain `:k` | when you genuinely need both shapes per-field |
## `metabase.util` (commonly aliased `[metabase.util :as u]`)
Sequences / collections:
- `(u/keepv f coll)` — like `keep` but returns a vector (eager).
- `(u/index-by kf coll)` / `(u/index-by kf vf coll)` — `{(kf x) (vf x)}` map.
Strings (locale-safe):
- `(u/lower-case-en s)`, `(u/upper-case-en s)` — DO use these instead of `clojure.string/lower-case`/`upper-case` whenever the result feeds into matching/comparison; the locale-default versions break on Turkish `i`.
- `(u/qualified-name x)` — keyword → `"ns/name"` or `"name"`; symbol → `(name x)`; string → identity.
Control flow:
- `(u/prog1 first-form & body)` — anaphoric. Result of `first-form` is bound to `<>`. Returns first-form's value. Use for "do a thing, side-effect using its result, return the thing."
- `(u/the-id x)` — get an entity id from an int or an instance.
Comparators:
- `(u/reverse-compare x y)` — `(compare y x)`. Pass as a sort comparator: `(sort-by f u/reverse-compare coll)`.
Other:
- `(u/conflicting-keys m1 m2)` — keys present in both with different values.
The full `metabase.util.cljc` is ~1300 lines — when in doubt, grep it.
## `metabase.util.namespaces` (aliased `shared.ns`)
- `(shared.ns/import-fns [other-ns f1 f2] [another-ns f3])` — re-export defns from another ns through the current ns. The `:require [other-ns :as other-ns]` alias **must stay** — clj-kondo may flag it as unused but it's needed at macro expansion. Add a `;; needed for import-fns` comment so it doesn't get auto-stripped.
## Toucan 2 (aliased `[toucan2.core :as t2]`)
Single-field reads (avoids fetching whole rows):
- `(t2/select-one-fn :col Model :id 123)` — projection-friendly: when `f` is a keyword, only that column is fetched. Use instead of `(:col (t2/select-one [Model :col] …))`.
- `(t2/select-fn-set f Model & conditions)` — set of `(f row)` values.
- `(t2/select-fn-vec f Model & conditions)` — vector of `(f row)` values.
- `(t2/select-pks-set Model & conditions)` — set of PKs.
Existence / counts:
- `(t2/exists? Model & conditions)` → boolean.
- `(t2/count Model & conditions)` → long.
Writes:
- `(t2/insert-returning-instances! Model row-or-rows)` — returns the rows with PKs set.
- `(t2/insert-returning-pks! Model row-or-rows)` — just the PKs.
- `(t2/update! Model id-or-conditions changes)`.
- `(t2/delete! Model id-or-conditions)`.
Transactions:
- `(t2/with-transaction [t-conn] body…)` — opens a txn on the app DB conn.
Hydration:
- `(t2/hydrate instances :key1 :key2)` — invokes `:batched-hydrate` methods.
- Define via `(methodical/defmethod t2/batched-hydrate [:model/Foo :the-key] [_ k rows] …)`.
Define a model:
- `(methodical/defmethod t2/table-name :model/Foo [_] :foo_table)`
- `(t2/deftransforms :model/Foo {:col mi/transform-json})` — common: `transform-json`, `transform-secret-value` (encrypts), `transform-keyword`.
## Better-cond (`[better-cond.core :as b]`)
`(b/cond …)` like `cond` but supports interleaved `:let [bindings]` and `:when` clauses. Lets you flatten cascading `let`/`if`/`if-let`/`let` into a linear spine.
```clojure
(b/cond
:let [thread (load-thread id)]
(nil? thread) :not-found
:let [exploration (load-exploration (:exploration-id thread))
reason (gate-check exploration)]
reason
(skip! reason)
:let [pool (build-pool thread)]
(empty? pool) :skip-no-data
:else
(run! thread pool))
```
Use it when a function would otherwise be a staircase of nested forms. Don't reach for it for a single `if`/`let`.
## Schemas — `mr/def` for shared, inline for single-use
When a schema is used in 2+ places or has a name worth documenting, extract it into the registry via `mr/def`:
```clojure
(:require [metabase.util.malli.registry :as mr])
(mr/def ::options
"Options for Pulse channel rendering."
[:map
[:channel.render/include-buttons? {:description "default: false" :optional true} :boolean]])
```
`mr/def` keys are always `::namespaced` keywords; downstream callers reference via the fully-qualified keyword. Single-use schemas stay inline in the `mu/defn`'s `:-` annotation — no need to extract.
## Malli — `metabase.util.malli`
- `(mu/defn my-fn :- :string [x :- :int, y :- [:maybe :string]] …)` — inline schemas; runtime validation in dev, no-op in prod by default.
- `(mu/disable-enforcement & body)` — wrap test/perf-sensitive blocks.
- Common malli schemas: `:int`, `:string`, `:boolean`, `:keyword`, `:map`, `[:maybe T]`, `[:sequential T]`, `[:enum :a :b]`, `[:map [:k T]]`, `pos-int?`, `nat-int?`.
## i18n — `[metabase.util.i18n :refer [tru deferred-tru]]`
- `(tru "Hello {0}" name)` — translate at call time. Use in request-handling code.
- `(deferred-tru "…")` — translate at read time. Use in static contexts: `defsetting :description`, `defn` metadata `:description`, top-level `def`s of user-visible labels.
- ICU MessageFormat: doubled apostrophe for a literal: `(tru "it''s ready")`. Numbered placeholders: `{0}`, `{1}`.
- **Don't translate** developer-only debug strings (REPL helper text, internal logs).
## Logging — `[metabase.util.log :as log]`
- Levels: `trace`, `debug`, `info`, `warn`, `error`.
- Two flavors per level:
- `(log/warn "msg")` or `(log/warn e "msg")` — exception first if present.
- `(log/warnf "fmt %s" arg)` or `(log/warnf e "fmt %s" arg)` — printf-style.
- Don't `(log/warn (format "fmt %s" arg))` — use `warnf`.
## Map / key normalization
When parsing loosely-typed external data (LLM JSON, request bodies) that may have **either** string or keyword keys:
- `(update-keys m keyword)` — top-level keys → keywords (Clojure 1.11+, in `clojure.core`).
- `(clojure.walk/keywordize-keys m)` — recursive (use sparingly; can over-keywordize value strings if they happen to be in nested maps).
- After normalizing once, downstream code uses plain `(:k m)` — don't write `(or (:k m) (get m (name k)))` at every use site.
Other useful map ops:
- `(update-vals m f)` — Clojure 1.11+, in `clojure.core`.
- `(medley.core/map-vals f m)`, `(m/map-keys f m)` — older alternatives. Medley pinned at **1.4** in this repo — `m/index-of` and some other newer fns are NOT available.
## Comparators & sorting
- `(sort-by f u/reverse-compare coll)` — descending.
- Vector comparator: `(sort-by (juxt :primary :secondary) coll)`.
- Use `(- x)` on a primary numeric key to invert: `(sort-by (juxt #(- (:score %)) :id) coll)` (handles ties on ascending `:id`).
## Anti-patterns to avoid
- **`(let [x (do-thing!)] (other-thing! x) x)`** — use `u/prog1`.
- **`(vec (keep …))`, `(vec (map …))`** — use `u/keepv` or a transducer `(into [] (comp …) coll)`.
- **Multiple `filter` passes over the same coll for different `:type`s** — one `(group-by :type coll)`.
- **Per-field string/keyword dual-lookup** — normalize once with `update-keys keyword`.
- **Reaching into another module's tables via raw `:left-join` SQL** — expose a function on the owning model namespace and call that.
- **Snake-case keys on a massaged in-memory map** — appdb-row only. Convert at the parse boundary (e.g., when a json response becomes an internal record).
- **`(double (:k m 0.0))` on a hydrated DB column** — present-but-nil NPEs. Use `(double (or (:k m) 0.0))`.
- **`defmulti` with every impl on one page** — extension story is a fiction. Use a private lookup map + a private fn.
- **`(pos? (count xs))` to test a lazy `xs` for non-emptiness** — `count` forces the whole seq into memory. Use `(seq xs)`. (Rebuilding the seq — `(map f xs)` twice — is the only thing that recomputes; a bound seq caches.)
- **Plain `with-redefs` on a `defn` var in a test** — not parallel-safe; the kondo hook will warn. Use `mt/with-dynamic-fn-redefs`.
- **`(Thread/sleep N)` in an async test** — flake source #1. `(deref p timeout-ms ::timeout)` and assert `not= ::timeout`.
- **Hand-rolled `(str/split host #":")` for origin/host comparison** — mis-handles IPv6. Use `mw.security/parse-url` (or `try-parse-url` for client-controlled input).
- **`(subs (pr-str huge) 0 N)` on a log path** — the multi-MB string is already allocated. Bind `*print-length*`/`*print-level*` around `pr-str` instead.
- **New retry loop / new "find this column" helper / new transform-source-type predicate** — search first. `metabase.util.retry/with-retry`, `metabase.lib.equality/find-matching-column`, and `metabase.transforms.feature-gating/any-transforms-enabled?` already exist (along with many others). Reviewers ask "isn't there already an X for this?" more than any single idiom.
- **Plain `defn` when the function has any real contract** — `mu/defn` (or `mu/defn-`) with `:- schema` on the return and each param is the house default; reserve plain `defn` for trivial dev/helper code.
- **`(:import (java.time …))` + `(LocalDate/now)`** in new code — use `[java-time.api :as t]` + `[metabase.util.date-2 :as u.date]`. Direct `java.time` interop only when a Java API genuinely needs the class.
- **Vanilla `defmethod`** — use `methodical/defmethod` (it takes a docstring; the codebase uses it uniformly).
- **`(when (premium/has-feature? :flag) …)` in code** — gate via `defenterprise` so OSS/EE bodies live in their respective namespaces; never sprinkle runtime feature checks.
- **No `(set! *warn-on-reflection* true)` after the `ns` form** in a new `.clj` file — every `.clj` source file in this repo has it (not `.cljc`).
- **`(ns … (:require [a :as a] [b :as b]))` on one line; `(:import java.io.File java.net.URI)` bare** — both wrong shapes. Requires one per line under `:require`, imports as `(Package Class)` lists.
- **Inventing a fresh `:as` alias for `metabase.util`, `metabase.util.malli`, `metabase.util.log`, `java-time.api`, etc.** — use the canonical alias (see the table in Style Conventions). Mixing aliases makes `grep`-based discovery worse.
## When in doubt
- Run `grep -n "defn " src/metabase/util.cljc | head -80` to scan helpers.
- Run `grep -rn "defmacro\|defn-? [a-z-]*\?\b" src/metabase/util.cljc | head` for predicates.
- Check `medley.core/` if it looks "collection-y" — but **Medley is pinned at 1.4** here; new fns aren't available.
- Search the codebase for an existing use of the pattern you're about to write — if no one else does it, there's usually a helper.

View File

@@ -0,0 +1,69 @@
# React, Redux, and Data-Layer Patterns
## API access and RTK Query
- **Use RTK Query for server data.** Add typed endpoints under `metabase/api` or `metabase-enterprise/api`; don't add ad-hoc `fetch`, service wrappers, or new thunks for ordinary API access.
- **Keep API files transport-focused.** Endpoint files should cover request/response typing, URLs, params, light response normalization, and cache tags — not feature business logic.
- **Use canonical API types.** Prefer `metabase-types/api`; fix or derive missing types instead of casting endpoint results. Refer to API endpoint implementation in Clojure when building new endpoint connections.
- **Tag caches deliberately.** Use `listTag`, `idTag`, `provide*Tags`, and `invalidateTags(error, tags)` where appropriate.
- **Guard missing query inputs.** Use `skipToken` or `skip` until all required inputs exist. Build query requirements where the query is created, not in a downstream render path.
- **Use lazy queries only for events.** Data needed to render a screen belongs in a regular query hook at the owner component/hook.
- **Handle mutations with `unwrap()`.** Prefer `await trigger(args).unwrap()` in submit handlers; otherwise branch on `result.error` immediately.
## Where data should live
- **Server data:** RTK Query cache, not duplicated Redux state.
- **Form state:** Form library or local component state, not global Redux.
- **Transient UI state:** Component state or narrow context, not store-wide flags.
- **Cross-route/global tasks:** Redux slice with public selectors.
- **Derived values:** Selectors or pure helpers, not stored copies of computed data. Memoized if identity is important.
## Redux state modeling
- **Avoid using Redux**. Most problems can be solved with local component state or RTK Query.
- **Use Redux only when needed.** Reach for Redux only when distant parts of the app need durable shared state.
- **Model async status explicitly.** Use a discriminated union or explicit `status`/`isLoading`/`error`; don't infer loaded or failed state from truthy/falsy `data`.
- **Store canonical state only.** Derive filtered lists, labels, permissions, booleans, and display variants in selectors.
- **Read through selectors.** Name selectors after what they return (`getCurrentTask`, `getHasPendingMutation`), not how they compute it.
- **Add missing public actions/selectors.** Don't reach into another feature's private state shape because an action or selector is missing.
- **Use `createSelector` for derived state.** Keep selectors pure, cheap, and stable by reference when consumers depend on identity.
## React hooks and components
- **`useMemo` computes render values.** Side effects belong in `useEffect`; event-driven changes belong in event handlers or mutation callbacks.
- **Keep effects narrow and idempotent.** Include all dependencies, guard inside the effect, and clean up timers/subscriptions. Complex logic should be split to multiple effects or custom hooks, also consider extracting functional pieces.
- **Hooks can be used to encapsulate complex logic.** For example, a hook can normalize data, handle form's state and validation, or a hook can manage a table's pagination and sorting. If component's logic becomes too complex, consider extracting a hook.
- **Hooks orchestrate behavior.** Custom hooks should return a small typed result object: data, loading/error state, and callbacks when relevant.
- **Don't mirror props/query data into state** unless the consumer can edit that local copy. Keep derived render data as such.
- **Use `useCallback` for stable identity needs, but deliberately.** Wrap callbacks passed to memoized children, dependency arrays, context values, or hooks that require stable identity — not every local handler.
- **Memoize object/array props only when identity matters.** Prefer simpler plain values otherwise.
- **Stories for presentational components**. Create Storybook stories for presentational components to test different states and props. Stories live next to the component.
## Performance
- **Optimize only where identity or scale matters.** Prefer clear code first, then add `memo`, `useMemo`, `useCallback`, selectors, virtualization, or split components when render cost, prop identity, or list size justifies it.
- **Keep context values stable and avoid frequent updates.** Values updated often should be avoided in context consumed by many components, or stored by reference with a stable context value and explicit subscriptions/selectors.
- **Read global state high in the tree.** Let parent components select context/Redux/API state, derive the view model, and pass narrow props top-down. But avoid passing props too deep (reconsider if more thatn 2 levels).
- **Avoid unstable props in hot paths.** Don't pass fresh object/array/function literals to memoized children; memoize them or move them outside render when identity matters.
- **Render large lists deliberately.** Use pagination, windowing/virtualization, stable keys, and row-level memoization for large or frequently updating lists.
- **Consider memoization for leaf components.** If the source of data updates often, but the component doesn't need to re-render, consider memoizing it.
## Loading, error, and empty states
- **Every async operation needs loading UI.** Use `LoadingAndErrorWrapper` or `DelayedLoadingAndErrorWrapper` for full-page/panel loading; use disabled controls and inline progress for local actions.
- **Every async operation needs an error branch.** Use wrappers or feature-specific alerts for query errors; use `getErrorMessage(error, fallback)` plus a toast/form error for mutation failures.
- **Empty is its own state.** Render no-results, empty-list, and permission-limited states intentionally; don't let them look like unfinished loading.
- **Combine multiple query states explicitly.** Example: `isLoading = a.isLoading || b.isLoading`; `error = a.error || b.error`.
- **Distinguish first load from refresh.** Use `isLoading` for first-load blockers and `isFetching` for background refresh indicators.
- **Test all async branches.** Cover loading, error, empty, and success states when adding or changing data access.
## Review checklist
- Server data uses a typed RTK Query endpoint with correct cache tags.
- Query inputs are guarded with `skipToken`/`skip` until ready.
- Global state is justified, minimal, and read through selectors.
- Context values are stable; frequently changing values don't force broad re-renders.
- Leaf components stay dumb and receive narrow props from parent containers.
- Loading, error, empty, and success branches are visible and tested.
- Hooks are pure during render; side effects are confined to effects or event handlers.
- Mutation failures are surfaced to people using the UI.

View File

@@ -2,8 +2,8 @@
- **Lint:** `bun run lint-eslint-pure`
- Run ESLint on the codebase
- **Format:** `bun run prettier`
- Format code using Prettier
- **Format:** `bun run format`
- Format code with oxfmt (`oxfmt --write`); use `bun run lint-format-pure` to check without writing
- **Type Check:** `bun run type-check-pure`
- Run TypeScript type checking

View File

@@ -102,3 +102,7 @@ breakage keeps happening, *that* is the signal a comment was warranted.
- End all files with a newline
- When editing tabular code, where the columns line up, try to keep them aligned
- 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`.

View File

@@ -22,10 +22,11 @@ Before starting, determine which mode to use:
3. **(Conditional)** If after reading the spec a specific assertion or selector is **ambiguous** — you can't tell if it's the right anchor, or whether the test actually verifies what its title claims — briefly grep the related component for the test ID / role / text. **Don't read components by default.** Only do this when there's a real signal of confusion in the spec.
4. Scan against the checklist + pattern table below.
5. Number all issues sequentially. Skip nits — only flag what's worth fixing.
6. **Always** finish with the honest e2e-vs-unit breakdown (see the section of that name below). It's part of every report, not an optional add-on.
### When to hand off instead of review
If the spec references an issue (`metabase#NNNNN`) and the user wants to **fix** flakiness or assess whether the test still reproduces the original bug, that's outside the review skill's scope. Point them at `/fix-flakey-test` (or the dedicated flake-fixing workflow), which knows to fetch the issue and the resolving PR's diff. The review skill stays focused on "is this test well-written and conformant" — it doesn't fetch external issue context by default.
If the spec references an issue (`metabase#NNNNN`) and the user wants to **fix** flakiness or assess whether the test still reproduces the original bug, that's outside the review skill's scope. Point them at the dedicated flake-fixing workflow, which knows to fetch the issue and the resolving PR's diff. The review skill stays focused on "is this test well-written and conformant" — it doesn't fetch external issue context by default.
## Review checklist
@@ -194,8 +195,41 @@ Use the pending review workflow:
Each comment body starts with `**Issue N: [Brief title]**`.
## Honest e2e-vs-unit breakdown (always include)
Every report ends with this section. The numbered issues above are about whether the test is *well-written*; this section is about whether it should be an **e2e test at all**. They're orthogonal — a flawless spec can still be paying e2e prices for component-test value, and that's worth saying out loud.
The bar is simple: **an `it()` earns its place in e2e only if it exercises a layer you cannot fake without gutting the test's value.** In this codebase that means one or more of:
- a **real backend query against seeded data** (the assertion depends on the server actually filtering/sorting/bucketing rows, not on a mocked response);
- **real rendering you then interact with** — clicking a charted ECharts SVG element at computed coordinates, drag/hit-testing, drill-through;
- **routing across screens** — navigation, URL param round-trips that the backend then honors, browser back/forward;
- **cross-screen traversal** — list → detail → back, where the value is the seam between screens.
Conversely, a test belongs in **Jest + RTL** (the cheaper layer this repo already uses for component/unit coverage) when its real subject is frontend-only:
- **pure frontend logic** — a bucketing/formatting/derivation decision (e.g. "single-day range → bucket by hour") that has one right answer independent of the backend;
- **render assertions** — "the page mounts N titled cards and an SVG exists." A mocked dataset response + RTL verifies the titles; that an ECharts SVG renders is library behavior, not your logic;
- **state/wiring** — tab → `aria-selected` → active-state, or select → querystring mapping. The *URL gets the param* half is component-level; only the *backend honors the param* half needs e2e.
Write the breakdown in three honest buckets. Ground each call in **which layers the test actually touches**, not in how the test is named:
1. **Genuinely must-be-e2e (keep)** — load-bearing. Name the layer(s) only a browser + backend can verify together.
2. **Defensible-but-narrowable e2e** — justified as integration, but over-split or doing more boots than the coverage requires. Say what to merge.
3. **Should be unit / component tests** — where the real savings are. Name the cheaper layer and what it would assert (often *more precisely* than the e2e test does indirectly).
Then a one-paragraph **bottom line**: what to keep as e2e, what to push down, and — if you pulled CI timing from `e2e/support/timings.json` for the Performance check — roughly how much of that wall time is *earned* by the must-be-e2e set versus paid by the rest.
Rules of engagement so this stays honest, not performative:
- **Don't inflate the keep bucket to look balanced.** If most of the spec is component-test value paying e2e prices, say exactly that. If every test is load-bearing, say that too — a spec where all 12 tests must be e2e is a legitimate outcome, not a failure to find candidates.
- **Be specific.** Cite the `it()` titles and line ranges. "Several tests could be unit tests" is useless; "tests 1/17/18 assert only that N titled cards mount — RTL with a mocked dataset" is actionable.
- **This is advice to the author, not a blocking issue.** It's a recommendation, separate from the numbered issues. Don't renumber it into the issue list.
- **Stay rooted in what exists.** The cheaper layer here is Jest + RTL component/unit tests. Don't invent infrastructure the repo doesn't have, and don't recommend deleting backend-dependent coverage just because part of the test is frontend-only — split it, keep the integration half.
## Final check
1. Trim issues that won't materially help the author.
2. Verify sequential numbering with no gaps.
3. In PR mode, verify each issue was posted as a separate review comment.
4. Verify the honest e2e-vs-unit breakdown is present — it's required in every report, even when the answer is "all of these need to be e2e."

View File

@@ -20,8 +20,8 @@ For EACH styled component, go through every CSS property and ask: "Can this be a
**Properties that ARE style props** (use these, not CSS modules):
- `display` → `display` prop
- `color` → `c` prop (`c="brand"`, `c="text-primary"`)
- `background-color` → `bg` prop (`bg="background-primary"`)
- `color` → `c` prop (`c="core-brand"`, `c="text-primary"`)
- `background-color` → `bg` prop (`bg="background_page-primary"`)
- `font-size` → `fz` prop (`fz="md"`)
- `font-weight` → `fw` prop (`fw="bold"`)
- `line-height` → `lh` prop (`lh="md"`)
@@ -57,7 +57,7 @@ For EACH styled component, go through every CSS property and ask: "Can this be a
align="center" /* style prop */
gap="sm" /* style prop */
p="md" /* style prop */
bg="background-primary" /* style prop */
bg="background_page-primary" /* style prop */
>
```
@@ -149,19 +149,19 @@ Read the `.styled.tsx` file AND every component that imports from it. Understand
For each styled component, apply the Mantine-First Decision Gate above. Then determine the migration target:
| Emotion Pattern | Migration Target |
| ------------------------------------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `styled.div` with only layout/spacing/color | `Box`, `Flex`, `Stack`, or `Group` with style props. **NO CSS module needed.** |
| `styled.div` with flexbox column | `Stack` component with style props |
| `styled.div` with flexbox row | `Flex` or `Group` component with style props |
| `styled.span` / `styled.p` with color/weight/size | **`Text component="span"` with style props** (`c`, `fw`, `fz`). NO CSS module. |
| `styled.div` with hover/focus/pseudo-selectors | **Hybrid**: Mantine component with style props for expressible properties + CSS module class for pseudo-selectors only |
| `styled.div` with media queries (simple spacing/sizing) | **Responsive style props**: `p={{ base: "md", lg: "xl" }}`. NO CSS module. |
| `styled.div` with media queries (complex/non-spacing) | CSS module for the media query parts, style props for the rest |
| `styled.div` with animations/keyframes | CSS module for animation, style props for layout |
| `styled(SomeComponent)` with only color/spacing/flex | **Wrap in Mantine component** with style props: `<Box c="brand" flex="0 0 auto"><Icon /></Box>`, or pass style props if the component accepts them |
| `styled(SomeComponent)` with pseudo-selectors/complex styles | CSS module `className` on the component |
| Dynamic props `styled.div<{ isActive: boolean }>` | Mantine style props for simple toggles (`c={active ? "brand" : "text-primary"}`), `cx()` with CSS module classes for complex state combinations involving pseudo-selectors |
| Emotion Pattern | Migration Target |
| ------------------------------------------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `styled.div` with only layout/spacing/color | `Box`, `Flex`, `Stack`, or `Group` with style props. **NO CSS module needed.** |
| `styled.div` with flexbox column | `Stack` component with style props |
| `styled.div` with flexbox row | `Flex` or `Group` component with style props |
| `styled.span` / `styled.p` with color/weight/size | **`Text component="span"` with style props** (`c`, `fw`, `fz`). NO CSS module. |
| `styled.div` with hover/focus/pseudo-selectors | **Hybrid**: Mantine component with style props for expressible properties + CSS module class for pseudo-selectors only |
| `styled.div` with media queries (simple spacing/sizing) | **Responsive style props**: `p={{ base: "md", lg: "xl" }}`. NO CSS module. |
| `styled.div` with media queries (complex/non-spacing) | CSS module for the media query parts, style props for the rest |
| `styled.div` with animations/keyframes | CSS module for animation, style props for layout |
| `styled(SomeComponent)` with only color/spacing/flex | **Wrap in Mantine component** with style props: `<Box c="core-brand" flex="0 0 auto"><Icon /></Box>`, or pass style props if the component accepts them |
| `styled(SomeComponent)` with pseudo-selectors/complex styles | CSS module `className` on the component |
| Dynamic props `styled.div<{ isActive: boolean }>` | Mantine style props for simple toggles (`c={active ? "core-brand" : "text-primary"}`), `cx()` with CSS module classes for complex state combinations involving pseudo-selectors |
### Step 3: Create CSS Module (if needed)
@@ -170,19 +170,19 @@ Create `ComponentName.module.css` alongside the component file:
```css
/* Use design system tokens — NEVER raw color/spacing values */
.root {
border: 1px solid var(--mb-color-border);
border: 1px solid var(--mb-color-border-neutral);
border-radius: var(--mantine-radius-md);
background-color: var(--mb-color-background-primary);
background-color: var(--mb-color-background_page-primary);
}
/* Conditional states as separate classes, combined with cx() */
.active {
background-color: var(--mb-color-brand);
background-color: var(--mb-color-core-brand);
color: var(--mb-color-text-primary-inverse);
}
.disabled {
color: var(--mb-color-text-tertiary);
color: var(--mb-color-text-disabled);
pointer-events: none;
}
@@ -191,8 +191,8 @@ Create `ComponentName.module.css` alongside the component file:
cursor: pointer;
&:hover {
color: var(--mb-color-brand);
background-color: var(--mb-color-background-hover);
color: var(--mb-color-core-brand);
background-color: var(--mb-color-background_surface-hover);
}
}
@@ -255,9 +255,9 @@ Remove the old styled file entirely. Remove all imports of it from other files.
**Colors** (`c`, `bg`):
- Text: `"text-primary"`, `"text-secondary"`, `"text-tertiary"`
- Background: `"background-primary"`, `"background-secondary"`, `"background-hover"`
- Brand: `"brand"`, `"error"`, `"success"`, `"warning"`
- Text: `"text-primary"`, `"text-secondary"`, `"text-disabled"`
- Background: `"background_page-primary"`, `"background_page-secondary"`, `"background_surface-hover"`
- Brand: `"core-brand"`, `"feedback-negative"`, `"feedback-positive"`, `"feedback-warning"`
**Typography** (`fz`, `fw`, `lh`, `ta`, `ff`):
@@ -279,11 +279,11 @@ Remove the old styled file entirely. Remove all imports of it from other files.
**Colors** — `var(--mb-color-<name>)`:
- `--mb-color-text-primary`, `--mb-color-text-secondary`, `--mb-color-text-tertiary`
- `--mb-color-background-primary`, `--mb-color-background-secondary`, `--mb-color-background-hover`
- `--mb-color-text-primary`, `--mb-color-text-secondary`, `--mb-color-text-disabled`
- `--mb-color-background_page-primary`, `--mb-color-background_page-secondary`, `--mb-color-background_surface-hover`
- `--mb-color-border`, `--mb-color-border-strong`, `--mb-color-border-subtle`
- `--mb-color-brand`, `--mb-color-brand-hover`
- `--mb-color-error`, `--mb-color-success`, `--mb-color-warning`
- `--mb-color-core-brand`, `--mb-color-core-brand-hover`
- `--mb-color-feedback-negative`, `--mb-color-feedback-positive`, `--mb-color-feedback-warning`
- `--mb-color-shadow`, `--mb-color-focus`
- `--mb-color-accent0` through `--mb-color-accent7`
@@ -398,13 +398,13 @@ export const Wrapper = styled.div`
```tsx
export const Item = styled.div<{ isSelected: boolean; disabled: boolean }>`
color: ${(props) =>
props.disabled ? color("text-tertiary") : color("text-primary")};
props.disabled ? color("text-disabled") : color("text-primary")};
background-color: ${(props) =>
props.isSelected ? color("brand") : "transparent"};
props.isSelected ? color("core-brand") : "transparent"};
cursor: ${(props) => (props.disabled ? "default" : "pointer")};
&:hover {
color: ${(props) => !props.disabled && color("brand")};
color: ${(props) => !props.disabled && color("core-brand")};
}
`;
```
@@ -418,20 +418,20 @@ export const Item = styled.div<{ isSelected: boolean; disabled: boolean }>`
cursor: pointer;
&:hover {
color: var(--mb-color-brand);
color: var(--mb-color-core-brand);
}
}
.selected {
background-color: var(--mb-color-brand);
background-color: var(--mb-color-core-brand);
}
.disabled {
color: var(--mb-color-text-tertiary);
color: var(--mb-color-text-disabled);
cursor: default;
&:hover {
color: var(--mb-color-text-tertiary);
color: var(--mb-color-text-disabled);
}
}
```
@@ -457,7 +457,7 @@ When a styled component wraps another component, first check if the styles can b
export const CardIcon = styled(Icon)`
display: block;
flex: 0 0 auto;
color: var(--mb-color-brand);
color: var(--mb-color-core-brand);
`;
export const CardTitle = styled(Ellipsified)`
@@ -471,7 +471,7 @@ export const CardTitle = styled(Ellipsified)`
**After — style props on Mantine wrapper (preferred when ALL properties are expressible):**
```tsx
<Box display="block" flex="0 0 auto" c="brand">
<Box display="block" flex="0 0 auto" c="core-brand">
<Icon {...icon} />
</Box>
<Box c="text-primary" fz="md" fw="bold" ml="md">
@@ -483,13 +483,13 @@ export const CardTitle = styled(Ellipsified)`
```css
.icon {
color: var(--mb-color-brand);
color: var(--mb-color-core-brand);
width: 1.5rem;
height: 1.5rem;
cursor: pointer;
&:hover {
color: var(--mb-color-brand-hover);
color: var(--mb-color-core-brand-hover);
}
}
```
@@ -570,12 +570,12 @@ export const Spinner = styled.div`
### Pattern 6: color() Function → CSS Variables
| Emotion (JS) | CSS Module | Mantine Style Prop |
| ----------------------- | ------------------------------------------------------------ | --------------------------- |
| `color("brand")` | `var(--mb-color-brand)` | `c="brand"` or `bg="brand"` |
| `color("text-primary")` | `var(--mb-color-text-primary)` | `c="text-primary"` |
| `color("border")` | `var(--mb-color-border)` | N/A (use CSS module) |
| `alpha("brand", 0.2)` | `color-mix(in srgb, var(--mb-color-brand), transparent 80%)` | N/A (use CSS module) |
| Emotion (JS) | CSS Module | Mantine Style Prop |
| -------------------------- | ----------------------------------------------------------------- | ------------------------------------- |
| `color("core-brand")` | `var(--mb-color-core-brand)` | `c="core-brand"` or `bg="core-brand"` |
| `color("text-primary")` | `var(--mb-color-text-primary)` | `c="text-primary"` |
| `color("border-neutral")` | `var(--mb-color-border-neutral)` | N/A (use CSS module) |
| `alpha("core-brand", 0.2)` | `color-mix(in srgb, var(--mb-color-core-brand), transparent 80%)` | N/A (use CSS module) |
### Pattern 7: Responsive Spacing/Sizing → Responsive Style Props (NOT CSS Media Queries)
@@ -627,13 +627,13 @@ export const Bar = styled.div<{ width: number }>`
If existing code already uses `CS` classes and you're not migrating that specific code, leave them alone. But when migrating Emotion → Mantine, replace with the proper alternative:
| Instead of `CS.*` | Use |
| ------------------- | ------------------------------------------------------- |
| `CS.overflowHidden` | CSS module: `overflow: hidden` |
| `CS.cursorPointer` | CSS module: `cursor: pointer` |
| `CS.flex1` | Style prop: `flex={1}` |
| `CS.flexNoShrink` | Style prop: `flex="0 0 auto"` |
| `CS.textBrandHover` | CSS module: `&:hover { color: var(--mb-color-brand); }` |
| Instead of `CS.*` | Use |
| ------------------- | ------------------------------------------------------------ |
| `CS.overflowHidden` | CSS module: `overflow: hidden` |
| `CS.cursorPointer` | CSS module: `cursor: pointer` |
| `CS.flex1` | Style prop: `flex={1}` |
| `CS.flexNoShrink` | Style prop: `flex="0 0 auto"` |
| `CS.textBrandHover` | CSS module: `&:hover { color: var(--mb-color-core-brand); }` |
### Pattern 10: Shared Emotion Styles Across Files → Shared CSS Module + cx()
@@ -759,7 +759,7 @@ import S from "./ComponentName.module.css"; // only if CSS module is needed
- [ ] The `.styled.tsx` file is deleted
- [ ] All imports of the deleted styled file are updated
- [ ] No static inline styles — `style={{ }}` used only for truly dynamic runtime values
- [ ] All colors use design tokens (`c="brand"`, `var(--mb-color-brand)`), not raw hex/rgb
- [ ] All colors use design tokens (`c="core-brand"`, `var(--mb-color-core-brand)`), not raw hex/rgb
- [ ] All spacing uses design tokens (`p="md"`, `var(--mantine-spacing-md)`), not arbitrary px values — hardcoded `rem`/`px` literals snapped to the nearest token (see mapping table above)
- [ ] All border-radius values use radius tokens (`var(--mantine-radius-md)`), not hardcoded `0.5rem`
- [ ] All font sizes use font-size tokens (`fz="md"`, `var(--mantine-font-size-md)`), not hardcoded `1rem`

View File

@@ -0,0 +1,244 @@
---
name: metabase-ui-component-from-figma
description: Update or build a Metabase design-system component (frontend/src/metabase/ui — Chip, Badge, Alert, Switch, etc.) to match a Figma spec described in a Linear issue. Use when a ticket asks to restyle an existing `metabase/ui` component or implement a new one from Figma. Covers: checking out the issue, mapping the component (usage/blast radius for an existing one, or scaffolding a new one), building a Storybook showcase matrix (before styling for existing components, after for new ones), styling from exact Figma tokens while iterating with the user, and committing + migrating call sites LAST.
---
# Metabase UI component from Figma
End-to-end workflow for bringing a `metabase/ui` (Mantine) component in line with a Figma design, driven by a Linear ticket.
The golden rule (existing components): **build the Storybook showcase before changing any component styles.** Build it while the old styles are still in place — so the team can see the current component at a glance and get accustomed to it before the migration, then watch it light up as you restyle. You end up with a visual-regression (Loki) candidate either way. A **new** component has nothing to render until it's built, so this rule doesn't apply to create mode — there the order flips: implement and style the component first, then build its showcase to present the result.
This is a frontend task — also load **typescript-write** (and **typescript-review** before handing off).
## Two modes
The ticket is one of two shapes; identify which up front, because Phase 2 differs:
- **Update an existing component** — the component already exists with call sites, either in `metabase/ui` *or* as a legacy component elsewhere (e.g. `frontend/src/metabase/common/components/`, possibly Emotion styled-components) that this ticket also migrates into `metabase/ui`. The risk is *regression* (call sites, behavior), so you map usage and lock behavior with tests before touching it.
- **Create a new component** — nothing equivalent exists anywhere yet. Rarer. The risk is *API design*, so you scaffold the component and its public surface first.
Phases 1, 2, 5 and 6 are shared. The middle two differ in **order**: update mode builds the showcase (Phase 3) *before* styling (Phase 4); create mode does the reverse — implement and style first, then build the showcase as the last step — because there's nothing to render until the component exists.
---
## Phase 1 — Check out the issue
1. Fetch the Linear issue with the Linear MCP `get_issue`.
2. Pull from it:
- **Figma link(s)** — extract the `node-id` (`?node-id=250-13588` → `250-13588`) and `fileKey` (the `/design/<fileKey>/…` segment).
- **`gitBranchName`** — switch to it if not already there.
- **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.
## Phase 2 — Understand the component
### Mode: update an existing component
1. Locate the component dir (typically containing `Component.config.ts` or `Component.tsx`, `Component.module.css`, `Component.stories.tsx`, `index.ts`). A ticket may also be **migrating a legacy component** — if it still uses Emotion styled-components, reach for the **emotion-migrate** skill.
2. Map every usage across `frontend/src` and `e2e` (JSX `<Component`, sub-components like `Component.Group`, and wrapper components).
3. Write findings to **`local/<TICKET>-<component>-usage-findings.md`**, one entry per usage: code location (`file:line`), short context, and **non-standard usage** (excessive customization, inline styling, invalid/legacy props). Invalid props are a signal that call sites will need migrating in Phase 6. This doc **stays** — the user walks it at the end to verify each real usage still looks right.
4. State the blast radius plainly: how many call sites, where, and whether they're confined.
5. **Lock behavior with tests before changing anything — when warranted.** Only for components that have **custom interactive behavior** (their own event handlers, state, keyboard logic, controlled/uncontrolled wiring). Add unit tests covering that current API/behavior so a regression shows up as a failing test. **Skip tests for thin Mantine wrappers** — don't test built-in Mantine behavior, and a pure visual restyle is covered by the showcase/Loki, not unit tests.
### Mode: create a new component
1. Decide whether it wraps a Mantine primitive (most common — extend it via a `.config.ts` using `<Mantine>.extend({...})` and theme registration) or is bespoke. Prefer wrapping Mantine.
2. Scaffold the component dir + its public surface: `Component.tsx`/`Component.config.ts`, `Component.module.css`, `Component.stories.tsx`, `index.ts`, and wire the export through the group barrel and the `metabase/ui` barrel.
3. There are no call sites to map yet; instead note the intended usage from the ticket so the eventual showcase reflects real props.
4. **Order note:** for a new component, implement and style it (Phase 4) first, *then* build the showcase (Phase 3) to present the finished result — there's nothing to render until it exists. The phases below are written update-first; just run 4 before 3 in create mode.
## Phase 3 — Build the Storybook showcase
Goal: one story that shows **every state at a glance**, themeable, suitable as a Loki visual-regression test. **Update mode: build this before Phase 4, while the old styles are still in place. Create mode: do this after Phase 4**, once the component exists to render.
### Reusable showcase helpers
Use the shared, Storybook-only primitives in **`frontend/src/metabase/ui/stories/showcase/`**: `StoryShowcase` (titled panel), `StorySection`, `StoryRow`, and `StoryJsx` (monospace JSX with light syntax highlighting via `tokenizeJsx`). Extend the set only when a new pattern is genuinely reusable.
### Derive the matrix from the component's full state space
Enumerate **all** the states the component can be in — every supported variant, size, and interaction/selection state (from its props/types and the design-system API, not merely the subset the issue happens to mention) — then cross-reference with the Figma spec and build the matrix on that. Don't omit a supported state because the ticket didn't list it; don't invent an axis Figma doesn't show (e.g. a static component has no hover/pressed).
**Exclude theme from the matrix.** Figma usually models light/dark as a component *property* (because it doesn't use variable modes), but theme is **not** a real component prop in the app — it's global. So never make theme a matrix axis or column; drive light/dark with the global Storybook `theme` toggle instead (see below).
Typical layout (mirrors the Figma component sheet): a `StoryShowcase` title, then a single **CSS-grid matrix** — state labels down the left column, one column per axis-combination (e.g. `variant × size`), each column headed by the real JSX usage via `StoryJsx`. Use `gridTemplateColumns: \`<labelWidth> repeat(N, max-content)\`` with a `React.Fragment` per row.
### Theme: use the global toggle, render ONE copy
Render the showcase once and let Storybook's global `theme` control (defined in `.storybook/preview.tsx`) switch light/dark. Do **not** render light and dark side by side: Metabase bakes per-scheme hex into `--mantine-color-*` at `:root`, and Mantine color tokens follow the global scheme — a nested scheme wrapper won't re-scope them.
### Forcing hover/pressed for the matrix
Use **`storybook-addon-pseudo-states`** (registered in `.storybook/main.ts`); don't add `data-force-*` hooks to component CSS. Set `parameters.pseudo` to force states per cell. Two things make or break it:
1. **Aim the selector at the element the pseudo-class actually sits on**, which for a Mantine component is often an inner slot, not the root. A string/array value applies `.pseudo-<state>` to the matched element, so it must match that slot. Import the CSS-module class (`S.<Slot>`) to target it.
2. **Land your per-cell hook on the root via the factory's root-props slot** (e.g. `wrapperProps`), because Mantine forwards top-level `data-*`/rest props to an inner element, not the root. Check the component's `.d.ts` for the right slot.
The addon toolbar toggle keeps working independently (it forces every rule in the story).
### Example: a finalized matrix story
Illustrative — adapt the axes and states to the component you're working on. This is the shape the pieces above add up to (state labels on the left, one column per `variant × size`, forced hover/pressed via `parameters.pseudo`, the root hook on `wrapperProps`, controls scoped to the meaningful knobs):
```tsx
import type { StoryFn } from "@storybook/react";
import { Fragment } from "react";
import { Box, Chip, type ChipProps, Text } from "metabase/ui";
import { StoryJsx, StoryShowcase } from "metabase/ui/stories/showcase";
import S from "./Chip.module.css";
// Axes derived from the component's API (here: variant × size).
const COLUMNS = [
{ variant: "light", size: "sm" },
{ variant: "light", size: "md" },
{ variant: "filled", size: "sm" },
{ variant: "filled", size: "md" },
] as const;
// Every state the component supports; `id` doubles as the pseudo-state hook.
const STATES = [
{ id: "default", label: "Default" },
{ id: "hover", label: "Hover" },
{ id: "pressed", label: "Pressed" },
{ id: "selected", label: "Selected", checked: true },
{ id: "hover-selected", label: "Hover selected", checked: true },
{ id: "disabled", label: "Disabled", disabled: true },
];
// Force hover/pressed by targeting the slot the pseudo-class sits on (.ChipLabel).
const labelSelector = (id: string) => `[data-state-row="${id}"] .${S.ChipLabel}`;
const Overview: StoryFn<ChipProps> = ({ children }) => (
<StoryShowcase title="Chip">
<Box
style={{
display: "grid",
gridTemplateColumns: `9rem repeat(${COLUMNS.length}, max-content)`,
columnGap: "2rem",
rowGap: "1rem",
alignItems: "center",
}}
>
<div />
{COLUMNS.map(({ variant, size }) => (
<StoryJsx
key={`${variant}-${size}`}
>{`<Chip variant="${variant}" size="${size}" />`}</StoryJsx>
))}
{STATES.map((state) => (
<Fragment key={state.id}>
<Text size="sm" c="text-secondary">
{state.label}
</Text>
{COLUMNS.map(({ variant, size }) => (
<Chip
key={`${variant}-${size}`}
wrapperProps={{ "data-state-row": state.id }} // hook on the ROOT
variant={variant}
size={size}
checked={state.checked ?? false}
disabled={state.disabled ?? false}
onChange={() => {}}
>
{children}
</Chip>
))}
</Fragment>
))}
</Box>
</StoryShowcase>
);
export const OverviewStory = {
render: Overview,
parameters: {
pseudo: {
hover: ["hover", "hover-selected"].map(labelSelector),
active: ["pressed"].map(labelSelector),
},
controls: { include: ["children", "theme"] },
},
};
```
### Story conventions
- Keep an interactive default story plus the matrix story.
- Restrict `argTypes` to the supported API (e.g. only the sizes the DS uses).
- **Scope controls per story.** A static matrix should hide knobs it ignores: `parameters.controls = { include: [...] }` (or `{ disable: true }`). Wire any kept knob (e.g. `children`) through to the cells so it does something.
- `loki.config.js` has a `storiesFilter`; check it before renaming a story that's already covered.
Validate: `bun run lint-eslint-pure -- <files>` and `bun run type-check-pure`.
### Optional: verify in the browser yourself
If a browser-driving MCP is connected (e.g. **chrome-devtools-mcp** or **playwright-mcp**: `navigate_page`, `take_screenshot`, `take_snapshot`, `evaluate_script`, `resize_page`), use it to check your own work against the running Storybook (`http://localhost:6006/iframe.html?id=<story-id>`, the kebab-cased title + story). Screenshot for a visual read; `evaluate_script`/`take_snapshot` to confirm DOM facts (a hook landed on the root, pseudo classes applied, a resolved `--mb-color-*`). This is a **convenience, never a requirement** — without it, rely on the user's visual check (and you may suggest installing the plugin). Storybook is usually already running; don't start it. (Screenshot writes may be sandboxed to the repo root — save under `local/` then `mv`.)
Pause here and let the user look. Iterate on layout/spacing only — **no component style changes yet.**
## Phase 4 — Style the component from Figma
Now change the component's `.config.ts` / `.module.css`. Get **exact tokens from Figma** — never eyeball hex from a screenshot.
### Figma desktop MCP is required for tokens
`get_screenshot` works by `nodeId`, but `get_variable_defs`, `get_design_context`, and `get_metadata` read the **current selection in the Figma desktop app** via the **Dev Mode MCP server**. If they error with "nothing selected" or the server isn't connected, **prompt the user** to enable the Dev Mode MCP server (Switch to Dev Mode → MCP section in right sidebar) and select the relevant layer(s). Don't pixel-sample a screenshot as a substitute.
### Extract and map tokens
1. `get_metadata` on the spec frame for the node id + name of each variant/size/state symbol.
2. `get_variable_defs` per symbol for exact colors, spacing, radius, font.
3. `get_design_context` (forceCode) on one symbol for exact CSS dimensions (padding, gap, icon size). It may ask about Code Connect — skip that.
4. **Use the semantic token names `get_variable_defs` returns.** An up-to-date spec binds each property to a semantic token (a role like `text/hover`, `background/selected`); match it to the corresponding `--mb-color-*` key (key list: `frontend/src/metabase/ui/colors/types/color-keys.ts`) and use it directly — one definition then works in both themes. Sanity-check the resolved shade against `colors/constants/themes/light.ts` / `dark.ts` and `base-colors.ts`. Caveat: returned *values* may be the wrong mode for dark symbols — trust the variable **names**, not the dark hex.
### Color rules — semantic tokens only, NO `color-mix`, NO primitives
Per `docs/developers-guide/frontend.md` ("Colors"): every color must be a **semantic** `--mb-color-*` token. No literal hex, and no `color-mix` in component CSS to fake a shade/alpha.
**Guardrail:** if `get_variable_defs` returns a **primitive ramp** (e.g. `Orion-Alpha/10`, `Ocean/60` — a ramp + number, not a role) bound directly to a property, do **not** translate it to a ramp, hardcode hex, or `color-mix` your way to it. **Stop and flag it to the user** with the specific property/state — it's a design-side gap (bind to a semantic token, or add one). Resume once the spec exposes a semantic token.
### Non-color tokens — flag scale mismatches too
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.
### Mantine implementation notes (reference)
General gotchas when extending Mantine components — adapt per component:
- **Know which slot each data-attribute lands on.** Mantine puts state attributes on specific slots (e.g. `data-variant` on the root, `data-checked`/`data-disabled` on an inner slot). Scope rules accordingly, usually through a root `classNames.root` class.
- **Out-specify Mantine's built-in variant CSS.** It styles slots at `.m_*:not([data-disabled])` specificity; a descendant combinator through your root class wins. Avoid chained `:not()` (stylelint's `selector-not-notation: complex` rejects it, and combining lowers specificity) — gain specificity via the root class / attributes instead.
- **Size via a `vars` resolver**, returning only Mantine's typed vars for that component (custom var names fail type-check). Map size → vars in `.config.ts`.
- **Built-in icons use `currentColor`**, so they inherit the slot's text color.
- For text on a brand fill, follow the existing convention (`text-primary-inverse`) unless the user wants pure white; flag the dark-theme implication.
After edits: `npx stylelint <css>`, `LINT_CSS_MODULES=true bun run lint-eslint-pure -- <files>`, `bun run type-check-pure`.
## Phase 5 — Iterate with the user
Show the result in the running Storybook and address feedback (color, spacing, radius, shadow, missing/extra state). Surface deliberate deviations explicitly so the user can veto them. If a browser MCP is connected, screenshot the matrix in both themes to catch issues first. **Do not commit until the user is satisfied.**
## Phase 6 — Commit, then migrate call sites
Only after sign-off:
1. Commit when the user explicitly asks; commit only relevant files (exclude build artifacts and the gitignored `local/` doc). Follow the user's commit conventions.
2. **Update mode:** migrate the call sites flagged in Phase 2 if the restyle requires it (e.g. invalid/renamed props). Be surgical with bulk find/replace — a blanket prop rename can hit unrelated components; verify each hit is the target. **Create mode:** confirm the public export is wired through the barrels and used as the ticket intends.
3. Leave the findings doc in place for the user's manual verification pass.
---
## Checklist
- [ ] Linear issue fetched; Figma node/fileKey + `gitBranchName` extracted; on the right branch; mode (update vs create) decided.
- [ ] **Update:** usage + blast radius in `local/<TICKET>-<component>-usage-findings.md`; behavior locked with unit tests **if** the component has custom interactive logic (skip for thin Mantine wrappers / pure restyles). **Create:** component scaffolded with its public surface and barrel exports.
- [ ] 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.
- [ ] Iterated with the user until satisfied.
- [ ] Committed (when asked); call sites migrated/verified (update) or export wired (create); findings doc handed back.

View File

@@ -1,20 +1,33 @@
---
name: typescript-review
description: Review TypeScript and JavaScript code changes for compliance with Metabase coding standards, style violations, and code quality issues. Use when reviewing pull requests or diffs containing TypeScript/JavaScript code.
allowed-tools: Read, Grep, Bash, Glob
allowed-tools: Read, Grep, Bash, Glob, Skill
---
# TypeScript/JavaScript Code Review Skill
@./../_shared/typescript-commands.md
@./../_shared/react-redux-patterns.md
## Code Review Guidelines
## Main Focus
Review pull requests with a focus on:
**Primary standard: the [`typescript-write`](../typescript-write/SKILL.md) skill.** Load it first — it defines the authoring rules this review enforces, alongside `frontend/CLAUDE.md` and `docs/developers-guide/frontend.md`.
- Readability and maintainability
- Appropriate test coverage
- Compliance with project coding standards and conventions
- Code quality and best practices
- Type safety and proper TypeScript usage
- React best practices (when applicable)
Adherence to `typescript-write` is the **highest-priority** review dimension: rank any violation of its provisions above all other findings. Treat its **no-`any` hard rule** (no explicit *or* implicit `any` in new code) as **blocking**, and verify it with the LSP rather than by eye.
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.
2. Compliance with `frontend/CLAUDE.md`.
3. Readability and maintainability.
4. Appropriate test coverage.
## Blind spots — act as the missing reviewer
These rarely surface in team reviews, so this skill should raise them. They are **additive** — raise them, but rank them below `typescript-write` violations:
- **Accessibility.** Interactive elements need keyboard support, focus management, and accessible names. Flag missing `aria-label`/`aria-labelledby`, non-semantic click targets, modals without focus trap, icon-only buttons without labels, and form inputs without a linked label.
- **Performance.** Flag areas that scale poorly and aren't memoized; inline object/array literals passed to memoized children; effects that fire on every batch of a progressive load; and new dependencies added to hot paths.
- **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.

View File

@@ -7,3 +7,77 @@ description: Write TypeScript and JavaScript code following Metabase coding stan
@./../_shared/development-workflow.md
@./../_shared/typescript-commands.md
@./../_shared/react-redux-patterns.md
## No `any` — hard rule
- **New code must not introduce `any`, explicit or implicit.** No `any` annotations, no `as any` / `as unknown as`, no untyped parameters or returns that infer `any`, no implicitly-`any` destructures or array/object literals.
- **Untyped third-party / boundary values** must be typed at the boundary (a declared type, `unknown` + type guard, or a small typed wrapper) — never let `any` propagate inward.
- **Mandatory LSP verification.** After writing or editing any TS/TSX, inspect the changed symbols with the TypeScript Language Server (hover to read inferred types; `goToDefinition` to confirm sources) and run the project type-check.
## Type tightening
- **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.
- **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.
- **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.
## 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.
- **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.
- **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";
const result = match(status)
.with({ type: "loading" }, () => <Spinner />)
.with({ type: "error", error: P.select() }, (error) => <Error message={error.message} />)
.with({ type: "success", data: P.select() }, (data) => <Content data={data} />)
.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.
- **Type async and error states explicitly** (a discriminated union or the data-layer's typed result) — never leave loading/error/empty implicit.
## 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.
- **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.
- **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`).
## Code structure and organization
- **Prioritize reusability over duplication**. The codebase already has many utility functions — leverage them. If you introduce duplicated logic, extract it to a shared utility.
- **Generic helpers do not belong in feature folders**. Promote to a shared utility.
- **Keep functions small and single-purpose**. A 100+ line function is hard to review — split into focused named helpers, each with one responsibility and a minimal dependency surface. When necessary, cover with unit tests.
- **Extract distinct complex JSX into named components**. Choose same-file vs separate-file by reuse, coupling, testability, and readability.
## Comments
- **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

@@ -61,6 +61,7 @@
:metabase/check-def-check-not-uppercase-name {:level :warning}
:metabase/check-def-no-underscores {:level :warning}
:metabase/check-me-humanize {:level :warning}
:metabase/check-testing-not-empty {:level :warning}
:metabase/defsetting-must-specify-export {:level :warning}
:metabase/defsetting-namespace {:level :warning}
:metabase/discourage-millis-duration {:level :warning}
@@ -178,14 +179,26 @@
clojure.core.async/take!
clojure.core.async/to-chan!
clojure.core.async/to-chan!!
metabase.ai-tracing.core/record!
metabase.api.macros.defendpoint.tools-manifest/assert-optional-fields-nullable!
metabase.channel.core/send!
metabase.channel.render.pdf/draw-too-large!
metabase.channel.render.pdf/draw-no-results!
metabase.channel.render.pdf/render-card-cell!
metabase.channel.render.pdf.font/load-fonts!
metabase.warehouses.models.database/assert-not-h2!
metabase.driver.sql-jdbc.execute/execute-prepared-statement!
metabase.mcp.usage/record-mcp-session!
metabase.mcp.usage/record-mcp-session-end!
metabase.mcp.usage/record-mcp-tool-call!
metabase.notification.models/create-notification!
metabase.oauth-server.core/reset-provider!
metabase.pulse.send/send-pulse!
metabase-enterprise.transforms-python.python-runner-test/execute!
;; MCP usage tests isolate their rows by unique keys (session id / tool name / duration /
;; client version) and clean up only those, so these deletes are safe in parallel.
metabase-enterprise.mcp.usage-test/cleanup!
metabase-enterprise.mcp.usage-test/cleanup-calls!
;; Workspace isolation functions are safe in parallel tests because they operate on
;; isolated, test-specific workspaces and databases that don't affect other tests
metabase-enterprise.workspaces.isolation/destroy-workspace-isolation!
@@ -247,9 +260,6 @@
;; misc config for built-in linters
;;
:invalid-arity {:skip-args [metabase.util.match/match-one
metabase.util.match/match-many
metabase.util.match/replace]} ; TODO (cam): can we fix these?
:refer-all {:level :warning, :exclude [clojure.test]}
:unused-referred-var {:exclude {compojure.core [GET DELETE POST PUT]}}
@@ -269,7 +279,6 @@
(metabase.util.match/match-many)
(metabase.util.match/replace-in)
(metabase.util.match/replace)
(metabase.driver-api.core/match)
(metabase.driver-api.core/match-one)
(metabase.driver-api.core/match-many)
(metabase.driver-api.core/replace)
@@ -444,6 +453,10 @@
instaparse.core/defparser clojure.core/def
metabase-enterprise.action-v2.test-util/with-test-tables! clojure.core/let
metabase-enterprise.content-translation.routes-test/with-new-secret-key! clojure.core/fn
metabase-enterprise.entity-retrieval.reconcile-test/with-isolated-index clojure.core/fn
metabase-enterprise.mfa.enrollment-flow-test/with-fresh-user-session! clojure.core/fn
metabase-enterprise.mfa.login-flow-test/with-enrolled-rasta! clojure.core/fn
metabase-enterprise.mfa.recovery-codes-test/with-confirmed-enrollment! clojure.core/fn
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
@@ -460,6 +473,7 @@
metabase.channel.impl.http-test/with-captured-http-requests clojure.core/fn
metabase.channel.impl.http-test/with-server clojure.core/let
metabase.collections.models.collection-test/with-collection-in-location clojure.core/let
metabase.collections.test-utils/with-library clojure.core/fn
metabase.driver.mongo.connection/with-mongo-client clojure.core/let
metabase.driver.mongo.connection/with-mongo-database clojure.core/let
metabase.driver.mongo.query-processor/mongo-let clojure.core/let
@@ -473,6 +487,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.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
metabase.premium-features.settings/define-premium-feature clojure.core/def
@@ -539,6 +554,7 @@
{:analyze-call
{cljs.test/deftest hooks.clojure.test/deftest
cljs.test/is hooks.clojure.test/is
cljs.test/testing hooks.clojure.test/testing
cljs.test/use-fixtures hooks.clojure.test/use-fixtures
clojure.core/def hooks.clojure.core.def/lint-def
clojure.core/definterface hooks.clojure.core.def/lint-def
@@ -557,6 +573,7 @@
clojure.core/- hooks.metabase.util.timing/discourage-millis-duration
clojure.test/deftest hooks.clojure.test/deftest
clojure.test/is hooks.clojure.test/is
clojure.test/testing hooks.clojure.test/testing
clojure.test/use-fixtures hooks.clojure.test/use-fixtures
malli.error/humanize hooks.malli.error/humanize
metabase-enterprise.advanced-permissions.models.permissions.application-permissions-test/with-new-group-and-current-graph hooks.common/with-two-top-level-bindings
@@ -572,7 +589,7 @@
metabase.api.common.internal-test/with-jetty-server hooks.common/with-one-binding
metabase.api.macros/defendpoint hooks.metabase.api.macros/defendpoint
metabase.app-db.schema-migrations-test.impl/test-migrations hooks.metabase.app-db.schema-migrations-test.impl/test-migrations
metabase.channel.render.js.svg/with-static-viz-context hooks.common/with-one-top-level-binding
metabase.channel.render.js.pool/with-static-viz-context hooks.common/with-one-top-level-binding
metabase.channel.template.handlebars-helper/defhelper hooks.metabase.channel.template.handlebars-helper/defhelper
metabase.channel.template.handlebars-test/with-temp-template! hooks.common/with-vec-first-binding
metabase.classloader.core/require hooks.clojure.core.require/lint-require
@@ -608,6 +625,9 @@
metabase.model-persistence.api-test/with-persistence-setup! hooks.common/with-one-top-level-binding
metabase.model-persistence.api-test/with-setup! hooks.common/with-one-top-level-binding
metabase.model-persistence.test-util/with-persistence-enabled! hooks.metabase.model-persistence.test-util/with-persistence-enabled!
metabase.mq.core/with-queue hooks.common/let-second
metabase.mq.test-util/with-test-mq hooks.common/with-one-binding
metabase.mq.core/def-listener! hooks.metabase.mq.impl/def-listener
metabase.models.interface/define-batched-hydration-method hooks.metabase.models.interface/define-hydration-method
metabase.models.interface/define-simple-hydration-method hooks.metabase.models.interface/define-hydration-method
metabase.permissions.core/allow-changing-all-users-group-members hooks.common/do*
@@ -699,6 +719,10 @@
metabase.util.log/warn hooks.metabase.util.log/info
metabase.util.log/warnf hooks.metabase.util.log/infof
metabase.util.malli.registry/def hooks.metabase.util.malli.registry/def
metabase.util.match/match-one hooks.metabase.util.match/match-one
metabase.util.match/match-many hooks.metabase.util.match/match-many
metabase.util.match/replace hooks.metabase.util.match/replace
metabase.util.match/replace-in hooks.metabase.util.match/replace-in
metabase.util/case-enum hooks.metabase.util/case-enum
metabase.util/format-color hooks.metabase.util/format-color
metabase.xrays.api.automagic-dashboards-test/with-indexed-model! hooks.metabase.xrays.api.automagic-dashboards-test/with-indexed-model!
@@ -742,6 +766,7 @@
metabase.test/with-temporary-raw-setting-values macros.metabase.test.util/with-temporary-raw-setting-values
metabase.users.models.user-test/with-groups! macros.metabase.users.models.user-test/with-groups!
metabase.util.namespaces/import-fn macros.metabase.util.namespaces/import-fn
metabase.util.namespaces/import-macro macros.metabase.util.namespaces/import-macro
metabase.xrays.related-test/with-world macros.metabase.xrays.related-test/with-world}}
:config-in-comment
@@ -799,16 +824,8 @@
;;
{:pattern "^metabase(?:((?:-enterprise\\.sandbox)?\\.query-processor)|(?:\\.driver\\.sql(?!server)(?!ite))).*-test$"
:name general-qp-and-driver-test-namespaces}
{:pattern "(?:^mage.*)"
:name mage-namespaces}
;;
;; Namespaces where `with-redefs` is still the idiom because they haven't been audited for conversion
;; to `with-dynamic-fn-redefs` yet (enterprise tests, driver tests). The linter's nudge is too noisy
;; here — audit can happen in follow-up PRs.
;;
{:pattern "^(?:metabase-enterprise\\..+-test(?:\\..+)?|metabase\\.driver\\..+-test(?:\\..+)?)$"
:name prefer-with-dynamic-fn-redefs-unaudited}]
:name mage-namespaces}]
:config-in-ns
{test-namespaces
@@ -832,10 +849,6 @@
metabase.util.time-test
{:linters {:metabase/prefer-with-dynamic-fn-redefs {:level :off}}}
;; Enterprise tests and driver tests haven't been audited yet — silence the linter so CI can ship.
prefer-with-dynamic-fn-redefs-unaudited
{:linters {:metabase/prefer-with-dynamic-fn-redefs {:level :off}}}
source-namespaces
{:linters
{:metabase/discourage-millis-duration {:level :warning}
@@ -930,10 +943,7 @@
:deprecated-namespace
{:exclude
[metabase.driver.common.parameters.dates
metabase.driver.common.parameters.operators
metabase.driver.common.parameters.values
metabase.legacy-mbql.normalize
[metabase.legacy-mbql.normalize
metabase.legacy-mbql.schema
metabase.legacy-mbql.schema.helpers
metabase.legacy-mbql.schema.macros

View File

@@ -128,6 +128,7 @@
analytics
api
collections
eid-translation
lib
permissions
public-sharing
@@ -158,22 +159,30 @@
{:team "Metabot"
:api #{metabase.agent-api.api
metabase.agent-api.init}
:uses #{api
:uses #{ai-tracing
api
auth-identity
channel
collections
dashboards
events
lib
lib-be
llm
metabot
queries
query-permissions
query-processor
request
server
settings
util}
:model-imports #{:model/Card
:model/Collection
:model/Dashboard
:model/DashboardCard
:model/DashboardTab
:model/Database
:model/Table
:model/User}}
@@ -186,9 +195,19 @@
models
util}}
ai-tracing
{:team "Metabot"
:api #{metabase.ai-tracing.api
metabase.ai-tracing.core
metabase.ai-tracing.init}
:uses #{api
settings
util}}
analytics
{:team "UX West"
:api #{metabase.analytics.api
metabase.analytics.api.proxy
metabase.analytics.core
metabase.analytics.event
metabase.analytics.init
@@ -245,7 +264,6 @@
{:team "Graphy"
:api #{metabase.analyze.core}
:uses #{config
driver
lib
models
query-processor
@@ -335,8 +353,7 @@
connection-pool
task
util}
:model-imports #{:model/Database
:model/Field
:model-imports #{:model/Field
:model/QueryCache
:model/Secret
:model/Setting}}
@@ -352,6 +369,7 @@
{:team "UX West"
:api #{metabase.audit-app.core
metabase.audit-app.init}
:friends #{enterprise/memoize-monitor}
:uses #{api
app-db
events
@@ -489,23 +507,29 @@
driver
events
formatter
geojson
lib
lib-be
models
notification
parameters
permissions
pivot
premium-features
query-processor
request
settings
slackbot
system
task
tiles
timeline
types
util}
:model-exports #{:model/Channel :model/ChannelTemplate}
:model-imports #{:model/Dashboard
:model/DashboardCard
:model/DashboardTab
:model/Database
:model/PulseChannel
:model/User}}
@@ -561,6 +585,7 @@
collections
{:team "UX West"
:api #{metabase.collections.core
metabase.collections.curation
metabase.collections.models.collection
metabase.collections.models.collection.root
metabase.collections.schema}
@@ -689,6 +714,7 @@
audit-app
collections
config
embedding
events
lib
models
@@ -699,8 +725,9 @@
query-processor
search
settings
util
warehouse-schema}
staleness
sync
util}
:model-exports #{:model/Dashboard
:model/DashboardCard
:model/DashboardCardSeries
@@ -813,7 +840,6 @@
metabase.driver.common
metabase.driver.connection
metabase.driver.ddl.interface
metabase.driver.h2
metabase.driver.impl
metabase.driver.init
metabase.driver.mysql
@@ -842,7 +868,6 @@
config
driver-api
events
legacy-mbql
lib
lib-be
premium-features
@@ -892,6 +917,7 @@
metabase.eid-translation.core
metabase.eid-translation.init}
:uses #{api
batch-processing
settings
util}
:model-imports #{:model/Action
@@ -948,7 +974,14 @@
request
tiles
util}
:model-imports #{:model/Card :model/Dashboard :model/EmbeddingTheme}}
:model-imports #{:model/Card :model/Dashboard :model/DashboardCard :model/EmbeddingTheme}}
entity-retrieval
{:team "Metabot"
:api #{metabase.entity-retrieval.core
metabase.entity-retrieval.mirror}
:uses #{premium-features}
:model-imports #{:model/OsiAiContext}}
events
{:team "DevEx"
@@ -989,7 +1022,8 @@
geojson
{:team "UX West"
:api #{metabase.geojson.api
metabase.geojson.init}
metabase.geojson.init
metabase.geojson.settings}
:uses #{api
config
permissions
@@ -1011,6 +1045,17 @@
:api #{metabase.graph.core}
:uses #{util}}
health-inspector
{:team "Querying Platform"
:api #{metabase.health-inspector.api
metabase.health-inspector.init}
:uses #{api
lib
lib-be
settings
task
util}}
indexed-entities
{:team "UX West"
:api #{metabase.indexed-entities.api
@@ -1021,6 +1066,7 @@
legacy-mbql
lib
models
permissions
query-processor
search
sync
@@ -1029,6 +1075,27 @@
:model-exports #{:model/ModelIndex :model/ModelIndexValue}
:model-imports #{:model/Card :model/Collection}}
indexes
{:team "Gadget"
:api #{metabase.indexes.models.table-index
metabase.indexes.reconcile
metabase.indexes.schema}
:uses #{driver
models
util}
:model-exports #{:model/TableIndex}}
indexes-rest
{:team "Gadget"
:api #{metabase.indexes-rest.api}
:uses #{api
indexes
transforms-base
util}
:model-imports #{:model/Database
:model/TableIndex
:model/Transform}}
initialization-status
{:team "UX West"
:api #{metabase.initialization-status.core}
@@ -1068,6 +1135,7 @@
metabase.lib.metadata
metabase.lib.metadata.protocols
metabase.lib.options
metabase.lib.pivot
metabase.lib.schema
metabase.lib.schema.actions
metabase.lib.schema.aggregation
@@ -1155,7 +1223,10 @@
sync
util
warehouse-schema}
:model-imports #{:model/Card :model/Database :model/Field :model/Table}}
:model-imports #{:model/Card
:model/Database
:model/Field
:model/Table}}
logger
{:team "DevEx"
@@ -1188,13 +1259,19 @@
:api #{metabase.mcp.api
metabase.mcp.callback-api
metabase.mcp.core
metabase.mcp.init}
metabase.mcp.init
metabase.mcp.usage}
:model-exports #{:model/McpSessionLog
:model/McpToolCallLog}
:uses #{agent-api
ai-tracing
api
app-db
config
llm
metabot
oauth-server
premium-features
request
server
session
@@ -1233,6 +1310,7 @@
slackbot}
:uses #{activity-feed
agent-lib
ai-tracing
analytics
analytics-interface
api
@@ -1244,6 +1322,7 @@
config
documents
driver
entity-retrieval
interestingness
legacy-mbql
lib
@@ -1263,7 +1342,6 @@
settings
slackbot
sql-tools
store-api
sync
system
task
@@ -1279,6 +1357,8 @@
:model-imports #{:model/Card
:model/Collection
:model/Dashboard
:model/DashboardCard
:model/DashboardTab
:model/Database
:model/Field
:model/Glossary
@@ -1368,6 +1448,17 @@
:model/Table
:model/User}}
mq
{:team "UX West"
:api #{metabase.mq.init}
:uses #{analytics-interface
app-db
classloader
settings
startup
task
util}}
native-query-snippets
{:team "Graphy"
:api #{metabase.native-query-snippets.api
@@ -1394,6 +1485,7 @@
:uses #{analytics
analytics-interface
api
app-db
appearance
auth-identity
channel
@@ -1424,14 +1516,18 @@
:model/Dashboard
:model/DashboardCard
:model/DashboardTab
:model/TaskHistory
:model/TaskRun
:model/User}}
oauth-server
{:team "UX West"
:api #{metabase.oauth-server.api
:api #{metabase.oauth-server.api ;; Special case OAuth standard endpoints under `/`
metabase.oauth-server.api.admin ;; The usual Metabase internal API endpoints under `/api`
metabase.oauth-server.core
metabase.oauth-server.init}
:uses #{api
api-scope
appearance
mcp
models
@@ -1442,6 +1538,20 @@
tracing
util}}
osi
{:team "Metabot"
:api #{metabase.osi.ai-context.api}
:uses #{api
app-db
entity-retrieval
models
request
util}
:model-exports #{:model/OsiAiContext}
:model-imports #{:model/Card
:model/Measure
:model/Segment}}
;; TODO -- too many API namespaces
parameters
{:team "Graphy"
@@ -1463,8 +1573,7 @@
models
query-processor
util
warehouse-schema
warehouses}
warehouse-schema}
:model-imports #{:model/Card
:model/Dashboard
:model/Field
@@ -1523,7 +1632,8 @@
pivot
{:team "UX West"
:api #{metabase.pivot.core}
:api #{metabase.pivot.core
metabase.pivot.postprocess}
:uses #{models
util}}
@@ -1662,7 +1772,9 @@
content-verification
dashboards
documents
embedding
events
graph
lib
lib-be
metrics
@@ -1676,6 +1788,9 @@
query-processor
request
search
settings
staleness
sync
util
view-log
warehouse-schema}
@@ -1763,6 +1878,7 @@
metabase.query-processor.middleware.permissions
metabase.query-processor.parameters.dates
metabase.query-processor.parameters.operators
metabase.query-processor.parameters.values
metabase.query-processor.pipeline
metabase.query-processor.pivot
metabase.query-processor.preprocess
@@ -1786,6 +1902,7 @@
cache
config
dashboards
database-routing
driver
events
formatter
@@ -1800,6 +1917,7 @@
premium-features
queries
query-permissions
request
server
settings
system
@@ -1808,8 +1926,6 @@
util
workspaces}
:model-imports #{:model/Card
:model/Dashboard
:model/DashboardCard
:model/DashboardCardSeries
:model/Database
:model/QueryCache
@@ -1868,15 +1984,24 @@
:model/Segment
:model/Transform}}
run-tracking
{:team "Gadget"
:api #{metabase.run-tracking.core}
:uses #{analytics-interface
app-db
task
util}}
sample-data
{:team "UX West"
:api #{metabase.sample-data.core
metabase.sample-data.init}
:uses #{plugins
:uses #{driver
plugins
settings
sync
util}
:model-imports #{:model/Database}}
:model-imports #{:model/DataPermissions :model/Database :model/Table}}
search
{:team "UX West"
@@ -1974,6 +2099,7 @@
tracing
users
util
enterprise/custom-viz-plugin
enterprise/sso}
:model-imports #{:model/Session}}
@@ -1989,6 +2115,7 @@
channel
config
events
premium-features
request
settings
sso
@@ -2086,8 +2213,7 @@
sql-parsing
{:team "DevEx"
:api #{metabase.sql-parsing.core}
:uses #{analytics-interface
util}}
:uses #{analytics-interface util}}
sql-tools
{:team "DevEx"
@@ -2121,6 +2247,10 @@
util}
:model-imports #{:model/AuthIdentity :model/PermissionsGroupMembership}}
staleness
{:team "UX West"
:api #{metabase.staleness.core}}
startup
{:team "DevEx"
:api #{metabase.startup.core}
@@ -2138,6 +2268,7 @@
{:team "Graphy"
:api #{metabase.sync.api
metabase.sync.core
metabase.sync.field-values
metabase.sync.init
metabase.sync.schedules
metabase.sync.task.sync-databases
@@ -2153,6 +2284,7 @@
events
interestingness
lib
lib-be
models
premium-features
query-processor
@@ -2190,16 +2322,17 @@
metabase.task-history.core
metabase.task-history.init}
:uses #{api
app-db
config
models
permissions
premium-features
query-processor
request
run-tracking
task
tracing
util}
:model-exports #{:model/TaskHistory :model/TaskRun}
:model-imports #{:model/Card :model/Dashboard :model/Database}}
tenants
@@ -2219,9 +2352,11 @@
config
lib
lib-be
mcp
permissions
premium-features
search
session
util}
:model-imports #{:model/AiUsageLog
:model/Card
@@ -2236,7 +2371,8 @@
tiles
{:team "UX West"
:api #{metabase.tiles.api
metabase.tiles.init}
metabase.tiles.init
metabase.tiles.settings}
:uses #{api
legacy-mbql
lib
@@ -2244,7 +2380,8 @@
parameters
query-processor
settings
util}}
util}
:model-imports #{:model/Card :model/Dashboard :model/DashboardCard}}
timeline
{:team "UX West"
@@ -2284,6 +2421,7 @@
database-routing
driver
events
indexes
lib
lib-be
models
@@ -2293,6 +2431,7 @@
query-processor
remote-sync
revisions
run-tracking
search
settings
task
@@ -2304,6 +2443,7 @@
enterprise/transforms-python}
:model-exports #{:model/Transform
:model/TransformJob
:model/TransformJobRun
:model/TransformJobTransformTag
:model/TransformRun
:model/TransformTag}
@@ -2311,6 +2451,7 @@
:model/Database
:model/Field
:model/Table
:model/TableIndex
:model/User}}
transforms-base
@@ -2322,12 +2463,15 @@
;; :model/TransformRun directly. Remove once the module is agnostic to global
;; versus workspace transforms. See https://linear.app/metabase/issue/BOT-1143
:model-imports #{:model/Database
:model/Field
:model/Table
:model/TableIndex
:model/Transform
:model/TransformRun}
:uses #{database-routing
driver
events
indexes
lib
lib-be
premium-features
@@ -2356,6 +2500,7 @@
util}
:model-imports #{:model/Transform
:model/TransformJob
:model/TransformJobRun
:model/TransformJobTransformTag
:model/TransformRun
:model/TransformTag}}
@@ -2393,6 +2538,23 @@
:model/Field
:model/Table}}
usage-metadata
{:team "UX West"
:api #{metabase.usage-metadata.init}
:model-imports #{:model/Card
:model/Field
:model/Query
:model/QueryExecution
:model/Segment
:model/Table}
:uses #{app-db
lib
lib-be
models
settings
task
util}}
user-key-value
{:team "UX West"
:api #{metabase.user-key-value.api
@@ -2498,6 +2660,7 @@
warehouse-schema
{:team "UX West"
:api #{metabase.warehouse-schema.field
metabase.warehouse-schema.field-values.distinct-batch
metabase.warehouse-schema.metadata-from-qp
metabase.warehouse-schema.metadata-queries
metabase.warehouse-schema.models.field
@@ -2672,10 +2835,11 @@
driver
events
lib
lib-be
models
query-processor
util
warehouse-schema}
sync
util}
:model-imports #{:model/Database
:model/Field
:model/FieldValues
@@ -2695,6 +2859,7 @@
lib
permissions
premium-features
sample-data
settings
setup
sync
@@ -2733,6 +2898,7 @@
:uses #{driver
premium-features
enterprise/advanced-config
enterprise/mfa
enterprise/scim
enterprise/semantic-search
enterprise/sso}
@@ -2758,7 +2924,6 @@
app-db
audit-app
classloader
config
driver
lib
models
@@ -2890,7 +3055,8 @@
enterprise/custom-viz-plugin
{:team "Gadget"
:api #{metabase-enterprise.custom-viz-plugin.api
metabase-enterprise.custom-viz-plugin.init}
metabase-enterprise.custom-viz-plugin.init
metabase-enterprise.custom-viz-plugin.settings}
:uses #{api
config
events
@@ -2966,7 +3132,6 @@
{:team "UX West"
:api #{metabase-enterprise.database-routing.api}
:uses #{api
config
database-routing
driver
events
@@ -2989,8 +3154,7 @@
metabase-enterprise.dependencies.core
metabase-enterprise.dependencies.init
metabase-enterprise.dependencies.models.dependency}
:uses #{analyze
api
:uses #{api
app-db
collections
database-routing
@@ -3001,7 +3165,6 @@
lib
lib-be
models
native-query-snippets
permissions
premium-features
queries
@@ -3064,6 +3227,33 @@
;; make token tracking a hook). Drop this dep once the relocation lands.
:uses #{enterprise/semantic-search}}
enterprise/entity-retrieval
{:team "Metabot"
:api #{metabase-enterprise.entity-retrieval.init}
:uses #{analytics-interface
collections
entity-retrieval
premium-features
task
util
enterprise/semantic-search}
:model-imports #{:model/Card
:model/Measure
:model/OsiAiContext
:model/Segment
:model/Table}}
enterprise/erd
{:team "Gadget"
:api #{metabase-enterprise.erd.api}
:uses #{api
models
util
warehouse-schema}
:model-imports #{:model/Database
:model/Field
:model/Table}}
enterprise/gsheets
{:team "Cloud"
:api #{metabase-enterprise.gsheets.api
@@ -3114,6 +3304,32 @@
premium-features}
:model-imports #{:model/Card :model/Collection :model/Table}}
enterprise/mcp
{:team "Metabot"
:api #{metabase-enterprise.mcp.init}
:uses #{analytics
mcp
metabot
premium-features
task
util}
:model-imports #{:model/McpSessionLog
:model/McpToolCallLog}}
enterprise/memoize-monitor
{:team "Graphy"
:api #{metabase-enterprise.memoize-monitor.init}
:uses #{analytics
analytics-interface
audit-app
collections
driver
models
util
warehouse-schema
warehouses
enterprise/serialization}}
enterprise/metabot
{:team "Metabot"
:api #{metabase-enterprise.metabot.api
@@ -3153,6 +3369,22 @@
util}
:model-imports #{:model/MetabotConversation :model/MetabotFeedback :model/MetabotMessage}}
enterprise/mfa
{:team "Graphy"
:api #{metabase-enterprise.mfa.core
metabase-enterprise.mfa.init
metabase-enterprise.mfa.routes}
:uses #{api
appearance
channel
config
events
premium-features
settings
sso
util}
:model-imports #{:model/AuthIdentity :model/User}}
enterprise/permission-debug
{:team "UX West"
:api #{metabase-enterprise.permission-debug.api}
@@ -3182,6 +3414,7 @@
events
models
premium-features
search
settings
startup
task
@@ -3319,14 +3552,19 @@
{:team "Metabot"
:api #{metabase-enterprise.semantic-search.api
metabase-enterprise.semantic-search.core
metabase-enterprise.semantic-search.db.datasource
metabase-enterprise.semantic-search.embedding
metabase-enterprise.semantic-search.init}
:uses #{activity-feed
analytics
analytics-interface
api
app-db
collections
config
connection-pool
events
lib-be
llm
metabot
models
@@ -3337,7 +3575,9 @@
task
tracing
util}
:model-imports #{:model/Card :model/Collection :model/Dashboard}}
:model-imports #{:model/Collection
:model/Dashboard
:model/Table}}
enterprise/serialization
{:team "Graphy"
@@ -3347,12 +3587,12 @@
metabase-enterprise.serialization.init
metabase-enterprise.serialization.schema
metabase-enterprise.serialization.v2.backfill-ids}
:friends #{enterprise/memoize-monitor}
:uses #{analytics
api
app-db
appearance
collections
config
events
lib
logger
@@ -3393,6 +3633,7 @@
settings
sso
system
task
util
enterprise/scim}
:model-imports #{:model/PermissionsGroup :model/Session}}
@@ -3404,11 +3645,11 @@
:uses #{analytics
api
collections
embedding
premium-features
queries
request
settings
staleness
util}
:model-imports #{:model/Card :model/Collection :model/Dashboard}}
@@ -3447,7 +3688,9 @@
{:team "Graphy"
:api #{metabase-enterprise.transforms.api}
:uses #{premium-features
enterprise/transforms-inspector}}
util
enterprise/transforms-inspector}
:model-imports #{:model/Transform}}
enterprise/transforms-inspector
{:team "Gadget"
@@ -3521,6 +3764,7 @@
permissions
premium-features
query-processor
sample-data
server
settings
sql-tools
@@ -3529,6 +3773,7 @@
enterprise/serialization}
:model-exports #{:model/Workspace}
:model-imports #{:model/Database
:model/Table
:model/User}}}
;; namespaces matching these patterns (with `re-find`) are excluded from the module linter. Since regex literals

View File

@@ -36,6 +36,9 @@
;; Definitely thread safe
metabase.test.util.dynamic-redefs/patch-vars!
;; test-only cleanup of in-memory throttle state (atom resets)
metabase.session.api/reset-throttlers-for-testing!
;; TODO: most of these symbols shouldn't be here, we should go through them and
;; find the functions/macros that use them and make sure their names end with !
;; best way to do this is try remove each of these and rely on kondo output to find places where it's used

View File

@@ -6,3 +6,8 @@
`(def ~(-> sym name symbol) "docstring" ~sym))
([sym name]
`(def ~name "docstring" ~sym)))
(defmacro import-macro
"Kondo macro replacement for [[metabase.util.namespaces/import-macro]]."
[sym]
`(def ~(-> sym name symbol) "docstring" ~sym))

View File

@@ -224,26 +224,38 @@
nil)))))))
(defn is [{:keys [node lang]}]
(defn is [{:keys [node lang], :as input}]
(when (= lang :cljs)
(warn-about-missing-test-expr-requires-in-cljs node))
{:node node})
input)
(defn use-fixtures
"Flag `:parallel/unsafe` forms inside fixtures. Skipped when the surrounding
namespace is marked `^:synchronous` -- 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.
namespace is marked `^:synchronous` -- 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
anything; no parallel tests allowed) or it isn't (fixtures must be
parallel-safe)."
[{:keys [node config], ns-sym :ns}]
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
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))
(let [linter-config (get-in config [:linters :metabase/validate-deftest])]
(doseq [form (rest (:children node))]
(warn-about-disallowed-parallel-forms form linter-config))))
{:node node})
input)
(defn testing
"Check that we don't have an empty `testing` form like
(testing \"message\")"
[{{[_testing _message & body] :children, :as node} :node, :as input}]
(when (empty? body)
(hooks/reg-finding!
(assoc (meta node)
:message "A `testing` form that doesn't wrap anything doesn't do anything"
:type :metabase/check-testing-not-empty)))
input)

View File

@@ -0,0 +1,18 @@
(ns hooks.metabase.mq.impl
(:require
[clj-kondo.hooks-api :as hooks]))
(defn def-listener
"Kondo hook for `mq/def-listener`. Rewrites to a `fn` form so kondo can analyze bindings.
Form:
(mq/def-listener! :queue/bar [msgs] body...)"
[{:keys [node]}]
(let [[_ _channel-name bindings & body] (:children node)
;; rewrite as: (fn [bindings...] body...)
new-node (hooks/list-node
(list*
(hooks/token-node 'fn)
bindings
body))]
{:node new-node}))

View File

@@ -1,7 +1,6 @@
(ns hooks.metabase.util.i18n
(:require
[clj-kondo.hooks-api :as api]
[clojure.string :as str]
[hooks.common]))
(defn- valid-apostrophes?

View File

@@ -0,0 +1,132 @@
(ns hooks.metabase.util.match
(:require [clj-kondo.hooks-api :as api]))
(defn- token-node? [node token-name]
(and (api/token-node? node)
(= (str (:value node)) token-name)))
(defn- keyword-node? [node k]
(and (api/keyword-node? node)
(= (:k node) k)))
(defn- binding-symbol?
"True when the token is a plain symbol that should be treated as a binding
(not a keyword, not a boolean literal, not nil, not a number, not `_`)."
[node]
(and (api/token-node? node)
(let [v (:value node)]
(and (symbol? v)
(not (contains? '#{_ nil true false} v))))))
;; To establish fake let bindings, we need to bind them to something. This "something" has to be vague enough to trick
;; kondo into not looking too much into it. E.g., if we bind everything to `nil`, Kondo linters will get fired up.
(def opaque-node (api/list-node (list (api/token-node 'rand-nth) (api/list-node []))))
(defn collect-bindings
"Return a list of token nodes (symbols) introduced as bindings by `pattern`."
[pattern]
(cond
(binding-symbol? pattern)
[[pattern opaque-node]]
;; Lists: (:or ...), (:and ...), (sym :guard pred ...), or a quoted symbol.
(api/list-node? pattern)
(let [[head & rst] (:children pattern)]
(cond (or (keyword-node? head :or)
(keyword-node? head :and))
(mapcat collect-bindings rst)
(api/token-node? head)
(cond-> []
(binding-symbol? head) (conj [head opaque-node])
(keyword-node? (first rst) :guard) (conj [(api/token-node '_) (second rst)]))
;; anything else (e.g. a function call used as predicate) — no bindings
:else []))
(api/vector-node? pattern)
(mapcat (fn [node]
(when-not (token-node? node "&")
(collect-bindings node)))
(:children pattern))
;; Maps: keys are literal selectors, values are sub-patterns.
;; Special value-symbols &truthy and _ are NOT user bindings.
(api/map-node? pattern)
(let [children (:children pattern)
pairs (partition 2 children)]
(mapcat (fn [[_k v]]
(when-not (or (token-node? v "&truthy")
(token-node? v "_"))
(collect-bindings v)))
pairs))
;; For sets, make sure to use them because they may reference some of the outer local bindings, so if we don't
;; include them, Kondo will complain about those bindings being unused.
(api/set-node? pattern)
[[(api/token-node '_) pattern]]
;; Anything else — no bindings.
:else []))
(defn- dedupe-bindings
"Prevent Kondo complaining that we have multiple fake bindings."
[pairs]
(loop [[[sym v] & r] pairs, seen #{}, result []]
(cond (nil? sym) result
(and (seen sym) (not (token-node? sym "_"))) (recur r seen result)
:else (recur r (conj seen sym) (conj result sym v)))))
(defn match-one
"clj-kondo :analyze-call hook for match-one.
Rewrites
(match-one value
pat1 ret1
pat2 ret2
...)
into a `let` form that declares all binding symbols introduced by the patterns, so clj-kondo knows they are
legitimate and won't warn about unresolved/unused symbols:
(let [<all-bindings> (rand-nth []) ...]
(or ret1 ret2 ...))"
[{:keys [node]}]
(let [[_ value & clauses] (:children node)]
(when (odd? (count clauses))
(api/reg-finding!
{:message "match-one/match-many/replace requires an even number of pattern/result pairs"
:type :metabase/match-odd-clauses
:row (:row node)
:col (:col node)
:filename (-> node meta :filename)}))
(let [pairs (partition 2 clauses)
all-bindings (->> pairs
(mapcat (fn [[pat _ret]] (collect-bindings pat)))
dedupe-bindings)
special-bindings [(api/token-node '_) value
(api/token-node '&match) opaque-node
(api/token-node '&parents) opaque-node
(api/token-node '&recur) opaque-node
;; Pretend to use &match, &parents, and &recur so that Kondo doesn't complain about them
;; if they are not used by the user code.
(api/token-node '_) (api/token-node '&match)
(api/token-node '_) (api/token-node '&parents)
(api/token-node '_) (api/token-node '&recur)]
binding-nodes (into special-bindings all-bindings)
result-exprs (map second pairs)
new-node (api/list-node
(list
(api/token-node 'let)
(api/vector-node binding-nodes)
(api/list-node
(concat [(api/token-node 'clojure.core/or)] result-exprs [opaque-node]))))]
{:node new-node})))
(def match-many match-one)
(def replace match-one)
(defn replace-in [context]
;; Everything is the same as in match-one, just drop the middle argument.
(match-one (update-in context [:node :children] (fn [[sym value path & clauses]] (list* sym value clauses)))))

View File

@@ -0,0 +1,59 @@
(ns hooks.metabase.util.match-test
(:require
[clj-kondo.hooks-api :as hooks]
[clj-kondo.impl.utils]
[clojure.test :refer :all]
[hooks.metabase.util.match :as sut]))
(defn- expand [src]
(-> (sut/match-one {:node (hooks/parse-string (pr-str src))})
:node
hooks/sexpr))
(defn- lint [src]
(binding [clj-kondo.impl.utils/*ctx* {:config {:linters {:metabase/match-odd-clauses {:level :warning}}}
:ignores (atom nil)
:findings (atom [])
:namespaces (atom {})}]
(expand src)
@(:findings clj-kondo.impl.utils/*ctx*)))
(deftest odd-clauses-triggers-warning-test
(is (=? [{:type :metabase/match-odd-clauses}]
(lint '(metabase.util.match/match-one [] [a b c])))))
(deftest expansion-test
(testing "simple expansion example"
(is (= '(let [_ []
&match (rand-nth ())
&parents (rand-nth ())
&recur (rand-nth ())
_ &match
_ &parents
_ &recur
a (rand-nth ())
b (rand-nth ())
c (rand-nth ())]
(clojure.core/or (+ a b) (rand-nth ())))
(expand '(match-one [] [a b c] (+ a b))))))
(testing "complicated expansion example that uses most match-one macro features, and also binding deduplication by the rewriter"
(is (= '(let [_ []
&match (rand-nth ())
&parents (rand-nth ())
&recur (rand-nth ())
_ &match
_ &parents
_ &recur
val1 (rand-nth ())
a (rand-nth ())
_ #{maybe important}
rst (rand-nth ())
x (rand-nth ())
_ (= x 3)
b (rand-nth ())]
(clojure.core/or (+ a val1) (rand-nth ())))
(expand '(match-one []
(:or [{:key1 val1, :key2 &truthy, :key3 _} _ a #{maybe important} & rst]
(:and (x :guard (= x 3))
[a b]))
(+ a val1)))))))

27
.clj-surgeon.edn Normal file
View File

@@ -0,0 +1,27 @@
{:aliases
{;; defendpoint shape: (api.macros/defendpoint METHOD URL DOCSTRING? [args] body)
;; No name slot — synthesize :route [METHOD "path"] from first 2 args.
"defendpoint"
{:fields {:method (fn [z] (some-> z z/down z/right z/sexpr name str/upper-case))
:path (fn [z] (-> z z/down z/right z/right z/sexpr))}}
;; defenterprise shape:
;; (defenterprise NAME DOCSTRING? EE-NAMESPACE [args] body)
"defenterprise"
{:fields {:name ->defn-name
:ee-namespace (fn [z]
;; Skip name + optional docstring; the next
;; symbol is the EE namespace.
(let [name-z (-> z z/down z/right)
after-doc (z/right name-z)
candidate (if (string? (try (z/sexpr after-doc)
(catch Exception _ nil)))
(z/right after-doc)
after-doc)]
(try (let [v (z/sexpr candidate)]
(when (symbol? v) v))
(catch Exception _ nil))))
:arglist ->defn-arg-list}}
"defsetting"
{:fields {:name ->defn-name}}}}

28
.coderabbit.yaml Normal file
View File

@@ -0,0 +1,28 @@
# yaml-language-server: $schema=https://coderabbit.ai/integrations/schema.v2.json
reviews:
high_level_summary: false
review_status: false
auto_review:
enabled: false
drafts: true
labels:
- "coderabbit"
path_filters:
- "!**/*.snap"
- "!**/*.po"
- "!**/bun.lock"
- "!**/package-lock.json"
tools:
eslint:
enabled: false
knowledge_base:
code_guidelines:
filePatterns:
- ".claude/skills/clojure-review/SKILL.md"
- ".claude/skills/typescript-review/SKILL.md"
- ".claude/skills/e2e-test-review/SKILL.md"
- ".claude/skills/docs-review/SKILL.md"

View File

@@ -1,10 +0,0 @@
# worktrunk project config — https://worktrunk.dev
# Hooks run when switching, creating, merging, or removing worktrees.
# Setup tasks for newly-created worktrees. Run once, blocking, in the
# new worktree's cwd before post-start background tasks kick off.
[pre-start]
# Trust mise config so it loads the project's tool versions without prompting.
trust-mise = "mise trust"
# Install JS deps so husky git hooks get wired up in the new worktree.
bun-install = "bun install"

32
.dependency-cruiser.cjs Normal file
View File

@@ -0,0 +1,32 @@
// dependency-cruiser config for the actual frontend import graph (what's
// imported, vs the *allowed* edges in module-boundaries.mjs). Consumed by
// .github/scripts/create-test-plan.ts.
//
// bunx depcruise frontend/src enterprise/frontend/src \
// --config .dependency-cruiser.cjs --output-type json > dependency-graph.json
/** @type {import('dependency-cruiser').IConfiguration} */
module.exports = {
options: {
// Keep only edges between our own source files (drops node_modules etc.),
// which keeps the JSON small.
includeOnly: "^(frontend/src|enterprise/frontend/src)/",
doNotFollow: { path: "node_modules" },
// Resolve the `"*": ["./frontend/src/*", ...]` aliases so bare imports like
// `metabase/lib/foo` map back to a real file.
tsConfig: { fileName: "tsconfig.json" },
// Keep type-only imports: a type-only dependent still breaks on a type change.
tsPreCompilationDeps: true,
moduleSystems: ["es6", "cjs", "tsd"],
enhancedResolveOptions: {
exportsFields: ["exports"],
conditionNames: ["import", "require", "node", "default", "types"],
extensions: [".js", ".jsx", ".ts", ".tsx", ".json"],
},
},
};

View File

@@ -1,4 +1,4 @@
FROM mcr.microsoft.com/vscode/devcontainers/java:21
FROM mcr.microsoft.com/vscode/devcontainers/java:25
# Set up nodesource, install node, bun, fontconfig for static viz, rlwrap for dev ergonomics

View File

@@ -1,5 +1,6 @@
.git
.babel_cache
target/*
target
.circleci
.cpcache
.devcontainer
@@ -15,6 +16,7 @@ test_config/*
test_modules/*
test_resources/*
node_modules
**/node_modules
**metabase.jar
*.db

6
.gitattributes vendored
View File

@@ -7,3 +7,9 @@
#
# TODO (Bryan 12/12/25) -- reenable this when we can completely verify correctness
# resources/migrations/*_update_migrations.yaml merge=yaml-migrations
# Generated API documentation/specs — regenerated by the "Auto-update documentation for master"
# CI automation, not edited by hand. Mark generated so tools/humans don't review or diff them as source.
docs/api.json linguist-generated
docs/api.html linguist-generated
resources/openapi/openapi.json linguist-generated

20
.github/CODEOWNERS vendored
View File

@@ -12,13 +12,27 @@ enterprise/backend/src/metabase_enterprise/dependencies @metabase/graphy
enterprise/frontend/src/metabase-enterprise/dependencies @metabase/graphy
# @metabase/embedding
enterprise/frontend/src/embedding-sdk-package @metabase/embedding
enterprise/frontend/src/embedding-sdk-bundle @metabase/embedding
enterprise/frontend/src/embedding-sdk-shared @metabase/embedding
frontend/src/metabase/embedding @metabase/embedding
frontend/src/metabase/embedding-sdk @metabase/embedding
frontend/src/embedding-sdk-bundle @metabase/embedding
frontend/src/embedding-sdk-shared @metabase/embedding
frontend/src/metabase/public/containers/PublicOrEmbeddedQuestion @metabase/embedding
frontend/src/metabase/public/containers/PublicOrEmbeddedDashboard @metabase/embedding
enterprise/frontend/src/embedding @metabase/embedding
enterprise/frontend/src/embedding-sdk-ee @metabase/embedding
enterprise/frontend/src/embedding-sdk-package @metabase/embedding
enterprise/frontend/src/metabase-enterprise/embedding @metabase/embedding
enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk @metabase/embedding
enterprise/frontend/src/metabase-enterprise/embedding_iframe_sdk_setup @metabase/embedding
enterprise/frontend/src/metabase-enterprise/embedding-sdk @metabase/embedding
e2e/test-component @metabase/embedding
e2e/test/scenarios/embedding @metabase/embedding
e2e/embedding-sdk-host-apps @metabase/embedding
# @metabase/tech-writers
docs @metabase/tech-writers
docs/developers-guide # exclude from tech-writer ownership

View File

@@ -1,5 +1,5 @@
> [!IMPORTANT]
> For those employed by Metabase: if you are merging into master, please add either a `backport` or a `no-backport` label to this PR. You will not be able to merge until you do this step. Refer to the section [Do I need to backport this PR?](https://www.notion.so/metabase/Metabase-Branching-Strategy-6eb577d5f61142aa960a626d6bbdfeb3?pvs=4#89f80d6f17714a0198aeb66c0efd1b71) in the Metabase Branching Strategy document for more details. If you're not employed by Metabase, this section does not apply to you, and the label will be taken care of by your reviewer.
> For those employed by Metabase: if you are fixing a P0 or P1 issue, add a `backport` label to this PR. No action is needed otherwise. Refer to the [Backporting](https://app.notion.com/p/metabase/Branching-Strategy-and-Backports-6eb577d5f61142aa960a626d6bbdfeb3?source=copy_link#e71f6e7de2f945d99fbb2d6b764e6f36) section in the Metabase Branching Strategy document for more details. If you're not employed by Metabase, this section does not apply to you, and the label will be taken care of by your reviewer.
> **Warning**
>

View File

@@ -0,0 +1,131 @@
name: Create test plan
description: Cruise the frontend import graph and compute the affected-tests plan.
inputs:
changed-files:
description: All changed files (CSV).
required: true
fe-changed-files:
description: Changed frontend_sources files (CSV).
required: true
be-changed-files:
description: Changed backend_sources files (CSV).
required: true
unit-infra-touched:
description: Whether FE unit infra changed.
required: true
loki-infra-touched:
description: Whether Loki infra changed.
required: true
e2e-infra-touched:
description: Whether e2e harness/support code changed.
required: true
shared-sources-touched:
description: Whether cljc/cljs/package.json changed.
required: true
outputs:
stats:
description: FE Affected Tests stats row (JSON).
value: ${{ steps.compute.outputs.stats }}
fe_unit_specs_to_run:
description: Unit specs to run (JSON array).
value: ${{ steps.compute.outputs.fe_unit_specs_to_run }}
loki_stories_to_run:
description: Loki stories to run (JSON array).
value: ${{ steps.compute.outputs.loki_stories_to_run }}
e2e_specs_to_run:
description: E2E specs to run (JSON array).
value: ${{ steps.compute.outputs.e2e_specs_to_run }}
runs:
using: composite
steps:
- name: Prepare Node + Bun
uses: ./.github/actions/prepare-node-bun
- name: Resolve closest-ancestor e2e coverage manifest
id: manifest
uses: actions/github-script@v9
with:
script: | # js
const { pathToFileURL } = require("url");
const { resolveCoverageManifest } = await import(
pathToFileURL(
`${process.env.GITHUB_WORKSPACE}/.github/scripts/resolve-coverage-manifest.mjs`,
).href,
);
const result = await resolveCoverageManifest({
github,
owner: context.repo.owner,
repo: context.repo.repo,
headSha: context.payload.pull_request?.head?.sha ?? context.sha,
});
core.setOutput("path", result?.path ?? "");
- name: Build dependency graph
shell: bash
run: |
# Quiet on success; surface output only if install fails.
bun install --frozen-lockfile > /tmp/bun-install.log 2>&1 \
|| { echo "bun install issues (continuing):"; tail -20 /tmp/bun-install.log; }
bunx depcruise frontend/src enterprise/frontend/src \
--config .dependency-cruiser.cjs \
--output-type json > dependency-graph.json || true
- name: Create test plan
id: compute
shell: bash
env:
CHANGED_FILES: ${{ inputs.changed-files }}
FE_CHANGED_FILES: ${{ inputs.fe-changed-files }}
BE_CHANGED_FILES: ${{ inputs.be-changed-files }}
UNIT_INFRA_TOUCHED: ${{ inputs.unit-infra-touched }}
LOKI_INFRA_TOUCHED: ${{ inputs.loki-infra-touched }}
E2E_INFRA_TOUCHED: ${{ inputs.e2e-infra-touched }}
SHARED_SOURCES_TOUCHED: ${{ inputs.shared-sources-touched }}
DEP_GRAPH_JSON: dependency-graph.json
E2E_SPEC_MANIFEST: ${{ steps.manifest.outputs.path }}
run: |
# stdout is the plan JSON; the planner's own info logs go to stderr.
bun .github/scripts/create-test-plan.ts > test-plan.json
echo "stats=$(jq -c '.stats' test-plan.json)" >> "$GITHUB_OUTPUT"
echo "fe_unit_specs_to_run=$(jq -c '.fe_unit_specs_to_run' test-plan.json)" >> "$GITHUB_OUTPUT"
echo "loki_stories_to_run=$(jq -c '.loki_stories_to_run' test-plan.json)" >> "$GITHUB_OUTPUT"
echo "e2e_specs_to_run=$(jq -c '.e2e_specs_to_run' test-plan.json)" >> "$GITHUB_OUTPUT"
- name: Report test plan
shell: bash
run: |
plan=test-plan.json
row() { # name, selected, total
if [ "$2" -eq "$3" ]; then echo "| $1 | all ($3) | $3 |"; else echo "| $1 | $2 | $3 |"; fi
}
{
echo "## Affected test plan"
echo
echo "| Suite | Selected | Total |"
echo "|---|---:|---:|"
row "Unit" "$(jq '.stats.unit_specs_to_run_usage' "$plan")" "$(jq '.stats.unit_specs_all' "$plan")"
row "Loki" "$(jq '.stats.loki_stories_to_run_usage' "$plan")" "$(jq '.stats.loki_stories_all' "$plan")"
row "E2E" "$(jq '.stats.e2e_specs_to_run_usage' "$plan")" "$(jq '.stats.e2e_specs_all' "$plan")"
echo
echo "Changed: $(jq '.stats.fe_files_changed' "$plan") FE / $(jq '.stats.be_files_changed' "$plan") BE file(s) · $(jq '.stats.fe_modules_affected_usage' "$plan") FE module(s) affected"
echo
e2e_run=$(jq '.stats.e2e_specs_to_run_usage' "$plan")
e2e_all=$(jq '.stats.e2e_specs_all' "$plan")
if [ "$e2e_run" -eq "$e2e_all" ]; then
echo "**E2E: full run** — no manifest, or a change the coverage manifest can't scope (backend, e2e infra, cljc/cljs)."
else
echo "<details><summary><b>E2E specs to run ($e2e_run)</b></summary>"
echo
jq -r '.e2e_specs_to_run[]' "$plan" | sed 's/^/- /'
echo
echo "</details>"
fi
echo
echo "<details><summary>Full stats (rules vs usage graph)</summary>"
echo
echo '```json'
jq '.stats' "$plan"
echo '```'
echo "</details>"
} | tee -a "${GITHUB_STEP_SUMMARY:-/dev/null}"

View File

@@ -40,10 +40,24 @@ runs:
using: "composite"
steps:
- name: Authenticate to prevent API rate limit
uses: docker/login-action@650006c6eb7dba73a995cc03b0b2d7f5ca915bee # v4.2.0
with:
username: ${{ inputs.username }}
password: ${{ inputs.password }}
shell: bash
env:
DOCKER_USERNAME: ${{ inputs.username }}
DOCKER_PASSWORD: ${{ inputs.password }}
run: |
for attempt in 1 2 3; do
echo "Docker login attempt $attempt of 3..."
if echo "$DOCKER_PASSWORD" | docker login --username "$DOCKER_USERNAME" --password-stdin; then
echo "Docker login succeeded on attempt $attempt"
break
fi
if [ $attempt -eq 3 ]; then
echo "::error::Docker login failed after 3 attempts"
exit 1
fi
echo "::warning::Docker login attempt $attempt failed, retrying in 15s..."
sleep 15
done
- name: Start Containers
shell: bash
@@ -53,16 +67,29 @@ runs:
cd e2e/test/scenarios/
docker compose up \
$([ ${{ inputs.postgres }} = true ] && echo "postgres-sample") \
$([ ${{ inputs.mysql }} = true ] && echo "mysql-sample") \
$([ ${{ inputs.mongo }} = true ] && echo "mongo-sample") \
$([ ${{ inputs.maildev }} = true ] && echo "maildev") \
$([ ${{ inputs.maildev }} = true ] && echo "maildev-ssl") \
$([ ${{ inputs.openldap }} = true ] && echo "ldap") \
$([ ${{ inputs.webhook }} = true ] && echo "webhook-tester") \
$([ ${{ inputs.snowplow }} = true ] && echo "snowplow-micro") \
-d
SERVICES=()
[ "${{ inputs.postgres }}" = true ] && SERVICES+=(postgres-sample)
[ "${{ inputs.mysql }}" = true ] && SERVICES+=(mysql-sample)
[ "${{ inputs.mongo }}" = true ] && SERVICES+=(mongo-sample)
[ "${{ inputs.maildev }}" = true ] && SERVICES+=(maildev maildev-ssl)
[ "${{ inputs.openldap }}" = true ] && SERVICES+=(ldap)
[ "${{ inputs.webhook }}" = true ] && SERVICES+=(webhook-tester)
[ "${{ inputs.snowplow }}" = true ] && SERVICES+=(snowplow-micro)
for attempt in 1 2 3; do
echo "Docker compose up attempt $attempt of 3..."
if docker compose up "${SERVICES[@]}" -d; then
echo "Docker compose up succeeded on attempt $attempt"
break
fi
if [ $attempt -eq 3 ]; then
echo "::error::Docker compose up failed after 3 attempts"
exit 1
fi
echo "::warning::Docker compose up attempt $attempt failed, retrying in 30s..."
docker compose down 2>/dev/null || true
sleep 30
done
if ${{ inputs.maildev }}; then
echo -e "${Y}checking maildev container..." &&

View File

@@ -4,7 +4,7 @@ description: |
inputs:
java-version:
required: true
default: "21"
default: "25"
clojure-version:
required: true
default: "1.12.0.1488"

View File

@@ -0,0 +1,52 @@
name: Prepare CI Conductor
description: >-
Make the ci-conductor sources runnable in the workspace.
Unless the checkout is headed for master, they are overlaid from master, so every
branch runs the latest scripts while its workflow wiring stays branch-historical.
runs:
using: composite
steps:
- name: Detect bun
id: bun
shell: bash
run: |
if command -v bun >/dev/null; then
echo "present=true" >> "$GITHUB_OUTPUT"
else
echo "present=false" >> "$GITHUB_OUTPUT"
fi
- name: Install bun
if: steps.bun.outputs.present != 'true'
uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0
with:
bun-version-file: "package.json"
token: ${{ github.token }}
# Anything headed for master runs master's own sources, so a PR can test its own changes.
- name: Fetch ci-conductor sources from master
if: ${{ github.base_ref != 'master' && github.ref_name != 'master' }}
uses: actions/checkout@v6
with:
repository: metabase/metabase
ref: master
path: .ci-conductor-master
persist-credentials: false
sparse-checkout-cone-mode: false
sparse-checkout: |
release/ci-conductor
e2e/support/ci_conductor.ts
# e2e/support/config.js and e2e/support/ci_conductor.ts resolve these by relative
# path at bundle time, so the sources have to land where the branch expects them.
- name: Overlay ci-conductor sources from master
if: ${{ github.base_ref != 'master' && github.ref_name != 'master' }}
shell: bash
run: |
set -euo pipefail
rm -rf release/ci-conductor
mv .ci-conductor-master/release/ci-conductor release/ci-conductor
mv .ci-conductor-master/e2e/support/ci_conductor.ts e2e/support/ci_conductor.ts
rm -rf .ci-conductor-master
echo "Overlaid ci-conductor sources from master."

View File

@@ -15,6 +15,10 @@ outputs:
runs:
using: "composite"
steps:
# e2e/support/config.js imports the reporter, so it has to be in place before Cypress bundles.
- name: Prepare CI Conductor
uses: ./.github/actions/prepare-ci-conductor
- name: Install Chrome v144
uses: browser-actions/setup-chrome@2e1d749697dd1612b833dba4a722266286fbefcd # v2.1.2
with:

View File

@@ -16,5 +16,5 @@ runs:
- name: Install bun
uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0
with:
bun-version: "1.3.7"
bun-version-file: 'package.json'
token: ${{ github.token }}

View File

@@ -6,7 +6,7 @@ runs:
steps:
- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0
with:
bun-version: "1.3.7"
bun-version-file: 'package.json'
token: ${{ github.token }}
- name: Build release scripts

View File

@@ -0,0 +1,38 @@
name: CI Conductor quarantine gate
description: >-
Check this job's test failures against ci-conductor's quarantine list.
Either enforces the quarantine or only prints a verdict (dry run).
Fails closed when enforcing but the `CI_CONDUCTOR_BASE_URL` is missing or unreachable.
inputs:
adapter:
description: Which gate to run — one of `backend`, `frontend`, `e2e`.
required: true
test-suite:
description: >-
Suite label to gate (CI_CONDUCTOR_TEST_SUITE). MUST match the label this
job reports under, or the gate checks the wrong quarantine list.
required: true
enforce-quarantine:
description: >-
Whether the gate actually gates the job. When "false", it only prints a verdict.
required: false
default: "false"
runs:
using: composite
steps:
- name: Prepare CI Conductor
uses: ./.github/actions/prepare-ci-conductor
- name: Check failures against the quarantine list
shell: bash
env:
CI_CONDUCTOR_TEST_SUITE: ${{ inputs.test-suite }}
ADAPTER: ${{ inputs.adapter }}
QUARANTINE_DRY_RUN: ${{ inputs.enforce-quarantine != 'true' }}
run: |
case "$ADAPTER" in
backend|frontend|e2e) ;;
*) echo "::error::quarantine-gate: unknown adapter '$ADAPTER' (expected backend|frontend|e2e)"; exit 1 ;;
esac
bun "release/ci-conductor/src/check-${ADAPTER}-quarantine.ts"

View File

@@ -0,0 +1,34 @@
name: Report failures to CI Conductor
description: >-
Report this job's test failures to ci-conductor. Best-effort; no-ops unless
CI_CONDUCTOR_BASE_URL is set. Gate it at the call site with continue-on-error
and an `if:` on the test step's outcome.
inputs:
test-suite:
description: Per-job identity label (CI_CONDUCTOR_TEST_SUITE); unique per job/leg.
required: true
adapter:
description: Which reporter to run; resolves to report-<adapter>.ts. backend or frontend.
required: true
runs:
using: composite
steps:
- name: Prepare CI Conductor
uses: ./.github/actions/prepare-ci-conductor
- name: Report failed tests to ci-conductor
shell: bash
env:
REPO_ID: ${{ github.event.repository.id }}
COMMIT_SHA: ${{ github.event.pull_request.head.sha || github.sha }}
TARGET_BRANCH: ${{ github.event.pull_request.base.ref || github.ref_name }}
CI_CONDUCTOR_TEST_SUITE: ${{ inputs.test-suite }}
ADAPTER: ${{ inputs.adapter }}
# Keep the path constrained to known entrypoints.
run: |
case "$ADAPTER" in
backend|frontend) ;;
*) echo "::error::Unknown ci-conductor adapter '$ADAPTER'"; exit 1 ;;
esac
bun "release/ci-conductor/src/report-${ADAPTER}.ts"

View File

@@ -0,0 +1,66 @@
name: Resolve current job id
description: >
Resolve this job's GitHub workflow_jobs.id via the Actions API and export it
as JOB_ID (and JOB_HTML_URL) to $GITHUB_ENV, so any later step can read the
numeric job id without making its own API call. Best-effort: warns and
proceeds on failure so it can never break the run.
runs:
using: composite
steps:
- name: Resolve JOB_ID
shell: bash
env:
# Use the built-in per-job token, not a PAT: this lookup is best-effort
# (a miss just leaves JOB_ID unset, never breaks the run) and other jobs
# depend on the automation PAT's rate-limit budget — we don't want ~70
# e2e shards drawing it down. Worst case under heavy CI load is the
# occasional unresolved job_id, which is acceptable. DEV-2117.
GH_TOKEN: ${{ github.token }}
RUNNER_NAME: ${{ runner.name }}
run: |
# GitHub doesn't expose the current job's numeric id, so we look it up
# from the Actions API. A runner runs exactly one job at a time, so the
# in-progress job with this runner_name within (run_id, run_attempt) is
# unique. We require status == in_progress and no completed_at so a
# reused runner can't match a job it already finished this attempt, with
# max_by(.started_at) as a final tiebreaker.
#
# $GITHUB_RUN_ID is the whole CI run, whose total job count exceeds the
# 100-per-page cap (~185 jobs), so this shard's job is frequently NOT on
# the first page. --paginate --slurp pulls every page and slurps them
# into one array so the filter sees all jobs, not just the first 100 —
# without it the lookup returned null whenever this job sorted past
# position 100 (DEV-2117).
#
# gh rejects `--slurp` together with `--jq` ("the --slurp option is not
# supported with --jq"), so we slurp with gh and run the filter through a
# standalone `jq`. The earlier `--slurp --jq` form errored on every
# attempt — swallowed by 2>/dev/null — leaving JOB_ID permanently unset.
set +e
api_url="/repos/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID/attempts/$GITHUB_RUN_ATTEMPT/jobs?per_page=100"
jq_filter="[.[].jobs[] | select(.runner_name == \"$RUNNER_NAME\" and .status == \"in_progress\" and .completed_at == null)] | max_by(.started_at) | \"\(.id) \(.html_url)\""
# The Actions jobs API is eventually consistent: after a runner picks
# up a job, it can take a few seconds for runner_name to appear in the
# response. Retry briefly to absorb that.
out=""
for attempt in 1 2 3 4 5; do
out=$(gh api --paginate --slurp "$api_url" 2>/dev/null | jq -r "$jq_filter" 2>/dev/null)
if [ -n "$out" ] && [ "$out" != "null null" ]; then
break
fi
out=""
echo "Attempt $attempt: job not yet visible in Actions API; retrying..."
sleep 3
done
if [ -n "$out" ]; then
read -r job_id job_url <<<"$out"
echo "JOB_ID=$job_id" >> "$GITHUB_ENV"
echo "JOB_HTML_URL=$job_url" >> "$GITHUB_ENV"
echo "Resolved JOB_ID=$job_id (runner=$RUNNER_NAME)"
else
echo "::warning::Could not resolve current job id after 5 attempts (runner=$RUNNER_NAME)"
fi
exit 0

View File

@@ -1,15 +1,17 @@
name: Embedding SDK Bundle Size Check
description: |
Downloads the current branch's uberjar and builds the base ref's
embedding-sdk.js from source, compares their sizes,
and sets output if the size change exceeds the threshold.
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 changes to the chunked SDK's reachable, gzipped size
beyond the threshold. 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 (e.g. merge base).'
description: 'Commit SHA of the base ref.'
required: true
threshold-percent:
description: 'Percent threshold for bundle size change'
@@ -26,86 +28,73 @@ outputs:
runs:
using: "composite"
steps:
- name: Prepare backend
uses: ./.github/actions/prepare-backend
- name: Prepare frontend
uses: ./.github/actions/prepare-frontend
- name: Download current uberjar
uses: ./.github/actions/fetch-artifact
with:
commit: ${{ github.event.pull_request.head.sha || github.sha }}
edition: ${{ inputs.edition }}
extract-path: temp/current-uberjar
- name: Extract embedding-sdk bundles from current uberjar
shell: bash
run: |
# Try new layout first (app/embedding-sdk/legacy/), fall back to old layout (app/embedding-sdk.js)
unzip -j temp/current-uberjar/metabase.jar \
"frontend_client/app/embedding-sdk/legacy/embedding-sdk.js" \
-d temp/current-bundle 2>/dev/null || \
unzip -j temp/current-uberjar/metabase.jar \
"frontend_client/app/embedding-sdk.js" \
-d temp/current-bundle
# Extract chunks directory if it exists (new layout only)
mkdir -p temp/current-chunks
unzip -j temp/current-uberjar/metabase.jar \
"frontend_client/app/embedding-sdk/chunks/*" \
-d temp/current-chunks 2>/dev/null || true
- name: Checkout base ref
uses: actions/checkout@v6
- name: Download base-ref uberjar
id: base-jar
continue-on-error: true
uses: ./.github/actions/fetch-artifact
with:
ref: ${{ inputs.base-ref-commit }}
path: temp/base-ref-src
- name: Build base-ref embedding-sdk.js
shell: bash
run: |
cd temp/base-ref-src
bun install
MB_EDITION=${{ inputs.edition }} bun run build-release
- name: Compare sizes and set output
commit: ${{ inputs.base-ref-commit }}
edition: ${{ inputs.edition }}
extract-path: temp/base-uberjar
- name: Measure and compare bundle sizes
id: compare
shell: bash
env:
GH_TOKEN: ${{ github.token }}
EDITION: ${{ inputs.edition }}
HEAD_SHA: ${{ github.event.pull_request.head.sha || github.sha }}
BASE_SHA: ${{ inputs.base-ref-commit }}
THRESHOLD: ${{ inputs.threshold-percent }}
MEASURE_BUNDLES: app,embedding-sdk-legacy,embedding-sdk-chunked
run: |
# --- Legacy (monolithic) bundle comparison ---
current_size=$(wc -c < temp/current-bundle/embedding-sdk.js) || { echo "::error::Failed to read current bundle"; exit 1; }
set -uo pipefail
# Base ref: try new layout first, fall back to old
if [ -f "temp/base-ref-src/resources/frontend_client/app/embedding-sdk/legacy/embedding-sdk.js" ]; then
base_ref_size=$(wc -c < "temp/base-ref-src/resources/frontend_client/app/embedding-sdk/legacy/embedding-sdk.js")
else
base_ref_size=$(wc -c < "temp/base-ref-src/resources/frontend_client/app/embedding-sdk.js")
fi
[ "$current_size" -gt 0 ] && [ "$base_ref_size" -gt 0 ] || { echo "::error::Bundle file is empty"; exit 1; }
skip() {
echo "::notice::Embedding SDK bundle-size check skipped: $1"
echo "status=stable" >> "$GITHUB_OUTPUT"
echo "size_change_percent=0" >> "$GITHUB_OUTPUT"
exit 0
}
diff=$((current_size - base_ref_size))
percent=$(( diff * 100 / base_ref_size ))
# 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.
[ -f temp/base-uberjar/metabase.jar ] || skip "base-ref uberjar not found for ${BASE_SHA}"
echo "=== Legacy (monolithic) bundle ==="
echo "Current size: $current_size bytes"
echo "Base ref size: $base_ref_size bytes"
echo "Difference: $diff bytes ($percent%)"
extract_js() { # $1=jar $2=dest-root
mkdir -p "$2/resources"
unzip -o "$1" \
"frontend_client/app/dist/*" \
"frontend_client/app/embed.js" \
"frontend_client/app/embedding-sdk/*" \
-d "$2/resources" >/dev/null || true
}
threshold="${{ inputs.threshold-percent }}"
if [ "$percent" -gt "$threshold" ]; then
status="increased"
elif [ "$percent" -lt "$(( -threshold ))" ]; then
status="decreased"
else
status="stable"
fi
fetch_stats() { # $1=sha $2=dest-dir
local name="metabase-bundle-stats-${EDITION}-$1"
local id
id=$(gh api "/repos/${GITHUB_REPOSITORY}/actions/artifacts?name=${name}" --jq '.artifacts[0].id // empty' 2>/dev/null)
[ -n "${id}" ] || return 1
mkdir -p "$2"
gh api "/repos/${GITHUB_REPOSITORY}/actions/artifacts/${id}/zip" > "$2.zip" 2>/dev/null || return 1
unzip -o "$2.zip" -d "$2" >/dev/null || return 1
}
echo "status=$status" >> $GITHUB_OUTPUT
echo "size_change_percent=$percent" >> $GITHUB_OUTPUT
extract_js temp/current-uberjar/metabase.jar temp/current
extract_js temp/base-uberjar/metabase.jar temp/base
# --- Chunked bundle (informational) ---
if ls temp/current-chunks/*.js 1>/dev/null 2>&1; then
chunks_size=$(cat temp/current-chunks/*.js | wc -c)
echo ""
echo "=== Chunked bundle (bootstrap + chunks) ==="
echo "Total chunked size: $chunks_size bytes"
echo "chunks_size=$chunks_size" >> $GITHUB_OUTPUT
else
echo ""
echo "No chunked bundle found (expected on master)"
fi
fetch_stats "${HEAD_SHA}" temp/current/artifacts || skip "bundle stats not found for current ${HEAD_SHA}"
fetch_stats "${BASE_SHA}" temp/base/artifacts || skip "bundle stats not found for base ${BASE_SHA}"
MEASURE_ROOT=temp/current node ./.github/scripts/measure-bundle-sizes.js > temp/current-sizes.json \
|| { echo "::error::Failed to measure current bundle sizes"; exit 1; }
MEASURE_ROOT=temp/base node ./.github/scripts/measure-bundle-sizes.js > temp/base-sizes.json \
|| { echo "::error::Failed to measure base bundle sizes"; exit 1; }
node ./.github/actions/sdk-bundle-size-check/compare.js temp/current-sizes.json temp/base-sizes.json

View File

@@ -0,0 +1,110 @@
/* eslint-disable import/no-commonjs */
// Diffs the bundle sizes produced by measure-bundle-sizes.js for the current
// build and the base ref. Every (bundle, kind) is compared strictly against the
// same (bundle, kind) — never one bundle type against another — using gzipped
// (served) bytes. The gate is driven by the chunked SDK's reachable total, which
// is what the SDK actually delivers.
//
// compareBundles is pure (data in, data out) so it can be unit-tested; main()
// is the thin I/O wrapper that reads the size files, prints the report and sets
// the step outputs / exit code.
const fs = require("fs");
const pick = (rows, bundle, kind) => rows.find(row => row.bundle === bundle && row.kind === kind);
const keyOf = row => `${row.bundle}/${row.kind}`;
const mb = bytes => (bytes / 1024 / 1024).toFixed(2);
const percentOf = (currentBytes, baseBytes) =>
baseBytes ? Math.trunc(((currentBytes - baseBytes) * 100) / baseBytes) : 0;
/**
* Compare two measurement sets and decide the gate. Returns a human-readable
* `report` (always), and exactly one of:
* - `gate` { status, percent }: the chunked SDK total moved by `percent`.
* - `skip` reason: the gate is non-actionable (report stable, no comment).
* - `error` reason: the gate inputs are missing (hard failure).
*/
function compareBundles({ current, base, threshold }) {
const report = ["=== Bundle sizes (gzipped, current vs base) ==="];
const keys = [...new Set([...current, ...base].map(keyOf))].sort();
for (const key of keys) {
const [bundle, kind] = key.split("/");
const currentRow = pick(current, bundle, kind);
const baseRow = pick(base, bundle, kind);
if (!currentRow || !baseRow) {
report.push(`${key}: present only in ${currentRow ? "current" : "base"} build`);
continue;
}
const diff = currentRow.gzipBytes - baseRow.gzipBytes;
const percent = percentOf(currentRow.gzipBytes, baseRow.gzipBytes);
report.push(`${key}: ${mb(currentRow.gzipBytes)}MB vs ${mb(baseRow.gzipBytes)}MB (${percent}%, ${diff} bytes)`);
}
// Gate on the chunked SDK's reachable total (gzipped) — what the SDK ships.
const gateCurrent = pick(current, "embedding-sdk-chunked", "total");
const gateBase = pick(base, "embedding-sdk-chunked", "total");
if (!gateCurrent || !gateBase || !gateBase.gzipBytes) {
return { report, error: "Could not find embedding-sdk-chunked total (gzip) in both builds" };
}
// Both sides must measure "total" the same way. A base ref built before the
// reachableAssets enrichment collapses its total to the initial set, so
// comparing it against the current reachable total reports a phantom jump
// (~30%). Skip until the base ref also carries reachable stats (i.e. once
// this change is on the base).
if (Boolean(gateCurrent.reachable) !== Boolean(gateBase.reachable)) {
return {
report,
skip:
`chunked "total" measured differently on each side ` +
`(current reachable=${Boolean(gateCurrent.reachable)}, base reachable=${Boolean(gateBase.reachable)}); ` +
`the base ref predates the reachable-chunk stats. Resolves once this change is on the base ref.`,
};
}
const percent = percentOf(gateCurrent.gzipBytes, gateBase.gzipBytes);
const status = percent > threshold ? "increased" : percent < -threshold ? "decreased" : "stable";
return { report, gate: { status, percent } };
}
module.exports = { compareBundles };
const setOutput = (name, value) => {
if (process.env.GITHUB_OUTPUT) {
fs.appendFileSync(process.env.GITHUB_OUTPUT, `${name}=${value}\n`);
}
};
function main() {
const [, , currentPath, basePath] = process.argv;
const threshold = Number(process.env.THRESHOLD ?? 2);
const current = JSON.parse(fs.readFileSync(currentPath, "utf8"));
const base = JSON.parse(fs.readFileSync(basePath, "utf8"));
const { report, gate, skip, error } = compareBundles({ current, base, threshold });
console.log(report.join("\n"));
if (error) {
console.error(`::error::${error}`);
process.exit(1);
}
if (skip) {
// Treat the gate as non-actionable: report stable so no regression comment
// is posted, mirroring the shell skip() for missing artifacts.
console.log(`::notice::Embedding SDK bundle-size gate skipped: ${skip}`);
setOutput("status", "stable");
setOutput("size_change_percent", "0");
process.exit(0);
}
console.log("");
console.log(`Gate: embedding-sdk-chunked total ${gate.percent}% (threshold ${threshold}%) → ${gate.status}`);
setOutput("status", gate.status);
setOutput("size_change_percent", gate.percent);
}
if (require.main === module) {
main();
}

View File

@@ -0,0 +1,65 @@
const { compareBundles } = require("./compare");
const total = (gzipBytes, over = {}) => ({
bundle: "embedding-sdk-chunked",
kind: "total",
gzipBytes,
reachable: true,
...over,
});
describe("compareBundles", () => {
it("gates on the chunked SDK total and flags an increase past the threshold", () => {
const { gate, report } = compareBundles({
current: [total(110)],
base: [total(100)],
threshold: 2,
});
expect(gate).toEqual({ status: "increased", percent: 10 });
expect(report[0]).toContain("current vs base");
});
it("flags a decrease and stays stable within the threshold", () => {
expect(compareBundles({ current: [total(90)], base: [total(100)], threshold: 2 }).gate).toEqual({
status: "decreased",
percent: -10,
});
expect(compareBundles({ current: [total(101)], base: [total(100)], threshold: 2 }).gate).toEqual({
status: "stable",
percent: 1,
});
});
it("skips when the two sides measured total differently (reachable mismatch)", () => {
const result = compareBundles({
current: [total(130, { reachable: true })],
base: [total(100, { reachable: false })],
threshold: 2,
});
expect(result.gate).toBeUndefined();
expect(result.skip).toContain("predates the reachable-chunk stats");
});
it("errors when the gate bundle is missing on either side", () => {
const result = compareBundles({
current: [{ bundle: "app", kind: "total", gzipBytes: 1 }],
base: [total(100)],
threshold: 2,
});
expect(result.gate).toBeUndefined();
expect(result.error).toContain("embedding-sdk-chunked total");
});
it("reports a bundle/kind present on only one side without erroring", () => {
const { report } = compareBundles({
current: [total(100), { bundle: "app", kind: "total", gzipBytes: 50 }],
base: [total(100)],
threshold: 2,
});
expect(report.some(line => line.includes("present only in current build"))).toBe(true);
});
});

View File

@@ -14,8 +14,15 @@ inputs:
description: Suffix to append to the test logs artifact name to avoid conflicts in matrix jobs
edition:
required: false
default: 'ee'
default: "ee"
description: Edition to test (oss or ee)
quarantine-engine:
required: false
driver-status:
required: false
default: ""
description: >-
Configured status for this driver ("info", "skip", "required", or empty), as reported by `mage driver-decisions`.
outputs:
test-outcome:
@@ -27,6 +34,10 @@ runs:
steps:
- name: Prepare back-end environment
uses: ./.github/actions/prepare-backend
- name: Resolve current job id
# Resolve JOB_ID early (before the long test step) so the ci-conductor
# reporter below can link failures to this exact job. Best-effort.
uses: ./.github/actions/resolve-job-id
- name: Prepare front-end environment
if: ${{ inputs.build-static-viz == 'true' }}
uses: ./.github/actions/prepare-frontend
@@ -35,15 +46,25 @@ runs:
run: bun run build-static-viz
shell: bash
env:
MB_EDITION: ee
MB_EDITION: ${{ inputs.edition }}
- name: Test database driver
run: clojure -X:dev:ci:${{ inputs.edition }}:${{ inputs.edition }}-dev:drivers:drivers-dev:test ${{ inputs.test-args }}
shell: bash
id: run-test
# Trunk Quarantine controls the final state of the run in the CI!
# Even if this step fails we let it pass, and then `trunk-io/analytics-uploader` determines
# whether to fail or to pass the whole job, based on the quarantine list.
# Keep this step continue-on-error because the quarantine logic controls whether it ultimately fails.
# Driver "info" status can affect this logic. See below.
continue-on-error: true
- name: Report failed tests to ci-conductor
if: ${{ !cancelled() && steps.run-test.outcome == 'failure' }}
# This step should NEVER fail the job!
continue-on-error: true
uses: ./.github/actions/report-failures-to-ci-conductor
with:
test-suite: ${{ inputs.junit-name }}
adapter: backend
- name: Publish Test Report (JUnit)
uses: dorny/test-reporter@a43b3a5f7366b97d083190328d2c652e1a8b6aa2 # v3.0.0
# As per the documentation: https://docs.github.com/en/actions/reference/workflows-and-actions/contexts#steps-context
@@ -57,6 +78,7 @@ runs:
list-suites: failed
list-tests: failed
fail-on-error: false
- name: Upload Logs on Failure
if: always() && steps.run-test.outcome != 'success'
uses: actions/upload-artifact@v7
@@ -66,3 +88,20 @@ runs:
retention-days: 1
# Failing to upload the artifact should never affect the outcome of the whole test run.
continue-on-error: true
# Last, because this is the only step allowed to fail the job: everything above it reports the
# failure (JUnit report, logs, ci-conductor) and must run regardless of the verdict below.
- name: Quarantine gate
# Off master and release branches an "info" driver is data-collection only - the test always passes!
# On master and release branches "info" carries no weight - the quarantine logic applies.
if: |
!cancelled()
&& steps.run-test.outcome == 'failure'
&& !(inputs.driver-status == 'info'
&& !(github.ref_name == 'master' || startsWith(github.ref_name, 'release-x')))
continue-on-error: ${{ inputs.quarantine-engine != 'ci-conductor' }}
uses: ./.github/actions/quarantine-gate
with:
adapter: backend
test-suite: ${{ inputs.junit-name }}
enforce-quarantine: ${{ inputs.quarantine-engine == 'ci-conductor' }}

View File

@@ -21,6 +21,23 @@ inputs:
default: ""
previous-step-outcome:
required: true
driver-status:
required: false
default: ""
description: >-
Configured status for this driver ("info", "skip", "required", or empty). When
"info", the job is reported as passing regardless of the real test outcome, and
that outcome is surfaced via a job summary and (on PRs) a comment instead.
report-variant:
required: false
default: ""
description: >-
Optional label disambiguating matrix legs of the same job, so the info-driver
job summary and PR comment stay distinct per leg.
run-trunk:
required: false
default: "true"
description: Whether to run the Trunk step at all.
runs:
using: "composite"
@@ -47,11 +64,13 @@ runs:
aws s3 cp ${OUTPUT_FILE}.zip s3://$BUCKET/$DATE/$GITHUB_RUN_ID/$GITHUB_RUN_ATTEMPT/
- name: Upload results to Trunk
if: ${{ always() && github.repository_owner == 'metabase' && inputs.run-trunk == 'true' }}
# Important!
# 1. This step must always run because it controls job's exit code.
# 2. There's no point in running this outside the organization
if: always() && github.repository_owner == 'metabase'
uses: trunk-io/analytics-uploader@main
# For "info" drivers off master/release branches, our own status takes precedence: we let this
# step pass so the job is reported as passing regardless of the real outcome (still uploaded).
# On master and release branches, info status is ignored and the real outcome gates the job.
continue-on-error: ${{ inputs.driver-status == 'info' && !(github.ref_name == 'master' || startsWith(github.ref_name, 'release-x')) }}
uses: trunk-io/analytics-uploader@1198efcc0976501147b10a7e343c3fa069527526 # v2.0.9
env:
TRUNK_REPO_URL: git@github.com:metabase/metabase.git
with:
@@ -62,3 +81,105 @@ runs:
token: ${{ inputs.trunk-api-token }}
use-cache: true
previous-step-outcome: ${{ inputs.previous-step-outcome }}
# For "info" drivers the job is forced green above, so surface the real outcome here —
# but only when it did NOT pass, to avoid spamming summaries/comments for healthy runs.
# Never include logs or stack traces — only the real status and a link to the run.
- name: Report info-level driver result (job summary)
if: ${{ always() && inputs.driver-status == 'info' && inputs.previous-step-outcome == 'failure' }}
shell: bash
env:
OUTCOME: ${{ inputs.previous-step-outcome }}
LABEL: ${{ inputs.output-name }}
VARIANT: ${{ inputs.report-variant }}
run: | # sh
if [ "$OUTCOME" = "success" ]; then EMOJI="✅"; else EMOJI="❌"; fi
TITLE="$LABEL"
[ -n "$VARIANT" ] && TITLE="$LABEL ($VARIANT)"
RUN_URL="$GITHUB_SERVER_URL/$GITHUB_REPOSITORY/actions/runs/$GITHUB_RUN_ID"
{
echo "### ℹ️ Info-level driver: $TITLE"
echo ""
echo "Reported as passing (non-blocking). Real result: $EMOJI \`$OUTCOME\`"
echo ""
echo "[View run]($RUN_URL)"
} >> "$GITHUB_STEP_SUMMARY"
# Maintain ONE PR comment per commit for all info drivers. Each leg upserts its own line
# (keyed by a hidden tag); a passing leg removes its line, and the comment is deleted once
# no failing legs remain. Comments from older commits are cleaned up. Runs on pass and fail
# so recoveries self-heal. Never includes logs or stack traces — only status and a run link.
- name: Sync info-level driver result into the PR comment
if: ${{ always() && inputs.driver-status == 'info' && github.event_name == 'pull_request' }}
uses: actions/github-script@v9
continue-on-error: true
env:
OUTCOME: ${{ inputs.previous-step-outcome }}
LABEL: ${{ inputs.output-name }}
VARIANT: ${{ inputs.report-variant }}
with:
script: | # js
const { OUTCOME, LABEL, VARIANT, GITHUB_SERVER_URL, GITHUB_REPOSITORY, GITHUB_RUN_ID } = process.env;
const pr = context.payload.pull_request;
if (!pr) return;
const { owner, repo } = context.repo;
const sha = pr.head.sha;
// PREFIX matches the current per-commit marker AND the older per-leg one, so legacy
// comments from a previous version get cleaned up on the next sync.
const PREFIX = "<!-- info-driver-result";
const marker = `<!-- info-driver-results:${sha} -->`;
const header = `${marker}\nℹ️ **Info-level drivers** failed (non-blocking) on \`${sha.slice(0, 7)}\` — these do not gate:`;
const lineKey = `${LABEL}:${VARIANT}`;
const title = VARIANT ? `${LABEL} (${VARIANT})` : LABEL;
const runUrl = `${GITHUB_SERVER_URL}/${GITHUB_REPOSITORY}/actions/runs/${GITHUB_RUN_ID}`;
// Only real failures are reported; cancelled/skipped/success remove this leg's line.
// List-item line with the hidden key tag at the END so markdown (links) renders.
const ourLine = OUTCOME === "failure"
? `- **${title}** — ❌ \`${OUTCOME}\` ([Logs](${runUrl})) <!--l:${lineKey}-->`
: null;
const linesOf = (body) => body.split("\n").filter((l) => l.includes("<!--l:"));
const sync = async () => {
const { data: comments } = await github.rest.issues.listComments({
owner, repo, issue_number: pr.number, per_page: 100,
});
const tagged = comments.filter((c) => c.body.includes(PREFIX));
// Drop comments left over from older commits.
for (const c of tagged.filter((c) => !c.body.includes(marker))) {
await github.rest.issues.deleteComment({ owner, repo, comment_id: c.id }).catch(() => {});
}
const mine = tagged
.filter((c) => c.body.includes(marker))
.sort((a, b) => new Date(a.created_at) - new Date(b.created_at));
// Merge any duplicates raced into existence; latest write of each line wins.
const byKey = new Map();
for (const c of mine) {
for (const l of linesOf(c.body)) {
const m = l.match(/<!--l:(.*?)-->/);
if (m) byKey.set(m[1], l);
}
}
if (ourLine) byKey.set(lineKey, ourLine);
else byKey.delete(lineKey);
const lines = [...byKey.values()].sort();
const target = mine[0];
for (const c of mine.slice(1)) {
await github.rest.issues.deleteComment({ owner, repo, comment_id: c.id }).catch(() => {});
}
if (lines.length === 0) {
if (target) await github.rest.issues.deleteComment({ owner, repo, comment_id: target.id }).catch(() => {});
return;
}
const body = [header, "", ...lines].join("\n");
if (target) {
await github.rest.issues.updateComment({ owner, repo, comment_id: target.id, body });
} else {
await github.rest.issues.createComment({ owner, repo, issue_number: pr.number, body });
}
};
// Retry to shrink the window where parallel legs clobber each other's update.
for (let i = 0; i < 4; i++) {
try { await sync(); break; }
catch (e) { if (i === 3) throw e; await new Promise((r) => setTimeout(r, 400 * (i + 1))); }
}

View File

@@ -7,6 +7,10 @@ default: &default
- "locales/**"
- "bin/**/!(*.md)"
actionlint:
- ".github/workflows/*.yml"
- ".github/workflows/*.yaml"
shared_sources: &shared_sources
- "src/**/*.cljc"
- "src/**/*.cljs"
@@ -95,6 +99,12 @@ frontend_loki_infra: &frontend_loki_infra
- *shared_ci
- *frontend_loki_ci
# e2e harness/support code (commands, support file, runner). Not in the
# instrumented bundle, so it maps to no covered module — a change here forces a
# full e2e run (see create-test-plan / e2eInfraTouched).
e2e_infra: &e2e_infra
- *shared_e2e
backend_ci: &backend_ci
- *shared_ci
- ".github/actions/test-driver/**"
@@ -195,6 +205,9 @@ documentation:
- "docs/**"
- "**/*.md"
docs:
- "docs/**"
embedding_documentation:
- ".typedoc/**"
- "docs/embedding/**"

View File

@@ -1,32 +1,191 @@
import micromatch from "micromatch";
export type ModuleDef = { type: string; pattern: string };
export type Rule = { from: string[]; allow: string[] };
type ModuleNode = { type: string; regex: RegExp };
export type ModuleNode = { type: string; regex: RegExp };
export type FileDependency = { source: string; dependencies: string[] };
/** First match wins, so element order matters for nested patterns. */
export function buildNodes(elements: ModuleDef[]): ModuleNode[] {
return elements.map((el) => ({
type: el.type,
// dot:true so files in dot-directories (e.g. .storybook) still match.
regex: micromatch.makeRe(el.pattern, { dot: true }),
}));
}
export function mapFileToModule(
nodes: ModuleNode[],
path: string,
): string | null {
for (const node of nodes) {
if (node.regex.test(path)) {
return node.type;
}
}
return null;
}
export function getChangedModules(
nodes: ModuleNode[],
changedFiles: string[],
): Set<string> {
const direct = new Set<string>();
for (const file of changedFiles) {
const module = mapFileToModule(nodes, file);
if (module) {
direct.add(module);
}
}
return direct;
}
export type FileGraph = {
nodes: ModuleNode[];
fileDependents: Map<string, Set<string>>;
};
/** Drops unresolvable imports (e.g. ambient types) that point at no real file. */
export function parseCruiseModules(
modules: Array<{
source: string;
dependencies?: Array<{ resolved: string; couldNotResolve?: boolean }>;
}>,
): FileDependency[] {
return modules.map((module) => ({
source: module.source,
dependencies: (module.dependencies ?? [])
.filter((dep) => !dep.couldNotResolve)
.map((dep) => dep.resolved),
}));
}
/** Inverts the import edges into the `fileDependents` reverse graph. */
export function buildFileGraph(
elements: ModuleDef[],
fileDependencies: FileDependency[],
): FileGraph {
const fileDependents = new Map<string, Set<string>>();
for (const { source, dependencies } of fileDependencies) {
for (const target of dependencies) {
let importers = fileDependents.get(target);
if (!importers) {
importers = new Set();
fileDependents.set(target, importers);
}
importers.add(source);
}
}
return { nodes: buildNodes(elements), fileDependents };
}
/** Changed files plus every file that transitively imports them. */
export function getAffectedFiles(
fileGraph: FileGraph,
changedFiles: string[],
): Set<string> {
const affected = new Set(changedFiles);
const queue = [...changedFiles];
while (queue.length > 0) {
const file = queue.shift()!;
for (const importer of fileGraph.fileDependents.get(file) ?? []) {
if (!affected.has(importer)) {
affected.add(importer);
queue.push(importer);
}
}
}
return affected;
}
export type ModuleGraph = {
nodes: ModuleNode[];
/**
* dependents.get(M) is every module affected when M changes — the full
* transitive closure, so getAffectedModules only needs a single hop.
*/
dependents: Map<string, Set<string>>;
};
/** Expands a direct-dependents map into its transitive closure. */
function transitiveClosure(
direct: Map<string, Set<string>>,
): Map<string, Set<string>> {
const closure = new Map<string, Set<string>>();
for (const start of direct.keys()) {
const reached = new Set<string>();
const queue = [...(direct.get(start) ?? [])];
while (queue.length > 0) {
const node = queue.shift()!;
if (reached.has(node)) {
continue;
}
reached.add(node);
for (const next of direct.get(node) ?? []) {
queue.push(next);
}
}
reached.delete(start);
closure.set(start, reached);
}
return closure;
}
/**
* Compiles a glob pattern to an anchored RegExp.
* Builds a module graph from the actual import graph. Reachability is computed
* per module at the file level and then collapsed to modules.
*/
export function globToRegex(glob: string): RegExp {
const escapeSegment = (seg: string) =>
seg.replace(/[.+?^${}()|[\]\\]/g, "\\$&").replace(/\*/g, "[^/]*");
const body = glob.split("**").map(escapeSegment).join(".*");
return new RegExp(`^${body}$`);
export function buildUsageModuleGraph(
elements: ModuleDef[],
fileDependencies: FileDependency[],
): ModuleGraph {
const nodes = buildNodes(elements);
const fileGraph = buildFileGraph(elements, fileDependencies);
const filesByModule = new Map<string, string[]>();
const allFiles = new Set<string>();
for (const { source, dependencies } of fileDependencies) {
allFiles.add(source);
for (const target of dependencies) {
allFiles.add(target);
}
}
for (const file of allFiles) {
const module = mapFileToModule(nodes, file);
if (module) {
const files = filesByModule.get(module);
if (files) {
files.push(file);
} else {
filesByModule.set(module, [file]);
}
}
}
const dependents = new Map<string, Set<string>>(
elements.map((el) => [el.type, new Set()]),
);
for (const [module, files] of filesByModule) {
const affected = new Set<string>();
for (const file of getAffectedFiles(fileGraph, files)) {
const owner = mapFileToModule(nodes, file);
if (owner && owner !== module) {
affected.add(owner);
}
}
dependents.set(module, affected);
}
return { nodes, dependents };
}
export function buildModuleGraph(
elements: ModuleDef[],
rules: Rule[],
): ModuleGraph {
const nodes = elements.map((el) => ({
type: el.type,
regex: globToRegex(el.pattern),
}));
const nodes = buildNodes(elements);
const allTypes = elements.map((e) => e.type);
function expandPattern(pattern: string): string[] {
@@ -40,9 +199,7 @@ export function buildModuleGraph(
return allTypes.includes(pattern) ? [pattern] : [];
}
// dependents.get(M) is the set of modules that depend on M
// i.e. modules that are affected when M changes
const dependents = new Map<string, Set<string>>(
const directDependents = new Map<string, Set<string>>(
allTypes.map((type) => [type, new Set()]),
);
for (const rule of rules) {
@@ -51,46 +208,13 @@ export function buildModuleGraph(
for (const target of allowTypes) {
for (const importer of fromTypes) {
if (importer !== target) {
dependents.get(target)?.add(importer);
directDependents.get(target)?.add(importer);
}
}
}
}
return { nodes, dependents };
}
/**
* Returns the module type that owns the given file.
* First match wins, so element ordering matters for nested patterns.
*/
export function mapFileToModule(
moduleGraph: ModuleGraph,
path: string,
): string | null {
for (const el of moduleGraph.nodes) {
if (el.regex.test(path)) {
return el.type;
}
}
return null;
}
/**
* Returns the set of module types containing any of the changed files.
*/
export function getChangedModules(
moduleGraph: ModuleGraph,
changedFiles: string[],
): Set<string> {
const direct = new Set<string>();
for (const file of changedFiles) {
const module = mapFileToModule(moduleGraph, file);
if (module) {
direct.add(module);
}
}
return direct;
return { nodes, dependents: transitiveClosure(directDependents) };
}
/**
@@ -100,16 +224,10 @@ export function getAffectedModules(
moduleGraph: ModuleGraph,
changedFiles: string[],
): Set<string> {
const direct = getChangedModules(moduleGraph, changedFiles);
const affected = new Set(direct);
const queue = [...direct];
while (queue.length > 0) {
const module = queue.shift()!;
const affected = getChangedModules(moduleGraph.nodes, changedFiles);
for (const module of [...affected]) {
for (const dep of moduleGraph.dependents.get(module) ?? []) {
if (!affected.has(dep)) {
affected.add(dep);
queue.push(dep);
}
affected.add(dep);
}
}
return affected;

View File

@@ -1,8 +1,13 @@
import {
buildFileGraph,
buildModuleGraph,
buildNodes,
buildUsageModuleGraph,
getAffectedFiles,
getAffectedModules,
getChangedModules,
mapFileToModule,
parseCruiseModules,
} from "./affected-modules";
const ELEMENTS = [
@@ -31,6 +36,7 @@ const RULES = [
{ from: ["app/*"], allow: ["lib/*", "feature/*", "app/*"] },
];
const nodes = buildNodes(ELEMENTS);
const graph = buildModuleGraph(ELEMENTS, RULES);
describe("affected modules", () => {
@@ -49,19 +55,19 @@ describe("affected modules", () => {
["external/lib/foo.ts", "feature/external"],
["src/embed.tsx", "app/main"],
])("should map %s to %s", (path, expected) => {
expect(mapFileToModule(graph, path)).toBe(expected);
expect(mapFileToModule(nodes, path)).toBe(expected);
});
it("should return null for files outside any pattern", () => {
expect(mapFileToModule(graph, "docs/foo.md")).toBe(null);
expect(mapFileToModule(graph, "README.md")).toBe(null);
expect(mapFileToModule(graph, "external/notlib/foo.ts")).toBe(null);
expect(mapFileToModule(nodes, "docs/foo.md")).toBe(null);
expect(mapFileToModule(nodes, "README.md")).toBe(null);
expect(mapFileToModule(nodes, "external/notlib/foo.ts")).toBe(null);
});
});
describe("getChangedModules", () => {
it("should return the unique set of modules whose files changed", () => {
const result = getChangedModules(graph, [
const result = getChangedModules(nodes, [
"src/utils/colors.ts",
"src/foo/x.ts",
"src/foo/y.ts",
@@ -71,11 +77,81 @@ describe("affected modules", () => {
});
it("should return an empty set when no file maps to a module", () => {
expect(getChangedModules(graph, ["docs/foo.md"]).size).toBe(0);
expect(getChangedModules(nodes, ["docs/foo.md"]).size).toBe(0);
});
});
describe("getAffectedModules", () => {
describe("parseCruiseModules", () => {
it("should flatten to source + resolved-paths and drop unresolved deps", () => {
expect(
parseCruiseModules([
{
source: "src/foo/foo.tsx",
dependencies: [
{ resolved: "src/utils/colors.ts" },
{ resolved: "ambient/types", couldNotResolve: true },
],
},
{ source: "src/bar/bar.tsx" }, // no dependencies key
]),
).toEqual([
{ source: "src/foo/foo.tsx", dependencies: ["src/utils/colors.ts"] },
{ source: "src/bar/bar.tsx", dependencies: [] },
]);
});
});
const FILE_DEPS = [
{ source: "src/app.js", dependencies: ["src/foo/foo.tsx"] },
{ source: "src/bar/bar.tsx", dependencies: ["src/embed.tsx"] },
{ source: "src/foo/foo.tsx", dependencies: ["src/utils/colors.ts"] },
];
const fileGraph = buildFileGraph(ELEMENTS, FILE_DEPS);
describe("getAffectedFiles", () => {
it("should return the changed file and everything that imports it", () => {
expect(
[...getAffectedFiles(fileGraph, ["src/utils/colors.ts"])].sort(),
).toEqual(["src/app.js", "src/foo/foo.tsx", "src/utils/colors.ts"]);
});
it("should include a changed file with no importers (itself only)", () => {
// Nothing imports the app.js entry point.
expect([...getAffectedFiles(fileGraph, ["src/app.js"])]).toEqual([
"src/app.js",
]);
});
});
describe("buildUsageModuleGraph + getAffectedModules", () => {
const usageGraph = buildUsageModuleGraph(ELEMENTS, FILE_DEPS);
it("should expand a changed module to its file-level affected modules", () => {
expect(
[...getAffectedModules(usageGraph, ["src/utils/colors.ts"])].sort(),
).toEqual(["app/main", "feature/foo", "lib/utils"]);
});
it("should NOT pull in feature/bar via the app/main hub", () => {
const affected = getAffectedModules(usageGraph, ["src/foo/foo.tsx"]);
expect([...affected].sort()).toEqual(["app/main", "feature/foo"]);
expect(affected.has("feature/bar")).toBe(false);
});
it("should treat the whole changed module as changed", () => {
// app.js itself has no importers, but app/main also owns embed.tsx, which
// feature/bar imports so changing any app/main file flags feature/bar.
expect(
[...getAffectedModules(usageGraph, ["src/app.js"])].sort(),
).toEqual(["app/main", "feature/bar"]);
});
it("should return empty when no file maps to a module", () => {
expect(getAffectedModules(usageGraph, ["docs/foo.md"]).size).toBe(0);
});
});
describe("getAffectedModules (rules graph)", () => {
it("should affect feature/super and app/main but not feature/bar when feature/foo changes", () => {
const result = getAffectedModules(graph, ["src/foo/x.ts"]);
expect([...result].sort()).toEqual([

View File

@@ -1,36 +1,40 @@
// Per-suite affected-tests logic: combines module-affected closure with
// per-suite "infra-touched" booleans (computed by dorny/paths-filter against
// the `frontend_unit_infra` / `frontend_loki_infra` anchors in file-paths.yaml).
// When infra files change, the whole suite runs in full.
// Builds the affected-tests plan from raw inputs: computes the rules and usage
// affected-module sets and selects, per suite, which specs to run under each.
import { getFeatureModules } from "../../frontend/lint/module-boundaries.mjs";
import {
type FileDependency,
type ModuleDef,
type ModuleGraph,
type ModuleNode,
type Rule,
buildModuleGraph,
buildUsageModuleGraph,
getAffectedModules,
getChangedModules,
mapFileToModule,
} from "./affected-modules";
export type TestSuiteDef = {
statsPrefix: string;
runAllTests?: boolean;
};
export type TestPlanStats = {
modules_changed: number;
modules_affected: number;
modules_affected_list: string[];
fe_unit_specs_total: number;
fe_unit_specs_run: number;
fe_unit_specs_skipped: number;
loki_stories_total: number;
loki_stories_run: number;
loki_stories_skipped: number;
e2e_specs_total: number;
e2e_specs_run: number;
e2e_specs_skipped: number;
fe_files_changed: number;
fe_files_total: number;
be_files_changed: number;
be_files_total: number;
unit_infra_touched: boolean;
loki_infra_touched: boolean;
shared_sources_touched: boolean;
fe_modules_total: number;
fe_modules_changed: number;
fe_modules_affected_rules: number;
fe_modules_affected_usage: number;
unit_specs_all: number;
unit_specs_to_run_rules: number;
unit_specs_to_run_usage: number;
loki_stories_all: number;
loki_stories_to_run_rules: number;
loki_stories_to_run_usage: number;
e2e_specs_all: number;
e2e_specs_to_run_rules: number;
e2e_specs_to_run_usage: number;
};
export type TestPlan = {
@@ -40,101 +44,187 @@ export type TestPlan = {
e2e_specs_to_run: string[];
};
export const TEST_SUITES = {
unit: {
statsPrefix: "fe_unit_specs",
},
loki: {
statsPrefix: "loki_stories",
},
e2e: {
statsPrefix: "e2e_specs",
// We don't map changed files to e2e tests yet, so for now just run them all
runAllTests: true,
},
} satisfies Record<string, TestSuiteDef>;
export function createTestPlan({
elements,
rules,
testSuites,
changedFiles,
testFilesBySuite,
infraTouchedBySuite,
}: {
export type CreateTestPlanInput = {
elements: ModuleDef[];
rules: Rule[];
testSuites: Record<string, TestSuiteDef>;
changedFiles: string[];
testFilesBySuite: Record<string, string[]>;
infraTouchedBySuite: Record<string, boolean>;
}): TestPlan {
const moduleGraph = buildModuleGraph(elements, rules);
// Parsed dependency-cruiser edges, or null to fall back to the rules graph.
fileDependencies: FileDependency[] | null;
testFilesBySuite: { unit: string[]; loki: string[]; e2e: string[] };
e2eSpecFiles: Record<string, string[]> | null;
unitInfraTouched: boolean;
lokiInfraTouched: boolean;
e2eInfraTouched: boolean;
sharedSourcesTouched: boolean;
feFilesChanged: number;
beFilesChanged: number;
feFilesTotal: number;
beFilesTotal: number;
};
const changedModules = getChangedModules(moduleGraph, changedFiles);
const modulesAffected = getAffectedModules(moduleGraph, changedFiles);
const modulesAffectedList = [...modulesAffected].sort();
const specsToRun: Record<string, string[]> = {};
const stats: Record<string, number | string[]> = {
modules_changed: changedModules.size,
modules_affected: modulesAffected.size,
modules_affected_list: modulesAffectedList,
};
for (const [name, testSuite] of Object.entries(testSuites)) {
const files = testFilesBySuite[name] ?? [];
const tests = createTestPlanForSuite(
moduleGraph,
testSuite,
infraTouchedBySuite[name] ?? false,
changedFiles,
files,
);
specsToRun[name] = tests;
stats[`${testSuite.statsPrefix}_total`] = files.length;
stats[`${testSuite.statsPrefix}_run`] = tests.length;
stats[`${testSuite.statsPrefix}_skipped`] = files.length - tests.length;
}
return {
stats: stats as TestPlanStats,
fe_unit_specs_to_run: specsToRun.unit ?? [],
loki_stories_to_run: specsToRun.loki ?? [],
e2e_specs_to_run: specsToRun.e2e ?? [],
};
}
/**
* Computes the test plan for one test suite
*
* Runs the full suite when `runAllTests` is set or `infraTouched` is true,
* otherwise runs the tests based on affected-modules.
*/
export function createTestPlanForSuite(
moduleGraph: ModuleGraph,
testSuite: TestSuiteDef,
infraTouched: boolean,
changedFiles: string[],
allTestFiles: string[],
): string[] {
if (testSuite.runAllTests || infraTouched) {
return allTestFiles;
}
const affected = getAffectedModules(moduleGraph, changedFiles);
return filterAffectedTests(moduleGraph, affected, allTestFiles);
}
/**
* Filters the test-file list down to tests whose owning module is affected.
*/
// Tests whose owning module is affected.
export function filterAffectedTests(
moduleGraph: ModuleGraph,
nodes: ModuleNode[],
affected: Set<string>,
testFiles: string[],
): string[] {
return testFiles.filter((file) => {
const module = mapFileToModule(moduleGraph, file);
const module = mapFileToModule(nodes, file);
return module !== null && affected.has(module);
});
}
// Collapse each spec's covered files to the *feature* modules it exercises,
// once, for reuse across the rules/usage selects. Non-feature tiers
// (shared/lib/...) are intentionally dropped: the manifest is a stale nightly
// artifact, so its coupling to the module graph stays minimal ("does this spec
// touch feature X?"). Accuracy comes from the fresh `affected` set, which
// already expands a shared/infra change into the feature modules that depend on
// it.
export function specFeatureModules(
nodes: ModuleNode[],
featureModules: Set<string>,
specFiles: Record<string, string[]>,
): Map<string, Set<string>> {
const moduleCache = new Map<string, string | null>();
const moduleOf = (file: string): string | null => {
let module = moduleCache.get(file);
if (module === undefined) {
module = mapFileToModule(nodes, file);
moduleCache.set(file, module);
}
return module;
};
const result = new Map<string, Set<string>>();
for (const [spec, files] of Object.entries(specFiles)) {
const features = new Set<string>();
for (const file of files) {
const module = moduleOf(file);
if (module !== null && featureModules.has(module)) {
features.add(module);
}
}
result.set(spec, features);
}
return result;
}
// A spec runs if any feature module it covers is affected.
// A spec doesn't map to any feature module always runs because its scope is unknown
export function filterAffectedE2eSpecs(
specFeatures: Map<string, Set<string>>,
affected: Set<string>,
e2eSpecs: string[],
): string[] {
return e2eSpecs.filter((spec) => {
const features = specFeatures.get(spec);
if (!features || features.size === 0) {
return true;
}
return [...features].some((module) => affected.has(module));
});
}
export function createTestPlan({
elements,
rules,
changedFiles,
fileDependencies,
testFilesBySuite,
e2eSpecFiles,
unitInfraTouched,
lokiInfraTouched,
e2eInfraTouched,
sharedSourcesTouched,
feFilesChanged,
beFilesChanged,
feFilesTotal,
beFilesTotal,
}: CreateTestPlanInput): TestPlan {
const rulesGraph = buildModuleGraph(elements, rules);
const usageGraph = fileDependencies
? buildUsageModuleGraph(elements, fileDependencies)
: rulesGraph;
const nodes = rulesGraph.nodes;
// Distinct module types (an element type can span several patterns).
const totalModules = new Set(elements.map((el) => el.type)).size;
const changedModules = getChangedModules(nodes, changedFiles);
const rulesAffected = getAffectedModules(rulesGraph, changedFiles);
const usageAffected = getAffectedModules(usageGraph, changedFiles);
// The coarse "feature" tier is the only set the e2e manifest is ever
// collapsed to (see filterAffectedE2eSpecs).
const featureModules = new Set(getFeatureModules(elements));
// cljc/cljs compile into the FE bundle, so they force a full run that module
// selection can't narrow — same effect as a suite's own infra changing.
const unitForceAll = unitInfraTouched || sharedSourcesTouched;
const lokiForceAll = lokiInfraTouched || sharedSourcesTouched;
// e2e is integration-level, so anything the FE-coverage manifest can't see
// forces a full run: cljc/cljs in the bundle (sharedSourcesTouched), a backend
// change that can break the UI (beFilesChanged), an e2e harness/support change
// (e2eInfraTouched), or no manifest at all.
const e2eForceAll =
sharedSourcesTouched ||
e2eInfraTouched ||
beFilesChanged > 0 ||
e2eSpecFiles === null;
const select = (forceAll: boolean, affected: Set<string>, files: string[]) =>
forceAll ? files : filterAffectedTests(nodes, affected, files);
const { unit, loki, e2e } = testFilesBySuite;
const unitRules = select(unitForceAll, rulesAffected, unit);
const unitUsage = select(unitForceAll, usageAffected, unit);
const lokiRules = select(lokiForceAll, rulesAffected, loki);
const lokiUsage = select(lokiForceAll, usageAffected, loki);
// Precompute spec -> feature modules once (null when e2e runs in full).
const specFeatures =
e2eForceAll || e2eSpecFiles === null
? null
: specFeatureModules(nodes, featureModules, e2eSpecFiles);
// A spec that was itself edited always runs, even when no app module changed.
const changedSet = new Set(changedFiles);
const selectE2e = (affected: Set<string>): string[] => {
if (specFeatures === null) {
return e2e;
}
const narrowed = new Set(
filterAffectedE2eSpecs(specFeatures, affected, e2e),
);
return e2e.filter((spec) => narrowed.has(spec) || changedSet.has(spec));
};
const e2eRules = selectE2e(rulesAffected);
const e2eUsage = selectE2e(usageAffected);
return {
stats: {
fe_files_changed: feFilesChanged,
fe_files_total: feFilesTotal,
be_files_changed: beFilesChanged,
be_files_total: beFilesTotal,
unit_infra_touched: unitInfraTouched,
loki_infra_touched: lokiInfraTouched,
shared_sources_touched: sharedSourcesTouched,
fe_modules_total: totalModules,
fe_modules_changed: changedModules.size,
fe_modules_affected_rules: rulesAffected.size,
fe_modules_affected_usage: usageAffected.size,
unit_specs_all: unit.length,
unit_specs_to_run_rules: unitRules.length,
unit_specs_to_run_usage: unitUsage.length,
loki_stories_all: loki.length,
loki_stories_to_run_rules: lokiRules.length,
loki_stories_to_run_usage: lokiUsage.length,
e2e_specs_all: e2e.length,
e2e_specs_to_run_rules: e2eRules.length,
e2e_specs_to_run_usage: e2eUsage.length,
},
fe_unit_specs_to_run: unitUsage,
loki_stories_to_run: lokiUsage,
e2e_specs_to_run: e2eUsage,
};
}

View File

@@ -1,9 +1,5 @@
import { buildModuleGraph } from "./affected-modules";
import {
createTestPlan,
createTestPlanForSuite,
filterAffectedTests,
} from "./affected-tests";
import { buildNodes } from "./affected-modules";
import { createTestPlan, filterAffectedTests } from "./affected-tests";
const ELEMENTS = [
{ type: "lib/utils", pattern: "src/utils/**" },
@@ -18,12 +14,6 @@ const RULES = [
{ from: ["feature/*"], allow: ["lib/*"] },
];
const TEST_SUITE_DEFS = {
unit: { statsPrefix: "fe_unit_specs" },
loki: { statsPrefix: "loki_stories" },
e2e: { statsPrefix: "e2e_specs", runAllTests: true },
};
const UNIT_FILES = [
"src/foo/foo.unit.spec.ts",
"src/foo/bar.unit.spec.ts",
@@ -33,158 +23,227 @@ const UNIT_FILES = [
const LOKI_FILES = ["src/foo/Foo.stories.tsx", "src/bar/Bar.stories.tsx"];
const E2E_FILES = ["e2e/test/scenarios/a.cy.spec.ts"];
const moduleGraph = buildModuleGraph(ELEMENTS, RULES);
const baseInput = {
elements: ELEMENTS,
rules: RULES,
fileDependencies: null,
testFilesBySuite: { unit: UNIT_FILES, loki: LOKI_FILES, e2e: E2E_FILES },
e2eSpecFiles: null,
unitInfraTouched: false,
lokiInfraTouched: false,
e2eInfraTouched: false,
sharedSourcesTouched: false,
feFilesChanged: 0,
beFilesChanged: 0,
feFilesTotal: 0,
beFilesTotal: 0,
};
describe("affected tests", () => {
describe("createTestPlanForSuite", () => {
it("should run all tests when infra is touched", () => {
const result = createTestPlanForSuite(
moduleGraph,
TEST_SUITE_DEFS.unit,
true, // infraTouched
["src/foo/x.ts"],
UNIT_FILES,
);
expect(result).toEqual(UNIT_FILES);
});
describe("createTestPlan", () => {
it("runs only specs in affected modules (rules graph)", () => {
const plan = createTestPlan({ ...baseInput, changedFiles: ["src/foo/x.ts"] });
it("should fall back to affected-tests filtering when infra not touched", () => {
const result = createTestPlanForSuite(
moduleGraph,
TEST_SUITE_DEFS.unit,
false, // infraTouched
["src/foo/x.ts"],
UNIT_FILES,
);
expect(result.sort()).toEqual([
"src/foo/bar.unit.spec.ts",
"src/foo/foo.unit.spec.ts",
]);
});
it("should return nothing when infra not touched and no file maps to a module", () => {
const result = createTestPlanForSuite(
moduleGraph,
TEST_SUITE_DEFS.unit,
false,
["docs/foo.md"],
UNIT_FILES,
);
expect(result).toEqual([]);
});
it("should run all tests for runAllTests suites regardless of inputs", () => {
expect(
createTestPlanForSuite(
moduleGraph,
TEST_SUITE_DEFS.e2e,
false,
["docs/foo.md"],
E2E_FILES,
),
).toEqual(E2E_FILES);
expect(
createTestPlanForSuite(
moduleGraph,
TEST_SUITE_DEFS.e2e,
false,
["src/foo/x.ts"],
E2E_FILES,
),
).toEqual(E2E_FILES);
});
expect(plan.stats.fe_modules_changed).toBe(1);
expect(plan.stats.fe_modules_affected_rules).toBe(1);
expect(plan.fe_unit_specs_to_run.sort()).toEqual([
"src/foo/bar.unit.spec.ts",
"src/foo/foo.unit.spec.ts",
]);
expect(plan.stats.unit_specs_to_run_rules).toBe(2);
expect(plan.stats.loki_stories_to_run_rules).toBe(1);
// With no file deps, usage falls back to rules.
expect(plan.stats.unit_specs_to_run_usage).toBe(2);
});
describe("createTestPlan", () => {
it("should return run lists and stats together", () => {
const result = createTestPlan({
elements: ELEMENTS,
rules: RULES,
testSuites: TEST_SUITE_DEFS,
changedFiles: ["src/foo/x.ts"],
testFilesBySuite: {
unit: UNIT_FILES,
loki: LOKI_FILES,
e2e: E2E_FILES,
},
infraTouchedBySuite: { unit: false, loki: false, e2e: false },
});
expect(result.fe_unit_specs_to_run.sort()).toEqual([
"src/foo/bar.unit.spec.ts",
"src/foo/foo.unit.spec.ts",
]);
expect(result.loki_stories_to_run).toEqual(["src/foo/Foo.stories.tsx"]);
expect(result.e2e_specs_to_run).toEqual(E2E_FILES);
expect(result.stats).toEqual({
modules_changed: 1,
modules_affected: 1,
modules_affected_list: ["feature/foo"],
fe_unit_specs_total: 4,
fe_unit_specs_run: 2,
fe_unit_specs_skipped: 2,
loki_stories_total: 2,
loki_stories_run: 1,
loki_stories_skipped: 1,
e2e_specs_total: 1,
e2e_specs_run: 1,
e2e_specs_skipped: 0,
});
it("narrows further with the usage graph than the rules graph", () => {
const plan = createTestPlan({
...baseInput,
changedFiles: ["src/utils/colors.ts"],
// Only feature/foo actually imports lib/utils.
fileDependencies: [
{ source: "src/foo/foo.tsx", dependencies: ["src/utils/colors.ts"] },
],
});
it("should run all unit specs when unit infra is touched", () => {
const result = createTestPlan({
elements: ELEMENTS,
rules: RULES,
testSuites: TEST_SUITE_DEFS,
changedFiles: ["docs/foo.md"],
testFilesBySuite: {
unit: UNIT_FILES,
loki: LOKI_FILES,
e2e: E2E_FILES,
},
infraTouchedBySuite: { unit: true, loki: false, e2e: false },
});
expect(result.stats.fe_unit_specs_run).toBe(UNIT_FILES.length);
expect(result.stats.fe_unit_specs_skipped).toBe(0);
// Only the unit suite was triggered.
expect(result.stats.loki_stories_run).toBe(0);
});
it("should not run anything when no infra is touched and no modules affected", () => {
const result = createTestPlan({
elements: ELEMENTS,
rules: RULES,
testSuites: TEST_SUITE_DEFS,
changedFiles: ["docs/foo.md"],
testFilesBySuite: {
unit: UNIT_FILES,
loki: LOKI_FILES,
e2e: E2E_FILES,
},
infraTouchedBySuite: { unit: false, loki: false, e2e: false },
});
expect(result.stats.fe_unit_specs_run).toBe(0);
expect(result.stats.loki_stories_run).toBe(0);
// e2e is runAllTests, so it still reports run = total.
expect(result.stats.e2e_specs_run).toBe(E2E_FILES.length);
});
// Rules allow both features to import lib/utils, so both are "affected".
expect(plan.stats.fe_modules_affected_rules).toBe(3);
// Usage sees only feature/foo + lib/utils.
expect(plan.stats.fe_modules_affected_usage).toBe(2);
expect(plan.stats.unit_specs_to_run_rules).toBe(4);
expect(plan.stats.unit_specs_to_run_usage).toBe(3);
});
describe("filterAffectedTests", () => {
it("should keep only tests inside affected modules", () => {
const affected = new Set(["feature/foo", "lib/utils"]);
const tests = [
"src/foo/foo.unit.spec.ts",
"src/utils/colors.unit.spec.ts",
"src/bar/bar.unit.spec.ts",
"docs/unrelated.unit.spec.ts",
];
expect(filterAffectedTests(moduleGraph, affected, tests)).toEqual([
"src/foo/foo.unit.spec.ts",
"src/utils/colors.unit.spec.ts",
]);
it("forces a full FE run on a shared-sources (cljc) change with no affected modules", () => {
const plan = createTestPlan({
...baseInput,
changedFiles: ["docs/readme.md"],
sharedSourcesTouched: true,
});
expect(plan.stats.fe_modules_affected_rules).toBe(0);
expect(plan.stats.unit_specs_to_run_rules).toBe(UNIT_FILES.length);
expect(plan.stats.unit_specs_to_run_usage).toBe(UNIT_FILES.length);
expect(plan.stats.loki_stories_to_run_rules).toBe(LOKI_FILES.length);
});
it("forces only the suite whose infra changed", () => {
const plan = createTestPlan({
...baseInput,
changedFiles: ["docs/readme.md"],
unitInfraTouched: true,
});
expect(plan.stats.unit_specs_to_run_rules).toBe(UNIT_FILES.length);
expect(plan.stats.loki_stories_to_run_rules).toBe(0);
});
it("runs the full e2e suite when no coverage manifest is available", () => {
const plan = createTestPlan({ ...baseInput, changedFiles: ["src/foo/x.ts"] });
expect(plan.stats.e2e_specs_to_run_rules).toBe(E2E_FILES.length);
expect(plan.stats.e2e_specs_to_run_usage).toBe(E2E_FILES.length);
expect(plan.e2e_specs_to_run).toEqual(E2E_FILES);
});
it("narrows e2e to specs covering affected feature modules", () => {
const e2e = [
"e2e/test/scenarios/foo.cy.spec.ts",
"e2e/test/scenarios/bar.cy.spec.ts",
"e2e/test/scenarios/new.cy.spec.ts",
];
const plan = createTestPlan({
...baseInput,
changedFiles: ["src/foo/x.ts"], // affects feature/foo only
testFilesBySuite: { unit: UNIT_FILES, loki: LOKI_FILES, e2e },
e2eSpecFiles: {
"e2e/test/scenarios/foo.cy.spec.ts": ["src/foo/a.ts"], // feature/foo
"e2e/test/scenarios/bar.cy.spec.ts": ["src/bar/b.ts"], // feature/bar
// new.cy.spec.ts intentionally absent from the manifest
},
});
// foo's feature module is affected; bar's is not; the unmapped new spec
// always runs.
expect(plan.e2e_specs_to_run.sort()).toEqual([
"e2e/test/scenarios/foo.cy.spec.ts",
"e2e/test/scenarios/new.cy.spec.ts",
]);
expect(plan.stats.e2e_specs_all).toBe(3);
});
it("runs a spec that maps to no feature module (unknown scope)", () => {
const e2e = ["e2e/test/scenarios/lib-only.cy.spec.ts"];
const plan = createTestPlan({
...baseInput,
changedFiles: ["src/foo/x.ts"], // affects feature/foo, NOT lib/utils
testFilesBySuite: { unit: UNIT_FILES, loki: LOKI_FILES, e2e },
e2eSpecFiles: {
// Covers only a non-feature module (e.g. a home/auth spec whose feature
// the baseline subtracted), so its feature scope is unknown.
"e2e/test/scenarios/lib-only.cy.spec.ts": ["src/utils/colors.ts"],
},
});
// No feature module to gate on -> can't bound scope -> always runs.
expect(plan.e2e_specs_to_run).toEqual(e2e);
});
it("force-runs all e2e on a backend change (invisible to FE coverage)", () => {
const e2e = ["e2e/test/scenarios/foo.cy.spec.ts"];
const plan = createTestPlan({
...baseInput,
changedFiles: ["src/metabase/api/card.clj"],
beFilesChanged: 1,
testFilesBySuite: { unit: UNIT_FILES, loki: LOKI_FILES, e2e },
e2eSpecFiles: { "e2e/test/scenarios/bar.cy.spec.ts": ["src/bar/b.ts"] },
});
expect(plan.e2e_specs_to_run).toEqual(e2e);
});
it("force-runs all e2e when e2e infra (support/runner) changes", () => {
const e2e = ["e2e/test/scenarios/foo.cy.spec.ts"];
const plan = createTestPlan({
...baseInput,
changedFiles: ["e2e/support/commands/api/createQuestion.js"],
e2eInfraTouched: true,
testFilesBySuite: { unit: UNIT_FILES, loki: LOKI_FILES, e2e },
e2eSpecFiles: { "e2e/test/scenarios/bar.cy.spec.ts": ["src/bar/b.ts"] },
});
expect(plan.e2e_specs_to_run).toEqual(e2e);
});
it("runs an edited spec even when no app module changed", () => {
const spec = "e2e/test/scenarios/foo.cy.spec.ts";
const e2e = [spec, "e2e/test/scenarios/bar.cy.spec.ts"];
const plan = createTestPlan({
...baseInput,
changedFiles: [spec], // only the spec itself changed
testFilesBySuite: { unit: UNIT_FILES, loki: LOKI_FILES, e2e },
e2eSpecFiles: {
[spec]: ["src/bar/b.ts"], // covers feature/bar, which is NOT affected
"e2e/test/scenarios/bar.cy.spec.ts": ["src/bar/b.ts"],
},
});
// No module is affected, but the edited spec must still run.
expect(plan.e2e_specs_to_run).toEqual([spec]);
});
it("runs a spec whose coverage was fully baseline-subtracted (empty files)", () => {
const e2e = ["e2e/test/scenarios/empty.cy.spec.ts"];
const plan = createTestPlan({
...baseInput,
changedFiles: ["src/foo/x.ts"], // affects feature/foo
testFilesBySuite: { unit: UNIT_FILES, loki: LOKI_FILES, e2e },
e2eSpecFiles: { "e2e/test/scenarios/empty.cy.spec.ts": [] },
});
// Empty coverage means unknown scope, so the spec runs.
expect(plan.e2e_specs_to_run).toEqual(e2e);
});
it("forces a full e2e run when shared (cljc) sources change", () => {
const e2e = ["e2e/test/scenarios/foo.cy.spec.ts"];
const plan = createTestPlan({
...baseInput,
changedFiles: ["src/foo/x.ts"],
sharedSourcesTouched: true,
testFilesBySuite: { unit: UNIT_FILES, loki: LOKI_FILES, e2e },
e2eSpecFiles: { "e2e/test/scenarios/bar.cy.spec.ts": ["src/bar/b.ts"] },
});
// Manifest is present but cljc is invisible to JS coverage, so run all.
expect(plan.e2e_specs_to_run).toEqual(e2e);
});
it("passes the FE/BE file counts through to stats", () => {
const plan = createTestPlan({
...baseInput,
changedFiles: [],
feFilesChanged: 5,
beFilesChanged: 3,
});
expect(plan.stats.fe_files_changed).toBe(5);
expect(plan.stats.be_files_changed).toBe(3);
});
});
describe("filterAffectedTests", () => {
it("keeps only tests inside affected modules", () => {
const nodes = buildNodes(ELEMENTS);
const affected = new Set(["feature/foo", "lib/utils"]);
const tests = [
"src/foo/foo.unit.spec.ts",
"src/utils/colors.unit.spec.ts",
"src/bar/bar.unit.spec.ts",
"docs/unrelated.unit.spec.ts",
];
expect(filterAffectedTests(nodes, affected, tests)).toEqual([
"src/foo/foo.unit.spec.ts",
"src/utils/colors.unit.spec.ts",
]);
});
});

View File

@@ -0,0 +1,152 @@
/* 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,87 @@
const { buildStatsRows } = require("./bundle-size-stats-prepare");
const meta = { date: "2026-06-30", commit: "abc123", commitMessage: "Fix the thing (#123)", version: "" };
const measurement = (over = {}) => ({
bundle: "embedding-sdk-chunked",
kind: "total",
rawBytes: 1000,
gzipBytes: 400,
brotliBytes: 300,
fileCount: 3,
...over,
});
describe("buildStatsRows", () => {
it("records the first point and leaves every delta empty", () => {
const result = buildStatsRows({
...meta,
measurements: [measurement()],
previous: [],
threshold: 1,
});
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]["Description"]).toBe("Fix the thing (#123)");
expect(result.cacheRows[0]).toEqual({
bundle: "embedding-sdk-chunked",
kind: "total",
rawBytes: 1000,
gzipBytes: 400,
brotliBytes: 300,
});
});
it("records a never-seen bundle/kind as a new series", () => {
const result = buildStatsRows({
...meta,
measurements: [measurement({ bundle: "app", kind: "initial" })],
previous: [{ bundle: "app", kind: "total", rawBytes: 1, gzipBytes: 1, brotliBytes: 1 }],
threshold: 99,
});
expect(result.hasNewSeries).toBe(true);
expect(result.significant).toBe(true);
expect(result.reason).toBe("new bundle/kind series");
});
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 big = buildStatsRows({
...meta,
measurements: [measurement({ brotliBytes: 315, gzipBytes: 400 })], // brotli +5%, gzip 0%
previous,
threshold: 1,
});
expect(big.maxServedDeltaPercent).toBeCloseTo(5);
expect(big.significant).toBe(true);
expect(big.rows[0]["Brotli delta %"]).toBeCloseTo(5);
const small = buildStatsRows({
...meta,
measurements: [measurement({ brotliBytes: 301, gzipBytes: 999 })], // brotli +0.33%, gzip ignored
previous,
threshold: 1,
});
expect(small.significant).toBe(false);
expect(small.reason).toContain("threshold 1%");
});
it("falls back to the gzip delta when the cached base predates brotli logging", () => {
const result = buildStatsRows({
...meta,
measurements: [measurement({ gzipBytes: 440, brotliBytes: 300 })], // gzip +10%
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]["Gzip delta %"]).toBeCloseTo(10);
});
});

View File

@@ -1,67 +1,112 @@
// Changed files come from dorny/paths-filter's `all_changed_files` output
// I/O entrypoint: gather inputs (env vars, the cruise graph, the test-file
// lists) and hand them to createTestPlan, which does the computing.
import { execFileSync } from "node:child_process";
import { existsSync, readFileSync } from "node:fs";
import micromatch from "micromatch";
import { elements, rules } from "../../frontend/lint/module-boundaries.mjs";
import { TEST_SUITES, createTestPlan } from "./affected-tests";
import { type FileDependency, parseCruiseModules } from "./affected-modules";
import { createTestPlan } from "./affected-tests";
import { listSpecFiles } from "./e2e-spec-globs.mjs";
const UNIT_ROOTS = ["frontend/src", "enterprise/frontend/src"];
const UNIT_GLOBS = [
"frontend/src/**/*.unit.spec.js",
"frontend/src/**/*.unit.spec.jsx",
"frontend/src/**/*.unit.spec.ts",
"frontend/src/**/*.unit.spec.tsx",
"enterprise/frontend/src/**/*.unit.spec.js",
"enterprise/frontend/src/**/*.unit.spec.jsx",
"enterprise/frontend/src/**/*.unit.spec.ts",
"enterprise/frontend/src/**/*.unit.spec.tsx",
"frontend/src/**/*.unit.spec.{js,jsx,ts,tsx}",
"enterprise/frontend/src/**/*.unit.spec.{js,jsx,ts,tsx}",
];
const STORY_ROOTS = ["frontend", "enterprise/frontend"];
const STORY_GLOBS = [
"frontend/**/*.stories.js",
"frontend/**/*.stories.jsx",
"frontend/**/*.stories.ts",
"frontend/**/*.stories.tsx",
"enterprise/frontend/**/*.stories.js",
"enterprise/frontend/**/*.stories.jsx",
"enterprise/frontend/**/*.stories.ts",
"enterprise/frontend/**/*.stories.tsx",
"frontend/**/*.stories.{js,jsx,ts,tsx}",
"enterprise/frontend/**/*.stories.{js,jsx,ts,tsx}",
];
const E2E_GLOBS = [
"e2e/test/scenarios/**/*.cy.spec.js",
"e2e/test/scenarios/**/*.cy.spec.jsx",
"e2e/test/scenarios/**/*.cy.spec.ts",
"e2e/test/scenarios/**/*.cy.spec.tsx",
];
function listFiles(globs: string[]): string[] {
return execFileSync("git", ["ls-files", "--", ...globs], { encoding: "utf8" })
// 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",
})
.split("\n")
.map((line) => line.trim())
.filter(Boolean);
return micromatch(tracked, globs, { dot: true });
}
const changedFiles = (process.env.CHANGED_FILES ?? "")
.split(",")
.map((s) => s.trim())
.filter(Boolean);
// dorny outputs comma-separated lists; CHANGED_FILES is `all_changed_files`.
const csvToList = (csv: string | undefined) =>
(csv ?? "")
.split(",")
.map((s) => s.trim())
.filter(Boolean);
// Reads the dependency-cruiser graph (DEP_GRAPH_JSON). Null falls back to the
// rules graph, so a missing or unparseable file never breaks the plan.
function readFileDependencies(): FileDependency[] | null {
const path = process.env.DEP_GRAPH_JSON;
if (path && existsSync(path)) {
try {
const { modules } = JSON.parse(readFileSync(path, "utf8"));
process.stderr.write(`Using usage graph from ${path}.\n`);
return parseCruiseModules(modules);
} catch (error) {
process.stderr.write(
`Failed to read ${path}; falling back to rules graph: ${error}\n`,
);
}
} else {
process.stderr.write(
"No DEP_GRAPH_JSON found; falling back to rules graph.\n",
);
}
return null;
}
// Reads the nightly coverage manifest (E2E_SPEC_MANIFEST): { builtAt, specs:
// { spec -> files } }. Returns the specs map, or null so e2e falls back to a
// full run when the manifest is missing/unparseable.
function readE2eSpecFiles(): Record<string, string[]> | null {
const path = process.env.E2E_SPEC_MANIFEST;
if (path && existsSync(path)) {
try {
const { specs } = JSON.parse(readFileSync(path, "utf8"));
if (specs && typeof specs === "object") {
process.stderr.write(`Using e2e coverage manifest from ${path}.\n`);
return specs;
}
} catch (error) {
process.stderr.write(
`Failed to read ${path}; e2e will run in full: ${error}\n`,
);
}
} else {
process.stderr.write("No E2E_SPEC_MANIFEST found; e2e will run in full.\n");
}
return null;
}
const testPlan = createTestPlan({
elements,
rules,
testSuites: TEST_SUITES,
changedFiles,
changedFiles: csvToList(process.env.CHANGED_FILES),
fileDependencies: readFileDependencies(),
testFilesBySuite: {
unit: listFiles(UNIT_GLOBS),
loki: listFiles(STORY_GLOBS),
e2e: listFiles(E2E_GLOBS),
},
infraTouchedBySuite: {
unit: process.env.UNIT_INFRA_TOUCHED === "true",
loki: process.env.LOKI_INFRA_TOUCHED === "true",
e2e: false,
unit: listFiles(UNIT_ROOTS, UNIT_GLOBS),
loki: listFiles(STORY_ROOTS, STORY_GLOBS),
e2e: listSpecFiles(),
},
e2eSpecFiles: readE2eSpecFiles(),
unitInfraTouched: process.env.UNIT_INFRA_TOUCHED === "true",
lokiInfraTouched: process.env.LOKI_INFRA_TOUCHED === "true",
e2eInfraTouched: process.env.E2E_INFRA_TOUCHED === "true",
sharedSourcesTouched: process.env.SHARED_SOURCES_TOUCHED === "true",
feFilesChanged: csvToList(process.env.FE_CHANGED_FILES).length,
beFilesChanged: csvToList(process.env.BE_CHANGED_FILES).length,
feFilesTotal: listFiles(["frontend", "enterprise/frontend"], ["**"]).length,
beFilesTotal: listFiles(["src", "enterprise/backend"], ["**"]).length,
});
process.stdout.write(JSON.stringify(testPlan) + "\n");

View File

@@ -19,23 +19,73 @@ function jsonToCsvFormData(jsonData) {
return formData;
}
function uploadCsvToMb({ baseUrl, tableId, jsonData, mode = 'append' }) {
const formData = jsonToCsvFormData(jsonData);
const operation = mode === 'replace' ? 'replace-csv' : 'append-csv';
// 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]);
return fetch(`${baseUrl}/api/table/${tableId}/${operation}`, {
method: 'POST',
headers: {
"x-api-key": process.env.API_KEY
},
body: formData
})
.then(response => {
if (!response.ok) {
throw new Error(`Upload failed`);
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);
}
return { success: true };
});
}
}
module.exports = { uploadCsvToMb };

50
.github/scripts/csv-to-mb.unit.spec.js vendored Normal file
View File

@@ -0,0 +1,50 @@
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);
});
});

32
.github/scripts/e2e-spec-globs.mjs vendored Normal file
View File

@@ -0,0 +1,32 @@
import { execFileSync } from "node:child_process";
import micromatch from "micromatch";
const SPEC_DIR = "e2e/test/scenarios";
// This is the nightly-only baseline helper that runs in the instrumented pass to
// capture boot-time coverage. It is not a product spec, so it is excluded from
// the test plan universe and from the manifest backfill reconciliation.
export const BASELINE_SPEC = `${SPEC_DIR}/coverage-baseline.cy.spec.js`;
// This glob set defines the spec "universe". The test planner
// (create-test-plan.ts) selects which specs to run from it, and the coverage
// manifest builder (build-coverage-manifest.mjs) reconciles against it when
// backfilling specs that did not run.
export const E2E_SPEC_GLOBS = [`${SPEC_DIR}/**/*.cy.spec.{js,jsx,ts,tsx}`];
// Returns the tracked e2e specs as repo-relative paths, excluding the baseline
// helper.
export function listSpecFiles(cwd = process.cwd()) {
const tracked = execFileSync("git", ["ls-files", "--", SPEC_DIR], {
cwd,
encoding: "utf8",
})
.split("\n")
.map((line) => line.trim())
.filter(Boolean);
return micromatch(tracked, E2E_SPEC_GLOBS, {
ignore: [BASELINE_SPEC],
dot: true,
});
}

258
.github/scripts/measure-bundle-sizes.js vendored Normal file
View File

@@ -0,0 +1,258 @@
/* eslint-disable import/no-commonjs */
// Measures the front-end bundles emitted into an extracted uberjar tree.
//
// Every bundle reports one or both of:
// - "initial": JS the browser downloads on first paint (the entry chunk plus
// its initial/sync split chunks). Never excludes initial chunks.
// - "total": all *reachable* JS (initial plus async chunks that are actually
// loadable at runtime). Never includes unreachable/never-fetched chunks.
// Reachability needs the per-entry asset list from the rspack stats file, so the
// app and chunked SDK bundles require their stats file to be present.
//
// The pure pieces — the asset-name selection (initial vs reachable, runtime
// filtering, the async-loadable flag) — are split out as select*Assets so they
// can be unit-tested against a stats object. The measure* functions and main()
// keep all the filesystem and env I/O, threading an explicit `config`.
const fs = require("fs");
const path = require("path");
const zlib = require("zlib");
const APP_DIST = "resources/frontend_client/app/dist";
const SDK_ROOT = "resources/frontend_client/app/embedding-sdk";
// The chunk runtime is inlined into the bootstrap, never sent as a standalone file.
const SDK_RUNTIME_RE = /embedding-sdk-chunk-runtime\./;
const notRuntime = name => !SDK_RUNTIME_RE.test(name);
const assetFiles = (root, names) => names.map(name => path.join(root, name));
const unique = files => [...new Set(files)];
// MEASURE_ROOT lets callers point at an extracted tree (e.g. the PR bundle-size
// check measures a current and a base-ref tree); defaults to cwd for the stats
// workflow. MEASURE_BUNDLES restricts which bundles are measured (comma-separated).
// SDK_ASYNC_CHUNKS_LOADABLE (see selectChunkedSdkAssets) toggles whether async
// SDK chunks count toward "total".
function buildConfig(env) {
const baseDir = env.MEASURE_ROOT ? path.resolve(env.MEASURE_ROOT) : process.cwd();
const bundleFilter = env.MEASURE_BUNDLES
? new Set(env.MEASURE_BUNDLES.split(",").map(bundle => bundle.trim()))
: null;
return {
resolve: (...relativeParts) => path.resolve(baseDir, ...relativeParts),
isBundleWanted: bundle => !bundleFilter || bundleFilter.has(bundle),
// Async SDK chunks are reachable once output.publicPath is set so import()
// chunks are actually fetched at runtime — which landed in master. Defaults
// to true to match master; set SDK_ASYNC_CHUNKS_LOADABLE=false to measure an
// older commit built before the publicPath fix (async unreachable, so
// "total" collapses to "initial").
sdkAsyncChunksLoadable: env.SDK_ASYNC_CHUNKS_LOADABLE !== "false",
};
}
function sizeOf(files) {
let rawBytes = 0;
let gzipBytes = 0;
let brotliBytes = 0;
for (const file of files) {
const contents = fs.readFileSync(file);
rawBytes += contents.length;
// gzip: recompressed, a proxy for the on-the-fly gzip served on every version
gzipBytes += zlib.gzipSync(contents).length;
// brotli: as-served — count the precompressed .br the build ships; files
// without one (static-viz, sub-threshold chunks) are served compressed on
// the fly, so estimate with brotli. Always reported (like gzip).
const brotliPath = `${file}.br`;
brotliBytes += fs.existsSync(brotliPath)
? fs.statSync(brotliPath).size
: zlib.brotliCompressSync(contents).length;
}
return {
fileCount: files.length,
rawBytes,
gzipBytes,
brotliBytes,
};
}
function collectJsFiles(absolutePath) {
if (fs.statSync(absolutePath).isFile()) {
return [absolutePath];
}
return fs
.readdirSync(absolutePath, { withFileTypes: true })
.flatMap(entry => {
const childPath = path.join(absolutePath, entry.name);
if (entry.isDirectory()) {
return collectJsFiles(childPath);
}
return entry.name.endsWith(".js") ? [childPath] : [];
});
}
function readStats(config, statsFile) {
const statsPath = config.resolve(statsFile);
return fs.existsSync(statsPath) ? JSON.parse(fs.readFileSync(statsPath, "utf8")) : null;
}
// An entrypoint's .js assets for a given field: "assets" = its initial
// (synchronous) load; "reachableAssets" = initial plus everything it can lazily
// import (the chunk graph walked at build time in bundle-stats.js).
function entrypointJsAssets(stats, name, field = "assets") {
const entry = stats && stats.entrypoints && stats.entrypoints[name];
if (!entry || !entry[field]) {
return null;
}
return entry[field].map(asset => asset.name || asset).filter(assetName => assetName.endsWith(".js"));
}
/**
* Main app = the app-main entrypoint only (app/dist also holds other pages like
* app-public, app-embed*, which are not the app). `reachableAssets` is null on
* older stats built before the chunk-graph enrichment — the caller then falls
* back to sizing the whole app/dist.
*/
function selectAppAssets(stats) {
const initialAssets = entrypointJsAssets(stats, "app-main", "assets");
if (!initialAssets) {
throw new Error('app: stats-main.json / "app-main" entrypoint missing');
}
return { initialAssets, reachableAssets: entrypointJsAssets(stats, "app-main", "reachableAssets") };
}
/**
* Legacy SDK: the "embedding-sdk" entry, a single eager file in legacy/. It still
* emits on-demand chunks (jspdf, echarts, leaflet, ...) into the shared chunks/
* dir via dynamic import(). initial = the eager legacy file; total = initial plus
* its reachable async chunks, but only when those are loadable at runtime
* (sdkAsyncChunksLoadable), otherwise total collapses to initial. Returns null
* when the stats lack the entry (older layout) so the caller can fall back.
*/
function selectLegacySdkAssets(stats, { sdkAsyncChunksLoadable }) {
const initialNames = entrypointJsAssets(stats, "embedding-sdk", "assets");
if (!initialNames) {
return null;
}
const reachableNames = entrypointJsAssets(stats, "embedding-sdk", "reachableAssets") || initialNames;
const initial = unique(initialNames).filter(notRuntime);
return {
initialNames: initial,
reachableNames: sdkAsyncChunksLoadable ? unique(reachableNames).filter(notRuntime) : initial,
};
}
/**
* Chunked SDK delivery. initial = bootstrap (minus its inlined runtime) + the
* chunked entry's initial chunks. total = the chunked entry's reachable set
* (initial + async children, from the chunk graph). includesAsyncChunks is true
* only when the stats carry the reachable chunk graph AND those chunks are
* loadable at runtime (sdkAsyncChunksLoadable). A base ref built before the
* reachableAssets enrichment has no graph, so its "total" must collapse to
* "initial" — the flag lets the comparison avoid measuring a reachable total
* against a collapsed one (an apples-to-oranges ~30% phantom).
*/
function selectChunkedSdkAssets(stats, { sdkAsyncChunksLoadable }) {
const chunkedInitial = entrypointJsAssets(stats, "embedding-sdk-chunked", "assets");
if (!chunkedInitial) {
throw new Error('embedding-sdk-chunked: stats-embedding-sdk.json / "embedding-sdk-chunked" entrypoint missing');
}
const bootstrapInitial = entrypointJsAssets(stats, "embedding-sdk-bootstrap", "assets") || [];
const chunkedReachableAssets = entrypointJsAssets(stats, "embedding-sdk-chunked", "reachableAssets");
const chunkedReachable = chunkedReachableAssets || chunkedInitial;
const bootstrapReachable = entrypointJsAssets(stats, "embedding-sdk-bootstrap", "reachableAssets") || bootstrapInitial;
return {
initialNames: unique([...bootstrapInitial, ...chunkedInitial]).filter(notRuntime),
reachableNames: unique([...bootstrapReachable, ...chunkedReachable]).filter(notRuntime),
includesAsyncChunks: chunkedReachableAssets != null && sdkAsyncChunksLoadable,
};
}
function measureApp(config) {
const dist = config.resolve(APP_DIST);
if (!fs.existsSync(dist)) {
throw new Error(`Bundle output not found for "app": ${dist}`);
}
const { initialAssets, reachableAssets } = selectAppAssets(readStats(config, "artifacts/stats-main.json"));
if (!reachableAssets) {
console.warn("app: stats has no reachableAssets; app total falls back to the whole app/dist");
}
const totalFiles = reachableAssets ? assetFiles(dist, reachableAssets) : collectJsFiles(dist);
return [
{ bundle: "app", kind: "initial", ...sizeOf(assetFiles(dist, initialAssets)) },
{ bundle: "app", kind: "total", ...sizeOf(totalFiles) },
];
}
function measureLegacySdk(config) {
const absRoot = config.resolve(SDK_ROOT);
const selected = selectLegacySdkAssets(readStats(config, "artifacts/stats-embedding-sdk.json"), config);
if (!selected) {
// No stats / older layout: fall back to whatever sits in the legacy dir.
const candidates = [`${SDK_ROOT}/legacy`, `${SDK_ROOT}.js`];
const chosen = candidates.find(candidate => fs.existsSync(config.resolve(candidate)));
if (!chosen) {
console.warn(`Skipping "embedding-sdk-legacy": output not found (${candidates.join(", ")})`);
return [];
}
return [{ bundle: "embedding-sdk-legacy", kind: "total", ...sizeOf(collectJsFiles(config.resolve(chosen))) }];
}
return [
{ bundle: "embedding-sdk-legacy", kind: "initial", ...sizeOf(assetFiles(absRoot, selected.initialNames)) },
{ bundle: "embedding-sdk-legacy", kind: "total", ...sizeOf(assetFiles(absRoot, selected.reachableNames)) },
];
}
function measureChunkedSdk(config) {
const chunksDir = config.resolve(SDK_ROOT, "chunks");
if (!fs.existsSync(chunksDir)) {
// pre-chunked layout (monolith only) — nothing to measure here
return [];
}
const absRoot = config.resolve(SDK_ROOT);
const { initialNames, reachableNames, includesAsyncChunks } = selectChunkedSdkAssets(
readStats(config, "artifacts/stats-embedding-sdk.json"),
config,
);
const initial = sizeOf(assetFiles(absRoot, initialNames));
const total = includesAsyncChunks ? sizeOf(assetFiles(absRoot, reachableNames)) : initial;
return [
{ bundle: "embedding-sdk-chunked", kind: "initial", ...initial },
{ bundle: "embedding-sdk-chunked", kind: "total", reachable: includesAsyncChunks, ...total },
];
}
// Single-file/dir bundles loaded in one shot — total only.
function measureWholeDir(config, bundle, candidates) {
const chosen = candidates.find(candidate => fs.existsSync(config.resolve(candidate)));
if (!chosen) {
console.warn(`Skipping "${bundle}": output not found (${candidates.join(", ")})`);
return [];
}
return [{ bundle, kind: "total", ...sizeOf(collectJsFiles(config.resolve(chosen))) }];
}
const bundles = {
app: measureApp,
"embedding-sdk-legacy": measureLegacySdk,
"embedding-sdk-chunked": measureChunkedSdk,
"embedding-sdk-package": config => measureWholeDir(config, "embedding-sdk-package", ["resources/embedding-sdk/dist"]),
"embed-js": config => measureWholeDir(config, "embed-js", ["resources/frontend_client/app/embed.js"]),
};
function measureBundleSizes(config) {
return Object.entries(bundles)
.filter(([bundle]) => config.isBundleWanted(bundle))
.flatMap(([, measure]) => measure(config));
}
module.exports = {
measureBundleSizes,
buildConfig,
entrypointJsAssets,
selectAppAssets,
selectLegacySdkAssets,
selectChunkedSdkAssets,
};
if (require.main === module) {
console.log(JSON.stringify(measureBundleSizes(buildConfig(process.env)), null, 2));
}

View File

@@ -0,0 +1,87 @@
const {
entrypointJsAssets,
selectAppAssets,
selectLegacySdkAssets,
selectChunkedSdkAssets,
} = require("./measure-bundle-sizes");
const RUNTIME = "embedding-sdk-chunk-runtime.deadbeef.js";
const stats = entrypoints => ({ entrypoints });
describe("entrypointJsAssets", () => {
it("returns the .js asset names for a field, accepting strings or {name}", () => {
const s = stats({ app: { assets: [{ name: "a.js" }, "b.js", { name: "c.css" }] } });
expect(entrypointJsAssets(s, "app", "assets")).toEqual(["a.js", "b.js"]);
});
it("returns null when the entrypoint or field is absent", () => {
expect(entrypointJsAssets(stats({}), "missing")).toBeNull();
expect(entrypointJsAssets(null, "app")).toBeNull();
});
});
describe("selectAppAssets", () => {
it("returns the initial set and a null reachable set on pre-enrichment stats", () => {
const s = stats({ "app-main": { assets: ["main.js"] } });
expect(selectAppAssets(s)).toEqual({ initialAssets: ["main.js"], reachableAssets: null });
});
it("throws when the app-main entrypoint is missing", () => {
expect(() => selectAppAssets(stats({}))).toThrow("app-main");
});
});
describe("selectChunkedSdkAssets", () => {
const base = {
"embedding-sdk-chunked": { assets: ["a.js", RUNTIME], reachableAssets: ["a.js", "b.js", RUNTIME] },
"embedding-sdk-bootstrap": { assets: ["boot.js"], reachableAssets: ["boot.js"] },
};
it("merges bootstrap + chunked, drops the inlined runtime, and counts async chunks", () => {
const result = selectChunkedSdkAssets(stats(base), { sdkAsyncChunksLoadable: true });
expect(result.initialNames).toEqual(["boot.js", "a.js"]);
expect(result.reachableNames).toEqual(["boot.js", "a.js", "b.js"]);
expect(result.includesAsyncChunks).toBe(true);
});
it("collapses total to initial when async chunks are not loadable", () => {
const result = selectChunkedSdkAssets(stats(base), { sdkAsyncChunksLoadable: false });
expect(result.includesAsyncChunks).toBe(false);
});
it("collapses total to initial when the stats carry no reachable graph", () => {
const noGraph = { "embedding-sdk-chunked": { assets: ["a.js"] } };
const result = selectChunkedSdkAssets(stats(noGraph), { sdkAsyncChunksLoadable: true });
expect(result.reachableNames).toEqual(["a.js"]);
expect(result.includesAsyncChunks).toBe(false);
});
it("throws when the chunked entrypoint is missing", () => {
expect(() => selectChunkedSdkAssets(stats({}), { sdkAsyncChunksLoadable: true })).toThrow(
"embedding-sdk-chunked",
);
});
});
describe("selectLegacySdkAssets", () => {
it("returns null when the legacy entry is absent so the caller can fall back", () => {
expect(selectLegacySdkAssets(stats({}), { sdkAsyncChunksLoadable: true })).toBeNull();
});
it("expands total to the reachable async set when loadable", () => {
const s = stats({ "embedding-sdk": { assets: ["legacy.js"], reachableAssets: ["legacy.js", "chunk.js"] } });
expect(selectLegacySdkAssets(s, { sdkAsyncChunksLoadable: true })).toEqual({
initialNames: ["legacy.js"],
reachableNames: ["legacy.js", "chunk.js"],
});
});
it("collapses total to initial when async chunks are not loadable", () => {
const s = stats({ "embedding-sdk": { assets: ["legacy.js"], reachableAssets: ["legacy.js", "chunk.js"] } });
expect(selectLegacySdkAssets(s, { sdkAsyncChunksLoadable: false })).toEqual({
initialNames: ["legacy.js"],
reachableNames: ["legacy.js"],
});
});
});

123
.github/scripts/module-usage.ts vendored Normal file
View File

@@ -0,0 +1,123 @@
// Builds module-level "usage" maps: for each module, the set of modules that
// depend on it, both directly and indirectly
//
// Both are computed at the FILE level off the real dependency-cruiser import
// graph, then collapsed to module granularity at the very end.
//
// bunx depcruise frontend/src enterprise/frontend/src \
// --config .dependency-cruiser.cjs --output-type json > dependency-graph.json
// DEP_GRAPH_JSON=dependency-graph.json \
// OUT_JSON=usage.json OUT_DIRECT_JSON=usage-direct.json \
// bun .github/scripts/module-usage.ts
import { readFileSync, writeFileSync } from "node:fs";
import { elements } from "../../frontend/lint/module-boundaries.mjs";
import {
buildFileGraph,
getAffectedFiles,
mapFileToModule,
parseCruiseModules,
} from "./affected-modules";
const depGraphPath = process.env.DEP_GRAPH_JSON ?? "dependency-graph.json";
const { modules } = JSON.parse(readFileSync(depGraphPath, "utf8"));
const fileDependencies = parseCruiseModules(modules);
const fileGraph = buildFileGraph(elements, fileDependencies);
// Group every known source file by its owning module. We seed from the cruise
// output's `source` files plus everything that appears as a dependency target,
// so files imported but never importing are still covered.
const filesByModule = new Map<string, string[]>();
const allFiles = new Set<string>();
for (const { source, dependencies } of fileDependencies) {
allFiles.add(source);
for (const dep of dependencies) {
allFiles.add(dep);
}
}
for (const file of allFiles) {
const module = mapFileToModule(fileGraph.nodes, file);
if (!module) {
continue;
}
const list = filesByModule.get(module);
if (list) {
list.push(file);
} else {
filesByModule.set(module, [file]);
}
}
// Ensure every module appears as a key, even those nothing depends on.
const emptyDependents = (): Record<string, Set<string>> => {
const map: Record<string, Set<string>> = {};
for (const module of filesByModule.keys()) {
map[module] = new Set();
}
return map;
};
// DIRECT usage: module B directly depends on module A if any file in B imports
// any file in A — a single edge in the import graph, collapsed to modules.
const directDependents = emptyDependents();
for (const { source, dependencies } of fileDependencies) {
const importer = mapFileToModule(fileGraph.nodes, source);
if (!importer) {
continue;
}
for (const target of dependencies) {
const owner = mapFileToModule(fileGraph.nodes, target);
if (owner && owner !== importer) {
directDependents[owner].add(importer);
}
}
}
// TRANSITIVE usage: for each module, take all its files, walk the file-level
// reverse graph to get every file that transitively imports them, collapse to
// modules, and drop the module itself.
const transitiveDependents = emptyDependents();
for (const [module, files] of filesByModule) {
const affectedFiles = getAffectedFiles(fileGraph, files);
for (const file of affectedFiles) {
const owner = mapFileToModule(fileGraph.nodes, file);
if (owner && owner !== module) {
transitiveDependents[module].add(owner);
}
}
}
// Stable, sorted output for clean diffs.
const toSorted = (
map: Record<string, Set<string>>,
): Record<string, string[]> => {
const sorted: Record<string, string[]> = {};
for (const module of Object.keys(map).sort()) {
sorted[module] = [...map[module]].sort();
}
return sorted;
};
const writeOut = (
map: Record<string, Set<string>>,
outVar: string,
label: string,
) => {
const sorted = toSorted(map);
const json = JSON.stringify(sorted, null, 2) + "\n";
const outPath = process.env[outVar];
if (outPath) {
writeFileSync(outPath, json);
process.stderr.write(
`Wrote ${Object.keys(sorted).length} modules (${label}) to ${outPath}.\n`,
);
} else {
process.stdout.write(json);
}
};
writeOut(transitiveDependents, "OUT_JSON", "transitive");
writeOut(directDependents, "OUT_DIRECT_JSON", "direct");

View File

@@ -0,0 +1,94 @@
/**
* Resolves the nightly e2e coverage manifest closest to a commit's point in
* history, so the test planner can narrow the e2e run.
*
* The whole flow lives here so callers "just get a manifest": list the retained
* manifest artifacts, find the one whose nightly commit is the nearest ancestor
* of `headSha` (via the GitHub compare API — no deep clone), download and unzip
* just that one, and return its parsed contents.
*
* `github` is an authenticated Octokit, as injected by actions/github-script.
* Returns { builtAt, specs, path, behindBy } or null when nothing is an
* ancestor (caller then runs e2e in full). Never throws: any API/IO failure is
* logged and resolves to null, because coverage resolution must not break the
* test plan.
*/
import { execFileSync } from "node:child_process";
import fs from "node:fs";
const ARTIFACT_NAME = "spec-file-manifest";
const EXTRACT_DIR = "e2e/coverage";
const MANIFEST_PATH = `${EXTRACT_DIR}/${ARTIFACT_NAME}.json`;
export async function resolveCoverageManifest({
github,
owner,
repo,
headSha,
log = console.log,
}) {
try {
// Every retained manifest artifact, newest first. Each carries its
// nightly's head_sha — the commit it was built from (== builtAt).
const artifacts = await github.paginate(
github.rest.actions.listArtifactsForRepo,
{ owner, repo, name: ARTIFACT_NAME, per_page: 100 },
);
const candidates = artifacts
.filter((artifact) => !artifact.expired && artifact.workflow_run?.head_sha)
.sort(
(a, b) =>
new Date(b.created_at).getTime() - new Date(a.created_at).getTime(),
);
// First candidate that is an ancestor of head is the closest in history
// (master is linear, candidates are chronological). compare base...head:
// behind_by === 0 ⇒ base is an ancestor of head; ahead_by is the distance.
let chosen = null;
for (const artifact of candidates) {
const base = artifact.workflow_run.head_sha;
// A stale candidate (force-pushed/GC'd commit) makes compare 404 — skip
// it rather than lose the optimization for everyone.
let comparison;
try {
({ data: comparison } =
await github.rest.repos.compareCommitsWithBasehead({
owner,
repo,
basehead: `${base}...${headSha}`,
}));
} catch {
continue;
}
if (comparison.behind_by === 0) {
chosen = { artifact, base, behindBy: comparison.ahead_by };
break;
}
}
if (!chosen) {
log("No ancestor coverage manifest found; e2e will run in full.");
return null;
}
const download = await github.rest.actions.downloadArtifact({
owner,
repo,
artifact_id: chosen.artifact.id,
archive_format: "zip",
});
fs.writeFileSync(`${ARTIFACT_NAME}.zip`, Buffer.from(download.data));
execFileSync("unzip", ["-o", `${ARTIFACT_NAME}.zip`, "-d", EXTRACT_DIR]);
const manifest = JSON.parse(fs.readFileSync(MANIFEST_PATH, "utf8"));
log(
`Using coverage manifest ${chosen.base.slice(0, 12)} ` +
`(${chosen.behindBy} commits behind HEAD).`,
);
return { ...manifest, path: MANIFEST_PATH, behindBy: chosen.behindBy };
} catch (error) {
log(`Coverage manifest resolution failed; e2e will run in full: ${error}`);
return null;
}
}

View File

@@ -19,7 +19,8 @@ while [[ $# -gt 0 ]]; do
done
echo "Cloning python-runner repository..."
git clone --depth 1 https://${METABASE_AUTOMATION_USER_TOKEN}@github.com/metabase/python-runner-container.git python-runner
git clone --depth 1 https://${METABASE_AUTOMATION_USER_TOKEN}@github.com/metabase/python-runner-container.git --branch seccomp python-runner
if [ "$SKIP_START" = false ]; then
echo "Starting python-runner..."

View File

@@ -1,41 +1,64 @@
// This script is used in .github/workflows/run-tests.yml.
// It uploads the test-plan stats row produced by create-test-plan.js to
// the stats.metabase.com tracking table.
// Reads STATS_JSON, PR_NUMBER, HEAD_SHA, BASE_SHA, API_KEY from env.
// 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.
const { uploadCsvToMb } = require("./csv-to-mb.js");
const stats = JSON.parse(process.env.STATS_JSON);
console.log("stats", stats);
// "FE Affected Tests" uploaded table on stats.metabase.com.
const TABLE_ID = 81818;
const row = {
Date: new Date().toISOString(),
PR: Number(process.env.PR_NUMBER),
"Head SHA": process.env.HEAD_SHA,
"Base SHA": process.env.BASE_SHA,
"Modules changed": stats.modules_changed,
"Modules affected": stats.modules_affected,
"FE Unit specs total": stats.fe_unit_specs_total,
"FE Unit specs run": stats.fe_unit_specs_run,
"FE Unit specs skipped": stats.fe_unit_specs_skipped,
"Loki stories total": stats.loki_stories_total,
"Loki stories run": stats.loki_stories_run,
"Loki stories skipped": stats.loki_stories_skipped,
"E2E specs total": stats.e2e_specs_total,
"E2E specs run": stats.e2e_specs_run,
"E2E specs skipped": stats.e2e_specs_skipped,
};
async function main() {
// create-test-plan doesn't always produce stats (e.g. on release branches
// running an older planner), leaving STATS_JSON empty. Nothing to upload.
const raw = (process.env.STATS_JSON || "").trim();
if (!raw || raw === "null") {
console.log("No STATS_JSON to upload; skipping.");
return;
}
uploadCsvToMb({
baseUrl: "https://stats.metabase.com",
tableId: 77008, // "Affected Tests Stats" table on stats.metabase.com
jsonData: [row],
mode: "append",
})
.then(() => {
console.log("Data uploaded successfully");
})
.catch((error) => {
console.error("Error uploading data:", error);
process.exit(1);
const s = JSON.parse(raw);
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,
PR: Number(process.env.PR_NUMBER),
"Head SHA": process.env.HEAD_SHA,
"Base SHA": process.env.BASE_SHA,
"FE Files Changed": s.fe_files_changed,
"FE Files Total": s.fe_files_total,
"BE Files Changed": s.be_files_changed,
"BE Files Total": s.be_files_total,
"Unit Infra Touched": s.unit_infra_touched,
"Loki Infra Touched": s.loki_infra_touched,
"Shared Sources Touched": s.shared_sources_touched,
"FE Modules Total": s.fe_modules_total,
"FE Modules Changed": s.fe_modules_changed,
"FE Modules Affected (Rules)": s.fe_modules_affected_rules,
"FE Modules Affected (Usage)": s.fe_modules_affected_usage,
"Unit Specs All": s.unit_specs_all,
"Unit Specs To Run (Rules)": s.unit_specs_to_run_rules,
"Unit Specs To Run (Usage)": s.unit_specs_to_run_usage,
"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,
};
await uploadCsvToMb({
baseUrl: "https://stats.metabase.com",
tableId: TABLE_ID,
jsonData: [row],
mode: "append",
});
console.log("Data uploaded successfully");
}
// Best-effort: never let a telemetry failure turn the job red.
main().catch((error) => {
console.error("Skipping stats upload after error:", error);
process.exit(0);
});

12
.github/team.json vendored
View File

@@ -4,7 +4,6 @@
"name": "Querying Platform",
"label": ".Team/QueryingPlatform",
"members": [
"bshepherdson",
"metamben",
"rileythomp",
"camsaul",
@@ -48,7 +47,8 @@
"members": [
"fraserdrops",
"nemanjaglumac",
"romeovs"
"romeovs",
"ChrisVandoo"
]
},
{
@@ -89,11 +89,12 @@
"npfitz",
"johnswanson",
"nvoxland",
"edpaget",
"bshepherdson",
"deniskaber",
"andsalves",
"kevinkelleher12",
"AndreyChernykh"
"AndreyChernykh",
"bowbahdoe"
]
},
{
@@ -120,7 +121,8 @@
"iethree",
"bpander",
"gantoreno",
"losrebellos"
"losrebellos",
"tmashara"
]
}
]

42
.github/workflows/actionlint.yml vendored Normal file
View File

@@ -0,0 +1,42 @@
name: Actionlint
on:
push:
branches:
- 'master'
- 'release-**'
paths:
- '.github/workflows/**'
pull_request:
paths:
- '.github/workflows/**'
concurrency:
group: ${{ github.workflow }}-${{ github.head_ref && github.ref || github.run_id }}
cancel-in-progress: true
jobs:
actionlint:
name: Lint Github Actions Workflows
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
steps:
- uses: actions/checkout@v6
- name: Get changed Github actions
uses: dorny/paths-filter@fbd0ab8f3e69293af611ebaee6363fc25e6d187d # v4.0.1
id: changes
with:
token: ${{ github.token }}
filters: .github/file-paths.yaml
list-files: shell
- name: Setup actionlint
id: download
shell: bash
run: |
if command -v actionlint; then
echo "executable=actionlint" >> "$GITHUB_OUTPUT"
else
# script sets executable output, for details see: https://github.com/rhysd/actionlint/blob/main/docs/usage.md#use-actionlint-on-github-actions
bash <(curl -fsSL https://raw.githubusercontent.com/rhysd/actionlint/v1.7.12/scripts/download-actionlint.bash)
fi
- name: Run actionlint
run: ${{ steps.download.outputs.executable }} --color --verbose ${{ steps.changes.outputs.actionlint_files }}

View File

@@ -11,6 +11,13 @@ concurrency:
group: ${{ github.workflow }}-${{ github.head_ref && github.ref || github.run_id }}-app-db
cancel-in-progress: true
# Exposed to every job so the test-driver action can report failures to
# 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_WEBHOOK_SECRET: ${{ secrets.CI_CONDUCTOR_WEBHOOK_SECRET }}
jobs:
be-tests-mariadb:
if: ${{ !inputs.skip }}
@@ -69,7 +76,7 @@ jobs:
github.event_name == 'push' &&
(
github.ref_name == 'master' ||
startsWith(github.ref_name, 'release-')
startsWith(github.ref_name, 'release-x')
) &&
''
) ||
@@ -113,6 +120,7 @@ jobs:
test-args: >-
${{ matrix.job.test-args }}
:exclude-tags '[ ${{ matrix.job.exclude-tag }} ${{ env.__ADDITIONAL_EXCLUDED_TAG__ }}]'
quarantine-engine: ${{ vars.QUARANTINE_ENGINE }}
- name: Upload Test Results
uses: ./.github/actions/upload-test-results
if: always()
@@ -124,6 +132,7 @@ jobs:
aws-region: ${{ vars.AWS_REGION }}
trunk-api-token: ${{ secrets.TRUNK_API_TOKEN }}
previous-step-outcome: ${{ steps.test-driver.outputs.test-outcome }}
run-trunk: ${{ vars.QUARANTINE_ENGINE != 'ci-conductor' }}
be-tests-mysql:
if: ${{ !inputs.skip }}
@@ -184,7 +193,7 @@ jobs:
github.event_name == 'push' &&
(
github.ref_name == 'master' ||
startsWith(github.ref_name, 'release-')
startsWith(github.ref_name, 'release-x')
) &&
''
) ||
@@ -236,6 +245,7 @@ jobs:
test-args: >-
${{ matrix.job.test-args }}
:exclude-tags '[ ${{ matrix.job.exclude-tag }} ${{ env.__ADDITIONAL_EXCLUDED_TAG__ }}]'
quarantine-engine: ${{ vars.QUARANTINE_ENGINE }}
- name: Upload Test Results
uses: ./.github/actions/upload-test-results
if: always()
@@ -247,6 +257,7 @@ jobs:
aws-region: ${{ vars.AWS_REGION }}
trunk-api-token: ${{ secrets.TRUNK_API_TOKEN }}
previous-step-outcome: ${{ steps.test-driver.outputs.test-outcome }}
run-trunk: ${{ vars.QUARANTINE_ENGINE != 'ci-conductor' }}
be-tests-postgres:
if: ${{ !inputs.skip }}
@@ -300,7 +311,7 @@ jobs:
github.event_name == 'push' &&
(
github.ref_name == 'master' ||
startsWith(github.ref_name, 'release-')
startsWith(github.ref_name, 'release-x')
) &&
''
) ||
@@ -346,6 +357,7 @@ jobs:
test-args: >-
${{ matrix.job.test-args }}
:exclude-tags '[ ${{ matrix.job.exclude-tag }} ${{ env.__ADDITIONAL_EXCLUDED_TAG__ }}]'
quarantine-engine: ${{ vars.QUARANTINE_ENGINE }}
- name: Upload Test Results
uses: ./.github/actions/upload-test-results
if: always()
@@ -357,6 +369,7 @@ jobs:
aws-region: ${{ vars.AWS_REGION }}
trunk-api-token: ${{ secrets.TRUNK_API_TOKEN }}
previous-step-outcome: ${{ steps.test-driver.outputs.test-outcome }}
run-trunk: ${{ vars.QUARANTINE_ENGINE != 'ci-conductor' }}
app-db-tests-result:
needs:

View File

@@ -5,17 +5,94 @@ on:
types: [closed, labeled]
jobs:
create-backport:
# --- Primary path: backport to every supported release line --------------
# Triggered by the plain `backport` label. `contains(array, 'backport')` is an
# exact element match, so this never fires for `double-backport`/`triple-backport`
# — those are handled by the legacy escape hatch at the end of this file.
prepare:
if:
| # the PR must have a backport label when it's merged, or be labeled with a backport label after merge
| # the PR must carry the `backport` label at merge, or be labeled `backport` after merge
github.event.pull_request.merged == true && (
github.event.action == 'closed' && contains(github.event.pull_request.labels.*.name, 'backport') ||
github.event.action == 'labeled' && github.event.label.name == 'backport'
)
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
outputs:
commit: ${{ steps.find_commit.outputs.commit }}
targets: ${{ steps.targets.outputs.result }}
steps:
- uses: actions/checkout@v6
with:
fetch-depth: 0
token: ${{ secrets.METABASE_AUTOMATION_USER_TOKEN }}
- uses: ./.github/actions/find-squashed-commit
name: Find commit
id: find_commit
with:
pull-request-number: ${{ github.event.pull_request.number }}
base-ref: ${{ github.event.pull_request.base.ref }}
- name: Prepare release scripts
uses: ./.github/actions/prepare-release-scripts
- name: Compute supported backport targets
id: targets
uses: actions/github-script@v9
env:
AWS_S3_STATIC_BUCKET: ${{ vars.AWS_S3_STATIC_BUCKET }}
AWS_REGION: ${{ vars.AWS_REGION }}
with:
script: | # js
// Backport targets are the supported major lines from version-info.json:
// a line is in support — and a backport target — if and only if its EoL is
// today or later. `getSupportedMajors` encapsulates that rule (and ignores
// the display-only `lts` flag); it is shared with the auto-minor scheduler.
const { getSupportedMajors } = require('${{ github.workspace }}/release/dist/index.cjs');
const targets = await getSupportedMajors();
console.log('supported backport targets', targets);
return targets;
backport:
needs: prepare
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
strategy:
fail-fast: false # one conflicting branch must not block the others
matrix:
target: ${{ fromJson(needs.prepare.outputs.targets) }}
steps:
- uses: actions/checkout@v6
with:
fetch-depth: 0
token: ${{ secrets.METABASE_AUTOMATION_USER_TOKEN }}
- name: Backport to v${{ matrix.target }}
uses: ./.github/actions/create-backport
with:
target-version: ${{ matrix.target }}
backport-commit: ${{ needs.prepare.outputs.commit }}
github-token: ${{ secrets.METABASE_AUTOMATION_USER_TOKEN }}
github-token-2: ${{ secrets.GITHUB_TOKEN }}
# --- Legacy escape hatch: explicit depth backports -----------------------
# `single-backport`/`double-backport`/`triple-backport` keep their original behavior —
# backport to CURRENT_VERSION and the 0–2 lines below it — independent of
# `major_version_support`. `single-backport` is a fallback for when the primary path
# can't be used and only CURRENT_VERSION is wanted. Kept for the short term for one-off
# manual depth control. If a branch from the primary path above already exists,
# create-backport simply errors on the duplicate.
legacy-backport:
if:
| # triggered only by the legacy depth labels, at merge or when added afterwards
github.event.pull_request.merged == true && (
github.event.action == 'closed' && (
contains(github.event.pull_request.labels.*.name, 'backport') ||
contains(github.event.pull_request.labels.*.name, 'single-backport') ||
contains(github.event.pull_request.labels.*.name, 'double-backport') ||
contains(github.event.pull_request.labels.*.name, 'triple-backport')
) ||
github.event.action == 'labeled' && (
github.event.label.name == 'backport' ||
github.event.label.name == 'single-backport' ||
github.event.label.name == 'double-backport' ||
github.event.label.name == 'triple-backport'
)

View File

@@ -57,7 +57,7 @@ jobs:
- name: Upload coverage to codecov.io
if: always()
uses: codecov/codecov-action@1af58845a975a7985b0beb0cbe6fbbb71a41dbad # v5
uses: codecov/codecov-action@e79a6962e0d4c0c17b229090214935d2e33f8354 # v6.0.1
with:
token: ${{ secrets.CODECOV_TOKEN }}
files: ./target/coverage/codecov.json
@@ -104,7 +104,7 @@ jobs:
- name: Upload coverage to codecov.io
if: always()
uses: codecov/codecov-action@1af58845a975a7985b0beb0cbe6fbbb71a41dbad # v5
uses: codecov/codecov-action@e79a6962e0d4c0c17b229090214935d2e33f8354 # v6.0.1
with:
token: ${{ secrets.CODECOV_TOKEN }}
files: ./target/coverage/codecov.json

View File

@@ -11,6 +11,13 @@ concurrency:
group: ${{ github.workflow }}-${{ github.head_ref && github.ref || github.run_id }}-backend
cancel-in-progress: true
# Exposed to the test jobs so they can report failures to ci-conductor
# (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_WEBHOOK_SECRET: ${{ secrets.CI_CONDUCTOR_WEBHOOK_SECRET }}
jobs:
be-linter-clj-kondo:
if: ${{ !inputs.skip }}
@@ -38,9 +45,9 @@ 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-')) }}
if: ${{ !inputs.skip && github.event_name == 'push' && (github.ref_name == 'master' || startsWith(github.ref_name, 'release-x')) }}
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
timeout-minutes: 30
timeout-minutes: 45
name: Eastwood (tests only)
steps:
- uses: actions/checkout@v6
@@ -114,7 +121,7 @@ jobs:
strategy:
fail-fast: false
matrix:
java-version: [21]
java-version: [25]
job:
- name: Enterprise Tests
edition: ee
@@ -160,7 +167,7 @@ jobs:
github.event_name == 'push' &&
(
github.ref_name == 'master' ||
startsWith(github.ref_name, 'release-')
startsWith(github.ref_name, 'release-x')
) &&
''
) ||
@@ -179,20 +186,42 @@ jobs:
env:
MB_EDITION: ${{ matrix.job.edition }}
- name: Resolve current job id
# Resolve JOB_ID before the long test step so the ci-conductor reporter
# below can link failures to this exact job. Best-effort.
uses: ./.github/actions/resolve-job-id
- name: "Test Java ${{ matrix.java-version }} ${{ matrix.job.name }}"
id: run-java-tests
run: >-
clojure -X:dev:ci:test:${{ matrix.job.edition }}:${{ matrix.job.edition }}-dev
:exclude-tags '[:mb/driver-tests ${{ env.__ADDITIONAL_EXCLUDED_TAG__ }}]'
${{ matrix.job.test-args }}
# Trunk Quarantine controls the final state of the run in the CI!
# Even if this step fails we let it pass, and then `trunk-io/analytics-uploader` determines
# whether to fail or to pass the whole job, based on the quarantine list.
# Keep this step continue-on-error because the quarantine logic controls whether it ultimately fails.
continue-on-error: true
- name: Report failed tests to ci-conductor
if: ${{ !cancelled() && steps.run-java-tests.outcome == 'failure' }}
# This step should NEVER fail the job!
continue-on-error: true
uses: ./.github/actions/report-failures-to-ci-conductor
with:
test-suite: be-tests-java-${{ matrix.java-version }}-${{ matrix.job.test-group-name }}
adapter: backend
- name: Quarantine gate
if: ${{ !cancelled() && steps.run-java-tests.outcome == 'failure' }}
continue-on-error: ${{ vars.QUARANTINE_ENGINE != 'ci-conductor' }}
timeout-minutes: 3
uses: ./.github/actions/quarantine-gate
with:
adapter: backend
test-suite: be-tests-java-${{ matrix.java-version }}-${{ matrix.job.test-group-name }}
enforce-quarantine: ${{ vars.QUARANTINE_ENGINE == 'ci-conductor' }}
- name: Upload Test Results
uses: ./.github/actions/upload-test-results
if: always() && (steps.run-java-tests.conclusion != 'skipped' || steps.run-java-tests-21.conclusion != 'skipped')
if: always()
with:
input-path: ./target/junit/
output-name: be-tests-java-${{ matrix.java-version }}-${{ matrix.job.edition }}
@@ -201,6 +230,7 @@ jobs:
aws-region: ${{ vars.AWS_REGION }}
trunk-api-token: ${{ secrets.TRUNK_API_TOKEN }}
previous-step-outcome: ${{ steps.run-java-tests.outcome }}
run-trunk: ${{ vars.QUARANTINE_ENGINE != 'ci-conductor' }}
- name: Publish Test Report (JUnit)
uses: dorny/test-reporter@a43b3a5f7366b97d083190328d2c652e1a8b6aa2 # v3.0.0
@@ -229,7 +259,7 @@ jobs:
timeout-minutes: 10
strategy:
matrix:
java-version: [21]
java-version: [25]
name: "Check Java ${{ matrix.java-version }}"
steps:
- uses: actions/checkout@v6

View File

@@ -2,19 +2,173 @@ name: Backport Reminder
on:
pull_request:
types: [auto_merge_enabled, review_requested, labeled, unlabeled, synchronize]
types: [opened, edited, auto_merge_enabled, review_requested, labeled, unlabeled, synchronize]
branches:
- "master"
merge_group:
concurrency:
group: "backport-reminder-${{ github.event.pull_request.number }}"
cancel-in-progress: true
jobs:
flags:
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
outputs:
has_backport_label: ${{ steps.c.outputs.value }}
steps:
- id: c
run: |
echo "value=${{
contains(github.event.pull_request.labels.*.name, 'no-backport') ||
contains(github.event.pull_request.labels.*.name, 'backport') ||
contains(github.event.pull_request.labels.*.name, 'single-backport') ||
contains(github.event.pull_request.labels.*.name, 'double-backport') ||
contains(github.event.pull_request.labels.*.name, 'triple-backport') }}" >> "$GITHUB_OUTPUT"
files-changed:
name: Check which files changed
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
timeout-minutes: 3
outputs:
docs: ${{ steps.changes.outputs.docs }}
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
backport-reminder:
needs: [ files-changed, flags ]
if: ${{ !cancelled() }}
name: Decide whether to backport or not
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
timeout-minutes: 5
permissions: {}
steps:
- uses: jesusvasquez333/verify-pr-label-action@657d111bbbe13e22bbd55870f1813c699bde1401 # v1.4.0
- name: Fail if backport decision label is missing
if: >
github.event_name == 'pull_request' &&
needs.files-changed.outputs.docs == 'true' &&
needs.flags.outputs.has_backport_label == 'false'
run: |
echo "::error::PR has docs changes and is missing a backport decision label. Add one of: no-backport, backport, single-backport, double-backport, or triple-backport"
exit 1
priority-backport-reminder:
name: Remind about backporting P0 + P1 fixes
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
timeout-minutes: 5
needs: [flags]
permissions:
contents: read
issues: write
pull-requests: write
steps:
- name: Add, update, or remove the high-priority backport reminder
if: ${{ github.event_name == 'pull_request' }}
uses: actions/github-script@v9
env:
HAS_BACKPORT_LABEL: ${{ needs.flags.outputs.has_backport_label }}
with:
github-token: '${{ secrets.GITHUB_TOKEN }}'
valid-labels: 'no-backport, backport, double-backport, triple-backport'
disable-reviews: true
script: | # js
const { owner, repo } = context.repo;
const prNumber = context.payload.pull_request.number;
// A backport decision has already been made if a decision label is present.
const alreadyDecided = process.env.HAS_BACKPORT_LABEL === "true";
// Issues linked to this PR via closing keywords (fixes/closes/resolves #N),
// together with their labels.
const query = `
query($owner: String!, $repo: String!, $pr: Int!) {
repository(owner: $owner, name: $repo) {
pullRequest(number: $pr) {
closingIssuesReferences(first: 50) {
nodes {
number
title
url
labels(first: 50) { nodes { name } }
}
}
}
}
}`;
const data = await github.graphql(query, { owner, repo, pr: prNumber });
const linkedIssues =
data.repository.pullRequest.closingIssuesReferences.nodes ?? [];
const PRIORITY_LABELS = ["Priority:P0", "Priority:P1"];
const priorityIssues = linkedIssues.filter((issue) =>
issue.labels.nodes.some((l) => PRIORITY_LABELS.includes(l.name)),
);
// Hidden marker so we can find/update/remove our own comment idempotently.
const MARKER = "<!-- backport-priority-reminder -->";
const comments = await github.paginate(
github.rest.issues.listComments,
{ owner, repo, issue_number: prNumber, per_page: 100 },
);
const existing = comments.find(
(c) => c.body && c.body.includes(MARKER),
);
// Remind only while a high-priority issue is closed AND no decision
// has been made yet. Once either stops being true the comment is no
// longer needed, so we remove any stale one below.
const shouldComment = priorityIssues.length > 0 && !alreadyDecided;
if (!shouldComment) {
if (existing) {
await github.rest.issues.deleteComment({
owner,
repo,
comment_id: existing.id,
});
console.log("Removed stale backport-priority reminder.");
} else {
console.log(
"Reminder not needed (no high-priority linked issues, or a backport decision label is already applied).",
);
}
return;
}
const list = priorityIssues
.map((i) => {
const tags = i.labels.nodes
.map((l) => l.name)
.filter((n) => PRIORITY_LABELS.includes(n))
.join(", ");
return `- #${i.number} ${i.title} (${tags})`;
})
.join("\n");
const body = [
MARKER,
"⚠️ This PR closes one or more high-priority issues:",
"",
list,
"",
"Please apply the `backport` label unless you have a very good reason not to.",
].join("\n");
if (existing) {
await github.rest.issues.updateComment({
owner,
repo,
comment_id: existing.id,
body,
});
} else {
await github.rest.issues.createComment({
owner,
repo,
issue_number: prNumber,
body,
});
}

148
.github/workflows/bundle-size-stats.yml vendored Normal file
View File

@@ -0,0 +1,148 @@
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.
on:
workflow_run:
workflows: ["Build Uberjar"]
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]
concurrency:
group: bundle-size-stats-${{ github.event.workflow_run.head_sha }}
cancel-in-progress: true
jobs:
bundle-size-stats:
if: ${{ github.event.workflow_run.conclusion == 'success' && github.repository == 'metabase/metabase' }}
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
timeout-minutes: 15
env:
HEAD_SHA: ${{ 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.
MIN_DELTA_PERCENT: "0.5"
steps:
- name: Check out the code
uses: actions/checkout@v6
with:
ref: ${{ github.event.workflow_run.head_sha }}
- name: Download EE uberjar
uses: ./.github/actions/fetch-artifact
with:
commit: ${{ github.event.workflow_run.head_sha }}
edition: ee
extract-path: temp/uberjar
- name: Extract front-end bundles from uberjar
run: |
mkdir -p resources artifacts
unzip -o "temp/uberjar/metabase.jar" \
"frontend_client/app/dist/*" \
"frontend_client/app/embed.js" \
"frontend_client/app/embedding-sdk/*" \
-d resources
unzip -o -j "temp/uberjar/metabase.jar" version.properties -d artifacts
- name: Download bundle stats and SDK package artifacts
uses: actions/github-script@v9
with:
script: | # js
const fs = require("fs");
async function fetchArtifact(name) {
const res = await github.rest.actions.listArtifactsForRepo({
owner: context.repo.owner,
repo: context.repo.repo,
name,
per_page: 1,
});
const artifact = res.data?.artifacts?.[0];
if (!artifact) {
console.log(`Artifact not found: ${name}`);
return "";
}
const download = await github.rest.actions.downloadArtifact({
owner: context.repo.owner,
repo: context.repo.repo,
artifact_id: artifact.id,
archive_format: "zip",
});
fs.writeFileSync(`${name}.zip`, Buffer.from(download.data));
console.log(`Downloaded ${name}`);
return `${name}.zip`;
}
const sha = process.env.HEAD_SHA;
core.exportVariable("STATS_ZIP", await fetchArtifact(`metabase-bundle-stats-ee-${sha}`));
core.exportVariable("PKG_ZIP", await fetchArtifact(`embedding-sdk-${sha}`));
- name: Extract stats and SDK package
run: |
mkdir -p artifacts resources/embedding-sdk
if [ -n "$STATS_ZIP" ]; then unzip -o "$STATS_ZIP" -d artifacts; fi
if [ -n "$PKG_ZIP" ]; then unzip -o "$PKG_ZIP" -d resources/embedding-sdk; fi
- name: Restore last plotted bundle sizes
uses: actions/cache/restore@v4
with:
path: bundle-size-cache
key: bundle-size-last-${{ github.run_id }}
restore-keys: |
bundle-size-last-
- name: Measure bundle sizes
run: node ./.github/scripts/measure-bundle-sizes.js | tee artifacts/bundle-sizes.json
- name: Compute deltas and decide whether to record this point
id: prepare
env:
CURRENT: artifacts/bundle-sizes.json
LAST: bundle-size-cache/last.json
CACHE_OUT: bundle-size-cache/last.json
ROWS_OUT: artifacts/upload-rows.json
VERSION_PROPS: artifacts/version.properties
# 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
id: upload
if: steps.prepare.outputs.significant == 'true'
uses: actions/github-script@v9
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");
}
- name: Remember this as the last plotted point
if: steps.upload.outputs.uploaded == 'true'
uses: actions/cache/save@v4
with:
path: bundle-size-cache
key: bundle-size-last-${{ github.run_id }}

View File

@@ -68,10 +68,47 @@ jobs:
- name: Prepare backend
uses: ./.github/actions/prepare-backend
# Add or remove aliases to affect the cache size and its contents.
# Adjust to taste, then redeploy this workflow.
# 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
run: clojure -A:build:dev:ee:ee-dev:drivers:drivers-dev:cljs -P
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) + generative-query-test.yml
":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 + presto script
":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

View File

@@ -43,7 +43,7 @@ jobs:
- name: Compile CLJS
run: NODE_ENV=development bun run build-pure:cljs
- name: Publish to Chromatic
uses: chromaui/action@c03d144dc72e609acbb960489fdd1e1a4a23b34f # v10.2.0
uses: chromaui/action@0b8c883861c1663076150cf1f4592b19d1ff6a54 # v17.0.1
env:
PUBLISH_CHROMATIC: ${{ secrets.CHROMATIC_PROJECT_TOKEN }}
STORYBOOK_BUILD_TIMEOUT: 900000

View File

@@ -68,7 +68,7 @@ jobs:
- name: Fix spelling errors with Claude Code
if: steps.codespell_check.outcome == 'failure'
uses: anthropics/claude-code-action@3ac52d0da9f8ec9ca7b4dc23bb477e36ef9c77a9 # v1
uses: anthropics/claude-code-action@787c5a0ce96a9a6cfb050ea0c8f4c05f2447c251 # v1.0.133
with:
anthropic_api_key: ${{ secrets.ANTHROPIC_API_KEY }}
github_token: ${{ steps.claude-app-token.outputs.token }}

View File

@@ -76,7 +76,7 @@ jobs:
with:
ref: ${{ github.event.inputs.commit || github.event.pull_request.head.sha || github.sha }}
- name: Run Trivy vulnerability scanner
uses: aquasecurity/trivy-action@57a97c7e7821a5776cebc9bb87c984fa69cba8f1
uses: aquasecurity/trivy-action@ed142fd0673e97e23eac54620cfb913e5ce36c25 # v0.36.0
env:
TRIVY_OFFLINE_SCAN: true
repo: ${{ fromJson(needs.get-container-info.outputs[matrix.edition]).repo }}
@@ -106,7 +106,7 @@ jobs:
edition: ee
- name: Post PR comment
uses: marocchino/sticky-pull-request-comment@773744901bac0e8cbb5a0dc842800d45e9b2b405 # v2
uses: marocchino/sticky-pull-request-comment@0ea0beb66eb9baf113663a64ec522f60e49231c0 # v3.0.4
with:
header: docker-build-status
message: |

View File

@@ -23,7 +23,7 @@ jobs:
--coverage \
--testTimeout=60000
- name: Upload coverage to codecov.io
uses: codecov/codecov-action@1af58845a975a7985b0beb0cbe6fbbb71a41dbad # v5
uses: codecov/codecov-action@e79a6962e0d4c0c17b229090214935d2e33f8354 # v6.0.1
with:
files: ./coverage/lcov.info
flags: front-end

View File

@@ -26,7 +26,7 @@ concurrency:
jobs:
migrations-h2-ee:
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
timeout-minutes: 10
timeout-minutes: 15
env:
CI: 'true'
MB_DB_TYPE: h2
@@ -40,7 +40,7 @@ jobs:
migrations-postgres-14-ee:
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
timeout-minutes: 10
timeout-minutes: 15
env:
CI: 'true'
MB_DB_TYPE: postgres
@@ -66,7 +66,7 @@ jobs:
migrations-postgres-latest-ee:
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
timeout-minutes: 10
timeout-minutes: 15
env:
CI: 'true'
MB_DB_TYPE: postgres
@@ -92,7 +92,7 @@ jobs:
migrations-mysql-8-0-ee:
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
timeout-minutes: 10
timeout-minutes: 15
env:
CI: 'true'
MB_DB_TYPE: mysql
@@ -117,7 +117,7 @@ jobs:
migrations-mysql-latest-ee:
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
timeout-minutes: 10
timeout-minutes: 15
env:
CI: 'true'
MB_DB_TYPE: mysql
@@ -143,7 +143,7 @@ jobs:
migrations-mariadb-10-6-ee:
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
timeout-minutes: 10
timeout-minutes: 15
env:
CI: 'true'
MB_DB_TYPE: mysql
@@ -168,7 +168,7 @@ jobs:
migrations-mariadb-latest-ee:
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
timeout-minutes: 10
timeout-minutes: 15
env:
CI: 'true'
MB_DB_TYPE: mysql

View File

@@ -70,6 +70,10 @@ jobs:
git push -u origin "$BRANCH"
echo "sha=$(git rev-parse HEAD)" >> "$GITHUB_OUTPUT"
# CURRENT_VERSION is an org-level variable — that's the canonical one,
# shared across repos. A repo-level variable of the same name would
# shadow it (repo vars override org vars), so we deliberately update
# the org-level value here and rely on no repo-level override existing.
- name: Bump vars.CURRENT_VERSION
id: bump
continue-on-error: true
@@ -78,7 +82,7 @@ jobs:
run: |
gh variable set CURRENT_VERSION \
--body "${{ steps.preflight.outputs.next }}" \
--repo "${{ github.repository }}"
--org "${{ github.repository_owner }}"
# Pre-create the milestone for the version AFTER this cut, so it's
# already open when next time's backfill needs somewhere to assign
@@ -204,7 +208,7 @@ jobs:
const notes = [
bumpFailed
? `:warning: Auto-bump of \`CURRENT_VERSION\` to *${next}* failed — please update it manually: <https://github.com/${owner}/${repo}/settings/variables/actions|Actions variables>`
? `:warning: Auto-bump of \`CURRENT_VERSION\` to *${next}* failed — please update it manually: <https://github.com/organizations/${owner}/settings/variables/actions|Org Actions variables>`
: `\`CURRENT_VERSION\` bumped to *${next}*.`,
milestoneFailed
? `:warning: Pre-creating milestone \`0.${{ steps.preflight.outputs.nextMilestone }}\` (for the next cut) failed — please create it manually: <https://github.com/${owner}/${repo}/milestones|Repository milestones>`

View File

@@ -30,15 +30,23 @@ jobs:
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.ignored?.drivers || [];
const drivers = config.drivers || [];
const lastUpdated = config.metadata?.last_updated || 'unknown';
const reason = config.metadata?.reason || 'No reason provided';
if (drivers.length === 0) {
console.log('No drivers are currently disabled. Skipping Slack notification.');
const skipped = drivers.filter(d => d.status === 'skip').map(d => d.name);
const info = drivers.filter(d => d.status === 'info').map(d => d.name);
if (skipped.length === 0 && info.length === 0) {
console.log('No drivers are disabled or collecting data. Skipping Slack notification.');
return;
}
const list = (names) => names.map(d => `\`${d}\``).join(' ');
const lines = [];
if (skipped.length) lines.push(`:no_entry: *Disabled (not run):* ${list(skipped)}`);
if (info.length) lines.push(`:information_source: *Collecting data (non-blocking):* ${list(info)}`);
if (!process.env.SLACK_BOT_TOKEN) {
throw new Error('SLACK_BOT_TOKEN is required');
}
@@ -47,13 +55,13 @@ jobs:
await slack.chat.postMessage({
channel: 'engineering-ci',
text: 'CI Disabled Drivers Report',
text: 'CI Driver Status Report',
blocks: [
{
type: 'section',
text: {
type: 'mrkdwn',
text: `:no_entry: *CI Disabled Drivers*\n${drivers.map(d => `\`${d}\``).join(' ')}`
text: `*CI Driver Status*\n${lines.join('\n')}`
},
accessory: {
type: 'button',

22
.github/workflows/docs-generate-63.yml vendored Normal file
View File

@@ -0,0 +1,22 @@
name: Auto-update documentation (release)
on:
schedule:
- cron: "0 23 * * 1-5" # Every Monday through Friday at 11 PM UTC
workflow_dispatch:
inputs:
target_branch:
description: "Target branch for documentation update"
required: false
default: "release-x.63.x"
type: string
jobs:
update-release-docs:
if: ${{ github.event_name != 'schedule' || github.repository == 'metabase/metabase' }}
name: Call documentation update for release branch
uses: ./.github/workflows/docs-generate-base.yml
with:
target_branch: ${{ inputs.target_branch || 'release-x.63.x' }}
secrets:
automation_token: ${{ secrets.METABASE_AUTOMATION_USER_TOKEN }}

View File

@@ -27,7 +27,7 @@ jobs:
- name: Run link checker
id: link-check
uses: lycheeverse/lychee-action@f613c4a64e50d792e0b31ec34bbcbba12263c6a6 # v2.3.0
uses: lycheeverse/lychee-action@8646ba30535128ac92d33dfc9133794bfdd9b411 # v2.8.0
with:
fail: true
args: docs --config ./.lychee/config.toml --offline

View File

@@ -8,7 +8,7 @@ on:
target_branch:
description: "Target branch for documentation update"
required: false
default: "release-x.60.x"
default: "release-x.62.x"
type: string
jobs:
@@ -17,6 +17,6 @@ jobs:
name: Call documentation update for release branch
uses: ./.github/workflows/docs-generate-base.yml
with:
target_branch: ${{ inputs.target_branch || 'release-x.60.x' }}
target_branch: ${{ inputs.target_branch || 'release-x.62.x' }}
secrets:
automation_token: ${{ secrets.METABASE_AUTOMATION_USER_TOKEN }}

View File

@@ -4,6 +4,10 @@ on:
workflow_dispatch:
inputs:
test:
# Technically this accepts anything that is accepted by Hawk:
# https://github.com/metabase/hawk/#leiningen-style-test-selection
# For example, to run everything in the tests/ dir you can do
# $ gh workflow run .github/workflows/drivers-stress-test.yml --field 'test=\"test/\" :only-tags [:mb/driver-tests]' --field times=2 --field driver=Snowflake
description: 'The exact test name with its namespace.'
type: string
required: true
@@ -79,6 +83,7 @@ jobs:
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 }}
steps:
- uses: actions/checkout@v6
- name: Test BigQuery Cloud SDK driver
@@ -573,9 +578,19 @@ jobs:
MB_SNOWFLAKE_TEST_USER: METABASE CI
MB_SNOWFLAKE_TEST_ACCOUNT: ${{ secrets.MB_SNOWFLAKE_TEST_ACCOUNT }}
MB_SNOWFLAKE_TEST_PASSWORD: ${{ secrets.MB_SNOWFLAKE_TEST_PASSWORD }}
MB_SNOWFLAKE_TEST_PRIVATE_KEY: ${{ secrets.MB_SNOWFLAKE_TEST_PRIVATE_KEY }}
MB_SNOWFLAKE_TEST_WAREHOUSE: ${{ secrets.MB_SNOWFLAKE_TEST_WAREHOUSE }}
MB_SNOWFLAKE_TEST_PK_USER: METABASE PK
MB_SNOWFLAKE_TEST_PK_PRIVATE_KEY: ${{ secrets.MB_SNOWFLAKE_TEST_PK_PRIVATE_KEY }}
MB_SNOWFLAKE_TEST_PK_PRIVATE_KEY_2: ${{ secrets.MB_SNOWFLAKE_TEST_PK_PRIVATE_KEY_2 }}
MB_SNOWFLAKE_TEST_PK_PUBLIC_KEY: ${{ secrets.MB_SNOWFLAKE_TEST_PK_PUBLIC_KEY }}
MB_SNOWFLAKE_TEST_PK_PUBLIC_KEY_2: ${{ secrets.MB_SNOWFLAKE_TEST_PK_PUBLIC_KEY_2 }}
# RSA Role testing:
MB_SNOWFLAKE_TEST_RSA_ROLE_TEST_DEFAULT_USER: RSA_ROLE_TEST_DEFAULT_USER
MB_SNOWFLAKE_TEST_RSA_ROLE_TEST_CUSTOM_USER: RSA_ROLE_TEST_CUSTOM_USER
MB_SNOWFLAKE_TEST_RSA_ROLE_TEST_ROLE: RSA_ROLE_TEST_ROLE
MB_SNOWFLAKE_TEST_RSA_ROLE_TEST_DB: RSA_ROLE_TEST_DB
steps:
- uses: actions/checkout@v6
- name: Test Snowflake driver

View File

@@ -11,6 +11,13 @@ concurrency:
group: ${{ github.workflow }}-${{ github.head_ref && github.ref || github.run_id }}-drivers
cancel-in-progress: true
# Exposed to every driver job so the test-driver action can report failures to
# 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_WEBHOOK_SECRET: ${{ secrets.CI_CONDUCTOR_WEBHOOK_SECRET }}
jobs:
# This job determines which driver tests should run based on PR context.
# All decision logic is consolidated in mage driver-decisions.
@@ -38,6 +45,26 @@ 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 configured status from ci-test-config (skip | info | required)
h2-status: ${{ steps.driver-decisions.outputs.h2-status }}
athena-status: ${{ steps.driver-decisions.outputs.athena-status }}
bigquery-status: ${{ steps.driver-decisions.outputs.bigquery-status }}
clickhouse-status: ${{ steps.driver-decisions.outputs.clickhouse-status }}
databricks-status: ${{ steps.driver-decisions.outputs.databricks-status }}
druid-jdbc-status: ${{ steps.driver-decisions.outputs.druid-jdbc-status }}
mongo-status: ${{ steps.driver-decisions.outputs.mongo-status }}
mongo-ssl-status: ${{ steps.driver-decisions.outputs.mongo-ssl-status }}
mongo-sharded-cluster-status: ${{ steps.driver-decisions.outputs.mongo-sharded-cluster-status }}
mysql-mariadb-status: ${{ steps.driver-decisions.outputs.mysql-mariadb-status }}
oracle-status: ${{ steps.driver-decisions.outputs.oracle-status }}
postgres-status: ${{ steps.driver-decisions.outputs.postgres-status }}
presto-jdbc-status: ${{ steps.driver-decisions.outputs.presto-jdbc-status }}
redshift-status: ${{ steps.driver-decisions.outputs.redshift-status }}
snowflake-status: ${{ steps.driver-decisions.outputs.snowflake-status }}
sparksql-status: ${{ steps.driver-decisions.outputs.sparksql-status }}
sqlite-status: ${{ steps.driver-decisions.outputs.sqlite-status }}
sqlserver-status: ${{ steps.driver-decisions.outputs.sqlserver-status }}
vertica-status: ${{ steps.driver-decisions.outputs.vertica-status }}
# 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 }}
@@ -59,6 +86,28 @@ jobs:
sqlserver-quarantine-conflict: ${{ steps.driver-decisions.outputs.sqlserver-quarantine-conflict }}
vertica-quarantine-conflict: ${{ steps.driver-decisions.outputs.vertica-quarantine-conflict }}
steps:
# Up front (before any driver job), drop info-driver comments from older commits so a
# superseded comment disappears immediately rather than waiting for this run's drivers.
# Keeps this commit's comment (if any) so a re-run doesn't flicker.
- name: Remove stale info-driver comments
if: ${{ github.event_name == 'pull_request' }}
uses: actions/github-script@v9
continue-on-error: true
with:
script: | # js
const pr = context.payload.pull_request;
if (!pr) return;
const { owner, repo } = context.repo;
const PREFIX = "<!-- info-driver-result";
const keep = `<!-- info-driver-results:${pr.head.sha} -->`;
const { data: comments } = await github.rest.issues.listComments({
owner, repo, issue_number: pr.number, per_page: 100,
});
for (const c of comments) {
if (c.body.includes(PREFIX) && !c.body.includes(keep)) {
await github.rest.issues.deleteComment({ owner, repo, comment_id: c.id }).catch(() => {});
}
}
- name: Checkout repository
uses: actions/checkout@v6
- name: Fetch base branch
@@ -89,7 +138,7 @@ 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-') }}
IS_MASTER_OR_RELEASE: ${{ github.ref_name == 'master' || startsWith(github.ref_name, 'release-x') }}
shell: bash
be-tests-athena-ee:
@@ -130,6 +179,8 @@ jobs:
test-args: >-
:only-tags [:mb/driver-tests]
:exclude-tags [:mb/transforms-python-test]
quarantine-engine: ${{ vars.QUARANTINE_ENGINE }}
driver-status: ${{ needs.determine-driver-skips.outputs.athena-status }}
- name: Upload Test Results
uses: ./.github/actions/upload-test-results
if: always()
@@ -141,6 +192,9 @@ jobs:
aws-region: ${{ vars.AWS_REGION }}
trunk-api-token: ${{ secrets.TRUNK_API_TOKEN }}
previous-step-outcome: ${{ steps.test-driver.outputs.test-outcome }}
driver-status: ${{ needs.determine-driver-skips.outputs.athena-status }}
report-variant: ${{ matrix.job.name }}
run-trunk: ${{ vars.QUARANTINE_ENGINE != 'ci-conductor' }}
be-tests-bigquery-cloud-sdk-ee:
needs: determine-driver-skips
@@ -151,11 +205,20 @@ jobs:
fail-fast: false
matrix:
job:
- name: Driver Tests
- 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]
@@ -195,6 +258,8 @@ jobs:
junit-name: 'be-tests-bigquery-cloud-sdk-ee'
test-args: ${{ matrix.job.test-args }}
logs-artifact-suffix: ${{ matrix.job.name }}
quarantine-engine: ${{ vars.QUARANTINE_ENGINE }}
driver-status: ${{ needs.determine-driver-skips.outputs.bigquery-status }}
- name: Upload Test Results
uses: ./.github/actions/upload-test-results
if: always()
@@ -206,6 +271,9 @@ jobs:
aws-region: ${{ vars.AWS_REGION }}
trunk-api-token: ${{ secrets.TRUNK_API_TOKEN }}
previous-step-outcome: ${{ steps.test-driver.outputs.test-outcome }}
driver-status: ${{ needs.determine-driver-skips.outputs.bigquery-status }}
report-variant: ${{ matrix.job.name }}
run-trunk: ${{ vars.QUARANTINE_ENGINE != 'ci-conductor' }}
- name: Cleanup python-runner
if: ${{ always() && matrix.job.needs-python-runner == true }}
uses: ./.github/actions/cleanup-python-runner
@@ -259,7 +327,7 @@ jobs:
run: |
sudo echo "127.0.0.1 server.clickhouseconnect.test" | sudo tee -a /etc/hosts
- name: Start ClickHouse in Docker
uses: hoverkraft-tech/compose-action@802a148945af6399a338c7906c267331b39a71af # v2.0.0
uses: hoverkraft-tech/compose-action@d2bee4f07e8ca410d6b196d00f90c12e7d48c33a # v2.6.0
with:
compose-file: "modules/drivers/clickhouse/docker-compose.yml"
down-flags: "--volumes"
@@ -278,6 +346,8 @@ jobs:
junit-name: 'be-tests-clickhouse-ee'
test-args: ${{ matrix.job.test-args }}
logs-artifact-suffix: ${{ matrix.job.name }}
quarantine-engine: ${{ vars.QUARANTINE_ENGINE }}
driver-status: ${{ needs.determine-driver-skips.outputs.clickhouse-status }}
- name: Upload Test Results
uses: ./.github/actions/upload-test-results
if: always()
@@ -289,6 +359,8 @@ jobs:
aws-region: ${{ vars.AWS_REGION }}
trunk-api-token: ${{ secrets.TRUNK_API_TOKEN }}
previous-step-outcome: ${{ steps.test-driver.outputs.test-outcome }}
driver-status: ${{ needs.determine-driver-skips.outputs.clickhouse-status }}
run-trunk: ${{ vars.QUARANTINE_ENGINE != 'ci-conductor' }}
- name: Cleanup python-runner
if: ${{ always() && matrix.job.needs-python-runner == true }}
uses: ./.github/actions/cleanup-python-runner
@@ -296,54 +368,6 @@ jobs:
upload-logs: ${{ steps.test-driver.outcome == 'failure' }}
logs-artifact-suffix: ${{ matrix.job.name }} ${{ matrix.version.name }}
be-tests-druid-ee:
needs: determine-driver-skips
if: ${{ needs.determine-driver-skips.outputs.druid-should-run == 'true' || needs.determine-driver-skips.outputs.druid-quarantine-conflict == 'true' }}
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
timeout-minutes: 40
env:
CI: 'true'
DRIVERS: druid
services:
druid:
image: metabase/druid:0.20.2
ports:
- "8082:8082"
env:
CLUSTER_SIZE: nano-quickstart
name: Druid (Legacy)
steps:
- name: Fail on quarantine conflict
if: ${{ needs.determine-driver-skips.outputs.druid-quarantine-conflict == 'true' }}
run: |
echo "::error::Druid driver is quarantined but you changed files in modules/drivers/druid/"
echo ""
echo "Your changes will NOT be tested because the driver is currently quarantined."
echo "To run Druid tests, add the label: break-quarantine-druid"
echo ""
echo "If you merge without testing, you risk breaking the Druid driver!"
exit 1
- uses: actions/checkout@v6
- name: Test Druid driver
id: test-driver
uses: ./.github/actions/test-driver
with:
junit-name: 'be-tests-druid-ee'
test-args: >-
:only-tags [:mb/driver-tests]
:exclude-tags [:mb/transforms-python-test]
- name: Upload Test Results
uses: ./.github/actions/upload-test-results
if: always()
with:
input-path: ./target/junit/
output-name: ${{ github.job }}
bucket: ${{ vars.AWS_S3_TEST_RESULTS_BUCKET }}
role-to-assume: ${{ secrets.CI_TEST_RESULTS_IAM_ROLE }}
aws-region: ${{ vars.AWS_REGION }}
trunk-api-token: ${{ secrets.TRUNK_API_TOKEN }}
previous-step-outcome: ${{ steps.test-driver.outputs.test-outcome }}
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' }}
@@ -380,6 +404,8 @@ jobs:
test-args: >-
:only-tags [:mb/driver-tests]
:exclude-tags [:mb/transforms-python-test]
quarantine-engine: ${{ vars.QUARANTINE_ENGINE }}
driver-status: ${{ needs.determine-driver-skips.outputs.druid-jdbc-status }}
- name: Upload Test Results
uses: ./.github/actions/upload-test-results
if: always()
@@ -391,12 +417,39 @@ jobs:
aws-region: ${{ vars.AWS_REGION }}
trunk-api-token: ${{ secrets.TRUNK_API_TOKEN }}
previous-step-outcome: ${{ steps.test-driver.outputs.test-outcome }}
driver-status: ${{ needs.determine-driver-skips.outputs.druid-jdbc-status }}
run-trunk: ${{ vars.QUARANTINE_ENGINE != 'ci-conductor' }}
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' }}
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
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 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
@@ -425,9 +478,9 @@ jobs:
uses: ./.github/actions/test-driver
with:
junit-name: 'be-tests-databricks-ee'
test-args: >-
:only-tags [:mb/driver-tests]
:exclude-tags [:mb/transforms-python-test]
test-args: ${{ matrix.job.test-args }}
quarantine-engine: ${{ vars.QUARANTINE_ENGINE }}
driver-status: ${{ needs.determine-driver-skips.outputs.databricks-status }}
- name: Upload Test Results
uses: ./.github/actions/upload-test-results
if: always()
@@ -439,12 +492,40 @@ jobs:
aws-region: ${{ vars.AWS_REGION }}
trunk-api-token: ${{ secrets.TRUNK_API_TOKEN }}
previous-step-outcome: ${{ steps.test-driver.outputs.test-outcome }}
driver-status: ${{ needs.determine-driver-skips.outputs.databricks-status }}
report-variant: ${{ matrix.job.name }}
run-trunk: ${{ vars.QUARANTINE_ENGINE != 'ci-conductor' }}
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: 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 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
@@ -474,9 +555,9 @@ jobs:
uses: ./.github/actions/test-driver
with:
junit-name: 'be-tests-databricks-multi-catalog-ee'
test-args: >-
:only-tags [:mb/driver-tests]
:exclude-tags [:mb/transforms-python-test]
test-args: ${{ matrix.job.test-args }}
quarantine-engine: ${{ vars.QUARANTINE_ENGINE }}
driver-status: ${{ needs.determine-driver-skips.outputs.databricks-status }}
- name: Upload Test Results
uses: ./.github/actions/upload-test-results
if: always()
@@ -488,6 +569,9 @@ jobs:
aws-region: ${{ vars.AWS_REGION }}
trunk-api-token: ${{ secrets.TRUNK_API_TOKEN }}
previous-step-outcome: ${{ steps.test-driver.outputs.test-outcome }}
driver-status: ${{ needs.determine-driver-skips.outputs.databricks-status }}
report-variant: ${{ matrix.job.name }}
run-trunk: ${{ vars.QUARANTINE_ENGINE != 'ci-conductor' }}
be-tests-h2:
needs: determine-driver-skips
@@ -507,6 +591,8 @@ jobs:
test-args: >-
:only-tags [:mb/driver-tests]
:exclude-tags [:mb/transforms-python-test]
quarantine-engine: ${{ vars.QUARANTINE_ENGINE }}
driver-status: ${{ needs.determine-driver-skips.outputs.h2-status }}
- name: Upload Test Results
uses: ./.github/actions/upload-test-results
if: always()
@@ -518,6 +604,8 @@ jobs:
aws-region: ${{ vars.AWS_REGION }}
trunk-api-token: ${{ secrets.TRUNK_API_TOKEN }}
previous-step-outcome: ${{ steps.test-driver.outputs.test-outcome }}
driver-status: ${{ needs.determine-driver-skips.outputs.h2-status }}
run-trunk: ${{ vars.QUARANTINE_ENGINE != 'ci-conductor' }}
be-tests-h2-oss:
needs: determine-driver-skips
@@ -538,6 +626,8 @@ jobs:
test-args: >-
:only-tags [:mb/driver-tests]
:exclude-tags [:mb/transforms-python-test]
quarantine-engine: ${{ vars.QUARANTINE_ENGINE }}
driver-status: ${{ needs.determine-driver-skips.outputs.h2-status }}
- name: Upload Test Results
uses: ./.github/actions/upload-test-results
if: always()
@@ -549,6 +639,8 @@ jobs:
aws-region: ${{ vars.AWS_REGION }}
trunk-api-token: ${{ secrets.TRUNK_API_TOKEN }}
previous-step-outcome: ${{ steps.test-driver.outputs.test-outcome }}
driver-status: ${{ needs.determine-driver-skips.outputs.h2-status }}
run-trunk: ${{ vars.QUARANTINE_ENGINE != 'ci-conductor' }}
be-tests-mysql-mariadb:
needs: determine-driver-skips
@@ -611,7 +703,7 @@ jobs:
github.event_name == 'push' &&
(
github.ref_name == 'master' ||
startsWith(github.ref_name, 'release-')
startsWith(github.ref_name, 'release-x')
) &&
''
) ||
@@ -668,6 +760,8 @@ jobs:
test-args: >-
${{ matrix.job.test-args }}
:exclude-tags '[ ${{ matrix.job.exclude-tag }} ${{ env.__ADDITIONAL_EXCLUDED_TAG__ }}]'
quarantine-engine: ${{ vars.QUARANTINE_ENGINE }}
driver-status: ${{ needs.determine-driver-skips.outputs.mysql-mariadb-status }}
- name: Upload Test Results
uses: ./.github/actions/upload-test-results
if: always()
@@ -679,6 +773,8 @@ jobs:
aws-region: ${{ vars.AWS_REGION }}
trunk-api-token: ${{ secrets.TRUNK_API_TOKEN }}
previous-step-outcome: ${{ steps.test-driver.outputs.test-outcome }}
driver-status: ${{ needs.determine-driver-skips.outputs.mysql-mariadb-status }}
run-trunk: ${{ vars.QUARANTINE_ENGINE != 'ci-conductor' }}
- name: Cleanup python-runner
if: always()
uses: ./.github/actions/cleanup-python-runner
@@ -748,6 +844,8 @@ jobs:
junit-name: ${{ matrix.version.junit-name }}
test-args: ${{ matrix.job.test-args }}
logs-artifact-suffix: ${{ matrix.job.name }}
quarantine-engine: ${{ vars.QUARANTINE_ENGINE }}
driver-status: ${{ needs.determine-driver-skips.outputs.mongo-status }}
- name: Upload Test Results
uses: ./.github/actions/upload-test-results
if: always()
@@ -759,6 +857,8 @@ jobs:
aws-region: ${{ vars.AWS_REGION }}
trunk-api-token: ${{ secrets.TRUNK_API_TOKEN }}
previous-step-outcome: ${{ steps.test-driver.outputs.test-outcome }}
driver-status: ${{ needs.determine-driver-skips.outputs.mongo-status }}
run-trunk: ${{ vars.QUARANTINE_ENGINE != 'ci-conductor' }}
- name: Cleanup python-runner
if: ${{ always() && matrix.job.needs-python-runner == true }}
uses: ./.github/actions/cleanup-python-runner
@@ -830,6 +930,8 @@ jobs:
test-args: >-
:exclude-tags '[:mongo-sharded-cluster-tests :mb/transforms-python-test]'
:only-tags [:mb/driver-tests]
quarantine-engine: ${{ vars.QUARANTINE_ENGINE }}
driver-status: ${{ needs.determine-driver-skips.outputs.mongo-ssl-status }}
- name: Upload Test Results
uses: ./.github/actions/upload-test-results
if: always()
@@ -841,6 +943,8 @@ jobs:
aws-region: ${{ vars.AWS_REGION }}
trunk-api-token: ${{ secrets.TRUNK_API_TOKEN }}
previous-step-outcome: ${{ steps.test-driver.outputs.test-outcome }}
driver-status: ${{ needs.determine-driver-skips.outputs.mongo-ssl-status }}
run-trunk: ${{ vars.QUARANTINE_ENGINE != 'ci-conductor' }}
be-tests-mongo-sharded-cluster-ee:
needs: determine-driver-skips
@@ -875,6 +979,8 @@ jobs:
junit-name: 'be-tests-mongo-sharded-cluster-ee'
test-args: >-
:only metabase.driver.mongo.sharded-cluster-test
quarantine-engine: ${{ vars.QUARANTINE_ENGINE }}
driver-status: ${{ needs.determine-driver-skips.outputs.mongo-sharded-cluster-status }}
- name: Upload Test Results
uses: ./.github/actions/upload-test-results
if: always()
@@ -886,6 +992,8 @@ jobs:
aws-region: ${{ vars.AWS_REGION }}
trunk-api-token: ${{ secrets.TRUNK_API_TOKEN }}
previous-step-outcome: ${{ steps.test-driver.outputs.test-outcome }}
driver-status: ${{ needs.determine-driver-skips.outputs.mongo-sharded-cluster-status }}
run-trunk: ${{ vars.QUARANTINE_ENGINE != 'ci-conductor' }}
be-tests-oracle:
needs: determine-driver-skips
@@ -960,6 +1068,8 @@ jobs:
test-args: >-
:only-tags [:mb/driver-tests]
:exclude-tags [:mb/transforms-python-test]
quarantine-engine: ${{ vars.QUARANTINE_ENGINE }}
driver-status: ${{ needs.determine-driver-skips.outputs.oracle-status }}
- name: Upload Test Results
uses: ./.github/actions/upload-test-results
if: always()
@@ -971,6 +1081,8 @@ jobs:
aws-region: ${{ vars.AWS_REGION }}
trunk-api-token: ${{ secrets.TRUNK_API_TOKEN }}
previous-step-outcome: ${{ steps.test-driver.outputs.test-outcome }}
driver-status: ${{ needs.determine-driver-skips.outputs.oracle-status }}
run-trunk: ${{ vars.QUARANTINE_ENGINE != 'ci-conductor' }}
be-tests-postgres:
needs: determine-driver-skips
@@ -1013,7 +1125,7 @@ jobs:
github.event_name == 'push' &&
(
github.ref_name == 'master' ||
startsWith(github.ref_name, 'release-')
startsWith(github.ref_name, 'release-x')
) &&
''
) ||
@@ -1064,6 +1176,8 @@ jobs:
test-args: >-
${{ matrix.job.test-args }}
:exclude-tags '[ ${{ matrix.job.exclude-tag }} ${{ env.__ADDITIONAL_EXCLUDED_TAG__ }}]'
quarantine-engine: ${{ vars.QUARANTINE_ENGINE }}
driver-status: ${{ needs.determine-driver-skips.outputs.postgres-status }}
- name: Upload Test Results
uses: ./.github/actions/upload-test-results
if: always()
@@ -1075,6 +1189,9 @@ jobs:
aws-region: ${{ vars.AWS_REGION }}
trunk-api-token: ${{ secrets.TRUNK_API_TOKEN }}
previous-step-outcome: ${{ steps.test-driver.outputs.test-outcome }}
driver-status: ${{ needs.determine-driver-skips.outputs.postgres-status }}
report-variant: ${{ matrix.version.name }}-${{ matrix.job.name }}
run-trunk: ${{ vars.QUARANTINE_ENGINE != 'ci-conductor' }}
- name: Cleanup python-runner
if: always()
uses: ./.github/actions/cleanup-python-runner
@@ -1151,6 +1268,8 @@ jobs:
test-args: >-
:only-tags [:mb/driver-tests]
:exclude-tags [:mb/transforms-python-test]
quarantine-engine: ${{ vars.QUARANTINE_ENGINE }}
driver-status: ${{ needs.determine-driver-skips.outputs.presto-jdbc-status }}
- name: Upload Test Results
uses: ./.github/actions/upload-test-results
if: always()
@@ -1162,6 +1281,8 @@ jobs:
aws-region: ${{ vars.AWS_REGION }}
trunk-api-token: ${{ secrets.TRUNK_API_TOKEN }}
previous-step-outcome: ${{ steps.test-driver.outputs.test-outcome }}
driver-status: ${{ needs.determine-driver-skips.outputs.presto-jdbc-status }}
run-trunk: ${{ vars.QUARANTINE_ENGINE != 'ci-conductor' }}
be-tests-redshift-ee:
needs: determine-driver-skips
@@ -1235,6 +1356,8 @@ jobs:
test-args: >-
${{ matrix.job.test-args }}
logs-artifact-suffix: ${{ matrix.job.name }}
quarantine-engine: ${{ vars.QUARANTINE_ENGINE }}
driver-status: ${{ needs.determine-driver-skips.outputs.redshift-status }}
- name: Upload Test Results
uses: ./.github/actions/upload-test-results
if: ${{ !matrix.job.skip && !cancelled() }}
@@ -1246,6 +1369,9 @@ jobs:
aws-region: ${{ vars.AWS_REGION }}
trunk-api-token: ${{ secrets.TRUNK_API_TOKEN }}
previous-step-outcome: ${{ steps.test-driver.outputs.test-outcome }}
driver-status: ${{ needs.determine-driver-skips.outputs.redshift-status }}
report-variant: ${{ matrix.job.name }}
run-trunk: ${{ vars.QUARANTINE_ENGINE != 'ci-conductor' }}
- name: Cleanup python-runner
if: ${{ always() && matrix.job.needs-python-runner == true }}
uses: ./.github/actions/cleanup-python-runner
@@ -1265,8 +1391,11 @@ jobs:
- name: Driver Tests
test-args: >-
:only-tags [:mb/driver-tests]
:exclude-tags [:mb/transforms-python-test]
:exclude-tags '[:mb/upload-tests :mb/transforms-python-test]'
:fail-fast? true
- name: Upload Tests
test-args: >-
:only-tags [:mb/upload-tests]
- name: Transforms Python Tests
test-args: >-
:only-tags [:mb/transforms-python-test]
@@ -1315,6 +1444,8 @@ jobs:
junit-name: 'be-tests-snowflake-ee'
test-args: ${{ matrix.job.test-args }}
logs-artifact-suffix: ${{ matrix.job.name }}
quarantine-engine: ${{ vars.QUARANTINE_ENGINE }}
driver-status: ${{ needs.determine-driver-skips.outputs.snowflake-status }}
- name: Upload Test Results
uses: ./.github/actions/upload-test-results
if: always()
@@ -1326,6 +1457,9 @@ jobs:
aws-region: ${{ vars.AWS_REGION }}
trunk-api-token: ${{ secrets.TRUNK_API_TOKEN }}
previous-step-outcome: ${{ steps.test-driver.outputs.test-outcome }}
driver-status: ${{ needs.determine-driver-skips.outputs.snowflake-status }}
report-variant: ${{ matrix.job.name }}
run-trunk: ${{ vars.QUARANTINE_ENGINE != 'ci-conductor' }}
- name: Cleanup python-runner
if: ${{ always() && matrix.job.needs-python-runner == true }}
uses: ./.github/actions/cleanup-python-runner
@@ -1367,6 +1501,8 @@ jobs:
test-args: >-
:only-tags [:mb/driver-tests]
:exclude-tags [:mb/transforms-python-test]
quarantine-engine: ${{ vars.QUARANTINE_ENGINE }}
driver-status: ${{ needs.determine-driver-skips.outputs.sparksql-status }}
- name: Upload Test Results
uses: ./.github/actions/upload-test-results
if: always()
@@ -1378,6 +1514,8 @@ jobs:
aws-region: ${{ vars.AWS_REGION }}
trunk-api-token: ${{ secrets.TRUNK_API_TOKEN }}
previous-step-outcome: ${{ steps.test-driver.outputs.test-outcome }}
driver-status: ${{ needs.determine-driver-skips.outputs.sparksql-status }}
run-trunk: ${{ vars.QUARANTINE_ENGINE != 'ci-conductor' }}
be-tests-sqlite-ee:
needs: determine-driver-skips
@@ -1392,7 +1530,7 @@ jobs:
- 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 in modules/drivers/sqlite/"
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"
@@ -1408,6 +1546,8 @@ jobs:
test-args: >-
:only-tags [:mb/driver-tests]
:exclude-tags [:mb/transforms-python-test]
quarantine-engine: ${{ vars.QUARANTINE_ENGINE }}
driver-status: ${{ needs.determine-driver-skips.outputs.sqlite-status }}
- name: Upload Test Results
uses: ./.github/actions/upload-test-results
if: always()
@@ -1419,6 +1559,8 @@ jobs:
aws-region: ${{ vars.AWS_REGION }}
trunk-api-token: ${{ secrets.TRUNK_API_TOKEN }}
previous-step-outcome: ${{ steps.test-driver.outputs.test-outcome }}
driver-status: ${{ needs.determine-driver-skips.outputs.sqlite-status }}
run-trunk: ${{ vars.QUARANTINE_ENGINE != 'ci-conductor' }}
be-tests-sqlserver:
needs: determine-driver-skips
@@ -1484,6 +1626,8 @@ jobs:
junit-name: ${{ matrix.version.junit-name }}
test-args: ${{ matrix.job.test-args }}
logs-artifact-suffix: ${{ matrix.version.name }}
quarantine-engine: ${{ vars.QUARANTINE_ENGINE }}
driver-status: ${{ needs.determine-driver-skips.outputs.sqlserver-status }}
- name: Upload Test Results
uses: ./.github/actions/upload-test-results
if: always()
@@ -1495,6 +1639,8 @@ jobs:
aws-region: ${{ vars.AWS_REGION }}
trunk-api-token: ${{ secrets.TRUNK_API_TOKEN }}
previous-step-outcome: ${{ steps.test-driver.outputs.test-outcome }}
driver-status: ${{ needs.determine-driver-skips.outputs.sqlserver-status }}
run-trunk: ${{ vars.QUARANTINE_ENGINE != 'ci-conductor' }}
- name: Cleanup python-runner
if: ${{ always() && matrix.job.needs-python-runner == true }}
uses: ./.github/actions/cleanup-python-runner
@@ -1609,6 +1755,8 @@ jobs:
test-args: >-
:only-tags [:mb/driver-tests]
:exclude-tags [:mb/transforms-python-test]
quarantine-engine: ${{ vars.QUARANTINE_ENGINE }}
driver-status: ${{ needs.determine-driver-skips.outputs.vertica-status }}
- name: Upload Test Results
uses: ./.github/actions/upload-test-results
if: always()
@@ -1620,16 +1768,24 @@ jobs:
aws-region: ${{ vars.AWS_REGION }}
trunk-api-token: ${{ secrets.TRUNK_API_TOKEN }}
previous-step-outcome: ${{ steps.test-driver.outputs.test-outcome }}
driver-status: ${{ needs.determine-driver-skips.outputs.vertica-status }}
run-trunk: ${{ vars.QUARANTINE_ENGINE != 'ci-conductor' }}
drivers-tests-result:
needs:
# Supplies each driver's configured status (info/skip/required) so this gate can ignore
# "info" drivers regardless of their result -- including cancelled or timed-out runs, which
# the per-job continue-on-error cannot force green because the controlling step never
# completes. Not a driver job; it is filtered out of the pass/fail check below.
- 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
# these are not reliable, but we want to run them anyway to gather data about failures
# - be-tests-snowflake-ee
# - be-tests-bigquery-cloud-sdk-ee
- be-tests-druid-ee
# Listed unconditionally; ci-test-config controls their effect via per-driver status.
# An "info" driver is reported as passing, so it never blocks this check; flip it to
# "required" in the config to make a real failure gate, with no change here.
- be-tests-snowflake-ee
- be-tests-bigquery-cloud-sdk-ee
- be-tests-databricks-ee
- be-tests-druid-jdbc-ee
- be-tests-mysql-mariadb
@@ -1656,15 +1812,46 @@ jobs:
uses: actions/github-script@v9
env:
needs: ${{ toJson(needs) }}
# Job name -> configured driver status, from determine-driver-skips. An "info" driver is
# data-collection only and must never gate; a cancelled/timed-out info job lands here as
# cancelled/failure (its own continue-on-error can't force it green), so we drop info jobs
# from the gate entirely. Empty/unknown status falls back to "required" (gates as before).
statuses: |
{
"be-tests-athena-ee": "${{ needs.determine-driver-skips.outputs.athena-status }}",
"be-tests-bigquery-cloud-sdk-ee": "${{ needs.determine-driver-skips.outputs.bigquery-status }}",
"be-tests-clickhouse-ee": "${{ needs.determine-driver-skips.outputs.clickhouse-status }}",
"be-tests-databricks-ee": "${{ needs.determine-driver-skips.outputs.databricks-status }}",
"be-tests-druid-jdbc-ee": "${{ needs.determine-driver-skips.outputs.druid-jdbc-status }}",
"be-tests-h2": "${{ needs.determine-driver-skips.outputs.h2-status }}",
"be-tests-mongo": "${{ needs.determine-driver-skips.outputs.mongo-status }}",
"be-tests-mongo-ssl": "${{ needs.determine-driver-skips.outputs.mongo-ssl-status }}",
"be-tests-mongo-sharded-cluster-ee": "${{ needs.determine-driver-skips.outputs.mongo-sharded-cluster-status }}",
"be-tests-mysql-mariadb": "${{ needs.determine-driver-skips.outputs.mysql-mariadb-status }}",
"be-tests-oracle": "${{ needs.determine-driver-skips.outputs.oracle-status }}",
"be-tests-postgres": "${{ needs.determine-driver-skips.outputs.postgres-status }}",
"be-tests-presto-jdbc-ee": "${{ needs.determine-driver-skips.outputs.presto-jdbc-status }}",
"be-tests-redshift-ee": "${{ needs.determine-driver-skips.outputs.redshift-status }}",
"be-tests-snowflake-ee": "${{ needs.determine-driver-skips.outputs.snowflake-status }}",
"be-tests-sparksql-ee": "${{ needs.determine-driver-skips.outputs.sparksql-status }}",
"be-tests-sqlite-ee": "${{ needs.determine-driver-skips.outputs.sqlite-status }}",
"be-tests-sqlserver": "${{ needs.determine-driver-skips.outputs.sqlserver-status }}"
}
with:
script: | # js
const needs = JSON.parse(process.env.needs);
const statuses = JSON.parse(process.env.statuses);
const jobs = Object.entries(needs).map(
([jobName, jobValues]) => ({
// Drop the determine-driver-skips bookkeeping job, then drop "info" drivers: they are
// non-gating, so their result (including cancelled/timed-out) must not fail this check.
const jobs = Object.entries(needs)
.filter(([jobName]) => jobName !== 'determine-driver-skips')
.map(([jobName, jobValues]) => ({
name: jobName,
result: jobValues.result
}));
result: jobValues.result,
status: statuses[jobName] || 'required'
}))
.filter(job => job.status !== 'info');
// are all jobs skipped or successful?
if (jobs.every(job => (job.result === 'skipped' || job.result === 'success'))) {

View File

@@ -0,0 +1,145 @@
name: E2E Coverage Manifest
# Nightly: builds an instrumented frontend, runs the e2e suite sharded to
# record which source files each spec exercises, and publishes a spec -> files
# manifest used for selective e2e runs on PRs.
#
# Isolated from the PR e2e path on purpose - the per-shard worker
# (e2e-coverage-shard.yml) is a dedicated, trimmed copy so coverage runs can
# never affect PR test results.
on:
schedule:
# Nightly, after the day's merges have settled (UTC).
- cron: "0 7 * * *"
workflow_dispatch:
inputs:
edition:
description: "Edition to instrument"
type: choice
options: ["ee", "oss"]
default: "ee"
concurrency:
group: e2e-coverage-manifest-${{ github.ref }}
cancel-in-progress: true
jobs:
build-instrumented:
name: Build instrumented uberjar
runs-on: ubuntu-22.04
timeout-minutes: 60
env:
MB_EDITION: ${{ inputs.edition || 'ee' }}
INSTRUMENT_COVERAGE: "true"
steps:
- uses: actions/checkout@v6
- name: Prepare front-end environment
uses: ./.github/actions/prepare-frontend
- name: Prepare back-end environment
uses: ./.github/actions/prepare-backend
# build.clj forwards INSTRUMENT_COVERAGE to the rspack build, so only the
# bundled FE is instrumented; everything else builds normally.
- name: Build instrumented uberjar
run: ./bin/build.sh
- name: Upload instrumented uberjar
uses: actions/upload-artifact@v7
with:
name: instrumented-uberjar
path: target/uberjar/metabase.jar
retention-days: 1
# Fixed-N sharding — coverage doesn't need the PR matrix-builder's tag/edition
# groups, just an even split of the regular spec set. The shard count lives in
# one place (SHARDS below); the matrix is generated from it.
setup:
name: Build shard matrix
runs-on: ubuntu-22.04
outputs:
matrix: ${{ steps.gen.outputs.matrix }}
count: ${{ steps.gen.outputs.count }}
steps:
- id: gen
env:
SHARDS: 100
run: |
matrix=$(node -e "console.log(JSON.stringify({split_index:[...Array(Number(process.env.SHARDS)).keys()]}))")
echo "matrix=$matrix" >> "$GITHUB_OUTPUT"
echo "count=$SHARDS" >> "$GITHUB_OUTPUT"
shards:
name: Shard
needs: [build-instrumented, setup]
strategy:
fail-fast: false
matrix: ${{ fromJson(needs.setup.outputs.matrix) }}
uses: ./.github/workflows/e2e-coverage-shard.yml
secrets: inherit
with:
edition: ${{ inputs.edition || 'ee' }}
total_chunks: ${{ fromJson(needs.setup.outputs.count) }}
split_index: ${{ matrix.split_index }}
merge:
name: Merge and publish manifest
needs: shards
if: always()
runs-on: ubuntu-22.04
timeout-minutes: 15
# github-script lists/downloads the previous manifest artifact.
permissions:
actions: read
contents: read
steps:
- uses: actions/checkout@v6
- name: Prepare front-end environment
uses: ./.github/actions/prepare-frontend
# merge-multiple unions every shard's per-spec dir into one tree; the
# per-spec file design means no conflict resolution is needed.
- name: Download all shard coverage
uses: actions/download-artifact@v8
with:
pattern: coverage-shard-*
path: e2e/coverage-manifest-raw
merge-multiple: true
# Backfill source: the newest existing manifest is the previous nightly
# (this run hasn't uploaded yet). build-coverage-manifest.mjs carries over
# any still-existing spec that didn't run today.
- name: Download previous manifest for backfill
id: prev
uses: actions/github-script@v9
with:
script: | # js
const fs = require("fs");
const { owner, repo } = context.repo;
const { data } = await github.rest.actions.listArtifactsForRepo({
owner, repo, name: "spec-file-manifest", per_page: 20,
});
const art = (data.artifacts ?? [])
.filter((a) => !a.expired)
.sort((a, b) => new Date(b.created_at) - new Date(a.created_at))[0];
if (!art) {
console.log("No previous manifest; nothing to backfill.");
return;
}
const dl = await github.rest.actions.downloadArtifact({
owner, repo, artifact_id: art.id, archive_format: "zip",
});
fs.writeFileSync("prev-manifest.zip", Buffer.from(dl.data));
core.setOutput("found", "true");
- name: Unzip previous manifest
if: steps.prev.outputs.found == 'true'
run: unzip -o prev-manifest.zip -d prev-manifest
# GITHUB_SHA (the master commit this nightly built from) is stamped into
# the manifest as `builtAt`, so a PR can later pick the manifest closest
# to its own point in history. See resolve-coverage-manifest.mjs.
- name: Build coverage manifest
env:
PREV_MANIFEST: ${{ steps.prev.outputs.found == 'true' && 'prev-manifest/spec-file-manifest.json' || '' }}
run: node e2e/coverage/build-coverage-manifest.mjs
- name: Upload manifest
uses: actions/upload-artifact@v7
with:
name: spec-file-manifest
path: e2e/coverage/spec-file-manifest.json
retention-days: 30

112
.github/workflows/e2e-coverage-shard.yml vendored Normal file
View File

@@ -0,0 +1,112 @@
name: E2E Coverage Shard
# Reusable per-shard worker for the coverage manifest run. Trimmed extract of
# e2e-test.yml: runs one cypress-split shard against an instrumented build and
# uploads that shard's per-spec coverage. Intentionally omits the PR-only
# concerns (failed-spec retry, Trunk quarantine, S3 result upload, timing
# output) since this is a nightly, non-blocking job.
on:
workflow_call:
inputs:
edition:
type: string
default: ee
total_chunks:
type: number
required: true
split_index:
type: number
required: true
env:
DISPLAY: ""
TERM: xterm
TZ: US/Pacific
INSTRUMENT_COVERAGE: "true"
jobs:
run:
runs-on: ubuntu-22.04
timeout-minutes: 60
name: coverage-shard-${{ inputs.split_index }}
env:
MB_EDITION: ${{ inputs.edition }}
CYPRESS_MB_ALL_FEATURES_TOKEN: ${{ secrets.STAGING_MB_ALL_FEATURES_TOKEN }}
CYPRESS_MB_STARTER_CLOUD_TOKEN: ${{ secrets.STAGING_MB_STARTER_CLOUD_TOKEN }}
CYPRESS_MB_PRO_CLOUD_TOKEN: ${{ secrets.STAGING_MB_PRO_CLOUD_TOKEN }}
CYPRESS_MB_PRO_SELF_HOSTED_TOKEN: ${{ secrets.STAGING_MB_PRO_SELF_HOSTED_TOKEN }}
steps:
- uses: actions/checkout@v6
with:
submodules: true
token: ${{ secrets.METABASE_AUTOMATION_USER_TOKEN }}
- name: Prepare Docker containers
uses: ./.github/actions/e2e-prepare-containers
with:
username: ${{ secrets.DOCKERHUB_USERNAME }}
password: ${{ secrets.DOCKERHUB_TOKEN }}
maildev: true
openldap: true
webhook: true
snowplow: true
postgres: true
mysql: true
mongo: true
# The orchestrator built and uploaded this in an earlier job of the same run.
- name: Download instrumented uberjar
uses: actions/download-artifact@v8
with:
name: instrumented-uberjar
path: target/uberjar
- name: Prepare front-end environment
uses: ./.github/actions/prepare-frontend
- name: Prepare back-end environment
uses: ./.github/actions/prepare-backend
- name: Prepare Cypress environment
id: cypress-prep
uses: ./.github/actions/prepare-cypress
- name: Compile CLJS
run: bun run build-pure:cljs
- name: Run Metabase
run: node e2e/runner/run_cypress_ci.js start
- name: Generate database snapshots
env:
CYPRESS_BROWSER: ${{ steps.cypress-prep.outputs.chrome-path }}
run: node e2e/runner/run_cypress_ci.js snapshot
# cypress-split divides the spec set by timing data; INSTRUMENT_COVERAGE
# makes the support hook drain __coverage__ into e2e/coverage-manifest-raw/.
- name: Run shard ${{ inputs.split_index }}
# No SPLIT_FILE: cypress-split shards evenly by spec count using
# SPLIT/SPLIT_INDEX alone. Omitting it means no timings are read or
# written, which avoids cypress-split's after:run writeback (it would
# otherwise try to overwrite ./e2e/support/timings.json from a cwd where
# that subpath isn't reachable, crashing the run). Even-by-count is fine
# here — every spec runs exactly once across the shards.
env:
SPLIT: ${{ inputs.total_chunks }}
SPLIT_INDEX: ${{ inputs.split_index }}
SPLIT_SUMMARY: false
CYPRESS_BROWSER: ${{ steps.cypress-prep.outputs.chrome-path }}
run: |
node e2e/runner/run_cypress_ci.js e2e \
--expose grepTags="-@mongo+-@python+-@OSS+-@skip"
# 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
- name: Upload shard coverage
if: always()
uses: actions/upload-artifact@v7
with:
name: coverage-shard-${{ inputs.split_index }}
path: e2e/coverage-manifest-raw/
retention-days: 7
if-no-files-found: warn

View File

@@ -46,7 +46,7 @@ jobs:
const { buildMatrix } = require('${{ github.workspace }}/.github/scripts/build-e2e-matrix.js');
const inputSpecs = "${{ inputs.specs }}";
const inputChunks = Number(process.env.chunks);
const java = 21;
const java = 25;
const defaultRunner = "${{ vars.DEFAULT_RUNNER_KEY }}";
const options = {
java,

View File

@@ -36,6 +36,54 @@ on:
type: boolean
required: false
default: false
build_jar:
description: "Build the uberjar from this branch (required to test frontend fixes) instead of downloading a prebuilt one"
type: boolean
required: false
default: false
# Reusable form so other workflows (e.g. the flaky-test-fix PR auto-runner) can fan a
# matrix of changed specs into individual stress runs. Inputs mirror workflow_dispatch;
# both triggers read them via the `inputs` context.
workflow_call:
inputs:
spec:
description: "Relative path of the target spec"
type: string
required: true
burn_in:
description: "Number of times to run the test (e.g. 20)"
type: string
required: false
default: "20"
grep:
description: "Grep and filter tests to run in isolation"
type: string
required: false
mb_edition:
description: 'Set MB_EDITION env var to "ee" (enterprise) or "oss" (open-source)'
type: string
required: false
default: "ee"
qa_db:
description: "Whether to set up and include external QA databases"
type: boolean
required: false
default: false
enable_network_throttling:
description: "Enable network throttling simulation (4g slow like in chrome dev tools)"
type: boolean
required: false
default: true
fail_fast:
description: "Stop running remaining tests after the first failure"
type: boolean
required: false
default: false
build_jar:
description: "Build the uberjar from this branch (required to test frontend fixes) instead of downloading a prebuilt one"
type: boolean
required: false
default: false
jobs:
determine-test-type:
@@ -73,6 +121,7 @@ jobs:
echo '- `qa_db`: "${{ inputs.qa_db }}"' >> $GITHUB_STEP_SUMMARY
echo '- `enable_network_throttling`: "${{ inputs.enable_network_throttling }}"' >> $GITHUB_STEP_SUMMARY
echo '- `fail_fast`: "${{ inputs.fail_fast }}"' >> $GITHUB_STEP_SUMMARY
echo '- `build_jar`: "${{ inputs.build_jar }}"' >> $GITHUB_STEP_SUMMARY
echo '' >> $GITHUB_STEP_SUMMARY
echo 'triggered by: @${{ github.event.sender.login }}' >> $GITHUB_STEP_SUMMARY
@@ -109,16 +158,24 @@ jobs:
mysql: ${{ inputs.qa_db }}
mongo: ${{ inputs.qa_db }}
- name: Download Metabase ${{ matrix.edition }} uberjar
- name: Download Metabase ${{ inputs.mb_edition }} uberjar
if: ${{ !inputs.build_jar }}
uses: ./.github/actions/e2e-download-uberjar
with:
edition: "ee"
edition: ${{ inputs.mb_edition }}
- name: Prepare front-end environment
uses: ./.github/actions/prepare-frontend
- name: Prepare back-end environment
uses: ./.github/actions/prepare-backend
- name: Build Metabase ${{ inputs.mb_edition }} uberjar from this branch
if: ${{ inputs.build_jar }}
run: ./bin/build.sh
env:
# license check is irrelevant for ephemeral e2e jars and slows the build down
SKIP_LICENSES: true
- name: Build Embedding SDK package
if: ${{ needs.determine-test-type.outputs.type == 'component' }}
run: bun run build-embedding-sdk-package
@@ -146,13 +203,13 @@ jobs:
# For all options and fine-grained control, take a look at the documentation
# https://github.com/cypress-io/cypress/tree/develop/npm/grep
- name: Stress-test ${{ github.event.inputs.spec }} ${{ github.event.inputs.burn_in }} times
- name: Stress-test ${{ inputs.spec }} ${{ inputs.burn_in }} times
env:
GREP: ${{ github.event.inputs.grep }}
GREP: ${{ inputs.grep }}
CYPRESS_BROWSER: ${{ steps.cypress-prep.outputs.chrome-path }}
FAIL_FAST: ${{ inputs.fail_fast }}
SPEC: ${{ github.event.inputs.spec }}
BURN_IN: ${{ github.event.inputs.burn_in }}
SPEC: ${{ inputs.spec }}
BURN_IN: ${{ inputs.burn_in }}
run: |
node e2e/runner/run_cypress_ci.js ${{ needs.determine-test-type.outputs.type }} \
--spec "${SPEC}" \

View File

@@ -0,0 +1,94 @@
name: E2E Stress Test (flaky-test-fix PR)
# Auto-runs the e2e stress test on every changed Cypress spec in a PR
on:
pull_request:
# `opened`/`reopened` catch PRs created already labelled; `labeled` catches the label
# being added later; `synchronize` re-burns after new commits while the label is set.
types: [opened, reopened, synchronize, labeled]
concurrency:
# One in-flight set of stress runs per PR branch — new commits cancel the previous burn.
group: ${{ github.workflow }}-${{ github.ref }}
cancel-in-progress: true
jobs:
detect-changed-specs:
name: Detect changed e2e specs
# The PR must carry the `flaky-test-fix` label (covers opened/reopened/synchronize), AND
# when this is a `labeled` event we only proceed if the label *just added* is
# `flaky-test-fix` — otherwise adding any unrelated label to an already-labelled
# PR would needlessly re-burn the whole stress matrix.
if: >-
contains(github.event.pull_request.labels.*.name, 'flaky-test-fix') &&
(github.event.action != 'labeled' || github.event.label.name == 'flaky-test-fix')
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
timeout-minutes: 5
outputs:
# JSON array of spec paths, consumed by the matrix below.
specs: ${{ steps.detect.outputs.specs }}
should_run: ${{ steps.detect.outputs.should_run }}
# burn-50 / burn-100 labels bump the burn-in past 20
burn_in: >-
${{ contains(github.event.pull_request.labels.*.name, 'burn-100') && '100'
|| contains(github.event.pull_request.labels.*.name, 'burn-50') && '50'
|| '20' }}
steps:
- name: Detect changed Cypress spec files
id: detect
env:
GH_TOKEN: ${{ github.token }}
REPO: ${{ github.repository }}
PR_NUMBER: ${{ github.event.pull_request.number }}
run: | # sh
# List every file in the PR, drop deletions, then keep only regular e2e Cypress
# specs: paths under e2e/ ending in .cy.spec.{js,ts,tsx}, excluding the
# embedding-SDK component specs under e2e/test-component/ (those use a different
# runner and are out of scope here). The greps are guarded with `|| true` so an
# empty match doesn't trip `pipefail`.
FILES=$(
gh api "repos/${REPO}/pulls/${PR_NUMBER}/files" \
--paginate \
--jq '.[] | select(.status != "removed") | .filename' \
| { grep -E '^e2e/.*\.cy\.spec\.(js|ts|tsx)$' || true; } \
| { grep -v '^e2e/test-component/' || true; } \
| sort -u
)
if [[ -z "$FILES" ]]; then
echo "No changed e2e Cypress spec files found — nothing to stress test."
echo "should_run=false" >> "$GITHUB_OUTPUT"
exit 0
fi
echo "Changed e2e Cypress specs:"
echo "$FILES" | sed 's/^/ - /'
# Compact JSON array for the matrix, e.g. ["e2e/test/scenarios/a.cy.spec.js"].
SPECS_JSON=$(echo "$FILES" | jq -R . | jq -cs .)
echo "specs=${SPECS_JSON}" >> "$GITHUB_OUTPUT"
echo "should_run=true" >> "$GITHUB_OUTPUT"
echo "Note: you can use the burn-50 or burn-100 labels to increase the burn-in count from the default of 20." >> $GITHUB_STEP_SUMMARY
stress-test:
name: Stress test
needs: detect-changed-specs
if: needs.detect-changed-specs.outputs.should_run == 'true'
strategy:
# Don't let one flaky spec (or one throttling regime) cancel the burn-in of the others.
fail-fast: false
matrix:
spec: ${{ fromJson(needs.detect-changed-specs.outputs.specs) }}
# Burn each spec with and without throttle
enable_network_throttling: [true, false]
uses: ./.github/workflows/e2e-stress-test-flake-fix.yml
secrets: inherit
with:
spec: ${{ matrix.spec }}
burn_in: ${{ needs.detect-changed-specs.outputs.burn_in }}
qa_db: true
mb_edition: ee
build_jar: true
enable_network_throttling: ${{ matrix.enable_network_throttling }}

View File

@@ -37,6 +37,20 @@ env:
HASH: ${{ github.event.pull_request.head.sha || github.sha }}-${{ github.run_attempt }}
PR_NUMBER: ${{ github.event.pull_request.number || '' }}
JOB_NAME: ${{ inputs.name }}
# ci-conductor reporting (DEV-1999). Secret holds the base origin
# (e.g. "https://conductor.<host>"); each consumer appends the path it needs
# (the reporter POSTs to "/webhooks/failed-tests"). Callers pass
# `secrets: inherit`; reporting no-ops when it's unset.
CI_CONDUCTOR_BASE_URL: ${{ secrets.CI_CONDUCTOR_BASE_URL }}
# Shared secret sent as the `x-internal-secret` header to authenticate.
CI_CONDUCTOR_WEBHOOK_SECRET: ${{ secrets.CI_CONDUCTOR_WEBHOOK_SECRET }}
REPO_ID: ${{ github.event.repository.id }}
# Commit + PR target branch under test, so conductor can tie failures to the
# right code. On PRs the ambient GITHUB_SHA is the synthetic merge commit and
# GITHUB_BASE_REF the target, so we pass the PR head sha / base ref explicitly
# (falling back to push-event values). The reporter reads these. DEV-1999.
COMMIT_SHA: ${{ github.event.pull_request.head.sha || github.sha }}
TARGET_BRANCH: ${{ github.event.pull_request.base.ref || github.ref_name }}
jobs:
e2e-tests:
@@ -45,6 +59,11 @@ jobs:
name: e2e-tests-${{ inputs.name }}-${{ inputs.edition }}
env:
MB_EDITION: ${{ inputs.edition }}
# Absolute path for the quarantine failures file (DEV-2082). The after:spec
# recorder runs in Cypress' plugins process, whose cwd differs from the
# workspace where the gate step runs; an absolute path anchored to the
# workspace makes both agree regardless of cwd.
QUARANTINE_FAILURES_FILE: ${{ github.workspace }}/target/quarantine-failures.jsonl
# Sensitive env vars (tokens, secrets) starting with `CYPRESS_` are accessed via async `cy.env()`
# Example: `cy.env(["FOO"]).then(({ FOO }) => ...)`
# For non-sensitive config, use `Cypress.expose()` in cypress config instead (synchronous)
@@ -112,6 +131,15 @@ jobs:
- name: Run Metabase
run: node e2e/runner/run_cypress_ci.js start
# Export this job's numeric GitHub job id as $JOB_ID for the Cypress runs
# below (ci-conductor failed-tests reporting reads it in after:spec).
# Snapshot generation is itself a Cypress run that fires after:spec, so
# this must precede it. Placed late, not after checkout: the Actions jobs
# API is eventually consistent, so the longer the job has been alive the
# more reliably the lookup resolves. JOB_ID exported here persists to the
# steps below. DEV-1999.
- uses: ./.github/actions/resolve-job-id
- name: Generate database snapshots
env:
CYPRESS_BROWSER: ${{ steps.cypress-prep.outputs.chrome-path }}
@@ -136,9 +164,7 @@ jobs:
node e2e/runner/run_cypress_ci.js e2e \
--expose grepTags="-@mongo+-@python+-@OSS+-@skip" \
--spec "$SPEC_PATH"
# Trunk Quarantine controls the final state of the run in the CI!
# Even if this step fails we let it pass, and then `trunk-io/analytics-uploader` determines
# whether to fail or to pass the whole job, based on the quarantine list.
# Keep this step continue-on-error because the quarantine logic controls whether it ultimately fails.
continue-on-error: true
- name: Run Tagged EE Cypress tests on ${{ inputs.name }}
@@ -151,20 +177,20 @@ jobs:
run: |
echo "Running tests with specs: $SPEC_PATH"
node e2e/runner/run_cypress_ci.js e2e \
--expose grepTags="${{inputs.tags && format('{0}+-@skip', inputs.tags) || '-@skip'}}" \
--expose grepTags="${{inputs.tags && format('{0}+-@skip', inputs.tags) || '-@mongo+-@python+-@OSS+-@skip'}}" \
--spec "$SPEC_PATH"
# Trunk Quarantine controls the final state of the run in the CI!
# Even if this step fails we let it pass, and then `trunk-io/analytics-uploader` determines
# whether to fail or to pass the whole job, based on the quarantine list.
# Keep this step continue-on-error because the quarantine logic controls whether it ultimately fails.
continue-on-error: true
- name: Rewrite JUnit hook failures (dry-run)
- name: Rewrite JUnit hook failures
if: always()
continue-on-error: true
timeout-minutes: 1
shell: bash
run: |
if [ -d ./target/junit ]; then
bun e2e/support/fix-junit-hooks.ts --dry-run ./target/junit
echo "fix-junit-hooks: invoking bun"
bun e2e/support/fix-junit-hooks.ts ./target/junit
else
echo "No ./target/junit directory; nothing to process."
fi
@@ -183,6 +209,18 @@ jobs:
variant: e2e-tests
trunk-api-token: ${{ secrets.TRUNK_API_TOKEN }}
previous-step-outcome: ${{ inputs.specs && steps.tagged-e2e.outcome || steps.split-e2e.outcome }}
run-trunk: ${{ vars.QUARANTINE_ENGINE != 'ci-conductor' }}
- name: Quarantine gate
# Only one of the two run steps executes; the other reports `skipped`. Only gate on actual failure.
if: ${{ !cancelled() && (steps.split-e2e.outcome == 'failure' || steps.tagged-e2e.outcome == 'failure') }}
continue-on-error: ${{ vars.QUARANTINE_ENGINE != 'ci-conductor' }}
timeout-minutes: 3
uses: ./.github/actions/quarantine-gate
with:
adapter: e2e
test-suite: e2e
enforce-quarantine: ${{ vars.QUARANTINE_ENGINE == 'ci-conductor' }}
- name: Upload Cypress Artifacts upon failure
uses: actions/upload-artifact@v7

View File

@@ -8,6 +8,12 @@ env:
TERM: xterm
TZ: US/Pacific # to make Node match the instance tz
MB_EDITION: "ee"
CI_CONDUCTOR_BASE_URL: ${{ secrets.CI_CONDUCTOR_BASE_URL }}
CI_CONDUCTOR_WEBHOOK_SECRET: ${{ secrets.CI_CONDUCTOR_WEBHOOK_SECRET }}
REPO_ID: ${{ github.event.repository.id }}
COMMIT_SHA: ${{ github.event.pull_request.head.sha || github.sha }}
TARGET_BRANCH: ${{ github.event.pull_request.base.ref || github.ref_name }}
QUARANTINE_FAILURES_FILE: ${{ github.workspace }}/target/quarantine-failures.jsonl
jobs:
sdk-component-tests:
@@ -19,6 +25,7 @@ jobs:
react-version: [18, 19]
fail-fast: false
env:
CI_CONDUCTOR_TEST_SUITE: embedding-sdk-component-react-${{ matrix.react-version }}
# Sensitive env vars (tokens, secrets) starting with `CYPRESS_` are accessed via async `cy.env()`
# Example: `cy.env(["FOO"]).then(({ FOO }) => ...)`
# For non-sensitive config, use `Cypress.expose()` in cypress config instead (synchronous)
@@ -38,7 +45,7 @@ jobs:
maildev: true
openldap: false
webhook: false
snowplow: false
snowplow: true
postgres: false
mysql: false
mongo: false
@@ -69,6 +76,8 @@ jobs:
- name: Run Metabase
run: node e2e/runner/run_cypress_ci.js start
- uses: ./.github/actions/resolve-job-id
- name: Make app db snapshot
env:
CYPRESS_BROWSER: ${{ steps.cypress-prep.outputs.chrome-path }}
@@ -86,14 +95,18 @@ jobs:
env:
CYPRESS_BROWSER: ${{ steps.cypress-prep.outputs.chrome-path }}
run: node e2e/runner/run_cypress_ci.js component
# Keep this step continue-on-error because the quarantine logic controls whether it ultimately fails.
continue-on-error: true
- name: Rewrite JUnit hook failures (dry-run)
- name: Rewrite JUnit hook failures
if: always()
continue-on-error: true
timeout-minutes: 1
shell: bash
run: |
if [ -d ./target/junit ]; then
bun e2e/support/fix-junit-hooks.ts --dry-run ./target/junit
echo "fix-junit-hooks: invoking bun"
bun e2e/support/fix-junit-hooks.ts ./target/junit
else
echo "No ./target/junit directory; nothing to process."
fi
@@ -109,10 +122,21 @@ jobs:
aws-region: ${{ vars.AWS_REGION }}
trunk-api-token: ${{ secrets.TRUNK_API_TOKEN }}
previous-step-outcome: ${{ steps.run-tests.outcome }}
run-trunk: ${{ vars.QUARANTINE_ENGINE != 'ci-conductor' }}
- name: Quarantine gate
if: ${{ !cancelled() && steps.run-tests.outcome == 'failure' }}
continue-on-error: ${{ vars.QUARANTINE_ENGINE != 'ci-conductor' }}
timeout-minutes: 3
uses: ./.github/actions/quarantine-gate
with:
adapter: e2e
test-suite: ${{ env.CI_CONDUCTOR_TEST_SUITE }}
enforce-quarantine: ${{ vars.QUARANTINE_ENGINE == 'ci-conductor' }}
- name: "SDK component tests > Upload Cypress Artifacts upon failure"
uses: actions/upload-artifact@v7
if: failure()
if: ${{ !cancelled() && steps.run-tests.outcome == 'failure' }}
with:
name: cypress-recording-embedding-sdk-react-${{ matrix.react-version }}
path: |
@@ -121,7 +145,7 @@ jobs:
if-no-files-found: ignore
- name: "SDK component tests > Publish Summary"
if: failure()
if: ${{ !cancelled() && steps.run-tests.outcome == 'failure' }}
uses: actions/github-script@v9
with:
script: | #js
@@ -166,6 +190,7 @@ jobs:
env:
MB_RUN_MODE: "e2e"
METASTORE_DEV_SERVER_URL: ${{ secrets.METASTORE_DEV_SERVER_URL }}
CI_CONDUCTOR_TEST_SUITE: embedding-sdk-component-backward-compatibility
# Sensitive env vars (tokens, secrets) starting with `CYPRESS_` are accessed via async `cy.env()`
# Example: `cy.env(["FOO"]).then(({ FOO }) => ...)`
# For non-sensitive config, use `Cypress.expose()` in cypress config instead (synchronous)
@@ -188,7 +213,7 @@ jobs:
maildev: true
openldap: false
webhook: false
snowplow: false
snowplow: true
postgres: false
mysql: false
mongo: false
@@ -235,6 +260,8 @@ jobs:
- name: Run Metabase
run: node e2e/runner/run_cypress_ci.js start
- uses: ./.github/actions/resolve-job-id
- name: Make app db snapshot
env:
CYPRESS_BROWSER: ${{ steps.cypress-prep.outputs.chrome-path }}
@@ -250,14 +277,18 @@ jobs:
run: |
node e2e/runner/run_cypress_ci.js component \
--expose grepTags="-@skip-backward-compatibility"
# Keep this step continue-on-error because the quarantine logic controls whether it ultimately fails.
continue-on-error: true
- name: Rewrite JUnit hook failures (dry-run)
- name: Rewrite JUnit hook failures
if: always()
continue-on-error: true
timeout-minutes: 1
shell: bash
run: |
if [ -d ./target/junit ]; then
bun e2e/support/fix-junit-hooks.ts --dry-run ./target/junit
echo "fix-junit-hooks: invoking bun"
bun e2e/support/fix-junit-hooks.ts ./target/junit
else
echo "No ./target/junit directory; nothing to process."
fi
@@ -273,10 +304,21 @@ jobs:
aws-region: ${{ vars.AWS_REGION }}
trunk-api-token: ${{ secrets.TRUNK_API_TOKEN }}
previous-step-outcome: ${{ steps.run-tests.outcome }}
run-trunk: ${{ vars.QUARANTINE_ENGINE != 'ci-conductor' }}
- name: Quarantine gate
if: ${{ !cancelled() && steps.run-tests.outcome == 'failure' }}
continue-on-error: ${{ vars.QUARANTINE_ENGINE != 'ci-conductor' }}
timeout-minutes: 3
uses: ./.github/actions/quarantine-gate
with:
adapter: e2e
test-suite: ${{ env.CI_CONDUCTOR_TEST_SUITE }}
enforce-quarantine: ${{ vars.QUARANTINE_ENGINE == 'ci-conductor' }}
- name: Upload Cypress Artifacts upon failure
uses: actions/upload-artifact@v7
if: failure()
if: ${{ !cancelled() && steps.run-tests.outcome == 'failure' }}
with:
name: cypress-recording-embedding-sdk-cross-version
path: |
@@ -285,7 +327,7 @@ jobs:
if-no-files-found: ignore
- name: Publish Summary
if: failure()
if: ${{ !cancelled() && steps.run-tests.outcome == 'failure' }}
uses: actions/github-script@v9
with:
script: | #js

View File

@@ -171,6 +171,8 @@ jobs:
- name: Log free disk space
run: df -h /
- uses: ./.github/actions/resolve-job-id
- name: Run e2e tests for Sample App
id: run-e2e-tests
if: ${{ steps.check-sample-app-branch.outputs.sample_app_branch_exists == 'true' }}
@@ -238,6 +240,8 @@ jobs:
shoppy-datadog-application-id: ${{ secrets.SHOPPY_METABASE_APP_DATADOG_APPLICATION_ID }}
shoppy-datadog-client-token: ${{ secrets.SHOPPY_METABASE_APP_DATADOG_CLIENT_TOKEN }}
- uses: ./.github/actions/resolve-job-id
- name: Run e2e tests for Shoppy
id: run-e2e-tests
if: ${{ steps.shoppy-prep.outputs.sample_app_branch_exists == 'true' }}
@@ -316,6 +320,8 @@ jobs:
env:
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
- uses: ./.github/actions/resolve-job-id
- name: Run synthetic monitoring tests
id: run-e2e-tests
if: ${{ steps.shoppy-prep.outputs.sample_app_branch_exists == 'true' }}
@@ -363,6 +369,19 @@ jobs:
timeout-minutes: 45
name: e2e-host-app-${{ matrix.test_suite }}-tests-${{ matrix.environment }}-bundle
env:
# Host apps are the only suite here running through Metabase's Cypress config,
# whose `after:spec` hook reports failures and writes QUARANTINE_FAILURES_FILE.
# Sample-app suites load their own config (no-op), so ci-conductor is scoped to this job.
CI_CONDUCTOR_BASE_URL: ${{ secrets.CI_CONDUCTOR_BASE_URL }}
CI_CONDUCTOR_WEBHOOK_SECRET: ${{ secrets.CI_CONDUCTOR_WEBHOOK_SECRET }}
CI_CONDUCTOR_TEST_SUITE: embedding-sdk-host-app
REPO_ID: ${{ github.event.repository.id }}
COMMIT_SHA: ${{ github.event.pull_request.head.sha || github.sha }}
TARGET_BRANCH: ${{ github.event.pull_request.base.ref || github.ref_name }}
QUARANTINE_FAILURES_FILE: ${{ github.workspace }}/target/quarantine-failures.jsonl
# `Fail job if tests failed` is the arbiter until ci-conductor takes over.
# Exactly one of the two gates the job.
CI_CONDUCTOR_QUARANTINE_ACTIVE: ${{ vars.QUARANTINE_ENGINE == 'ci-conductor' }}
CYPRESS_MB_ALL_FEATURES_TOKEN: ${{ secrets.STAGING_MB_ALL_FEATURES_TOKEN }}
HOST_APP_ENVIRONMENT: ${{ matrix.environment }}
permissions:
@@ -399,6 +418,8 @@ jobs:
- name: Run Metabase
run: node e2e/runner/run_cypress_ci.js start
- uses: ./.github/actions/resolve-job-id
- name: Generate database snapshots
run: |
node e2e/runner/run_cypress_ci.js snapshot \
@@ -416,14 +437,24 @@ jobs:
- name: Upload Cypress Artifacts upon failure
uses: actions/upload-artifact@v7
if: ${{ steps.run-e2e-tests.outcome != 'success' }}
if: ${{ !cancelled() && steps.run-e2e-tests.outcome == 'failure' }}
with:
name: cypress-recording-host-app-${{ matrix.test_suite }}-${{ matrix.environment }}-latest
path: |
./cypress
if-no-files-found: ignore
- name: Quarantine gate
if: ${{ !cancelled() && steps.run-e2e-tests.outcome == 'failure' }}
continue-on-error: ${{ env.CI_CONDUCTOR_QUARANTINE_ACTIVE != 'true' }}
timeout-minutes: 3
uses: ./.github/actions/quarantine-gate
with:
adapter: e2e
test-suite: ${{ env.CI_CONDUCTOR_TEST_SUITE }}
enforce-quarantine: ${{ env.CI_CONDUCTOR_QUARANTINE_ACTIVE }}
- name: Fail job if tests failed
if: ${{ steps.run-e2e-tests.outcome != 'success' }}
if: ${{ !cancelled() && steps.run-e2e-tests.outcome == 'failure' && env.CI_CONDUCTOR_QUARANTINE_ACTIVE != 'true' }}
run: |
exit 1

View File

@@ -0,0 +1,45 @@
name: Tag Embedding SDK npm release as latest
on:
workflow_dispatch:
inputs:
version:
description: "npm version to tag as latest, e.g. 0.61.5"
type: string
required: true
workflow_call:
inputs:
version:
description: "npm version to tag as latest, e.g. 0.61.5"
type: string
required: true
concurrency:
group: npm-dist-tag-latest
cancel-in-progress: false
permissions: {}
jobs:
tag-latest:
name: Tag npm release as latest
runs-on: ${{ vars.DEFAULT_RUNNER_KEY }}
timeout-minutes: 5
env:
VERSION: ${{ inputs.version }}
steps:
- name: Setup Node.js
uses: actions/setup-node@v6.4.0
with:
node-version: 24
registry-url: https://registry.npmjs.org
- name: Verify version exists on npm
run: npm view "@metabase/embedding-sdk-react@$VERSION" version
- name: Add `latest` dist-tag to npm release
run: |
npm dist-tag add "@metabase/embedding-sdk-react@$VERSION" latest
echo "Tagged @metabase/embedding-sdk-react@$VERSION as latest" >> "$GITHUB_STEP_SUMMARY"
env:
NODE_AUTH_TOKEN: ${{ secrets.NPM_RELEASE_TOKEN }}

View File

@@ -150,7 +150,7 @@ jobs:
with:
remove-previous-comment: true
add-new-comment: true
message: "⚠️ Embedding SDK bundle size increased by ${{ steps.compare.outputs.size_change_percent }}% compared to the ${{ github.base_ref }} branch (threshold: ${{ env.BUNDLE_SIZE_THRESHOLD_PERCENT }}%). Please contact Embedding team."
message: "⚠️ Embedding SDK chunked bundle size (gzipped) increased by ${{ steps.compare.outputs.size_change_percent }}% compared to the ${{ github.base_ref }} branch (threshold: ${{ env.BUNDLE_SIZE_THRESHOLD_PERCENT }}%). Please contact Embedding team."
include-log: false
- name: Send notification to Slack via Zapier
@@ -165,7 +165,7 @@ jobs:
PR_URL: ${{ github.event.pull_request.html_url }}
run: |
curl -s -X POST "$ZAPIER_WEBHOOK_URL" \
-d "⚠️ Embedding SDK bundle size increased by ${SIZE_CHANGE_PERCENT}% (threshold: ${BUNDLE_SIZE_THRESHOLD_PERCENT}%)
-d "⚠️ Embedding SDK chunked bundle size (gzipped) increased by ${SIZE_CHANGE_PERCENT}% (threshold: ${BUNDLE_SIZE_THRESHOLD_PERCENT}%)
PR #${PR_NUMBER} ${PR_TITLE} (${PR_URL})"
@@ -175,7 +175,7 @@ jobs:
with:
remove-previous-comment: true
add-new-comment: true
message: "🎉 Embedding SDK bundle size decreased by ${{ steps.compare.outputs.size_change_percent }}% compared to the ${{ github.base_ref }} branch. Nice work!"
message: "🎉 Embedding SDK chunked bundle size (gzipped) decreased by ${{ steps.compare.outputs.size_change_percent }}% compared to the ${{ github.base_ref }} branch. Nice work!"
include-log: false
embedding-sdk-tests-result:

View File

@@ -18,8 +18,10 @@ jobs:
core.setOutput('issue_title', ${{ toJson(github.event.issue.title) }}.replaceAll(/"/g, '\\"'));
- name: Send escalated issue ${{ github.event.issue.number }} to Slack
id: slack
uses: slackapi/slack-github-action@007b2c3c751a190b6f0f040e47ed024deaa72844 # v1.23.0
uses: slackapi/slack-github-action@45a88b9581bfab2566dc881e2cd66d334e621e2c # v3.0.3
with:
webhook: ${{ secrets.SLACK_ESCALATIONS_WEBHOOK_URL }}
webhook-type: incoming-webhook
payload: |
{
"blocks": [
@@ -32,6 +34,3 @@ jobs:
}
]
}
env:
SLACK_WEBHOOK_URL: ${{ secrets.SLACK_ESCALATIONS_WEBHOOK_URL }}
SLACK_WEBHOOK_TYPE: INCOMING_WEBHOOK

View File

@@ -31,6 +31,13 @@ concurrency:
group: ${{ github.workflow }}-${{ github.head_ref && github.ref || github.run_id }}-frontend
cancel-in-progress: true
env:
# Consumed by the report-failures-to-ci-conductor step in fe-tests-unit. Absent
# (e.g. fork PRs without secret access) the reporter no-ops. Matches the other
# suite workflows (backend, drivers, e2e, app-db, semantic-search).
CI_CONDUCTOR_BASE_URL: ${{ secrets.CI_CONDUCTOR_BASE_URL }}
CI_CONDUCTOR_WEBHOOK_SECRET: ${{ secrets.CI_CONDUCTOR_WEBHOOK_SECRET }}
jobs:
fe-lint:
if: ${{ !inputs.skip-lint }}
@@ -96,13 +103,32 @@ jobs:
uses: ./.github/actions/prepare-frontend
- name: Prepare back-end environment
uses: ./.github/actions/prepare-backend
- name: Resolve current job id
# Resolve JOB_ID before the long test step so the ci-conductor reporter
# below can link failures to this exact job. Best-effort.
uses: ./.github/actions/resolve-job-id
- name: Run frontend unit tests
id: fe-tests
run: bun run test-unit --silent --shard=${{ matrix.shard }}/${{ env.SHARDS }}
# Trunk Quarantine controls the final state of the run in the CI!
# Even if this step fails we let it pass, and then `trunk-io/analytics-uploader` determines
# whether to fail or to pass the whole job, based on the quarantine list.
# Keep this step continue-on-error because the quarantine logic controls whether it ultimately fails.
continue-on-error: true
- name: Report failed tests to ci-conductor
if: ${{ !cancelled() && steps.fe-tests.outcome == 'failure' }}
# This step should NEVER fail the job!
continue-on-error: true
uses: ./.github/actions/report-failures-to-ci-conductor
with:
test-suite: fe-tests-unit
adapter: frontend
- name: Quarantine gate
if: ${{ !cancelled() && steps.fe-tests.outcome == 'failure' }}
continue-on-error: ${{ vars.QUARANTINE_ENGINE != 'ci-conductor' }}
timeout-minutes: 3
uses: ./.github/actions/quarantine-gate
with:
adapter: frontend
test-suite: fe-tests-unit
enforce-quarantine: ${{ vars.QUARANTINE_ENGINE == 'ci-conductor' }}
- name: Upload Test Results
uses: ./.github/actions/upload-test-results
if: always() && github.event_name != 'workflow_dispatch'
@@ -114,6 +140,7 @@ jobs:
aws-region: ${{ vars.AWS_REGION }}
trunk-api-token: ${{ secrets.TRUNK_API_TOKEN }}
previous-step-outcome: ${{ steps.fe-tests.outcome }}
run-trunk: ${{ vars.QUARANTINE_ENGINE != 'ci-conductor' }}
fe-tests-timezones:
if: ${{ !inputs.skip }}

View File

@@ -13,10 +13,10 @@ on:
type: string
required: true
burn_in:
description: "Number of times to run the test (e.g. 50)"
description: "Number of times to run the test (e.g. 10)"
type: string
required: true
default: "50"
default: "10"
jobs:
detect-changed-stories:
@@ -59,7 +59,9 @@ jobs:
fi
FILES=$( \
gh pr view ${{ github.event.pull_request.number }} --repo ${{ github.repository }} --json files --jq '.files[].path' \
gh api "repos/${{ github.repository }}/pulls/${{ github.event.pull_request.number }}/files" \
--paginate \
--jq '.[] | select(.status != "removed") | .filename' \
| grep '\.stories\.tsx$' \
| xargs -n1 \
| sort -u \
@@ -91,7 +93,7 @@ jobs:
env:
BRANCH_NAME: ${{ github.head_ref || github.ref_name }}
STORY_FILES: ${{ needs.detect-changed-stories.outputs.story_files }}
BURN_IN: ${{ inputs.burn_in || 50 }}
BURN_IN: ${{ inputs.burn_in || 10 }}
EVENT_NAME: ${{ github.event_name }}
PR_NUMBER: ${{ github.event.pull_request.number }}
PR_ACTOR: ${{ github.event.pull_request.user.login }}
@@ -152,7 +154,7 @@ jobs:
- name: Stress-test Loki
run: |
BURN_IN=${{ inputs.burn_in || '50' }}
BURN_IN=${{ inputs.burn_in || '10' }}
STORY_FILES='${{ needs.detect-changed-stories.outputs.story_files }}'
echo "Story files: $STORY_FILES"

View File

@@ -42,7 +42,7 @@ jobs:
git config --global user.name "Metabase Automation"
git config --global user.email "github-automation@metabase.com"
git add .loki/reference/
git commit -m "Update Loki Snapshots"
git commit -m "Update Loki Snapshots" --no-verify
git push
env:
GITHUB_TOKEN: ${{ secrets.METABASE_AUTOMATION_USER_TOKEN }}

View File

@@ -19,8 +19,10 @@ jobs:
core.setOutput('issue_title', ${{ toJson(github.event.issue.title) }}.replaceAll(/"/g, '\\"'));
- name: Send the issue ${{ github.event.issue.number }} to Slack
id: slack
uses: slackapi/slack-github-action@70cd7be8e40a46e8b0eced40b0de447bdb42f68e # v1.26.0
uses: slackapi/slack-github-action@45a88b9581bfab2566dc881e2cd66d334e621e2c # v3.0.3
with:
webhook: ${{ secrets.SLACK_FEATURE_REQUEST_TRIAGE_WEBHOOK_URL }}
webhook-type: incoming-webhook
payload: |
{
"blocks": [
@@ -33,6 +35,3 @@ jobs:
}
]
}
env:
SLACK_WEBHOOK_URL: ${{ secrets.SLACK_FEATURE_REQUEST_TRIAGE_WEBHOOK_URL }}
SLACK_WEBHOOK_TYPE: INCOMING_WEBHOOK

View File

@@ -13,6 +13,8 @@ jobs:
steps:
- uses: actions/checkout@v6
- uses: oven-sh/setup-bun@0c5077e51419868618aeaa5fe8019c62421857d6 # v2.2.0
with:
bun-version-file: 'package.json'
- name: Install dependencies
run: bun install --frozen-lockfile
- name: get module boundary stats

View File

@@ -23,7 +23,7 @@ jobs:
- name: Get changed PNG files
id: changed-files
uses: tj-actions/changed-files@ed68ef82c095e0d48ec87eccea555d944a631a4c # v46
uses: tj-actions/changed-files@9426d40962ed5378910ee2e21d5f8c6fcbf2dd96 # v47.0.6
with:
files: |
docs/**/*.png

View File

@@ -56,7 +56,7 @@ jobs:
- name: Checkout source code
uses: actions/checkout@v6
- name: Tailscale
uses: tailscale/github-action@4e4c49acaa9818630ce0bd7a564372c17e33fb4d # v2
uses: tailscale/github-action@306e68a486fd2350f2bfc3b19fcd143891a4a2d8 # v4.1.2
with:
oauth-client-id: ${{ secrets.PR_ENV_TAILSCALE_OAUTH_CLIENT_ID }}
oauth-secret: ${{ secrets.PR_ENV_TAILSCALE_OAUTH_SECRET }}
@@ -74,7 +74,7 @@ jobs:
env:
PR_ENV_K8S_AUDIENCE: ${{ secrets.PR_ENV_K8S_AUDIENCE }}
- name: Setup Kube Context
uses: azure/k8s-set-context@0b53301dcc7ddd3f6d35f97fb67228ac4e5ab2fd # v2
uses: azure/k8s-set-context@89b837d75b40a7bd2ddafde837473c212db8b313 # v5.0.0
with:
method: kubeconfig
kubeconfig: |
@@ -110,7 +110,7 @@ jobs:
id: split
run: echo "fragment=${SHA:5}" >> $GITHUB_OUTPUT
- name: Render Deployment YAML
uses: nowactions/envsubst@c4b8e3977354d294659a7ec164279ce8fba5c2e1 # v1
uses: nowactions/envsubst@c4b8e3977354d294659a7ec164279ce8fba5c2e1 # v1.0.1
with:
input: ./perf-test-pr.yml.tmpl
output: ./perf-test-pr.yml

Some files were not shown because too many files have changed in this diff Show More