: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(bugsnag): sync stability trends, release groups and pivot values (#100157)
Tom Owers5c9c3902cf3c
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.mdindex 70ea2441a1ec..0bfcf9c69695 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/COVERAGE_GAPS_APPENDIX.md@@ -1027,14 +1027,16 @@ Note: docs.bugherd.com/api is a Scalar shell; the real spec is at /api/openapi.y## Bugsnag — gaps-Today (11): `collaborators`, `errors`, `event_fields`, `events`, `organizations`, `pivots`, `projects`, `releases`, `saved_searches`, `teams`, `trace_fields`+Today (15): `collaborators`, `errors`, `event_fields`, `events`, `organizations`, `pivot_values`, `pivots`, `projects`, `release_groups`, `releases`, `saved_searches`, `stability_trend`, `teams`, `trace_fields`, `trend`Diffed against: <https://bugsnagapiv2.docs.apiary.io/api-description-document>-- [ ] `GET /projects/{project_id}/stability_trend` — crash-free sessions and users over time — BugSnag's headline stability metric (high)-- [ ] `GET /projects/{project_id}/release_groups` — lookup grouping the releases already synced (e.g. by app version), plus their stability rollups (high)-- [ ] `GET /projects/{project_id}/trend and GET /projects/{project_id}/errors/{error_id}/trend` — bucketed error occurrence time series at project and error grain (high)-- [ ] `GET /projects/{project_id}/pivots/{event_field_display_id}/values and /errors/{error_id}/pivots/{display_id}/values` — the actual breakdown values behind the pivots table already synced; pivots alone list only dimension names (high)+- [x] `GET /projects/{project_id}/stability_trend` — crash-free sessions and users over time — BugSnag's headline stability metric (high)+- [x] `GET /projects/{project_id}/release_groups` — lookup grouping the releases already synced (e.g. by app version), plus their stability rollups (high)+- [x] `GET /projects/{project_id}/trend` — bucketed error occurrence time series at project grain (high)+- [ ] `GET /projects/{project_id}/errors/{error_id}/trend` — the same time series at error grain; skipped because it costs one request per error per sync, unbounded and with no server-side filter to narrow it (high)+- [x] `GET /projects/{project_id}/pivots/{event_field_display_id}/values` — the actual breakdown values behind the pivots table already synced; pivots alone list only dimension names (high)+- [ ] `GET /projects/{project_id}/errors/{error_id}/pivots/{display_id}/values` — the same breakdown at error grain; skipped for the same per-error fan-out cost (high)- [ ] `GET /projects/{project_id}/span_groups` — performance monitoring aggregates — an entire product surface with no coverage today (medium)- [ ] `GET /projects/{project_id}/span_groups/{id}/spans and /projects/{project_id}/traces/{trace_id}/spans` — individual span records, the event grain under span groups (trace_fields is already synced but has nothing to describe) (medium)- [ ] `GET /projects/{project_id}/page_load_span_groups` — web vitals / page load performance breakdown (medium)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bugsnag/bugsnag.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bugsnag/bugsnag.pyindex 9e5d0f235c10..cd2d9bb585e6 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/bugsnag/bugsnag.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bugsnag/bugsnag.py@@ -45,7 +45,7 @@ class BugsnagResumeConfig:parent_id: str | None = None[email protected](frozen=True)class _FanOutParent:# Id used to resolve the endpoint path and to bookmark resume position.resume_id: str@@ -54,6 +54,9 @@ class _FanOutParent:# 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]+ # Query parameters that identify this parent, for endpoints that scope by parameter rather than+ # by path (release groups take their release stage this way).+ params: dict[str, str] = dataclasses.field(default_factory=dict)def _get_headers(auth_token: str) -> dict[str, str]:@@ -92,7 +95,13 @@ def _parse_next_url(link_header: str) -> str | None: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):+def _fetch_page(+ session: requests.Session,+ page_url: str,+ headers: dict[str, str],+ logger: FilteringBoundLogger,+ tolerated_statuses: tuple[int, ...] = (),+):response = session.get(page_url, headers=headers, timeout=60)# BugSnag rate limits per 1-minute window and returns 429 on exceed; retry those plus@@ -100,7 +109,7 @@ def _fetch_page(session: requests.Session, page_url: str, headers: dict[str, strif 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:+ if not response.ok and response.status_code not in tolerated_statuses:logger.error(f"BugSnag API error: status={response.status_code}, body={response.text}, url={page_url}")response.raise_for_status()@@ -142,6 +151,42 @@ def _fetch_list_page_or_stop(raise+def _endpoint_params(config: BugsnagEndpointConfig, parent: _FanOutParent | None = None) -> dict[str, Any]:+ params: dict[str, Any] = {}+ if config.page_size is not None:+ params["per_page"] = config.page_size+ params.update(config.params)+ if parent is not None:+ params.update(parent.params)+ return params+++def _object_rows(+ session: requests.Session,+ url: str,+ headers: dict[str, str],+ config: BugsnagEndpointConfig,+ logger: FilteringBoundLogger,+) -> list[dict[str, Any]]:+ """Flatten a single-object endpoint into one row per item of its nested array.++ The object's own scalar fields (e.g. the release stage the trend describes) are copied onto+ every row, so each row stands alone in the warehouse."""+ row_field = config.object_row_field+ if row_field is None:+ return []+ response = _fetch_page(session, url, headers, logger, tolerated_statuses=config.missing_data_statuses)+ # 204 is the documented "this parent has no data yet" answer, and carries no body to parse.+ if response.status_code == 204 or not response.ok or not response.content:+ return []+ data = response.json()+ if not isinstance(data, dict):+ return []+ nested = data.get(row_field) or []+ scalars = {key: value for key, value in data.items() if key != row_field}+ return [{**scalars, **item} for item in nested if isinstance(item, dict)]++def _iter_all_pages(session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger) -> Iterator[dict[str, Any]]:@@ -159,12 +204,20 @@ def _resolve_org_ids(session: requests.Session, headers: dict[str, str], logger:return [org["id"] for org in _iter_all_pages(session, url, headers, logger)]+def _iter_projects(+ session: requests.Session, headers: dict[str, str], logger: FilteringBoundLogger+) -> Iterator[tuple[str, dict[str, Any]]]:+ """Yield (organization_id, project) for every project the token can see."""+ for org_id in _resolve_org_ids(session, headers, logger):+ 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):+ yield org_id, project++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(@@ -172,22 +225,53 @@ def _resolve_parents(path_kwargs={"organization_id": org_id},inject={"organization_id": org_id},)- for org_id in org_ids+ for org_id in _resolve_org_ids(session, headers, logger)]- # 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},+ for org_id, project in _iter_projects(session, headers, logger):+ project_id = project["id"]+ inject = {"organization_id": org_id, "project_id": project_id}++ if config.scope == BugsnagScope.PER_PROJECT:+ parents.append(_FanOutParent(resume_id=project_id, path_kwargs={"project_id": project_id}, inject=inject))+ continue++ project_parents: list[_FanOutParent] = []+ if config.scope == BugsnagScope.PER_PROJECT_RELEASE_STAGE:+ # A project reports the stages it has seen events for; one with none has no release+ # groups to list, and the endpoint rejects a request without a stage.+ for stage in project.get("release_stages") or []:+ project_parents.append(+ _FanOutParent(+ resume_id=f"{project_id}:{stage}",+ path_kwargs={"project_id": project_id},+ inject=inject,+ params={"release_stage_name": stage},+ )+ )+ elif config.scope == BugsnagScope.PER_PROJECT_PIVOT:+ pivots_url = _build_url(f"{BUGSNAG_BASE_URL}/projects/{project_id}/pivots", {"per_page": PAGE_SIZE})+ for pivot in _iter_all_pages(session, pivots_url, headers, logger):+ display_id = pivot["event_field_display_id"]+ project_parents.append(+ _FanOutParent(+ resume_id=f"{project_id}:{display_id}",+ path_kwargs={"project_id": project_id, "event_field_display_id": display_id},+ inject={**inject, "event_field_display_id": display_id},+ ))++ cap = config.max_parents_per_project+ if cap is not None and len(project_parents) > cap:+ # Each parent is a paginated collection of its own, so an inflated count turns one+ # project into an unbounded sync. Take a deterministic prefix and say so.+ logger.warning(+ f"BugSnag: project={project_id} offers {len(project_parents)} fan-out parents for "+ f"{config.name}; syncing the first {cap}")+ project_parents = project_parents[:cap]+ parents.extend(project_parents)return parents@@ -205,7 +289,7 @@ def _iter_top_level(url = resume.next_urllogger.debug(f"BugSnag: resuming {config.name} from URL: {url}")else:- url = _build_url(f"{BUGSNAG_BASE_URL}{config.path}", {"per_page": config.page_size})+ url = _build_url(f"{BUGSNAG_BASE_URL}{config.path}", _endpoint_params(config))first_page = Truewhile True:@@ -257,13 +341,22 @@ def _iter_fan_out(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": config.page_size})+ params = _endpoint_params(config, parent)+ url = resume_url or _build_url(f"{BUGSNAG_BASE_URL}{path}", params)resume_url = None # only the resumed-into parent uses the saved URL; the rest start fresh- first_page = True+ if config.object_row_field is not None:+ for item in _object_rows(session, url, headers, config, logger):+ batcher.batch({**item, **parent.inject})+ if batcher.should_yield():+ yield batcher.get_table()+ manager.save_state(BugsnagResumeConfig(next_url=None, parent_id=parent.resume_id))+ continue++ page_count = 0while True:- items, next_url = _fetch_list_page_or_stop(session, url, headers, logger, is_first_page=first_page)- first_page = False+ items, next_url = _fetch_list_page_or_stop(session, url, headers, logger, is_first_page=page_count == 0)+ page_count += 1# 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@@ -278,6 +371,12 @@ def _iter_fan_out(manager.save_state(BugsnagResumeConfig(next_url=checkpoint_url, parent_id=parent.resume_id))if not next_url:break+ if config.max_pages is not None and page_count >= config.max_pages:+ logger.warning(+ f"BugSnag: page cap reached for {config.name} on parent={parent.resume_id}; "+ "stopping this collection early"+ )+ breakurl = next_urldiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bugsnag/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bugsnag/canonical_descriptions.pyindex 25a8f022bf70..9abf1df1d5b2 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/bugsnag/canonical_descriptions.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bugsnag/canonical_descriptions.py@@ -100,6 +100,72 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {"unhandled_sessions_count": "Number of sessions with an unhandled error.",},},+ "stability_trend": {+ "description": "Unhandled session information for each UTC day of the last 30 days, for the project's primary release stage. One row per project per day. Session stability is (1 - unhandled_sessions_count / total_sessions_count) * 100; user stability is (1 - users_with_unhandled / users_seen) * 100.",+ "docs_url": "https://bugsnagapiv2.docs.apiary.io/#reference/projects/stability-trend",+ "columns": {+ "project_id": "Identifier of the project the trend describes.",+ "organization_id": "Identifier of the organization that owns the project (injected by the connector).",+ "release_stage_name": "Name of the primary release stage the trend covers.",+ "bucket_start": "Timestamp marking the beginning of the day this row covers.",+ "bucket_end": "Timestamp marking the end of the day this row covers.",+ "total_sessions_count": "Total number of sessions in the time range.",+ "unhandled_sessions_count": "Number of sessions with at least one unhandled event in the time range.",+ "users_seen": "Number of users with at least one session in the time range.",+ "users_with_unhandled": "Number of users who experienced an unhandled session in the time range.",+ },+ },+ "trend": {+ "description": "Event occurrences for a project bucketed over time, one row per bucket. Buckets span 12 hours.",+ "docs_url": "https://bugsnagapiv2.docs.apiary.io/#reference/errors/trends",+ "columns": {+ "project_id": "Identifier of the project the trend describes (injected by the connector).",+ "organization_id": "Identifier of the organization that owns the project (injected by the connector).",+ "from": "Start of the bucket's time range.",+ "to": "End of the bucket's time range.",+ "events_count": "Number of events that occurred in the bucket.",+ },+ },+ "release_groups": {+ "description": "A collection of releases sharing a release stage and app version, with the group's stability rollups. Non-mobile projects usually have one release per group; mobile projects can have many, one per secondary version.",+ "docs_url": "https://bugsnagapiv2.docs.apiary.io/#reference/releases/release-groups",+ "columns": {+ "id": "Unique identifier for the release group.",+ "project_id": "Identifier of the project the release group belongs to.",+ "organization_id": "Identifier of the organization that owns the project (injected by the connector).",+ "release_stage_name": "Name of the release stage for this release group.",+ "app_version": "Version string shared by the releases in this group.",+ "first_released_at": "When the first release of this group was released.",+ "first_release_id": "Identifier of the first release in this group.",+ "releases_count": "Number of releases that belong to this group.",+ "has_secondary_versions": "Whether the releases in this group use version codes or bundle versions.",+ "build_tool": "Tool that reported the first release of this group.",+ "builder_name": "Person or system that triggered the first release of this group.",+ "source_control": "Source control information for the first release of this group.",+ "total_sessions_count": "Total number of sessions seen for this release group.",+ "unhandled_sessions_count": "Number of sessions in this group that had at least one unhandled event.",+ "sessions_count_in_last_24h": "Number of sessions seen in the last 24 hours for this group.",+ "accumulative_daily_users_seen": "Number of users with at least one session in this group.",+ "accumulative_daily_users_with_unhandled": "Number of user sessions with at least one unhandled event.",+ "top_release_group": "Whether this group is one of the project's top releases.",+ "visible": "Whether this release group is visible in the dashboard.",+ },+ },+ "pivot_values": {+ "description": "The individual values behind each of a project's pivots — the release stages, app versions, users or other event-field values events are broken down by — with how many events each accounts for.",+ "docs_url": "https://bugsnagapiv2.docs.apiary.io/#reference/errors/pivots",+ "columns": {+ "project_id": "Identifier of the project the pivot belongs to (injected by the connector).",+ "organization_id": "Identifier of the organization that owns the project (injected by the connector).",+ "event_field_display_id": "Display id of the event field this value belongs to, e.g. app.release_stage (injected by the connector).",+ "event_field_value": "One value of the event field, e.g. a stage name, a version number or a user id.",+ "events": "Number of events that had this value for the event field.",+ "proportion": "Proportion of the matching events represented by this value.",+ "first_seen": "First event occurrence with this value.",+ "last_seen": "Most recent event occurrence with this value.",+ "fields": "Additional event field values describing this pivot value, e.g. the name and email behind a user id.",+ },+ },"saved_searches": {"description": "A saved error filter/search defined in a project.","docs_url": "https://bugsnagapiv2.docs.apiary.io/#reference/saved-searches",diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bugsnag/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bugsnag/settings.pyindex a17262f43b7f..dc24af2f0147 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/bugsnag/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bugsnag/settings.py@@ -20,9 +20,15 @@ class BugsnagScope(Enum):PER_ORG = "per_org"# Fan out over every project in every organization (GET /projects/{project_id}/...).PER_PROJECT = "per_project"+ # Fan out over every (project, release stage) pair. Release-stage-scoped endpoints require the+ # stage as a query parameter; the stages a project has seen come back on the project itself.+ PER_PROJECT_RELEASE_STAGE = "per_project_release_stage"+ # Fan out over every (project, pivot) pair, where the pivots are the ones the `pivots` endpoint+ # lists for that project.+ PER_PROJECT_PIVOT = "per_project_pivot"-@dataclass+@dataclass(frozen=True)class BugsnagEndpointConfig:name: strscope: BugsnagScope@@ -38,8 +44,23 @@ class BugsnagEndpointConfig:partition_key: Optional[str] = None# per_page value used when paginating this endpoint. Most list endpoints accept up to 100, but# a few cap lower and hard-reject an over-max value with a 400 instead of clamping, so those- # need their own limit.- page_size: int = 100+ # need their own limit. None omits the parameter, for endpoints that return a fixed-size result.+ page_size: Optional[int] = 100+ # Static query parameters every request to this endpoint carries.+ params: dict[str, str] = field(default_factory=dict)+ # When set, the endpoint returns a single JSON object instead of a list, and each item of the+ # named nested array becomes a row carrying the object's own scalar fields.+ object_row_field: Optional[str] = None+ # Statuses meaning "this parent has no data here" rather than "the sync is broken". Fanning out+ # over every project reaches projects the endpoint has nothing for, so those are skipped.+ missing_data_statuses: tuple[int, ...] = ()+ # Hard page cap per fan-out parent. Guards endpoints whose result size follows the cardinality+ # of user-supplied data rather than anything the API bounds.+ max_pages: Optional[int] = None+ # Cap on how many fan-out parents a single project contributes. Release stages and pivots are+ # both derived from client-reported event data, so nothing in the API bounds how many a project+ # accumulates — a misconfigured reporter alone can add one per build.+ max_parents_per_project: Optional[int] = 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.@@ -130,6 +151,55 @@ BUGSNAG_ENDPOINTS: dict[str, BugsnagEndpointConfig] = {path="/projects/{project_id}/saved_searches",primary_keys=["id", "project_id"],),+ # One row per UTC day per project for the last 30 days, flattened out of the single object the+ # endpoint returns. Projects with no sessions answer 204 or 404 and are skipped.+ "stability_trend": BugsnagEndpointConfig(+ name="stability_trend",+ scope=BugsnagScope.PER_PROJECT,+ path="/projects/{project_id}/stability_trend",+ primary_keys=["project_id", "bucket_start"],+ partition_key="bucket_start",+ page_size=None,+ object_row_field="timeline_points",+ missing_data_statuses=(404,),+ ),+ # Bucketed event counts for the project as a whole. `resolution` gives fixed-width buckets, so+ # re-syncs merge onto the same boundaries instead of accumulating shifted ones; 12h keeps the+ # point count far below the endpoint's 2000-point ceiling.+ "trend": BugsnagEndpointConfig(+ name="trend",+ scope=BugsnagScope.PER_PROJECT,+ path="/projects/{project_id}/trend",+ primary_keys=["project_id", "from"],+ partition_key="from",+ page_size=None,+ params={"resolution": "12h"},+ ),+ "release_groups": BugsnagEndpointConfig(+ name="release_groups",+ scope=BugsnagScope.PER_PROJECT_RELEASE_STAGE,+ path="/projects/{project_id}/release_groups",+ primary_keys=["id", "project_id"],+ partition_key="first_released_at",+ # The endpoint documents 30 per page and no maximum, so stay on the documented value.+ page_size=30,+ max_parents_per_project=25,+ ),+ # The breakdown values behind each pivot. Cardinality follows the underlying event field — a+ # user-id pivot has a value per user — so it is off by default and capped per pivot.+ "pivot_values": BugsnagEndpointConfig(+ name="pivot_values",+ scope=BugsnagScope.PER_PROJECT_PIVOT,+ path="/projects/{project_id}/pivots/{event_field_display_id}/values",+ primary_keys=["project_id", "event_field_display_id", "event_field_value"],+ page_size=30,+ # Sorted results are truncated with error code 60000 once there are too many of them, and+ # the API documents `unsorted` as the way to read a pivot's values in full.+ params={"sort": "unsorted"},+ max_pages=100,+ max_parents_per_project=25,+ should_sync_default=False,+ ),}ENDPOINTS = tuple(BUGSNAG_ENDPOINTS.keys())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bugsnag/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bugsnag/source.pyindex bb8d780a8d3c..23dd2d44939b 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/bugsnag/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bugsnag/source.py@@ -99,6 +99,8 @@ You can generate a personal auth token in the **My Account** section of your [Budef _description(endpoint: str) -> str | None:if endpoint == "events":return "One row per captured event. Can be very large — full refresh only, off by default."+ if endpoint == "pivot_values":+ return "One row per value of each pivot. As wide as the underlying event field — off by default."return Nonedef _build_schema(endpoint: str) -> SourceSchema:diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bugsnag/tests/test_bugsnag.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bugsnag/tests/test_bugsnag.pyindex 9f4b679d6645..5e8cc1eeec72 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/bugsnag/tests/test_bugsnag.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bugsnag/tests/test_bugsnag.py@@ -1,4 +1,5 @@import json+import dataclassesfrom collections.abc import Mappingfrom typing import Any@@ -12,6 +13,7 @@ from tenacity import stop_after_attempt, wait_nonefrom products.warehouse_sources.backend.temporal.data_imports.sources.bugsnag import bugsnagfrom products.warehouse_sources.backend.temporal.data_imports.sources.bugsnag.bugsnag import (BUGSNAG_BASE_URL,+ BUGSNAG_ENDPOINTS,BugsnagResumeConfig,BugsnagRetryableError,_build_url,@@ -59,6 +61,42 @@ class _FakeSession:return self._responses.pop(0)+def _collect_objects(+ endpoint: str,+ pages: Mapping[str, tuple[list[dict], str | None]],+ objects: Mapping[str, requests.Response],+ manager: _FakeResumableManager,+ monkeypatch: Any,+) -> list[dict]:+ """Like `_collect`, but also serves the single-object endpoints out of `objects`."""+ 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]++ def fake_fetch_page(+ session: Any, url: str, headers: Any, logger: Any, tolerated_statuses: tuple[int, ...] = ()+ ) -> requests.Response:+ if url not in objects:+ raise AssertionError(f"unexpected object URL requested: {url}")+ return objects[url]++ monkeypatch.setattr(bugsnag, "_fetch_list_page", fake_fetch_list_page)+ monkeypatch.setattr(bugsnag, "_fetch_page", fake_fetch_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++def _collect(endpoint: str,pages: Mapping[str, tuple[list[dict], str | None]],@@ -138,6 +176,22 @@ class TestFetchPage:# 404 is not retryable, so only one request is made.assert len(session.requested_urls) == 1+ def test_tolerated_status_is_returned_instead_of_raising(self) -> None:+ # Fanning out a single-object endpoint reaches projects it has no data for. Those answers+ # are expected, so they must come back as a response rather than an error log plus a raise.+ not_found = _make_response(404, body={"errors": ["Project not found"]})+ session = _FakeSession([not_found])+ logger = MagicMock()+ returned = bugsnag._fetch_page(+ session, # type: ignore[arg-type]+ "https://api.bugsnag.com/x",+ {},+ logger,+ tolerated_statuses=(404,),+ )+ assert returned is not_found+ logger.error.assert_not_called()+def test_ok_response_returned(self) -> None:ok = _make_response(200, body=[{"id": "o1"}])session = _FakeSession([ok])@@ -386,3 +440,187 @@ class TestTokenRedaction:))assert captured.get("redact_values") == ("super-secret-token",)+++_ORGS_URL = "https://api.bugsnag.com/user/organizations?per_page=100"+_PROJECTS_URL = "https://api.bugsnag.com/organizations/o1/projects?per_page=100"+++class TestStabilityTrend:+ """The endpoint answers with a single object per project rather than a list, so the connector+ flattens its nested timeline points into one row per project per day."""++ def test_flattens_timeline_points_carrying_the_object_scalars(self, monkeypatch: Any) -> None:+ pages = {+ _ORGS_URL: ([{"id": "o1"}], None),+ _PROJECTS_URL: ([{"id": "p1"}], None),+ }+ objects = {+ "https://api.bugsnag.com/projects/p1/stability_trend": _make_response(+ 200,+ body={+ "project_id": "p1",+ "release_stage_name": "production",+ "timeline_points": [+ {"bucket_start": "2019-03-02T00:00:00.000Z", "total_sessions_count": 10},+ {"bucket_start": "2019-03-03T00:00:00.000Z", "total_sessions_count": 20},+ ],+ },+ )+ }+ rows = _collect_objects("stability_trend", pages, objects, _FakeResumableManager(), monkeypatch)+ assert rows == [+ {+ "project_id": "p1",+ "release_stage_name": "production",+ "bucket_start": "2019-03-02T00:00:00.000Z",+ "total_sessions_count": 10,+ "organization_id": "o1",+ },+ {+ "project_id": "p1",+ "release_stage_name": "production",+ "bucket_start": "2019-03-03T00:00:00.000Z",+ "total_sessions_count": 20,+ "organization_id": "o1",+ },+ ]++ @parameterized.expand([("no_sessions_yet", 204), ("no_primary_release_stage", 404)])+ def test_project_without_stability_data_is_skipped(self, _name: str, status_code: int) -> None:+ # Every project is fanned out over, including ones the endpoint has nothing for. Those+ # answers must produce no rows instead of failing the whole table's sync.+ pages = {+ _ORGS_URL: ([{"id": "o1"}], None),+ _PROJECTS_URL: ([{"id": "p1"}, {"id": "p2"}], None),+ }+ objects = {+ "https://api.bugsnag.com/projects/p1/stability_trend": _make_response(status_code),+ "https://api.bugsnag.com/projects/p2/stability_trend": _make_response(+ 200,+ body={"project_id": "p2", "timeline_points": [{"bucket_start": "2019-03-02T00:00:00.000Z"}]},+ ),+ }+ with pytest.MonkeyPatch.context() as mp:+ rows = _collect_objects("stability_trend", pages, objects, _FakeResumableManager(), mp)+ assert rows == [{"bucket_start": "2019-03-02T00:00:00.000Z", "project_id": "p2", "organization_id": "o1"}]+++class TestProjectTrend:+ def test_requests_fixed_width_buckets_and_no_per_page(self, monkeypatch: Any) -> None:+ # The endpoint takes no per_page and rejects a request carrying neither `resolution` nor+ # `buckets_count`; a URL that drifts from this shape is absent from `pages` and raises.+ pages: dict[str, tuple[list[dict], str | None]] = {+ _ORGS_URL: ([{"id": "o1"}], None),+ _PROJECTS_URL: ([{"id": "p1"}], None),+ "https://api.bugsnag.com/projects/p1/trend?resolution=12h": (+ [{"from": "2017-04-03T22:43:49Z", "to": "2017-04-04T10:43:49Z", "events_count": 3}],+ None,+ ),+ }+ rows = _collect("trend", pages, _FakeResumableManager(), monkeypatch)+ assert rows == [+ {+ "from": "2017-04-03T22:43:49Z",+ "to": "2017-04-04T10:43:49Z",+ "events_count": 3,+ "organization_id": "o1",+ "project_id": "p1",+ }+ ]+++class TestReleaseGroups:+ def test_fans_out_once_per_release_stage(self, monkeypatch: Any) -> None:+ # The stage is a required query parameter, and a project can have several, so each stage+ # is its own fan-out parent.+ pages: dict[str, tuple[list[dict], str | None]] = {+ _ORGS_URL: ([{"id": "o1"}], None),+ _PROJECTS_URL: ([{"id": "p1", "release_stages": ["production", "staging"]}], None),+ "https://api.bugsnag.com/projects/p1/release_groups?per_page=30&release_stage_name=production": (+ [{"id": "rg1"}],+ None,+ ),+ "https://api.bugsnag.com/projects/p1/release_groups?per_page=30&release_stage_name=staging": (+ [{"id": "rg2"}],+ None,+ ),+ }+ rows = _collect("release_groups", pages, _FakeResumableManager(), monkeypatch)+ assert rows == [+ {"id": "rg1", "organization_id": "o1", "project_id": "p1"},+ {"id": "rg2", "organization_id": "o1", "project_id": "p1"},+ ]++ def test_release_stage_count_is_capped_per_project(self, monkeypatch: Any) -> None:+ # Release stages come from client-reported event data, so a project can accumulate any+ # number of them and each is a paginated collection. Only the capped prefix is requested —+ # the stage past the cap is absent from `pages`, so requesting it would raise.+ capped = dataclasses.replace(BUGSNAG_ENDPOINTS["release_groups"], max_parents_per_project=2)+ monkeypatch.setitem(BUGSNAG_ENDPOINTS, "release_groups", capped)+ base = "https://api.bugsnag.com/projects/p1/release_groups?per_page=30&release_stage_name="+ pages: dict[str, tuple[list[dict], str | None]] = {+ _ORGS_URL: ([{"id": "o1"}], None),+ _PROJECTS_URL: ([{"id": "p1", "release_stages": ["s1", "s2", "s3"]}], None),+ f"{base}s1": ([{"id": "rg1"}], None),+ f"{base}s2": ([{"id": "rg2"}], None),+ }+ rows = _collect("release_groups", pages, _FakeResumableManager(), monkeypatch)+ assert [row["id"] for row in rows] == ["rg1", "rg2"]++ def test_project_without_release_stages_is_skipped(self, monkeypatch: Any) -> None:+ # A project that has seen no events has no stages, and the endpoint rejects a request+ # without one — so it must not be requested at all.+ pages: dict[str, tuple[list[dict], str | None]] = {+ _ORGS_URL: ([{"id": "o1"}], None),+ _PROJECTS_URL: ([{"id": "p1"}, {"id": "p2", "release_stages": []}], None),+ }+ rows = _collect("release_groups", pages, _FakeResumableManager(), monkeypatch)+ assert rows == []+++class TestPivotValues:+ def _pivot_pages(self) -> dict[str, tuple[list[dict], str | None]]:+ return {+ _ORGS_URL: ([{"id": "o1"}], None),+ _PROJECTS_URL: ([{"id": "p1"}], None),+ "https://api.bugsnag.com/projects/p1/pivots?per_page=100": (+ [{"event_field_display_id": "app.release_stage"}],+ None,+ ),+ }++ def test_fans_out_over_project_pivots_and_injects_the_display_id(self, monkeypatch: Any) -> None:+ # The display id only exists in the request path, so without injection the rows could not be+ # told apart per pivot and the primary key would collapse.+ pages = self._pivot_pages()+ pages["https://api.bugsnag.com/projects/p1/pivots/app.release_stage/values?per_page=30&sort=unsorted"] = (+ [{"event_field_value": "production", "events": 23}],+ None,+ )+ rows = _collect("pivot_values", pages, _FakeResumableManager(), monkeypatch)+ assert rows == [+ {+ "event_field_value": "production",+ "events": 23,+ "organization_id": "o1",+ "project_id": "p1",+ "event_field_display_id": "app.release_stage",+ }+ ]++ def test_page_cap_stops_a_high_cardinality_pivot(self, monkeypatch: Any) -> None:+ # A pivot over a field like user id has a value per user, and the API keeps handing out+ # cursors. The cap must stop that parent — the third page is absent from `pages`, so+ # following it would raise.+ values_url = "https://api.bugsnag.com/projects/p1/pivots/app.release_stage/values?per_page=30&sort=unsorted"+ page2 = f"{values_url}&offset=2"+ pages = self._pivot_pages()+ pages[values_url] = ([{"event_field_value": "v1"}], page2)+ pages[page2] = ([{"event_field_value": "v2"}], f"{values_url}&offset=3")++ capped = dataclasses.replace(BUGSNAG_ENDPOINTS["pivot_values"], max_pages=2)+ monkeypatch.setitem(BUGSNAG_ENDPOINTS, "pivot_values", capped)++ rows = _collect("pivot_values", pages, _FakeResumableManager(), monkeypatch)+ assert [row["event_field_value"] for row in rows] == ["v1", "v2"]diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/bugsnag/tests/test_bugsnag_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/bugsnag/tests/test_bugsnag_source.pyindex ba0ff7bc5a9b..77834e22a211 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/bugsnag/tests/test_bugsnag_source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/bugsnag/tests/test_bugsnag_source.py@@ -76,6 +76,10 @@ class TestBugsnagSource:("pivots", False),("event_fields", False),("trace_fields", False),+ ("stability_trend", True),+ ("trend", True),+ ("release_groups", True),+ ("pivot_values", False),])def test_should_sync_default(self, endpoint: str, expected_default: bool) -> None:@@ -113,6 +117,10 @@ class TestBugsnagSource:("collaborators", ["id", "organization_id"]),("errors", ["id", "project_id"]),("event_fields", ["display_id", "project_id"]),+ ("stability_trend", ["project_id", "bucket_start"]),+ ("trend", ["project_id", "from"]),+ ("release_groups", ["id", "project_id"]),+ ("pivot_values", ["project_id", "event_field_display_id", "event_field_value"]),])def test_source_response_primary_keys(self, endpoint: str, expected_keys: list[str]) -> None:@@ -126,10 +134,15 @@ class TestBugsnagSource:# 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.+ project_scopes = {+ BugsnagScope.PER_PROJECT,+ BugsnagScope.PER_PROJECT_RELEASE_STAGE,+ BugsnagScope.PER_PROJECT_PIVOT,+ }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:+ elif config.scope in project_scopes:assert "project_id" in config.primary_keys, config.name@parameterized.expand(