: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 five incident.io tables (#111888)
Tom Owers8d26d17ccba4
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 e7261ec98f50..0db2b9b8aa57 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@@ -4230,22 +4230,23 @@ Note: docs.imagga.com is a JS SPA that ships no server-rendered resource list, n## IncidentIo — gaps-Today (17): `alerts`, `catalog_entries`, `catalog_types`, `custom_field_options`, `custom_fields`, `escalations`, `follow_ups`, `incident_alerts`, `incident_roles`, `incident_statuses`, `incident_timestamps`, `incident_types`, `incident_updates`, `incidents`, `schedules`, `severities`, `users`+Today (22): `alert_sources`, `alerts`, `catalog_entries`, `catalog_types`, `custom_field_options`, `custom_fields`, `escalation_paths`, `escalations`, `follow_ups`, `incident_alerts`, `incident_roles`, `incident_statuses`, `incident_timestamps`, `incident_types`, `incident_updates`, `incidents`, `schedule_entries`, `schedules`, `severities`, `status_page_incidents`, `status_pages`, `users`Diffed against: <https://api-docs.incident.io/>- [x] `/v2/incident_alerts` — join table linking alerts to the incidents they triggered - without it the synced `alerts` and `incidents` tables cannot be related at all (high)- [x] `/v1/custom_field_options` — lookup resolving the option IDs stored inside the custom field values on every incident; `custom\_fields` alone only gives definitions (high). Added as `custom_field_options` (fan-out over `custom_fields`, since `custom_field_id` is a required query param).- [x] `/v2/incident_timestamps` — lookup naming the timestamp IDs carried in incident timestamp_values - required to compute MTTA/MTTR from the incidents table (high)-- [ ] `/v2/escalation_paths` — lookup resolving the escalation path IDs referenced by the already-synced `escalations` rows (high)-- [ ] `/v2/alert_sources` — lookup resolving alert_source_config IDs on `alerts`, so alert volume can be attributed to Datadog/Sentry/etc (high)-- [ ] `/v2/schedule_entries` — the actual on-call shifts; `schedules` today is only the rota config, so no one can query who was on call when (high)+- [x] `/v2/escalation_paths` — lookup resolving the escalation path IDs referenced by the already-synced `escalations` rows (high)+- [x] `/v2/alert_sources` — lookup resolving alert_source_config IDs on `alerts`, so alert volume can be attributed to Datadog/Sentry/etc (high). Added as `alert_sources`, with `secret_token` dropped from every row.+- [x] `/v2/schedule_entries` — the actual on-call shifts; `schedules` today is only the rota config, so no one can query who was on call when (high). Added as `schedule_entries` (fan-out over `schedules`, since `schedule_id` is a required query param). The endpoint returns nothing before "now" without a window, so each full refresh reads the `final` entries from 365 days back to 30 days ahead.- [x] `/v3/catalog_types and /v3/catalog_entries` — the service/team catalog that custom fields, alert routes and escalation paths all reference by ID - the master lookup for the whole account (high). Added as `catalog_types` and `catalog_entries` (fan-out over `catalog_types`, since `catalog_type_id` is a required query param).- [ ] `/v3/teams` — team lookup for attributing incidents, escalations and follow-ups to owning teams (medium)- [ ] `/v2/actions` — per-incident action items during the response, complementing the already-synced follow_ups (medium)- [ ] `/v2/incident_participants and /v2/incident_participant_workloads` — membership table of who participated in each incident plus incident.io's on-call workload metric (medium)- [ ] `/v2/alert_attributes` — lookup resolving the attribute IDs in each alert's attribute payload (medium)-- [ ] `/v2/status_page_incidents and /v2/status_page_incident_updates` — customer-facing incident communications, separate objects from internal incidents (medium)+- [x] `/v2/status_page_incidents and /v2/status_page_incident_updates` — customer-facing incident communications, separate objects from internal incidents (medium). Added as `status_page_incidents` (fan-out over `status_pages`, since `status_page_id` is a required query param). `/v2/status_page_incident_updates` is create-only (no list operation); the updates arrive in each incident's `updates` column.+- [x] `/v2/status_pages` — status page lookup, and the parent the status page incident fan-out iterates. Added as `status_pages`.Note: The Mintlify docs site serves the same 537KB SPA shell for every path (including /openapi.json, /llms.txt, /docs.json), but that shell embeds the full route table plus a per-tag spec manifest (openapi/tags/\*.json, 53 tags). I diffed against that. Note the API spans three versions concurrently - v1 (severities, incident_statuses, incident_types, custom_field_options, postmortem_documents, maintenance_windows), v2 (most things) and v3 (catalog, teams, alert_routes) - and the existing PostHog source already mixes v1 and v2, so adding v3 paths is consistent. Excluded as config/plumbing: alert_routes, workflows, secrets, api_keys, ip_allowlists, heartbeat, telemetry, notification methods/rules, schedule sync rules/targets.diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/incident_io/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/incident_io/canonical_descriptions.pyindex 485751fc5c7b..f9a7a0098f08 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/incident_io/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/incident_io/canonical_descriptions.py@@ -240,4 +240,70 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"updated_at": "Time at which the catalog entry was last updated.",},},+ "schedule_entries": {+ "description": "An on-call shift on an incident.io schedule after overrides are applied, covering a rolling window around the sync time.",+ "docs_url": "https://api-docs.incident.io/tag/Schedules-V2",+ "columns": {+ "schedule_id": "Identifier of the schedule this shift belongs to.",+ "entry_id": "Unique identifier of the schedule entry.",+ "fingerprint": "Identifier used to determine a unique shift.",+ "rotation_id": "Identifier of the rotation this entry applies to on the schedule, if any.",+ "user": "The user who is on call for this shift.",+ "start_at": "Time at which the shift starts.",+ "end_at": "Time at which the shift ends.",+ },+ },+ "escalation_paths": {+ "description": "An escalation path in incident.io: the steps that describe how a page is escalated.",+ "docs_url": "https://api-docs.incident.io/tag/Escalations-V2",+ "columns": {+ "id": "Unique identifier for the escalation path.",+ "name": "The name of the escalation path.",+ "kind": "Whether the path carries its own nodes or is built from an escalation path template.",+ "path": "The nodes that form the levels and branches of the escalation path.",+ "template_id": "For a templated path, the template it is built from.",+ "param_bindings": "For a templated path, the values bound to the template's parameters.",+ "team_ids": "Identifiers of the teams that own the escalation path.",+ "current_responders": "Users who are currently on call for the escalation path.",+ "repeat_config": "How the escalation path repeats when nobody acknowledges.",+ "working_hours": "The working hours for the escalation path.",+ },+ },+ "alert_sources": {+ "description": "A source that sends alerts into incident.io, such as Datadog, Sentry, or an HTTP endpoint.",+ "docs_url": "https://api-docs.incident.io/tag/Alert-Sources-V2",+ "columns": {+ "id": "Unique identifier for the alert source.",+ "name": "Unique name of the alert source.",+ "source_type": "Type of alert source (e.g. datadog, sentry, http).",+ "template": "How incoming events are mapped to alert title, description, and attributes.",+ "alert_events_url": "URL that HTTP-based sources send alert events to.",+ "owning_team_ids": "Identifiers of the teams that own the alert source.",+ "fixed_team_id": "The team every alert from this source is attributed to, if set.",+ "auto_resolve_timeout_minutes": "Minutes after which alerts from this source resolve automatically, if set.",+ },+ },+ "status_pages": {+ "description": "A public or customer status page managed in incident.io.",+ "docs_url": "https://api-docs.incident.io/tag/Status-Pages-V2",+ "columns": {+ "id": "Unique identifier for the status page.",+ "name": "The title of the status page.",+ "description": "The description of the status page.",+ "public_url": "The public URL of the status page.",+ },+ },+ "status_page_incidents": {+ "description": "A customer-facing incident published on an incident.io status page, with its updates.",+ "docs_url": "https://api-docs.incident.io/tag/Status-Pages-V2",+ "columns": {+ "id": "Unique identifier for the status page incident.",+ "status_page_id": "Identifier of the status page the incident is published on.",+ "name": "The title of the incident.",+ "incident_status": "Current status of the incident.",+ "published_at": "Time at which the incident was published to the status page.",+ "updates": "Updates posted to the incident, each with its message, status, and publish time.",+ "component_impacts": "Time periods in which the incident affected a component.",+ },+ },}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/incident_io/incident_io.py b/products/warehouse_sources/backend/temporal/data_imports/sources/incident_io/incident_io.pyindex 3d24f7dff6fa..0444eb1e2919 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/incident_io/incident_io.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/incident_io/incident_io.py@@ -1,6 +1,6 @@import dataclasses-from collections.abc import Iterable-from datetime import date, datetime+from collections.abc import Callable, Iterable+from datetime import UTC, date, datetimefrom typing import Any, Optional, castfrom urllib.parse import parse_qsl, quote, urlencode, urlsplit@@ -17,12 +17,16 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.resJSONResponseCursorPaginator,SinglePagePaginator,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import ClientConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (+ ClientConfig,+ EndpointResource,+)from 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 SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.incident_io.settings import (INCIDENT_IO_ENDPOINTS,+ EntryWindow,IncidentIoEndpointConfig,)@@ -37,6 +41,8 @@ class IncidentIoResumeConfig:# Framework fan-out resume state for the parent-scoped endpoints, opaque to this source and# passed straight back to the fan-out helper.fanout_state: Optional[dict[str, Any]] = None+ # The window a windowed fan-out started with. Its cursor is only valid against that window's end.+ window_params: Optional[dict[str, str]] = Nonedef _build_url(path: str, params: dict[str, Any]) -> str:@@ -89,8 +95,8 @@ def _build_params(incremental_value: Optional[str],) -> dict[str, Any]:params: dict[str, Any] = {}- if config.paginated:- params["page_size"] = config.page_size+ if config.paginated and config.page_size_param:+ params[config.page_size_param] = config.page_sizeif config.sort_by:params["sort_by"] = config.sort_byif incremental_field and incremental_value:@@ -98,13 +104,30 @@ def _build_params(return params-def _client_config(api_key: str) -> ClientConfig:+def _window_params(window: EntryWindow, now: datetime) -> dict[str, str]:+ return {+ window.start_param: (now - window.lookback).strftime("%Y-%m-%dT%H:%M:%SZ"),+ window.end_param: (now + window.lookahead).strftime("%Y-%m-%dT%H:%M:%SZ"),+ }+++def _drop_fields(fields: tuple[str, ...]) -> Callable[[dict[str, Any]], dict[str, Any]]:+ def _mapper(row: dict[str, Any]) -> dict[str, Any]:+ for name in fields:+ row.pop(name, None)+ return row++ return _mapper+++def _client_config(api_key: str, capture: bool = True) -> ClientConfig:# Bearer token goes through the framework auth config so it's redacted from logs and raised# errors; only the non-secret Accept header rides in the client headers.return {"base_url": INCIDENT_IO_BASE_URL,"headers": {"Accept": "application/json"},"auth": {"type": "bearer", "token": api_key},+ "capture": capture,}@@ -132,7 +155,9 @@ def _fanout_child_probe_url(api_key: str, config: IncidentIoEndpointConfig) -> Oreturn Noneparent_id = quote(str(rows[0][config.fanout.resolve_field]), safe="")path = config.path.replace(f"{{{config.fanout.resolve_param}}}", parent_id)- return f"{INCIDENT_IO_BASE_URL}{path}&{urlencode({'page_size': 1})}"+ if config.page_size_param is None:+ return f"{INCIDENT_IO_BASE_URL}{path}"+ return f"{INCIDENT_IO_BASE_URL}{path}&{urlencode({config.page_size_param: 1})}"def _probe_result(api_key: str, url: str, schema_name: Optional[str]) -> tuple[bool, str | None]:@@ -174,7 +199,9 @@ def validate_credentials(api_key: str, schema_name: Optional[str] = None) -> tupconfig = INCIDENT_IO_ENDPOINTS.get(schema_name or "", INCIDENT_IO_ENDPOINTS["incidents"])# A fan-out child can't be listed without a parent id, so the parent list is probed first.probe_config = INCIDENT_IO_ENDPOINTS[config.fanout.parent_name] if config.fanout is not None else config- params: dict[str, Any] = {"page_size": 1} if probe_config.paginated else {}+ params: dict[str, Any] = (+ {probe_config.page_size_param: 1} if probe_config.paginated and probe_config.page_size_param else {}+ )is_valid, error = _probe_result(api_key, _build_url(probe_config.path, params), schema_name)if not is_valid or config.fanout is None:@@ -187,10 +214,11 @@ def validate_credentials(api_key: str, schema_name: Optional[str] = None) -> tupdef _paginator(config: IncidentIoEndpointConfig) -> BasePaginator:- # incident.io paginates via a record-ID cursor in `pagination_meta.after`, replayed as the- # `after` query param. Config-style endpoints return the full list in one unpaginated response.+ # incident.io paginates via a cursor in `pagination_meta.after`, replayed as the endpoint's+ # cursor param (`after` for most lists). Config-style endpoints return the full list in one+ # unpaginated response.return (- JSONResponseCursorPaginator(cursor_path="pagination_meta.after", cursor_param="after")+ JSONResponseCursorPaginator(cursor_path="pagination_meta.after", cursor_param=config.cursor_param)if config.paginatedelse SinglePagePaginator())@@ -226,13 +254,23 @@ def _fanout_source(parent_config = INCIDENT_IO_ENDPOINTS[config.fanout.parent_name]initial_paginator_state: Optional[dict[str, Any]] = None+ window_params: Optional[dict[str, str]] = Noneif resumable_source_manager.can_resume():resume = resumable_source_manager.load_state()if resume is not None and resume.fanout_state:initial_paginator_state = resume.fanout_state+ window_params = resume.window_params+ if config.entry_window is not None and window_params is None:+ window_params = _window_params(config.entry_window, datetime.now(UTC))def save_checkpoint(state: Optional[dict[str, Any]]) -> None:- resumable_source_manager.save_state(IncidentIoResumeConfig(fanout_state=state))+ resumable_source_manager.save_state(IncidentIoResumeConfig(fanout_state=state, window_params=window_params))++ child_params: dict[str, Any] = {}+ if config.page_size_param:+ child_params[config.page_size_param] = config.page_size+ if window_params:+ child_params.update(window_params)resource = cast(Iterable[Any],@@ -245,10 +283,10 @@ def _fanout_source(team_id=team_id,job_id=job_id,db_incremental_field_last_value=None,- # The parent lookup lists are unpaginated and take no page-size param, so the child's- # page size rides in `child_params_extra` instead.+ # Parent page sizes ride in each fan-out's `parent_params`, since some parent lookup+ # lists are unpaginated and take no page-size param.page_size_param=None,- child_params_extra={"page_size": config.page_size},+ child_params_extra=child_params,parent_endpoint_extra={"paginator": _paginator(parent_config), "data_selector": parent_config.data_key},child_endpoint_extra={"paginator": _paginator(config), "data_selector": config.data_key},resume_hook=save_checkpoint,@@ -287,19 +325,22 @@ def incident_io_source()params = _build_params(config, incremental_field if should_use_incremental_field else None, incremental_value)+ resource_config: EndpointResource = {+ "name": endpoint,+ "endpoint": {+ "path": config.path,+ "params": params,+ "data_selector": config.data_key,+ "paginator": _paginator(config),+ },+ }+ if config.excluded_fields:+ resource_config["data_map"] = _drop_fields(config.excluded_fields)+rest_config: RESTAPIConfig = {- "client": _client_config(api_key),- "resources": [- {- "name": endpoint,- "endpoint": {- "path": config.path,- "params": params,- "data_selector": config.data_key,- "paginator": _paginator(config),- },- }- ],+ # Excluded fields are dropped from rows only after HTTP sample capture saw the raw body.+ "client": _client_config(api_key, capture=not config.excluded_fields),+ "resources": [resource_config],}def save_checkpoint(state: Optional[dict[str, Any]]) -> None:diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/incident_io/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/incident_io/settings.pyindex 0603aceb78f3..8c2fd195b862 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/incident_io/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/incident_io/settings.py@@ -1,4 +1,5 @@from dataclasses import dataclass, field+from datetime import timedeltafrom typing import Optionalfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (@@ -7,6 +8,16 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.resfrom products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType+@dataclass(frozen=True)+class EntryWindow:+ """A rolling time window sent as a pair of query params, anchored on the sync's start time."""++ start_param: str+ end_param: str+ lookback: timedelta+ lookahead: timedelta++@dataclass(frozen=True)class IncidentIoEndpointConfig:name: str@@ -18,6 +29,10 @@ class IncidentIoEndpointConfig:# response and accept no pagination params.paginated: bool = Falsepage_size: int = 250+ # None for a paginated endpoint that takes no page-size param.+ page_size_param: Optional[str] = "page_size"+ # Query param the `pagination_meta.after` cursor is replayed as.+ cursor_param: str = "after"primary_keys: list[str] = field(default_factory=lambda: ["id"])# Fields with a documented server-side `<field>[gte]` filter on the list endpoint.# Endpoints without one are full refresh only.@@ -30,6 +45,10 @@ class IncidentIoEndpointConfig:sort_by: Optional[str] = None# Set for endpoints that require a parent id filter and so are fetched once per parent row.fanout: Optional[DependentEndpointConfig] = None+ # Required time window for endpoints that return nothing older than "now" without one.+ entry_window: Optional[EntryWindow] = None+ # Top-level response fields never written to the warehouse, e.g. credentials.+ excluded_fields: tuple[str, ...] = ()@propertydef default_incremental_field(self) -> Optional[str]:@@ -67,6 +86,32 @@ _CUSTOM_FIELD_OPTIONS_FANOUT = DependentEndpointConfig(include_from_parent=[],)+# Schedule entries don't carry their schedule's id, so it's copied from the parent row.+_SCHEDULE_ENTRIES_FANOUT = DependentEndpointConfig(+ parent_name="schedules",+ resolve_param="schedule_id",+ resolve_field="id",+ include_from_parent=["id"],+ parent_field_renames={"id": "schedule_id"},+ parent_params={"page_size": 250},+)++_STATUS_PAGE_INCIDENTS_FANOUT = DependentEndpointConfig(+ parent_name="status_pages",+ resolve_param="status_page_id",+ resolve_field="id",+ include_from_parent=[],+ parent_params={"page_size": 250},+)++# Full refresh re-reads this window on every sync, so shifts older than the lookback drop out of the table.+_SCHEDULE_ENTRIES_WINDOW = EntryWindow(+ start_param="entry_window_start",+ end_param="entry_window_end",+ lookback=timedelta(days=365),+ lookahead=timedelta(days=30),+)+# Alerts and escalations also document `created_at[gte]` filters, but neither endpoint# accepts a sort param and the default ordering is undocumented, so we keep them full@@ -197,6 +242,55 @@ INCIDENT_IO_ENDPOINTS: dict[str, IncidentIoEndpointConfig] = {partition_key="created_at",fanout=_CATALOG_ENTRIES_FANOUT,),+ "schedule_entries": IncidentIoEndpointConfig(+ name="schedule_entries",+ # `{schedule_id}` is bound per parent schedule row by the fan-out.+ path="/v2/schedule_entries?schedule_id={schedule_id}",+ # `final` is the effective rota after overrides are merged in.+ data_key="schedule_entries.final",+ paginated=True,+ page_size_param=None,+ # The next-page cursor replaces the window start; the window end stays fixed.+ cursor_param="entry_window_start",+ # Entries carry no id of their own that the API guarantees; a fingerprint names the shift+ # and an override can split one shift into several entries, so the start time is part of the key.+ primary_keys=["schedule_id", "fingerprint", "start_at"],+ partition_key="start_at",+ fanout=_SCHEDULE_ENTRIES_FANOUT,+ entry_window=_SCHEDULE_ENTRIES_WINDOW,+ ),+ "escalation_paths": IncidentIoEndpointConfig(+ name="escalation_paths",+ path="/v2/escalation_paths",+ data_key="escalation_paths",+ paginated=True,+ page_size=25,+ ),+ "alert_sources": IncidentIoEndpointConfig(+ name="alert_sources",+ path="/v2/alert_sources",+ data_key="alert_sources",+ # The token lets anyone push alerts into the account, so it never reaches the warehouse.+ excluded_fields=("secret_token",),+ ),+ "status_pages": IncidentIoEndpointConfig(+ name="status_pages",+ path="/v2/status_pages",+ data_key="status_pages",+ paginated=True,+ page_size=250,+ ),+ "status_page_incidents": IncidentIoEndpointConfig(+ name="status_page_incidents",+ # `{status_page_id}` is bound per parent status page row by the fan-out.+ path="/v2/status_page_incidents?status_page_id={status_page_id}",+ data_key="status_page_incidents",+ paginated=True,+ page_size=250,+ primary_keys=["status_page_id", "id"],+ partition_key="published_at",+ fanout=_STATUS_PAGE_INCIDENTS_FANOUT,+ ),}ENDPOINTS = tuple(INCIDENT_IO_ENDPOINTS.keys())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/incident_io/tests/test_incident_io.py b/products/warehouse_sources/backend/temporal/data_imports/sources/incident_io/tests/test_incident_io.pyindex 3529fc0cd36f..5f0c8347e443 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/incident_io/tests/test_incident_io.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/incident_io/tests/test_incident_io.py@@ -5,6 +5,7 @@ from typing import Any, castfrom urllib.parse import parse_qs, urlsplitimport pytest+import time_machinefrom unittest import mockfrom requests import Response@@ -234,6 +235,19 @@ class TestValidateCredentials:],True,),+ # Schedule entries take no page-size param, so the child probe sends only the parent id.+ (+ "schedule_entries",+ "schedules",+ [{"id": "S1"}],+ 200,+ [+ "https://api.incident.io/v2/schedules?page_size=1",+ "https://api.incident.io/v2/schedules",+ "https://api.incident.io/v2/schedule_entries?schedule_id=S1",+ ],+ True,+ ),# No parent row to bind, so the child scope can't be probed and the parent probe decides.("catalog_entries",@@ -371,6 +385,16 @@ class TestGetRows:assert [r["id"] for r in rows] == ["01A"]manager.save_state.assert_not_called()+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_alert_sources_drop_secret_token(self, MockSession):+ session = MockSession.return_value+ body = {"alert_sources": [{"id": "01A", "name": "Datadog", "secret_token": "not-a-real-token"}]}+ rows, _ = _source(session, [_response(body)], "alert_sources", _make_manager())++ assert rows == [{"id": "01A", "name": "Datadog"}]+ # The raw body still carries the token, so it must never reach HTTP sample capture.+ assert MockSession.call_args.kwargs["capture"] is False+@mock.patch(CLIENT_SESSION_PATCH)def test_empty_response_yields_no_rows(self, MockSession):session = MockSession.return_value@@ -435,14 +459,23 @@ class TestGetRows:class TestFanout:@pytest.mark.parametrize(- "endpoint, parent_key, child_path, parent_id_param",+ "endpoint, parent_key, child_path, parent_id_param, parent_params",[- ("catalog_entries", "catalog_types", "/v3/catalog_entries", "catalog_type_id"),- ("custom_field_options", "custom_fields", "/v1/custom_field_options", "custom_field_id"),+ ("catalog_entries", "catalog_types", "/v3/catalog_entries", "catalog_type_id", {}),+ ("custom_field_options", "custom_fields", "/v1/custom_field_options", "custom_field_id", {}),+ (+ "status_page_incidents",+ "status_pages",+ "/v2/status_page_incidents",+ "status_page_id",+ {"page_size": 250},+ ),],)@mock.patch(CLIENT_SESSION_PATCH)- def test_fetches_child_pages_per_parent(self, MockSession, endpoint, parent_key, child_path, parent_id_param):+ def test_fetches_child_pages_per_parent(+ self, MockSession, endpoint, parent_key, child_path, parent_id_param, parent_params+ ):session = MockSession.return_valuemanager = _make_manager()urls: list[str] = []@@ -461,14 +494,91 @@ class TestFanout:rows = [row for page in cast("Iterable[Any]", response.items()) for row in page]assert [(r["id"], r[parent_id_param]) for r in rows] == [("C1", "P1"), ("C2", "P1"), ("C3", "P2")]- # The unpaginated parent list takes no params; each child request is bound to its parent.- assert params[0] == {}+ assert params[0] == parent_paramsassert [urlsplit(url).path for url in urls[1:]] == [child_path] * 3assert [parse_qs(urlsplit(url).query)[parent_id_param] for url in urls[1:]] == [["P1"], ["P1"], ["P2"]]assert [p.get("page_size") for p in params[1:]] == [250, 250, 250]assert [p.get("after") for p in params[1:]] == [None, "C1", None]assert manager.save_state.call_args.args[0].fanout_state is not None+ @time_machine.travel(datetime(2026, 3, 1, 12, 0, tzinfo=UTC), tick=False)+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_schedule_entries_page_through_window_per_schedule(self, MockSession):+ session = MockSession.return_value+ urls: list[str] = []++ def _entries_body(final: list[dict[str, Any]], after: str | None) -> dict[str, Any]:+ body: dict[str, Any] = {+ "schedule_entries": {"final": final, "scheduled": [{"fingerprint": "raw"}], "overrides": []}+ }+ if after is not None:+ body["pagination_meta"] = {"after": after, "after_url": "https://api.incident.io/next"}+ return body++ manager = _make_manager()+ params = _wire(+ session,+ [+ _response({"schedules": [{"id": "S1"}, {"id": "S2"}], "pagination_meta": {"page_size": 250}}),+ _response(_entries_body([{"fingerprint": "F1", "start_at": "2026-01-01T00:00:00Z"}], "opaque-1")),+ _response(_entries_body([{"fingerprint": "F2", "start_at": "2026-01-08T00:00:00Z"}], None)),+ _response(_entries_body([{"fingerprint": "F3", "start_at": "2026-01-02T00:00:00Z"}], None)),+ ],+ urls,+ )++ response = incident_io_source(+ "key", "schedule_entries", team_id=1, job_id="j", resumable_source_manager=manager+ )+ rows = [row for page in cast("Iterable[Any]", response.items()) for row in page]++ assert [(r["schedule_id"], r["fingerprint"]) for r in rows] == [("S1", "F1"), ("S1", "F2"), ("S2", "F3")]+ assert params[0] == {"page_size": 250}+ assert [parse_qs(urlsplit(url).query)["schedule_id"] for url in urls[1:]] == [["S1"], ["S1"], ["S2"]]+ # The cursor replaces the window start; the window end stays fixed across pages.+ assert [p.get("entry_window_start") for p in params[1:]] == [+ "2025-03-01T12:00:00Z",+ "opaque-1",+ "2025-03-01T12:00:00Z",+ ]+ assert {p.get("entry_window_end") for p in params[1:]} == {"2026-03-31T12:00:00Z"}+ assert all("page_size" not in p for p in params[1:])+ assert manager.save_state.call_args.args[0].window_params == {+ "entry_window_start": "2025-03-01T12:00:00Z",+ "entry_window_end": "2026-03-31T12:00:00Z",+ }++ @time_machine.travel(datetime(2026, 3, 2, 12, 0, tzinfo=UTC), tick=False)+ @mock.patch(CLIENT_SESSION_PATCH)+ def test_schedule_entries_resume_keeps_original_window(self, MockSession):+ session = MockSession.return_value+ window = {"entry_window_start": "2025-03-01T12:00:00Z", "entry_window_end": "2026-03-31T12:00:00Z"}+ manager = _make_manager(+ IncidentIoResumeConfig(+ fanout_state={+ "completed": [],+ "current": "/v2/schedule_entries?schedule_id=S1",+ "child_state": {"cursor": "opaque-1"},+ },+ window_params=window,+ )+ )+ params = _wire(+ session,+ [+ _response({"schedules": [{"id": "S1"}], "pagination_meta": {"page_size": 250}}),+ _response({"schedule_entries": {"final": [{"fingerprint": "F1"}]}}),+ ],+ )++ response = incident_io_source(+ "key", "schedule_entries", team_id=1, job_id="j", resumable_source_manager=manager+ )+ list(cast("Iterable[Any]", response.items()))++ assert params[1]["entry_window_start"] == "opaque-1"+ assert params[1]["entry_window_end"] == "2026-03-31T12:00:00Z"+class TestIncidentIoSourceResponse:@mock.patch(CLIENT_SESSION_PATCH)@@ -490,7 +600,7 @@ class TestIncidentIoSourceResponse:@pytest.mark.parametrize("config", list(INCIDENT_IO_ENDPOINTS.values()))def test_partition_keys_are_stable_creation_fields(self, config):if config.partition_key:- assert config.partition_key == "created_at"+ assert config.partition_key in {"created_at", "start_at", "published_at"}@pytest.mark.parametrize("config", list(INCIDENT_IO_ENDPOINTS.values()))def test_endpoint_paths_are_versioned(self, config):