:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.
Python ab-testingai-analyticsanalyticscdpdata-warehouseexperimentsfeature-flagsjavascriptproduct-analyticspythonreactsession-replaysurveystypescriptweb-analytics
feat(data-warehouse): implement the speedcurve import source (#112233)
Tom Owerscbd5e8f2462c
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex a16382c99e7a..3b2fd1143c38 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -757,6 +757,7 @@ the row lists both.| sourcegraph | HTTP (GraphQL) | requests | ✅ || spacelift | HTTP (GraphQL) | requests | ✅ || sparkpost | HTTP + Webhook | requests + `rest_source.RESTClient` + `WebhookSourceManager` | ✅ (pull) / ➖ (webhook) |+| speedcurve | HTTP | requests | ✅ || split_io | HTTP | requests | ✅ || spot_io | HTTP | requests + `rest_source.RESTClient` | ✅ || spotlercrm | HTTP | requests + `rest_source.RESTClient` | ✅ |@@ -1419,7 +1420,6 @@ doesn't conflict with concurrent PRs.- sonar_cloud- sonatype_nexus- spacelift-- speedcurve- spotify_ads- sprinklr- sprintodiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/speedcurve.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/speedcurve.pyindex 04032fec0e05..765ac57ec7e4 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/speedcurve.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/speedcurve.py@@ -6,4 +6,4 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass SpeedcurveSourceConfig(config.Config):- pass+ api_key: strdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/speedcurve/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/speedcurve/canonical_descriptions.pynew file mode 100644index 000000000000..d9a4ac1bf423--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/speedcurve/canonical_descriptions.py@@ -0,0 +1,80 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "sites": {+ "description": "Sites configured for synthetic monitoring in the SpeedCurve team.",+ "docs_url": "https://support.speedcurve.com/reference/get-all-sites-1",+ "columns": {+ "site_id": "Identifier of the monitored site.",+ "name": "Site name.",+ "checks_scheduled": "Number of scheduled checks.",+ "urls": "URLs monitored for the site.",+ },+ },+ "urls": {+ "description": "Monitored URLs across the team's sites, with metadata for their latest tests.",+ "docs_url": "https://support.speedcurve.com/reference/get-all-urls",+ "columns": {+ "site_id": "Identifier of the parent site, copied from the response containing this URL.",+ "url_id": "Identifier of the monitored URL.",+ "url": "Address of the monitored page.",+ "label": "Label assigned to the page.",+ "latest_tests": "Latest test identifiers, timestamps, regions, and browsers for this URL.",+ },+ },+ "tests": {+ "description": "Synthetic tests, including queued, failed, and successful tests, with available performance metrics.",+ "docs_url": "https://support.speedcurve.com/reference/get-all-tests",+ "columns": {+ "test_id": "Identifier of the synthetic test.",+ "site_id": "Identifier of the monitored site.",+ "url_id": "Identifier of the monitored URL.",+ "timestamp": "Test time as a Unix timestamp in seconds.",+ "status": "Test status: -2 means queued, -1 means failed, and 0 means successful.",+ "region": "Test location identifier.",+ "browser": "Browser used for the test.",+ "largest_contentful_paint": "Largest Contentful Paint metric for the test.",+ "cumulative_layout_shift": "Cumulative Layout Shift metric for the test.",+ "lighthouse_performance": "Lighthouse performance score for the test.",+ },+ },+ "deploys": {+ "description": "Deployments recorded in SpeedCurve, with their sites, timestamps, and notes.",+ "docs_url": "https://support.speedcurve.com/reference/get-all-deploys",+ "columns": {+ "deploy_id": "Identifier of the deployment.",+ "site_id": "Identifier of the deployment's site.",+ "timestamp": "Deployment time as a Unix timestamp in seconds.",+ "note": "Short note for the deployment.",+ "detail": "Additional details for the deployment.",+ },+ },+ "notes": {+ "description": "Notes attached to the team's sites to explain changes in performance.",+ "docs_url": "https://support.speedcurve.com/reference/get-all-notes",+ "columns": {+ "note_id": "Identifier of the note.",+ "site_id": "Identifier of the note's site.",+ "timestamp": "Note time as a Unix timestamp in seconds.",+ "note": "Short note text.",+ "detail": "Additional note details.",+ },+ },+ "budgets": {+ "description": "Synthetic performance budgets from dashboards visible to the entire team, with their evaluation data.",+ "docs_url": "https://support.speedcurve.com/reference/get-all-budgets",+ "columns": {+ "budget_id": "Identifier of the performance budget.",+ "metric": "Metric evaluated by the budget.",+ "absolute_threshold": "Absolute threshold for the metric.",+ "relative_threshold": "Relative threshold for the metric.",+ "created_at": "Budget creation time as a Unix timestamp in seconds.",+ "modified_at": "Last modification time as a Unix timestamp in seconds.",+ "status": "Result of the budget evaluation.",+ "notifications_enabled": "Whether the budget sends notifications.",+ "chart": "Chart configuration associated with the budget.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/speedcurve/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/speedcurve/settings.pynew file mode 100644index 000000000000..1fdeef08b0ec--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/speedcurve/settings.py@@ -0,0 +1,36 @@+from posthog.dataclasses import frozen++from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++BASE_URL = "https://api.speedcurve.com"+TEST_HISTORY_DAYS = 364+INCREMENTAL_LOOKBACK_SECONDS = 86400+++@frozen+class SpeedcurveEndpoint:+ selector: str+ primary_keys: tuple[str, ...]+ paginated: bool = False+++ENDPOINTS = {+ "sites": SpeedcurveEndpoint(selector="sites", primary_keys=("site_id",)),+ "urls": SpeedcurveEndpoint(selector="sites", primary_keys=("site_id", "url_id")),+ "tests": SpeedcurveEndpoint(selector="data", primary_keys=("test_id",), paginated=True),+ "deploys": SpeedcurveEndpoint(selector="deploys", primary_keys=("deploy_id",), paginated=True),+ "notes": SpeedcurveEndpoint(selector="notes", primary_keys=("note_id",)),+ "budgets": SpeedcurveEndpoint(selector="budgets", primary_keys=("budget_id",)),+}++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: [+ {+ "label": "timestamp",+ "type": IncrementalFieldType.DateTime,+ "field": "timestamp",+ "field_type": IncrementalFieldType.Integer,+ }+ ]+ for name in ("tests", "deploys")+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/speedcurve/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/speedcurve/source.pyindex a0528f4d0c85..e5b8c225f073 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/speedcurve/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/speedcurve/source.py@@ -1,16 +1,49 @@from typing import cast-from products.warehouse_sources.backend.facade.source_config import DataWarehouseSourceCategory, SourceConfig-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+from products.warehouse_sources.backend.facade.source_config import (+ DataWarehouseSourceCategory,+ ReleaseStatus,+ SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, ResumableSource+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.resumable import ResumableSourceManager+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.common.typings import SourceInputs, SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.speedcurve import (SpeedcurveSourceConfig,)+from products.warehouse_sources.backend.temporal.data_imports.sources.speedcurve.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ INCREMENTAL_LOOKBACK_SECONDS,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.speedcurve.speedcurve import (+ AUTH_ERROR,+ PERMISSION_ERROR,+ SpeedcurveResumeConfig,+ speedcurve_source,+ validate_credentials,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class SpeedcurveSource(SimpleSource[SpeedcurveSourceConfig]):+class SpeedcurveSource(ResumableSource[SpeedcurveSourceConfig, SpeedcurveResumeConfig]):+ lists_tables_without_credentials = True+ # SpeedCurve v2 remains beta: https://support.speedcurve.com/reference/getting-started-with-api-v2+ supported_versions = ("v1",)+ default_version = "v1"+ api_docs_url = "https://support.speedcurve.com/reference/getting-started"+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.SPEEDCURVE@@ -22,6 +55,75 @@ class SpeedcurveSource(SimpleSource[SpeedcurveSourceConfig]):category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="SpeedCurve",iconPath="/static/services/speedcurve.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ caption="Find your API key in SpeedCurve under **Admin > Teams**. An organization admin can access this page.",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ )+ ],+ ),+ releaseStatus=ReleaseStatus.ALPHA,+ )++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {"401 Client Error": AUTH_ERROR, "403 Client Error": PERMISSION_ERROR}++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.speedcurve.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_schemas(+ self,+ config: SpeedcurveSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ api_version: str | None = None,+ ) -> list[SourceSchema]:+ schemas = build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names, merge_only=INCREMENTAL_FIELDS)+ for schema in schemas:+ schema.detected_primary_keys = list(ENDPOINTS[schema.name].primary_keys)+ if schema.supports_incremental:+ # Recent tests can still be queued, and deployment notes can change after creation.+ schema.default_incremental_lookback_seconds = INCREMENTAL_LOOKBACK_SECONDS+ return schemas++ def validate_credentials(+ self,+ config: SpeedcurveSourceConfig,+ team_id: int,+ schema_name: str | None = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ return validate_credentials(config.api_key, self.resolve_api_version(api_version))++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[SpeedcurveResumeConfig]:+ return ResumableSourceManager(inputs, SpeedcurveResumeConfig)++ def source_for_pipeline(+ self,+ config: SpeedcurveSourceConfig,+ resumable_source_manager: ResumableSourceManager[SpeedcurveResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return speedcurve_source(+ api_key=config.api_key,+ api_version=self.resolve_api_version(inputs.api_version),+ endpoint=inputs.schema_name,+ team_id=inputs.team_id,+ job_id=inputs.job_id,+ resumable_source_manager=resumable_source_manager,+ should_use_incremental_field=inputs.should_use_incremental_field,+ db_incremental_field_last_value=inputs.db_incremental_field_last_value,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/speedcurve/speedcurve.py b/products/warehouse_sources/backend/temporal/data_imports/sources/speedcurve/speedcurve.pynew file mode 100644index 000000000000..b5f8dbb569e3--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/speedcurve/speedcurve.py@@ -0,0 +1,168 @@+from datetime import UTC, datetime, timedelta+from typing import Any, cast++from requests.exceptions import HTTPError+from urllib3.util.retry import Retry++from posthog.dataclasses import frozen++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.rest_source import (+ RESTAPIConfig,+ rest_api_resource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.auth import HttpBasicAuth+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.paginators import (+ SinglePagePaginator,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import RESTClient+from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.typing import (+ Endpoint,+ PaginatorConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import schema_for_resource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.speedcurve.settings import (+ BASE_URL,+ ENDPOINTS,+ TEST_HISTORY_DAYS,+)++AUTH_ERROR = "SpeedCurve rejected the API key. Check the key and confirm that your SpeedCurve account is active."+PERMISSION_ERROR = "SpeedCurve denied access. Check the API key permissions for your team."+++@frozen+class SpeedcurveResumeConfig:+ page: int+ start_timestamp: int | None+ end_timestamp: int+++def validate_credentials(api_key: str, api_version: str) -> tuple[bool, str | None]:+ with make_tracked_session(redact_values=(api_key,), retry=Retry(total=0)) as session:+ client = RESTClient(+ base_url=f"{BASE_URL}/{api_version}/",+ auth=HttpBasicAuth(username=api_key, password="x"),+ session=session,+ request_timeout=60,+ )+ try:+ next(+ client.paginate(+ "sites",+ params={"median": 0},+ paginator=SinglePagePaginator(),+ data_selector="sites",+ data_selector_required=True,+ )+ )+ except HTTPError as error:+ if error.response is not None:+ if error.response.status_code == 401:+ return False, AUTH_ERROR+ if error.response.status_code == 403:+ return False, PERMISSION_ERROR+ raise+ return True, None+++def _site_urls(site: dict[str, Any]) -> list[dict[str, Any]]:+ return [{**url, "site_id": site["site_id"]} for url in site["urls"]]+++def speedcurve_source(+ api_key: str,+ api_version: str,+ endpoint: str,+ team_id: int,+ job_id: str,+ resumable_source_manager: ResumableSourceManager[SpeedcurveResumeConfig],+ should_use_incremental_field: bool,+ db_incremental_field_last_value: int | float | str | None,+) -> SourceResponse:+ settings = schema_for_resource(ENDPOINTS, endpoint)+ now = datetime.now(UTC)+ end_timestamp = int(now.timestamp())+ start_timestamp = None+ page = 1+ if settings.paginated:+ if should_use_incremental_field and db_incremental_field_last_value is not None:+ start_timestamp = int(db_incremental_field_last_value)+ if endpoint == "tests":+ # Leave one day inside the API's rolling twelve-month retention limit.+ retention_start = int((now - timedelta(days=TEST_HISTORY_DAYS)).timestamp())+ start_timestamp = max(start_timestamp or retention_start, retention_start)+ if resumable_source_manager.can_resume():+ saved = resumable_source_manager.load_state()+ if saved is not None:+ page = saved.page+ start_timestamp = saved.start_timestamp+ end_timestamp = saved.end_timestamp++ def save_checkpoint(state: dict[str, Any] | None) -> None:+ if state is not None:+ resumable_source_manager.save_state(+ SpeedcurveResumeConfig(page=state["page"], start_timestamp=start_timestamp, end_timestamp=end_timestamp)+ )++ endpoint_config: Endpoint = {+ "path": endpoint,+ "data_selector": settings.selector,+ "data_selector_required": True,+ "paginator": "single_page",+ }+ if settings.paginated:+ endpoint_config["params"] = {+ "per_page": 100,+ "start_timestamp": start_timestamp,+ "end_timestamp": end_timestamp,+ }+ endpoint_config["paginator"] = cast(+ PaginatorConfig,+ {+ "type": "page_number",+ "base_page": 1,+ "total_path": "meta.last_page" if endpoint == "tests" else None,+ },+ )++ config: RESTAPIConfig = {+ "client": {+ "base_url": f"{BASE_URL}/{api_version}/",+ "auth": {"type": "http_basic", "username": api_key, "password": "x"},+ "session": make_tracked_session(redact_values=(api_key,), retry=Retry(total=0)),+ "request_timeout": 60,+ },+ "resources": [+ {+ "name": endpoint,+ "table_format": "delta",+ "endpoint": endpoint_config,+ }+ ],+ }+ resource = rest_api_resource(+ config,+ team_id,+ job_id,+ None,+ resume_hook=save_checkpoint if settings.paginated else None,+ initial_paginator_state={"page": page} if settings.paginated else None,+ )+ if endpoint == "urls":+ resource.add_map(_site_urls)++ return SourceResponse(+ name=endpoint,+ items=lambda: resource,+ primary_keys=list(settings.primary_keys),+ # The API has no ascending sort option, so checkpoint the watermark after the complete scan.+ sort_mode="desc",+ partition_keys=["timestamp"] if settings.paginated else None,+ partition_mode="datetime" if settings.paginated else None,+ partition_format="month" if settings.paginated else None,+ supports_resume=settings.paginated,+ on_complete=resumable_source_manager.clear_state if settings.paginated else None,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/speedcurve/tests/test_speedcurve.py b/products/warehouse_sources/backend/temporal/data_imports/sources/speedcurve/tests/test_speedcurve.pynew file mode 100644index 000000000000..f133b5acda40--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/speedcurve/tests/test_speedcurve.py@@ -0,0 +1,243 @@+from collections.abc import Iterable, Iterator+from datetime import UTC, datetime, timedelta+from typing import Any, cast+from urllib.parse import parse_qs, urlsplit++import pytest+from unittest.mock import MagicMock, patch++import responses+from requests.exceptions import HTTPError++from products.warehouse_sources.backend.temporal.data_imports.sources.common.rest_source.rest_client import (+ RESTClientRetryableError,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import UnknownResourceError+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.speedcurve.source import SpeedcurveSource+from products.warehouse_sources.backend.temporal.data_imports.sources.speedcurve.speedcurve import (+ SpeedcurveResumeConfig,+ speedcurve_source,+ validate_credentials,+)++NOW = datetime(2026, 6, 15, tzinfo=UTC)+BASE_URL = "https://api.speedcurve.com/v1/"++[email protected](autouse=True)+def fixed_clock() -> Iterator[None]:+ with patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.speedcurve.speedcurve.datetime"+ ) as clock:+ clock.now.return_value = NOW+ yield+++def manager() -> MagicMock:+ result = MagicMock(spec=ResumableSourceManager)+ result.can_resume.return_value = False+ return result+++def _source(+ manager: MagicMock,+ endpoint: str,+ incremental: bool = False,+ watermark: int | float | str | None = None,+) -> SourceResponse:+ return speedcurve_source(+ api_key="fake-key",+ api_version="v1",+ endpoint=endpoint,+ team_id=1,+ job_id="speedcurve-test",+ resumable_source_manager=manager,+ should_use_incremental_field=incremental,+ db_incremental_field_last_value=watermark,+ )+++def _rows(source: SourceResponse) -> list[dict[str, Any]]:+ return [row for page in cast(Iterable[list[dict[str, Any]]], source.items()) for row in page]+++ ("endpoint", "body", "expected"),+ [+ ("sites", {"sites": [{"site_id": 1, "name": "Example"}]}, [{"site_id": 1, "name": "Example"}]),+ ("notes", {"notes": [{"note_id": 2, "note": "New layout"}]}, [{"note_id": 2, "note": "New layout"}]),+ ("budgets", {"budgets": [{"budget_id": 3, "status": "over"}]}, [{"budget_id": 3, "status": "over"}]),+ (+ "urls",+ {+ "sites": [+ {"site_id": 1, "urls": [{"url_id": 4, "url": "https://example.com"}]},+ {"site_id": 2, "urls": [{"url_id": 4, "url": "https://example.org"}]},+ {"site_id": 3, "urls": []},+ ]+ },+ [+ {"site_id": 1, "url_id": 4, "url": "https://example.com"},+ {"site_id": 2, "url_id": 4, "url": "https://example.org"},+ ],+ ),+ ],+)+def test_single_page_rows_and_auth(+ manager: MagicMock, endpoint: str, body: dict[str, Any], expected: list[dict[str, Any]]+) -> None:+ responses.get(BASE_URL + endpoint, json=body)++ source = _source(manager, endpoint)+ assert _rows(source) == expected+ assert len(responses.calls) == 1+ request = responses.calls[0].request+ assert request.headers["Authorization"] == "Basic ZmFrZS1rZXk6eA=="+ assert not urlsplit(request.url).query+ if endpoint == "urls":+ assert len({tuple(row[key] for key in source.primary_keys or []) for row in expected}) == 2+ manager.can_resume.assert_not_called()++[email protected]("endpoint", ["tests", "deploys"])+def test_pagination_and_resume_checkpoint(manager: MagicMock, endpoint: str) -> None:+ selector = "data" if endpoint == "tests" else "deploys"+ key = "test_id" if endpoint == "tests" else "deploy_id"+ for page in (1, 2):+ body: dict[str, Any] = {selector: [{key: page, "timestamp": int(NOW.timestamp()) - page}]}+ if endpoint == "tests":+ body["meta"] = {"last_page": 2}+ responses.get(BASE_URL + endpoint, json=body)+ if endpoint == "deploys":+ responses.get(BASE_URL + endpoint, json={selector: []})++ source = _source(manager, endpoint)+ assert [row[key] for row in _rows(source)] == [1, 2]+ query_params = [parse_qs(urlsplit(call.request.url).query) for call in responses.calls]+ assert [params["page"] for params in query_params] == (+ [["1"], ["2"]] if endpoint == "tests" else [["1"], ["2"], ["3"]]+ )+ assert all(params["per_page"] == ["100"] for params in query_params)+ assert all(params["end_timestamp"] == [str(int(NOW.timestamp()))] for params in query_params)+ checkpoints = [call.args[0] for call in manager.save_state.call_args_list]+ assert [checkpoint.page for checkpoint in checkpoints] == ([2] if endpoint == "tests" else [2, 3])+ assert all(checkpoint.end_timestamp == int(NOW.timestamp()) for checkpoint in checkpoints)+ assert source.sort_mode == "desc"+ manager.clear_state.assert_not_called()+ assert source.on_complete is not None+ source.on_complete()+ manager.clear_state.assert_called_once()++[email protected]("endpoint", ["tests", "deploys"])+def test_resume_preserves_range_when_clock_and_watermark_change(manager: MagicMock, endpoint: str) -> None:+ saved = SpeedcurveResumeConfig(page=4, start_timestamp=1751000000, end_timestamp=1752000000)+ manager.can_resume.return_value = True+ manager.load_state.return_value = saved+ selector = "data" if endpoint == "tests" else "deploys"+ responses.get(BASE_URL + endpoint, json={selector: []})++ assert _rows(_source(manager, endpoint, incremental=True, watermark=1780000000)) == []+ assert parse_qs(urlsplit(responses.calls[0].request.url).query) == {+ "page": ["4"],+ "per_page": ["100"],+ "start_timestamp": ["1751000000"],+ "end_timestamp": ["1752000000"],+ }+ manager.save_state.assert_not_called()++[email protected]("endpoint", ["tests", "deploys"])+ ("incremental", "watermark"),+ [(False, 1780000000), (True, None), (True, 1780000000), (True, "1780000000"), (True, 1)],+)+def test_incremental_and_full_refresh_ranges(+ manager: MagicMock, endpoint: str, incremental: bool, watermark: int | str | None+) -> None:+ selector = "data" if endpoint == "tests" else "deploys"+ responses.get(BASE_URL + endpoint, json={selector: []})++ assert _rows(_source(manager, endpoint, incremental, watermark)) == []+ params = parse_qs(urlsplit(responses.calls[0].request.url).query)+ expected_start = int(watermark) if incremental and watermark is not None else None+ if endpoint == "tests":+ retention_start = int((NOW - timedelta(days=364)).timestamp())+ expected_start = max(expected_start or retention_start, retention_start)+ if expected_start is None:+ assert "start_timestamp" not in params+ else:+ assert params["start_timestamp"] == [str(expected_start)]+ assert len(responses.calls) == 1+ manager.save_state.assert_not_called()+++def test_validation_uses_one_cheap_request() -> None:+ responses.get(BASE_URL + "sites", json={"sites": []})+ assert validate_credentials("fake-key", "v1") == (True, None)+ assert len(responses.calls) == 1+ request = responses.calls[0].request+ assert parse_qs(urlsplit(request.url).query) == {"median": ["0"]}+ assert request.headers["Authorization"] == "Basic ZmFrZS1rZXk6eA=="++[email protected]("status", [401, 403])+def test_auth_errors_are_terminal_and_have_actionable_messages(manager: MagicMock, status: int) -> None:+ responses.get(+ BASE_URL + "sites",+ status=status,+ json={+ "status": "error",+ "message": "A valid API key is required. Check you have the correct API key for your team and your account is active.",+ },+ )+ valid, message = validate_credentials("fake-key", "v1")+ assert valid is False+ assert message is not None and "Check" in message and "API key" in message+ assert len(responses.calls) == 1+ with pytest.raises(HTTPError) as error:+ _rows(_source(manager, "sites"))+ mapped = [+ value for pattern, value in SpeedcurveSource().get_non_retryable_errors().items() if pattern in str(error.value)+ ]+ assert mapped == [message]+ assert len(responses.calls) == 2++[email protected]("status", [429, 500, 503])+def test_transient_errors_retry_without_becoming_invalid_credentials(status: int) -> None:+ responses.get(BASE_URL + "sites", status=status, json={"message": "Unavailable"}, headers={"Retry-After": "0"})+ with pytest.raises(RESTClientRetryableError):+ validate_credentials("fake-key", "v1")+ assert len(responses.calls) == 5+++def test_other_client_errors_propagate() -> None:+ responses.get(BASE_URL + "sites", status=422, json={"message": "Parameters are not valid."})+ with pytest.raises(HTTPError):+ validate_credentials("fake-key", "v1")+ assert len(responses.calls) == 1++[email protected]("endpoint", ["sites", "urls", "tests", "deploys", "notes", "budgets"])+def test_missing_collection_does_not_silently_empty_table(manager: MagicMock, endpoint: str) -> None:+ responses.get(BASE_URL + endpoint, json={"unexpected": []})+ with pytest.raises(ValueError, match="selector"):+ _rows(_source(manager, endpoint))+++def test_unknown_table_fails_before_network(manager: MagicMock) -> None:+ with pytest.raises(UnknownResourceError):+ _source(manager, "unknown")diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/speedcurve/tests/test_speedcurve_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/speedcurve/tests/test_speedcurve_source.pynew file mode 100644index 000000000000..ba9595f324c9--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/speedcurve/tests/test_speedcurve_source.py@@ -0,0 +1,19 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import build_default_sync_settings+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.speedcurve import (+ SpeedcurveSourceConfig,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.speedcurve.source import SpeedcurveSource+++def test_incremental_defaults_revisit_recent_records_and_merge_updates() -> None:+ schemas = SpeedcurveSource().get_schemas(+ SpeedcurveSourceConfig(api_key="fake-key"), team_id=1, names=["tests", "deploys", "budgets"]+ )+ settings = {schema.name: build_default_sync_settings(schema) for schema in schemas}+ for name in ("tests", "deploys"):+ assert settings[name]["sync_type"] == "incremental"+ assert settings[name]["incremental_field_lookback_seconds"] == 86400+ assert settings[name]["incremental_field_type"] == "integer"+ assert settings["budgets"]["sync_type"] == "full_refresh"+ assert "incremental_field_lookback_seconds" not in settings["budgets"]+ assert not any(schema.supports_append for schema in schemas)