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_sources): support incident.io API version v3 (#113229)

Tom Owerse9dd4740ce43
diff --git a/.agents/skills/warehouse-source-new-version/SKILL.md b/.agents/skills/warehouse-source-new-version/SKILL.md
index 9fcfa1f4a7f4..1b73eccd8d14 100644
--- a/.agents/skills/warehouse-source-new-version/SKILL.md
+++ b/.agents/skills/warehouse-source-new-version/SKILL.md
@@ -70,6 +70,7 @@ The opposite gap also occurs: a reference rendered from one version-blind OpenAP
1. Implement the newer version first (steps above) if not already supported. When the version being sunset is the vendor's **terminal** version (the whole product is discontinued and there is no successor to add), per-version deprecation cannot apply — the framework never deprecates a source's sole/default version, and there is no version to repin to. Don't fabricate a successor or relax the invariant to force the metadata: leave `supported_versions`/`default_version` unchanged, document the vendor sunset and the customer off-ramp (move off the source entirely before shutdown) in the PR, and surface whether a source-level whole-product deprecation surface is warranted for a human to decide.
2. Add the old version to `deprecated_versions` with the vendor's announced sunset date (or `sunset_at=None` if none). When the vendor gives only a month ("supported until January 2027"), use the first day of that month: it is the earliest day the version can stop working, so the warning never comes after the vendor stops serving the version. Never deprecate `default_version` — flip the default to the new version in the same PR.
+ The version to deprecate is the source label whose wire reads the retired path, which can differ from the vendor label in the request. A source on the unversioned `v1` label that reads a vendor `/v2/...` endpoint deprecates and repins `v1`. Never declare the vendor's old label just to deprecate it: no row is pinned to it, and the repin would match nothing.
3. The in-product warning banner and API fields light up automatically from the metadata — zero per-source UI work.
4. **Deprecated is not migrated.** Existing pins move only when the vendor has announced the version will stop being served (a sunset/removal date). A deprecation without a sunset date is advisory: mark it, leave every existing pin on it fully supported, and write no migration — repinning working customers off a version the vendor still serves is exactly the silent version move the pinning framework exists to prevent. Two narrow cases still repin under an advisory (`sunset_at=None`) deprecation: the deprecated label resolves to a byte-identical request as the new default (a pure alias — no per-version dispatch — so the repin is not a move), or the vendor already errors on the old version (e.g. `410`/`406`) so leaving pins is worse than moving them. A source that sends a per-version header/URL for a version the vendor still serves is neither — stay advisory. A published fixed support window ("each dated version is supported for N months after release") is an announced sunset: compute `sunset_at` from it, even when that date has already passed, and repin. If the docs do not say how the API answers an expired version, add no rejection signature to `get_non_retryable_errors`.
5. Only for a sunsetting version: include a **written-not-run** migration script that repins affected `ExternalDataSource` rows (`api_version` column) from the deprecated version to the new one, plus any safe data/schema transforms. It must be idempotent and reviewable, and its reverse must be a no-op — repinned rows are indistinguishable from natively-created ones, so a blanket downgrade would clobber legitimate native pins. Repin only rows explicitly on the deprecated version: when the default is already the target (you are deprecating an old label without flipping the default in this PR), do not also repin NULL pins — they already resolve to the current default, so touching them is redundant churn — and leave other still-served deprecated versions alone. Where migration is lossy or unsafe — including when the new version needs credentials that can't be derived from the stored ones — do not script it: document the manual path in the PR. When only a subset of rows is unsafe (the version diverges for one endpoint that needs a credential others don't), split the cohort: script the repin for the safe rows and exclude the unsafe ones by querying their schemas, documenting only that cohort as manual — don't drop the whole migration to manual because one endpoint can't move. Whether a column whose _type_ changes across the versions needs a transform is decided by the schema's sync type, not by the type change: a full-refresh schema drops its table before every sync, so the next run rebuilds it under the newly inferred types and the repin alone is enough, while a merge-based schema carries the old type forward and needs a `reset_pipeline` stamp (delta-rs cannot widen in place, and the automatic resync covers only safe numeric widenings). Do not execute migrations or backfills; humans review and run them.
diff --git a/products/warehouse_sources/backend/migrations/0180_repin_incident_io_api_version_v3.py b/products/warehouse_sources/backend/migrations/0180_repin_incident_io_api_version_v3.py
new file mode 100644
index 000000000000..1735d4d2f7c1
--- /dev/null
+++ b/products/warehouse_sources/backend/migrations/0180_repin_incident_io_api_version_v3.py
@@ -0,0 +1,35 @@
+from django.db import migrations
+
+# incident.io removes GET /v2/follow_ups on 2026-12-31, which the "v1" label reads for the
+# follow_ups table; its successor is GET /v3/follow_ups. The source now defaults new instances to
+# "v3", which reads that successor and keeps every other table on the same path as "v1". This
+# repins existing source-level pins from "v1" to "v3" so their next sync reads the live endpoint.
+# follow_ups is full refresh only and keeps the string `id` primary key, so the next sync rebuilds
+# the table with the new `category` column; the pin is the only thing that needs to move.
+INCIDENT_IO_SOURCE_TYPE = "IncidentIo"
+OLD_VERSION = "v1"
+NEW_VERSION = "v3"
+
+
+def repin_incident_io_v1_to_v3(apps, schema_editor):
+ ExternalDataSource = apps.get_model("warehouse_sources", "ExternalDataSource")
+
+ # Only source-level pins still on the deprecated version move. NULL pins already resolve to
+ # the source's default_version (now "v3"), so they need no update. Filtering on the exact old
+ # value keeps this idempotent — a re-run matches nothing. Schema-level overrides
+ # (ExternalDataSchema.api_version) are intentionally customer-pinned and are left untouched;
+ # the schema-level deprecation warning prompts the user to migrate those.
+ ExternalDataSource.objects.filter(source_type=INCIDENT_IO_SOURCE_TYPE, api_version=OLD_VERSION).update(
+ api_version=NEW_VERSION
+ )
+
+
+class Migration(migrations.Migration):
+ dependencies = [("warehouse_sources", "0179_pin_omnisend_null_api_version_to_v3")]
+
+ operations = [
+ # Reverse is a no-op: once repinned, these rows are indistinguishable from natively-created
+ # v3 rows, so a blanket downgrade would clobber legitimate v3 pins and move customers back
+ # onto an endpoint that stops being served after the sunset.
+ migrations.RunPython(repin_incident_io_v1_to_v3, migrations.RunPython.noop, elidable=False),
+ ]
diff --git a/products/warehouse_sources/backend/migrations/max_migration.txt b/products/warehouse_sources/backend/migrations/max_migration.txt
index 3c919c551000..eef74519a7e0 100644
--- a/products/warehouse_sources/backend/migrations/max_migration.txt
+++ b/products/warehouse_sources/backend/migrations/max_migration.txt
@@ -1 +1 @@
-0179_pin_omnisend_null_api_version_to_v3
+0180_repin_incident_io_api_version_v3
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.py
index f9a7a0098f08..aa45f61a0a32 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
@@ -55,6 +55,7 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"description": "Description of the follow-up action.",
"status": "Current status of the follow-up (e.g. outstanding, completed, deleted).",
"assignee": "The user the follow-up is assigned to.",
+ "category": "The category the follow-up is filed under. Only returned from API version v3.",
"priority": "The priority assigned to the follow-up.",
"external_issue_reference": "Reference to the linked external issue (e.g. Jira, GitHub).",
"completed_at": "Time at which the follow-up was completed.",
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.py
index 0444eb1e2919..05389c4afdf5 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
@@ -25,9 +25,9 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.res
from products.warehouse_sources.backend.temporal.data_imports.sources.common.source_helpers import validate_via_probe
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
from products.warehouse_sources.backend.temporal.data_imports.sources.incident_io.settings import (
- INCIDENT_IO_ENDPOINTS,
EntryWindow,
IncidentIoEndpointConfig,
+ endpoints_for_version,
)
# Single global host — incident.io has no regions or per-account base paths.
@@ -135,14 +135,16 @@ def _probe_headers(api_key: str) -> dict[str, str]:
return {"Authorization": f"Bearer {api_key}", "Accept": "application/json"}
-def _fanout_child_probe_url(api_key: str, config: IncidentIoEndpointConfig) -> Optional[str]:
+def _fanout_child_probe_url(
+ api_key: str, endpoints: dict[str, IncidentIoEndpointConfig], config: IncidentIoEndpointConfig
+) -> Optional[str]:
"""Build a one-row child request bound to a real parent id, or None when there is no parent row.
A fan-out child can have its own scope (catalog entries need `catalog_entries.view`, separate
from `catalog_types.view`), so probing only the parent can pass a key that can't sync the child.
"""
assert config.fanout is not None
- parent = INCIDENT_IO_ENDPOINTS[config.fanout.parent_name]
+ parent = endpoints[config.fanout.parent_name]
try:
response = make_tracked_session(redact_values=(api_key,)).get(
_build_url(parent.path, {}), headers=_probe_headers(api_key), timeout=VALIDATION_TIMEOUT_SECONDS
@@ -188,7 +190,7 @@ def _probe_result(api_key: str, url: str, schema_name: Optional[str]) -> tuple[b
return False, f"incident.io API returned an unexpected response (status {status})."
-def validate_credentials(api_key: str, schema_name: Optional[str] = None) -> tuple[bool, str | None]:
+def validate_credentials(api_key: str, api_version: str, schema_name: Optional[str] = None) -> tuple[bool, str | None]:
"""Probe the API to confirm the key is genuine.
incident.io API keys carry granular per-resource view/list scopes, so a 403 from one
@@ -196,9 +198,10 @@ def validate_credentials(api_key: str, schema_name: Optional[str] = None) -> tup
(``schema_name=None``) we accept 403 — the key authenticated, it's only missing a
scope the user may not need. When validating a specific schema, a 403 is an error.
"""
- config = INCIDENT_IO_ENDPOINTS.get(schema_name or "", INCIDENT_IO_ENDPOINTS["incidents"])
+ endpoints = endpoints_for_version(api_version)
+ config = endpoints.get(schema_name or "", 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
+ probe_config = endpoints[config.fanout.parent_name] if config.fanout is not None else config
params: dict[str, Any] = (
{probe_config.page_size_param: 1} if probe_config.paginated and probe_config.page_size_param else {}
)
@@ -207,7 +210,7 @@ def validate_credentials(api_key: str, schema_name: Optional[str] = None) -> tup
if not is_valid or config.fanout is None:
return is_valid, error
- child_url = _fanout_child_probe_url(api_key, config)
+ child_url = _fanout_child_probe_url(api_key, endpoints, config)
if child_url is None:
return True, None
return _probe_result(api_key, child_url, schema_name)
@@ -244,6 +247,7 @@ def _source_response(config: IncidentIoEndpointConfig, items: Iterable[Any]) ->
def _fanout_source(
api_key: str,
+ endpoints: dict[str, IncidentIoEndpointConfig],
config: IncidentIoEndpointConfig,
team_id: int,
job_id: str,
@@ -251,7 +255,7 @@ def _fanout_source(
) -> SourceResponse:
"""Fetch a parent-scoped endpoint once per row of its parent lookup list."""
assert config.fanout is not None
- parent_config = INCIDENT_IO_ENDPOINTS[config.fanout.parent_name]
+ parent_config = endpoints[config.fanout.parent_name]
initial_paginator_state: Optional[dict[str, Any]] = None
window_params: Optional[dict[str, str]] = None
@@ -275,7 +279,7 @@ def _fanout_source(
resource = cast(
Iterable[Any],
build_dependent_resource(
- endpoint_configs=INCIDENT_IO_ENDPOINTS,
+ endpoint_configs=endpoints,
child_endpoint=config.name,
fanout=config.fanout,
client_config=_client_config(api_key),
@@ -302,13 +306,15 @@ def incident_io_source(
team_id: int,
job_id: str,
resumable_source_manager: ResumableSourceManager[IncidentIoResumeConfig],
+ api_version: str,
should_use_incremental_field: bool = False,
db_incremental_field_last_value: Optional[Any] = None,
incremental_field: str | None = None,
) -> SourceResponse:
- config = INCIDENT_IO_ENDPOINTS[endpoint]
+ endpoints = endpoints_for_version(api_version)
+ config = endpoints[endpoint]
if config.fanout is not None:
- return _fanout_source(api_key, config, team_id, job_id, resumable_source_manager)
+ return _fanout_source(api_key, endpoints, config, team_id, job_id, resumable_source_manager)
initial_paginator_state: Optional[dict[str, Any]] = None
resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else 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.py
index 8c2fd195b862..97b7997f0a3f 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,12 +1,23 @@
+import dataclasses
from dataclasses import dataclass, field
from datetime import timedelta
from typing import Optional
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import UNVERSIONED_API_VERSION
from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.fanout import (
DependentEndpointConfig,
)
from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+# incident.io versions each resource's path on its own track (/v1, /v2, /v3), so the source-level
+# label is opaque: "v1" is the original endpoint set; "v3" moves follow_ups from GET /v2/follow_ups,
+# which incident.io removes on 2026-12-31, to its GET /v3/follow_ups successor. Every other
+# resource reads the same path under both labels.
+INCIDENT_IO_API_VERSION_V1 = UNVERSIONED_API_VERSION
+INCIDENT_IO_API_VERSION_V3 = "v3"
+INCIDENT_IO_SUPPORTED_VERSIONS = (INCIDENT_IO_API_VERSION_V1, INCIDENT_IO_API_VERSION_V3)
+INCIDENT_IO_DEFAULT_API_VERSION = INCIDENT_IO_API_VERSION_V3
+
@dataclass(frozen=True)
class EntryWindow:
@@ -293,6 +304,29 @@ INCIDENT_IO_ENDPOINTS: dict[str, IncidentIoEndpointConfig] = {
),
}
+INCIDENT_IO_ENDPOINTS_V3: dict[str, IncidentIoEndpointConfig] = {
+ **INCIDENT_IO_ENDPOINTS,
+ # Same rows as v2 plus a `category` object, now paged by `pagination_meta.after` with a 250 cap.
+ "follow_ups": dataclasses.replace(INCIDENT_IO_ENDPOINTS["follow_ups"], path="/v3/follow_ups"),
+}
+
+INCIDENT_IO_ENDPOINTS_BY_VERSION: dict[str, dict[str, IncidentIoEndpointConfig]] = {
+ INCIDENT_IO_API_VERSION_V1: INCIDENT_IO_ENDPOINTS,
+ INCIDENT_IO_API_VERSION_V3: INCIDENT_IO_ENDPOINTS_V3,
+}
+
+
+def endpoints_for_version(api_version: str) -> dict[str, IncidentIoEndpointConfig]:
+ # An undeclared pin raises rather than falling back, so a sync never drifts onto another version's paths.
+ try:
+ return INCIDENT_IO_ENDPOINTS_BY_VERSION[api_version]
+ except KeyError as e:
+ raise ValueError(
+ f"Unsupported incident.io API version {api_version!r}; supported: {INCIDENT_IO_SUPPORTED_VERSIONS}"
+ ) from e
+
+
+# The table set is identical across versions, so discovery never orphans a table on repin.
ENDPOINTS = tuple(INCIDENT_IO_ENDPOINTS.keys())
INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/incident_io/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/incident_io/source.py
index 7b2dffab2e3c..b86268e571e7 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/incident_io/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/incident_io/source.py
@@ -1,3 +1,4 @@
+from datetime import date
from typing import Optional, cast
from products.warehouse_sources.backend.facade.source_config import (
@@ -7,7 +8,11 @@ from products.warehouse_sources.backend.facade.source_config import (
SourceFieldInputConfig,
SourceFieldInputConfigType,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import (
+ FieldType,
+ ResumableSource,
+ VersionDeprecation,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
CanonicalDescriptions,
)
@@ -28,14 +33,23 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.incident_i
)
from products.warehouse_sources.backend.temporal.data_imports.sources.incident_io.settings import (
ENDPOINTS,
+ INCIDENT_IO_API_VERSION_V1,
+ INCIDENT_IO_DEFAULT_API_VERSION,
+ INCIDENT_IO_SUPPORTED_VERSIONS,
INCREMENTAL_FIELDS,
)
from products.warehouse_sources.backend.types import ExternalDataSourceType
+FOLLOW_UPS_V2_REMOVED_MESSAGE = "incident.io removed the follow-ups endpoint that API version v1 reads. Contact PostHog support to move this source to API version v3."
+
@SourceRegistry.register
class IncidentIoSource(ResumableSource[IncidentIoSourceConfig, IncidentIoResumeConfig]):
api_docs_url = "https://api-docs.incident.io"
+ supported_versions = INCIDENT_IO_SUPPORTED_VERSIONS
+ default_version = INCIDENT_IO_DEFAULT_API_VERSION
+ # "v1" reads follow-ups from GET /v2/follow_ups, which incident.io removes on 2026-12-31.
+ deprecated_versions = (VersionDeprecation(version=INCIDENT_IO_API_VERSION_V1, sunset_at=date(2026, 12, 31)),)
lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
@@ -54,6 +68,8 @@ class IncidentIoSource(ResumableSource[IncidentIoSourceConfig, IncidentIoResumeC
return {
"401 Client Error: Unauthorized for url: https://api.incident.io": "incident.io authentication failed. Please check that your API key is valid and has not been revoked.",
"403 Client Error: Forbidden for url: https://api.incident.io": "Your incident.io API key is missing a required permission. incident.io API keys have per-resource permissions — grant the key the 'view' scope for the resources you want to sync.",
+ "404 Client Error: Not Found for url: https://api.incident.io/v2/follow_ups": FOLLOW_UPS_V2_REMOVED_MESSAGE,
+ "410 Client Error: Gone for url: https://api.incident.io/v2/follow_ups": FOLLOW_UPS_V2_REMOVED_MESSAGE,
}
@property
@@ -102,7 +118,7 @@ You can create an API key in your [incident.io dashboard](https://app.incident.i
schema_name: Optional[str] = None,
api_version: str | None = None,
) -> tuple[bool, str | None]:
- return validate_incident_io_credentials(config.api_key, schema_name)
+ return validate_incident_io_credentials(config.api_key, self.resolve_api_version(api_version), schema_name)
def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[IncidentIoResumeConfig]:
return ResumableSourceManager[IncidentIoResumeConfig](inputs, IncidentIoResumeConfig)
@@ -119,6 +135,7 @@ You can create an API key in your [incident.io dashboard](https://app.incident.i
team_id=inputs.team_id,
job_id=inputs.job_id,
resumable_source_manager=resumable_source_manager,
+ api_version=self.resolve_api_version(inputs.api_version),
should_use_incremental_field=inputs.should_use_incremental_field,
db_incremental_field_last_value=inputs.db_incremental_field_last_value
if inputs.should_use_incremental_field
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.py
index 5f0c8347e443..7fd463660da1 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
@@ -21,7 +21,11 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.incident_i
)
from products.warehouse_sources.backend.temporal.data_imports.sources.incident_io.settings import (
ENDPOINTS,
+ INCIDENT_IO_API_VERSION_V1,
+ INCIDENT_IO_API_VERSION_V3,
+ INCIDENT_IO_DEFAULT_API_VERSION,
INCIDENT_IO_ENDPOINTS,
+ endpoints_for_version,
)
# RESTClient builds its session via make_tracked_session in the rest_client module.
@@ -74,6 +78,7 @@ def _wire(session: mock.MagicMock, responses: list[Response], urls: list[str] |
def _source(session: mock.MagicMock, responses: list[Response], endpoint: str, manager: mock.MagicMock, **kwargs):
params = _wire(session, responses)
+ kwargs.setdefault("api_version", INCIDENT_IO_DEFAULT_API_VERSION)
response = incident_io_source("key", endpoint, team_id=1, job_id="j", resumable_source_manager=manager, **kwargs)
rows = [row for page in cast("Iterable[Any]", response.items()) for row in page]
return rows, params
@@ -161,7 +166,7 @@ class TestValidateCredentials:
def test_status_mapping_at_source_create(self, mock_session, status_code, expected_valid):
mock_session.return_value.get.return_value = mock.MagicMock(status_code=status_code)
- is_valid, _ = validate_credentials("key")
+ is_valid, _ = validate_credentials("key", INCIDENT_IO_DEFAULT_API_VERSION)
assert is_valid is expected_valid
@@ -178,7 +183,7 @@ class TestValidateCredentials:
def test_status_mapping_with_schema_name(self, mock_session, status_code, expected_valid):
mock_session.return_value.get.return_value = mock.MagicMock(status_code=status_code)
- is_valid, error = validate_credentials("key", schema_name="alerts")
+ is_valid, error = validate_credentials("key", INCIDENT_IO_DEFAULT_API_VERSION, schema_name="alerts")
assert is_valid is expected_valid
if status_code == 403:
@@ -188,22 +193,24 @@ class TestValidateCredentials:
def test_probes_incidents_with_minimal_page_at_source_create(self, mock_session):
mock_session.return_value.get.return_value = mock.MagicMock(status_code=200)
- validate_credentials("key")
+ validate_credentials("key", INCIDENT_IO_DEFAULT_API_VERSION)
url = mock_session.return_value.get.call_args.args[0]
assert url == "https://api.incident.io/v2/incidents?page_size=1"
@pytest.mark.parametrize(
- "schema_name, expected_url",
+ "api_version, schema_name, expected_url",
[
- ("severities", "https://api.incident.io/v1/severities"),
+ (INCIDENT_IO_API_VERSION_V3, "severities", "https://api.incident.io/v1/severities"),
+ (INCIDENT_IO_API_VERSION_V1, "follow_ups", "https://api.incident.io/v2/follow_ups?page_size=1"),
+ (INCIDENT_IO_API_VERSION_V3, "follow_ups", "https://api.incident.io/v3/follow_ups?page_size=1"),
],
)
@mock.patch(INCIDENT_IO_SESSION_PATCH)
- def test_probe_url_per_schema(self, mock_session, schema_name, expected_url):
+ def test_probe_url_per_schema(self, mock_session, api_version, schema_name, expected_url):
mock_session.return_value.get.return_value = mock.MagicMock(status_code=200)
- validate_credentials("key", schema_name=schema_name)
+ validate_credentials("key", api_version, schema_name=schema_name)
url = mock_session.return_value.get.call_args.args[0]
assert url == expected_url
@@ -267,7 +274,7 @@ class TestValidateCredentials:
parent.json.return_value = {parent_key: parent_rows}
mock_session.return_value.get.side_effect = [parent, parent, mock.MagicMock(status_code=child_status)]
- is_valid, error = validate_credentials("key", schema_name=schema_name)
+ is_valid, error = validate_credentials("key", INCIDENT_IO_DEFAULT_API_VERSION, schema_name=schema_name)
assert [call.args[0] for call in mock_session.return_value.get.call_args_list] == expected_urls
assert is_valid is expected_valid
@@ -278,7 +285,7 @@ class TestValidateCredentials:
def test_sends_bearer_auth_header(self, mock_session):
mock_session.return_value.get.return_value = mock.MagicMock(status_code=200)
- validate_credentials("secret-key")
+ validate_credentials("secret-key", INCIDENT_IO_DEFAULT_API_VERSION)
headers = mock_session.return_value.get.call_args.kwargs["headers"]
assert headers["Authorization"] == "Bearer secret-key"
@@ -287,7 +294,7 @@ class TestValidateCredentials:
def test_swallows_network_exceptions(self, mock_session):
mock_session.return_value.get.side_effect = Exception("boom")
- is_valid, error = validate_credentials("key")
+ is_valid, error = validate_credentials("key", INCIDENT_IO_DEFAULT_API_VERSION)
assert is_valid is False
assert error is not None
@@ -315,6 +322,46 @@ class TestGetRows:
manager.save_state.assert_called_once()
assert "after=01B" in manager.save_state.call_args.args[0].next_url
+ @pytest.mark.parametrize(
+ "api_version, expected_path, pages",
+ [
+ # v2 returns every follow-up in one unpaginated response.
+ (INCIDENT_IO_API_VERSION_V1, "/v2/follow_ups", [{"follow_ups": [{"id": "01A"}, {"id": "01B"}]}]),
+ (
+ INCIDENT_IO_API_VERSION_V3,
+ "/v3/follow_ups",
+ [
+ _page_body("follow_ups", [{"id": "01A", "category": {"id": "C1"}}], "01A"),
+ _page_body("follow_ups", [{"id": "01B", "category": None}], None),
+ ],
+ ),
+ ],
+ )
+ @mock.patch(CLIENT_SESSION_PATCH)
+ def test_follow_ups_path_per_version(self, MockSession, api_version, expected_path, pages):
+ session = MockSession.return_value
+ urls: list[str] = []
+ _wire(session, [_response(page) for page in pages], urls)
+
+ response = incident_io_source(
+ "key",
+ "follow_ups",
+ team_id=1,
+ job_id="j",
+ resumable_source_manager=_make_manager(),
+ api_version=api_version,
+ )
+ rows = [row for page in cast("Iterable[Any]", response.items()) for row in page]
+
+ assert [r["id"] for r in rows] == ["01A", "01B"]
+ assert {urlsplit(url).path for url in urls} == {expected_path}
+
+ def test_unknown_api_version_raises(self):
+ with pytest.raises(ValueError, match="Unsupported incident.io API version"):
+ incident_io_source(
+ "key", "follow_ups", team_id=1, job_id="j", resumable_source_manager=_make_manager(), api_version="v2"
+ )
+
@mock.patch(CLIENT_SESSION_PATCH)
def test_incremental_request_includes_filter_and_sort(self, MockSession):
session = MockSession.return_value
@@ -451,7 +498,12 @@ class TestGetRows:
_wire(session, [_response({}, status_code=404)])
response = incident_io_source(
- "key", "incidents", team_id=1, job_id="j", resumable_source_manager=_make_manager()
+ "key",
+ "incidents",
+ team_id=1,
+ job_id="j",
+ resumable_source_manager=_make_manager(),
+ api_version=INCIDENT_IO_DEFAULT_API_VERSION,
)
with pytest.raises(Exception):
[row for page in cast("Iterable[Any]", response.items()) for row in page]
@@ -490,7 +542,14 @@ class TestFanout:
urls,
)
- response = incident_io_source("key", endpoint, team_id=1, job_id="j", resumable_source_manager=manager)
+ response = incident_io_source(
+ "key",
+ endpoint,
+ team_id=1,
+ job_id="j",
+ resumable_source_manager=manager,
+ api_version=INCIDENT_IO_DEFAULT_API_VERSION,
+ )
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")]
@@ -528,7 +587,12 @@ class TestFanout:
)
response = incident_io_source(
- "key", "schedule_entries", team_id=1, job_id="j", resumable_source_manager=manager
+ "key",
+ "schedule_entries",
+ team_id=1,
+ job_id="j",
+ resumable_source_manager=manager,
+ api_version=INCIDENT_IO_DEFAULT_API_VERSION,
)
rows = [row for page in cast("Iterable[Any]", response.items()) for row in page]
@@ -572,7 +636,12 @@ class TestFanout:
)
response = incident_io_source(
- "key", "schedule_entries", team_id=1, job_id="j", resumable_source_manager=manager
+ "key",
+ "schedule_entries",
+ team_id=1,
+ job_id="j",
+ resumable_source_manager=manager,
+ api_version=INCIDENT_IO_DEFAULT_API_VERSION,
)
list(cast("Iterable[Any]", response.items()))
@@ -585,7 +654,14 @@ class TestIncidentIoSourceResponse:
@pytest.mark.parametrize("endpoint", list(ENDPOINTS))
def test_response_metadata_per_endpoint(self, MockSession, endpoint):
config = INCIDENT_IO_ENDPOINTS[endpoint]
- response = incident_io_source("key", endpoint, team_id=1, job_id="j", resumable_source_manager=_make_manager())
+ response = incident_io_source(
+ "key",
+ endpoint,
+ team_id=1,
+ job_id="j",
+ resumable_source_manager=_make_manager(),
+ api_version=INCIDENT_IO_DEFAULT_API_VERSION,
+ )
assert response.name == endpoint
assert response.primary_keys == config.primary_keys
@@ -602,6 +678,13 @@ class TestIncidentIoSourceResponse:
if config.partition_key:
assert config.partition_key in {"created_at", "start_at", "published_at"}
- @pytest.mark.parametrize("config", list(INCIDENT_IO_ENDPOINTS.values()))
+ @pytest.mark.parametrize(
+ "config",
+ [
+ config
+ for version in (INCIDENT_IO_API_VERSION_V1, INCIDENT_IO_API_VERSION_V3)
+ for config in endpoints_for_version(version).values()
+ ],
+ )
def test_endpoint_paths_are_versioned(self, config):
assert config.path.startswith(("/v1/", "/v2/", "/v3/"))
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/incident_io/tests/test_incident_io_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/incident_io/tests/test_incident_io_source.py
index d9b8db5a758e..16bd8522624b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/incident_io/tests/test_incident_io_source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/incident_io/tests/test_incident_io_source.py
@@ -1,4 +1,5 @@
import pytest
+from unittest import mock
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.incidentio import (
IncidentIoSourceConfig,
@@ -6,6 +7,13 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_
from products.warehouse_sources.backend.temporal.data_imports.sources.incident_io.settings import ENDPOINTS
from products.warehouse_sources.backend.temporal.data_imports.sources.incident_io.source import IncidentIoSource
+INCIDENT_IO_SESSION_PATCH = (
+ "products.warehouse_sources.backend.temporal.data_imports.sources.incident_io.incident_io.make_tracked_session"
+)
+INCIDENT_IO_SOURCE_FN_PATCH = (
+ "products.warehouse_sources.backend.temporal.data_imports.sources.incident_io.source.incident_io_source"
+)
+
class TestIncidentIoSource:
def setup_method(self):
@@ -18,6 +26,8 @@ class TestIncidentIoSource:
[
"401 Client Error: Unauthorized for url: https://api.incident.io/v2/incidents?page_size=250",
"403 Client Error: Forbidden for url: https://api.incident.io/v2/alerts",
+ "404 Client Error: Not Found for url: https://api.incident.io/v2/follow_ups?page_size=250",
+ "410 Client Error: Gone for url: https://api.incident.io/v2/follow_ups?page_size=250",
],
)
def test_non_retryable_errors_match_auth_failures(self, observed_error):
@@ -29,6 +39,7 @@ class TestIncidentIoSource:
[
"401 Client Error: Unauthorized for url: https://api.stripe.com/v1/customers",
"500 Server Error for url: https://api.incident.io/v2/incidents",
+ "404 Client Error: Not Found for url: https://api.incident.io/v3/follow_ups?page_size=250",
],
)
def test_non_retryable_errors_does_not_match_unrelated(self, other_vendor_error):
@@ -42,3 +53,28 @@ class TestIncidentIoSource:
incremental = {schema.name for schema in schemas if schema.supports_incremental}
# Only the incidents list exposes server-side timestamp filters with a sortable order.
assert incremental == {"incidents"}
+
+ @pytest.mark.parametrize(
+ "pinned, expected_url",
+ [
+ (None, "https://api.incident.io/v3/follow_ups?page_size=1"),
+ ("v3", "https://api.incident.io/v3/follow_ups?page_size=1"),
+ ("v1", "https://api.incident.io/v2/follow_ups?page_size=1"),
+ ],
+ )
+ @mock.patch(INCIDENT_IO_SESSION_PATCH)
+ def test_validate_credentials_probes_the_pinned_version(self, mock_session, pinned, expected_url):
+ mock_session.return_value.get.return_value = mock.MagicMock(status_code=200)
+
+ self.source.validate_credentials(self.config, self.team_id, schema_name="follow_ups", api_version=pinned)
+
+ assert mock_session.return_value.get.call_args.args[0] == expected_url
+
+ @pytest.mark.parametrize("pinned", ["v1", "v3"])
+ @mock.patch(INCIDENT_IO_SOURCE_FN_PATCH)
+ def test_source_for_pipeline_passes_the_pinned_version(self, mock_source_fn, pinned):
+ inputs = mock.MagicMock(api_version=pinned, schema_name="follow_ups")
+
+ self.source.source_for_pipeline(self.config, mock.MagicMock(), inputs)
+
+ assert mock_source_fn.call_args.kwargs["api_version"] == pinned