: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(cronitor): sync issues, groups, sites and site errors (#103716)
Tom Owers6c4a35b12e08
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.mdindex 04254c147a0b..c84173550889 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md@@ -2150,19 +2150,19 @@ Note: Verified against the live OpenAPI document at https://crates.io/api/openap## Cronitor — gaps-Today (3): `invocations`, `metrics`, `monitors`+Today (7): `groups`, `invocations`, `issues`, `metrics`, `monitors`, `site_errors`, `sites`Diffed against: <https://cronitor.io/docs/api.md>-- [ ] `GET /api/issues` — incidents with state, severity, and start/resolve timestamps - the core reliability object, filterable and listable (high)-- [ ] `GET /api/groups` — lookup table resolving the group each synced monitor belongs to; enables per-service rollups (high)-- [ ] `GET /api/site_errors` — RUM JavaScript errors, the analytical event stream for the Sites product (medium)-- [ ] `GET /api/sites` — lookup for RUM sites that site_errors and RUM analytics rows reference (medium)+- [x] `GET /api/issues` — incidents with state, severity, and start/resolve timestamps - the core reliability object, filterable and listable (high)+- [x] `GET /api/groups` — lookup table resolving the group each synced monitor belongs to; enables per-service rollups (high)+- [x] `GET /api/site_errors` — RUM JavaScript errors, the analytical event stream for the Sites product (medium)+- [x] `GET /api/sites` — lookup for RUM sites that site_errors and RUM analytics rows reference (medium)- [ ] `RUM analytics query endpoint (aggregate/breakdown/timeseries over sites)` — pageviews, web vitals, and top-pages breakdowns - the headline RUM metrics (medium)- [ ] `GET /api/maintenance_windows` — scheduled maintenance periods needed to exclude planned downtime from uptime and alert analysis (medium)- [ ] `GET /api/environments` — lookup resolving the environment tag on telemetry, invocations, and monitors (low)-Note: Notifications, API keys, and status pages were excluded as configuration. Telemetry API is write-only ingestion. Source is static (three endpoints in cronitor/cronitor.py), no dynamic table discovery.+Note: Notifications, API keys, and status pages were excluded as configuration. Telemetry API is write-only ingestion. Source is static (endpoint catalog in cronitor/settings.py), no dynamic table discovery.## Crunchbase — gapsdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cronitor/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cronitor/canonical_descriptions.pyindex 6916f0e43ad7..211223122451 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/cronitor/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cronitor/canonical_descriptions.py@@ -50,4 +50,79 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"run_count": "Number of runs recorded in the interval.",},},+ "groups": {+ "description": "A group of Cronitor monitors, used to organize related monitors and to act on them together.",+ "docs_url": "https://cronitor.io/docs/groups-api",+ "columns": {+ "key": "Unique identifier of the group, used in API URLs and to reference the group from a monitor.",+ "name": "Display name of the group.",+ "monitors": "Keys of the monitors that belong to the group.",+ "created": "ISO 8601 timestamp of when the group was created.",+ "latest_event": "The most recent telemetry event from any monitor in the group.",+ "latest_issue": "The most recent issue raised by any monitor in the group, if any.",+ },+ },+ "issues": {+ "description": "An incident or maintenance event tracked in Cronitor, with its severity, lifecycle state, and the monitors and status pages it affects.",+ "docs_url": "https://cronitor.io/docs/issues-api",+ "columns": {+ "key": "Unique identifier of the issue, used in API URLs.",+ "name": "Display name of the issue, shown in alerts and on status pages.",+ "severity": "Severity of the issue: missing_data, operational, maintenance, degraded_performance, minor_outage, or outage.",+ "state": "Lifecycle state of the issue: unresolved, investigating, identified, monitoring, or resolved.",+ "started": "ISO 8601 timestamp of when the issue began.",+ "ended": "ISO 8601 timestamp of when the issue was resolved. Null while it is open.",+ "duration": "Length of the issue in seconds, once it has ended.",+ "environment": "The environment the issue belongs to, as a key and name.",+ "assigned_to": "Email address of the person the issue is assigned to.",+ "created_by": "Who opened the issue, as a kind and name.",+ "statuspages": "Keys of the status pages the issue is published to.",+ "affected_components": "Keys of the status page components the issue affects.",+ "monitors": "The monitors associated with the issue.",+ "updates": "Timeline of status updates posted on the issue.",+ "alerts": "Alerts sent for the issue.",+ "created": "ISO 8601 timestamp of when the issue record was created.",+ "updated": "ISO 8601 timestamp of when the issue record was last changed.",+ },+ },+ "sites": {+ "description": "A Real User Monitoring site, collecting web vitals, performance metrics, and JavaScript errors from a web application.",+ "docs_url": "https://cronitor.io/docs/sites-api",+ "columns": {+ "key": "Unique identifier of the site, used in API URLs.",+ "name": "Display name of the site.",+ "client_key": "Public key the browser script uses to report data for this site.",+ "public_report_enabled": "Whether the site's performance report is published publicly.",+ "webvitals_enabled": "Whether web vitals collection is on.",+ "errors_enabled": "Whether JavaScript error tracking is on.",+ "filter_localhost": "Whether traffic from localhost is discarded.",+ "filter_bots": "Whether bot traffic is discarded.",+ "filter_browser_extensions": "Whether errors raised by browser extensions are discarded.",+ "exclude_internal_referrers": "Whether referrals from the site's own pages are excluded.",+ "origin_allowlist": "Origins allowed to report data for the site.",+ "ip_denylist": "IP addresses whose traffic is discarded.",+ "country_code_denylist": "Country codes whose traffic is discarded.",+ "path_denylist": "URL paths whose traffic is discarded.",+ "sampling": "Percentage of sessions sampled for collection.",+ "ingestion_enabled": "Whether the site is currently accepting data.",+ "created": "ISO 8601 timestamp of when the site was created.",+ "updated": "ISO 8601 timestamp of when the site was last changed.",+ },+ },+ "site_errors": {+ "description": "JavaScript errors collected from RUM sites, grouped by error. One row per error per site.",+ "docs_url": "https://cronitor.io/docs/sites-api",+ "columns": {+ "site_key": "Key of the site the error was collected from.",+ "key": "Unique identifier of the error, used in API URLs.",+ "message": "The error message reported by the browser.",+ "source": "URL of the script the error was raised from.",+ "line": "Line number in the source script.",+ "column": "Column number in the source script.",+ "count": "Number of times the error has been seen.",+ "first_seen": "ISO 8601 timestamp of when the error was first recorded.",+ "last_seen": "ISO 8601 timestamp of when the error was most recently recorded.",+ "status": "Whether the error is open or resolved.",+ },+ },}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cronitor/cronitor.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cronitor/cronitor.pyindex 16b41451bbec..a32be4996f54 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/cronitor/cronitor.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cronitor/cronitor.py@@ -1,6 +1,5 @@import time-import dataclasses-from collections.abc import Iterator+from collections.abc import Callable, Iteratorfrom datetime import UTC, date, datetimefrom typing import Any, Optionalfrom urllib.parse import quote, urlencode, urlsplit, urlunsplit@@ -10,6 +9,8 @@ from dateutil import parserfrom structlog.types import FilteringBoundLoggerfrom tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter+from posthog.dataclasses import frozen+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_sessionfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse@@ -22,6 +23,9 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.cronitor.sMETRICS_MIN_WINDOW_SECONDS,METRICS_WINDOW_SECONDS,PAGE_SIZE,+ PAGINATED_LIST_ENDPOINTS,+ SITE_ERRORS_ENDPOINT,+ CronitorListEndpoint,)@@ -29,15 +33,21 @@ class CronitorRetryableError(Exception):pass+class CronitorResponseShapeError(Exception):+ pass+++@frozenclass CronitorResumeConfig:- # monitors: next 1-indexed page to fetch.+ # Paginated list endpoints (and site_errors within one site): next 1-indexed page to fetch.page: int | None = None# invocations: stable key bookmark of the next monitor to fan out into (not a positional# index, so monitors added/removed between a crash and the retry can't shift the resume point).monitor_key: str | None = None# metrics: Unix start of the next time window to fetch.window_start: int | None = None+ # site_errors: stable key bookmark of the next site to fan out into, paired with `page`.+ site_key: str | None = Nonedef _build_url(path: str, params: list[tuple[str, Any]] | dict[str, Any]) -> str:@@ -135,39 +145,90 @@ def _redact_monitor(monitor: dict[str, Any]) -> dict[str, Any]:return {**monitor, "request": redacted_request}-def _fetch_monitors_page(- session: requests.Session, api_key: str, logger: FilteringBoundLogger, page: int+def _extract_rows(data: Any, endpoint: CronitorListEndpoint) -> list[dict[str, Any]]:+ """Pull the row list out of a paginated response.++ Cronitor is not consistent about the envelope: monitors and groups nest the rows under a+ resource-named key while sites and site errors use `data`, so try the endpoint's documented+ key, then `data`, then a bare list.++ A 200 carrying none of them is a shape change rather than an empty page. Reading it as empty+ would let a full refresh replace the table with nothing and report success, so fail instead.+ An empty list is still a legitimate empty page.+ """+ rows: Any = data+ if isinstance(data, dict):+ rows = data.get(endpoint.envelope_key)+ if not isinstance(rows, list):+ rows = data.get("data")+ if not isinstance(rows, list):+ raise CronitorResponseShapeError(+ f"Cronitor returned an unexpected response shape for {endpoint.path}: "+ f"no list under '{endpoint.envelope_key}' or 'data'"+ )+ return [row for row in rows if isinstance(row, dict)]+++def _fetch_list_page(+ session: requests.Session,+ api_key: str,+ logger: FilteringBoundLogger,+ endpoint: CronitorListEndpoint,+ page: int,+ extra_params: list[tuple[str, Any]] | None = None,) -> tuple[list[dict[str, Any]], bool]:- """Fetch one page of the monitors list, returning (rows, has_more).+ """Fetch one page of a `page`/`pageSize` list, returning (rows, has_more).- Sort by creation time so the page walk stays stable if monitors are added mid-sync. The list- envelope documents no total count, so a short page signals the end.+ No list envelope documents a total count, so a short page signals the end."""- url = _build_url("/monitors", {"page": page, "pageSize": PAGE_SIZE, "sort": "created"})- data = _fetch(session, url, api_key, logger)- monitors = data.get("monitors") if isinstance(data, dict) else data- if not isinstance(monitors, list):- return [], False- rows = [_redact_monitor(monitor) for monitor in monitors if isinstance(monitor, dict)]+ params: list[tuple[str, Any]] = [("page", page), ("pageSize", PAGE_SIZE)]+ params.extend(endpoint.params)+ if extra_params:+ params.extend(extra_params)+ data = _fetch(session, _build_url(endpoint.path, params), api_key, logger)+ rows = _extract_rows(data, endpoint)return rows, len(rows) >= PAGE_SIZE-def _get_monitor_rows(+# Anyone holding a site's public report key can open that report without a Cronitor login, so+# drop it before a row is persisted rather than leaving the capability in a table every project+# member can query. `client_key` stays: it ships in the site's own browser snippet.+_SENSITIVE_SITE_FIELDS = ("public_report_key",)+++def _redact_site(site: dict[str, Any]) -> dict[str, Any]:+ if not any(field in site for field in _SENSITIVE_SITE_FIELDS):+ return site+ return {key: value for key, value in site.items() if key not in _SENSITIVE_SITE_FIELDS}+++# Row normalizers applied to a paginated list before its rows are yielded.+_LIST_ROW_MAPPERS: dict[str, Callable[[dict[str, Any]], dict[str, Any]]] = {+ "monitors": _redact_monitor,+ "sites": _redact_site,+}+++def _get_paginated_rows(session: requests.Session,api_key: str,logger: FilteringBoundLogger,resumable_source_manager: ResumableSourceManager[CronitorResumeConfig],+ schema_name: str,) -> Iterator[list[dict[str, Any]]]:+ endpoint = PAGINATED_LIST_ENDPOINTS[schema_name]+ row_mapper = _LIST_ROW_MAPPERS.get(schema_name)+resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else Nonepage = resume.page if resume is not None and resume.page else 1if page > 1:- logger.debug(f"Cronitor: resuming monitors from page {page}")+ logger.debug(f"Cronitor: resuming {schema_name} from page {page}")while True:- rows, has_more = _fetch_monitors_page(session, api_key, logger, page)+ rows, has_more = _fetch_list_page(session, api_key, logger, endpoint, page)if not rows:break- yield rows+ yield [row_mapper(row) for row in rows] if row_mapper is not None else rowsif not has_more:breakpage += 1@@ -176,17 +237,71 @@ def _get_monitor_rows(resumable_source_manager.save_state(CronitorResumeConfig(page=page))-def _list_monitor_keys(session: requests.Session, api_key: str, logger: FilteringBoundLogger) -> list[str]:+def _list_keys(+ session: requests.Session, api_key: str, logger: FilteringBoundLogger, endpoint: CronitorListEndpoint+) -> list[str]:keys: list[str] = []page = 1while True:- rows, has_more = _fetch_monitors_page(session, api_key, logger, page)- keys.extend(str(monitor["key"]) for monitor in rows if monitor.get("key"))+ rows, has_more = _fetch_list_page(session, api_key, logger, endpoint, page)+ keys.extend(str(row["key"]) for row in rows if row.get("key"))if not has_more:return keyspage += 1+def _list_monitor_keys(session: requests.Session, api_key: str, logger: FilteringBoundLogger) -> list[str]:+ return _list_keys(session, api_key, logger, PAGINATED_LIST_ENDPOINTS["monitors"])+++def _list_site_keys(session: requests.Session, api_key: str, logger: FilteringBoundLogger) -> list[str]:+ # The sites list takes no sort parameter, so the API order is not guaranteed between runs.+ # Sorting here gives the fan-out a stable order, which is what makes resuming at a saved site+ # key safe: without it a reordered list would skip the sites that moved behind the bookmark.+ return sorted(_list_keys(session, api_key, logger, PAGINATED_LIST_ENDPOINTS["sites"]))+++def _get_site_error_rows(+ session: requests.Session,+ api_key: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[CronitorResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ """Fan out over every RUM site, tagging each error with the site it came from.++ The errors list takes an optional `site` filter but returns no site key on the rows, so+ without the fan-out there would be no way to attribute an error to a site.+ """+ site_keys = _list_site_keys(session, api_key, logger)++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ remaining = site_keys+ page = 1+ if resume is not None and resume.site_key is not None and resume.site_key in site_keys:+ remaining = site_keys[site_keys.index(resume.site_key) :]+ page = resume.page or 1+ logger.debug(f"Cronitor: resuming site errors from site {resume.site_key} page {page}")++ for index, site_key in enumerate(remaining):+ while True:+ rows, has_more = _fetch_list_page(+ session, api_key, logger, SITE_ERRORS_ENDPOINT, page, [("site", site_key)]+ )+ if rows:+ yield [{**row, "site_key": site_key} for row in rows]+ if not has_more:+ break+ page += 1+ # Save AFTER yielding, here and below, so a crash re-yields the last page rather than+ # skipping it — merge dedupes on the primary key.+ resumable_source_manager.save_state(CronitorResumeConfig(site_key=site_key, page=page))++ if index + 1 < len(remaining):+ resumable_source_manager.save_state(CronitorResumeConfig(site_key=remaining[index + 1], page=1))+ # Only the site resumed into starts mid-list; every later site starts at page one.+ page = 1++def _get_invocation_rows(session: requests.Session,api_key: str,@@ -333,8 +448,10 @@ def get_rows(# HTTP sample capture entirely.session = make_tracked_session(capture=False)- if endpoint == "monitors":- yield from _get_monitor_rows(session, api_key, logger, resumable_source_manager)+ if endpoint in PAGINATED_LIST_ENDPOINTS:+ yield from _get_paginated_rows(session, api_key, logger, resumable_source_manager, endpoint)+ elif endpoint == "site_errors":+ yield from _get_site_error_rows(session, api_key, logger, resumable_source_manager)elif endpoint == "invocations":yield from _get_invocation_rows(session, api_key, logger, resumable_source_manager)elif endpoint == "metrics":diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cronitor/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cronitor/settings.pyindex f813e90c3d6a..8e65fc53fa7a 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/cronitor/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cronitor/settings.py@@ -1,6 +1,8 @@from dataclasses import dataclass, fieldfrom typing import Literal, Optional+from posthog.dataclasses import frozen+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldTypeBASE_URL = "https://cronitor.io/api"@@ -61,8 +63,59 @@ CRONITOR_ENDPOINTS: dict[str, CronitorEndpointConfig] = {# desc persists the incremental watermark only once the job completes.sort_mode="desc",),+ "groups": CronitorEndpointConfig(+ name="groups",+ primary_keys=["key"],+ partition_key="created",+ ),+ "issues": CronitorEndpointConfig(+ name="issues",+ primary_keys=["key"],+ # `state`, `ended`, and `duration` all change as an incident is worked, and the list offers+ # only a relative `time` window rather than an absolute since-filter, so a full refresh is+ # the only way to keep resolved incidents accurate.+ partition_key="created",+ ),+ "sites": CronitorEndpointConfig(+ name="sites",+ primary_keys=["key"],+ partition_key="created",+ ),+ "site_errors": CronitorEndpointConfig(+ name="site_errors",+ # The error key looks globally unique but the docs do not say so; the site key keeps the+ # merge key unique table-wide across the fan-out.+ primary_keys=["site_key", "key"],+ # `last_seen` moves every time the error recurs, so partition on the stable first sighting.+ partition_key="first_seen",+ ),}++@frozen+class CronitorListEndpoint:+ """A Cronitor resource served as a plain `page`/`pageSize` list."""++ path: str+ # Key the rows sit under in the response envelope.+ envelope_key: str+ params: tuple[tuple[str, str], ...] = ()+++# Endpoints synced by walking one paginated list, keyed by schema name.+PAGINATED_LIST_ENDPOINTS: dict[str, CronitorListEndpoint] = {+ # Sort by creation time so the page walk stays stable if monitors are added mid-sync.+ "monitors": CronitorListEndpoint(path="/monitors", envelope_key="monitors", params=(("sort", "created"),)),+ "groups": CronitorListEndpoint(path="/groups", envelope_key="groups"),+ # `orderBy=started` keeps the page walk stable while issues are opened mid-sync.+ "issues": CronitorListEndpoint(path="/issues", envelope_key="issues", params=(("orderBy", "started"),)),+ "sites": CronitorListEndpoint(path="/sites", envelope_key="data"),+}++# The site errors list carries no site attribution of its own, so it is fanned out over the sites+# list and each row is tagged with the site it was fetched for.+SITE_ERRORS_ENDPOINT = CronitorListEndpoint(path="/site_errors", envelope_key="data")+ENDPOINTS = tuple(CRONITOR_ENDPOINTS.keys())INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cronitor/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cronitor/source.pyindex ed0e46e588bd..9f739dc58ee0 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/cronitor/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cronitor/source.py@@ -46,9 +46,9 @@ class CronitorSource(ResumableSource[CronitorSourceConfig, CronitorResumeConfig]category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="Cronitor",releaseStatus=ReleaseStatus.ALPHA,- caption="""Import your Cronitor monitors, their recent job invocations, and time-series reliability metrics into the PostHog Data warehouse.+ caption="""Import your Cronitor monitors, monitor groups, recent job invocations, time-series reliability metrics, issues, and RUM sites with their JavaScript errors into the PostHog Data warehouse.-Create an API key with the `monitor:read` scope under **Settings → API keys** in your Cronitor account, and enter it here.""",+Create an API key under **Settings → API keys** in your Cronitor account, and enter it here. The key needs `monitor:read` to connect. Add `issue:read` to sync issues, and `site:read` to sync sites and site errors.""",iconPath="/static/services/cronitor.png",docsUrl="https://posthog.com/docs/cdp/sources/cronitor",fields=cast(@@ -79,7 +79,10 @@ Create an API key with the `monitor:read` scope under **Settings → API keys**# Retrying can never fix a credential/scope problem, so fail the sync. Match the stable# status text, not the per-request path."401 Client Error: Unauthorized": "Your Cronitor API key is invalid or has been revoked. Create a new key in your Cronitor account's API settings, then reconnect.",- "403 Client Error: Forbidden": "Your Cronitor API key is missing the monitor:read scope needed to sync this data. Update the key's scopes, then reconnect.",+ # A changed response shape cannot fix itself on retry, so fail with something the+ # user can act on instead of looping.+ "Cronitor returned an unexpected response shape": "Cronitor returned data PostHog could not read, so this table was not synced. The Cronitor API may have changed. Contact support so the connector can be updated.",+ "403 Client Error: Forbidden": "Your Cronitor API key is missing a scope needed to sync this table. Monitors, groups, invocations and metrics need monitor:read, issues need issue:read, and sites and site errors need site:read. Update the key's scopes, then reconnect.",}def get_schemas(diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cronitor/tests/test_cronitor.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cronitor/tests/test_cronitor.pyindex 77c71b0ec2cd..a103d9b81cce 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/cronitor/tests/test_cronitor.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cronitor/tests/test_cronitor.py@@ -18,6 +18,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.cronitor.cget_rows,)from products.warehouse_sources.backend.temporal.data_imports.sources.cronitor.settings import (+ CRONITOR_ENDPOINTS,+ ENDPOINTS,METRICS_MIN_WINDOW_SECONDS,PAGE_SIZE,)@@ -77,8 +79,12 @@ def _collect(manager: _FakeResumableManager, endpoint: str, **kwargs: Any) -> lireturn rows+def _list_url(path: str, page: int, extra: str = "") -> str:+ return f"https://cronitor.io/api{path}?page={page}&pageSize={PAGE_SIZE}{extra}"++def _monitors_url(page: int) -> str:- return f"https://cronitor.io/api/monitors?page={page}&pageSize={PAGE_SIZE}&sort=created"+ return _list_url("/monitors", page, "&sort=created")def _monitors_page(count: int, prefix: str = "job") -> dict[str, Any]:@@ -128,9 +134,12 @@ class TestMonitors:assert len(rows) == 1assert fetched == [_monitors_url(3)]- def test_unexpected_envelope_yields_nothing(self, monkeypatch: Any) -> None:+ def test_unexpected_envelope_fails_the_sync(self, monkeypatch: Any) -> None:+ # Reading an unrecognized 200 as an empty page would let a full refresh replace the table+ # with nothing and report success._patch_fetch(monkeypatch, {_monitors_url(1): {"detail": "something unexpected"}})- assert _collect(_FakeResumableManager(), "monitors") == []+ with pytest.raises(cronitor.CronitorResponseShapeError):+ _collect(_FakeResumableManager(), "monitors")def test_sensitive_request_config_is_redacted(self, monkeypatch: Any) -> None:# HTTP-check monitors embed the outbound request config, which can carry credentials:@@ -230,6 +239,128 @@ class TestInvocations:assert self._detail_url("job-a") not in fetched+class TestPaginatedListEndpoints:+ @pytest.mark.parametrize(+ "endpoint, path, extra, envelope_key",+ [+ ("groups", "/groups", "", "groups"),+ # Issues are ordered by start time so the page walk stays stable as incidents open.+ ("issues", "/issues", "&orderBy=started", "issues"),+ # Sites nests its rows under `data` rather than a resource-named key.+ ("sites", "/sites", "", "data"),+ ],+ )+ def test_requests_the_documented_path_and_reads_its_envelope(+ self, endpoint: str, path: str, extra: str, envelope_key: str, monkeypatch: Any+ ) -> None:+ url = _list_url(path, 1, extra)+ fetched = _patch_fetch(monkeypatch, {url: {envelope_key: [{"key": "a"}, {"key": "b"}]}})+ rows = _collect(_FakeResumableManager(), endpoint)++ assert fetched == [url]+ assert [row["key"] for row in rows] == ["a", "b"]++ def test_issues_envelope_falls_back_to_data(self, monkeypatch: Any) -> None:+ # The issues list envelope is the one Cronitor does not publish, so a `data` envelope has+ # to keep working or the table would silently sync zero rows.+ url = _list_url("/issues", 1, "&orderBy=started")+ _patch_fetch(monkeypatch, {url: {"data": [{"key": "c096dd184de20330"}]}})++ assert [row["key"] for row in _collect(_FakeResumableManager(), "issues")] == ["c096dd184de20330"]++ def test_every_schema_is_routed_to_a_transport(self, monkeypatch: Any) -> None:+ # A schema listed in the wizard but missing a transport branch only fails once a user+ # selects it, so walk every advertised endpoint against an API holding no rows.+ empty_page: dict[str, Any] = {"monitors": [], "groups": [], "issues": [], "data": []}+ _freeze_now(monkeypatch)+ monkeypatch.setattr(cronitor, "_fetch", lambda session, url, api_key, logger: empty_page)++ for endpoint in ENDPOINTS:+ assert _collect(_FakeResumableManager(), endpoint) == []+++class TestSiteErrors:+ def _errors_url(self, site_key: str, page: int) -> str:+ return _list_url("/site_errors", page, f"&site={site_key}")++ def _sites_page(self, *keys: str) -> dict[str, Any]:+ return {"data": [{"key": key} for key in keys]}++ def test_fans_out_over_sites_and_tags_rows_with_site_key(self, monkeypatch: Any) -> None:+ responses = {+ _list_url("/sites", 1): self._sites_page("site-a", "site-b"),+ self._errors_url("site-a", 1): {"data": [{"key": "err-1"}]},+ self._errors_url("site-b", 1): {"data": [{"key": "err-2"}]},+ }+ _patch_fetch(monkeypatch, responses)+ manager = _FakeResumableManager()+ rows = _collect(manager, "site_errors")++ assert [(row["site_key"], row["key"]) for row in rows] == [("site-a", "err-1"), ("site-b", "err-2")]+ # The site key is injected by the fan-out, not returned by the API, so every declared+ # merge key must actually be present or the merge would key on nulls.+ primary_keys = CRONITOR_ENDPOINTS["site_errors"].primary_keys+ assert all(all(key in row for key in primary_keys) for row in rows)+ # Bookmark advanced to the next site after site-a's rows were yielded.+ assert manager.saved == [CronitorResumeConfig(site_key="site-b", page=1)]++ def test_public_report_key_is_redacted(self, monkeypatch: Any) -> None:+ # The key opens the site's performance report without a Cronitor login, so it must not+ # land in a table every project member can query.+ site: dict[str, Any] = {+ "key": "site-a",+ "name": "Main Website",+ "client_key": "ck_public",+ "public_report_key": "pr_capability",+ }+ _patch_fetch(monkeypatch, {_list_url("/sites", 1): {"data": [site]}})+ rows = _collect(_FakeResumableManager(), "sites")++ assert rows == [{"key": "site-a", "name": "Main Website", "client_key": "ck_public"}]+ # The original response dict must not be mutated in place.+ assert "public_report_key" in site++ def test_fan_out_order_does_not_follow_the_api(self, monkeypatch: Any) -> None:+ # The sites list takes no sort parameter, so a reordered list would push sites behind a+ # saved bookmark and skip them on resume.+ responses = {+ _list_url("/sites", 1): self._sites_page("site-c", "site-a", "site-b"),+ self._errors_url("site-a", 1): {"data": [{"key": "err-a"}]},+ self._errors_url("site-b", 1): {"data": [{"key": "err-b"}]},+ self._errors_url("site-c", 1): {"data": [{"key": "err-c"}]},+ }+ _patch_fetch(monkeypatch, responses)+ rows = _collect(_FakeResumableManager(), "site_errors")++ assert [row["site_key"] for row in rows] == ["site-a", "site-b", "site-c"]++ def test_paginates_within_a_site_until_short_page(self, monkeypatch: Any) -> None:+ responses = {+ _list_url("/sites", 1): self._sites_page("site-a"),+ self._errors_url("site-a", 1): {"data": [{"key": f"full-{i}"} for i in range(PAGE_SIZE)]},+ self._errors_url("site-a", 2): {"data": [{"key": "tail-0"}]},+ }+ fetched = _patch_fetch(monkeypatch, responses)+ manager = _FakeResumableManager()+ rows = _collect(manager, "site_errors")++ assert len(rows) == PAGE_SIZE + 1+ assert fetched == list(responses)+ assert manager.saved == [CronitorResumeConfig(site_key="site-a", page=2)]++ def test_resumes_from_site_and_page_bookmark(self, monkeypatch: Any) -> None:+ responses = {+ _list_url("/sites", 1): self._sites_page("site-a", "site-b"),+ self._errors_url("site-b", 3): {"data": [{"key": "err-9"}]},+ }+ fetched = _patch_fetch(monkeypatch, responses)+ rows = _collect(_FakeResumableManager(CronitorResumeConfig(site_key="site-b", page=3)), "site_errors")++ assert [(row["site_key"], row["key"]) for row in rows] == [("site-b", "err-9")]+ # site-a finished before the crash, and site-b restarts at the saved page, not page 1.+ assert self._errors_url("site-a", 1) not in fetched++class TestFlattenMetricsResponse:def test_flattens_and_coerces_stamp_to_int(self) -> None:data = {diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/cronitor/tests/test_cronitor_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/cronitor/tests/test_cronitor_source.pyindex a5ce318609e9..a49133503edf 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/cronitor/tests/test_cronitor_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/cronitor/tests/test_cronitor_source.py@@ -9,7 +9,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.generated_# Only the metrics API exposes a server-side time filter (start/end); everything else is full refresh._INCREMENTAL_ENDPOINTS = {"metrics"}-_FULL_REFRESH_ENDPOINTS = {"monitors", "invocations"}+_FULL_REFRESH_ENDPOINTS = {"monitors", "invocations", "groups", "issues", "sites", "site_errors"}class TestCronitorSource: