: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(warehouse): sync depot ci job attempts (#106073)
Raúl Negrón-Oteroa6cc7e27f7db
diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.mdindex d5e98137b270..a6990b62b73e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/SOURCES.md@@ -233,6 +233,7 @@ the row lists both.| deepgram | HTTP | requests | ✅ || deepsource | HTTP (GraphQL) | requests | ✅ || deno_deploy | HTTP | requests | ✅ |+| depot | HTTP (Connect RPC) | requests | ✅ || descope | HTTP | requests + `rest_source.RESTClient` | ✅ || devin_ai | HTTP | requests | ✅ || ding_connect | HTTP | requests | ✅ |@@ -985,7 +986,6 @@ doesn't conflict with concurrent PRs.- deelflows- demodesk- deno_deploy-- depot- deputy- develocity- dialpaddiff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/depot/canonical_descriptions.py b/products/warehouse_sources/backend/temporal/data_imports/sources/depot/canonical_descriptions.pynew file mode 100644index 000000000000..ec5b79b8ec93--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/depot/canonical_descriptions.py@@ -0,0 +1,45 @@+from products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (+ CanonicalDescriptions,+)++CANONICAL_DESCRIPTIONS: CanonicalDescriptions = {+ "job_attempts": {+ "description": (+ "One row per attempt of a Depot CI job, with the context of its run, workflow, and job. "+ "Jobs that never ran, such as skipped jobs and matrix expansion placeholders, have no rows."+ ),+ "docs_url": "https://depot.dev/docs/api/ci/reference",+ "columns": {+ "run_id": "Unique identifier of the Depot CI run.",+ "run_workflow_count": "Number of workflows the run started.",+ "repo": "GitHub repository of the run, as owner/name.",+ "ref": "Git ref the run was triggered for.",+ "sha": "Commit SHA of the run.",+ "head_sha": "Head commit SHA reported for the run.",+ "trigger": "Event that triggered the run.",+ "run_status": "Terminal status of the run: finished, failed, or cancelled.",+ "run_created_at": "Time the run was created, as an RFC 3339 timestamp.",+ "run_started_at": "Time the run started, as an RFC 3339 timestamp.",+ "run_finished_at": "Time the run finished, as an RFC 3339 timestamp.",+ "workflow_id": "Unique identifier of the workflow within the run.",+ "workflow_name": "Name of the workflow.",+ "workflow_path": "Path of the workflow file in the repository.",+ "workflow_status": "Status of the workflow.",+ "workflow_created_at": "Time the workflow was created, as an RFC 3339 timestamp.",+ "workflow_started_at": "Time the workflow started, as an RFC 3339 timestamp.",+ "workflow_finished_at": "Time the workflow finished, as an RFC 3339 timestamp.",+ "job_id": "Unique identifier of the job.",+ "job_key": "Key of the job, as workflow file and job ID, for example ci-backend.yml:turbo-tests:matrix-38 for a matrix cell.",+ "job_display_name": "Human-readable job name, including matrix values.",+ "job_status": "Status of the job: finished, failed, cancelled or skipped.",+ "job_started_at": "Time the job started, as an RFC 3339 timestamp.",+ "job_finished_at": "Time the job finished, as an RFC 3339 timestamp.",+ "attempt_id": "Unique identifier of the job attempt.",+ "attempt": "Attempt number of the job.",+ "attempt_status": "Status of the attempt: finished, failed or cancelled.",+ "attempt_started_at": "Time the attempt started, as an RFC 3339 timestamp.",+ "attempt_finished_at": "Time the attempt finished, as an RFC 3339 timestamp.",+ "sandbox_id": "Identifier of the sandbox that ran the attempt.",+ },+ },+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/depot/depot.py b/products/warehouse_sources/backend/temporal/data_imports/sources/depot/depot.pynew file mode 100644index 000000000000..96ad1d8c2774--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/depot/depot.py@@ -0,0 +1,208 @@+import datetime as dt+from collections.abc import Iterator+from typing import Any++from requests import Response, Session+from structlog.types import FilteringBoundLogger++from products.warehouse_sources.backend.temporal.data_imports.sources.common.datetime_utils import parse_datetime_value+from products.warehouse_sources.backend.temporal.data_imports.sources.common.http import (+ DEFAULT_RETRY,+ make_tracked_session,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.depot.settings import (+ JOB_ATTEMPTS,+ PRIMARY_KEY,+ RUN_CREATED_AT,+)++JSONObject = dict[str, Any]++DEPOT_CI_SERVICE_URL = "https://api.depot.dev/depot.ci.v1.CIService"+REQUEST_TIMEOUT_SECONDS = 60+LIST_RUNS_PAGE_SIZE = 200+IN_FLIGHT_STATUSES = ["queued", "running"]+TERMINAL_STATUSES = ["finished", "failed", "cancelled"]+# Depot can leave a run in `queued` and never start it. A queued run older than this counts as stuck,+# so it does not hold the sync horizon back. A running run always holds it, because its jobs time out.+QUEUED_MAX_AGE = dt.timedelta(hours=6)++# Connect sends every RPC as a POST. Every RPC this source calls is a read, so a retry is as safe as+# a retried GET.+_DEPOT_RETRY = DEFAULT_RETRY.new(allowed_methods=frozenset(DEFAULT_RETRY.allowed_methods or ()) | {"POST"})+++def _make_session(api_token: str) -> Session:+ return make_tracked_session(+ headers={"Authorization": f"Bearer {api_token}"},+ retry=_DEPOT_RETRY,+ redact_values=(api_token,),+ )+++def _post(session: Session, method: str, body: JSONObject) -> Response:+ return session.post(f"{DEPOT_CI_SERVICE_URL}/{method}", json=body, timeout=REQUEST_TIMEOUT_SECONDS)+++def _call(session: Session, method: str, body: JSONObject) -> JSONObject:+ response = _post(session, method, body)+ response.raise_for_status()+ return response.json()+++def _parse_timestamp(value: dt.datetime | str) -> dt.datetime:+ parsed = parse_datetime_value(value)+ if parsed is None:+ raise ValueError(f"Depot returned an unparseable timestamp: {value!r}")+ return parsed+++def _list_runs(session: Session, repository: str, statuses: list[str]) -> Iterator[JSONObject]:+ body: JSONObject = {"repo": repository, "status": statuses, "pageSize": LIST_RUNS_PAGE_SIZE}+ while True:+ page = _call(session, "ListRuns", body)+ yield from page.get("runs", [])+ next_page_token = page.get("nextPageToken")+ if not next_page_token:+ return+ body = {**body, "pageToken": next_page_token}+++# The sync only takes runs created before every recent in-flight run, so the watermark never passes+# a run that has not finished and each run is fetched once, after it is terminal. A job that is+# retried after its run was synced is therefore never picked up.+def _in_flight_horizon(session: Session, repository: str, now: dt.datetime) -> dt.datetime:+ horizon = now+ for run in _list_runs(session, repository, IN_FLIGHT_STATUSES):+ created_at = _parse_timestamp(run["createdAt"])+ if run["status"] == "running" or created_at > now - QUEUED_MAX_AGE:+ horizon = min(horizon, created_at)+ return horizon+++def _runs_to_sync(+ session: Session, repository: str, created_after: dt.datetime | None, created_before: dt.datetime+) -> list[JSONObject]:+ runs: list[JSONObject] = []+ # ListRuns has no time filter but returns terminal runs newest first, so the walk stops at the+ # first run at or before the lower bound, and reversing the walk yields the runs oldest first.+ for run in _list_runs(session, repository, TERMINAL_STATUSES):+ created_at = _parse_timestamp(run["createdAt"])+ if created_after is not None and created_at <= created_after:+ break+ if created_at < created_before:+ runs.append(run)+ return runs[::-1]+++def _attempt_rows(run: JSONObject, workflow: JSONObject, run_workflow_count: int) -> list[JSONObject]:+ shared_columns = {+ "run_id": run["runId"],+ "run_workflow_count": run_workflow_count,+ "repo": workflow.get("repo"),+ "ref": workflow.get("ref"),+ "sha": workflow.get("sha"),+ "head_sha": workflow.get("headSha"),+ "trigger": workflow.get("trigger"),+ "run_status": workflow.get("runStatus"),+ # The listing's value, so the incremental cursor stays in the clock the listing walk compares.+ "run_created_at": run["createdAt"],+ "run_started_at": workflow.get("runStartedAt"),+ "run_finished_at": workflow.get("runFinishedAt"),+ "workflow_id": workflow["workflowId"],+ "workflow_name": workflow.get("workflowName"),+ "workflow_path": workflow.get("workflowPath"),+ "workflow_status": workflow.get("workflowStatus"),+ "workflow_created_at": workflow.get("workflowCreatedAt"),+ "workflow_started_at": workflow.get("workflowStartedAt"),+ "workflow_finished_at": workflow.get("workflowFinishedAt"),+ }+ rows: list[JSONObject] = []+ for job in workflow.get("jobs", []):+ job_columns = {+ "job_id": job["jobId"],+ "job_key": job.get("jobKey"),+ "job_display_name": job.get("jobDisplayName"),+ "job_status": job.get("status"),+ "job_started_at": job.get("startedAt"),+ "job_finished_at": job.get("finishedAt"),+ }+ for attempt in job.get("attempts", []):+ rows.append(+ {+ **shared_columns,+ **job_columns,+ "attempt_id": attempt["attemptId"],+ "attempt": attempt.get("attempt"),+ "attempt_status": attempt.get("status"),+ "attempt_started_at": attempt.get("startedAt"),+ "attempt_finished_at": attempt.get("finishedAt"),+ "sandbox_id": attempt.get("sandboxId"),+ }+ )+ return rows+++def _run_attempt_rows(session: Session, run: JSONObject) -> list[JSONObject]:+ # GetRunMetrics would answer in one call, but Depot refuses it with ResourceExhausted for a run+ # with many attempts. GetWorkflow answers for any workflow size, so the run is read per workflow.+ workflows = _call(session, "GetRunStatus", {"runId": run["runId"]}).get("workflows", [])+ return [+ row+ for workflow in workflows+ for row in _attempt_rows(+ run, _call(session, "GetWorkflow", {"workflowId": workflow["workflowId"]}), len(workflows)+ )+ ]+++def depot_source(+ api_token: str,+ repository: str,+ created_after: dt.datetime | str | None,+ logger: FilteringBoundLogger,+) -> SourceResponse:+ lower_bound = _parse_timestamp(created_after) if created_after is not None else None++ def items() -> Iterator[list[JSONObject]]:+ session = _make_session(api_token)+ horizon = _in_flight_horizon(session, repository, dt.datetime.now(dt.UTC))+ runs = _runs_to_sync(session, repository, lower_bound, horizon)+ logger.info(+ "depot_ci.runs_to_sync",+ run_count=len(runs),+ created_after=lower_bound.isoformat() if lower_bound else None,+ created_before=horizon.isoformat(),+ )+ for run in runs:+ rows = _run_attempt_rows(session, run)+ if rows:+ yield rows++ return SourceResponse(+ name=JOB_ATTEMPTS,+ items=items,+ primary_keys=[PRIMARY_KEY],+ partition_mode="datetime",+ partition_format="week",+ partition_keys=[RUN_CREATED_AT],+ sort_mode="asc",+ )+++def validate_credentials(api_token: str, repository: str) -> tuple[bool, str | None]:+ response = _post(_make_session(api_token), "ListRuns", {"repo": repository, "pageSize": 1})+ if response.status_code == 401:+ return False, "Depot didn't accept this API token. Check that you copied the whole token and try again."+ if response.status_code == 403:+ return (+ False,+ "This API token can't read Depot CI runs. Create an organization API token in your Depot organization settings and try again.",+ )+ if not response.ok:+ return (+ False,+ f"Couldn't list Depot CI runs for {repository} (HTTP {response.status_code}). Check the repository and try again.",+ )+ return True, Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/depot/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/depot/settings.pynew file mode 100644index 000000000000..3c6fec5913a8--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/depot/settings.py@@ -0,0 +1,21 @@+from products.warehouse_sources.backend.types import IncrementalField, IncrementalFieldType++JOB_ATTEMPTS = "job_attempts"++ENDPOINTS = (JOB_ATTEMPTS,)++PRIMARY_KEY = "attempt_id"++# A run's creation time never changes, so it is a stable partition key and a monotonic cursor.+RUN_CREATED_AT = "run_created_at"++INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {+ JOB_ATTEMPTS: [+ {+ "label": RUN_CREATED_AT,+ "type": IncrementalFieldType.DateTime,+ "field": RUN_CREATED_AT,+ "field_type": IncrementalFieldType.DateTime,+ },+ ],+}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/depot/source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/depot/source.pyindex 3130b269b96d..293fca40ce80 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/depot/source.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/depot/source.py@@ -1,14 +1,44 @@-from typing import cast+import re+import datetime+from typing import Optional, cast-from products.warehouse_sources.backend.facade.source_config import DataWarehouseSourceCategory, SourceConfig+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, 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.common.typings import SourceInputs, SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.depot.depot import (+ depot_source,+ validate_credentials as validate_depot_credentials,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.depot.settings import (+ ENDPOINTS,+ INCREMENTAL_FIELDS,+)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.depot import DepotSourceConfigfrom products.warehouse_sources.backend.types import ExternalDataSourceType+_REPOSITORY_RE = re.compile(r"^[A-Za-z0-9-]+/[A-Za-z0-9._-]+$")+@SourceRegistry.registerclass DepotSource(SimpleSource[DepotSourceConfig]):+ api_docs_url = "https://depot.dev/docs/api/ci/reference"+ lists_tables_without_credentials = True+ history_lookback = datetime.timedelta(days=7)+@propertydef source_type(self) -> ExternalDataSourceType:return ExternalDataSourceType.DEPOT@@ -19,8 +49,74 @@ class DepotSource(SimpleSource[DepotSourceConfig]):name=ExternalDataSourceType.DEPOT,category=DataWarehouseSourceCategory.ENGINEERING___MONITORING,label="Depot",- keywords=["depot.dev"],+ keywords=["depot.dev", "depot ci"],+ caption="Sync Depot CI job attempts for one GitHub repository. Create an organization API token in your Depot organization settings, then enter the repository as `owner/name`.",+ releaseStatus=ReleaseStatus.ALPHA,+ docsUrl="https://posthog.com/docs/cdp/sources/depot",iconPath="/static/services/depot.png",- fields=cast(list[FieldType], []),- unreleasedSource=True,+ fields=cast(+ list[FieldType],+ [+ SourceFieldInputConfig(+ name="api_token",+ label="API token",+ type=SourceFieldInputConfigType.PASSWORD,+ required=True,+ placeholder="",+ secret=True,+ ),+ SourceFieldInputConfig(+ name="repository",+ label="Repository",+ type=SourceFieldInputConfigType.TEXT,+ required=True,+ placeholder="owner/name",+ secret=False,+ ),+ ],+ ),+ )++ def get_canonical_descriptions(self) -> CanonicalDescriptions:+ from products.warehouse_sources.backend.temporal.data_imports.sources.depot.canonical_descriptions import ( # noqa: PLC0415 (keeps the descriptions dict off the registry import path)+ CANONICAL_DESCRIPTIONS,+ )++ return CANONICAL_DESCRIPTIONS++ def get_non_retryable_errors(self) -> dict[str, str | None]:+ return {+ "401 Client Error": "Depot didn't accept your API token. Create a new organization API token in Depot and reconnect.",+ "403 Client Error": "Your Depot API token can't read Depot CI runs. Use an organization API token and reconnect.",+ }++ def get_schemas(+ self,+ config: DepotSourceConfig,+ 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: DepotSourceConfig,+ team_id: int,+ schema_name: Optional[str] = None,+ api_version: str | None = None,+ ) -> tuple[bool, str | None]:+ if not _REPOSITORY_RE.match(config.repository):+ return False, "Enter the repository as owner/name, for example PostHog/posthog."+ return validate_depot_credentials(config.api_token, config.repository)++ def source_for_pipeline(self, config: DepotSourceConfig, inputs: SourceInputs) -> SourceResponse:+ watermark = inputs.db_incremental_field_last_value if inputs.should_use_incremental_field else None+ return depot_source(+ api_token=config.api_token,+ repository=config.repository,+ created_after=watermark if watermark is not None else inputs.history_start,+ logger=inputs.logger,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/depot/tests/test_depot.py b/products/warehouse_sources/backend/temporal/data_imports/sources/depot/tests/test_depot.pynew file mode 100644index 000000000000..ba811d802492--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/depot/tests/test_depot.py@@ -0,0 +1,293 @@+import json+import datetime as dt+from collections.abc import Iterable+from typing import Any, cast++import pytest+from unittest import mock++from requests import Response++from products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponse+from products.warehouse_sources.backend.temporal.data_imports.sources.depot.depot import (+ DEPOT_CI_SERVICE_URL,+ depot_source,+ validate_credentials,+)++MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.depot.depot"+REPOSITORY = "example-org/example-repo"+API_TOKEN = "depot-test-token"+IN_FLIGHT = ["queued", "running"]+TERMINAL = ["finished", "failed", "cancelled"]+NOW = dt.datetime.now(dt.UTC)+++def _iso(value: dt.datetime) -> str:+ return value.isoformat(timespec="milliseconds").replace("+00:00", "Z")+++def _run(run_id: str, age: dt.timedelta) -> dict[str, Any]:+ return {"runId": run_id, "repo": REPOSITORY, "status": "finished", "createdAt": _iso(NOW - age)}+++def _response(status: int, body: dict[str, Any], method: str) -> Response:+ response = Response()+ response.status_code = status+ response.reason = {200: "OK", 401: "Unauthorized", 403: "Forbidden"}.get(status, "Error")+ response.url = f"{DEPOT_CI_SERVICE_URL}/{method}"+ response._content = json.dumps(body).encode()+ return response+++def _single_attempt_workflow(run: dict[str, Any]) -> dict[str, Any]:+ return {+ "runId": run["runId"],+ "workflowId": f"{run['runId']}-wf",+ "jobs": [+ {"jobId": f"{run['runId']}-job", "attempts": [{"attemptId": f"{run['runId']}-attempt", "attempt": 1}]}+ ],+ }+++def _fake_session(+ terminal_pages: list[list[dict[str, Any]]],+ in_flight_runs: list[dict[str, Any]] | None = None,+ workflows_by_run: dict[str, list[dict[str, Any]]] | None = None,+) -> mock.MagicMock:+ workflows = workflows_by_run or {+ run["runId"]: [_single_attempt_workflow(run)] for page in terminal_pages for run in page+ }+ workflows_by_id = {workflow["workflowId"]: workflow for runs in workflows.values() for workflow in runs}++ def post(url: str, json: dict[str, Any], timeout: float) -> Response:+ method = url.removeprefix(f"{DEPOT_CI_SERVICE_URL}/")+ if method == "ListRuns" and json["status"] == IN_FLIGHT:+ return _response(200, {"runs": in_flight_runs or []}, method)+ if method == "ListRuns":+ page_index = int(json.get("pageToken", "0"))+ next_page_token = str(page_index + 1) if page_index + 1 < len(terminal_pages) else ""+ return _response(200, {"runs": terminal_pages[page_index], "nextPageToken": next_page_token}, method)+ if method == "GetRunStatus":+ run_workflows = workflows.get(json["runId"], [])+ return _response(200, {"workflows": [{"workflowId": w["workflowId"]} for w in run_workflows]}, method)+ return _response(200, workflows_by_id[json["workflowId"]], method)++ session = mock.MagicMock()+ session.post.side_effect = post+ return session+++def _requests(session: mock.MagicMock) -> list[tuple[str, dict[str, Any]]]:+ return [+ (call.args[0].removeprefix(f"{DEPOT_CI_SERVICE_URL}/"), call.kwargs["json"])+ for call in session.post.call_args_list+ ]+++def _batches(response: SourceResponse) -> list[list[dict[str, Any]]]:+ return list(cast(Iterable[list[dict[str, Any]]], response.items()))+++def _synced_rows(session: mock.MagicMock, created_after: dt.datetime | str | None) -> list[dict[str, Any]]:+ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):+ batches = _batches(depot_source(API_TOKEN, REPOSITORY, created_after, mock.MagicMock()))+ return [row for batch in batches for row in batch]+++# Newest first, the order ListRuns returns terminal runs in.+TERMINAL_PAGES = [+ [_run("r6", dt.timedelta(minutes=10)), _run("r5", dt.timedelta(hours=1))],+ [_run("r4", dt.timedelta(hours=2)), _run("r3", dt.timedelta(hours=3))],+ [_run("r2", dt.timedelta(hours=4)), _run("r1", dt.timedelta(hours=5))],+ [_run("r0", dt.timedelta(days=6))],+]+WATERMARK = NOW - dt.timedelta(hours=4)+RECENT_IN_FLIGHT = {**_run("in-flight", dt.timedelta(minutes=90)), "status": "queued"}+STALE_QUEUED = {**_run("stale", dt.timedelta(days=30)), "status": "queued"}+LONG_RUNNING = {**_run("long", dt.timedelta(minutes=150)), "status": "running"}+# Older than the queued cutoff, and still running, so it holds the horizon.+VERY_LONG_RUNNING = {**_run("very-long", dt.timedelta(hours=7)), "status": "running"}+++class TestDepotSource:+ @pytest.mark.parametrize(+ "in_flight_runs, expected_run_ids",+ [+ ([], ["r3", "r4", "r5", "r6"]),+ ([RECENT_IN_FLIGHT], ["r3", "r4"]),+ ([STALE_QUEUED], ["r3", "r4", "r5", "r6"]),+ ([STALE_QUEUED, RECENT_IN_FLIGHT], ["r3", "r4"]),+ ([LONG_RUNNING], ["r3"]),+ ([VERY_LONG_RUNNING], []),+ ],+ )+ def test_syncs_only_runs_created_before_the_oldest_recent_in_flight_run(+ self, in_flight_runs: list[dict[str, Any]], expected_run_ids: list[str]+ ) -> None:+ session = _fake_session(TERMINAL_PAGES, in_flight_runs)++ rows = _synced_rows(session, WATERMARK)++ assert [row["run_id"] for row in rows] == expected_run_ids++ @pytest.mark.parametrize(+ "created_after, expected_run_ids, expected_terminal_pages",+ [+ (WATERMARK, ["r3", "r4", "r5", "r6"], 3),+ (_iso(WATERMARK), ["r3", "r4", "r5", "r6"], 3),+ (None, ["r0", "r1", "r2", "r3", "r4", "r5", "r6"], 4),+ ],+ # The bounds derive from the wall clock, so fixed ids keep every xdist worker collecting the same tests.+ ids=["datetime_watermark", "string_watermark", "no_watermark"],+ )+ def test_walks_terminal_runs_down_to_the_lower_bound_and_yields_them_oldest_first(+ self, created_after: dt.datetime | str | None, expected_run_ids: list[str], expected_terminal_pages: int+ ) -> None:+ session = _fake_session(TERMINAL_PAGES)++ rows = _synced_rows(session, created_after)++ assert [row["run_id"] for row in rows] == expected_run_ids+ terminal_list_calls = [+ body for method, body in _requests(session) if method == "ListRuns" and body["status"] == TERMINAL+ ]+ assert len(terminal_list_calls) == expected_terminal_pages++ def test_request_shapes(self) -> None:+ session = _fake_session(TERMINAL_PAGES[:2])++ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session) as make_session:+ _batches(depot_source(API_TOKEN, REPOSITORY, None, mock.MagicMock()))++ assert make_session.call_args.kwargs["headers"] == {"Authorization": f"Bearer {API_TOKEN}"}+ assert API_TOKEN in make_session.call_args.kwargs["redact_values"]+ # Every Depot RPC is a POST, which the shared retry leaves out, so a 429 must still retry.+ assert make_session.call_args.kwargs["retry"].is_retry("POST", 429)+ assert _requests(session)[:3] == [+ ("ListRuns", {"repo": REPOSITORY, "status": IN_FLIGHT, "pageSize": 200}),+ ("ListRuns", {"repo": REPOSITORY, "status": TERMINAL, "pageSize": 200}),+ ("ListRuns", {"repo": REPOSITORY, "status": TERMINAL, "pageSize": 200, "pageToken": "1"}),+ ]+ assert _requests(session)[3:5] == [("GetRunStatus", {"runId": "r3"}), ("GetWorkflow", {"workflowId": "r3-wf"})]++ def test_flattens_one_row_per_attempt_of_every_workflow_in_the_run(self) -> None:+ run = _run("run-1", dt.timedelta(hours=1))+ backend = {+ "runId": "run-1",+ "repo": REPOSITORY,+ "ref": "refs/pull/42/merge",+ "sha": "abc123",+ "headSha": "def456",+ "trigger": "pull_request",+ "runStatus": "failed",+ # A different precision from the listing, which the cursor must not take.+ "runCreatedAt": "2026-01-01T00:00:00Z",+ "runStartedAt": "2026-01-01T00:00:01Z",+ "runFinishedAt": "2026-01-01T00:10:00Z",+ "workflowId": "wf-1",+ "workflowName": "Backend CI",+ "workflowPath": "ci-backend.yml",+ "workflowStatus": "failed",+ "workflowCreatedAt": "2026-01-01T00:00:00Z",+ "workflowStartedAt": "2026-01-01T00:00:02Z",+ "workflowFinishedAt": "2026-01-01T00:09:59Z",+ "jobs": [+ {+ "jobId": "job-matrix",+ "jobKey": "ci-backend.yml:turbo-tests:matrix-38",+ "jobDisplayName": "Product tests (shard 38)",+ "status": "finished",+ "startedAt": "2026-01-01T00:00:04Z",+ "finishedAt": "2026-01-01T00:08:00Z",+ "attempts": [+ {+ "attemptId": "attempt-1",+ "attempt": 1,+ "status": "failed",+ "sandboxId": "sandbox-1",+ "sessionId": "session-1",+ "startedAt": "2026-01-01T00:00:04Z",+ "finishedAt": "2026-01-01T00:04:00Z",+ },+ {"attemptId": "attempt-2", "attempt": 2},+ ],+ },+ {"jobId": "job-placeholder", "jobKey": "ci-backend.yml:django:_dynamicMatrix", "status": "skipped"},+ ],+ }+ report = {+ "runId": "run-1",+ "workflowId": "wf-2",+ "jobs": [{"jobId": "job-report", "attempts": [{"attemptId": "attempt-3"}]}],+ }+ session = _fake_session([[run]], workflows_by_run={"run-1": [backend, report]})++ rows = _synced_rows(session, None)++ assert [(row["workflow_id"], row["attempt_id"], row["job_display_name"]) for row in rows] == [+ ("wf-1", "attempt-1", "Product tests (shard 38)"),+ ("wf-1", "attempt-2", "Product tests (shard 38)"),+ ("wf-2", "attempt-3", None),+ ]+ assert rows[0] == {+ "run_id": "run-1",+ "run_workflow_count": 2,+ "repo": REPOSITORY,+ "ref": "refs/pull/42/merge",+ "sha": "abc123",+ "head_sha": "def456",+ "trigger": "pull_request",+ "run_status": "failed",+ "run_created_at": run["createdAt"],+ "run_started_at": "2026-01-01T00:00:01Z",+ "run_finished_at": "2026-01-01T00:10:00Z",+ "workflow_id": "wf-1",+ "workflow_name": "Backend CI",+ "workflow_path": "ci-backend.yml",+ "workflow_status": "failed",+ "workflow_created_at": "2026-01-01T00:00:00Z",+ "workflow_started_at": "2026-01-01T00:00:02Z",+ "workflow_finished_at": "2026-01-01T00:09:59Z",+ "job_id": "job-matrix",+ "job_key": "ci-backend.yml:turbo-tests:matrix-38",+ "job_display_name": "Product tests (shard 38)",+ "job_status": "finished",+ "job_started_at": "2026-01-01T00:00:04Z",+ "job_finished_at": "2026-01-01T00:08:00Z",+ "attempt_id": "attempt-1",+ "attempt": 1,+ "attempt_status": "failed",+ "attempt_started_at": "2026-01-01T00:00:04Z",+ "attempt_finished_at": "2026-01-01T00:04:00Z",+ "sandbox_id": "sandbox-1",+ }+++class TestValidateCredentials:+ @pytest.mark.parametrize(+ "status, expected_valid, expected_message_fragment",+ [+ (200, True, None),+ (401, False, "didn't accept this API token"),+ (403, False, "organization API token"),+ (500, False, "HTTP 500"),+ ],+ )+ def test_maps_probe_status_to_result(+ self, status: int, expected_valid: bool, expected_message_fragment: str | None+ ) -> None:+ session = mock.MagicMock()+ session.post.return_value = _response(+ status, {"runs": []} if status == 200 else {"code": "permission_denied", "message": "denied"}, "ListRuns"+ )++ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):+ valid, message = validate_credentials(API_TOKEN, REPOSITORY)++ assert valid is expected_valid+ if expected_message_fragment is None:+ assert message is None+ else:+ assert message is not None and expected_message_fragment in message+ assert session.post.call_args.kwargs["json"] == {"repo": REPOSITORY, "pageSize": 1}diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/depot/tests/test_depot_source.py b/products/warehouse_sources/backend/temporal/data_imports/sources/depot/tests/test_depot_source.pynew file mode 100644index 000000000000..b6dc27f27433--- /dev/null+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/depot/tests/test_depot_source.py@@ -0,0 +1,73 @@+import json+from collections.abc import Iterable+from typing import Any, cast++import pytest+from unittest import mock++from requests import HTTPError, Response++from products.warehouse_sources.backend.temporal.data_imports.sources.depot.depot import DEPOT_CI_SERVICE_URL+from products.warehouse_sources.backend.temporal.data_imports.sources.depot.source import DepotSource+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.depot import DepotSourceConfig++MODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.depot.depot"+++def _response(status: int, reason: str, body: dict[str, str | list[str]]) -> Response:+ response = Response()+ response.status_code = status+ response.reason = reason+ response.url = f"{DEPOT_CI_SERVICE_URL}/ListRuns"+ response._content = json.dumps(body).encode()+ return response+++class TestDepotSource:+ @pytest.mark.parametrize(+ "repository",+ ["posthog", "https://github.com/PostHog/posthog", "PostHog/posthog/tree/master", "PostHog/ posthog", ""],+ )+ def test_rejects_a_repository_that_is_not_owner_slash_name_without_calling_depot(self, repository: str) -> None:+ with mock.patch(f"{MODULE}.make_tracked_session") as make_session:+ valid, message = DepotSource().validate_credentials(+ DepotSourceConfig(api_token="token", repository=repository), team_id=1+ )++ assert valid is False+ assert message is not None and "owner/name" in message+ make_session.assert_not_called()++ @pytest.mark.parametrize("repository", ["PostHog/posthog", "example-org/repo.name_2"])+ def test_accepts_an_owner_slash_name_repository_that_depot_lists(self, repository: str) -> None:+ session = mock.MagicMock()+ session.post.return_value = _response(200, "OK", {"runs": []})++ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):+ result = DepotSource().validate_credentials(+ DepotSourceConfig(api_token="token", repository=repository), team_id=1+ )++ assert result == (True, None)++ @pytest.mark.parametrize(+ "status, reason, body",+ [+ (401, "Unauthorized", {"code": "unauthenticated", "message": "invalid token"}),+ (403, "Forbidden", {"code": "permission_denied", "message": "permission denied"}),+ ],+ )+ def test_auth_failures_during_sync_are_non_retryable(+ self, status: int, reason: str, body: dict[str, str | list[str]]+ ) -> None:+ source = DepotSource()+ session = mock.MagicMock()+ session.post.return_value = _response(status, reason, body)+ inputs = mock.MagicMock(should_use_incremental_field=False, history_start=None)++ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):+ response = source.source_for_pipeline(DepotSourceConfig(api_token="token", repository="a/b"), inputs)+ with pytest.raises(HTTPError) as error:+ list(cast(Iterable[list[dict[str, Any]]], response.items()))++ assert any(pattern in str(error.value) for pattern in source.get_non_retryable_errors())diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/depot.py b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/depot.pyindex 3f69aab3f460..c6be4a0d2c06 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/depot.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/generated_configs/depot.py@@ -6,4 +6,5 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common imp@config.configclass DepotSourceConfig(config.Config):- pass+ api_token: str+ repository: str