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 hatchet import source (#70019)

Tom Owers89515ecfee7d
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 2a30b0527293..c57245114ae9 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -200,6 +200,7 @@ the row lists both.
| guardian | HTTP | requests | ✅ |
| guru | HTTP | requests | ✅ |
| harvey | HTTP | requests | ✅ |
+| hatchet | HTTP | requests | ✅ |
| healthchecks | HTTP | requests | ✅ |
| height | HTTP | requests | ✅ |
| hellobaton | HTTP | requests | ✅ |
@@ -588,7 +589,6 @@ doesn't conflict with concurrent PRs.
- gusto
- harness
- harvey
-- hatchet
- heap
- helicone
- helpscout
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 a82105bdb22c..1e0ca4c63324 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
@@ -1679,7 +1679,9 @@ class HarveySourceConfig(config.Config):
@config.config
class HatchetSourceConfig(config.Config):
- pass
+ api_token: str
+ host: str | None = None
+ tenant_id: str | None = None
@config.config
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hatchet/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hatchet/canonical_descriptions.py
new file mode 100644
index 000000000000..6bb2524649e7
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hatchet/canonical_descriptions.py
@@ -0,0 +1,84 @@
+"""Canonical, documentation-sourced descriptions for Hatchet endpoints and columns.
+
+Sourced from the Hatchet stable v1 REST API contract
+(https://github.com/hatchet-dev/hatchet/tree/main/api-contracts/openapi). Keyed by the endpoint
+names in `settings.py` `HATCHET_ENDPOINTS`, which match the `ExternalDataSchema.name` of a synced
+table. The nested `metadata` object is flattened onto each row (`id`, `created_at`, `updated_at`),
+so those appear as top-level columns. Columns absent here fall back to LLM enrichment.
+"""
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+# workflow_runs and tasks are both V1TaskSummary rows off the same endpoint (only_tasks toggles
+# DAG-level runs vs individual task runs), so they share a column dictionary.
+_TASK_SUMMARY_COLUMNS = {
+ "id": "Unique identifier for the run.",
+ "created_at": "Time at which the run resource was created.",
+ "updated_at": "Time at which the run resource was last updated.",
+ "displayName": "Human-readable name for the run.",
+ "status": "Current run status (QUEUED, RUNNING, COMPLETED, CANCELLED, or FAILED).",
+ "type": "Whether the run is a DAG or a single TASK.",
+ "workflowId": "Identifier of the workflow this run belongs to.",
+ "workflowName": "Name of the workflow this run belongs to.",
+ "workflowVersionId": "Identifier of the workflow version that produced this run.",
+ "workflowRunExternalId": "External identifier of the parent workflow run.",
+ "taskId": "Internal numeric identifier of the task.",
+ "taskExternalId": "External identifier of the task.",
+ "taskInsertedAt": "Time at which the task was inserted.",
+ "actionId": "Identifier of the action executed by the task.",
+ "stepId": "Identifier of the step the task corresponds to.",
+ "tenantId": "Identifier of the tenant that owns the run.",
+ "createdAt": "Time at which the run was created.",
+ "startedAt": "Time at which the run started executing.",
+ "finishedAt": "Time at which the run finished executing.",
+ "duration": "Duration of the run, in milliseconds.",
+ "retryCount": "Number of times the task has been retried.",
+ "attempt": "The current attempt number.",
+ "input": "The input payload the run was invoked with.",
+ "output": "The output payload the run produced.",
+ "errorMessage": "Error message when the run failed.",
+ "additionalMetadata": "Arbitrary key-value metadata attached to the run.",
+ "isDurable": "Whether the task is a durable task.",
+ "numSpawnedChildren": "Number of child tasks spawned by this run.",
+ "parentTaskExternalId": "External identifier of the parent task, if any.",
+}
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "workflow_runs": {
+ "description": "A workflow (DAG) run or standalone task run in Hatchet, capturing its status, timings, and input/output payloads.",
+ "docs_url": "https://docs.hatchet.run/home/runs-and-tasks",
+ "columns": _TASK_SUMMARY_COLUMNS,
+ },
+ "tasks": {
+ "description": "An individual task run in Hatchet, including the tasks that make up a DAG workflow run.",
+ "docs_url": "https://docs.hatchet.run/home/runs-and-tasks",
+ "columns": _TASK_SUMMARY_COLUMNS,
+ },
+ "events": {
+ "description": "An event ingested into the Hatchet tenant. Events can trigger workflow runs.",
+ "docs_url": "https://docs.hatchet.run/home/run-on-event",
+ "columns": {
+ "id": "Unique identifier for the event.",
+ "created_at": "Time at which the event was created.",
+ "updated_at": "Time at which the event was last updated.",
+ "key": "The event key used to match workflows that run on this event.",
+ "tenantId": "Identifier of the tenant the event belongs to.",
+ "scope": "Scope used to categorize or filter the event.",
+ "seenAt": "Time at which the event was seen.",
+ "payload": "The event payload.",
+ "additionalMetadata": "Arbitrary key-value metadata attached to the event.",
+ "workflowRunSummary": "Summary of the workflow runs triggered by this event.",
+ "triggeredRuns": "External identifiers of the runs triggered by this event.",
+ "triggeringWebhookName": "Name of the webhook that triggered the event, if any.",
+ },
+ },
+ "event_keys": {
+ "description": "The distinct event keys seen in the tenant, used to match workflows that run on events.",
+ "docs_url": "https://docs.hatchet.run/home/run-on-event",
+ "columns": {
+ "key": "An event key seen in the tenant.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hatchet/hatchet.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hatchet/hatchet.py
new file mode 100644
index 000000000000..8c6c068e9456
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hatchet/hatchet.py
@@ -0,0 +1,433 @@
+import re
+import json
+import base64
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime, timedelta
+from typing import Any, Optional
+from urllib.parse import urlencode, urlparse
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from posthog.cloud_utils import is_cloud
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.batcher import Batcher
+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.mixins import _is_host_safe
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.hatchet.settings import (
+ FULL_REFRESH_SINCE_DAYS,
+ HATCHET_ENDPOINTS,
+ HatchetEndpointConfig,
+)
+
+# Hatchet Cloud's API host. Self-hosted users override it, but the token also embeds a `server_url`
+# claim we prefer when the user leaves the host blank.
+DEFAULT_HATCHET_HOST = "https://cloud.onhatchet.run"
+
+# Returned when the resolved host resolves to a private/internal address on cloud (SSRF guard).
+HOST_NOT_ALLOWED_ERROR = "Hatchet host is not allowed"
+
+# Returned when a cloud connection would send the bearer token over plaintext HTTP.
+INSECURE_SCHEME_ERROR = "Hatchet host must use https"
+
+
+class HatchetRetryableError(Exception):
+ pass
+
+
+class HatchetHostNotAllowedError(Exception):
+ """The resolved host is blocked (SSRF guard) or tried to redirect the authenticated request."""
+
+ pass
+
+
+class HatchetTokenError(ValueError):
+ """The API token could not be decoded, or is missing the tenant / server URL claims we need."""
+
+
+class HatchetResumeConfig:
+ # Offset to resume paginating from. The `since` used when the sync started is pinned here so a
+ # resumed run keeps paging the same time window (a different `since` would shift what each
+ # offset points at).
+ offset: int
+ since: str | None = None
+
+
[email protected](frozen=True)
+class HatchetConnection:
+ base_url: str
+ tenant_id: str
+
+
+def _decode_token_claims(token: str) -> dict[str, Any]:
+ """Decode the (unverified) claims from a Hatchet API token. Hatchet tokens are standard 3-part
+ JWTs whose payload carries `sub` (the tenant id) and `server_url`; the SDKs read them the same
+ way. We only read claims, never trust them for auth, so skipping signature verification is safe."""
+ parts = token.split(".")
+ if len(parts) != 3:
+ raise HatchetTokenError("Invalid Hatchet API token format")
+ payload = parts[1]
+ payload += "=" * ((4 - len(payload) % 4) % 4) # restore base64 padding the JWT stripped
+ try:
+ return json.loads(base64.urlsafe_b64decode(payload))
+ except (ValueError, TypeError) as e:
+ raise HatchetTokenError("Could not decode the Hatchet API token") from e
+
+
+def _normalize_origin(raw: str) -> str:
+ """Reduce a host or URL to a clean `scheme://host[:port]` origin.
+
+ Any path, query, or fragment is dropped so a crafted host value can't extend or retarget the
+ fixed Hatchet API path. A bare host gains an https scheme; an explicit http/https scheme is
+ preserved (self-hosted instances may run plaintext on a private network)."""
+ raw = raw.strip()
+ if not re.match(r"^https?://", raw, flags=re.IGNORECASE):
+ raw = f"https://{raw}"
+ parsed = urlparse(raw)
+ scheme = parsed.scheme.lower()
+ scheme = scheme if scheme in ("http", "https") else "https"
+ return f"{scheme}://{parsed.netloc}"
+
+
+def _host_from_url(base_url: str) -> str:
+ return (urlparse(base_url).hostname or "").lower()
+
+
+def _is_scheme_safe(base_url: str) -> tuple[bool, str | None]:
+ """On cloud, refuse to send the bearer token over plaintext HTTP.
+
+ Self-hosted PostHog may reach a private Hatchet instance over http on a trusted network, so — as
+ with the SSRF host check — this is only enforced on cloud, where a plaintext origin would leak
+ the token in transit."""
+ if urlparse(base_url).scheme == "https" or not is_cloud():
+ return True, None
+ return False, INSECURE_SCHEME_ERROR
+
+
+def resolve_connection(api_token: str, host: str | None = None, tenant_id: str | None = None) -> HatchetConnection:
+ """Resolve the base URL and tenant id for the API calls.
+
+ Both can be supplied explicitly (self-hosted overrides), otherwise they are read from the
+ token's `server_url` / `sub` claims. The explicit host still falls back to the Cloud default so
+ a token without a `server_url` claim keeps working. The resolved host — from the field or the
+ claim — is normalized to a clean origin; callers still SSRF-check it before sending the token."""
+ claims = _decode_token_claims(api_token)
+
+ resolved_host = _normalize_origin(host or claims.get("server_url") or DEFAULT_HATCHET_HOST)
+ resolved_tenant = (tenant_id or claims.get("sub") or "").strip()
+
+ if not resolved_tenant:
+ raise HatchetTokenError(
+ "Could not determine the Hatchet tenant id from the token. Enter it manually in the tenant id field."
+ )
+
+ return HatchetConnection(base_url=resolved_host, tenant_id=resolved_tenant)
+
+
+def _get_headers(api_token: str) -> dict[str, str]:
+ return {
+ "Authorization": f"Bearer {api_token}",
+ "Accept": "application/json",
+ }
+
+
+def _format_datetime(value: Any) -> str:
+ """Format a datetime/date as an RFC 3339 timestamp with a `Z` suffix (what Hatchet expects)."""
+ if isinstance(value, datetime):
+ dt = value if value.tzinfo is not None else value.replace(tzinfo=UTC)
+ elif isinstance(value, date):
+ dt = datetime.combine(value, datetime.min.time(), tzinfo=UTC)
+ else:
+ return str(value)
+ return dt.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%S.%fZ")
+
+
+def _to_datetime(value: Any) -> datetime | None:
+ if isinstance(value, datetime):
+ return value if value.tzinfo is not None else value.replace(tzinfo=UTC)
+ if isinstance(value, date):
+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC)
+ return None
+
+
+def _resolve_since(
+ config: HatchetEndpointConfig,
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+) -> datetime | None:
+ """Compute the `since` timestamp to send.
+
+ - Incremental run with a watermark: the watermark, shifted back by the lookback overlap and
+ capped at now (a future-dated cursor would make the API return nothing).
+ - First incremental run (no watermark): floored to `default_lookback_days` so the backfill is
+ bounded instead of crawling the whole retention window.
+ - Full refresh (or `since` required but no incremental): a fixed far-past floor so we pull
+ everything still retained.
+ """
+ now = datetime.now(UTC)
+
+ if should_use_incremental_field and db_incremental_field_last_value:
+ watermark = _to_datetime(db_incremental_field_last_value) or now
+ watermark = min(watermark, now)
+ if config.incremental_lookback:
+ watermark = watermark - config.incremental_lookback
+ return watermark
+
+ if should_use_incremental_field and config.default_lookback_days:
+ return now - timedelta(days=config.default_lookback_days)
+
+ if config.requires_since:
+ return now - timedelta(days=FULL_REFRESH_SINCE_DAYS)
+
+ return None
+
+
+def _build_initial_params(
+ config: HatchetEndpointConfig,
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+) -> dict[str, Any]:
+ params: dict[str, Any] = dict(config.extra_params)
+ if config.page_size:
+ params["limit"] = config.page_size
+
+ if config.supports_time_window:
+ since = _resolve_since(config, should_use_incremental_field, db_incremental_field_last_value)
+ if since is not None:
+ params["since"] = _format_datetime(since)
+
+ return params
+
+
+def _build_url(base_url: str, path: str, params: dict[str, Any]) -> str:
+ url = f"{base_url}{path}"
+ if not params:
+ return url
+ return f"{url}?{urlencode(params)}"
+
+
+@retry(
+ retry=retry_if_exception_type(
+ (
+ HatchetRetryableError,
+ requests.ReadTimeout,
+ requests.ConnectionError,
+ requests.exceptions.ChunkedEncodingError,
+ )
+ ),
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+)
+def _fetch_page(session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger) -> Any:
+ response = session.get(url, headers=headers, timeout=60)
+
+ # 429 and transient 5xx are retryable; auth/permission errors below are not.
+ if response.status_code == 429 or response.status_code >= 500:
+ raise HatchetRetryableError(f"Hatchet API error (retryable): status={response.status_code}, url={url}")
+
+ # Redirects are disabled as an SSRF boundary; a 3xx means the host tried to bounce the
+ # authenticated request elsewhere, so fail instead of parsing (or following) it.
+ if 300 <= response.status_code < 400:
+ raise HatchetHostNotAllowedError(
+ f"Hatchet API returned an unexpected redirect: status={response.status_code}, url={url}"
+ )
+
+ if not response.ok:
+ logger.error(f"Hatchet API error: status={response.status_code}, body={response.text}, url={url}")
+ response.raise_for_status()
+
+ return response.json()
+
+
+def validate_credentials(
+ api_token: str, host: str | None, tenant_id: str | None, team_id: int | None = None
+) -> tuple[bool, str | None]:
+ """Probe the token by listing event keys — the cheapest tenant-scoped read with no required
+ filters. A 200 confirms the token is genuine and scoped to the tenant."""
+ try:
+ connection = resolve_connection(api_token, host, tenant_id)
+ except HatchetTokenError as e:
+ return False, str(e)
+
+ # The host (from the `host` field or the token's `server_url` claim) is user-controlled and the
+ # bearer token is sent to it, so block hosts that resolve to private/internal addresses (SSRF).
+ # Only enforced on cloud — see _is_host_safe.
+ if team_id is not None:
+ host_ok, host_err = _is_host_safe(_host_from_url(connection.base_url), team_id)
+ if not host_ok:
+ return False, host_err or HOST_NOT_ALLOWED_ERROR
+
+ scheme_ok, scheme_err = _is_scheme_safe(connection.base_url)
+ if not scheme_ok:
+ return False, scheme_err or INSECURE_SCHEME_ERROR
+
+ url = f"{connection.base_url}/api/v1/stable/tenants/{connection.tenant_id}/events/keys"
+ try:
+ # Redact the token, never follow a redirect off the validated host, and keep the response
+ # out of HTTP sample capture — Hatchet payloads can carry opaque secrets the name-based
+ # scrubber won't recognise (all defense-in-depth alongside the host check above).
+ response = make_tracked_session(redact_values=(api_token,), allow_redirects=False, capture=False).get(
+ url, headers=_get_headers(api_token), timeout=10
+ )
+ except requests.exceptions.RequestException as e:
+ return False, str(e)
+
+ if response.status_code == 200:
+ return True, None
+ if response.status_code == 401:
+ return False, "Invalid or expired Hatchet API token"
+ if response.status_code == 403:
+ return False, "This Hatchet API token does not have access to the tenant"
+ if response.status_code == 404:
+ return False, "Hatchet tenant not found. Check the tenant id and host."
+ return False, f"Hatchet API returned status {response.status_code}"
+
+
+def _normalize_row(item: Any) -> dict[str, Any]:
+ """Flatten the resource envelope into a flat row.
+
+ Standard resources carry a nested `metadata` object (id, createdAt, updatedAt); we lift those to
+ top-level `id` / `created_at` / `updated_at` so the primary key, partition, and incremental
+ cursor resolve against real columns. Event keys come back as bare strings, wrapped into a single
+ `key` column."""
+ if isinstance(item, str):
+ return {"key": item}
+
+ if isinstance(item, dict) and isinstance(item.get("metadata"), dict):
+ metadata = item.pop("metadata")
+ item["id"] = metadata.get("id")
+ item["created_at"] = metadata.get("createdAt")
+ item["updated_at"] = metadata.get("updatedAt")
+
+ return item
+
+
+def get_rows(
+ api_token: str,
+ connection: HatchetConnection,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[HatchetResumeConfig],
+ team_id: int,
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[Any]:
+ config = HATCHET_ENDPOINTS[endpoint]
+ headers = _get_headers(api_token)
+
+ # Re-check at run time (not just at source-create): the host could have been edited or now
+ # resolve to an internal address (SSRF / DNS rebinding). Only enforced on cloud.
+ host_ok, host_err = _is_host_safe(_host_from_url(connection.base_url), team_id)
+ if not host_ok:
+ raise HatchetHostNotAllowedError(host_err or HOST_NOT_ALLOWED_ERROR)
+
+ # Never send the bearer token over plaintext HTTP on cloud (see _is_scheme_safe).
+ scheme_ok, scheme_err = _is_scheme_safe(connection.base_url)
+ if not scheme_ok:
+ raise HatchetHostNotAllowedError(scheme_err or INSECURE_SCHEME_ERROR)
+
+ batcher = Batcher(logger=logger, chunk_size=2000, chunk_size_bytes=100 * 1024 * 1024)
+ # Redact the token and never follow a redirect off the validated host. Keep response bodies out
+ # of HTTP sample capture — workflow inputs/outputs and event payloads are opaque and can carry
+ # secrets the name-based scrubber won't recognise.
+ session = make_tracked_session(redact_values=(api_token,), allow_redirects=False, capture=False)
+
+ params = _build_initial_params(config, should_use_incremental_field, db_incremental_field_last_value)
+ path = config.path.format(tenant=connection.tenant_id)
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ if resume is not None:
+ offset = resume.offset
+ # Keep paging the same window the interrupted run started on.
+ if resume.since is not None:
+ params["since"] = resume.since
+ logger.debug(f"Hatchet: resuming {endpoint} from offset={offset}")
+ else:
+ offset = 0
+
+ # The window actually in use (after any resume override); re-saved state pins this same window.
+ effective_since = params.get("since")
+
+ while True:
+ # Checkpoint the offset of the page we're about to read. The batcher accumulates across
+ # pages and only flushes at its size threshold, so on resume we re-read from this page and
+ # let the delta merge dedupe on the primary key rather than risk skipping un-yielded rows.
+ page_offset = offset
+ page_params = {**params, "offset": page_offset}
+ url = _build_url(connection.base_url, path, page_params)
+ data = _fetch_page(session, url, headers, logger)
+
+ # List endpoints wrap results as `{"rows": [...]}`, but some (e.g. event keys) return a bare
+ # top-level array; take that directly so those endpoints don't silently sync zero rows.
+ if isinstance(data, list):
+ rows = data
+ elif isinstance(data, dict):
+ rows = data.get(config.response_data_path, [])
+ else:
+ rows = []
+ if not isinstance(rows, list) or not rows:
+ break
+
+ # A short page is the last page; a full page can still be the last if pagination says so.
+ is_last_page = len(rows) < config.page_size
+ pagination = data.get("pagination") if isinstance(data, dict) else None
+ if not is_last_page and isinstance(pagination, dict):
+ current_page = pagination.get("current_page")
+ num_pages = pagination.get("num_pages")
+ if isinstance(current_page, int) and isinstance(num_pages, int) and current_page >= num_pages:
+ is_last_page = True
+
+ for item in rows:
+ batcher.batch(_normalize_row(item))
+ if batcher.should_yield():
+ yield batcher.get_table()
+ # Save state AFTER yielding so a crash re-reads this page rather than skipping it.
+ if not is_last_page:
+ resumable_source_manager.save_state(HatchetResumeConfig(offset=page_offset, since=effective_since))
+
+ if is_last_page:
+ break
+ offset = page_offset + config.page_size
+
+ if batcher.should_yield(include_incomplete_chunk=True):
+ yield batcher.get_table()
+
+
+def hatchet_source(
+ api_token: str,
+ connection: HatchetConnection,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[HatchetResumeConfig],
+ team_id: int,
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ config = HATCHET_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ api_token=api_token,
+ connection=connection,
+ endpoint=endpoint,
+ logger=logger,
+ resumable_source_manager=resumable_source_manager,
+ team_id=team_id,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ ),
+ primary_keys=config.primary_keys,
+ sort_mode=config.sort_mode,
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime" if config.partition_key else None,
+ partition_format="week" if config.partition_key else None,
+ partition_keys=[config.partition_key] if config.partition_key else None,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hatchet/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hatchet/settings.py
new file mode 100644
index 000000000000..853067b2b87a
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hatchet/settings.py
@@ -0,0 +1,116 @@
+from dataclasses import dataclass, field
+from datetime import timedelta
+from typing import Literal, Optional
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+
+@dataclass
+class HatchetEndpointConfig:
+ name: str
+ # Tenant-scoped path template. `{tenant}` is filled with the tenant UUID derived from the token.
+ path: str
+ incremental_fields: list[IncrementalField]
+ default_incremental_field: Optional[str] = None
+ # Stable creation timestamp to partition by (never a mutable `updated`/`lastSeen` field).
+ partition_key: Optional[str] = None
+ page_size: int = 100
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ # Static query params merged into every request (e.g. `only_tasks`, `include_payloads`).
+ extra_params: dict[str, str] = field(default_factory=dict)
+ # True only when the API exposes a genuine server-side `since`/`until` time window we can
+ # advance a watermark against. `since` is required on the workflow-runs/tasks endpoint, so
+ # those pass a floor even on full refresh.
+ supports_time_window: bool = False
+ # `since` is a required query param on this endpoint (workflow-runs); a value is always sent.
+ requires_since: bool = False
+ # Floor the first incremental backfill (and full refresh) to the last N days instead of the
+ # entire retention window, bounding the initial pull.
+ default_lookback_days: Optional[int] = None
+ # Trailing overlap re-subtracted from the watermark on every incremental run, re-pulling a
+ # window of rows so runs/events whose fields mutate after creation are re-read; the delta
+ # merge dedupes them on the primary key.
+ incremental_lookback: Optional[timedelta] = None
+ # All list endpoints wrap results as `{"rows": [...], "pagination": {...}}`.
+ response_data_path: str = "rows"
+ # Rows arrive newest-first, so we declare desc: the pipeline then persists the incremental
+ # watermark only at successful job end (a partial run's max says nothing about the older rows
+ # it never reached), and resume replays from the saved offset instead.
+ sort_mode: Literal["asc", "desc"] = "asc"
+
+
+# `since` is required on the workflow-runs/tasks endpoint even for a full refresh. Retention windows
+# bound real history anyway, so a fixed far-past floor pulls everything the tenant still retains.
+FULL_REFRESH_SINCE_DAYS = 3650
+
+_TIME_WINDOW_INCREMENTAL_FIELDS: list[IncrementalField] = [
+ {
+ "label": "created_at",
+ "type": IncrementalFieldType.DateTime,
+ "field": "created_at",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+]
+
+
+HATCHET_ENDPOINTS: dict[str, HatchetEndpointConfig] = {
+ # Top-level workflow (DAG) runs plus standalone task runs. `only_tasks=false` keeps the
+ # DAG-level parent runs; the `tasks` endpoint below drills into the task grain.
+ "workflow_runs": HatchetEndpointConfig(
+ name="workflow_runs",
+ path="/api/v1/stable/tenants/{tenant}/workflow-runs",
+ partition_key="created_at",
+ incremental_fields=_TIME_WINDOW_INCREMENTAL_FIELDS,
+ default_incremental_field="created_at",
+ supports_time_window=True,
+ requires_since=True,
+ default_lookback_days=30,
+ # A run's status/output mutate after it is created, and the created_at cursor only refreshes
+ # rows at/above the watermark. Re-read a trailing day each run so a run that finishes after
+ # newer runs landed is picked up again; merge dedupes on id.
+ incremental_lookback=timedelta(days=1),
+ sort_mode="desc",
+ extra_params={"only_tasks": "false", "include_payloads": "true"},
+ ),
+ # Individual task-level runs (`only_tasks=true`), including the children of DAG runs.
+ "tasks": HatchetEndpointConfig(
+ name="tasks",
+ path="/api/v1/stable/tenants/{tenant}/workflow-runs",
+ partition_key="created_at",
+ incremental_fields=_TIME_WINDOW_INCREMENTAL_FIELDS,
+ default_incremental_field="created_at",
+ supports_time_window=True,
+ requires_since=True,
+ default_lookback_days=30,
+ incremental_lookback=timedelta(days=1),
+ sort_mode="desc",
+ extra_params={"only_tasks": "true", "include_payloads": "true"},
+ ),
+ # Events ingested into the tenant (each can trigger workflow runs). `since`/`until` are optional
+ # here but still bound the pull; created_at is the incremental cursor.
+ "events": HatchetEndpointConfig(
+ name="events",
+ path="/api/v1/stable/tenants/{tenant}/events",
+ partition_key="created_at",
+ incremental_fields=_TIME_WINDOW_INCREMENTAL_FIELDS,
+ default_incremental_field="created_at",
+ supports_time_window=True,
+ default_lookback_days=30,
+ incremental_lookback=timedelta(days=1),
+ sort_mode="desc",
+ ),
+ # The distinct event keys seen in the tenant. Tiny, timestamp-free reference list, so full
+ # refresh only; each row is the key string, keyed on itself.
+ "event_keys": HatchetEndpointConfig(
+ name="event_keys",
+ path="/api/v1/stable/tenants/{tenant}/events/keys",
+ incremental_fields=[],
+ primary_keys=["key"],
+ ),
+}
+
+ENDPOINTS = tuple(HATCHET_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in HATCHET_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hatchet/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hatchet/source.py
index ae58fef9d435..1875d88f1d87 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/hatchet/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hatchet/source.py
@@ -1,19 +1,44 @@
-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 HatchetSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.hatchet.hatchet import (
+ HatchetResumeConfig,
+ hatchet_source,
+ resolve_connection,
+ validate_credentials as validate_hatchet_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.hatchet.settings import (
+ ENDPOINTS,
+ HATCHET_ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class HatchetSource(SimpleSource[HatchetSourceConfig]):
+class HatchetSource(ResumableSource[HatchetSourceConfig, HatchetResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.HATCHET
@@ -24,8 +49,118 @@ class HatchetSource(SimpleSource[HatchetSourceConfig]):
name=SchemaExternalDataSourceType.HATCHET,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="Hatchet",
+ releaseStatus=ReleaseStatus.ALPHA,
+ unreleasedSource=True,
+ caption="""Enter a Hatchet API token to sync your workflow runs, tasks, and events into the PostHog Data warehouse.
+
+Create a tenant-scoped API token in your Hatchet dashboard under **Settings > API Tokens**. The token encodes your tenant and server URL, so that's usually all you need.
+
+If you self-host Hatchet, or the token can't be decoded, set the **Host** and **Tenant id** fields to point the connection at your instance.""",
iconPath="/static/services/hatchet.png",
+ docsUrl="https://posthog.com/docs/cdp/sources/hatchet",
keywords=["task queue", "workflows", "orchestration", "background jobs"],
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_token",
+ label="API token",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="Bearer token from Settings > API Tokens",
+ secret=True,
+ ),
+ SourceFieldInputConfig(
+ name="host",
+ label="Host",
+ type=SourceFieldInputConfigType.TEXT,
+ required=False,
+ placeholder="https://cloud.onhatchet.run",
+ secret=False,
+ ),
+ SourceFieldInputConfig(
+ name="tenant_id",
+ label="Tenant id",
+ type=SourceFieldInputConfigType.TEXT,
+ required=False,
+ placeholder="Derived from the token when left blank",
+ secret=False,
+ ),
+ ],
+ ),
+ )
+
+ @property
+ def connection_host_fields(self) -> list[str]:
+ # The API token is sent to `host`; retargeting it must re-require the token so a preserved
+ # secret can't be redirected at a server the editor controls.
+ return ["host"]
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.hatchet.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error": "Your Hatchet API token is invalid or has expired. Create a new token in your Hatchet dashboard, then reconnect.",
+ "403 Client Error": "Your Hatchet API token does not have access to this tenant. Check the token's tenant scope, then reconnect.",
+ "Invalid Hatchet API token format": "The Hatchet API token could not be read. Paste the full token from your Hatchet dashboard.",
+ "Could not decode the Hatchet API token": "The Hatchet API token could not be read. Paste the full token from your Hatchet dashboard.",
+ "Could not determine the Hatchet tenant id": "The Hatchet tenant id could not be determined from the token. Enter it manually in the tenant id field.",
+ }
+
+ def get_schemas(
+ self,
+ config: HatchetSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ def _build_schema(endpoint: str) -> SourceSchema:
+ endpoint_config = HATCHET_ENDPOINTS[endpoint]
+ supports_incremental = endpoint_config.supports_time_window and bool(INCREMENTAL_FIELDS.get(endpoint))
+ return SourceSchema(
+ name=endpoint,
+ supports_incremental=supports_incremental,
+ supports_append=supports_incremental,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ detected_primary_keys=endpoint_config.primary_keys,
+ )
+
+ 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: HatchetSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ return validate_hatchet_credentials(config.api_token, config.host or None, config.tenant_id or None, team_id)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[HatchetResumeConfig]:
+ return ResumableSourceManager[HatchetResumeConfig](inputs, HatchetResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: HatchetSourceConfig,
+ resumable_source_manager: ResumableSourceManager[HatchetResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ connection = resolve_connection(config.api_token, config.host or None, config.tenant_id or None)
+ return hatchet_source(
+ api_token=config.api_token,
+ connection=connection,
+ endpoint=inputs.schema_name,
+ logger=inputs.logger,
+ resumable_source_manager=resumable_source_manager,
+ team_id=inputs.team_id,
+ 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,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hatchet/tests/test_hatchet.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hatchet/tests/test_hatchet.py
new file mode 100644
index 000000000000..274aa89b99e3
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hatchet/tests/test_hatchet.py
@@ -0,0 +1,412 @@
+import json
+import base64
+from datetime import UTC, datetime, timedelta
+from typing import Any
+
+import pytest
+from unittest import mock
+
+import structlog
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.hatchet.hatchet import (
+ HatchetConnection,
+ HatchetHostNotAllowedError,
+ HatchetResumeConfig,
+ HatchetTokenError,
+ _build_initial_params,
+ _normalize_row,
+ _resolve_since,
+ get_rows,
+ resolve_connection,
+ validate_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.hatchet.settings import HATCHET_ENDPOINTS
+
+logger = structlog.get_logger()
+
+
+def _make_token(claims: dict[str, Any]) -> str:
+ """Build a JWT-shaped token whose (unverified) payload carries the given claims."""
+ header = base64.urlsafe_b64encode(json.dumps({"alg": "none"}).encode()).rstrip(b"=").decode()
+ payload = base64.urlsafe_b64encode(json.dumps(claims).encode()).rstrip(b"=").decode()
+ return f"{header}.{payload}.signature"
+
+
+class FakeManager:
+ """Stand-in for ResumableSourceManager that records saved state and can replay a resume value."""
+
+ def __init__(self, resume: HatchetResumeConfig | None = None):
+ self._resume = resume
+ self.saved: list[HatchetResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._resume is not None
+
+ def load_state(self) -> HatchetResumeConfig | None:
+ return self._resume
+
+ def save_state(self, data: HatchetResumeConfig) -> None:
+ self.saved.append(data)
+
+
+class TestResolveConnection:
+ def test_derives_tenant_and_host_from_token_claims(self):
+ token = _make_token({"sub": "tenant-abc", "server_url": "https://my.hatchet.example/"})
+
+ connection = resolve_connection(token)
+
+ assert connection.tenant_id == "tenant-abc"
+ # Trailing slash trimmed so path concatenation doesn't double up.
+ assert connection.base_url == "https://my.hatchet.example"
+
+ def test_explicit_overrides_win_over_token_claims(self):
+ token = _make_token({"sub": "tenant-abc", "server_url": "https://cloud.example"})
+
+ connection = resolve_connection(token, host="https://self-hosted.example/", tenant_id="tenant-override")
+
+ assert connection.tenant_id == "tenant-override"
+ assert connection.base_url == "https://self-hosted.example"
+
+ def test_falls_back_to_cloud_host_when_token_has_no_server_url(self):
+ token = _make_token({"sub": "tenant-abc"})
+
+ connection = resolve_connection(token)
+
+ assert connection.base_url == "https://cloud.onhatchet.run"
+
+ @pytest.mark.parametrize("token", ["not-a-jwt", "only.two", ""])
+ def test_malformed_token_raises_token_error(self, token):
+ with pytest.raises(HatchetTokenError):
+ resolve_connection(token)
+
+ def test_missing_tenant_raises_token_error(self):
+ token = _make_token({"server_url": "https://cloud.example"})
+
+ with pytest.raises(HatchetTokenError):
+ resolve_connection(token)
+
+
+class TestResolveSince:
+ def test_incremental_with_watermark_subtracts_lookback(self):
+ config = HATCHET_ENDPOINTS["workflow_runs"]
+ watermark = datetime(2026, 6, 1, 12, 0, 0, tzinfo=UTC)
+
+ since = _resolve_since(config, should_use_incremental_field=True, db_incremental_field_last_value=watermark)
+
+ lookback = config.incremental_lookback
+ assert lookback is not None
+ assert since == watermark - lookback
+
+ def test_future_watermark_capped_to_now(self):
+ config = HATCHET_ENDPOINTS["workflow_runs"]
+ future = datetime.now(UTC) + timedelta(days=30)
+
+ since = _resolve_since(config, should_use_incremental_field=True, db_incremental_field_last_value=future)
+
+ # A future cursor would make the API return nothing, so it's capped at ~now (then shifted back).
+ assert since is not None and since <= datetime.now(UTC)
+
+ def test_first_incremental_sync_floors_to_lookback_days(self):
+ config = HATCHET_ENDPOINTS["workflow_runs"]
+
+ since = _resolve_since(config, should_use_incremental_field=True, db_incremental_field_last_value=None)
+
+ assert since is not None
+ delta_days = (datetime.now(UTC) - since).days
+ assert delta_days == pytest.approx(config.default_lookback_days, abs=1)
+
+ def test_full_refresh_uses_far_past_floor_when_since_required(self):
+ config = HATCHET_ENDPOINTS["workflow_runs"]
+
+ since = _resolve_since(config, should_use_incremental_field=False, db_incremental_field_last_value=None)
+
+ # workflow-runs requires `since` even on full refresh, so a far-past floor is sent.
+ assert since is not None and since.year <= 2020
+
+ def test_full_refresh_without_required_since_sends_nothing(self):
+ config = HATCHET_ENDPOINTS["event_keys"]
+
+ since = _resolve_since(config, should_use_incremental_field=False, db_incremental_field_last_value=None)
+
+ assert since is None
+
+
+class TestBuildInitialParams:
+ def test_workflow_runs_carries_required_static_params(self):
+ params = _build_initial_params(
+ HATCHET_ENDPOINTS["workflow_runs"],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 6, 1, tzinfo=UTC),
+ )
+
+ # only_tasks and include_payloads are required/expected by the endpoint and must always be sent.
+ assert params["only_tasks"] == "false"
+ assert params["include_payloads"] == "true"
+ assert params["limit"] == 100
+ assert "since" in params
+
+ def test_tasks_endpoint_sets_only_tasks_true(self):
+ params = _build_initial_params(
+ HATCHET_ENDPOINTS["tasks"], should_use_incremental_field=False, db_incremental_field_last_value=None
+ )
+
+ assert params["only_tasks"] == "true"
+
+ def test_event_keys_has_no_time_window(self):
+ params = _build_initial_params(
+ HATCHET_ENDPOINTS["event_keys"], should_use_incremental_field=False, db_incremental_field_last_value=None
+ )
+
+ assert "since" not in params
+
+
+class TestNormalizeRow:
+ def test_flattens_metadata_envelope(self):
+ row = _normalize_row(
+ {
+ "metadata": {"id": "run-1", "createdAt": "2026-06-01T00:00:00Z", "updatedAt": "2026-06-02T00:00:00Z"},
+ "status": "COMPLETED",
+ }
+ )
+
+ assert row["id"] == "run-1"
+ assert row["created_at"] == "2026-06-01T00:00:00Z"
+ assert row["updated_at"] == "2026-06-02T00:00:00Z"
+ assert row["status"] == "COMPLETED"
+ assert "metadata" not in row
+
+ def test_wraps_bare_event_key_string(self):
+ assert _normalize_row("user:signed_up") == {"key": "user:signed_up"}
+
+ def test_leaves_row_without_metadata_untouched(self):
+ assert _normalize_row({"key": "abc"}) == {"key": "abc"}
+
+
+def _collect(tables) -> list[dict[str, Any]]:
+ rows: list[dict[str, Any]] = []
+ for table in tables:
+ rows.extend(table.to_pylist())
+ return rows
+
+
+def _row(row_id: str) -> dict[str, Any]:
+ return {"metadata": {"id": row_id, "createdAt": "2026-06-01T00:00:00Z", "updatedAt": "2026-06-01T00:00:00Z"}}
+
+
+class TestGetRows:
+ def _connection(self) -> HatchetConnection:
+ return HatchetConnection(base_url="https://cloud.example", tenant_id="tenant-1")
+
+ def test_single_short_page_terminates_after_one_fetch(self):
+ manager = FakeManager()
+ page = {"rows": [_row("a"), _row("b")], "pagination": {"current_page": 1, "num_pages": 1}}
+
+ with mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.hatchet.hatchet._fetch_page",
+ return_value=page,
+ ) as fetch:
+ rows = _collect(
+ get_rows("tok", self._connection(), "workflow_runs", logger, manager, team_id=1) # type: ignore[arg-type]
+ )
+
+ assert fetch.call_count == 1
+ assert [r["id"] for r in rows] == ["a", "b"]
+ # Last page → no resume state persisted.
+ assert manager.saved == []
+
+ def test_pagination_walks_offsets_until_num_pages_reached(self):
+ manager = FakeManager()
+ full_page = [_row(f"p1-{i}") for i in range(100)]
+ second_page = [_row(f"p2-{i}") for i in range(100)]
+ pages = [
+ {"rows": full_page, "pagination": {"current_page": 1, "num_pages": 2}},
+ {"rows": second_page, "pagination": {"current_page": 2, "num_pages": 2}},
+ ]
+ captured_urls: list[str] = []
+
+ def fake_fetch(session, url, headers, log):
+ captured_urls.append(url)
+ return pages[len(captured_urls) - 1]
+
+ with mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.hatchet.hatchet._fetch_page",
+ side_effect=fake_fetch,
+ ):
+ rows = _collect(
+ get_rows("tok", self._connection(), "workflow_runs", logger, manager, team_id=1) # type: ignore[arg-type]
+ )
+
+ assert len(rows) == 200
+ # Second request advances the offset by the page size.
+ assert "offset=0" in captured_urls[0]
+ assert "offset=100" in captured_urls[1]
+
+ def test_resume_starts_from_saved_offset_and_pins_since(self):
+ manager = FakeManager(resume=HatchetResumeConfig(offset=100, since="2026-01-01T00:00:00.000000Z"))
+ captured_urls: list[str] = []
+
+ def fake_fetch(session, url, headers, log):
+ captured_urls.append(url)
+ return {"rows": [_row("x")], "pagination": {"current_page": 2, "num_pages": 2}}
+
+ with mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.hatchet.hatchet._fetch_page",
+ side_effect=fake_fetch,
+ ):
+ _collect(get_rows("tok", self._connection(), "workflow_runs", logger, manager, 1, True, None)) # type: ignore[arg-type]
+
+ assert "offset=100" in captured_urls[0]
+ # The window the interrupted run started on is replayed, not recomputed from a new watermark.
+ assert "since=2026-01-01T00%3A00%3A00.000000Z" in captured_urls[0]
+
+ def test_syncs_bare_top_level_array_response(self):
+ # event_keys returns a top-level JSON array, not a `{"rows": [...]}` envelope; it must still
+ # sync instead of silently loading zero rows.
+ manager = FakeManager()
+
+ with mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.hatchet.hatchet._fetch_page",
+ return_value=["user:signed_up", "billing:charged"],
+ ):
+ rows = _collect(
+ get_rows("tok", self._connection(), "event_keys", logger, manager, team_id=1) # type: ignore[arg-type]
+ )
+
+ assert rows == [{"key": "user:signed_up"}, {"key": "billing:charged"}]
+
+ def test_unsafe_host_raises_before_any_fetch(self):
+ manager = FakeManager()
+
+ with (
+ mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.hatchet.hatchet._is_host_safe",
+ return_value=(False, "Hosts with internal IP addresses are not allowed"),
+ ),
+ mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.hatchet.hatchet._fetch_page",
+ ) as fetch,
+ ):
+ with pytest.raises(HatchetHostNotAllowedError):
+ _collect(get_rows("tok", self._connection(), "workflow_runs", logger, manager, team_id=99)) # type: ignore[arg-type]
+
+ fetch.assert_not_called()
+
+ def test_plaintext_http_host_raises_on_cloud(self):
+ # On cloud the bearer token must never go over plaintext http, even when the host passes the
+ # SSRF check.
+ manager = FakeManager()
+ connection = HatchetConnection(base_url="http://cloud.example", tenant_id="tenant-1")
+
+ with (
+ mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.hatchet.hatchet._is_host_safe",
+ return_value=(True, None),
+ ),
+ mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.hatchet.hatchet.is_cloud",
+ return_value=True,
+ ),
+ mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.hatchet.hatchet._fetch_page",
+ ) as fetch,
+ ):
+ with pytest.raises(HatchetHostNotAllowedError):
+ _collect(get_rows("tok", connection, "workflow_runs", logger, manager, team_id=1)) # type: ignore[arg-type]
+
+ fetch.assert_not_called()
+
+ def test_session_disables_redirects_and_redacts_token(self):
+ # The bearer token is sent to a user-controlled host, so the session must never follow a
+ # redirect off it and must redact the token from captured samples/logs. Response bodies
+ # carry opaque workflow payloads, so they must also be excluded from HTTP sample capture.
+ manager = FakeManager()
+ page = {"rows": [_row("a")], "pagination": {"current_page": 1, "num_pages": 1}}
+
+ with (
+ mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.hatchet.hatchet.make_tracked_session"
+ ) as session,
+ mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.hatchet.hatchet._fetch_page",
+ return_value=page,
+ ),
+ ):
+ _collect(get_rows("tok", self._connection(), "workflow_runs", logger, manager, team_id=1)) # type: ignore[arg-type]
+
+ assert session.call_args.kwargs["allow_redirects"] is False
+ assert session.call_args.kwargs["redact_values"] == ("tok",)
+ assert session.call_args.kwargs["capture"] is False
+
+
+class TestValidateCredentials:
+ @pytest.mark.parametrize(
+ "status_code,expected_valid",
+ [(200, True), (401, False), (403, False), (404, False), (500, False)],
+ )
+ def test_status_mapping(self, status_code, expected_valid):
+ token = _make_token({"sub": "tenant-1", "server_url": "https://cloud.example"})
+ response = mock.MagicMock()
+ response.status_code = status_code
+
+ with mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.hatchet.hatchet.make_tracked_session"
+ ) as session:
+ session.return_value.get.return_value = response
+ valid, message = validate_credentials(token, None, None)
+
+ assert valid is expected_valid
+ if not expected_valid:
+ assert message
+
+ def test_undecodable_token_fails_without_network_call(self):
+ with mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.hatchet.hatchet.make_tracked_session"
+ ) as session:
+ valid, message = validate_credentials("garbage", None, None)
+
+ assert valid is False
+ assert message
+ session.assert_not_called()
+
+ def test_unsafe_host_fails_before_network_call(self):
+ # A host resolving to an internal address must be rejected before the token is ever sent.
+ token = _make_token({"sub": "tenant-1", "server_url": "https://internal.example"})
+
+ with (
+ mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.hatchet.hatchet._is_host_safe",
+ return_value=(False, "Hosts with internal IP addresses are not allowed"),
+ ),
+ mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.hatchet.hatchet.make_tracked_session"
+ ) as session,
+ ):
+ valid, message = validate_credentials(token, None, None, team_id=99)
+
+ assert valid is False
+ assert message
+ session.assert_not_called()
+
+ def test_plaintext_http_host_fails_on_cloud(self):
+ # On cloud, a plaintext http host must be rejected before the token is sent — even when the
+ # host itself passes the SSRF check.
+ token = _make_token({"sub": "tenant-1", "server_url": "http://cloud.example"})
+
+ with (
+ mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.hatchet.hatchet._is_host_safe",
+ return_value=(True, None),
+ ),
+ mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.hatchet.hatchet.is_cloud",
+ return_value=True,
+ ),
+ mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.hatchet.hatchet.make_tracked_session"
+ ) as session,
+ ):
+ valid, message = validate_credentials(token, None, None, team_id=99)
+
+ assert valid is False
+ assert message
+ session.assert_not_called()
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/hatchet/tests/test_hatchet_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/hatchet/tests/test_hatchet_source.py
new file mode 100644
index 000000000000..e3d209fad165
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/hatchet/tests/test_hatchet_source.py
@@ -0,0 +1,135 @@
+import pytest
+from unittest import mock
+
+from posthog.schema import SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import HatchetSourceConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.hatchet.hatchet import (
+ HatchetConnection,
+ HatchetResumeConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.hatchet.source import HatchetSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestHatchetSource:
+ def setup_method(self):
+ self.source = HatchetSource()
+ self.team_id = 123
+ self.config = HatchetSourceConfig(api_token="tok", host=None, tenant_id=None)
+
+ def test_source_type(self):
+ assert self.source.source_type == ExternalDataSourceType.HATCHET
+
+ def test_config_fields(self):
+ field_names = {f.name for f in self.source.get_source_config.fields}
+ assert field_names == {"api_token", "host", "tenant_id"}
+
+ api_token = next(f for f in self.source.get_source_config.fields if f.name == "api_token")
+ # The token is a secret; the wizard must render it as a password input.
+ assert isinstance(api_token, SourceFieldInputConfig)
+ assert api_token.required is True
+ assert api_token.type == SourceFieldInputConfigType.PASSWORD
+
+ def test_host_is_a_connection_host_field(self):
+ # The token is sent to `host`; retargeting it must force re-entry of the token secret.
+ assert self.source.connection_host_fields == ["host"]
+
+ @pytest.mark.parametrize(
+ "endpoint,expected_incremental,expected_primary_keys",
+ [
+ ("workflow_runs", True, ["id"]),
+ ("tasks", True, ["id"]),
+ ("events", True, ["id"]),
+ ("event_keys", False, ["key"]),
+ ],
+ )
+ def test_get_schemas(self, endpoint, expected_incremental, expected_primary_keys):
+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}
+
+ assert endpoint in schemas
+ schema = schemas[endpoint]
+ assert schema.supports_incremental is expected_incremental
+ assert schema.supports_append is expected_incremental
+ assert schema.detected_primary_keys == expected_primary_keys
+
+ @pytest.mark.parametrize("expected_key", ["401 Client Error", "403 Client Error"])
+ def test_auth_errors_are_non_retryable(self, expected_key):
+ assert expected_key in self.source.get_non_retryable_errors()
+
+ 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 HatchetResumeConfig
+
+ def test_validate_credentials_delegates_with_resolved_overrides(self):
+ config = HatchetSourceConfig(api_token="tok", host="", tenant_id="")
+
+ with mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.hatchet.source.validate_hatchet_credentials",
+ return_value=(True, None),
+ ) as validate:
+ result = self.source.validate_credentials(config, self.team_id)
+
+ assert result == (True, None)
+ # Empty override strings collapse to None so the token-derived values are used; team_id is
+ # forwarded so the credential probe can SSRF-check the resolved host.
+ validate.assert_called_once_with("tok", None, None, self.team_id)
+
+ def test_source_for_pipeline_plumbs_endpoint_and_connection(self):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "workflow_runs"
+ inputs.should_use_incremental_field = True
+ inputs.db_incremental_field_last_value = "2026-06-01T00:00:00Z"
+ manager = mock.MagicMock()
+ connection = HatchetConnection(base_url="https://cloud.example", tenant_id="tenant-1")
+
+ with (
+ mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.hatchet.source.resolve_connection",
+ return_value=connection,
+ ),
+ mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.hatchet.source.hatchet_source"
+ ) as hatchet_source,
+ ):
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ _, kwargs = hatchet_source.call_args
+ assert kwargs["endpoint"] == "workflow_runs"
+ assert kwargs["connection"] is connection
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == "2026-06-01T00:00:00Z"
+
+ def test_source_for_pipeline_drops_incremental_value_on_full_refresh(self):
+ inputs = mock.MagicMock()
+ inputs.schema_name = "events"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = "2026-06-01T00:00:00Z"
+
+ with (
+ mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.hatchet.source.resolve_connection",
+ return_value=HatchetConnection(base_url="https://cloud.example", tenant_id="t"),
+ ),
+ mock.patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.hatchet.source.hatchet_source"
+ ) as hatchet_source,
+ ):
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ _, kwargs = hatchet_source.call_args
+ # A stale watermark must not leak into a full-refresh run.
+ assert kwargs["db_incremental_field_last_value"] is None
+
+ def test_documented_tables_render_from_static_catalog(self):
+ # lists_tables_without_credentials must expose the table catalog (+ canonical descriptions)
+ # for the public docs <SourceTables /> component without needing credentials.
+ assert self.source.lists_tables_without_credentials is True
+
+ tables = {t["name"]: t for t in self.source.get_documented_tables()}
+
+ assert set(tables) == {"workflow_runs", "tasks", "events", "event_keys"}
+ assert tables["workflow_runs"]["description"]
+ assert "Incremental" in tables["workflow_runs"]["sync_methods"]
+ assert tables["event_keys"]["sync_methods"] == ["Full refresh"]