: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 rootly import source (#65634)
Tom Owers50cfad2480c4
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.mdindex 5cb13be4e921..5c38cd4b7fa8 100644--- a/posthog/temporal/data_imports/sources/SOURCES.md+++ b/posthog/temporal/data_imports/sources/SOURCES.md@@ -186,6 +186,7 @@ the row lists both.| revenuecat | HTTP + Webhook | requests + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) || rippling | HTTP | requests | ✅ || rollbar | HTTP | requests | ✅ |+| rootly | HTTP | requests | ✅ || salesforce | HTTP | requests + `rest_source.RESTClient` | ✅ || salesloft | HTTP | requests | ✅ || segment | HTTP | requests | ✅ |@@ -596,7 +597,6 @@ doesn't conflict with concurrent PRs.- rki_covid- rocket_chat- rocketlane-- rootly- rss- ruddr- safetyculturediff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.pyindex fa032a6e352a..989e572a4449 100644--- a/posthog/temporal/data_imports/sources/generated_configs.py+++ b/posthog/temporal/data_imports/sources/generated_configs.py@@ -2649,7 +2649,7 @@ class RollbarSourceConfig(config.Config):@config.configclass RootlySourceConfig(config.Config):- pass+ api_key: str@config.configdiff --git a/posthog/temporal/data_imports/sources/rootly/canonical_descriptions.py b/posthog/temporal/data_imports/sources/rootly/canonical_descriptions.pynew file mode 100644index 000000000000..3117f1fd1e94--- /dev/null+++ b/posthog/temporal/data_imports/sources/rootly/canonical_descriptions.py@@ -0,0 +1,178 @@+from posthog.temporal.data_imports.sources.common.canonical_descriptions import CanonicalDescriptions++_DOCS = "https://docs.rootly.com/api-reference"++# Descriptions are sourced from Rootly's public API reference. Partial coverage is fine — any+# endpoint, column, or table-level description not listed here falls back to LLM enrichment.+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "incidents": {+ "description": "Incidents tracked in Rootly, with their lifecycle status, severity, and timeline.",+ "docs_url": _DOCS,+ "columns": {+ "id": "Unique identifier for the incident.",+ "title": "Human-readable title of the incident.",+ "summary": "Short summary describing the incident.",+ "status": "Lifecycle status of the incident (e.g. started, mitigated, resolved, closed).",+ "severity": "Severity assigned to the incident.",+ "created_at": "When the incident record was created.",+ "updated_at": "When the incident was last updated.",+ "started_at": "When the incident is considered to have started.",+ "detected_at": "When the incident was detected.",+ "acknowledged_at": "When the incident was acknowledged.",+ "mitigated_at": "When the incident was mitigated.",+ "resolved_at": "When the incident was resolved.",+ "closed_at": "When the incident was closed.",+ },+ },+ "alerts": {+ "description": "Alerts ingested by Rootly from monitoring and on-call integrations.",+ "docs_url": _DOCS,+ "columns": {+ "id": "Unique identifier for the alert.",+ "summary": "Summary of the alert.",+ "status": "Status of the alert.",+ "source": "Integration or system the alert came from.",+ "created_at": "When the alert was created.",+ "updated_at": "When the alert was last updated.",+ },+ },+ "action_items": {+ "description": "Follow-up action items associated with incidents.",+ "docs_url": _DOCS,+ "columns": {+ "id": "Unique identifier for the action item.",+ "summary": "Description of the action item.",+ "status": "Completion status of the action item.",+ "priority": "Priority assigned to the action item.",+ "created_at": "When the action item was created.",+ "updated_at": "When the action item was last updated.",+ },+ },+ "post_mortems": {+ "description": "Post-incident retrospectives (post-mortems) documenting what happened and why.",+ "docs_url": _DOCS,+ "columns": {+ "id": "Unique identifier for the post-mortem.",+ "title": "Title of the post-mortem.",+ "status": "Status of the post-mortem (e.g. draft, published).",+ "created_at": "When the post-mortem was created.",+ "updated_at": "When the post-mortem was last updated.",+ },+ },+ "pulses": {+ "description": "Pulse events forming the activity timeline within Rootly.",+ "docs_url": _DOCS,+ "columns": {+ "id": "Unique identifier for the pulse event.",+ "summary": "Summary of the pulse event.",+ "source": "Source of the pulse event.",+ "created_at": "When the pulse event was created.",+ "updated_at": "When the pulse event was last updated.",+ },+ },+ "users": {+ "description": "Users belonging to the Rootly organization.",+ "docs_url": _DOCS,+ "columns": {+ "id": "Unique identifier for the user.",+ "email": "Email address of the user.",+ "name": "Full name of the user.",+ "created_at": "When the user was created.",+ "updated_at": "When the user was last updated.",+ },+ },+ "teams": {+ "description": "Teams (groups) configured in Rootly.",+ "docs_url": _DOCS,+ "columns": {+ "id": "Unique identifier for the team.",+ "name": "Name of the team.",+ "created_at": "When the team was created.",+ "updated_at": "When the team was last updated.",+ },+ },+ "services": {+ "description": "Services that can be affected by incidents.",+ "docs_url": _DOCS,+ "columns": {+ "id": "Unique identifier for the service.",+ "name": "Name of the service.",+ "created_at": "When the service was created.",+ "updated_at": "When the service was last updated.",+ },+ },+ "functionalities": {+ "description": "Functionalities (product areas) that can be affected by incidents.",+ "docs_url": _DOCS,+ "columns": {+ "id": "Unique identifier for the functionality.",+ "name": "Name of the functionality.",+ "created_at": "When the functionality was created.",+ "updated_at": "When the functionality was last updated.",+ },+ },+ "environments": {+ "description": "Environments (e.g. production, staging) defined in Rootly.",+ "docs_url": _DOCS,+ "columns": {+ "id": "Unique identifier for the environment.",+ "name": "Name of the environment.",+ },+ },+ "severities": {+ "description": "Severity levels that can be assigned to incidents.",+ "docs_url": _DOCS,+ "columns": {+ "id": "Unique identifier for the severity.",+ "name": "Name of the severity level.",+ "severity": "Relative severity ranking.",+ },+ },+ "incident_types": {+ "description": "Incident type classifications.",+ "docs_url": _DOCS,+ "columns": {+ "id": "Unique identifier for the incident type.",+ "name": "Name of the incident type.",+ },+ },+ "schedules": {+ "description": "On-call schedules configured in Rootly.",+ "docs_url": _DOCS,+ "columns": {+ "id": "Unique identifier for the schedule.",+ "name": "Name of the schedule.",+ "created_at": "When the schedule was created.",+ "updated_at": "When the schedule was last updated.",+ },+ },+ "escalation_policies": {+ "description": "Escalation policies that route alerts to responders.",+ "docs_url": _DOCS,+ "columns": {+ "id": "Unique identifier for the escalation policy.",+ "name": "Name of the escalation policy.",+ "created_at": "When the escalation policy was created.",+ "updated_at": "When the escalation policy was last updated.",+ },+ },+ "workflows": {+ "description": "Automation workflows that run in response to incident lifecycle events.",+ "docs_url": _DOCS,+ "columns": {+ "id": "Unique identifier for the workflow.",+ "name": "Name of the workflow.",+ "enabled": "Whether the workflow is enabled.",+ "created_at": "When the workflow was created.",+ "updated_at": "When the workflow was last updated.",+ },+ },+ "causes": {+ "description": "Root-cause categories that can be attributed to incidents.",+ "docs_url": _DOCS,+ "columns": {+ "id": "Unique identifier for the cause.",+ "name": "Name of the cause.",+ },+ },+}diff --git a/posthog/temporal/data_imports/sources/rootly/rootly.py b/posthog/temporal/data_imports/sources/rootly/rootly.pynew file mode 100644index 000000000000..6ec08b47c50e--- /dev/null+++ b/posthog/temporal/data_imports/sources/rootly/rootly.py@@ -0,0 +1,208 @@+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.rootly.settings import ROOTLY_ENDPOINTS, RootlyEndpointConfig++ROOTLY_BASE_URL = "https://api.rootly.com/v1"+# Rootly is a JSON:API service and expects/returns the JSON:API media type.+ROOTLY_JSON_API_MEDIA_TYPE = "application/vnd.api+json"+REQUEST_TIMEOUT_SECONDS = 60+++class RootlyRetryableError(Exception):+ pass+++class RootlyResumeConfig:+ # Full next-page URL from the JSON:API `links.next` field. It already carries the page,+ # sort, and filter params, so following it preserves the incremental window on every page.+ next_url: str | None = None+++def _get_headers(api_key: str) -> dict[str, str]:+ return {+ "Authorization": f"Bearer {api_key}",+ "Accept": ROOTLY_JSON_API_MEDIA_TYPE,+ }+++def _build_url(base_url: str, params: dict[str, Any]) -> str:+ """Build a URL. Rootly is Rails/JSON:API and parses percent-encoded bracket params+ (`filter[updated_at][gt]`, `page[size]`) correctly, so standard urlencode is safe."""+ if not params:+ return base_url+ return f"{base_url}?{urlencode(params)}"+++def _format_incremental_value(value: Any) -> str:+ """Format an incremental cursor value as an ISO 8601 UTC timestamp for Rootly's date filters."""+ if isinstance(value, datetime):+ aware = value if value.tzinfo is not None else value.replace(tzinfo=UTC)+ return aware.astimezone(UTC).isoformat()+ if isinstance(value, date):+ return datetime.combine(value, datetime.min.time(), tzinfo=UTC).isoformat()+ return str(value)+++def _clamp_future_value_to_now(value: Any) -> Any:+ """Cap a future datetime/date cursor at now. A future-dated record could push the cursor+ past now; asking for records newer than now is a no-op, so clamping keeps the filter sane."""+ now = datetime.now(UTC)+ if isinstance(value, datetime):+ aware = value if value.tzinfo is not None else value.replace(tzinfo=UTC)+ return now if aware > now else value+ if isinstance(value, date):+ return now.date() if value > now.date() else value+ return value+++def _build_initial_params(+ config: RootlyEndpointConfig,+ should_use_incremental_field: bool,+ db_incremental_field_last_value: Any,+ incremental_field: str | None,+) -> dict[str, Any]:+ """Build query params for the first request to a Rootly collection endpoint."""+ params: dict[str, Any] = {"page[size]": config.page_size}++ if config.supports_incremental and should_use_incremental_field:+ # Cursor on the user's chosen field; fall back to the endpoint's first advertised field.+ field_name = incremental_field or (config.incremental_fields[0]["field"] if config.incremental_fields else None)+ if field_name:+ # Sort ascending on the same field we filter on so rows arrive in watermark order and+ # the pipeline can checkpoint safely (matches SourceResponse.sort_mode="asc").+ params["sort"] = field_name+ if db_incremental_field_last_value:+ value = _clamp_future_value_to_now(db_incremental_field_last_value)+ params[f"filter[{field_name}][gt]"] = _format_incremental_value(value)++ return params+++def _flatten_item(item: dict[str, Any]) -> dict[str, Any]:+ """Flatten a JSON:API resource object's `attributes` into the root and keep `id`/`type`."""+ flattened = {k: v for k, v in item.items() if k != "attributes"}+ attributes = item.get("attributes")+ if isinstance(attributes, dict):+ flattened.update(attributes)+ return flattened+++@retry(+ retry=retry_if_exception_type((RootlyRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _fetch_page(+ session: requests.Session, page_url: str, headers: dict[str, str], logger: FilteringBoundLogger+) -> dict:+ response = session.get(page_url, headers=headers, timeout=REQUEST_TIMEOUT_SECONDS)++ # 429 (rate limited — Rootly's default is 3000 req/min) and 5xx are transient; retry them.+ if response.status_code == 429 or response.status_code >= 500:+ raise RootlyRetryableError(f"Rootly API error (retryable): status={response.status_code}, url={page_url}")++ if not response.ok:+ logger.error(f"Rootly API error: status={response.status_code}, body={response.text}, url={page_url}")+ response.raise_for_status()++ return response.json()+++def probe_credentials(api_key: str, endpoint: str | None = None) -> int | None:+ """Cheap probe of a Rootly collection. Returns the HTTP status code, or None on a connection+ failure. Probes the given endpoint's path when set, else a generic, cheap collection."""+ config = ROOTLY_ENDPOINTS.get(endpoint) if endpoint else None+ path = config.path if config else "/users"+ url = _build_url(f"{ROOTLY_BASE_URL}{path}", {"page[size]": 1})+ try:+ response = make_tracked_session().get(url, headers=_get_headers(api_key), timeout=10)+ except Exception:+ return None+ return response.status_code+++def get_rows(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[RootlyResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Any = None,+ incremental_field: str | None = None,+) -> Iterator[Any]:+ config = ROOTLY_ENDPOINTS[endpoint]+ headers = _get_headers(api_key)+ # One session reused across pages so urllib3 keeps the connection alive.+ session = make_tracked_session()++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ if resume is not None and resume.next_url:+ url = resume.next_url+ logger.debug(f"Rootly: resuming {endpoint} from URL: {url}")+ else:+ params = _build_initial_params(+ config, should_use_incremental_field, db_incremental_field_last_value, incremental_field+ )+ url = _build_url(f"{ROOTLY_BASE_URL}{config.path}", params)++ while True:+ data = _fetch_page(session, url, headers, logger)++ items = data.get("data", [])+ next_url = data.get("links", {}).get("next")++ if items:+ # Yield one page at a time as a list[dict]; the pipeline buffers and batches for us.+ yield [_flatten_item(item) for item in items]++ if not next_url:+ break++ # Save AFTER yielding so a crash re-yields the last page rather than skipping it — merge+ # dedupes on the primary key. Advance the URL before the next fetch to avoid re-looping it.+ resumable_source_manager.save_state(RootlyResumeConfig(next_url=next_url))+ url = next_url+++def rootly_source(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[RootlyResumeConfig],+ should_use_incremental_field: bool = False,+ db_incremental_field_last_value: Optional[Any] = None,+ incremental_field: str | None = None,+) -> SourceResponse:+ config = ROOTLY_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ 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,+ incremental_field=incremental_field,+ ),+ primary_keys=config.primary_keys,+ 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/rootly/settings.py b/posthog/temporal/data_imports/sources/rootly/settings.pynew file mode 100644index 000000000000..9eb2f6de44f9--- /dev/null+++ b/posthog/temporal/data_imports/sources/rootly/settings.py@@ -0,0 +1,91 @@+from dataclasses import dataclass, field+from typing import Optional++from products.data_warehouse.backend.types import IncrementalField, IncrementalFieldType+++def _timestamp_field(name: str) -> IncrementalField:+ return {+ "label": name,+ "type": IncrementalFieldType.DateTime,+ "field": name,+ "field_type": IncrementalFieldType.DateTime,+ }+++# Rootly resources are Rails records that all expose `updated_at` / `created_at`. For mutable+# collections we advertise both: `updated_at` (default, catches edits) and `created_at`.+_UPDATED_THEN_CREATED: list[IncrementalField] = [_timestamp_field("updated_at"), _timestamp_field("created_at")]+++@dataclass+class RootlyEndpointConfig:+ name: str+ path: str+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # Only True where Rootly exposes a genuine server-side `filter[<field>][gt]` + `sort=<field>`.+ # When True the transport cursors and sorts ascending on the user's chosen incremental field, so+ # rows arrive in watermark order and pagination terminates server-side at the cutoff.+ supports_incremental: bool = False+ # Stable field to partition by — always a creation timestamp, never `updated_at`.+ partition_key: Optional[str] = "created_at"+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ should_sync_default: bool = True+ page_size: int = 100+++# Endpoint catalog. Paths are relative to https://api.rootly.com/v1. The set mirrors the streams a+# user actually wants from an incident-management platform and matches the resource list other+# connectors (Airbyte/Fivetran) expose for Rootly. Every path here was confirmed to be a real route+# against the live API (real routes return 401 on a bad token; unknown routes return 404).+ROOTLY_ENDPOINTS: dict[str, RootlyEndpointConfig] = {+ # High-value, high-volume mutable collections — incremental.+ "incidents": RootlyEndpointConfig(+ name="incidents",+ path="/incidents",+ supports_incremental=True,+ incremental_fields=_UPDATED_THEN_CREATED,+ ),+ "alerts": RootlyEndpointConfig(+ name="alerts",+ path="/alerts",+ supports_incremental=True,+ incremental_fields=_UPDATED_THEN_CREATED,+ ),+ "action_items": RootlyEndpointConfig(+ name="action_items",+ path="/action_items",+ supports_incremental=True,+ incremental_fields=_UPDATED_THEN_CREATED,+ ),+ "post_mortems": RootlyEndpointConfig(+ name="post_mortems",+ path="/post_mortems",+ supports_incremental=True,+ incremental_fields=_UPDATED_THEN_CREATED,+ ),+ # Pulses are the per-incident activity timeline — high volume, so off by default.+ "pulses": RootlyEndpointConfig(+ name="pulses",+ path="/pulses",+ supports_incremental=True,+ incremental_fields=_UPDATED_THEN_CREATED,+ should_sync_default=False,+ ),+ # Configuration / reference resources — small and slowly-changing, so full refresh each sync.+ "users": RootlyEndpointConfig(name="users", path="/users"),+ "teams": RootlyEndpointConfig(name="teams", path="/teams"),+ "services": RootlyEndpointConfig(name="services", path="/services"),+ "functionalities": RootlyEndpointConfig(name="functionalities", path="/functionalities"),+ "schedules": RootlyEndpointConfig(name="schedules", path="/schedules"),+ "escalation_policies": RootlyEndpointConfig(name="escalation_policies", path="/escalation_policies"),+ "workflows": RootlyEndpointConfig(name="workflows", path="/workflows"),+ # Small enumeration resources whose timestamp columns we haven't confirmed against the live API.+ # Partitioning a handful of rows buys nothing, so don't risk partitioning on an absent field.+ "environments": RootlyEndpointConfig(name="environments", path="/environments", partition_key=None),+ "severities": RootlyEndpointConfig(name="severities", path="/severities", partition_key=None),+ "incident_types": RootlyEndpointConfig(name="incident_types", path="/incident_types", partition_key=None),+ "causes": RootlyEndpointConfig(name="causes", path="/causes", partition_key=None),+}++ENDPOINTS = tuple(ROOTLY_ENDPOINTS.keys())diff --git a/posthog/temporal/data_imports/sources/rootly/source.py b/posthog/temporal/data_imports/sources/rootly/source.pyindex 507927225b5c..a1b7e5f6d11f 100644--- a/posthog/temporal/data_imports/sources/rootly/source.py+++ b/posthog/temporal/data_imports/sources/rootly/source.py@@ -1,20 +1,30 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,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, ResumableSource+from posthog.temporal.data_imports.sources.common.canonical_descriptions import CanonicalDescriptionsfrom 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 RootlySourceConfig+from posthog.temporal.data_imports.sources.rootly.canonical_descriptions import CANONICAL_DESCRIPTIONS+from posthog.temporal.data_imports.sources.rootly.rootly import RootlyResumeConfig, probe_credentials, rootly_source+from posthog.temporal.data_imports.sources.rootly.settings import ENDPOINTS, ROOTLY_ENDPOINTSfrom products.data_warehouse.backend.types import ExternalDataSourceType@SourceRegistry.register-class RootlySource(SimpleSource[RootlySourceConfig]):+class RootlySource(ResumableSource[RootlySourceConfig, RootlyResumeConfig]):@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.ROOTLY@@ -25,7 +35,98 @@ class RootlySource(SimpleSource[RootlySourceConfig]):name=SchemaExternalDataSourceType.ROOTLY,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="Rootly",- iconPath="/static/services/rootly.png",- fields=cast(list[FieldType], []),+ releaseStatus=ReleaseStatus.ALPHA,unreleasedSource=True,+ caption="""Enter your Rootly API key to automatically pull your Rootly incident-management data into the PostHog Data warehouse.++You can create an API key in your [Rootly account settings](https://rootly.com/account/api_keys). A Global-scope key can read every resource; Team- and User-scope keys only see the resources they are granted.""",+ iconPath="/static/services/rootly.png",+ docsUrl="https://posthog.com/docs/cdp/sources/rootly",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="rootly_...",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # 401/403 surface as a requests HTTPError when `_fetch_page` calls `raise_for_status()`.+ # No retry can satisfy a credential/scope problem. Match the stable status text + base+ # host, not the per-request path/query.+ "401 Client Error: Unauthorized for url: https://api.rootly.com": "Your Rootly API key is invalid or has been revoked. Create a new API key in your Rootly account settings, then reconnect.",+ "403 Client Error: Forbidden for url: https://api.rootly.com": "Your Rootly API key is missing access to this resource. Grant the key access in your Rootly account settings, then reconnect.",+ }++ def get_schemas(+ self,+ config: RootlySourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ def _build_schema(endpoint: str) -> SourceSchema:+ endpoint_config = ROOTLY_ENDPOINTS[endpoint]+ return SourceSchema(+ name=endpoint,+ supports_incremental=endpoint_config.supports_incremental,+ supports_append=endpoint_config.supports_incremental,+ incremental_fields=endpoint_config.incremental_fields,+ should_sync_default=endpoint_config.should_sync_default,+ )++ schemas = [_build_schema(endpoint) 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: RootlySourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ status = probe_credentials(config.api_key, schema_name)++ if status == 200:+ return True, None+ # At source-create (schema_name is None) a 403 means the token is genuine but scoped away+ # from the probe resource — accept it; per-endpoint scope is checked when configuring a schema.+ if status == 403 and schema_name is None:+ return True, None+ if status == 401:+ return False, "Your Rootly API key is invalid or has been revoked."+ if status == 403:+ return False, "Your Rootly API key does not have access to this resource."+ return False, "Could not validate your Rootly API key. Please check the key and try again."++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[RootlyResumeConfig]:+ return ResumableSourceManager[RootlyResumeConfig](inputs, RootlyResumeConfig)++ def source_for_pipeline(+ self,+ config: RootlySourceConfig,+ resumable_source_manager: ResumableSourceManager[RootlyResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return rootly_source(+ api_key=config.api_key,+ 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,+ incremental_field=inputs.incremental_field,)diff --git a/posthog/temporal/data_imports/sources/rootly/tests/test_rootly.py b/posthog/temporal/data_imports/sources/rootly/tests/test_rootly.pynew file mode 100644index 000000000000..124a95a95e2e--- /dev/null+++ b/posthog/temporal/data_imports/sources/rootly/tests/test_rootly.py@@ -0,0 +1,216 @@+from datetime import UTC, date, datetime+from typing import Any++from freezegun import freeze_time+from unittest import mock+from unittest.mock import MagicMock++from parameterized import parameterized++from posthog.temporal.data_imports.sources.rootly import rootly+from posthog.temporal.data_imports.sources.rootly.rootly import (+ RootlyResumeConfig,+ _build_initial_params,+ _build_url,+ _clamp_future_value_to_now,+ _flatten_item,+ _format_incremental_value,+ get_rows,+)+from posthog.temporal.data_imports.sources.rootly.settings import ROOTLY_ENDPOINTS+++class TestBuildUrl:+ def test_no_params_returns_base(self) -> None:+ assert _build_url("https://api.rootly.com/v1/users", {}) == "https://api.rootly.com/v1/users"++ def test_bracket_params_are_percent_encoded(self) -> None:+ # Rootly is Rails/JSON:API and parses percent-encoded brackets; urlencode keeps them safe.+ url = _build_url("https://api.rootly.com/v1/incidents", {"page[size]": 100})+ assert url == "https://api.rootly.com/v1/incidents?page%5Bsize%5D=100"+++class TestFormatIncrementalValue:+ @parameterized.expand(+ [+ ("utc_datetime", datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04T02:58:14+00:00"),+ ("naive_datetime", datetime(2026, 3, 4, 2, 58, 14), "2026-03-04T02:58:14+00:00"),+ ("date_value", date(2026, 3, 4), "2026-03-04T00:00:00+00:00"),+ ("string_passthrough", "cursor-token", "cursor-token"),+ ]+ )+ def test_format_incremental_value(self, _name: str, value: object, expected: str) -> None:+ assert _format_incremental_value(value) == expected+++class TestClampFutureValueToNow:+ @freeze_time("2026-06-15T12:00:00Z")+ def test_future_datetime_is_clamped(self) -> None:+ assert _clamp_future_value_to_now(datetime(2027, 2, 5, tzinfo=UTC)) == datetime(2026, 6, 15, 12, 0, tzinfo=UTC)++ @freeze_time("2026-06-15T12:00:00Z")+ def test_past_datetime_is_unchanged(self) -> None:+ value = datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC)+ assert _clamp_future_value_to_now(value) == value++ def test_string_passthrough(self) -> None:+ assert _clamp_future_value_to_now("cursor-token") == "cursor-token"+++class TestFlattenItem:+ def test_attributes_hoisted_to_root_and_id_type_kept(self) -> None:+ item = {+ "id": "123",+ "type": "incidents",+ "attributes": {"title": "DB down", "status": "started", "created_at": "2026-01-01T00:00:00Z"},+ }+ assert _flatten_item(item) == {+ "id": "123",+ "type": "incidents",+ "title": "DB down",+ "status": "started",+ "created_at": "2026-01-01T00:00:00Z",+ }++ def test_missing_attributes_is_safe(self) -> None:+ assert _flatten_item({"id": "123", "type": "incidents"}) == {"id": "123", "type": "incidents"}+++class TestBuildInitialParams:+ def test_incremental_endpoint_sorts_and_filters_on_cursor_field(self) -> None:+ params = _build_initial_params(+ ROOTLY_ENDPOINTS["incidents"],+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC),+ incremental_field="updated_at",+ )+ # Sort and filter must reference the same field so rows arrive in watermark order.+ assert params["sort"] == "updated_at"+ assert params["filter[updated_at][gt]"] == "2026-03-04T02:58:14+00:00"++ def test_incremental_first_sync_sorts_without_filter(self) -> None:+ params = _build_initial_params(+ ROOTLY_ENDPOINTS["incidents"],+ should_use_incremental_field=True,+ db_incremental_field_last_value=None,+ incremental_field="updated_at",+ )+ assert params["sort"] == "updated_at"+ assert not any(key.startswith("filter[") for key in params)++ @freeze_time("2026-06-15T12:00:00Z")+ def test_future_cursor_is_clamped(self) -> None:+ params = _build_initial_params(+ ROOTLY_ENDPOINTS["incidents"],+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2027, 2, 5, tzinfo=UTC),+ incremental_field="updated_at",+ )+ assert params["filter[updated_at][gt]"] == "2026-06-15T12:00:00+00:00"++ def test_full_refresh_endpoint_has_no_sort_or_filter(self) -> None:+ params = _build_initial_params(+ ROOTLY_ENDPOINTS["users"],+ should_use_incremental_field=True,+ db_incremental_field_last_value=datetime(2026, 3, 4, tzinfo=UTC),+ incremental_field="updated_at",+ )+ assert "sort" not in params+ assert not any(key.startswith("filter[") for key in params)+ assert params["page[size]"] == 100+++class _FakeResumableManager:+ def __init__(self, state: RootlyResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[RootlyResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> RootlyResumeConfig | None:+ return self._state++ def save_state(self, data: RootlyResumeConfig) -> None:+ self.saved.append(data)+++class TestGetRows:+ @staticmethod+ def _collect(manager: _FakeResumableManager, monkeypatch: Any, pages: dict[str, Any], **kwargs: Any) -> list[dict]:+ def fake_fetch(session: Any, url: str, headers: dict[str, str], logger: Any) -> dict:+ return pages[url]++ monkeypatch.setattr(rootly, "_fetch_page", fake_fetch)++ rows: list[dict] = []+ for page in get_rows(+ api_key="rootly_test",+ endpoint="incidents",+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ **kwargs,+ ):+ rows.extend(page)+ return rows++ def test_follows_links_next_and_flattens(self, monkeypatch: Any) -> None:+ first = "https://api.rootly.com/v1/incidents?page%5Bsize%5D=100"+ second = "https://api.rootly.com/v1/incidents?page%5Bnumber%5D=2"+ pages = {+ first: {+ "data": [{"id": "1", "type": "incidents", "attributes": {"title": "A"}}],+ "links": {"next": second},+ },+ second: {+ "data": [{"id": "2", "type": "incidents", "attributes": {"title": "B"}}],+ "links": {"next": None},+ },+ }+ rows = self._collect(_FakeResumableManager(), monkeypatch, pages)+ assert rows == [+ {"id": "1", "type": "incidents", "title": "A"},+ {"id": "2", "type": "incidents", "title": "B"},+ ]++ def test_saves_state_after_each_page_except_the_last(self, monkeypatch: Any) -> None:+ first = "https://api.rootly.com/v1/incidents?page%5Bsize%5D=100"+ second = "https://api.rootly.com/v1/incidents?page%5Bnumber%5D=2"+ pages = {+ first: {"data": [{"id": "1", "attributes": {}}], "links": {"next": second}},+ second: {"data": [{"id": "2", "attributes": {}}], "links": {"next": None}},+ }+ manager = _FakeResumableManager()+ self._collect(manager, monkeypatch, pages)+ # State saved once (pointing at the second page) so a crash re-yields that page; nothing+ # is saved after the final page (no next link).+ assert [s.next_url for s in manager.saved] == [second]++ def test_resumes_from_saved_next_url(self, monkeypatch: Any) -> None:+ resume_url = "https://api.rootly.com/v1/incidents?page%5Bnumber%5D=3"+ pages = {resume_url: {"data": [{"id": "9", "attributes": {"title": "Z"}}], "links": {"next": None}}}+ manager = _FakeResumableManager(RootlyResumeConfig(next_url=resume_url))+ rows = self._collect(manager, monkeypatch, pages)+ # Starts at the resumed URL, not the freshly-built first page.+ assert rows == [{"id": "9", "title": "Z"}]++ def test_empty_collection_yields_nothing(self, monkeypatch: Any) -> None:+ first = "https://api.rootly.com/v1/incidents?page%5Bsize%5D=100"+ pages = {first: {"data": [], "links": {"next": None}}}+ rows = self._collect(_FakeResumableManager(), monkeypatch, pages)+ assert rows == []+++class TestProbeCredentials:+ @parameterized.expand([("ok", 200), ("unauthorized", 401), ("forbidden", 403)])+ def test_returns_status_code(self, _name: str, status_code: int) -> None:+ session = MagicMock()+ session.get.return_value = MagicMock(status_code=status_code)+ with mock.patch.object(rootly, "make_tracked_session", return_value=session):+ assert rootly.probe_credentials("rootly_test", "incidents") == status_code++ def test_connection_failure_returns_none(self) -> None:+ session = MagicMock()+ session.get.side_effect = Exception("boom")+ with mock.patch.object(rootly, "make_tracked_session", return_value=session):+ assert rootly.probe_credentials("rootly_test") is Nonediff --git a/posthog/temporal/data_imports/sources/rootly/tests/test_rootly_source.py b/posthog/temporal/data_imports/sources/rootly/tests/test_rootly_source.pynew file mode 100644index 000000000000..8b8a64240be3--- /dev/null+++ b/posthog/temporal/data_imports/sources/rootly/tests/test_rootly_source.py@@ -0,0 +1,185 @@+from unittest import mock+from unittest.mock import MagicMock++from parameterized import parameterized++from posthog.schema import (+ DataWarehouseSourceCategory,+ ReleaseStatus,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+)++from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.rootly import source as rootly_source_module+from posthog.temporal.data_imports.sources.rootly.rootly import RootlyResumeConfig+from posthog.temporal.data_imports.sources.rootly.settings import ENDPOINTS+from posthog.temporal.data_imports.sources.rootly.source import RootlySource++from products.data_warehouse.backend.types import ExternalDataSourceType+++class TestRootlySourceConfig:+ def test_source_type(self) -> None:+ assert RootlySource().source_type == ExternalDataSourceType.ROOTLY++ def test_config_basics(self) -> None:+ config = RootlySource().get_source_config+ assert config.label == "Rootly"+ assert config.category == DataWarehouseSourceCategory.ENGINEERING___MONITORING+ assert config.releaseStatus == ReleaseStatus.ALPHA+ # Ships hidden until end-to-end sync is verified against a live key.+ assert config.unreleasedSource is True++ def test_single_password_api_key_field(self) -> None:+ fields = RootlySource().get_source_config.fields+ assert len(fields) == 1+ field = fields[0]+ assert isinstance(field, SourceFieldInputConfig)+ assert field.name == "api_key"+ assert field.required is True+ assert field.type == SourceFieldInputConfigType.PASSWORD+++class TestRootlyGetSchemas:+ def test_returns_every_endpoint(self) -> None:+ schemas = RootlySource().get_schemas(MagicMock(), team_id=1)+ assert {s.name for s in schemas} == set(ENDPOINTS)++ @parameterized.expand(+ [+ ("incidents", True),+ ("alerts", True),+ ("action_items", True),+ ("post_mortems", True),+ ("pulses", True),+ ("users", False),+ ("teams", False),+ ("severities", False),+ ("workflows", False),+ ]+ )+ def test_incremental_support_matches_settings(self, endpoint: str, expected_incremental: bool) -> None:+ schemas = {s.name: s for s in RootlySource().get_schemas(MagicMock(), team_id=1)}+ schema = schemas[endpoint]+ assert schema.supports_incremental is expected_incremental+ assert schema.supports_append is expected_incremental+ # Incremental endpoints advertise updated_at/created_at; full-refresh ones advertise nothing.+ assert bool(schema.incremental_fields) is expected_incremental++ def test_pulses_off_by_default(self) -> None:+ # Pulses are the high-volume activity timeline, so they shouldn't sync unless opted in.+ schemas = {s.name: s for s in RootlySource().get_schemas(MagicMock(), team_id=1)}+ assert schemas["pulses"].should_sync_default is False+ assert schemas["incidents"].should_sync_default is True++ def test_names_filter(self) -> None:+ schemas = RootlySource().get_schemas(MagicMock(), team_id=1, names=["incidents", "users"])+ assert {s.name for s in schemas} == {"incidents", "users"}+++class TestRootlyValidateCredentials:+ @parameterized.expand(+ [+ # (probe status, schema_name, expected_ok)+ ("ok", 200, None, True),+ ("ok_for_schema", 200, "incidents", True),+ # A 403 at source-create is a genuine token scoped away from the probe resource — accept it.+ ("forbidden_at_create_accepted", 403, None, True),+ # A 403 while configuring a specific schema means no access to that resource — reject.+ ("forbidden_for_schema_rejected", 403, "incidents", False),+ ("unauthorized_rejected", 401, None, False),+ ("connection_failure_rejected", None, None, False),+ ("unexpected_status_rejected", 500, None, False),+ ]+ )+ def test_status_mapping(+ self, _name: str, probe_status: int | None, schema_name: str | None, expected_ok: bool+ ) -> None:+ with mock.patch.object(rootly_source_module, "probe_credentials", return_value=probe_status):+ ok, error = RootlySource().validate_credentials(+ MagicMock(api_key="rootly_test"), team_id=1, schema_name=schema_name+ )+ assert ok is expected_ok+ assert (error is None) is expected_ok+++class TestRootlyNonRetryableErrors:+ @parameterized.expand(+ [+ (+ "unauthorized",+ "401 Client Error: Unauthorized for url: https://api.rootly.com/v1/incidents?page[size]=100",+ ),+ ("forbidden", "403 Client Error: Forbidden for url: https://api.rootly.com/v1/secrets"),+ ]+ )+ def test_credential_errors_are_non_retryable(self, _name: str, observed_error: str) -> None:+ non_retryable = RootlySource().get_non_retryable_errors()+ assert any(key in observed_error for key in non_retryable)++ @parameterized.expand(+ [+ ("rate_limited", "429 Client Error: Too Many Requests for url: https://api.rootly.com/v1/incidents"),+ ("server_error", "500 Server Error: Internal Server Error for url: https://api.rootly.com/v1/incidents"),+ ("read_timeout", "HTTPSConnectionPool(host='api.rootly.com', port=443): Read timed out."),+ ]+ )+ def test_transient_errors_remain_retryable(self, _name: str, other_error: str) -> None:+ non_retryable = RootlySource().get_non_retryable_errors()+ assert not any(key in other_error for key in non_retryable)+++class TestRootlyResumableAndPipeline:+ def test_resumable_manager_bound_to_resume_config(self) -> None:+ manager = RootlySource().get_resumable_source_manager(MagicMock())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is RootlyResumeConfig++ def test_source_for_pipeline_plumbs_endpoint_and_keys(self) -> None:+ inputs = MagicMock()+ inputs.schema_name = "incidents"+ inputs.should_use_incremental_field = False+ inputs.incremental_field = None+ response = RootlySource().source_for_pipeline(+ MagicMock(api_key="rootly_test"), resumable_source_manager=MagicMock(), inputs=inputs+ )+ assert response.name == "incidents"+ assert response.primary_keys == ["id"]+ assert response.partition_keys == ["created_at"]+ assert response.partition_mode == "datetime"++ @parameterized.expand(+ [+ # Endpoints partition on the stable created_at field...+ ("incidents", ["created_at"], "datetime"),+ ("users", ["created_at"], "datetime"),+ # ...except small enumeration resources whose timestamp columns aren't confirmed —+ # partitioning on an absent field would fail the sync, so they don't partition.+ ("environments", None, None),+ ("severities", None, None),+ ("incident_types", None, None),+ ("causes", None, None),+ ]+ )+ def test_partitioning_per_endpoint(+ self, endpoint: str, expected_keys: list[str] | None, expected_mode: str | None+ ) -> None:+ inputs = MagicMock()+ inputs.schema_name = endpoint+ inputs.should_use_incremental_field = False+ inputs.incremental_field = None+ response = RootlySource().source_for_pipeline(+ MagicMock(api_key="rootly_test"), resumable_source_manager=MagicMock(), inputs=inputs+ )+ assert response.partition_keys == expected_keys+ assert response.partition_mode == expected_mode+++class TestRootlyCanonicalDescriptions:+ def test_descriptions_keyed_by_endpoint_name(self) -> None:+ descriptions = RootlySource().get_canonical_descriptions()+ # Every documented key must be a real endpoint so enrichment binds to the right table.+ assert set(descriptions).issubset(set(ENDPOINTS))+ assert "incidents" in descriptions+ assert descriptions["incidents"]["columns"]["id"]