: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): implement pagerduty import source (#61154)
Tom Owers314a25036baa
diff --git a/posthog/session_recordings/queries/test/listing_recordings/__snapshots__/test_session_recording_list_from_query.ambr b/posthog/session_recordings/queries/test/listing_recordings/__snapshots__/test_session_recording_list_from_query.ambrindex 800a3fff4b5e..4d81dc6a2021 100644--- a/posthog/session_recordings/queries/test/listing_recordings/__snapshots__/test_session_recording_list_from_query.ambr+++ b/posthog/session_recordings/queries/test/listing_recordings/__snapshots__/test_session_recording_list_from_query.ambr@@ -1122,7 +1122,7 @@WHERE and(equals(s.team_id, 99999), greaterOrEquals(s.min_first_timestamp, toDateTime64('2020-12-29 00:00:00.000000', 6, 'UTC')), lessOrEquals(s.min_first_timestamp, toDateTime64('today', 6, 'UTC')), globalIn(s.session_id,(SELECT nullIf(nullIf(events.`$session_id`, ''), 'null') AS session_idFROM events- WHERE and(equals(events.team_id, 99999), notEmpty(nullIf(nullIf(events.`$session_id`, ''), 'null')), lessOrEquals(events.timestamp, now64(6, 'UTC')), ifNull(equals(replaceRegexpAll(nullIf(nullIf(JSONExtractRaw(events.person_properties, 'email'), ''), 'null'), '^"|"$', ''), 'bla'), 0), greaterOrEquals(events.timestamp, toDateTime64('2020-12-28 00:00:00.000000', 6, 'UTC')))+ WHERE and(equals(events.team_id, 99999), notEmpty(nullIf(nullIf(events.`$session_id`, ''), 'null')), lessOrEquals(events.timestamp, now64(6, 'UTC')), equals(events.mat_pp_email, 'bla'), greaterOrEquals(events.timestamp, toDateTime64('2020-12-28 00:00:00.000000', 6, 'UTC')))GROUP BY nullIf(nullIf(events.`$session_id`, ''), 'null')HAVING 1ORDER BY min(toTimeZone(events.timestamp, 'UTC')) DESCdiff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.mdindex d8a9f98b039b..6b41fee1dabd 100644--- a/posthog/temporal/data_imports/sources/SOURCES.md+++ b/posthog/temporal/data_imports/sources/SOURCES.md@@ -74,6 +74,7 @@ the row lists both.| mssql | DB protocol | pyodbc / pymssql | ➖ || mysql | DB protocol | pymysql | ➖ || paddle | HTTP | requests | ✅ |+| pagerduty | HTTP | requests | ✅ || pinterest_ads | HTTP | requests | ✅ || plain | HTTP | requests | ✅ || polar | HTTP | requests | ✅ |diff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.pyindex 4ea74c7ecc8f..149ce0608573 100644--- a/posthog/temporal/data_imports/sources/generated_configs.py+++ b/posthog/temporal/data_imports/sources/generated_configs.py@@ -587,7 +587,7 @@ class PaddleSourceConfig(config.Config):@config.configclass PagerDutySourceConfig(config.Config):- pass+ api_token: str@config.configdiff --git a/posthog/temporal/data_imports/sources/pagerduty/pagerduty.py b/posthog/temporal/data_imports/sources/pagerduty/pagerduty.pynew file mode 100644index 000000000000..c55a3c8c4bec--- /dev/null+++ b/posthog/temporal/data_imports/sources/pagerduty/pagerduty.py@@ -0,0 +1,196 @@+import dataclasses+from collections.abc import Iterator+from datetime import UTC, date, datetime+from typing import Any, Optional+from urllib.parse import urlencode++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from posthog.temporal.data_imports.sources.common.http import make_tracked_session+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.pagerduty.settings import PAGERDUTY_ENDPOINTS, PagerDutyEndpointConfig++PAGERDUTY_BASE_URL = "https://api.pagerduty.com"++# PagerDuty's max page size is 100; the default is 25.+PAGE_SIZE = 100++# PagerDuty rejects requests where `offset + limit` exceeds 10,000 with an HTTP 400.+# Stop paginating before we cross it. Incremental endpoints stay well under this because+# the `since` filter bounds the window; full-refresh endpoints could in theory truncate+# on very large accounts (logged when it happens).+MAX_OFFSET = 10_000++# Retry/throttle settings kept near the top for easy tuning.+RETRY_ATTEMPTS = 5+REQUEST_TIMEOUT_SECONDS = 60+++class PagerDutyRetryableError(Exception):+ pass+++class PagerDutyResumeConfig:+ offset: int+++def _format_incremental_value(value: Any) -> str:+ """Format an incremental field value as an ISO 8601 string for PagerDuty's `since` filter."""+ if isinstance(value, datetime):+ utc_value = value.astimezone(UTC) if value.tzinfo else value.replace(tzinfo=UTC)+ return utc_value.isoformat()+ if isinstance(value, date):+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC).isoformat()+ return str(value)+++def _get_headers(api_token: str) -> dict[str, str]:+ return {+ "Authorization": f"Token token={api_token}",+ "Accept": "application/vnd.pagerduty+json;version=2",+ "Content-Type": "application/json",+ }+++def _build_params(+ config: PagerDutyEndpointConfig,+ offset: int,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+) -> dict[str, Any]:+ params: dict[str, Any] = {"limit": PAGE_SIZE, "offset": offset}++ if config.supports_since:+ # created_at is immutable, so an ascending sort means new rows append to the end+ # and never shift pages we've already read. We send this on every sync (not just+ # incremental ones) so full refreshes paginate over a stable ordering too.+ params["sort_by"] = "created_at:asc"+ if should_use_incremental_field and db_incremental_field_last_value:+ params["since"] = _format_incremental_value(db_incremental_field_last_value)++ return params+++def validate_credentials(api_token: str, endpoint: Optional[str] = None) -> tuple[bool, int, str | None]:+ """Probe PagerDuty with a cheap single-row request.++ Returns ``(ok, status_code, error_message)``. ``status_code`` is 0 on transport failure.+ The caller decides how to treat 403 (valid token, missing scope for the probed endpoint).+ """+ config = PAGERDUTY_ENDPOINTS.get(endpoint) if endpoint else None+ path = config.path if config else "/users"+ url = f"{PAGERDUTY_BASE_URL}{path}?{urlencode({'limit': 1})}"++ try:+ response = make_tracked_session().get(url, headers=_get_headers(api_token), timeout=10)+ except requests.exceptions.RequestException as e:+ return False, 0, str(e)++ if response.status_code == 200:+ return True, 200, None+ if response.status_code == 401:+ return False, 401, "Invalid PagerDuty API key"+ if response.status_code == 403:+ return False, 403, "Your PagerDuty API key does not have access to this resource"++ try:+ message = response.json().get("error", {}).get("message", response.text)+ except Exception:+ message = response.text+ return False, response.status_code, message+++def get_rows(+ api_token: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[PagerDutyResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+) -> Iterator[Any]:+ config = PAGERDUTY_ENDPOINTS[endpoint]+ headers = _get_headers(api_token)++ resume_config = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ offset = resume_config.offset if resume_config is not None else 0+ if resume_config is not None:+ logger.debug(f"PagerDuty: resuming {endpoint} from offset {offset}")++ @retry(+ retry=retry_if_exception_type((PagerDutyRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(RETRY_ATTEMPTS),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+ )+ def fetch_page(page_offset: int) -> dict:+ params = _build_params(config, page_offset, should_use_incremental_field, db_incremental_field_last_value)+ url = f"{PAGERDUTY_BASE_URL}{config.path}?{urlencode(params)}"+ response = make_tracked_session().get(url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)++ if response.status_code == 429 or response.status_code >= 500:+ raise PagerDutyRetryableError(f"PagerDuty API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"PagerDuty API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ return response.json()++ while True:+ data = fetch_page(offset)++ items = data.get(config.envelope_key, [])+ if not items:+ break++ yield items++ if not data.get("more", False):+ break++ offset += PAGE_SIZE+ if offset + PAGE_SIZE > MAX_OFFSET:+ logger.warning(+ f"PagerDuty: reached max offset {MAX_OFFSET} for endpoint '{endpoint}'; "+ f"stopping pagination (results may be truncated)"+ )+ break++ # Save AFTER yielding so a crash re-fetches the last page; merge dedupes on primary key.+ resumable_source_manager.save_state(PagerDutyResumeConfig(offset=offset))+++def pagerduty_source(+ api_token: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[PagerDutyResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+) -> SourceResponse:+ config = PAGERDUTY_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_token=api_token,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=should_use_incremental_field,+ db_incremental_field_last_value=db_incremental_field_last_value,+ ),+ primary_keys=[config.primary_key],+ # We always request created_at ascending where a sort is available, and full-refresh+ # endpoints replace wholesale, so ascending is correct everywhere.+ sort_mode="asc",+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if config.partition_key else None,+ partition_format="week" if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ )diff --git a/posthog/temporal/data_imports/sources/pagerduty/settings.py b/posthog/temporal/data_imports/sources/pagerduty/settings.pynew file mode 100644index 000000000000..39a027698fe3--- /dev/null+++ b/posthog/temporal/data_imports/sources/pagerduty/settings.py@@ -0,0 +1,83 @@+from dataclasses import dataclass, field+from typing import Optional++from products.data_warehouse.backend.types import IncrementalField, IncrementalFieldType+++@dataclass+class PagerDutyEndpointConfig:+ path: str # Path under the API base URL, e.g. "/incidents"+ envelope_key: str # Key the list of objects is wrapped under in the response body+ primary_key: str = "id"+ partition_key: Optional[str] = None # Stable datetime field used to partition (never a mutable field)+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # True only when the endpoint exposes a server-side `since` filter on created_at AND+ # accepts a `sort_by=created_at:asc` ordering we control. Both are required for safe+ # incremental sync: the filter bounds the window, the sort guarantees a stable+ # ascending watermark. Endpoints without a controllable sort stay full-refresh so the+ # cursor can't advance past unread rows.+ supports_since: bool = False+++_CREATED_AT_INCREMENTAL: list[IncrementalField] = [+ {+ "label": "created_at",+ "type": IncrementalFieldType.DateTime,+ "field": "created_at",+ "field_type": IncrementalFieldType.DateTime,+ },+]+++PAGERDUTY_ENDPOINTS: dict[str, PagerDutyEndpointConfig] = {+ "incidents": PagerDutyEndpointConfig(+ path="/incidents",+ envelope_key="incidents",+ partition_key="created_at",+ incremental_fields=_CREATED_AT_INCREMENTAL,+ # `since`/`until` filter incidents by created_at and `sort_by=created_at:asc` is+ # supported, so incremental sync is safe. Note this only picks up newly *created*+ # incidents — status changes to incidents created before the cursor are not+ # re-fetched (PagerDuty's REST filters key on created_at, not updated_at). Webhooks+ # would be needed for true change capture.+ supports_since=True,+ ),+ "log_entries": PagerDutyEndpointConfig(+ path="/log_entries",+ envelope_key="log_entries",+ partition_key="created_at",+ # `/log_entries` accepts a `since` filter but exposes no controllable sort param, so+ # we can't guarantee an ascending watermark. Ship full refresh rather than risk the+ # cursor advancing past unread rows.+ ),+ "services": PagerDutyEndpointConfig(+ path="/services",+ envelope_key="services",+ ),+ "users": PagerDutyEndpointConfig(+ path="/users",+ envelope_key="users",+ ),+ "teams": PagerDutyEndpointConfig(+ path="/teams",+ envelope_key="teams",+ ),+ "escalation_policies": PagerDutyEndpointConfig(+ path="/escalation_policies",+ envelope_key="escalation_policies",+ ),+ "schedules": PagerDutyEndpointConfig(+ path="/schedules",+ envelope_key="schedules",+ ),+ "priorities": PagerDutyEndpointConfig(+ path="/priorities",+ envelope_key="priorities",+ ),+ "vendors": PagerDutyEndpointConfig(+ path="/vendors",+ envelope_key="vendors",+ ),+}++ENDPOINTS = tuple(PAGERDUTY_ENDPOINTS.keys())diff --git a/posthog/temporal/data_imports/sources/pagerduty/source.py b/posthog/temporal/data_imports/sources/pagerduty/source.pyindex dd4fb57109c7..25823b70c469 100644--- a/posthog/temporal/data_imports/sources/pagerduty/source.py+++ b/posthog/temporal/data_imports/sources/pagerduty/source.py@@ -1,19 +1,31 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from posthog.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs, SourceResponse+from posthog.temporal.data_imports.sources.common.base import FieldType, ResumableSourcefrom posthog.temporal.data_imports.sources.common.registry import SourceRegistry+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.common.schema import SourceSchemafrom posthog.temporal.data_imports.sources.generated_configs import PagerDutySourceConfig+from posthog.temporal.data_imports.sources.pagerduty.pagerduty import (+ PagerDutyResumeConfig,+ pagerduty_source,+ validate_credentials as validate_pagerduty_credentials,+)+from posthog.temporal.data_imports.sources.pagerduty.settings import ENDPOINTS, PAGERDUTY_ENDPOINTSfrom products.data_warehouse.backend.types import ExternalDataSourceType@SourceRegistry.register-class PagerDutySource(SimpleSource[PagerDutySourceConfig]):+class PagerDutySource(ResumableSource[PagerDutySourceConfig, PagerDutyResumeConfig]):@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.PAGERDUTY@@ -23,7 +35,86 @@ class PagerDutySource(SimpleSource[PagerDutySourceConfig]):return SourceConfig(name=SchemaExternalDataSourceType.PAGER_DUTY,label="PagerDuty",- iconPath="/static/services/pagerduty.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ caption="""Enter your PagerDuty REST API key to pull your PagerDuty data into the PostHog Data warehouse.++You can create a read-only API key in your PagerDuty account under **Integrations → API Access Keys**. Select the **Read-only** option — that's all this source needs.""",+ iconPath="/static/services/pagerduty.svg",+ docsUrl="https://posthog.com/docs/cdp/sources/pagerduty",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_token",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ releaseStatus=ReleaseStatus.ALPHA,+ )++ def get_schemas(+ self,+ config: PagerDutySourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ schemas = [+ SourceSchema(+ name=endpoint,+ supports_incremental=PAGERDUTY_ENDPOINTS[endpoint].supports_since,+ supports_append=False,+ incremental_fields=PAGERDUTY_ENDPOINTS[endpoint].incremental_fields,+ )+ for endpoint in ENDPOINTS+ ]+ if names is not None:+ names_set = set(names)+ schemas = [s for s in schemas if s.name in names_set]+ return schemas++ def validate_credentials(+ self, config: PagerDutySourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ ok, status, error = validate_pagerduty_credentials(config.api_token, schema_name)+ if ok:+ return True, None++ # A valid token may legitimately lack scope for a specific endpoint. Accept 403 at+ # source-create (schema_name is None) so users can connect with a key scoped to only+ # the resources they want; re-raise it for per-schema checks.+ if status == 403 and schema_name is None:+ return True, None++ return False, error++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error: Unauthorized for url: https://api.pagerduty.com": "Your PagerDuty API key is invalid or expired. Please generate a new key and reconnect.",+ "403 Client Error: Forbidden for url: https://api.pagerduty.com": "Your PagerDuty API key does not have the required permissions. Please check the key's access and try again.",+ }++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[PagerDutyResumeConfig]:+ return ResumableSourceManager[PagerDutyResumeConfig](inputs, PagerDutyResumeConfig)++ def source_for_pipeline(+ self,+ config: PagerDutySourceConfig,+ resumable_source_manager: ResumableSourceManager[PagerDutyResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return pagerduty_source(+ api_token=config.api_token,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,+ 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+ else None,)diff --git a/posthog/temporal/data_imports/sources/pagerduty/tests/test_pagerduty.py b/posthog/temporal/data_imports/sources/pagerduty/tests/test_pagerduty.pynew file mode 100644index 000000000000..cb1d8f151546--- /dev/null+++ b/posthog/temporal/data_imports/sources/pagerduty/tests/test_pagerduty.py@@ -0,0 +1,240 @@+from datetime import UTC, date, datetime+from typing import Any, Optional++import pytest+from unittest.mock import MagicMock, patch++import requests++from posthog.temporal.data_imports.sources.pagerduty.pagerduty import (+ PAGE_SIZE,+ PagerDutyResumeConfig,+ _build_params,+ _format_incremental_value,+ _get_headers,+ get_rows,+ pagerduty_source,+ validate_credentials,+)+from posthog.temporal.data_imports.sources.pagerduty.settings import PAGERDUTY_ENDPOINTS++PAGERDUTY_MODULE = "posthog.temporal.data_imports.sources.pagerduty.pagerduty"+++class FakeResumableManager:+ """In-memory stand-in for ResumableSourceManager that records saved state."""++ def __init__(self, resume_state: Optional[PagerDutyResumeConfig] = None) -> None:+ self._resume_state = resume_state+ self.saved_states: list[PagerDutyResumeConfig] = []++ def can_resume(self) -> bool:+ return self._resume_state is not None++ def load_state(self) -> Optional[PagerDutyResumeConfig]:+ return self._resume_state++ def save_state(self, data: PagerDutyResumeConfig) -> None:+ self.saved_states.append(data)+++def _mock_response(status_code: int = 200, body: Any = None, text: str = "") -> MagicMock:+ response = MagicMock()+ response.status_code = status_code+ response.ok = 200 <= status_code < 300+ response.text = text+ response.json.return_value = body if body is not None else {}+ if not response.ok:+ error_response = requests.Response()+ error_response.status_code = status_code+ response.raise_for_status.side_effect = requests.HTTPError(+ f"{status_code} Client Error: error for url: https://api.pagerduty.com", response=error_response+ )+ return response+++def _patch_session(get_side_effect: Any) -> Any:+ session = MagicMock()+ session.get.side_effect = get_side_effect+ return patch(f"{PAGERDUTY_MODULE}.make_tracked_session", return_value=session), session+++class TestFormatIncrementalValue:+ @pytest.mark.parametrize(+ "value,expected",+ [+ (datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04T02:58:14+00:00"),+ (datetime(2026, 3, 4, 2, 58, 14), "2026-03-04T02:58:14+00:00"),+ (date(2026, 3, 4), "2026-03-04T00:00:00+00:00"),+ ("already-a-cursor", "already-a-cursor"),+ ],+ )+ def test_format(self, value: Any, expected: str) -> None:+ assert _format_incremental_value(value) == expected+++class TestHeaders:+ def test_token_auth_header(self) -> None:+ headers = _get_headers("tok_abc")+ assert headers["Authorization"] == "Token token=tok_abc"+ assert headers["Accept"] == "application/vnd.pagerduty+json;version=2"+++class TestBuildParams:+ def test_full_refresh_incremental_endpoint_sends_stable_sort_only(self) -> None:+ params = _build_params(+ PAGERDUTY_ENDPOINTS["incidents"],+ offset=0,+ should_use_incremental_field=False,+ db_incremental_field_last_value=None,+ )+ assert params == {"limit": PAGE_SIZE, "offset": 0, "sort_by": "created_at:asc"}++ def test_incremental_endpoint_sends_since(self) -> None:+ params = _build_params(+ PAGERDUTY_ENDPOINTS["incidents"],+ offset=200,+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 1, 1, tzinfo=UTC),+ )+ assert params["offset"] == 200+ assert params["sort_by"] == "created_at:asc"+ assert params["since"] == "2026-01-01T00:00:00+00:00"++ def test_non_incremental_endpoint_has_no_sort_or_since(self) -> None:+ params = _build_params(+ PAGERDUTY_ENDPOINTS["users"],+ offset=0,+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 1, 1, tzinfo=UTC),+ )+ assert params == {"limit": PAGE_SIZE, "offset": 0}+++class TestValidateCredentials:+ @pytest.mark.parametrize(+ "status_code,expected_ok,expected_status",+ [+ (200, True, 200),+ (401, False, 401),+ (403, False, 403),+ (500, False, 500),+ ],+ )+ def test_status_mapping(self, status_code: int, expected_ok: bool, expected_status: int) -> None:+ ctx, _ = _patch_session([_mock_response(status_code, body={}, text="boom")])+ with ctx:+ ok, status, _error = validate_credentials("tok")+ assert ok is expected_ok+ assert status == expected_status++ def test_transport_failure_returns_zero_status(self) -> None:+ ctx, _ = _patch_session(requests.ConnectionError("no network"))+ with ctx:+ ok, status, error = validate_credentials("tok")+ assert ok is False+ assert status == 0+ assert error == "no network"++ def test_uses_endpoint_path_when_schema_given(self) -> None:+ ctx, session = _patch_session([_mock_response(200)])+ with ctx:+ validate_credentials("tok", endpoint="incidents")+ called_url = session.get.call_args.args[0]+ assert called_url.startswith("https://api.pagerduty.com/incidents?")+++class TestGetRows:+ def test_paginates_and_yields_lists_of_dicts(self) -> None:+ page1 = _mock_response(200, body={"incidents": [{"id": "1"}, {"id": "2"}], "more": True})+ page2 = _mock_response(200, body={"incidents": [{"id": "3"}], "more": False})+ manager = FakeResumableManager()++ ctx, session = _patch_session([page1, page2])+ with ctx:+ batches = list(+ get_rows("tok", "incidents", MagicMock(), manager) # type: ignore[arg-type]+ )++ assert batches == [[{"id": "1"}, {"id": "2"}], [{"id": "3"}]]+ assert session.get.call_count == 2++ def test_saves_state_after_yielding_each_page(self) -> None:+ page1 = _mock_response(200, body={"incidents": [{"id": "1"}], "more": True})+ page2 = _mock_response(200, body={"incidents": [{"id": "2"}], "more": False})+ manager = FakeResumableManager()++ ctx, _ = _patch_session([page1, page2])+ with ctx:+ list(get_rows("tok", "incidents", MagicMock(), manager)) # type: ignore[arg-type]++ # State is checkpointed once (the next offset) after the first page is yielded;+ # the final page sets more=False so no further checkpoint is written.+ assert [s.offset for s in manager.saved_states] == [PAGE_SIZE]++ def test_advances_offset_between_pages(self) -> None:+ page1 = _mock_response(200, body={"incidents": [{"id": "1"}], "more": True})+ page2 = _mock_response(200, body={"incidents": [{"id": "2"}], "more": False})+ manager = FakeResumableManager()++ ctx, session = _patch_session([page1, page2])+ with ctx:+ list(get_rows("tok", "incidents", MagicMock(), manager)) # type: ignore[arg-type]++ first_url = session.get.call_args_list[0].args[0]+ second_url = session.get.call_args_list[1].args[0]+ assert "offset=0" in first_url+ assert f"offset={PAGE_SIZE}" in second_url++ def test_resumes_from_saved_offset(self) -> None:+ manager = FakeResumableManager(resume_state=PagerDutyResumeConfig(offset=PAGE_SIZE))+ page = _mock_response(200, body={"incidents": [{"id": "x"}], "more": False})++ ctx, session = _patch_session([page])+ with ctx:+ list(get_rows("tok", "incidents", MagicMock(), manager)) # type: ignore[arg-type]++ assert f"offset={PAGE_SIZE}" in session.get.call_args_list[0].args[0]++ def test_empty_page_stops_iteration(self) -> None:+ page = _mock_response(200, body={"incidents": [], "more": True})+ manager = FakeResumableManager()++ ctx, session = _patch_session([page])+ with ctx:+ batches = list(get_rows("tok", "incidents", MagicMock(), manager)) # type: ignore[arg-type]++ assert batches == []+ assert session.get.call_count == 1++ def test_uses_envelope_key_per_endpoint(self) -> None:+ page = _mock_response(200, body={"services": [{"id": "svc_1"}], "more": False})+ manager = FakeResumableManager()++ ctx, _ = _patch_session([page])+ with ctx:+ batches = list(get_rows("tok", "services", MagicMock(), manager)) # type: ignore[arg-type]++ assert batches == [[{"id": "svc_1"}]]+++class TestPagerDutySourceResponse:+ def test_incidents_partitioned_on_created_at(self) -> None:+ response = pagerduty_source("tok", "incidents", MagicMock(), MagicMock())+ assert response.primary_keys == ["id"]+ assert response.partition_keys == ["created_at"]+ assert response.partition_mode == "datetime"+ assert response.sort_mode == "asc"++ def test_unpartitioned_endpoint_has_no_partition_settings(self) -> None:+ response = pagerduty_source("tok", "users", MagicMock(), MagicMock())+ assert response.primary_keys == ["id"]+ assert response.partition_keys is None+ assert response.partition_mode is None++ @pytest.mark.parametrize("endpoint", list(PAGERDUTY_ENDPOINTS.keys()))+ def test_every_endpoint_builds_a_response(self, endpoint: str) -> None:+ response = pagerduty_source("tok", endpoint, MagicMock(), MagicMock())+ assert response.name == endpoint+ assert response.primary_keys == [PAGERDUTY_ENDPOINTS[endpoint].primary_key]+ assert callable(response.items)diff --git a/posthog/temporal/data_imports/sources/pagerduty/tests/test_pagerduty_source.py b/posthog/temporal/data_imports/sources/pagerduty/tests/test_pagerduty_source.pynew file mode 100644index 000000000000..b9f5cde5e736--- /dev/null+++ b/posthog/temporal/data_imports/sources/pagerduty/tests/test_pagerduty_source.py@@ -0,0 +1,147 @@+import pytest+from unittest.mock import MagicMock, patch++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.pagerduty.pagerduty import PagerDutyResumeConfig+from posthog.temporal.data_imports.sources.pagerduty.settings import ENDPOINTS+from posthog.temporal.data_imports.sources.pagerduty.source import PagerDutySource++from products.data_warehouse.backend.types import ExternalDataSourceType, IncrementalFieldType++PAGERDUTY_MODULE = "posthog.temporal.data_imports.sources.pagerduty"+++class TestPagerDutySource:+ def setup_method(self) -> None:+ self.source = PagerDutySource()+ self.config = MagicMock(api_token="tok_123")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.PAGERDUTY++ def test_source_config_shape(self) -> None:+ config = self.source.get_source_config++ assert config.label == "PagerDuty"+ assert config.iconPath == "/static/services/pagerduty.svg"+ assert not config.unreleasedSource+ assert config.releaseStatus == ReleaseStatus.ALPHA++ assert config.fields is not None+ assert len(config.fields) == 1+ field = config.fields[0]+ assert isinstance(field, SourceFieldInputConfig)+ assert field.name == "api_token"+ assert field.type == SourceFieldInputConfigType.PASSWORD+ assert field.required is True+ assert field.secret is True++ def test_get_schemas_lists_all_endpoints(self) -> None:+ schemas = self.source.get_schemas(self.config, team_id=1)+ assert {s.name for s in schemas} == set(ENDPOINTS)++ def test_only_incidents_supports_incremental(self) -> None:+ schemas = {s.name: s for s in self.source.get_schemas(self.config, team_id=1)}++ assert schemas["incidents"].supports_incremental is True+ assert schemas["incidents"].incremental_fields[0]["field"] == "created_at"+ assert schemas["incidents"].incremental_fields[0]["field_type"] == IncrementalFieldType.DateTime++ for name in ENDPOINTS:+ if name == "incidents":+ continue+ assert schemas[name].supports_incremental is False, name+ assert schemas[name].incremental_fields == [], name++ def test_no_endpoint_supports_append(self) -> None:+ # PagerDuty incidents mutate after creation, so append-only mode is never offered.+ schemas = self.source.get_schemas(self.config, team_id=1)+ assert all(s.supports_append is False for s in schemas)++ def test_get_schemas_filters_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, team_id=1, names=["incidents", "services"])+ assert {s.name for s in schemas} == {"incidents", "services"}++ @pytest.mark.parametrize(+ "pattern",+ [+ "401 Client Error: Unauthorized for url: https://api.pagerduty.com",+ "403 Client Error: Forbidden for url: https://api.pagerduty.com",+ ],+ )+ def test_non_retryable_errors_includes_pattern(self, pattern: str) -> None:+ assert pattern in self.source.get_non_retryable_errors()++ def test_validate_credentials_success(self) -> None:+ with patch(f"{PAGERDUTY_MODULE}.source.validate_pagerduty_credentials", return_value=(True, 200, None)):+ assert self.source.validate_credentials(self.config, team_id=1) == (True, None)++ def test_validate_credentials_invalid_token(self) -> None:+ with patch(+ f"{PAGERDUTY_MODULE}.source.validate_pagerduty_credentials",+ return_value=(False, 401, "Invalid PagerDuty API key"),+ ):+ ok, error = self.source.validate_credentials(self.config, team_id=1)+ assert ok is False+ assert error == "Invalid PagerDuty API key"++ def test_validate_credentials_accepts_403_at_source_create(self) -> None:+ # A valid token may only be scoped to a subset of resources; don't block connection.+ with patch(+ f"{PAGERDUTY_MODULE}.source.validate_pagerduty_credentials",+ return_value=(False, 403, "Your PagerDuty API key does not have access to this resource"),+ ):+ assert self.source.validate_credentials(self.config, team_id=1, schema_name=None) == (True, None)++ def test_validate_credentials_rejects_403_for_specific_schema(self) -> None:+ with patch(+ f"{PAGERDUTY_MODULE}.source.validate_pagerduty_credentials",+ return_value=(False, 403, "Your PagerDuty API key does not have access to this resource"),+ ):+ ok, error = self.source.validate_credentials(self.config, team_id=1, schema_name="incidents")+ assert ok is False+ assert error == "Your PagerDuty API key does not have access to this resource"++ def test_get_resumable_source_manager_binds_resume_config(self) -> None:+ inputs = MagicMock(team_id=1, job_id="job_1", logger=MagicMock())+ manager = self.source.get_resumable_source_manager(inputs)+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is PagerDutyResumeConfig++ def test_source_for_pipeline_plumbs_arguments(self) -> None:+ manager = MagicMock()+ inputs = MagicMock(+ schema_name="incidents",+ should_use_incremental_field=True,+ db_incremental_field_last_value="2026-01-01T00:00:00+00:00",+ logger=MagicMock(),+ )++ with patch(f"{PAGERDUTY_MODULE}.source.pagerduty_source") as mock_source:+ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_source.assert_called_once()+ kwargs = mock_source.call_args.kwargs+ assert kwargs["api_token"] == "tok_123"+ assert kwargs["endpoint"] == "incidents"+ assert kwargs["resumable_source_manager"] is manager+ assert kwargs["should_use_incremental_field"] is True+ assert kwargs["db_incremental_field_last_value"] == "2026-01-01T00:00:00+00:00"++ def test_source_for_pipeline_drops_last_value_when_not_incremental(self) -> None:+ manager = MagicMock()+ inputs = MagicMock(+ schema_name="services",+ should_use_incremental_field=False,+ db_incremental_field_last_value="2026-01-01T00:00:00+00:00",+ logger=MagicMock(),+ )++ with patch(f"{PAGERDUTY_MODULE}.source.pagerduty_source") as mock_source:+ self.source.source_for_pipeline(self.config, manager, inputs)++ kwargs = mock_source.call_args.kwargs+ assert kwargs["should_use_incremental_field"] is False+ assert kwargs["db_incremental_field_last_value"] is None