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(data-warehouse): add DebugBear source (#73189)

Tom Owers8288b0a100a3
diff --git a/frontend/public/services/debugbear.png b/frontend/public/services/debugbear.png
index 648f4a5e53f7..fefc068bcdfb 100644
Binary files a/frontend/public/services/debugbear.png and b/frontend/public/services/debugbear.png differ
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
index 8d3c6db12920..4024b9c140a7 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md
@@ -176,6 +176,7 @@ the row lists both.
| dataforseo | HTTP | requests | ✅ |
| datahub | HTTP | requests | ✅ |
| dbt | HTTP | requests | ✅ |
+| debugbear | HTTP | requests | ✅ |
| decagon | HTTP | requests | ✅ |
| deel | HTTP | requests | ✅ |
| deepgram | HTTP | requests | ✅ |
@@ -865,7 +866,6 @@ doesn't conflict with concurrent PRs.
- datorama
- dayforce
- db2
-- debugbear
- deno_deploy
- deputy
- develocity
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
new file mode 100644
index 000000000000..8b70ed25b197
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/debugbear/canonical_descriptions.py
@@ -0,0 +1,53 @@
+"""Canonical, documentation-sourced descriptions for DebugBear endpoints and columns.
+
+Sourced from the official DebugBear API docs (https://www.debugbear.com/docs/api). Keyed by
+the endpoint names in `settings.py` `ENDPOINTS`, which match the `ExternalDataSchema.name` of
+a synced DebugBear table. Columns absent here fall back to LLM enrichment.
+"""
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
+
+CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {
+ "Projects": {
+ "description": "A DebugBear project — a group of monitored pages that share alerting and reporting settings.",
+ "docs_url": "https://www.debugbear.com/docs/projects-api",
+ "columns": {
+ "id": "Unique identifier for the project.",
+ "name": "The project's display name.",
+ "pages": "The monitored pages configured within this project (id, name, url, region, test schedule, and device settings), as returned by the DebugBear API.",
+ },
+ },
+ "PageMetrics": {
+ "description": (
+ "A single synthetic (Lighthouse-based) lab test result for a monitored page — "
+ "performance/accessibility/SEO scores, Core Web Vitals, and page weight for one build."
+ ),
+ "docs_url": "https://www.debugbear.com/docs/lab-test-api",
+ "columns": {
+ "project_id": "Identifier of the DebugBear project the tested page belongs to.",
+ "project_name": "Display name of the DebugBear project the tested page belongs to.",
+ "page_id": "Identifier of the monitored page that was tested.",
+ "page_name": "Display name of the monitored page that was tested.",
+ "page_url": "URL of the monitored page that was tested.",
+ "analysis_date": "Date and time the test (analysis) was run.",
+ "performance_score": "Lighthouse performance score (0-1) for this test.",
+ "accessibility_score": "Lighthouse accessibility score (0-1) for this test.",
+ "bestPractices_score": "Lighthouse best-practices score (0-1) for this test.",
+ "seo_score": "Lighthouse SEO score (0-1) for this test.",
+ "pwa_score": "Lighthouse Progressive Web App score (0-1) for this test.",
+ "performance_speedIndex": "Speed Index metric (ms) for this test.",
+ "performance_interactive": "Time to Interactive metric (ms) for this test.",
+ "performance_firstContentfulPaint": "First Contentful Paint metric (ms) for this test.",
+ "performance_firstMeaningfulPaint": "First Meaningful Paint metric (ms) for this test.",
+ "performance_largestContentfulPaint": "Largest Contentful Paint metric (ms) for this test.",
+ "performance_totalBlockingTime": "Total Blocking Time metric (ms) for this test.",
+ "pageWeight_total": "Total page weight in bytes for this test.",
+ "crux_lcp_p75": "Chrome UX Report field-data Largest Contentful Paint, 75th percentile (ms).",
+ "crux_cls_p75": "Chrome UX Report field-data Cumulative Layout Shift, 75th percentile.",
+ "crux_fcp_p75": "Chrome UX Report field-data First Contentful Paint, 75th percentile (ms).",
+ "crux_fid_p75": "Chrome UX Report field-data First Input Delay, 75th percentile (ms).",
+ },
+ },
+}
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
new file mode 100644
index 000000000000..09497b9f3591
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/debugbear/debugbear.py
@@ -0,0 +1,216 @@
+from collections.abc import Iterator
+from datetime import datetime
+from typing import Any, Optional
+from urllib.parse import urlencode
+
+from dateutil import parser as dateutil_parser
+from requests import Session
+from requests.exceptions import RequestException
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.datetime_utils import (
+ coerce_datetime_to_utc,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import make_tracked_session
+from products.warehouse_sources.backend.temporal.data_imports.sources.debugbear.settings import BEFORE_PARAM
+
+BASE_URL = "https://www.debugbear.com/api/v1"
+_REQUEST_TIMEOUT = 30
+# DebugBear's `before` cursor only has day-level granularity (see `_date_only`), so a project
+# 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
+
+
+def _auth_headers(api_key: str) -> dict[str, str]:
+ return {"x-api-key": api_key, "Accept": "application/json"}
+
+
+def _session(api_key: str) -> Session:
+ # The API key rides in a custom `x-api-key` header the tracked transport's denylist
+ # scrubber wouldn't otherwise recognize, so redact it explicitly. `requests` replays
+ # custom headers across cross-origin redirects, so a 3xx from the upstream could forward
+ # the key to another host — disable redirects to keep it pinned to the validated origin.
+ return make_tracked_session(redact_values=(api_key,), allow_redirects=False)
+
+
+def _get_json(session: Session, path: str, headers: dict[str, str], params: dict[str, Any] | None = None) -> Any:
+ url = f"{BASE_URL}{path}"
+ if params:
+ url = f"{url}?{urlencode(params)}"
+ response = session.get(url, headers=headers, timeout=_REQUEST_TIMEOUT)
+ response.raise_for_status()
+ return response.json()
+
+
+def validate_credentials(api_key: str) -> tuple[bool, str | None]:
+ try:
+ response = _session(api_key).get(
+ f"{BASE_URL}/projects", headers=_auth_headers(api_key), timeout=_REQUEST_TIMEOUT
+ )
+ except RequestException as exc:
+ return False, str(exc)
+
+ if response.status_code == 200:
+ return True, None
+ if response.status_code == 401:
+ return False, "Invalid DebugBear API key."
+ if response.status_code == 403:
+ return (
+ False,
+ "This DebugBear API key can't list projects. Use an Admin API key (Account settings > API Keys).",
+ )
+ return False, f"DebugBear credential check failed with status {response.status_code}."
+
+
+def _iter_projects(session: Session, headers: dict[str, str]) -> list[dict[str, Any]]:
+ payload = _get_json(session, "/projects", headers)
+ if not isinstance(payload, list):
+ return []
+ return [project for project in payload if isinstance(project, dict)]
+
+
+def _parse_datetime(value: Any) -> datetime | None:
+ if isinstance(value, str):
+ try:
+ parsed = dateutil_parser.parse(value)
+ except (ValueError, TypeError):
+ return None
+ return coerce_datetime_to_utc(parsed)
+ return coerce_datetime_to_utc(value)
+
+
+def _date_only(value: str) -> str | None:
+ """DebugBear's `before` param only documents a plain YYYY-MM-DD date, not a full timestamp."""
+ if not value:
+ return None
+ return value[:10]
+
+
+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.
+
+ DebugBear reports metrics as dotted keys (e.g. `"performance.score"`, `"analysis.date"`);
+ flatten those into safe column names (`performance_score`, `analysis_date`).
+ """
+ raw_page = item.get("page")
+ page = raw_page if isinstance(raw_page, dict) else {}
+ raw_metrics = item.get("metrics")
+ metrics = raw_metrics if isinstance(raw_metrics, dict) else {}
+
+ page_id = page.get("id")
+ if page_id is None:
+ return None
+
+ row: dict[str, Any] = {
+ "project_id": str(project.get("id")),
+ "project_name": project.get("name"),
+ "page_id": str(page_id),
+ "page_name": page.get("name"),
+ "page_url": page.get("url"),
+ }
+ for key, value in metrics.items():
+ row[key.replace(".", "_")] = value
+
+ if not row.get("analysis_date"):
+ return None
+ return row
+
+
+def _iter_page_metrics_for_project(
+ session: Session,
+ headers: dict[str, str],
+ project: dict[str, Any],
+ stop_when_older_than: datetime | None,
+) -> Iterator[dict[str, Any]]:
+ """Walk a project's build history backward via the `before` cutoff.
+
+ DebugBear returns the most recent results by default; passing `before=<date>` fetches
+ older builds (see https://www.debugbear.com/docs/lab-test-api). There is no forward
+ `since`/`after` filter, so an incremental sync still starts from the most recent page and
+ stops as soon as a whole page is no newer than the watermark, rather than asking the API
+ to filter server-side.
+ """
+ project_id = project.get("id")
+ if project_id is None:
+ return
+
+ before: str | None = None
+ last_before_sent: str | None = None
+
+ for _ in range(_MAX_PAGES_PER_PROJECT):
+ params = {BEFORE_PARAM: before} if before else None
+ payload = _get_json(session, f"/projects/{project_id}/pageMetrics", headers, params=params)
+ if not isinstance(payload, list) or not payload:
+ return
+
+ rows = [
+ row
+ for row in (_flatten_page_metrics_item(project, item) for item in payload if isinstance(item, dict))
+ if row is not None
+ ]
+ if not rows:
+ return
+
+ yield from rows
+
+ parsed_dates = [_parse_datetime(row["analysis_date"]) for row in rows]
+ valid_dates: list[datetime] = [d for d in parsed_dates if d is not None]
+ if not valid_dates:
+ return
+
+ if stop_when_older_than is not None and max(valid_dates) <= stop_when_older_than:
+ return
+
+ next_before = _date_only(min(row["analysis_date"] for row in rows))
+ if not next_before or next_before == last_before_sent:
+ # No backward progress possible (day-granularity cutoff can't move further) —
+ # stop rather than re-fetching the same page forever.
+ return
+ last_before_sent = next_before
+ before = next_before
+
+
+def debugbear_source(
+ api_key: str,
+ endpoint: str,
+ should_use_incremental_field: bool = False,
+ db_incremental_field_last_value: Optional[Any] = None,
+) -> SourceResponse:
+ headers = _auth_headers(api_key)
+ session = _session(api_key)
+
+ if endpoint == "Projects":
+
+ def _iter_project_rows() -> Iterator[dict[str, Any]]:
+ yield from _iter_projects(session, headers)
+
+ return SourceResponse(
+ name="projects",
+ items=_iter_project_rows,
+ primary_keys=["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)
+
+ return SourceResponse(
+ name="page_metrics",
+ items=_iter_page_metrics_rows,
+ primary_keys=["project_id", "page_id", "analysis_date"],
+ sort_mode="desc",
+ partition_count=1,
+ partition_size=1,
+ partition_mode="datetime",
+ partition_format="week",
+ partition_keys=["analysis_date"],
+ )
+
+ 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
new file mode 100644
index 000000000000..1e05c9dd68c3
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/debugbear/settings.py
@@ -0,0 +1,23 @@
+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType
+
+ENDPOINTS = (
+ "Projects",
+ "PageMetrics",
+)
+
+INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {
+ "PageMetrics": [
+ {
+ "label": "analysis_date",
+ "type": IncrementalFieldType.DateTime,
+ "field": "analysis_date",
+ "field_type": IncrementalFieldType.DateTime,
+ },
+ ],
+}
+
+# DebugBear's `pageMetrics` endpoint only exposes a `before` cutoff (walk backward through
+# history); there is no forward `since`/`after` filter, so incremental syncs simply stop
+# 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"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/debugbear/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/debugbear/source.py
index 1d4ee6259682..63fbf47260fd 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/debugbear/source.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/debugbear/source.py
@@ -1,13 +1,35 @@
-from typing import cast
+from typing import Optional, cast
from posthog.schema import (
DataWarehouseSourceCategory,
ExternalDataSourceType as SchemaExternalDataSourceType,
+ ReleaseStatus,
SourceConfig,
+ SourceFieldInputConfig,
+ SourceFieldInputConfigType,
)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import (
+ SourceInputs,
+ SourceResponse,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (
+ CanonicalDescriptions,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistry
+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (
+ SourceSchema,
+ build_endpoint_schemas,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.debugbear.debugbear import (
+ debugbear_source,
+ validate_credentials as validate_debugbear_credentials,
+)
+from products.warehouse_sources.backend.temporal.data_imports.sources.debugbear.settings import (
+ ENDPOINTS,
+ INCREMENTAL_FIELDS,
+)
from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.debugbear import (
DebugbearSourceConfig,
)
@@ -16,17 +38,79 @@ from products.warehouse_sources.backend.types import ExternalDataSourceType
@SourceRegistry.register
class DebugbearSource(SimpleSource[DebugbearSourceConfig]):
+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs
+ api_docs_url = "https://www.debugbear.com/docs/api"
+
@property
def source_type(self) -> ExternalDataSourceType:
return ExternalDataSourceType.DEBUGBEAR
+ def get_non_retryable_errors(self) -> dict[str, str | None]:
+ return {
+ "401 Client Error": "Your DebugBear API key is invalid or expired. Please generate a new key and reconnect.",
+ "403 Client Error": "Your DebugBear API key doesn't have permission for this request. Use an Admin API key (Account settings > API Keys) and reconnect.",
+ }
+
+ def get_canonical_descriptions(self) -> CanonicalDescriptions:
+ from products.warehouse_sources.backend.temporal.data_imports.sources.debugbear.canonical_descriptions import (
+ CANONICAL_DESCRIPTIONS,
+ )
+
+ return CANONICAL_DESCRIPTIONS
+
+ def get_schemas(
+ self,
+ config: DebugbearSourceConfig,
+ team_id: int,
+ with_counts: bool = False,
+ names: list[str] | None = None,
+ force_refresh: bool = False,
+ api_version: str | None = None,
+ ) -> list[SourceSchema]:
+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)
+
+ def validate_credentials(
+ self,
+ config: DebugbearSourceConfig,
+ team_id: int,
+ schema_name: Optional[str] = None,
+ api_version: str | None = None,
+ ) -> tuple[bool, str | None]:
+ return validate_debugbear_credentials(config.api_key)
+
+ def source_for_pipeline(self, config: DebugbearSourceConfig, inputs: SourceInputs) -> SourceResponse:
+ return debugbear_source(
+ api_key=config.api_key,
+ endpoint=inputs.schema_name,
+ should_use_incremental_field=inputs.should_use_incremental_field,
+ db_incremental_field_last_value=inputs.db_incremental_field_last_value
+ if inputs.should_use_incremental_field
+ else None,
+ )
+
@property
def get_source_config(self) -> SourceConfig:
return SourceConfig(
name=SchemaExternalDataSourceType.DEBUGBEAR,
category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,
label="DebugBear",
+ caption="Sync DebugBear's monitored projects and synthetic Lighthouse / Core Web Vitals test results into your warehouse.",
+ docsUrl="https://posthog.com/docs/cdp/sources/debugbear",
iconPath="/static/services/debugbear.png",
- fields=cast(list[FieldType], []),
- unreleasedSource=True,
+ releaseStatus=ReleaseStatus.ALPHA,
+ keywords=["core web vitals", "lighthouse", "web performance"],
+ fields=cast(
+ list[FieldType],
+ [
+ SourceFieldInputConfig(
+ name="api_key",
+ label="API key",
+ type=SourceFieldInputConfigType.PASSWORD,
+ required=True,
+ placeholder="",
+ secret=True,
+ caption="Use an Admin API key so PostHog can list every monitored project. Generate one from DebugBear's account settings — see the [API docs](https://www.debugbear.com/docs/api).",
+ ),
+ ],
+ ),
)
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
new file mode 100644
index 000000000000..ded40e6c1eaf
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/debugbear/tests/test_debugbear.py
@@ -0,0 +1,272 @@
+from collections.abc import Iterable
+from datetime import UTC, datetime
+from typing import Any, cast
+
+import pytest
+from unittest.mock import MagicMock, patch
+
+from requests.exceptions import (
+ ConnectionError as RequestsConnectionError,
+ HTTPError,
+)
+
+from products.warehouse_sources.backend.temporal.data_imports.sources.debugbear.debugbear import (
+ _date_only,
+ _flatten_page_metrics_item,
+ _iter_page_metrics_for_project,
+ _iter_projects,
+ _parse_datetime,
+ debugbear_source,
+ validate_credentials,
+)
+
+
+def _response(json_body: Any, status_code: int = 200) -> MagicMock:
+ response = MagicMock()
+ response.status_code = status_code
+ response.json.return_value = json_body
+ if status_code >= 400:
+ response.raise_for_status.side_effect = HTTPError(f"{status_code} Client Error", response=response)
+ else:
+ response.raise_for_status.side_effect = None
+ return response
+
+
+class TestFlattenPageMetricsItem:
+ def test_flattens_dotted_metric_keys(self) -> None:
+ project = {"id": "p1", "name": "My Project"}
+ item = {
+ "page": {"id": "pg1", "name": "Homepage", "url": "https://example.com"},
+ "metrics": {"analysis.date": "2024-01-10T00:00:00.000Z", "performance.score": 0.96},
+ }
+
+ row = _flatten_page_metrics_item(project, item)
+
+ assert row == {
+ "project_id": "p1",
+ "project_name": "My Project",
+ "page_id": "pg1",
+ "page_name": "Homepage",
+ "page_url": "https://example.com",
+ "analysis_date": "2024-01-10T00:00:00.000Z",
+ "performance_score": 0.96,
+ }
+
+ def test_missing_page_id_returns_none(self) -> None:
+ project = {"id": "p1"}
+ item = {"page": {"name": "Homepage"}, "metrics": {"analysis.date": "2024-01-10T00:00:00.000Z"}}
+
+ assert _flatten_page_metrics_item(project, item) is None
+
+ def test_missing_analysis_date_returns_none(self) -> None:
+ project = {"id": "p1"}
+ item = {"page": {"id": "pg1"}, "metrics": {"performance.score": 0.9}}
+
+ assert _flatten_page_metrics_item(project, item) is None
+
+ def test_missing_page_and_metrics_keys_handled_gracefully(self) -> None:
+ assert _flatten_page_metrics_item({"id": "p1"}, {}) is None
+
+
+class TestDateOnly:
+ @pytest.mark.parametrize(
+ ("value", "expected"),
+ [
+ ("2024-01-10T19:06:42.201Z", "2024-01-10"),
+ ("2024-01-10", "2024-01-10"),
+ ("", None),
+ ],
+ )
+ def test_date_only(self, value: str, expected: str | None) -> None:
+ assert _date_only(value) == expected
+
+
+class TestParseDatetime:
+ def test_parses_iso_string(self) -> None:
+ parsed = _parse_datetime("2024-01-10T19:06:42.201Z")
+ assert parsed == datetime(2024, 1, 10, 19, 6, 42, 201000, tzinfo=UTC)
+
+ def test_invalid_string_returns_none(self) -> None:
+ assert _parse_datetime("not-a-date") is None
+
+ def test_none_returns_none(self) -> None:
+ assert _parse_datetime(None) is None
+
+ def test_datetime_passthrough(self) -> None:
+ value = datetime(2024, 1, 1, tzinfo=UTC)
+ assert _parse_datetime(value) == value
+
+
+class TestValidateCredentials:
+ @pytest.mark.parametrize(
+ ("status_code", "expected_valid"),
+ [(200, True), (401, False), (403, False), (500, False)],
+ )
+ def test_status_code_mapping(self, status_code: int, expected_valid: bool) -> None:
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.debugbear.debugbear.make_tracked_session"
+ ) as mock_make_session:
+ mock_make_session.return_value.get.return_value = _response([], status_code=status_code)
+ is_valid, error = validate_credentials("test-key")
+
+ assert is_valid is expected_valid
+ if not expected_valid:
+ assert error
+
+ def test_request_exception_is_reported(self) -> None:
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.debugbear.debugbear.make_tracked_session"
+ ) as mock_make_session:
+ mock_make_session.return_value.get.side_effect = RequestsConnectionError("boom")
+ is_valid, error = validate_credentials("test-key")
+
+ assert is_valid is False
+ assert "boom" in str(error)
+
+
+class TestSessionFactory:
+ def test_session_disables_redirects_so_api_key_is_not_replayed(self) -> None:
+ # The API key rides in a custom `x-api-key` header, which `requests` would replay
+ # across a cross-origin redirect — so the tracked session must never follow redirects.
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.debugbear.debugbear.make_tracked_session"
+ ) as mock_make_session:
+ mock_make_session.return_value.get.return_value = _response([])
+ validate_credentials("test-key")
+
+ mock_make_session.assert_called_once_with(redact_values=("test-key",), allow_redirects=False)
+
+
+class TestIterProjects:
+ def test_filters_non_dict_entries(self) -> None:
+ session = MagicMock()
+ session.get.return_value = _response([{"id": "p1"}, "unexpected", {"id": "p2"}])
+
+ projects = _iter_projects(session, {})
+
+ assert projects == [{"id": "p1"}, {"id": "p2"}]
+
+ def test_non_list_response_returns_empty(self) -> None:
+ session = MagicMock()
+ session.get.return_value = _response({"error": "nope"})
+
+ assert _iter_projects(session, {}) == []
+
+
+class TestIterPageMetricsForProject:
+ def test_walks_backward_until_empty_page(self) -> None:
+ session = MagicMock()
+ page1 = [
+ {"page": {"id": "pg1"}, "metrics": {"analysis.date": "2024-01-10T00:00:00.000Z"}},
+ {"page": {"id": "pg2"}, "metrics": {"analysis.date": "2024-01-08T00:00:00.000Z"}},
+ ]
+ page2 = [{"page": {"id": "pg1"}, "metrics": {"analysis.date": "2024-01-01T00:00:00.000Z"}}]
+ session.get.side_effect = [_response(page1), _response(page2), _response([])]
+
+ rows = list(_iter_page_metrics_for_project(session, {}, {"id": "proj1"}, stop_when_older_than=None))
+
+ assert [row["page_id"] for row in rows] == ["pg1", "pg2", "pg1"]
+ assert session.get.call_count == 3
+ # First request has no `before`; the second and third walk backward using the
+ # oldest date seen so far (date-only, per the documented `before=YYYY-MM-DD` param).
+ sent_urls = [call.args[0] for call in session.get.call_args_list]
+ assert "before" not in sent_urls[0]
+ assert "before=2024-01-08" in sent_urls[1]
+ assert "before=2024-01-01" in sent_urls[2]
+
+ def test_stops_early_once_page_predates_watermark(self) -> None:
+ session = MagicMock()
+ page1 = [
+ {"page": {"id": "pg1"}, "metrics": {"analysis.date": "2024-01-10T00:00:00.000Z"}},
+ {"page": {"id": "pg2"}, "metrics": {"analysis.date": "2024-01-08T00:00:00.000Z"}},
+ ]
+ page2 = [{"page": {"id": "pg1"}, "metrics": {"analysis.date": "2024-01-05T00:00:00.000Z"}}]
+ session.get.side_effect = [_response(page1), _response(page2)]
+ watermark = datetime(2024, 1, 9, tzinfo=UTC)
+
+ rows = list(_iter_page_metrics_for_project(session, {}, {"id": "proj1"}, stop_when_older_than=watermark))
+
+ # Page 1's newest item (2024-01-10) is after the watermark, so we keep paginating and
+ # yield it; page 2's newest item (2024-01-05) already predates the watermark, so its
+ # rows are yielded (merge dedupes) but pagination stops there — no third request.
+ assert len(rows) == 3
+ assert session.get.call_count == 2
+
+ def test_no_backward_progress_stops_pagination(self) -> None:
+ session = MagicMock()
+ # Every item lands on the same calendar day, so the day-granularity `before`
+ # cursor can never move further back — must stop rather than loop forever.
+ same_day_page = [
+ {"page": {"id": "pg1"}, "metrics": {"analysis.date": "2024-01-05T10:00:00.000Z"}},
+ {"page": {"id": "pg2"}, "metrics": {"analysis.date": "2024-01-05T08:00:00.000Z"}},
+ ]
+ session.get.side_effect = [_response(same_day_page), _response(same_day_page)]
+
+ rows = list(_iter_page_metrics_for_project(session, {}, {"id": "proj1"}, stop_when_older_than=None))
+
+ # Both pages are yielded (merge dedupes the repeat), but a third request never fires.
+ assert session.get.call_count == 2
+ assert len(rows) == 4
+
+ def test_no_project_id_yields_nothing(self) -> None:
+ session = MagicMock()
+
+ rows = list(_iter_page_metrics_for_project(session, {}, {}, stop_when_older_than=None))
+
+ assert rows == []
+ session.get.assert_not_called()
+
+ def test_page_with_no_usable_rows_stops(self) -> None:
+ session = MagicMock()
+ session.get.return_value = _response([{"page": {}, "metrics": {}}])
+
+ rows = list(_iter_page_metrics_for_project(session, {}, {"id": "proj1"}, stop_when_older_than=None))
+
+ assert rows == []
+ assert session.get.call_count == 1
+
+
+class TestDebugbearSourceRouting:
+ def test_projects_source_response(self) -> None:
+ response = debugbear_source(api_key="key", endpoint="Projects")
+
+ assert response.name == "projects"
+ assert response.primary_keys == ["id"]
+ assert response.sort_mode == "asc"
+
+ def test_page_metrics_source_response(self) -> None:
+ response = debugbear_source(api_key="key", endpoint="PageMetrics")
+
+ 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"]
+
+ def test_unknown_endpoint_raises(self) -> None:
+ with pytest.raises(ValueError, match="Unknown DebugBear endpoint"):
+ debugbear_source(api_key="key", endpoint="Nope")
+
+ def test_page_metrics_items_iterates_all_projects(self) -> None:
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.debugbear.debugbear.make_tracked_session"
+ ) as mock_make_session:
+ mock_session = mock_make_session.return_value
+ projects_response = _response([{"id": "proj1"}, {"id": "proj2"}])
+ proj1_metrics = _response(
+ [{"page": {"id": "pg1"}, "metrics": {"analysis.date": "2024-01-10T00:00:00.000Z"}}]
+ )
+ proj2_metrics = _response(
+ [{"page": {"id": "pg2"}, "metrics": {"analysis.date": "2024-01-11T00:00:00.000Z"}}]
+ )
+ mock_session.get.side_effect = [
+ projects_response,
+ proj1_metrics,
+ _response([]),
+ proj2_metrics,
+ _response([]),
+ ]
+
+ response = debugbear_source(api_key="key", endpoint="PageMetrics")
+ rows = list(cast("Iterable[Any]", response.items()))
+
+ assert [row["project_id"] for row in rows] == ["proj1", "proj2"]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/debugbear/tests/test_debugbear_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/debugbear/tests/test_debugbear_source.py
new file mode 100644
index 000000000000..d59a8e857ec9
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/debugbear/tests/test_debugbear_source.py
@@ -0,0 +1,123 @@
+import pytest
+from unittest.mock import MagicMock, patch
+
+from posthog.schema import ReleaseStatus, SourceFieldInputConfig
+
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceInputs
+from products.warehouse_sources.backend.temporal.data_imports.sources.debugbear.source import DebugbearSource
+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.debugbear import (
+ DebugbearSourceConfig,
+)
+from products.warehouse_sources.backend.types import ExternalDataSourceType
+
+
+class TestDebugbearSource:
+ def setup_method(self) -> None:
+ self.source = DebugbearSource()
+ self.team_id = 123
+ self.config = DebugbearSourceConfig(api_key="test-key")
+
+ def test_source_type(self) -> None:
+ assert self.source.source_type == ExternalDataSourceType.DEBUGBEAR
+
+ def test_lists_tables_without_credentials(self) -> None:
+ # get_schemas is a static endpoint catalog with no I/O, so the public docs table
+ # catalog can render without a real credential.
+ assert self.source.lists_tables_without_credentials is True
+
+ def test_get_source_config_has_no_unreleased_flag(self) -> None:
+ # A finished source must not stay hidden behind unreleasedSource.
+ assert self.source.get_source_config.unreleasedSource is None
+
+ def test_get_source_config_release_status(self) -> None:
+ assert self.source.get_source_config.releaseStatus == ReleaseStatus.ALPHA
+
+ def test_get_source_config_has_category(self) -> None:
+ assert self.source.get_source_config.category is not None
+
+ def test_get_source_config_api_key_field(self) -> None:
+ fields = self.source.get_source_config.fields
+ assert len(fields) == 1
+ field = fields[0]
+ assert isinstance(field, SourceFieldInputConfig)
+ assert field.name == "api_key"
+ assert field.secret is True
+ assert field.required is True
+
+ def test_get_schemas_returns_expected_endpoints(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ assert {s.name for s in schemas} == {"Projects", "PageMetrics"}
+
+ def test_get_schemas_projects_is_full_refresh(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ projects = next(s for s in schemas if s.name == "Projects")
+ assert projects.supports_incremental is False
+ assert projects.incremental_fields == []
+
+ def test_get_schemas_page_metrics_supports_incremental(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id)
+ page_metrics = next(s for s in schemas if s.name == "PageMetrics")
+ assert page_metrics.supports_incremental is True
+ assert [f["field"] for f in page_metrics.incremental_fields] == ["analysis_date"]
+
+ def test_get_schemas_filters_by_names(self) -> None:
+ schemas = self.source.get_schemas(self.config, self.team_id, names=["Projects"])
+ assert [s.name for s in schemas] == ["Projects"]
+
+ @pytest.mark.parametrize(
+ ("pattern", "message"),
+ [
+ ("401 Client Error", "401 Client Error: Unauthorized for url: https://www.debugbear.com/api/v1/projects"),
+ ("403 Client Error", "403 Client Error: Forbidden for url: https://www.debugbear.com/api/v1/projects"),
+ ],
+ )
+ def test_non_retryable_errors_match(self, pattern: str, message: str) -> None:
+ errors = self.source.get_non_retryable_errors()
+ assert pattern in errors
+ assert any(p in message for p in errors)
+
+ def test_validate_credentials_delegates_to_transport(self) -> None:
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.debugbear.source.validate_debugbear_credentials"
+ ) as mock_validate:
+ mock_validate.return_value = (True, None)
+ result = self.source.validate_credentials(self.config, self.team_id)
+
+ mock_validate.assert_called_once_with("test-key")
+ assert result == (True, None)
+
+ def test_get_canonical_descriptions_covers_declared_endpoints(self) -> None:
+ descriptions = self.source.get_canonical_descriptions()
+ assert set(descriptions.keys()) == {"Projects", "PageMetrics"}
+
+ @pytest.mark.parametrize("schema_name", ["Projects", "PageMetrics"])
+ def test_source_for_pipeline_plumbs_schema_name(self, schema_name: str) -> None:
+ inputs = MagicMock(spec=SourceInputs)
+ inputs.schema_name = schema_name
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = None
+
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.debugbear.source.debugbear_source"
+ ) as mock_debugbear_source:
+ self.source.source_for_pipeline(self.config, inputs)
+
+ mock_debugbear_source.assert_called_once_with(
+ api_key="test-key",
+ endpoint=schema_name,
+ should_use_incremental_field=False,
+ db_incremental_field_last_value=None,
+ )
+
+ def test_source_for_pipeline_omits_watermark_when_not_incremental(self) -> None:
+ inputs = MagicMock(spec=SourceInputs)
+ inputs.schema_name = "PageMetrics"
+ inputs.should_use_incremental_field = False
+ inputs.db_incremental_field_last_value = "2024-01-01T00:00:00Z"
+
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.sources.debugbear.source.debugbear_source"
+ ) as mock_debugbear_source:
+ self.source.source_for_pipeline(self.config, inputs)
+
+ assert mock_debugbear_source.call_args.kwargs["db_incremental_field_last_value"] is None
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/debugbear.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/debugbear.py
index a45dbc527ce9..664144cbbe30 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/debugbear.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/debugbear.py
@@ -6,4 +6,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp
@config.config
class DebugbearSourceConfig(config.Config):
- pass
+ api_key: str