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.

fix(bugsnag): stop errors sync crashing at pagination ceiling (#94579)

Tom Owersce8127487c9b
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 709accb7801b..9e5d0f235c10 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
@@ -122,6 +122,26 @@ def _fetch_list_page(
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
+) -> tuple[list[dict[str, Any]], str | None]:
+ """Like `_fetch_list_page`, but ends pagination gracefully at BugSnag's depth ceiling.
+
+ BugSnag's deep list endpoints (errors, events) cap how far pagination can go, yet still emit a
+ `next` cursor in the Link header past that ceiling and then reject the very cursor they gave us
+ with a 422. That's deterministic — retrying never clears it — so on a follow-up page we treat
+ 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)
+ except requests.HTTPError as e:
+ response = e.response
+ if not is_first_page and response is not None and response.status_code == 422:
+ logger.warning("BugSnag pagination ceiling reached; stopping this collection early")
+ return [], None
+ raise
+
+
def _iter_all_pages(
session: requests.Session, url: str, headers: dict[str, str], logger: FilteringBoundLogger
) -> Iterator[dict[str, Any]]:
@@ -187,8 +207,10 @@ def _iter_top_level(
else:
url = _build_url(f"{BUGSNAG_BASE_URL}{config.path}", {"per_page": config.page_size})
+ first_page = True
while True:
- items, next_url = _fetch_list_page(session, url, headers, logger)
+ items, next_url = _fetch_list_page_or_stop(session, url, headers, logger, is_first_page=first_page)
+ 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
# already-yielded ones) rather than skip ahead and drop the items still in the batcher.
@@ -238,8 +260,10 @@ def _iter_fan_out(
url = resume_url or _build_url(f"{BUGSNAG_BASE_URL}{path}", {"per_page": config.page_size})
resume_url = None # only the resumed-into parent uses the saved URL; the rest start fresh
+ first_page = True
while True:
- items, next_url = _fetch_list_page(session, url, headers, logger)
+ items, next_url = _fetch_list_page_or_stop(session, url, headers, logger, is_first_page=first_page)
+ first_page = False
# 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
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 e117641a990d..9f4b679d6645 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
@@ -251,6 +251,67 @@ class TestPerProjectFanOut:
{"id": "e2", "organization_id": "o1", "project_id": "p2"},
]
+ def _collect_with_pages(
+ self,
+ endpoint: str,
+ pages: Mapping[str, tuple[list[dict], str | None] | Exception],
+ manager: _FakeResumableManager,
+ monkeypatch: Any,
+ ) -> list[dict]:
+ # Like `_collect`, but a page value may be an Exception to raise instead of a (items, next)
+ # 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]:
+ if url not in pages:
+ raise AssertionError(f"unexpected URL requested: {url}")
+ page = pages[url]
+ if isinstance(page, Exception):
+ raise page
+ return page
+
+ 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
+
+ def test_pagination_ceiling_422_stops_parent_and_continues(self, monkeypatch: Any) -> None:
+ # BugSnag advertises a `next` cursor past its depth ceiling, then 422s the very cursor it
+ # gave us. The sync must keep the rows already pulled from p1, stop that parent, and move on
+ # to p2 — rather than failing the whole errors sync.
+ p1_page2 = "https://api.bugsnag.com/projects/p1/errors?base=t&offset=500&per_page=100"
+ ceiling = requests.HTTPError(response=_make_response(422))
+ pages: dict[str, tuple[list[dict], str | None] | Exception] = {
+ "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"}], p1_page2),
+ p1_page2: ceiling,
+ "https://api.bugsnag.com/projects/p2/errors?per_page=100": ([{"id": "e2"}], None),
+ }
+ rows = self._collect_with_pages("errors", pages, _FakeResumableManager(), monkeypatch)
+ assert rows == [
+ {"id": "e1", "organization_id": "o1", "project_id": "p1"},
+ {"id": "e2", "organization_id": "o1", "project_id": "p2"},
+ ]
+
+ def test_pagination_ceiling_422_on_first_page_propagates(self, monkeypatch: Any) -> None:
+ # A 422 on a parent's first page isn't a cursor BugSnag handed us, so it must surface rather
+ # than silently yielding an empty table.
+ pages: dict[str, tuple[list[dict], str | None] | Exception] = {
+ "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": requests.HTTPError(response=_make_response(422)),
+ }
+ with pytest.raises(requests.HTTPError):
+ self._collect_with_pages("errors", pages, _FakeResumableManager(), monkeypatch)
+
def test_releases_caps_page_size_at_ten(self, monkeypatch: Any) -> None:
# The releases endpoint rejects per_page above 10 with a 400, so it must request per_page=10
# while the parent enumeration keeps the default 100. A per_page=100 releases URL is absent