: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(data-warehouse): add 2 missing tables to the Dynatrace source (#117304)
Tom Owers897c8ba28cd6
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 c15d9876efaf..82473ede7cc1 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@@ -4048,7 +4048,7 @@ Note: Parsed the official method index and fetched the selected reference pages## Dynatrace — gaps-Today (23): `applications`, `audit_logs`, `cloud_applications`, `custom_devices`, `databases`, `disks`, `entity_tags`, `entity_types`, `events`, `hosts`, `kubernetes_clusters`, `kubernetes_nodes`, `metric_data_points`, `metrics`, `problems`, `process_groups`, `queues`, `releases`, `security_problems`, `services`, `slos`, `synthetic_executions`, `synthetic_monitors`+Today (25): `applications`, `attacks`, `audit_logs`, `cloud_applications`, `custom_devices`, `databases`, `disks`, `entity_tags`, `entity_types`, `events`, `hosts`, `kubernetes_clusters`, `kubernetes_nodes`, `metric_data_points`, `metrics`, `problems`, `process_groups`, `queues`, `releases`, `security_problem_remediation_items`, `security_problems`, `services`, `slos`, `synthetic_executions`, `synthetic_monitors`Diffed against: <https://docs.dynatrace.com/docs/dynatrace-api/environment-api/metric-v2/get-data-points>@@ -4060,13 +4060,15 @@ Diffed against: <https://docs.dynatrace.com/docs/dynatrace-api/environment-api/m- [ ] `GET /api/v1/userSessionQueryLanguage/table` — RUM user sessions - session-level real-user data, currently only aggregate application entities are synced (medium)- [x] `GET /api/v2/tags` — entity tag lookup; management-zone and tag dimensions are how Dynatrace users slice everything (medium)- [x] `GET /api/v2/releases` — release inventory joining deployed versions to entities, for change-vs-problem correlation (medium)-- [ ] `GET /api/v2/attacks` — application-security attack events, the transactional counterpart to the security_problems already synced (medium)-- [ ] `GET /api/v2/securityProblems/{id}/remediationItems` — per-vulnerability remediation items and their tracking state (medium)+- [x] `GET /api/v2/attacks` — application-security attack events, the transactional counterpart to the security_problems already synced (medium)+- [x] `GET /api/v2/securityProblems/{id}/remediationItems` — per-vulnerability remediation items and their tracking state (medium)- [ ] `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)`/api/v1/userSessionQueryLanguage/table` stays unticked: it runs a USQL query supplied by the caller and answers with `columnNames` plus positional `values` rows, so the table's schema is whatever the query asked for rather than anything the source can declare. Dynatrace also computes the result from a sample of the data when it needs to (`extrapolationLevel`), and paginates it by `pageOffset` over a live result set, so the rows are neither complete nor stable between pages. It needs a different token scope (`DTAQLAccess`) from every other endpoint here. A user who wants this should point the custom REST source at it with their own query.+`/api/v2/logs/search` stays unticked: Dynatrace has deprecated it, with removal by the end of 2027. It returns only the first `limit` records (at most 1000) that match the query, not a listing a sync can page through to the end. A log record carries no identifier to merge on. On environments with Log Management and Analytics powered by Grail, Dynatrace documents an OAuth bearer token for it, not the API token this source takes. Its replacement, the Logs on Grail API, also needs an OAuth or platform token.+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. `/api/v2/tags` requires an `entitySelector` naming a single entity type and returns no entity reference, so the `entity_tags` table reads it once per type the entity tables cover and keys each row on that type. `/api/v2/releases` needs its own `releases.read` scope, and a release row carries no timestamp, so the table is full refresh over a 30-day window rather than incremental.## 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 459bb8b31a74..6cb662a7560c 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@@ -91,6 +91,45 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"lastUpdatedTimestamp": "Timestamp of the most recent update, in UTC milliseconds.",},},+ "security_problem_remediation_items": {+ "description": "Remediation items of third-party and Kubernetes vulnerabilities: the process groups or Kubernetes nodes that must be fixed, and their tracking state.",+ "docs_url": "https://docs.dynatrace.com/docs/dynatrace-api/environment-api/application-security/vulnerabilities/get-remediation-items",+ "columns": {+ "securityProblemId": "Identifier of the security problem the remediation item belongs to.",+ "id": "Identifier of the remediation item, the entity ID of the affected process group or Kubernetes node.",+ "name": "Name of the affected process group or Kubernetes node.",+ "entityIds": "Entity IDs the remediation item covers.",+ "vulnerabilityState": "Whether the entity is still affected: VULNERABLE or RESOLVED.",+ "firstAffectedTimestamp": "Timestamp when the entity was first affected, in UTC milliseconds.",+ "resolvedTimestamp": "Timestamp when the vulnerability was resolved for the entity, in UTC milliseconds.",+ "muteState": "Mute state of the remediation item, with the reason, user and time of the last change.",+ "assessment": "Davis assessment of the item: network exposure, reachable data assets and vulnerable function usage.",+ "remediationProgress": "Related entities that are and are not affected by the security problem.",+ "trackingLink": "External tracking link (for example an issue URL) set for the remediation item.",+ "vulnerableComponents": "Vulnerable components (for example libraries) that cause the security problem.",+ },+ },+ "attacks": {+ "description": "Attacks on your applications detected by Dynatrace Application Protection, one row per attack.",+ "docs_url": "https://docs.dynatrace.com/docs/dynatrace-api/environment-api/application-security/attacks/get-attacks",+ "columns": {+ "attackId": "Unique identifier of the attack.",+ "displayId": "Human-friendly identifier of the attack.",+ "displayName": "Display name of the attack.",+ "attackType": "Type of the attack: COMMAND_INJECTION, JNDI_INJECTION, SQL_INJECTION or SSRF.",+ "state": "State of the attack: EXPLOITED, BLOCKED or ALLOWLISTED.",+ "technology": "Technology of the attacked application (e.g. JAVA, DOTNET).",+ "timestamp": "Timestamp when the attack occurred, in UTC milliseconds.",+ "attacker": "Source IP and location of the attacker.",+ "attackTarget": "Host or database the attack targeted.",+ "request": "The request the attacker sent.",+ "entrypoint": "Entry point and payload the attacker used to start the attack.",+ "vulnerability": "The vulnerability the attack exploited.",+ "securityProblem": "The related security problem and its assessment.",+ "affectedEntities": "Process group and process group instance the attack affected.",+ "managementZones": "Management zones of the affected entities.",+ },+ },"hosts": {"description": "Monitored host entities and their metadata.","docs_url": "https://docs.dynatrace.com/docs/dynatrace-api/environment-api/entity-v2",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 594e37d13572..7884db7a25d0 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@@ -3,7 +3,7 @@ import dataclassesfrom collections.abc import Callable, Iteratorfrom datetime import UTC, date, datetime, timedeltafrom typing import Any, Optional-from urllib.parse import urlencode, urlparse+from urllib.parse import quote, urlencode, urlparseimport requestsfrom requests import Request, Response@@ -17,6 +17,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.resrest_api_resource,)from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import BasePaginator+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import ResponseActionfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse@@ -413,6 +414,8 @@ def _endpoint_pages(db_incremental_field_last_value: Optional[Any],resume_hook: Optional[Callable[[Optional[dict[str, Any]]], None]] = None,initial_paginator_state: Optional[dict[str, Any]] = None,+ path: Optional[str] = None,+ response_actions: Optional[list[ResponseAction]] = None,) -> Iterator[list[dict[str, Any]]]:"""Pages of one Dynatrace list endpoint, built on the shared REST framework.@@ -442,11 +445,12 @@ def _endpoint_pages({"name": endpoint,"endpoint": {- "path": config.path,+ "path": path or config.path,"params": params,# Missing key / non-list body yields 0 rows (matches the previous behavior),# so no data_selector_required here."data_selector": config.data_key,+ "response_actions": response_actions or [],},}],@@ -462,6 +466,52 @@ def _endpoint_pages()+def _parent_fan_out(+ base_url: str,+ api_token: str,+ endpoint: str,+ config: DynatraceEndpointConfig,+ parent_endpoint: str,+ parent_id_field: str,+ params: dict[str, Any],+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[DynatraceResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ """Read ``endpoint`` once per row of its parent listing, stamping each row with the parent id.++ No resume state is kept: a staged parent cursor would skip the children of the page it was+ read from. A safe point after each parent lets a worker shutdown hand the run over even when+ many parents have no children.+ """+ parent_config = DYNATRACE_ENDPOINTS[parent_endpoint]+ parent_params = {**_build_request_params(parent_config, None), **config.parent_params}+ parent_pages = _endpoint_pages(+ base_url, api_token, parent_config.name, parent_config, parent_params, team_id, job_id, None+ )+ for parent_page in parent_pages:+ for parent in parent_page:+ parent_id = parent.get(parent_id_field)+ if not parent_id:+ continue+ pages = _endpoint_pages(+ base_url,+ api_token,+ endpoint,+ config,+ params,+ team_id,+ job_id,+ None,+ path=config.path.replace("{id}", quote(str(parent_id), safe="")),+ # A security problem can be removed between the listing and this request.+ response_actions=[{"status_code": 404, "action": "ignore"}],+ )+ for page in pages:+ yield [{**row, parent_id_field: parent_id} for row in page]+ resumable_source_manager.safe_point()++def dynatrace_source(environment_url: str,api_token: str,@@ -506,6 +556,21 @@ def dynatrace_source(yield [{**row, "entityType": entity_type} for row in page]return+ if config.parent_endpoint and config.parent_id_field:+ yield from _parent_fan_out(+ base_url,+ api_token,+ endpoint,+ config,+ config.parent_endpoint,+ config.parent_id_field,+ params,+ team_id,+ job_id,+ resumable_source_manager,+ )+ return+initial_paginator_state: Optional[dict[str, Any]] = Noneif resumable_source_manager.can_resume():resume = resumable_source_manager.load_state()diff --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 6bda20db7c45..4fba7b27dc83 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@@ -45,6 +45,12 @@ class DynatraceEndpointConfig:# Endpoint has no listing of its own: Dynatrace requires an `entitySelector` naming a single# entity type, so it is read once per type the entity tables cover.fans_out_over_entity_types: bool = False+ # Endpoint has no listing of its own: it is read once per row of this parent endpoint, with the+ # `{id}` in `path` taking the row's `parent_id_field`, and each row is stamped with that id.+ parent_endpoint: Optional[str] = None+ parent_id_field: Optional[str] = None+ # First-page params added to the parent listing when it is walked for the fan-out.+ parent_params: dict[str, str] = field(default_factory=dict)# 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`.@@ -94,8 +100,8 @@ def _entity_endpoint(name: str, entity_type: str) -> DynatraceEndpointConfig:# vulnerabilities, entity inventory, metric catalog and values, SLO status, and synthetic# availability.#-# 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 vs full refresh: problems, events, audit logs, attacks, 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(@@ -136,6 +142,36 @@ DYNATRACE_ENDPOINTS: dict[str, DynatraceEndpointConfig] = {primary_keys=["securityProblemId"],page_size=100,),+ "security_problem_remediation_items": DynatraceEndpointConfig(+ name="security_problem_remediation_items",+ path="/api/v2/securityProblems/{id}/remediationItems",+ data_key="remediationItems",+ # An item's id names the affected process group or Kubernetes node, which several security+ # problems can share.+ primary_keys=["securityProblemId", "id"],+ # The endpoint takes no pageSize and returns every item of the problem in one response.+ page_size=None,+ parent_endpoint="security_problems",+ parent_id_field="securityProblemId",+ # Dynatrace tracks remediation for third-party and Kubernetes (runtime) vulnerabilities+ # only, so code-level problems have nothing to read.+ parent_params={"securityProblemSelector": 'vulnerabilityType("THIRD_PARTY","RUNTIME")'},+ scope_probe_endpoint="security_problems",+ ),+ "attacks": DynatraceEndpointConfig(+ name="attacks",+ path="/api/v2/attacks",+ data_key="attacks",+ primary_keys=["attackId"],+ page_size=500,+ supports_time_filter=True,+ incremental_field="timestamp",+ default_from="now-30d",+ extra_params={+ "fields": "+attackTarget,+request,+entrypoint,+vulnerability,+securityProblem,+attacker,"+ "+managementZones,+affectedEntities"+ },+ ),"releases": DynatraceEndpointConfig(name="releases",path="/api/v2/releases",@@ -257,6 +293,8 @@ ENDPOINT_SCOPES: dict[str, str] = {"events": "events.read","audit_logs": "auditLogs.read","security_problems": "securityProblems.read",+ "security_problem_remediation_items": "securityProblems.read",+ "attacks": "attacks.read","releases": "releases.read","entity_types": "entities.read","hosts": "entities.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 ead6b3213772..76aaa769ecc2 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@@ -36,6 +36,8 @@ _SCHEMA_DESCRIPTIONS: dict[str, str] = {"problems": "Only syncs the last 365 days on initial sync","events": "Only syncs the last 30 days on initial sync; limited by your Dynatrace event retention","audit_logs": "Only syncs the last 30 days on initial sync; requires audit logging to be enabled in the environment",+ "security_problem_remediation_items": "Process groups and Kubernetes nodes to fix for each third-party and Kubernetes vulnerability, with their tracking state",+ "attacks": "Only syncs the last 30 days on initial sync; requires Application Protection","releases": "Releases seen in the last 30 days, with the process group instances running them","entity_types": "Every monitored entity type, with the properties and relationships an entity of that type can have","hosts": "Hosts active in the last 30 days",@@ -89,7 +91,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, tags, releases, audit logs, vulnerabilities, metrics, SLOs, and synthetic monitoring into the PostHog Data warehouse.+ caption="""Enter your Dynatrace environment URL and an API access token to sync problems, events, entity inventory, tags, releases, audit logs, vulnerabilities, attacks, 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`.@@ -99,6 +101,7 @@ Create an [access token](https://docs.dynatrace.com/docs/manage/identity-access-- `entities.read`- `auditLogs.read`- `securityProblems.read`+- `attacks.read`- `releases.read`- `metrics.read`- `slo.read`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 b2c7d3b71bb7..8d936603ce73 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@@ -10,6 +10,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.tesScriptedResponse,SourceDriver,always,+ route,scripted_network,)from products.warehouse_sources.backend.temporal.data_imports.sources.dynatrace import dynatrace as dt@@ -130,6 +131,26 @@ class TestFirstPageParams:earliest_ms = int((datetime.now(UTC) - timedelta(hours=6)).timestamp() * 1000)assert int(result.requests[0].param("executionFrom") or "0") == pytest.approx(earliest_ms, abs=5000)+ @pytest.mark.parametrize(+ ("should_use_incremental_field", "expected_from"),+ [+ (False, "now-30d"),+ (True, "1735689600000"),+ ],+ )+ def test_attacks_window_starts_at_the_watermark_on_incremental_runs(+ self, should_use_incremental_field: bool, expected_from: str+ ) -> None:+ result = _driver().run(+ "attacks",+ [ScriptedResponse(json={"attacks": [], "nextPageKey": None})],+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=1735689600000 if should_use_incremental_field else None,+ )+ assert result.raised is None+ assert result.requests[0].param("from") == expected_from+ assert "+request" in (result.requests[0].param("fields") or "")+def test_metric_data_points_without_a_selector_is_refused(self) -> None:result = _driver(metric_selector=" ").run("metric_data_points", [])assert isinstance(result.raised, ValueError)@@ -197,6 +218,48 @@ class TestEntityTagFanOut:assert result.requests[2].param("nextPageKey") is None+class TestRemediationItemFanOut:+ def test_items_are_read_per_security_problem_and_stamped_with_its_id(self) -> None:+ problems = "/api/v2/securityProblems"+ script = route(+ {+ f"{problems}/S-1/remediationItems": [+ ScriptedResponse(json={"remediationItems": [{"id": "PROCESS_GROUP-1"}, {"id": "PROCESS_GROUP-2"}]})+ ],+ f"{problems}/S%2F2/remediationItems": [ScriptedResponse(status=404, json={"error": {"code": 404}})],+ f"{problems}/S-3/remediationItems": [+ ScriptedResponse(json={"remediationItems": [{"id": "PROCESS_GROUP-1"}]})+ ],+ problems: [+ ScriptedResponse(+ json={+ "securityProblems": [+ {"securityProblemId": "S-1"},+ {"displayId": "S-no-id"},+ {"securityProblemId": "S/2"},+ ],+ "nextPageKey": "key-2",+ }+ ),+ ScriptedResponse(json={"securityProblems": [{"securityProblemId": "S-3"}], "nextPageKey": None}),+ ],+ }+ )+ result = _driver().run("security_problem_remediation_items", script)++ assert result.raised is None+ assert [(row["securityProblemId"], row["id"]) for row in result.rows] == [+ ("S-1", "PROCESS_GROUP-1"),+ ("S-1", "PROCESS_GROUP-2"),+ ("S-3", "PROCESS_GROUP-1"),+ ]+ parent_requests = [request for request in result.requests if request.path == problems]+ assert parent_requests[0].param("securityProblemSelector") == 'vulnerabilityType("THIRD_PARTY","RUNTIME")'+ assert parent_requests[1].query == {"nextPageKey": ("key-2",)}+ # The parent walk keeps no cursor: a staged parent cursor would skip the children of its page.+ assert result.saved_states == []++class TestFlattenMetricDataPoints: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@@ -244,7 +307,12 @@ class TestValidateCredentials:def _validate(self, status_code: int, schema_name: str | None = None) -> tuple[bool, str | None]:with scripted_network([ScriptedResponse(status=status_code)]) as network:result = validate_credentials(BASE_URL, "token", team_id=None, schema_name=schema_name)- assert network.requests_log[0].path == ("/api/v2/entities" if schema_name == "hosts" else "/api/v2/problems")+ expected_paths = {+ "hosts": "/api/v2/entities",+ # The child path needs a security problem id, so the scope is probed on the parent listing.+ "security_problem_remediation_items": "/api/v2/securityProblems",+ }+ assert network.requests_log[0].path == expected_paths.get(schema_name or "", "/api/v2/problems")return result@pytest.mark.parametrize(@@ -257,6 +325,7 @@ class TestValidateCredentials:(403, None, True),(403, "problems", False),(200, "hosts", True),+ (200, "security_problem_remediation_items", True),(500, None, False),(400, None, False),(302, None, False),