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 datadog import source (#61590)

Tom Owers3f17373cbda3
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.md
index c2b6576d5b48..17a8f5a8cf7d 100644
--- a/posthog/temporal/data_imports/sources/SOURCES.md
+++ b/posthog/temporal/data_imports/sources/SOURCES.md
@@ -64,6 +64,7 @@ the row lists both.
| convex | HTTP | requests | ✅ |
| copper | HTTP | requests | ✅ |
| customer_io | HTTP + Webhook | requests + `WebhookSourceManager` | ✅ (App API) / ➖ (webhook) |
+| datadog | HTTP | requests | ✅ |
| doit | HTTP | requests | ✅ |
| drip | HTTP | requests | ✅ |
| freshdesk | HTTP | requests | ✅ |
@@ -171,7 +172,6 @@ doesn't conflict with concurrent PRs.
- cockroachdb
- confluence
- copper
-- datadog
- dynamodb
- elasticsearch
- facebook_pages
diff --git a/posthog/temporal/data_imports/sources/datadog/datadog.py b/posthog/temporal/data_imports/sources/datadog/datadog.py
new file mode 100644
index 000000000000..bd3688762c99
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/datadog/datadog.py
@@ -0,0 +1,290 @@
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime, timedelta
+from typing import Any, Optional
+from urllib.parse import parse_qsl, urlencode, urlparse, urlunparse
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from posthog.temporal.data_imports.sources.common.http import make_tracked_session
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.datadog.settings import DATADOG_ENDPOINTS, DatadogEndpointConfig
+
+# Datadog regional sites. The site selects which API host the credentials are sent to. The set is
+# a fixed allow-list, so the host can't be retargeted at an arbitrary server.
+DATADOG_SITES = (
+ "datadoghq.com",
+ "us3.datadoghq.com",
+ "us5.datadoghq.com",
+ "datadoghq.eu",
+ "ap1.datadoghq.com",
+ "ddog-gov.com",
+)
+DEFAULT_SITE = "datadoghq.com"
+
+REQUEST_TIMEOUT_SECONDS = 60
+
+
+class DatadogRetryableError(Exception):
+ pass
+
+
+class DatadogResumeConfig:
+ next_url: str
+
+
+def base_url(site: Optional[str]) -> str:
+ resolved = site or DEFAULT_SITE
+ if resolved not in DATADOG_SITES:
+ resolved = DEFAULT_SITE
+ return f"https://api.{resolved}"
+
+
+def _get_headers(api_key: str, app_key: str) -> dict[str, str]:
+ return {
+ "DD-API-KEY": api_key,
+ "DD-APPLICATION-KEY": app_key,
+ "Accept": "application/json",
+ }
+
+
+def _format_datetime(value: Any) -> str:
+ """Format an incremental cursor value as ISO 8601 with a ``Z`` suffix for Datadog filters."""
+ if isinstance(value, datetime):
+ dt = value
+ elif isinstance(value, date):
+ dt = datetime.combine(value, datetime.min.time())
+ else:
+ return str(value)
+ dt = dt.replace(tzinfo=UTC) if dt.tzinfo is None else dt.astimezone(UTC)
+ return dt.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"
+
+
+def validate_credentials(site: Optional[str], api_key: str, app_key: str) -> tuple[bool, str | None]:
+ """Validate Datadog credentials with a single cheap probe.
+
+ ``/api/v1/validate`` confirms the API key is genuine but does NOT exercise the application key
+ (no v1/v2 endpoint validates the app key without reading real data). Missing application-key
+ scopes surface at sync time as 403s, handled by ``get_non_retryable_errors``.
+ """
+ url = f"{base_url(site)}/api/v1/validate"
+ try:
+ session = make_tracked_session(redact_values=(api_key, app_key))
+ response = session.get(url, headers=_get_headers(api_key, app_key), timeout=10)
+ if response.status_code == 200:
+ return True, None
+ if response.status_code in (401, 403):
+ return False, "Invalid Datadog API key. Check the API key and selected site, then try again."
+ return False, f"Datadog credential validation failed (status {response.status_code})."
+ except requests.exceptions.RequestException as e:
+ return False, str(e)
+
+
+def _build_initial_params(
+ config: DatadogEndpointConfig,
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+) -> dict[str, Any]:
+ params: dict[str, Any] = {}
+
+ if config.pagination != "none" and config.page_size_param:
+ params[config.page_size_param] = config.page_size
+ if config.pagination == "offset" and config.offset_param:
+ params[config.offset_param] = 0
+ if config.pagination == "page" and config.page_index_param:
+ params[config.page_index_param] = 0
+
+ if config.sort_param:
+ params["sort"] = config.sort_param
+
+ if config.timestamp_filter_param:
+ # Continue from the stored watermark on incremental runs; otherwise seed the first sync
+ # with the lookback window so we don't fall back to Datadog's ``now-15m`` default.
+ if should_use_incremental_field and db_incremental_field_last_value:
+ cutoff: Any = db_incremental_field_last_value
+ elif config.default_lookback_days:
+ cutoff = datetime.now(UTC) - timedelta(days=config.default_lookback_days)
+ else:
+ cutoff = None
+
+ if cutoff is not None:
+ params[config.timestamp_filter_param] = _format_datetime(cutoff)
+
+ return params
+
+
+def _build_initial_url(host: str, config: DatadogEndpointConfig, params: dict[str, Any]) -> str:
+ url = f"{host}{config.path}"
+ if not params:
+ return url
+ # Keep the JSON:API bracket syntax (``page[limit]``) literal; Datadog expects it.
+ return f"{url}?{urlencode(params, safe='[]')}"
+
+
+def _extract_items(response_json: Any, config: DatadogEndpointConfig) -> list[dict[str, Any]]:
+ if config.data_path is None:
+ return response_json if isinstance(response_json, list) else []
+ if isinstance(response_json, dict):
+ items = response_json.get(config.data_path, [])
+ return items if isinstance(items, list) else []
+ return []
+
+
+def _flatten_item(item: dict[str, Any]) -> dict[str, Any]:
+ """Lift a v2 JSON:API record's ``attributes`` object to the root, keeping ``id``/``type``."""
+ attributes = item.get("attributes")
+ if isinstance(attributes, dict):
+ item.pop("attributes")
+ for key, value in attributes.items():
+ item.setdefault(key, value)
+ return item
+
+
+def _is_same_host(url: str, host: str) -> bool:
+ """True only for ``https`` URLs whose netloc matches the resolved Datadog API host."""
+ parsed = urlparse(url)
+ return parsed.scheme == "https" and parsed.netloc == urlparse(host).netloc
+
+
+def _compute_next_url(
+ config: DatadogEndpointConfig,
+ current_url: str,
+ response_json: Any,
+ item_count: int,
+ host: str,
+) -> str | None:
+ if config.pagination == "cursor":
+ links = response_json.get("links") if isinstance(response_json, dict) else None
+ next_link = links.get("next") if isinstance(links, dict) else None
+ # Only follow pagination URLs that stay on the resolved Datadog API host, so a tampered or
+ # compromised API response can't point our authenticated request at an internal address
+ # (SSRF) and leak the DD-API-KEY / DD-APPLICATION-KEY headers.
+ if isinstance(next_link, str) and _is_same_host(next_link, host):
+ return next_link
+ return None
+
+ # Numeric pagination: a short page means we've reached the end.
+ if item_count < config.page_size:
+ return None
+
+ parsed = urlparse(current_url)
+ query = dict(parse_qsl(parsed.query, keep_blank_values=True))
+
+ if config.pagination == "page" and config.page_index_param:
+ current = int(query.get(config.page_index_param, 0))
+ query[config.page_index_param] = str(current + 1)
+ elif config.pagination == "offset" and config.offset_param:
+ current = int(query.get(config.offset_param, 0))
+ query[config.offset_param] = str(current + config.page_size)
+ else:
+ return None
+
+ return urlunparse(parsed._replace(query=urlencode(query, safe="[]")))
+
+
+def get_rows(
+ site: Optional[str],
+ api_key: str,
+ app_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[DatadogResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> Iterator[list[dict[str, Any]]]:
+ config = DATADOG_ENDPOINTS[endpoint]
+ headers = _get_headers(api_key, app_key)
+ host = base_url(site)
+ # One tracked session reused across pages and retries; credentials are redacted from logged
+ # URLs and captured samples.
+ session = make_tracked_session(headers=headers, redact_values=(api_key, app_key))
+
+ params = _build_initial_params(config, should_use_incremental_field, db_incremental_field_last_value)
+
+ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ if resume_config is not None:
+ url = resume_config.next_url
+ # Guard the persisted resume URL too — only ever saved from _compute_next_url (host-pinned),
+ # but re-check so a tampered Redis state can't redirect our authenticated request.
+ if not _is_same_host(url, host):
+ raise ValueError(f"Datadog resume state contains an unexpected URL: {url!r}")
+ logger.debug(f"Datadog: resuming from URL: {url}")
+ else:
+ url = _build_initial_url(host, config, params)
+
+ @retry(
+ retry=retry_if_exception_type((DatadogRetryableError, requests.ReadTimeout, requests.ConnectionError)),
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+ )
+ def fetch_page(page_url: str) -> Any:
+ response = session.get(page_url, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ if response.status_code == 429 or response.status_code >= 500:
+ raise DatadogRetryableError(f"Datadog API error (retryable): status={response.status_code}, url={page_url}")
+
+ if not response.ok:
+ logger.error(f"Datadog API error: status={response.status_code}, body={response.text}, url={page_url}")
+ response.raise_for_status()
+
+ return response.json()
+
+ while True:
+ data = fetch_page(url)
+
+ items = _extract_items(data, config)
+ if not items:
+ break
+
+ if config.flatten_attributes:
+ items = [_flatten_item(item) for item in items]
+
+ yield items
+
+ next_url = _compute_next_url(config, url, data, len(items), host)
+ if not next_url:
+ break
+
+ # Save state AFTER yielding the batch — a crash re-yields the last batch (merge dedupes on
+ # primary key) instead of skipping it.
+ resumable_source_manager.save_state(DatadogResumeConfig(next_url=next_url))
+ url = next_url
+
+
+def datadog_source(
+ site: Optional[str],
+ api_key: str,
+ app_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[DatadogResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ config = DATADOG_ENDPOINTS[endpoint]
+
+ return SourceResponse(
+ name=endpoint,
+ items=lambda: get_rows(
+ site=site,
+ api_key=api_key,
+ app_key=app_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,
+ ),
+ primary_keys=[config.primary_key],
+ sort_mode="asc",
+ 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/posthog/temporal/data_imports/sources/datadog/settings.py b/posthog/temporal/data_imports/sources/datadog/settings.py
new file mode 100644
index 000000000000..9c7523b9f4d8
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/datadog/settings.py
@@ -0,0 +1,189 @@
+from dataclasses import dataclass, field
+from typing import Literal, Optional
+
+from products.data_warehouse.backend.types import IncrementalField, IncrementalFieldType
+
+PaginationStyle = Literal["cursor", "page", "offset", "none"]
+
+
+@dataclass
+class DatadogEndpointConfig:
+ name: str
+ path: str
+ # Key in the response body holding the list of records. ``None`` means the body itself is the list.
+ data_path: Optional[str] = None
+ primary_key: str = "id"
+ pagination: PaginationStyle = "none"
+ page_size: int = 100
+ # Pagination param names (only the ones relevant to ``pagination`` are set per endpoint).
+ page_size_param: Optional[str] = None
+ page_index_param: Optional[str] = None # zero-indexed page number
+ offset_param: Optional[str] = None # row offset
+ # v2 JSON:API records nest their useful fields under ``attributes``; flatten them to the root.
+ flatten_attributes: bool = False
+ # Stable, immutable datetime field used for partitioning (never ``modified``/``updated``).
+ partition_key: Optional[str] = None
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ default_incremental_field: Optional[str] = None
+ # Server-side timestamp filter param (e.g. ``filter[from]``). Only set when the API genuinely
+ # filters server-side — leaving it ``None`` keeps the endpoint full-refresh only.
+ timestamp_filter_param: Optional[str] = None
+ # Value for the ``sort`` query param. For incremental endpoints this must be an ascending,
+ # monotonic field so the pipeline's watermark advances correctly.
+ sort_param: Optional[str] = None
+ # First-sync lookback window for endpoints with a server-side timestamp filter. Datadog's
+ # event-search endpoints default ``filter[from]`` to ``now-15m`` when it's omitted, so without
+ # this the very first sync would only fetch the last 15 minutes. We seed ``filter[from]`` to
+ # ``now - default_lookback_days`` instead; Datadog clamps it to the account's retention.
+ default_lookback_days: Optional[int] = None
+
+ @property
+ def supports_incremental(self) -> bool:
+ return self.timestamp_filter_param is not None
+
+
+def _timestamp_incremental_fields(field_name: str) -> list[IncrementalField]:
+ return [
+ {
+ "label": field_name,
+ "type": IncrementalFieldType.DateTime,
+ "field": field_name,
+ "field_type": IncrementalFieldType.DateTime,
+ }
+ ]
+
+
+# Endpoint catalog. Coverage mirrors the canonical Datadog streams exposed by the Airbyte and
+# Fivetran connectors (logs, audit logs, events, dashboards, monitors, users, incidents, SLOs,
+# synthetic tests, downtimes).
+#
+# Incremental vs full refresh: only the v2 event-style endpoints (logs / audit_logs / events)
+# expose a genuine server-side timestamp filter (``filter[from]``) and an ascending ``timestamp``
+# sort, so only those are marked incremental. The list/config endpoints have no server-side time
+# filter, so they ship as full refresh and dedupe on their primary key.
+DATADOG_ENDPOINTS: dict[str, DatadogEndpointConfig] = {
+ # --- Append-only, server-side timestamp filter (incremental) ---
+ "logs": DatadogEndpointConfig(
+ name="logs",
+ path="/api/v2/logs/events",
+ data_path="data",
+ pagination="cursor",
+ page_size=1000,
+ page_size_param="page[limit]",
+ flatten_attributes=True,
+ partition_key="timestamp",
+ incremental_fields=_timestamp_incremental_fields("timestamp"),
+ default_incremental_field="timestamp",
+ timestamp_filter_param="filter[from]",
+ sort_param="timestamp",
+ default_lookback_days=30,
+ ),
+ "audit_logs": DatadogEndpointConfig(
+ name="audit_logs",
+ path="/api/v2/audit/events",
+ data_path="data",
+ pagination="cursor",
+ page_size=1000,
+ page_size_param="page[limit]",
+ flatten_attributes=True,
+ partition_key="timestamp",
+ incremental_fields=_timestamp_incremental_fields("timestamp"),
+ default_incremental_field="timestamp",
+ timestamp_filter_param="filter[from]",
+ sort_param="timestamp",
+ default_lookback_days=30,
+ ),
+ "events": DatadogEndpointConfig(
+ name="events",
+ path="/api/v2/events",
+ data_path="data",
+ pagination="cursor",
+ page_size=1000,
+ page_size_param="page[limit]",
+ flatten_attributes=True,
+ partition_key="timestamp",
+ incremental_fields=_timestamp_incremental_fields("timestamp"),
+ default_incremental_field="timestamp",
+ timestamp_filter_param="filter[from]",
+ sort_param="timestamp",
+ default_lookback_days=30,
+ ),
+ # --- Full refresh ---
+ "dashboards": DatadogEndpointConfig(
+ name="dashboards",
+ path="/api/v1/dashboard",
+ data_path="dashboards",
+ pagination="none",
+ partition_key="created_at",
+ ),
+ "monitors": DatadogEndpointConfig(
+ name="monitors",
+ path="/api/v1/monitor",
+ data_path=None,
+ pagination="page",
+ page_size=100,
+ page_size_param="page_size",
+ page_index_param="page",
+ partition_key="created",
+ ),
+ "users": DatadogEndpointConfig(
+ name="users",
+ path="/api/v2/users",
+ data_path="data",
+ pagination="page",
+ page_size=100,
+ page_size_param="page[size]",
+ page_index_param="page[number]",
+ flatten_attributes=True,
+ partition_key="created_at",
+ ),
+ "incidents": DatadogEndpointConfig(
+ name="incidents",
+ path="/api/v2/incidents",
+ data_path="data",
+ pagination="offset",
+ page_size=100,
+ page_size_param="page[size]",
+ offset_param="page[offset]",
+ flatten_attributes=True,
+ partition_key="created",
+ ),
+ "slos": DatadogEndpointConfig(
+ name="slos",
+ path="/api/v1/slo",
+ data_path="data",
+ pagination="offset",
+ page_size=100,
+ page_size_param="limit",
+ offset_param="offset",
+ # SLO ``created_at`` is a unix epoch integer rather than an ISO datetime, so it isn't a
+ # safe partition key — left unpartitioned.
+ ),
+ "synthetic_tests": DatadogEndpointConfig(
+ name="synthetic_tests",
+ path="/api/v1/synthetics/tests",
+ data_path="tests",
+ pagination="none",
+ primary_key="public_id",
+ ),
+ "downtimes": DatadogEndpointConfig(
+ name="downtimes",
+ path="/api/v2/downtime",
+ data_path="data",
+ pagination="offset",
+ page_size=100,
+ page_size_param="page[limit]",
+ offset_param="page[offset]",
+ flatten_attributes=True,
+ ),
+}
+
+ENDPOINTS = tuple(DATADOG_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in DATADOG_ENDPOINTS.items()
+}
+
+# Datadog retains logs / audit logs / events for a limited window, so the first sync can only
+# reach back as far as the account's retention allows.
+LIMITED_RETENTION_ENDPOINTS = {"logs", "audit_logs", "events"}
diff --git a/posthog/temporal/data_imports/sources/datadog/source.py b/posthog/temporal/data_imports/sources/datadog/source.py
index 5ba61360d205..eeaef75c8e9e 100644
--- a/posthog/temporal/data_imports/sources/datadog/source.py
+++ b/posthog/temporal/data_imports/sources/datadog/source.py
@@ -1,29 +1,161 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
+ SourceFieldSelectConfig,
+ SourceFieldSelectConfigOption,
)
-from posthog.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponse
+from posthog.temporal.data_imports.sources.common.base import FieldType, ResumableSource
from posthog.temporal.data_imports.sources.common.registry import SourceRegistry
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.common.schema import SourceSchema
+from posthog.temporal.data_imports.sources.datadog.datadog import (
+ DatadogResumeConfig,
+ datadog_source,
+ validate_credentials as validate_datadog_credentials,
+)
+from posthog.temporal.data_imports.sources.datadog.settings import (
+ DATADOG_ENDPOINTS,
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+ LIMITED_RETENTION_ENDPOINTS,
+)
from posthog.temporal.data_imports.sources.generated_configs import DatadogSourceConfig
from products.data_warehouse.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class DatadogSource(SimpleSource[DatadogSourceConfig]):
+class DatadogSource(ResumableSource[DatadogSourceConfig, DatadogResumeConfig]):
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.DATADOG
+ @property
+ def connection_host_fields(self) -> list[str]:
+ # The API/application keys are sent to the host derived from `site`, so changing the site
+ # must re-require the secrets rather than reusing them against a different host.
+ return ["site"]
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.DATADOG,
label="Datadog",
- iconPath="/static/services/datadog.png",
- fields=cast(list[FieldType], []),
+ releaseStatus=ReleaseStatus.ALPHA,
unreleasedSource=True,
+ caption="""Connect your Datadog account to sync logs, events, monitors, dashboards, and more into the PostHog Data warehouse.
+
+Create an API key and an application key in your [Datadog organization settings](https://app.datadoghq.com/organization-settings/api-keys). The application key should be granted read scopes for the data you want to sync, for example:
+- `dashboards_read`
+- `monitors_read`
+- `incident_read`
+- `slos_read`
+- `synthetics_read`
+- `user_access_read`
+
+Logs, audit logs, and events read access is governed by your Datadog account's data retention.""",
+ iconPath="/static/services/datadog.svg",
+ docsUrl="https://posthog.com/docs/cdp/sources/datadog",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldSelectConfig(
+ name="site",
+ label="Datadog site",
+ required=True,
+ defaultValue="datadoghq.com",
+ options=[
+ SourceFieldSelectConfigOption(label="US1 (datadoghq.com)", value="datadoghq.com"),
+ SourceFieldSelectConfigOption(label="US3 (us3.datadoghq.com)", value="us3.datadoghq.com"),
+ SourceFieldSelectConfigOption(label="US5 (us5.datadoghq.com)", value="us5.datadoghq.com"),
+ SourceFieldSelectConfigOption(label="EU1 (datadoghq.eu)", value="datadoghq.eu"),
+ SourceFieldSelectConfigOption(label="AP1 (ap1.datadoghq.com)", value="ap1.datadoghq.com"),
+ SourceFieldSelectConfigOption(label="US1-FED (ddog-gov.com)", value="ddog-gov.com"),
+ ],
+ ),
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="Datadog API key",
+ secret=True,
+ ),
+ SourceFieldInputConfig(
+ name="application_key",
+ label="Application key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="Datadog application key",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error": "Invalid Datadog API key. Generate a valid key and reconnect.",
+ "403 Client Error": "Your Datadog application key is missing the required read scopes for this data. Grant the scopes and reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: DatadogSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=DATADOG_ENDPOINTS[endpoint].supports_incremental,
+ supports_append=DATADOG_ENDPOINTS[endpoint].supports_incremental,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ description=(
+ "Limited to your Datadog account's retention window on initial sync"
+ if endpoint in LIMITED_RETENTION_ENDPOINTS
+ else None
+ ),
+ )
+ for endpoint in list(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: DatadogSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ return validate_datadog_credentials(config.site, config.api_key, config.application_key)
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[DatadogResumeConfig]:
+ return ResumableSourceManager[DatadogResumeConfig](inputs, DatadogResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: DatadogSourceConfig,
+ resumable_source_manager: ResumableSourceManager[DatadogResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return datadog_source(
+ site=config.site,
+ api_key=config.api_key,
+ app_key=config.application_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,
)
diff --git a/posthog/temporal/data_imports/sources/datadog/tests/test_datadog.py b/posthog/temporal/data_imports/sources/datadog/tests/test_datadog.py
new file mode 100644
index 000000000000..3b2a35d428f6
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/datadog/tests/test_datadog.py
@@ -0,0 +1,408 @@
+from datetime import UTC, date, datetime
+from typing import Any
+from urllib.parse import parse_qs, urlparse
+
+import pytest
+from unittest import mock
+
+import requests
+
+from posthog.temporal.data_imports.sources.datadog import datadog as ddog
+from posthog.temporal.data_imports.sources.datadog.datadog import (
+ DEFAULT_SITE,
+ DatadogResumeConfig,
+ _build_initial_params,
+ _build_initial_url,
+ _compute_next_url,
+ _extract_items,
+ _flatten_item,
+ _format_datetime,
+ base_url,
+ datadog_source,
+ validate_credentials,
+)
+from posthog.temporal.data_imports.sources.datadog.settings import DATADOG_ENDPOINTS
+
+
+class TestBaseUrl:
+ @pytest.mark.parametrize(
+ ("site", "expected"),
+ [
+ ("datadoghq.com", "https://api.datadoghq.com"),
+ ("datadoghq.eu", "https://api.datadoghq.eu"),
+ ("ap1.datadoghq.com", "https://api.ap1.datadoghq.com"),
+ # Unknown / spoofed hosts fall back to the default US site.
+ ("evil.example.com", f"https://api.{DEFAULT_SITE}"),
+ (None, f"https://api.{DEFAULT_SITE}"),
+ ],
+ )
+ def test_base_url(self, site: Any, expected: str) -> None:
+ assert base_url(site) == expected
+
+
+class TestFormatDatetime:
+ @pytest.mark.parametrize(
+ ("value", "expected"),
+ [
+ (datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04T02:58:14.000Z"),
+ (datetime(2026, 1, 15, 10, 30, 45, 123456, tzinfo=UTC), "2026-01-15T10:30:45.123Z"),
+ (datetime(2026, 3, 4, 2, 58, 14), "2026-03-04T02:58:14.000Z"),
+ (date(2026, 3, 4), "2026-03-04T00:00:00.000Z"),
+ ("already-a-string", "already-a-string"),
+ ],
+ )
+ def test_format_datetime(self, value: Any, expected: str) -> None:
+ assert _format_datetime(value) == expected
+
+ def test_no_plus_zero_offset(self) -> None:
+ assert "+00:00" not in _format_datetime(datetime(2026, 3, 4, tzinfo=UTC))
+
+
+class TestExtractItems:
+ def test_top_level_list(self) -> None:
+ config = DATADOG_ENDPOINTS["monitors"] # data_path=None
+ assert _extract_items([{"id": 1}, {"id": 2}], config) == [{"id": 1}, {"id": 2}]
+
+ def test_top_level_list_with_unexpected_dict(self) -> None:
+ config = DATADOG_ENDPOINTS["monitors"]
+ assert _extract_items({"unexpected": "shape"}, config) == []
+
+ def test_wrapped_data_path(self) -> None:
+ config = DATADOG_ENDPOINTS["logs"] # data_path="data"
+ assert _extract_items({"data": [{"id": "a"}]}, config) == [{"id": "a"}]
+
+ def test_wrapped_custom_path(self) -> None:
+ config = DATADOG_ENDPOINTS["dashboards"] # data_path="dashboards"
+ assert _extract_items({"dashboards": [{"id": "x"}]}, config) == [{"id": "x"}]
+
+ def test_missing_path_returns_empty(self) -> None:
+ config = DATADOG_ENDPOINTS["logs"]
+ assert _extract_items({"meta": {}}, config) == []
+
+
+class TestFlattenItem:
+ def test_flattens_attributes_to_root(self) -> None:
+ item = {"id": "abc", "type": "log", "attributes": {"timestamp": "2026-01-01T00:00:00Z", "status": "info"}}
+ flat = _flatten_item(item)
+ assert flat["id"] == "abc"
+ assert flat["type"] == "log"
+ assert flat["timestamp"] == "2026-01-01T00:00:00Z"
+ assert flat["status"] == "info"
+ assert "attributes" not in flat
+
+ def test_does_not_clobber_existing_root_keys(self) -> None:
+ item = {"id": "abc", "attributes": {"id": "SHOULD_NOT_WIN", "name": "x"}}
+ flat = _flatten_item(item)
+ assert flat["id"] == "abc"
+ assert flat["name"] == "x"
+
+ def test_no_attributes_is_noop(self) -> None:
+ item = {"id": "abc", "name": "x"}
+ assert _flatten_item(item) == {"id": "abc", "name": "x"}
+
+
+class TestBuildInitialParams:
+ @pytest.mark.parametrize(
+ ("endpoint", "should_use_incremental_field", "last_value", "expected_present", "expected_absent"),
+ [
+ # Cursor endpoint, first sync / full refresh: page size + sort set, lookback seeds filter[from].
+ (
+ "logs",
+ False,
+ None,
+ {"page[limit]": 1000, "sort": "timestamp"},
+ [],
+ ),
+ # Cursor endpoint, incremental continuation: filter[from] is the stored watermark.
+ (
+ "logs",
+ True,
+ datetime(2026, 1, 1, tzinfo=UTC),
+ {"sort": "timestamp", "filter[from]": "2026-01-01T00:00:00.000Z"},
+ [],
+ ),
+ # Full-refresh endpoint never sends a server-side time filter, even when incremental is on.
+ (
+ "monitors",
+ True,
+ datetime(2026, 1, 1, tzinfo=UTC),
+ {"page": 0, "page_size": 100},
+ ["filter[from]"],
+ ),
+ # Offset-paginated endpoint seeds offset + size at zero.
+ (
+ "incidents",
+ False,
+ None,
+ {"page[offset]": 0, "page[size]": 100},
+ ["filter[from]"],
+ ),
+ # Single-shot endpoint has no pagination or filter params.
+ (
+ "synthetic_tests",
+ False,
+ None,
+ {},
+ ["filter[from]", "sort"],
+ ),
+ ],
+ )
+ def test_build_initial_params(
+ self,
+ endpoint: str,
+ should_use_incremental_field: bool,
+ last_value: Any,
+ expected_present: dict[str, Any],
+ expected_absent: list[str],
+ ) -> None:
+ config = DATADOG_ENDPOINTS[endpoint]
+ params = _build_initial_params(
+ config,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=last_value,
+ )
+
+ for key, value in expected_present.items():
+ assert params[key] == value
+ for key in expected_absent:
+ assert key not in params
+
+ def test_cursor_endpoint_first_sync_seeds_lookback_window(self) -> None:
+ # No stored watermark, but the cursor endpoints must still send filter[from] so Datadog
+ # doesn't fall back to its now-15m default.
+ config = DATADOG_ENDPOINTS["logs"]
+ params = _build_initial_params(config, should_use_incremental_field=True, db_incremental_field_last_value=None)
+ assert params["filter[from]"].endswith("Z")
+
+
+class TestBuildInitialUrl:
+ def test_keeps_brackets_literal(self) -> None:
+ config = DATADOG_ENDPOINTS["logs"]
+ url = _build_initial_url("https://api.datadoghq.com", config, {"page[limit]": 1000})
+ assert url == "https://api.datadoghq.com/api/v2/logs/events?page[limit]=1000"
+
+ def test_no_params(self) -> None:
+ config = DATADOG_ENDPOINTS["dashboards"]
+ assert (
+ _build_initial_url("https://api.datadoghq.com", config, {}) == "https://api.datadoghq.com/api/v1/dashboard"
+ )
+
+
+class TestComputeNextUrl:
+ HOST = "https://api.datadoghq.com"
+
+ def test_cursor_uses_links_next(self) -> None:
+ config = DATADOG_ENDPOINTS["logs"]
+ nxt = _compute_next_url(
+ config,
+ "https://api.datadoghq.com/api/v2/logs/events",
+ {"links": {"next": "https://api.datadoghq.com/api/v2/logs/events?cursor=abc"}},
+ 1000,
+ self.HOST,
+ )
+ assert nxt == "https://api.datadoghq.com/api/v2/logs/events?cursor=abc"
+
+ def test_cursor_no_links_terminates(self) -> None:
+ config = DATADOG_ENDPOINTS["logs"]
+ assert (
+ _compute_next_url(config, "https://api.datadoghq.com/api/v2/logs/events", {"data": []}, 0, self.HOST)
+ is None
+ )
+
+ @pytest.mark.parametrize(
+ "next_link",
+ [
+ "https://evil.example.com/steal", # off-host
+ "http://api.datadoghq.com/api/v2/logs/events", # non-https
+ "https://api.datadoghq.com.evil.com/api/v2/logs/events", # look-alike host
+ "ftp://api.datadoghq.com/api/v2/logs/events", # non-https scheme
+ ],
+ )
+ def test_cursor_rejects_offhost_next(self, next_link: str) -> None:
+ config = DATADOG_ENDPOINTS["logs"]
+ assert (
+ _compute_next_url(
+ config,
+ "https://api.datadoghq.com/api/v2/logs/events",
+ {"links": {"next": next_link}},
+ 1000,
+ self.HOST,
+ )
+ is None
+ )
+
+ def test_page_bumps_page_number(self) -> None:
+ config = DATADOG_ENDPOINTS["monitors"] # page_size=100
+ nxt = _compute_next_url(
+ config, "https://api.datadoghq.com/api/v1/monitor?page=0&page_size=100", {}, 100, self.HOST
+ )
+ assert nxt is not None
+ query = parse_qs(urlparse(nxt).query)
+ assert query["page"] == ["1"]
+
+ def test_page_short_page_terminates(self) -> None:
+ config = DATADOG_ENDPOINTS["monitors"]
+ nxt = _compute_next_url(
+ config, "https://api.datadoghq.com/api/v1/monitor?page=0&page_size=100", {}, 42, self.HOST
+ )
+ assert nxt is None
+
+ def test_offset_advances_by_page_size(self) -> None:
+ config = DATADOG_ENDPOINTS["incidents"] # page_size=100
+ nxt = _compute_next_url(
+ config, "https://api.datadoghq.com/api/v2/incidents?page[offset]=0&page[size]=100", {}, 100, self.HOST
+ )
+ assert nxt is not None
+ query = parse_qs(urlparse(nxt).query)
+ assert query["page[offset]"] == ["100"]
+
+ def test_offset_short_page_terminates(self) -> None:
+ config = DATADOG_ENDPOINTS["incidents"]
+ nxt = _compute_next_url(
+ config, "https://api.datadoghq.com/api/v2/incidents?page[offset]=0&page[size]=100", {}, 7, self.HOST
+ )
+ assert nxt is None
+
+ def test_none_pagination_terminates(self) -> None:
+ config = DATADOG_ENDPOINTS["dashboards"]
+ assert (
+ _compute_next_url(
+ config, "https://api.datadoghq.com/api/v1/dashboard", {"dashboards": [1, 2]}, 2, self.HOST
+ )
+ is None
+ )
+
+
+class TestValidateCredentials:
+ @pytest.mark.parametrize(
+ ("status_code", "expected_valid"),
+ [
+ (200, True),
+ (401, False),
+ (403, False),
+ (500, False),
+ ],
+ )
+ @mock.patch("posthog.temporal.data_imports.sources.datadog.datadog.make_tracked_session")
+ def test_status_mapping(self, mock_session: mock.MagicMock, status_code: int, expected_valid: bool) -> None:
+ response = mock.MagicMock()
+ response.status_code = status_code
+ mock_session.return_value.get.return_value = response
+
+ is_valid, error = validate_credentials("datadoghq.com", "api", "app")
+
+ assert is_valid is expected_valid
+ if expected_valid:
+ assert error is None
+ else:
+ assert error is not None
+
+ @mock.patch("posthog.temporal.data_imports.sources.datadog.datadog.make_tracked_session")
+ def test_request_exception_is_caught(self, mock_session: mock.MagicMock) -> None:
+ mock_session.return_value.get.side_effect = requests.exceptions.ConnectionError("boom")
+ is_valid, error = validate_credentials("datadoghq.com", "api", "app")
+ assert is_valid is False
+ assert error is not None
+
+
+class TestDatadogSourceResponse:
+ @pytest.mark.parametrize(
+ ("endpoint", "expected_pk", "expect_partition"),
+ [
+ ("logs", "id", True),
+ ("monitors", "id", True),
+ ("synthetic_tests", "public_id", False),
+ ("slos", "id", False),
+ ],
+ )
+ def test_source_response_shape(self, endpoint: str, expected_pk: str, expect_partition: bool) -> None:
+ manager = mock.MagicMock()
+ response = datadog_source(
+ site="datadoghq.com",
+ api_key="api",
+ app_key="app",
+ endpoint=endpoint,
+ logger=mock.MagicMock(),
+ resumable_source_manager=manager,
+ )
+ assert response.name == endpoint
+ assert response.primary_keys == [expected_pk]
+ assert response.sort_mode == "asc"
+ if expect_partition:
+ assert response.partition_mode == "datetime"
+ assert response.partition_keys == [DATADOG_ENDPOINTS[endpoint].partition_key]
+ else:
+ assert response.partition_mode is None
+ assert response.partition_keys is None
+
+
+class TestGetRowsResume:
+ def _run(
+ self, endpoint: str, pages: list[Any], can_resume: bool, resume_url: str | None
+ ) -> tuple[list[Any], list[str], list[str]]:
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = can_resume
+ manager.load_state.return_value = DatadogResumeConfig(next_url=resume_url) if resume_url else None
+ saved: list[str] = []
+ manager.save_state.side_effect = lambda state: saved.append(state.next_url)
+
+ fetched_urls: list[str] = []
+
+ def fake_get(url: str, headers: Any = None, timeout: Any = None) -> Any:
+ fetched_urls.append(url)
+ resp = mock.MagicMock()
+ resp.status_code = 200
+ resp.ok = True
+ resp.json.return_value = pages[len(fetched_urls) - 1]
+ return resp
+
+ with mock.patch.object(ddog, "make_tracked_session") as mock_session:
+ mock_session.return_value.get.side_effect = fake_get
+ rows = list(
+ ddog.get_rows(
+ site="datadoghq.com",
+ api_key="api",
+ app_key="app",
+ endpoint=endpoint,
+ logger=mock.MagicMock(),
+ resumable_source_manager=manager,
+ )
+ )
+ return rows, saved, fetched_urls
+
+ def test_cursor_pagination_yields_and_saves_state(self) -> None:
+ pages = [
+ {
+ "data": [{"id": "1", "attributes": {"timestamp": "t1"}}],
+ "links": {"next": "https://api.datadoghq.com/p2"},
+ },
+ {"data": [{"id": "2", "attributes": {"timestamp": "t2"}}], "links": {}},
+ ]
+ rows, saved, fetched = self._run("logs", pages, can_resume=False, resume_url=None)
+
+ # Attributes flattened to root.
+ assert rows[0][0]["timestamp"] == "t1"
+ assert rows[1][0]["id"] == "2"
+ # State saved after the first batch (before fetching page 2).
+ assert saved == ["https://api.datadoghq.com/p2"]
+ assert fetched[1] == "https://api.datadoghq.com/p2"
+
+ def test_resumes_from_saved_url(self) -> None:
+ pages = [{"data": [{"id": "9", "attributes": {}}], "links": {}}]
+ _rows, _saved, fetched = self._run(
+ "logs", pages, can_resume=True, resume_url="https://api.datadoghq.com/resume-here"
+ )
+ assert fetched[0] == "https://api.datadoghq.com/resume-here"
+
+ @pytest.mark.parametrize(
+ "resume_url",
+ [
+ "https://evil.example.com/steal",
+ "http://api.datadoghq.com/resume-here",
+ "https://api.datadoghq.com.evil.com/resume-here",
+ ],
+ )
+ def test_tampered_resume_url_is_rejected(self, resume_url: str) -> None:
+ pages = [{"data": [{"id": "9", "attributes": {}}], "links": {}}]
+ with pytest.raises(ValueError, match="unexpected URL"):
+ self._run("logs", pages, can_resume=True, resume_url=resume_url)
diff --git a/posthog/temporal/data_imports/sources/datadog/tests/test_datadog_source.py b/posthog/temporal/data_imports/sources/datadog/tests/test_datadog_source.py
new file mode 100644
index 000000000000..7b1937d2a818
--- /dev/null
+++ b/posthog/temporal/data_imports/sources/datadog/tests/test_datadog_source.py
@@ -0,0 +1,191 @@
+from typing import Any
+
+import pytest
+from unittest import mock
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType, SourceFieldSelectConfig
+
+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs
+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from posthog.temporal.data_imports.sources.datadog.datadog import DatadogResumeConfig
+from posthog.temporal.data_imports.sources.datadog.settings import ENDPOINTS, LIMITED_RETENTION_ENDPOINTS
+from posthog.temporal.data_imports.sources.datadog.source import DatadogSource
+from posthog.temporal.data_imports.sources.generated_configs import DatadogSourceConfig
+
+from products.data_warehouse.backend.types import ExternalDataSourceType
+
+INCREMENTAL_ENDPOINTS = {"logs", "audit_logs", "events"}
+
+
+def _make_inputs(**overrides: Any) -> SourceInputs:
+ defaults: dict[str, Any] = {
+ "schema_name": "logs",
+ "schema_id": "schema-1",
+ "source_id": "source-1",
+ "team_id": 123,
+ "should_use_incremental_field": False,
+ "db_incremental_field_last_value": None,
+ "db_incremental_field_earliest_value": None,
+ "incremental_field": None,
+ "incremental_field_type": None,
+ "job_id": "job-1",
+ "logger": mock.MagicMock(),
+ "reset_pipeline": False,
+ }
+ defaults.update(overrides)
+ return SourceInputs(**defaults)
+
+
+class TestDatadogSource:
+ def setup_method(self) -> None:
+ self.source = DatadogSource()
+ self.team_id = 123
+ self.config = DatadogSourceConfig(api_key="dd-api", application_key="dd-app", site="datadoghq.com")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.DATADOG
+
+ def test_site_is_a_connection_host_field(self) -> None:
+ # Changing the site must force the secrets to be re-entered so they're never
+ # sent to a freshly-specified host.
+ assert self.source.connection_host_fields == ["site"]
+
+ def test_get_source_config(self) -> None:
+ config = self.source.get_source_config
+
+ assert config.name.value == "Datadog"
+ assert config.label == "Datadog"
+ assert config.unreleasedSource is True
+ assert config.releaseStatus == ReleaseStatus.ALPHA
+ assert config.iconPath == "/static/services/datadog.svg"
+
+ site_field, api_key_field, app_key_field = config.fields
+
+ assert isinstance(site_field, SourceFieldSelectConfig)
+ assert site_field.name == "site"
+ assert site_field.required is True
+ assert site_field.defaultValue == "datadoghq.com"
+ assert {o.value for o in site_field.options} == {
+ "datadoghq.com",
+ "us3.datadoghq.com",
+ "us5.datadoghq.com",
+ "datadoghq.eu",
+ "ap1.datadoghq.com",
+ "ddog-gov.com",
+ }
+
+ assert isinstance(api_key_field, SourceFieldInputConfig)
+ assert api_key_field.name == "api_key"
+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD
+ assert api_key_field.required is True
+ assert api_key_field.secret is True
+
+ assert isinstance(app_key_field, SourceFieldInputConfig)
+ assert app_key_field.name == "application_key"
+ assert app_key_field.type == SourceFieldInputConfigType.PASSWORD
+ assert app_key_field.required is True
+ assert app_key_field.secret is True
+
+ @pytest.mark.parametrize("expected_key", ["401 Client Error", "403 Client Error"])
+ def test_non_retryable_errors(self, expected_key: str) -> None:
+ assert expected_key in self.source.get_non_retryable_errors()
+
+ def test_get_schemas_returns_all_endpoints(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ assert {s.name for s in schemas} == set(ENDPOINTS)
+
+ def test_get_schemas_incremental_flags(self) -> None:
+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}
+
+ for name in INCREMENTAL_ENDPOINTS:
+ assert schemas[name].supports_incremental is True
+ assert schemas[name].supports_append is True
+ assert schemas[name].incremental_fields == [
+ {
+ "label": "timestamp",
+ "type": "datetime",
+ "field": "timestamp",
+ "field_type": "datetime",
+ }
+ ]
+
+ for name in set(ENDPOINTS) - INCREMENTAL_ENDPOINTS:
+ assert schemas[name].supports_incremental is False
+ assert schemas[name].supports_append is False
+ assert schemas[name].incremental_fields == []
+
+ def test_get_schemas_retention_description(self) -> None:
+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}
+ for name in LIMITED_RETENTION_ENDPOINTS:
+ assert schemas[name].description is not None
+ assert schemas["dashboards"].description is None
+
+ def test_get_schemas_filtered_by_names(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["monitors"])
+ assert len(schemas) == 1
+ assert schemas[0].name == "monitors"
+
+ def test_get_schemas_unknown_name_returns_empty(self) -> None:
+ assert self.source.get_schemas(self.config, self.team_id, names=["nonexistent"]) == []
+
+ @pytest.mark.parametrize(
+ ("mock_return", "expected_valid", "expected_message"),
+ [
+ ((True, None), True, None),
+ ((False, "Invalid Datadog API key."), False, "Invalid Datadog API key."),
+ ],
+ )
+ @mock.patch("posthog.temporal.data_imports.sources.datadog.source.validate_datadog_credentials")
+ def test_validate_credentials(
+ self,
+ mock_validate: mock.MagicMock,
+ mock_return: tuple[bool, str | None],
+ expected_valid: bool,
+ expected_message: str | None,
+ ) -> None:
+ 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("datadoghq.com", "dd-api", "dd-app")
+
+ def test_get_resumable_source_manager_bound_to_resume_config(self) -> None:
+ manager = self.source.get_resumable_source_manager(_make_inputs())
+ assert isinstance(manager, ResumableSourceManager)
+ assert manager._data_class is DatadogResumeConfig
+
+ @mock.patch("posthog.temporal.data_imports.sources.datadog.source.datadog_source")
+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:
+ inputs = _make_inputs(schema_name="monitors", team_id=99, job_id="job-xyz")
+ manager = mock.MagicMock(spec=ResumableSourceManager)
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ mock_source.assert_called_once_with(
+ site="datadoghq.com",
+ api_key="dd-api",
+ app_key="dd-app",
+ endpoint="monitors",
+ logger=inputs.logger,
+ resumable_source_manager=manager,
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=None,
+ )
+
+ @mock.patch("posthog.temporal.data_imports.sources.datadog.source.datadog_source")
+ def test_source_for_pipeline_passes_incremental_value_when_enabled(self, mock_source: mock.MagicMock) -> None:
+ inputs = _make_inputs(
+ schema_name="logs",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value="2026-01-01T00:00:00Z",
+ incremental_field="timestamp",
+ )
+ manager = mock.MagicMock(spec=ResumableSourceManager)
+
+ self.source.source_for_pipeline(self.config, manager, inputs)
+
+ _, kwargs = mock_source.call_args
+ assert kwargs["should_use_incremental_field"] is True
+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01T00:00:00Z"
diff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.py
index 0ebd369b0092..5e68fcca5cb8 100644
--- a/posthog/temporal/data_imports/sources/generated_configs.py
+++ b/posthog/temporal/data_imports/sources/generated_configs.py
@@ -310,7 +310,11 @@ class CustomerIOSourceConfig(config.Config):
@config.config
class DatadogSourceConfig(config.Config):
- pass
+ api_key: str
+ application_key: str
+ site: Literal[
+ "datadoghq.com", "us3.datadoghq.com", "us5.datadoghq.com", "datadoghq.eu", "ap1.datadoghq.com", "ddog-gov.com"
+ ] = config.value(default="datadoghq.com")
@config.config