: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.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(warehouse-sources): add dynatrace metric, entity and synthetic tables (#106638)
Tom Owersf18041cc1c11
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.mdindex 016b12e56ce5..717acfdd91f3 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@@ -2695,15 +2695,15 @@ Note: api.dub.co/openapi.json 404s; the live spec is served from spec.speakeasy.## Dynatrace — gaps-Today (10): `applications`, `audit_logs`, `events`, `hosts`, `metrics`, `problems`, `process_groups`, `security_problems`, `services`, `slos`+Today (20): `applications`, `audit_logs`, `cloud_applications`, `custom_devices`, `databases`, `disks`, `events`, `hosts`, `kubernetes_clusters`, `kubernetes_nodes`, `metric_data_points`, `metrics`, `problems`, `process_groups`, `queues`, `security_problems`, `services`, `slos`, `synthetic_executions`, `synthetic_monitors`Diffed against: <https://docs.dynatrace.com/docs/dynatrace-api/environment-api/metric-v2/get-data-points>-- [ ] `GET /api/v2/metrics/query` — actual metric data points; the existing `metrics` table is descriptor metadata only (settings.py hits GET /api/v2/metrics), so no timeseries values are syncable today (high)+- [x] `GET /api/v2/metrics/query` — actual metric data points; the existing `metrics` table is descriptor metadata only (settings.py hits GET /api/v2/metrics), so no timeseries values are syncable today (high)- [ ] `GET /api/v2/entityTypes` — lookup of every monitored entity type and its properties/relationships - needed to interpret entity IDs and to know what else is syncable (high)-- [ ] `GET /api/v2/entities with entitySelector for types beyond HOST/SERVICE/APPLICATION/PROCESS_GROUP` — DATABASE, KUBERNETES_CLUSTER/NODE, CLOUD_APPLICATION, DISK, QUEUE and custom devices are all served by the same endpoint the source already calls, just with a different type selector (high)-- [ ] `GET /api/v1/synthetic/monitors` — synthetic monitor definitions - the availability side of the product is entirely absent (high)-- [ ] `GET /api/v2/synthetic/executions` — synthetic monitor execution results, the per-run success/duration facts you would actually chart (high)+- [x] `GET /api/v2/entities with entitySelector for types beyond HOST/SERVICE/APPLICATION/PROCESS_GROUP` — DATABASE, KUBERNETES_CLUSTER/NODE, CLOUD_APPLICATION, DISK, QUEUE and custom devices are all served by the same endpoint the source already calls, just with a different type selector (high)+- [x] `GET /api/v1/synthetic/monitors` — synthetic monitor definitions - the availability side of the product is entirely absent (high)+- [x] `GET /api/v2/synthetic/executions` — synthetic monitor execution results, the per-run success/duration facts you would actually chart (high)- [ ] `GET /api/v1/userSessionQueryLanguage/table` — RUM user sessions - session-level real-user data, currently only aggregate application entities are synced (medium)- [ ] `GET /api/v2/tags` — entity tag lookup; management-zone and tag dimensions are how Dynatrace users slice everything (medium)- [ ] `GET /api/v2/releases` — release inventory joining deployed versions to entities, for change-vs-problem correlation (medium)@@ -2712,7 +2712,7 @@ Diffed against: <https://docs.dynatrace.com/docs/dynatrace-api/environment-api/m- [ ] `GET /api/v2/logs/search` — log records; high volume but the standard analytical join partner for problems and events (medium)- [ ] `GET /api/v2/synthetic/locations` — synthetic location lookup resolving the location IDs on executions (low)-Note: Diffed against the Environment API section of docs.dynatrace.com/docs/sitemap.xml (770 URLs under /dynatrace-api/environment-api/), then confirmed individual paths on their doc pages (/api/v2/entityTypes, /api/v1/synthetic/monitors, /api/v2/synthetic/executions, /api/v2/releases, /api/v2/tags, /api/v2/attacks, /api/v2/logs/search, /api/v1/userSessionQueryLanguage/table). Important: the source's `metrics` table is descriptors, not values - verified in products/warehouse_sources/backend/temporal/data_imports/sources/dynatrace/settings.py. Entity tables are hardcoded to four types via \_entity_endpoint(); no dynamic type discovery. Config-only areas (settings objects, extensions, credential vault, tokens, network zones, ActiveGate deployment) deliberately excluded.+Note: Diffed against the Environment API section of docs.dynatrace.com/docs/sitemap.xml (770 URLs under /dynatrace-api/environment-api/), then confirmed individual paths on their doc pages (/api/v2/entityTypes, /api/v1/synthetic/monitors, /api/v2/synthetic/executions, /api/v2/releases, /api/v2/tags, /api/v2/attacks, /api/v2/logs/search, /api/v1/userSessionQueryLanguage/table). Important: the source's `metrics` table is descriptors, not values - verified in products/warehouse_sources/backend/temporal/data_imports/sources/dynatrace/settings.py. Entity tables are hardcoded per type via \_entity_endpoint(); no dynamic type discovery. Config-only areas (settings objects, extensions, credential vault, tokens, network zones, ActiveGate deployment) deliberately excluded. `DATABASE` is not a Dynatrace entity type, so the `databases` table selects `RELATIONAL_DATABASE_SERVICE`. `/api/v2/synthetic/executions` returns on-demand executions only, and Dynatrace serves at most the last six hours of them, so the watermark is clamped to that window. Synthetic monitors are read from the v1 listing: the v2 equivalent needs the broad `settings.read` scope and currently covers only browser and multi-protocol monitors.## E2B — gapsdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dynatrace/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dynatrace/canonical_descriptions.pyindex 20a856fd361f..504b228b684c 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/dynatrace/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dynatrace/canonical_descriptions.py@@ -111,6 +111,41 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"docs_url": "https://docs.dynatrace.com/docs/dynatrace-api/environment-api/entity-v2","columns": _ENTITY_COLUMNS,},+ "databases": {+ "description": "Monitored relational database service entities (for example Amazon RDS) and their metadata.",+ "docs_url": "https://docs.dynatrace.com/docs/dynatrace-api/environment-api/entity-v2",+ "columns": _ENTITY_COLUMNS,+ },+ "disks": {+ "description": "Monitored disk entities and their metadata.",+ "docs_url": "https://docs.dynatrace.com/docs/dynatrace-api/environment-api/entity-v2",+ "columns": _ENTITY_COLUMNS,+ },+ "queues": {+ "description": "Monitored messaging queue entities and their metadata.",+ "docs_url": "https://docs.dynatrace.com/docs/dynatrace-api/environment-api/entity-v2",+ "columns": _ENTITY_COLUMNS,+ },+ "kubernetes_clusters": {+ "description": "Monitored Kubernetes cluster entities and their metadata.",+ "docs_url": "https://docs.dynatrace.com/docs/dynatrace-api/environment-api/entity-v2",+ "columns": _ENTITY_COLUMNS,+ },+ "kubernetes_nodes": {+ "description": "Monitored Kubernetes node entities and their metadata.",+ "docs_url": "https://docs.dynatrace.com/docs/dynatrace-api/environment-api/entity-v2",+ "columns": _ENTITY_COLUMNS,+ },+ "cloud_applications": {+ "description": "Monitored Kubernetes workload entities and their metadata.",+ "docs_url": "https://docs.dynatrace.com/docs/dynatrace-api/environment-api/entity-v2",+ "columns": _ENTITY_COLUMNS,+ },+ "custom_devices": {+ "description": "Custom device entities reported through the Dynatrace API and their metadata.",+ "docs_url": "https://docs.dynatrace.com/docs/dynatrace-api/environment-api/entity-v2",+ "columns": _ENTITY_COLUMNS,+ },"metrics": {"description": "Catalog of metric descriptors available in the environment (built-in and custom).","docs_url": "https://docs.dynatrace.com/docs/dynatrace-api/environment-api/metric-v2",@@ -126,6 +161,18 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"tags": "Tags applied to the metric.",},},+ "metric_data_points": {+ "description": "Hourly metric values for the metric keys configured on the source, one row per metric, dimension combination and timestamp.",+ "docs_url": "https://docs.dynatrace.com/docs/dynatrace-api/environment-api/metric-v2/get-data-points",+ "columns": {+ "metricId": "Key of the metric the data point belongs to, including any transformation applied.",+ "dimensionKey": "Sorted dimension name/value pairs identifying the series the data point belongs to.",+ "dimensionMap": "Dimension names mapped to their values for this series.",+ "dimensions": "Ordered dimension values of the series. Deprecated by Dynatrace in favour of dimensionMap.",+ "timestamp": "End of the time slot the data point covers, in UTC milliseconds.",+ "value": "Value of the metric in that time slot.",+ },+ },"slos": {"description": "Service-level objectives with their current evaluation status and error budget.","docs_url": "https://docs.dynatrace.com/docs/dynatrace-api/environment-api/service-level-objectives",@@ -145,4 +192,34 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"relatedOpenProblems": "Number of open problems related to the SLO.",},},+ "synthetic_monitors": {+ "description": "Synthetic monitors configured in the environment.",+ "docs_url": "https://docs.dynatrace.com/docs/dynatrace-api/environment-api/synthetic/synthetic-monitors/get-all-monitors",+ "columns": {+ "entityId": "Unique identifier of the synthetic monitor (e.g. SYNTHETIC_TEST-ABC123).",+ "name": "Name of the synthetic monitor.",+ "type": "Type of the monitor: BROWSER or HTTP.",+ "enabled": "Whether the monitor is enabled.",+ },+ },+ "synthetic_executions": {+ "description": "On-demand executions of synthetic monitors, with their stage, location and results.",+ "docs_url": "https://docs.dynatrace.com/docs/dynatrace-api/environment-api/synthetic-v2/synthetic-monitor-execution/get-all-executions",+ "columns": {+ "executionId": "Unique identifier of the execution.",+ "batchId": "Identifier of the batch the execution belongs to.",+ "monitorId": "Identifier of the executed monitor.",+ "locationId": "Identifier of the location the monitor ran from.",+ "executionStage": "Stage of the execution: TRIGGERED, EXECUTED, DATA_RETRIEVED, WAITING, TIMED_OUT, or NOT_TRIGGERED.",+ "schedulingTimestamp": "Time the execution was scheduled, in UTC milliseconds.",+ "executionTimestamp": "Time the execution finished, in UTC milliseconds.",+ "dataDeliveryTimestamp": "Time the full result set reached the server, in UTC milliseconds.",+ "source": "Source of the triggering request: API or UI.",+ "userId": "Name of the user who triggered the execution.",+ "processingMode": "Processing mode of the execution.",+ "simpleResults": "Basic results of the execution, such as status, total time and response code.",+ "fullResults": "Extended execution details, including per-step results and failure messages.",+ "metadata": "Metadata map of the execution batch.",+ },+ },}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dynatrace/dynatrace.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dynatrace/dynatrace.pyindex 076280d40c7d..6892bb5eb042 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/dynatrace/dynatrace.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dynatrace/dynatrace.py@@ -1,7 +1,7 @@import reimport dataclasses-from collections.abc import Iterator-from datetime import UTC, date, datetime+from collections.abc import Callable, Iterator+from datetime import UTC, date, datetime, timedeltafrom typing import Any, Optionalfrom urllib.parse import urlencode, urlparse@@ -128,6 +128,20 @@ def _format_from_value(value: Any) -> str:return str(value)+def _clamped_from_value(value: Any, max_lookback: timedelta) -> str:+ """Format an incremental cursor, held inside the endpoint's longest supported window.++ Synthetic executions are only served for the last six hours, so a watermark older than that+ would ask for a timeframe Dynatrace refuses. Relative seeds (``now-6h``) are already inside+ the window and pass through untouched.+ """+ formatted = _format_from_value(value)+ if not formatted.isdigit():+ return formatted+ earliest_ms = int((datetime.now(UTC) - max_lookback).timestamp() * 1000)+ return str(max(int(formatted), earliest_ms))++def _build_url(base_url: str, path: str, params: dict[str, str]) -> str:url = f"{base_url}{path}"if not params:@@ -135,31 +149,100 @@ def _build_url(base_url: str, path: str, params: dict[str, str]) -> str:return f"{url}?{urlencode(params)}"-def _build_request_params(config: DynatraceEndpointConfig) -> dict[str, Any]:+def _build_request_params(config: DynatraceEndpointConfig, metric_selector: Optional[str]) -> dict[str, Any]:"""First-page query params for the framework resource.- Time-filtered endpoints declare ``from`` as a framework incremental param: it's seeded with the- endpoint's lookback (so a first sync / full refresh isn't clamped to Dynatrace's narrow default- window) and replaced with the stored watermark on incremental runs. Non-incremental endpoints- that still carry a ``default_from`` (the entity tables) send it as a static param.+ Time-filtered endpoints declare their window-start param as a framework incremental param: it's+ seeded with the endpoint's lookback (so a first sync / full refresh isn't clamped to Dynatrace's+ narrow default window) and replaced with the stored watermark on incremental runs.+ Non-incremental endpoints that still carry a ``default_from`` (the entity tables) send it as a+ static param."""- params: dict[str, Any] = {"pageSize": str(config.page_size)}+ params: dict[str, Any] = {}+ if config.page_size is not None:+ params["pageSize"] = str(config.page_size)if config.entity_selector:params["entitySelector"] = config.entity_selector+ if config.requires_metric_selector and metric_selector:+ params["metricSelector"] = metric_selector.strip()params.update(config.extra_params)+ max_lookback = config.max_lookbackif config.supports_time_filter and config.incremental_field:- params["from"] = {+ params[config.time_filter_param] = {"type": "incremental","cursor_path": config.incremental_field,"initial_value": config.default_from,- "convert": _format_from_value,+ "convert": _format_from_value+ if max_lookback is None+ else lambda value: _clamped_from_value(value, max_lookback),}elif config.default_from:- params["from"] = config.default_from+ params[config.time_filter_param] = config.default_from+ return params+++def _scope_probe_config(endpoint: str) -> DynatraceEndpointConfig:+ """Endpoint config whose path is probed when checking ``endpoint``'s token scope."""+ config = DYNATRACE_ENDPOINTS[endpoint]+ return DYNATRACE_ENDPOINTS[config.scope_probe_endpoint] if config.scope_probe_endpoint else config+++def _probe_params(config: DynatraceEndpointConfig) -> dict[str, str]:+ params: dict[str, str] = {}+ if config.page_size is not None:+ params["pageSize"] = "1"+ if config.entity_selector:+ params["entitySelector"] = config.entity_selector+ if config.supports_time_filter or config.default_from:+ params[config.time_filter_param] = "now-1h"return params+def _dimension_key(dimension_map: dict[str, Any], dimensions: list[Any]) -> str:+ """Stable identity of one metric series, used as part of the data point primary key.++ ``dimensions`` is deprecated in favour of ``dimensionMap``, so prefer the map and sort it —+ Dynatrace makes no ordering promise about either.+ """+ if dimension_map:+ return "|".join(f"{key}={dimension_map[key]}" for key in sorted(dimension_map))+ return "|".join(str(dimension) for dimension in dimensions)+++def _flatten_metric_data_points(page: list[dict[str, Any]]) -> list[dict[str, Any]]:+ """Expand the metrics query response into one row per data point.++ Each series carries ``timestamps`` and ``values`` as two index-aligned arrays, which is not a+ shape a warehouse table can be queried on.+ """+ rows: list[dict[str, Any]] = []+ for series_collection in page:+ metric_id = series_collection.get("metricId")+ for series in series_collection.get("data") or []:+ dimension_map = series.get("dimensionMap") or {}+ dimensions = series.get("dimensions") or []+ dimension_key = _dimension_key(dimension_map, dimensions)+ for timestamp, value in zip(series.get("timestamps") or [], series.get("values") or []):+ rows.append(+ {+ "metricId": metric_id,+ "dimensionKey": dimension_key,+ "dimensionMap": dimension_map,+ "dimensions": dimensions,+ "timestamp": timestamp,+ "value": value,+ }+ )+ return rows+++# Endpoints whose response rows need reshaping before they can land in a table.+ROW_MAPPERS: dict[str, Callable[[list[dict[str, Any]]], list[dict[str, Any]]]] = {+ "metric_data_points": _flatten_metric_data_points,+}++class DynatraceNextPageKeyPaginator(BasePaginator):"""Cursor pagination via Dynatrace's ``nextPageKey``.@@ -236,13 +319,8 @@ def validate_credentials(return False, host_err or HOST_NOT_ALLOWED_ERRORif schema_name is not None and schema_name in DYNATRACE_ENDPOINTS:- config = DYNATRACE_ENDPOINTS[schema_name]- probe_params: dict[str, str] = {"pageSize": "1"}- if config.entity_selector:- probe_params["entitySelector"] = config.entity_selector- if config.supports_time_filter or config.default_from:- probe_params["from"] = "now-1h"- url = _build_url(base_url, config.path, probe_params)+ config = _scope_probe_config(schema_name)+ url = _build_url(base_url, config.path, _probe_params(config))required_scope = ENDPOINT_SCOPES.get(schema_name)else:url = _build_url(base_url, PROBE_PATH, {"pageSize": "1", "from": "now-1h"})@@ -266,12 +344,18 @@ def validate_credentials(return False, f"Dynatrace credential validation failed (status {status})."+METRIC_SELECTOR_REQUIRED_ERROR = (+ "Dynatrace needs to know which metrics to read. Add the metric keys to the 'Metric keys' "+ "field on the source, then try again."+)++def check_endpoint_permissions(- environment_url: str, api_token: str, endpoints: list[str], team_id: int+ environment_url: str, api_token: str, endpoints: list[str], team_id: int, metric_selector: Optional[str] = None) -> dict[str, str | None]:- """Per-endpoint scope probe for the schema picker. ``None`` = reachable, else a short reason.+ """Per-endpoint readiness probe for the schema picker. ``None`` = reachable, else a short reason.- Endpoints sharing a scope (the four entity tables) share one probe. Only a real 403 denial is+ Endpoints sharing a scope (the entity tables) share one probe. Only a real 403 denial isreported — throttles, 5xx, and network blips must not mark a table as missing permissions."""base_url = normalize_environment_url(environment_url)@@ -287,25 +371,23 @@ def check_endpoint_permissions(denial_by_scope: dict[str, str | None] = {}for endpoint in endpoints:- config = DYNATRACE_ENDPOINTS.get(endpoint)- if config is None:+ if endpoint not in DYNATRACE_ENDPOINTS:results[endpoint] = Nonecontinue+ if DYNATRACE_ENDPOINTS[endpoint].requires_metric_selector and not (metric_selector or "").strip():+ results[endpoint] = METRIC_SELECTOR_REQUIRED_ERROR+ continue+scope = ENDPOINT_SCOPES.get(endpoint, "")if scope in denial_by_scope:results[endpoint] = denial_by_scope[scope]continue- probe_params: dict[str, str] = {"pageSize": "1"}- if config.entity_selector:- probe_params["entitySelector"] = config.entity_selector- if config.supports_time_filter or config.default_from:- probe_params["from"] = "now-1h"-+ config = _scope_probe_config(endpoint)try:response = session.get(- _build_url(base_url, config.path, probe_params),+ _build_url(base_url, config.path, _probe_params(config)),timeout=10,)except requests.exceptions.RequestException:@@ -328,8 +410,12 @@ def dynatrace_source(resumable_source_manager: ResumableSourceManager[DynatraceResumeConfig],should_use_incremental_field: bool = False,db_incremental_field_last_value: Optional[Any] = None,+ metric_selector: Optional[str] = None,) -> SourceResponse:config = DYNATRACE_ENDPOINTS[endpoint]+ if config.requires_metric_selector and not (metric_selector or "").strip():+ raise ValueError(METRIC_SELECTOR_REQUIRED_ERROR)+ row_mapper = ROW_MAPPERS.get(endpoint)def items() -> Iterator[list[dict[str, Any]]]:# Re-check at run time (not just at source-create) in case the environment URL was edited or@@ -374,7 +460,7 @@ def dynatrace_source("name": endpoint,"endpoint": {"path": config.path,- "params": _build_request_params(config),+ "params": _build_request_params(config, metric_selector),# Missing key / non-list body yields 0 rows (matches the previous behavior),# so no data_selector_required here."data_selector": config.data_key,@@ -391,12 +477,16 @@ def dynatrace_source(resume_hook=save_checkpoint,initial_paginator_state=initial_paginator_state,)- yield from resource+ if row_mapper is None:+ yield from resource+ else:+ for page in resource:+ yield row_mapper(page)return SourceResponse(name=endpoint,items=items,- primary_keys=[config.primary_key],+ primary_keys=config.primary_keys,# Dynatrace documents no reliable ascending sort we can verify for the time-filtered# endpoints (audit logs default to newest-first), so incremental endpoints run in desc# mode: the watermark is the max seen across the run, persisted only at successful jobdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dynatrace/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dynatrace/settings.pyindex 69e233b11130..fd2a550eea6e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/dynatrace/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dynatrace/settings.py@@ -1,6 +1,9 @@-from dataclasses import dataclass, field+from dataclasses import field+from datetime import timedeltafrom typing import Optional+from posthog.dataclasses import frozen+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType# Dynatrace timestamps (startTime, endTime, timestamp, firstSeenTms, ...) are integers in UTC@@ -8,14 +11,18 @@ from products.warehouse_sources.backend.types import IncrementalField, Increment# integer isn't a safe partition key for `partition_mode="datetime"`.-@dataclass+@frozenclass DynatraceEndpointConfig:name: strpath: str# Key in the response body holding the list of records (e.g. "problems", "events").data_key: str- primary_key: str = "id"- page_size: int = 100+ # Row fields that identify a record. A tuple is needed where no single field is unique, as on+ # metric data points (one row per metric, dimension tuple and timestamp).+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ # None where the endpoint takes no page-size param (the metrics query and both synthetic+ # endpoints return their whole result in one response).+ page_size: Optional[int] = 100# Server-side timeframe filter: the endpoint accepts `from`/`to` params. Only endpoints where# the docs guarantee a genuine server-side time filter are marked incremental via this.supports_time_filter: bool = False@@ -25,8 +32,20 @@ class DynatraceEndpointConfig:# since Dynatrace defaults to very narrow windows (problems/events: now-2h) when `from` is# omitted. Dynatrace relative format: now-NU with units m, h, d, w, M, y.default_from: Optional[str] = None+ # Query param carrying the start of the window. The synthetic executions endpoint names its+ # timeframe params after the timestamp they filter on rather than plain `from`/`to`.+ time_filter_param: str = "from"+ # Longest window the endpoint serves. Watermarks older than this are clamped, so an+ # incremental run never asks for a timeframe Dynatrace refuses.+ max_lookback: Optional[timedelta] = None# Required `entitySelector` for the entities endpoint (must specify a type on the first page).entity_selector: Optional[str] = None+ # Endpoint whose path stands in for this one when probing token scope. The metrics query needs+ # a metric selector a probe has no way to guess, so it borrows the descriptor endpoint's probe+ # — both sit behind `metrics.read`.+ scope_probe_endpoint: Optional[str] = None+ # Endpoint syncs nothing until the user names the metrics they want.+ requires_metric_selector: bool = False# Extra query params sent on the first page only — follow-up pages must carry nothing but# `nextPageKey` (the key encodes the original query).extra_params: dict[str, str] = field(default_factory=dict)@@ -56,7 +75,7 @@ def _entity_endpoint(name: str, entity_type: str) -> DynatraceEndpointConfig:name=name,path="/api/v2/entities",data_key="entities",- primary_key="entityId",+ primary_keys=["entityId"],page_size=100,entity_selector=f'type("{entity_type}")',default_from="now-30d",@@ -64,19 +83,20 @@ def _entity_endpoint(name: str, entity_type: str) -> DynatraceEndpointConfig:)-# Endpoint catalog for the Dynatrace Environment API v2. Coverage follows the streams an+# Endpoint catalog for the Dynatrace Environment API. Coverage follows the streams an# SRE/observability team wants in a warehouse: problem history, events, audit trail,-# vulnerabilities, entity inventory, metric catalog, and SLO status.+# vulnerabilities, entity inventory, metric catalog and values, SLO status, and synthetic+# availability.#-# Incremental vs full refresh: only problems, events, and audit logs expose a documented-# server-side `from`/`to` timeframe filter, so only those are marked incremental. The rest are-# full refresh and dedupe on their primary key.+# Incremental vs full refresh: problems, events, audit logs, metric data points and synthetic+# executions expose a documented server-side timeframe filter, so only those are marked+# incremental. The rest are full refresh and dedupe on their primary key.DYNATRACE_ENDPOINTS: dict[str, DynatraceEndpointConfig] = {"problems": DynatraceEndpointConfig(name="problems",path="/api/v2/problems",data_key="problems",- primary_key="problemId",+ primary_keys=["problemId"],page_size=500,supports_time_filter=True,incremental_field="startTime",@@ -87,7 +107,7 @@ DYNATRACE_ENDPOINTS: dict[str, DynatraceEndpointConfig] = {name="events",path="/api/v2/events",data_key="events",- primary_key="eventId",+ primary_keys=["eventId"],page_size=1000,supports_time_filter=True,incremental_field="startTime",@@ -97,7 +117,7 @@ DYNATRACE_ENDPOINTS: dict[str, DynatraceEndpointConfig] = {name="audit_logs",path="/api/v2/auditlogs",data_key="auditLogs",- primary_key="logId",+ primary_keys=["logId"],page_size=1000,supports_time_filter=True,incremental_field="timestamp",@@ -107,30 +127,75 @@ DYNATRACE_ENDPOINTS: dict[str, DynatraceEndpointConfig] = {name="security_problems",path="/api/v2/securityProblems",data_key="securityProblems",- primary_key="securityProblemId",+ primary_keys=["securityProblemId"],page_size=100,),"hosts": _entity_endpoint("hosts", "HOST"),"services": _entity_endpoint("services", "SERVICE"),"applications": _entity_endpoint("applications", "APPLICATION"),"process_groups": _entity_endpoint("process_groups", "PROCESS_GROUP"),+ "databases": _entity_endpoint("databases", "RELATIONAL_DATABASE_SERVICE"),+ "disks": _entity_endpoint("disks", "DISK"),+ "queues": _entity_endpoint("queues", "QUEUE"),+ "kubernetes_clusters": _entity_endpoint("kubernetes_clusters", "KUBERNETES_CLUSTER"),+ "kubernetes_nodes": _entity_endpoint("kubernetes_nodes", "KUBERNETES_NODE"),+ "cloud_applications": _entity_endpoint("cloud_applications", "CLOUD_APPLICATION"),+ "custom_devices": _entity_endpoint("custom_devices", "CUSTOM_DEVICE"),"metrics": DynatraceEndpointConfig(name="metrics",path="/api/v2/metrics",data_key="metrics",- primary_key="metricId",+ primary_keys=["metricId"],page_size=500,extra_params={"fields": "+created,+lastWritten,+entityType,+aggregationTypes,+tags"},),+ "metric_data_points": DynatraceEndpointConfig(+ name="metric_data_points",+ path="/api/v2/metrics/query",+ data_key="result",+ primary_keys=["metricId", "dimensionKey", "timestamp"],+ # The query endpoint takes no pageSize, and its nextPageKey is documented as always null:+ # one request returns the whole timeframe.+ page_size=None,+ supports_time_filter=True,+ incremental_field="timestamp",+ default_from="now-30d",+ requires_metric_selector=True,+ scope_probe_endpoint="metrics",+ # Without a resolution Dynatrace spreads a fixed 120 data points over whatever timeframe+ # was asked for, so the grain would shift between the first sync and later ones.+ extra_params={"resolution": "1h"},+ ),"slos": DynatraceEndpointConfig(name="slos",path="/api/v2/slo",data_key="slo",- primary_key="id",+ primary_keys=["id"],# With `evaluate=true` (needed for status / error budget) the endpoint caps pageSize at 25.page_size=25,extra_params={"evaluate": "true"},),+ "synthetic_monitors": DynatraceEndpointConfig(+ name="synthetic_monitors",+ # The v2 monitor listing needs the broad `settings.read` scope and currently covers only+ # browser and multi-protocol monitors, so the source reads the v1 listing instead.+ path="/api/v1/synthetic/monitors",+ data_key="monitors",+ primary_keys=["entityId"],+ page_size=None,+ ),+ "synthetic_executions": DynatraceEndpointConfig(+ name="synthetic_executions",+ path="/api/v2/synthetic/executions",+ data_key="executions",+ primary_keys=["executionId"],+ page_size=None,+ supports_time_filter=True,+ incremental_field="executionTimestamp",+ time_filter_param="executionFrom",+ default_from="now-6h",+ max_lookback=timedelta(hours=6),+ ),}ENDPOINTS = tuple(DYNATRACE_ENDPOINTS.keys())@@ -150,6 +215,16 @@ ENDPOINT_SCOPES: dict[str, str] = {"services": "entities.read","applications": "entities.read","process_groups": "entities.read",+ "databases": "entities.read",+ "disks": "entities.read",+ "queues": "entities.read",+ "kubernetes_clusters": "entities.read",+ "kubernetes_nodes": "entities.read",+ "cloud_applications": "entities.read",+ "custom_devices": "entities.read","metrics": "metrics.read",+ "metric_data_points": "metrics.read","slos": "slo.read",+ "synthetic_monitors": "ReadSyntheticData",+ "synthetic_executions": "syntheticExecutions.read",}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dynatrace/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dynatrace/source.pyindex 38cf972b2d65..585086737159 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/dynatrace/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dynatrace/source.py@@ -39,7 +39,17 @@ _SCHEMA_DESCRIPTIONS: dict[str, str] = {"services": "Services active in the last 30 days","applications": "Applications active in the last 30 days","process_groups": "Process groups active in the last 30 days",+ "databases": "Relational database services (for example Amazon RDS) active in the last 30 days",+ "disks": "Disks active in the last 30 days",+ "queues": "Messaging queues active in the last 30 days",+ "kubernetes_clusters": "Kubernetes clusters active in the last 30 days",+ "kubernetes_nodes": "Kubernetes nodes active in the last 30 days",+ "cloud_applications": "Kubernetes workloads active in the last 30 days",+ "custom_devices": "Custom devices active in the last 30 days",+ "metric_data_points": "One row per metric, dimension and hour, for the metric keys you entered. Only syncs the last 30 days on initial sync","slos": "Includes the current evaluation (status, error budget) of each SLO",+ "synthetic_monitors": "Name, type and enabled state of each synthetic monitor",+ "synthetic_executions": "On-demand executions only. Dynatrace serves the last 6 hours, so sync often to build up history",}@@ -65,7 +75,7 @@ class DynatraceSource(ResumableSource[DynatraceSourceConfig, DynatraceResumeConflabel="Dynatrace",releaseStatus=ReleaseStatus.ALPHA,keywords=["apm", "observability", "monitoring"],- caption="""Enter your Dynatrace environment URL and an API access token to sync problems, events, entity inventory, audit logs, vulnerabilities, metric metadata, and SLOs into the PostHog Data warehouse.+ caption="""Enter your Dynatrace environment URL and an API access token to sync problems, events, entity inventory, audit logs, vulnerabilities, metrics, SLOs, and synthetic monitoring into the PostHog Data warehouse.The environment URL is where you open Dynatrace — for SaaS it looks like `https://abc12345.live.dynatrace.com`; for Managed it's `https://your-domain/e/your-environment-id`.@@ -77,6 +87,8 @@ Create an [access token](https://docs.dynatrace.com/docs/manage/identity-access-- `securityProblems.read`- `metrics.read`- `slo.read`+- `ReadSyntheticData`+- `syntheticExecutions.read`""",iconPath="/static/services/dynatrace.png",docsUrl="https://posthog.com/docs/cdp/sources/dynatrace",@@ -99,6 +111,15 @@ Create an [access token](https://docs.dynatrace.com/docs/manage/identity-access-placeholder="dt0c01.…",secret=True,),+ SourceFieldInputConfig(+ name="metric_selector",+ label="Metric keys",+ caption="Up to 10 comma-separated [metric keys](https://docs.dynatrace.com/docs/dynatrace-api/environment-api/metric-v2/metric-selector) to sync hourly values for. Leave empty to sync only the metric catalog.",+ type=SourceFieldInputConfigType.TEXT,+ required=False,+ placeholder="builtin:host.cpu.usage,builtin:service.response.time",+ secret=False,+ ),],),)@@ -154,7 +175,9 @@ Create an [access token](https://docs.dynatrace.com/docs/manage/identity-access-) -> dict[str, str | None]:# Dynatrace scopes are granted per API area, so per-table access varies with the token.# Probe each scope so the schema picker can flag tables the token can't read.- return check_endpoint_permissions(config.environment_url, config.api_token, endpoints, team_id)+ return check_endpoint_permissions(+ config.environment_url, config.api_token, endpoints, team_id, metric_selector=config.metric_selector+ )def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[DynatraceResumeConfig]:return ResumableSourceManager[DynatraceResumeConfig](inputs, DynatraceResumeConfig)@@ -176,4 +199,5 @@ Create an [access token](https://docs.dynatrace.com/docs/manage/identity-access-db_incremental_field_last_value=inputs.db_incremental_field_last_valueif inputs.should_use_incremental_fieldelse None,+ metric_selector=config.metric_selector,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dynatrace/tests/test_dynatrace.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dynatrace/tests/test_dynatrace.pyindex 1b3ce427a07b..63d9c547d7dd 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/dynatrace/tests/test_dynatrace.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dynatrace/tests/test_dynatrace.py@@ -1,5 +1,5 @@import json-from datetime import UTC, datetime+from datetime import UTC, datetime, timedeltafrom typing import Anyfrom urllib.parse import parse_qs, urlparse@@ -11,9 +11,12 @@ from requests import Responsefrom products.warehouse_sources.backend.temporal.data_imports.sources.dynatrace import dynatrace as dtfrom products.warehouse_sources.backend.temporal.data_imports.sources.dynatrace.dynatrace import (+ METRIC_SELECTOR_REQUIRED_ERROR,DynatraceHostNotAllowedError,DynatraceResumeConfig,_build_url,+ _clamped_from_value,+ _flatten_metric_data_points,_format_from_value,_validated_hostname,check_endpoint_permissions,@@ -88,6 +91,22 @@ class TestFormatFromValue:assert _format_from_value(value) == expected+class TestClampedFromValue:+ def test_watermark_older_than_the_window_is_pulled_forward(self) -> None:+ # Synthetic executions are served for six hours only, so an older watermark would ask+ # for a timeframe Dynatrace refuses.+ clamped = int(_clamped_from_value(1735689600000, timedelta(hours=6)))+ earliest_ms = int((datetime.now(UTC) - timedelta(hours=6)).timestamp() * 1000)+ assert clamped == pytest.approx(earliest_ms, abs=5000)++ def test_watermark_inside_the_window_is_kept(self) -> None:+ recent_ms = int((datetime.now(UTC) - timedelta(hours=1)).timestamp() * 1000)+ assert _clamped_from_value(recent_ms, timedelta(hours=6)) == str(recent_ms)++ def test_relative_seed_passes_through(self) -> None:+ assert _clamped_from_value("now-6h", timedelta(hours=6)) == "now-6h"++def _response(body: dict[str, Any], *, status: int = 200, location: str | None = None) -> Response:resp = Response()resp.status_code = status@@ -137,6 +156,7 @@ def _source(*,should_use_incremental_field: bool = False,db_incremental_field_last_value: Any = None,+ metric_selector: str | None = "builtin:host.cpu.usage",) -> Any:return dynatrace_source(environment_url=BASE_URL,@@ -147,6 +167,7 @@ def _source(resumable_source_manager=manager,should_use_incremental_field=should_use_incremental_field,db_incremental_field_last_value=db_incremental_field_last_value,+ metric_selector=metric_selector,)@@ -196,6 +217,48 @@ class TestFirstPageParams:)assert "from" not in params[0]+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_metric_data_points_sends_selector_and_resolution_but_no_page_size(+ self, MockSession: mock.MagicMock+ ) -> None:+ session = MockSession.return_value+ params = _wire(session, [_response({"result": [], "nextPageKey": None})])+ manager, _ = _make_manager()+ _rows(_source("metric_data_points", manager, metric_selector=" builtin:host.cpu.usage "))+ assert params[0]["metricSelector"] == "builtin:host.cpu.usage"+ assert params[0]["resolution"] == "1h"+ # The metrics query endpoint has no pageSize param.+ assert "pageSize" not in params[0]++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_synthetic_executions_window_uses_its_own_param_name(self, MockSession: mock.MagicMock) -> None:+ session = MockSession.return_value+ params = _wire(session, [_response({"executions": [], "nextPageKey": None})])+ manager, _ = _make_manager()+ _rows(_source("synthetic_executions", manager))+ assert params[0]["executionFrom"] == "now-6h"+ assert "from" not in params[0]++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_synthetic_executions_watermark_is_clamped_to_the_served_window(self, MockSession: mock.MagicMock) -> None:+ session = MockSession.return_value+ params = _wire(session, [_response({"executions": [], "nextPageKey": None})])+ manager, _ = _make_manager()+ _rows(+ _source(+ "synthetic_executions",+ manager,+ should_use_incremental_field=True,+ db_incremental_field_last_value=1735689600000,+ )+ )+ earliest_ms = int((datetime.now(UTC) - timedelta(hours=6)).timestamp() * 1000)+ assert int(params[0]["executionFrom"]) == pytest.approx(earliest_ms, abs=5000)++ def test_metric_data_points_without_a_selector_is_refused(self) -> None:+ with pytest.raises(ValueError, match="Metric keys"):+ _source("metric_data_points", mock.MagicMock(), metric_selector=" ")+@mock.patch(CLIENT_SESSION_PATCH)def test_slos_request_evaluation(self, MockSession: mock.MagicMock) -> None:session = MockSession.return_value@@ -284,24 +347,115 @@ class TestPagination:class TestDynatraceSourceResponse:@pytest.mark.parametrize(- ("endpoint", "expected_pk", "expected_sort_mode"),+ ("endpoint", "expected_pks", "expected_sort_mode"),[- ("problems", "problemId", "desc"),- ("events", "eventId", "desc"),- ("audit_logs", "logId", "desc"),- ("security_problems", "securityProblemId", "asc"),- ("hosts", "entityId", "asc"),- ("metrics", "metricId", "asc"),- ("slos", "id", "asc"),+ ("problems", ["problemId"], "desc"),+ ("events", ["eventId"], "desc"),+ ("audit_logs", ["logId"], "desc"),+ ("security_problems", ["securityProblemId"], "asc"),+ ("hosts", ["entityId"], "asc"),+ ("kubernetes_clusters", ["entityId"], "asc"),+ ("metrics", ["metricId"], "asc"),+ # A data point is only unique on the metric, its dimension tuple and the timestamp.+ ("metric_data_points", ["metricId", "dimensionKey", "timestamp"], "desc"),+ ("slos", ["id"], "asc"),+ ("synthetic_monitors", ["entityId"], "asc"),+ ("synthetic_executions", ["executionId"], "desc"),],)- def test_source_response_shape(self, endpoint: str, expected_pk: str, expected_sort_mode: str) -> None:+ def test_source_response_shape(self, endpoint: str, expected_pks: list[str], expected_sort_mode: str) -> None:response = _source(endpoint, mock.MagicMock())assert response.name == endpoint- assert response.primary_keys == [expected_pk]+ assert response.primary_keys == expected_pksassert response.sort_mode == expected_sort_mode+class TestFlattenMetricDataPoints:+ def test_series_become_one_row_per_data_point(self) -> None:+ rows = _flatten_metric_data_points(+ [+ {+ "metricId": "builtin:host.disk.avail",+ "data": [+ {+ "dimensionMap": {"dt.entity.host": "HOST-1", "dt.entity.disk": "DISK-1"},+ "dimensions": ["HOST-1", "DISK-1"],+ "timestamps": [1735689600000, 1735693200000],+ "values": [11.1, 22.2],+ }+ ],+ }+ ]+ )++ assert rows == [+ {+ "metricId": "builtin:host.disk.avail",+ "dimensionKey": "dt.entity.disk=DISK-1|dt.entity.host=HOST-1",+ "dimensionMap": {"dt.entity.host": "HOST-1", "dt.entity.disk": "DISK-1"},+ "dimensions": ["HOST-1", "DISK-1"],+ "timestamp": 1735689600000,+ "value": 11.1,+ },+ {+ "metricId": "builtin:host.disk.avail",+ "dimensionKey": "dt.entity.disk=DISK-1|dt.entity.host=HOST-1",+ "dimensionMap": {"dt.entity.host": "HOST-1", "dt.entity.disk": "DISK-1"},+ "dimensions": ["HOST-1", "DISK-1"],+ "timestamp": 1735693200000,+ "value": 22.2,+ },+ ]++ def test_dimension_key_falls_back_to_the_ordered_dimensions(self) -> None:+ # Older responses carry only the deprecated `dimensions` list, and the key still has to+ # separate the series.+ rows = _flatten_metric_data_points(+ [+ {+ "metricId": "builtin:host.cpu.usage",+ "data": [{"dimensions": ["HOST-1"], "timestamps": [1], "values": [1.0]}],+ }+ ]+ )+ assert [row["dimensionKey"] for row in rows] == ["HOST-1"]++ def test_series_without_data_points_yields_no_rows(self) -> None:+ # Dynatrace returns an empty `data` list, and a warning, for a metric it could not read.+ assert _flatten_metric_data_points([{"metricId": "builtin:host.cpu.usage", "data": []}]) == []++ @mock.patch(CLIENT_SESSION_PATCH)+ def test_the_metrics_query_response_is_flattened_end_to_end(self, MockSession: mock.MagicMock) -> None:+ session = MockSession.return_value+ _wire(+ session,+ [+ _response(+ {+ "result": [+ {+ "metricId": "builtin:host.cpu.usage",+ "data": [+ {+ "dimensionMap": {"dt.entity.host": "HOST-1"},+ "timestamps": [1735689600000],+ "values": [42.0],+ }+ ],+ }+ ],+ "nextPageKey": None,+ }+ )+ ],+ )+ manager, _ = _make_manager()+ rows = _rows(_source("metric_data_points", manager))+ assert [(row["metricId"], row["timestamp"], row["value"]) for row in rows] == [+ ("builtin:host.cpu.usage", 1735689600000, 42.0)+ ]++class TestValidateCredentials:def _validate(self, status_code: int, schema_name: str | None = None) -> tuple[bool, str | None]:response = mock.MagicMock()@@ -369,6 +523,44 @@ class TestCheckEndpointPermissions:# The four entity tables share the entities.read scope, so one probe covers them all.assert call_count == 2+ def test_metric_data_points_scope_is_probed_on_the_descriptor_endpoint(self) -> None:+ # The query endpoint rejects a request with no metric selector, so probing it could never+ # tell a missing scope apart from a malformed probe.+ probed: list[str] = []++ def fake_get(url: str, timeout: Any = None) -> Any:+ probed.append(url)+ response = mock.MagicMock()+ response.status_code = 403+ return response++ with (+ mock.patch.object(dt, "make_tracked_session") as mock_session,+ mock.patch.object(dt, "_is_host_safe", return_value=(True, None)),+ ):+ mock_session.return_value.get.side_effect = fake_get+ results = check_endpoint_permissions(+ BASE_URL, "token", ["metric_data_points"], team_id=1, metric_selector="builtin:host.cpu.usage"+ )++ assert probed == [f"{BASE_URL}/api/v2/metrics?pageSize=1"]+ reason = results["metric_data_points"]+ assert reason is not None+ assert "metrics.read" in reason++ def test_metric_data_points_reports_the_missing_metric_keys_instead_of_probing(self) -> None:+ # Nothing about the token stops this table syncing — the user has not said which metrics+ # to read — so the picker must say that rather than run a probe that cannot answer it.+ with (+ mock.patch.object(dt, "make_tracked_session") as mock_session,+ mock.patch.object(dt, "_is_host_safe", return_value=(True, None)),+ ):+ results = check_endpoint_permissions(BASE_URL, "token", ["metric_data_points"], team_id=1)+ call_count = mock_session.return_value.get.call_count++ assert results["metric_data_points"] == METRIC_SELECTOR_REQUIRED_ERROR+ assert call_count == 0+def test_network_blip_is_not_reported_as_missing_permission(self) -> None:with (mock.patch.object(dt, "make_tracked_session") as mock_session,diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/dynatrace/tests/test_dynatrace_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/dynatrace/tests/test_dynatrace_source.pyindex 4d73c31c218b..85e2e8a8937e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/dynatrace/tests/test_dynatrace_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/dynatrace/tests/test_dynatrace_source.py@@ -4,7 +4,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_DynatraceSourceConfig,)-INCREMENTAL_ENDPOINTS = {"problems", "events", "audit_logs"}+INCREMENTAL_ENDPOINTS = {"problems", "events", "audit_logs", "metric_data_points", "synthetic_executions"}class TestDynatraceSource:diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/dynatrace.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/dynatrace.pyindex 5bac82ef82f0..e7344563ba69 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/dynatrace.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/dynatrace.py@@ -8,3 +8,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common impclass DynatraceSourceConfig(config.Config):environment_url: strapi_token: str+ metric_selector: str | None = None