: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 deployment, insights, run log and org tables (#105924)
Tom Owersc60b2fa28038
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 a5a611a8161b..ac156c205a27 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,8 +2228,10 @@ Note: Pulled the raw Postman collection JSON behind the published documenter lin## DagsterCloud — gaps-Today (10): `asset_materializations`, `asset_nodes`, `asset_observations`, `assets`, `backfills`,-`instigation_states`, `instigation_ticks`, `runs`, `schedules`, `sensors`+Today (18): `asset_materializations`, `asset_nodes`, `asset_observations`, `assets`, `backfills`,+`custom_roles`, `deployments`, `insights_asset_metrics`, `insights_deployment_metrics`,+`insights_job_metrics`, `instigation_states`, `instigation_ticks`, `run_logs`, `runs`, `schedules`,+`sensors`, `teams`, `users`Diffed against: <https://raw.githubusercontent.com/dagster-io/dagster/master/python_modules/libraries/dagster-dg-cli/dagster_dg_cli/cli/plus/schema.graphql>@@ -2237,17 +2239,23 @@ Diffed against: <https://raw.githubusercontent.com/dagster-io/dagster/master/pyt- [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)+- [x] `deployments / fullDeployments / branchDeployments` — lookup resolving which Dagster+ deployment each run and asset belongs to (high)+- [x] `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)- [ ] `repositoriesOrError / workspaceOrError (code locations, jobs, pipelines)` — lookup resolving repositoryOrigin and jobName already present on run rows (medium)-- [ ] `logsForRun (run event / step log)` — step-level timings, failures and retries inside runs we already sync (medium)-- [ ] `usersOrError / teamPermissions / customRoles` — org membership and role assignment for attributing runs and backfills to people (medium)+- [x] `logsForRun (run event / step log)` — step-level timings, failures and retries inside runs we already sync (medium)+- [x] `usersOrError / teamPermissions / customRoles` — org membership and role assignment for attributing runs and backfills to people (medium)- [ ] `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 `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: `deployments / fullDeployments / branchDeployments` land as one `deployments` table. All three resolvers return `DagsterCloudDeployment`, and `deployments` is the subset the caller can reach, so the table unions `fullDeployments` with `branchDeployments` and each row carries `isBranchDeployment`. `branchDeployments` takes a required limit and exposes no cursor, so the sync asks for 500 and logs a warning when a response comes back at that cap.++Note: the Insights tables are one row per metric, entity and time bucket, at DAILY granularity. `reportingMetricsBy*` takes one required `metricName` per request, so each sync reads the deployment's metric catalog (`metricTypesForJob` / `ForAsset` / `ForDeployment`) and walks it. `reportingMetricsByAssetGroup` and `reportingMetricsByAssetSelection` were left out: they report the same metrics rolled up over a grouping that the asset table already carries as a column.++Note: `run_logs` has no timestamp filter of its own, so an incremental sync bounds the parent run walk with `RunsFilter.updatedAfter` and `updatedBefore` instead and re-reads only the runs that moved inside that window. Child rows carry the parent's `updateTime` and checkpoint on it rather than on their own event timestamp, because the two advance independently. A run event carries no identifier, so the key is the run id plus the event's position in the run's append-only stream, which also means the walk restarts a run rather than resuming mid-stream.+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 d25a9753d3ec..fd4f253dead5 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@@ -186,4 +186,123 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"metadataEntries": "Metadata the run attached to the observation, with each entry's type and label.",},},+ "deployments": {+ "description": "Every deployment in the organization, both the full deployments and the branch deployments open against them. The lookup resolving which Dagster+ deployment a run or asset belongs to.",+ "docs_url": "https://docs.dagster.io/api/graphql",+ "columns": {+ "organizationId": "Identifier of the organization the deployment belongs to.",+ "organizationName": "Name of the organization the deployment belongs to.",+ "deploymentId": "Unique identifier for the deployment.",+ "deploymentName": "Name of the deployment (e.g. prod).",+ "deploymentStatus": "Whether the deployment is ACTIVE or PENDING_DELETION.",+ "deploymentType": "Whether the deployment is a PRODUCTION or a BRANCH deployment.",+ "isBranchDeployment": "Whether the deployment is an ephemeral branch deployment.",+ "agentType": "Whether the deployment runs on a HYBRID or a SERVERLESS agent.",+ "parentDeployment": "Full deployment a branch deployment was created from.",+ "branchDeploymentGitMetadata": "Branch, repository and pull request a branch deployment tracks.",+ "latestCommit": "Most recent commit deployed to the deployment, with its author and message.",+ },+ },+ "run_logs": {+ "description": "Event log for each run, covering step starts, successes, failures, retries and log messages. Resolves what happened inside the runs table's rows.",+ "docs_url": "https://docs.dagster.io/api/graphql",+ "columns": {+ "runId": "Identifier of the run the event belongs to.",+ "eventIndex": "Position of the event in its run's event stream, counted from zero.",+ "runUpdateTime": "When the run record was last updated. Each incremental sync reads the runs that moved since the previous one.",+ "eventTypename": "GraphQL type of the event (e.g. ExecutionStepFailureEvent, LogMessageEvent).",+ "eventType": "Dagster event type the event reports (e.g. STEP_START, STEP_FAILURE), when it has one.",+ "message": "Human-readable message recorded with the event.",+ "timestamp": "When the event was recorded.",+ "level": "Log level of the event (e.g. DEBUG, INFO, ERROR).",+ "stepKey": "Step within the run that emitted the event.",+ "solidHandleID": "Handle of the op that emitted the event.",+ "pipelineName": "Name of the job the run executed, on run-level events.",+ "markerStart": "Name of the timing marker the event opens, for step and engine timings.",+ "markerEnd": "Name of the timing marker the event closes.",+ "error": "Error the event carries, with its message and exception class.",+ },+ },+ "users": {+ "description": "Organization members and the roles granted to each, for attributing runs and backfills to people. Needs organization-level permissions.",+ "docs_url": "https://docs.dagster.io/api/graphql",+ "columns": {+ "id": "Unique identifier for the user's permission record.",+ "licensedRole": "Highest role the user holds, which is what the organization is billed for.",+ "user": "The user's profile: identifier, email, name, and whether SCIM provisioned them.",+ "organizationPermissionGrant": "Role granted across the whole organization, if any.",+ "allBranchDeploymentsPermissionGrant": "Role granted across every branch deployment, if any.",+ "deploymentPermissionGrants": "Roles granted on individual deployments, each with its location-scoped overrides.",+ },+ },+ "teams": {+ "description": "Teams in the organization, their members, and the roles granted to each team. Needs organization-level permissions.",+ "docs_url": "https://docs.dagster.io/api/graphql",+ "columns": {+ "id": "Unique identifier for the team's permission record.",+ "team": "The team itself: identifier, name, and the users in it.",+ "organizationPermissionGrant": "Role granted across the whole organization, if any.",+ "allBranchDeploymentsPermissionGrant": "Role granted across every branch deployment, if any.",+ "deploymentPermissionGrants": "Roles granted on individual deployments, each with its location-scoped overrides.",+ },+ },+ "custom_roles": {+ "description": "Custom roles defined in the organization and the permissions each one carries. Resolves the custom role identifiers on the users and teams tables. Needs organization-level permissions.",+ "docs_url": "https://docs.dagster.io/api/graphql",+ "columns": {+ "id": "Unique identifier for the custom role.",+ "name": "Name of the custom role.",+ "description": "Description declared on the custom role.",+ "iconName": "Icon chosen for the custom role.",+ "permissions": "Permissions the role grants (e.g. START_AND_STOP_RUNS, EDIT_ALERTS).",+ "deploymentScope": "Whether the role applies at DEPLOYMENT or ORGANIZATION scope.",+ },+ },+ "insights_job_metrics": {+ "description": "Dagster+ Insights metrics per job over time, such as credits consumed, execution time, and materialization and retry counts. One row per metric, job and time bucket.",+ "docs_url": "https://docs.dagster.io/guides/monitor/insights",+ "columns": {+ "metricName": "Name of the Insights metric the row measures (e.g. dagster_credits, execution_time_ms).",+ "entityId": "Stable identifier of the entity the measurement belongs to.",+ "entityType": "Kind of entity the measurement belongs to.",+ "timestamp": "Start of the bucket the value covers.",+ "value": "Value of the metric in that bucket. Buckets the metric did not report are left out.",+ "granularity": "Size of each bucket the metric is reported in.",+ "jobName": "Name of the job the measurement belongs to.",+ "codeLocationName": "Code location the job is loaded from.",+ "repositoryName": "Repository the job is defined in.",+ },+ },+ "insights_asset_metrics": {+ "description": "Dagster+ Insights metrics per asset over time, such as credits consumed, execution time, and materialization and retry counts. One row per metric, asset and time bucket.",+ "docs_url": "https://docs.dagster.io/guides/monitor/insights",+ "columns": {+ "metricName": "Name of the Insights metric the row measures (e.g. dagster_credits, execution_time_ms).",+ "entityId": "Stable identifier of the entity the measurement belongs to.",+ "entityType": "Kind of entity the measurement belongs to.",+ "timestamp": "Start of the bucket the value covers.",+ "value": "Value of the metric in that bucket. Buckets the metric did not report are left out.",+ "granularity": "Size of each bucket the metric is reported in.",+ "assetKey": "The asset key as a path list.",+ "assetGroup": "Asset group the asset belongs to.",+ "codeLocationName": "Code location the asset is loaded from.",+ "repositoryName": "Repository the asset is defined in.",+ },+ },+ "insights_deployment_metrics": {+ "description": "Dagster+ Insights metrics per deployment over time, such as credits consumed, execution time, and materialization and retry counts. One row per metric, deployment and time bucket.",+ "docs_url": "https://docs.dagster.io/guides/monitor/insights",+ "columns": {+ "metricName": "Name of the Insights metric the row measures (e.g. dagster_credits, execution_time_ms).",+ "entityId": "Stable identifier of the entity the measurement belongs to.",+ "entityType": "Kind of entity the measurement belongs to.",+ "timestamp": "Start of the bucket the value covers.",+ "value": "Value of the metric in that bucket. Buckets the metric did not report are left out.",+ "granularity": "Size of each bucket the metric is reported in.",+ "deploymentId": "Identifier of the deployment the measurement belongs to.",+ "deploymentName": "Name of the deployment the measurement belongs to.",+ "deploymentType": "Whether the deployment is a PRODUCTION or a BRANCH deployment.",+ "isBranchDeployment": "Whether the deployment is an ephemeral branch deployment.",+ },+ },}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 f02bbf2a1d28..6c568a1c2932 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@@ -15,10 +15,14 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.typfrom products.warehouse_sources.backend.temporal.data_imports.sources.dagster_cloud.queries import VALIDATION_QUERYfrom products.warehouse_sources.backend.temporal.data_imports.sources.dagster_cloud.settings import (DAGSTER_CLOUD_ENDPOINTS,+ DAGSTER_CLOUD_INSIGHTS_ENTITY_LIMIT,+ DAGSTER_CLOUD_INSIGHTS_GRANULARITY,+ DAGSTER_CLOUD_INSIGHTS_LOOKBACK_DAYS,DAGSTER_CLOUD_PAGE_SIZE,REPOSITORIES_PARENT_CONFIG,DagsterCloudEndpointConfig,DagsterCloudFanOutConfig,+ DagsterCloudInsightsConfig,WindowUnit,)@@ -207,8 +211,31 @@ def _execute_query(sess: requests.Session, url: str, query: str, variables: dictreturn _validate_response(response, url)+def _read_extra_list_rows(+ payload: dict[str, Any],+ endpoint_config: DagsterCloudEndpointConfig,+ logger: FilteringBoundLogger | None,+) -> list[dict[str, Any]]:+ """Read the sibling root fields whose rows belong in the same table as the main field's."""+ rows: list[dict[str, Any]] = []+ for extra in endpoint_config.extra_list_fields:+ value = payload["data"].get(extra.response_field)+ if extra.results_key is not None:+ value = (value or {}).get(extra.results_key)+ extra_rows = list(value or [])+ if extra.truncation_cap is not None and len(extra_rows) >= extra.truncation_cap and logger is not None:+ logger.warning(+ f"Dagster Cloud {endpoint_config.name}: {extra.response_field} returned its maximum "+ f"{extra.truncation_cap} rows, so some may be missing"+ )+ rows.extend(extra_rows)+ return rows++def _extract_rows(- payload: dict[str, Any], endpoint_config: DagsterCloudEndpointConfig+ payload: dict[str, Any],+ endpoint_config: DagsterCloudEndpointConfig,+ logger: FilteringBoundLogger | None = None,) -> tuple[dict[str, Any], list[dict[str, Any]]] | None:"""Unwrap the OrError union member holding the rows.@@ -217,9 +244,10 @@ def _extract_rows(children, so a parent deleted in between must be skipped rather than fail the sync."""container = payload["data"][endpoint_config.response_field]+ extra_rows = _read_extra_list_rows(payload, endpoint_config, logger)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 [])+ return {}, list(container or []) + extra_rowstypename = container.get("__typename")if typename in endpoint_config.skip_typenames:@@ -227,7 +255,7 @@ def _extract_rows(if typename != endpoint_config.success_typename:message = container.get("message", "")raise Exception(f"Dagster Cloud {endpoint_config.response_field} returned {typename}: {message}")- return container, list(container.get(endpoint_config.results_key) or [])+ return container, list(container.get(endpoint_config.results_key) or []) + extra_rowsdef _read_next_cursor(@@ -244,6 +272,7 @@ def _iter_cursor_pages(url: str,endpoint_config: DagsterCloudEndpointConfig,variables: dict[str, Any],+ logger: FilteringBoundLogger | None = None,) -> Iterator[tuple[list[dict[str, Any]], str | None]]:"""Walk a cursor-paginated list endpoint, yielding raw rows with the cursor that follows them.@@ -255,7 +284,7 @@ def _iter_cursor_pages(while True:payload = _execute_query(sess, url, endpoint_config.query, variables)- extracted = _extract_rows(payload, endpoint_config)+ extracted = _extract_rows(payload, endpoint_config, logger)if extracted is None:returncontainer, rows = extracted@@ -293,7 +322,9 @@ def _make_paginated_request(url = build_graphql_url(organization, deployment)sess = _make_session(api_token)- variables: dict[str, Any] = {"limit": DAGSTER_CLOUD_PAGE_SIZE}+ variables: dict[str, Any] = dict(endpoint_config.static_variables)+ if endpoint_config.cursor_mode is not None:+ variables["limit"] = DAGSTER_CLOUD_PAGE_SIZEif runs_filter is not None:variables["filter"] = runs_filter@@ -303,7 +334,7 @@ def _make_paginated_request(logger.debug(f"Dagster Cloud: resuming {endpoint_name} from saved cursor")try:- for rows, next_cursor in _iter_cursor_pages(sess, url, endpoint_config, variables):+ for rows, next_cursor in _iter_cursor_pages(sess, url, endpoint_config, variables, logger):yield [_normalize_row(row, endpoint_config) for row in rows]# Checkpoint the next page to fetch AFTER yielding this one, so a crash re-fetches the@@ -336,6 +367,32 @@ def _iter_asset_parents(sess: requests.Session, url: str) -> Iterator[dict[str,yield {"assetId": row.get("id"), "assetKeyPath": path, "assetKeyInput": {"path": path}}+def _iter_run_parents(+ sess: requests.Session,+ url: str,+ watermark_epoch: float | None,+ sync_start_epoch: float,+) -> Iterator[dict[str, Any]]:+ """Walk the runs whose `updateTime` falls in this sync's window, newest first.++ logsForRun takes no timestamp filter, so the only way an incremental sync avoids re-reading+ every run's whole log is to narrow the parent walk instead. `updatedBefore` pins the top of+ the window to the instant the walk started: the walk pages backwards from the newest run, so+ a run that moves while it is in progress would otherwise never be fetched, and the watermark+ would still advance past it.+ """+ endpoint_config = DAGSTER_CLOUD_ENDPOINTS["runs"]+ runs_filter: dict[str, float] = {"updatedBefore": sync_start_epoch}+ if watermark_epoch is not None:+ runs_filter["updatedAfter"] = watermark_epoch+ variables: dict[str, Any] = {"limit": DAGSTER_CLOUD_PAGE_SIZE, "filter": runs_filter}+ for rows, _ in _iter_cursor_pages(sess, url, endpoint_config, variables):+ for row in rows:+ # The child rows checkpoint on this, not on their own event timestamp, so the next+ # window starts where this one ended.+ yield {"runId": row.get("runId"), "runUpdateTime": _epoch_to_iso(row.get("updateTime"))}++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):@@ -354,11 +411,19 @@ def _iter_instigation_state_parents(sess: requests.Session, url: str) -> Iterato}-def _iter_parents(sess: requests.Session, url: str, fan_out: DagsterCloudFanOutConfig) -> Iterator[dict[str, Any]]:+def _iter_parents(+ sess: requests.Session,+ url: str,+ fan_out: DagsterCloudFanOutConfig,+ watermark_epoch: float | None,+ sync_start_epoch: float,+) -> 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)+ elif fan_out.parent_kind == "runs":+ yield from _iter_run_parents(sess, url, watermark_epoch, sync_start_epoch)else:yield from _iter_instigation_state_parents(sess, url)@@ -402,6 +467,49 @@ def _inject_parent_fields(return enriched+def _iter_forward_cursor_pages(+ sess: requests.Session,+ url: str,+ endpoint_config: DagsterCloudEndpointConfig,+ parent: dict[str, Any],+ variables: dict[str, Any],+) -> Iterator[tuple[list[dict[str, Any]], str | None]]:+ """Yield one parent's child rows through an opaque forward cursor plus a `hasMore` flag."""+ fan_out = endpoint_config.fan_out+ assert fan_out is not None and fan_out.cursor_variable is not None and fan_out.has_more_key is not None++ row_index = 0+ previous_cursor: str | None = None++ 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++ page: list[dict[str, Any]] = []+ for row in rows:+ enriched = _inject_parent_fields(_normalize_row(row, endpoint_config), parent, fan_out)+ if fan_out.row_index_field is not None:+ enriched = {**enriched, fan_out.row_index_field: row_index}+ row_index += 1+ page.append(enriched)++ # No mid-parent checkpoint: the row index is only stable when the parent is read from its+ # start, so a resume has to restart this parent rather than pick up at its cursor.+ yield page, None++ if not container.get(fan_out.has_more_key):+ return+ cursor = container.get("cursor")+ # Nothing else bounds this walk, so a cursor that repeats would replay one page forever.+ if not cursor or cursor == previous_cursor:+ raise Exception(f"Dagster Cloud {endpoint_config.name}: page cursor did not advance")+ previous_cursor = cursor+ variables[fan_out.cursor_variable] = cursor++def _iter_child_pages(sess: requests.Session,url: str,@@ -419,6 +527,11 @@ def _iter_child_pages(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.cursor_variable is not None:+ yield from _iter_forward_cursor_pages(sess, url, endpoint_config, parent, variables)+ return+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:@@ -480,6 +593,7 @@ def _iter_fanout_rows(resumable_source_manager: ResumableSourceManager[DagsterCloudResumeConfig],resume_config: DagsterCloudResumeConfig | None,watermark_epoch: float | None,+ sync_start_epoch: float,) -> Iterator[list[dict[str, Any]]]:fan_out = endpoint_config.fan_outassert fan_out is not None@@ -493,7 +607,7 @@ def _iter_fanout_rows(index = parents_done - 1batch: list[dict[str, Any]] = []- for index, parent in enumerate(_iter_parents(sess, url, fan_out)):+ for index, parent in enumerate(_iter_parents(sess, url, fan_out, watermark_epoch, sync_start_epoch)):if index < parents_done:continue@@ -541,6 +655,151 @@ def _make_fanout_request(try:yield from _iter_fanout_rows(+ sess,+ url,+ endpoint_config,+ logger,+ resumable_source_manager,+ resume_config,+ watermark_epoch,+ datetime.now(tz=UTC).timestamp(),+ )+ finally:+ sess.close()+++def _fetch_metric_names(sess: requests.Session, url: str, insights: DagsterCloudInsightsConfig) -> list[str]:+ payload = _execute_query(sess, url, insights.metric_types_query, {})+ container = payload["data"][insights.metric_types_field] or {}+ typename = container.get("__typename")+ if typename != "MetricTypeList":+ raise Exception(+ f"Dagster Cloud {insights.metric_types_field} returned {typename}: {container.get('message', '')}"+ )+ return [+ metric["metricName"] for metric in container.get("metricTypes") or [] if metric and metric.get("metricName")+ ]+++def _flatten_reporting_entity(entity: dict[str, Any]) -> tuple[str | None, dict[str, Any]]:+ """Reduce a ReportingObjet union member to a stable id plus the columns identifying it."""+ typename = entity.get("__typename")+ columns = {key: value for key, value in entity.items() if key != "__typename"}+ if typename == "ReportingJob":+ parts = ("codeLocationName", "repositoryName", "jobName")+ return "/".join(str(entity.get(part) or "") for part in parts), columns+ if typename == "ReportingAsset":+ return "/".join((entity.get("assetKey") or {}).get("path") or []), columns+ if typename == "DagsterCloudDeployment":+ return str(entity.get("deploymentId")), columns+ return None, columns+++def _expand_metric_entries(+ metric_name: str, entries: list[dict[str, Any]], timestamps: list[Any]+) -> list[dict[str, Any]]:+ """Flatten one metric's response into a row per entity per bucket.++ Insights returns the bucket starts once and each entity's values positionally against them.+ """+ iso_timestamps = [_epoch_to_iso(timestamp) for timestamp in timestamps]+ rows: list[dict[str, Any]] = []+ for entry in entries:+ if not entry:+ continue+ entity = entry.get("entity") or {}+ entity_id, entity_columns = _flatten_reporting_entity(entity)+ if entity_id is None:+ continue+ for iso_timestamp, value in zip(iso_timestamps, entry.get("values") or []):+ # A null bucket means the metric reported nothing in that window, and a row per empty+ # bucket per entity would dwarf the measurements.+ if value is None:+ continue+ rows.append(+ {+ "metricName": metric_name,+ "entityId": entity_id,+ "entityType": entity.get("__typename"),+ "timestamp": iso_timestamp,+ "value": value,+ "granularity": DAGSTER_CLOUD_INSIGHTS_GRANULARITY,+ **entity_columns,+ }+ )+ return rows+++def _iter_insights_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]]]:+ insights = endpoint_config.insights+ assert insights is not None++ before = datetime.now(tz=UTC).timestamp()+ after = watermark_epoch if watermark_epoch is not None else before - DAGSTER_CLOUD_INSIGHTS_LOOKBACK_DAYS * 86400++ metric_names = _fetch_metric_names(sess, url, insights)+ metrics_done = resume_config.parents_done if resume_config else 0+ if metrics_done:+ logger.debug(f"Dagster Cloud: resuming {endpoint_config.name} after {metrics_done} metrics")++ for index, metric_name in enumerate(metric_names):+ if index < metrics_done:+ continue++ variables: dict[str, Any] = {+ "metricsSelector": {+ "after": after,+ "before": before,+ "metricName": metric_name,+ "granularity": DAGSTER_CLOUD_INSIGHTS_GRANULARITY,+ },+ "metricsFilter": {"limit": DAGSTER_CLOUD_INSIGHTS_ENTITY_LIMIT},+ }+ payload = _execute_query(sess, url, endpoint_config.query, variables)+ extracted = _extract_rows(payload, endpoint_config)+ if extracted is None:+ continue+ container, entries = extracted++ # The resolver bounds its entity list with that filter limit and offers no cursor, so a+ # response at the cap is the only signal that entities were left out.+ if len(entries) >= DAGSTER_CLOUD_INSIGHTS_ENTITY_LIMIT:+ logger.warning(+ f"Dagster Cloud {endpoint_config.name}: metric {metric_name} returned its maximum "+ f"{DAGSTER_CLOUD_INSIGHTS_ENTITY_LIMIT} entities, so some may be missing"+ )++ yield _expand_metric_entries(metric_name, entries, container.get("timestamps") or [])+ resumable_source_manager.save_state(DagsterCloudResumeConfig(parents_done=index + 1))+++def _make_insights_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.insights is None:+ raise ValueError(f"Unknown Dagster Cloud insights 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_insights_rows(sess, url, endpoint_config, logger, resumable_source_manager, resume_config, watermark_epoch)finally:@@ -571,6 +830,18 @@ def dagster_cloud_source():watermark_epoch = _to_epoch_seconds(db_incremental_field_last_value)+ if endpoint_config.insights is not None:+ yield from _make_insights_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+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}")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 9ea8750add8f..f7cfe628ae39 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@@ -329,3 +329,194 @@ query AssetObservations(}"""+ _METADATA_ENTRY_FRAGMENT)++_DEPLOYMENT_FIELDS_FRAGMENT = """+fragment DeploymentFields on DagsterCloudDeployment {+ organizationId+ organizationName+ deploymentId+ deploymentName+ deploymentStatus+ deploymentType+ isBranchDeployment+ agentType+ parentDeployment { deploymentId deploymentName }+ branchDeploymentGitMetadata {+ branchName+ repoName+ branchUrl+ pullRequestUrl+ pullRequestStatus+ pullRequestNumber+ }+ latestCommit { timestamp commitHash commitMessage commitUrl authorName authorEmail }+}"""++# `deployments` returns only the subset the caller can reach, so the table is built from+# `fullDeployments` plus `branchDeployments` instead, because together they cover every deployment+# the organization has. Each row carries `isBranchDeployment` to tell the two apart.+DEPLOYMENTS_QUERY = (+ """+query Deployments($branchDeploymentLimit: Int!) {+ fullDeployments { ...DeploymentFields }+ branchDeployments(limit: $branchDeploymentLimit) {+ nodes { ...DeploymentFields }+ }+}"""+ + _DEPLOYMENT_FIELDS_FRAGMENT+)++# Every member of the DagsterRunEvent union implements MessageEvent, so the interface fragment+# alone gives every row its identity and timing; the rest add the step-timing markers and the+# error payload that make a failure readable.+RUN_LOGS_QUERY = """+query RunLogs($runId: ID!, $limit: Int!, $afterCursor: String) {+ logsForRun(runId: $runId, limit: $limit, afterCursor: $afterCursor) {+ __typename+ ... on EventConnection {+ cursor+ hasMore+ events {+ eventTypename: __typename+ ... on MessageEvent {+ runId+ message+ timestamp+ level+ stepKey+ solidHandleID+ eventType+ }+ ... on RunEvent { pipelineName }+ ... on MarkerEvent { markerStart markerEnd }+ ... on ErrorEvent { error { message className } }+ }+ }+ ... on RunNotFoundError { message }+ ... on PythonError { message }+ }+}"""++_PERMISSION_GRANT_FRAGMENT = """+fragment PermissionGrantFields on DagsterCloudScopedPermissionGrant {+ id+ organizationId+ deploymentId+ grant+ customRoleId+ deploymentScope+ locationGrants { locationName grant customRoleId }+}"""++USERS_QUERY = (+ """+query OrganizationUsers {+ usersOrError {+ __typename+ ... on DagsterCloudUsersWithScopedPermissionGrants {+ users {+ id+ licensedRole+ user { id userId email name firstName lastName isScimProvisioned }+ organizationPermissionGrant { ...PermissionGrantFields }+ allBranchDeploymentsPermissionGrant { ...PermissionGrantFields }+ deploymentPermissionGrants { ...PermissionGrantFields }+ }+ }+ ... on UnauthorizedError { message }+ ... on PythonError { message }+ }+}"""+ + _PERMISSION_GRANT_FRAGMENT+)++TEAM_PERMISSIONS_QUERY = (+ """+query TeamPermissions {+ teamPermissions {+ id+ team { id name members { id userId email name } }+ organizationPermissionGrant { ...PermissionGrantFields }+ allBranchDeploymentsPermissionGrant { ...PermissionGrantFields }+ deploymentPermissionGrants { ...PermissionGrantFields }+ }+}"""+ + _PERMISSION_GRANT_FRAGMENT+)++CUSTOM_ROLES_QUERY = """+query CustomRoles {+ customRoles {+ id+ name+ description+ iconName+ permissions+ deploymentScope+ }+}"""+++def _metric_types_query(operation: str, field: str) -> str:+ return f"""+query {operation} {{+ {field} {{+ __typename+ ... on MetricTypeList {{+ metricTypes {{ metricName displayName unitType category costMultiplier }}+ }}+ ... on UnauthorizedError {{ message }}+ ... on PythonError {{ message }}+ }}+}}"""+++# reportingMetricsBy* takes one required metricName per request, so the sync reads the+# deployment's metric catalog first and walks it.+METRIC_TYPES_FOR_JOB_QUERY = _metric_types_query("MetricTypesForJob", "metricTypesForJob")+METRIC_TYPES_FOR_ASSET_QUERY = _metric_types_query("MetricTypesForAsset", "metricTypesForAsset")+METRIC_TYPES_FOR_DEPLOYMENT_QUERY = _metric_types_query("MetricTypesForDeployment", "metricTypesForDeployment")+++def _reporting_metrics_query(operation: str, field: str, filter_type: str, entity_fragment: str) -> str:+ return f"""+query {operation}($metricsSelector: ReportingMetricsSelector!, $metricsFilter: {filter_type}) {{+ {field}(metricsSelector: $metricsSelector, metricsFilter: $metricsFilter) {{+ __typename+ ... on ReportingMetrics {{+ timestamps+ metrics {{+ values+ entity {{+ __typename+ {entity_fragment}+ }}+ }}+ }}+ ... on UnauthorizedError {{ message }}+ ... on ReportingInputError {{ message }}+ ... on PythonError {{ message }}+ }}+}}"""+++REPORTING_METRICS_BY_JOB_QUERY = _reporting_metrics_query(+ "ReportingMetricsByJob",+ "reportingMetricsByJob",+ "JobReportingMetricsFilter",+ "... on ReportingJob { jobName codeLocationName repositoryName }",+)++REPORTING_METRICS_BY_ASSET_QUERY = _reporting_metrics_query(+ "ReportingMetricsByAsset",+ "reportingMetricsByAsset",+ "AssetReportingMetricsFilter",+ "... on ReportingAsset { assetKey { path } assetGroup codeLocationName repositoryName }",+)++REPORTING_METRICS_BY_DEPLOYMENT_QUERY = _reporting_metrics_query(+ "ReportingMetricsByDeployment",+ "reportingMetricsByDeployment",+ "DeploymentReportingMetricsFilter",+ "... on DagsterCloudDeployment { deploymentId deploymentName deploymentType isBranchDeployment }",+)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 6180377a870f..65ce2d854331 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,5 +1,5 @@from dataclasses import field-from typing import Literal+from typing import Any, Literalfrom posthog.dataclasses import frozen@@ -10,12 +10,23 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.dagster_clASSET_OBSERVATIONS_QUERY,ASSETS_QUERY,BACKFILLS_QUERY,+ CUSTOM_ROLES_QUERY,+ DEPLOYMENTS_QUERY,INSTIGATION_STATES_QUERY,INSTIGATION_TICKS_QUERY,+ METRIC_TYPES_FOR_ASSET_QUERY,+ METRIC_TYPES_FOR_DEPLOYMENT_QUERY,+ METRIC_TYPES_FOR_JOB_QUERY,+ REPORTING_METRICS_BY_ASSET_QUERY,+ REPORTING_METRICS_BY_DEPLOYMENT_QUERY,+ REPORTING_METRICS_BY_JOB_QUERY,REPOSITORIES_QUERY,+ RUN_LOGS_QUERY,RUNS_QUERY,SCHEDULES_QUERY,SENSORS_QUERY,+ TEAM_PERMISSIONS_QUERY,+ USERS_QUERY,)from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType@@ -23,12 +34,26 @@ from products.warehouse_sources.backend.types import IncrementalField, Increment# runs/backfills/assets list resolvers.DAGSTER_CLOUD_PAGE_SIZE = 100+# `branchDeployments` and the Insights metrics resolvers bound their result set with a required+# argument and expose no cursor, so the only defence against silent truncation is to ask for far+# more than any deployment realistically has and warn when a response comes back at the cap.+DAGSTER_CLOUD_BRANCH_DEPLOYMENT_LIMIT = 500+DAGSTER_CLOUD_INSIGHTS_ENTITY_LIMIT = 1000++# Insights buckets the deployment's metrics; DAILY is the grain the vendor's own reporting uses+# and keeps a first sync to a few hundred rows per metric.+DAGSTER_CLOUD_INSIGHTS_GRANULARITY = "DAILY"++# How far back a first Insights sync reaches. Matches `ReportingTimeRange.Last120Days`, the widest+# window Dagster+ offers in its own UI.+DAGSTER_CLOUD_INSIGHTS_LOOKBACK_DAYS = 120+# "row" -> next cursor is a field read off the last result row (runId / backfill id).# "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"]+ParentKind = Literal["repositories", "assets", "instigation_states", "runs"]# 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.@@ -65,6 +90,33 @@ class DagsterCloudFanOutConfig:after_variable: str | None = Nonewindow_row_field: str | None = Nonewindow_unit: WindowUnit | None = None+ # Forward-cursor children page with an opaque cursor plus a `hasMore` flag instead of a+ # timestamp window. Such a walk is never checkpointed mid-parent, for the reason+ # `row_index_field` gives below.+ cursor_variable: str | None = None+ has_more_key: str | None = None+ # Child rows with no identifier of their own get their 0-based position in the parent's+ # stream written here, so (parent id, index) keys the table. Only sound for an append-only+ # collection always read from its start, which is why a forward-cursor walk resumes a parent+ # from the beginning rather than mid-stream.+ row_index_field: str | None = None+++@frozen+class DagsterCloudExtraListField:+ response_field: str+ results_key: str | None = None+ # Row count at which the resolver's required limit truncated the list. The resolver exposes+ # no cursor to page past it, so reaching the cap is only ever reported, never worked around.+ truncation_cap: int | None = None+++@frozen+class DagsterCloudInsightsConfig:+ # `reportingMetricsBy*` takes one required metric name per request, so a sync first reads the+ # deployment's metric catalog for this entity kind and then walks it metric by metric.+ metric_types_query: str+ metric_types_field: str@frozen@@ -92,6 +144,12 @@ class DagsterCloudEndpointConfig:# For cursor_mode="row": which row field to use as the next-page cursor.cursor_row_field: str | None = Nonefan_out: DagsterCloudFanOutConfig | None = None+ insights: DagsterCloudInsightsConfig | None = None+ # Extra root query fields concatenated onto this endpoint's page. Used where one table is+ # the union of sibling root fields that return the same type.+ extra_list_fields: tuple[DagsterCloudExtraListField, ...] = ()+ # Constant GraphQL variables the endpoint's query requires.+ static_variables: dict[str, Any] = field(default_factory=dict)incremental_fields: list[IncrementalField] = field(default_factory=list)supports_incremental: bool = False# Stable creation-time field to partition by (never an updated-at style field).@@ -304,6 +362,149 @@ DAGSTER_CLOUD_ENDPOINTS: dict[str, DagsterCloudEndpointConfig] = {window_unit="millis_string",),),+ "deployments": DagsterCloudEndpointConfig(+ name="deployments",+ query=DEPLOYMENTS_QUERY,+ # `fullDeployments` returns the list directly; `branchDeployments` adds the branch ones+ # through its connection, and both carry the same DagsterCloudDeployment shape.+ response_field="fullDeployments",+ extra_list_fields=(+ DagsterCloudExtraListField(+ response_field="branchDeployments",+ results_key="nodes",+ truncation_cap=DAGSTER_CLOUD_BRANCH_DEPLOYMENT_LIMIT,+ ),+ ),+ static_variables={"branchDeploymentLimit": DAGSTER_CLOUD_BRANCH_DEPLOYMENT_LIMIT},+ primary_keys=["deploymentId"],+ # A deployment row changes in place (status, latest commit), so full refresh keeps it+ # current; the list is a handful of rows either way.+ ),+ "run_logs": DagsterCloudEndpointConfig(+ name="run_logs",+ query=RUN_LOGS_QUERY,+ response_field="logsForRun",+ success_typename="EventConnection",+ results_key="events",+ skip_typenames=("RunNotFoundError",),+ # A run event carries no identifier of its own. The event log is append-only and every+ # sync reads a run from its start, so the event's position in the run is stable.+ primary_keys=["runId", "eventIndex"],+ millis_timestamp_fields=["timestamp"],+ # logsForRun has no timestamp filter, so incremental works by narrowing the parent walk.+ # The cursor is the parent run's updateTime rather than the event's own timestamp: the+ # two advance independently, and checkpointing the event time would move the next window+ # past runs whose logs were never read.+ incremental_fields=[_incremental_datetime_field("runUpdateTime")],+ supports_incremental=True,+ partition_key="timestamp",+ # Events ascend inside a run, but runs arrive newest-first, so the stream as a whole is+ # not ordered, so "desc" holds the watermark until the fan-out finishes.+ sort_mode="desc",+ # One row per log line of every run is the largest table this source can produce, and a+ # first sync walks the deployment's whole run history.+ should_sync_default=False,+ fan_out=DagsterCloudFanOutConfig(+ parent_kind="runs",+ parent_variables={"runId": "runId"},+ include_from_parent=["runId", "runUpdateTime"],+ cursor_variable="afterCursor",+ has_more_key="hasMore",+ row_index_field="eventIndex",+ ),+ ),+ "users": DagsterCloudEndpointConfig(+ name="users",+ query=USERS_QUERY,+ response_field="usersOrError",+ success_typename="DagsterCloudUsersWithScopedPermissionGrants",+ results_key="users",+ primary_keys=["id"],+ # Reading the organization's members needs organization-level permissions a+ # deployment-scoped token often lacks, so the table is opt-in.+ should_sync_default=False,+ ),+ "teams": DagsterCloudEndpointConfig(+ name="teams",+ query=TEAM_PERMISSIONS_QUERY,+ # teamPermissions returns [DagsterCloudTeamPermissions!]! directly.+ response_field="teamPermissions",+ primary_keys=["id"],+ should_sync_default=False,+ ),+ "custom_roles": DagsterCloudEndpointConfig(+ name="custom_roles",+ query=CUSTOM_ROLES_QUERY,+ response_field="customRoles",+ primary_keys=["id"],+ should_sync_default=False,+ ),+ "insights_job_metrics": DagsterCloudEndpointConfig(+ name="insights_job_metrics",+ query=REPORTING_METRICS_BY_JOB_QUERY,+ response_field="reportingMetricsByJob",+ success_typename="ReportingMetrics",+ results_key="metrics",+ primary_keys=["metricName", "entityId", "timestamp"],+ # The selector's after/before are genuine epoch-second bounds on the reporting window.+ incremental_fields=[_incremental_datetime_field("timestamp")],+ supports_incremental=True,+ partition_key="timestamp",+ # One request returns every bucket of one metric at once, so the rows it produces are+ # not in time order, so "desc" holds the watermark until the whole walk finishes.+ sort_mode="desc",+ # Insights is a Dagster+ feature the token may not be entitled to, and a metric catalog+ # is deployment-specific, so leave the choice to the user.+ should_sync_default=False,+ insights=DagsterCloudInsightsConfig(+ metric_types_query=METRIC_TYPES_FOR_JOB_QUERY,+ metric_types_field="metricTypesForJob",+ ),+ ),+ "insights_asset_metrics": DagsterCloudEndpointConfig(+ name="insights_asset_metrics",+ query=REPORTING_METRICS_BY_ASSET_QUERY,+ response_field="reportingMetricsByAsset",+ success_typename="ReportingMetrics",+ results_key="metrics",+ primary_keys=["metricName", "entityId", "timestamp"],+ # The selector's after/before are genuine epoch-second bounds on the reporting window.+ incremental_fields=[_incremental_datetime_field("timestamp")],+ supports_incremental=True,+ partition_key="timestamp",+ # One request returns every bucket of one metric at once, so the rows it produces are+ # not in time order, so "desc" holds the watermark until the whole walk finishes.+ sort_mode="desc",+ # Insights is a Dagster+ feature the token may not be entitled to, and a metric catalog+ # is deployment-specific, so leave the choice to the user.+ should_sync_default=False,+ insights=DagsterCloudInsightsConfig(+ metric_types_query=METRIC_TYPES_FOR_ASSET_QUERY,+ metric_types_field="metricTypesForAsset",+ ),+ ),+ "insights_deployment_metrics": DagsterCloudEndpointConfig(+ name="insights_deployment_metrics",+ query=REPORTING_METRICS_BY_DEPLOYMENT_QUERY,+ response_field="reportingMetricsByDeployment",+ success_typename="ReportingMetrics",+ results_key="metrics",+ primary_keys=["metricName", "entityId", "timestamp"],+ # The selector's after/before are genuine epoch-second bounds on the reporting window.+ incremental_fields=[_incremental_datetime_field("timestamp")],+ supports_incremental=True,+ partition_key="timestamp",+ # One request returns every bucket of one metric at once, so the rows it produces are+ # not in time order, so "desc" holds the watermark until the whole walk finishes.+ sort_mode="desc",+ # Insights is a Dagster+ feature the token may not be entitled to, and a metric catalog+ # is deployment-specific, so leave the choice to the user.+ should_sync_default=False,+ insights=DagsterCloudInsightsConfig(+ metric_types_query=METRIC_TYPES_FOR_DEPLOYMENT_QUERY,+ metric_types_field="metricTypesForDeployment",+ ),+ ),}ENDPOINTS = tuple(DAGSTER_CLOUD_ENDPOINTS.keys())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 7b0be3980247..eb9320403535 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@@ -13,7 +13,10 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.dagster_clDagsterCloudResumeConfig,_build_runs_filter,_epoch_to_iso,+ _expand_metric_entries,+ _flatten_reporting_entity,_make_fanout_request,+ _make_insights_request,_make_paginated_request,_to_epoch_seconds,build_graphql_url,@@ -22,6 +25,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.dagster_cl)from products.warehouse_sources.backend.temporal.data_imports.sources.dagster_cloud.settings import (DAGSTER_CLOUD_ENDPOINTS,+ DAGSTER_CLOUD_INSIGHTS_LOOKBACK_DAYS,)# 2024-01-01T00:00:00Z@@ -42,7 +46,9 @@ def _gql_response(response_field: str, container: dict[str, Any]) -> MagicMock:def _runs_container(run_ids: list[str]) -> dict[str, Any]:return {"__typename": "Runs",- "results": [{"runId": rid, "status": "SUCCESS", "creationTime": EPOCH_2024} for rid in run_ids],+ "results": [+ {"runId": rid, "status": "SUCCESS", "creationTime": EPOCH_2024, "updateTime": EPOCH_2024} for rid in run_ids+ ],}@@ -322,11 +328,22 @@ class TestValidateCredentials:class TestEndpointCatalog: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.+ # RunsFilter.updatedAfter, InstigationState.ticks(afterTimestamp), the asset event+ # resolvers' afterTimestampMillis and the Insights selector's after/before genuinely filter+ # server-side; run_logs has no filter of its own but narrows its parent run walk with+ # RunsFilter.updatedAfter. 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", "instigation_ticks", "asset_materializations", "asset_observations"}+ assert incremental == {+ "runs",+ "instigation_ticks",+ "asset_materializations",+ "asset_observations",+ "run_logs",+ "insights_job_metrics",+ "insights_asset_metrics",+ "insights_deployment_metrics",+ }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@@ -749,3 +766,372 @@ class TestCursorProgress:with pytest.raises(Exception, match="pagination cursor did not advance"):list(_make_paginated_request("org", "prod", "tok", "runs", MagicMock(), _manager()))+++def _deployments_response(full: list[str], branch: list[str]) -> MagicMock:+ response = MagicMock()+ response.status_code = 200+ response.ok = True+ response.json.return_value = {+ "data": {+ "fullDeployments": [{"deploymentId": name, "isBranchDeployment": False} for name in full],+ "branchDeployments": {"nodes": [{"deploymentId": name, "isBranchDeployment": True} for name in branch]},+ }+ }+ return response+++class TestDeployments:+ @patch(f"{MODULE}.make_tracked_session")+ def test_full_and_branch_deployments_land_in_one_table(self, mock_session_cls: MagicMock) -> None:+ # `deployments` alone returns only what the caller can reach, so the table unions the two+ # sibling root fields, because a branch deployment missing here orphans the runs that ran on it.+ session = MagicMock()+ session.post.side_effect, calls = _route({"Deployments": [_deployments_response(["prod"], ["pr-7"])]})+ mock_session_cls.return_value = session++ pages = list(_make_paginated_request("org", "prod", "tok", "deployments", MagicMock(), _manager()))++ assert [row["deploymentId"] for page in pages for row in page] == ["prod", "pr-7"]+ # branchDeployments takes a required limit, so the query cannot go out without it.+ assert calls[0][1]["branchDeploymentLimit"] == 500++ @patch(f"{MODULE}.make_tracked_session")+ def test_branch_deployment_cap_is_reported(self, mock_session_cls: MagicMock) -> None:+ # The resolver offers no cursor past its limit, so a response at the cap is the only+ # signal that deployments were left out.+ session = MagicMock()+ cap = DAGSTER_CLOUD_ENDPOINTS["deployments"].extra_list_fields[0].truncation_cap+ assert cap is not None+ session.post.side_effect, _ = _route(+ {"Deployments": [_deployments_response([], [f"pr-{i}" for i in range(cap)])]}+ )+ mock_session_cls.return_value = session+ logger = MagicMock()++ list(_make_paginated_request("org", "prod", "tok", "deployments", logger, _manager()))++ assert "branchDeployments" in logger.warning.call_args[0][0]+++def _run_logs_response(messages: list[str], cursor: str | None, has_more: bool) -> MagicMock:+ return _gql_response(+ "logsForRun",+ {+ "__typename": "EventConnection",+ "cursor": cursor,+ "hasMore": has_more,+ "events": [+ {+ "eventTypename": "LogMessageEvent",+ "runId": "r1",+ "message": message,+ "timestamp": "1704067200000",+ }+ for message in messages+ ],+ },+ )+++class TestRunLogFanOut:+ @patch(f"{MODULE}.DAGSTER_CLOUD_PAGE_SIZE", 2)+ @patch(f"{MODULE}.make_tracked_session")+ def test_forward_cursor_pages_and_numbers_events_across_pages(self, mock_session_cls: MagicMock) -> None:+ # A run event carries no id, so its position in the run's stream is the key, and it has to+ # keep counting across the parent's pages rather than restart at each one.+ session = MagicMock()+ session.post.side_effect, calls = _route(+ {+ "PaginatedRuns": [_gql_response("runsOrError", _runs_container(["r1"]))],+ "RunLogs": [+ _run_logs_response(["a", "b"], cursor="c1", has_more=True),+ _run_logs_response(["c"], cursor="c2", has_more=False),+ ],+ }+ )+ mock_session_cls.return_value = session+ manager = _manager()++ pages = list(_make_fanout_request("org", "prod", "tok", "run_logs", MagicMock(), manager))++ rows = [row for page in pages for row in page]+ assert [row["eventIndex"] for row in rows] == [0, 1, 2]+ assert [row["message"] for row in rows] == ["a", "b", "c"]+ assert rows[0]["timestamp"] == ISO_2024+ # The second page follows the cursor the first one returned.+ assert [v.get("afterCursor") for op, v in calls if op == "RunLogs"] == [None, "c1"]+ # Resuming mid-run would restart the index at zero and rewrite every key, so the walk+ # only checkpoints once a run is finished.+ assert manager.save_state.call_args_list == [call(DagsterCloudResumeConfig(parents_done=1))]++ @parameterized.expand([("incremental", EPOCH_2024), ("full_refresh", None)])+ @patch(f"{MODULE}.DAGSTER_CLOUD_PAGE_SIZE", 2)+ @patch(f"{MODULE}.make_tracked_session")+ def test_the_parent_run_walk_is_bounded_at_both_ends(+ self, _name: str, watermark: float | None, mock_session_cls: MagicMock+ ) -> None:+ # logsForRun has no timestamp filter of its own; without narrowing the parent walk every+ # incremental sync would re-read the whole log of every run the deployment ever had.+ session = MagicMock()+ session.post.side_effect, calls = _route(+ {+ "PaginatedRuns": [_gql_response("runsOrError", _runs_container(["r1"]))],+ "RunLogs": [_run_logs_response(["a"], cursor=None, has_more=False)],+ }+ )+ mock_session_cls.return_value = session++ before = datetime.now(tz=UTC).timestamp()+ pages = list(_make_fanout_request("org", "prod", "tok", "run_logs", MagicMock(), _manager(), watermark))++ runs_filter = next(v for op, v in calls if op == "PaginatedRuns")["filter"]+ assert runs_filter.get("updatedAfter") == watermark+ # The walk pages backwards from the newest run, so a run that moves after it started+ # would never be fetched while the watermark advanced past it.+ assert before <= runs_filter["updatedBefore"] <= datetime.now(tz=UTC).timestamp()+ # The child checkpoints on the parent's update time, so the parent has to put it on+ # every row rather than leave the row's own event timestamp as the cursor.+ assert pages[0][0]["runUpdateTime"] == ISO_2024++ @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:+ session = MagicMock()+ session.post.side_effect, _ = _route(+ {+ "PaginatedRuns": [_gql_response("runsOrError", _runs_container(["r1"]))],+ "RunLogs": _run_logs_response(["a"], cursor="c1", has_more=True),+ }+ )+ mock_session_cls.return_value = session++ with pytest.raises(Exception, match="page cursor did not advance"):+ list(_make_fanout_request("org", "prod", "tok", "run_logs", MagicMock(), _manager()))++ @patch(f"{MODULE}.DAGSTER_CLOUD_PAGE_SIZE", 2)+ @patch(f"{MODULE}.make_tracked_session")+ def test_a_run_deleted_mid_sync_is_skipped(self, mock_session_cls: MagicMock) -> None:+ # The run list is read before the logs, so a run purged in between must not fail the sync.+ session = MagicMock()+ session.post.side_effect, _ = _route(+ {+ "PaginatedRuns": [_gql_response("runsOrError", _runs_container(["r1"]))],+ "RunLogs": _gql_response("logsForRun", {"__typename": "RunNotFoundError", "message": "gone"}),+ }+ )+ mock_session_cls.return_value = session++ pages = list(_make_fanout_request("org", "prod", "tok", "run_logs", MagicMock(), _manager()))++ assert [row for page in pages for row in page] == []+++class TestReportingEntities:+ @parameterized.expand(+ [+ (+ "job",+ {"__typename": "ReportingJob", "codeLocationName": "loc", "repositoryName": "repo", "jobName": "etl"},+ "loc/repo/etl",+ ),+ ("asset", {"__typename": "ReportingAsset", "assetKey": {"path": ["a", "b"]}}, "a/b"),+ ("deployment", {"__typename": "DagsterCloudDeployment", "deploymentId": 7}, "7"),+ ]+ )+ def test_entity_id_identifies_the_entity(self, _name: str, entity: dict[str, Any], expected: str) -> None:+ # The id is half the primary key, so two different entities collapsing onto one would+ # silently overwrite each other's measurements on every merge.+ entity_id, columns = _flatten_reporting_entity(entity)+ assert entity_id == expected+ assert "__typename" not in columns++ def test_an_unexpected_entity_kind_has_no_id(self) -> None:+ assert _flatten_reporting_entity({"__typename": "ReportingAssetGroup", "groupName": "g"})[0] is None+++class TestInsightsExpansion:+ def test_buckets_expand_against_the_shared_timestamps(self) -> None:+ # The response reports the bucket starts once and each entity's values positionally+ # against them, so a misalignment would file every measurement under the wrong day.+ entries = [+ {+ "entity": {"__typename": "DagsterCloudDeployment", "deploymentId": 7, "deploymentName": "prod"},+ "values": [1.5, None, 3.5],+ }+ ]+ rows = _expand_metric_entries("dagster_credits", entries, [EPOCH_2024, EPOCH_2024 + 86400, EPOCH_2024 + 172800])++ # A null bucket means the metric reported nothing, and a row per empty bucket per entity+ # would dwarf the measurements.+ assert [(row["timestamp"], row["value"]) for row in rows] == [+ (ISO_2024, 1.5),+ (_epoch_to_iso(EPOCH_2024 + 172800), 3.5),+ ]+ assert rows[0]["entityId"] == "7"+ assert rows[0]["deploymentName"] == "prod"+ assert rows[0]["metricName"] == "dagster_credits"++ def test_an_entity_with_no_id_is_dropped(self) -> None:+ entries = [{"entity": {"__typename": "ReportingAssetSelection", "selection": "*"}, "values": [1.0]}]+ assert _expand_metric_entries("m", entries, [EPOCH_2024]) == []+++def _metric_types_response(field: str, names: list[str]) -> MagicMock:+ return _gql_response(field, {"__typename": "MetricTypeList", "metricTypes": [{"metricName": n} for n in names]})+++def _metrics_response(field: str, entity_ids: list[int], timestamps: list[float]) -> MagicMock:+ return _gql_response(+ field,+ {+ "__typename": "ReportingMetrics",+ "timestamps": timestamps,+ "metrics": [+ {+ "entity": {"__typename": "DagsterCloudDeployment", "deploymentId": entity_id},+ "values": [1.0] * len(timestamps),+ }+ for entity_id in entity_ids+ ],+ },+ )+++class TestInsightsRequests:+ @patch(f"{MODULE}.make_tracked_session")+ def test_one_request_per_metric_name_checkpointed_as_it_goes(self, mock_session_cls: MagicMock) -> None:+ # reportingMetricsByDeployment takes one required metricName per call, so the catalog is+ # walked; a resume that replayed it from the start would re-fetch every metric.+ session = MagicMock()+ session.post.side_effect, calls = _route(+ {+ "MetricTypesForDeployment": _metric_types_response(+ "metricTypesForDeployment", ["dagster_credits", "execution_time_ms"]+ ),+ "ReportingMetricsByDeployment": _metrics_response("reportingMetricsByDeployment", [7], [EPOCH_2024]),+ }+ )+ mock_session_cls.return_value = session+ manager = _manager()++ pages = list(_make_insights_request("org", "prod", "tok", "insights_deployment_metrics", MagicMock(), manager))++ metric_variables = [v for op, v in calls if op == "ReportingMetricsByDeployment"]+ assert [v["metricsSelector"]["metricName"] for v in metric_variables] == [+ "dagster_credits",+ "execution_time_ms",+ ]+ assert [row["metricName"] for page in pages for row in page] == ["dagster_credits", "execution_time_ms"]+ assert manager.save_state.call_args_list == [+ call(DagsterCloudResumeConfig(parents_done=1)),+ call(DagsterCloudResumeConfig(parents_done=2)),+ ]++ @parameterized.expand([("incremental", EPOCH_2024), ("full_refresh", None)])+ @patch(f"{MODULE}.make_tracked_session")+ def test_the_watermark_bounds_the_reporting_window(+ self, _name: str, watermark: float | None, mock_session_cls: MagicMock+ ) -> None:+ session = MagicMock()+ session.post.side_effect, calls = _route(+ {+ "MetricTypesForDeployment": _metric_types_response("metricTypesForDeployment", ["dagster_credits"]),+ "ReportingMetricsByDeployment": _metrics_response("reportingMetricsByDeployment", [7], [EPOCH_2024]),+ }+ )+ mock_session_cls.return_value = session++ list(+ _make_insights_request(+ "org", "prod", "tok", "insights_deployment_metrics", MagicMock(), _manager(), watermark+ )+ )++ selector = next(v for op, v in calls if op == "ReportingMetricsByDeployment")["metricsSelector"]+ if watermark is None:+ # A first sync reaches back as far as Dagster+ reports, not to the epoch.+ assert selector["before"] - selector["after"] == pytest.approx(DAGSTER_CLOUD_INSIGHTS_LOOKBACK_DAYS * 86400)+ else:+ assert selector["after"] == watermark++ @patch(f"{MODULE}.make_tracked_session")+ def test_resume_skips_the_metrics_already_synced(self, mock_session_cls: MagicMock) -> None:+ session = MagicMock()+ session.post.side_effect, calls = _route(+ {+ "MetricTypesForDeployment": _metric_types_response(+ "metricTypesForDeployment", ["dagster_credits", "execution_time_ms"]+ ),+ "ReportingMetricsByDeployment": _metrics_response("reportingMetricsByDeployment", [7], [EPOCH_2024]),+ }+ )+ mock_session_cls.return_value = session++ list(+ _make_insights_request(+ "org",+ "prod",+ "tok",+ "insights_deployment_metrics",+ MagicMock(),+ _manager(DagsterCloudResumeConfig(parents_done=1)),+ )+ )++ metric_variables = [v for op, v in calls if op == "ReportingMetricsByDeployment"]+ assert [v["metricsSelector"]["metricName"] for v in metric_variables] == ["execution_time_ms"]++ @patch(f"{MODULE}.DAGSTER_CLOUD_INSIGHTS_ENTITY_LIMIT", 2)+ @patch(f"{MODULE}.make_tracked_session")+ def test_an_entity_list_at_the_cap_is_reported(self, mock_session_cls: MagicMock) -> None:+ # The resolver bounds its entity list with that filter limit and offers no cursor, so a+ # response at the cap is the only signal that entities were left out.+ session = MagicMock()+ session.post.side_effect, calls = _route(+ {+ "MetricTypesForDeployment": _metric_types_response("metricTypesForDeployment", ["dagster_credits"]),+ "ReportingMetricsByDeployment": _metrics_response("reportingMetricsByDeployment", [7, 8], [EPOCH_2024]),+ }+ )+ mock_session_cls.return_value = session+ logger = MagicMock()++ list(_make_insights_request("org", "prod", "tok", "insights_deployment_metrics", logger, _manager()))++ assert next(v for op, v in calls if op == "ReportingMetricsByDeployment")["metricsFilter"]["limit"] == 2+ assert "dagster_credits" in logger.warning.call_args[0][0]++ @patch(f"{MODULE}.make_tracked_session")+ def test_a_token_without_insights_fails_naming_the_resolver(self, mock_session_cls: MagicMock) -> None:+ # Insights is a Dagster+ entitlement; an empty table would read as "no metrics" rather+ # than "your token cannot see them".+ session = MagicMock()+ session.post.side_effect, _ = _route(+ {+ "MetricTypesForDeployment": _gql_response(+ "metricTypesForDeployment", {"__typename": "UnauthorizedError", "message": "not permitted"}+ )+ }+ )+ mock_session_cls.return_value = session++ with pytest.raises(Exception, match="metricTypesForDeployment returned UnauthorizedError"):+ list(_make_insights_request("org", "prod", "tok", "insights_deployment_metrics", MagicMock(), _manager()))++ def test_unknown_insights_endpoint_raises(self) -> None:+ with pytest.raises(ValueError, match="Unknown Dagster Cloud insights endpoint"):+ list(_make_insights_request("org", "prod", "tok", "runs", MagicMock(), _manager()))+++class TestOrganizationEndpoints:+ @patch(f"{MODULE}.make_tracked_session")+ def test_a_token_without_organization_access_fails_naming_the_resolver(self, mock_session_cls: MagicMock) -> None:+ session = MagicMock()+ session.post.return_value = _gql_response(+ "usersOrError", {"__typename": "UnauthorizedError", "message": "not permitted"}+ )+ mock_session_cls.return_value = session++ with pytest.raises(Exception, match="usersOrError returned UnauthorizedError"):+ list(_make_paginated_request("org", "prod", "tok", "users", MagicMock(), _manager()))