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 prefect_cloud import source (#71152)

Tom Owersa7eed51b307a
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 0b511a55f9bc..253014bf96e2 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -356,6 +356,7 @@ the row lists both.
| plaid | HTTP | requests | ✅ |
| postgres | DB protocol | psycopg | ➖ |
| postmark | HTTP | requests | ✅ |
+| prefect_cloud | HTTP | requests | ✅ |
| pretix | HTTP | requests | ✅ |
| printify | HTTP | requests | ✅ |
| productboard | HTTP | requests | ✅ |
@@ -812,7 +813,6 @@ doesn't conflict with concurrent PRs.
- podium
- polygon
- poplar
-- prefect_cloud
- prestashop
- primetric
- productive
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 2b3165a6b2f4..b57fc8a3797c 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
@@ -3281,7 +3281,9 @@ class PostmarkSourceConfig(config.Config):
@config.config
class PrefectCloudSourceConfig(config.Config):
- pass
+ account_id: str
+ workspace_id: str
+ api_key: str
@config.config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/prefect_cloud/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/prefect_cloud/canonical_descriptions.py
new file mode 100644
index 000000000000..fa892d0b534b
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/prefect_cloud/canonical_descriptions.py
@@ -0,0 +1,140 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "flows": {
+ "description": "A flow is a Prefect workflow definition — the top-level container that flow runs are instances of.",
+ "docs_url": "https://docs.prefect.io/v3/api-ref/rest-api/server/flows",
+ "columns": {
+ "id": "Unique identifier for the flow.",
+ "created": "When the flow was first registered.",
+ "updated": "When the flow was last updated.",
+ "name": "The name of the flow.",
+ "tags": "A list of flow tags.",
+ "labels": "A dictionary of key-value labels on the flow.",
+ },
+ },
+ "flow_runs": {
+ "description": "A single execution (or scheduled execution) of a flow, with its state, timing, and infrastructure details.",
+ "docs_url": "https://docs.prefect.io/v3/api-ref/rest-api/server/flow-runs",
+ "columns": {
+ "id": "Unique identifier for the flow run.",
+ "created": "When the flow run record was created.",
+ "updated": "When the flow run record was last updated.",
+ "name": "The name of the flow run. Defaults to a random slug if not specified.",
+ "flow_id": "The id of the flow being run.",
+ "flow_name": "The name of the flow being run.",
+ "flow_version": "The version of the flow executed in this flow run.",
+ "deployment_id": "The deployment associated with this flow run, if any.",
+ "deployment_version": "The version of the deployment associated with this flow run.",
+ "work_queue_name": "The work queue that handled this flow run.",
+ "work_pool_name": "The name of the flow run's work pool.",
+ "parameters": "Parameters passed to the flow run.",
+ "tags": "A list of tags on the flow run.",
+ "parent_task_run_id": "If the flow run is a subflow, the id of the parent flow's dummy task representing it.",
+ "state_type": "The type of the flow run's current state (e.g. SCHEDULED, RUNNING, COMPLETED, FAILED).",
+ "state_name": "The name of the flow run's current state.",
+ "state": "The full current state object of the flow run.",
+ "run_count": "The number of times the flow run was executed.",
+ "expected_start_time": "The flow run's expected start time.",
+ "next_scheduled_start_time": "The next time the flow run is scheduled to start.",
+ "start_time": "The actual start time. Null until the run starts.",
+ "end_time": "The actual end time. Null until the run finishes.",
+ "total_run_time": "Total run time in seconds across all executions of the flow run.",
+ "estimated_run_time": "A real-time estimate of the total run time, in seconds.",
+ "estimated_start_time_delta": "The difference between actual and expected start time, in seconds.",
+ "auto_scheduled": "Whether the flow run was automatically scheduled by a deployment schedule.",
+ "idempotency_key": "Optional idempotency key ensuring the same flow run is not created multiple times.",
+ },
+ },
+ "task_runs": {
+ "description": "A single execution of a task within a flow run, with its state, timing, and retry details.",
+ "docs_url": "https://docs.prefect.io/v3/api-ref/rest-api/server/task-runs",
+ "columns": {
+ "id": "Unique identifier for the task run.",
+ "created": "When the task run record was created.",
+ "updated": "When the task run record was last updated.",
+ "name": "The name of the task run.",
+ "flow_run_id": "The flow run this task run belongs to.",
+ "task_key": "A unique identifier for the task being run.",
+ "dynamic_key": "Differentiates multiple runs of the same task within the same flow run.",
+ "cache_key": "Optional cache key; a completed state with the same key is used instead of re-running.",
+ "cache_expiration": "When the cached state should expire.",
+ "task_version": "The version of the task being run.",
+ "tags": "A list of tags on the task run.",
+ "state_type": "The type of the task run's current state (e.g. PENDING, RUNNING, COMPLETED, FAILED).",
+ "state_name": "The name of the task run's current state.",
+ "state": "The full current state object of the task run.",
+ "run_count": "The number of times the task run has been executed.",
+ "flow_run_run_count": "The flow retry this task run is associated with, if the parent flow retried.",
+ "expected_start_time": "The task run's expected start time.",
+ "next_scheduled_start_time": "The next time the task run is scheduled to start.",
+ "start_time": "The actual start time. Null until the run starts.",
+ "end_time": "The actual end time. Null until the run finishes.",
+ "total_run_time": "Total run time in seconds across all executions of the task run.",
+ "estimated_run_time": "A real-time estimate of total run time, in seconds.",
+ },
+ },
+ "deployments": {
+ "description": "A deployment is a server-side representation of a flow that can be scheduled and triggered remotely, with its schedule, work pool, and parameters.",
+ "docs_url": "https://docs.prefect.io/v3/api-ref/rest-api/server/deployments",
+ "columns": {
+ "id": "Unique identifier for the deployment.",
+ "created": "When the deployment was created.",
+ "updated": "When the deployment was last updated.",
+ "name": "The name of the deployment.",
+ "version": "An optional version for the deployment.",
+ "description": "A description of the deployment.",
+ "flow_id": "The flow this deployment is for.",
+ "paused": "Whether the deployment is paused.",
+ "disabled": "Whether the deployment is disabled.",
+ "schedules": "A list of schedules for the deployment.",
+ "is_schedule_active": "Whether the deployment schedule is active.",
+ "parameters": "Parameters for flow runs scheduled by the deployment.",
+ "tags": "A list of tags on the deployment.",
+ "work_queue_name": "The work queue the deployment submits runs to.",
+ "work_pool_name": "The name of the deployment's work pool.",
+ "last_polled": "The last time the deployment was polled for status updates.",
+ "entrypoint": "The path to the flow's entrypoint, relative to its working directory.",
+ "status": "Whether the deployment is ready to run flows.",
+ },
+ },
+ "work_pools": {
+ "description": "A work pool organizes and distributes flow runs to workers of a given infrastructure type.",
+ "docs_url": "https://docs.prefect.io/v3/api-ref/rest-api/server/work-pools",
+ "columns": {
+ "id": "Unique identifier for the work pool.",
+ "created": "When the work pool was created.",
+ "updated": "When the work pool was last updated.",
+ "name": "The name of the work pool.",
+ "description": "A description of the work pool.",
+ "type": "The work pool type (e.g. kubernetes, docker, process).",
+ "is_paused": "Whether the work pool is paused, stopping delivery of all work.",
+ "concurrency_limit": "An optional concurrency limit for the work pool.",
+ "is_push_pool": "Whether the pool is a push pool, which is not polled by workers.",
+ "is_mex_pool": "Whether the pool is a Prefect-managed pool.",
+ "status": "The current status of the work pool.",
+ "default_queue_id": "The id of the pool's default work queue.",
+ "last_polled": "The last time a worker polled this work pool for work.",
+ },
+ },
+ "work_queues": {
+ "description": "A work queue within a work pool that prioritizes and delivers flow runs to workers.",
+ "docs_url": "https://docs.prefect.io/v3/api-ref/rest-api/server/work-queues",
+ "columns": {
+ "id": "Unique identifier for the work queue.",
+ "created": "When the work queue was created.",
+ "updated": "When the work queue was last updated.",
+ "name": "The name of the work queue.",
+ "description": "An optional description of the work queue.",
+ "is_paused": "Whether the work queue is paused.",
+ "concurrency_limit": "An optional concurrency limit for the work queue.",
+ "priority": "The queue's priority. Lower values are higher priority (1 is the highest).",
+ "work_pool_id": "The work pool the queue belongs to.",
+ "work_pool_name": "The name of the work pool the queue resides within.",
+ "status": "The work queue's current status.",
+ "last_polled": "The last time a worker polled this queue for work.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/prefect_cloud/prefect_cloud.py b/products/warehouse_sources/backend/temporal/data_imports/sources/prefect_cloud/prefect_cloud.py
new file mode 100644
index 000000000000..61d6027dd4cb
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/prefect_cloud/prefect_cloud.py
@@ -0,0 +1,222 @@
+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.prefect_cloud.settings import (
+ PAGE_LIMIT,
+ PREFECT_CLOUD_ENDPOINTS,
+ PrefectCloudEndpointConfig,
+)
+
+PREFECT_CLOUD_API_BASE = "https://api.prefect.cloud/api"
+
+# Account and workspace IDs are UUIDs embedded in the request path. Rejecting anything else keeps
+# user input from rewriting the path (e.g. `../` traversal into another account's routes).
+_UUID_RE = re.compile(r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$")
+
+
+class PrefectCloudRetryableError(Exception):
+ pass
+
+
+class PrefectCloudResumeConfig:
+ # Row offset of the next page to fetch. 0 means "start from the first page".
+ offset: int = 0
+
+
+def normalize_uuid(value: str, label: str) -> str:
+ """Reduce user input to a bare lowercase UUID, raising ``ValueError`` on anything else."""
+ cleaned = value.strip().lower()
+ if not _UUID_RE.match(cleaned):
+ raise ValueError(
+ f"Invalid Prefect Cloud {label}: {value!r}. Copy the UUID from your workspace URL: "
+ "https://app.prefect.cloud/account/<account ID>/workspace/<workspace ID>."
+ )
+ return cleaned
+
+
+def _workspace_url(account_id: str, workspace_id: str) -> str:
+ account = normalize_uuid(account_id, "account ID")
+ workspace = normalize_uuid(workspace_id, "workspace ID")
+ return f"{PREFECT_CLOUD_API_BASE}/accounts/{account}/workspaces/{workspace}"
+
+
+def _headers(api_key: str) -> dict[str, str]:
+ return {"Authorization": f"Bearer {api_key}", "Accept": "application/json"}
+
+
+def _format_after(value: Any) -> str:
+ """Format an incremental cursor as the ISO 8601 UTC string Prefect's `after_` filters expect.
+
+ Microseconds are truncated, which can only shift the cursor slightly earlier — the re-pulled
+ boundary rows are deduped on the primary key at merge.
+ """
+ if isinstance(value, datetime):
+ aware = value if value.tzinfo is not None else value.replace(tzinfo=UTC)
+ return aware.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
+ if isinstance(value, date):
+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
+ return str(value)
+
+
+def _resolve_incremental_sort(config: PrefectCloudEndpointConfig, incremental_field: str | None) -> tuple[str, str]:
+ """Pick the (filter field, ascending sort) pair, honoring the user's chosen cursor field."""
+ if incremental_field and incremental_field in config.incremental_sorts:
+ return incremental_field, config.incremental_sorts[incremental_field]
+ first = next(iter(config.incremental_sorts))
+ return first, config.incremental_sorts[first]
+
+
+def _build_request_body(
+ config: PrefectCloudEndpointConfig,
+ offset: int,
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+ incremental_field: str | None,
+) -> dict[str, Any]:
+ """Build the POST body for one page. Prefect's filter endpoints take filter, sort, limit, and
+ offset in the JSON body (not query params), so the same watermark filter rides every page."""
+ body: dict[str, Any] = {"limit": PAGE_LIMIT, "offset": offset}
+ sort = config.sort
+
+ if (
+ config.filter_key
+ and config.incremental_sorts
+ and should_use_incremental_field
+ and db_incremental_field_last_value is not None
+ ):
+ field_name, sort = _resolve_incremental_sort(config, incremental_field)
+ body[config.filter_key] = {field_name: {"after_": _format_after(db_incremental_field_last_value)}}
+
+ if sort:
+ body["sort"] = sort
+ return body
+
+
+@retry(
+ retry=retry_if_exception_type(
+ (PrefectCloudRetryableError, requests.ReadTimeout, requests.ConnectionError),
+ ),
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+)
+def _fetch_page(
+ session: requests.Session,
+ url: str,
+ body: dict[str, Any],
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+) -> list[dict[str, Any]]:
+ response = session.post(url, json=body, headers=headers, timeout=60)
+
+ # Prefect Cloud rate limits per workspace; 429 and transient 5xx are worth backing off on.
+ if response.status_code == 429 or response.status_code >= 500:
+ raise PrefectCloudRetryableError(
+ f"Prefect Cloud API error (retryable): status={response.status_code}, url={url}"
+ )
+
+ if not response.ok:
+ logger.error(f"Prefect Cloud API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ return response.json()
+
+
+def get_rows(
+ account_id: str,
+ workspace_id: str,
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[PrefectCloudResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+ incremental_field: str | None = None,
+) -> Iterator[Any]:
+ config = PREFECT_CLOUD_ENDPOINTS[endpoint]
+ url = f"{_workspace_url(account_id, workspace_id)}{config.path}"
+ headers = _headers(api_key)
+ session = make_tracked_session()
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ offset = resume.offset if resume is not None else 0
+ if offset:
+ logger.debug(f"Prefect Cloud: resuming {endpoint} from offset {offset}")
+
+ while True:
+ body = _build_request_body(
+ config, offset, should_use_incremental_field, db_incremental_field_last_value, incremental_field
+ )
+ items = _fetch_page(session, url, body, headers, logger)
+ if not items:
+ break
+
+ yield items
+ offset += len(items)
+
+ # A short page is the last one. Checkpoint only while more pages remain, and save AFTER
+ # yielding so a crash re-yields the last page rather than skipping it — merge dedupes on
+ # the primary key.
+ if len(items) < PAGE_LIMIT:
+ break
+ resumable_source_manager.save_state(PrefectCloudResumeConfig(offset=offset))
+
+
+def prefect_cloud_source(
+ account_id: str,
+ workspace_id: str,
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[PrefectCloudResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+ incremental_field: str | None = None,
+) -> SourceResponse:
+ config = PREFECT_CLOUD_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ account_id=account_id,
+ workspace_id=workspace_id,
+ api_key=api_key,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ incremental_field=incremental_field,
+ ),
+ primary_keys=config.primary_keys,
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format="month" if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ )
+
+
+def validate_credentials(account_id: str, workspace_id: str, api_key: str) -> tuple[bool, int | None]:
+ """Probe the workspace's flows/filter endpoint to confirm the key reaches the workspace.
+
+ Returns ``(ok, status_code)``. ``status_code`` is ``None`` on a transport error. Raises
+ ``ValueError`` if either ID is malformed so the caller can surface a precise message.
+ """
+ url = f"{_workspace_url(account_id, workspace_id)}/flows/filter"
+ try:
+ response = make_tracked_session().post(url, json={"limit": 1}, headers=_headers(api_key), timeout=10)
+ except Exception:
+ return False, None
+ return response.status_code == 200, response.status_code
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/prefect_cloud/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/prefect_cloud/settings.py
new file mode 100644
index 000000000000..323dda8a187a
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/prefect_cloud/settings.py
@@ -0,0 +1,106 @@
+from dataclasses import dataclass, field
+from typing import Optional
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+# Prefect Cloud caps `limit` on the /filter endpoints at 200 (the server's default API limit).
+PAGE_LIMIT = 200
+
+# Runs can change state (finish, fail, retry) after their start time has passed the watermark, so
+# incremental syncs re-read a trailing day; merge dedupes the re-pulled rows on `id`.
+RUN_LOOKBACK_SECONDS = 24 * 60 * 60
+
+
+def _datetime_incremental_field(name: str) -> IncrementalField:
+ return {
+ "label": name,
+ "type": IncrementalFieldType.DateTime,
+ "field": name,
+ "field_type": IncrementalFieldType.DateTime,
+ }
+
+
+@dataclass
+class PrefectCloudEndpointConfig:
+ name: str
+ path: str # POST path under the workspace base URL, e.g. "/flow_runs/filter"
+ # Body key carrying the endpoint's own nested filter object (e.g. "flow_runs"). None when the
+ # endpoint's filter model exposes no server-side time filter — those endpoints are full refresh.
+ filter_key: Optional[str] = None
+ # Advertised incremental cursor field -> the ascending sort enum the API accepts for it. Only
+ # fields with BOTH a server-side `after_` filter and an ascending sort are advertised, so the
+ # pipeline's asc watermark stays correct.
+ incremental_sorts: dict[str, str] = field(default_factory=dict)
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ # Explicit stable sort for full-refresh paging — the API's implicit default is ID_DESC on run
+ # endpoints, and offset pagination skips/dups rows without a stable order.
+ sort: Optional[str] = None
+ # Stable creation-time field to partition by. Only set on the high-volume run tables.
+ partition_key: Optional[str] = None
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ default_incremental_lookback_seconds: Optional[int] = None
+ should_sync_default: bool = True
+
+
+PREFECT_CLOUD_ENDPOINTS: dict[str, PrefectCloudEndpointConfig] = {
+ "flows": PrefectCloudEndpointConfig(
+ name="flows",
+ path="/flows/filter",
+ # FlowFilter has no time-range filters (only id/name/tags), so full refresh only.
+ sort="CREATED_ASC",
+ ),
+ "flow_runs": PrefectCloudEndpointConfig(
+ name="flow_runs",
+ path="/flow_runs/filter",
+ filter_key="flow_runs",
+ incremental_sorts={
+ "start_time": "START_TIME_ASC",
+ "expected_start_time": "EXPECTED_START_TIME_ASC",
+ },
+ incremental_fields=[
+ _datetime_incremental_field("start_time"),
+ _datetime_incremental_field("expected_start_time"),
+ ],
+ # `expected_start_time` is set on every run (including scheduled ones whose `start_time`
+ # is still null), so it's the stable full-refresh paging order.
+ sort="EXPECTED_START_TIME_ASC",
+ partition_key="created",
+ default_incremental_lookback_seconds=RUN_LOOKBACK_SECONDS,
+ ),
+ "task_runs": PrefectCloudEndpointConfig(
+ name="task_runs",
+ path="/task_runs/filter",
+ filter_key="task_runs",
+ # TaskRunSort has no START_TIME_ASC, so `expected_start_time` is the only cursor whose
+ # server-side filter can be paired with an ascending sort.
+ incremental_sorts={"expected_start_time": "EXPECTED_START_TIME_ASC"},
+ incremental_fields=[_datetime_incremental_field("expected_start_time")],
+ sort="EXPECTED_START_TIME_ASC",
+ partition_key="created",
+ default_incremental_lookback_seconds=RUN_LOOKBACK_SECONDS,
+ ),
+ "deployments": PrefectCloudEndpointConfig(
+ name="deployments",
+ path="/deployments/filter",
+ # DeploymentFilter has no time-range filters, so full refresh only.
+ sort="CREATED_ASC",
+ ),
+ "work_pools": PrefectCloudEndpointConfig(
+ name="work_pools",
+ path="/work_pools/filter",
+ sort="NAME_ASC",
+ ),
+ "work_queues": PrefectCloudEndpointConfig(
+ name="work_queues",
+ path="/work_queues/filter",
+ # The work_queues filter body accepts no `sort` at all; the table is small enough that
+ # offset paging on the implicit order is acceptable for full refresh.
+ sort=None,
+ ),
+}
+
+ENDPOINTS = tuple(PREFECT_CLOUD_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in PREFECT_CLOUD_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/prefect_cloud/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/prefect_cloud/source.py
index d3931b483dcb..45f047d774e9 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/prefect_cloud/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/prefect_cloud/source.py
@@ -1,30 +1,185 @@
-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.generated_configs import PrefectCloudSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.prefect_cloud.prefect_cloud import (
+ PrefectCloudResumeConfig,
+ prefect_cloud_source,
+ validate_credentials as validate_prefect_cloud_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.prefect_cloud.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ PREFECT_CLOUD_ENDPOINTS,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class PrefectCloudSource(SimpleSource[PrefectCloudSourceConfig]):
+class PrefectCloudSource(ResumableSource[PrefectCloudSourceConfig, PrefectCloudResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.PREFECTCLOUD
+ @property
+ def connection_host_fields(self) -> list[str]:
+ # account_id and workspace_id select which Prefect Cloud workspace the stored API key is
+ # used against; changing either must require re-entering the secret so a preserved key
+ # can't be retargeted at another workspace the key happens to have access to.
+ return ["account_id", "workspace_id"]
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.PREFECT_CLOUD,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
- label="Prefect (Prefect Technologies, Inc.)",
+ label="Prefect Cloud",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Enter your Prefect Cloud account ID, workspace ID, and an API key to pull your flow and task run history into the PostHog Data warehouse.
+
+Both IDs are in your workspace URL: `https://app.prefect.cloud/account/<account ID>/workspace/<workspace ID>`.
+
+Create an API key under [API keys in your profile settings](https://app.prefect.cloud/my/api-keys), or use a service account key on paid tiers. The key inherits the owner's permissions, so read access to the workspace is all it needs.""",
iconPath="/static/services/prefect_cloud.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/prefect-cloud",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="account_id",
+ label="Account ID",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="00000000-0000-0000-0000-000000000000",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="workspace_id",
+ label="Workspace ID",
+ type=SourceFieldInputConfigType.TEXT,
+ required=True,
+ placeholder="00000000-0000-0000-0000-000000000000",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="pnu_...",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.prefect_cloud.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ # 401/403 surface as a requests HTTPError when `_fetch_page` calls `raise_for_status()`.
+ # Retrying can never fix a credential/permission problem, so fail the sync. Match the
+ # stable status text and base host, not the per-request account/workspace path.
+ "401 Client Error: Unauthorized for url: https://api.prefect.cloud": "Your Prefect Cloud API key is invalid or has expired. Create a new API key in Prefect Cloud, then reconnect.",
+ "403 Client Error: Forbidden for url: https://api.prefect.cloud": "Your Prefect Cloud API key does not have access to this workspace. Check the key's workspace permissions, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: PrefectCloudSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ def _description(endpoint: str) -> str | None:
+ if endpoint in ("flow_runs", "task_runs"):
+ return (
+ "Incremental syncs re-read a 24-hour trailing window so recently started runs pick up "
+ "state changes; runs that change state later than that are only refreshed by a full refresh"
+ )
+ return None
+
+ def _build_schema(endpoint: str) -> SourceSchema:
+ endpoint_config = PREFECT_CLOUD_ENDPOINTS[endpoint]
+ has_incremental = bool(endpoint_config.incremental_sorts)
+ return SourceSchema(
+ name=endpoint,
+ supports_incremental=has_incremental,
+ supports_append=has_incremental,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ should_sync_default=endpoint_config.should_sync_default,
+ default_incremental_lookback_seconds=endpoint_config.default_incremental_lookback_seconds,
+ description=_description(endpoint),
+ )
+
+ schemas = [_build_schema(endpoint) 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: PrefectCloudSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ try:
+ ok, status_code = validate_prefect_cloud_credentials(config.account_id, config.workspace_id, config.api_key)
+ except ValueError as e:
+ return False, str(e)
+
+ if ok:
+ return True, None
+ if status_code == 401:
+ return False, "Invalid Prefect Cloud API key"
+ if status_code == 404:
+ return False, "Prefect Cloud account or workspace not found — check the account ID and workspace ID"
+ return False, "Could not connect to Prefect Cloud with the provided account ID, workspace ID, and API key"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[PrefectCloudResumeConfig]:
+ return ResumableSourceManager[PrefectCloudResumeConfig](inputs, PrefectCloudResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: PrefectCloudSourceConfig,
+ resumable_source_manager: ResumableSourceManager[PrefectCloudResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return prefect_cloud_source(
+ account_id=config.account_id,
+ workspace_id=config.workspace_id,
+ api_key=config.api_key,
+ endpoint=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/prefect_cloud/tests/test_prefect_cloud.py b/products/warehouse_sources/backend/temporal/data_imports/sources/prefect_cloud/tests/test_prefect_cloud.py
new file mode 100644
index 000000000000..1e8e8efade9c
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/prefect_cloud/tests/test_prefect_cloud.py
@@ -0,0 +1,269 @@
+from datetime import UTC, date, datetime
+from typing import Any
+
+import pytest
+from unittest.mock import MagicMock
+
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.prefect_cloud import prefect_cloud
+from products.warehouse_sources.backend.temporal.data_imports.sources.prefect_cloud.prefect_cloud import (
+ PrefectCloudResumeConfig,
+ _build_request_body,
+ _format_after,
+ get_rows,
+ normalize_uuid,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.prefect_cloud.settings import (
+ PAGE_LIMIT,
+ PREFECT_CLOUD_ENDPOINTS,
+)
+
+_ACCOUNT_ID = "11111111-2222-3333-4444-555555555555"
+_WORKSPACE_ID = "66666666-7777-8888-9999-aaaaaaaaaaaa"
+_WORKSPACE_URL = f"https://api.prefect.cloud/api/accounts/{_ACCOUNT_ID}/workspaces/{_WORKSPACE_ID}"
+
+
+class TestNormalizeUuid:
+ @parameterized.expand(
+ [
+ ("lowercase", _ACCOUNT_ID, _ACCOUNT_ID),
+ ("uppercase", _ACCOUNT_ID.upper(), _ACCOUNT_ID),
+ ("whitespace", f" {_ACCOUNT_ID} ", _ACCOUNT_ID),
+ ]
+ )
+ def test_valid_uuids(self, _name: str, value: str, expected: str) -> None:
+ assert normalize_uuid(value, "account ID") == expected
+
+ @parameterized.expand(
+ [
+ ("path_injection", "1111/../other-account"),
+ ("url", "https://app.prefect.cloud/account/11111111-2222-3333-4444-555555555555"),
+ ("empty", ""),
+ ("not_a_uuid", "my-workspace"),
+ ]
+ )
+ def test_invalid_uuids_raise(self, _name: str, value: str) -> None:
+ with pytest.raises(ValueError):
+ normalize_uuid(value, "account ID")
+
+
+class TestFormatAfter:
+ @parameterized.expand(
+ [
+ ("utc_datetime", datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04T02:58:14Z"),
+ ("naive_datetime", datetime(2026, 3, 4, 2, 58, 14), "2026-03-04T02:58:14Z"),
+ ("date_value", date(2026, 3, 4), "2026-03-04T00:00:00Z"),
+ ("string_passthrough", "2026-03-04T02:58:14Z", "2026-03-04T02:58:14Z"),
+ ]
+ )
+ def test_format(self, _name: str, value: Any, expected: str) -> None:
+ result = _format_after(value)
+ assert result == expected
+ assert "+00:00" not in result
+
+
+class TestBuildRequestBody:
+ def test_incremental_adds_nested_filter_and_ascending_sort(self) -> None:
+ body = _build_request_body(
+ PREFECT_CLOUD_ENDPOINTS["flow_runs"],
+ offset=0,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC),
+ incremental_field="start_time",
+ )
+ assert body == {
+ "limit": PAGE_LIMIT,
+ "offset": 0,
+ "flow_runs": {"start_time": {"after_": "2026-03-04T02:58:14Z"}},
+ "sort": "START_TIME_ASC",
+ }
+
+ def test_incremental_honors_users_chosen_cursor_field(self) -> None:
+ body = _build_request_body(
+ PREFECT_CLOUD_ENDPOINTS["flow_runs"],
+ offset=0,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 3, 4, tzinfo=UTC),
+ incremental_field="expected_start_time",
+ )
+ assert body["flow_runs"] == {"expected_start_time": {"after_": "2026-03-04T00:00:00Z"}}
+ assert body["sort"] == "EXPECTED_START_TIME_ASC"
+
+ def test_incremental_unknown_field_falls_back_to_first_advertised(self) -> None:
+ body = _build_request_body(
+ PREFECT_CLOUD_ENDPOINTS["flow_runs"],
+ offset=0,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 3, 4, tzinfo=UTC),
+ incremental_field="updated",
+ )
+ assert body["flow_runs"] == {"start_time": {"after_": "2026-03-04T00:00:00Z"}}
+ assert body["sort"] == "START_TIME_ASC"
+
+ def test_incremental_without_cursor_omits_filter(self) -> None:
+ body = _build_request_body(
+ PREFECT_CLOUD_ENDPOINTS["flow_runs"],
+ offset=0,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=None,
+ incremental_field="start_time",
+ )
+ assert body == {"limit": PAGE_LIMIT, "offset": 0, "sort": "EXPECTED_START_TIME_ASC"}
+
+ def test_full_refresh_endpoint_never_filters(self) -> None:
+ # flows has no server-side time filter; a cursor must not leak into the request.
+ body = _build_request_body(
+ PREFECT_CLOUD_ENDPOINTS["flows"],
+ offset=200,
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 3, 4, tzinfo=UTC),
+ incremental_field="created",
+ )
+ assert body == {"limit": PAGE_LIMIT, "offset": 200, "sort": "CREATED_ASC"}
+
+ def test_work_queues_body_has_no_sort(self) -> None:
+ # The work_queues filter endpoint rejects unknown body keys, and its model has no `sort`.
+ body = _build_request_body(
+ PREFECT_CLOUD_ENDPOINTS["work_queues"],
+ offset=0,
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=None,
+ incremental_field=None,
+ )
+ assert body == {"limit": PAGE_LIMIT, "offset": 0}
+
+
+class _FakeResumableManager:
+ def __init__(self, state: PrefectCloudResumeConfig | None = None) -> None:
+ self._state = state
+ self.saved: list[PrefectCloudResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._state is not None
+
+ def load_state(self) -> PrefectCloudResumeConfig | None:
+ return self._state
+
+ def save_state(self, data: PrefectCloudResumeConfig) -> None:
+ self.saved.append(data)
+
+
+def _patch_fetch(monkeypatch: Any, pages: dict[int, list[dict]]) -> list[dict]:
+ """Serve pages keyed by the request body's offset, recording each body."""
+ bodies: list[dict] = []
+
+ def fake_fetch(session: Any, url: str, body: dict, headers: dict[str, str], logger: Any) -> list[dict]:
+ bodies.append({"url": url, **body})
+ return pages.get(body["offset"], [])
+
+ monkeypatch.setattr(prefect_cloud, "_fetch_page", fake_fetch)
+ return bodies
+
+
+def _collect(manager: _FakeResumableManager, **kwargs: Any) -> list[dict]:
+ rows: list[dict] = []
+ for batch in get_rows(
+ account_id=_ACCOUNT_ID,
+ workspace_id=_WORKSPACE_ID,
+ api_key="pnu_key",
+ logger=MagicMock(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ **kwargs,
+ ):
+ rows.extend(batch)
+ return rows
+
+
+class TestGetRows:
+ def test_paginates_until_short_page(self, monkeypatch: Any) -> None:
+ pages = {
+ 0: [{"id": str(n)} for n in range(PAGE_LIMIT)],
+ PAGE_LIMIT: [{"id": "last"}],
+ }
+ bodies = _patch_fetch(monkeypatch, pages)
+ rows = _collect(_FakeResumableManager(), endpoint="flows")
+
+ assert len(rows) == PAGE_LIMIT + 1
+ assert rows[-1]["id"] == "last"
+ assert [b["offset"] for b in bodies] == [0, PAGE_LIMIT]
+ assert all(b["url"] == f"{_WORKSPACE_URL}/flows/filter" for b in bodies)
+
+ def test_saves_resume_state_after_each_yielded_full_page(self, monkeypatch: Any) -> None:
+ pages = {
+ 0: [{"id": str(n)} for n in range(PAGE_LIMIT)],
+ PAGE_LIMIT: [{"id": "last"}],
+ }
+ _patch_fetch(monkeypatch, pages)
+ manager = _FakeResumableManager()
+ _collect(manager, endpoint="flows")
+
+ # State is saved only while more pages remain (after the full page), never on the last page.
+ assert manager.saved == [PrefectCloudResumeConfig(offset=PAGE_LIMIT)]
+
+ def test_resumes_from_saved_offset(self, monkeypatch: Any) -> None:
+ pages = {PAGE_LIMIT: [{"id": "resumed"}]}
+ bodies = _patch_fetch(monkeypatch, pages)
+ rows = _collect(_FakeResumableManager(PrefectCloudResumeConfig(offset=PAGE_LIMIT)), endpoint="flows")
+
+ assert [r["id"] for r in rows] == ["resumed"]
+ assert [b["offset"] for b in bodies] == [PAGE_LIMIT]
+
+ def test_stops_on_empty_first_page(self, monkeypatch: Any) -> None:
+ bodies = _patch_fetch(monkeypatch, {0: []})
+ rows = _collect(_FakeResumableManager(), endpoint="flows")
+
+ assert rows == []
+ assert len(bodies) == 1
+
+ def test_incremental_filter_rides_every_page(self, monkeypatch: Any) -> None:
+ # Prefect takes the filter in the POST body, so later pages must carry the same watermark.
+ pages = {
+ 0: [{"id": str(n)} for n in range(PAGE_LIMIT)],
+ PAGE_LIMIT: [{"id": "last"}],
+ }
+ bodies = _patch_fetch(monkeypatch, pages)
+ _collect(
+ _FakeResumableManager(),
+ endpoint="flow_runs",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC),
+ incremental_field="start_time",
+ )
+
+ assert all(b["flow_runs"] == {"start_time": {"after_": "2026-03-04T02:58:14Z"}} for b in bodies)
+ assert all(b["sort"] == "START_TIME_ASC" for b in bodies)
+
+
+class TestValidateCredentials:
+ @pytest.mark.parametrize(
+ "status_code, expected",
+ [
+ (200, (True, 200)),
+ (401, (False, 401)),
+ (404, (False, 404)),
+ ],
+ )
+ def test_status_mapping(self, status_code: int, expected: tuple, monkeypatch: Any) -> None:
+ session = MagicMock()
+ session.post.return_value = MagicMock(status_code=status_code)
+ monkeypatch.setattr(prefect_cloud, "make_tracked_session", lambda: session)
+
+ assert validate_credentials(_ACCOUNT_ID, _WORKSPACE_ID, "pnu_key") == expected
+ assert session.post.call_args.args[0] == f"{_WORKSPACE_URL}/flows/filter"
+
+ def test_transport_error_returns_none_status(self, monkeypatch: Any) -> None:
+ session = MagicMock()
+ session.post.side_effect = ConnectionError("boom")
+ monkeypatch.setattr(prefect_cloud, "make_tracked_session", lambda: session)
+
+ assert validate_credentials(_ACCOUNT_ID, _WORKSPACE_ID, "pnu_key") == (False, None)
+
+ def test_malformed_id_raises_before_any_request(self, monkeypatch: Any) -> None:
+ session = MagicMock()
+ monkeypatch.setattr(prefect_cloud, "make_tracked_session", lambda: session)
+
+ with pytest.raises(ValueError):
+ validate_credentials("not-a-uuid", _WORKSPACE_ID, "pnu_key")
+ session.post.assert_not_called()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/prefect_cloud/tests/test_prefect_cloud_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/prefect_cloud/tests/test_prefect_cloud_source.py
new file mode 100644
index 000000000000..9c4caaabe655
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/prefect_cloud/tests/test_prefect_cloud_source.py
@@ -0,0 +1,194 @@
+import pytest
+from unittest import mock
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import PrefectCloudSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.prefect_cloud.prefect_cloud import (
+ PrefectCloudResumeConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.prefect_cloud.settings import (
+ ENDPOINTS,
+ PREFECT_CLOUD_ENDPOINTS,
+ RUN_LOOKBACK_SECONDS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.prefect_cloud.source import PrefectCloudSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+# Endpoints whose Prefect filter model exposes a server-side `after_` time filter with an
+# ascending sort; everything else is full refresh only.
+_INCREMENTAL_ENDPOINTS = {"flow_runs", "task_runs"}
+_FULL_REFRESH_ENDPOINTS = {"flows", "deployments", "work_pools", "work_queues"}
+
+_ACCOUNT_ID = "11111111-2222-3333-4444-555555555555"
+_WORKSPACE_ID = "66666666-7777-8888-9999-aaaaaaaaaaaa"
+
+
+class TestPrefectCloudSource:
+ def setup_method(self):
+ self.source = PrefectCloudSource()
+ self.team_id = 123
+ self.config = PrefectCloudSourceConfig(account_id=_ACCOUNT_ID, workspace_id=_WORKSPACE_ID, api_key="pnu_key")
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.PREFECTCLOUD
+
+ def test_get_source_config(self):
+ config = self.source.get_source_config
+
+ assert config.name.value == "PrefectCloud"
+ assert config.label == "Prefect Cloud"
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.unreleasedSource is None
+ assert config.iconPath == "/static/services/prefect_cloud.png"
+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/prefect-cloud"
+
+ field_names = [f.name for f in config.fields if isinstance(f, SourceFieldInputConfig)]
+ assert field_names == ["account_id", "workspace_id", "api_key"]
+
+ def test_connection_host_fields_force_secret_reentry_on_workspace_change(self):
+ # Both IDs retarget the stored API key, so changing either must require re-entering it.
+ assert self.source.connection_host_fields == ["account_id", "workspace_id"]
+
+ def test_api_key_field_is_secret_password(self):
+ config = self.source.get_source_config
+ api_key_field = next(f for f in config.fields if isinstance(f, SourceFieldInputConfig) and f.name == "api_key")
+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD
+ assert api_key_field.secret is True
+ assert api_key_field.required is True
+
+ @pytest.mark.parametrize(
+ "observed_error",
+ [
+ "401 Client Error: Unauthorized for url: https://api.prefect.cloud/api/accounts/x/workspaces/y/flow_runs/filter",
+ "403 Client Error: Forbidden for url: https://api.prefect.cloud/api/accounts/x/workspaces/y/task_runs/filter",
+ ],
+ )
+ def test_non_retryable_errors_match_auth_failures(self, observed_error):
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable_errors)
+
+ @pytest.mark.parametrize(
+ "other_error",
+ [
+ "429 Client Error: Too Many Requests for url: https://api.prefect.cloud/api/accounts/x/workspaces/y/flow_runs/filter",
+ "500 Server Error: Internal Server Error for url: https://api.prefect.cloud/api/accounts/x/workspaces/y/flows/filter",
+ "HTTPSConnectionPool(host='api.prefect.cloud', port=443): Read timed out.",
+ ],
+ )
+ def test_non_retryable_errors_do_not_match_transient(self, other_error):
+ non_retryable_errors = self.source.get_non_retryable_errors()
+ assert not any(key in other_error for key in non_retryable_errors)
+
+ def test_get_schemas_match_endpoints_with_correct_sync_modes(self):
+ schemas = {schema.name: schema for schema in self.source.get_schemas(self.config, self.team_id)}
+
+ assert set(schemas) == set(ENDPOINTS)
+ for name in _INCREMENTAL_ENDPOINTS:
+ assert schemas[name].supports_incremental is True
+ assert schemas[name].supports_append is True
+ assert [f["field"] for f in schemas[name].incremental_fields] == list(
+ PREFECT_CLOUD_ENDPOINTS[name].incremental_sorts
+ )
+ # Losing the trailing re-read window silently freezes run states at first import.
+ assert schemas[name].default_incremental_lookback_seconds == RUN_LOOKBACK_SECONDS
+ for name in _FULL_REFRESH_ENDPOINTS:
+ assert schemas[name].supports_incremental is False
+ assert schemas[name].supports_append is False
+ assert schemas[name].incremental_fields == []
+
+ def test_get_schemas_filtered_by_names(self):
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["flow_runs"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "flow_runs"
+
+ def test_lists_tables_without_credentials_publishes_catalog(self):
+ # Static endpoint catalog (no I/O) — the public docs table list should render.
+ assert self.source.lists_tables_without_credentials is True
+ documented = self.source.get_documented_tables()
+ assert {table["name"] for table in documented} == set(ENDPOINTS)
+
+ def test_canonical_descriptions_cover_every_endpoint(self):
+ canonical = self.source.get_canonical_descriptions()
+ assert set(canonical) == set(PREFECT_CLOUD_ENDPOINTS)
+
+ @pytest.mark.parametrize(
+ "mock_return, expected_valid, expected_message",
+ [
+ ((True, 200), True, None),
+ ((False, 401), False, "Invalid Prefect Cloud API key"),
+ (
+ (False, 404),
+ False,
+ "Prefect Cloud account or workspace not found — check the account ID and workspace ID",
+ ),
+ (
+ (False, None),
+ False,
+ "Could not connect to Prefect Cloud with the provided account ID, workspace ID, and API key",
+ ),
+ ],
+ )
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.prefect_cloud.source.validate_prefect_cloud_credentials"
+ )
+ def test_validate_credentials(self, mock_validate, mock_return, expected_valid, expected_message):
+ mock_validate.return_value = mock_return
+
+ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)
+
+ assert is_valid is expected_valid
+ assert error_message == expected_message
+ mock_validate.assert_called_once_with(_ACCOUNT_ID, _WORKSPACE_ID, "pnu_key")
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.prefect_cloud.source.validate_prefect_cloud_credentials"
+ )
+ def test_validate_credentials_surfaces_malformed_ids(self, mock_validate):
+ mock_validate.side_effect = ValueError("Invalid Prefect Cloud account ID: 'not-a-uuid'.")
+
+ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)
+
+ assert is_valid is False
+ assert "Invalid Prefect Cloud account ID" in (error_message or "")
+
+ def test_get_resumable_source_manager_bound_to_resume_config(self):
+ inputs = mock.MagicMock()
+ manager = self.source.get_resumable_source_manager(inputs)
+ assert manager._data_class is PrefectCloudResumeConfig
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.prefect_cloud.source.prefect_cloud_source"
+ )
+ def test_source_for_pipeline_plumbs_arguments(self, mock_prefect_cloud_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "flow_runs"
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"
+ inputs.incremental_field = "start_time"
+ manager = mock.MagicMock()
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_prefect_cloud_source.assert_called_once()
+ kwargs = mock_prefect_cloud_source.call_args.kwargs
+ assert kwargs["account_id"] == _ACCOUNT_ID
+ assert kwargs["workspace_id"] == _WORKSPACE_ID
+ assert kwargs["api_key"] == "pnu_key"
+ assert kwargs["endpoint"] == "flow_runs"
+ assert kwargs["resumable_source_manager"] is manager
+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01T00:00:00Z"
+ assert kwargs["incremental_field"] == "start_time"
+
+ @mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.prefect_cloud.source.prefect_cloud_source"
+ )
+ def test_source_for_pipeline_omits_cursor_when_not_incremental(self, mock_prefect_cloud_source):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "flows"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = "2026-01-01T00:00:00Z"
+
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ assert mock_prefect_cloud_source.call_args.kwargs["db_incremental_field_last_value"] is None