: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 bugsnag import source (#65623)
Tom Owers8019aa9c0bd3
diff --git a/posthog/temporal/data_imports/sources/SOURCES.md b/posthog/temporal/data_imports/sources/SOURCES.mdindex 5bdc567c3331..12e3c4d99317 100644--- a/posthog/temporal/data_imports/sources/SOURCES.md+++ b/posthog/temporal/data_imports/sources/SOURCES.md@@ -63,6 +63,7 @@ the row lists both.| braze | HTTP | requests | ✅ || brevo | HTTP | requests | ✅ || brex | HTTP | requests | ✅ |+| bugsnag | HTTP | requests | ✅ || buildbetter | HTTP | requests | ✅ || buildkite | HTTP | requests | ✅ || calendly | HTTP | requests | ✅ |@@ -302,7 +303,6 @@ doesn't conflict with concurrent PRs.- branch- breezometer- breezy_hr-- bugsnag- bunny- buzzsprout- cal_comdiff --git a/posthog/temporal/data_imports/sources/bugsnag/bugsnag.py b/posthog/temporal/data_imports/sources/bugsnag/bugsnag.pynew file mode 100644index 000000000000..e8f33fdea20e--- /dev/null+++ b/posthog/temporal/data_imports/sources/bugsnag/bugsnag.py@@ -0,0 +1,324 @@+import re+import dataclasses+from collections.abc import Iterator+from typing import Any+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.batcher import Batcher+from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+from posthog.temporal.data_imports.sources.bugsnag.settings import (+ BUGSNAG_ENDPOINTS,+ BugsnagEndpointConfig,+ BugsnagScope,+)+from posthog.temporal.data_imports.sources.common.http import make_tracked_session+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager++# BugSnag uses a single global host for its Data Access API. On-prem / Enterprise installs use a+# custom host, which this source does not yet support.+BUGSNAG_BASE_URL = "https://api.bugsnag.com"+# BugSnag's documented per_page maximum for list endpoints.+PAGE_SIZE = 100+# The Data Access API is versioned via the X-Version header. v2 is current; v1 is decommissioned.+BUGSNAG_API_VERSION = "2"+++class BugsnagRetryableError(Exception):+ pass+++class BugsnagResumeConfig:+ # Next page URL (from the Link header) to fetch. None means "start the current parent at its+ # first page" — used when the bookmark advances to a new fan-out parent whose first page URL+ # isn't known until it's built.+ next_url: str | None = None+ # The fan-out parent currently being processed, identified by its stable id (organization_id+ # for per-org endpoints, project_id for per-project ones). A stable id rather than a positional+ # index so parents added/removed between a crash and the retry can't resume into the wrong one.+ # None for the top-level (non-fan-out) organizations endpoint.+ parent_id: str | None = None+++class _FanOutParent:+ # Id used to resolve the endpoint path and to bookmark resume position.+ resume_id: str+ # kwargs passed to ``str.format`` on the endpoint path template.+ path_kwargs: dict[str, str]+ # Parent identifiers injected into every child row so the composite primary key is unique+ # table-wide and the rows are joinable back to their organization/project.+ inject: dict[str, str]+++def _get_headers(auth_token: str) -> dict[str, str]:+ return {+ "Authorization": f"token {auth_token}",+ "X-Version": BUGSNAG_API_VERSION,+ "Content-Type": "application/json",+ }+++def _build_url(base_url: str, params: dict[str, Any]) -> str:+ if not params:+ return base_url+ return f"{base_url}?{urlencode(params)}"+++def _parse_next_url(link_header: str) -> str | None:+ """Return the URL with rel="next" from BugSnag's Link header, if any.++ BugSnag paginates via the Link response header (the same RFC 5988 format GitHub uses)+ rather than page parameters in the body, so we follow the `next` relation until it's gone.+ """+ if not link_header:+ return None+ for part in link_header.split(","):+ part = part.strip()+ match = re.match(r'<([^>]+)>;\s*rel="next"', part)+ if match:+ return match.group(1)+ return None+++@retry(+ retry=retry_if_exception_type((BugsnagRetryableError, requests.ReadTimeout, requests.ConnectionError)),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=60),+ reraise=True,+)+def _fetch_page(session: requests.Session, page_url: str, headers: dict[str, str], logger: FilteringBoundLogger):+ response = session.get(page_url, headers=headers, timeout=60)++ # BugSnag rate limits per 1-minute window and returns 429 on exceed; retry those plus+ # transient 5xx. Exponential backoff covers the (typically sub-minute) reset window.+ if response.status_code == 429 or response.status_code >= 500:+ raise BugsnagRetryableError(f"BugSnag API error (retryable): status={response.status_code}, url={page_url}")++ if not response.ok:+ logger.error(f"BugSnag API error: status={response.status_code}, body={response.text}, url={page_url}")+ response.raise_for_status()++ return response+++def _fetch_list_page(+ session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger+) -> tuple[list[dict[str, Any]], str | None]:+ """Fetch one page of a BugSnag list endpoint, returning (items, next_page_url).++ BugSnag list endpoints return a top-level JSON array; the next-page cursor lives in the+ Link header, not the body."""+ response = _fetch_page(session, url, headers, logger)+ data = response.json()+ if not isinstance(data, list):+ # Defensive: a non-list body has no rows to emit and no Link cursor to follow.+ return [], None+ return data, _parse_next_url(response.headers.get("Link", ""))+++def _iter_all_pages(+ session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger+) -> Iterator[dict[str, Any]]:+ """Yield every item across all pages of a list endpoint, following the Link header."""+ while True:+ items, next_url = _fetch_list_page(session, url, headers, logger)+ yield from items+ if not next_url:+ return+ url = next_url+++def _resolve_org_ids(session: requests.Session, headers: dict[str, str], logger: FilteringBoundLogger) -> list[str]:+ url = _build_url(f"{BUGSNAG_BASE_URL}/user/organizations", {"per_page": PAGE_SIZE})+ return [org["id"] for org in _iter_all_pages(session, url, headers, logger)]+++def _resolve_parents(+ session: requests.Session, headers: dict[str, str], config: BugsnagEndpointConfig, logger: FilteringBoundLogger+) -> list[_FanOutParent]:+ """Build the ordered list of fan-out parents for a per-org or per-project endpoint."""+ org_ids = _resolve_org_ids(session, headers, logger)++ if config.scope == BugsnagScope.PER_ORG:+ return [+ _FanOutParent(+ resume_id=org_id,+ path_kwargs={"organization_id": org_id},+ inject={"organization_id": org_id},+ )+ for org_id in org_ids+ ]++ # PER_PROJECT: walk each organization's projects and flatten to (org_id, project_id) pairs.+ parents: list[_FanOutParent] = []+ for org_id in org_ids:+ projects_url = _build_url(f"{BUGSNAG_BASE_URL}/organizations/{org_id}/projects", {"per_page": PAGE_SIZE})+ for project in _iter_all_pages(session, projects_url, headers, logger):+ project_id = project["id"]+ parents.append(+ _FanOutParent(+ resume_id=project_id,+ path_kwargs={"project_id": project_id},+ inject={"organization_id": org_id, "project_id": project_id},+ )+ )+ return parents+++def _iter_top_level(+ session: requests.Session,+ headers: dict[str, str],+ config: BugsnagEndpointConfig,+ logger: FilteringBoundLogger,+ batcher: Batcher,+ manager: ResumableSourceManager[BugsnagResumeConfig],+) -> Iterator[Any]:+ """Paginate a top-level collection (organizations) with resume support."""+ resume = manager.load_state() if manager.can_resume() else None+ if resume is not None and resume.next_url:+ url = resume.next_url+ logger.debug(f"BugSnag: resuming {config.name} from URL: {url}")+ else:+ url = _build_url(f"{BUGSNAG_BASE_URL}{config.path}", {"per_page": PAGE_SIZE})++ while True:+ items, next_url = _fetch_list_page(session, url, headers, logger)+ # Checkpoint the CURRENT page, not next_url: a chunk can be yielded part-way through this+ # page, so on resume we must re-fetch this page and re-batch every item (merge dedupes the+ # already-yielded ones) rather than skip ahead and drop the items still in the batcher.+ checkpoint_url = url+ for item in items:+ batcher.batch(item)+ if batcher.should_yield():+ yield batcher.get_table()+ # Save AFTER yielding so a crash resumes at this page rather than losing buffered rows.+ manager.save_state(BugsnagResumeConfig(next_url=checkpoint_url))+ if not next_url:+ break+ url = next_url+++def _iter_fan_out(+ session: requests.Session,+ headers: dict[str, str],+ config: BugsnagEndpointConfig,+ logger: FilteringBoundLogger,+ batcher: Batcher,+ manager: ResumableSourceManager[BugsnagResumeConfig],+) -> Iterator[Any]:+ """Walk every fan-out parent and emit each parent's child rows, injecting parent ids.++ Full refresh: BugSnag's project-scoped list endpoints expose dashboard-style time filters,+ but those aren't verified here, so each sync re-walks every parent. Re-pulled rows on resume+ or re-run dedupe on the composite primary key.+ """+ parents = _resolve_parents(session, headers, config, logger)++ # Resolve the saved parent bookmark to the slice of parents still to process. If the bookmarked+ # parent no longer exists (deleted between runs), start over — merge dedupes the re-pulled rows.+ resume = manager.load_state() if manager.can_resume() else None+ start_index = 0+ resume_url: str | None = None+ if resume is not None and resume.parent_id is not None:+ resume_ids = [parent.resume_id for parent in parents]+ if resume.parent_id in resume_ids:+ start_index = resume_ids.index(resume.parent_id)+ resume_url = resume.next_url+ logger.debug(f"BugSnag: resuming {config.name} fan-out from parent={resume.parent_id}, url={resume_url}")++ for index in range(start_index, len(parents)):+ parent = parents[index]+ path = config.path.format(**parent.path_kwargs)+ url = resume_url or _build_url(f"{BUGSNAG_BASE_URL}{path}", {"per_page": PAGE_SIZE})+ resume_url = None # only the resumed-into parent uses the saved URL; the rest start fresh++ while True:+ items, next_url = _fetch_list_page(session, url, headers, logger)+ # Checkpoint the CURRENT page (and parent), not next_url. The batcher is shared across+ # parents and can yield part-way through this page, so resume must re-fetch this exact+ # page and re-batch every item (merge dedupes the already-yielded ones). Saving next_url+ # — or advancing the bookmark to the next parent — would skip rows still buffered in the+ # batcher when a crash hits, losing them. We never advance the bookmark past a yielded+ # batch; redundant re-pulls of fully-processed parents are deduped on merge.+ checkpoint_url = url+ for item in items:+ batcher.batch({**item, **parent.inject})+ if batcher.should_yield():+ yield batcher.get_table()+ manager.save_state(BugsnagResumeConfig(next_url=checkpoint_url, parent_id=parent.resume_id))+ if not next_url:+ break+ url = next_url+++def get_rows(+ auth_token: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[BugsnagResumeConfig],+) -> Iterator[Any]:+ config = BUGSNAG_ENDPOINTS[endpoint]+ headers = _get_headers(auth_token)+ batcher = Batcher(logger=logger, chunk_size=2000, chunk_size_bytes=100 * 1024 * 1024)+ # One session reused across every page (and every fan-out parent) so urllib3 keeps the+ # connection alive instead of re-handshaking per request. Redact the token: it rides in the+ # `Authorization: token …` header under BugSnag's custom scheme, which the tracked transport's+ # built-in scrubber doesn't recognise, so a logged/sampled request would otherwise leak it.+ session = make_tracked_session(redact_values=(auth_token,))++ if config.scope == BugsnagScope.ORGANIZATION:+ yield from _iter_top_level(session, headers, config, logger, batcher, resumable_source_manager)+ else:+ yield from _iter_fan_out(session, headers, config, logger, batcher, resumable_source_manager)++ if batcher.should_yield(include_incomplete_chunk=True):+ yield batcher.get_table()+++def bugsnag_source(+ auth_token: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[BugsnagResumeConfig],+) -> SourceResponse:+ endpoint_config = BUGSNAG_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ auth_token=auth_token,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ ),+ primary_keys=endpoint_config.primary_keys,+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if endpoint_config.partition_key else None,+ partition_format="week" if endpoint_config.partition_key else None,+ partition_keys=[endpoint_config.partition_key] if endpoint_config.partition_key else None,+ )+++def validate_credentials(auth_token: str) -> tuple[bool, str | None]:+ """Confirm the auth token is genuine by listing the organizations it can access.++ The token is org-scoped (not per-endpoint), so a single cheap probe is enough."""+ url = _build_url(f"{BUGSNAG_BASE_URL}/user/organizations", {"per_page": 1})+ try:+ # Redact the token here too — see get_rows() for why BugSnag's custom auth scheme needs it.+ session = make_tracked_session(redact_values=(auth_token,))+ response = session.get(url, headers=_get_headers(auth_token), timeout=10)+ except requests.exceptions.RequestException as e:+ return False, str(e)++ if response.status_code == 200:+ return True, None+ if response.status_code in (401, 403):+ return False, "Invalid BugSnag auth token"+ return False, f"BugSnag API error: {response.status_code}"diff --git a/posthog/temporal/data_imports/sources/bugsnag/canonical_descriptions.py b/posthog/temporal/data_imports/sources/bugsnag/canonical_descriptions.pynew file mode 100644index 000000000000..f3530c2bafe4--- /dev/null+++ b/posthog/temporal/data_imports/sources/bugsnag/canonical_descriptions.py@@ -0,0 +1,110 @@+from posthog.temporal.data_imports.sources.common.canonical_descriptions import CanonicalDescriptions++# Sourced from the BugSnag Data Access API docs (https://bugsnagapiv2.docs.apiary.io/). Partial+# coverage is fine — any endpoint, column, or table missing here falls back to LLM enrichment.+# `organization_id` / `project_id` are injected by this connector during fan-out, not returned by+# the API, so they're documented alongside the API's own fields.+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "organizations": {+ "description": "An organization the auth token can access; the top of BugSnag's resource hierarchy, owning projects and collaborators.",+ "docs_url": "https://bugsnagapiv2.docs.apiary.io/#reference/organizations",+ "columns": {+ "id": "Unique identifier for the organization.",+ "name": "Display name of the organization.",+ "slug": "URL-friendly slug for the organization.",+ "created_at": "When the organization was created.",+ "updated_at": "When the organization was last updated.",+ },+ },+ "projects": {+ "description": "An application or service monitored in BugSnag. Errors and events are scoped to a project.",+ "docs_url": "https://bugsnagapiv2.docs.apiary.io/#reference/projects",+ "columns": {+ "id": "Unique identifier for the project.",+ "organization_id": "Identifier of the organization that owns the project (injected by the connector).",+ "name": "Display name of the project.",+ "slug": "URL-friendly slug for the project.",+ "api_key": "Notifier API key used by BugSnag SDKs to send events to this project.",+ "type": "Platform/framework of the project (e.g. js, rails, android).",+ "created_at": "When the project was created.",+ "updated_at": "When the project was last updated.",+ "errors_url": "API URL for the project's errors.",+ "events_url": "API URL for the project's events.",+ },+ },+ "collaborators": {+ "description": "A user with access to an organization in BugSnag.",+ "docs_url": "https://bugsnagapiv2.docs.apiary.io/#reference/collaborators",+ "columns": {+ "id": "Unique identifier for the collaborator.",+ "organization_id": "Identifier of the organization the collaborator belongs to (injected by the connector).",+ "name": "Collaborator's display name.",+ "email": "Collaborator's email address.",+ },+ },+ "teams": {+ "description": "A team within an organization, used to group collaborators and scope project access.",+ "docs_url": "https://bugsnagapiv2.docs.apiary.io/#reference/teams",+ "columns": {+ "id": "Unique identifier for the team.",+ "organization_id": "Identifier of the organization the team belongs to (injected by the connector).",+ "name": "Team name.",+ },+ },+ "errors": {+ "description": "A group of similar events (a distinct error) in a project, with aggregate counts and first/last-seen timestamps.",+ "docs_url": "https://bugsnagapiv2.docs.apiary.io/#reference/errors",+ "columns": {+ "id": "Unique identifier for the error.",+ "project_id": "Identifier of the project the error belongs to (injected by the connector).",+ "error_class": "Class/type of the error (e.g. RuntimeError).",+ "message": "Representative error message.",+ "context": "Context the error occurred in (e.g. the controller/route).",+ "severity": "Severity of the error (error, warning, info).",+ "status": "Workflow status of the error (open, fixed, ignored, snoozed).",+ "first_seen": "When the error was first seen.",+ "last_seen": "When the error was most recently seen.",+ "events": "Total number of events recorded for this error.",+ "users": "Number of distinct users affected by this error.",+ },+ },+ "events": {+ "description": "An individual occurrence (a single crash/exception report) within a project.",+ "docs_url": "https://bugsnagapiv2.docs.apiary.io/#reference/events",+ "columns": {+ "id": "Unique identifier for the event.",+ "project_id": "Identifier of the project the event belongs to (injected by the connector).",+ "error_id": "Identifier of the error this event belongs to.",+ "received_at": "When BugSnag received the event.",+ "severity": "Severity reported for the event.",+ "context": "Context the event occurred in.",+ "unhandled": "Whether the event was an unhandled error.",+ "app": "App metadata recorded with the event (version, release stage, …).",+ "device": "Device metadata recorded with the event.",+ "user": "User metadata recorded with the event.",+ },+ },+ "releases": {+ "description": "A released version of a project's app, with stability and event metrics.",+ "docs_url": "https://bugsnagapiv2.docs.apiary.io/#reference/releases",+ "columns": {+ "id": "Unique identifier for the release.",+ "project_id": "Identifier of the project the release belongs to (injected by the connector).",+ "release_stage_name": "Release stage (e.g. production, staging).",+ "app_version": "Application version string for the release.",+ "released_at": "When the release was made.",+ "first_released_at": "When this version was first released.",+ "total_sessions_count": "Number of sessions recorded for the release.",+ "unhandled_sessions_count": "Number of sessions with an unhandled error.",+ },+ },+ "saved_searches": {+ "description": "A saved error filter/search defined in a project.",+ "docs_url": "https://bugsnagapiv2.docs.apiary.io/#reference/saved-searches",+ "columns": {+ "id": "Unique identifier for the saved search.",+ "project_id": "Identifier of the project the saved search belongs to (injected by the connector).",+ "name": "Name of the saved search.",+ },+ },+}diff --git a/posthog/temporal/data_imports/sources/bugsnag/settings.py b/posthog/temporal/data_imports/sources/bugsnag/settings.pynew file mode 100644index 000000000000..a205bf21ac65--- /dev/null+++ b/posthog/temporal/data_imports/sources/bugsnag/settings.py@@ -0,0 +1,133 @@+from dataclasses import dataclass, field+from enum import Enum+from typing import Optional++from products.data_warehouse.backend.types import IncrementalField+++class BugsnagScope(Enum):+ """Where an endpoint lives in BugSnag's resource hierarchy.++ The Data Access API is nested: a personal auth token grants access to one or more+ organizations, each organization owns projects, and most analytical resources+ (errors, events, releases, …) are scoped to a project. So fetching a project-scoped+ table means walking ``organizations -> projects -> <endpoint>``.+ """++ # Top-level collection reachable directly from the token (GET /user/organizations).+ ORGANIZATION = "organization"+ # Fan out over every organization the token can see (GET /organizations/{organization_id}/...).+ PER_ORG = "per_org"+ # Fan out over every project in every organization (GET /projects/{project_id}/...).+ PER_PROJECT = "per_project"+++@dataclass+class BugsnagEndpointConfig:+ name: str+ scope: BugsnagScope+ # Path template. PER_ORG paths contain ``{organization_id}``; PER_PROJECT paths contain+ # ``{project_id}``. ORGANIZATION paths are static.+ path: str+ # Primary key columns used for merge dedup. For fan-out children the parent identifier is+ # included (and injected into every row) so the key is unique across the whole table — the+ # API only guarantees ids are unique within a parent resource.+ primary_keys: list[str]+ # Stable, creation-time datetime column to partition by. Never a `last_seen`/`updated_at`+ # style field — those move and would rewrite partitions every sync. None disables partitioning.+ partition_key: Optional[str] = None+ # The menu of incremental cursor candidates advertised to the user. Empty = full refresh only.+ incremental_fields: list[IncrementalField] = field(default_factory=list)+ # Whether the table is selected for sync by default in the connection wizard.+ should_sync_default: bool = True+++# BugSnag's id values are 24-character hex ObjectIds that are globally unique, but the Data Access+# API documents uniqueness only within a parent resource. We therefore include the parent id in+# every fan-out child's primary key (and inject it into the row) so merge dedup stays correct even+# if that assumption ever breaks — a redundant-but-safe composite never seeds duplicate rows.+BUGSNAG_ENDPOINTS: dict[str, BugsnagEndpointConfig] = {+ "organizations": BugsnagEndpointConfig(+ name="organizations",+ scope=BugsnagScope.ORGANIZATION,+ path="/user/organizations",+ primary_keys=["id"],+ partition_key="created_at",+ ),+ "projects": BugsnagEndpointConfig(+ name="projects",+ scope=BugsnagScope.PER_ORG,+ path="/organizations/{organization_id}/projects",+ primary_keys=["id", "organization_id"],+ partition_key="created_at",+ ),+ "collaborators": BugsnagEndpointConfig(+ name="collaborators",+ scope=BugsnagScope.PER_ORG,+ path="/organizations/{organization_id}/collaborators",+ primary_keys=["id", "organization_id"],+ ),+ "teams": BugsnagEndpointConfig(+ name="teams",+ scope=BugsnagScope.PER_ORG,+ path="/organizations/{organization_id}/teams",+ primary_keys=["id", "organization_id"],+ ),+ "errors": BugsnagEndpointConfig(+ name="errors",+ scope=BugsnagScope.PER_PROJECT,+ path="/projects/{project_id}/errors",+ primary_keys=["id", "project_id"],+ partition_key="first_seen",+ ),+ # Events can be very large (one row per captured event), so it's off by default to avoid a+ # surprise full-history sync. Enable deliberately when raw event-level data is needed.+ "events": BugsnagEndpointConfig(+ name="events",+ scope=BugsnagScope.PER_PROJECT,+ path="/projects/{project_id}/events",+ primary_keys=["id", "project_id"],+ partition_key="received_at",+ should_sync_default=False,+ ),+ "releases": BugsnagEndpointConfig(+ name="releases",+ scope=BugsnagScope.PER_PROJECT,+ path="/projects/{project_id}/releases",+ primary_keys=["id", "project_id"],+ partition_key="released_at",+ ),+ "pivots": BugsnagEndpointConfig(+ name="pivots",+ scope=BugsnagScope.PER_PROJECT,+ path="/projects/{project_id}/pivots",+ primary_keys=["event_field_display_id", "project_id"],+ should_sync_default=False,+ ),+ "event_fields": BugsnagEndpointConfig(+ name="event_fields",+ scope=BugsnagScope.PER_PROJECT,+ path="/projects/{project_id}/event_fields",+ primary_keys=["display_id", "project_id"],+ should_sync_default=False,+ ),+ "trace_fields": BugsnagEndpointConfig(+ name="trace_fields",+ scope=BugsnagScope.PER_PROJECT,+ path="/projects/{project_id}/trace_fields",+ primary_keys=["display_id", "project_id"],+ should_sync_default=False,+ ),+ "saved_searches": BugsnagEndpointConfig(+ name="saved_searches",+ scope=BugsnagScope.PER_PROJECT,+ path="/projects/{project_id}/saved_searches",+ primary_keys=["id", "project_id"],+ ),+}++ENDPOINTS = tuple(BUGSNAG_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in BUGSNAG_ENDPOINTS.items()+}diff --git a/posthog/temporal/data_imports/sources/bugsnag/source.py b/posthog/temporal/data_imports/sources/bugsnag/source.pyindex 15602515c8f8..3a69478de78c 100644--- a/posthog/temporal/data_imports/sources/bugsnag/source.py+++ b/posthog/temporal/data_imports/sources/bugsnag/source.py@@ -1,20 +1,33 @@-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.bugsnag.bugsnag import (+ BugsnagResumeConfig,+ bugsnag_source,+ validate_credentials as validate_bugsnag_credentials,+)+from posthog.temporal.data_imports.sources.bugsnag.settings import BUGSNAG_ENDPOINTS, ENDPOINTS, INCREMENTAL_FIELDS+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 BugsnagSourceConfigfrom products.data_warehouse.backend.types import ExternalDataSourceType@SourceRegistry.register-class BugsnagSource(SimpleSource[BugsnagSourceConfig]):+class BugsnagSource(ResumableSource[BugsnagSourceConfig, BugsnagResumeConfig]):@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.BUGSNAG@@ -25,7 +38,94 @@ class BugsnagSource(SimpleSource[BugsnagSourceConfig]):name=SchemaExternalDataSourceType.BUGSNAG,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="Bugsnag",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your BugSnag personal auth token to pull your BugSnag error-monitoring data into the PostHog Data warehouse.++You can generate a personal auth token in the **My Account** section of your [BugSnag account settings](https://app.bugsnag.com/settings/my-account/). The token inherits your account's access, so it can read every organization and project you can see.""",iconPath="/static/services/bugsnag.png",- fields=cast(list[FieldType], []),+ docsUrl="https://posthog.com/docs/cdp/sources/bugsnag",unreleasedSource=True,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="auth_token",+ label="Auth token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="Personal auth token",+ secret=True,+ ),+ ],+ ),+ )++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ # 401/403 surface as a requests HTTPError when `_fetch_page` calls `raise_for_status()`.+ # No amount of retrying fixes a bad or under-permissioned token, so stop the sync. Match the+ # stable status text and base host, not the per-request path/query.+ return {+ "401 Client Error: Unauthorized for url: https://api.bugsnag.com": "Your BugSnag auth token is invalid or has been revoked. Generate a new personal auth token in your BugSnag account settings, then reconnect.",+ "403 Client Error: Forbidden for url: https://api.bugsnag.com": "Your BugSnag auth token does not have access to this data. Check the token's account permissions, then reconnect.",+ }++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from posthog.temporal.data_imports.sources.bugsnag.canonical_descriptions import ( # noqa: PLC0415+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: BugsnagSourceConfig,+ 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 == "events":+ return "One row per captured event. Can be very large — full refresh only, off by default."+ return None++ def _build_schema(endpoint: str) -> SourceSchema:+ endpoint_config = BUGSNAG_ENDPOINTS[endpoint]+ # Full refresh only: BugSnag exposes dashboard-style time filters on errors/events/releases,+ # but the filter+pagination behavior isn't verified against the live API yet, so we don't+ # advertise incremental rather than risk a sync that silently re-walks history.+ return SourceSchema(+ name=endpoint,+ supports_incremental=False,+ supports_append=False,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ should_sync_default=endpoint_config.should_sync_default,+ description=_description(endpoint),+ )++ 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: BugsnagSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ return validate_bugsnag_credentials(config.auth_token)++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[BugsnagResumeConfig]:+ return ResumableSourceManager[BugsnagResumeConfig](inputs, BugsnagResumeConfig)++ def source_for_pipeline(+ self,+ config: BugsnagSourceConfig,+ resumable_source_manager: ResumableSourceManager[BugsnagResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return bugsnag_source(+ auth_token=config.auth_token,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,)diff --git a/posthog/temporal/data_imports/sources/bugsnag/tests/test_bugsnag.py b/posthog/temporal/data_imports/sources/bugsnag/tests/test_bugsnag.pynew file mode 100644index 000000000000..9ed499845646--- /dev/null+++ b/posthog/temporal/data_imports/sources/bugsnag/tests/test_bugsnag.py@@ -0,0 +1,315 @@+import json+from collections.abc import Mapping+from typing import Any++import pytest+from unittest.mock import MagicMock++import requests+from parameterized import parameterized+from tenacity import stop_after_attempt, wait_none++from posthog.temporal.data_imports.sources.bugsnag import bugsnag+from posthog.temporal.data_imports.sources.bugsnag.bugsnag import (+ BUGSNAG_BASE_URL,+ BugsnagResumeConfig,+ BugsnagRetryableError,+ _build_url,+ _get_headers,+ _parse_next_url,+ get_rows,+ validate_credentials,+)+++class _FakeResumableManager:+ def __init__(self, state: BugsnagResumeConfig | None = None) -> None:+ self._state = state+ self.saved: list[BugsnagResumeConfig] = []++ def can_resume(self) -> bool:+ return self._state is not None++ def load_state(self) -> BugsnagResumeConfig | None:+ return self._state++ def save_state(self, data: BugsnagResumeConfig) -> None:+ self.saved.append(data)+++def _make_response(status_code: int, body: Any = None, link: str | None = None) -> requests.Response:+ response = requests.Response()+ response.status_code = status_code+ if link is not None:+ response.headers["Link"] = link+ if body is not None:+ response._content = json.dumps(body).encode()+ return response+++class _FakeSession:+ """Returns queued responses in order, recording the URLs requested."""++ def __init__(self, responses: list[requests.Response]) -> None:+ self._responses = list(responses)+ self.requested_urls: list[str] = []++ def get(self, url: str, headers: dict[str, str] | None = None, timeout: int | None = None) -> requests.Response:+ self.requested_urls.append(url)+ return self._responses.pop(0)+++def _collect(+ endpoint: str,+ pages: Mapping[str, tuple[list[dict], str | None]],+ manager: _FakeResumableManager,+ monkeypatch: Any,+) -> list[dict]:+ monkeypatch.setattr(bugsnag, "make_tracked_session", lambda *args, **kwargs: MagicMock())++ def fake_fetch_list_page(session: Any, url: str, headers: Any, logger: Any) -> tuple[list[dict], str | None]:+ if url not in pages:+ raise AssertionError(f"unexpected URL requested: {url}")+ return pages[url]++ monkeypatch.setattr(bugsnag, "_fetch_list_page", fake_fetch_list_page)++ rows: list[dict] = []+ for table in get_rows(+ auth_token="tok",+ endpoint=endpoint,+ logger=MagicMock(),+ resumable_source_manager=manager, # type: ignore[arg-type]+ ):+ rows.extend(table.to_pylist())+ return rows+++class TestParseNextUrl:+ @parameterized.expand(+ [+ (+ "single_next",+ '<https://api.bugsnag.com/projects/p1/errors?offset=abc>; rel="next"',+ "https://api.bugsnag.com/projects/p1/errors?offset=abc",+ ),+ (+ "next_among_others",+ '<https://api.bugsnag.com/x?o=1>; rel="prev", <https://api.bugsnag.com/x?o=2>; rel="next"',+ "https://api.bugsnag.com/x?o=2",+ ),+ ("no_next", '<https://api.bugsnag.com/x?o=1>; rel="prev"', None),+ ("empty", "", None),+ ]+ )+ def test_parse_next_url(self, _name: str, header: str, expected: str | None) -> None:+ assert _parse_next_url(header) == expected+++class TestHelpers:+ def test_get_headers_sets_token_and_version(self) -> None:+ headers = _get_headers("tok_123")+ assert headers["Authorization"] == "token tok_123"+ assert headers["X-Version"] == "2"++ def test_build_url_encodes_params(self) -> None:+ assert _build_url(f"{BUGSNAG_BASE_URL}/user/organizations", {"per_page": 100}) == (+ "https://api.bugsnag.com/user/organizations?per_page=100"+ )++ def test_build_url_no_params(self) -> None:+ assert _build_url("https://api.bugsnag.com/x", {}) == "https://api.bugsnag.com/x"+++class TestFetchPage:+ @parameterized.expand([("rate_limited", 429), ("server_error", 500), ("bad_gateway", 503)])+ def test_retryable_statuses_raise_retryable_error(self, _name: str, status_code: int) -> None:+ session = _FakeSession([_make_response(status_code) for _ in range(5)])+ # tenacity exposes retry_with on the decorated callable to rebuild it with different+ # retry settings; here we drop the backoff so the test doesn't actually sleep.+ fast_fetch = bugsnag._fetch_page.retry_with(wait=wait_none(), stop=stop_after_attempt(3)) # type: ignore[attr-defined]+ with pytest.raises(BugsnagRetryableError):+ fast_fetch(session, "https://api.bugsnag.com/x", {}, MagicMock())++ def test_client_error_raises_http_error_without_retry(self) -> None:+ session = _FakeSession([_make_response(404, body={"errors": ["Not Found"]})])+ with pytest.raises(requests.HTTPError):+ bugsnag._fetch_page(session, "https://api.bugsnag.com/x", {}, MagicMock()) # type: ignore[arg-type]+ # 404 is not retryable, so only one request is made.+ assert len(session.requested_urls) == 1++ def test_ok_response_returned(self) -> None:+ ok = _make_response(200, body=[{"id": "o1"}])+ session = _FakeSession([ok])+ assert bugsnag._fetch_page(session, "https://api.bugsnag.com/x", {}, MagicMock()) is ok # type: ignore[arg-type]+++class TestTopLevelOrganizations:+ def test_paginates_following_link_header(self, monkeypatch: Any) -> None:+ page1 = "https://api.bugsnag.com/user/organizations?per_page=100"+ page2 = "https://api.bugsnag.com/user/organizations?offset=2"+ pages = {+ page1: ([{"id": "o1"}], page2),+ page2: ([{"id": "o2"}], None),+ }+ rows = _collect("organizations", pages, _FakeResumableManager(), monkeypatch)+ assert rows == [{"id": "o1"}, {"id": "o2"}]++ def test_resumes_from_saved_next_url(self, monkeypatch: Any) -> None:+ page2 = "https://api.bugsnag.com/user/organizations?offset=2"+ pages = {page2: ([{"id": "o2"}], None)}+ manager = _FakeResumableManager(BugsnagResumeConfig(next_url=page2))+ rows = _collect("organizations", pages, manager, monkeypatch)+ assert rows == [{"id": "o2"}]+++class TestPerOrgFanOut:+ def test_injects_organization_id(self, monkeypatch: Any) -> None:+ pages = {+ "https://api.bugsnag.com/user/organizations?per_page=100": ([{"id": "o1"}], None),+ "https://api.bugsnag.com/organizations/o1/projects?per_page=100": ([{"id": "p1"}, {"id": "p2"}], None),+ }+ rows = _collect("projects", pages, _FakeResumableManager(), monkeypatch)+ assert rows == [+ {"id": "p1", "organization_id": "o1"},+ {"id": "p2", "organization_id": "o1"},+ ]+++class TestPerProjectFanOut:+ def _two_project_pages(self) -> dict[str, tuple[list[dict], str | None]]:+ return {+ "https://api.bugsnag.com/user/organizations?per_page=100": ([{"id": "o1"}], None),+ "https://api.bugsnag.com/organizations/o1/projects?per_page=100": ([{"id": "p1"}, {"id": "p2"}], None),+ "https://api.bugsnag.com/projects/p1/errors?per_page=100": ([{"id": "e1"}], None),+ "https://api.bugsnag.com/projects/p2/errors?per_page=100": ([{"id": "e2"}], None),+ }++ def test_walks_org_then_project_and_injects_both_ids(self, monkeypatch: Any) -> None:+ rows = _collect("errors", self._two_project_pages(), _FakeResumableManager(), monkeypatch)+ assert rows == [+ {"id": "e1", "organization_id": "o1", "project_id": "p1"},+ {"id": "e2", "organization_id": "o1", "project_id": "p2"},+ ]++ def test_follows_child_pagination(self, monkeypatch: Any) -> None:+ next_url = "https://api.bugsnag.com/projects/p1/errors?offset=2"+ pages = {+ "https://api.bugsnag.com/user/organizations?per_page=100": ([{"id": "o1"}], None),+ "https://api.bugsnag.com/organizations/o1/projects?per_page=100": ([{"id": "p1"}], None),+ "https://api.bugsnag.com/projects/p1/errors?per_page=100": ([{"id": "e1"}], next_url),+ next_url: ([{"id": "e2"}], None),+ }+ rows = _collect("errors", pages, _FakeResumableManager(), monkeypatch)+ assert rows == [+ {"id": "e1", "organization_id": "o1", "project_id": "p1"},+ {"id": "e2", "organization_id": "o1", "project_id": "p1"},+ ]++ def test_no_bookmark_advanced_across_parents_without_a_yield(self, monkeypatch: Any) -> None:+ # Small syncs never fill the batcher, so nothing is checkpointed — and crucially the bookmark+ # is never advanced at parent boundaries. Advancing it there (the old behavior) would skip+ # rows still buffered in the shared batcher if a crash hit between parents.+ manager = _FakeResumableManager()+ _collect("errors", self._two_project_pages(), manager, monkeypatch)+ assert manager.saved == []++ def test_resume_refetches_checkpointed_page_then_continues(self, monkeypatch: Any) -> None:+ # A checkpoint points at the CURRENT page of the in-flight parent; resume re-fetches that+ # page (merge dedupes already-yielded rows) and then proceeds to later parents.+ p1_page2 = "https://api.bugsnag.com/projects/p1/errors?offset=2"+ pages = {+ "https://api.bugsnag.com/user/organizations?per_page=100": ([{"id": "o1"}], None),+ "https://api.bugsnag.com/organizations/o1/projects?per_page=100": ([{"id": "p1"}, {"id": "p2"}], None),+ p1_page2: ([{"id": "e1b"}], None),+ "https://api.bugsnag.com/projects/p2/errors?per_page=100": ([{"id": "e2"}], None),+ }+ manager = _FakeResumableManager(BugsnagResumeConfig(next_url=p1_page2, parent_id="p1"))+ rows = _collect("errors", pages, manager, monkeypatch)+ assert rows == [+ {"id": "e1b", "organization_id": "o1", "project_id": "p1"},+ {"id": "e2", "organization_id": "o1", "project_id": "p2"},+ ]++ def test_resume_skips_already_processed_parents(self, monkeypatch: Any) -> None:+ # Bookmarked at p2: p1 must not be re-fetched (its errors URL is absent from `pages`, so a+ # fetch would raise), only p2's rows are produced.+ pages = {+ "https://api.bugsnag.com/user/organizations?per_page=100": ([{"id": "o1"}], None),+ "https://api.bugsnag.com/organizations/o1/projects?per_page=100": ([{"id": "p1"}, {"id": "p2"}], None),+ "https://api.bugsnag.com/projects/p2/errors?per_page=100": ([{"id": "e2"}], None),+ }+ manager = _FakeResumableManager(BugsnagResumeConfig(next_url=None, parent_id="p2"))+ rows = _collect("errors", pages, manager, monkeypatch)+ assert rows == [{"id": "e2", "organization_id": "o1", "project_id": "p2"}]++ def test_resume_from_deleted_parent_restarts_from_first(self, monkeypatch: Any) -> None:+ manager = _FakeResumableManager(BugsnagResumeConfig(next_url=None, parent_id="GONE"))+ rows = _collect("errors", self._two_project_pages(), manager, monkeypatch)+ assert rows == [+ {"id": "e1", "organization_id": "o1", "project_id": "p1"},+ {"id": "e2", "organization_id": "o1", "project_id": "p2"},+ ]+++class TestValidateCredentials:+ @parameterized.expand(+ [+ ("ok", 200, True),+ ("unauthorized", 401, False),+ ("forbidden", 403, False),+ ("server_error", 500, False),+ ]+ )+ def test_status_mapping(self, _name: str, status_code: int, expected_ok: bool) -> None:+ # parameterized.expand can't also receive the `monkeypatch` fixture, so manage our own.+ session = _FakeSession([_make_response(status_code, body=[])])+ with pytest.MonkeyPatch.context() as mp:+ mp.setattr(bugsnag, "make_tracked_session", lambda *args, **kwargs: session)+ ok, _error = validate_credentials("tok")+ assert ok is expected_ok++ def test_request_exception_is_failure(self, monkeypatch: Any) -> None:+ class _BoomSession:+ def get(self, *args: Any, **kwargs: Any) -> requests.Response:+ raise requests.exceptions.ConnectionError("boom")++ monkeypatch.setattr(bugsnag, "make_tracked_session", lambda *args, **kwargs: _BoomSession())+ ok, error = validate_credentials("tok")+ assert ok is False+ assert error is not None+++class TestTokenRedaction:+ """The token rides in a custom `Authorization: token …` scheme the tracked transport's+ scrubber doesn't recognise, so every session it builds must redact the token by value."""++ def test_validate_credentials_redacts_token(self, monkeypatch: Any) -> None:+ captured: dict[str, Any] = {}++ def fake_make_session(*args: Any, **kwargs: Any) -> Any:+ captured.update(kwargs)+ return _FakeSession([_make_response(200, body=[])])++ monkeypatch.setattr(bugsnag, "make_tracked_session", fake_make_session)+ validate_credentials("super-secret-token")+ assert captured.get("redact_values") == ("super-secret-token",)++ def test_get_rows_redacts_token(self, monkeypatch: Any) -> None:+ captured: dict[str, Any] = {}++ def fake_make_session(*args: Any, **kwargs: Any) -> Any:+ captured.update(kwargs)+ return MagicMock()++ monkeypatch.setattr(bugsnag, "make_tracked_session", fake_make_session)+ monkeypatch.setattr(bugsnag, "_fetch_list_page", lambda *args, **kwargs: ([], None))+ list(+ get_rows(+ auth_token="super-secret-token",+ endpoint="organizations",+ logger=MagicMock(),+ resumable_source_manager=_FakeResumableManager(), # type: ignore[arg-type]+ )+ )+ assert captured.get("redact_values") == ("super-secret-token",)diff --git a/posthog/temporal/data_imports/sources/bugsnag/tests/test_bugsnag_source.py b/posthog/temporal/data_imports/sources/bugsnag/tests/test_bugsnag_source.pynew file mode 100644index 000000000000..b137e29721d5--- /dev/null+++ b/posthog/temporal/data_imports/sources/bugsnag/tests/test_bugsnag_source.py@@ -0,0 +1,188 @@+from typing import Any++from unittest import mock+from unittest.mock import MagicMock++from parameterized import parameterized++from posthog.schema import SourceFieldInputConfig++from posthog.temporal.data_imports.pipelines.pipeline.typings import SourceInputs+from posthog.temporal.data_imports.sources.bugsnag.bugsnag import BugsnagResumeConfig+from posthog.temporal.data_imports.sources.bugsnag.settings import BUGSNAG_ENDPOINTS, ENDPOINTS, BugsnagScope+from posthog.temporal.data_imports.sources.bugsnag.source import BugsnagSource+from posthog.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from posthog.temporal.data_imports.sources.generated_configs import BugsnagSourceConfig++from products.data_warehouse.backend.types import ExternalDataSourceType+++def _source_inputs(schema_name: str = "errors") -> SourceInputs:+ return SourceInputs(+ schema_name=schema_name,+ schema_id="schema-1",+ source_id="source-1",+ team_id=1,+ should_use_incremental_field=False,+ db_incremental_field_last_value=None,+ db_incremental_field_earliest_value=None,+ incremental_field=None,+ incremental_field_type=None,+ job_id="job-1",+ logger=MagicMock(),+ reset_pipeline=False,+ )+++class TestBugsnagSource:+ def setup_method(self) -> None:+ self.source = BugsnagSource()+ self.team_id = 1++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.BUGSNAG++ def test_source_config_basics(self) -> None:+ config = self.source.get_source_config+ assert config.label == "Bugsnag"+ # Alpha + still unreleased while it ships full-refresh-only and awaits live-API verification.+ assert config.unreleasedSource is True+ field_names = [f.name for f in config.fields]+ assert field_names == ["auth_token"]+ auth_field = config.fields[0]+ assert isinstance(auth_field, SourceFieldInputConfig)+ assert auth_field.required is True+ assert auth_field.secret is True++ def test_generated_config_parses_auth_token(self) -> None:+ # Guards the hand-checked generated_configs.py edit: the form field must map to `auth_token`.+ config = BugsnagSourceConfig.from_dict({"auth_token": "tok_123"})+ assert config.auth_token == "tok_123"++ def test_get_schemas_lists_every_endpoint(self) -> None:+ schemas = self.source.get_schemas(MagicMock(), team_id=self.team_id)+ assert {s.name for s in schemas} == set(ENDPOINTS)++ def test_all_schemas_are_full_refresh(self) -> None:+ # Incremental isn't advertised until the server-side time-filter behavior is verified+ # against the live API, so every table ships full refresh only.+ for schema in self.source.get_schemas(MagicMock(), team_id=self.team_id):+ assert schema.supports_incremental is False, schema.name+ assert schema.supports_append is False, schema.name++ @parameterized.expand(+ [+ ("organizations", True),+ ("projects", True),+ ("errors", True),+ ("events", False),+ ("pivots", False),+ ("event_fields", False),+ ("trace_fields", False),+ ]+ )+ def test_should_sync_default(self, endpoint: str, expected_default: bool) -> None:+ schemas = {s.name: s for s in self.source.get_schemas(MagicMock(), team_id=self.team_id)}+ assert schemas[endpoint].should_sync_default is expected_default++ def test_get_schemas_filters_by_names(self) -> None:+ schemas = self.source.get_schemas(MagicMock(), team_id=self.team_id, names=["errors", "projects"])+ assert {s.name for s in schemas} == {"errors", "projects"}++ @mock.patch("posthog.temporal.data_imports.sources.bugsnag.source.validate_bugsnag_credentials")+ def test_validate_credentials_success(self, mock_validate: MagicMock) -> None:+ mock_validate.return_value = (True, None)+ ok, error = self.source.validate_credentials(BugsnagSourceConfig(auth_token="tok"), self.team_id)+ assert ok is True+ assert error is None+ mock_validate.assert_called_once_with("tok")++ @mock.patch("posthog.temporal.data_imports.sources.bugsnag.source.validate_bugsnag_credentials")+ def test_validate_credentials_failure(self, mock_validate: MagicMock) -> None:+ mock_validate.return_value = (False, "Invalid BugSnag auth token")+ ok, error = self.source.validate_credentials(BugsnagSourceConfig(auth_token="bad"), self.team_id)+ assert ok is False+ assert error == "Invalid BugSnag auth token"++ def test_get_resumable_source_manager_binds_resume_config(self) -> None:+ manager = self.source.get_resumable_source_manager(_source_inputs())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is BugsnagResumeConfig++ def test_source_for_pipeline_plumbs_args(self) -> None:+ manager = self.source.get_resumable_source_manager(_source_inputs("errors"))+ response = self.source.source_for_pipeline(+ BugsnagSourceConfig(auth_token="tok"), manager, _source_inputs("errors")+ )+ assert response.name == "errors"+ assert response.primary_keys == BUGSNAG_ENDPOINTS["errors"].primary_keys++ @parameterized.expand(+ [+ ("organizations", ["id"]),+ ("projects", ["id", "organization_id"]),+ ("collaborators", ["id", "organization_id"]),+ ("errors", ["id", "project_id"]),+ ("event_fields", ["display_id", "project_id"]),+ ]+ )+ def test_source_response_primary_keys(self, endpoint: str, expected_keys: list[str]) -> None:+ manager = self.source.get_resumable_source_manager(_source_inputs(endpoint))+ response = self.source.source_for_pipeline(+ BugsnagSourceConfig(auth_token="tok"), manager, _source_inputs(endpoint)+ )+ assert response.primary_keys == expected_keys++ def test_fan_out_children_carry_parent_id_in_primary_key(self) -> None:+ # Fan-out children aggregate rows from every parent, so the parent id injected into each row+ # must be part of the primary key — otherwise per-parent-unique ids collide table-wide and+ # seed duplicate rows that slow every subsequent merge.+ for config in BUGSNAG_ENDPOINTS.values():+ if config.scope is BugsnagScope.PER_ORG:+ assert "organization_id" in config.primary_keys, config.name+ elif config.scope is BugsnagScope.PER_PROJECT:+ assert "project_id" in config.primary_keys, config.name++ @parameterized.expand(+ [+ (+ "unauthorized",+ "401 Client Error: Unauthorized for url: https://api.bugsnag.com/projects/abc/errors?per_page=100",+ ),+ (+ "forbidden",+ "403 Client Error: Forbidden for url: https://api.bugsnag.com/user/organizations?per_page=1",+ ),+ ]+ )+ def test_credential_errors_are_non_retryable(self, _name: str, observed_error: str) -> None:+ non_retryable = self.source.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.bugsnag.com/projects/abc/errors",+ ),+ (+ "server_error",+ "500 Server Error: Internal Server Error for url: https://api.bugsnag.com/user/organizations",+ ),+ ("read_timeout", "HTTPSConnectionPool(host='api.bugsnag.com', port=443): Read timed out."),+ ]+ )+ def test_transient_errors_remain_retryable(self, _name: str, other_error: str) -> None:+ non_retryable = self.source.get_non_retryable_errors()+ assert not any(key in other_error for key in non_retryable)++ def test_canonical_descriptions_cover_core_endpoints(self) -> None:+ descriptions = self.source.get_canonical_descriptions()+ for endpoint in ("organizations", "projects", "errors", "events", "releases"):+ assert endpoint in descriptions+ assert descriptions[endpoint]["description"]++ def test_canonical_description_keys_are_real_endpoints(self) -> None:+ # Canonical descriptions are keyed by schema name; a typo'd key would silently never apply.+ descriptions: dict[str, Any] = self.source.get_canonical_descriptions()+ assert set(descriptions).issubset(set(ENDPOINTS))diff --git a/posthog/temporal/data_imports/sources/generated_configs.py b/posthog/temporal/data_imports/sources/generated_configs.pyindex 30cbc8d80244..8d2940ff0aef 100644--- a/posthog/temporal/data_imports/sources/generated_configs.py+++ b/posthog/temporal/data_imports/sources/generated_configs.py@@ -488,7 +488,7 @@ class BrexSourceConfig(config.Config):@config.configclass BugsnagSourceConfig(config.Config):- pass+ auth_token: str@config.config