:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(metabase): add data model, permissions and query log tables (#115054)
Tom Owersd9a00a456f79
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.mdindex 8bfb439a5e34..433724649363 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md@@ -5549,10 +5549,10 @@ Today (6): `cards`, `collections`, `dashboards`, `databases`, `native_query_snipDiffed against: <https://www.metabase.com/docs/latest/api.json>-- [ ] `table (GET /api/table, /api/table/{id}/query_metadata)` — lookup table resolving the table IDs referenced by synced cards and databases (high)-- [ ] `field (GET /api/database/{id}/fields, /api/field/{id})` — column-level metadata lookup for the databases we already sync (high)-- [ ] `permissions groups and membership (GET /api/permissions/group, /api/permissions/membership)` — membership table joining synced users to permission groups (high)-- [ ] `query execution log (GET /api/ee/logs/query_execution/{yyyy-mm})` — per-execution runtime/error history — the core usage-analytics fact table (high)+- [x] `table (GET /api/table, /api/table/{id}/query_metadata)` — lookup table resolving the table IDs referenced by synced cards and databases (high)+- [x] `field (GET /api/database/{id}/fields, /api/field/{id})` — column-level metadata lookup for the databases we already sync (high)+- [x] `permissions groups and membership (GET /api/permissions/group, /api/permissions/membership)` — membership table joining synced users to permission groups (high)+- [x] `query execution log (GET /api/ee/logs/query_execution/{yyyy-mm})` — per-execution runtime/error history — the core usage-analytics fact table (high)- [ ] `activity recents (GET /api/activity/recent_views, /api/activity/recents, /api/activity/popular_items)` — who viewed which card/dashboard, the main content-usage signal (medium)- [ ] `revision (GET /api/revision, /api/revision/{entity}/{id})` — change history for cards and dashboards (medium)- [ ] `task runs (GET /api/task, /api/task/runs)` — sync/scheduled job history for database health monitoring (medium)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/metabase/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/metabase/canonical_descriptions.pyindex b0070fa113e2..c501f3935738 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/metabase/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/metabase/canonical_descriptions.py@@ -96,4 +96,74 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"updated_at": "Timestamp when the snippet was last updated.",},},+ "tables": {+ "description": "Tables Metabase has synced from the connected databases, with their data-model metadata.",+ "docs_url": "https://www.metabase.com/docs/latest/api",+ "columns": {+ "id": "Unique identifier for the table. Cards reference it as table_id.",+ "db_id": "Id of the database the table belongs to.",+ "name": "Name of the table in the source database.",+ "schema": "Schema the table lives in, when the database has schemas.",+ "display_name": "Human-friendly name shown in Metabase.",+ "description": "Optional description set in the data model.",+ "entity_type": "Semantic kind of table (e.g. entity/UserTable, entity/TransactionTable).",+ "visibility_type": "Why the table is hidden, if it is (e.g. hidden, technical, cruft). Null when visible.",+ "active": "Whether the table still exists in the source database.",+ "created_at": "Timestamp when Metabase first synced the table.",+ "updated_at": "Timestamp when the table metadata was last updated.",+ },+ },+ "fields": {+ "description": "Columns of the tables in each connected database, as Metabase models them.",+ "docs_url": "https://www.metabase.com/docs/latest/api",+ "columns": {+ "id": "Unique identifier for the field.",+ "name": "Name of the column in the source database.",+ "display_name": "Human-friendly name shown in Metabase.",+ "base_type": "Metabase base type of the column (e.g. type/Integer, type/Text).",+ "semantic_type": "Semantic type assigned in the data model (e.g. type/PK, type/Email), if any.",+ "table_id": "Id of the table the field belongs to.",+ "table_name": "Name of the table the field belongs to.",+ "schema": "Schema of the table the field belongs to.",+ "database_id": "Id of the database the field belongs to.",+ },+ },+ "permission_groups": {+ "description": "Permission groups that grant users access to data and collections.",+ "docs_url": "https://www.metabase.com/docs/latest/api",+ "columns": {+ "id": "Unique identifier for the group.",+ "name": "Display name of the group.",+ "member_count": "Number of users in the group.",+ },+ },+ "permission_group_memberships": {+ "description": "Which users belong to which permission groups.",+ "docs_url": "https://www.metabase.com/docs/latest/api",+ "columns": {+ "membership_id": "Unique identifier for the membership.",+ "group_id": "Id of the permission group.",+ "user_id": "Id of the user.",+ "is_group_manager": "Whether the user manages the group.",+ },+ },+ "query_executions": {+ "description": "One row per query Metabase ran, with its runtime, row count, and error. Pro and Enterprise only.",+ "docs_url": "https://www.metabase.com/docs/latest/api",+ "columns": {+ "id": "Unique identifier for the query execution.",+ "started_at": "Timestamp when the query started.",+ "running_time": "Time the query took to run, in milliseconds.",+ "result_rows": "Number of rows the query returned.",+ "native": "Whether the query was a native (SQL) query.",+ "context": "Where the query ran from (e.g. question, dashboard, ad-hoc).",+ "error": "Error message when the query failed, otherwise null.",+ "executor_id": "Id of the user who ran the query.",+ "card_id": "Id of the card that ran the query, if any.",+ "dashboard_id": "Id of the dashboard that ran the query, if any.",+ "pulse_id": "Id of the subscription or alert that ran the query, if any.",+ "database_id": "Id of the database the query ran against.",+ "cache_hit": "Whether the result came from the cache.",+ },+ },}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/metabase/metabase.py b/products/warehouse_sources/backend/temporal/data_imports/sources/metabase/metabase.pyindex e8468517acf2..871e97e70b7c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/metabase/metabase.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/metabase/metabase.py@@ -1,6 +1,7 @@import reimport dataclasses-from collections.abc import Iterator+from collections.abc import Iterable, Iterator+from datetime import UTC, datetimefrom typing import Any, Optionalfrom urllib.parse import urlparse@@ -16,10 +17,17 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.resRESTAPIConfig,rest_api_resource,)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (+ build_dependent_resource,+)from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (SinglePagePaginator,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import Endpoint+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (+ ClientConfig,+ Endpoint,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.metabase.settings import (METABASE_ENDPOINTS,@@ -28,6 +36,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.metabase.sREQUEST_TIMEOUT_SECONDS = 60+# Metabase deletes query_execution rows older than `audit-max-retention-days` (720 by default), so a+# full refresh walks back this many months before the current one.+QUERY_EXECUTION_LOOKBACK_MONTHS = 24+HOST_NOT_ALLOWED_ERROR = "Metabase host is not allowed"# Returned when the Instance URL responds with a 3xx. We refuse to follow redirects (an off-host@@ -42,6 +54,10 @@ REDIRECT_NOT_FOLLOWED_ERROR = (# returns a 2xx that isn't JSON (the Instance URL isn't a Metabase API).SESSION_RESPONSE_NOT_JSON_ERROR = "Metabase session response was not valid JSON"+# Stable substring matched by MetabaseSource.get_non_retryable_errors when the query log endpoint is+# missing (open-source edition) or not licensed.+QUERY_LOGS_UNAVAILABLE_ERROR = "Metabase query execution logs are unavailable"+API_KEY_AUTH = "api_key"SESSION_AUTH = "session"@@ -58,6 +74,10 @@ class MetabaseHostNotAllowedError(Exception):pass+class MetabaseQueryLogsUnavailableError(Exception):+ pass++class MetabaseAuthError(Exception):"""Raised when credentials are rejected (bad API key, or username/password that won't mint asession). Deterministic — retrying never fixes it — so it surfaces via get_non_retryable_errors."""@@ -65,6 +85,12 @@ class MetabaseAuthError(Exception):pass[email protected](frozen=True)+class MetabaseResumeConfig:+ # The next yyyy-mm window of the query log walk.+ next_month: str++@frozenclass MetabaseAuth:# "api_key" sends a static X-API-Key header; "session" mints a short-lived token via@@ -266,14 +292,111 @@ def validate_credentials()+def _parse_timestamp(value: Any) -> Optional[datetime]:+ if isinstance(value, datetime):+ parsed = value+ elif isinstance(value, str):+ try:+ parsed = datetime.fromisoformat(value)+ except ValueError:+ return None+ else:+ return None+ return parsed if parsed.tzinfo else parsed.replace(tzinfo=UTC)+++def _month_index(year: int, month: int) -> int:+ return year * 12 + (month - 1)+++def query_execution_months(now: datetime, last_value: Any) -> list[str]:+ """The yyyy-mm windows to fetch, oldest first, ending with the month of ``now``.++ Metabase buckets rows by month in its application database's timezone, so an incremental run+ starts one month before the watermark's UTC month to cover rows across that boundary.+ """+ watermark = _parse_timestamp(last_value)+ if watermark is None:+ start = _month_index(now.year, now.month) - QUERY_EXECUTION_LOOKBACK_MONTHS+ else:+ start = _month_index(watermark.year, watermark.month) - 1++ return [f"{index // 12:04d}-{index % 12 + 1:02d}" for index in range(start, _month_index(now.year, now.month) + 1)]+++def _started_at_sort_key(row: dict[str, Any]) -> datetime:+ return _parse_timestamp(row.get("started_at")) or datetime.min.replace(tzinfo=UTC)+++def _list_pages(+ client_config: ClientConfig, config: MetabaseEndpointConfig, path: str, team_id: int, job_id: str+) -> Iterable[Any]:+ endpoint_config: Endpoint = {"path": path, "params": dict(config.params)}+ if config.data_selector:+ endpoint_config["data_selector"] = config.data_selector++ rest_config: RESTAPIConfig = {+ "client": client_config,+ "resource_defaults": {},+ "resources": [{"name": config.name, "endpoint": endpoint_config}],+ }+ return rest_api_resource(rest_config, team_id, job_id, None)+++def _get_query_execution_rows(+ client_config: ClientConfig,+ config: MetabaseEndpointConfig,+ team_id: int,+ job_id: str,+ db_incremental_field_last_value: Any,+ resumable_source_manager: ResumableSourceManager[MetabaseResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ watermark = _parse_timestamp(db_incremental_field_last_value)+ months = query_execution_months(datetime.now(UTC), db_incremental_field_last_value)+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ if resume is not None and resume.next_month in months:+ months = months[months.index(resume.next_month) :]++ for index, month in enumerate(months):+ path = config.path.replace("{month}", month)+ try:+ rows = [row for page in _list_pages(client_config, config, path, team_id, job_id) for row in page]+ except requests.exceptions.HTTPError as e:+ # The route only exists on Pro/Enterprise builds, and an unlicensed instance refuses it.+ if e.response is not None and e.response.status_code in (402, 404):+ raise MetabaseQueryLogsUnavailableError(QUERY_LOGS_UNAVAILABLE_ERROR) from e+ raise++ if watermark is not None:+ rows = [row for row in rows if _started_at_sort_key(row) >= watermark]+ # Metabase returns each month newest first; ascending order keeps the incremental watermark+ # monotonic across months.+ rows.sort(key=_started_at_sort_key)+ if index + 1 < len(months):+ resumable_source_manager.save_state(MetabaseResumeConfig(next_month=months[index + 1]))+ if rows:+ yield rows+ else:+ resumable_source_manager.safe_point()+++def _flatten_grouped_rows(pages: Iterable[Any]) -> Iterator[list[dict[str, Any]]]:+ for page in pages:+ rows = [row for group in page for rows_for_key in group.values() for row in rows_for_key]+ if rows:+ yield rows++def get_rows(host: str,auth: MetabaseAuth,endpoint: str,logger: FilteringBoundLogger,team_id: int,+ resumable_source_manager: ResumableSourceManager[MetabaseResumeConfig],job_id: str = "",-) -> Iterator[list[dict[str, Any]]]:+ db_incremental_field_last_value: Any = None,+) -> Iterator[Any]:config = METABASE_ENDPOINTS[endpoint]base_url = normalize_host(host)@@ -294,27 +417,40 @@ def get_rows(session = make_tracked_session(redact_values=_redact_values_for_data_requests(auth, headers))- endpoint_config: Endpoint = {"path": config.path, "params": dict(config.params)}- if config.data_selector:- endpoint_config["data_selector"] = config.data_selector-- rest_config: RESTAPIConfig = {- "client": {- "base_url": base_url,- "headers": {"Accept": "application/json"},- "auth": {"type": "api_key", "name": auth_header_name, "api_key": secret, "location": "header"},- # Metabase list endpoints are unpaginated — one request returns the whole collection.- "paginator": SinglePagePaginator(),- # A pre-built tracked session carries the value redaction; disabling redirects rejects a- # customer-controlled host that 3xx-es toward an internal address (SSRF).- "session": session,- "allow_redirects": False,- },- "resource_defaults": {},- "resources": [{"name": endpoint, "endpoint": endpoint_config}],+ client_config: ClientConfig = {+ "base_url": base_url,+ "headers": {"Accept": "application/json"},+ "auth": {"type": "api_key", "name": auth_header_name, "api_key": secret, "location": "header"},+ # Metabase list endpoints are unpaginated — one request returns the whole collection.+ "paginator": SinglePagePaginator(),+ # A pre-built tracked session carries the value redaction; disabling redirects rejects a+ # customer-controlled host that 3xx-es toward an internal address (SSRF).+ "session": session,+ "allow_redirects": False,}- yield from rest_api_resource(rest_config, team_id, job_id, None)+ if config.fanout is not None:+ parent = METABASE_ENDPOINTS[config.fanout.parent_name]+ yield from build_dependent_resource(+ endpoint_configs=METABASE_ENDPOINTS,+ child_endpoint=endpoint,+ fanout=config.fanout,+ client_config=client_config,+ path_format_values={},+ team_id=team_id,+ job_id=job_id,+ db_incremental_field_last_value=None,+ parent_endpoint_extra={"data_selector": parent.data_selector} if parent.data_selector else None,+ page_size_param=None,+ )+ elif config.month_windowed:+ yield from _get_query_execution_rows(+ client_config, config, team_id, job_id, db_incremental_field_last_value, resumable_source_manager+ )+ elif config.grouped_by_key:+ yield from _flatten_grouped_rows(_list_pages(client_config, config, config.path, team_id, job_id))+ else:+ yield from _list_pages(client_config, config, config.path, team_id, job_id)def metabase_source(@@ -323,13 +459,26 @@ def metabase_source(endpoint: str,logger: FilteringBoundLogger,team_id: int,+ resumable_source_manager: ResumableSourceManager[MetabaseResumeConfig],job_id: str = "",+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,) -> SourceResponse:config: MetabaseEndpointConfig = METABASE_ENDPOINTS[endpoint]+ last_value = db_incremental_field_last_value if should_use_incremental_field else Nonereturn SourceResponse(name=endpoint,- items=lambda: get_rows(host=host, auth=auth, endpoint=endpoint, logger=logger, team_id=team_id, job_id=job_id),+ items=lambda: get_rows(+ host=host,+ auth=auth,+ endpoint=endpoint,+ logger=logger,+ team_id=team_id,+ resumable_source_manager=resumable_source_manager,+ job_id=job_id,+ db_incremental_field_last_value=last_value,+ ),primary_keys=config.primary_keys,partition_count=1,partition_size=1,diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/metabase/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/metabase/settings.pyindex b8ac554d443d..48db94664a15 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/metabase/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/metabase/settings.py@@ -1,8 +1,13 @@from dataclasses import dataclass, fieldfrom typing import Optional+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (+ DependentEndpointConfig,+)+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType-@dataclass++@dataclass(frozen=True)class MetabaseEndpointConfig:name: strpath: str@@ -17,11 +22,23 @@ class MetabaseEndpointConfig:# /api/collection, /api/native-query-snippet) return a bare JSON array — left None. Others# (/api/database, /api/user) wrap it as {"data": [...], "total": N} — set "data".data_selector: Optional[str] = None+ # Child endpoints fetched once per parent row (e.g. fields per database).+ fanout: Optional[DependentEndpointConfig] = None+ # The path carries a `{month}` placeholder (yyyy-mm) and returns that calendar month's rows.+ month_windowed: bool = False+ # The response is a JSON object mapping a key to a list of rows rather than a list of rows.+ grouped_by_key: bool = False+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # Read by the shared fan-out helper; Metabase list endpoints take no page-size param.+ default_incremental_field: Optional[str] = None+ page_size: int = 0# Metabase list endpoints return the full collection in a single response — there is no pagination-# and no server-side timestamp filter, so every schema is full-refresh only. The stream set mirrors-# the canonical Metabase connector (cards, dashboards, collections, databases, users, snippets).+# and no server-side timestamp filter, so every schema except the month-windowed query log is+# full-refresh only. The stream set mirrors+# the canonical Metabase connector (cards, dashboards, collections, databases, users, snippets), plus+# the data-model, permissions, and query-log tables.METABASE_ENDPOINTS: dict[str, MetabaseEndpointConfig] = {"cards": MetabaseEndpointConfig(name="cards", path="/api/card", partition_key="created_at"),"dashboards": MetabaseEndpointConfig(name="dashboards", path="/api/dashboard", partition_key="created_at"),@@ -34,6 +51,44 @@ METABASE_ENDPOINTS: dict[str, MetabaseEndpointConfig] = {"native_query_snippets": MetabaseEndpointConfig(name="native_query_snippets", path="/api/native-query-snippet", partition_key="created_at"),+ "tables": MetabaseEndpointConfig(name="tables", path="/api/table", partition_key="created_at"),+ # Field rows carry no creation timestamp and no database id, so the parent id is copied in.+ "fields": MetabaseEndpointConfig(+ name="fields",+ path="/api/database/{id}/fields",+ fanout=DependentEndpointConfig(+ parent_name="databases",+ resolve_param="id",+ resolve_field="id",+ include_from_parent=["id"],+ parent_field_renames={"id": "database_id"},+ # A database deleted between the parent listing and its fields fetch.+ child_response_actions=[{"status_code": 404, "action": "ignore"}],+ ),+ ),+ "permission_groups": MetabaseEndpointConfig(name="permission_groups", path="/api/permissions/group"),+ # Returns {user_id: [{membership_id, group_id, user_id, is_group_manager}, ...]}.+ "permission_group_memberships": MetabaseEndpointConfig(+ name="permission_group_memberships",+ path="/api/permissions/membership",+ primary_keys=["membership_id"],+ grouped_by_key=True,+ ),+ # Pro/Enterprise only and superuser only. The month window is the only server-side time filter.+ "query_executions": MetabaseEndpointConfig(+ name="query_executions",+ path="/api/ee/logs/query_execution/{month}",+ partition_key="started_at",+ month_windowed=True,+ incremental_fields=[+ {+ "label": "started_at",+ "type": IncrementalFieldType.DateTime,+ "field": "started_at",+ "field_type": IncrementalFieldType.DateTime,+ }+ ],+ ),}ENDPOINTS = tuple(METABASE_ENDPOINTS.keys())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/metabase/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/metabase/source.pyindex bae44502e482..a74c16e08999 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/metabase/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/metabase/source.py@@ -9,11 +9,12 @@ from products.warehouse_sources.backend.facade.source_config import (SourceFieldSelectConfig,SourceFieldSelectConfigOption,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSourcefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (CanonicalDescriptions,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.metabase import (@@ -22,18 +23,23 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_from products.warehouse_sources.backend.temporal.data_imports.sources.metabase.metabase import (API_KEY_AUTH,HOST_NOT_ALLOWED_ERROR,+ QUERY_LOGS_UNAVAILABLE_ERROR,SESSION_AUTH,SESSION_RESPONSE_NOT_JSON_ERROR,MetabaseAuth,+ MetabaseResumeConfig,metabase_source,validate_credentials as validate_metabase_credentials,)-from products.warehouse_sources.backend.temporal.data_imports.sources.metabase.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.metabase.settings import (+ ENDPOINTS,+ METABASE_ENDPOINTS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class MetabaseSource(SimpleSource[MetabaseSourceConfig]):+class MetabaseSource(ResumableSource[MetabaseSourceConfig, MetabaseResumeConfig]):api_docs_url = "https://www.metabase.com/docs/latest/api"@property@@ -127,6 +133,7 @@ The API key (or user) needs read access to the data you want to sync.""","401 Client Error": "Your Metabase credentials are invalid or expired. Update them and reconnect.","403 Client Error": "Your Metabase credentials lack the permissions needed to sync this data. Grant read access and reconnect.",HOST_NOT_ALLOWED_ERROR: "The Metabase host is not allowed. Please use your instance's public URL.",+ QUERY_LOGS_UNAVAILABLE_ERROR: "The query_executions table needs Metabase Pro or Enterprise. Deselect it, or upgrade your Metabase plan and reconnect.",SESSION_RESPONSE_NOT_JSON_ERROR: "Metabase didn't return a valid session response. Check that the Instance URL points to your Metabase instance, then reconnect.",# `_is_host_safe` raises this when the Instance URL doesn't resolve via DNS — a# hostname the customer typed wrong or one that's no longer publicly reachable.@@ -156,14 +163,14 @@ The API key (or user) needs read access to the data you want to sync.""",force_refresh: bool = False,api_version: str | None = None,) -> list[SourceSchema]:- # Metabase exposes no server-side timestamp filter or pagination cursor, so every endpoint- # is full refresh only.+ # Only the query log has a server-side time filter (its month window); every other+ # endpoint is full refresh only.schemas = [SourceSchema(name=endpoint,- supports_incremental=False,+ supports_incremental=bool(METABASE_ENDPOINTS[endpoint].incremental_fields),supports_append=False,- incremental_fields=[],+ incremental_fields=METABASE_ENDPOINTS[endpoint].incremental_fields,)for endpoint in ENDPOINTS]@@ -181,14 +188,25 @@ The API key (or user) needs read access to the data you want to sync.""",) -> tuple[bool, str | None]:return validate_metabase_credentials(config.host, self._build_auth(config), team_id, schema_name)- def source_for_pipeline(self, config: MetabaseSourceConfig, inputs: SourceInputs) -> SourceResponse:+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[MetabaseResumeConfig]:+ return ResumableSourceManager[MetabaseResumeConfig](inputs, MetabaseResumeConfig)++ def source_for_pipeline(+ self,+ config: MetabaseSourceConfig,+ resumable_source_manager: ResumableSourceManager[MetabaseResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:return metabase_source(host=config.host,auth=self._build_auth(config),endpoint=inputs.schema_name,logger=inputs.logger,team_id=inputs.team_id,+ resumable_source_manager=resumable_source_manager,job_id=inputs.job_id,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value,)def get_canonical_descriptions(self) -> CanonicalDescriptions:diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/metabase/tests/test_metabase.py b/products/warehouse_sources/backend/temporal/data_imports/sources/metabase/tests/test_metabase.pyindex 9d34f4b0df25..761ede89bd73 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/metabase/tests/test_metabase.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/metabase/tests/test_metabase.py@@ -1,7 +1,9 @@import json+from datetime import UTC, datetimefrom typing import Any, Optionalimport pytest+import time_machinefrom unittest import mockimport requests@@ -15,10 +17,13 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.metabase.mMetabaseAuth,MetabaseAuthError,MetabaseHostNotAllowedError,+ MetabaseQueryLogsUnavailableError,+ MetabaseResumeConfig,_resolve_auth_headers,get_rows,metabase_source,normalize_host,+ query_execution_months,validate_credentials,)@@ -53,6 +58,13 @@ def _real_response(*, status_code: int = 200, json_data: Any = None) -> Responsereturn resp+def _manager(next_month: Optional[str] = None) -> mock.MagicMock:+ manager = mock.MagicMock()+ manager.can_resume.return_value = next_month is not None+ manager.load_state.return_value = MetabaseResumeConfig(next_month=next_month) if next_month else None+ return manager++def _api_key_auth() -> MetabaseAuth:return MetabaseAuth(method=API_KEY_AUTH, api_key="mb_secret")@@ -81,6 +93,23 @@ class TestNormalizeHost:assert normalize_host(raw) == expected+class TestQueryExecutionMonths:+ @pytest.mark.parametrize(+ "now, last_value, first, last, count",+ [+ # Full refresh walks back the default retention window.+ (datetime(2026, 3, 10, tzinfo=UTC), None, "2024-03", "2026-03", 25),+ # Incremental starts one month before the watermark, across a year boundary.+ (datetime(2026, 2, 10, tzinfo=UTC), "2026-01-05T08:00:00Z", "2025-12", "2026-02", 3),+ (datetime(2026, 2, 10, tzinfo=UTC), datetime(2026, 2, 1, 0, 30), "2026-01", "2026-02", 2),+ ],+ )+ def test_month_windows(self, now, last_value, first, last, count):+ months = query_execution_months(now, last_value)+ assert (months[0], months[-1], len(months)) == (first, last, count)+ assert months == sorted(set(months))++class TestResolveAuthHeaders:def _patch_mint(self, post_response=None):session = mock.MagicMock()@@ -246,6 +275,7 @@ class TestMetabaseSourceResponse:endpoint=endpoint,logger=mock.MagicMock(),team_id=1,+ resumable_source_manager=_manager(),)assert response.name == endpointassert response.primary_keys == primary_keys@@ -293,6 +323,7 @@ class TestGetRows:endpoint=endpoint,logger=mock.MagicMock(),team_id=1,+ resumable_source_manager=_manager(),):rows.extend(table)return rows, session, requests_seen@@ -327,3 +358,78 @@ class TestGetRows:assert auth.name == "X-Metabase-Session"assert auth.api_key == "tok-123"assert [r["id"] for r in rows] == [1]++ def test_memberships_flatten_user_map(self):+ body = {+ "1": [{"membership_id": 10, "group_id": 1, "user_id": 1, "is_group_manager": False}],+ "2": [+ {"membership_id": 11, "group_id": 1, "user_id": 2, "is_group_manager": False},+ {"membership_id": 12, "group_id": 3, "user_id": 2, "is_group_manager": True},+ ],+ }+ rows, _, requests_seen = self._run([_real_response(json_data=body)], endpoint="permission_group_memberships")+ assert requests_seen[0].url.endswith("/api/permissions/membership")+ assert [(r["membership_id"], r["user_id"]) for r in rows] == [(10, 1), (11, 2), (12, 2)]++ def test_fields_fan_out_over_databases(self):+ rows, _, requests_seen = self._run(+ [+ _real_response(json_data={"data": [{"id": 1}, {"id": 2}], "total": 2}),+ _real_response(json_data=[{"id": 100, "table_id": 5, "name": "email"}]),+ _real_response(json_data=[{"id": 200, "table_id": 9, "name": "amount"}]),+ ],+ endpoint="fields",+ )+ assert [r.url.split("x.metabaseapp.com")[1] for r in requests_seen] == [+ "/api/database",+ "/api/database/1/fields",+ "/api/database/2/fields",+ ]+ assert [(r["id"], r["database_id"]) for r in rows] == [(100, 1), (200, 2)]++ @time_machine.travel(datetime(2026, 4, 10, tzinfo=UTC), tick=False)+ @pytest.mark.parametrize(+ "last_value, resume_month, expected_ids, expected_requests",+ [+ (None, None, [1, 2, 3, 4], 25),+ # Rows before the watermark drop out; the month before the watermark is still fetched.+ ("2026-03-20T00:00:00Z", None, [3, 4], 3),+ (None, "2026-02", [1, 2, 3, 4], 3),+ ],+ )+ def test_query_executions_walk_months_ascending(self, last_value, resume_month, expected_ids, expected_requests):+ february = [{"id": 1, "started_at": "2026-02-15T10:00:00+00:00"}]+ # Metabase returns each month newest first.+ march = [{"id": 3, "started_at": "2026-03-25T10:00:00Z"}, {"id": 2, "started_at": "2026-03-02T10:00:00Z"}]+ april = [{"id": 4, "started_at": "2026-04-02T10:00:00Z"}]+ responses = [_real_response(json_data=[]) for _ in range(expected_requests - 3)] + [+ _real_response(json_data=month) for month in (february, march, april)+ ]++ session = mock.MagicMock()+ requests_seen = self._wire(session, responses)+ manager = _manager(resume_month)+ with mock.patch(METABASE_SESSION_PATCH, return_value=session):+ rows = [+ row+ for page in get_rows(+ host="https://x.metabaseapp.com",+ auth=_api_key_auth(),+ endpoint="query_executions",+ logger=mock.MagicMock(),+ team_id=1,+ resumable_source_manager=manager,+ db_incremental_field_last_value=last_value,+ )+ for row in page+ ]++ assert [r["id"] for r in rows] == expected_ids+ assert len(requests_seen) == expected_requests+ assert requests_seen[-1].url.endswith("/api/ee/logs/query_execution/2026-04")+ assert [c.args[0].next_month for c in manager.save_state.call_args_list][-2:] == ["2026-03", "2026-04"]++ @pytest.mark.parametrize("status_code", [402, 404])+ def test_query_executions_unavailable_is_typed(self, status_code):+ with pytest.raises(MetabaseQueryLogsUnavailableError):+ self._run([_real_response(status_code=status_code)], endpoint="query_executions")diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/metabase/tests/test_metabase_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/metabase/tests/test_metabase_source.pyindex 893d5984d4ae..31bf7ade965e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/metabase/tests/test_metabase_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/metabase/tests/test_metabase_source.py@@ -57,7 +57,7 @@ class TestMetabaseSource:inputs.schema_name = "cards"inputs.team_id = 42- self.source.source_for_pipeline(self.config, inputs)+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)mock_metabase_source.assert_called_once()kwargs = mock_metabase_source.call_args.kwargs