Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

feat(data-warehouse): implement airbrake import source (#71182)

Tom Owers4e430ff4c6f4
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index d6be39a739ab..56741d344703 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -47,6 +47,7 @@ the row lists both.
| adroll | HTTP | requests | ✅ |
| agilecrm | HTTP | requests | ✅ |
| aha | HTTP | requests | ✅ |
+| airbrake | HTTP | requests | ✅ |
| aircall | HTTP | requests | ✅ |
| airops | HTTP | requests | ✅ |
| airtable | HTTP | requests | ✅ |
@@ -543,7 +544,6 @@ doesn't conflict with concurrent PRs.
- adyen
- ahrefs
- aikido_security
-- airbrake
- airbyte
- airops
- aiven
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/airbrake/airbrake.py b/products/warehouse_sources/backend/temporal/data_imports/sources/airbrake/airbrake.py
new file mode 100644
index 000000000000..dfacd4cf4cf2
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/airbrake/airbrake.py
@@ -0,0 +1,377 @@
+import dataclasses
+from collections.abc import Iterator
+from datetime import UTC, date, datetime
+from typing import Any, Optional
+
+import requests
+from structlog.types import FilteringBoundLogger
+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.airbrake.settings import (
+ AIRBRAKE_ENDPOINTS,
+ AirbrakeEndpointConfig,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+
+AIRBRAKE_BASE_URL = "https://api.airbrake.io"
+PAGE_LIMIT = 100
+# Page/limit pagination has no cursor, so a server that ignored `page` would loop forever
+# on the same items. This cap is a safety valve, far above any realistic collection size.
+MAX_PAGES_PER_COLLECTION = 10_000
+# Notices are the unbounded fan-out (every occurrence of every error group); cap the history
+# pulled per group so one noisy group can't dominate the sync.
+NOTICES_MAX_PAGES_PER_GROUP = 20
+# Per-group and per-collection caps bound each child request, but not the two-level fan-out as a
+# whole: an account with a huge number of error groups would otherwise keep an import worker busy
+# for the full activity timeout. Bound the total groups a single notice sync fans out into — a
+# safety valve far above any realistic account, not an expected limit.
+NOTICES_MAX_GROUPS_PER_SYNC = 10_000
+
+
+class AirbrakeRetryableError(Exception):
+ pass
+
+
+class AirbrakeResumeConfig:
+ # Next page to fetch within the current collection.
+ page: int = 1
+ # Stable parent bookmarks (not positional indexes), so projects/groups added or removed
+ # between a crash and the retry can't resume us into the wrong parent.
+ project_id: int | None = None
+ group_id: str | None = None
+
+
+def _format_start_time(value: Any) -> str:
+ """Format an incremental cursor as the RFC 3339 UTC timestamp Airbrake expects."""
+ if isinstance(value, datetime):
+ utc_value = value.replace(tzinfo=UTC) if value.tzinfo is None else value.astimezone(UTC)
+ return utc_value.strftime("%Y-%m-%dT%H:%M:%S.%f")[:-3] + "Z"
+ if isinstance(value, date):
+ return _format_start_time(datetime.combine(value, datetime.min.time(), tzinfo=UTC))
+ return str(value)
+
+
+@retry(
+ retry=retry_if_exception_type(
+ (
+ AirbrakeRetryableError,
+ requests.ReadTimeout,
+ requests.ConnectionError,
+ requests.exceptions.ChunkedEncodingError,
+ )
+ ),
+ stop=stop_after_attempt(5),
+ wait=wait_exponential_jitter(initial=1, max=30),
+ reraise=True,
+)
+def _fetch_page(
+ session: requests.Session, url: str, params: dict[str, Any], logger: FilteringBoundLogger
+) -> dict[str, Any]:
+ response = session.get(url, params=params, timeout=60)
+
+ # Airbrake returns 429 on quota exhaustion; explicit request rate limits aren't documented.
+ if response.status_code == 429 or response.status_code >= 500:
+ raise AirbrakeRetryableError(f"Airbrake API error (retryable): status={response.status_code}, url={url}")
+
+ if not response.ok:
+ # 404 is expected during fan-out (a project/group deleted mid-sync) and handled by callers.
+ log = logger.warning if response.status_code == 404 else logger.error
+ log(f"Airbrake API error: status={response.status_code}, body={response.text}, url={url}")
+ # Not raise_for_status(): its message embeds response.url, which carries the ?key=
+ # credential, and the message is persisted into job errors and logs. `url` is query-free.
+ raise requests.HTTPError(
+ f"{response.status_code} Client Error: {response.reason} for url: {url}", response=response
+ )
+
+ return response.json()
+
+
+def _iter_pages(
+ session: requests.Session,
+ api_key: str,
+ path: str,
+ collection_key: str,
+ logger: FilteringBoundLogger,
+ params: Optional[dict[str, Any]] = None,
+ start_page: int = 1,
+ max_pages: int = MAX_PAGES_PER_COLLECTION,
+) -> Iterator[tuple[int, list[dict[str, Any]]]]:
+ """Walk a page/limit-paginated collection, yielding (page_number, items) per page.
+
+ Termination is driven by an empty page rather than `len(items) < limit`: the docs state no
+ maximum for `limit`, so a server silently clamping our requested page size below PAGE_LIMIT
+ must not be mistaken for the final page.
+ """
+ page = start_page
+ while True:
+ if page - start_page + 1 > max_pages:
+ logger.warning(f"Airbrake: page cap ({max_pages}) reached for {path}, truncating collection")
+ break
+
+ data = _fetch_page(
+ session,
+ f"{AIRBRAKE_BASE_URL}{path}",
+ {"key": api_key, "limit": PAGE_LIMIT, "page": page, **(params or {})},
+ logger,
+ )
+ items = data.get(collection_key) or []
+ if not items:
+ break
+
+ yield page, items
+
+ # When the whole collection fits in the first page, `count` lets us skip the
+ # trailing empty-page request.
+ count = data.get("count")
+ if page == 1 and start_page == 1 and isinstance(count, int) and count <= len(items):
+ break
+ page += 1
+
+
+def _list_projects(session: requests.Session, api_key: str, logger: FilteringBoundLogger) -> list[dict[str, Any]]:
+ return [
+ item for _page, items in _iter_pages(session, api_key, "/api/v4/projects", "projects", logger) for item in items
+ ]
+
+
+def _load_resume(manager: ResumableSourceManager[AirbrakeResumeConfig]) -> AirbrakeResumeConfig | None:
+ return manager.load_state() if manager.can_resume() else None
+
+
+def _is_not_found(exc: requests.HTTPError) -> bool:
+ return exc.response is not None and exc.response.status_code == 404
+
+
+def _projects_rows(
+ session: requests.Session,
+ api_key: str,
+ logger: FilteringBoundLogger,
+ manager: ResumableSourceManager[AirbrakeResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ resume = _load_resume(manager)
+ start_page = resume.page if resume else 1
+
+ for page, items in _iter_pages(session, api_key, "/api/v4/projects", "projects", logger, start_page=start_page):
+ yield items
+ # Save AFTER yielding so a crash re-yields the last page rather than skipping it.
+ manager.save_state(AirbrakeResumeConfig(page=page + 1))
+
+
+def _slice_from_bookmark(items: list[Any], bookmark: Any) -> tuple[list[Any], bool]:
+ """Return the slice starting at `bookmark` (or the full list when it's gone) and whether it matched."""
+ if bookmark is not None and bookmark in items:
+ return items[items.index(bookmark) :], True
+ return items, False
+
+
+def _project_fan_out_rows(
+ session: requests.Session,
+ api_key: str,
+ endpoint_config: AirbrakeEndpointConfig,
+ logger: FilteringBoundLogger,
+ manager: ResumableSourceManager[AirbrakeResumeConfig],
+ params: Optional[dict[str, Any]] = None,
+ inject_project_id: bool = False,
+) -> Iterator[list[dict[str, Any]]]:
+ """Fan out one paginated collection request per project (groups, deploys)."""
+ project_ids = [project["id"] for project in _list_projects(session, api_key, logger)]
+
+ resume = _load_resume(manager)
+ remaining, resumed = _slice_from_bookmark(project_ids, resume.project_id if resume else None)
+ resume_page = resume.page if resume is not None and resumed else 1
+
+ for index, project_id in enumerate(remaining):
+ path = endpoint_config.path.format(project_id=project_id)
+ start_page = resume_page if index == 0 else 1
+
+ try:
+ for page, items in _iter_pages(
+ session, api_key, path, endpoint_config.collection_key, logger, params=params, start_page=start_page
+ ):
+ if inject_project_id:
+ items = [{**item, "projectId": project_id} for item in items]
+ yield items
+ manager.save_state(AirbrakeResumeConfig(page=page + 1, project_id=project_id))
+ except requests.HTTPError as exc:
+ # A project deleted between enumeration and this fetch 404s; its data is genuinely
+ # gone, so skip it rather than failing the whole sync.
+ if _is_not_found(exc):
+ logger.warning(f"Airbrake: project {project_id} not found while fetching {endpoint_config.name}")
+ else:
+ raise
+
+ if index + 1 < len(remaining):
+ manager.save_state(AirbrakeResumeConfig(page=1, project_id=remaining[index + 1]))
+
+
+def _list_group_ids(
+ session: requests.Session, api_key: str, project_id: int, logger: FilteringBoundLogger
+) -> list[str]:
+ return [
+ group["id"]
+ for _page, items in _iter_pages(
+ session, api_key, f"/api/v4/projects/{project_id}/groups", "groups", logger, params={"order": "created"}
+ )
+ for group in items
+ ]
+
+
+def _notices_rows(
+ session: requests.Session,
+ api_key: str,
+ endpoint_config: AirbrakeEndpointConfig,
+ logger: FilteringBoundLogger,
+ manager: ResumableSourceManager[AirbrakeResumeConfig],
+) -> Iterator[list[dict[str, Any]]]:
+ """Two-level fan-out: every error group of every project, then that group's notices."""
+ project_ids = [project["id"] for project in _list_projects(session, api_key, logger)]
+
+ resume = _load_resume(manager)
+ remaining_projects, resumed_project = _slice_from_bookmark(project_ids, resume.project_id if resume else None)
+
+ groups_fanned_out = 0
+ for project_index, project_id in enumerate(remaining_projects):
+ try:
+ group_ids = _list_group_ids(session, api_key, project_id, logger)
+ except requests.HTTPError as exc:
+ if _is_not_found(exc):
+ logger.warning(f"Airbrake: project {project_id} not found while enumerating groups")
+ continue
+ raise
+
+ resume_this_project = project_index == 0 and resumed_project
+ remaining_groups, resumed_group = _slice_from_bookmark(
+ group_ids, resume.group_id if resume is not None and resume_this_project else None
+ )
+
+ for group_index, group_id in enumerate(remaining_groups):
+ if groups_fanned_out >= NOTICES_MAX_GROUPS_PER_SYNC:
+ logger.warning(
+ f"Airbrake: notice group budget ({NOTICES_MAX_GROUPS_PER_SYNC}) reached, stopping notice sync"
+ )
+ return
+ groups_fanned_out += 1
+
+ start_page = resume.page if resume is not None and resumed_group and group_index == 0 else 1
+ path = endpoint_config.path.format(project_id=project_id, group_id=group_id)
+
+ try:
+ for page, items in _iter_pages(
+ session,
+ api_key,
+ path,
+ endpoint_config.collection_key,
+ logger,
+ start_page=start_page,
+ max_pages=NOTICES_MAX_PAGES_PER_GROUP,
+ ):
+ yield items
+ manager.save_state(AirbrakeResumeConfig(page=page + 1, project_id=project_id, group_id=group_id))
+ except requests.HTTPError as exc:
+ if _is_not_found(exc):
+ logger.warning(f"Airbrake: group {group_id} in project {project_id} not found, skipping notices")
+ else:
+ raise
+
+ if group_index + 1 < len(remaining_groups):
+ manager.save_state(
+ AirbrakeResumeConfig(page=1, project_id=project_id, group_id=remaining_groups[group_index + 1])
+ )
+
+ if project_index + 1 < len(remaining_projects):
+ manager.save_state(AirbrakeResumeConfig(page=1, project_id=remaining_projects[project_index + 1]))
+
+
+def _build_groups_params(
+ should_use_incremental_field: bool, db_incremental_field_last_value: Optional[Any]
+) -> dict[str, Any]:
+ # `created` is the one immutable sort key, keeping page boundaries stable while new
+ # notices arrive mid-sync (the default `last_notice` order reshuffles groups between pages).
+ params: dict[str, Any] = {"order": "created"}
+ if should_use_incremental_field and db_incremental_field_last_value is not None:
+ # start_time is a server-side filter on group creation time.
+ params["start_time"] = _format_start_time(db_incremental_field_last_value)
+ return params
+
+
+def get_rows(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[AirbrakeResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> Iterator[list[dict[str, Any]]]:
+ endpoint_config = AIRBRAKE_ENDPOINTS[endpoint]
+ # One session reused across every page and parent so the connection stays alive.
+ session = make_tracked_session()
+
+ if endpoint == "projects":
+ yield from _projects_rows(session, api_key, logger, resumable_source_manager)
+ elif endpoint == "groups":
+ yield from _project_fan_out_rows(
+ session,
+ api_key,
+ endpoint_config,
+ logger,
+ resumable_source_manager,
+ params=_build_groups_params(should_use_incremental_field, db_incremental_field_last_value),
+ )
+ elif endpoint == "deploys":
+ # Deploy rows don't reference their project, so stamp projectId on for joinability.
+ yield from _project_fan_out_rows(
+ session, api_key, endpoint_config, logger, resumable_source_manager, inject_project_id=True
+ )
+ elif endpoint == "notices":
+ yield from _notices_rows(session, api_key, endpoint_config, logger, resumable_source_manager)
+ else:
+ raise ValueError(f"Unknown Airbrake endpoint: {endpoint}")
+
+
+def airbrake_source(
+ api_key: str,
+ endpoint: str,
+ logger: FilteringBoundLogger,
+ resumable_source_manager: ResumableSourceManager[AirbrakeResumeConfig],
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ endpoint_config = AIRBRAKE_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,
+ ),
+ primary_keys=endpoint_config.primary_keys,
+ # Fan-out endpoints persist the incremental watermark only at successful job end (desc
+ # mode): a partial run's max says nothing about projects it never reached. Airbrake also
+ # doesn't document the direction of its `order` sorts, so per-batch asc checkpointing
+ # can't be trusted for the top-level list either.
+ sort_mode="desc",
+ partition_count=1 if endpoint_config.partition_key else None,
+ partition_size=1 if endpoint_config.partition_key else None,
+ partition_mode="datetime" if endpoint_config.partition_key else None,
+ partition_format="month" if endpoint_config.partition_key else None,
+ partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,
+ )
+
+
+def validate_credentials(api_key: str) -> bool:
+ try:
+ response = make_tracked_session().get(
+ f"{AIRBRAKE_BASE_URL}/api/v4/projects",
+ params={"key": api_key, "limit": "1"},
+ timeout=10,
+ )
+ return response.status_code == 200
+ except Exception:
+ return False
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/airbrake/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/airbrake/canonical_descriptions.py
new file mode 100644
index 000000000000..cf31fd4a38c7
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/airbrake/canonical_descriptions.py
@@ -0,0 +1,71 @@
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "projects": {
+ "description": "Airbrake projects accessible to the connected user key, with per-project error and deploy counters.",
+ "docs_url": "https://docs.airbrake.io/docs/devops-tools/api/",
+ "columns": {
+ "id": "Unique identifier for the project.",
+ "name": "Name of the project as shown in Airbrake.",
+ "deployId": "Identifier of the project's most recent deploy.",
+ "deployAt": "Timestamp of the project's most recent deploy.",
+ "noticeTotalCount": "Total number of notices (error occurrences) recorded for the project.",
+ "rejectionCount": "Number of notices rejected (e.g. over quota or filtered).",
+ "fileCount": "Number of distinct source files referenced by the project's errors.",
+ "deployCount": "Total number of deploys tracked for the project.",
+ "groupResolvedCount": "Number of error groups marked as resolved.",
+ "groupUnresolvedCount": "Number of error groups not yet resolved.",
+ },
+ },
+ "groups": {
+ "description": "Error groups (aggregated occurrences of the same error) across every project the key can access.",
+ "docs_url": "https://docs.airbrake.io/docs/devops-tools/api/",
+ "columns": {
+ "id": "Unique identifier for the error group.",
+ "projectId": "Identifier of the project the group belongs to.",
+ "resolved": "Whether the group has been marked as resolved.",
+ "errors": "Error type, message, and backtrace of the group's representative error.",
+ "context": "Context shared by the group's notices, such as the environment.",
+ "lastDeployId": "Identifier of the deploy most recently associated with the group.",
+ "lastDeployAt": "Timestamp of the deploy most recently associated with the group.",
+ "lastNoticeId": "Identifier of the group's most recent notice.",
+ "lastNoticeAt": "Timestamp of the group's most recent notice.",
+ "noticeCount": "Number of notices in the group since it was last resolved.",
+ "noticeTotalCount": "Total number of notices ever recorded in the group.",
+ "createdAt": "Timestamp when the error group was first created.",
+ },
+ },
+ "notices": {
+ "description": "Individual error occurrences, fetched per error group across every project.",
+ "docs_url": "https://docs.airbrake.io/docs/devops-tools/api/",
+ "columns": {
+ "id": "Unique identifier for the notice.",
+ "projectId": "Identifier of the project the notice belongs to.",
+ "groupId": "Identifier of the error group the notice was aggregated into.",
+ "deployId": "Identifier of the deploy active when the notice was recorded.",
+ "deployAt": "Timestamp of the deploy active when the notice was recorded.",
+ "errors": "Error type, message, and backtrace captured by the notifier.",
+ "context": "Request/runtime context: environment, hostname, language, severity, notifier, and more.",
+ "environment": "Application-supplied environment variables attached to the notice.",
+ "session": "Application-supplied session data attached to the notice.",
+ "params": "Application-supplied parameters attached to the notice.",
+ "createdAt": "Timestamp when the notice was recorded.",
+ },
+ },
+ "deploys": {
+ "description": "Deploys tracked per project. Airbrake's API returns no deploy identifier, so this table is full-refresh only; projectId is added by PostHog for joinability.",
+ "docs_url": "https://docs.airbrake.io/docs/devops-tools/api/",
+ "columns": {
+ "projectId": "Identifier of the project the deploy belongs to (added by PostHog; not returned by the Airbrake API).",
+ "environment": "Environment the deploy targeted, e.g. production.",
+ "username": "User who performed the deploy.",
+ "email": "Email of the user who performed the deploy.",
+ "gravatarId": "Gravatar hash of the deploying user.",
+ "repository": "Repository the deploy was made from.",
+ "revision": "VCS revision (e.g. git SHA) that was deployed.",
+ "version": "Application version label for the deploy.",
+ },
+ },
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/airbrake/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/airbrake/settings.py
new file mode 100644
index 000000000000..e5fac7b363a2
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/airbrake/settings.py
@@ -0,0 +1,72 @@
+from dataclasses import dataclass, field
+
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+
+@dataclass
+class AirbrakeEndpointConfig:
+ name: str
+ # Path template; `{project_id}` / `{group_id}` are resolved during fan-out.
+ path: str
+ # Key wrapping the item collection in the response body (e.g. {"count": 1, "groups": [...]}).
+ collection_key: str
+ # None for endpoints whose rows expose no unique identifier (deploys) — full refresh only.
+ primary_keys: list[str] | None
+ incremental_fields: list[IncrementalField] = field(default_factory=list)
+ partition_key: str | None = None
+ should_sync_default: bool = True
+ # Fan-out depth: 0 = top-level, 1 = per project, 2 = per project per group.
+ fan_out_depth: int = 0
+
+
+AIRBRAKE_ENDPOINTS: dict[str, AirbrakeEndpointConfig] = {
+ "projects": AirbrakeEndpointConfig(
+ name="projects",
+ path="/api/v4/projects",
+ collection_key="projects",
+ primary_keys=["id"],
+ ),
+ "groups": AirbrakeEndpointConfig(
+ name="groups",
+ path="/api/v4/projects/{project_id}/groups",
+ collection_key="groups",
+ # Group ids are unique across projects (the cross-project /api/v4/groups endpoint
+ # addresses groups by bare id).
+ primary_keys=["id"],
+ partition_key="createdAt",
+ fan_out_depth=1,
+ incremental_fields=[
+ {
+ "label": "createdAt",
+ "type": IncrementalFieldType.DateTime,
+ "field": "createdAt",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
+ ),
+ "deploys": AirbrakeEndpointConfig(
+ name="deploys",
+ path="/api/v4/projects/{project_id}/deploys",
+ collection_key="deploys",
+ # Deploy rows carry no id or timestamp, so there is nothing to merge or partition on.
+ primary_keys=None,
+ fan_out_depth=1,
+ ),
+ # One paginated request per error group across every project, so this is the most
+ # API-expensive table — opt-in rather than synced by default.
+ "notices": AirbrakeEndpointConfig(
+ name="notices",
+ path="/api/v4/projects/{project_id}/groups/{group_id}/notices",
+ collection_key="notices",
+ primary_keys=["groupId", "id"],
+ partition_key="createdAt",
+ should_sync_default=False,
+ fan_out_depth=2,
+ ),
+}
+
+ENDPOINTS = tuple(AIRBRAKE_ENDPOINTS.keys())
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ name: config.incremental_fields for name, config in AIRBRAKE_ENDPOINTS.items()
+}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/airbrake/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/airbrake/source.py
index 54f6fbb068a7..88348fefc12b 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/airbrake/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/airbrake/source.py
@@ -1,19 +1,43 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (
+ SourceInputs,
+ SourceResponse,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.airbrake.airbrake import (
+ AirbrakeResumeConfig,
+ airbrake_source,
+ validate_credentials as validate_airbrake_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.airbrake.settings import (
+ AIRBRAKE_ENDPOINTS,
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import SourceSchema
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import AirbrakeSourceConfig
from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
-class AirbrakeSource(SimpleSource[AirbrakeSourceConfig]):
+class AirbrakeSource(ResumableSource[AirbrakeSourceConfig, AirbrakeResumeConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.AIRBRAKE
@@ -24,7 +48,106 @@ class AirbrakeSource(SimpleSource[AirbrakeSourceConfig]):
name=SchemaExternalDataSourceType.AIRBRAKE,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="Airbrake",
+ releaseStatus=ReleaseStatus.ALPHA,
+ caption="""Enter your Airbrake user API key to pull your Airbrake error monitoring data into the PostHog Data warehouse.
+
+You can find your user key in your Airbrake profile settings under **User settings**. All projects the key can access are synced.
+""",
iconPath="/static/services/airbrake.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ docsUrl="https://posthog.com/docs/cdp/sources/airbrake",
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="User API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ ),
+ ],
+ ),
+ )
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.airbrake.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ # Auth failures surface as a requests HTTPError from `raise_for_status()`. Match the
+ # stable status text and base host, not the per-request path/query.
+ "401 Client Error: Unauthorized for url: https://api.airbrake.io": "Your Airbrake user API key is invalid or has been revoked. Generate a new key in your Airbrake user settings, then reconnect.",
+ "403 Client Error: Forbidden for url: https://api.airbrake.io": "Your Airbrake user API key does not have access to this data. Check the key's project access in Airbrake, then reconnect.",
+ }
+
+ def get_schemas(
+ self,
+ config: AirbrakeSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ ) -> list[SourceSchema]:
+ def _description(endpoint: str) -> str | None:
+ if endpoint == "groups":
+ return (
+ "Incremental syncs only pick up newly created error groups; fields that mutate on "
+ "existing groups (noticeCount, resolved, lastNoticeAt) are only refreshed by a full refresh"
+ )
+ if endpoint == "notices":
+ return (
+ "Individual error occurrences, fetched per error group across every project — the most "
+ "API-expensive table, capped at the most recent pages per group"
+ )
+ return None
+
+ schemas = [
+ SourceSchema(
+ name=endpoint,
+ supports_incremental=len(INCREMENTAL_FIELDS.get(endpoint, [])) > 0,
+ supports_append=len(INCREMENTAL_FIELDS.get(endpoint, [])) > 0,
+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),
+ should_sync_default=AIRBRAKE_ENDPOINTS[endpoint].should_sync_default,
+ description=_description(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: AirbrakeSourceConfig, team_id: int, schema_name: Optional[str] = None
+ ) -> tuple[bool, str | None]:
+ if validate_airbrake_credentials(config.api_key):
+ return True, None
+
+ return False, "Invalid Airbrake user API key"
+
+ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[AirbrakeResumeConfig]:
+ return ResumableSourceManager[AirbrakeResumeConfig](inputs, AirbrakeResumeConfig)
+
+ def source_for_pipeline(
+ self,
+ config: AirbrakeSourceConfig,
+ resumable_source_manager: ResumableSourceManager[AirbrakeResumeConfig],
+ inputs: SourceInputs,
+ ) -> SourceResponse:
+ return airbrake_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,
)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/airbrake/tests/test_airbrake.py b/products/warehouse_sources/backend/temporal/data_imports/sources/airbrake/tests/test_airbrake.py
new file mode 100644
index 000000000000..7016dbdac426
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/airbrake/tests/test_airbrake.py
@@ -0,0 +1,421 @@
+from datetime import UTC, date, datetime
+from typing import Any
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+import requests
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.airbrake import airbrake
+from products.warehouse_sources.backend.temporal.data_imports.sources.airbrake.airbrake import (
+ NOTICES_MAX_PAGES_PER_GROUP,
+ PAGE_LIMIT,
+ AirbrakeResumeConfig,
+ _build_groups_params,
+ _format_start_time,
+ airbrake_source,
+ get_rows,
+ validate_credentials,
+)
+
+
+class _FakeResumableManager:
+ def __init__(self, state: AirbrakeResumeConfig | None = None) -> None:
+ self._state = state
+ self.saved: list[AirbrakeResumeConfig] = []
+
+ def can_resume(self) -> bool:
+ return self._state is not None
+
+ def load_state(self) -> AirbrakeResumeConfig | None:
+ return self._state
+
+ def save_state(self, data: AirbrakeResumeConfig) -> None:
+ self.saved.append(data)
+
+
+def _response_with_status(status_code: int) -> requests.Response:
+ response = requests.Response()
+ response.status_code = status_code
+ return response
+
+
+class _FakePages:
+ """Fixture keyed by (path, page). Missing keys mean 'empty page' so pagination terminates."""
+
+ def __init__(self, pages: dict[tuple[str, int], Any]) -> None:
+ self.pages = pages
+ self.requests: list[tuple[str, dict[str, Any]]] = []
+
+ def __call__(self, session: Any, url: str, params: dict[str, Any], logger: Any) -> dict[str, Any]:
+ path = url.removeprefix("https://api.airbrake.io")
+ self.requests.append((path, params))
+ result = self.pages.get((path, params["page"]), {})
+ if isinstance(result, Exception):
+ raise result
+ return result
+
+
+def _collect(
+ manager: _FakeResumableManager, monkeypatch: Any, pages: _FakePages, endpoint: str, **kwargs: Any
+) -> list[dict]:
+ monkeypatch.setattr(airbrake, "_fetch_page", pages)
+ rows: list[dict] = []
+ for batch in get_rows(
+ api_key="user-key",
+ endpoint=endpoint,
+ logger=MagicMock(),
+ resumable_source_manager=manager, # type: ignore[arg-type]
+ **kwargs,
+ ):
+ rows.extend(batch)
+ return rows
+
+
+class TestFormatStartTime:
+ @parameterized.expand(
+ [
+ ("utc_datetime", datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC), "2026-03-04T02:58:14.000Z"),
+ ("naive_datetime", datetime(2026, 3, 4, 2, 58, 14), "2026-03-04T02:58:14.000Z"),
+ ("date_value", date(2026, 3, 4), "2026-03-04T00:00:00.000Z"),
+ ("string_passthrough", "2026-03-04T00:00:00Z", "2026-03-04T00:00:00Z"),
+ ]
+ )
+ def test_format_start_time(self, _name: str, value: Any, expected: str) -> None:
+ # Airbrake expects RFC 3339; a +00:00 offset or bare isoformat drifts from the documented shape.
+ assert _format_start_time(value) == expected
+
+
+class TestBuildGroupsParams:
+ def test_incremental_run_sets_server_side_start_time(self) -> None:
+ params = _build_groups_params(True, datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC))
+ assert params == {"order": "created", "start_time": "2026-03-04T02:58:14.000Z"}
+
+ @parameterized.expand(
+ [
+ ("first_sync_no_watermark", True, None),
+ ("full_refresh", False, datetime(2026, 3, 4, tzinfo=UTC)),
+ ]
+ )
+ def test_no_start_time_without_incremental_watermark(
+ self, _name: str, should_use_incremental_field: bool, last_value: Any
+ ) -> None:
+ # start_time=None (or a stale watermark on full refresh) must not leak into the query string.
+ params = _build_groups_params(should_use_incremental_field, last_value)
+ assert params == {"order": "created"}
+
+
+class TestIterPages:
+ def test_walks_pages_until_empty_page(self, monkeypatch: Any) -> None:
+ pages = _FakePages(
+ {
+ ("/api/v4/projects", 1): {"count": 150, "projects": [{"id": 1}] * PAGE_LIMIT},
+ ("/api/v4/projects", 2): {"count": 150, "projects": [{"id": 2}] * 50},
+ }
+ )
+ monkeypatch.setattr(airbrake, "_fetch_page", pages)
+ result = list(airbrake._iter_pages(MagicMock(), "user-key", "/api/v4/projects", "projects", MagicMock()))
+ assert [(page, len(items)) for page, items in result] == [(1, PAGE_LIMIT), (2, 50)]
+ # Page 2 was short of the limit but non-empty: only the empty page 3 may terminate the walk,
+ # otherwise a server that clamps `limit` below PAGE_LIMIT truncates every collection to one page.
+ assert [params["page"] for _path, params in pages.requests] == [1, 2, 3]
+
+ def test_single_page_collection_skips_trailing_empty_request(self, monkeypatch: Any) -> None:
+ pages = _FakePages({("/api/v4/projects", 1): {"count": 2, "projects": [{"id": 1}, {"id": 2}]}})
+ monkeypatch.setattr(airbrake, "_fetch_page", pages)
+ result = list(airbrake._iter_pages(MagicMock(), "user-key", "/api/v4/projects", "projects", MagicMock()))
+ assert [(page, len(items)) for page, items in result] == [(1, 2)]
+ assert len(pages.requests) == 1
+
+ def test_max_pages_cap_truncates_collection(self, monkeypatch: Any) -> None:
+ pages = _FakePages({("/p", page): {"count": 999, "notices": [{"id": page}]} for page in range(1, 10)})
+ monkeypatch.setattr(airbrake, "_fetch_page", pages)
+ result = list(airbrake._iter_pages(MagicMock(), "user-key", "/p", "notices", MagicMock(), max_pages=3))
+ assert [page for page, _items in result] == [1, 2, 3]
+
+ def test_key_and_limit_sent_on_every_page(self, monkeypatch: Any) -> None:
+ pages = _FakePages({("/api/v4/projects", 1): {"count": 999, "projects": [{"id": 1}]}})
+ monkeypatch.setattr(airbrake, "_fetch_page", pages)
+ list(airbrake._iter_pages(MagicMock(), "user-key", "/api/v4/projects", "projects", MagicMock()))
+ for _path, params in pages.requests:
+ assert params["key"] == "user-key"
+ assert params["limit"] == PAGE_LIMIT
+
+
+class TestFetchPageRetries:
+ @parameterized.expand([("rate_limited", 429), ("server_error", 500)])
+ def test_retryable_statuses_are_retried(self, _name: str, status_code: int) -> None:
+ bad = MagicMock()
+ bad.status_code = status_code
+ good = MagicMock()
+ good.status_code = 200
+ good.ok = True
+ good.json.return_value = {"projects": []}
+
+ session = MagicMock()
+ session.get.side_effect = [bad, good]
+
+ with pytest.MonkeyPatch.context() as mp:
+ mp.setattr(airbrake._fetch_page.retry, "sleep", lambda *_: None) # type: ignore[attr-defined]
+ result = airbrake._fetch_page(session, "https://api.airbrake.io/api/v4/projects", {}, MagicMock())
+
+ assert result == {"projects": []}
+ assert session.get.call_count == 2
+
+ def test_auth_error_raises_immediately_without_leaking_key(self) -> None:
+ # 401 must surface as HTTPError on the first attempt so get_non_retryable_errors can stop
+ # the sync — and its message must not carry the ?key= credential, since it is persisted
+ # into job errors and logs.
+ response = MagicMock()
+ response.status_code = 401
+ response.ok = False
+ response.reason = "Unauthorized"
+ response.text = '{"code":401,"type":"Unauthorized"}'
+ session = MagicMock()
+ session.get.return_value = response
+
+ with pytest.raises(requests.HTTPError) as exc_info:
+ airbrake._fetch_page(
+ session,
+ "https://api.airbrake.io/api/v4/projects",
+ {"key": "SECRET-KEY", "limit": PAGE_LIMIT, "page": 1},
+ MagicMock(),
+ )
+
+ assert session.get.call_count == 1
+ assert "401 Client Error: Unauthorized for url: https://api.airbrake.io/api/v4/projects" in str(exc_info.value)
+ assert "SECRET-KEY" not in str(exc_info.value)
+ # `response` must ride along so fan-out callers can distinguish 404s.
+ assert exc_info.value.response is response
+
+
+class TestGroupsFanOut:
+ def test_fans_out_over_every_project(self, monkeypatch: Any) -> None:
+ pages = _FakePages(
+ {
+ ("/api/v4/projects", 1): {"count": 2, "projects": [{"id": 1}, {"id": 2}]},
+ ("/api/v4/projects/1/groups", 1): {"count": 1, "groups": [{"id": "g1", "projectId": 1}]},
+ ("/api/v4/projects/2/groups", 1): {"count": 1, "groups": [{"id": "g2", "projectId": 2}]},
+ }
+ )
+ rows = _collect(_FakeResumableManager(), monkeypatch, pages, "groups")
+ assert rows == [{"id": "g1", "projectId": 1}, {"id": "g2", "projectId": 2}]
+
+ def test_incremental_run_passes_start_time_to_every_project(self, monkeypatch: Any) -> None:
+ pages = _FakePages(
+ {
+ ("/api/v4/projects", 1): {"count": 2, "projects": [{"id": 1}, {"id": 2}]},
+ ("/api/v4/projects/1/groups", 1): {"count": 1, "groups": [{"id": "g1"}]},
+ ("/api/v4/projects/2/groups", 1): {"count": 1, "groups": [{"id": "g2"}]},
+ }
+ )
+ _collect(
+ _FakeResumableManager(),
+ monkeypatch,
+ pages,
+ "groups",
+ should_use_incremental_field=True,
+ db_incremental_field_last_value=datetime(2026, 3, 4, 2, 58, 14, tzinfo=UTC),
+ )
+ groups_requests = [params for path, params in pages.requests if path.endswith("/groups")]
+ assert len(groups_requests) == 2
+ for params in groups_requests:
+ assert params["start_time"] == "2026-03-04T02:58:14.000Z"
+ assert params["order"] == "created"
+
+ def test_resume_skips_projects_before_bookmark_and_reuses_saved_page(self, monkeypatch: Any) -> None:
+ pages = _FakePages(
+ {
+ ("/api/v4/projects", 1): {"count": 3, "projects": [{"id": 1}, {"id": 2}, {"id": 3}]},
+ # Project 1 must not be re-fetched; project 2 resumes at page 3.
+ ("/api/v4/projects/2/groups", 3): {"count": 999, "groups": [{"id": "g2-p3"}]},
+ ("/api/v4/projects/3/groups", 1): {"count": 1, "groups": [{"id": "g3"}]},
+ }
+ )
+ manager = _FakeResumableManager(AirbrakeResumeConfig(page=3, project_id=2))
+ rows = _collect(manager, monkeypatch, pages, "groups")
+ assert rows == [{"id": "g2-p3"}, {"id": "g3"}]
+ fetched_group_paths = [path for path, _params in pages.requests if path.endswith("/groups")]
+ assert "/api/v4/projects/1/groups" not in fetched_group_paths
+
+ def test_resume_from_deleted_project_restarts_from_first(self, monkeypatch: Any) -> None:
+ pages = _FakePages(
+ {
+ ("/api/v4/projects", 1): {"count": 1, "projects": [{"id": 1}]},
+ ("/api/v4/projects/1/groups", 1): {"count": 1, "groups": [{"id": "g1"}]},
+ }
+ )
+ manager = _FakeResumableManager(AirbrakeResumeConfig(page=5, project_id=999))
+ rows = _collect(manager, monkeypatch, pages, "groups")
+ assert rows == [{"id": "g1"}]
+
+ def test_state_saved_after_each_page_and_bookmark_advanced_between_projects(self, monkeypatch: Any) -> None:
+ pages = _FakePages(
+ {
+ ("/api/v4/projects", 1): {"count": 2, "projects": [{"id": 1}, {"id": 2}]},
+ ("/api/v4/projects/1/groups", 1): {"count": 1, "groups": [{"id": "g1"}]},
+ ("/api/v4/projects/2/groups", 1): {"count": 1, "groups": [{"id": "g2"}]},
+ }
+ )
+ manager = _FakeResumableManager()
+ _collect(manager, monkeypatch, pages, "groups")
+ assert manager.saved == [
+ AirbrakeResumeConfig(page=2, project_id=1),
+ AirbrakeResumeConfig(page=1, project_id=2),
+ AirbrakeResumeConfig(page=2, project_id=2),
+ ]
+
+ def test_project_deleted_mid_fan_out_is_skipped(self, monkeypatch: Any) -> None:
+ pages = _FakePages(
+ {
+ ("/api/v4/projects", 1): {"count": 2, "projects": [{"id": 1}, {"id": 2}]},
+ ("/api/v4/projects/1/groups", 1): requests.HTTPError(response=_response_with_status(404)),
+ ("/api/v4/projects/2/groups", 1): {"count": 1, "groups": [{"id": "g2"}]},
+ }
+ )
+ rows = _collect(_FakeResumableManager(), monkeypatch, pages, "groups")
+ assert rows == [{"id": "g2"}]
+
+ def test_non_404_http_error_propagates(self, monkeypatch: Any) -> None:
+ pages = _FakePages(
+ {
+ ("/api/v4/projects", 1): {"count": 1, "projects": [{"id": 1}]},
+ ("/api/v4/projects/1/groups", 1): requests.HTTPError(response=_response_with_status(500)),
+ }
+ )
+ with pytest.raises(requests.HTTPError):
+ _collect(_FakeResumableManager(), monkeypatch, pages, "groups")
+
+
+class TestDeploysFanOut:
+ def test_project_id_is_injected_into_deploy_rows(self, monkeypatch: Any) -> None:
+ # The Airbrake deploy payload carries no project reference; without injection the table
+ # can't be joined back to projects.
+ pages = _FakePages(
+ {
+ ("/api/v4/projects", 1): {"count": 1, "projects": [{"id": 7}]},
+ ("/api/v4/projects/7/deploys", 1): {
+ "count": 1,
+ "deploys": [{"environment": "production", "revision": "abc123"}],
+ },
+ }
+ )
+ rows = _collect(_FakeResumableManager(), monkeypatch, pages, "deploys")
+ assert rows == [{"environment": "production", "revision": "abc123", "projectId": 7}]
+
+
+class TestNoticesFanOut:
+ def test_fans_out_per_project_per_group(self, monkeypatch: Any) -> None:
+ pages = _FakePages(
+ {
+ ("/api/v4/projects", 1): {"count": 1, "projects": [{"id": 1}]},
+ ("/api/v4/projects/1/groups", 1): {"count": 2, "groups": [{"id": "g1"}, {"id": "g2"}]},
+ ("/api/v4/projects/1/groups/g1/notices", 1): {"count": 1, "notices": [{"id": "n1", "groupId": "g1"}]},
+ ("/api/v4/projects/1/groups/g2/notices", 1): {"count": 1, "notices": [{"id": "n2", "groupId": "g2"}]},
+ }
+ )
+ rows = _collect(_FakeResumableManager(), monkeypatch, pages, "notices")
+ assert rows == [{"id": "n1", "groupId": "g1"}, {"id": "n2", "groupId": "g2"}]
+
+ def test_resume_skips_groups_before_bookmark(self, monkeypatch: Any) -> None:
+ pages = _FakePages(
+ {
+ ("/api/v4/projects", 1): {"count": 1, "projects": [{"id": 1}]},
+ ("/api/v4/projects/1/groups", 1): {"count": 2, "groups": [{"id": "g1"}, {"id": "g2"}]},
+ ("/api/v4/projects/1/groups/g2/notices", 2): {"count": 999, "notices": [{"id": "n2-p2"}]},
+ }
+ )
+ manager = _FakeResumableManager(AirbrakeResumeConfig(page=2, project_id=1, group_id="g2"))
+ rows = _collect(manager, monkeypatch, pages, "notices")
+ assert rows == [{"id": "n2-p2"}]
+ fetched_notice_paths = [path for path, _params in pages.requests if "/notices" in path]
+ assert "/api/v4/projects/1/groups/g1/notices" not in fetched_notice_paths
+
+ def test_group_deleted_mid_fan_out_is_skipped(self, monkeypatch: Any) -> None:
+ pages = _FakePages(
+ {
+ ("/api/v4/projects", 1): {"count": 1, "projects": [{"id": 1}]},
+ ("/api/v4/projects/1/groups", 1): {"count": 2, "groups": [{"id": "gone"}, {"id": "g2"}]},
+ ("/api/v4/projects/1/groups/gone/notices", 1): requests.HTTPError(response=_response_with_status(404)),
+ ("/api/v4/projects/1/groups/g2/notices", 1): {"count": 1, "notices": [{"id": "n2"}]},
+ }
+ )
+ rows = _collect(_FakeResumableManager(), monkeypatch, pages, "notices")
+ assert rows == [{"id": "n2"}]
+
+ def test_per_group_history_is_capped(self, monkeypatch: Any) -> None:
+ # One noisy group with unbounded history must not dominate the sync.
+ pages = _FakePages(
+ {
+ ("/api/v4/projects", 1): {"count": 1, "projects": [{"id": 1}]},
+ ("/api/v4/projects/1/groups", 1): {"count": 1, "groups": [{"id": "g1"}]},
+ **{
+ ("/api/v4/projects/1/groups/g1/notices", page): {"count": 99999, "notices": [{"id": f"n{page}"}]}
+ for page in range(1, NOTICES_MAX_PAGES_PER_GROUP + 50)
+ },
+ }
+ )
+ rows = _collect(_FakeResumableManager(), monkeypatch, pages, "notices")
+ assert len(rows) == NOTICES_MAX_PAGES_PER_GROUP
+
+ def test_group_budget_caps_total_fan_out(self, monkeypatch: Any) -> None:
+ # The per-group page cap bounds each group, but only this budget bounds the two-level
+ # fan-out as a whole; an account with many groups must stop once it is exhausted.
+ monkeypatch.setattr(airbrake, "NOTICES_MAX_GROUPS_PER_SYNC", 2)
+ pages = _FakePages(
+ {
+ ("/api/v4/projects", 1): {"count": 1, "projects": [{"id": 1}]},
+ ("/api/v4/projects/1/groups", 1): {
+ "count": 4,
+ "groups": [{"id": "g1"}, {"id": "g2"}, {"id": "g3"}, {"id": "g4"}],
+ },
+ **{
+ (f"/api/v4/projects/1/groups/{g}/notices", 1): {"count": 1, "notices": [{"id": f"n-{g}"}]}
+ for g in ("g1", "g2", "g3", "g4")
+ },
+ }
+ )
+ rows = _collect(_FakeResumableManager(), monkeypatch, pages, "notices")
+ assert rows == [{"id": "n-g1"}, {"id": "n-g2"}]
+ fetched_notice_paths = [path for path, _params in pages.requests if "/notices" in path]
+ assert "/api/v4/projects/1/groups/g3/notices" not in fetched_notice_paths
+
+
+class TestSourceResponse:
+ @parameterized.expand(
+ [
+ ("projects", ["id"], None),
+ ("groups", ["id"], ["createdAt"]),
+ ("deploys", None, None),
+ ("notices", ["groupId", "id"], ["createdAt"]),
+ ]
+ )
+ def test_primary_and_partition_keys(
+ self, endpoint: str, expected_pks: list[str] | None, expected_partition_keys: list[str] | None
+ ) -> None:
+ # Dropping groupId from the notices key multi-matches merges if notice ids repeat across
+ # groups; partitioning on a mutable field rewrites partitions every sync.
+ response = airbrake_source(
+ api_key="user-key", endpoint=endpoint, logger=MagicMock(), resumable_source_manager=MagicMock()
+ )
+ assert response.primary_keys == expected_pks
+ assert response.partition_keys == expected_partition_keys
+ # Watermark persistence must stay deferred to job end: fan-out batches arrive per project,
+ # so per-batch asc checkpointing could advance the cursor past projects a crashed run never reached.
+ assert response.sort_mode == "desc"
+
+
+class TestValidateCredentials:
+ @parameterized.expand([("valid", 200, True), ("invalid_key", 401, False), ("forbidden", 403, False)])
+ def test_status_mapping(self, _name: str, status_code: int, expected: bool) -> None:
+ session = MagicMock()
+ session.get.return_value = MagicMock(status_code=status_code)
+ with patch.object(airbrake, "make_tracked_session", return_value=session):
+ assert validate_credentials("user-key") is expected
+
+ def test_network_error_maps_to_invalid(self) -> None:
+ session = MagicMock()
+ session.get.side_effect = requests.ConnectionError("boom")
+ with patch.object(airbrake, "make_tracked_session", return_value=session):
+ assert validate_credentials("user-key") is False
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/airbrake/tests/test_airbrake_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/airbrake/tests/test_airbrake_source.py
new file mode 100644
index 000000000000..5e316ed02ccd
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/airbrake/tests/test_airbrake_source.py
@@ -0,0 +1,120 @@
+from datetime import UTC, datetime
+
+from unittest.mock import MagicMock, patch
+
+from parameterized import parameterized
+
+from posthog.schema import SourceFieldInputConfig, SourceFieldInputConfigType
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.airbrake.airbrake import AirbrakeResumeConfig
+from products.warehouse_sources.backend.temporal.data_imports.sources.airbrake.source import AirbrakeSource
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestAirbrakeSource:
+ def test_source_type(self) -> None:
+ assert AirbrakeSource().source_type == ExternalDataSourceType.AIRBRAKE
+
+ def test_source_is_visible_with_secret_api_key_field(self) -> None:
+ config = AirbrakeSource().get_source_config
+ # Re-adding unreleasedSource would silently hide the connector from every user.
+ assert not config.unreleasedSource
+
+ assert config.fields is not None
+ field_by_name = {f.name: f for f in config.fields}
+ api_key = field_by_name["api_key"]
+ assert isinstance(api_key, SourceFieldInputConfig)
+ assert api_key.type == SourceFieldInputConfigType.PASSWORD
+ assert api_key.secret is True
+ assert api_key.required is True
+
+ def test_get_schemas_returns_static_catalog(self) -> None:
+ schemas = {s.name: s for s in AirbrakeSource().get_schemas(MagicMock(), team_id=1)}
+ assert set(schemas) == {"projects", "groups", "deploys", "notices"}
+
+ # groups is the only endpoint with a server-side time filter (start_time on createdAt).
+ assert schemas["groups"].supports_incremental is True
+ assert [f["field"] for f in schemas["groups"].incremental_fields] == ["createdAt"]
+ for full_refresh_only in ("projects", "deploys", "notices"):
+ assert schemas[full_refresh_only].supports_incremental is False, full_refresh_only
+ assert schemas[full_refresh_only].incremental_fields == []
+
+ # notices is the API-expensive two-level fan-out and must stay opt-in.
+ assert schemas["notices"].should_sync_default is False
+ assert schemas["projects"].should_sync_default is True
+
+ def test_get_schemas_filters_by_names(self) -> None:
+ schemas = AirbrakeSource().get_schemas(MagicMock(), team_id=1, names=["groups"])
+ assert [s.name for s in schemas] == ["groups"]
+
+ @parameterized.expand([("valid", True, (True, None)), ("invalid", False, (False, "Invalid Airbrake user API key"))])
+ def test_validate_credentials(self, _name: str, transport_result: bool, expected: tuple) -> None:
+ config = MagicMock()
+ config.api_key = "user-key"
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.airbrake.source.validate_airbrake_credentials",
+ return_value=transport_result,
+ ) as validate:
+ assert AirbrakeSource().validate_credentials(config, team_id=1) == expected
+ validate.assert_called_once_with("user-key")
+
+ def test_resumable_source_manager_is_bound_to_airbrake_resume_config(self) -> None:
+ inputs = MagicMock()
+ manager = AirbrakeSource().get_resumable_source_manager(inputs)
+ assert manager._data_class is AirbrakeResumeConfig
+
+ @parameterized.expand(
+ [
+ # The watermark must not leak into a full-refresh run: a stale value would silently
+ # turn the refresh into a partial sync.
+ ("incremental", True, datetime(2026, 3, 4, tzinfo=UTC), datetime(2026, 3, 4, tzinfo=UTC)),
+ ("full_refresh_drops_stale_watermark", False, datetime(2026, 3, 4, tzinfo=UTC), None),
+ ]
+ )
+ def test_source_for_pipeline_plumbs_incremental_inputs(
+ self, _name: str, should_use_incremental_field: bool, last_value: datetime, expected_last_value: datetime | None
+ ) -> None:
+ config = MagicMock()
+ config.api_key = "user-key"
+ inputs = MagicMock()
+ inputs.schema_name = "groups"
+ inputs.should_use_incremental_field = should_use_incremental_field
+ inputs.db_incremental_field_last_value = last_value
+ manager = MagicMock()
+
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.airbrake.source.airbrake_source"
+ ) as airbrake_source_mock:
+ AirbrakeSource().source_for_pipeline(config, manager, inputs)
+
+ airbrake_source_mock.assert_called_once_with(
+ api_key="user-key",
+ endpoint="groups",
+ logger=inputs.logger,
+ resumable_source_manager=manager,
+ should_use_incremental_field=should_use_incremental_field,
+ db_incremental_field_last_value=expected_last_value,
+ )
+
+ @parameterized.expand(
+ [
+ ("unauthorized", "401 Client Error: Unauthorized for url: https://api.airbrake.io/api/v4/projects?key=x"),
+ ("forbidden", "403 Client Error: Forbidden for url: https://api.airbrake.io/api/v4/projects/1/groups"),
+ ]
+ )
+ def test_credential_errors_are_non_retryable(self, _name: str, observed_error: str) -> None:
+ non_retryable_errors = AirbrakeSource().get_non_retryable_errors()
+ assert any(key in observed_error for key in non_retryable_errors)
+
+ @parameterized.expand(
+ [
+ ("read_timeout", "HTTPSConnectionPool(host='api.airbrake.io', port=443): Read timed out."),
+ (
+ "server_error",
+ "500 Server Error: Internal Server Error for url: https://api.airbrake.io/api/v4/projects",
+ ),
+ ]
+ )
+ def test_transient_errors_remain_retryable(self, _name: str, observed_error: str) -> None:
+ non_retryable_errors = AirbrakeSource().get_non_retryable_errors()
+ assert not any(key in observed_error for key in non_retryable_errors)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
index 74fd561fd04e..2003e65983a8 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py
@@ -191,7 +191,7 @@ class AirOpsSourceConfig(config.Config):
@config.config
class AirbrakeSourceConfig(config.Config):
- pass
+ api_key: str
@config.config