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 event spec, release, slo and synthetic ci/cd tables (#111525)

Tom Owers0a45bc8b420f
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 a43f81da9775..8c66cc4d6ff8 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
@@ -4334,10 +4334,10 @@ Today (9): `alert_configs`, `alerting_channels`, `applications`, `endpoints`, `e
Diffed against: <https://instana.github.io/openapi/openapi.json>
-- [ ] `/api/events/settings/event-specifications/built-in and /custom` — lookup resolving the eventSpecificationId carried on every row of the already-synced `events` table - without it events cannot be named or grouped (high)
-- [ ] `/api/releases (+ /api/releases/{releaseId})` — release markers used to correlate deploys with events and metric regressions; the standard overlay on every Instana chart (high)
-- [ ] `/api/settings/slo and /api/slo/report/{sloId}` — SLO definitions plus attainment/error-budget reports - the headline reliability metric, entirely absent today (high)
-- [ ] `/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)
+- [x] `/api/events/settings/event-specifications/built-in and /custom` — lookup resolving the eventSpecificationId carried on every row of the already-synced `events` table - without it events cannot be named or grouped (high). Added as `built_in_event_specifications` and `custom_event_specifications`.
+- [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)
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 8955f4aa34e3..8ff3fa4f9966 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
@@ -113,4 +113,104 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"tags": "Tags attached to the monitored entity.",
},
},
+ "built_in_event_specifications": {
+ "description": "Built-in event specifications: the rules Instana ships to detect issues and incidents. Join `events.eventSpecificationId` to `id` to name events.",
+ "docs_url": "https://instana.github.io/openapi/#operation/getBuiltInEventSpecifications",
+ "columns": {
+ "id": "Unique identifier of the built-in event specification.",
+ "name": "Name of the built-in event specification.",
+ "description": "Description of the built-in event specification.",
+ "shortPluginId": "Short identifier of the plugin (entity type) the specification applies to.",
+ "severity": "Severity level of events raised by the specification.",
+ "triggering": "Whether the specification triggers an incident.",
+ "enabled": "Whether the specification is enabled.",
+ "hidden": "Whether the specification is hidden.",
+ "hyperParams": "Hyper parameters of the specification.",
+ "ruleInputs": "Input rules of the specification.",
+ },
+ },
+ "custom_event_specifications": {
+ "description": "Custom event specifications: user-defined rules that raise Instana events. Join `events.eventSpecificationId` to `id` to name events.",
+ "docs_url": "https://instana.github.io/openapi/#operation/getCustomEventSpecifications",
+ "columns": {
+ "id": "Unique identifier of the custom event specification.",
+ "name": "Name of the custom event specification.",
+ "description": "Description of the custom event specification.",
+ "entityType": "Type of entity the specification is evaluated against.",
+ "query": "Dynamic focus query that scopes the specification to matching entities.",
+ "rules": "Rules that raise an event when they match.",
+ "ruleLogicalOperator": "How the rules combine: AND or OR.",
+ "triggering": "Whether the specification triggers an incident.",
+ "enabled": "Whether the specification is enabled.",
+ "deleted": "Whether the specification is deleted.",
+ "expirationTime": "Time after which an open event expires, in milliseconds.",
+ "lastUpdated": "Timestamp of the last modification, in epoch milliseconds.",
+ },
+ },
+ "releases": {
+ "description": "Release markers that record deployments, used to correlate changes with events and metrics.",
+ "docs_url": "https://instana.github.io/openapi/#operation/getAllReleases",
+ "columns": {
+ "id": "Unique identifier of the release.",
+ "name": "Name of the release (e.g. frontend/release-2000).",
+ "start": "Timestamp when the release was created, in epoch milliseconds.",
+ "lastUpdated": "Timestamp of the last modification, in epoch milliseconds.",
+ "applications": "Application perspectives where the release is shown.",
+ "services": "Services where the release is shown.",
+ },
+ },
+ "slo_configs": {
+ "description": "Service level objective (SLO) configurations.",
+ "docs_url": "https://instana.github.io/openapi/#operation/getAllSloConfigs",
+ "columns": {
+ "id": "Unique identifier of the SLO configuration.",
+ "name": "Name of the SLO configuration.",
+ "target": "Target ratio of good events or time (e.g. 0.99).",
+ "entity": "Entity the SLO measures (application, website, synthetic test, or infrastructure).",
+ "indicator": "Service level indicator the SLO evaluates (e.g. latency, availability).",
+ "timeWindow": "Time window the SLO is evaluated over.",
+ "tags": "Tags attached to the SLO configuration.",
+ "rbacTags": "Access-control tags attached to the SLO configuration.",
+ "createdDate": "When the SLO configuration was created.",
+ "lastUpdated": "When the SLO configuration was last modified.",
+ },
+ },
+ "slo_reports": {
+ "description": "Current attainment and error budget for each SLO over its configured time window. Rebuilt on every sync.",
+ "docs_url": "https://instana.github.io/openapi/#operation/getSlo",
+ "columns": {
+ "sloId": "Identifier of the SLO configuration the report belongs to.",
+ "sli": "Latest measured service level indicator value.",
+ "slo": "Target value of the SLO.",
+ "totalErrorBudget": "Total error budget available in the window.",
+ "errorBudgetRemaining": "Error budget remaining in the window.",
+ "errorBudgetSpent": "Error budget spent in the window.",
+ "errorBurnRate": "Latest error budget burn rate.",
+ "fromTimestamp": "Start of the report window, in epoch milliseconds.",
+ "toTimestamp": "End of the report window, in epoch milliseconds.",
+ "errorChart": "Bad minutes or events over the window, keyed by timestamp.",
+ "errorAccumulationChart": "Accumulated bad minutes or events over the window, keyed by timestamp.",
+ "errorBudgetRemainChart": "Remaining error budget over the window, keyed by timestamp.",
+ "errorBurnRateChart": "Error budget burn rate over the window, keyed by timestamp.",
+ "violationDistribution": "SLO violations over the window, keyed by timestamp.",
+ },
+ },
+ "synthetic_test_ci_cds": {
+ "description": "Synthetic test runs triggered on demand, for example from a CI/CD pipeline.",
+ "docs_url": "https://instana.github.io/openapi/#operation/getSyntheticTestCICDs",
+ "columns": {
+ "testResultId": "Unique identifier of the test run result.",
+ "testId": "Identifier of the synthetic test that ran.",
+ "testLabel": "Display name of the synthetic test.",
+ "testType": "Type of the synthetic test (e.g. HTTPAction).",
+ "locationId": "Identifier of the location the test ran from.",
+ "locationLabel": "Display name of the location the test ran from.",
+ "runType": "How the run was triggered (e.g. CI/CD or OnDemand).",
+ "completed": "Whether the run has completed.",
+ "customization": "Configuration overrides applied to this run.",
+ "applications": "Application perspectives associated with the run.",
+ "websites": "Websites associated with the run.",
+ "mobileApps": "Mobile apps associated with the run.",
+ },
+ },
}
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 84393617db34..308c5dc76937 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
@@ -1,15 +1,16 @@
import json
import time
-import dataclasses
from collections.abc import Iterator
from datetime import UTC, date, datetime
from typing import Any, Optional
-from urllib.parse import urlencode, urlparse
+from urllib.parse import quote, urlencode, urlparse
import requests
from structlog.types import FilteringBoundLogger
from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+from posthog.dataclasses import frozen
+
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
from products.warehouse_sources.backend.temporal.data_imports.sources.common.mixins import _is_host_safe
from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
@@ -23,6 +24,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.instana.se
PAGE_SIZE,
SNAPSHOTS_MAX_SIZE,
InstanaEndpointConfig,
+ InstanaFanOutConfig,
)
REQUEST_TIMEOUT_SECONDS = 60
@@ -95,10 +97,12 @@ def _read_capped_body(response: requests.Response) -> bytes:
return b"".join(chunks)
+@frozen
class InstanaResumeConfig:
# Next page to fetch for the page-paginated application-monitoring catalogs.
next_page: int | None = None
+ # Next `offset` to fetch for offset/limit-paginated endpoints. Instana counts it in pages.
+ next_offset: int | None = None
# Epoch-ms start of the next `/api/events` window chunk.
events_window_from: int | None = None
@@ -281,6 +285,22 @@ def _get_event_rows(
window_from = window_to
+def _check_walk_bounds(config: InstanaEndpointConfig, walk_deadline: float, pages_walked: int) -> None:
+ # A self-hosted host can return a full page forever while never signalling the end, so the
+ # termination conditions never trip; bound the walk so the loop (and its ingestion) can't run
+ # for the whole activity. Both bounds are non-retryable — the same host replays the same loop.
+ # The wall-clock budget is the effective bound: a slow host can stay under the page cap while
+ # streaming each page for MAX_DOWNLOAD_SECONDS, so pages alone wouldn't cap worker time.
+ if time.monotonic() > walk_deadline:
+ raise InstanaPaginationLimitError(
+ f"{PAGINATION_LIMIT_ERROR}: exceeded {MAX_CATALOG_WALK_SECONDS}s walk budget for {config.name}"
+ )
+ if pages_walked >= MAX_CATALOG_PAGES:
+ raise InstanaPaginationLimitError(
+ f"{PAGINATION_LIMIT_ERROR}: stopped after {MAX_CATALOG_PAGES} pages for {config.name}"
+ )
+
+
def _get_paged_rows(
session: requests.Session,
root: str,
@@ -303,20 +323,7 @@ def _get_paged_rows(
pages_walked = 0
walk_deadline = time.monotonic() + MAX_CATALOG_WALK_SECONDS
while True:
- # A self-hosted host can return a full page forever while omitting `totalHits`, so the
- # termination conditions below never trip; bound the walk so the loop (and its ingestion)
- # can't run for the whole activity. Both bounds are non-retryable — the same host replays
- # the same loop. The wall-clock budget is the effective bound: a slow host can stay under
- # the page cap while streaming each page for MAX_DOWNLOAD_SECONDS, so pages alone wouldn't
- # cap worker time.
- if time.monotonic() > walk_deadline:
- raise InstanaPaginationLimitError(
- f"{PAGINATION_LIMIT_ERROR}: exceeded {MAX_CATALOG_WALK_SECONDS}s walk budget for {config.name}"
- )
- if pages_walked >= MAX_CATALOG_PAGES:
- raise InstanaPaginationLimitError(
- f"{PAGINATION_LIMIT_ERROR}: stopped after {MAX_CATALOG_PAGES} pages for {config.name}"
- )
+ _check_walk_bounds(config, walk_deadline, pages_walked)
params: dict[str, Any] = {"pageSize": PAGE_SIZE}
if page is not None:
params["page"] = page
@@ -343,13 +350,100 @@ def _get_paged_rows(
page = next_page
+def _get_offset_rows(
+ session: requests.Session,
+ root: str,
+ config: InstanaEndpointConfig,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[InstanaResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ """Walk an offset/limit-paginated list (synthetic CI/CD runs) until a short page.
+
+ Instana's `offset` is the number of pages of `limit` items to skip, not an item count.
+ """
+ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None
+ offset = resume.next_offset if resume is not None and resume.next_offset is not None else 0
+ if offset:
+ logger.debug(f"Instana: resuming {config.name} from offset={offset}")
+
+ pages_walked = 0
+ walk_deadline = time.monotonic() + MAX_CATALOG_WALK_SECONDS
+ while True:
+ _check_walk_bounds(config, walk_deadline, pages_walked)
+ url = _build_url(root, config.path, {"offset": offset, "limit": PAGE_SIZE})
+ items = _extract_items(_fetch(session, url, logger), config)
+ pages_walked += 1
+
+ if not items:
+ break
+
+ yield items
+
+ if len(items) < PAGE_SIZE:
+ break
+
+ offset += 1
+ resumable_source_manager.save_state(InstanaResumeConfig(next_offset=offset))
+
+
+def _get_fan_out_rows(
+ session: requests.Session,
+ root: str,
+ config: InstanaEndpointConfig,
+ fan_out: InstanaFanOutConfig,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[InstanaResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ """Walk the parent catalog and fetch one child resource per parent row.
+
+ Each child response is yielded on its own, so memory stays bounded by one response rather
+ than one parent page of them. Resume state is the parent walk's page, which the parent walk
+ saves only after all of that page's children are yielded, so a resumed run re-fetches the
+ children of at most one parent page.
+ """
+ parent_config = INSTANA_ENDPOINTS[fan_out.parent]
+ if parent_config.pagination == "page":
+ parent_pages = _get_paged_rows(session, root, parent_config, logger, resumable_source_manager)
+ else:
+ parent_pages = _get_list_rows(session, root, parent_config, logger)
+
+ # 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.
+ children_fetched = 0
+ walk_deadline = time.monotonic() + MAX_CATALOG_WALK_SECONDS
+ for parent_rows in parent_pages:
+ yielded_any = False
+ for parent_row in parent_rows:
+ parent_id = parent_row.get(fan_out.parent_field)
+ if not isinstance(parent_id, str) or not parent_id:
+ 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="")}), {})
+ try:
+ data = _fetch(session, url, logger)
+ except requests.HTTPError as e:
+ # The parent can be deleted between listing it and fetching its child.
+ if e.response is not None and e.response.status_code == 404:
+ logger.debug(f"Instana: {config.name} not found for {fan_out.child_field}={parent_id}, skipping")
+ continue
+ raise
+ records = data if isinstance(data, list) else [data]
+ child_rows = [{**record, fan_out.child_field: parent_id} for record in records if isinstance(record, dict)]
+ if child_rows:
+ yielded_any = True
+ yield child_rows
+ if not yielded_any:
+ resumable_source_manager.safe_point()
+
+
def _get_list_rows(
session: requests.Session,
root: str,
config: InstanaEndpointConfig,
logger: FilteringBoundLogger,
) -> Iterator[list[dict[str, Any]]]:
- """Fetch a single-shot list endpoint (websites, alerting settings, snapshots)."""
+ """Fetch a single-shot list endpoint (websites, alerting settings, snapshots, releases, ...)."""
url = _build_url(root, config.path, dict(config.extra_params))
items = _extract_items(_fetch(session, url, logger), config)
if config.name == "infrastructure_snapshots" and len(items) >= SNAPSHOTS_MAX_SIZE:
@@ -389,8 +483,12 @@ def get_rows(
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":
yield from _get_paged_rows(session, root, config, logger, resumable_source_manager)
+ elif config.pagination == "offset":
+ yield from _get_offset_rows(session, root, config, logger, resumable_source_manager)
else:
yield from _get_list_rows(session, root, config, logger)
@@ -419,7 +517,7 @@ def instana_source(
should_use_incremental_field=should_use_incremental_field,
db_incremental_field_last_value=db_incremental_field_last_value,
),
- primary_keys=[config.primary_key],
+ primary_keys=config.primary_keys,
# Event windows ascend, so batches arrive in (chunk-level) ascending `start` order; the
# catalog endpoints are full refresh where the watermark is unused.
sort_mode="asc",
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 d7931459cad7..bbf20367d024 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
@@ -1,6 +1,8 @@
-from dataclasses import dataclass, field
+from dataclasses import field
from typing import Literal, Optional
+from posthog.dataclasses import frozen
+
from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
# Instana's paginated application-monitoring catalogs accept a `pageSize` param; their analyze
@@ -33,17 +35,28 @@ EVENTS_DEFAULT_LOOKBACK_DAYS = 30
SNAPSHOTS_WINDOW_MS = 60 * 60 * 1000
SNAPSHOTS_MAX_SIZE = 1000
-PaginationStyle = Literal["page", "none"]
+PaginationStyle = Literal["page", "offset", "none"]
+
+
+@frozen
+class InstanaFanOutConfig:
+ # Endpoint whose rows are walked to build each child request.
+ parent: str
+ # Field on the parent row substituted into the child `path`.
+ parent_field: str
+ # Column the parent id is written to on every child row, so rows stay attributable.
+ child_field: str
-@dataclass
+@frozen
class InstanaEndpointConfig:
name: str
path: str
# Key in the response body holding the list of records. ``None`` means the body itself is the list.
data_path: Optional[str] = None
- primary_key: str = "id"
+ primary_keys: list[str] = field(default_factory=lambda: ["id"])
pagination: PaginationStyle = "none"
+ fan_out: Optional[InstanaFanOutConfig] = None
# Only `events` filters server-side (from/to epoch-ms window on the event `start`); everything
# else is a config/topology catalog with no updated-since cursor, so it ships full refresh.
is_events: bool = False
@@ -72,13 +85,14 @@ def _start_incremental_fields() -> list[IncrementalField]:
# (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,
-# and the infrastructure snapshot inventory. Metric time-series and trace analytics endpoints are
-# POST-with-body cursor APIs and are intentionally out of scope for the first release.
+# 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.
INSTANA_ENDPOINTS: dict[str, InstanaEndpointConfig] = {
"events": InstanaEndpointConfig(
name="events",
path="/api/events",
- primary_key="eventId",
+ primary_keys=["eventId"],
is_events=True,
incremental_fields=_start_incremental_fields(),
),
@@ -120,9 +134,43 @@ INSTANA_ENDPOINTS: dict[str, InstanaEndpointConfig] = {
name="infrastructure_snapshots",
path="/api/infrastructure-monitoring/snapshots",
data_path="items",
- primary_key="snapshotId",
+ primary_keys=["snapshotId"],
extra_params={"windowSize": str(SNAPSHOTS_WINDOW_MS), "size": str(SNAPSHOTS_MAX_SIZE)},
),
+ "built_in_event_specifications": InstanaEndpointConfig(
+ name="built_in_event_specifications",
+ path="/api/events/settings/event-specifications/built-in",
+ ),
+ "custom_event_specifications": InstanaEndpointConfig(
+ name="custom_event_specifications",
+ path="/api/events/settings/event-specifications/custom",
+ ),
+ # `from`/`to` only bound releases by time, and releases are edited in place (`lastUpdated`),
+ # so a start-windowed incremental sync would miss edits. The list is small; full refresh.
+ "releases": InstanaEndpointConfig(
+ name="releases",
+ path="/api/releases",
+ ),
+ "slo_configs": InstanaEndpointConfig(
+ name="slo_configs",
+ path="/api/settings/slo",
+ data_path="items",
+ pagination="page",
+ ),
+ # One report per SLO over the SLO's own time window (no `from`/`to` sent), so each sync
+ # replaces the table with current attainment and error budget.
+ "slo_reports": InstanaEndpointConfig(
+ name="slo_reports",
+ path="/api/slo/report/{sloId}",
+ primary_keys=["sloId", "fromTimestamp"],
+ fan_out=InstanaFanOutConfig(parent="slo_configs", parent_field="id", child_field="sloId"),
+ ),
+ "synthetic_test_ci_cds": InstanaEndpointConfig(
+ name="synthetic_test_ci_cds",
+ path="/api/synthetics/settings/tests/ci-cd",
+ primary_keys=["testResultId"],
+ pagination="offset",
+ ),
}
ENDPOINTS = tuple(INSTANA_ENDPOINTS.keys())
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 d7c9a9f6c870..8317ff6b68a7 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
@@ -284,6 +284,91 @@ class TestPagedRows:
)
+class TestOffsetRows:
+ @staticmethod
+ def _page(n: int, start: int = 0) -> list[dict[str, Any]]:
+ return [{"testResultId": f"r{start + i}"} for i in range(n)]
+
+ def test_walks_offsets_until_short_page(self) -> None:
+ pages = [self._page(PAGE_SIZE), self._page(3, start=PAGE_SIZE)]
+ rows, saved, fetched = _run_get_rows("synthetic_test_ci_cds", pages)
+
+ assert [_query(url)["offset"] for url in fetched] == [["0"], ["1"]]
+ assert all(_query(url)["limit"] == [str(PAGE_SIZE)] for url in fetched)
+ assert saved == [InstanaResumeConfig(next_offset=1)]
+ assert sum(len(batch) for batch in rows) == PAGE_SIZE + 3
+
+ def test_resume_starts_at_saved_offset(self) -> None:
+ _rows, _saved, fetched = _run_get_rows(
+ "synthetic_test_ci_cds",
+ [self._page(1)],
+ can_resume=True,
+ resume_state=InstanaResumeConfig(next_offset=2),
+ )
+
+ assert _query(fetched[0])["offset"] == ["2"]
+
+
+class TestFanOutRows:
+ def _run(self, reports: dict[str, Any]) -> tuple[list[Any], list[str]]:
+ 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)
+ path = urlparse(url).path
+ if path == "/api/settings/slo":
+ return _make_response(200, {"items": [{"id": slo_id} for slo_id in reports], "page": 1, "totalHits": 2})
+ report = reports[path.rsplit("/", 1)[-1]]
+ if report is None:
+ resp = _make_response(404, {"message": "not found"})
+ resp.raise_for_status.side_effect = requests.HTTPError("404", response=resp)
+ return resp
+ return _make_response(200, report)
+
+ 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="slo_reports",
+ team_id=1,
+ logger=mock.MagicMock(),
+ resumable_source_manager=manager,
+ )
+ )
+ return rows, fetched_urls
+
+ @pytest.mark.parametrize(
+ "report_body",
+ [
+ {"sli": 0.99, "fromTimestamp": 1},
+ [{"sli": 0.99, "fromTimestamp": 1}],
+ ],
+ )
+ def test_reports_carry_parent_id_and_deleted_parent_is_skipped(self, report_body: Any) -> None:
+ rows, fetched = self._run({"SLO1": report_body, "SLO_GONE": None, "SLO2": report_body})
+
+ assert [urlparse(url).path for url in fetched[1:]] == [
+ "/api/slo/report/SLO1",
+ "/api/slo/report/SLO_GONE",
+ "/api/slo/report/SLO2",
+ ]
+ assert rows == [
+ [{"sli": 0.99, "fromTimestamp": 1, "sloId": "SLO1"}],
+ [{"sli": 0.99, "fromTimestamp": 1, "sloId": "SLO2"}],
+ ]
+
+ def test_child_requests_count_against_the_walk_bounds(self) -> None:
+ # One parent page can hold many slow child requests; the bound must trip inside the page,
+ # not only when the parent walk asks for its next page.
+ with mock.patch.object(inst, "MAX_CATALOG_PAGES", 1):
+ with pytest.raises(inst.InstanaPaginationLimitError):
+ self._run({"SLO1": {"sli": 1}, "SLO2": {"sli": 1}})
+
+
class TestListRows:
def test_bare_list_body_is_yielded(self) -> None:
pages: list[Any] = [[{"id": "w1", "name": "site"}]]
@@ -376,12 +461,12 @@ class TestInstanaSourceResponse:
@pytest.mark.parametrize(
("endpoint", "expected_pk"),
[
- ("events", "eventId"),
- ("applications", "id"),
- ("infrastructure_snapshots", "snapshotId"),
+ ("events", ["eventId"]),
+ ("applications", ["id"]),
+ ("infrastructure_snapshots", ["snapshotId"]),
],
)
- def test_source_response_shape(self, endpoint: str, expected_pk: str) -> None:
+ def test_source_response_shape(self, endpoint: str, expected_pk: list[str]) -> None:
response = instana_source(
base_url=BASE_URL,
api_token="token",
@@ -392,7 +477,7 @@ class TestInstanaSourceResponse:
)
assert response.name == endpoint
- assert response.primary_keys == [expected_pk]
+ assert response.primary_keys == expected_pk
assert response.sort_mode == "asc"
# Instana timestamps are epoch-ms integers, so tables are unpartitioned.
assert response.partition_mode is None