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(warehouse-sources): add Bugsnag error-grain and performance tables (#100952)

Tom Owersea45f6e62596
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.md
index 122215835aa8..451f6caee81f 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
@@ -1033,18 +1033,19 @@ Note: docs.bugherd.com/api is a Scalar shell; the real spec is at /api/openapi.y
## Bugsnag — gaps
-Today (15): `collaborators`, `errors`, `event_fields`, `events`, `organizations`, `pivot_values`, `pivots`, `projects`, `release_groups`, `releases`, `saved_searches`, `stability_trend`, `teams`, `trace_fields`, `trend`
+Today (19): `collaborators`, `error_pivot_values`, `error_trend`, `errors`, `event_fields`, `events`, `organizations`, `pivot_values`, `pivots`, `projects`, `release_groups`, `releases`, `saved_searches`, `span_group_spans`, `span_groups`, `stability_trend`, `teams`, `trace_fields`, `trend`
Diffed against: <https://bugsnagapiv2.docs.apiary.io/api-description-document>
- [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}/errors/{error_id}/trend` — the same time series at error grain; capped at each project's most recently seen errors, since it costs one request per error and the API exposes no filter to narrow the error list (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)
+- [x] `GET /projects/{project_id}/errors/{error_id}/pivots/{display_id}/values` — the same breakdown at error grain; both the error and pivot dimensions are capped to bound the fan-out (high)
+- [x] `GET /projects/{project_id}/span_groups` — performance monitoring aggregates — an entire product surface with no coverage today (medium)
+- [x] `GET /projects/{project_id}/span_groups/{id}/spans` — individual span records, the event grain under span groups (trace_fields is already synced but has nothing to describe). The endpoint takes no offset or cursor, so the table is a sample of each group's most recent spans (medium)
+- [ ] `GET /projects/{project_id}/traces/{trace_id}/spans` — the same span records addressed by trace; skipped because the API has no endpoint that lists trace ids, so there is nothing to fan out over (medium)
- [ ] `GET /projects/{project_id}/page_load_span_groups` — web vitals / page load performance breakdown (medium)
- [ ] `GET /organizations/{organization_id}/teams/{id}/collaborators` — membership join between the teams and collaborators tables already synced (medium)
- [ ] `GET /organizations/{organization_id}/collaborators/{collaborator_id}/project_accesses` — which projects each collaborator can access — needed to attribute errors to owners (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.py
index cd2d9bb585e6..6cdcc7b2b70a 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
@@ -1,8 +1,9 @@
import re
import dataclasses
-from collections.abc import Iterator
+from collections.abc import Callable, Iterator
+from itertools import islice
from typing import Any
-from urllib.parse import urlencode
+from urllib.parse import parse_qs, quote, urlencode, urlparse, urlunparse
import requests
from structlog.types import FilteringBoundLogger
@@ -89,6 +90,20 @@ def _parse_next_url(link_header: str) -> str | None:
return None
+def _next_offset_url(url: str, page_len: int) -> str | None:
+ """Return the next page URL of an ``offset``-paginated endpoint, or None at the last page.
+
+ BugSnag's performance endpoints page by a numeric row offset and send no Link header, so a
+ page shorter than ``per_page`` is the only end-of-data signal available."""
+ parsed = urlparse(url)
+ query = parse_qs(parsed.query)
+ per_page = int(query.get("per_page", ["0"])[0] or 0)
+ if per_page <= 0 or page_len < per_page:
+ return None
+ query["offset"] = [str(int(query.get("offset", ["0"])[0] or 0) + page_len)]
+ return urlunparse(parsed._replace(query=urlencode(query, doseq=True)))
+
+
@retry(
retry=retry_if_exception_type((BugsnagRetryableError, requests.ReadTimeout, requests.ConnectionError)),
stop=stop_after_attempt(5),
@@ -117,22 +132,38 @@ def _fetch_page(
def _fetch_list_page(
- session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger
+ session: requests.Session,
+ url: str,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ tolerated_statuses: tuple[int, ...] = (),
+ paginate_by_offset: bool = False,
) -> 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)
+ Link header, not the body. The performance endpoints are the exception and page by offset."""
+ response = _fetch_page(session, url, headers, logger, tolerated_statuses=tolerated_statuses)
+ # A tolerated failure, a 204, or an empty body all mean "nothing here" rather than an error.
+ if response.status_code == 204 or not response.ok or not response.content:
+ return [], None
data = response.json()
if not isinstance(data, list):
- # Defensive: a non-list body has no rows to emit and no Link cursor to follow.
+ # Defensive: a non-list body has no rows to emit and no cursor to follow.
return [], None
+ if paginate_by_offset:
+ return data, _next_offset_url(url, len(data))
return data, _parse_next_url(response.headers.get("Link", ""))
def _fetch_list_page_or_stop(
- session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger, is_first_page: bool
+ session: requests.Session,
+ url: str,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ is_first_page: bool,
+ tolerated_statuses: tuple[int, ...] = (),
+ paginate_by_offset: bool = False,
) -> tuple[list[dict[str, Any]], str | None]:
"""Like `_fetch_list_page`, but ends pagination gracefully at BugSnag's depth ceiling.
@@ -142,7 +173,14 @@ def _fetch_list_page_or_stop(
the 422 as end-of-data and keep the rows already pulled rather than failing the whole sync. A
422 on the first page is left to propagate: BugSnag didn't hand us that cursor."""
try:
- return _fetch_list_page(session, url, headers, logger)
+ return _fetch_list_page(
+ session,
+ url,
+ headers,
+ logger,
+ tolerated_statuses=tolerated_statuses,
+ paginate_by_offset=paginate_by_offset,
+ )
except requests.HTTPError as e:
response = e.response
if not is_first_page and response is not None and response.status_code == 422:
@@ -188,17 +226,49 @@ def _object_rows(
def _iter_all_pages(
- session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger
+ session: requests.Session,
+ url: str,
+ headers: dict[str, str],
+ logger: FilteringBoundLogger,
+ tolerated_statuses: tuple[int, ...] = (),
+ paginate_by_offset: bool = False,
) -> Iterator[dict[str, Any]]:
- """Yield every item across all pages of a list endpoint, following the Link header."""
+ """Yield every item across all pages of a list endpoint, following its next-page cursor."""
while True:
- items, next_url = _fetch_list_page(session, url, headers, logger)
+ items, next_url = _fetch_list_page(
+ session,
+ url,
+ headers,
+ logger,
+ tolerated_statuses=tolerated_statuses,
+ paginate_by_offset=paginate_by_offset,
+ )
yield from items
if not next_url:
return
url = next_url
+def _take_capped(
+ items: Iterator[dict[str, Any]],
+ cap: int | None,
+ what: str,
+ project_id: str,
+ logger: FilteringBoundLogger,
+) -> list[dict[str, Any]]:
+ """Take at most `cap` fan-out parents, reporting when more were available.
+
+ Reads one item past the cap so the truncation can be logged: a table that quietly covers part
+ of a project reads as complete, and each dropped parent is a paginated collection of rows."""
+ if cap is None:
+ return list(items)
+ taken = list(islice(items, cap + 1))
+ if len(taken) > cap:
+ logger.warning(f"BugSnag: project={project_id} has more than {cap} {what}; syncing the first {cap}")
+ return taken[:cap]
+ return taken
+
+
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)]
@@ -214,6 +284,182 @@ def _iter_projects(
yield org_id, project
+def _project_pivot_display_ids(
+ session: requests.Session, headers: dict[str, str], project_id: str, logger: FilteringBoundLogger
+) -> list[str]:
+ url = _build_url(f"{BUGSNAG_BASE_URL}/projects/{project_id}/pivots", {"per_page": PAGE_SIZE})
+ return [pivot["event_field_display_id"] for pivot in _iter_all_pages(session, url, headers, logger)]
+
+
+def _project_error_ids(
+ session: requests.Session,
+ headers: dict[str, str],
+ config: BugsnagEndpointConfig,
+ project_id: str,
+ logger: FilteringBoundLogger,
+) -> list[str]:
+ """The project's errors, most recently seen first, capped for error-grain fan-out.
+
+ The endpoint defaults to `sort=last_seen&direction=desc`, so a capped prefix is the project's
+ active errors, which are the ones an error-grain table is worth having rows for."""
+ cap = config.max_errors_per_project
+ page_size = PAGE_SIZE if cap is None else min(cap + 1, PAGE_SIZE)
+ url = _build_url(f"{BUGSNAG_BASE_URL}/projects/{project_id}/errors", {"per_page": page_size})
+ errors = _take_capped(_iter_all_pages(session, url, headers, logger), cap, "errors", project_id, logger)
+ return [error["id"] for error in errors]
+
+
+def _project_span_group_ids(
+ session: requests.Session,
+ headers: dict[str, str],
+ config: BugsnagEndpointConfig,
+ project_id: str,
+ logger: FilteringBoundLogger,
+) -> list[str]:
+ """The project's span groups, in name order, capped for per-group fan-out.
+
+ The listing carries the endpoint's tolerated statuses because a project that never enabled
+ BugSnag Performance answers here, not on the child path. Without them one such project fails
+ the whole table instead of contributing no parents."""
+ url = _build_url(
+ f"{BUGSNAG_BASE_URL}/projects/{project_id}/span_groups",
+ {"per_page": PAGE_SIZE, "sort": "name", "direction": "asc"},
+ )
+ pages = _iter_all_pages(
+ session,
+ url,
+ headers,
+ logger,
+ tolerated_statuses=config.missing_data_statuses,
+ paginate_by_offset=True,
+ )
+ groups = _take_capped(pages, config.max_parents_per_project, "span groups", project_id, logger)
+ return [group["id"] for group in groups]
+
+
+def _release_stage_parents(
+ session: requests.Session,
+ headers: dict[str, str],
+ config: BugsnagEndpointConfig,
+ project: dict[str, Any],
+ inject: dict[str, str],
+ logger: FilteringBoundLogger,
+) -> list[_FanOutParent]:
+ # 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.
+ project_id = project["id"]
+ return [
+ _FanOutParent(
+ resume_id=f"{project_id}:{stage}",
+ path_kwargs={"project_id": project_id},
+ inject=inject,
+ params={"release_stage_name": stage},
+ )
+ for stage in project.get("release_stages") or []
+ ]
+
+
+def _pivot_parents(
+ session: requests.Session,
+ headers: dict[str, str],
+ config: BugsnagEndpointConfig,
+ project: dict[str, Any],
+ inject: dict[str, str],
+ logger: FilteringBoundLogger,
+) -> list[_FanOutParent]:
+ project_id = project["id"]
+ return [
+ _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},
+ )
+ for display_id in _project_pivot_display_ids(session, headers, project_id, logger)
+ ]
+
+
+def _error_parents(
+ session: requests.Session,
+ headers: dict[str, str],
+ config: BugsnagEndpointConfig,
+ project: dict[str, Any],
+ inject: dict[str, str],
+ logger: FilteringBoundLogger,
+) -> list[_FanOutParent]:
+ project_id = project["id"]
+ return [
+ _FanOutParent(
+ resume_id=f"{project_id}:{error_id}",
+ path_kwargs={"project_id": project_id, "error_id": error_id},
+ inject={**inject, "error_id": error_id},
+ )
+ for error_id in _project_error_ids(session, headers, config, project_id, logger)
+ ]
+
+
+def _error_pivot_parents(
+ session: requests.Session,
+ headers: dict[str, str],
+ config: BugsnagEndpointConfig,
+ project: dict[str, Any],
+ inject: dict[str, str],
+ logger: FilteringBoundLogger,
+) -> list[_FanOutParent]:
+ project_id = project["id"]
+ display_ids = _project_pivot_display_ids(session, headers, project_id, logger)
+ return [
+ _FanOutParent(
+ resume_id=f"{project_id}:{error_id}:{display_id}",
+ path_kwargs={
+ "project_id": project_id,
+ "error_id": error_id,
+ "event_field_display_id": display_id,
+ },
+ inject={**inject, "error_id": error_id, "event_field_display_id": display_id},
+ )
+ for error_id in _project_error_ids(session, headers, config, project_id, logger)
+ for display_id in display_ids
+ ]
+
+
+def _span_group_parents(
+ session: requests.Session,
+ headers: dict[str, str],
+ config: BugsnagEndpointConfig,
+ project: dict[str, Any],
+ inject: dict[str, str],
+ logger: FilteringBoundLogger,
+) -> list[_FanOutParent]:
+ project_id = project["id"]
+ return [
+ _FanOutParent(
+ resume_id=f"{project_id}:{span_group_id}",
+ # A span group id is `{version}.{category}.{name}`, and the name can carry slashes
+ # (`AppStart/Cold`), so it has to be escaped into the path.
+ path_kwargs={"project_id": project_id, "span_group_id": quote(span_group_id, safe="")},
+ inject={**inject, "span_group_id": span_group_id},
+ )
+ for span_group_id in _project_span_group_ids(session, headers, config, project_id, logger)
+ ]
+
+
+# Builders for the scopes that turn one project into several fan-out parents. Every builder takes
+# the same arguments so the scope can be dispatched rather than branched on.
+_PROJECT_PARENT_BUILDERS: dict[
+ BugsnagScope,
+ Callable[
+ [requests.Session, dict[str, str], BugsnagEndpointConfig, dict[str, Any], dict[str, str], FilteringBoundLogger],
+ list[_FanOutParent],
+ ],
+] = {
+ BugsnagScope.PER_PROJECT_RELEASE_STAGE: _release_stage_parents,
+ BugsnagScope.PER_PROJECT_PIVOT: _pivot_parents,
+ BugsnagScope.PER_PROJECT_ERROR: _error_parents,
+ BugsnagScope.PER_PROJECT_ERROR_PIVOT: _error_pivot_parents,
+ BugsnagScope.PER_PROJECT_SPAN_GROUP: _span_group_parents,
+}
+
+
def _resolve_parents(
session: requests.Session, headers: dict[str, str], config: BugsnagEndpointConfig, logger: FilteringBoundLogger
) -> list[_FanOutParent]:
@@ -237,30 +483,8 @@ def _resolve_parents(
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},
- )
- )
+ build_parents = _PROJECT_PARENT_BUILDERS[config.scope]
+ project_parents = build_parents(session, headers, config, project, inject, logger)
cap = config.max_parents_per_project
if cap is not None and len(project_parents) > cap:
@@ -293,7 +517,15 @@ def _iter_top_level(
first_page = True
while True:
- items, next_url = _fetch_list_page_or_stop(session, url, headers, logger, is_first_page=first_page)
+ items, next_url = _fetch_list_page_or_stop(
+ session,
+ url,
+ headers,
+ logger,
+ is_first_page=first_page,
+ tolerated_statuses=config.missing_data_statuses,
+ paginate_by_offset=config.paginate_by_offset,
+ )
first_page = False
# 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
@@ -355,7 +587,15 @@ def _iter_fan_out(
page_count = 0
while True:
- items, next_url = _fetch_list_page_or_stop(session, url, headers, logger, is_first_page=page_count == 0)
+ items, next_url = _fetch_list_page_or_stop(
+ session,
+ url,
+ headers,
+ logger,
+ is_first_page=page_count == 0,
+ tolerated_statuses=config.missing_data_statuses,
+ paginate_by_offset=config.paginate_by_offset,
+ )
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
diff --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.py
index 9abf1df1d5b2..860e734d8089 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
@@ -166,6 +166,73 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"fields": "Additional event field values describing this pivot value, e.g. the name and email behind a user id.",
},
},
+ "error_trend": {
+ "description": "Event occurrences for a single error bucketed over time, one row per error per bucket. Buckets span 12 hours. Covers a capped number of each project's most recently seen errors.",
+ "docs_url": "https://bugsnagapiv2.docs.apiary.io/#reference/errors/trends",
+ "columns": {
+ "project_id": "Identifier of the project the error belongs to (injected by the connector).",
+ "organization_id": "Identifier of the organization that owns the project (injected by the connector).",
+ "error_id": "Identifier of the error the trend describes (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 of this error that occurred in the bucket.",
+ },
+ },
+ "error_pivot_values": {
+ "description": "The individual values behind each pivot for a single error: the release stages, app versions, users or other event-field values that error's events break down by. Covers a capped number of each project's most recently seen errors.",
+ "docs_url": "https://bugsnagapiv2.docs.apiary.io/#reference/errors/pivots",
+ "columns": {
+ "project_id": "Identifier of the project the error belongs to (injected by the connector).",
+ "organization_id": "Identifier of the organization that owns the project (injected by the connector).",
+ "error_id": "Identifier of the error the breakdown is scoped to (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 this error's events that had this value for the event field.",
+ "proportion": "Proportion of the error's matching events represented by this value.",
+ "first_seen": "First event occurrence of this error with this value.",
+ "last_seen": "Most recent event occurrence of this error with this value.",
+ "fields": "Additional event field values describing this pivot value, e.g. the name and email behind a user id.",
+ },
+ },
+ "span_groups": {
+ "description": "A BugSnag Performance span group: the spans for one operation, such as an app start, a screen or page load, a network request or a custom timing, aggregated with its duration percentiles and span counts.",
+ "docs_url": "https://bugsnagapiv2.docs.apiary.io/#reference/span-groups",
+ "columns": {
+ "id": "Identifier of the span group, formed from its version, category and name.",
+ "project_id": "Identifier of the project the span group belongs to (injected by the connector).",
+ "organization_id": "Identifier of the organization that owns the project (injected by the connector).",
+ "category": "Performance category of the span group, e.g. app_start, page_load, network.",
+ "name": "Name of the span group.",
+ "display_name": "Name of the span group as shown in the BugSnag dashboard.",
+ "is_starred": "Whether the account behind the auth token has starred this span group.",
+ "statistics": "Aggregated statistics for the group's spans: duration percentiles, span counts, last-seen time, and any category, rendering, system-metric and HTTP statistics.",
+ "performance_target": "The performance target configured for this span group, if any.",
+ },
+ },
+ "span_group_spans": {
+ "description": "An individual BugSnag Performance span, which is one timed operation in one trace, under its span group. BugSnag serves only the most recent page of spans per group, so this table is a sample of recent spans rather than the full history.",
+ "docs_url": "https://bugsnagapiv2.docs.apiary.io/#reference/span-groups",
+ "columns": {
+ "id": "Identifier of the span.",
+ "project_id": "Identifier of the project the span belongs to (injected by the connector).",
+ "organization_id": "Identifier of the organization that owns the project (injected by the connector).",
+ "span_group_id": "Identifier of the span group the span was read under (injected by the connector).",
+ "parent_span_id": "Identifier of the span's parent span, if it has one.",
+ "trace_id": "Identifier of the trace the span belongs to.",
+ "category": "Performance category of the span, e.g. app_start, page_load, network.",
+ "name": "Name of the span.",
+ "display_name": "Name of the span as shown in the BugSnag dashboard.",
+ "duration": "Duration of the span in milliseconds.",
+ "timestamp": "Timestamp BugSnag attributes the span to.",
+ "start_time": "Time the span started.",
+ "time_adjustment_type": "How the span's time was adjusted: adjusted, device, received or unadjusted.",
+ "is_first_class": "Whether the span is a first-class span rather than a sub-span.",
+ "build_id": "Identifier of the build the span is associated with.",
+ "virtual_span_group_id": "Identifier of the page load span group the span belongs to, if any.",
+ "statistics": "Measurements recorded while the span was active: category statistics such as web vitals, system metrics, rendering statistics and HTTP response code.",
+ "metadata": "Additional metadata attributes attached to the span.",
+ },
+ },
"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.py
index dc24af2f0147..594911e30a11 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
@@ -26,6 +26,14 @@ class BugsnagScope(Enum):
# 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"
+ # Fan out over every (project, error) pair. Error-grain endpoints cost one request per error and
+ # BugSnag offers no filter to narrow the error list, so the fan-out is capped.
+ PER_PROJECT_ERROR = "per_project_error"
+ # Fan out over every (project, error, pivot) triple, for the error-grain breakdown endpoints.
+ PER_PROJECT_ERROR_PIVOT = "per_project_error_pivot"
+ # Fan out over every (project, span group) pair, where the span groups are the ones the
+ # `span_groups` endpoint lists for that project.
+ PER_PROJECT_SPAN_GROUP = "per_project_span_group"
@dataclass(frozen=True)
@@ -54,6 +62,10 @@ class BugsnagEndpointConfig:
# 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, ...] = ()
+ # Whether the endpoint pages by a numeric row `offset` instead of the Link header. The
+ # performance (span) endpoints send no Link header, so a short page is the only end-of-data
+ # signal there.
+ paginate_by_offset: bool = False
# 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
@@ -61,6 +73,10 @@ class BugsnagEndpointConfig:
# 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
+ # Cap on how many of a project's errors an error-grain endpoint fans out over, taken from the
+ # most recently seen end of the error list. Separate from `max_parents_per_project` so an
+ # endpoint that crosses errors with a second dimension can bound each independently.
+ max_errors_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.
@@ -145,6 +161,25 @@ BUGSNAG_ENDPOINTS: dict[str, BugsnagEndpointConfig] = {
primary_keys=["display_id", "project_id"],
should_sync_default=False,
),
+ # The same breakdown values as `pivot_values`, narrowed to one error, which answers "which
+ # users did this error affect". Every (error, pivot) pair is its own request, so both dimensions
+ # are capped and the table is off by default.
+ "error_pivot_values": BugsnagEndpointConfig(
+ name="error_pivot_values",
+ scope=BugsnagScope.PER_PROJECT_ERROR_PIVOT,
+ path="/projects/{project_id}/errors/{error_id}/pivots/{event_field_display_id}/values",
+ primary_keys=["project_id", "error_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"},
+ # An error deleted or merged away between listing and fan-out answers 404.
+ missing_data_statuses=(404,),
+ max_pages=100,
+ max_errors_per_project=10,
+ max_parents_per_project=100,
+ should_sync_default=False,
+ ),
"saved_searches": BugsnagEndpointConfig(
name="saved_searches",
scope=BugsnagScope.PER_PROJECT,
@@ -175,6 +210,22 @@ BUGSNAG_ENDPOINTS: dict[str, BugsnagEndpointConfig] = {
page_size=None,
params={"resolution": "12h"},
),
+ # The same bucketed counts as `trend`, but per error rather than per project. Error grain costs
+ # one request per error and the endpoint takes no time filter, so the fan-out is capped at the
+ # project's most recently seen errors and the table is off by default.
+ "error_trend": BugsnagEndpointConfig(
+ name="error_trend",
+ scope=BugsnagScope.PER_PROJECT_ERROR,
+ path="/projects/{project_id}/errors/{error_id}/trend",
+ primary_keys=["project_id", "error_id", "from"],
+ partition_key="from",
+ page_size=None,
+ params={"resolution": "12h"},
+ # An error deleted or merged away between listing and fan-out answers 404.
+ missing_data_statuses=(404,),
+ max_errors_per_project=25,
+ should_sync_default=False,
+ ),
"release_groups": BugsnagEndpointConfig(
name="release_groups",
scope=BugsnagScope.PER_PROJECT_RELEASE_STAGE,
@@ -200,6 +251,37 @@ BUGSNAG_ENDPOINTS: dict[str, BugsnagEndpointConfig] = {
max_parents_per_project=25,
should_sync_default=False,
),
+ # BugSnag Performance aggregates: one row per operation (app start, page load, network request,
+ # custom timing) with its duration percentiles and span counts. Sorted by name so the offset
+ # cursor stays put while a sync walks it, because the ranking sorts shift as spans arrive.
+ "span_groups": BugsnagEndpointConfig(
+ name="span_groups",
+ scope=BugsnagScope.PER_PROJECT,
+ path="/projects/{project_id}/span_groups",
+ primary_keys=["id", "project_id"],
+ params={"sort": "name", "direction": "asc"},
+ # Projects without BugSnag Performance have no span groups to list.
+ missing_data_statuses=(404,),
+ paginate_by_offset=True,
+ max_pages=100,
+ ),
+ # Individual spans under each span group, the event grain of BugSnag Performance. The endpoint
+ # takes no offset or cursor, so one request per span group returns the most recent page and
+ # nothing more. The table is a recent-spans sample rather than the full history, and is off by
+ # default because it still costs a request per group.
+ "span_group_spans": BugsnagEndpointConfig(
+ name="span_group_spans",
+ scope=BugsnagScope.PER_PROJECT_SPAN_GROUP,
+ path="/projects/{project_id}/span_groups/{span_group_id}/spans",
+ primary_keys=["project_id", "span_group_id", "id"],
+ partition_key="timestamp",
+ params={"sort": "timestamp", "direction": "desc"},
+ # Projects without BugSnag Performance have no spans to list.
+ missing_data_statuses=(404,),
+ max_pages=1,
+ max_parents_per_project=50,
+ 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.py
index 23dd2d44939b..b7afe5110fdc 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
@@ -101,6 +101,21 @@ You can generate a personal auth token in the **My Account** section of your [Bu
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."
+ if endpoint == "error_trend":
+ return (
+ "Event counts over time for each error, in 12-hour buckets. Covers each project's 25 most "
+ "recently seen errors. Off by default because it makes one request per error."
+ )
+ if endpoint == "error_pivot_values":
+ return (
+ "One row per pivot value for each error. Covers each project's 10 most recently seen "
+ "errors. Off by default because it makes one request for every error and pivot."
+ )
+ if endpoint == "span_group_spans":
+ return (
+ "Individual spans under each span group. BugSnag serves only the most recent page per "
+ "group, so this is a sample of recent spans rather than the full history. Off by default."
+ )
return None
def _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.py
index 5e8cc1eeec72..9e1b1751a466 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
@@ -18,6 +18,7 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.bugsnag.bu
BugsnagRetryableError,
_build_url,
_get_headers,
+ _next_offset_url,
_parse_next_url,
get_rows,
validate_credentials,
@@ -71,7 +72,9 @@ def _collect_objects(
"""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]:
+ def fake_fetch_list_page(
+ session: Any, url: str, headers: Any, logger: Any, **kwargs: Any
+ ) -> tuple[list[dict], str | None]:
if url not in pages:
raise AssertionError(f"unexpected URL requested: {url}")
return pages[url]
@@ -105,7 +108,9 @@ def _collect(
) -> 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]:
+ def fake_fetch_list_page(
+ session: Any, url: str, headers: Any, logger: Any, **kwargs: Any
+ ) -> tuple[list[dict], str | None]:
if url not in pages:
raise AssertionError(f"unexpected URL requested: {url}")
return pages[url]
@@ -123,6 +128,43 @@ def _collect(
return rows
+def _collect_via_responses(
+ endpoint: str,
+ responses: Mapping[str, requests.Response],
+ manager: _FakeResumableManager,
+ monkeypatch: Any,
+) -> tuple[list[dict], list[str]]:
+ """Collect rows with only the HTTP layer faked, so pagination runs for real.
+
+ Returns (rows, requested_urls); the URL list is what proves the offset cursor and the escaped
+ span group id in the path."""
+ monkeypatch.setattr(bugsnag, "make_tracked_session", lambda *args, **kwargs: MagicMock())
+ requested: list[str] = []
+
+ def fake_fetch_page(
+ session: Any, url: str, headers: Any, logger: Any, tolerated_statuses: tuple[int, ...] = ()
+ ) -> requests.Response:
+ requested.append(url)
+ if url not in responses:
+ raise AssertionError(f"unexpected URL requested: {url}")
+ response = responses[url]
+ if not response.ok and response.status_code not in tolerated_statuses:
+ raise requests.HTTPError(response=response)
+ return response
+
+ 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, requested
+
+
class TestParseNextUrl:
@parameterized.expand(
[
@@ -144,6 +186,32 @@ class TestParseNextUrl:
assert _parse_next_url(header) == expected
+class TestNextOffsetUrl:
+ """The performance endpoints send no Link header, so the cursor is derived from the URL."""
+
+ @parameterized.expand(
+ [
+ (
+ "full_page_advances_offset",
+ "https://api.bugsnag.com/projects/p1/span_groups?per_page=2&sort=name",
+ 2,
+ "https://api.bugsnag.com/projects/p1/span_groups?per_page=2&sort=name&offset=2",
+ ),
+ (
+ "existing_offset_accumulates",
+ "https://api.bugsnag.com/projects/p1/span_groups?per_page=2&offset=4",
+ 2,
+ "https://api.bugsnag.com/projects/p1/span_groups?per_page=2&offset=6",
+ ),
+ ("short_page_is_terminal", "https://api.bugsnag.com/projects/p1/span_groups?per_page=2", 1, None),
+ ("empty_page_is_terminal", "https://api.bugsnag.com/projects/p1/span_groups?per_page=2", 0, None),
+ ("no_per_page_means_unpaginated", "https://api.bugsnag.com/projects/p1/span_groups", 5, None),
+ ]
+ )
+ def test_next_offset_url(self, _name: str, url: str, page_len: int, expected: str | None) -> None:
+ assert _next_offset_url(url, page_len) == expected
+
+
class TestHelpers:
def test_get_headers_sets_token_and_version(self) -> None:
headers = _get_headers("tok_123")
@@ -316,7 +384,9 @@ class TestPerProjectFanOut:
# tuple — used to drive the graceful-stop-on-422 pagination path.
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]:
+ def fake_fetch_list_page(
+ session: Any, url: str, headers: Any, logger: Any, **kwargs: Any
+ ) -> tuple[list[dict], str | None]:
if url not in pages:
raise AssertionError(f"unexpected URL requested: {url}")
page = pages[url]
@@ -624,3 +694,220 @@ class TestPivotValues:
rows = _collect("pivot_values", pages, _FakeResumableManager(), monkeypatch)
assert [row["event_field_value"] for row in rows] == ["v1", "v2"]
+
+
+class TestErrorTrend:
+ def _error_pages(self, errors: list[dict], per_page: int) -> dict[str, tuple[list[dict], str | None]]:
+ return {
+ _ORGS_URL: ([{"id": "o1"}], None),
+ _PROJECTS_URL: ([{"id": "p1"}], None),
+ f"https://api.bugsnag.com/projects/p1/errors?per_page={per_page}": (errors, None),
+ }
+
+ def test_fans_out_per_error_injecting_the_error_id(self, monkeypatch: Any) -> None:
+ # The error id only exists in the request path, so without injection every error's buckets
+ # would collapse onto the same primary key.
+ capped = dataclasses.replace(BUGSNAG_ENDPOINTS["error_trend"], max_errors_per_project=2)
+ monkeypatch.setitem(BUGSNAG_ENDPOINTS, "error_trend", capped)
+ pages = self._error_pages([{"id": "e1"}, {"id": "e2"}], per_page=3)
+ bucket = {"from": "2017-04-03T22:43:49Z", "to": "2017-04-04T10:43:49Z", "events_count": 3}
+ for error_id in ("e1", "e2"):
+ pages[f"https://api.bugsnag.com/projects/p1/errors/{error_id}/trend?resolution=12h"] = ([bucket], None)
+
+ rows = _collect("error_trend", pages, _FakeResumableManager(), monkeypatch)
+ assert rows == [
+ {**bucket, "organization_id": "o1", "project_id": "p1", "error_id": "e1"},
+ {**bucket, "organization_id": "o1", "project_id": "p1", "error_id": "e2"},
+ ]
+
+ def test_error_count_is_capped_per_project(self, monkeypatch: Any) -> None:
+ # One request per error with no server-side filter to narrow the list, so the cap is the
+ # only thing bounding the table. The third error's trend URL is absent from `pages`, so
+ # fanning out over it would raise.
+ capped = dataclasses.replace(BUGSNAG_ENDPOINTS["error_trend"], max_errors_per_project=2)
+ monkeypatch.setitem(BUGSNAG_ENDPOINTS, "error_trend", capped)
+ pages = self._error_pages([{"id": "e1"}, {"id": "e2"}, {"id": "e3"}], per_page=3)
+ for error_id in ("e1", "e2"):
+ pages[f"https://api.bugsnag.com/projects/p1/errors/{error_id}/trend?resolution=12h"] = (
+ [{"from": "2017-04-03T22:43:49Z", "events_count": 1}],
+ None,
+ )
+
+ rows = _collect("error_trend", pages, _FakeResumableManager(), monkeypatch)
+ assert [row["error_id"] for row in rows] == ["e1", "e2"]
+
+ def test_error_deleted_between_listing_and_fan_out_is_skipped(self, monkeypatch: Any) -> None:
+ # A long sync can reach an error that was merged or deleted after the listing; its 404 must
+ # produce no rows rather than fail the whole table.
+ capped = dataclasses.replace(BUGSNAG_ENDPOINTS["error_trend"], max_errors_per_project=2)
+ monkeypatch.setitem(BUGSNAG_ENDPOINTS, "error_trend", capped)
+ responses = {
+ _ORGS_URL: _make_response(200, body=[{"id": "o1"}]),
+ _PROJECTS_URL: _make_response(200, body=[{"id": "p1"}]),
+ "https://api.bugsnag.com/projects/p1/errors?per_page=3": _make_response(
+ 200, body=[{"id": "e1"}, {"id": "e2"}]
+ ),
+ "https://api.bugsnag.com/projects/p1/errors/e1/trend?resolution=12h": _make_response(
+ 404, body={"errors": ["Error not found"]}
+ ),
+ "https://api.bugsnag.com/projects/p1/errors/e2/trend?resolution=12h": _make_response(
+ 200, body=[{"from": "2017-04-03T22:43:49Z", "events_count": 1}]
+ ),
+ }
+ rows, _requested = _collect_via_responses("error_trend", responses, _FakeResumableManager(), monkeypatch)
+ assert [row["error_id"] for row in rows] == ["e2"]
+
+
+class TestErrorPivotValues:
+ def _pages(self, errors: list[dict], per_page: int) -> 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"}, {"event_field_display_id": "user.id"}],
+ None,
+ ),
+ f"https://api.bugsnag.com/projects/p1/errors?per_page={per_page}": (errors, None),
+ }
+
+ def _values_url(self, error_id: str, display_id: str) -> str:
+ return (
+ f"https://api.bugsnag.com/projects/p1/errors/{error_id}/pivots/{display_id}"
+ "/values?per_page=30&sort=unsorted"
+ )
+
+ def test_crosses_errors_with_pivots_and_injects_both_ids(self, monkeypatch: Any) -> None:
+ capped = dataclasses.replace(BUGSNAG_ENDPOINTS["error_pivot_values"], max_errors_per_project=1)
+ monkeypatch.setitem(BUGSNAG_ENDPOINTS, "error_pivot_values", capped)
+ pages = self._pages([{"id": "e1"}], per_page=2)
+ for display_id in ("app.release_stage", "user.id"):
+ pages[self._values_url("e1", display_id)] = ([{"event_field_value": "production"}], None)
+
+ rows = _collect("error_pivot_values", pages, _FakeResumableManager(), monkeypatch)
+ assert rows == [
+ {
+ "event_field_value": "production",
+ "organization_id": "o1",
+ "project_id": "p1",
+ "error_id": "e1",
+ "event_field_display_id": "app.release_stage",
+ },
+ {
+ "event_field_value": "production",
+ "organization_id": "o1",
+ "project_id": "p1",
+ "error_id": "e1",
+ "event_field_display_id": "user.id",
+ },
+ ]
+
+ def test_error_pivot_product_is_capped_per_project(self, monkeypatch: Any) -> None:
+ # Every (error, pivot) pair is its own paginated request, so the product needs a cap of its
+ # own on top of the error cap. The fourth pair's URL is absent from `pages`, so requesting
+ # it would raise.
+ capped = dataclasses.replace(
+ BUGSNAG_ENDPOINTS["error_pivot_values"], max_errors_per_project=2, max_parents_per_project=3
+ )
+ monkeypatch.setitem(BUGSNAG_ENDPOINTS, "error_pivot_values", capped)
+ pages = self._pages([{"id": "e1"}, {"id": "e2"}], per_page=3)
+ for error_id, display_id in (("e1", "app.release_stage"), ("e1", "user.id"), ("e2", "app.release_stage")):
+ pages[self._values_url(error_id, display_id)] = ([{"event_field_value": f"{error_id}:{display_id}"}], None)
+
+ rows = _collect("error_pivot_values", pages, _FakeResumableManager(), monkeypatch)
+ assert [row["event_field_value"] for row in rows] == [
+ "e1:app.release_stage",
+ "e1:user.id",
+ "e2:app.release_stage",
+ ]
+
+
+class TestSpanGroups:
+ """The performance endpoints page by a numeric offset and send no Link header, so these tests
+ fake only the HTTP layer and let the real paginator derive its own cursors."""
+
+ def test_follows_the_offset_cursor_until_a_short_page(self, monkeypatch: Any) -> None:
+ paged = dataclasses.replace(BUGSNAG_ENDPOINTS["span_groups"], page_size=2)
+ monkeypatch.setitem(BUGSNAG_ENDPOINTS, "span_groups", paged)
+ page1 = "https://api.bugsnag.com/projects/p1/span_groups?per_page=2&sort=name&direction=asc"
+ page2 = f"{page1}&offset=2"
+ responses = {
+ _ORGS_URL: _make_response(200, body=[{"id": "o1"}]),
+ _PROJECTS_URL: _make_response(200, body=[{"id": "p1"}]),
+ page1: _make_response(200, body=[{"id": "1.app_start.Cold"}, {"id": "1.network.GET"}]),
+ page2: _make_response(200, body=[{"id": "1.page_load./home"}]),
+ }
+ rows, requested = _collect_via_responses("span_groups", responses, _FakeResumableManager(), monkeypatch)
+ assert [row["id"] for row in rows] == ["1.app_start.Cold", "1.network.GET", "1.page_load./home"]
+ assert requested[-2:] == [page1, page2]
+
+
+class TestSpanGroupSpans:
+ def test_escapes_the_span_group_id_into_the_path_and_injects_the_raw_id(self, monkeypatch: Any) -> None:
+ # A span group id is `{version}.{category}.{name}` and the name can carry slashes, so an
+ # unescaped id would address a different route entirely. The row keeps the raw id, which is
+ # what joins these spans back to the span_groups table.
+ group_id = "1.app_start.AppStart/Cold"
+ spans_url = (
+ "https://api.bugsnag.com/projects/p1/span_groups/1.app_start.AppStart%2FCold"
+ "/spans?per_page=100&sort=timestamp&direction=desc"
+ )
+ responses = {
+ _ORGS_URL: _make_response(200, body=[{"id": "o1"}]),
+ _PROJECTS_URL: _make_response(200, body=[{"id": "p1"}]),
+ "https://api.bugsnag.com/projects/p1/span_groups?per_page=100&sort=name&direction=asc": _make_response(
+ 200, body=[{"id": group_id}]
+ ),
+ spans_url: _make_response(200, body=[{"id": "s1", "duration": 1000}]),
+ }
+ rows, requested = _collect_via_responses("span_group_spans", responses, _FakeResumableManager(), monkeypatch)
+ assert rows == [
+ {
+ "id": "s1",
+ "duration": 1000,
+ "organization_id": "o1",
+ "project_id": "p1",
+ "span_group_id": group_id,
+ }
+ ]
+ assert spans_url in requested
+
+ def test_span_group_count_is_capped_per_project(self, monkeypatch: Any) -> None:
+ # Each span group costs a request, and a project accumulates one per grouped operation. The
+ # second group's spans URL is absent from `responses`, so fanning out over it would raise.
+ capped = dataclasses.replace(BUGSNAG_ENDPOINTS["span_group_spans"], max_parents_per_project=1)
+ monkeypatch.setitem(BUGSNAG_ENDPOINTS, "span_group_spans", capped)
+ responses = {
+ _ORGS_URL: _make_response(200, body=[{"id": "o1"}]),
+ _PROJECTS_URL: _make_response(200, body=[{"id": "p1"}]),
+ "https://api.bugsnag.com/projects/p1/span_groups?per_page=100&sort=name&direction=asc": _make_response(
+ 200, body=[{"id": "1.app_start.Cold"}, {"id": "1.network.GET"}]
+ ),
+ (
+ "https://api.bugsnag.com/projects/p1/span_groups/1.app_start.Cold"
+ "/spans?per_page=100&sort=timestamp&direction=desc"
+ ): _make_response(200, body=[{"id": "s1"}]),
+ }
+ rows, _requested = _collect_via_responses("span_group_spans", responses, _FakeResumableManager(), monkeypatch)
+ assert [row["span_group_id"] for row in rows] == ["1.app_start.Cold"]
+
+ def test_project_without_performance_contributes_no_parents(self, monkeypatch: Any) -> None:
+ # A project that never enabled BugSnag Performance answers on the span group listing, which
+ # is the parent enumeration rather than the child path. The 404 must leave that project with
+ # no parents instead of failing the whole table for every other project.
+ spans_url = (
+ "https://api.bugsnag.com/projects/p2/span_groups/1.app_start.Cold"
+ "/spans?per_page=100&sort=timestamp&direction=desc"
+ )
+ responses = {
+ _ORGS_URL: _make_response(200, body=[{"id": "o1"}]),
+ _PROJECTS_URL: _make_response(200, body=[{"id": "p1"}, {"id": "p2"}], link=None),
+ "https://api.bugsnag.com/projects/p1/span_groups?per_page=100&sort=name&direction=asc": _make_response(
+ 404, body={"errors": ["Project not found"]}
+ ),
+ "https://api.bugsnag.com/projects/p2/span_groups?per_page=100&sort=name&direction=asc": _make_response(
+ 200, body=[{"id": "1.app_start.Cold"}]
+ ),
+ spans_url: _make_response(200, body=[{"id": "s1"}]),
+ }
+ rows, _requested = _collect_via_responses("span_group_spans", responses, _FakeResumableManager(), monkeypatch)
+ assert [row["project_id"] for row in rows] == ["p2"]
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.py
index 77834e22a211..4f8e97b26d10 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
@@ -80,6 +80,10 @@ class TestBugsnagSource:
("trend", True),
("release_groups", True),
("pivot_values", False),
+ ("error_trend", False),
+ ("error_pivot_values", False),
+ ("span_groups", True),
+ ("span_group_spans", False),
]
)
def test_should_sync_default(self, endpoint: str, expected_default: bool) -> None:
@@ -121,6 +125,10 @@ class TestBugsnagSource:
("trend", ["project_id", "from"]),
("release_groups", ["id", "project_id"]),
("pivot_values", ["project_id", "event_field_display_id", "event_field_value"]),
+ ("error_trend", ["project_id", "error_id", "from"]),
+ ("error_pivot_values", ["project_id", "error_id", "event_field_display_id", "event_field_value"]),
+ ("span_groups", ["id", "project_id"]),
+ ("span_group_spans", ["project_id", "span_group_id", "id"]),
]
)
def test_source_response_primary_keys(self, endpoint: str, expected_keys: list[str]) -> None:
@@ -138,6 +146,9 @@ class TestBugsnagSource:
BugsnagScope.PER_PROJECT,
BugsnagScope.PER_PROJECT_RELEASE_STAGE,
BugsnagScope.PER_PROJECT_PIVOT,
+ BugsnagScope.PER_PROJECT_ERROR,
+ BugsnagScope.PER_PROJECT_ERROR_PIVOT,
+ BugsnagScope.PER_PROJECT_SPAN_GROUP,
}
for config in BUGSNAG_ENDPOINTS.values():
if config.scope is BugsnagScope.PER_ORG:
@@ -182,3 +193,12 @@ class TestBugsnagSource:
# 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))
+
+ def test_error_grain_endpoints_bound_their_error_fan_out(self) -> None:
+ # Error-grain endpoints cost one request per error and BugSnag exposes no filter to narrow
+ # the error list, so an uncapped one would walk every error a project has ever recorded.
+ error_scopes = {BugsnagScope.PER_PROJECT_ERROR, BugsnagScope.PER_PROJECT_ERROR_PIVOT}
+ error_grain = [c for c in BUGSNAG_ENDPOINTS.values() if c.scope in error_scopes]
+ assert error_grain
+ for config in error_grain:
+ assert config.max_errors_per_project is not None, config.name