: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 dagster cloud automation and asset event tables (#104406)
Tom Owersc2d05c9eea0f
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 e928bb84ed65..e0757131758d 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@@ -2228,14 +2228,15 @@ Note: Pulled the raw Postman collection JSON behind the published documenter lin## DagsterCloud — gaps-Today (3): `assets`, `backfills`, `runs`+Today (10): `asset_materializations`, `asset_nodes`, `asset_observations`, `assets`, `backfills`,+`instigation_states`, `instigation_ticks`, `runs`, `schedules`, `sensors`Diffed against: <https://raw.githubusercontent.com/dagster-io/dagster/master/python_modules/libraries/dagster-dg-cli/dagster_dg_cli/cli/plus/schema.graphql>-- [ ] `assetOrError(assetKey){ assetMaterializations } / assetObservations` — per-asset materialization event history with metadata — the core fact table behind the asset list we already sync (high)-- [ ] `assetNodes / assetNodeOrError` — asset definition metadata (group, owning job, description, dependencies, freshness policy) — lookup resolving the bare asset keys we sync (high)-- [ ] `schedulesOrError / sensorsOrError` — automation definitions and their status; lookup resolving the schedule/sensor tags carried on runs (high)-- [ ] `instigationStatesOrError / InstigationTick history (autoMaterializeTicks)` — schedule and sensor tick success/failure/skip history — orchestration reliability analysis (high)+- [x] `assetOrError(assetKey){ assetMaterializations } / assetObservations` — per-asset materialization event history with metadata — the core fact table behind the asset list we already sync (high)+- [x] `assetNodes / assetNodeOrError` — asset definition metadata (group, owning job, description, dependencies, freshness policy) — lookup resolving the bare asset keys we sync (high)+- [x] `schedulesOrError / sensorsOrError` — automation definitions and their status; lookup resolving the schedule/sensor tags carried on runs (high)+- [x] `instigationStatesOrError / InstigationTick history (autoMaterializeTicks)` — schedule and sensor tick success/failure/skip history — orchestration reliability analysis (high)- [ ] `deployments / fullDeployments / branchDeployments` — lookup resolving which Dagster+ deployment each run and asset belongs to (high)- [ ] `reportingMetricsByJob / reportingMetricsByAsset / reportingMetricsByDeployment (Dagster+ Insights)` — Dagster+'s headline metrics — credits consumed, run duration, materialization and retry counts per job/asset/deployment (high)- [ ] `assetCheckExecutions` — data quality check results per asset over time (medium)@@ -2245,7 +2246,9 @@ Diffed against: <https://raw.githubusercontent.com/dagster-io/dagster/master/pyt- [ ] `auditLog` — who changed deployments, code locations and automation settings (medium)- [ ] `slasForAssets / assetSlaTimeline` — asset SLA state and breach timeline for freshness reporting (low)-Note: Diffed against the Dagster+ cloud GraphQL schema snapshot vendored in dagster-dg-cli (type CloudQuery), which is a superset of the OSS webserver schema at js_modules/ui-core/src/graphql/schema.graphql. The synced `assets` table is especially thin — the source's ASSETS_QUERY selects only id and key.path, so no asset metadata or materialization history lands at all.+Note: Diffed against the Dagster+ cloud GraphQL schema snapshot vendored in dagster-dg-cli (type CloudQuery), which is a superset of the OSS webserver schema at js_modules/ui-core/src/graphql/schema.graphql. The `assets` table stays thin by design — ASSETS_QUERY is the asset-key enumeration the `asset_nodes`, `asset_materializations` and `asset_observations` fan-outs walk, and the metadata and event history land in those tables instead.++Note: `autoMaterializeTicks` was not implemented separately. It returns the ticks of the legacy global auto-materialize daemon; current Dagster runs automation as an asset daemon whose ticks are an ordinary instigation state, so `instigation_ticks` already covers them.## Datadog — gapsdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dagster_cloud/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dagster_cloud/canonical_descriptions.pyindex c2bbd709b166..d25a9753d3ec 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/dagster_cloud/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dagster_cloud/canonical_descriptions.py@@ -48,4 +48,142 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"key": "The asset key as a path list.",},},+ "schedules": {+ "description": "Schedule definitions in each code location, with their cron expression and default status.",+ "docs_url": "https://docs.dagster.io/api/graphql",+ "columns": {+ "id": "Unique identifier for the schedule definition.",+ "name": "Name of the schedule.",+ "cronSchedule": "Cron expression the schedule ticks on.",+ "pipelineName": "Name of the job the schedule launches.",+ "mode": "Execution mode the schedule launches runs in.",+ "executionTimezone": "Timezone the cron expression is evaluated in.",+ "description": "Description declared on the schedule.",+ "defaultStatus": "Status the schedule starts in when the code location loads (RUNNING or STOPPED).",+ "scheduleState": "Current instigation state of the schedule, including its live status.",+ "assetSelection": "Assets the schedule targets, if it is an asset schedule.",+ "tags": "Key/value tags declared on the schedule.",+ "repositoryName": "Repository the schedule is defined in.",+ "repositoryLocationName": "Code location the repository is loaded from.",+ },+ },+ "sensors": {+ "description": "Sensor definitions in each code location, with their type, tick interval, and default status.",+ "docs_url": "https://docs.dagster.io/api/graphql",+ "columns": {+ "id": "Unique identifier for the sensor definition.",+ "name": "Name of the sensor.",+ "jobOriginId": "Identifier of the sensor's origin within its code location.",+ "sensorType": "Kind of sensor (e.g. STANDARD, RUN_STATUS, ASSET, AUTOMATION, FRESHNESS_POLICY).",+ "description": "Description declared on the sensor.",+ "defaultStatus": "Status the sensor starts in when the code location loads (RUNNING or STOPPED).",+ "minIntervalSeconds": "Minimum seconds Dagster waits between sensor evaluations.",+ "targets": "Jobs the sensor can launch.",+ "sensorState": "Current instigation state of the sensor, including its live status.",+ "assetSelection": "Assets the sensor targets, if it is an asset sensor.",+ "metadata": "Asset keys the sensor monitors.",+ "tags": "Key/value tags declared on the sensor.",+ "repositoryName": "Repository the sensor is defined in.",+ "repositoryLocationName": "Code location the repository is loaded from.",+ },+ },+ "instigation_states": {+ "description": "Live state of every schedule and sensor, including the cursor a sensor last stored.",+ "docs_url": "https://docs.dagster.io/api/graphql",+ "columns": {+ "id": "Compound identifier for the instigation state.",+ "selectorId": "Stable identifier of the schedule or sensor this state belongs to.",+ "name": "Name of the schedule or sensor.",+ "instigationType": "Whether the state belongs to a SCHEDULE or a SENSOR.",+ "status": "Whether the schedule or sensor is currently RUNNING or STOPPED.",+ "repositoryName": "Repository the schedule or sensor is defined in.",+ "repositoryLocationName": "Code location the repository is loaded from.",+ "repositoryOrigin": "The code location and repository the state originated from.",+ "runsCount": "Number of runs launched by this schedule or sensor.",+ "typeSpecificData": "Schedule cron and start time, or sensor last tick, last run key, and last cursor.",+ },+ },+ "instigation_ticks": {+ "description": "Tick history for every schedule and sensor — one row per evaluation, with its outcome and the runs it requested. Used for orchestration reliability analysis.",+ "docs_url": "https://docs.dagster.io/api/graphql",+ "columns": {+ "id": "Identifier for the tick, scoped to its schedule or sensor.",+ "tickId": "Identifier of the stored tick record.",+ "status": "Outcome of the tick (STARTED, SKIPPED, SUCCESS, or FAILURE).",+ "timestamp": "When the tick was evaluated.",+ "endTimestamp": "When the tick finished, if it has.",+ "runIds": "Identifiers of the runs the tick launched.",+ "runKeys": "Idempotency keys of the run requests the tick produced.",+ "originRunIds": "Identifiers of the runs that caused this tick, for run-status sensors.",+ "skipReason": "Why the tick requested no runs, when it was skipped.",+ "cursor": "Cursor the sensor stored at the end of the tick.",+ "instigationType": "Whether the tick belongs to a SCHEDULE or a SENSOR.",+ "requestedAssetMaterializationCount": "Number of asset materializations the tick requested.",+ "requestedAssetKeys": "Asset keys the tick requested, each as a path list.",+ "error": "Error raised during the tick, when it failed.",+ "instigationName": "Name of the schedule or sensor the tick belongs to.",+ "instigationSelectorId": "Stable identifier of the schedule or sensor the tick belongs to.",+ "repositoryName": "Repository the schedule or sensor is defined in.",+ "repositoryLocationName": "Code location the repository is loaded from.",+ },+ },+ "asset_nodes": {+ "description": "Asset definition metadata — group, owning jobs, dependencies, partitioning, and freshness policy. Resolves the bare asset keys in the assets table.",+ "docs_url": "https://docs.dagster.io/api/graphql",+ "columns": {+ "id": "Unique identifier for the asset definition.",+ "assetKey": "The asset key as a path list.",+ "groupName": "Asset group the definition belongs to.",+ "description": "Description declared on the asset.",+ "computeKind": "Compute kind label declared on the asset (e.g. dbt, python).",+ "opName": "Name of the op that computes the asset.",+ "opNames": "Names of every op that computes the asset.",+ "jobNames": "Jobs that can materialize the asset.",+ "kinds": "Kind labels declared on the asset.",+ "isPartitioned": "Whether the asset is partitioned.",+ "isObservable": "Whether the asset can be observed rather than materialized.",+ "isMaterializable": "Whether the asset can be materialized by Dagster.",+ "isExecutable": "Whether the asset has executable compute attached.",+ "owners": "Owners declared on the asset, each a user email or a team name.",+ "dependencyKeys": "Asset keys this asset reads from.",+ "dependedByKeys": "Asset keys that read from this asset.",+ "freshnessPolicy": "Freshness policy declared on the asset, if any.",+ "autoMaterializePolicy": "Automation policy declared on the asset, if any.",+ "partitionDefinition": "How the asset is partitioned, if it is.",+ "tags": "Key/value tags declared on the asset.",+ "repository": "Repository and code location the definition is loaded from.",+ },+ },+ "asset_materializations": {+ "description": "Materialization event history per asset — one row each time an asset was materialized, with the metadata the run attached. The fact table behind the asset catalog.",+ "docs_url": "https://docs.dagster.io/api/graphql",+ "columns": {+ "assetId": "Identifier of the asset the event belongs to.",+ "runId": "Identifier of the run that materialized the asset.",+ "timestamp": "When the materialization was recorded.",+ "stepKey": "Step within the run that reported the materialization.",+ "partition": "Partition materialized, for a partitioned asset.",+ "label": "Label recorded on the materialization.",+ "description": "Description recorded on the materialization.",+ "assetKey": "The asset key as a path list.",+ "tags": "Key/value tags recorded on the materialization event.",+ "metadataEntries": "Metadata the run attached to the materialization, with each entry's type and label.",+ },+ },+ "asset_observations": {+ "description": "Observation event history per asset — one row each time an observable asset was observed, with the metadata the observation reported.",+ "docs_url": "https://docs.dagster.io/api/graphql",+ "columns": {+ "assetId": "Identifier of the asset the event belongs to.",+ "runId": "Identifier of the run that observed the asset.",+ "timestamp": "When the observation was recorded.",+ "stepKey": "Step within the run that reported the observation.",+ "partition": "Partition observed, for a partitioned asset.",+ "label": "Label recorded on the observation.",+ "description": "Description recorded on the observation.",+ "assetKey": "The asset key as a path list.",+ "tags": "Key/value tags recorded on the observation event.",+ "metadataEntries": "Metadata the run attached to the observation, with each entry's type and label.",+ },+ },}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dagster_cloud/dagster_cloud.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dagster_cloud/dagster_cloud.pyindex a3b035731d5d..f02bbf2a1d28 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/dagster_cloud/dagster_cloud.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dagster_cloud/dagster_cloud.py@@ -1,5 +1,4 @@import re-import dataclassesfrom collections.abc import Iteratorfrom datetime import UTC, date, datetimefrom typing import Any, Optional@@ -8,6 +7,8 @@ import requestsfrom structlog.types import FilteringBoundLoggerfrom tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter+from posthog.dataclasses import frozen+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_sessionfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse@@ -15,7 +16,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.dagster_clfrom products.warehouse_sources.backend.temporal.data_imports.sources.dagster_cloud.settings import (DAGSTER_CLOUD_ENDPOINTS,DAGSTER_CLOUD_PAGE_SIZE,+ REPOSITORIES_PARENT_CONFIG,DagsterCloudEndpointConfig,+ DagsterCloudFanOutConfig,+ WindowUnit,)# Dagster+'s edge occasionally returns short bursts of 5xx/429; retry in-process long enough to@@ -33,9 +37,15 @@ class DagsterCloudRetryableError(Exception):pass+@frozenclass DagsterCloudResumeConfig:- cursor: str+ # Top-level endpoints: the next page cursor to request.+ cursor: str = ""+ # Fan-out endpoints: how many parents of the walk finished, and where the parent after them+ # had got to in its backwards page walk. The parent walk itself is replayed from the start on+ # resume — parent lists are small and cheap next to the child pages they drive.+ parents_done: int = 0+ window_cursor: str = ""def build_graphql_url(organization: str, deployment: str) -> str:@@ -75,6 +85,21 @@ def _epoch_to_iso(value: Any) -> Any:return value+def _millis_to_iso(value: Any) -> Any:+ """Normalize a Dagster epoch-milliseconds value to an ISO-8601 UTC string.++ The asset event resolvers return `timestamp` as a string of epoch milliseconds, unlike the+ run/backfill resolvers' epoch-seconds floats. Non-numeric values pass through.+ """+ if isinstance(value, bool):+ return value+ try:+ millis = int(value)+ except (TypeError, ValueError):+ return value+ return datetime.fromtimestamp(millis / 1000.0, tz=UTC).isoformat(timespec="microseconds")++def _to_epoch_seconds(value: Any) -> float | None:"""Convert an incremental watermark (datetime / date / ISO string / number) to epoch seconds.@@ -110,12 +135,15 @@ def _build_runs_filter(incremental_field: str | None, last_value_epoch: float |def _normalize_row(row: dict[str, Any], endpoint_config: DagsterCloudEndpointConfig) -> dict[str, Any]:- if not endpoint_config.timestamp_fields:+ if not endpoint_config.timestamp_fields and not endpoint_config.millis_timestamp_fields:return rownormalized = dict(row)for field_name in endpoint_config.timestamp_fields:if normalized.get(field_name) is not None:normalized[field_name] = _epoch_to_iso(normalized[field_name])+ for field_name in endpoint_config.millis_timestamp_fields:+ if normalized.get(field_name) is not None:+ normalized[field_name] = _millis_to_iso(normalized[field_name])return normalized@@ -179,13 +207,27 @@ def _execute_query(sess: requests.Session, url: str, query: str, variables: dictreturn _validate_response(response, url)-def _extract_success_member(payload: dict[str, Any], endpoint_config: DagsterCloudEndpointConfig) -> dict[str, Any]:+def _extract_rows(+ payload: dict[str, Any], endpoint_config: DagsterCloudEndpointConfig+) -> tuple[dict[str, Any], list[dict[str, Any]]] | None:+ """Unwrap the OrError union member holding the rows.++ Returns the container alongside its rows (the container carries the connection cursor), or+ None when the response says the parent is gone — a fan-out reads its parent list before its+ children, so a parent deleted in between must be skipped rather than fail the sync.+ """container = payload["data"][endpoint_config.response_field]+ if endpoint_config.success_typename is None:+ # The root field returns the row list directly rather than an OrError union (assetNodes).+ return {}, list(container or [])+typename = container.get("__typename")+ if typename in endpoint_config.skip_typenames:+ return Noneif typename != endpoint_config.success_typename:message = container.get("message", "")raise Exception(f"Dagster Cloud {endpoint_config.response_field} returned {typename}: {message}")- return container+ return container, list(container.get(endpoint_config.results_key) or [])def _read_next_cursor(@@ -197,6 +239,44 @@ def _read_next_cursor(return rows[-1].get(endpoint_config.cursor_row_field)+def _iter_cursor_pages(+ sess: requests.Session,+ url: str,+ endpoint_config: DagsterCloudEndpointConfig,+ variables: dict[str, Any],+) -> Iterator[tuple[list[dict[str, Any]], str | None]]:+ """Walk a cursor-paginated list endpoint, yielding raw rows with the cursor that follows them.++ The cursor is handed back rather than checkpointed so the caller decides whether a page+ boundary is worth resume state — a parent walk replays from the start, a synced table does not.+ """+ variables = dict(variables)+ previous_cursor: str | None = variables.get("cursor")++ while True:+ payload = _execute_query(sess, url, endpoint_config.query, variables)+ extracted = _extract_rows(payload, endpoint_config)+ if extracted is None:+ return+ container, rows = extracted++ next_cursor: str | None = None+ # A short page means we've reached the end of the (optionally filtered) result set.+ if endpoint_config.cursor_mode is not None and len(rows) >= DAGSTER_CLOUD_PAGE_SIZE:+ raw_cursor = _read_next_cursor(container, rows, endpoint_config)+ next_cursor = str(raw_cursor) if raw_cursor else None++ yield rows, next_cursor+ if next_cursor is None:+ return+ # A cursor that repeats would replay the same page forever, since nothing else bounds+ # this walk.+ if next_cursor == previous_cursor:+ raise Exception(f"Dagster Cloud {endpoint_config.name}: pagination cursor did not advance")+ previous_cursor = next_cursor+ variables["cursor"] = next_cursor++def _make_paginated_request(organization: str,deployment: str,@@ -223,24 +303,246 @@ def _make_paginated_request(logger.debug(f"Dagster Cloud: resuming {endpoint_name} from saved cursor")try:- while True:- payload = _execute_query(sess, url, endpoint_config.query, variables)- container = _extract_success_member(payload, endpoint_config)- rows = container.get(endpoint_config.results_key) or []+ for rows, next_cursor in _iter_cursor_pages(sess, url, endpoint_config, variables):yield [_normalize_row(row, endpoint_config) for row in rows]- # A short page means we've reached the end of the (optionally filtered) result set.- if len(rows) < DAGSTER_CLOUD_PAGE_SIZE:- break-- next_cursor = _read_next_cursor(container, rows, endpoint_config)- if not next_cursor:- break-- variables["cursor"] = next_cursor# Checkpoint the next page to fetch AFTER yielding this one, so a crash re-fetches the# last page rather than skipping it — merge dedupes the overlap on primary_keys.- resumable_source_manager.save_state(DagsterCloudResumeConfig(cursor=str(next_cursor)))+ if next_cursor is not None:+ resumable_source_manager.save_state(DagsterCloudResumeConfig(cursor=next_cursor))+ finally:+ sess.close()+++def _iter_repository_parents(sess: requests.Session, url: str) -> Iterator[dict[str, Any]]:+ payload = _execute_query(sess, url, REPOSITORIES_PARENT_CONFIG.query, {})+ extracted = _extract_rows(payload, REPOSITORIES_PARENT_CONFIG)+ if extracted is None:+ return+ _, rows = extracted+ for row in rows:+ yield {+ "repositoryId": row.get("id"),+ "repositoryName": row.get("name"),+ "repositoryLocationName": (row.get("location") or {}).get("name"),+ }+++def _iter_asset_parents(sess: requests.Session, url: str) -> Iterator[dict[str, Any]]:+ endpoint_config = DAGSTER_CLOUD_ENDPOINTS["assets"]+ for rows, _ in _iter_cursor_pages(sess, url, endpoint_config, {"limit": DAGSTER_CLOUD_PAGE_SIZE}):+ for row in rows:+ path = (row.get("key") or {}).get("path") or []+ yield {"assetId": row.get("id"), "assetKeyPath": path, "assetKeyInput": {"path": path}}+++def _iter_instigation_state_parents(sess: requests.Session, url: str) -> Iterator[dict[str, Any]]:+ endpoint_config = DAGSTER_CLOUD_ENDPOINTS["instigation_states"]+ for repository in _iter_repository_parents(sess, url):+ payload = _execute_query(sess, url, endpoint_config.query, {"repositoryID": repository["repositoryId"]})+ extracted = _extract_rows(payload, endpoint_config)+ if extracted is None:+ continue+ _, rows = extracted+ for row in rows:+ yield {+ "repositoryName": row.get("repositoryName") or repository["repositoryName"],+ "repositoryLocationName": row.get("repositoryLocationName") or repository["repositoryLocationName"],+ "instigationName": row.get("name"),+ "instigationStateId": row.get("id"),+ "instigationSelectorId": row.get("selectorId"),+ }+++def _iter_parents(sess: requests.Session, url: str, fan_out: DagsterCloudFanOutConfig) -> Iterator[dict[str, Any]]:+ if fan_out.parent_kind == "repositories":+ yield from _iter_repository_parents(sess, url)+ elif fan_out.parent_kind == "assets":+ yield from _iter_asset_parents(sess, url)+ else:+ yield from _iter_instigation_state_parents(sess, url)+++def _window_from_epoch_seconds(seconds: float, unit: WindowUnit | None) -> str | float:+ return str(int(seconds * 1000)) if unit == "millis_string" else seconds+++def _window_to_wire(value: str, unit: WindowUnit | None) -> str | float:+ return value if unit == "millis_string" else float(value)+++def _oldest_window_value(rows: list[dict[str, Any]], fan_out: DagsterCloudFanOutConfig) -> str | None:+ """The oldest window value on a page, which bounds the next (older) page.++ Dagster applies these bounds strictly (`timestamp < before`), so paging on the page's minimum+ neither re-reads it nor skips past it — with the one exception of events sharing that exact+ instant across a page boundary, which the API gives no way to disambiguate.+ """+ assert fan_out.window_row_field is not None+ values = [row.get(fan_out.window_row_field) for row in rows]+ present = [value for value in values if value is not None]+ if not present:+ return None+ try:+ if fan_out.window_unit == "millis_string":+ return str(min(int(value) for value in present))+ return str(min(float(value) for value in present))+ except (TypeError, ValueError):+ return None+++def _inject_parent_fields(+ row: dict[str, Any], parent: dict[str, Any], fan_out: DagsterCloudFanOutConfig+) -> dict[str, Any]:+ if not fan_out.include_from_parent:+ return row+ enriched = dict(row)+ for parent_key in fan_out.include_from_parent:+ enriched[parent_key] = parent.get(parent_key)+ return enriched+++def _iter_child_pages(+ sess: requests.Session,+ url: str,+ endpoint_config: DagsterCloudEndpointConfig,+ parent: dict[str, Any],+ watermark_epoch: float | None,+ start_window: str,+) -> Iterator[tuple[list[dict[str, Any]], str | None]]:+ """Yield one parent's child rows, page by page, with the window bound that follows each page."""+ fan_out = endpoint_config.fan_out+ assert fan_out is not None++ before_variable = fan_out.before_variable++ variables: dict[str, Any] = {"limit": DAGSTER_CLOUD_PAGE_SIZE}+ for variable_name, parent_key in fan_out.parent_variables.items():+ variables[variable_name] = parent.get(parent_key)+ if fan_out.after_variable is not None and watermark_epoch is not None:+ variables[fan_out.after_variable] = _window_from_epoch_seconds(watermark_epoch, fan_out.window_unit)+ if before_variable is not None and start_window:+ variables[before_variable] = _window_to_wire(start_window, fan_out.window_unit)++ previous_window = start_window++ while True:+ payload = _execute_query(sess, url, endpoint_config.query, variables)+ extracted = _extract_rows(payload, endpoint_config)+ if extracted is None:+ return+ _, rows = extracted++ next_window: str | None = None+ if before_variable is not None and len(rows) >= DAGSTER_CLOUD_PAGE_SIZE:+ next_window = _oldest_window_value(rows, fan_out)++ yield (+ [_inject_parent_fields(_normalize_row(row, endpoint_config), parent, fan_out) for row in rows],+ next_window,+ )++ if next_window is None or before_variable is None:+ return+ # The walk is otherwise unbounded, and only a strictly older bound guarantees it ends.+ # Truncating a parent instead would be silent data loss: sort_mode is "desc", so the+ # watermark commits at the top of this parent's history and the skipped events below it+ # would never be requested again.+ if next_window == previous_window:+ raise Exception(f"Dagster Cloud {endpoint_config.name}: page window did not advance past {next_window}")+ previous_window = next_window+ variables[before_variable] = _window_to_wire(next_window, fan_out.window_unit)+++def _fetch_parent_batch(+ sess: requests.Session,+ url: str,+ endpoint_config: DagsterCloudEndpointConfig,+ batch: list[dict[str, Any]],+) -> Iterator[list[dict[str, Any]]]:+ fan_out = endpoint_config.fan_out+ assert fan_out is not None and fan_out.batch_variable is not None and fan_out.batch_field is not None++ variables = {fan_out.batch_variable: [parent.get(fan_out.batch_field) for parent in batch]}+ payload = _execute_query(sess, url, endpoint_config.query, variables)+ extracted = _extract_rows(payload, endpoint_config)+ if extracted is None:+ return+ _, rows = extracted+ yield [_normalize_row(row, endpoint_config) for row in rows]+++def _iter_fanout_rows(+ sess: requests.Session,+ url: str,+ endpoint_config: DagsterCloudEndpointConfig,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[DagsterCloudResumeConfig],+ resume_config: DagsterCloudResumeConfig | None,+ watermark_epoch: float | None,+) -> Iterator[list[dict[str, Any]]]:+ fan_out = endpoint_config.fan_out+ assert fan_out is not None++ parents_done = resume_config.parents_done if resume_config else 0+ start_window = resume_config.window_cursor if resume_config else ""+ if parents_done or start_window:+ logger.debug(f"Dagster Cloud: resuming {endpoint_config.name} after {parents_done} parents")++ # Kept live past the loop so a trailing partial batch can checkpoint the parents it covered.+ index = parents_done - 1+ batch: list[dict[str, Any]] = []++ for index, parent in enumerate(_iter_parents(sess, url, fan_out)):+ if index < parents_done:+ continue++ if fan_out.batch_variable is not None:+ batch.append(parent)+ if len(batch) >= fan_out.batch_size:+ yield from _fetch_parent_batch(sess, url, endpoint_config, batch)+ resumable_source_manager.save_state(DagsterCloudResumeConfig(parents_done=index + 1))+ batch = []+ continue++ # Only the parent the saved state stopped inside resumes mid-window; the ones after it+ # start from their newest event.+ window = start_window if index == parents_done else ""+ for page, next_window in _iter_child_pages(sess, url, endpoint_config, parent, watermark_epoch, window):+ yield page+ # Save after yielding, so a crash re-reads the last page instead of skipping it.+ if next_window is not None:+ resumable_source_manager.save_state(+ DagsterCloudResumeConfig(parents_done=index, window_cursor=next_window)+ )+ resumable_source_manager.save_state(DagsterCloudResumeConfig(parents_done=index + 1))++ if batch:+ yield from _fetch_parent_batch(sess, url, endpoint_config, batch)+ resumable_source_manager.save_state(DagsterCloudResumeConfig(parents_done=index + 1))+++def _make_fanout_request(+ organization: str,+ deployment: str,+ api_token: str,+ endpoint_name: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[DagsterCloudResumeConfig],+ watermark_epoch: float | None = None,+) -> Iterator[list[dict[str, Any]]]:+ endpoint_config = DAGSTER_CLOUD_ENDPOINTS.get(endpoint_name)+ if not endpoint_config or endpoint_config.fan_out is None:+ raise ValueError(f"Unknown Dagster Cloud fan-out endpoint: {endpoint_name}")++ url = build_graphql_url(organization, deployment)+ sess = _make_session(api_token)+ resume_config = resumable_source_manager.load_state()++ try:+ yield from _iter_fanout_rows(+ sess, url, endpoint_config, logger, resumable_source_manager, resume_config, watermark_epoch+ )finally:sess.close()@@ -261,14 +563,30 @@ def dagster_cloud_source(raise ValueError(f"Unknown Dagster Cloud endpoint: {endpoint_name}")def get_rows() -> Iterator[list[dict[str, Any]]]:- runs_filter = None+ watermark_epoch = Noneif (endpoint_config.supports_incrementaland should_use_incremental_fieldand db_incremental_field_last_value is not None):- last_value_epoch = _to_epoch_seconds(db_incremental_field_last_value)- runs_filter = _build_runs_filter(incremental_field, last_value_epoch)+ watermark_epoch = _to_epoch_seconds(db_incremental_field_last_value)++ if endpoint_config.fan_out is not None:+ if watermark_epoch is not None:+ logger.debug(f"Dagster Cloud: incremental sync for {endpoint_name} after {watermark_epoch}")+ yield from _make_fanout_request(+ organization=organization,+ deployment=deployment,+ api_token=api_token,+ endpoint_name=endpoint_name,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ watermark_epoch=watermark_epoch,+ )+ return++ runs_filter = _build_runs_filter(incremental_field, watermark_epoch)+ if runs_filter is not None:logger.debug(f"Dagster Cloud: incremental sync for {endpoint_name} with filter {runs_filter}")yield from _make_paginated_request(diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dagster_cloud/queries.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dagster_cloud/queries.pyindex bc37a0b8053a..9ea8750add8f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/dagster_cloud/queries.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dagster_cloud/queries.py@@ -68,3 +68,264 @@ query PaginatedAssets($limit: Int!, $cursor: String) {... on PythonError { message }}}"""++# Fan-out parent walk: every schedule, sensor, instigation state and asset node is scoped to a+# code location + repository, and only `repositoriesOrError` enumerates them.+REPOSITORIES_QUERY = """+query Repositories {+ repositoriesOrError {+ __typename+ ... on RepositoryConnection {+ nodes {+ id+ name+ location { name }+ }+ }+ ... on RepositoryNotFoundError { message }+ ... on PythonError { message }+ }+}"""++SCHEDULES_QUERY = """+query RepositorySchedules($repositoryName: String!, $repositoryLocationName: String!) {+ schedulesOrError(+ repositorySelector: {+ repositoryName: $repositoryName+ repositoryLocationName: $repositoryLocationName+ }+ ) {+ __typename+ ... on Schedules {+ results {+ id+ name+ cronSchedule+ pipelineName+ mode+ executionTimezone+ description+ defaultStatus+ scheduleState { id selectorId status instigationType }+ assetSelection { assetSelectionString assetKeys { path } }+ tags { key value }+ }+ }+ ... on RepositoryNotFoundError { message }+ ... on PythonError { message }+ }+}"""++SENSORS_QUERY = """+query RepositorySensors($repositoryName: String!, $repositoryLocationName: String!) {+ sensorsOrError(+ repositorySelector: {+ repositoryName: $repositoryName+ repositoryLocationName: $repositoryLocationName+ }+ ) {+ __typename+ ... on Sensors {+ results {+ id+ name+ jobOriginId+ sensorType+ description+ defaultStatus+ minIntervalSeconds+ targets { pipelineName mode }+ sensorState { id selectorId status instigationType }+ assetSelection { assetSelectionString assetKeys { path } }+ metadata { assetKeys { path } }+ tags { key value }+ }+ }+ ... on RepositoryNotFoundError { message }+ ... on PythonError { message }+ }+}"""++INSTIGATION_STATES_QUERY = """+query RepositoryInstigationStates($repositoryID: String!) {+ instigationStatesOrError(repositoryID: $repositoryID) {+ __typename+ ... on InstigationStates {+ results {+ id+ selectorId+ name+ instigationType+ status+ repositoryName+ repositoryLocationName+ runsCount+ typeSpecificData {+ __typename+ ... on ScheduleData { cronSchedule startTimestamp }+ ... on SensorData { lastTickTimestamp lastRunKey lastCursor }+ }+ }+ }+ ... on PythonError { message }+ }+}"""++# `instigationStateOrError` takes the state's own CompoundID as `id`, which disambiguates a+# schedule and a sensor that share a name inside one repository.+INSTIGATION_TICKS_QUERY = """+query InstigationTicks(+ $repositoryName: String!+ $repositoryLocationName: String!+ $instigationName: String!+ $instigationStateId: String+ $limit: Int!+ $beforeTimestamp: Float+ $afterTimestamp: Float+) {+ instigationStateOrError(+ instigationSelector: {+ repositoryName: $repositoryName+ repositoryLocationName: $repositoryLocationName+ name: $instigationName+ }+ id: $instigationStateId+ ) {+ __typename+ ... on InstigationState {+ ticks(limit: $limit, beforeTimestamp: $beforeTimestamp, afterTimestamp: $afterTimestamp) {+ id+ tickId+ status+ timestamp+ endTimestamp+ runIds+ runKeys+ originRunIds+ skipReason+ cursor+ instigationType+ requestedAssetMaterializationCount+ requestedAssetKeys { path }+ error { message }+ }+ }+ ... on InstigationStateNotFoundError { message }+ ... on PythonError { message }+ }+}"""++ASSET_NODES_QUERY = """+query AssetNodes($assetKeys: [AssetKeyInput!]) {+ assetNodes(assetKeys: $assetKeys) {+ id+ assetKey { path }+ groupName+ description+ computeKind+ opName+ opNames+ jobNames+ kinds+ isPartitioned+ isObservable+ isMaterializable+ isExecutable+ owners {+ __typename+ ... on UserAssetOwner { email }+ ... on TeamAssetOwner { team }+ }+ dependencyKeys { path }+ dependedByKeys { path }+ freshnessPolicy { maximumLagMinutes cronSchedule cronScheduleTimezone }+ autoMaterializePolicy { policyType maxMaterializationsPerMinute }+ partitionDefinition { description type name }+ tags { key value }+ repository { id name location { name } }+ }+}"""++# Only the scalar-valued members are unwrapped; every other entry still lands with its+# __typename and label so the row records that metadata was attached.+_METADATA_ENTRY_FRAGMENT = """+fragment MetadataEntryFields on MetadataEntry {+ __typename+ label+ description+ ... on TextMetadataEntry { text }+ ... on UrlMetadataEntry { url }+ ... on PathMetadataEntry { path }+ ... on IntMetadataEntry { intValue intRepr }+ ... on FloatMetadataEntry { floatValue }+ ... on BoolMetadataEntry { boolValue }+ ... on JsonMetadataEntry { jsonString }+ ... on MarkdownMetadataEntry { mdStr }+ ... on TimestampMetadataEntry { timestamp }+}"""++ASSET_MATERIALIZATIONS_QUERY = (+ """+query AssetMaterializations(+ $assetKeyPath: [String!]!+ $limit: Int!+ $beforeTimestampMillis: String+ $afterTimestampMillis: String+) {+ assetOrError(assetKey: { path: $assetKeyPath }) {+ __typename+ ... on Asset {+ assetMaterializations(+ limit: $limit+ beforeTimestampMillis: $beforeTimestampMillis+ afterTimestampMillis: $afterTimestampMillis+ ) {+ runId+ timestamp+ stepKey+ partition+ label+ description+ assetKey { path }+ tags { key value }+ metadataEntries { ...MetadataEntryFields }+ }+ }+ ... on AssetNotFoundError { message }+ }+}"""+ + _METADATA_ENTRY_FRAGMENT+)++ASSET_OBSERVATIONS_QUERY = (+ """+query AssetObservations(+ $assetKeyPath: [String!]!+ $limit: Int!+ $beforeTimestampMillis: String+ $afterTimestampMillis: String+) {+ assetOrError(assetKey: { path: $assetKeyPath }) {+ __typename+ ... on Asset {+ assetObservations(+ limit: $limit+ beforeTimestampMillis: $beforeTimestampMillis+ afterTimestampMillis: $afterTimestampMillis+ ) {+ runId+ timestamp+ stepKey+ partition+ label+ description+ assetKey { path }+ tags { key value }+ metadataEntries { ...MetadataEntryFields }+ }+ }+ ... on AssetNotFoundError { message }+ }+}"""+ + _METADATA_ENTRY_FRAGMENT+)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dagster_cloud/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dagster_cloud/settings.pyindex c3ae58e54924..6180377a870f 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/dagster_cloud/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dagster_cloud/settings.py@@ -1,11 +1,21 @@-from dataclasses import dataclass, field+from dataclasses import fieldfrom typing import Literal+from posthog.dataclasses import frozen+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SortModefrom products.warehouse_sources.backend.temporal.data_imports.sources.dagster_cloud.queries import (+ ASSET_MATERIALIZATIONS_QUERY,+ ASSET_NODES_QUERY,+ ASSET_OBSERVATIONS_QUERY,ASSETS_QUERY,BACKFILLS_QUERY,+ INSTIGATION_STATES_QUERY,+ INSTIGATION_TICKS_QUERY,+ REPOSITORIES_QUERY,RUNS_QUERY,+ SCHEDULES_QUERY,+ SENSORS_QUERY,)from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType@@ -17,6 +27,13 @@ DAGSTER_CLOUD_PAGE_SIZE = 100# "connection" -> next cursor is the connection object's own `cursor` field (assetsOrError).CursorMode = Literal["row", "connection"]+# Which collection a fan-out child iterates one request at a time.+ParentKind = Literal["repositories", "assets", "instigation_states"]++# Wire type of a windowed child's timestamp bounds: assetMaterializations/assetObservations take+# epoch milliseconds as a string, InstigationState.ticks takes epoch seconds as a float.+WindowUnit = Literal["millis_string", "seconds_float"]+def _incremental_datetime_field(name: str) -> IncrementalField:return {@@ -27,23 +44,54 @@ def _incremental_datetime_field(name: str) -> IncrementalField:}-@dataclass+@frozen+class DagsterCloudFanOutConfig:+ parent_kind: ParentKind+ # GraphQL variable name -> parent descriptor key. One request per parent.+ parent_variables: dict[str, str] = field(default_factory=dict)+ # Parent descriptor keys copied onto every child row. Fan-out children aggregate rows from+ # every parent, so the row has to carry its parent's identity for the primary key to stay+ # unique across the whole table.+ include_from_parent: list[str] = field(default_factory=list)+ # Batched form: one request per `batch_size` parents, collecting each parent's `batch_field`+ # into the `batch_variable` list. Mutually exclusive with `parent_variables`.+ batch_variable: str | None = None+ batch_field: str | None = None+ batch_size: int = 1+ # Windowed children have no cursor, so they page backwards: `before_variable` is set to the+ # oldest `window_row_field` value the previous page carried, and `after_variable` carries the+ # incremental watermark. Unset for children that return one unpaged list per parent.+ before_variable: str | None = None+ after_variable: str | None = None+ window_row_field: str | None = None+ window_unit: WindowUnit | None = None+++@frozenclass DagsterCloudEndpointConfig:name: strquery: str# Root query field wrapping the union result (e.g. "runsOrError").response_field: str- # __typename of the success member of the OrError union.- success_typename: str- # Key on the success member holding the list of rows ("results" or "nodes").- results_key: str- cursor_mode: CursorMode+ # __typename of the success member of the OrError union, or None when the root field returns+ # the row list directly (assetNodes).+ success_typename: str | None = None+ # Key on the success member holding the list of rows ("results", "nodes", "ticks").+ results_key: str | None = None+ # __typename values meaning "this parent is gone" rather than "the sync failed". The parent+ # list is read before the children, so a parent deleted mid-sync must be skipped.+ skip_typenames: tuple[str, ...] = ()+ # Set for top-level endpoints paginated by a cursor; None for fan-out children.+ cursor_mode: CursorMode | None = Noneprimary_keys: list[str] = field(default_factory=lambda: ["id"])# Row fields carrying Dagster epoch-seconds floats, normalized to ISO-8601 UTC strings so# datetime partitioning and the incremental watermark can read them like every other source.timestamp_fields: list[str] = field(default_factory=list)+ # Same, for row fields carrying epoch milliseconds as a string (the asset event resolvers).+ millis_timestamp_fields: list[str] = field(default_factory=list)# For cursor_mode="row": which row field to use as the next-page cursor.cursor_row_field: str | None = None+ fan_out: DagsterCloudFanOutConfig | None = Noneincremental_fields: list[IncrementalField] = field(default_factory=list)supports_incremental: bool = False# Stable creation-time field to partition by (never an updated-at style field).@@ -101,6 +149,161 @@ DAGSTER_CLOUD_ENDPOINTS: dict[str, DagsterCloudEndpointConfig] = {primary_keys=["id"],# Catalog snapshot with no timestamp to filter or partition on — full refresh.),+ "schedules": DagsterCloudEndpointConfig(+ name="schedules",+ query=SCHEDULES_QUERY,+ response_field="schedulesOrError",+ success_typename="Schedules",+ results_key="results",+ skip_typenames=("RepositoryNotFoundError",),+ # Definition snapshot with no event timestamp — full refresh.+ primary_keys=["repositoryLocationName", "repositoryName", "name"],+ fan_out=DagsterCloudFanOutConfig(+ parent_kind="repositories",+ parent_variables={+ "repositoryName": "repositoryName",+ "repositoryLocationName": "repositoryLocationName",+ },+ include_from_parent=["repositoryName", "repositoryLocationName"],+ ),+ ),+ "sensors": DagsterCloudEndpointConfig(+ name="sensors",+ query=SENSORS_QUERY,+ response_field="sensorsOrError",+ success_typename="Sensors",+ results_key="results",+ skip_typenames=("RepositoryNotFoundError",),+ primary_keys=["repositoryLocationName", "repositoryName", "name"],+ fan_out=DagsterCloudFanOutConfig(+ parent_kind="repositories",+ parent_variables={+ "repositoryName": "repositoryName",+ "repositoryLocationName": "repositoryLocationName",+ },+ include_from_parent=["repositoryName", "repositoryLocationName"],+ ),+ ),+ "instigation_states": DagsterCloudEndpointConfig(+ name="instigation_states",+ query=INSTIGATION_STATES_QUERY,+ response_field="instigationStatesOrError",+ success_typename="InstigationStates",+ results_key="results",+ # A schedule and a sensor may share a name inside one repository, so the type belongs in+ # the key. repositoryName / repositoryLocationName are native fields on the row.+ primary_keys=["repositoryLocationName", "repositoryName", "instigationType", "name"],+ fan_out=DagsterCloudFanOutConfig(+ parent_kind="repositories",+ parent_variables={"repositoryID": "repositoryId"},+ ),+ ),+ "instigation_ticks": DagsterCloudEndpointConfig(+ name="instigation_ticks",+ query=INSTIGATION_TICKS_QUERY,+ response_field="instigationStateOrError",+ success_typename="InstigationState",+ results_key="ticks",+ skip_typenames=("InstigationStateNotFoundError",),+ primary_keys=["instigationSelectorId", "tickId"],+ timestamp_fields=["timestamp", "endTimestamp"],+ # InstigationState.ticks takes a real afterTimestamp filter, so an incremental run only+ # fetches ticks newer than the watermark. A tick's timestamp never moves once written.+ incremental_fields=[_incremental_datetime_field("timestamp")],+ supports_incremental=True,+ partition_key="timestamp",+ # Rows arrive newest-first within a parent and in parent order across the fan-out, so the+ # stream is not ascending. "desc" also holds the watermark back until the whole fan-out+ # finished, which is the only safe point once rows stop arriving in time order.+ sort_mode="desc",+ fan_out=DagsterCloudFanOutConfig(+ parent_kind="instigation_states",+ parent_variables={+ "repositoryName": "repositoryName",+ "repositoryLocationName": "repositoryLocationName",+ "instigationName": "instigationName",+ "instigationStateId": "instigationStateId",+ },+ include_from_parent=[+ "repositoryName",+ "repositoryLocationName",+ "instigationName",+ "instigationSelectorId",+ ],+ before_variable="beforeTimestamp",+ after_variable="afterTimestamp",+ window_row_field="timestamp",+ window_unit="seconds_float",+ ),+ ),+ "asset_nodes": DagsterCloudEndpointConfig(+ name="asset_nodes",+ query=ASSET_NODES_QUERY,+ response_field="assetNodes",+ # assetNodes returns [AssetNode!]! directly rather than an OrError union.+ primary_keys=["id"],+ fan_out=DagsterCloudFanOutConfig(+ parent_kind="assets",+ # assetNodes with no argument would return every definition, with all its metadata, in+ # one unbounded response; batching the keys keeps each response a page-sized chunk.+ batch_variable="assetKeys",+ batch_field="assetKeyInput",+ batch_size=DAGSTER_CLOUD_PAGE_SIZE,+ ),+ ),+ "asset_materializations": DagsterCloudEndpointConfig(+ name="asset_materializations",+ query=ASSET_MATERIALIZATIONS_QUERY,+ response_field="assetOrError",+ success_typename="Asset",+ results_key="assetMaterializations",+ skip_typenames=("AssetNotFoundError",),+ # MaterializationEvent exposes no id, so the key is the event's natural identity. A run+ # step may report the same asset and partition more than once, and only the millisecond+ # timestamp separates those, so two reports inside one millisecond would collapse.+ primary_keys=["assetId", "runId", "timestamp", "partition", "stepKey"],+ millis_timestamp_fields=["timestamp"],+ # afterTimestampMillis is a genuine server-side filter on the event log.+ incremental_fields=[_incremental_datetime_field("timestamp")],+ supports_incremental=True,+ partition_key="timestamp",+ sort_mode="desc",+ fan_out=DagsterCloudFanOutConfig(+ parent_kind="assets",+ parent_variables={"assetKeyPath": "assetKeyPath"},+ include_from_parent=["assetId"],+ before_variable="beforeTimestampMillis",+ after_variable="afterTimestampMillis",+ window_row_field="timestamp",+ window_unit="millis_string",+ ),+ ),+ "asset_observations": DagsterCloudEndpointConfig(+ name="asset_observations",+ query=ASSET_OBSERVATIONS_QUERY,+ response_field="assetOrError",+ success_typename="Asset",+ results_key="assetObservations",+ skip_typenames=("AssetNotFoundError",),+ primary_keys=["assetId", "runId", "timestamp", "partition", "stepKey"],+ millis_timestamp_fields=["timestamp"],+ incremental_fields=[_incremental_datetime_field("timestamp")],+ supports_incremental=True,+ partition_key="timestamp",+ sort_mode="desc",+ # Only observable source assets emit observations, and most deployments define none, so+ # syncing this by default would spend a full fan-out over every asset to find nothing.+ should_sync_default=False,+ fan_out=DagsterCloudFanOutConfig(+ parent_kind="assets",+ parent_variables={"assetKeyPath": "assetKeyPath"},+ include_from_parent=["assetId"],+ before_variable="beforeTimestampMillis",+ after_variable="afterTimestampMillis",+ window_row_field="timestamp",+ window_unit="millis_string",+ ),+ ),}ENDPOINTS = tuple(DAGSTER_CLOUD_ENDPOINTS.keys())@@ -108,3 +311,14 @@ ENDPOINTS = tuple(DAGSTER_CLOUD_ENDPOINTS.keys())INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {name: config.incremental_fields for name, config in DAGSTER_CLOUD_ENDPOINTS.items()}+++# Not a synced table: the fan-out parent walk that resolves every code location + repository a+# schedule, sensor, instigation state or asset definition is scoped to.+REPOSITORIES_PARENT_CONFIG = DagsterCloudEndpointConfig(+ name="_repositories",+ query=REPOSITORIES_QUERY,+ response_field="repositoriesOrError",+ success_typename="RepositoryConnection",+ results_key="nodes",+)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dagster_cloud/tests/test_dagster_cloud.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dagster_cloud/tests/test_dagster_cloud.pyindex bb0dc63078eb..7b0be3980247 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/dagster_cloud/tests/test_dagster_cloud.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dagster_cloud/tests/test_dagster_cloud.py@@ -1,9 +1,11 @@+import refrom collections.abc import Iterable+from dataclasses import replacefrom datetime import UTC, date, datetimefrom typing import Any, castimport pytest-from unittest.mock import MagicMock, patch+from unittest.mock import MagicMock, call, patchfrom parameterized import parameterized@@ -11,6 +13,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.dagster_clDagsterCloudResumeConfig,_build_runs_filter,_epoch_to_iso,+ _make_fanout_request,_make_paginated_request,_to_epoch_seconds,build_graphql_url,@@ -318,7 +321,431 @@ class TestValidateCredentials:class TestEndpointCatalog:- def test_only_runs_is_incremental(self) -> None:- # Backfills/assets have no server-side timestamp filter, so they must stay full-refresh.+ def test_incremental_endpoints_are_the_ones_with_server_side_filters(self) -> None:+ # RunsFilter.updatedAfter, InstigationState.ticks(afterTimestamp) and the asset event+ # resolvers' afterTimestampMillis genuinely filter server-side. Every other endpoint would+ # walk full history on an "incremental" run, so it must stay full-refresh.incremental = {name for name, cfg in DAGSTER_CLOUD_ENDPOINTS.items() if cfg.supports_incremental}- assert incremental == {"runs"}+ assert incremental == {"runs", "instigation_ticks", "asset_materializations", "asset_observations"}++ def test_fanout_primary_keys_carry_their_parent(self) -> None:+ # A fan-out child aggregates rows from every parent, so a key that is only unique per+ # parent seeds duplicates the merge then multi-matches on every later sync.+ for name, cfg in DAGSTER_CLOUD_ENDPOINTS.items():+ if cfg.fan_out is None or not cfg.fan_out.include_from_parent:+ continue+ assert set(cfg.fan_out.include_from_parent) & set(cfg.primary_keys), name+++def _with_batch_size(endpoint_name: str, batch_size: int) -> Any:+ endpoint_config = DAGSTER_CLOUD_ENDPOINTS[endpoint_name]+ assert endpoint_config.fan_out is not None+ return replace(endpoint_config, fan_out=replace(endpoint_config.fan_out, batch_size=batch_size))+++def _route(handlers: dict[str, Any]) -> tuple[Any, list[tuple[str, dict[str, Any]]]]:+ """Mock session.post, dispatching on the posted query's GraphQL operation name.++ A handler is one response reused for every call, or a list consumed in order. Every call is+ recorded so a test can assert what each hop of a fan-out actually sent.+ """+ calls: list[tuple[str, dict[str, Any]]] = []++ def side_effect(*_args: object, **kwargs: object) -> MagicMock:+ payload = cast(dict, kwargs["json"])+ match = re.search(r"query (\w+)", payload["query"])+ assert match is not None+ operation = match.group(1)+ variables = payload.get("variables") or {}+ # Copied: the paginators mutate one variables dict in place across a parent's pages.+ calls.append((operation, dict(variables)))++ handler = handlers[operation]+ return handler.pop(0) if isinstance(handler, list) else handler++ return side_effect, calls+++def _repositories_response(names: list[tuple[str, str, str]]) -> MagicMock:+ return _gql_response(+ "repositoriesOrError",+ {+ "__typename": "RepositoryConnection",+ "nodes": [+ {"id": repo_id, "name": name, "location": {"name": location}} for repo_id, name, location in names+ ],+ },+ )+++def _assets_page(ids: list[str], cursor: str | None) -> MagicMock:+ return _gql_response("assetsOrError", _assets_container(ids, cursor))+++def _materializations_response(timestamps_millis: list[str]) -> MagicMock:+ return _gql_response(+ "assetOrError",+ {+ "__typename": "Asset",+ "assetMaterializations": [+ {"runId": f"run-{ts}", "timestamp": ts, "stepKey": "step", "partition": None}+ for ts in timestamps_millis+ ],+ },+ )+++def _ticks_response(timestamps: list[float]) -> MagicMock:+ return _gql_response(+ "instigationStateOrError",+ {+ "__typename": "InstigationState",+ "ticks": [+ {"tickId": str(int(ts)), "status": "SUCCESS", "timestamp": ts, "endTimestamp": ts + 1}+ for ts in timestamps+ ],+ },+ )+++class TestRepositoryFanOut:+ @patch(f"{MODULE}.make_tracked_session")+ def test_one_child_request_per_repository_with_parent_fields_injected(self, mock_session_cls: MagicMock) -> None:+ session = MagicMock()+ session.post.side_effect, calls = _route(+ {+ "Repositories": _repositories_response([("r1", "repo_a", "loc_a"), ("r2", "repo_b", "loc_b")]),+ "RepositorySchedules": [+ _gql_response("schedulesOrError", {"__typename": "Schedules", "results": [{"name": "daily"}]}),+ _gql_response("schedulesOrError", {"__typename": "Schedules", "results": [{"name": "hourly"}]}),+ ],+ }+ )+ mock_session_cls.return_value = session+ manager = _manager()++ pages = list(_make_fanout_request("org", "prod", "tok", "schedules", MagicMock(), manager))++ rows = [row for page in pages for row in page]+ # Each row has to name its repository: the primary key is only unique with it.+ assert rows == [+ {"name": "daily", "repositoryName": "repo_a", "repositoryLocationName": "loc_a"},+ {"name": "hourly", "repositoryName": "repo_b", "repositoryLocationName": "loc_b"},+ ]+ child_variables = [variables for operation, variables in calls if operation == "RepositorySchedules"]+ assert [v["repositoryName"] for v in child_variables] == ["repo_a", "repo_b"]+ # One parent finished per checkpoint, so a resume restarts at the next repository.+ assert manager.save_state.call_args_list == [+ call(DagsterCloudResumeConfig(parents_done=1)),+ call(DagsterCloudResumeConfig(parents_done=2)),+ ]++ @patch(f"{MODULE}.make_tracked_session")+ def test_repository_deleted_mid_sync_is_skipped(self, mock_session_cls: MagicMock) -> None:+ # The parent list is read before the children, so a repository removed in between must+ # not fail the whole sync.+ session = MagicMock()+ session.post.side_effect, _ = _route(+ {+ "Repositories": _repositories_response([("r1", "repo_a", "loc_a"), ("r2", "repo_b", "loc_b")]),+ "RepositorySensors": [+ _gql_response("sensorsOrError", {"__typename": "RepositoryNotFoundError", "message": "gone"}),+ _gql_response("sensorsOrError", {"__typename": "Sensors", "results": [{"name": "s"}]}),+ ],+ }+ )+ mock_session_cls.return_value = session++ pages = list(_make_fanout_request("org", "prod", "tok", "sensors", MagicMock(), _manager()))++ assert [row["name"] for page in pages for row in page] == ["s"]++ @patch(f"{MODULE}.make_tracked_session")+ def test_resume_skips_finished_parents(self, mock_session_cls: MagicMock) -> None:+ session = MagicMock()+ session.post.side_effect, calls = _route(+ {+ "Repositories": _repositories_response([("r1", "repo_a", "loc_a"), ("r2", "repo_b", "loc_b")]),+ "RepositorySchedules": _gql_response("schedulesOrError", {"__typename": "Schedules", "results": []}),+ }+ )+ mock_session_cls.return_value = session++ list(+ _make_fanout_request(+ "org",+ "prod",+ "tok",+ "schedules",+ MagicMock(),+ _manager(DagsterCloudResumeConfig(parents_done=1)),+ )+ )++ child_variables = [variables for operation, variables in calls if operation == "RepositorySchedules"]+ assert [v["repositoryName"] for v in child_variables] == ["repo_b"]+++class TestTwoLevelFanOut:+ @patch(f"{MODULE}.DAGSTER_CLOUD_PAGE_SIZE", 2)+ @patch(f"{MODULE}.make_tracked_session")+ def test_tick_parents_resolve_through_repositories(self, mock_session_cls: MagicMock) -> None:+ # instigation_ticks fans out over instigation states, which themselves only exist per+ # repository — so the walk is repositories -> states -> ticks.+ session = MagicMock()+ session.post.side_effect, calls = _route(+ {+ "Repositories": _repositories_response([("repo-id-1", "repo_a", "loc_a")]),+ "RepositoryInstigationStates": _gql_response(+ "instigationStatesOrError",+ {+ "__typename": "InstigationStates",+ "results": [+ {+ "id": "compound-id",+ "selectorId": "selector-1",+ "name": "daily",+ "instigationType": "SCHEDULE",+ "repositoryName": "repo_a",+ "repositoryLocationName": "loc_a",+ }+ ],+ },+ ),+ "InstigationTicks": _ticks_response([1704067200.0]),+ }+ )+ mock_session_cls.return_value = session++ pages = list(_make_fanout_request("org", "prod", "tok", "instigation_ticks", MagicMock(), _manager()))++ state_variables = next(v for op, v in calls if op == "RepositoryInstigationStates")+ assert state_variables == {"repositoryID": "repo-id-1"}+ tick_variables = next(v for op, v in calls if op == "InstigationTicks")+ # The state's compound id disambiguates a schedule and a sensor sharing a name.+ assert tick_variables["instigationStateId"] == "compound-id"+ assert tick_variables["instigationName"] == "daily"++ row = pages[0][0]+ assert row["instigationSelectorId"] == "selector-1"+ # Tick timestamps are epoch-seconds floats, normalized like every other Dagster timestamp.+ assert row["timestamp"] == ISO_2024++ @patch(f"{MODULE}.make_tracked_session")+ def test_incremental_ticks_send_seconds_float_watermark(self, mock_session_cls: MagicMock) -> None:+ session = MagicMock()+ session.post.side_effect, calls = _route(+ {+ "Repositories": _repositories_response([("repo-id-1", "repo_a", "loc_a")]),+ "RepositoryInstigationStates": _gql_response(+ "instigationStatesOrError",+ {+ "__typename": "InstigationStates",+ "results": [{"id": "c", "selectorId": "s", "name": "daily"}],+ },+ ),+ "InstigationTicks": _ticks_response([]),+ }+ )+ mock_session_cls.return_value = session++ response = dagster_cloud_source(+ organization="org",+ deployment="prod",+ api_token="tok",+ endpoint_name="instigation_ticks",+ logger=MagicMock(),+ resumable_source_manager=_manager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2024, 1, 1, tzinfo=UTC),+ incremental_field="timestamp",+ )+ list(cast(Iterable[Any], response.items()))++ tick_variables = next(v for op, v in calls if op == "InstigationTicks")+ # ticks(afterTimestamp:) is a Float of epoch seconds, not the asset resolvers' millis string.+ assert tick_variables["afterTimestamp"] == EPOCH_2024+++class TestAssetEventFanOut:+ @patch(f"{MODULE}.DAGSTER_CLOUD_PAGE_SIZE", 2)+ @patch(f"{MODULE}.make_tracked_session")+ def test_pages_backwards_on_the_oldest_timestamp(self, mock_session_cls: MagicMock) -> None:+ # assetMaterializations has no cursor: the only way to reach older events is to lower+ # beforeTimestampMillis to the oldest timestamp the last page carried.+ session = MagicMock()+ session.post.side_effect, calls = _route(+ {+ "PaginatedAssets": _assets_page(["a1"], cursor=None),+ "AssetMaterializations": [+ _materializations_response(["1700000002000", "1700000001000"]),+ _materializations_response(["1700000000000"]),+ ],+ }+ )+ mock_session_cls.return_value = session+ manager = _manager()++ pages = list(_make_fanout_request("org", "prod", "tok", "asset_materializations", MagicMock(), manager))++ event_variables = [v for op, v in calls if op == "AssetMaterializations"]+ assert "beforeTimestampMillis" not in event_variables[0]+ assert event_variables[1]["beforeTimestampMillis"] == "1700000001000"+ assert event_variables[0]["assetKeyPath"] == ["a1"]++ rows = [row for page in pages for row in page]+ assert len(rows) == 3+ assert all(row["assetId"] == "a1" for row in rows)+ # Asset events report epoch milliseconds as a string, unlike runs' epoch-seconds floats.+ assert rows[0]["timestamp"] == "2023-11-14T22:13:22.000000+00:00"+ # Checkpointed mid-parent, then once the parent finished.+ assert manager.save_state.call_args_list == [+ call(DagsterCloudResumeConfig(parents_done=0, window_cursor="1700000001000")),+ call(DagsterCloudResumeConfig(parents_done=1)),+ ]++ @patch(f"{MODULE}.DAGSTER_CLOUD_PAGE_SIZE", 2)+ @patch(f"{MODULE}.make_tracked_session")+ def test_a_window_that_does_not_advance_fails_the_sync(self, mock_session_cls: MagicMock) -> None:+ # An API that ignored beforeTimestampMillis would replay one page forever. Failing beats+ # truncating: sort_mode is "desc", so a silently short parent still commits a watermark+ # above the events it skipped, and no later sync would ask for them.+ session = MagicMock()+ page = _materializations_response(["1700000001000", "1700000001000"])+ session.post.side_effect, _ = _route(+ {+ "PaginatedAssets": _assets_page(["a1"], cursor=None),+ "AssetMaterializations": [page, page],+ }+ )+ mock_session_cls.return_value = session++ with pytest.raises(Exception, match="page window did not advance"):+ list(_make_fanout_request("org", "prod", "tok", "asset_materializations", MagicMock(), _manager()))++ @patch(f"{MODULE}.make_tracked_session")+ def test_incremental_sends_millis_string_watermark(self, mock_session_cls: MagicMock) -> None:+ session = MagicMock()+ session.post.side_effect, calls = _route(+ {+ "PaginatedAssets": _assets_page(["a1"], cursor=None),+ "AssetMaterializations": _materializations_response([]),+ }+ )+ mock_session_cls.return_value = session++ response = dagster_cloud_source(+ organization="org",+ deployment="prod",+ api_token="tok",+ endpoint_name="asset_materializations",+ logger=MagicMock(),+ resumable_source_manager=_manager(),+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2024, 1, 1, tzinfo=UTC),+ incremental_field="timestamp",+ )+ list(cast(Iterable[Any], response.items()))++ event_variables = next(v for op, v in calls if op == "AssetMaterializations")+ assert event_variables["afterTimestampMillis"] == "1704067200000"++ @patch(f"{MODULE}.make_tracked_session")+ def test_full_refresh_omits_the_watermark(self, mock_session_cls: MagicMock) -> None:+ session = MagicMock()+ session.post.side_effect, calls = _route(+ {+ "PaginatedAssets": _assets_page(["a1"], cursor=None),+ "AssetMaterializations": _materializations_response([]),+ }+ )+ mock_session_cls.return_value = session++ response = dagster_cloud_source(+ organization="org",+ deployment="prod",+ api_token="tok",+ endpoint_name="asset_materializations",+ logger=MagicMock(),+ resumable_source_manager=_manager(),+ should_use_incremental_field=False,+ db_incremental_field_last_value=datetime(2024, 1, 1, tzinfo=UTC),+ )+ list(cast(Iterable[Any], response.items()))++ event_variables = next(v for op, v in calls if op == "AssetMaterializations")+ assert "afterTimestampMillis" not in event_variables++ @patch(f"{MODULE}.make_tracked_session")+ def test_asset_deleted_mid_sync_is_skipped(self, mock_session_cls: MagicMock) -> None:+ session = MagicMock()+ session.post.side_effect, _ = _route(+ {+ "PaginatedAssets": _assets_page(["a1"], cursor=None),+ "AssetObservations": _gql_response(+ "assetOrError", {"__typename": "AssetNotFoundError", "message": "gone"}+ ),+ }+ )+ mock_session_cls.return_value = session++ pages = list(_make_fanout_request("org", "prod", "tok", "asset_observations", MagicMock(), _manager()))++ assert [row for page in pages for row in page] == []+++class TestBatchedFanOut:+ @patch(f"{MODULE}.DAGSTER_CLOUD_PAGE_SIZE", 2)+ @patch.dict(DAGSTER_CLOUD_ENDPOINTS, {"asset_nodes": _with_batch_size("asset_nodes", 2)})+ @patch(f"{MODULE}.make_tracked_session")+ def test_asset_nodes_batches_keys_and_reads_a_bare_root_list(self, mock_session_cls: MagicMock) -> None:+ # assetNodes returns [AssetNode!]! rather than an OrError union, and takes the keys in+ # one list — so the walk batches parents instead of issuing a request each.+ session = MagicMock()+ node_response = MagicMock()+ node_response.status_code = 200+ node_response.ok = True+ node_response.json.return_value = {+ "data": {"assetNodes": [{"id": "n1", "groupName": "default"}, {"id": "n2", "groupName": "default"}]}+ }+ session.post.side_effect, calls = _route(+ {+ "PaginatedAssets": [_assets_page(["a1", "a2"], cursor="p2"), _assets_page(["a3"], cursor=None)],+ "AssetNodes": [node_response, node_response],+ }+ )+ mock_session_cls.return_value = session+ manager = _manager()++ pages = list(_make_fanout_request("org", "prod", "tok", "asset_nodes", MagicMock(), manager))++ node_variables = [v for op, v in calls if op == "AssetNodes"]+ # Parents are collected up to batch_size, so the first two assets go out together and+ # the trailing one follows in a final partial batch.+ assert node_variables[0]["assetKeys"] == [{"path": ["a1"]}, {"path": ["a2"]}]+ assert node_variables[1]["assetKeys"] == [{"path": ["a3"]}]+ assert len([row for page in pages for row in page]) == 4+ assert manager.save_state.call_args_list == [+ call(DagsterCloudResumeConfig(parents_done=2)),+ call(DagsterCloudResumeConfig(parents_done=3)),+ ]+++class TestFanOutRouting:+ def test_unknown_fanout_endpoint_raises(self) -> None:+ with pytest.raises(ValueError, match="Unknown Dagster Cloud fan-out endpoint"):+ list(_make_fanout_request("org", "prod", "tok", "runs", MagicMock(), _manager()))+++class TestCursorProgress:+ @patch(f"{MODULE}.DAGSTER_CLOUD_PAGE_SIZE", 2)+ @patch(f"{MODULE}.make_tracked_session")+ def test_a_cursor_that_does_not_advance_fails_the_sync(self, mock_session_cls: MagicMock) -> None:+ # Nothing else bounds the cursor walk, so a repeated cursor would re-request one page+ # until the activity timed out.+ session = MagicMock()+ session.post.return_value = _gql_response("runsOrError", _runs_container(["r1", "r1"]))+ mock_session_cls.return_value = session++ with pytest.raises(Exception, match="pagination cursor did not advance"):+ list(_make_paginated_request("org", "prod", "tok", "runs", MagicMock(), _manager()))diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dagster_cloud/tests/test_dagster_cloud_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dagster_cloud/tests/test_dagster_cloud_source.pyindex 9fb4473f3694..16dcb5f8b723 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/dagster_cloud/tests/test_dagster_cloud_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dagster_cloud/tests/test_dagster_cloud_source.py@@ -7,6 +7,7 @@ from products.warehouse_sources.backend.facade.source_config import (SourceFieldInputConfig,SourceFieldInputConfigType,)+from products.warehouse_sources.backend.temporal.data_imports.sources.dagster_cloud.settings import ENDPOINTSfrom products.warehouse_sources.backend.temporal.data_imports.sources.dagster_cloud.source import DagsterCloudSourceMODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.dagster_cloud.source"@@ -38,7 +39,6 @@ class TestDagsterCloudSourceConfig:class TestDagsterCloudSchemas:def test_schema_incremental_flags(self) -> None:schemas = {s.name: s for s in DagsterCloudSource().get_schemas(MagicMock(), team_id=1)}- assert set(schemas) == {"runs", "backfills", "assets"}assert schemas["runs"].supports_incremental is Trueassert {f["field"] for f in schemas["runs"].incremental_fields} == {"updateTime", "creationTime"}assert schemas["backfills"].supports_incremental is False@@ -53,8 +53,9 @@ class TestDagsterCloudSchemas:def test_documented_tables_render_for_public_docs(self) -> None:# lists_tables_without_credentials=True — the static catalog must surface in public docs.tables = {t["name"]: t for t in DagsterCloudSource().get_documented_tables()}- assert set(tables) == {"runs", "backfills", "assets"}- assert tables["runs"]["description"] # canonical description present+ assert set(tables) == set(ENDPOINTS)+ # Every table carries a curated description rather than falling back to the LLM.+ assert all(tables[name]["description"] for name in ENDPOINTS)assert "Incremental" in tables["runs"]["sync_methods"]assert "Incremental" not in tables["assets"]["sync_methods"]