: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(warehouse-sources): add lightdash explores and scheduler tables (#114524)
Tom Owersc4d4451e40e1
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 7853edf7e589..a279d144df98 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@@ -5134,14 +5134,14 @@ Note: Most Lever gaps are sub-resources nested under /opportunities/{id}, which## Lightdash — gaps-Today (6): `charts`, `dashboards`, `metrics_catalog`, `org_users`, `projects`, `spaces`+Today (9): `charts`, `dashboards`, `explores`, `metrics_catalog`, `org_users`, `projects`, `scheduler_runs`, `schedulers`, `spaces`Diffed against: <https://raw.githubusercontent.com/lightdash/lightdash/main/packages/backend/src/generated/swagger.json>-- [ ] `projects/{projectUuid}/explores` — lookup of every dbt model/table and its fields - resolves the field IDs embedded in the charts we already sync (high)-- [ ] `analytics/user-activity/{projectUuid}` — Lightdash's headline adoption metric: per-user views, queries and chart creation (high)-- [ ] `schedulers/{projectUuid}/list` — scheduled delivery definitions; the parent for run history below (high)-- [ ] `schedulers/{projectUuid}/runs (and /logs)` — per-run state and failure history for scheduled deliveries - the reliability table (high)+- [x] `projects/{projectUuid}/explores` — lookup of every dbt model/table and its fields - resolves the field IDs embedded in the charts we already sync (high). Added as `explores` (fan-out over `projects`). The list returns explore summaries only; per-field definitions need one `explores/{exploreId}` call per explore and were not added.+- [ ] `analytics/user-activity/{projectUuid}` — Lightdash's headline adoption metric: per-user views, queries and chart creation (high). Skipped: it returns one object of project-level aggregates and top-N user lists, not one row per user, so it is not table material.+- [x] `schedulers/{projectUuid}/list` — scheduled delivery definitions; the parent for run history below (high). Added as `schedulers` (fan-out over `projects`).+- [x] `schedulers/{projectUuid}/runs (and /logs)` — per-run state and failure history for scheduled deliveries - the reliability table (high). Added as `scheduler_runs` (fan-out over `projects`, incremental merge on `runId` because the API returns only the last 7 days of runs). `/logs` skipped: its rows are per-job status transitions with no unique key, and each run row already carries its status and child job counts.- [ ] `projects/{projectUuid}/dataCatalog/{table}/analytics (and /{field})` — which charts and dashboards use each table/field - drives model deprecation decisions (medium)- [ ] `org/groups (+ groups/{groupUuid}/members)` — group membership table resolving access for the org users we already sync (medium)- [ ] `v2/content` — unified listing of charts, dashboards and sql charts including spaces and last-updated, useful as a single content inventory (medium)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/lightdash/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/lightdash/canonical_descriptions.pyindex 596721277ddd..605da4270da1 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/lightdash/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/lightdash/canonical_descriptions.py@@ -109,4 +109,66 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"userUpdatedAt": "Timestamp the user account was last updated.",},},+ "explores": {+ "description": "A Lightdash explore: a queryable table compiled from a dbt model, with its warehouse location and any compilation errors. Field definitions are not included.",+ "docs_url": "https://docs.lightdash.com/api-reference/v1/introduction",+ "columns": {+ "name": "Explore name, matching the dbt model name. Unique within a project.",+ "label": "Human-readable label for the explore.",+ "projectUuid": "Unique identifier of the project the explore belongs to.",+ "type": "Explore type, e.g. default, virtual, semantic_layer, or pre_aggregate.",+ "tags": "dbt tags applied to the underlying model.",+ "groups": "Nested sidebar group keys the explore is listed under.",+ "databaseName": "Warehouse database (or project/catalog) the model's table lives in.",+ "schemaName": "Warehouse schema (or dataset) the model's table lives in.",+ "description": "Description of the model from the dbt project's metadata.",+ "errors": "Compilation errors that make the explore unusable, if any.",+ "warnings": "Non-fatal compilation or validation warnings. The explore is still usable.",+ "warehouseConnectionUuid": "Unique identifier of the warehouse connection the explore queries, if bound to one.",+ },+ },+ "schedulers": {+ "description": "A Lightdash scheduled delivery: a chart or dashboard sent on a cron schedule to email, Slack, Microsoft Teams, Google Chat, or a Google Sheet.",+ "docs_url": "https://docs.lightdash.com/api-reference/v1/introduction",+ "columns": {+ "schedulerUuid": "Unique identifier for the scheduled delivery.",+ "name": "Display name of the scheduled delivery.",+ "message": "Optional message included with each delivery.",+ "format": "Delivery format, e.g. csv, xlsx, image, or gsheets.",+ "cron": "Cron expression that sets when the delivery runs.",+ "timezone": "Timezone the cron expression is evaluated in, if overridden on the delivery.",+ "enabled": "Whether the scheduled delivery is active.",+ "createdAt": "Timestamp the scheduled delivery was created.",+ "updatedAt": "Timestamp the scheduled delivery was last updated.",+ "createdBy": "Unique identifier of the user who created the scheduled delivery.",+ "createdByName": "Display name of the user who created the scheduled delivery.",+ "savedChartUuid": "Unique identifier of the delivered chart, for a chart delivery.",+ "dashboardUuid": "Unique identifier of the delivered dashboard, for a dashboard delivery.",+ "projectUuid": "Unique identifier of the project the scheduled delivery belongs to.",+ "targets": "Destinations the delivery is sent to (email addresses, Slack channels, and so on).",+ "latestRun": "The most recent run of the scheduled delivery, if requested.",+ },+ },+ "scheduler_runs": {+ "description": "One run of a Lightdash scheduled delivery, with its overall status and counts of its child delivery jobs. The API returns runs scheduled in the last 7 days.",+ "docs_url": "https://docs.lightdash.com/api-reference/v1/introduction",+ "columns": {+ "runId": "Unique identifier for the run (the parent job id).",+ "schedulerUuid": "Unique identifier of the scheduled delivery that ran.",+ "schedulerName": "Display name of the scheduled delivery that ran.",+ "scheduledTime": "Timestamp the run was scheduled for.",+ "createdAt": "Timestamp of the run's most recent status update.",+ "status": "Status of the run's parent job: scheduled, started, completed, or error.",+ "runStatus": "Overall run status across its child jobs: scheduled, running, completed, partial_failure, or failed.",+ "logCounts": "Counts of the run's child jobs by latest status (scheduled, started, completed, error, total).",+ "details": "Additional run details, such as the error message for a failed run.",+ "format": "Delivery format, e.g. csv, xlsx, image, or gsheets.",+ "resourceType": "Kind of content delivered, e.g. chart or dashboard.",+ "resourceUuid": "Unique identifier of the delivered chart or dashboard.",+ "resourceName": "Display name of the delivered chart or dashboard.",+ "createdByUserUuid": "Unique identifier of the user who created the scheduled delivery.",+ "createdByUserName": "Display name of the user who created the scheduled delivery.",+ "projectUuid": "Unique identifier of the project the run belongs to.",+ },+ },}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/lightdash/lightdash.py b/products/warehouse_sources/backend/temporal/data_imports/sources/lightdash/lightdash.pyindex 555d9d38837e..53ed74579f56 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/lightdash/lightdash.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/lightdash/lightdash.py@@ -144,13 +144,20 @@ def _paginator(config: LightdashEndpointConfig) -> BasePaginator:return PageNumberPaginator(base_page=1, page_param="page", total_path=_PAGINATED_TOTAL_PATH)+def _params(config: LightdashEndpointConfig) -> dict[str, Any]:+ params: dict[str, Any] = dict(config.params)+ if config.paginated:+ params["pageSize"] = config.page_size+ return params++def get_resource(config: LightdashEndpointConfig) -> EndpointResource:if config.fanout:raise ValueError(f"Fan-out endpoint '{config.name}' must use the fan-out path")endpoint_config: Endpoint = {"path": config.path,- "params": {"pageSize": config.page_size} if config.paginated else {},+ "params": _params(config),"data_selector": config.data_selector,"paginator": _paginator(config),}@@ -168,7 +175,8 @@ def _make_source_response(config: LightdashEndpointConfig, items_fn: Callable[[]name=config.name,items=items_fn,primary_keys=config.primary_key if isinstance(config.primary_key, list) else [config.primary_key],- # Full refresh only — Lightdash exposes no server-side updated-since filter on any endpoint.+ # Lightdash exposes no server-side updated-since filter on any endpoint; rows arrive in the+ # endpoint's natural order or the ascending sort set in its params.sort_mode="asc",partition_count=1,partition_size=1,@@ -209,8 +217,8 @@ def lightdash_source(job_id=job_id,db_incremental_field_last_value=None,# `GET /api/v1/org/projects` (the parent) takes no page-size param at all — it- # always returns the full collection — so no size param is added to it. Only- # metrics_catalog's child request needs one, added below via child_params_extra.+ # always returns the full collection — so no size param is added to it. Paginated+ # children get theirs below via child_params_extra.page_size_param=None,parent_endpoint_extra={"paginator": SinglePagePaginator(),@@ -220,7 +228,7 @@ def lightdash_source("paginator": _paginator(config),"data_selector": config.data_selector,},- child_params_extra={"pageSize": config.page_size} if config.paginated else None,+ child_params_extra=_params(config) or None,),)return _make_source_response(config, lambda: dependent_resource)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/lightdash/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/lightdash/settings.pyindex cab6959be3db..f80c51a898bc 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/lightdash/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/lightdash/settings.py@@ -1,8 +1,12 @@-from dataclasses import dataclass, field+from dataclasses import field+from typing import Any++from posthog.dataclasses import frozenfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (DependentEndpointConfig,)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import incremental_fieldfrom products.warehouse_sources.backend.types import IncrementalField# Lightdash documents no default/max page size for its paginated endpoints (org/users,@@ -10,7 +14,7 @@ from products.warehouse_sources.backend.types import IncrementalFieldPAGE_SIZE = 100-@dataclass+@frozenclass LightdashEndpointConfig:name: strpath: str@@ -20,7 +24,7 @@ class LightdashEndpointConfig:data_selector: strprimary_key: str | list[str]# Lightdash has no server-side updated-since/created-since filter on any list endpoint, so- # every stream is full-refresh only. Left empty; kept for the fan-out helper's endpoint protocol.+ # streams are full-refresh only unless the server bounds the response itself (scheduler_runs).incremental_fields: list[IncrementalField] = field(default_factory=list)default_incremental_field: str | None = None# Stable creation-time field used for datetime partitioning. Left None when the resource has no@@ -30,6 +34,7 @@ class LightdashEndpointConfig:paginated: bool = Falsepage_size: int = PAGE_SIZEfanout: DependentEndpointConfig | None = None+ params: dict[str, Any] = field(default_factory=dict)LIGHTDASH_ENDPOINTS: dict[str, LightdashEndpointConfig] = {@@ -115,6 +120,67 @@ LIGHTDASH_ENDPOINTS: dict[str, LightdashEndpointConfig] = {partition_key="userCreatedAt",paginated=True,),+ "explores": LightdashEndpointConfig(+ name="explores",+ path="/api/v1/projects/{projectUuid}/explores",+ data_selector="results",+ # Explore names are dbt model names, unique only within a project.+ primary_key=["projectUuid", "name"],+ fanout=DependentEndpointConfig(+ parent_name="projects",+ resolve_param="projectUuid",+ resolve_field="projectUuid",+ include_from_parent=["projectUuid"],+ # The framework injects the parent value under `_projects_projectUuid`; renaming it+ # back to `projectUuid` guarantees the column even if a future Lightdash response+ # ever omitted its own copy of the field.+ parent_field_renames={"projectUuid": "projectUuid"},+ ),+ ),+ "schedulers": LightdashEndpointConfig(+ name="schedulers",+ path="/api/v1/schedulers/{projectUuid}/list",+ data_selector="results.data",+ primary_key="schedulerUuid",+ partition_key="createdAt",+ paginated=True,+ params={"sortBy": "createdAt", "sortDirection": "asc"},+ fanout=DependentEndpointConfig(+ parent_name="projects",+ resolve_param="projectUuid",+ resolve_field="projectUuid",+ include_from_parent=["projectUuid"],+ # The framework injects the parent value under `_projects_projectUuid`; renaming it+ # back to `projectUuid` guarantees the column even if a future Lightdash response+ # ever omitted its own copy of the field.+ parent_field_renames={"projectUuid": "projectUuid"},+ ),+ ),+ "scheduler_runs": LightdashEndpointConfig(+ name="scheduler_runs",+ path="/api/v1/schedulers/{projectUuid}/runs",+ data_selector="results.data",+ # `runId` is the run's parent job id, a globally unique uuid.+ primary_key="runId",+ # Lightdash only returns runs scheduled in the last 7 days, so a full refresh drops older+ # runs. Incremental merge on `runId` re-reads the bounded window each sync and keeps the+ # history; there is no request filter to apply the watermark to.+ incremental_fields=[incremental_field("scheduledTime")],+ default_incremental_field="scheduledTime",+ partition_key="scheduledTime",+ paginated=True,+ params={"sortBy": "scheduledTime", "sortDirection": "asc"},+ fanout=DependentEndpointConfig(+ parent_name="projects",+ resolve_param="projectUuid",+ resolve_field="projectUuid",+ include_from_parent=["projectUuid"],+ # The framework injects the parent value under `_projects_projectUuid`; renaming it+ # back to `projectUuid` guarantees the column even if a future Lightdash response+ # ever omitted its own copy of the field.+ parent_field_renames={"projectUuid": "projectUuid"},+ ),+ ),}ENDPOINTS = tuple(LIGHTDASH_ENDPOINTS)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/lightdash/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/lightdash/source.pyindex 02080cc11125..49ae150d3d84 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/lightdash/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/lightdash/source.py@@ -72,7 +72,8 @@ class LightdashSource(SimpleSource[LightdashSourceConfig]):force_refresh: bool = False,api_version: str | None = None,) -> list[SourceSchema]:- return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)+ # Appending would add a copy of every run in the API's rolling 7-day window on each sync.+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names, merge_only=["scheduler_runs"])def validate_credentials(self,diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/lightdash/tests/test_lightdash.py b/products/warehouse_sources/backend/temporal/data_imports/sources/lightdash/tests/test_lightdash.pyindex 46a4535f4325..6435dedb222a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/lightdash/tests/test_lightdash.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/lightdash/tests/test_lightdash.py@@ -140,6 +140,9 @@ class TestLightdashSourceResponse:("charts", ["uuid"], None),("metrics_catalog", ["catalogSearchUuid"], None),("org_users", ["userUuid"], "userCreatedAt"),+ ("explores", ["projectUuid", "name"], None),+ ("schedulers", ["schedulerUuid"], "createdAt"),+ ("scheduler_runs", ["runId"], "scheduledTime"),])@mock.patch(@@ -177,6 +180,41 @@ class TestLightdashSourceResponse:class TestLightdashSourceTransport:+ @parameterized.expand(+ [+ ("explores", "/api/v1/projects/{projectUuid}/explores", {}),+ (+ "schedulers",+ "/api/v1/schedulers/{projectUuid}/list",+ {"sortBy": "createdAt", "sortDirection": "asc", "pageSize": 100},+ ),+ (+ "scheduler_runs",+ "/api/v1/schedulers/{projectUuid}/runs",+ {"sortBy": "scheduledTime", "sortDirection": "asc", "pageSize": 100},+ ),+ ]+ )+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout.rest_api_resources"+ )+ def test_child_request_params(+ self, endpoint: str, path: str, params: dict[str, Any], mock_rest_api_resources: mock.MagicMock+ ) -> None:+ mock_rest_api_resources.return_value = [+ _FakeDltResource("projects", []),+ _FakeDltResource(endpoint, []),+ ]++ lightdash_source(+ instance_url="https://x.lightdash.cloud", api_token="tok", endpoint=endpoint, team_id=1, job_id="job-1"+ )++ resources = mock_rest_api_resources.call_args.args[0]["resources"]+ child = next(r for r in resources if isinstance(r, dict) and r["name"] == endpoint)+ assert child["endpoint"]["path"] == path+ assert {k: v for k, v in child["endpoint"]["params"].items() if k != "projectUuid"} == params+def test_blocks_unsafe_host_at_runtime(self) -> None:with mock.patch.object(lightdash_module, "_is_host_safe", return_value=(False, "internal address")):with pytest.raises(LightdashHostNotAllowedError):