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 debugbear rum, pages and annotation tables (#105181)

Tom Owers77291da3297f
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 f7847f2e8600..d4a576310e87 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
@@ -2329,20 +2329,20 @@ Note: Diffed against the vendor's own OpenAPI specs (openapi-v2.yaml, openapi-v3
## Debugbear — gaps
-Today (2): `PageMetrics`, `Projects`
+Today (6): `Annotations`, `PageMetrics`, `Pages`, `Projects`, `RumMetrics`, `RumPageViews`
Diffed against: <https://www.debugbear.com/docs/api>
-- [ ] `GET /api/v1/project/{projectId}/rumMetrics` — real-user Core Web Vitals aggregates — DebugBear's headline product, with nothing synced today (high)
-- [ ] `GET /api/v1/project/{projectId}/rumPageViews` — page-view-grain RUM data for slicing real-user performance by page, device and country (high)
-- [ ] `GET /api/v1/projects/{projectId}/pages` — lookup resolving the page IDs that every PageMetrics row is keyed on (URL, name, test settings) (high)
+- [x] `GET /api/v1/project/{projectId}/rumMetrics` — real-user Core Web Vitals aggregates — DebugBear's headline product, with nothing synced today (high) — added as `rum_metrics`, one row per metric per day (`groupByTime=day`)
+- [x] `GET /api/v1/project/{projectId}/rumPageViews` — page-view-grain RUM data for slicing real-user performance by page, device and country (high) — added as `rum_page_views`
+- [x] `GET /api/v1/projects/{projectId}/pages` — lookup resolving the page IDs that every PageMetrics row is keyed on (URL, name, test settings) (high) — added as `pages`. That path is documented for POST only; the readable representation of a page is the `pages` array on each project in `GET /api/v1/projects`, which is where the table reads from.
- [ ] `GET /api/v1/analysis/{analysisId}` — individual lab test results behind the aggregated page metrics, including test metadata and status (medium)
- [ ] `GET /api/v1/analysis/{analysisId}/requests` — request-level waterfall breakdown — which resources drive the page weight and load time (medium)
-- [ ] `GET /api/v1/project/{projectId}/annotations` — timeline annotations (deploy markers) needed to attribute metric changes to releases (medium)
+- [x] `GET /api/v1/project/{projectId}/annotations` — timeline annotations (deploy markers) needed to attribute metric changes to releases (medium) — added as `annotations`
- [ ] `GET /api/v1/analysis/{analysisId}/lhr` — full Lighthouse report per test, including audit-level scores (low)
- [ ] `GET /api/v1/project/{projectId}/quickTests` — one-off test results run outside monitored pages (low)
-Note: Enumerated all five API areas from the docs index (/docs/api) and extracted paths from each sub-page: projects-api, lab-test-api, quick-tests-api, rum-api, timeline-annotation-api. Twelve documented paths in total; the source syncs two. The RUM API being absent is the biggest miss since real-user monitoring is half the product.
+Note: Enumerated all five API areas from the docs index (/docs/api) and extracted paths from each sub-page: projects-api, lab-test-api, quick-tests-api, rum-api, timeline-annotation-api. Twelve documented paths in total; the source synced two when the sweep ran.
## Decagon — could not verify
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/debugbear/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/debugbear/canonical_descriptions.py
index 8b70ed25b197..f669eddf697c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/debugbear/canonical_descriptions.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/debugbear/canonical_descriptions.py
@@ -19,6 +19,22 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"pages": "The monitored pages configured within this project (id, name, url, region, test schedule, and device settings), as returned by the DebugBear API.",
},
},
+ "Pages": {
+ "description": "A monitored page inside a DebugBear project — the URL, its test schedule, and the device it is tested on.",
+ "docs_url": "https://www.debugbear.com/docs/lab-test-api",
+ "columns": {
+ "id": "Unique identifier for the monitored page. Matches `page_id` on PageMetrics rows.",
+ "name": "The page's display name.",
+ "url": "The URL that is tested.",
+ "region": "Server location the page is tested from.",
+ "testSchedules": "The schedules the page is tested on (id, name, days, and times), as returned by the DebugBear API.",
+ "device": "The simulated device the page is tested on (name, form factor, CPU throttling, and network settings).",
+ "advancedSettings": "Advanced test settings applied to the page, such as basic auth or custom headers.",
+ "tags": "Tags assigned to the page.",
+ "project_id": "Identifier of the DebugBear project the page belongs to.",
+ "project_name": "Display name of the DebugBear project the page belongs to.",
+ },
+ },
"PageMetrics": {
"description": (
"A single synthetic (Lighthouse-based) lab test result for a monitored page — "
@@ -50,4 +66,66 @@ CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
"crux_fid_p75": "Chrome UX Report field-data First Input Delay, 75th percentile (ms).",
},
},
+ "RumMetrics": {
+ "description": (
+ "Real user monitoring aggregates for a project, one row per metric per day. Values are "
+ "the 75th percentile by default and cover the page views recorded in that day."
+ ),
+ "docs_url": "https://www.debugbear.com/docs/rum-api",
+ "columns": {
+ "project_id": "Identifier of the DebugBear project the metric was aggregated for.",
+ "project_name": "Display name of the DebugBear project the metric was aggregated for.",
+ "metric": "The aggregated metric, for example lcp, cls, inp, fcp, or ttfb.",
+ "date": "Start of the day the aggregate covers.",
+ "value": "The aggregated metric value for the day.",
+ "count": "Number of page views included in the aggregate.",
+ "stat": "The statistic the value reports, for example p75.",
+ },
+ },
+ "RumPageViews": {
+ "description": "An individual real user page view, with the metric values, page, device, and location recorded for it.",
+ "docs_url": "https://www.debugbear.com/docs/rum-api",
+ "columns": {
+ "id": "Identifier PostHog derives from the page view's contents, because DebugBear returns no identifier for a page view.",
+ "project_id": "Identifier of the DebugBear project the page view was recorded for.",
+ "project_name": "Display name of the DebugBear project the page view was recorded for.",
+ "date": "Date and time the page view happened.",
+ "origin": "Origin of the page that was viewed.",
+ "domain": "Domain of the page that was viewed.",
+ "path": "URL path of the page that was viewed.",
+ "queryString": "Query string of the page that was viewed.",
+ "pageTitle": "Title of the page that was viewed.",
+ "country": "Country the page view came from.",
+ "device": "Device type the page view came from, for example desktop or mobile.",
+ "operatingSystem": "Operating system the page view came from.",
+ "devicePixelRatio": "Device pixel ratio of the viewing device.",
+ "windowWidth": "Browser window width in pixels.",
+ "windowHeight": "Browser window height in pixels.",
+ "ttfbValue": "Time to First Byte for this page view, in milliseconds.",
+ "fcp": "First Contentful Paint for this page view, in milliseconds.",
+ "lcpValue": "Largest Contentful Paint for this page view, in milliseconds.",
+ "lcpSelector": "CSS selector of the Largest Contentful Paint element.",
+ "lcpText": "Text content of the Largest Contentful Paint element.",
+ "lcpUrl": "URL of the Largest Contentful Paint resource, when it is an image.",
+ "clsScrollTop": "Scroll position when the largest layout shift happened.",
+ "inpValue": "Interaction to Next Paint for this page view, in milliseconds.",
+ "inpStartTime": "Time the measured interaction started, in milliseconds after page load.",
+ "inpSelector": "CSS selector of the element the measured interaction targeted.",
+ "inpText": "Text content of the element the measured interaction targeted.",
+ "inpEventName": "Name of the event behind the measured interaction, for example click.",
+ },
+ },
+ "Annotations": {
+ "description": "A timeline annotation marking an event, such as a release or a configuration change, on a project's performance charts.",
+ "docs_url": "https://www.debugbear.com/docs/timeline-annotation-api",
+ "columns": {
+ "id": "Unique identifier for the annotation.",
+ "title": "Short title shown on the chart.",
+ "description": "Longer description of the annotated event.",
+ "pageFilter": "Filter limiting the annotation to specific pages, for example `pageId:1234`. Empty when it applies to every page.",
+ "date": "Date and time the annotated event happened.",
+ "project_id": "Identifier of the DebugBear project the annotation belongs to.",
+ "project_name": "Display name of the DebugBear project the annotation belongs to.",
+ },
+ },
}
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/debugbear/debugbear.py b/products/warehouse_sources/backend/temporal/data_imports/sources/debugbear/debugbear.py
index 54c4f0b7b638..f894074ec091 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/debugbear/debugbear.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/debugbear/debugbear.py
@@ -1,8 +1,11 @@
+import hashlib
from collections.abc import Iterator
-from datetime import datetime
+from datetime import UTC, datetime, timedelta
from typing import Any, Optional
from urllib.parse import urlencode
+import orjson
+import structlog
from dateutil import parser as dateutil_parser
from requests import Session
from requests.exceptions import RequestException
@@ -12,7 +15,14 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.dat
)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse
-from products.warehouse_sources.backend.temporal.data_imports.sources.debugbear.settings import BEFORE_PARAM
+from products.warehouse_sources.backend.temporal.data_imports.sources.debugbear.settings import (
+ BEFORE_PARAM,
+ RUM_BACKFILL_DAYS,
+ RUM_GROUP_BY_TIME,
+ RUM_PAGE_VIEWS_PAGE_SIZE,
+)
+
+logger = structlog.get_logger(__name__)
BASE_URL = "https://www.debugbear.com/api/v1"
_REQUEST_TIMEOUT = 30
@@ -20,6 +30,8 @@ _REQUEST_TIMEOUT = 30
# with many builds landing on the same date could otherwise never make backward progress.
# Bound the walk defensively rather than looping forever.
_MAX_PAGES_PER_PROJECT = 500
+# `rumMetrics` returns one array per metric alongside an `info` object describing the query.
+_RUM_METRICS_INFO_KEY = "info"
def _auth_headers(api_key: str) -> dict[str, str]:
@@ -87,6 +99,27 @@ def _date_only(value: str) -> str | None:
return value[:10]
+def _iso(value: datetime) -> str:
+ return value.astimezone(UTC).strftime("%Y-%m-%dT%H:%M:%SZ")
+
+
+def _content_id(row: dict[str, Any]) -> str:
+ """Deterministic id for a record the API returns without one.
+
+ Identical payloads — the same record re-fetched across overlapping windows — collapse to
+ one row on merge, while any field difference yields a distinct key. Two genuinely
+ identical records collapse too, an accepted tradeoff versus unbounded duplication.
+ """
+ return hashlib.sha256(orjson.dumps(row, option=orjson.OPT_SORT_KEYS)).hexdigest()
+
+
+def _project_fields(project: dict[str, Any]) -> dict[str, Any] | None:
+ project_id = project.get("id")
+ if project_id is None:
+ return None
+ return {"project_id": str(project_id), "project_name": project.get("name")}
+
+
def _flatten_page_metrics_item(project: dict[str, Any], item: dict[str, Any]) -> dict[str, Any] | None:
"""Shape a `{page, metrics}` pageMetrics entry into a flat row.
@@ -171,6 +204,157 @@ def _iter_page_metrics_for_project(
before = next_before
+def _iter_pages(session: Session, headers: dict[str, str]) -> Iterator[dict[str, Any]]:
+ """Yield every monitored page, read from the pages nested in the projects listing.
+
+ DebugBear documents `/projects/{id}/pages` for creating a page only; the readable
+ representation of a page is the `pages` array each project carries.
+ """
+ for project in _iter_projects(session, headers):
+ project_fields = _project_fields(project)
+ if project_fields is None:
+ continue
+ raw_pages = project.get("pages")
+ if not isinstance(raw_pages, list):
+ continue
+ for page in raw_pages:
+ if not isinstance(page, dict) or page.get("id") is None:
+ continue
+ yield {**page, "id": str(page["id"]), **project_fields}
+
+
+def _flatten_rum_metrics(project_fields: dict[str, Any], payload: Any) -> Iterator[dict[str, Any]]:
+ """Turn the `{info, lcp: [...], cls: [...]}` rumMetrics body into one row per metric bucket."""
+ if not isinstance(payload, dict):
+ return
+ raw_info = payload.get(_RUM_METRICS_INFO_KEY)
+ info = raw_info if isinstance(raw_info, dict) else {}
+
+ for metric, series in payload.items():
+ if metric == _RUM_METRICS_INFO_KEY or not isinstance(series, list):
+ continue
+ for bucket in series:
+ if not isinstance(bucket, dict):
+ continue
+ date = bucket.get("date")
+ if not date:
+ continue
+ yield {
+ **project_fields,
+ "metric": metric,
+ "date": date,
+ "value": bucket.get("value"),
+ "count": bucket.get("count"),
+ "stat": info.get("stat"),
+ }
+
+
+def _iter_rum_metrics_for_project(
+ session: Session,
+ headers: dict[str, str],
+ project: dict[str, Any],
+ since: datetime | None,
+) -> Iterator[dict[str, Any]]:
+ project_fields = _project_fields(project)
+ if project_fields is None:
+ return
+
+ start = since or datetime.now(UTC) - timedelta(days=RUM_BACKFILL_DAYS)
+ params = {"groupByTime": RUM_GROUP_BY_TIME, "from": _iso(start)}
+ payload = _get_json(session, f"/project/{project['id']}/rumMetrics", headers, params=params)
+ yield from _flatten_rum_metrics(project_fields, payload)
+
+
+def _normalize_rum_page_view(project_fields: dict[str, Any], item: dict[str, Any]) -> dict[str, Any] | None:
+ if not item.get("date"):
+ return None
+ row = {**item, **project_fields}
+ # The endpoint returns no identifier for a page view, so key rows on their content.
+ row["id"] = _content_id(row)
+ return row
+
+
+def _iter_rum_page_views_for_project(
+ session: Session,
+ headers: dict[str, str],
+ project: dict[str, Any],
+ since: datetime | None,
+) -> Iterator[dict[str, Any]]:
+ """Walk a project's page views backward, newest first, by moving the `to` cutoff.
+
+ The endpoint returns at most 5000 rows ordered by date descending with no cursor, so each
+ request asks for everything older than the oldest row seen so far. An incremental sync
+ also passes `from`, which the server applies, so the walk ends at the watermark.
+ """
+ project_fields = _project_fields(project)
+ if project_fields is None:
+ return
+
+ to_cutoff: str | None = None
+ last_to_sent: str | None = None
+
+ for _ in range(_MAX_PAGES_PER_PROJECT):
+ params: dict[str, Any] = {"count": RUM_PAGE_VIEWS_PAGE_SIZE}
+ if since is not None:
+ params["from"] = _iso(since)
+ if to_cutoff:
+ params["to"] = to_cutoff
+
+ payload = _get_json(session, f"/project/{project['id']}/rumPageViews", headers, params=params)
+ if not isinstance(payload, list) or not payload:
+ return
+
+ rows = [
+ row
+ for row in (_normalize_rum_page_view(project_fields, item) for item in payload if isinstance(item, dict))
+ if row is not None
+ ]
+ if not rows:
+ return
+
+ yield from rows
+
+ next_to = min(row["date"] for row in rows)
+ if next_to == last_to_sent:
+ # The oldest row didn't move, so the next request would return the same page.
+ return
+ last_to_sent = next_to
+ to_cutoff = next_to
+ else:
+ # The watermark still advances to the newest row, so anything older than this cutoff
+ # is never fetched again — say so rather than truncating quietly.
+ logger.warning(
+ "DebugBear page view cap reached; truncating project history",
+ project_id=project_fields["project_id"],
+ pages=_MAX_PAGES_PER_PROJECT,
+ to_cutoff=to_cutoff,
+ )
+
+
+def _iter_annotations_for_project(
+ session: Session, headers: dict[str, str], project: dict[str, Any]
+) -> Iterator[dict[str, Any]]:
+ project_fields = _project_fields(project)
+ if project_fields is None:
+ return
+
+ payload = _get_json(session, f"/project/{project['id']}/annotations", headers)
+ if isinstance(payload, dict):
+ payload = payload.get("annotations")
+ if not isinstance(payload, list):
+ return
+
+ for annotation in payload:
+ if not isinstance(annotation, dict):
+ continue
+ row = {**annotation, **project_fields}
+ annotation_id = annotation.get("id")
+ # The list response shape isn't documented, so fall back to a content id rather than
+ # dropping an annotation that arrives without one.
+ row["id"] = str(annotation_id) if annotation_id is not None else _content_id(row)
+ yield row
+
+
def debugbear_source(
api_key: str,
endpoint: str,
@@ -180,6 +364,10 @@ def debugbear_source(
headers = _auth_headers(api_key)
session = _session(api_key)
+ incremental_since: datetime | None = None
+ if should_use_incremental_field and db_incremental_field_last_value is not None:
+ incremental_since = _parse_datetime(db_incremental_field_last_value)
+
if endpoint == "Projects":
def _iter_project_rows() -> Iterator[dict[str, Any]]:
@@ -192,14 +380,23 @@ def debugbear_source(
sort_mode="asc",
)
+ if endpoint == "Pages":
+
+ def _iter_page_rows() -> Iterator[dict[str, Any]]:
+ yield from _iter_pages(session, headers)
+
+ return SourceResponse(
+ name="pages",
+ items=_iter_page_rows,
+ primary_keys=["project_id", "id"],
+ sort_mode="asc",
+ )
+
if endpoint == "PageMetrics":
- stop_when_older_than: datetime | None = None
- if should_use_incremental_field and db_incremental_field_last_value is not None:
- stop_when_older_than = _parse_datetime(db_incremental_field_last_value)
def _iter_page_metrics_rows() -> Iterator[dict[str, Any]]:
for project in _iter_projects(session, headers):
- yield from _iter_page_metrics_for_project(session, headers, project, stop_when_older_than)
+ yield from _iter_page_metrics_for_project(session, headers, project, incremental_since)
return SourceResponse(
name="page_metrics",
@@ -213,4 +410,55 @@ def debugbear_source(
partition_keys=["analysis_date"],
)
+ if endpoint == "RumMetrics":
+
+ def _iter_rum_metrics_rows() -> Iterator[dict[str, Any]]:
+ for project in _iter_projects(session, headers):
+ yield from _iter_rum_metrics_for_project(session, headers, project, incremental_since)
+
+ return SourceResponse(
+ name="rum_metrics",
+ items=_iter_rum_metrics_rows,
+ primary_keys=["project_id", "metric", "date"],
+ # Buckets ascend within a project but the stream restarts at each project, so the
+ # watermark must only advance once every project has been read.
+ sort_mode="desc",
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime",
+ partition_format="month",
+ partition_keys=["date"],
+ )
+
+ if endpoint == "RumPageViews":
+
+ def _iter_rum_page_view_rows() -> Iterator[dict[str, Any]]:
+ for project in _iter_projects(session, headers):
+ yield from _iter_rum_page_views_for_project(session, headers, project, incremental_since)
+
+ return SourceResponse(
+ name="rum_page_views",
+ items=_iter_rum_page_view_rows,
+ primary_keys=["project_id", "id"],
+ sort_mode="desc",
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime",
+ partition_format="week",
+ partition_keys=["date"],
+ )
+
+ if endpoint == "Annotations":
+
+ def _iter_annotation_rows() -> Iterator[dict[str, Any]]:
+ for project in _iter_projects(session, headers):
+ yield from _iter_annotations_for_project(session, headers, project)
+
+ return SourceResponse(
+ name="annotations",
+ items=_iter_annotation_rows,
+ primary_keys=["project_id", "id"],
+ sort_mode="asc",
+ )
+
raise ValueError(f"Unknown DebugBear endpoint: {endpoint}")
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/debugbear/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/debugbear/settings.py
index 1e05c9dd68c3..e8ad0392748d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/debugbear/settings.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/debugbear/settings.py
@@ -2,7 +2,11 @@ from products.warehouse_sources.backend.types import IncrementalField, Increment
ENDPOINTS = (
"Projects",
+ "Pages",
"PageMetrics",
+ "RumMetrics",
+ "RumPageViews",
+ "Annotations",
)
INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
@@ -14,6 +18,22 @@ INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
"field_type": IncrementalFieldType.DateTime,
},
],
+ "RumMetrics": [
+ {
+ "label": "date",
+ "type": IncrementalFieldType.DateTime,
+ "field": "date",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
+ "RumPageViews": [
+ {
+ "label": "date",
+ "type": IncrementalFieldType.DateTime,
+ "field": "date",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
}
# DebugBear's `pageMetrics` endpoint only exposes a `before` cutoff (walk backward through
@@ -21,3 +41,15 @@ INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
# paginating once a whole page's results are no newer than the watermark instead of asking
# the API to filter server-side.
BEFORE_PARAM = "before"
+
+# `rumMetrics` aggregates the whole range into one value per metric unless `groupByTime`
+# splits it into buckets. Daily buckets give a row grain that merges cleanly and lets the
+# watermark advance.
+RUM_GROUP_BY_TIME = "day"
+
+# Neither RUM endpoint reports how far back a project's data goes, so a first sync asks for
+# a year and the API returns whatever falls inside the account's retention.
+RUM_BACKFILL_DAYS = 365
+
+# `rumPageViews` returns at most 5000 rows per request (the documented maximum for `count`).
+RUM_PAGE_VIEWS_PAGE_SIZE = 5000
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/debugbear/tests/test_debugbear.py b/products/warehouse_sources/backend/temporal/data_imports/sources/debugbear/tests/test_debugbear.py
index ded40e6c1eaf..ef9e32562ccc 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/debugbear/tests/test_debugbear.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/debugbear/tests/test_debugbear.py
@@ -1,6 +1,7 @@
from collections.abc import Iterable
-from datetime import UTC, datetime
+from datetime import UTC, datetime, timedelta
from typing import Any, cast
+from urllib.parse import parse_qs, urlparse
import pytest
from unittest.mock import MagicMock, patch
@@ -13,8 +14,13 @@ from requests.exceptions import (
from products.warehouse_sources.backend.temporal.data_imports.sources.debugbear.debugbear import (
_date_only,
_flatten_page_metrics_item,
+ _flatten_rum_metrics,
+ _iter_annotations_for_project,
_iter_page_metrics_for_project,
+ _iter_pages,
_iter_projects,
+ _iter_rum_metrics_for_project,
+ _iter_rum_page_views_for_project,
_parse_datetime,
debugbear_source,
validate_credentials,
@@ -226,21 +232,264 @@ class TestIterPageMetricsForProject:
assert session.get.call_count == 1
-class TestDebugbearSourceRouting:
- def test_projects_source_response(self) -> None:
- response = debugbear_source(api_key="key", endpoint="Projects")
+def _query(call: Any) -> dict[str, list[str]]:
+ return parse_qs(urlparse(call.args[0]).query)
+
+
+class TestIterPages:
+ def test_flattens_pages_out_of_the_projects_listing(self) -> None:
+ session = MagicMock()
+ session.get.return_value = _response(
+ [
+ {
+ "id": "p1",
+ "name": "My Project",
+ "pages": [
+ {"id": 999, "name": "Homepage", "url": "https://example.com"},
+ {"name": "No id"},
+ "unexpected",
+ ],
+ },
+ {"id": "p2", "name": "Empty", "pages": None},
+ ]
+ )
+
+ rows = list(_iter_pages(session, {}))
+
+ assert rows == [
+ {
+ "id": "999",
+ "name": "Homepage",
+ "url": "https://example.com",
+ "project_id": "p1",
+ "project_name": "My Project",
+ }
+ ]
+
+
+class TestFlattenRumMetrics:
+ def test_one_row_per_metric_bucket(self) -> None:
+ payload = {
+ "info": {"groupByTime": "day", "stat": "p75"},
+ "lcp": [
+ {"date": "2026-04-06T00:00:00.000Z", "count": 2, "value": 1400},
+ {"date": "2026-04-07T00:00:00.000Z", "count": 1, "value": 2000},
+ ],
+ "cls": [{"date": "2026-04-06T00:00:00.000Z", "count": 2, "value": 0.01}],
+ }
+
+ rows = list(_flatten_rum_metrics({"project_id": "p1", "project_name": "Proj"}, payload))
+
+ assert rows == [
+ {
+ "project_id": "p1",
+ "project_name": "Proj",
+ "metric": "lcp",
+ "date": "2026-04-06T00:00:00.000Z",
+ "value": 1400,
+ "count": 2,
+ "stat": "p75",
+ },
+ {
+ "project_id": "p1",
+ "project_name": "Proj",
+ "metric": "lcp",
+ "date": "2026-04-07T00:00:00.000Z",
+ "value": 2000,
+ "count": 1,
+ "stat": "p75",
+ },
+ {
+ "project_id": "p1",
+ "project_name": "Proj",
+ "metric": "cls",
+ "date": "2026-04-06T00:00:00.000Z",
+ "value": 0.01,
+ "count": 2,
+ "stat": "p75",
+ },
+ ]
+
+ @pytest.mark.parametrize(
+ "payload",
+ [
+ [],
+ {"info": {"stat": "p75"}},
+ {"lcp": [{"count": 2, "value": 1400}]},
+ {"lcp": ["unexpected"]},
+ ],
+ )
+ def test_unusable_payloads_yield_nothing(self, payload: Any) -> None:
+ assert list(_flatten_rum_metrics({"project_id": "p1"}, payload)) == []
+
+
+class TestIterRumMetricsForProject:
+ def test_incremental_asks_the_server_for_rows_after_the_watermark(self) -> None:
+ session = MagicMock()
+ session.get.return_value = _response({"info": {"stat": "p75"}, "lcp": []})
- assert response.name == "projects"
- assert response.primary_keys == ["id"]
- assert response.sort_mode == "asc"
+ list(_iter_rum_metrics_for_project(session, {}, {"id": "p1"}, since=datetime(2026, 4, 6, 12, 30, tzinfo=UTC)))
- def test_page_metrics_source_response(self) -> None:
- response = debugbear_source(api_key="key", endpoint="PageMetrics")
+ query = _query(session.get.call_args)
+ assert query["from"] == ["2026-04-06T12:30:00Z"]
+ assert query["groupByTime"] == ["day"]
+
+ def test_full_refresh_asks_for_the_backfill_window(self) -> None:
+ session = MagicMock()
+ session.get.return_value = _response({"info": {"stat": "p75"}, "lcp": []})
+
+ list(_iter_rum_metrics_for_project(session, {}, {"id": "p1"}, since=None))
+
+ requested_from = _parse_datetime(_query(session.get.call_args)["from"][0])
+ assert requested_from is not None
+ assert abs((datetime.now(UTC) - requested_from) - timedelta(days=365)) < timedelta(minutes=5)
+
+ def test_project_without_id_makes_no_request(self) -> None:
+ session = MagicMock()
+
+ assert list(_iter_rum_metrics_for_project(session, {}, {}, since=None)) == []
+ session.get.assert_not_called()
+
+
+class TestIterRumPageViewsForProject:
+ def test_walks_backward_with_the_to_cutoff_until_empty(self) -> None:
+ session = MagicMock()
+ page1 = [
+ {"path": "/", "date": "2026-04-14T20:30:15.000Z"},
+ {"path": "/pricing", "date": "2026-04-14T18:00:00.000Z"},
+ ]
+ page2 = [{"path": "/", "date": "2026-04-13T09:00:00.000Z"}]
+ session.get.side_effect = [_response(page1), _response(page2), _response([])]
+
+ rows = list(_iter_rum_page_views_for_project(session, {}, {"id": "p1"}, since=None))
+
+ assert [row["date"] for row in rows] == [
+ "2026-04-14T20:30:15.000Z",
+ "2026-04-14T18:00:00.000Z",
+ "2026-04-13T09:00:00.000Z",
+ ]
+ queries = [_query(call) for call in session.get.call_args_list]
+ assert "to" not in queries[0]
+ assert queries[0]["count"] == ["5000"]
+ assert queries[1]["to"] == ["2026-04-14T18:00:00.000Z"]
+ assert queries[2]["to"] == ["2026-04-13T09:00:00.000Z"]
+
+ def test_incremental_passes_the_watermark_as_from(self) -> None:
+ session = MagicMock()
+ session.get.side_effect = [_response([{"date": "2026-04-14T20:30:15.000Z"}]), _response([])]
- assert response.name == "page_metrics"
- assert response.primary_keys == ["project_id", "page_id", "analysis_date"]
- assert response.sort_mode == "desc"
- assert response.partition_keys == ["analysis_date"]
+ list(_iter_rum_page_views_for_project(session, {}, {"id": "p1"}, since=datetime(2026, 4, 14, tzinfo=UTC)))
+
+ assert all(_query(call)["from"] == ["2026-04-14T00:00:00Z"] for call in session.get.call_args_list)
+
+ def test_stops_when_the_oldest_row_does_not_move(self) -> None:
+ session = MagicMock()
+ page = [{"path": "/", "date": "2026-04-14T20:30:15.000Z"}]
+ session.get.side_effect = [_response(page), _response(page)]
+
+ rows = list(_iter_rum_page_views_for_project(session, {}, {"id": "p1"}, since=None))
+
+ assert session.get.call_count == 2
+ # The repeat is yielded, but its id matches the first row's so merge collapses them.
+ assert len({row["id"] for row in rows}) == 1
+
+ def test_synthesized_id_separates_different_page_views(self) -> None:
+ session = MagicMock()
+ session.get.side_effect = [
+ _response(
+ [
+ {"path": "/", "device": "mobile", "date": "2026-04-14T20:30:15.000Z"},
+ {"path": "/", "device": "desktop", "date": "2026-04-14T20:30:15.000Z"},
+ ]
+ ),
+ _response([]),
+ ]
+
+ rows = list(_iter_rum_page_views_for_project(session, {}, {"id": "p1"}, since=None))
+
+ assert len({row["id"] for row in rows}) == 2
+
+ def test_rows_without_a_date_are_skipped(self) -> None:
+ session = MagicMock()
+ session.get.return_value = _response([{"path": "/"}])
+
+ assert list(_iter_rum_page_views_for_project(session, {}, {"id": "p1"}, since=None)) == []
+ assert session.get.call_count == 1
+
+
+class TestIterAnnotationsForProject:
+ def test_reads_a_bare_list(self) -> None:
+ session = MagicMock()
+ session.get.return_value = _response([{"id": 7, "title": "V5 release", "date": "2026-04-14T20:30:15.000Z"}])
+
+ rows = list(_iter_annotations_for_project(session, {}, {"id": "p1", "name": "Proj"}))
+
+ assert rows == [
+ {
+ "id": "7",
+ "title": "V5 release",
+ "date": "2026-04-14T20:30:15.000Z",
+ "project_id": "p1",
+ "project_name": "Proj",
+ }
+ ]
+
+ def test_reads_a_wrapped_list(self) -> None:
+ session = MagicMock()
+ session.get.return_value = _response({"annotations": [{"id": "7", "title": "V5 release"}]})
+
+ rows = list(_iter_annotations_for_project(session, {}, {"id": "p1"}))
+
+ assert [row["id"] for row in rows] == ["7"]
+
+ def test_annotation_without_an_id_gets_a_content_id(self) -> None:
+ session = MagicMock()
+ session.get.return_value = _response([{"title": "V5 release"}, {"title": "V6 release"}])
+
+ rows = list(_iter_annotations_for_project(session, {}, {"id": "p1"}))
+
+ assert len({row["id"] for row in rows}) == 2
+
+ @pytest.mark.parametrize("payload", [{"error": "nope"}, "unexpected"])
+ def test_unusable_payloads_yield_nothing(self, payload: Any) -> None:
+ session = MagicMock()
+ session.get.return_value = _response(payload)
+
+ assert list(_iter_annotations_for_project(session, {}, {"id": "p1"})) == []
+
+
+class TestDebugbearSourceRouting:
+ @pytest.mark.parametrize(
+ ("endpoint", "name", "primary_keys", "sort_mode", "partition_keys"),
+ [
+ ("Projects", "projects", ["id"], "asc", None),
+ ("Pages", "pages", ["project_id", "id"], "asc", None),
+ (
+ "PageMetrics",
+ "page_metrics",
+ ["project_id", "page_id", "analysis_date"],
+ "desc",
+ ["analysis_date"],
+ ),
+ ("RumMetrics", "rum_metrics", ["project_id", "metric", "date"], "desc", ["date"]),
+ ("RumPageViews", "rum_page_views", ["project_id", "id"], "desc", ["date"]),
+ ("Annotations", "annotations", ["project_id", "id"], "asc", None),
+ ],
+ )
+ def test_endpoint_routes_to_its_response(
+ self,
+ endpoint: str,
+ name: str,
+ primary_keys: list[str],
+ sort_mode: str,
+ partition_keys: list[str] | None,
+ ) -> None:
+ response = debugbear_source(api_key="key", endpoint=endpoint)
+
+ assert response.name == name
+ assert response.primary_keys == primary_keys
+ assert response.sort_mode == sort_mode
+ assert response.partition_keys == partition_keys
def test_unknown_endpoint_raises(self) -> None:
with pytest.raises(ValueError, match="Unknown DebugBear endpoint"):