: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 linearb import source (#71159)
Tom Owers8f4b42402f0f
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex 794864f84dd9..20de9e93f080 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -304,6 +304,7 @@ the row lists both.| less_annoying_crm | HTTP | requests | ✅ || lightspeed_retail | HTTP | requests | ✅ || linear | HTTP | requests | ✅ |+| linearb | HTTP | requests | ✅ || lever | HTTP | requests | ✅ || lingo_dev | HTTP | requests + `rest_source.RESTClient` | ✅ || linkedin_ads | HTTP (vendor SDK, RESTli) | linkedin-api (RestliClient) | ⚠️ |@@ -771,7 +772,6 @@ doesn't conflict with concurrent PRs.- lever- liana- lightfield-- linearb- lingo_dev- linkedin_pages- linnworksdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.pyindex 3f6b82737a89..bb85d4272e44 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs.py@@ -2490,7 +2490,7 @@ class LinearSourceConfig(config.Config):@config.configclass LinearbSourceConfig(config.Config):- pass+ api_key: str@config.configdiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/linearb/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/linearb/canonical_descriptions.pynew file mode 100644index 000000000000..1e22fa59b493--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/linearb/canonical_descriptions.py@@ -0,0 +1,65 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "teams": {+ "description": "Teams configured in LinearB, including their hierarchy and membership.",+ "docs_url": "https://docs.linearb.io/api-teams-v2/",+ "columns": {+ "id": "Unique identifier for the team.",+ "organization_id": "Identifier of the organization the team belongs to.",+ "name": "Team name.",+ "created_at": "When the team was created.",+ "initials": "Short initials shown for the team in the UI.",+ "color": "Display color assigned to the team.",+ "parent_id": "Identifier of the parent team, if this team is nested.",+ "contributors": "Contributors that belong to the team.",+ },+ },+ "users": {+ "description": "Users and their cross-platform contributor identity mapping in LinearB.",+ "docs_url": "https://docs.linearb.io/api-users/",+ "columns": {+ "id": "Unique identifier for the user.",+ "organization_id": "Identifier of the organization the user belongs to.",+ "name": "User's display name.",+ "email": "User's email address.",+ "avatar_url": "URL of the user's avatar image.",+ "created_at": "When the user was created.",+ "updated_at": "When the user was last updated.",+ "deleted_at": "When the user was deleted, if applicable.",+ "team_membership": "Teams the user is a member of.",+ "connected_users": "Platform users and contributors linked to this user's identity.",+ },+ },+ "services": {+ "description": "Services configured in LinearB and the repositories and paths mapped to each.",+ "docs_url": "https://docs.linearb.io/api-services/",+ "columns": {+ "id": "Unique identifier for the service.",+ "name": "Service name.",+ "paths": "Repositories and directory paths mapped to the service.",+ },+ },+ "deployments": {+ "description": "Deployments recorded in LinearB, used to compute deploy frequency, change failure rate, and MTTR.",+ "docs_url": "https://docs.linearb.io/api-deployments/",+ "columns": {+ "id": "Unique identifier for the deployment.",+ "repo_url": "Git repository the deployment came from.",+ "ref_name": "Deployed ref (branch or tag).",+ "stage": "Deployment stage/environment (premium feature).",+ "services": "Services associated with the deployment.",+ },+ },+ "measurements": {+ "description": "Organization-level Git/DORA metrics computed by LinearB, rolled up daily.",+ "docs_url": "https://docs.linearb.io/api-measurements-v2/",+ "columns": {+ "after": "Start date (inclusive) of the daily metric window.",+ "before": "End date of the daily metric window.",+ "organization_id": "Identifier of the organization the metrics belong to.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/linearb/linearb.py b/products/warehouse_sources/backend/temporal/data_imports/sources/linearb/linearb.pynew file mode 100644index 000000000000..95dbfabdff5e--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/linearb/linearb.py@@ -0,0 +1,249 @@+import re+import dataclasses+from collections.abc import Iterator+from datetime import UTC, datetime, timedelta+from typing import Any++import requests+from structlog.types import FilteringBoundLogger+from tenacity import retry, retry_if_exception_type, stop_after_attempt, wait_exponential_jitter++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceResponse+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.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.linearb.settings import (+ LINEARB_ENDPOINTS,+ MEASUREMENT_METRICS,+ MEASUREMENTS_DEFAULT_WINDOW_DAYS,+ LinearbEndpointConfig,+)++LINEARB_BASE_URL = "https://public-api.linearb.io"++# LinearB caps every endpoint at 60 calls/minute. We stay well under it with a single sequential+# paginator per sync, but bound retries so a sustained 429 fails cleanly rather than looping.+PAGE_TIMEOUT_SECONDS = 60++_NON_COLUMN_SAFE = re.compile(r"[^0-9a-zA-Z_]+")+++class LinearbRetryableError(Exception):+ pass+++class LinearbResumeConfig:+ # Offset of the next page to fetch for list endpoints. Measurements is a single windowed query+ # and does not resume.+ offset: int = 0+++def _get_headers(api_key: str) -> dict[str, str]:+ return {+ "x-api-key": api_key,+ "Content-Type": "application/json",+ "Accept": "application/json",+ }+++def _sanitize_metric_key(key: str) -> str:+ """Normalize a LinearB metric key (e.g. "branch.computed.cycle_time:p75") into a column-safe name."""+ return _NON_COLUMN_SAFE.sub("_", key).strip("_")+++@retry(+ retry=retry_if_exception_type(+ (+ LinearbRetryableError,+ requests.ReadTimeout,+ requests.ConnectionError,+ requests.exceptions.ChunkedEncodingError,+ )+ ),+ stop=stop_after_attempt(5),+ wait=wait_exponential_jitter(initial=1, max=30),+ reraise=True,+)+def _request(+ session: requests.Session,+ method: str,+ url: str,+ headers: dict[str, str],+ logger: FilteringBoundLogger,+ params: dict[str, Any] | None = None,+ json_body: dict[str, Any] | None = None,+) -> requests.Response:+ response = session.request(+ method, url, headers=headers, params=params, json=json_body, timeout=PAGE_TIMEOUT_SECONDS+ )++ # Honor the per-endpoint 60/min rate limit and transient server errors by retrying.+ if response.status_code == 429 or response.status_code >= 500:+ raise LinearbRetryableError(f"LinearB API error (retryable): status={response.status_code}, url={url}")++ if not response.ok:+ logger.error(f"LinearB API error: status={response.status_code}, body={response.text}, url={url}")+ response.raise_for_status()++ return response+++def validate_credentials(api_key: str) -> bool:+ # The teams endpoint is available on every plan, so it is the cheapest genuine token probe. A+ # bad or missing key returns 403 from LinearB's API gateway; a valid key returns 200.+ url = f"{LINEARB_BASE_URL}/api/v2/teams"+ try:+ # allow_redirects=False: a redirect would otherwise forward the x-api-key header to the+ # redirect target; LinearB's API never legitimately redirects.+ response = make_tracked_session(allow_redirects=False).get(+ url, headers=_get_headers(api_key), params={"page_size": 1}, timeout=10+ )+ return response.status_code == 200+ except Exception:+ return False+++def _iter_list_rows(+ session: requests.Session,+ headers: dict[str, str],+ logger: FilteringBoundLogger,+ config: LinearbEndpointConfig,+ resumable_source_manager: ResumableSourceManager[LinearbResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ """Page through a wrapped `{total, items}` list endpoint using offset pagination.++ Termination is driven by the response's `total` count first (some endpoints ignore paging params+ and return everything in one page), then by an empty or short page, so an endpoint that silently+ ignores `offset` can't loop forever.+ """+ url = f"{LINEARB_BASE_URL}{config.path}"+ page_size = config.page_size++ resume = resumable_source_manager.load_state() if resumable_source_manager.can_resume() else None+ offset = resume.offset if resume else 0+ fetched = offset++ while True:+ params: dict[str, Any] = {}+ if config.page_size_param and page_size:+ params[config.page_size_param] = page_size+ params["offset"] = offset++ response = _request(session, "GET", url, headers, logger, params=params)+ payload = response.json()+ items = payload.get(config.data_selector, []) if config.data_selector else payload+ if not items:+ break++ yield items+ fetched += len(items)++ # Save offset AFTER yielding so a crash re-yields the last page (merge dedupes on the primary+ # key) rather than skipping it.+ if config.page_size_param and page_size:+ resumable_source_manager.save_state(LinearbResumeConfig(offset=fetched))++ total = payload.get("total") if isinstance(payload, dict) else None+ if not config.page_size_param or not page_size:+ break+ if total is not None and fetched >= total:+ break+ if len(items) < page_size:+ break++ offset = fetched+++def _measurements_body() -> dict[str, Any]:+ """Build the Measurements V2 request body for an organization-level daily rollup.++ Grouping by organization needs no team/repository IDs, so it works for any account without extra+ configuration. The window is the trailing `MEASUREMENTS_DEFAULT_WINDOW_DAYS` days.+ """+ before = datetime.now(UTC).date()+ after = before - timedelta(days=MEASUREMENTS_DEFAULT_WINDOW_DAYS)+ requested_metrics = [{"name": name, "agg": agg} if agg else {"name": name} for name, agg in MEASUREMENT_METRICS]+ return {+ "requested_metrics": requested_metrics,+ "group_by": "organization",+ "roll_up": "1d",+ "time_ranges": [{"after": after.isoformat(), "before": before.isoformat()}],+ }+++def _iter_measurements_rows(+ session: requests.Session,+ headers: dict[str, str],+ logger: FilteringBoundLogger,+) -> Iterator[list[dict[str, Any]]]:+ """Fetch the daily measurements windows and flatten each metric object into a row.++ The response is an array of `{after, before, metrics: [...]}` windows; each metrics object carries+ the group id (`organization_id`) plus one key per requested metric. We stamp the window's+ `after`/`before` onto every flattened row so they can be partitioned and deduped by day.+ """+ url = f"{LINEARB_BASE_URL}/api/v2/measurements"+ response = _request(session, "POST", url, headers, logger, json_body=_measurements_body())++ # No data for the window returns 204; treat it as an empty sync.+ if response.status_code == 204 or not response.content:+ return++ windows = response.json()+ rows: list[dict[str, Any]] = []+ for window in windows:+ after = window.get("after")+ before = window.get("before")+ for metric in window.get("metrics", []):+ row = {"after": after, "before": before}+ for key, value in metric.items():+ row[_sanitize_metric_key(key)] = value+ rows.append(row)++ if rows:+ yield rows+++def get_rows(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[LinearbResumeConfig],+) -> Iterator[list[dict[str, Any]]]:+ config = LINEARB_ENDPOINTS[endpoint]+ headers = _get_headers(api_key)+ # allow_redirects=False: a redirect would otherwise forward the x-api-key header to the+ # redirect target; LinearB's API never legitimately redirects.+ session = make_tracked_session(allow_redirects=False)++ if config.method == "POST":+ yield from _iter_measurements_rows(session, headers, logger)+ return++ yield from _iter_list_rows(session, headers, logger, config, resumable_source_manager)+++def linearb_source(+ api_key: str,+ endpoint: str,+ logger: FilteringBoundLogger,+ resumable_source_manager: ResumableSourceManager[LinearbResumeConfig],+) -> SourceResponse:+ config = LINEARB_ENDPOINTS[endpoint]++ return SourceResponse(+ name=endpoint,+ items=lambda: get_rows(+ api_key=api_key,+ endpoint=endpoint,+ logger=logger,+ resumable_source_manager=resumable_source_manager,+ ),+ primary_keys=config.primary_keys,+ sort_mode="asc",+ partition_count=1,+ partition_size=1,+ partition_mode="datetime" if config.partition_key else None,+ partition_format=config.partition_format if config.partition_key else None,+ partition_keys=[config.partition_key] if config.partition_key else None,+ )diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/linearb/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/linearb/settings.pynew file mode 100644index 000000000000..8376a73cd9c9--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/linearb/settings.py@@ -0,0 +1,99 @@+from dataclasses import dataclass, field+from typing import Literal, Optional++from products.warehouse_sources.backend.types import IncrementalField++# Curated set of Git/DORA metrics pulled from the Measurements V2 endpoint. Names are taken from the+# public metric glossary; each entry pairs a metric with the aggregation LinearB documents for it+# (duration/size metrics take a percentile, counts take no agg). The response keys each value as+# "<name>:<agg>" (or just "<name>" for counts), which the transport flattens into columns.+MEASUREMENT_METRICS: tuple[tuple[str, Optional[str]], ...] = (+ ("branch.computed.cycle_time", "p75"),+ ("branch.time_to_pr", "p75"),+ ("branch.time_to_review", "p75"),+ ("branch.review_time", "p75"),+ ("branch.time_to_prod", "p75"),+ ("pr.merged.size", "avg"),+ ("pr.merged", None),+ ("pr.new", None),+ ("pr.reviews", None),+ ("pr.merged.without.review.count", None),+ ("releases.count", None),+ ("commit.total.count", None),+ ("commit.total_changes", None),+ ("commit.activity.new_work.count", None),+ ("commit.activity.refactor.count", None),+ ("commit.activity.rework.count", None),+)++# Default window (in days) pulled on every measurements sync. Measurements are a computed time series;+# a full refresh re-pulls the window each run and merge dedupes on [after, organization_id].+MEASUREMENTS_DEFAULT_WINDOW_DAYS = 90+++@dataclass+class LinearbEndpointConfig:+ name: str+ path: str+ method: Literal["GET", "POST"] = "GET"+ # Key inside the wrapped `{total, items}` response holding the row array. `None` for the+ # measurements endpoint, which returns a bare array of time-window objects.+ data_selector: Optional[str] = "items"+ # Name of the page-size query param this endpoint accepts (`page_size` vs `limit`), and its cap.+ # `None` when the endpoint documents no pagination params (a single response holds every row).+ page_size_param: Optional[str] = None+ page_size: Optional[int] = None+ primary_keys: list[str] = field(default_factory=lambda: ["id"])+ # Stable creation-time field used for datetime partitioning. Never an updated_at-style field,+ # which would rewrite partitions on every sync.+ partition_key: Optional[str] = None+ partition_format: Literal["month", "week", "day"] = "month"+ should_sync_default: bool = True+ # Server-side timestamp filter params are documented for deployments (after/before) but left+ # unverified against a live account, so every endpoint currently ships full refresh only.+ incremental_fields: list[IncrementalField] = field(default_factory=list)+++LINEARB_ENDPOINTS: dict[str, LinearbEndpointConfig] = {+ "teams": LinearbEndpointConfig(+ name="teams",+ path="/api/v2/teams",+ page_size_param="page_size",+ page_size=50,+ partition_key="created_at",+ ),+ "users": LinearbEndpointConfig(+ name="users",+ path="/api/v1/users",+ page_size_param="page_size",+ page_size=50,+ partition_key="created_at",+ ),+ "services": LinearbEndpointConfig(+ name="services",+ path="/api/v1/services",+ ),+ "deployments": LinearbEndpointConfig(+ name="deployments",+ path="/api/v1/deployments",+ page_size_param="limit",+ page_size=100,+ ),+ # Measurements is a POST metric query rather than a list endpoint. It is plan-gated (LinearB+ # Business/Enterprise only), so it is off by default; users on an eligible plan opt in.+ "measurements": LinearbEndpointConfig(+ name="measurements",+ path="/api/v2/measurements",+ method="POST",+ data_selector=None,+ primary_keys=["after", "organization_id"],+ partition_key="after",+ should_sync_default=False,+ ),+}++ENDPOINTS = tuple(LINEARB_ENDPOINTS.keys())++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ name: config.incremental_fields for name, config in LINEARB_ENDPOINTS.items()+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/linearb/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/linearb/source.pyindex 860268edbc63..05607c32c561 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/linearb/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/linearb/source.py@@ -1,19 +1,43 @@-from typing import cast+from typing import Optional, castfrom posthog.schema import (DataWarehouseSourceCategory,ExternalDataSourceType as SchemaExternalDataSourceType,+ ReleaseStatus,SourceConfig,+ SourceFieldInputConfig,+ SourceFieldInputConfigType,)-from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import FieldType, SimpleSource+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, 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 SourceSchemafrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import LinearbSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.linearb.linearb import (+ LinearbResumeConfig,+ linearb_source,+ validate_credentials as validate_linearb_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.linearb.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+ LINEARB_ENDPOINTS,+)from products.warehouse_sources.backend.types import ExternalDataSourceType@SourceRegistry.register-class LinearbSource(SimpleSource[LinearbSourceConfig]):+class LinearbSource(ResumableSource[LinearbSourceConfig, LinearbResumeConfig]):+ lists_tables_without_credentials = True # static endpoint catalog — safe for public docs+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.LINEARB@@ -24,7 +48,98 @@ class LinearbSource(SimpleSource[LinearbSourceConfig]):name=SchemaExternalDataSourceType.LINEARB,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="LinearB",+ releaseStatus=ReleaseStatus.ALPHA,+ caption="""Enter your LinearB API key to pull your engineering intelligence and DORA metrics into the PostHog Data warehouse.++Generate an API token from **Settings → API Tokens** in your [LinearB account](https://app.linearb.io/). The token grants access to your organization's teams, users, services, deployments, and computed metrics.++The **Measurements** table is only available on LinearB Business and Enterprise plans and is off by default — enable it if your plan includes API metrics access.""",iconPath="/static/services/linearb.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ docsUrl="https://posthog.com/docs/cdp/sources/linearb",+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_key",+ label="API key",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.linearb.canonical_descriptions import (+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ # LinearB's API gateway returns 403 for a missing, invalid, or revoked key (there is no+ # distinct 401). Retrying can never satisfy a credential problem, so stop the sync. Match+ # the stable status text and base host, not the per-request path/query.+ "403 Client Error: Forbidden for url: https://public-api.linearb.io": "Your LinearB API key is invalid, revoked, or lacks access to this data (the Measurements table needs a Business or Enterprise plan). Generate a new token in your LinearB account settings, then reconnect.",+ }++ def get_schemas(+ self,+ config: LinearbSourceConfig,+ team_id: int,+ with_counts: bool = False,+ names: list[str] | None = None,+ force_refresh: bool = False,+ ) -> list[SourceSchema]:+ def _description(endpoint: str) -> str | None:+ if endpoint == "measurements":+ return (+ "Organization-level Git/DORA metrics (cycle time, PR throughput, deploy frequency) "+ "rolled up daily for the last 90 days. Requires a LinearB Business or Enterprise plan"+ )+ return None++ def _build_schema(endpoint: str) -> SourceSchema:+ endpoint_config = LINEARB_ENDPOINTS[endpoint]+ return SourceSchema(+ name=endpoint,+ supports_incremental=False,+ supports_append=False,+ incremental_fields=INCREMENTAL_FIELDS.get(endpoint, []),+ should_sync_default=endpoint_config.should_sync_default,+ detected_primary_keys=endpoint_config.primary_keys,+ description=_description(endpoint),+ )++ schemas = [_build_schema(endpoint) for endpoint in ENDPOINTS]+ if names is not None:+ names_set = set(names)+ schemas = [s for s in schemas if s.name in names_set]+ return schemas++ def validate_credentials(+ self, config: LinearbSourceConfig, team_id: int, schema_name: Optional[str] = None+ ) -> tuple[bool, str | None]:+ if validate_linearb_credentials(config.api_key):+ return True, None++ return False, "Invalid LinearB API key"++ def get_resumable_source_manager(self, inputs: SourceInputs) -> ResumableSourceManager[LinearbResumeConfig]:+ return ResumableSourceManager[LinearbResumeConfig](inputs, LinearbResumeConfig)++ def source_for_pipeline(+ self,+ config: LinearbSourceConfig,+ resumable_source_manager: ResumableSourceManager[LinearbResumeConfig],+ inputs: SourceInputs,+ ) -> SourceResponse:+ return linearb_source(+ api_key=config.api_key,+ endpoint=inputs.schema_name,+ logger=inputs.logger,+ resumable_source_manager=resumable_source_manager,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/linearb/tests/test_linearb.py b/products/warehouse_sources/backend/temporal/data_imports/sources/linearb/tests/test_linearb.pynew file mode 100644index 000000000000..b9f1eab93138--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/linearb/tests/test_linearb.py@@ -0,0 +1,202 @@+from typing import Any++import pytest+from unittest import mock++from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.linearb.linearb import (+ LinearbResumeConfig,+ _get_headers,+ _iter_list_rows,+ _iter_measurements_rows,+ _sanitize_metric_key,+ linearb_source,+ validate_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.linearb.settings import (+ ENDPOINTS,+ LINEARB_ENDPOINTS,+ LinearbEndpointConfig,+)+++def _response(status_code: int = 200, payload: Any = None, content: bytes = b"x") -> mock.MagicMock:+ response = mock.MagicMock()+ response.status_code = status_code+ response.ok = status_code < 400+ response.content = content+ response.json.return_value = payload+ return response+++def _session_returning(responses: list[mock.MagicMock]) -> mock.MagicMock:+ session = mock.MagicMock()+ session.request.side_effect = responses+ return session+++def _list_config(page_size: int = 2) -> LinearbEndpointConfig:+ return LinearbEndpointConfig(name="teams", path="/api/v2/teams", page_size_param="page_size", page_size=page_size)+++class TestHeaders:+ def test_sets_api_key_header(self) -> None:+ headers = _get_headers("secret-key")+ assert headers["x-api-key"] == "secret-key"+ assert headers["Content-Type"] == "application/json"+++class TestSanitizeMetricKey:+ @pytest.mark.parametrize(+ ("raw", "expected"),+ [+ ("branch.computed.cycle_time:p75", "branch_computed_cycle_time_p75"),+ ("releases.count", "releases_count"),+ ("organization_id", "organization_id"),+ ("pr.merged.without.review.count", "pr_merged_without_review_count"),+ ],+ )+ def test_sanitize(self, raw: str, expected: str) -> None:+ assert _sanitize_metric_key(raw) == expected+++class TestValidateCredentials:+ @pytest.mark.parametrize(+ ("status_code", "expected"),+ [(200, True), (403, False), (401, False), (500, False)],+ )+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.linearb.linearb.make_tracked_session")+ def test_status_mapping(self, mock_make_session: mock.MagicMock, status_code: int, expected: bool) -> None:+ session = mock.MagicMock()+ session.get.return_value = _response(status_code=status_code)+ mock_make_session.return_value = session++ assert validate_credentials("key") is expected++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.linearb.linearb.make_tracked_session")+ def test_network_error_is_invalid(self, mock_make_session: mock.MagicMock) -> None:+ session = mock.MagicMock()+ session.get.side_effect = Exception("boom")+ mock_make_session.return_value = session++ assert validate_credentials("key") is False+++class TestListPagination:+ def _manager(self) -> mock.MagicMock:+ manager = mock.MagicMock(spec=ResumableSourceManager)+ manager.can_resume.return_value = False+ return manager++ def test_paginates_until_total_reached(self) -> None:+ # total=3 with page_size=2 -> a full page then a final short page.+ responses = [+ _response(payload={"total": 3, "items": [{"id": 1}, {"id": 2}]}),+ _response(payload={"total": 3, "items": [{"id": 3}]}),+ ]+ session = _session_returning(responses)++ pages = list(_iter_list_rows(session, {}, mock.MagicMock(), _list_config(), self._manager()))++ assert [row["id"] for page in pages for row in page] == [1, 2, 3]+ assert session.request.call_count == 2++ def test_stops_when_total_covered_without_extra_request(self) -> None:+ # A single full page whose total says we already have everything must not fetch again.+ responses = [_response(payload={"total": 2, "items": [{"id": 1}, {"id": 2}]})]+ session = _session_returning(responses)++ pages = list(_iter_list_rows(session, {}, mock.MagicMock(), _list_config(), self._manager()))++ assert [row["id"] for page in pages for row in page] == [1, 2]+ assert session.request.call_count == 1++ def test_stops_on_empty_page(self) -> None:+ session = _session_returning([_response(payload={"total": 0, "items": []})])+ pages = list(_iter_list_rows(session, {}, mock.MagicMock(), _list_config(), self._manager()))+ assert pages == []++ def test_single_page_endpoint_without_paging_params_fetches_once(self) -> None:+ # services documents no paging params; even a large page must not loop forever.+ config = LinearbEndpointConfig(name="services", path="/api/v1/services")+ session = _session_returning([_response(payload={"total": 5, "items": [{"id": i} for i in range(5)]})])++ pages = list(_iter_list_rows(session, {}, mock.MagicMock(), config, self._manager()))++ assert len(pages) == 1+ assert session.request.call_count == 1++ def test_saves_offset_after_yielding_page(self) -> None:+ responses = [+ _response(payload={"total": 3, "items": [{"id": 1}, {"id": 2}]}),+ _response(payload={"total": 3, "items": [{"id": 3}]}),+ ]+ manager = self._manager()+ list(_iter_list_rows(_session_returning(responses), {}, mock.MagicMock(), _list_config(), manager))++ # State is saved after the first (non-terminal) page carrying the next offset.+ saved = [call.args[0] for call in manager.save_state.call_args_list]+ assert LinearbResumeConfig(offset=2) in saved++ def test_resumes_from_saved_offset(self) -> None:+ manager = self._manager()+ manager.can_resume.return_value = True+ manager.load_state.return_value = LinearbResumeConfig(offset=2)+ session = _session_returning([_response(payload={"total": 3, "items": [{"id": 3}]})])++ list(_iter_list_rows(session, {}, mock.MagicMock(), _list_config(), manager))++ # The first (only) request must start at the saved offset, not 0.+ assert session.request.call_args.kwargs["params"]["offset"] == 2+++class TestMeasurements:+ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.linearb.linearb._measurements_body")+ def test_flattens_windows_into_rows(self, mock_body: mock.MagicMock) -> None:+ mock_body.return_value = {}+ windows = [+ {+ "after": "2024-01-01",+ "before": "2024-01-02",+ "metrics": [{"organization_id": 7, "releases.count": 3, "branch.computed.cycle_time:p75": 100}],+ }+ ]+ session = _session_returning([_response(payload=windows)])++ pages = list(_iter_measurements_rows(session, {}, mock.MagicMock()))++ assert len(pages) == 1+ row = pages[0][0]+ assert row["after"] == "2024-01-01"+ assert row["before"] == "2024-01-02"+ assert row["organization_id"] == 7+ assert row["releases_count"] == 3+ assert row["branch_computed_cycle_time_p75"] == 100++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.linearb.linearb._measurements_body")+ def test_no_content_yields_nothing(self, mock_body: mock.MagicMock) -> None:+ mock_body.return_value = {}+ session = _session_returning([_response(status_code=204, content=b"")])++ assert list(_iter_measurements_rows(session, {}, mock.MagicMock())) == []+++class TestLinearbSource:+ @pytest.mark.parametrize("endpoint", ENDPOINTS)+ def test_source_response_matches_endpoint_config(self, endpoint: str) -> None:+ response = linearb_source(+ api_key="key",+ endpoint=endpoint,+ logger=mock.MagicMock(),+ resumable_source_manager=mock.MagicMock(spec=ResumableSourceManager),+ )+ config = LINEARB_ENDPOINTS[endpoint]++ assert response.name == endpoint+ assert response.primary_keys == config.primary_keys+ assert response.sort_mode == "asc"+ if config.partition_key:+ assert response.partition_mode == "datetime"+ assert response.partition_keys == [config.partition_key]+ else:+ assert response.partition_mode is Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/linearb/tests/test_linearb_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/linearb/tests/test_linearb_source.pynew file mode 100644index 000000000000..5a5babd60099--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/linearb/tests/test_linearb_source.py@@ -0,0 +1,138 @@+from typing import Any++import pytest+from unittest import mock++from posthog.schema import ReleaseStatus, SourceFieldInputConfig, SourceFieldInputConfigType++from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline.typings import SourceInputs+from products.warehouse_sources.backend.temporal.data_imports.sources.common.resumable import ResumableSourceManager+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs import LinearbSourceConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.linearb.linearb import LinearbResumeConfig+from products.warehouse_sources.backend.temporal.data_imports.sources.linearb.settings import ENDPOINTS+from products.warehouse_sources.backend.temporal.data_imports.sources.linearb.source import LinearbSource+from products.warehouse_sources.backend.types import ExternalDataSourceType+++def _make_inputs(**overrides: Any) -> SourceInputs:+ defaults: dict[str, Any] = {+ "schema_name": "teams",+ "schema_id": "schema-1",+ "source_id": "source-1",+ "team_id": 123,+ "should_use_incremental_field": False,+ "db_incremental_field_last_value": None,+ "db_incremental_field_earliest_value": None,+ "incremental_field": None,+ "incremental_field_type": None,+ "job_id": "job-1",+ "logger": mock.MagicMock(),+ "reset_pipeline": False,+ }+ defaults.update(overrides)+ return SourceInputs(**defaults)+++class TestLinearbSource:+ def setup_method(self) -> None:+ self.source = LinearbSource()+ self.team_id = 123+ self.config = LinearbSourceConfig(api_key="test-key")++ def test_source_type(self) -> None:+ assert self.source.source_type == ExternalDataSourceType.LINEARB++ def test_get_source_config(self) -> None:+ config = self.source.get_source_config++ assert config.name.value == "Linearb"+ assert config.label == "LinearB"+ # A finished source must ship visible, not hidden behind unreleasedSource.+ assert config.unreleasedSource is None+ assert config.releaseStatus == ReleaseStatus.ALPHA+ assert config.iconPath == "/static/services/linearb.png"+ assert config.docsUrl == "https://posthog.com/docs/cdp/sources/linearb"++ assert len(config.fields) == 1+ api_key_field = config.fields[0]+ assert isinstance(api_key_field, SourceFieldInputConfig)+ assert api_key_field.name == "api_key"+ assert api_key_field.type == SourceFieldInputConfigType.PASSWORD+ assert api_key_field.required is True+ assert api_key_field.secret is True++ def test_lists_tables_without_credentials(self) -> None:+ # get_schemas is a static catalog with no I/O, so the public docs render the table list.+ assert self.source.lists_tables_without_credentials is True+ assert len(self.source.get_documented_tables()) == len(ENDPOINTS)++ def test_non_retryable_errors_cover_forbidden(self) -> None:+ # LinearB's gateway returns 403 for any bad/missing key (there is no distinct 401).+ errors = self.source.get_non_retryable_errors()+ assert any("403 Client Error" in key for key in errors)++ def test_get_schemas_all_full_refresh(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id)++ assert {s.name for s in schemas} == set(ENDPOINTS)+ assert all(not s.supports_incremental for s in schemas)+ assert all(not s.supports_append for s in schemas)++ def test_measurements_is_opt_in(self) -> None:+ schemas = {s.name: s for s in self.source.get_schemas(self.config, self.team_id)}+ # Measurements is plan-gated (Business/Enterprise), so it must not be enabled by default.+ assert schemas["measurements"].should_sync_default is False+ assert schemas["measurements"].detected_primary_keys == ["after", "organization_id"]+ # The entity endpoints are on by default.+ assert schemas["teams"].should_sync_default is True++ def test_get_schemas_filtered_by_names(self) -> None:+ schemas = self.source.get_schemas(self.config, self.team_id, names=["teams"])+ assert [s.name for s in schemas] == ["teams"]++ def test_get_schemas_unknown_name_returns_empty(self) -> None:+ assert self.source.get_schemas(self.config, self.team_id, names=["nonexistent"]) == []++ @pytest.mark.parametrize(+ ("mock_return", "expected_valid", "expected_message"),+ [+ (True, True, None),+ (False, False, "Invalid LinearB API key"),+ ],+ )+ @mock.patch(+ "products.warehouse_sources.backend.temporal.data_imports.sources.linearb.source.validate_linearb_credentials"+ )+ def test_validate_credentials(+ self,+ mock_validate: mock.MagicMock,+ mock_return: bool,+ expected_valid: bool,+ expected_message: str | None,+ ) -> None:+ mock_validate.return_value = mock_return++ is_valid, error_message = self.source.validate_credentials(self.config, self.team_id)++ assert is_valid is expected_valid+ assert error_message == expected_message+ mock_validate.assert_called_once_with("test-key")++ def test_get_resumable_source_manager_bound_to_resume_config(self) -> None:+ manager = self.source.get_resumable_source_manager(_make_inputs())+ assert isinstance(manager, ResumableSourceManager)+ assert manager._data_class is LinearbResumeConfig++ @mock.patch("products.warehouse_sources.backend.temporal.data_imports.sources.linearb.source.linearb_source")+ def test_source_for_pipeline_plumbs_arguments(self, mock_source: mock.MagicMock) -> None:+ inputs = _make_inputs(schema_name="deployments", team_id=99, job_id="job-xyz")+ manager = mock.MagicMock(spec=ResumableSourceManager)++ self.source.source_for_pipeline(self.config, manager, inputs)++ mock_source.assert_called_once_with(+ api_key="test-key",+ endpoint="deployments",+ logger=inputs.logger,+ resumable_source_manager=manager,+ )