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): add instana metrics, apdex, mobile app and synthetic location tables (#111889)

Tom Owersaa983e0f393a
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 cd642749c7de..023cdfae9af9 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
@@ -4339,13 +4339,13 @@ Diffed against: <https://instana.github.io/openapi/openapi.json>
- [x] `/api/releases (+ /api/releases/{releaseId})` — release markers used to correlate deploys with events and metric regressions; the standard overlay on every Instana chart (high). Added as `releases`. `/api/releases/{releaseId}` skipped: it returns the same object as the list row.
- [x] `/api/settings/slo and /api/slo/report/{sloId}` — SLO definitions plus attainment/error-budget reports - the headline reliability metric, entirely absent today (high). Added as `slo_configs` and `slo_reports` (fan-out over `slo_configs`).
- [x] `/api/synthetics/settings/tests/ci-cd and /api/synthetics/results/{testid}/{testresultid}` — actual synthetic test results; `synthetic\_tests` today is only the test configuration, so there is no pass/fail or latency data (high). Added as `synthetic_test_ci_cds` (on-demand and CI/CD runs with their completion state). `/api/synthetics/results/{testid}/{testresultid}` skipped: it returns only playback file names, not results. Pass/fail and latency live behind the POST `/api/synthetics/results/list` query API.
-- [ ] `/api/synthetics/settings/locations and /api/synthetics/settings/datacenters` — lookup resolving the location IDs on synthetic tests and results - required to break results down by PoP (high)
-- [ ] `POST /api/application-monitoring/metrics/{applications,services,endpoints}` — the golden-signal time series (calls, errors, latency percentiles) for the applications/services/endpoints already synced as catalogs only (high)
-- [ ] `/api/settings/apdex and /api/apdex/report/{apdexId}` — Apdex configs and scores, the per-service user-satisfaction metric (medium)
+- [x] `/api/synthetics/settings/locations and /api/synthetics/settings/datacenters` — lookup resolving the location IDs on synthetic tests and results - required to break results down by PoP (high). Added as `synthetic_locations` and `synthetic_datacenters`.
+- [x] `POST /api/application-monitoring/metrics/{applications,services,endpoints}` — the golden-signal time series (calls, errors, latency percentiles) for the applications/services/endpoints already synced as catalogs only (high). Added as `application_metrics`, `service_metrics` and `endpoint_metrics`: a daily rollup (calls, erroneous calls, error rate, mean/p50/p90/p99 latency), incremental on the bucket `timestamp`.
+- [x] `/api/settings/apdex and /api/apdex/report/{apdexId}` — Apdex configs and scores, the per-service user-satisfaction metric (medium). Added as `apdex_configs` and `apdex_reports` (fan-out over `apdex_configs`, trailing 7-day window).
- [ ] `/api/host-agent (+ /api/host-agent/{id})` — agent and host inventory with versions, for fleet coverage and upgrade tracking (medium)
- [ ] `/api/settings/users, /api/settings/rbac/teams, /api/settings/rbac/groups` — user and team membership tables for attributing alerts and ownership (medium)
- [ ] `/api/settings/auditlog and /api/settings/accesslog` — who changed which alert config or dashboard and when - the standard compliance table (medium)
-- [ ] `/api/mobile-app-monitoring/config` — mobile app inventory, the exact parallel of the `websites` table already synced from website-monitoring/config (medium)
+- [x] `/api/mobile-app-monitoring/config` — mobile app inventory, the exact parallel of the `websites` table already synced from website-monitoring/config (medium). Added as `mobile_apps`.
- [ ] `/api/business-monitoring/business-perspectives` — business perspective definitions that segment traces by business context, a key breakdown dimension (medium)
Note: Instana publishes a full OpenAPI 3 spec (1.9MB JSON / 1.5MB YAML, version 1.307.1417) at instana.github.io/openapi - very reliable to diff against. Two caveats for an implementer: (1) much of the analytical surface is POST-with-body (metrics, analyze/traces, analyze/beacons, analyze/entities) rather than GET, so those tables need request bodies rather than query params; (2) as the source's own settings.py notes, /api/events has no pagination and infrastructure snapshots use a `size` cap, so wide time windows must be chunked. Excluded as config: custom dashboards, API tokens, alert channel infos, maintenance windows, session settings, automation policies, sourcemap uploads, and the per-plugin catalog/tag metadata endpoints.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/instana/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/instana/canonical_descriptions.py
index 8ff3fa4f9966..d1b257bfcf83 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/instana/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/instana/canonical_descriptions.py
@@ -213,4 +213,116 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"mobileApps": "Mobile apps associated with the run.",
},
},
+ "synthetic_locations": {
+ "description": "Points of presence (PoPs) that run synthetic tests. Resolves the location IDs on synthetic tests and runs.",
+ "docs_url": "https://instana.github.io/openapi/#operation/getSyntheticLocations",
+ "columns": {
+ "id": "Unique identifier of the synthetic location.",
+ "label": "Name of the synthetic location.",
+ "displayLabel": "Display name of the synthetic location.",
+ "description": "Description of the synthetic location.",
+ "locationType": "Whether the location is managed by Instana or private.",
+ "status": "Current status of the location.",
+ "popVersion": "Version of the PoP software running at the location.",
+ "geoPoint": "Geographic coordinates of the location.",
+ "playbackCapabilities": "Synthetic test types and browsers the location can run.",
+ "totalTests": "Number of synthetic tests assigned to the location.",
+ "createdAt": "Timestamp when the location was created, in epoch milliseconds.",
+ "modifiedAt": "Timestamp when the location was last modified, in epoch milliseconds.",
+ "observedAt": "Timestamp when the location last reported, in epoch milliseconds.",
+ },
+ },
+ "synthetic_datacenters": {
+ "description": "Data centers that host Instana-managed synthetic locations.",
+ "docs_url": "https://instana.github.io/openapi/#operation/getSyntheticDatacenters",
+ "columns": {
+ "datacenterId": "Unique identifier of the data center.",
+ "label": "Name of the data center.",
+ "code": "Short code of the data center.",
+ "provider": "Cloud provider that hosts the data center.",
+ "cityName": "City where the data center is located.",
+ "countryName": "Country where the data center is located.",
+ "locationLabel": "Label of the synthetic location served by the data center.",
+ "latitude": "Latitude of the data center.",
+ "longitude": "Longitude of the data center.",
+ "status": "Current status of the data center.",
+ "modifiedAt": "Timestamp when the data center was last modified, in epoch milliseconds.",
+ },
+ },
+ "mobile_apps": {
+ "description": "Mobile apps configured in Instana's mobile app monitoring.",
+ "docs_url": "https://instana.github.io/openapi/#operation/getMobileAppConfig",
+ "columns": {
+ "id": "Unique identifier of the mobile app.",
+ "name": "Name of the mobile app.",
+ },
+ },
+ "application_metrics": {
+ "description": "Daily golden-signal metrics (calls, errors, latency) for each application perspective, one row per application perspective per day.",
+ "docs_url": "https://instana.github.io/openapi/#operation/getApplicationMetrics",
+ "columns": {
+ "applicationId": "Identifier of the application perspective the metrics belong to.",
+ "application": "The application perspective the metrics belong to, as returned by Instana.",
+ "timestamp": "Timestamp of the daily metric bucket, in epoch milliseconds.",
+ "calls_sum": "Number of calls received in the day.",
+ "erroneousCalls_sum": "Number of erroneous calls in the day.",
+ "errors_mean": "Error rate of calls in the day, between 0 and 1.",
+ "latency_mean": "Mean call latency in the day, in milliseconds.",
+ "latency_p50": "Median call latency in the day, in milliseconds.",
+ "latency_p90": "90th percentile call latency in the day, in milliseconds.",
+ "latency_p99": "99th percentile call latency in the day, in milliseconds.",
+ },
+ },
+ "service_metrics": {
+ "description": "Daily golden-signal metrics (calls, errors, latency) for each service, one row per service per day.",
+ "docs_url": "https://instana.github.io/openapi/#operation/getServicesMetrics",
+ "columns": {
+ "serviceId": "Identifier of the service the metrics belong to.",
+ "service": "The service the metrics belong to, as returned by Instana.",
+ "timestamp": "Timestamp of the daily metric bucket, in epoch milliseconds.",
+ "calls_sum": "Number of calls received in the day.",
+ "erroneousCalls_sum": "Number of erroneous calls in the day.",
+ "errors_mean": "Error rate of calls in the day, between 0 and 1.",
+ "latency_mean": "Mean call latency in the day, in milliseconds.",
+ "latency_p50": "Median call latency in the day, in milliseconds.",
+ "latency_p90": "90th percentile call latency in the day, in milliseconds.",
+ "latency_p99": "99th percentile call latency in the day, in milliseconds.",
+ },
+ },
+ "endpoint_metrics": {
+ "description": "Daily golden-signal metrics (calls, errors, latency) for each endpoint, one row per endpoint per day.",
+ "docs_url": "https://instana.github.io/openapi/#operation/getEndpointsMetrics",
+ "columns": {
+ "endpointId": "Identifier of the endpoint the metrics belong to.",
+ "endpoint": "The endpoint the metrics belong to, as returned by Instana.",
+ "timestamp": "Timestamp of the daily metric bucket, in epoch milliseconds.",
+ "calls_sum": "Number of calls received in the day.",
+ "erroneousCalls_sum": "Number of erroneous calls in the day.",
+ "errors_mean": "Error rate of calls in the day, between 0 and 1.",
+ "latency_mean": "Mean call latency in the day, in milliseconds.",
+ "latency_p50": "Median call latency in the day, in milliseconds.",
+ "latency_p90": "90th percentile call latency in the day, in milliseconds.",
+ "latency_p99": "99th percentile call latency in the day, in milliseconds.",
+ },
+ },
+ "apdex_configs": {
+ "description": "Apdex configurations that define the user-satisfaction threshold for an application, service, website or mobile app.",
+ "docs_url": "https://instana.github.io/openapi/#operation/getAllApdexConfigurations",
+ "columns": {
+ "id": "Unique identifier of the Apdex configuration.",
+ "apdexName": "Name of the Apdex configuration.",
+ "apdexEntity": "Entity the Apdex is measured on, with its type, threshold and tag filter.",
+ "createdAt": "Timestamp when the Apdex configuration was created, in epoch milliseconds.",
+ },
+ },
+ "apdex_reports": {
+ "description": "Apdex scores for each Apdex configuration over the trailing 7 days. Rebuilt on every sync.",
+ "docs_url": "https://instana.github.io/openapi/#operation/getApdexReport",
+ "columns": {
+ "apdexId": "Identifier of the Apdex configuration the report belongs to.",
+ "apdexScore": "Apdex scores over the report window, as [timestamp, score] pairs.",
+ "from": "Start of the report window, in epoch milliseconds.",
+ "to": "End of the report window, in epoch milliseconds.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/instana/instana.py b/products/warehouse_sources/backend/temporal/data_imports/sources/instana/instana.py
index 308c5dc76937..3e70325adcfd 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/instana/instana.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/instana/instana.py
@@ -16,11 +16,15 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.mix
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.instana.settings import (
+ APPLICATION_METRICS,
EVENTS_DEFAULT_LOOKBACK_DAYS,
EVENTS_WINDOW_CHUNK_MS,
INSTANA_ENDPOINTS,
MAX_CATALOG_PAGES,
MAX_CATALOG_WALK_SECONDS,
+ METRICS_DEFAULT_LOOKBACK_DAYS,
+ METRICS_MAX_LOOKBACK_DAYS,
+ METRICS_WINDOW_MS,
PAGE_SIZE,
SNAPSHOTS_MAX_SIZE,
InstanaEndpointConfig,
@@ -105,6 +109,8 @@ class InstanaResumeConfig:
next_offset: int | None = None
# Epoch-ms start of the next `/api/events` window chunk.
events_window_from: int | None = None
+ # Epoch-ms start of the metrics window being walked; `next_page` is the page within it.
+ metrics_window_from: int | None = None
def normalize_base_url(url: str) -> str:
@@ -197,6 +203,7 @@ def _fetch(
session: requests.Session,
url: str,
logger: FilteringBoundLogger,
+ json_body: Any = None,
) -> Any:
@retry(
retry=retry_if_exception_type((InstanaRetryableError, requests.ReadTimeout, requests.ConnectionError)),
@@ -206,7 +213,10 @@ def _fetch(
)
def fetch_once() -> Any:
# stream=True so the body isn't buffered until we cap it — see _read_capped_body.
- response = session.get(url, timeout=REQUEST_TIMEOUT_SECONDS, stream=True)
+ if json_body is None:
+ response = session.get(url, timeout=REQUEST_TIMEOUT_SECONDS, stream=True)
+ else:
+ response = session.post(url, json=json_body, timeout=REQUEST_TIMEOUT_SECONDS, stream=True)
# Instana rate-limits to 5000 calls/hour and answers excess with 429; transient 5xx are
# retryable too. Back off and retry rather than failing the sync.
@@ -386,6 +396,108 @@ def _get_offset_rows(
resumable_source_manager.save_state(InstanaResumeConfig(next_offset=offset))
+def _metric_rows(item: dict[str, Any], entity_key: str) -> list[dict[str, Any]]:
+ """Pivot one metrics item into a row per timestamp, one column per metric.
+
+ Instana returns each metric as ``{"latency.mean": [[timestamp, value], ...]}``; the dot in the
+ key becomes an underscore so every metric is a plain column.
+ """
+ entity = item.get(entity_key)
+ metrics = item.get("metrics")
+ if not isinstance(entity, dict) or not isinstance(metrics, dict):
+ return []
+ entity_id = entity.get("id")
+ if not isinstance(entity_id, str) or not entity_id:
+ return []
+
+ rows: dict[int, dict[str, Any]] = {}
+ for metric_name, points in metrics.items():
+ if not isinstance(points, list):
+ continue
+ for point in points:
+ if not isinstance(point, list) or len(point) != 2 or not isinstance(point[0], int | float):
+ continue
+ timestamp = int(point[0])
+ row = rows.setdefault(timestamp, {f"{entity_key}Id": entity_id, entity_key: entity, "timestamp": timestamp})
+ row[metric_name.replace(".", "_")] = point[1]
+ return list(rows.values())
+
+
+def _floor_to_window(epoch_ms: int) -> int:
+ return epoch_ms - epoch_ms % METRICS_WINDOW_MS
+
+
+def _get_metric_rows(
+ session: requests.Session,
+ root: str,
+ config: InstanaEndpointConfig,
+ entity_key: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[InstanaResumeConfig],
+ should_use_incremental_field: bool,
+ db_incremental_field_last_value: Any,
+) -> Iterator[list[dict[str, Any]]]:
+ """Walk the daily golden-signal metrics for every application, service or endpoint.
+
+ Each one-day window is one POST query, paginated by entity. A window holds a single bucket,
+ so the incremental watermark is the bucket timestamp. The spec does not say whether that
+ timestamp marks the start or the end of the bucket, so an incremental run restarts one window
+ before the watermark's window. That re-fetches at most one extra day, and merge dedupes it.
+ """
+ end = _floor_to_window(int(datetime.now(UTC).timestamp() * 1000))
+
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ watermark = _to_epoch_ms(db_incremental_field_last_value) if should_use_incremental_field else None
+ page = 1
+ if resume is not None and resume.metrics_window_from is not None:
+ window_from = resume.metrics_window_from
+ page = resume.next_page or 1
+ logger.debug(f"Instana: resuming {config.name} from window_from={window_from}, page={page}")
+ elif watermark is not None:
+ window_from = max(
+ _floor_to_window(min(watermark, end) - METRICS_WINDOW_MS),
+ end - METRICS_MAX_LOOKBACK_DAYS * METRICS_WINDOW_MS,
+ )
+ else:
+ window_from = end - METRICS_DEFAULT_LOOKBACK_DAYS * METRICS_WINDOW_MS
+
+ url = _build_url(root, config.path, {})
+ granularity_seconds = METRICS_WINDOW_MS // 1000
+ while window_from < end:
+ window_to = window_from + METRICS_WINDOW_MS
+ fetched = 0
+ pages_walked = 0
+ walk_deadline = time.monotonic() + MAX_CATALOG_WALK_SECONDS
+ while True:
+ _check_walk_bounds(config, walk_deadline, pages_walked)
+ body = {
+ "metrics": [{**metric, "granularity": granularity_seconds} for metric in APPLICATION_METRICS],
+ "timeFrame": {"to": window_to, "windowSize": METRICS_WINDOW_MS},
+ "pagination": {"page": page, "pageSize": PAGE_SIZE},
+ }
+ data = _fetch(session, url, logger, json_body=body)
+ pages_walked += 1
+
+ items = _extract_items(data, config)
+ rows = [row for item in items if isinstance(item, dict) for row in _metric_rows(item, entity_key)]
+ if rows:
+ yield rows
+ fetched += len(items)
+
+ total_hits = data.get("totalHits") if isinstance(data, dict) else None
+ if len(items) < PAGE_SIZE or (isinstance(total_hits, int) and fetched >= total_hits):
+ break
+ page += 1
+ resumable_source_manager.save_state(InstanaResumeConfig(metrics_window_from=window_from, next_page=page))
+ if not rows:
+ resumable_source_manager.safe_point()
+
+ page = 1
+ window_from = window_to
+ if window_from < end:
+ resumable_source_manager.save_state(InstanaResumeConfig(metrics_window_from=window_from, next_page=1))
+
+
def _get_fan_out_rows(
session: requests.Session,
root: str,
@@ -409,6 +521,11 @@ def _get_fan_out_rows(
# The parent walk checks its bounds only between parent pages, so the child requests of one
# page need their own: one page holds up to PAGE_SIZE slow or retried child requests.
+ window_params: dict[str, Any] = {}
+ if config.report_window_ms is not None:
+ now_ms = int(datetime.now(UTC).timestamp() * 1000)
+ window_params = {"from": now_ms - config.report_window_ms, "to": now_ms}
+
children_fetched = 0
walk_deadline = time.monotonic() + MAX_CATALOG_WALK_SECONDS
for parent_rows in parent_pages:
@@ -419,7 +536,8 @@ def _get_fan_out_rows(
continue
_check_walk_bounds(config, walk_deadline, children_fetched)
children_fetched += 1
- url = _build_url(root, config.path.format(**{fan_out.child_field: quote(parent_id, safe="")}), {})
+ path = config.path.format(**{fan_out.child_field: quote(parent_id, safe="")})
+ url = _build_url(root, path, window_params)
try:
data = _fetch(session, url, logger)
except requests.HTTPError as e:
@@ -483,6 +601,17 @@ def get_rows(
should_use_incremental_field,
db_incremental_field_last_value,
)
+ elif config.metrics_entity is not None:
+ yield from _get_metric_rows(
+ session,
+ root,
+ config,
+ config.metrics_entity,
+ logger,
+ resumable_source_manager,
+ should_use_incremental_field,
+ db_incremental_field_last_value,
+ )
elif config.fan_out is not None:
yield from _get_fan_out_rows(session, root, config, config.fan_out, logger, resumable_source_manager)
elif config.pagination == "page":
@@ -518,7 +647,7 @@ def instana_source(
db_incremental_field_last_value=db_incremental_field_last_value,
),
primary_keys=config.primary_keys,
- # Event windows ascend, so batches arrive in (chunk-level) ascending `start` order; the
+ # Event and metrics windows ascend, so batches arrive in (window-level) ascending order; the
# catalog endpoints are full refresh where the watermark is unused.
sort_mode="asc",
partition_count=1,
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/instana/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/instana/settings.py
index bbf20367d024..4c3c3c5f938a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/instana/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/instana/settings.py
@@ -35,6 +35,29 @@ EVENTS_DEFAULT_LOOKBACK_DAYS = 30
SNAPSHOTS_WINDOW_MS = 60 * 60 * 1000
SNAPSHOTS_MAX_SIZE = 1000
+# The application-monitoring metrics APIs are POST-with-body time-series queries. They are synced
+# as a daily rollup: one-day windows aligned to UTC midnight with a one-day granularity, so every
+# window holds exactly one bucket per entity. Only complete days are requested.
+METRICS_WINDOW_MS = 24 * 60 * 60 * 1000
+METRICS_DEFAULT_LOOKBACK_DAYS = 7
+# An incremental run never reaches further back than this, so a bogus (e.g. epoch-zero) bucket
+# timestamp from the host can't turn every later sync into a day-by-day walk from 1970.
+METRICS_MAX_LOOKBACK_DAYS = 31
+# Golden signals. Each aggregation is one the spec allows for its metric.
+APPLICATION_METRICS: list[dict[str, str]] = [
+ {"metric": "calls", "aggregation": "SUM"},
+ {"metric": "erroneousCalls", "aggregation": "SUM"},
+ {"metric": "errors", "aggregation": "MEAN"},
+ {"metric": "latency", "aggregation": "MEAN"},
+ {"metric": "latency", "aggregation": "P50"},
+ {"metric": "latency", "aggregation": "P90"},
+ {"metric": "latency", "aggregation": "P99"},
+]
+
+# `/api/apdex/report/{apdexId}` requires a `from`/`to` window. Each sync replaces the table with
+# the scores over the trailing window.
+APDEX_REPORT_WINDOW_MS = 7 * 24 * 60 * 60 * 1000
+
PaginationStyle = Literal["page", "offset", "none"]
@@ -63,10 +86,15 @@ class InstanaEndpointConfig:
incremental_fields: list[IncrementalField] = field(default_factory=list)
# Extra query params sent on every request.
extra_params: dict[str, str] = field(default_factory=dict)
+ # Set on the application-monitoring metrics endpoints: the key in each response item holding
+ # the entity (`application`, `service` or `endpoint`) the metrics belong to.
+ metrics_entity: Optional[str] = None
+ # Fan-out children that require a time window get `from`/`to` covering this trailing span.
+ report_window_ms: Optional[int] = None
@property
def supports_incremental(self) -> bool:
- return self.is_events
+ return self.is_events or self.metrics_entity is not None
def _start_incremental_fields() -> list[IncrementalField]:
@@ -81,13 +109,24 @@ def _start_incremental_fields() -> list[IncrementalField]:
]
+def _timestamp_incremental_fields() -> list[IncrementalField]:
+ return [
+ {
+ "label": "timestamp",
+ "type": IncrementalFieldType.Integer,
+ "field": "timestamp",
+ "field_type": IncrementalFieldType.Integer,
+ }
+ ]
+
+
# Endpoint catalog, verified against the official OpenAPI spec
# (https://instana.github.io/openapi/openapi.yaml). Instana has no Airbyte/Fivetran connector to
# mirror, so coverage follows what the UI surfaces: events, the application-monitoring catalogs
-# (applications/services/endpoints), website + synthetic monitoring configs, alerting settings,
-# event specifications, releases, SLOs, and the infrastructure snapshot inventory. Metric
-# time-series, trace analytics and synthetic result endpoints are POST-with-body cursor APIs and
-# are intentionally out of scope.
+# (applications/services/endpoints) and their daily golden-signal metrics, website, mobile app and
+# synthetic monitoring configs, alerting settings, event specifications, releases, SLOs, Apdex, and
+# the infrastructure snapshot inventory. Trace analytics and synthetic result endpoints are
+# POST-with-body cursor APIs and are intentionally out of scope.
INSTANA_ENDPOINTS: dict[str, InstanaEndpointConfig] = {
"events": InstanaEndpointConfig(
name="events",
@@ -171,6 +210,55 @@ INSTANA_ENDPOINTS: dict[str, InstanaEndpointConfig] = {
primary_keys=["testResultId"],
pagination="offset",
),
+ "synthetic_locations": InstanaEndpointConfig(
+ name="synthetic_locations",
+ path="/api/synthetics/settings/locations",
+ pagination="offset",
+ ),
+ "synthetic_datacenters": InstanaEndpointConfig(
+ name="synthetic_datacenters",
+ path="/api/synthetics/settings/datacenters",
+ primary_keys=["datacenterId"],
+ ),
+ "mobile_apps": InstanaEndpointConfig(
+ name="mobile_apps",
+ path="/api/mobile-app-monitoring/config",
+ ),
+ "application_metrics": InstanaEndpointConfig(
+ name="application_metrics",
+ path="/api/application-monitoring/metrics/applications",
+ data_path="items",
+ primary_keys=["applicationId", "timestamp"],
+ metrics_entity="application",
+ incremental_fields=_timestamp_incremental_fields(),
+ ),
+ "service_metrics": InstanaEndpointConfig(
+ name="service_metrics",
+ path="/api/application-monitoring/metrics/services",
+ data_path="items",
+ primary_keys=["serviceId", "timestamp"],
+ metrics_entity="service",
+ incremental_fields=_timestamp_incremental_fields(),
+ ),
+ "endpoint_metrics": InstanaEndpointConfig(
+ name="endpoint_metrics",
+ path="/api/application-monitoring/metrics/endpoints",
+ data_path="items",
+ primary_keys=["endpointId", "timestamp"],
+ metrics_entity="endpoint",
+ incremental_fields=_timestamp_incremental_fields(),
+ ),
+ "apdex_configs": InstanaEndpointConfig(
+ name="apdex_configs",
+ path="/api/settings/apdex",
+ ),
+ "apdex_reports": InstanaEndpointConfig(
+ name="apdex_reports",
+ path="/api/apdex/report/{apdexId}",
+ primary_keys=["apdexId", "from"],
+ fan_out=InstanaFanOutConfig(parent="apdex_configs", parent_field="id", child_field="apdexId"),
+ report_window_ms=APDEX_REPORT_WINDOW_MS,
+ ),
}
ENDPOINTS = tuple(INSTANA_ENDPOINTS.keys())
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/instana/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/instana/source.py
index c486a64b27de..8417172bc4d5 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/instana/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/instana/source.py
@@ -32,6 +32,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.instana.se
EVENTS_DEFAULT_LOOKBACK_DAYS,
INCREMENTAL_FIELDS,
INSTANA_ENDPOINTS,
+ METRICS_DEFAULT_LOOKBACK_DAYS,
)
from products.warehouse_sources.backend.types import ExternalDataSourceType
@@ -116,18 +117,22 @@ Your base URL is the address you use to open the Instana UI, e.g. `https://unit-
) -> list[SourceSchema]:
def _build_schema(endpoint: str) -> SourceSchema:
endpoint_config = INSTANA_ENDPOINTS[endpoint]
+ description: str | None = None
+ if endpoint_config.is_events:
+ description = f"Only syncs the last {EVENTS_DEFAULT_LOOKBACK_DAYS} days on initial sync"
+ elif endpoint_config.metrics_entity is not None:
+ description = (
+ f"Daily metrics. Only syncs the last {METRICS_DEFAULT_LOOKBACK_DAYS} full days on initial sync"
+ )
return SourceSchema(
name=endpoint,
supports_incremental=endpoint_config.supports_incremental,
# Events mutate after creation (`state` and `end` change while an issue is open),
- # so append mode would materialize each update as a duplicate row — merge only.
+ # and incremental metrics re-fetch the last day, so append mode would materialize
+ # each re-fetch as a duplicate row — merge only.
supports_append=False,
incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
- description=(
- f"Only syncs the last {EVENTS_DEFAULT_LOOKBACK_DAYS} days on initial sync"
- if endpoint == "events"
- else None
- ),
+ description=description,
)
schemas = [_build_schema(endpoint) for endpoint in ENDPOINTS]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/instana/tests/test_instana.py b/products/warehouse_sources/backend/temporal/data_imports/sources/instana/tests/test_instana.py
index 8317ff6b68a7..6fd56605f6c9 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/instana/tests/test_instana.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/instana/tests/test_instana.py
@@ -18,8 +18,12 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.instana.in
validate_credentials,
)
from products.warehouse_sources.backend.temporal.data_imports.sources.instana.settings import (
+ APDEX_REPORT_WINDOW_MS,
EVENTS_DEFAULT_LOOKBACK_DAYS,
EVENTS_WINDOW_CHUNK_MS,
+ METRICS_DEFAULT_LOOKBACK_DAYS,
+ METRICS_MAX_LOOKBACK_DAYS,
+ METRICS_WINDOW_MS,
PAGE_SIZE,
)
@@ -309,6 +313,148 @@ class TestOffsetRows:
assert _query(fetched[0])["offset"] == ["2"]
+def _run_metric_rows(
+ endpoint: str,
+ pages: list[Any],
+ can_resume: bool = False,
+ resume_state: InstanaResumeConfig | None = None,
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Any = None,
+) -> tuple[list[Any], list[InstanaResumeConfig], list[dict[str, Any]]]:
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = can_resume
+ manager.load_state.return_value = resume_state
+ saved: list[InstanaResumeConfig] = []
+ manager.save_state.side_effect = saved.append
+
+ bodies: list[dict[str, Any]] = []
+
+ def fake_post(url: str, json: Any = None, timeout: Any = None, stream: bool = False) -> Any:
+ bodies.append(json)
+ return _make_response(200, pages[min(len(bodies), len(pages)) - 1])
+
+ with _patch_host_safe(), mock.patch.object(inst, "make_tracked_session") as mock_session:
+ mock_session.return_value.post.side_effect = fake_post
+ rows = list(
+ inst.get_rows(
+ base_url=BASE_URL,
+ api_token="token",
+ endpoint=endpoint,
+ team_id=1,
+ logger=mock.MagicMock(),
+ resumable_source_manager=manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=db_incremental_field_last_value,
+ )
+ )
+ return rows, saved, bodies
+
+
+class TestMetricRows:
+ @pytest.fixture(autouse=True)
+ def _frozen_clock(self):
+ with time_machine.travel("2026-01-10T15:30:00Z", tick=False):
+ yield
+
+ # 2026-01-10T00:00:00Z: the last complete day ends here.
+ TODAY_MS = 1768003200000
+
+ @staticmethod
+ def _windows(bodies: list[dict[str, Any]]) -> list[int]:
+ return [body["timeFrame"]["to"] for body in bodies]
+
+ def test_items_are_pivoted_into_a_row_per_entity_and_timestamp(self) -> None:
+ service = {"id": "svc1", "label": "checkout"}
+ page = {
+ "items": [
+ {
+ "service": service,
+ "metrics": {"calls.sum": [[100, 7], [200, 9]], "latency.p90": [[100, 12.5]]},
+ },
+ # Items without an entity id can't be keyed, so they are dropped.
+ {"service": {"label": "orphan"}, "metrics": {"calls.sum": [[100, 1]]}},
+ ],
+ "totalHits": 2,
+ }
+ rows, _saved, _bodies = _run_metric_rows(
+ "service_metrics", [page], should_use_incremental_field=True, db_incremental_field_last_value=self.TODAY_MS
+ )
+
+ assert rows[0] == [
+ {"serviceId": "svc1", "service": service, "timestamp": 100, "calls_sum": 7, "latency_p90": 12.5},
+ {"serviceId": "svc1", "service": service, "timestamp": 200, "calls_sum": 9},
+ ]
+
+ def test_first_sync_walks_complete_days_of_the_lookback(self) -> None:
+ rows, saved, bodies = _run_metric_rows("application_metrics", [{"items": [], "totalHits": 0}])
+
+ assert self._windows(bodies) == [
+ self.TODAY_MS - (METRICS_DEFAULT_LOOKBACK_DAYS - 1 - i) * METRICS_WINDOW_MS
+ for i in range(METRICS_DEFAULT_LOOKBACK_DAYS)
+ ]
+ for body in bodies:
+ assert body["timeFrame"]["windowSize"] == METRICS_WINDOW_MS
+ assert body["pagination"] == {"page": 1, "pageSize": PAGE_SIZE}
+ # One bucket per window keeps the incremental watermark aligned to whole windows.
+ assert {metric["granularity"] for metric in body["metrics"]} == {METRICS_WINDOW_MS // 1000}
+ assert rows == []
+ assert [s.metrics_window_from for s in saved] == self._windows(bodies)[:-1]
+
+ @pytest.mark.parametrize(
+ "watermark",
+ [
+ # Bucket timestamp at the window start or at the window end: both re-fetch that bucket.
+ 1768003200000 - 2 * 24 * 60 * 60 * 1000,
+ 1768003200000 - 1 * 24 * 60 * 60 * 1000,
+ ],
+ )
+ def test_incremental_run_refetches_the_watermark_bucket(self, watermark: int) -> None:
+ _rows, _saved, bodies = _run_metric_rows(
+ "endpoint_metrics",
+ [{"items": [], "totalHits": 0}],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=watermark,
+ )
+
+ windows = self._windows(bodies)
+ assert windows[-1] == self.TODAY_MS
+ # The window ending at the watermark (end-of-bucket reading) and the one after it
+ # (start-of-bucket reading) are both re-fetched.
+ assert watermark in windows
+ assert watermark + METRICS_WINDOW_MS in windows
+
+ def test_ancient_watermark_is_clamped_to_the_max_lookback(self) -> None:
+ _rows, _saved, bodies = _run_metric_rows(
+ "endpoint_metrics",
+ [{"items": [], "totalHits": 0}],
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=0,
+ )
+
+ assert len(bodies) == METRICS_MAX_LOOKBACK_DAYS
+ assert self._windows(bodies)[-1] == self.TODAY_MS
+
+ def test_paginates_within_a_window_and_resumes_from_saved_page(self) -> None:
+ full = {"items": [{"application": {"id": f"a{i}"}, "metrics": {}} for i in range(PAGE_SIZE)], "totalHits": 999}
+ last = {"items": [{"application": {"id": "z"}, "metrics": {"calls.sum": [[1, 1]]}}], "totalHits": 999}
+ window_from = self.TODAY_MS - METRICS_WINDOW_MS
+
+ _rows, saved, bodies = _run_metric_rows("application_metrics", [full, last])
+ assert [b["pagination"]["page"] for b in bodies[:2]] == [1, 2]
+ assert InstanaResumeConfig(metrics_window_from=self.TODAY_MS - 7 * METRICS_WINDOW_MS, next_page=2) in saved
+
+ rows, _saved, bodies = _run_metric_rows(
+ "application_metrics",
+ [last],
+ can_resume=True,
+ resume_state=InstanaResumeConfig(metrics_window_from=window_from, next_page=3),
+ )
+ assert len(bodies) == 1
+ assert bodies[0]["pagination"]["page"] == 3
+ assert bodies[0]["timeFrame"]["to"] == self.TODAY_MS
+ assert rows == [[{"applicationId": "z", "application": {"id": "z"}, "timestamp": 1, "calls_sum": 1}]]
+
+
class TestFanOutRows:
def _run(self, reports: dict[str, Any]) -> tuple[list[Any], list[str]]:
manager = mock.MagicMock()
@@ -368,6 +514,40 @@ class TestFanOutRows:
with pytest.raises(inst.InstanaPaginationLimitError):
self._run({"SLO1": {"sli": 1}, "SLO2": {"sli": 1}})
+ @time_machine.travel("2026-01-10T00:00:00Z", tick=False)
+ def test_apdex_reports_request_a_trailing_window(self) -> None:
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = False
+ fetched_urls: list[str] = []
+
+ def fake_get(url: str, timeout: Any = None, stream: bool = False) -> Any:
+ fetched_urls.append(url)
+ if urlparse(url).path == "/api/settings/apdex":
+ return _make_response(200, [{"id": "APDEX1"}])
+ return _make_response(200, [{"apdexId": "APDEX1", "apdexScore": [[1, 0.9]], "from": 1, "to": 2}])
+
+ with _patch_host_safe(), mock.patch.object(inst, "make_tracked_session") as mock_session:
+ mock_session.return_value.get.side_effect = fake_get
+ rows = list(
+ inst.get_rows(
+ base_url=BASE_URL,
+ api_token="token",
+ endpoint="apdex_reports",
+ team_id=1,
+ logger=mock.MagicMock(),
+ resumable_source_manager=manager,
+ )
+ )
+
+ report_url = fetched_urls[1]
+ assert urlparse(report_url).path == "/api/apdex/report/APDEX1"
+ now_ms = 1768003200000
+ assert _query(report_url) == {
+ "from": [str(now_ms - APDEX_REPORT_WINDOW_MS)],
+ "to": [str(now_ms)],
+ }
+ assert rows == [[{"apdexId": "APDEX1", "apdexScore": [[1, 0.9]], "from": 1, "to": 2}]]
+
class TestListRows:
def test_bare_list_body_is_yielded(self) -> None:
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/instana/tests/test_instana_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/instana/tests/test_instana_source.py
index e9cbc1cfb0a2..faf5d724b7ad 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/instana/tests/test_instana_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/instana/tests/test_instana_source.py
@@ -38,7 +38,14 @@ class TestInstanaSource:
]
assert schemas["events"].description is not None
- for name in set(ENDPOINTS) - {"events"}:
+ metrics_tables = {"application_metrics", "service_metrics", "endpoint_metrics"}
+ for name in metrics_tables:
+ assert schemas[name].supports_incremental is True
+ assert schemas[name].supports_append is False
+ assert [f["field"] for f in schemas[name].incremental_fields] == ["timestamp"]
+ assert schemas[name].description is not None
+
+ for name in set(ENDPOINTS) - {"events"} - metrics_tables:
assert schemas[name].supports_incremental is False
assert schemas[name].supports_append is False
assert schemas[name].incremental_fields == []