Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-warehouse): implement dagster_cloud import source (#71187)

Tom Owers30f051baa112
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index b495c11d46f0..7748c6dc052a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -164,6 +164,7 @@ the row lists both.
| cursor | HTTP | requests | ✅ |
| customer_io | HTTP + Webhook | requests + `WebhookSourceManager` | ✅ (App API) / ➖ (webhook) |
| customerly | HTTP | requests | ✅ |
+| dagster_cloud | HTTP (GraphQL) | requests | ✅ |
| datadog | HTTP | requests | ✅ |
| datahub | HTTP | requests | ✅ |
| dbt | HTTP | requests | ✅ |
@@ -659,7 +660,6 @@ doesn't conflict with concurrent PRs.
- couchbase
- criteo
- curve
-- dagster_cloud
- databricks
- datascope
- datorama
diff --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.py
new file mode 100644
index 000000000000..c2bbd709b166
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dagster_cloud/canonical_descriptions.py
@@ -0,0 +1,51 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+# Timestamp columns are Dagster epoch-seconds floats at the API, normalized to ISO-8601 UTC strings
+# on ingest (see dagster_cloud.py:_epoch_to_iso).
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "runs": {
+ "description": "Historical job/pipeline run records for the deployment, used to compute reliability, DORA, and SLA metrics.",
+ "docs_url": "https://docs.dagster.io/api/graphql",
+ "columns": {
+ "runId": "Unique identifier for the run.",
+ "jobName": "Name of the job (pipeline) the run executed.",
+ "pipelineName": "Legacy alias for the job name.",
+ "status": "Run status (e.g. QUEUED, STARTED, SUCCESS, FAILURE, CANCELED).",
+ "mode": "Execution mode the run used.",
+ "creationTime": "When the run record was created.",
+ "startTime": "When the run started executing.",
+ "endTime": "When the run finished executing.",
+ "updateTime": "When the run record was last updated (advances as the run's status changes).",
+ "tags": "Key/value tags attached to the run.",
+ "repositoryOrigin": "The code location and repository the run originated from.",
+ "assetSelection": "Asset keys the run targeted, each as a path list.",
+ },
+ },
+ "backfills": {
+ "description": "Partition backfills launched in the deployment, including asset backfills.",
+ "docs_url": "https://docs.dagster.io/api/graphql",
+ "columns": {
+ "id": "Unique identifier for the backfill.",
+ "status": "Bulk-action status of the backfill (e.g. REQUESTED, COMPLETED, FAILED, CANCELED).",
+ "timestamp": "When the backfill was created.",
+ "endTimestamp": "When the backfill finished, if it has.",
+ "numPartitions": "Number of partitions targeted by the backfill.",
+ "partitionSetName": "Name of the partition set the backfill ran against.",
+ "jobName": "Name of the job the backfill executed, if any.",
+ "isAssetBackfill": "Whether this is an asset backfill rather than a job backfill.",
+ "title": "User-provided title for the backfill.",
+ "description": "User-provided description for the backfill.",
+ "user": "User who launched the backfill.",
+ },
+ },
+ "assets": {
+ "description": "Catalog of assets known to the deployment.",
+ "docs_url": "https://docs.dagster.io/api/graphql",
+ "columns": {
+ "id": "Unique identifier for the asset (its serialized asset key).",
+ "key": "The asset key as a path list.",
+ },
+ },
+}
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.py
new file mode 100644
index 000000000000..6b1615bf15b6
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dagster_cloud/dagster_cloud.py
@@ -0,0 +1,297 @@
+import re
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime
+from typing import Any, Optional
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.dagster_cloud.queries import VALIDATION_QUERY
+from products.warehouse_sources.backend.temporal.data_imports.sources.dagster_cloud.settings import (
+ DAGSTER_CLOUD_ENDPOINTS,
+ DAGSTER_CLOUD_PAGE_SIZE,
+ DagsterCloudEndpointConfig,
+)
+
+# Dagster+'s edge occasionally returns short bursts of 5xx/429; retry in-process long enough to
+# ride those out. The wait blocks the source thread, but activity heartbeats are sent from an
+# independent background task, so a multi-minute wait here won't trip the heartbeat timeout.
+DAGSTER_CLOUD_MAX_RETRY_ATTEMPTS = 8
+
+# Only letters/numbers/hyphen/underscore: the organization is a `*.dagster.cloud` subdomain label
+# and the deployment a path segment, so restricting them keeps a crafted value from redirecting the
+# stored token to an arbitrary host.
+_SLUG_RE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_-]*$")
+
+
+class DagsterCloudRetryableError(Exception):
+ pass
+
+
+class DagsterCloudResumeConfig:
+ cursor: str
+
+
+def build_graphql_url(organization: str, deployment: str) -> str:
+ org = (organization or "").strip()
+ deploy = (deployment or "").strip()
+ if not _SLUG_RE.match(org) or not _SLUG_RE.match(deploy):
+ raise ValueError(
+ "Dagster+ organization and deployment must contain only letters, numbers, hyphens, and underscores."
+ )
+ return f"https://{org}.dagster.cloud/{deploy}/graphql"
+
+
+def _make_session(api_token: str) -> requests.Session:
+ # `Dagster-Cloud-Api-Token` is a custom header the sample-capture scrubber doesn't know, so the
+ # token must be redacted by value; redirects stay off because `requests` only strips the standard
+ # `Authorization` header on a cross-host redirect — a 30x would forward this header to its target.
+ return make_tracked_session(
+ headers={
+ "Dagster-Cloud-Api-Token": api_token,
+ "Content-Type": "application/json",
+ },
+ redact_values=(api_token,),
+ allow_redirects=False,
+ )
+
+
+def _epoch_to_iso(value: Any) -> Any:
+ """Normalize a Dagster epoch-seconds float to an ISO-8601 UTC string (fixed precision).
+
+ Fixed microsecond precision keeps the watermark's max comparison stable regardless of whether
+ the framework tracks it as a datetime or lexicographically. Non-numeric values pass through.
+ """
+ if isinstance(value, bool):
+ return value
+ if isinstance(value, int | float):
+ return datetime.fromtimestamp(float(value), tz=UTC).isoformat(timespec="microseconds")
+ return value
+
+
+def _to_epoch_seconds(value: Any) -> float | None:
+ """Convert an incremental watermark (datetime / date / ISO string / number) to epoch seconds.
+
+ RunsFilter's createdAfter/updatedAfter are Float epoch seconds, but the framework can hand the
+ stored watermark back in any of these shapes depending on how it round-tripped the column.
+ """
+ if value is None or isinstance(value, bool):
+ return None
+ if isinstance(value, int | float):
+ return float(value)
+ if isinstance(value, datetime):
+ dt = value if value.tzinfo is not None else value.replace(tzinfo=UTC)
+ return dt.timestamp()
+ if isinstance(value, date):
+ return datetime(value.year, value.month, value.day, tzinfo=UTC).timestamp()
+ if isinstance(value, str):
+ try:
+ dt = datetime.fromisoformat(value.replace("Z", "+00:00"))
+ except ValueError:
+ return None
+ if dt.tzinfo is None:
+ dt = dt.replace(tzinfo=UTC)
+ return dt.timestamp()
+ return None
+
+
+def _build_runs_filter(incremental_field: str | None, last_value_epoch: float | None) -> dict[str, float] | None:
+ if last_value_epoch is None:
+ return None
+ # createdAfter for a creation-time cursor, updatedAfter for everything else (the default).
+ filter_key = "createdAfter" if incremental_field == "creationTime" else "updatedAfter"
+ return {filter_key: last_value_epoch}
+
+
+def _normalize_row(row: dict[str, Any], endpoint_config: DagsterCloudEndpointConfig) -> dict[str, Any]:
+ if not endpoint_config.timestamp_fields:
+ return row
+ normalized = 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])
+ return normalized
+
+
+def _make_paginated_request(
+ organization: str,
+ deployment: str,
+ api_token: str,
+ endpoint_name: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[DagsterCloudResumeConfig],
+ runs_filter: dict[str, float] | None = None,
+) -> Iterator[list[dict[str, Any]]]:
+ endpoint_config = DAGSTER_CLOUD_ENDPOINTS.get(endpoint_name)
+ if not endpoint_config:
+ raise ValueError(f"Unknown Dagster Cloud endpoint: {endpoint_name}")
+
+ url = build_graphql_url(organization, deployment)
+ sess = _make_session(api_token)
+
+ @retry(
+ retry=retry_if_exception_type(DagsterCloudRetryableError),
+ stop=stop_after_attempt(DAGSTER_CLOUD_MAX_RETRY_ATTEMPTS),
+ wait=wait_exponential_jitter(initial=1, max=60),
+ reraise=True,
+ )
+ def execute(variables: dict[str, Any]) -> dict:
+ try:
+ response = sess.post(url, json={"query": endpoint_config.query, "variables": variables}, timeout=60)
+ except (requests.ConnectionError, requests.Timeout) as e:
+ # The session's urllib3 Retry only covers idempotent methods, so these POSTs get no
+ # transport-level retry — fold transient network failures into the application backoff.
+ raise DagsterCloudRetryableError(f"Dagster Cloud: transient network error - {e}")
+
+ if response.status_code >= 500:
+ raise DagsterCloudRetryableError(f"Dagster Cloud: server error {response.status_code}")
+ if response.status_code == 429:
+ raise DagsterCloudRetryableError("Dagster Cloud: rate limited (429)")
+ # Redirects are pinned off (see _make_session), so a 30x is terminal — following it would
+ # hand the token header to whatever host the Location points at.
+ if 300 <= response.status_code < 400:
+ raise Exception(f"Dagster Cloud: unexpected redirect ({response.status_code}) for url: {url}")
+
+ try:
+ payload = response.json()
+ except Exception as e:
+ if not response.ok:
+ raise Exception(f"{response.status_code} Client Error: {response.reason} for url: {url}") from e
+ # A 2xx whose body won't parse is almost always a truncated transfer; ride it out rather
+ # than failing the activity. Don't echo the body — a partial page can carry data.
+ raise DagsterCloudRetryableError(f"Dagster Cloud: incomplete JSON response ({e})") from e
+
+ if not response.ok:
+ raise Exception(f"{response.status_code} Client Error: {response.reason} for url: {url}")
+
+ if "errors" in payload:
+ messages = "; ".join(e.get("message", "") for e in payload["errors"])
+ if "rate limit" in messages.lower():
+ raise DagsterCloudRetryableError(f"Dagster Cloud: rate limited - {messages}")
+ raise Exception(f"Dagster Cloud GraphQL error: {messages}")
+
+ if "data" not in payload:
+ raise Exception(f"Unexpected Dagster Cloud response format. Keys: {list(payload.keys())}")
+
+ return payload
+
+ variables: dict[str, Any] = {"limit": DAGSTER_CLOUD_PAGE_SIZE}
+ if runs_filter is not None:
+ variables["filter"] = runs_filter
+
+ resume_config = resumable_source_manager.load_state()
+ if resume_config is not None and resume_config.cursor:
+ variables["cursor"] = resume_config.cursor
+ logger.debug(f"Dagster Cloud: resuming {endpoint_name} from saved cursor")
+
+ try:
+ while True:
+ payload = execute(variables)
+ container = payload["data"][endpoint_config.response_field]
+
+ typename = container.get("__typename")
+ if typename != endpoint_config.success_typename:
+ message = container.get("message", "")
+ raise Exception(f"Dagster Cloud {endpoint_config.response_field} returned {typename}: {message}")
+
+ rows = container.get(endpoint_config.results_key) or []
+ 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
+
+ if endpoint_config.cursor_mode == "connection":
+ next_cursor = container.get("cursor")
+ else:
+ assert endpoint_config.cursor_row_field is not None
+ next_cursor = rows[-1].get(endpoint_config.cursor_row_field)
+
+ 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)))
+ finally:
+ sess.close()
+
+
+def dagster_cloud_source(
+ organization: str,
+ deployment: str,
+ api_token: str,
+ endpoint_name: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[DagsterCloudResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+ incremental_field: str | None = None,
+) -> SourceResponse:
+ endpoint_config = DAGSTER_CLOUD_ENDPOINTS.get(endpoint_name)
+ if not endpoint_config:
+ raise ValueError(f"Unknown Dagster Cloud endpoint: {endpoint_name}")
+
+ def get_rows() -> Iterator[list[dict[str, Any]]]:
+ runs_filter = None
+ if (
+ endpoint_config.supports_incremental
+ and should_use_incremental_field
+ and 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)
+ logger.debug(f"Dagster Cloud: incremental sync for {endpoint_name} with filter {runs_filter}")
+
+ yield from _make_paginated_request(
+ organization=organization,
+ deployment=deployment,
+ api_token=api_token,
+ endpoint_name=endpoint_name,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ runs_filter=runs_filter,
+ )
+
+ return SourceResponse(
+ name=endpoint_name,
+ items=get_rows,
+ primary_keys=endpoint_config.primary_keys,
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if endpoint_config.partition_key else None,
+ partition_format="week" if endpoint_config.partition_key else None,
+ partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,
+ sort_mode=endpoint_config.sort_mode,
+ )
+
+
+def validate_credentials(organization: str, deployment: str, api_token: str) -> tuple[bool, str | None]:
+ try:
+ url = build_graphql_url(organization, deployment)
+ except ValueError as e:
+ return False, str(e)
+
+ try:
+ sess = _make_session(api_token)
+ response = sess.post(url, json={"query": VALIDATION_QUERY}, timeout=10)
+ if response.status_code in (401, 403):
+ return False, "Invalid Dagster+ API token, or the token cannot access this deployment."
+ if 300 <= response.status_code < 400:
+ return False, "Dagster+ responded with an unexpected redirect. Check the organization and deployment names."
+ response.raise_for_status()
+ data = response.json()
+ if "errors" in data:
+ return False, f"Dagster+ API error: {data['errors']}"
+ if data.get("data") is not None:
+ return True, None
+ return False, "Could not verify Dagster+ credentials"
+ except Exception as e:
+ return False, str(e)
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.py
new file mode 100644
index 000000000000..bc37a0b8053a
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dagster_cloud/queries.py
@@ -0,0 +1,70 @@
+# Hand-written GraphQL queries against the Dagster+ (Dagster Cloud) webserver schema.
+# The schema is explicitly documented as internal-webserver-oriented and subject to breaking
+# changes, so field sets are kept lean and defensive (scalars + well-known nested shapes only).
+
+# Cheap, permission-free probe used by validate_credentials: a bad token 401s at the gateway
+# before any resolver runs, so this never depends on which scopes the token carries.
+VALIDATION_QUERY = "query { __typename }"
+
+RUNS_QUERY = """
+query PaginatedRuns($limit: Int!, $cursor: String, $filter: RunsFilter) {
+ runsOrError(limit: $limit, cursor: $cursor, filter: $filter) {
+ __typename
+ ... on Runs {
+ results {
+ runId
+ jobName
+ pipelineName
+ status
+ mode
+ creationTime
+ startTime
+ endTime
+ updateTime
+ tags { key value }
+ repositoryOrigin { id repositoryName repositoryLocationName }
+ assetSelection { path }
+ }
+ }
+ ... on InvalidPipelineRunsFilterError { message }
+ ... on PythonError { message }
+ }
+}"""
+
+BACKFILLS_QUERY = """
+query PaginatedBackfills($limit: Int!, $cursor: String) {
+ partitionBackfillsOrError(limit: $limit, cursor: $cursor) {
+ __typename
+ ... on PartitionBackfills {
+ results {
+ id
+ status
+ timestamp
+ endTimestamp
+ numPartitions
+ partitionSetName
+ jobName
+ isAssetBackfill
+ title
+ description
+ user
+ }
+ }
+ ... on PythonError { message }
+ }
+}"""
+
+ASSETS_QUERY = """
+query PaginatedAssets($limit: Int!, $cursor: String) {
+ assetsOrError(limit: $limit, cursor: $cursor) {
+ __typename
+ ... on AssetConnection {
+ cursor
+ nodes {
+ id
+ key { path }
+ }
+ }
+ ... on PythonError { message }
+ }
+}"""
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.py
new file mode 100644
index 000000000000..d631fcdd9e3e
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dagster_cloud/settings.py
@@ -0,0 +1,110 @@
+from dataclasses import dataclass, field
+from typing import Literal
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SortMode
+from products.warehouse_sources.backend.temporal.data_imports.sources.dagster_cloud.queries import (
+ ASSETS_QUERY,
+ BACKFILLS_QUERY,
+ RUNS_QUERY,
+)
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+# Dagster's runsOrError caps well below 100 in practice; 100 is a safe request size across the
+# runs/backfills/assets list resolvers.
+DAGSTER_CLOUD_PAGE_SIZE = 100
+
+# "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"]
+
+
+def _incremental_datetime_field(name: str) -> IncrementalField:
+ return {
+ "label": name,
+ "type": IncrementalFieldType.DateTime,
+ "field": name,
+ "field_type": IncrementalFieldType.DateTime,
+ }
+
+
+@dataclass
+class DagsterCloudEndpointConfig:
+ name: str
+ query: 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
+ primary_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)
+ # For cursor_mode="row": which row field to use as the next-page cursor.
+ cursor_row_field: str | None = None
+ 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).
+ partition_key: str | None = None
+ # runsOrError / partitionBackfillsOrError return newest-first with no ascending option, so the
+ # rows genuinely arrive descending.
+ sort_mode: SortMode = "asc"
+ should_sync_default: bool = True
+
+
+DAGSTER_CLOUD_ENDPOINTS: dict[str, DagsterCloudEndpointConfig] = {
+ "runs": DagsterCloudEndpointConfig(
+ name="runs",
+ query=RUNS_QUERY,
+ response_field="runsOrError",
+ success_typename="Runs",
+ results_key="results",
+ cursor_mode="row",
+ cursor_row_field="runId",
+ primary_keys=["runId"],
+ timestamp_fields=["creationTime", "startTime", "endTime", "updateTime"],
+ # RunsFilter.updatedAfter / .createdAfter are genuine server-side epoch filters, so an
+ # incremental run only fetches runs changed since the watermark. updateTime is the default
+ # (a run's status advances after creation); creationTime is offered for append-style pulls.
+ incremental_fields=[
+ _incremental_datetime_field("updateTime"),
+ _incremental_datetime_field("creationTime"),
+ ],
+ supports_incremental=True,
+ partition_key="creationTime",
+ sort_mode="desc",
+ ),
+ "backfills": DagsterCloudEndpointConfig(
+ name="backfills",
+ query=BACKFILLS_QUERY,
+ response_field="partitionBackfillsOrError",
+ success_typename="PartitionBackfills",
+ results_key="results",
+ cursor_mode="row",
+ cursor_row_field="id",
+ primary_keys=["id"],
+ timestamp_fields=["timestamp", "endTimestamp"],
+ partition_key="timestamp",
+ # partitionBackfillsOrError exposes only a status filter, no timestamp filter, so an
+ # "incremental" pull would still walk full history every run — ship full refresh instead.
+ sort_mode="desc",
+ ),
+ "assets": DagsterCloudEndpointConfig(
+ name="assets",
+ query=ASSETS_QUERY,
+ response_field="assetsOrError",
+ success_typename="AssetConnection",
+ results_key="nodes",
+ cursor_mode="connection",
+ primary_keys=["id"],
+ # Catalog snapshot with no timestamp to filter or partition on — full refresh.
+ ),
+}
+
+ENDPOINTS = tuple(DAGSTER_CLOUD_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in DAGSTER_CLOUD_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dagster_cloud/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dagster_cloud/source.py
index fc344e7f665b..347411f23fe4 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/dagster_cloud/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dagster_cloud/source.py
@@ -1,30 +1,158 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (
+ SourceInputs,
+ SourceResponse,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema
+from products.warehouse_sources.backend.temporal.data_imports.sources.dagster_cloud.dagster_cloud import (
+ DagsterCloudResumeConfig,
+ dagster_cloud_source,
+ validate_credentials as validate_dagster_cloud_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.dagster_cloud.settings import (
+ DAGSTER_CLOUD_ENDPOINTS,
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import DagsterCloudSourceConfig
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class DagsterCloudSource(SimpleSource[DagsterCloudSourceConfig]):
+class DagsterCloudSource(ResumableSource[DagsterCloudSourceConfig, DagsterCloudResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.DAGSTERCLOUD
+ @property
+ def connection_host_fields(self) -> list[str]:
+ # Both fields determine the `*.dagster.cloud` URL the stored API token is sent to, so
+ # changing either must force the editor to re-enter the token.
+ return ["organization", "deployment"]
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.DAGSTER_CLOUD,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
- label="Dagster Labs (Dagster+ / Dagster Cloud)",
+ label="Dagster+ (Dagster Cloud)",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Connect your Dagster+ deployment to sync run history, backfills, and your asset catalog into the PostHog Data warehouse.
+
+Create a user token under **Organization settings → Tokens** in Dagster+, then enter your organization name, deployment name, and the token below.""",
iconPath="/static/services/dagster_cloud.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/dagster-cloud",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="organization",
+ label="Organization",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="your-org",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="deployment",
+ label="Deployment",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="prod",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="api_token",
+ label="API token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="user:...",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.dagster_cloud.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error": "Your Dagster+ API token is invalid or has been revoked. Create a new user token in your organization settings, then reconnect.",
+ "403 Client Error": "Your Dagster+ API token cannot access this deployment. Check the token's permissions and the organization/deployment names, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: DagsterCloudSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=DAGSTER_CLOUD_ENDPOINTS[endpoint].supports_incremental,
+ # Runs mutate after creation (status advances), so append-only would materialize
+ # duplicate rows per run — merge on the primary key is the only correct mode.
+ supports_append=False,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ should_sync_default=DAGSTER_CLOUD_ENDPOINTS[endpoint].should_sync_default,
+ )
+ for endpoint in ENDPOINTS
+ ]
+ if names is not None:
+ names_set = set(names)
+ schemas = [s for s in schemas if s.name in names_set]
+ return schemas
+
+ def validate_credentials(
+ self, config: DagsterCloudSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ return validate_dagster_cloud_credentials(config.organization, config.deployment, config.api_token)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[DagsterCloudResumeConfig]:
+ return ResumableSourceManager[DagsterCloudResumeConfig](inputs, DagsterCloudResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: DagsterCloudSourceConfig,
+ resumable_source_manager: ResumableSourceManager[DagsterCloudResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return dagster_cloud_source(
+ organization=config.organization,
+ deployment=config.deployment,
+ api_token=config.api_token,
+ endpoint_name=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=inputs.should_use_incremental_field,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value
+ if inputs.should_use_incremental_field
+ else None,
+ incremental_field=inputs.incremental_field,
)
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.py
new file mode 100644
index 000000000000..bb0dc63078eb
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dagster_cloud/tests/test_dagster_cloud.py
@@ -0,0 +1,324 @@
+from collections.abc import Iterable
+from datetime import UTC, date, datetime
+from typing import Any, cast
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.dagster_cloud.dagster_cloud import (
+ DagsterCloudResumeConfig,
+ _build_runs_filter,
+ _epoch_to_iso,
+ _make_paginated_request,
+ _to_epoch_seconds,
+ build_graphql_url,
+ dagster_cloud_source,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.dagster_cloud.settings import (
+ DAGSTER_CLOUD_ENDPOINTS,
+)
+
+# 2024-01-01T00:00:00Z
+EPOCH_2024 = 1704067200.0
+ISO_2024 = "2024-01-01T00:00:00.000000+00:00"
+
+MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.dagster_cloud.dagster_cloud"
+
+
+def _gql_response(response_field: str, container: dict[str, Any]) -> MagicMock:
+ response = MagicMock()
+ response.status_code = 200
+ response.ok = True
+ response.json.return_value = {"data": {response_field: container}}
+ return response
+
+
+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],
+ }
+
+
+def _assets_container(ids: list[str], cursor: str | None) -> dict[str, Any]:
+ return {
+ "__typename": "AssetConnection",
+ "cursor": cursor,
+ "nodes": [{"id": i, "key": {"path": [i]}} for i in ids],
+ }
+
+
+def _manager(saved: DagsterCloudResumeConfig | None = None) -> MagicMock:
+ manager = MagicMock()
+ manager.load_state.return_value = saved
+ return manager
+
+
+class TestBuildGraphqlUrl:
+ def test_valid(self) -> None:
+ assert build_graphql_url("my-org", "prod") == "https://my-org.dagster.cloud/prod/graphql"
+
+ @parameterized.expand(
+ [
+ ("space", "my org", "prod"),
+ ("host_injection", "evil.com/x", "prod"),
+ ("path_traversal", "../etc", "prod"),
+ ("empty_org", "", "prod"),
+ ("slash_in_deployment", "org", "prod/../admin"),
+ ("dot_in_org", "a.b", "prod"),
+ ]
+ )
+ def test_rejects_unsafe_values(self, _name: str, org: str, deployment: str) -> None:
+ # The org/deployment build the *.dagster.cloud URL the stored token is sent to; anything
+ # that isn't a plain slug could redirect the credential to another host.
+ with pytest.raises(ValueError):
+ build_graphql_url(org, deployment)
+
+
+class TestTimestampConversion:
+ def test_epoch_to_iso_is_fixed_precision(self) -> None:
+ assert _epoch_to_iso(EPOCH_2024) == ISO_2024
+
+ @parameterized.expand([("string", "not-a-number"), ("none", None)])
+ def test_epoch_to_iso_passes_through_non_numeric(self, _name: str, value: Any) -> None:
+ assert _epoch_to_iso(value) == value
+
+ @parameterized.expand(
+ [
+ ("float", EPOCH_2024, EPOCH_2024),
+ ("datetime_utc", datetime(2024, 1, 1, tzinfo=UTC), EPOCH_2024),
+ ("naive_datetime_treated_utc", datetime(2024, 1, 1), EPOCH_2024),
+ ("date", date(2024, 1, 1), EPOCH_2024),
+ ("iso_offset", "2024-01-01T00:00:00+00:00", EPOCH_2024),
+ ("iso_zulu", "2024-01-01T00:00:00Z", EPOCH_2024),
+ ("none", None, None),
+ ("garbage", "soon", None),
+ ]
+ )
+ def test_to_epoch_seconds(self, _name: str, value: Any, expected: float | None) -> None:
+ assert _to_epoch_seconds(value) == expected
+
+
+class TestBuildRunsFilter:
+ @parameterized.expand(
+ [
+ ("update_default", "updateTime", EPOCH_2024, {"updatedAfter": EPOCH_2024}),
+ ("none_field_defaults_to_updated", None, EPOCH_2024, {"updatedAfter": EPOCH_2024}),
+ ("creation_uses_created", "creationTime", EPOCH_2024, {"createdAfter": EPOCH_2024}),
+ ("no_value", "updateTime", None, None),
+ ]
+ )
+ def test_filter(self, _name: str, field: str | None, value: float | None, expected: dict | None) -> None:
+ assert _build_runs_filter(field, value) == expected
+
+
+class TestPagination:
+ @patch(f"{MODULE}.DAGSTER_CLOUD_PAGE_SIZE", 2)
+ @patch(f"{MODULE}.make_tracked_session")
+ def test_row_cursor_paginates_and_checkpoints(self, mock_session_cls: MagicMock) -> None:
+ # A full page continues from the last row's runId; a short page ends the walk.
+ session = MagicMock()
+ session.post.side_effect = [
+ _gql_response("runsOrError", _runs_container(["r1", "r2"])),
+ _gql_response("runsOrError", _runs_container(["r3"])),
+ ]
+ mock_session_cls.return_value = session
+ manager = _manager()
+
+ pages = list(_make_paginated_request("org", "prod", "tok", "runs", MagicMock(), manager))
+
+ assert [row["runId"] for page in pages for row in page] == ["r1", "r2", "r3"]
+ # Timestamps are normalized to ISO on the way out so partitioning can read them.
+ assert pages[0][0]["creationTime"] == ISO_2024
+ # Only the non-final page checkpoints, pointing at the next page's cursor.
+ manager.save_state.assert_called_once_with(DagsterCloudResumeConfig(cursor="r2"))
+ assert session.post.call_count == 2
+ # The token rides a custom header the sample scrubber doesn't know, so it must be redacted
+ # by value, and redirects must stay off so a 30x can't forward the header cross-host.
+ session_kwargs = mock_session_cls.call_args.kwargs
+ assert session_kwargs["redact_values"] == ("tok",)
+ assert session_kwargs["allow_redirects"] is False
+
+ @patch(f"{MODULE}.make_tracked_session")
+ def test_redirect_raises_without_retry(self, mock_session_cls: MagicMock) -> None:
+ # Redirects are pinned off; a 30x must fail fast (not spin through the retry budget).
+ session = MagicMock()
+ response = MagicMock()
+ response.status_code = 301
+ session.post.return_value = response
+ mock_session_cls.return_value = session
+
+ with pytest.raises(Exception, match="unexpected redirect"):
+ list(_make_paginated_request("org", "prod", "tok", "runs", MagicMock(), _manager()))
+
+ assert session.post.call_count == 1
+
+ @patch(f"{MODULE}.DAGSTER_CLOUD_PAGE_SIZE", 2)
+ @patch(f"{MODULE}.make_tracked_session")
+ def test_connection_cursor_mode_uses_connection_cursor(self, mock_session_cls: MagicMock) -> None:
+ # assetsOrError returns its next cursor on the connection object, not from the last row.
+ session = MagicMock()
+ session.post.side_effect = [
+ _gql_response("assetsOrError", _assets_container(["a1", "a2"], cursor="page2")),
+ _gql_response("assetsOrError", _assets_container(["a3"], cursor=None)),
+ ]
+ mock_session_cls.return_value = session
+ manager = _manager()
+
+ list(_make_paginated_request("org", "prod", "tok", "assets", MagicMock(), manager))
+
+ manager.save_state.assert_called_once_with(DagsterCloudResumeConfig(cursor="page2"))
+
+ @patch(f"{MODULE}.DAGSTER_CLOUD_PAGE_SIZE", 2)
+ @patch(f"{MODULE}.make_tracked_session")
+ def test_resumes_from_saved_cursor(self, mock_session_cls: MagicMock) -> None:
+ session = MagicMock()
+ captured: list[Any] = []
+
+ def side_effect(*_args: object, **kwargs: object) -> MagicMock:
+ payload = cast(dict, kwargs["json"])
+ captured.append(payload["variables"].get("cursor"))
+ return _gql_response("runsOrError", _runs_container(["r9"]))
+
+ session.post.side_effect = side_effect
+ mock_session_cls.return_value = session
+
+ list(
+ _make_paginated_request(
+ "org", "prod", "tok", "runs", MagicMock(), _manager(DagsterCloudResumeConfig(cursor="saved"))
+ )
+ )
+
+ assert captured[0] == "saved"
+
+ @patch(f"{MODULE}.DAGSTER_CLOUD_PAGE_SIZE", 2)
+ @patch(f"{MODULE}.make_tracked_session")
+ def test_error_typename_raises(self, mock_session_cls: MagicMock) -> None:
+ session = MagicMock()
+ session.post.return_value = _gql_response("runsOrError", {"__typename": "PythonError", "message": "boom"})
+ mock_session_cls.return_value = session
+
+ with pytest.raises(Exception, match="PythonError"):
+ list(_make_paginated_request("org", "prod", "tok", "runs", MagicMock(), _manager()))
+
+ @patch(f"{MODULE}.make_tracked_session")
+ def test_incremental_runs_send_server_filter(self, mock_session_cls: MagicMock) -> None:
+ # The whole point of incremental: the watermark must reach the API as a server-side filter,
+ # not be applied client-side after fetching everything.
+ session = MagicMock()
+ captured: list[Any] = []
+
+ def side_effect(*_args: object, **kwargs: object) -> MagicMock:
+ payload = cast(dict, kwargs["json"])
+ captured.append(payload["variables"].get("filter"))
+ return _gql_response("runsOrError", _runs_container([]))
+
+ session.post.side_effect = side_effect
+ mock_session_cls.return_value = session
+
+ response = dagster_cloud_source(
+ organization="org",
+ deployment="prod",
+ api_token="tok",
+ endpoint_name="runs",
+ logger=MagicMock(),
+ resumable_source_manager=_manager(),
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2024, 1, 1, tzinfo=UTC),
+ incremental_field="updateTime",
+ )
+ list(cast(Iterable[Any], response.items()))
+
+ assert captured[0] == {"updatedAfter": EPOCH_2024}
+
+
+class TestSourceResponse:
+ def test_runs_response_is_incremental_desc_partitioned(self) -> None:
+ response = dagster_cloud_source(
+ organization="org",
+ deployment="prod",
+ api_token="tok",
+ endpoint_name="runs",
+ logger=MagicMock(),
+ resumable_source_manager=_manager(),
+ )
+ assert response.primary_keys == ["runId"]
+ # runsOrError returns newest-first with no ascending option — declaring asc would corrupt
+ # the incremental watermark.
+ assert response.sort_mode == "desc"
+ assert response.partition_keys == ["creationTime"]
+ assert response.partition_mode == "datetime"
+
+ def test_assets_response_has_no_partitioning(self) -> None:
+ response = dagster_cloud_source(
+ organization="org",
+ deployment="prod",
+ api_token="tok",
+ endpoint_name="assets",
+ logger=MagicMock(),
+ resumable_source_manager=_manager(),
+ )
+ assert response.primary_keys == ["id"]
+ assert response.partition_mode is None
+ assert response.partition_keys is None
+
+ def test_unknown_endpoint_raises(self) -> None:
+ with pytest.raises(ValueError, match="Unknown Dagster Cloud endpoint"):
+ dagster_cloud_source("org", "prod", "tok", "nope", MagicMock(), _manager())
+
+
+class TestValidateCredentials:
+ @parameterized.expand([("unauthorized", 401), ("forbidden", 403)])
+ @patch(f"{MODULE}.make_tracked_session")
+ def test_auth_failure(self, _name: str, status: int, mock_session_cls: MagicMock) -> None:
+ session = MagicMock()
+ response = MagicMock()
+ response.status_code = status
+ session.post.return_value = response
+ mock_session_cls.return_value = session
+
+ ok, error = validate_credentials("org", "prod", "bad")
+ assert ok is False
+ assert error is not None
+
+ @patch(f"{MODULE}.make_tracked_session")
+ def test_success(self, mock_session_cls: MagicMock) -> None:
+ session = MagicMock()
+ response = MagicMock()
+ response.status_code = 200
+ response.json.return_value = {"data": {"__typename": "Query"}}
+ session.post.return_value = response
+ mock_session_cls.return_value = session
+
+ assert validate_credentials("org", "prod", "tok") == (True, None)
+ # Validation sends the same credentialed header — same redaction/no-redirect posture.
+ session_kwargs = mock_session_cls.call_args.kwargs
+ assert session_kwargs["redact_values"] == ("tok",)
+ assert session_kwargs["allow_redirects"] is False
+
+ @patch(f"{MODULE}.make_tracked_session")
+ def test_redirect_fails_validation(self, mock_session_cls: MagicMock) -> None:
+ session = MagicMock()
+ response = MagicMock()
+ response.status_code = 302
+ session.post.return_value = response
+ mock_session_cls.return_value = session
+
+ ok, error = validate_credentials("org", "prod", "tok")
+ assert ok is False
+ assert error is not None and "redirect" in error
+
+ def test_invalid_slug_fails_before_request(self) -> None:
+ ok, error = validate_credentials("bad host", "prod", "tok")
+ assert ok is False
+ assert error is not None
+
+
+class TestEndpointCatalog:
+ def test_only_runs_is_incremental(self) -> None:
+ # Backfills/assets have no server-side timestamp filter, so they must stay full-refresh.
+ incremental = {name for name, cfg in DAGSTER_CLOUD_ENDPOINTS.items() if cfg.supports_incremental}
+ assert incremental == {"runs"}
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.py
new file mode 100644
index 000000000000..d39100e2939e
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dagster_cloud/tests/test_dagster_cloud_source.py
@@ -0,0 +1,119 @@
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.dagster_cloud.dagster_cloud import (
+ DagsterCloudResumeConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.dagster_cloud.source import DagsterCloudSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.dagster_cloud.source"
+
+
+class TestDagsterCloudSourceConfig:
+ def test_source_type(self) -> None:
+ assert DagsterCloudSource().source_type == ExternalDataSourceType.DAGSTERCLOUD
+
+ def test_config_is_released_alpha_not_hidden(self) -> None:
+ config = DagsterCloudSource().get_source_config
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ # A finished source must be visible; unreleasedSource would hide it from every user.
+ assert config.unreleasedSource is None
+
+ def test_config_fields(self) -> None:
+ fields: dict[str, SourceFieldInputConfig] = {}
+ for field in DagsterCloudSource().get_source_config.fields:
+ assert isinstance(field, SourceFieldInputConfig)
+ fields[field.name] = field
+ assert set(fields) == {"organization", "deployment", "api_token"}
+ assert all(f.required for f in fields.values())
+ # The token is the only secret; it must be a password input so it's stored encrypted.
+ assert fields["api_token"].type == SourceFieldInputConfigType.PASSWORD
+ assert fields["api_token"].secret is True
+
+ def test_connection_host_fields_force_token_reentry(self) -> None:
+ # Both feed the *.dagster.cloud URL the token is sent to, so editing either must re-require it.
+ assert set(DagsterCloudSource().connection_host_fields) == {"organization", "deployment"}
+
+
+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 True
+ assert {f["field"] for f in schemas["runs"].incremental_fields} == {"updateTime", "creationTime"}
+ assert schemas["backfills"].supports_incremental is False
+ assert schemas["assets"].supports_incremental is False
+ # Runs mutate after creation, so append-only would duplicate rows — merge only, everywhere.
+ assert all(s.supports_append is False for s in schemas.values())
+
+ def test_names_filter(self) -> None:
+ schemas = DagsterCloudSource().get_schemas(MagicMock(), team_id=1, names=["runs"])
+ assert [s.name for s in schemas] == ["runs"]
+
+ 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 "Incremental" in tables["runs"]["sync_methods"]
+ assert "Incremental" not in tables["assets"]["sync_methods"]
+
+
+class TestDagsterCloudNonRetryableErrors:
+ @parameterized.expand(
+ [
+ ("auth_401", "401 Client Error: Unauthorized for url: https://acme.dagster.cloud/prod/graphql"),
+ ("forbidden_403", "403 Client Error: Forbidden for url: https://acme.dagster.cloud/prod/graphql"),
+ ]
+ )
+ def test_matches_permanent_failures(self, _name: str, observed: str) -> None:
+ errors = DagsterCloudSource().get_non_retryable_errors()
+ assert any(key in observed for key in errors)
+
+ @parameterized.expand(
+ [
+ ("server_500", "500 Client Error: Internal Server Error for url: https://acme.dagster.cloud/prod/graphql"),
+ ("rate_limited", "Dagster Cloud: rate limited (429)"),
+ ("network", "Dagster Cloud: transient network error - Read timed out"),
+ ]
+ )
+ def test_leaves_transient_errors_retryable(self, _name: str, observed: str) -> None:
+ errors = DagsterCloudSource().get_non_retryable_errors()
+ assert not any(key in observed for key in errors)
+
+
+class TestDagsterCloudPlumbing:
+ def test_resumable_manager_bound_to_resume_config(self) -> None:
+ manager = DagsterCloudSource().get_resumable_source_manager(MagicMock())
+ assert manager._data_class is DagsterCloudResumeConfig
+
+ @patch(f"{MODULE}.validate_dagster_cloud_credentials")
+ def test_validate_credentials_passes_config_fields(self, mock_validate: MagicMock) -> None:
+ mock_validate.return_value = (True, None)
+ config = MagicMock(organization="acme", deployment="prod", api_token="tok")
+
+ DagsterCloudSource().validate_credentials(config, team_id=1)
+
+ mock_validate.assert_called_once_with("acme", "prod", "tok")
+
+ @patch(f"{MODULE}.dagster_cloud_source")
+ def test_source_for_pipeline_gates_incremental_value(self, mock_source: MagicMock) -> None:
+ config = MagicMock(organization="acme", deployment="prod", api_token="tok")
+ inputs = MagicMock(
+ schema_name="runs",
+ should_use_incremental_field=False,
+ db_incremental_field_last_value="should-be-dropped",
+ incremental_field="updateTime",
+ )
+
+ DagsterCloudSource().source_for_pipeline(config, MagicMock(), inputs)
+
+ _, kwargs = mock_source.call_args
+ assert kwargs["endpoint_name"] == "runs"
+ assert kwargs["organization"] == "acme"
+ # A non-incremental run must not leak a stale watermark into the request.
+ assert kwargs["db_incremental_field_last_value"] is None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
index 2817da992831..80ebceda7a3c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
@@ -1193,7 +1193,9 @@ class CustomerlySourceConfig(config.Config):
@config.config
class DagsterCloudSourceConfig(config.Config):
- pass
+ organization: str
+ deployment: str
+ api_token: str
@config.config