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(warehouse-sources): add datadog metrics, usage, slo and team tables (#104403)

Tom Owersfe023c4abd31
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
index 9f114ff8156e..e928bb84ed65 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md
@@ -2249,14 +2249,14 @@ Note: Diffed against the Dagster+ cloud GraphQL schema snapshot vendored in dags
## Datadog — gaps
-Today (10): `audit_logs`, `dashboards`, `downtimes`, `events`, `incidents`, `logs`, `monitors`, `slos`, `synthetic_tests`, `users`
+Today (20): `audit_logs`, `dashboards`, `downtimes`, `events`, `incidents`, `logs`, `metrics`, `monitors`, `slo_corrections`, `slo_history`, `slos`, `synthetic_tests`, `team_memberships`, `teams`, `usage_billable_summary`, `usage_estimated_cost`, `usage_historical_cost`, `usage_hourly`, `usage_summary`, `users`
Diffed against: <https://raw.githubusercontent.com/DataDog/datadog-api-client-go/master/.generator/schemas/v2/openapi.yaml>
-- [ ] `GET /api/v2/team and /api/v2/team/{team_id}/memberships` — lookup resolving the team handles attached to monitors, incidents, SLOs and services we already sync (high)
-- [ ] `GET /api/v1/metrics, GET /api/v1/metrics/{metric_name}, GET /api/v1/query` — metric metadata and timeseries point query — Datadog's headline data type, entirely absent today (high)
-- [ ] `GET /api/v1/usage/* (summary, billable-summary, hourly-attribution) and /api/v2/usage/hourly_usage, /estimated_cost, /cost_by_org` — billable usage and cost attribution, the most-requested Datadog warehouse use case (high)
-- [ ] `GET /api/v1/slo/{slo_id}/history, /api/v1/slo/{slo_id}/corrections, GET /api/v2/slo/{slo_id}/status` — error-budget and status history for the SLOs we already sync as static definitions (high)
+- [x] `GET /api/v2/team and /api/v2/team/{team_id}/memberships` — lookup resolving the team handles attached to monitors, incidents, SLOs and services we already sync (high)
+- [x] `GET /api/v1/metrics, GET /api/v1/metrics/{metric_name}, GET /api/v1/query` — metric metadata and timeseries point query — Datadog's headline data type, entirely absent today (high)
+- [x] `GET /api/v1/usage/* (summary, billable-summary, hourly-attribution) and /api/v2/usage/hourly_usage, /estimated_cost, /cost_by_org` — billable usage and cost attribution, the most-requested Datadog warehouse use case (high)
+- [x] `GET /api/v1/slo/{slo_id}/history, /api/v1/slo/{slo_id}/corrections, GET /api/v2/slo/{slo_id}/status` — error-budget and status history for the SLOs we already sync as static definitions (high)
- [ ] `GET /api/v1/hosts and /api/v1/hosts/totals` — host inventory with tags, agent version and muting state — the join key for infrastructure metrics (medium)
- [ ] `POST /api/v2/security_monitoring/signals/search` — security signal events, the analytical output of the detection rules (medium)
- [ ] `POST /api/v2/rum/events/search` — RUM event stream for real-user performance and session analysis (medium)
@@ -2266,7 +2266,16 @@ Diffed against: <https://raw.githubusercontent.com/DataDog/datadog-api-client-go
- [ ] `GET /api/v2/roles and /api/v2/roles/{role_id}/users` — lookup resolving role assignments for the users table we already sync (medium)
- [ ] `GET /api/v2/services/definitions and /api/v2/catalog/entity` — Software Catalog service definitions — lookup resolving the service names on monitors, incidents and spans (medium)
-Note: Diffed against both machine-readable specs (v1: 1.6 MB, v2: 7.3 MB), 1062 paths total. Coverage of the core observability config objects is solid; the missing pieces are almost entirely the metric/usage/cost and event-search families plus the team and role lookup tables. Also unqueried but lower value: on-call schedules and escalation policies, DORA deployments/failures, Scorecards, notebooks, powerpacks.
+Note: Diffed against both machine-readable specs (v1: 1.6 MB, v2: 7.3 MB), 1062 paths total. Coverage of the core observability config objects is solid; the remaining missing pieces are the event-search families plus the role and service-catalog lookup tables. Also unqueried but lower value: on-call schedules and escalation policies, DORA deployments/failures, Scorecards, notebooks, powerpacks.
+
+Ticked above with substitutions, because four of the audited paths were verified against the spec and rejected:
+
+- `GET /api/v1/query` takes a required free-text `query` string with no default, so it has no table shape without per-schema query input, and the spec itself steers callers to `/api/v2/query/timeseries`. `metrics` covers the metric-name half of that line.
+- `GET /api/v1/metrics/{metric_name}` answers for exactly one metric per request, and `/api/v1/metrics` routinely returns tens of thousands of names, so the table would cost one request per metric per sync with no cursor to checkpoint.
+- `GET /api/v1/usage/hourly-attribution` requires a single `usage_type` enum value per request with no "all" option, so one table means fanning out over every usage type and re-walking the full hourly history for each. `usage_hourly` reports the same hourly grain in one paginated, time-filtered call.
+- `GET /api/v2/usage/cost_by_org` is marked `deprecated: true`; `usage_historical_cost` implements `/api/v2/usage/historical_cost`, the replacement the spec names.
+- `GET /api/v2/slo/{slo_id}/status` carries `x-unstable` (public beta, subject to change) and reports the same overall SLI and error budget that `slo_history` already returns.
+- `slo_corrections` reads the org-wide `/api/v1/slo/correction` list rather than fanning `/api/v1/slo/{slo_id}/corrections` out per SLO: the rows are the same and each one carries `slo_id`.
## DataForSEO — **thin**
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/datadog/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/datadog/canonical_descriptions.py
index 56d2267815de..9fa8f4e34385 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/datadog/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/datadog/canonical_descriptions.py
@@ -143,4 +143,137 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"modified": "Time at which the downtime was last modified.",
},
},
+ "metrics": {
+ "description": "A metric name that has actively reported data to Datadog in the lookback window.",
+ "docs_url": "https://docs.datadoghq.com/api/latest/metrics/#get-active-metrics-list",
+ "columns": {
+ "metric": "Name of the actively reporting metric.",
+ },
+ },
+ "usage_hourly": {
+ "description": "Hourly usage for one product family, for one organization.",
+ "docs_url": "https://docs.datadoghq.com/api/latest/usage-metering/#get-hourly-usage-by-product-family",
+ "columns": {
+ "id": "Unique identifier of the usage record.",
+ "timestamp": "The hour the usage was measured in, UTC.",
+ "product_family": "The product the usage is reported for.",
+ "org_name": "Name of the organization the usage belongs to.",
+ "public_id": "Public identifier of the organization.",
+ "account_name": "Name of the account the organization belongs to.",
+ "account_public_id": "Public identifier of the account.",
+ "region": "Datadog region the organization belongs to.",
+ "measurements": "Measured usage values for the product family in the hour, by usage type.",
+ },
+ },
+ "usage_summary": {
+ "description": "Daily usage across every billing dimension, aggregated over all organizations in the account.",
+ "docs_url": "https://docs.datadoghq.com/api/latest/usage-metering/#get-usage-across-your-account",
+ "columns": {
+ "date": "The day the usage was measured on.",
+ "orgs": "Per-organization breakdown of the day's usage.",
+ },
+ },
+ "usage_billable_summary": {
+ "description": "Billable usage for one organization over one billing period.",
+ "docs_url": "https://docs.datadoghq.com/api/latest/usage-metering/#get-billable-usage-across-your-account",
+ "columns": {
+ "org_name": "Name of the organization.",
+ "public_id": "Public identifier of the organization.",
+ "account_name": "Name of the account the organization belongs to.",
+ "account_public_id": "Public identifier of the account.",
+ "start_date": "First date of billable usage in the period.",
+ "end_date": "Last date of billable usage in the period.",
+ "num_orgs": "Number of organizations covered by the summary.",
+ "usage": "Billable usage amounts for the period, by billing dimension.",
+ },
+ },
+ "usage_estimated_cost": {
+ "description": "Estimated cost for the current and previous month. Datadog delays it by up to 72 hours from when the cost was incurred.",
+ "docs_url": "https://docs.datadoghq.com/api/latest/usage-metering/#get-estimated-cost-across-your-account",
+ "columns": {
+ "id": "Unique identifier of the cost record.",
+ "date": "The month the cost applies to.",
+ "org_name": "Name of the organization the cost belongs to.",
+ "public_id": "Public identifier of the organization.",
+ "account_name": "Name of the account the organization belongs to.",
+ "account_public_id": "Public identifier of the account.",
+ "charges": "Breakdown of the estimated charges by product.",
+ "total_cost": "Total estimated cost for the month.",
+ },
+ },
+ "usage_historical_cost": {
+ "description": "Final cost per month, per organization. Datadog publishes a month by the 16th of the month after it.",
+ "docs_url": "https://docs.datadoghq.com/api/latest/usage-metering/#get-historical-cost-across-your-account",
+ "columns": {
+ "id": "Unique identifier of the cost record.",
+ "date": "The month the cost applies to.",
+ "org_name": "Name of the organization the cost belongs to.",
+ "public_id": "Public identifier of the organization.",
+ "account_name": "Name of the account the organization belongs to.",
+ "account_public_id": "Public identifier of the account.",
+ "charges": "Breakdown of the charges by product.",
+ "total_cost": "Total cost for the month.",
+ },
+ },
+ "slo_corrections": {
+ "description": "A correction that excludes a time window from an SLO's error budget, for example a maintenance window.",
+ "docs_url": "https://docs.datadoghq.com/api/latest/service-level-objective-corrections/#get-all-slo-corrections",
+ "columns": {
+ "id": "Unique identifier for the SLO correction.",
+ "slo_id": "Identifier of the SLO the correction applies to.",
+ "category": "Why the correction was made (e.g. Scheduled Maintenance, Deployment).",
+ "description": "Description of the correction.",
+ "start": "Start of the corrected window, in epoch seconds.",
+ "end": "End of the corrected window, in epoch seconds.",
+ "duration": "Length of a recurring correction, in seconds.",
+ "rrule": "Recurrence rule for a repeating correction.",
+ "timezone": "Timezone the correction window is expressed in.",
+ "creator": "User who created the correction.",
+ "created_at": "Time the correction was created, in epoch seconds.",
+ "modified_at": "Time the correction was last modified, in epoch seconds.",
+ },
+ },
+ "slo_history": {
+ "description": "Error-budget history for one SLO over the synced window, including its SLI value against each configured threshold.",
+ "docs_url": "https://docs.datadoghq.com/api/latest/service-level-objectives/#get-an-slos-history",
+ "columns": {
+ "slo_id": "Identifier of the SLO the history belongs to.",
+ "from_ts": "Start of the history window, in epoch seconds.",
+ "to_ts": "End of the history window, in epoch seconds.",
+ "type": "Source type of the SLO (e.g. metric, monitor).",
+ "overall": "SLI value and error budget across the whole window.",
+ "thresholds": "SLI value and error budget per configured timeframe.",
+ "groups": "SLI data per group, for grouped monitor SLOs.",
+ "monitors": "SLI data per monitor, for multi-monitor SLOs.",
+ "group_by": "Grouping parameters, for metric SLOs with a group-by clause.",
+ },
+ },
+ "teams": {
+ "description": "A Datadog team, the owner handle attached to monitors, incidents, SLOs and services.",
+ "docs_url": "https://docs.datadoghq.com/api/latest/teams/#get-all-teams",
+ "columns": {
+ "id": "Unique identifier for the team.",
+ "name": "Display name of the team.",
+ "handle": "Handle used to reference the team on other resources.",
+ "description": "Markdown description shown on the team's homepage.",
+ "avatar": "Avatar character for the team.",
+ "user_count": "Number of users in the team.",
+ "link_count": "Number of links attached to the team.",
+ "is_managed": "Whether team membership is managed externally.",
+ "created_at": "Time the team was created.",
+ "modified_at": "Time the team was last modified.",
+ },
+ },
+ "team_memberships": {
+ "description": "A user's membership of a team, including the role they hold in it.",
+ "docs_url": "https://docs.datadoghq.com/api/latest/teams/#get-team-memberships",
+ "columns": {
+ "id": "Unique identifier for the membership.",
+ "team_id": "Identifier of the team the membership belongs to.",
+ "role": "Role the user holds in the team (e.g. admin).",
+ "provisioned_by": "How the membership was provisioned (e.g. service_account, saml_mapping).",
+ "provisioned_by_id": "Identifier of the user or service account that provisioned the membership.",
+ "relationships": "Links to the team and user the membership joins.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/datadog/datadog.py b/products/warehouse_sources/backend/temporal/data_imports/sources/datadog/datadog.py
index 746acc6bed87..5c5fbd083469 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/datadog/datadog.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/datadog/datadog.py
@@ -1,8 +1,8 @@
import dataclasses
-from collections.abc import Iterator
+from collections.abc import Callable, Iterator
from datetime import UTC, date, datetime, timedelta
from typing import Any, Optional
-from urllib.parse import parse_qsl, urlencode, urlparse, urlunparse
+from urllib.parse import parse_qsl, quote, urlencode, urlparse, urlunparse
import requests
from structlog.types import FilteringBoundLogger
@@ -14,6 +14,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.typ
from products.warehouse_sources.backend.temporal.data_imports.sources.datadog.settings import (
DATADOG_ENDPOINTS,
DatadogEndpointConfig,
+ TimestampFormat,
)
# Datadog regional sites. The site selects which API host the credentials are sent to. The set is
@@ -35,6 +36,10 @@ class DatadogRetryableError(Exception):
pass
+class DatadogFanOutLimitError(Exception):
+ pass
+
+
@dataclasses.dataclass
class DatadogResumeConfig:
next_url: str
@@ -55,18 +60,46 @@ def _get_headers(api_key: str, app_key: str) -> dict[str, str]:
}
-def _format_datetime(value: Any) -> str:
- """Format an incremental cursor value as ISO 8601 with a ``Z`` suffix for Datadog filters."""
+def _coerce_datetime(value: Any) -> datetime | None:
if isinstance(value, datetime):
dt = value
elif isinstance(value, date):
dt = datetime.combine(value, datetime.min.time())
+ elif isinstance(value, str):
+ # The month, hour and epoch filters cannot pass a raw string through the way an ISO filter
+ # can, so parse it here rather than sending Datadog a value it rejects.
+ try:
+ dt = datetime.fromisoformat(value.replace("Z", "+00:00"))
+ except ValueError:
+ return None
else:
+ return None
+ return dt.replace(tzinfo=UTC) if dt.tzinfo is None else dt.astimezone(UTC)
+
+
+def _format_datetime(value: Any) -> str:
+ """Format an incremental cursor value as ISO 8601 with a ``Z`` suffix for Datadog filters."""
+ dt = _coerce_datetime(value)
+ if dt is None:
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 _format_filter_value(value: Any, timestamp_format: TimestampFormat) -> str:
+ """Encode a cursor value the way the target endpoint's time filter expects it."""
+ if timestamp_format == "iso_ms":
+ return _format_datetime(value)
+
+ dt = _coerce_datetime(value)
+ if dt is None:
+ return str(value)
+ if timestamp_format == "month":
+ return dt.strftime("%Y-%m")
+ if timestamp_format == "hour":
+ return dt.strftime("%Y-%m-%dT%H")
+ return str(int(dt.timestamp()))
+
+
def validate_credentials(site: Optional[str], api_key: str, app_key: str) -> tuple[bool, str | None]:
"""Validate Datadog credentials with a single cheap probe.
@@ -94,6 +127,8 @@ def _build_initial_params(
) -> dict[str, Any]:
params: dict[str, Any] = {}
+ params.update(config.static_params)
+
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:
@@ -104,24 +139,29 @@ def _build_initial_params(
if config.sort_param:
params["sort"] = config.sort_param
+ now = datetime.now(UTC)
+
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)
+ cutoff = now - timedelta(days=config.default_lookback_days)
else:
cutoff = None
if cutoff is not None:
- params[config.timestamp_filter_param] = _format_datetime(cutoff)
+ params[config.timestamp_filter_param] = _format_filter_value(cutoff, config.timestamp_filter_format)
+
+ if config.window_end_param:
+ params[config.window_end_param] = _format_filter_value(now, config.timestamp_filter_format)
return params
-def _build_initial_url(host: str, config: DatadogEndpointConfig, params: dict[str, Any]) -> str:
- url = f"{host}{config.path}"
+def _build_initial_url(host: str, path: str, params: dict[str, Any]) -> str:
+ url = f"{host}{path}"
if not params:
return url
# Keep the JSON:API bracket syntax (``page[limit]``) literal; Datadog expects it.
@@ -129,12 +169,21 @@ def _build_initial_url(host: str, config: DatadogEndpointConfig, params: dict[st
def _extract_items(response_json: Any, config: DatadogEndpointConfig) -> list[dict[str, Any]]:
+ raw: 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 []
+ raw = response_json if isinstance(response_json, list) else []
+ elif isinstance(response_json, dict):
+ raw = response_json.get(config.data_path, [])
+ else:
+ raw = []
+
+ if config.single_object:
+ return [raw] if isinstance(raw, dict) else []
+ if not isinstance(raw, list):
+ return []
+ if config.scalar_field:
+ return [{config.scalar_field: value} for value in raw]
+ return raw
def _flatten_item(item: dict[str, Any]) -> dict[str, Any]:
@@ -170,6 +219,19 @@ def _compute_next_url(
return next_link
return None
+ if config.pagination == "record_id":
+ # The usage-metering endpoints hand back an opaque record id instead of a URL, and it is
+ # the only termination signal — a short page does not mean the walk is over.
+ next_record_id: Any = response_json
+ for key in config.record_id_path:
+ next_record_id = next_record_id.get(key) if isinstance(next_record_id, dict) else None
+ if not isinstance(next_record_id, str) or not next_record_id or not config.record_id_param:
+ return None
+ parsed = urlparse(current_url)
+ query = dict(parse_qsl(parsed.query, keep_blank_values=True))
+ query[config.record_id_param] = next_record_id
+ return urlunparse(parsed._replace(query=urlencode(query, safe="[]")))
+
# Numeric pagination: a short page means we've reached the end.
if item_count < config.page_size:
return None
@@ -189,6 +251,116 @@ def _compute_next_url(
return urlunparse(parsed._replace(query=urlencode(query, safe="[]")))
+def _make_fetcher(
+ session: requests.Session,
+ logger: FilteringBoundLogger,
+) -> Callable[..., Any]:
+ @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, allow_missing: bool = False) -> Any:
+ response = session.get(page_url, timeout=REQUEST_TIMEOUT_SECONDS)
+
+ # 408 is a transient request timeout on Datadog's side; retry it like 429/5xx rather than
+ # letting it raise_for_status() into a fatal, non-retried HTTPError.
+ if response.status_code in (408, 429) or response.status_code >= 500:
+ raise DatadogRetryableError(f"Datadog API error (retryable): status={response.status_code}, url={page_url}")
+
+ if allow_missing and response.status_code == 404:
+ return None
+
+ 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()
+
+ return fetch_page
+
+
+def _walk(
+ config: DatadogEndpointConfig,
+ start_url: str,
+ fetch_page: Callable[..., Any],
+ host: str,
+ save_state: Callable[[str], None] | None = None,
+ allow_missing: bool = False,
+) -> Iterator[list[dict[str, Any]]]:
+ """Page through one endpoint URL, yielding a normalized batch per response."""
+ url = start_url
+ while True:
+ data = fetch_page(url, allow_missing)
+ if data is None:
+ return
+
+ items = _extract_items(data, config)
+ if items:
+ if config.flatten_attributes:
+ items = [_flatten_item(item) for item in items]
+ yield items
+
+ # An empty page is not the end of the walk: the usage endpoints carry their cursor in
+ # `meta` independently of `data`, so only the paginator decides when to stop.
+ next_url = _compute_next_url(config, url, data, len(items), host)
+ # A cursor the API repeats would otherwise loop this walk forever.
+ if not next_url or next_url == url:
+ return
+
+ if save_state is not None:
+ # Save state AFTER yielding the batch — a crash re-yields the last batch (merge dedupes
+ # on primary key) instead of skipping it.
+ save_state(next_url)
+ url = next_url
+
+
+def _fan_out_rows(
+ config: DatadogEndpointConfig,
+ fetch_page: Callable[..., Any],
+ host: str,
+) -> Iterator[list[dict[str, Any]]]:
+ """Walk a parent endpoint and query the child endpoint once per parent id."""
+ fan_out = config.parent
+ assert fan_out is not None
+ parent_config = DATADOG_ENDPOINTS[fan_out.parent_endpoint]
+ parent_url = _build_initial_url(
+ host,
+ parent_config.path,
+ _build_initial_params(parent_config, should_use_incremental_field=False, db_incremental_field_last_value=None),
+ )
+
+ parents_seen = 0
+ for parent_batch in _walk(parent_config, parent_url, fetch_page, host):
+ for parent in parent_batch:
+ if parents_seen >= fan_out.max_parents:
+ # Returning here would write a truncated table that looks like a complete sync.
+ raise DatadogFanOutLimitError(
+ f"{config.name} expands one Datadog request per {fan_out.parent_endpoint} record, "
+ f"and this account has more than the {fan_out.max_parents} we sync. "
+ f"Deselect {config.name} to keep the rest of your Datadog tables syncing."
+ )
+ parents_seen += 1
+
+ parent_id = parent.get(fan_out.parent_id_field)
+ if parent_id in (None, ""):
+ continue
+
+ child_path = config.path.replace("{parent_id}", quote(str(parent_id), safe=""))
+ child_url = _build_initial_url(
+ host,
+ child_path,
+ _build_initial_params(config, should_use_incremental_field=False, db_incremental_field_last_value=None),
+ )
+ # A parent deleted between the list call and its child call answers 404; skip it
+ # rather than failing the whole sync.
+ for child_batch in _walk(config, child_url, fetch_page, host, allow_missing=True):
+ for row in child_batch:
+ row[fan_out.child_id_field] = parent_id
+ yield child_batch
+
+
def get_rows(
site: Optional[str],
api_key: str,
@@ -205,8 +377,13 @@ def get_rows(
# 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))
+ fetch_page = _make_fetcher(session, logger)
- params = _build_initial_params(config, should_use_incremental_field, db_incremental_field_last_value)
+ if config.parent is not None:
+ # A fan-out position is a parent cursor plus a child page, which the single-URL resume
+ # state cannot express, so these endpoints restart from the first parent instead.
+ yield from _fan_out_rows(config, fetch_page, host)
+ return
resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
if resume_config is not None:
@@ -217,48 +394,16 @@ def get_rows(
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,
+ params = _build_initial_params(config, should_use_incremental_field, db_incremental_field_last_value)
+ url = _build_initial_url(host, config.path, params)
+
+ yield from _walk(
+ config,
+ url,
+ fetch_page,
+ host,
+ save_state=lambda next_url: resumable_source_manager.save_state(DatadogResumeConfig(next_url=next_url)),
)
- def fetch_page(page_url: str) -> Any:
- response = session.get(page_url, timeout=REQUEST_TIMEOUT_SECONDS)
-
- # 408 is a transient request timeout on Datadog's side; retry it like 429/5xx rather than
- # letting it raise_for_status() into a fatal, non-retried HTTPError.
- if response.status_code in (408, 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(
@@ -285,7 +430,7 @@ def datadog_source(
should_use_incremental_field=should_use_incremental_field,
db_incremental_field_last_value=db_incremental_field_last_value,
),
- primary_keys=[config.primary_key],
+ primary_keys=list(config.primary_keys),
sort_mode="asc",
partition_count=1,
partition_size=1,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/datadog/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/datadog/settings.py
index fdc8b91129d2..a2625ee0e790 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/datadog/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/datadog/settings.py
@@ -1,24 +1,55 @@
-from dataclasses import dataclass, field
+from dataclasses import field
from typing import Literal, Optional
+from posthog.dataclasses import frozen
+
from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
-PaginationStyle = Literal["cursor", "page", "offset", "none"]
+PaginationStyle = Literal["cursor", "page", "offset", "record_id", "none"]
+# How a timestamp filter value is rendered for the endpoint's query param. Datadog uses a
+# different encoding per family: ISO-8601 with milliseconds for event search, month or hour
+# precision for usage metering, and epoch seconds for the metrics and SLO history endpoints.
+TimestampFormat = Literal["iso_ms", "month", "hour", "epoch_seconds"]
+
+
+@frozen
+class DatadogFanOutConfig:
+ """Wires a child endpoint to the parent endpoint whose ids fill its path placeholder."""
+
+ parent_endpoint: str
+ # Field on each parent row holding the id substituted into the child path's ``{parent_id}``.
+ parent_id_field: str
+ # Field name the parent id is written to on every child row, so the child table joins back.
+ child_id_field: str
+ # Datadog caps neither the SLO nor the team list, so bound the walk rather than letting a
+ # pathological account turn one sync into an unbounded request fan.
+ max_parents: int = 2000
-@dataclass
+@frozen
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"
+ # The record's key, unique across the whole table. Fan-out children include the parent id.
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
+ # ``/api/v1/slo/{slo_id}/history`` answers with one object under ``data`` rather than a list.
+ single_object: bool = False
+ # Endpoints that answer with bare strings (``/api/v1/metrics``) wrap each one in a row under
+ # this column name.
+ scalar_field: Optional[str] = None
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
+ record_id_param: Optional[str] = None # opaque next-record cursor echoed back as a param
+ # Where the next-record cursor sits in the response body.
+ record_id_path: tuple[str, ...] = ("meta", "pagination", "next_record_id")
+ # Constant query params the endpoint requires on every request.
+ static_params: dict[str, str] = field(default_factory=dict)
# 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``).
@@ -28,6 +59,12 @@ class DatadogEndpointConfig:
# 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
+ timestamp_filter_format: TimestampFormat = "iso_ms"
+ # Closing bound for endpoints that require a window rather than an open-ended start
+ # (``/api/v1/slo/{slo_id}/history`` rejects a request without ``to_ts``). Always sent as now.
+ window_end_param: Optional[str] = None
+ # Parent endpoint to fan out over, for paths carrying a ``{parent_id}`` placeholder.
+ parent: Optional[DatadogFanOutConfig] = 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
@@ -39,7 +76,10 @@ class DatadogEndpointConfig:
@property
def supports_incremental(self) -> bool:
- return self.timestamp_filter_param is not None
+ # A server-side time filter alone isn't incremental — the endpoint also has to return a
+ # cursor field the pipeline can checkpoint. ``metrics`` filters on ``from`` but every row
+ # is just a metric name, so it stays full refresh.
+ return self.timestamp_filter_param is not None and bool(self.incremental_fields)
def _timestamp_incremental_fields(field_name: str) -> list[IncrementalField]:
@@ -55,12 +95,13 @@ def _timestamp_incremental_fields(field_name: str) -> list[IncrementalField]:
# 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).
+# synthetic tests, downtimes), plus the metrics, usage metering, SLO history and teams families.
#
-# 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.
+# Incremental vs full refresh: the v2 event-style endpoints (logs / audit_logs / events) expose a
+# genuine server-side timestamp filter (``filter[from]``) and an ascending ``timestamp`` sort, and
+# the usage-metering endpoints filter on ``filter[timestamp][start]`` / ``start_month``, so 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(
@@ -108,6 +149,55 @@ DATADOG_ENDPOINTS: dict[str, DatadogEndpointConfig] = {
sort_param="timestamp",
default_lookback_days=30,
),
+ "usage_hourly": DatadogEndpointConfig(
+ name="usage_hourly",
+ path="/api/v2/usage/hourly_usage",
+ data_path="data",
+ # ``id`` is documented only as "unique ID of the response", so key on the grain the
+ # endpoint actually reports: one row per org, per product family, per hour.
+ primary_keys=["public_id", "product_family", "timestamp"],
+ pagination="record_id",
+ page_size=500,
+ page_size_param="page[limit]",
+ record_id_param="page[next_record_id]",
+ # ``filter[product_families]`` is required and has no implicit default.
+ static_params={"filter[product_families]": "all"},
+ flatten_attributes=True,
+ partition_key="timestamp",
+ incremental_fields=_timestamp_incremental_fields("timestamp"),
+ default_incremental_field="timestamp",
+ timestamp_filter_param="filter[timestamp][start]",
+ timestamp_filter_format="hour",
+ default_lookback_days=30,
+ ),
+ "usage_summary": DatadogEndpointConfig(
+ name="usage_summary",
+ path="/api/v1/usage/summary",
+ data_path="usage",
+ primary_keys=["date"],
+ pagination="none",
+ partition_key="date",
+ incremental_fields=_timestamp_incremental_fields("date"),
+ default_incremental_field="date",
+ timestamp_filter_param="start_month",
+ timestamp_filter_format="month",
+ # ``start_month`` is required and rejected beyond 15 months back; stay inside that.
+ default_lookback_days=400,
+ ),
+ "usage_historical_cost": DatadogEndpointConfig(
+ name="usage_historical_cost",
+ path="/api/v2/usage/historical_cost",
+ data_path="data",
+ primary_keys=["public_id", "date"],
+ pagination="none",
+ flatten_attributes=True,
+ partition_key="date",
+ incremental_fields=_timestamp_incremental_fields("date"),
+ default_incremental_field="date",
+ timestamp_filter_param="start_month",
+ timestamp_filter_format="month",
+ default_lookback_days=400,
+ ),
# --- Full refresh ---
"dashboards": DatadogEndpointConfig(
name="dashboards",
@@ -164,7 +254,7 @@ DATADOG_ENDPOINTS: dict[str, DatadogEndpointConfig] = {
path="/api/v1/synthetics/tests",
data_path="tests",
pagination="none",
- primary_key="public_id",
+ primary_keys=["public_id"],
),
"downtimes": DatadogEndpointConfig(
name="downtimes",
@@ -176,6 +266,90 @@ DATADOG_ENDPOINTS: dict[str, DatadogEndpointConfig] = {
offset_param="page[offset]",
flatten_attributes=True,
),
+ "metrics": DatadogEndpointConfig(
+ name="metrics",
+ path="/api/v1/metrics",
+ data_path="metrics",
+ # The endpoint answers with bare metric-name strings rather than objects.
+ scalar_field="metric",
+ primary_keys=["metric"],
+ pagination="none",
+ timestamp_filter_param="from",
+ timestamp_filter_format="epoch_seconds",
+ default_lookback_days=30,
+ ),
+ "usage_billable_summary": DatadogEndpointConfig(
+ name="usage_billable_summary",
+ path="/api/v1/usage/billable-summary",
+ data_path="usage",
+ # One row per org per billing period; omitting ``month`` returns every available period.
+ primary_keys=["public_id", "start_date"],
+ pagination="none",
+ partition_key="start_date",
+ ),
+ "usage_estimated_cost": DatadogEndpointConfig(
+ name="usage_estimated_cost",
+ path="/api/v2/usage/estimated_cost",
+ data_path="data",
+ primary_keys=["public_id", "date"],
+ pagination="none",
+ flatten_attributes=True,
+ partition_key="date",
+ # Datadog only holds estimated cost for the current and previous month, so there is no
+ # history to filter into and the whole window is cheap to re-read each sync.
+ ),
+ "slo_corrections": DatadogEndpointConfig(
+ name="slo_corrections",
+ # The org-wide list returns the same corrections as ``/api/v1/slo/{slo_id}/corrections``
+ # and carries ``slo_id`` on every row, so it needs no fan-out over the SLO list.
+ path="/api/v1/slo/correction",
+ data_path="data",
+ pagination="offset",
+ page_size=100,
+ page_size_param="limit",
+ offset_param="offset",
+ flatten_attributes=True,
+ # ``created_at`` is epoch seconds rather than an ISO datetime, so it isn't a partition key.
+ ),
+ "slo_history": DatadogEndpointConfig(
+ name="slo_history",
+ path="/api/v1/slo/{parent_id}/history",
+ data_path="data",
+ # The history of one SLO is a single object, not a list of them.
+ single_object=True,
+ primary_keys=["slo_id", "from_ts"],
+ pagination="none",
+ parent=DatadogFanOutConfig(parent_endpoint="slos", parent_id_field="id", child_id_field="slo_id"),
+ timestamp_filter_param="from_ts",
+ timestamp_filter_format="epoch_seconds",
+ window_end_param="to_ts",
+ default_lookback_days=30,
+ ),
+ "teams": DatadogEndpointConfig(
+ name="teams",
+ path="/api/v2/team",
+ 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",
+ ),
+ "team_memberships": DatadogEndpointConfig(
+ name="team_memberships",
+ path="/api/v2/team/{parent_id}/memberships",
+ data_path="data",
+ # The membership id embeds the team id, but key on both so the table stays unique even if
+ # Datadog ever changes that encoding.
+ primary_keys=["team_id", "id"],
+ pagination="page",
+ page_size=100,
+ page_size_param="page[size]",
+ page_index_param="page[number]",
+ parent=DatadogFanOutConfig(parent_endpoint="teams", parent_id_field="id", child_id_field="team_id"),
+ flatten_attributes=True,
+ ),
}
# Vendor API versions. Datadog serves each resource under a fixed API version, so this source
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/datadog/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/datadog/source.py
index c5f8ae160c58..06daa84a4042 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/datadog/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/datadog/source.py
@@ -78,6 +78,9 @@ Create an API key and an application key in your [Datadog organization settings]
- `slos_read`
- `synthetics_read`
- `user_access_read`
+- `metrics_read`
+- `teams_read`
+- `usage_read` and `billing_read` (usage and cost tables)
Logs, audit logs, and events read access is governed by your Datadog account's data retention.""",
iconPath="/static/services/datadog.svg",
@@ -123,6 +126,7 @@ Logs, audit logs, and events read access is governed by your Datadog account's d
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.",
+ "expands one Datadog request per": "This table needs one Datadog request per parent record, and your account has more than we sync. Deselect the table to keep your other Datadog tables syncing.",
"410 Client Error: Gone": "The requested Datadog data has fallen outside your account's retention window, or its pagination cursor expired. Retry the sync to start a fresh query.",
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/datadog/tests/test_datadog.py b/products/warehouse_sources/backend/temporal/data_imports/sources/datadog/tests/test_datadog.py
index 623cec790275..4e7ad3aca351 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/datadog/tests/test_datadog.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/datadog/tests/test_datadog.py
@@ -1,3 +1,4 @@
+import dataclasses
from datetime import UTC, date, datetime
from typing import Any
from urllib.parse import parse_qs, urlparse
@@ -10,6 +11,7 @@ import requests
from products.warehouse_sources.backend.temporal.data_imports.sources.datadog import datadog as ddog
from products.warehouse_sources.backend.temporal.data_imports.sources.datadog.datadog import (
DEFAULT_SITE,
+ DatadogFanOutLimitError,
DatadogResumeConfig,
DatadogRetryableError,
_build_initial_params,
@@ -18,6 +20,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.datadog.da
_extract_items,
_flatten_item,
_format_datetime,
+ _format_filter_value,
base_url,
datadog_source,
validate_credentials,
@@ -146,6 +149,29 @@ class TestBuildInitialParams:
{},
["filter[from]", "sort"],
),
+ # filter[product_families] is required and has no implicit default, so omitting it 400s.
+ (
+ "usage_hourly",
+ False,
+ None,
+ {"filter[product_families]": "all", "page[limit]": 500},
+ [],
+ ),
+ # The usage endpoints take hour- and month-precision cutoffs, not the ISO filter format.
+ (
+ "usage_hourly",
+ True,
+ datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC),
+ {"filter[timestamp][start]": "2026-03-04T02"},
+ [],
+ ),
+ (
+ "usage_summary",
+ True,
+ datetime(2026, 3, 4, tzinfo=UTC),
+ {"start_month": "2026-03"},
+ [],
+ ),
],
)
def test_build_initial_params(
@@ -168,6 +194,14 @@ class TestBuildInitialParams:
for key in expected_absent:
assert key not in params
+ def test_full_refresh_ignores_a_stored_watermark(self) -> None:
+ params = _build_initial_params(
+ DATADOG_ENDPOINTS["usage_hourly"],
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=datetime(2026, 3, 4, tzinfo=UTC),
+ )
+ assert params["filter[timestamp][start]"] != "2026-03-04T00"
+
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.
@@ -178,14 +212,13 @@ class TestBuildInitialParams:
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})
+ url = _build_initial_url("https://api.datadoghq.com", "/api/v2/logs/events", {"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"
+ _build_initial_url("https://api.datadoghq.com", "/api/v1/dashboard", {})
+ == "https://api.datadoghq.com/api/v1/dashboard"
)
@@ -264,6 +297,48 @@ class TestComputeNextUrl:
)
assert nxt is None
+ def test_advances_with_the_record_cursor(self) -> None:
+ config = DATADOG_ENDPOINTS["usage_hourly"]
+ nxt = _compute_next_url(
+ config,
+ "https://api.datadoghq.com/api/v2/usage/hourly_usage?page[limit]=500",
+ {"meta": {"pagination": {"next_record_id": "rec-2"}}},
+ 500,
+ self.HOST,
+ )
+ assert nxt is not None
+ query = parse_qs(urlparse(nxt).query)
+ assert query["page[next_record_id]"] == ["rec-2"]
+ assert query["page[limit]"] == ["500"]
+
+ @pytest.mark.parametrize(
+ "body",
+ [
+ {"meta": {"pagination": {"next_record_id": None}}},
+ {"meta": {"pagination": {}}},
+ {"meta": {}},
+ {},
+ ],
+ )
+ def test_absent_cursor_terminates(self, body: Any) -> None:
+ config = DATADOG_ENDPOINTS["usage_hourly"]
+ assert (
+ _compute_next_url(config, "https://api.datadoghq.com/api/v2/usage/hourly_usage", body, 500, self.HOST)
+ is None
+ )
+
+ def test_short_page_does_not_terminate(self) -> None:
+ # The record cursor is the only termination signal here — a short page is normal.
+ config = DATADOG_ENDPOINTS["usage_hourly"]
+ nxt = _compute_next_url(
+ config,
+ "https://api.datadoghq.com/api/v2/usage/hourly_usage?page[limit]=500",
+ {"meta": {"pagination": {"next_record_id": "rec-2"}}},
+ 3,
+ self.HOST,
+ )
+ assert nxt is not None
+
def test_none_pagination_terminates(self) -> None:
config = DATADOG_ENDPOINTS["dashboards"]
assert (
@@ -314,9 +389,15 @@ class TestDatadogSourceResponse:
("monitors", "id", True),
("synthetic_tests", "public_id", False),
("slos", "id", False),
+ # Composite keys: these grains have no single unique column.
+ ("usage_hourly", ["public_id", "product_family", "timestamp"], True),
+ ("usage_billable_summary", ["public_id", "start_date"], True),
+ ("team_memberships", ["team_id", "id"], False),
+ ("slo_history", ["slo_id", "from_ts"], False),
+ ("metrics", ["metric"], False),
],
)
- def test_source_response_shape(self, endpoint: str, expected_pk: str, expect_partition: bool) -> None:
+ def test_source_response_shape(self, endpoint: str, expected_pk: Any, expect_partition: bool) -> None:
manager = mock.MagicMock()
response = datadog_source(
site="datadoghq.com",
@@ -327,7 +408,7 @@ class TestDatadogSourceResponse:
resumable_source_manager=manager,
)
assert response.name == endpoint
- assert response.primary_keys == [expected_pk]
+ assert response.primary_keys == ([expected_pk] if isinstance(expected_pk, str) else expected_pk)
assert response.sort_mode == "asc"
if expect_partition:
assert response.partition_mode == "datetime"
@@ -460,3 +541,216 @@ class TestFetchPageRetry:
# DatadogRetryableError. Guards against widening the 408 fix to swallow all 4xx.
with pytest.raises(requests.HTTPError):
self._run([400])
+
+
+class TestFormatFilterValue:
+ @pytest.mark.parametrize(
+ ("timestamp_format", "expected"),
+ [
+ ("iso_ms", "2026-03-04T02:58:14.000Z"),
+ ("month", "2026-03"),
+ ("hour", "2026-03-04T02"),
+ ("epoch_seconds", "1772593094"),
+ ],
+ )
+ def test_each_family_encoding(self, timestamp_format: Any, expected: str) -> None:
+ assert _format_filter_value(datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), timestamp_format) == expected
+
+ @pytest.mark.parametrize("timestamp_format", ["month", "hour", "epoch_seconds"])
+ def test_iso_string_watermark_is_parsed(self, timestamp_format: Any) -> None:
+ # A string watermark can pass straight through an ISO filter but would be rejected by the
+ # month / hour / epoch filters, so it has to be parsed rather than forwarded.
+ value = _format_filter_value("2026-03-04T02:58:14Z", timestamp_format)
+ assert value != "2026-03-04T02:58:14Z"
+ assert _format_filter_value(datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), timestamp_format) == value
+
+ def test_unparseable_string_falls_back_to_itself(self) -> None:
+ assert _format_filter_value("not-a-date", "month") == "not-a-date"
+
+
+class TestExtractItemsForNewShapes:
+ def test_single_object_endpoint_wraps_the_object(self) -> None:
+ config = DATADOG_ENDPOINTS["slo_history"]
+ assert _extract_items({"data": {"from_ts": 1, "type": "metric"}}, config) == [{"from_ts": 1, "type": "metric"}]
+
+ def test_single_object_endpoint_rejects_a_list(self) -> None:
+ config = DATADOG_ENDPOINTS["slo_history"]
+ assert _extract_items({"data": [{"from_ts": 1}]}, config) == []
+
+ def test_scalar_endpoint_wraps_each_name(self) -> None:
+ config = DATADOG_ENDPOINTS["metrics"]
+ assert _extract_items({"metrics": ["system.cpu.idle", "system.load.1"]}, config) == [
+ {"metric": "system.cpu.idle"},
+ {"metric": "system.load.1"},
+ ]
+
+
+class TestWindowedEndpointParams:
+ def test_sends_both_bounds_in_epoch_seconds(self) -> None:
+ # /api/v1/slo/{slo_id}/history rejects a request missing either bound.
+ params = _build_initial_params(
+ DATADOG_ENDPOINTS["slo_history"],
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=None,
+ )
+ assert int(params["from_ts"]) < int(params["to_ts"])
+
+
+class TestFanOut:
+ def _run(self, endpoint: str, bodies: dict[str, Any], statuses: dict[str, int] | None = None) -> dict[str, Any]:
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = False
+ manager.load_state.return_value = None
+ saved: list[str] = []
+ manager.save_state.side_effect = lambda state: saved.append(state.next_url)
+
+ requested: list[str] = []
+
+ def fake_get(url: str, timeout: Any = None) -> Any:
+ requested.append(url)
+ path = urlparse(url).path
+ resp = mock.MagicMock()
+ resp.status_code = (statuses or {}).get(path, 200)
+ resp.ok = resp.status_code < 400
+ resp.text = "body"
+ resp.json.return_value = bodies.get(path, {})
+ if not resp.ok:
+ resp.raise_for_status.side_effect = requests.HTTPError("error", response=resp)
+ return resp
+
+ with mock.patch.object(ddog, "make_tracked_session") as mock_session:
+ mock_session.return_value.get.side_effect = fake_get
+ rows = [row for batch in self._rows(endpoint, manager) for row in batch]
+
+ return {"rows": rows, "saved": saved, "paths": [urlparse(u).path for u in requested]}
+
+ def _rows(self, endpoint: str, manager: Any) -> Any:
+ return ddog.get_rows(
+ site="datadoghq.com",
+ api_key="api",
+ app_key="app",
+ endpoint=endpoint,
+ logger=mock.MagicMock(),
+ resumable_source_manager=manager,
+ )
+
+ def test_queries_each_parent_and_stamps_the_parent_id(self) -> None:
+ result = self._run(
+ "team_memberships",
+ {
+ "/api/v2/team": {"data": [{"id": "team-a", "attributes": {}}, {"id": "team-b", "attributes": {}}]},
+ "/api/v2/team/team-a/memberships": {"data": [{"id": "m1", "attributes": {"role": "admin"}}]},
+ "/api/v2/team/team-b/memberships": {"data": [{"id": "m2", "attributes": {"role": "member"}}]},
+ },
+ )
+
+ assert result["rows"] == [
+ {"id": "m1", "role": "admin", "team_id": "team-a"},
+ {"id": "m2", "role": "member", "team_id": "team-b"},
+ ]
+ assert "/api/v2/team/team-a/memberships" in result["paths"]
+ assert "/api/v2/team/team-b/memberships" in result["paths"]
+
+ def test_single_object_child_is_yielded_as_one_row(self) -> None:
+ result = self._run(
+ "slo_history",
+ {
+ "/api/v1/slo": {"data": [{"id": "slo-1"}]},
+ "/api/v1/slo/slo-1/history": {"data": {"from_ts": 1, "overall": {"sli_value": 99.9}}},
+ },
+ )
+ assert result["rows"] == [{"from_ts": 1, "overall": {"sli_value": 99.9}, "slo_id": "slo-1"}]
+
+ def test_parent_deleted_mid_sync_is_skipped(self) -> None:
+ # A 404 on one child must not fail the whole sync — the parent list is a snapshot.
+ result = self._run(
+ "slo_history",
+ {
+ "/api/v1/slo": {"data": [{"id": "gone"}, {"id": "slo-2"}]},
+ "/api/v1/slo/slo-2/history": {"data": {"from_ts": 2}},
+ },
+ statuses={"/api/v1/slo/gone/history": 404},
+ )
+ assert result["rows"] == [{"from_ts": 2, "slo_id": "slo-2"}]
+
+ def test_raises_when_the_parent_cap_is_exceeded(self) -> None:
+ fan_out = DATADOG_ENDPOINTS["team_memberships"].parent
+ assert fan_out is not None
+ capped = dataclasses.replace(
+ DATADOG_ENDPOINTS["team_memberships"],
+ parent=dataclasses.replace(fan_out, max_parents=1),
+ )
+ # A truncated table that reports success would look like a complete sync.
+ with mock.patch.dict(DATADOG_ENDPOINTS, {"team_memberships": capped}):
+ with pytest.raises(DatadogFanOutLimitError, match="team_memberships"):
+ self._run(
+ "team_memberships",
+ {
+ "/api/v2/team": {"data": [{"id": "team-a"}, {"id": "team-b"}]},
+ "/api/v2/team/team-a/memberships": {"data": [{"id": "m1"}]},
+ "/api/v2/team/team-b/memberships": {"data": [{"id": "m2"}]},
+ },
+ )
+
+ def test_no_resume_state_is_saved(self) -> None:
+ # A fan-out position is a parent cursor plus a child page, which the single-URL resume
+ # state can't express — saving one would resume the child walk against the wrong parent.
+ result = self._run(
+ "team_memberships",
+ {
+ "/api/v2/team": {"data": [{"id": "team-a"}]},
+ "/api/v2/team/team-a/memberships": {"data": [{"id": "m1"}]},
+ },
+ )
+ assert result["saved"] == []
+
+
+class TestWalkTermination:
+ def _pages(self, endpoint: str, bodies: list[Any]) -> tuple[list[Any], list[str]]:
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = False
+ manager.load_state.return_value = None
+ fetched: list[str] = []
+
+ def fake_get(url: str, timeout: Any = None) -> Any:
+ resp = mock.MagicMock()
+ resp.status_code = 200
+ resp.ok = True
+ resp.json.return_value = bodies[min(len(fetched), len(bodies) - 1)]
+ fetched.append(url)
+ 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, fetched
+
+ def test_repeated_record_cursor_stops_the_walk(self) -> None:
+ # Datadog echoing the same cursor would otherwise loop this walk forever.
+ rows, fetched = self._pages(
+ "usage_hourly",
+ [{"data": [{"id": "u1", "attributes": {}}], "meta": {"pagination": {"next_record_id": "same"}}}],
+ )
+ assert len(fetched) == 2
+ assert len(rows) == 2
+
+ def test_empty_page_with_a_cursor_keeps_paginating(self) -> None:
+ # The usage cursor lives in meta, independently of data, so an empty page is not the end.
+ rows, fetched = self._pages(
+ "usage_hourly",
+ [
+ {"data": [], "meta": {"pagination": {"next_record_id": "rec-2"}}},
+ {"data": [{"id": "u2", "attributes": {}}], "meta": {"pagination": {}}},
+ ],
+ )
+ assert [batch[0]["id"] for batch in rows] == ["u2"]
+ assert len(fetched) == 2
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/datadog/tests/test_datadog_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/datadog/tests/test_datadog_source.py
index 6b5e57628dea..5b2738cd9dff 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/datadog/tests/test_datadog_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/datadog/tests/test_datadog_source.py
@@ -12,7 +12,16 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_
DatadogSourceConfig,
)
-INCREMENTAL_ENDPOINTS = {"logs", "audit_logs", "events"}
+# Endpoint -> the cursor field it advertises. Only endpoints with a genuine server-side time
+# filter belong here; everything else must come back full-refresh only.
+INCREMENTAL_ENDPOINTS = {
+ "logs": "timestamp",
+ "audit_logs": "timestamp",
+ "events": "timestamp",
+ "usage_hourly": "timestamp",
+ "usage_summary": "date",
+ "usage_historical_cost": "date",
+}
def _make_inputs(**overrides: Any) -> SourceInputs:
@@ -52,19 +61,19 @@ class TestDatadogSource:
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:
+ for name, cursor_field in INCREMENTAL_ENDPOINTS.items():
assert schemas[name].supports_incremental is True
assert schemas[name].supports_append is True
assert schemas[name].incremental_fields == [
{
- "label": "timestamp",
+ "label": cursor_field,
"type": "datetime",
- "field": "timestamp",
+ "field": cursor_field,
"field_type": "datetime",
}
]
- for name in set(ENDPOINTS) - INCREMENTAL_ENDPOINTS:
+ for name in set(ENDPOINTS) - set(INCREMENTAL_ENDPOINTS):
assert schemas[name].supports_incremental is False
assert schemas[name].supports_append is False
assert schemas[name].incremental_fields == []