Skip to content

: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.

feat(warehouse-sources): add datahub run, assertion and profile tables (#104408)

Tom Owers131c895ab634
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.md
index a1e309ba68d5..4736c557078c 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
@@ -2291,24 +2291,24 @@ Note: DataForSEO docs are a WordPress site with no OpenAPI, llms.txt or sitemap
## Datahub — gaps
-Today (14): `charts`, `containers`, `dashboards`, `data_flows`, `data_jobs`, `data_platforms`, `data_products`, `datasets`, `domains`, `glossary_nodes`, `glossary_terms`, `groups`, `tags`, `users`
+Today (22): `assertion_run_events`, `assertions`, `charts`, `containers`, `dashboards`, `data_flows`, `data_jobs`, `data_platforms`, `data_process_instance_run_events`, `data_process_instances`, `data_products`, `dataset_operations`, `dataset_profiles`, `dataset_usage_statistics`, `datasets`, `domains`, `glossary_nodes`, `glossary_terms`, `groups`, `schema_fields`, `tags`, `users`
Diffed against: <https://docs.datahub.com/docs/generated/metamodel/entities/chart>
-- [ ] `dataProcessInstance` — individual task/pipeline run instances with status and timings — the execution fact table for the data_jobs and data_flows we already sync (high)
-- [ ] `assertion (and its assertionRunEvent results)` — data quality assertions and their pass/fail run history per dataset (high)
-- [ ] `schemaField` — column-level entity — lookup resolving dataset fields for column-level lineage, tags and glossary term assignment (high)
-- [ ] `dataset timeseries aspects: datasetProfile, datasetUsageStatistics, operation` — row counts, null/distinct column stats, query and user usage counts, and last-modified operations for the datasets we already sync (high)
+- [x] `dataProcessInstance` — individual task/pipeline run instances with status and timings — the execution fact table for the data_jobs and data_flows we already sync (high)
+- [x] `assertion (and its assertionRunEvent results)` — data quality assertions and their pass/fail run history per dataset (high)
+- [x] `schemaField` — column-level entity — lookup resolving dataset fields for column-level lineage, tags and glossary term assignment (high)
+- [x] `dataset timeseries aspects: datasetProfile, datasetUsageStatistics, operation` — row counts, null/distinct column stats, query and user usage counts, and last-modified operations for the datasets we already sync (high)
- [ ] `incident` — data incidents raised against datasets and jobs, with state transitions (medium)
- [ ] `query` — SQL queries associated with datasets, the source of column-level lineage and usage (medium)
- [ ] `mlModel, mlModelGroup, mlFeature, mlFeatureTable, mlPrimaryKey, mlModelDeployment` — ML metadata entities, entirely absent while their analytics counterparts are synced (medium)
- [ ] `dataPlatformInstance` — lookup resolving the platform-instance URNs carried on datasets, charts and dashboards (medium)
- [ ] `structuredProperty and businessAttribute` — lookup resolving custom structured property definitions applied across entities (medium)
- [ ] `dataContract` — contract definitions and their assertion bindings per dataset (medium)
-- [ ] `application, service, api, semanticModel, metric` — newer catalog entity types not covered by the current fourteen (low)
+- [ ] `application, service, api, semanticModel, metric` — newer catalog entity types not covered by the current set (low)
- [ ] `notebook` — notebook assets and their dataset references (low)
-Note: The metamodel index lists 71 entity types; the source syncs 14. I confirmed the dataset timeseries aspects (datasetProfile, datasetUsageStatistics, operation) exist on the dataset entity page. Excluded as config/plumbing: dataHubPolicy, dataHubRole, dataHubSecret, dataHubAccessToken, dataHubIngestionSource, inviteToken, globalSettings, dataHubView, form, post, dataHubUpgrade.
+Note: The metamodel index lists 71 entity types; the source syncs 22. The run-event, profile, usage and operation tables read the OpenAPI v2 timeseries scroll (`/openapi/v2/timeseries/{entity}/{aspect}`) — the v3 entity scroll returns versioned aspects only. `schemaField` returns materialized field entities only; a dataset's full column list stays in its `schemaMetadata` aspect on `datasets`. I confirmed the dataset timeseries aspects (datasetProfile, datasetUsageStatistics, operation) exist on the dataset entity page. Excluded as config/plumbing: dataHubPolicy, dataHubRole, dataHubSecret, dataHubAccessToken, dataHubIngestionSource, inviteToken, globalSettings, dataHubView, form, post, dataHubUpgrade.
## Dbt — gaps
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/datahub/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/datahub/canonical_descriptions.py
index eb0071631879..e9d8c970ec5d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/datahub/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/datahub/canonical_descriptions.py
@@ -154,4 +154,112 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"ownership": "Owners of the group and their ownership types.",
},
},
+ "data_process_instances": {
+ "description": "A single run of a data job or data flow, such as one Airflow task instance or DAG run, with the assets it read and wrote.",
+ "docs_url": "https://docs.datahub.com/docs/generated/metamodel/entities/dataprocessinstance",
+ "columns": {
+ "urn": "Unique resource name identifying the process instance.",
+ "dataProcessInstanceProperties": "Name, process type, external URL, creation audit stamp, and custom properties of the run.",
+ "dataProcessInstanceInput": "Assets the run consumed, as lineage edges.",
+ "dataProcessInstanceOutput": "Assets the run produced, as lineage edges.",
+ "dataProcessInstanceRelationships": "The data job or data flow this is a run of, the parent run it belongs to, and upstream runs.",
+ "dataPlatformInstance": "The platform instance the run executed on.",
+ "container": "The container the run belongs to.",
+ "subTypes": "More specific type of the run.",
+ "mlTrainingRunProperties": "Training run details when the process instance is an ML training run.",
+ "testResults": "Results of DataHub tests evaluated against the run.",
+ "status": "Soft-deletion status of the entity.",
+ },
+ },
+ "data_process_instance_run_events": {
+ "description": "Execution history of data job and data flow runs: one row per recorded state change, with status, attempt number and result.",
+ "docs_url": "https://docs.datahub.com/docs/generated/metamodel/entities/dataprocessinstance",
+ "columns": {
+ "id": "Surrogate key for the event, derived from the identifying fields DataHub itself keys a timeseries record by.",
+ "urn": "Unique resource name of the process instance the event belongs to.",
+ "timestampMillis": "Event time as a Unix timestamp in milliseconds.",
+ "messageId": "Optional user-defined identifier supplied when the event was ingested.",
+ "event": "The run event: status (STARTED, COMPLETE, SKIPPED), attempt number, result type and native result type, external URL, and duration.",
+ },
+ },
+ "assertions": {
+ "description": "A data quality assertion defined against a dataset, data job or column, such as a freshness, volume, column value or custom SQL check.",
+ "docs_url": "https://docs.datahub.com/docs/generated/metamodel/entities/assertion",
+ "columns": {
+ "urn": "Unique resource name identifying the assertion.",
+ "assertionInfo": "Definition of the assertion: its type, the asset it is asserted on, the per-type parameters (freshness, volume, SQL, field, schema), its source and description.",
+ "assertionRunSummary": "Latest status of the assertion plus the times it last passed, failed, errored and initialized.",
+ "assertionActions": "Actions DataHub runs when the assertion passes or fails.",
+ "dataPlatformInstance": "The platform instance the assertion runs against.",
+ "globalTags": "Tags applied to the assertion.",
+ "ownership": "Owners of the assertion and their ownership types.",
+ "status": "Soft-deletion status of the entity.",
+ },
+ },
+ "assertion_run_events": {
+ "description": "Pass and fail history of data quality assertions: one row per assertion evaluation, with its status and result.",
+ "docs_url": "https://docs.datahub.com/docs/generated/metamodel/entities/assertion",
+ "columns": {
+ "id": "Surrogate key for the event, derived from the identifying fields DataHub itself keys a timeseries record by.",
+ "urn": "Unique resource name of the assertion the event belongs to.",
+ "timestampMillis": "Evaluation time as a Unix timestamp in milliseconds.",
+ "messageId": "Optional user-defined identifier supplied when the event was ingested.",
+ "event": "The evaluation: run id, the asserted asset, run status, result (SUCCESS, FAILURE, ERROR) with actual and expected values, the batch evaluated, and runtime parameters.",
+ },
+ },
+ "schema_fields": {
+ "description": "A dataset column that carries its own metadata in DataHub. Only fields materialized as entities appear here; the full column list of a dataset is in its schemaMetadata aspect on the datasets table.",
+ "docs_url": "https://docs.datahub.com/docs/generated/metamodel/entities/schemafield",
+ "columns": {
+ "urn": "Unique resource name identifying the field, built from the parent dataset urn and the field path.",
+ "schemafieldInfo": "Name of the field and the parent asset it belongs to.",
+ "schemaFieldAliases": "Other field-path spellings that resolve to this field.",
+ "documentation": "Documentation written against the field, with its attribution.",
+ "globalTags": "Tags applied to the field.",
+ "glossaryTerms": "Business glossary terms attached to the field.",
+ "businessAttributes": "Business attributes associated with the field.",
+ "structuredProperties": "Values of custom structured properties set on the field.",
+ "domains": "Domains the field belongs to.",
+ "ownership": "Owners of the field and their ownership types.",
+ "deprecation": "Deprecation state of the field, with note and decommission time.",
+ "subTypes": "More specific type of the field.",
+ "logicalParent": "The logical parent asset of the field.",
+ "incidentsSummary": "Open and resolved incidents raised against the field.",
+ "testResults": "Results of DataHub tests evaluated against the field.",
+ "status": "Soft-deletion status of the entity.",
+ },
+ },
+ "dataset_profiles": {
+ "description": "Profiling snapshots of datasets: row count, column count, storage size and per-column statistics at a point in time.",
+ "docs_url": "https://docs.datahub.com/docs/generated/metamodel/entities/dataset",
+ "columns": {
+ "id": "Surrogate key for the snapshot, derived from the identifying fields DataHub itself keys a timeseries record by.",
+ "urn": "Unique resource name of the profiled dataset.",
+ "timestampMillis": "Profile time as a Unix timestamp in milliseconds.",
+ "messageId": "Optional user-defined identifier supplied when the profile was ingested.",
+ "event": "The profile: rowCount, columnCount, sizeInBytes, and fieldProfiles holding per-column null, distinct, min, max, mean, median, quantile and sample-value statistics.",
+ },
+ },
+ "dataset_usage_statistics": {
+ "description": "Usage of datasets per time bucket: how many queries ran, how many distinct users read them, and which users, queries and columns were involved.",
+ "docs_url": "https://docs.datahub.com/docs/generated/metamodel/entities/dataset",
+ "columns": {
+ "id": "Surrogate key for the bucket, derived from the identifying fields DataHub itself keys a timeseries record by.",
+ "urn": "Unique resource name of the dataset the usage belongs to.",
+ "timestampMillis": "Start of the usage bucket as a Unix timestamp in milliseconds.",
+ "messageId": "Optional user-defined identifier supplied when the bucket was ingested.",
+ "event": "The bucket: uniqueUserCount, totalSqlQueries, topSqlQueries, per-user counts, per-column counts, and the bucket granularity.",
+ },
+ },
+ "dataset_operations": {
+ "description": "Write operations recorded against datasets: inserts, updates, deletes and custom operations, with when they happened and how many rows they touched.",
+ "docs_url": "https://docs.datahub.com/docs/generated/metamodel/entities/dataset",
+ "columns": {
+ "id": "Surrogate key for the operation, derived from the identifying fields DataHub itself keys a timeseries record by.",
+ "urn": "Unique resource name of the dataset the operation was performed on.",
+ "timestampMillis": "Time the operation was reported, as a Unix timestamp in milliseconds.",
+ "messageId": "Optional user-defined identifier supplied when the operation was ingested.",
+ "event": "The operation: operationType, customOperationType, the actor who issued it, numAffectedRows, affectedDatasets, source type, the queries used, and lastUpdatedTimestamp (the time the operation actually occurred).",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/datahub/datahub.py b/products/warehouse_sources/backend/temporal/data_imports/sources/datahub/datahub.py
index 96b3e0c61b39..250e83824353 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/datahub/datahub.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/datahub/datahub.py
@@ -1,5 +1,6 @@
import re
import json
+import hashlib
import dataclasses
from collections.abc import Iterator
from typing import Any, Optional
@@ -10,6 +11,7 @@ from structlog.types import FilteringBoundLogger
from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
from posthog.cloud_utils import is_cloud
+from posthog.dataclasses import frozen
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import _is_host_safe
@@ -17,6 +19,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.datahub.settings import (
DATAHUB_ENDPOINTS,
+ TIMESERIES_ROW_ID_COLUMN,
DatahubEndpointConfig,
)
@@ -40,6 +43,13 @@ MAX_PAGES_PER_SWEEP = 100_000
DEFAULT_PROBE_ENTITY = "dataPlatform"
HOST_NOT_ALLOWED_ERROR = "DataHub instance URL is not allowed"
+# The OpenAPI v2 timeseries endpoint only started returning a scroll cursor in DataHub v1.4.0
+# (datahub-project/datahub#15784). An older instance answers every page with results and no cursor,
+# so a sweep would end after the first page and truncate the table without any error. A fixed
+# instance always returns a cursor alongside a full page, which makes a full page with no cursor an
+# exact signature of the old server. This string is matched by `get_non_retryable_errors`.
+MIN_TIMESERIES_SCROLL_VERSION = "v1.4.0"
+TIMESERIES_SCROLL_UNSUPPORTED_ERROR = "returned a full page of timeseries events with no scroll cursor"
class DatahubRetryableError(Exception):
@@ -58,6 +68,10 @@ class DatahubTooManyPagesError(Exception):
pass
+class DatahubTimeseriesScrollUnsupportedError(Exception):
+ pass
+
+
@dataclasses.dataclass
class DatahubResumeConfig:
# Opaque scroll cursor returned by the OpenAPI v3 entity endpoint; passing it back fetches
@@ -134,6 +148,10 @@ def _entity_url(base_url: str, entity_type: str) -> str:
return f"{base_url}/openapi/v3/entity/{entity_type}"
+def _timeseries_url(base_url: str, entity_type: str, aspect_name: str) -> str:
+ return f"{base_url}/openapi/v2/timeseries/{entity_type}/{aspect_name}"
+
+
def _scroll_params(scroll_id: str | None, count: int = PAGE_SIZE) -> dict[str, Any]:
# Sort by urn ascending so page boundaries stay stable while scrolling — entities ingested
# mid-sync can't shuffle already-walked pages.
@@ -148,19 +166,89 @@ def _scroll_params(scroll_id: str | None, count: int = PAGE_SIZE) -> dict[str, A
return params
-def _extract_entities(data: Any, url: str) -> tuple[list[dict[str, Any]], str | None]:
- """Pull the entity rows and next-page cursor out of a scroll response.
+def _timeseries_params(scroll_id: str | None, start_time_millis: int | None, count: int = PAGE_SIZE) -> dict[str, Any]:
+ # The timeseries endpoint takes no sort parameter. It always returns timestampMillis
+ # descending, which is why the response declares sort_mode="desc".
+ params: dict[str, Any] = {"count": count}
+ if scroll_id:
+ params["scrollId"] = scroll_id
+ # Re-sent on every page: the cursor is a stateless search_after token, so the server only
+ # keeps the window bound if we keep passing it, and an incremental sweep would otherwise walk
+ # back through all history after the first page.
+ if start_time_millis is not None:
+ params["startTimeMillis"] = start_time_millis
+ return params
+
+
+@frozen
+class _PageRequest:
+ url: str
+ params: dict[str, Any]
+ # Top-level key the page's rows live under in the response envelope.
+ items_key: str
+
+
+def _page_request(
+ config: DatahubEndpointConfig,
+ base_url: str,
+ scroll_id: str | None = None,
+ start_time_millis: int | None = None,
+ count: int = PAGE_SIZE,
+) -> _PageRequest:
+ if config.timeseries_aspect:
+ return _PageRequest(
+ url=_timeseries_url(base_url, config.entity_type, config.timeseries_aspect),
+ params=_timeseries_params(scroll_id, start_time_millis, count=count),
+ items_key="results",
+ )
+ return _PageRequest(
+ url=_entity_url(base_url, config.entity_type),
+ params=_scroll_params(scroll_id, count=count),
+ items_key="entities",
+ )
+
+
+def _extract_page(data: Any, url: str, items_key: str) -> tuple[list[dict[str, Any]], str | None]:
+ """Pull the rows and next-page cursor out of a scroll response.
- The scroll envelope is ``{"scrollId": "...", "entities": [...]}``; the final page omits
- ``scrollId``. A missing ``entities`` key on a dict payload is treated as an empty result.
+ The scroll envelope is ``{"scrollId": "...", "<items_key>": [...]}``, where the items key is
+ ``entities`` for the entity endpoints and ``results`` for the timeseries ones. The final page
+ omits ``scrollId``. A missing items key on a dict payload is treated as an empty result.
"""
if not isinstance(data, dict):
raise DatahubRetryableError(f"DataHub returned an unexpected payload for {url}: {type(data).__name__}")
- entities = data.get("entities") or []
- if not isinstance(entities, list):
- raise DatahubRetryableError(f"DataHub returned an unexpected 'entities' payload for {url}")
+ rows = data.get(items_key) or []
+ if not isinstance(rows, list):
+ raise DatahubRetryableError(f"DataHub returned an unexpected '{items_key}' payload for {url}")
scroll_id = data.get("scrollId")
- return entities, scroll_id if isinstance(scroll_id, str) and scroll_id else None
+ return rows, scroll_id if isinstance(scroll_id, str) and scroll_id else None
+
+
+def _timeseries_row_id(row: dict[str, Any]) -> str:
+ """Deterministic surrogate key matching DataHub's own uniqueness rule for a timeseries row.
+
+ A timeseries document is keyed by timestamp, event granularity, urn, message id and partition
+ spec: urn plus timestamp alone is not unique, because one dataset can carry both a daily and an
+ hourly bucket, or one row per partition. Hash exactly those identity fields, and never the
+ metric values, so a bucket the instance restates merges onto itself instead of landing twice.
+ """
+ event = row.get("event")
+ event = event if isinstance(event, dict) else {}
+ parts = (
+ row.get("timestampMillis"),
+ event.get("eventGranularity"),
+ row.get("urn"),
+ row.get("messageId"),
+ event.get("partitionSpec"),
+ )
+ # Serialize each part so a nested partitionSpec hashes stably, and use a sentinel for the
+ # absent ones so a missing field can never collide with an empty-string value.
+ joined = "|".join("\x00" if part is None else json.dumps(part, sort_keys=True, default=str) for part in parts)
+ return hashlib.sha256(joined.encode()).hexdigest()
+
+
+def _with_timeseries_row_ids(rows: list[dict[str, Any]]) -> list[dict[str, Any]]:
+ return [{**row, TIMESERIES_ROW_ID_COLUMN: _timeseries_row_id(row)} for row in rows]
def _read_capped_bytes(response: requests.Response, max_bytes: int) -> bytes:
@@ -221,6 +309,7 @@ def get_rows(
team_id: int,
logger: FilteringBoundLogger,
resumable_source_manager: ResumableSourceManager[DatahubResumeConfig],
+ db_incremental_field_last_value: Optional[Any] = None,
) -> Iterator[list[dict[str, Any]]]:
config = DATAHUB_ENDPOINTS[endpoint]
# Re-check at run time (not just at source-create) in case the instance URL was edited or now
@@ -228,8 +317,8 @@ def get_rows(
_check_host(instance_url, team_id)
base_url = normalize_instance_url(instance_url)
- url = _entity_url(base_url, config.entity_type)
session = _get_session(api_token)
+ start_time_millis = int(db_incremental_field_last_value) if db_incremental_field_last_value is not None else None
resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
scroll_id = resume.scroll_id if resume else None
@@ -239,8 +328,10 @@ def get_rows(
pages_fetched = 0
while True:
+ page = _page_request(config, base_url, scroll_id, start_time_millis, count=PAGE_SIZE)
+ url = page.url
try:
- data = _fetch(session, url, _scroll_params(scroll_id), logger)
+ data = _fetch(session, url, page.params, logger)
except requests.HTTPError as exc:
# A saved scroll cursor can go stale between attempts (scroll contexts are
# server-side and expire). If the resumed first request is rejected, restart the
@@ -256,13 +347,22 @@ def get_rows(
resuming = False
pages_fetched += 1
- entities, next_scroll_id = _extract_entities(data, url)
- if entities:
- yield entities
+ rows, next_scroll_id = _extract_page(data, url, page.items_key)
+
+ # Raise before yielding, so a sync against an instance too old to paginate fails instead of
+ # writing a table silently truncated to one page.
+ if config.timeseries_aspect and not next_scroll_id and len(rows) >= PAGE_SIZE:
+ raise DatahubTimeseriesScrollUnsupportedError(
+ f"DataHub {TIMESERIES_SCROLL_UNSUPPORTED_ERROR} for {endpoint}. The timeseries API "
+ f"paginates from DataHub {MIN_TIMESERIES_SCROLL_VERSION} onwards."
+ )
+
+ if rows:
+ yield _with_timeseries_row_ids(rows) if config.timeseries_aspect else rows
# No cursor (or an empty page, guarding against a server that echoes a cursor forever)
# means the sweep is complete.
- if not next_scroll_id or not entities:
+ if not next_scroll_id or not rows:
break
# A hostile instance can echo a fresh non-empty page and cursor indefinitely. Abort past
@@ -287,6 +387,7 @@ def datahub_source(
team_id: int,
logger: FilteringBoundLogger,
resumable_source_manager: ResumableSourceManager[DatahubResumeConfig],
+ db_incremental_field_last_value: Optional[Any] = None,
) -> SourceResponse:
config: DatahubEndpointConfig = DATAHUB_ENDPOINTS[endpoint]
@@ -299,8 +400,11 @@ def datahub_source(
team_id=team_id,
logger=logger,
resumable_source_manager=resumable_source_manager,
+ db_incremental_field_last_value=db_incremental_field_last_value,
),
primary_keys=config.primary_keys,
+ # The timeseries endpoint offers no sort parameter and always returns newest first.
+ sort_mode="desc" if config.timeseries_aspect else "asc",
partition_count=1,
partition_size=1,
)
@@ -350,9 +454,12 @@ def validate_credentials(
if not host_ok:
return False, host_err or HOST_NOT_ALLOWED_ERROR
- probe_entity = DEFAULT_PROBE_ENTITY
- if schema_name is not None and schema_name in DATAHUB_ENDPOINTS:
- probe_entity = DATAHUB_ENDPOINTS[schema_name].entity_type
+ # Probe the endpoint the scoped schema would actually read. A timeseries aspect needs the
+ # timeseries read privilege on top of the entity one, so the entity list is not a stand-in.
+ probe_config = DATAHUB_ENDPOINTS.get(schema_name) if schema_name is not None else None
+ if probe_config is None:
+ probe_config = DatahubEndpointConfig(name=DEFAULT_PROBE_ENTITY, entity_type=DEFAULT_PROBE_ENTITY)
+ probe = _page_request(probe_config, base_url, count=1)
session = _get_session(api_token)
try:
@@ -360,9 +467,7 @@ def validate_credentials(
# address, defeating the host check above (SSRF). stream=True so a hostile server can't
# exhaust the API worker with an unbounded body — a 200 returns without reading it, and
# error snippets are read under a cap.
- response = session.get(
- _entity_url(base_url, probe_entity), params=_scroll_params(None, count=1), timeout=15, stream=True
- )
+ response = session.get(probe.url, params=probe.params, timeout=15, stream=True)
except requests.exceptions.RequestException as e:
return False, f"Could not connect to DataHub: {e}"
@@ -411,15 +516,11 @@ def check_endpoint_permissions(
if config is None:
results[endpoint] = None
continue
+ probe = _page_request(config, base_url, count=1)
try:
# stream=True so a hostile instance can't exhaust the API worker with an unbounded
# body; only a capped error snippet is read below when the status warrants a message.
- response = session.get(
- _entity_url(base_url, config.entity_type),
- params=_scroll_params(None, count=1),
- timeout=15,
- stream=True,
- )
+ response = session.get(probe.url, params=probe.params, timeout=15, stream=True)
except requests.exceptions.RequestException:
results[endpoint] = None
continue
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/datahub/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/datahub/settings.py
index 2672243b83d6..54ccde860740 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/datahub/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/datahub/settings.py
@@ -1,7 +1,21 @@
-from dataclasses import dataclass, field
+from dataclasses import field
+from typing import Optional
+from posthog.dataclasses import frozen
-@dataclass
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+# Synthesized surrogate key for a timeseries row. DataHub's own uniqueness rule for a timeseries
+# document spans the timestamp, event granularity, urn, message id and partition spec, and none of
+# those is unique on its own, so the source hashes them into this column.
+TIMESERIES_ROW_ID_COLUMN = "id"
+
+# Every timeseries aspect carries this epoch-millis field, and the scroll endpoint filters on it
+# server-side, so it is the cursor for an incremental sync.
+TIMESERIES_INCREMENTAL_FIELD = "timestampMillis"
+
+
+@frozen
class DatahubEndpointConfig:
name: str
# DataHub metadata-model entity name, interpolated into /openapi/v3/entity/{entity_type}.
@@ -9,12 +23,28 @@ class DatahubEndpointConfig:
entity_type: str
# Every DataHub entity is identified by its URN, unique across the whole metadata graph.
primary_keys: list[str] = field(default_factory=lambda: ["urn"])
+ # Timeseries aspect of `entity_type` to scroll instead of the entity's versioned aspects. When
+ # set, the endpoint reads /openapi/v2/timeseries/{entity_type}/{timeseries_aspect} and yields
+ # one row per recorded event rather than one row per entity.
+ timeseries_aspect: Optional[str] = None
-# DataHub OpenAPI v3 entity scroll endpoints. All full refresh only: the generic entity list has
-# no server-side updated-since filter (freshness only exists as per-aspect
-# systemMetadata.lastObserved, which mutates and isn't filterable here), so there is no timestamp
-# cursor to advance an incremental sync. The scroll cursor makes a single full sweep resumable.
+def _timeseries_endpoint(name: str, entity_type: str, aspect: str) -> DatahubEndpointConfig:
+ return DatahubEndpointConfig(
+ name=name,
+ entity_type=entity_type,
+ primary_keys=[TIMESERIES_ROW_ID_COLUMN],
+ timeseries_aspect=aspect,
+ )
+
+
+# DataHub OpenAPI v3 entity scroll endpoints and OpenAPI v2 timeseries aspect scroll endpoints.
+#
+# Entity endpoints are full refresh only: the generic entity list has no server-side updated-since
+# filter (freshness only exists as per-aspect systemMetadata.lastObserved, which mutates and isn't
+# filterable here), so there is no timestamp cursor to advance an incremental sync. The scroll
+# cursor makes a single full sweep resumable.
+#
# Lineage edges ride along on the entities themselves (datasets carry the upstreamLineage aspect,
# data jobs carry dataJobInputOutput), so no separate per-entity relationship fan-out is needed.
DATAHUB_ENDPOINTS: dict[str, DatahubEndpointConfig] = {
@@ -32,8 +62,34 @@ DATAHUB_ENDPOINTS: dict[str, DatahubEndpointConfig] = {
"tags": DatahubEndpointConfig(name="tags", entity_type="tag"),
"users": DatahubEndpointConfig(name="users", entity_type="corpuser"),
"groups": DatahubEndpointConfig(name="groups", entity_type="corpGroup"),
+ "data_process_instances": DatahubEndpointConfig(name="data_process_instances", entity_type="dataProcessInstance"),
+ "assertions": DatahubEndpointConfig(name="assertions", entity_type="assertion"),
+ # Only fields that have been materialized as their own entity appear here. The full column list
+ # of a dataset stays in its schemaMetadata aspect on the `datasets` table.
+ "schema_fields": DatahubEndpointConfig(name="schema_fields", entity_type="schemaField"),
+ "data_process_instance_run_events": _timeseries_endpoint(
+ "data_process_instance_run_events", "dataProcessInstance", "dataProcessInstanceRunEvent"
+ ),
+ "assertion_run_events": _timeseries_endpoint("assertion_run_events", "assertion", "assertionRunEvent"),
+ "dataset_profiles": _timeseries_endpoint("dataset_profiles", "dataset", "datasetProfile"),
+ "dataset_usage_statistics": _timeseries_endpoint("dataset_usage_statistics", "dataset", "datasetUsageStatistics"),
+ "dataset_operations": _timeseries_endpoint("dataset_operations", "dataset", "operation"),
}
ENDPOINTS = tuple(DATAHUB_ENDPOINTS.keys())
-INCREMENTAL_FIELDS: dict[str, list[dict[str, str]]] = {}
+TIMESERIES_ENDPOINTS = tuple(name for name, config in DATAHUB_ENDPOINTS.items() if config.timeseries_aspect)
+
+# Merge only: the server-side `startTimeMillis` bound is inclusive, so every sync re-reads the
+# boundary event and an append would land it a second time.
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: [
+ {
+ "label": TIMESERIES_INCREMENTAL_FIELD,
+ "type": IncrementalFieldType.Integer,
+ "field": TIMESERIES_INCREMENTAL_FIELD,
+ "field_type": IncrementalFieldType.Integer,
+ }
+ ]
+ for name in TIMESERIES_ENDPOINTS
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/datahub/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/datahub/source.py
index b8b0fe898402..438a07ddae94 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/datahub/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/datahub/source.py
@@ -13,9 +13,14 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.can
)
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 ResumableSourceManager
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (
+ SourceSchema,
+ build_endpoint_schemas,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceInputs, SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.datahub.datahub import (
+ MIN_TIMESERIES_SCROLL_VERSION,
+ TIMESERIES_SCROLL_UNSUPPORTED_ERROR,
DatahubResumeConfig,
check_endpoint_permissions,
datahub_source,
@@ -24,6 +29,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.datahub.da
from products.warehouse_sources.backend.temporal.data_imports.sources.datahub.settings import (
DATAHUB_ENDPOINTS,
ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ TIMESERIES_ENDPOINTS,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.datahub import (
DatahubSourceConfig,
@@ -95,6 +102,11 @@ The token is a [personal access token](https://docs.datahub.com/docs/authenticat
"401 Client Error": "Your DataHub access token is invalid or has expired. Generate a new personal access token under Settings → Access Tokens and reconnect.",
"Unauthorized for url": "Your DataHub access token is invalid or has expired. Generate a new personal access token under Settings → Access Tokens and reconnect.",
"403 Client Error": "Your DataHub access token does not have permission to read this data. Check the token owner's view privileges, then reconnect.",
+ TIMESERIES_SCROLL_UNSUPPORTED_ERROR: (
+ f"Your DataHub instance is older than {MIN_TIMESERIES_SCROLL_VERSION}, whose timeseries API cannot "
+ "paginate. Upgrade the instance to sync the run event, profile, usage and operation tables, or turn "
+ "those tables off."
+ ),
}
def get_schemas(
@@ -106,22 +118,10 @@ The token is a [personal access token](https://docs.datahub.com/docs/authenticat
force_refresh: bool = False,
api_version: str | None = None,
) -> list[SourceSchema]:
- # Every endpoint is full refresh only — the generic entity scroll exposes no server-side
- # updated-since filter, so there is no timestamp cursor to advance an incremental sync
- # (see settings.py).
- schemas = [
- SourceSchema(
- name=endpoint,
- supports_incremental=False,
- supports_append=False,
- incremental_fields=[],
- )
- for endpoint in ENDPOINTS
- ]
- if names is not None:
- names_set = set(names)
- schemas = [s for s in schemas if s.name in names_set]
- return schemas
+ # The entity endpoints are full refresh only, because the generic entity scroll exposes no
+ # server-side updated-since filter, so there is no timestamp cursor to advance an
+ # incremental sync. The timeseries aspect endpoints do take one (see settings.py).
+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names, merge_only=TIMESERIES_ENDPOINTS)
def validate_credentials(
self,
@@ -158,4 +158,7 @@ The token is a [personal access token](https://docs.datahub.com/docs/authenticat
team_id=inputs.team_id,
logger=inputs.logger,
resumable_source_manager=resumable_source_manager,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value
+ if inputs.should_use_incremental_field
+ else None,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/datahub/tests/test_datahub.py b/products/warehouse_sources/backend/temporal/data_imports/sources/datahub/tests/test_datahub.py
index 29e6296ff6b0..8acb82a94b80 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/datahub/tests/test_datahub.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/datahub/tests/test_datahub.py
@@ -14,9 +14,11 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.datahub.da
DatahubResponseTooLargeError,
DatahubResumeConfig,
DatahubRetryableError,
+ DatahubTimeseriesScrollUnsupportedError,
DatahubTooManyPagesError,
- _extract_entities,
+ _extract_page,
_headers,
+ _timeseries_row_id,
check_endpoint_permissions,
datahub_source,
get_rows,
@@ -107,28 +109,34 @@ class TestDatahub:
@parameterized.expand(
[
- ("page_with_cursor", {"scrollId": "abc", "entities": [{"urn": "u1"}]}, [{"urn": "u1"}], "abc"),
- ("final_page", {"entities": [{"urn": "u2"}]}, [{"urn": "u2"}], None),
- # An empty final page may omit `entities` entirely — that's a valid empty result.
- ("empty_without_key", {}, [], None),
+ ("page_with_cursor", "entities", {"scrollId": "abc", "entities": [{"urn": "u1"}]}, [{"urn": "u1"}], "abc"),
+ ("final_page", "entities", {"entities": [{"urn": "u2"}]}, [{"urn": "u2"}], None),
+ # An empty final page may omit the items key entirely — that's a valid empty result.
+ ("empty_without_key", "entities", {}, [], None),
# An empty-string scrollId must not be followed as a cursor.
- ("empty_cursor", {"scrollId": "", "entities": []}, [], None),
+ ("empty_cursor", "entities", {"scrollId": "", "entities": []}, [], None),
+ # The timeseries endpoint wraps its rows under `results` instead of `entities`.
+ ("timeseries_page", "results", {"scrollId": "abc", "results": [{"urn": "u1"}]}, [{"urn": "u1"}], "abc"),
+ ("timeseries_final_page", "results", {"results": [{"urn": "u2"}]}, [{"urn": "u2"}], None),
+ # An entity envelope read with the timeseries key must not silently yield entity rows.
+ ("wrong_key_reads_empty", "results", {"entities": [{"urn": "u1"}]}, [], None),
]
)
- def test_extract_entities(
- self, _name: str, payload: Any, expected_rows: list[dict], expected_cursor: str | None
+ def test_extract_page(
+ self, _name: str, items_key: str, payload: Any, expected_rows: list[dict], expected_cursor: str | None
) -> None:
- assert _extract_entities(payload, "http://url") == (expected_rows, expected_cursor)
+ assert _extract_page(payload, "http://url", items_key) == (expected_rows, expected_cursor)
@parameterized.expand(
[
- ("bare_list", [{"urn": "u1"}]),
- ("entities_not_a_list", {"entities": {"urn": "u1"}}),
+ ("bare_list", "entities", [{"urn": "u1"}]),
+ ("entities_not_a_list", "entities", {"entities": {"urn": "u1"}}),
+ ("results_not_a_list", "results", {"results": {"urn": "u1"}}),
]
)
- def test_extract_entities_rejects_unexpected_payloads(self, _name: str, payload: Any) -> None:
+ def test_extract_page_rejects_unexpected_payloads(self, _name: str, items_key: str, payload: Any) -> None:
with pytest.raises(DatahubRetryableError):
- _extract_entities(payload, "http://url")
+ _extract_page(payload, "http://url", items_key)
# --- fetch ---
@@ -179,6 +187,7 @@ class TestDatahub:
monkeypatch: Any,
pages: dict[Any, Any],
endpoint: str = "datasets",
+ db_incremental_field_last_value: Any = None,
) -> tuple[list[dict], list[dict[str, Any]]]:
"""Run get_rows with a fake _fetch keyed by the `scrollId` param (None = first page)."""
calls: list[dict[str, Any]] = []
@@ -202,6 +211,7 @@ class TestDatahub:
team_id=1,
logger=MagicMock(),
resumable_source_manager=manager, # type: ignore[arg-type]
+ db_incremental_field_last_value=db_incremental_field_last_value,
):
rows.extend(batch)
return rows, calls
@@ -214,7 +224,8 @@ class TestDatahub:
}
rows, calls = self._collect(manager, monkeypatch, pages)
- assert [r["urn"] for r in rows] == ["u1", "u2", "u3"]
+ # Compared whole, so the timeseries row-id transform can't leak onto an entity endpoint.
+ assert rows == [{"urn": "u1"}, {"urn": "u2"}, {"urn": "u3"}]
assert calls[0]["url"] == f"{BASE_URL}/openapi/v3/entity/dataset"
# Stable ascending urn sort keeps page boundaries fixed while scrolling.
assert all(
@@ -332,10 +343,102 @@ class TestDatahub:
)
)
+ # --- timeseries aspect endpoints ---
+
+ # pytest.mark.parametrize (not parameterized.expand) because the test also needs the
+ # monkeypatch fixture, which parameterized's wrapper doesn't forward.
+ @pytest.mark.parametrize("last_value", [1500, None])
+ def test_timeseries_sweep_windows_every_page(self, last_value: Optional[int], monkeypatch: Any) -> None:
+ # The cursor is a stateless search_after token, so the server only keeps the time bound
+ # while we keep sending it. Drop it after page one and an incremental sync walks back
+ # through the whole history instead of stopping at the watermark. A full refresh must send
+ # no bound at all.
+ manager = _FakeResumableManager()
+ pages = {
+ None: {"scrollId": "cursor-1", "results": [{"urn": "u1", "timestampMillis": 3000}]},
+ "cursor-1": {"results": [{"urn": "u1", "timestampMillis": 2000}]},
+ }
+ rows, calls = self._collect(
+ manager, monkeypatch, pages, endpoint="dataset_profiles", db_incremental_field_last_value=last_value
+ )
+
+ assert [r["timestampMillis"] for r in rows] == [3000, 2000]
+ assert calls[0]["url"] == f"{BASE_URL}/openapi/v2/timeseries/dataset/datasetProfile"
+ assert all(c["params"].get("startTimeMillis") == last_value for c in calls)
+ assert all(c["params"]["count"] == PAGE_SIZE for c in calls)
+ # The endpoint takes no sort parameter, so none of the entity scroll's sort params apply.
+ assert all("sortCriteria" not in c["params"] for c in calls)
+
+ def test_timeseries_rows_carry_a_synthesized_primary_key(self, monkeypatch: Any) -> None:
+ manager = _FakeResumableManager()
+ pages = {None: {"results": [{"urn": "u1", "timestampMillis": 3000, "event": {"rowCount": 1}}]}}
+ rows, _calls = self._collect(manager, monkeypatch, pages, endpoint="dataset_profiles")
+ assert rows[0]["id"] == _timeseries_row_id(pages[None]["results"][0])
+ assert rows[0]["event"] == {"rowCount": 1}
+
+ def test_timeseries_full_page_without_a_cursor_fails_instead_of_truncating(self, monkeypatch: Any) -> None:
+ # DataHub before v1.4.0 never returns a scroll cursor from the timeseries endpoint, so the
+ # sweep would end after one page and write a silently truncated table. A fixed instance
+ # always pairs a full page with a cursor, so this shape only happens on an old one.
+ monkeypatch.setattr(datahub, "PAGE_SIZE", 2)
+ manager = _FakeResumableManager()
+ pages = {None: {"results": [{"urn": "u1", "timestampMillis": 3000}, {"urn": "u2", "timestampMillis": 2000}]}}
+ with pytest.raises(DatahubTimeseriesScrollUnsupportedError):
+ self._collect(manager, monkeypatch, pages, endpoint="dataset_profiles")
+
+ def test_timeseries_short_final_page_without_a_cursor_ends_the_sweep(self, monkeypatch: Any) -> None:
+ monkeypatch.setattr(datahub, "PAGE_SIZE", 2)
+ manager = _FakeResumableManager()
+ pages = {None: {"results": [{"urn": "u1", "timestampMillis": 3000}]}}
+ rows, _calls = self._collect(manager, monkeypatch, pages, endpoint="dataset_profiles")
+ assert [r["urn"] for r in rows] == ["u1"]
+
+ def test_entity_full_page_without_a_cursor_ends_the_sweep(self, monkeypatch: Any) -> None:
+ # The entity scroll has always signalled its last page by omitting the cursor, so the
+ # timeseries guard must not fire on it.
+ monkeypatch.setattr(datahub, "PAGE_SIZE", 2)
+ manager = _FakeResumableManager()
+ pages = {None: {"entities": [{"urn": "u1"}, {"urn": "u2"}]}}
+ rows, _calls = self._collect(manager, monkeypatch, pages)
+ assert [r["urn"] for r in rows] == ["u1", "u2"]
+
+ @parameterized.expand(
+ [
+ # urn plus timestamp alone is not unique: one dataset can carry a daily and an hourly
+ # bucket, one row per partition, and separately ingested events with distinct ids. A
+ # key that collapses those loses rows and makes every later merge multi-match.
+ ("event_granularity", {"event": {"eventGranularity": {"unit": "HOUR", "multiple": 1}}}, False),
+ ("partition_spec", {"event": {"partitionSpec": {"partition": "2026-09-01"}}}, False),
+ ("message_id", {"messageId": "m2"}, False),
+ # Metric values stay out of the key, so a bucket the instance restates merges onto
+ # itself rather than landing twice.
+ ("restated_metric", {"event": {"rowCount": 11}}, True),
+ ]
+ )
+ def test_timeseries_row_id_keys_on_identity_not_metrics(
+ self, _name: str, delta: dict[str, Any], expect_same: bool
+ ) -> None:
+ base: dict[str, Any] = {"urn": "u1", "timestampMillis": 3000, "messageId": "m1", "event": {"rowCount": 10}}
+ same = _timeseries_row_id(base) == _timeseries_row_id({**base, **delta})
+ assert same is expect_same
+
# --- SourceResponse assembly ---
- @parameterized.expand([("datasets",), ("users",), ("tags",)])
- def test_datahub_source_uses_urn_primary_key(self, endpoint: str) -> None:
+ @parameterized.expand(
+ [
+ ("datasets", ["urn"], "asc"),
+ ("users", ["urn"], "asc"),
+ ("tags", ["urn"], "asc"),
+ ("schema_fields", ["urn"], "asc"),
+ # The timeseries endpoint always returns newest first and has no sort parameter, so a
+ # response claiming "asc" would checkpoint the watermark to now after the first batch.
+ ("dataset_profiles", ["id"], "desc"),
+ ("assertion_run_events", ["id"], "desc"),
+ ]
+ )
+ def test_datahub_source_primary_key_and_sort_mode(
+ self, endpoint: str, expected_keys: list[str], expected_sort: str
+ ) -> None:
response = datahub_source(
instance_url=BASE_URL,
api_token=TOKEN,
@@ -345,7 +448,8 @@ class TestDatahub:
resumable_source_manager=_FakeResumableManager(), # type: ignore[arg-type]
)
assert response.name == endpoint
- assert response.primary_keys == ["urn"]
+ assert response.primary_keys == expected_keys
+ assert response.sort_mode == expected_sort
# --- credential validation ---
@@ -458,6 +562,16 @@ class TestDatahub:
result = check_endpoint_permissions(BASE_URL, TOKEN, ["datasets"], team_id=1)
assert result["datasets"] == expected
+ def test_check_endpoint_permissions_probes_the_endpoint_the_sync_reads(self, monkeypatch: Any) -> None:
+ # A timeseries aspect needs the timeseries read privilege on top of the entity one, so
+ # probing the entity list would report a table as readable that the sync cannot read.
+ session = MagicMock()
+ session.get.return_value = _mock_response(200, {"results": []})
+ monkeypatch.setattr(datahub, "make_tracked_session", lambda **kwargs: session)
+ monkeypatch.setattr(datahub, "_is_host_safe", lambda host, team_id: (True, None))
+ check_endpoint_permissions(BASE_URL, TOKEN, ["dataset_operations"], team_id=1)
+ assert session.get.call_args.args[0] == f"{BASE_URL}/openapi/v2/timeseries/dataset/operation"
+
def test_check_endpoint_permissions_treats_network_blips_as_reachable(self, monkeypatch: Any) -> None:
session = MagicMock()
session.get.side_effect = requests.ConnectionError("boom")
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/datahub/tests/test_datahub_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/datahub/tests/test_datahub_source.py
index d81de299fd6a..58f8de8d5344 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/datahub/tests/test_datahub_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/datahub/tests/test_datahub_source.py
@@ -4,7 +4,10 @@ from unittest import mock
from parameterized import parameterized
from products.warehouse_sources.backend.facade.source_config import ReleaseStatus, SourceFieldInputConfig
-from products.warehouse_sources.backend.temporal.data_imports.sources.datahub.settings import ENDPOINTS
+from products.warehouse_sources.backend.temporal.data_imports.sources.datahub.settings import (
+ ENDPOINTS,
+ TIMESERIES_ENDPOINTS,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.datahub.source import DatahubSource
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.datahub import (
DatahubSourceConfig,
@@ -37,12 +40,18 @@ class TestDatahubSource:
def test_lists_tables_without_credentials(self) -> None:
assert self.source.lists_tables_without_credentials is True
- def test_get_schemas_covers_all_endpoints_as_full_refresh(self) -> None:
- schemas = self.source.get_schemas(self.config, self.team_id)
- assert {s.name for s in schemas} == set(ENDPOINTS)
- assert all(s.supports_incremental is False for s in schemas)
- assert all(s.supports_append is False for s in schemas)
- assert all(s.incremental_fields == [] for s in schemas)
+ def test_get_schemas_marks_only_timeseries_endpoints_incremental(self) -> None:
+ # Entity endpoints have no server-side updated-since filter, so a cursor offered on one
+ # would silently re-read everything each sync while claiming to be incremental.
+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}
+ assert set(schemas) == set(ENDPOINTS)
+ for name, schema in schemas.items():
+ is_timeseries = name in TIMESERIES_ENDPOINTS
+ assert schema.supports_incremental is is_timeseries
+ assert [f["field"] for f in schema.incremental_fields] == (["timestampMillis"] if is_timeseries else [])
+ # Merge only: the startTimeMillis bound is inclusive, so an append would land the
+ # boundary event again on every sync.
+ assert schema.supports_append is False
def test_get_schemas_filtered_by_names(self) -> None:
schemas = self.source.get_schemas(self.config, self.team_id, names=["datasets"])
@@ -57,6 +66,11 @@ class TestDatahubSource:
assert {t["name"] for t in tables} == set(ENDPOINTS)
assert all("Full refresh" in t["sync_methods"] for t in tables)
+ def test_every_table_is_documented(self) -> None:
+ # The public docs render this catalog, and a table with no entry falls back to an LLM
+ # guess at its columns.
+ assert set(self.source.get_canonical_descriptions()) == set(ENDPOINTS)
+
@parameterized.expand(
[
("401 Client Error: Unauthorized for url: https://datahub.example.com/openapi/v3/entity/dataset",),
@@ -105,6 +119,20 @@ class TestDatahubSource:
assert kwargs["team_id"] == self.team_id
assert kwargs["resumable_source_manager"] is manager
+ @parameterized.expand([(True, 1500), (False, None)])
+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.datahub.source.datahub_source")
+ def test_source_for_pipeline_only_passes_the_watermark_on_an_incremental_run(
+ self, should_use_incremental_field: bool, expected: int | None, mock_source: mock.MagicMock
+ ) -> None:
+ inputs = mock.MagicMock()
+ inputs.schema_name = "dataset_profiles"
+ inputs.should_use_incremental_field = should_use_incremental_field
+ inputs.db_incremental_field_last_value = 1500
+
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ assert mock_source.call_args.kwargs["db_incremental_field_last_value"] == expected
+
def test_source_for_pipeline_rejects_unknown_schema(self) -> None:
inputs = mock.MagicMock()
inputs.schema_name = "nope"