: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
fix(depot): reconcile late ci retries (#109297)
Raúl Negrón-Oteroc63f99d75401
diff --git a/products/engineering_analytics/SPEC.md b/products/engineering_analytics/SPEC.mdindex 8aa41fdfa432..06cea3569201 100644--- a/products/engineering_analytics/SPEC.md+++ b/products/engineering_analytics/SPEC.md@@ -196,6 +196,7 @@ Warehouse tables (GitHub source):Warehouse table (Depot source):- `depot_job_attempts`: one row per Depot CI job attempt, for the repository the Depot source names. Reads keep only that repository's rows, because a source moved to another repository keeps what it synced before. Depot CI is its own engine, so these runs never reach the GitHub tables. `logic/views/depot_ci.py` reshapes the attempts into rows of the GitHub runs and jobs contracts and unions them onto those tables, so every builder reads both engines. Each Depot workflow is one runs row. A run with one workflow decodes its id to the integer `GITHUB_RUN_ID` Depot CI gives its jobs, which joins them to the CI test spans; a run with several workflows keys each by its own decoded workflow id, so no join fans out. The PR number comes from the run's `refs/pull/<n>/merge` ref, and the run's branch from that PR's snapshot. Job rows carry no branch, because a PR snapshot lookup in the jobs builder would add two full PR scans to every jobs read; a read that joins a job to its run takes the branch through `workflow_jobs.branch`, which falls back to the run's. Depot numbers attempts per job, not per run, so a job's last attempt is listed again under each later attempt of its run, as GitHub lists a job it did not re-run; the jobs builder flags those rows as `is_rerun_copy`. Depot's API reports no `runs-on`, so every attempt is costed as the default `depot-ubuntu-24.04` sandbox. Optional, and reads degrade to GitHub-only CI when unsynced.+ - Depot ingestion replays seven days behind the creation-time watermark on every incremental sync and reconciles the schema's retained history weekly. The first sync after this policy deploys also reconciles retained history. The fixed `history_start` bounds new sources; a legacy source without that bound reconciles all available history. The durable reconciliation cursor advances only after extraction finishes and the pipeline makes the rows durable. Completed runs do not wait behind queued or stuck runs. Late retries older than the replay window can remain stale until the next reconciliation. Replayed attempts merge by `attempt_id`; append mode is unsupported, and an existing append sync stops before extraction with instructions to change its sync method. Depot's existing two-page-size pagination workaround still cannot guarantee recovery of every same-second cursor omission.- The shared CI sources assign `ci_engine` from the warehouse source: `github_actions` or `depot_ci`. Runner provider is independent: GitHub Actions can use Depot runners. Managed job-history and job-cost views append `ci_engine`, `native_run_id`, `native_workflow_run_id`, `native_job_id`, and `native_attempt_id`. GitHub's native workflow execution ID is its run ID; Depot's is its workflow ID. These additive string IDs preserve source identity while the existing integer IDs remain compatible with test traces and API consumers. CI job-to-run joins, failure attribution, job run shares, and timeline paging qualify integer IDs with `ci_engine`. The friction view consumes the same normalized sources and resolves a Depot job's default branch through its run. Run and job APIs append engine and source-native IDs; per-run costs and UI caches qualify compatible integers with the engine. Detail, job, and log lookups accept `ci_engine`; an unqualified integer that names both engines fails with a 400. New failure logs and test traces stamp the engine. Recovery evidence groups by engine, native workflow identity, and commit SHA; historical untagged telemetry remains unknown and cannot establish cross-engine identity. Legacy logs are read only for integer IDs unique to one engine in the selected source. Depot workflows without a hand-off job remain visible, including default-branch pushes; their branch and commit come from `ref` and `sha` when no PR head is present.- While a workflow moves to Depot CI, GitHub Actions routes each pull request to one engine, and both engines record a run of the commit. The union suppresses a successful Depot workflow whose `wait-for-handoff` job ran alone. A GitHub run is suppressed only when it succeeded, its `Hand off backend tests to Depot CI` job succeeded, its latest `Django Tests Pass` job succeeded, no synced job attempt decisively failed, and a successful Depot workflow took the hand-off for the same PR number and `head_sha`. Missing association or replacement data leaves the GitHub run visible. Failed, cancelled and unsettled GitHub relays and Depot waits stay visible. A relay that recovered retains its earlier failure history. Suppression applies to both runs and jobs; raw source rows remain available for full runner-cost accounting. Curated estimates cover the visible execution jobs; suppressed hand-off and relay overhead is excluded. These figures are not total runner spend or invoice reconciliation.diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/common/typings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/common/typings.pyindex f6a62591902f..e1f3bb57d072 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/common/typings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/common/typings.py@@ -9,7 +9,7 @@ from typing import TYPE_CHECKING, Any, ClassVar, Literal, Optional, Protocol, Tyfrom structlog.types import FilteringBoundLogger-from products.warehouse_sources.backend.types import IncrementalFieldType+from products.warehouse_sources.backend.types import ExternalDataSchemaSyncType, IncrementalFieldTypeif TYPE_CHECKING:import pyarrow as pa@@ -179,3 +179,4 @@ class SourceInputs:# Set for a source that implements `CursorSource`. It holds the cursor stored by the last# successful run, or no cursor when this run rebuilds the table.source_cursor: Optional[SourceCursorManager[Any]] = None+ sync_type: ExternalDataSchemaSyncType | None = Nonediff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/depot/depot.py b/products/warehouse_sources/backend/temporal/data_imports/sources/depot/depot.pyindex 8f3d310da29f..f5a9576d524e 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/depot/depot.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/depot/depot.py@@ -1,5 +1,5 @@import datetime as dt-from collections.abc import Iterator+from collections.abc import Callable, Iteratorfrom typing import Anyfrom requests import Response, Session@@ -26,11 +26,6 @@ REQUEST_TIMEOUT_SECONDS = 60# until Depot fixes its cursor. Depot caps pages at 100.LIST_RUNS_PAGE_SIZES = (100, 57)TERMINAL_STATUSES = ["finished", "failed", "cancelled"]-# Depot can leave a run queued or running forever. A real run can take hours, but a real queued run-# starts in minutes, so past these ages an in-flight run counts as stuck.-IN_FLIGHT_MAX_AGE = {"queued": dt.timedelta(hours=6), "running": dt.timedelta(hours=24)}-IN_FLIGHT_STATUSES = list(IN_FLIGHT_MAX_AGE)-# 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"})@@ -92,31 +87,6 @@ def _list_runs(return sorted(runs.values(), key=lambda entry: (entry[0], entry[1]["runId"]))-# The watermark stays behind every run still going, because a run it passed is never read. A stuck run-# with no workflows is the exception: it can never produce rows, and holding for it would stop every-# sync. A job retried after its run synced is not read again.-def _in_flight_horizon(- session: Session, repository: str, now: dt.datetime, logger: FilteringBoundLogger-) -> dt.datetime:- horizon = now- for created_at, run in _list_runs(session, repository, IN_FLIGHT_STATUSES):- if created_at < now - IN_FLIGHT_MAX_AGE.get(run["status"], IN_FLIGHT_MAX_AGE["queued"]):- if not _call(session, "GetRunStatus", {"runId": run["runId"]}).get("workflows"):- continue- logger.warning("depot_ci.stuck_run_holds_horizon", run_id=run["runId"], created_at=created_at.isoformat())- 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]:- # Depot stamps runs in whole seconds, and a sync that stopped partway through a second saved it as- # the watermark, so that second is read again. The merge on attempt_id drops the repeats.- runs = _list_runs(session, repository, TERMINAL_STATUSES, created_after)- return [run for created_at, run in runs if created_at < created_before]--def _attempt_rows(run: JSONObject, workflow: JSONObject, run_workflow_count: int) -> list[JSONObject]:shared_columns = {"run_id": run["runId"],@@ -183,23 +153,25 @@ def depot_source(repository: str,created_after: dt.datetime | str | None,logger: FilteringBoundLogger,+ on_complete: Callable[[], None] | None = None,) -> SourceResponse:lower_bound = _parse_timestamp(created_after) if created_after is not None else Nonedef items() -> Iterator[list[JSONObject]]:session = _make_session(api_token)- horizon = _in_flight_horizon(session, repository, dt.datetime.now(dt.UTC), logger)- runs = _runs_to_sync(session, repository, lower_bound, horizon)+ # Newest first, so a sync that stops partway has already stored the runs that no earlier sync read.+ runs = [run for _, run in reversed(_list_runs(session, repository, TERMINAL_STATUSES, lower_bound))]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+ if on_complete is not None:+ on_complete()return SourceResponse(name=JOB_ATTEMPTS,@@ -208,8 +180,9 @@ def depot_source(partition_mode="datetime",partition_format="week",partition_keys=[RUN_CREATED_AT],- sort_mode="asc",- # The watermark saves per chunk, and the default chunk holds a whole first sync of a busy repository.+ # Descending defers the watermark save to the end of the sync, so a replay that stops partway cannot move it back.+ sort_mode="desc",+ # Rows become durable per chunk, and the default chunk holds a whole first sync of a busy repository.chunk_size=5_000,)diff --git a/products/warehouse_sources/backend/temporal/data_imports/sources/depot/settings.py b/products/warehouse_sources/backend/temporal/data_imports/sources/depot/settings.pyindex 3c6fec5913a8..c40fcba8f953 100644--- a/products/warehouse_sources/backend/temporal/data_imports/sources/depot/settings.py+++ b/products/warehouse_sources/backend/temporal/data_imports/sources/depot/settings.py@@ -6,7 +6,7 @@ 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.+# Creation time is stable for partitioning. The source replays runs to pick up late retries.RUN_CREATED_AT = "run_created_at"INCREMENTAL_FIELDS: dict[str, list[IncrementalField]] = {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 293fca40ce80..1ed3eda3befc 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,6 +1,8 @@import reimport datetime-from typing import Optional, cast+from typing import ClassVar, Optional, cast++from posthog.dataclasses import frozenfrom products.warehouse_sources.backend.facade.source_config import (DataWarehouseSourceCategory,@@ -13,6 +15,8 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.common.basfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.canonical_descriptions import (CanonicalDescriptions,)+from products.warehouse_sources.backend.temporal.data_imports.sources.common.cursor import CursorSource+from products.warehouse_sources.backend.temporal.data_imports.sources.common.datetime_utils import parse_datetime_valuefrom products.warehouse_sources.backend.temporal.data_imports.sources.common.registry import SourceRegistryfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.schema import (SourceSchema,@@ -28,13 +32,26 @@ from products.warehouse_sources.backend.temporal.data_imports.sources.depot.settINCREMENTAL_FIELDS,)from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.depot import DepotSourceConfig-from products.warehouse_sources.backend.types import ExternalDataSourceType+from products.warehouse_sources.backend.types import ExternalDataSchemaSyncType, ExternalDataSourceType_REPOSITORY_RE = re.compile(r"^[A-Za-z0-9-]+/[A-Za-z0-9._-]+$")+_RETRY_LOOKBACK = datetime.timedelta(days=7)+_RECONCILIATION_INTERVAL = datetime.timedelta(days=7)+_APPEND_UNSUPPORTED = (+ "Depot CI replays job attempts. Switch this table to incremental merge or full refresh to avoid duplicates."+)+++@frozen+class DepotReconciliationCursor:+ cursor_kind: ClassVar[str] = "depot_reconciliation"+ reconciled_at: str++@SourceRegistry.register-class DepotSource(SimpleSource[DepotSourceConfig]):+class DepotSource(SimpleSource[DepotSourceConfig], CursorSource[DepotReconciliationCursor]):api_docs_url = "https://depot.dev/docs/api/ci/reference"lists_tables_without_credentials = Truehistory_lookback = datetime.timedelta(days=7)@@ -86,6 +103,7 @@ class DepotSource(SimpleSource[DepotSourceConfig]):def get_non_retryable_errors(self) -> dict[str, str | None]:return {+ _APPEND_UNSUPPORTED: _APPEND_UNSUPPORTED,"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.",}@@ -99,7 +117,7 @@ class DepotSource(SimpleSource[DepotSourceConfig]):force_refresh: bool = False,api_version: str | None = None,) -> list[SourceSchema]:- return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names)+ return build_endpoint_schemas(ENDPOINTS, INCREMENTAL_FIELDS, names, merge_only=ENDPOINTS)def validate_credentials(self,@@ -112,11 +130,36 @@ class DepotSource(SimpleSource[DepotSourceConfig]):return False, "Enter the repository as owner/name, for example PostHog/posthog."return validate_depot_credentials(config.api_token, config.repository)+ def cursor_class(self) -> type[DepotReconciliationCursor]:+ return DepotReconciliationCursor+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+ if inputs.sync_type == ExternalDataSchemaSyncType.APPEND:+ raise ValueError(_APPEND_UNSUPPORTED)+ manager = self.get_cursor_manager(inputs)+ cursor = manager.load()+ now = datetime.datetime.now(datetime.UTC)+ reconciled_at = parse_datetime_value(cursor.reconciled_at) if cursor is not None else None+ watermark = (+ parse_datetime_value(inputs.db_incremental_field_last_value)+ if inputs.should_use_incremental_field+ else None+ )+ reconcile = reconciled_at is None or now - reconciled_at >= _RECONCILIATION_INTERVAL or watermark is None+ # Creation time cannot reveal a late retry. Replay recent runs each sync and retained history+ # weekly; history_start is the schema's fixed initial floor, not a rolling seven-day window.+ lower_bound = inputs.history_start+ if not reconcile and watermark is not None:+ lower_bound = watermark - _RETRY_LOOKBACK+ if inputs.history_start is not None:+ lower_bound = max(lower_bound, inputs.history_start)+return depot_source(api_token=config.api_token,repository=config.repository,- created_after=watermark if watermark is not None else inputs.history_start,+ created_after=lower_bound,logger=inputs.logger,+ on_complete=(lambda: manager.stage(DepotReconciliationCursor(reconciled_at=now.isoformat())))+ if reconcile+ else None,)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.pyindex 98828cc801bd..3d3e3c3d94e5 100644--- 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.py@@ -1,19 +1,34 @@import jsonimport datetime as dt-from collections.abc import Iterable+from collections.abc import Iterable, Iterator+from pathlib import Pathfrom typing import Any, castimport pytest+import time_machinefrom unittest import mock-from requests import Response+import pyarrow as pa+import deltalake+from requests import HTTPError, Response+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.test.helpers import (+ make_local_table_ref,+)+from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.delta.writer import DeltaWriter+from products.warehouse_sources.backend.temporal.data_imports.sources.common.cursor import SourceCursorManagerfrom products.warehouse_sources.backend.temporal.data_imports.sources.common.typings import SourceResponsefrom products.warehouse_sources.backend.temporal.data_imports.sources.depot.depot import (DEPOT_CI_SERVICE_URL,depot_source,validate_credentials,)+from products.warehouse_sources.backend.temporal.data_imports.sources.depot.source import (+ DepotReconciliationCursor,+ DepotSource,+)+from products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.depot import DepotSourceConfig+from products.warehouse_sources.backend.types import ExternalDataSchemaSyncTypeMODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.depot.depot"REPOSITORY = "example-org/example-repo"@@ -110,53 +125,27 @@ TERMINAL_RUNS = []# Between r3 and r2, so no run can tie it.WATERMARK = NOW - dt.timedelta(hours=3, minutes=30)-RECENT_IN_FLIGHT = {**_run("in-flight", dt.timedelta(minutes=90)), "status": "queued"}-QUEUED_PAST_CUTOFF = {**_run("queued-7h", dt.timedelta(hours=7)), "status": "queued"}-LONG_RUNNING = {**_run("long", dt.timedelta(minutes=150)), "status": "running"}-RUNNING_INSIDE_CUTOFF = {**_run("running-23h", dt.timedelta(hours=23)), "status": "running"}-RUNNING_PAST_CUTOFF = {**_run("running-25h", dt.timedelta(hours=25)), "status": "running"}class TestDepotSource:- @pytest.mark.parametrize(- "in_flight_runs, expected_run_ids",- [- ([], ["r3", "r4", "r5", "r6"]),- ([RECENT_IN_FLIGHT], ["r3", "r4"]),- ([QUEUED_PAST_CUTOFF], ["r3", "r4", "r5", "r6"]),- ([RECENT_IN_FLIGHT, QUEUED_PAST_CUTOFF], ["r3", "r4"]),- ([LONG_RUNNING], ["r3"]),- ([RUNNING_INSIDE_CUTOFF], []),- ([RUNNING_PAST_CUTOFF], ["r3", "r4", "r5", "r6"]),- ],- )- 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_RUNS, in_flight_runs)-- rows = _synced_rows(session, WATERMARK)-- assert [row["run_id"] for row in rows] == expected_run_ids-- def test_a_stuck_run_with_workflows_still_holds_the_horizon(self) -> None:+ def test_in_flight_runs_do_not_block_terminal_runs(self) -> None:stuck = {**_run("stuck", dt.timedelta(days=30)), "status": "running"}workflows = {run["runId"]: [_single_attempt_workflow(run)] for run in [*TERMINAL_RUNS, stuck]}session = _fake_session(TERMINAL_RUNS, [stuck], workflows_by_run=workflows)- assert _synced_rows(session, WATERMARK) == []+ assert [row["run_id"] for row in _synced_rows(session, WATERMARK)] == ["r6", "r5", "r4", "r3"]@pytest.mark.parametrize("created_after, expected_run_ids, expected_terminal_pages",[- (WATERMARK, ["r3", "r4", "r5", "r6"], 5),- (TERMINAL_RUNS[4]["createdAt"], ["r2", "r3", "r4", "r5", "r6"], 5),- (None, ["r0", "r1", "r2", "r3", "r4", "r5", "r6"], 7),+ (WATERMARK, ["r6", "r5", "r4", "r3"], 5),+ (TERMINAL_RUNS[4]["createdAt"], ["r6", "r5", "r4", "r3", "r2"], 5),+ (None, ["r6", "r5", "r4", "r3", "r2", "r1", "r0"], 7),],# The bounds derive from the wall clock, so fixed ids keep every xdist worker collecting the same tests.ids=["datetime_watermark", "watermark_in_a_runs_second", "no_watermark"],)- def test_walks_terminal_runs_down_to_the_lower_bound_and_yields_them_oldest_first(+ def test_walks_terminal_runs_down_to_the_lower_bound_and_yields_them_newest_first(self, created_after: dt.datetime | str | None, expected_run_ids: list[str], expected_terminal_pages: int) -> None:session = _fake_session(TERMINAL_RUNS)@@ -173,8 +162,8 @@ class TestDepotSource:@pytest.mark.parametrize("page_sizes, expected_run_ids",[- ((3,), ["oldest", "tied-0", "tied-1", "newest"]),- ((3, 4), ["oldest", "tied-0", "tied-1", "tied-2", "newest"]),+ ((3,), ["newest", "tied-1", "tied-0", "oldest"]),+ ((3, 4), ["newest", "tied-2", "tied-1", "tied-0", "oldest"]),],ids=["one_walk_skips_the_rest_of_the_second", "a_second_walk_returns_it"],)@@ -206,14 +195,13 @@ class TestDepotSource: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)[:5] == [- ("ListRuns", {"repo": REPOSITORY, "status": IN_FLIGHT, "pageSize": 2}),+ assert _requests(session)[:4] == [("ListRuns", {"repo": REPOSITORY, "status": TERMINAL, "pageSize": 2}),("ListRuns", {"repo": REPOSITORY, "status": TERMINAL, "pageSize": 2, "pageToken": "2"}),("ListRuns", {"repo": REPOSITORY, "status": TERMINAL, "pageSize": 3}),("ListRuns", {"repo": REPOSITORY, "status": TERMINAL, "pageSize": 3, "pageToken": "3"}),]- assert _requests(session)[5:7] == [("GetRunStatus", {"runId": "r3"}), ("GetWorkflow", {"workflowId": "r3-wf"})]+ assert _requests(session)[4:6] == [("GetRunStatus", {"runId": "r6"}), ("GetWorkflow", {"workflowId": "r6-wf"})]def test_flattens_one_row_per_attempt_of_every_workflow_in_the_run(self) -> None:run = _run("run-1", dt.timedelta(hours=1))@@ -308,6 +296,132 @@ class TestDepotSource:}+class TestDepotReconciliation:+ @pytest.mark.asyncio+ @pytest.mark.parametrize("age_days,reconciled_days_ago", [(2, 1), (14, 7)])+ async def test_replayed_attempts_update_storage_without_duplicates(+ self, age_days: int, reconciled_days_ago: int, tmp_path: Path+ ) -> None:+ source = DepotSource()+ config = DepotSourceConfig(api_token=API_TOKEN, repository=REPOSITORY)+ run = _run("run-1", dt.timedelta(days=age_days))+ workflow = _single_attempt_workflow(run)+ workflow["workflowStatus"] = "failed"+ job = workflow["jobs"][0]+ job["attempts"][0]["status"] = "failed"+ session = _fake_session([run], workflows_by_run={run["runId"]: [workflow]})+ manager = SourceCursorManager(source.cursor_class(), None, source)+ inputs = mock.MagicMock(+ sync_type=ExternalDataSchemaSyncType.INCREMENTAL,+ should_use_incremental_field=True,+ db_incremental_field_last_value=None,+ history_start=NOW - dt.timedelta(days=30),+ source_cursor=manager,+ )+ columns = ("attempt_id", "attempt_status", "workflow_status")++ async def sync_and_read_storage() -> list[tuple[str, str, str]]:+ response = source.source_for_pipeline(config, inputs)+ rows = [row for batch in _batches(response) for row in batch]+ await DeltaWriter(make_local_table_ref(str(tmp_path / "attempts"))).write(+ data=pa.Table.from_pylist([{key: row[key] for key in columns} for row in rows]),+ write_type="incremental",+ should_overwrite_table=False,+ primary_keys=response.primary_keys,+ )+ stored = deltalake.DeltaTable(str(tmp_path / "attempts")).to_pyarrow_table().to_pylist()+ return sorted(tuple(row[key] for key in columns) for row in stored)++ with time_machine.travel(NOW, tick=False), mock.patch(f"{MODULE}.make_tracked_session", return_value=session):+ assert await sync_and_read_storage() == [("run-1-attempt", "failed", "failed")]++ workflow["workflowStatus"] = "finished"+ job["attempts"].append({"attemptId": "retry-2", "attempt": 2, "status": "finished"})+ inputs.db_incremental_field_last_value = _iso(NOW - dt.timedelta(minutes=10))+ inputs.source_cursor = SourceCursorManager(+ source.cursor_class(),+ DepotReconciliationCursor(reconciled_at=_iso(NOW - dt.timedelta(days=reconciled_days_ago))),+ source,+ )+ after_retry = [("retry-2", "finished", "finished"), ("run-1-attempt", "failed", "finished")]+ assert await sync_and_read_storage() == after_retry+ assert await sync_and_read_storage() == after_retry++ @pytest.mark.parametrize(+ "reconciled_days_ago, history_days, has_watermark, expected_runs, expected_reconciled",+ [+ (None, 30, True, ["recent", "old"], True),+ (1, 30, True, ["recent"], False),+ (7, 30, True, ["recent", "old"], True),+ (1, 30, False, ["recent", "old"], True),+ (None, None, True, ["recent", "old", "outside"], True),+ (1, 1, True, [], False),+ ],+ )+ def test_replays_retries_and_reconciles_retained_history(+ self,+ reconciled_days_ago: int | None,+ history_days: int | None,+ has_watermark: bool,+ expected_runs: list[str],+ expected_reconciled: bool,+ ) -> None:+ source = DepotSource()+ cursor = (+ DepotReconciliationCursor(reconciled_at=_iso(NOW - dt.timedelta(days=reconciled_days_ago)))+ if reconciled_days_ago is not None+ else None+ )+ manager = SourceCursorManager(source.cursor_class(), cursor, source)+ inputs = mock.MagicMock(+ should_use_incremental_field=True,+ db_incremental_field_last_value=_iso(NOW - dt.timedelta(minutes=10)) if has_watermark else None,+ history_start=NOW - dt.timedelta(days=history_days) if history_days is not None else None,+ source_cursor=manager,+ )+ runs = [+ _run("recent", dt.timedelta(days=2)),+ _run("old", dt.timedelta(days=14)),+ _run("outside", dt.timedelta(days=40)),+ ]+ workflows = {run["runId"]: [_single_attempt_workflow(run)] for run in runs}+ for run_workflows in workflows.values():+ job = run_workflows[0]["jobs"][0]+ job["attempts"].append({"attemptId": f"{job['jobId']}-retry", "attempt": 2})+ session = _fake_session(runs, workflows_by_run=workflows)++ with time_machine.travel(NOW, tick=False), mock.patch(f"{MODULE}.make_tracked_session", return_value=session):+ response = source.source_for_pipeline(DepotSourceConfig(api_token=API_TOKEN, repository=REPOSITORY), inputs)+ assert manager.staged is None+ rows = [row for batch in _batches(response) for row in batch]++ assert [row["run_id"] for row in rows if row["attempt"] == 2] == expected_runs+ assert (manager.staged is not None) == expected_reconciled++ def test_incomplete_reconciliation_does_not_advance_the_cursor(self) -> None:+ source = DepotSource()+ manager = SourceCursorManager(source.cursor_class(), None, source)+ inputs = mock.MagicMock(should_use_incremental_field=False, history_start=None, source_cursor=manager)+ runs = [_run("recent", dt.timedelta(days=2)), _run("old", dt.timedelta(days=14))]+ session = _fake_session(runs)+ post = session.post.side_effect++ def interrupted_post(url: str, json: dict[str, Any], timeout: float) -> Response:+ if url.endswith("/GetWorkflow") and json["workflowId"] == "old-wf":+ return _response(500, {}, "GetWorkflow")+ return cast(Response, post(url, json=json, timeout=timeout))++ session.post.side_effect = interrupted_post+ with mock.patch(f"{MODULE}.make_tracked_session", return_value=session):+ response = source.source_for_pipeline(DepotSourceConfig(api_token=API_TOKEN, repository=REPOSITORY), inputs)+ batches = cast(Iterator[list[dict[str, Any]]], response.items())+ assert next(batches)[0]["run_id"] == "recent"+ assert manager.staged is None+ with pytest.raises(HTTPError, match="500 Server Error"):+ list(batches)+ assert manager.staged is None++class TestValidateCredentials:@pytest.mark.parametrize("status, expected_valid, expected_message_fragment",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.pyindex b6dc27f27433..7f64ddcccc59 100644--- 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.py@@ -10,6 +10,7 @@ from requests import HTTPError, Responsefrom products.warehouse_sources.backend.temporal.data_imports.sources.depot.depot import DEPOT_CI_SERVICE_URLfrom products.warehouse_sources.backend.temporal.data_imports.sources.depot.source import DepotSourcefrom products.warehouse_sources.backend.temporal.data_imports.sources.generated_configs.depot import DepotSourceConfig+from products.warehouse_sources.backend.types import ExternalDataSchemaSyncTypeMODULE = "products.warehouse_sources.backend.temporal.data_imports.sources.depot.depot"@@ -71,3 +72,12 @@ class TestDepotSource:list(cast(Iterable[list[dict[str, Any]]], response.items()))assert any(pattern in str(error.value) for pattern in source.get_non_retryable_errors())++ def test_rejects_existing_append_mode_before_extracting_replayed_attempts(self) -> None:+ source = DepotSource()+ inputs = mock.MagicMock(sync_type=ExternalDataSchemaSyncType.APPEND)+ with mock.patch(f"{MODULE}.make_tracked_session") as make_session:+ with pytest.raises(ValueError, match="Switch this table to incremental merge") as error:+ source.source_for_pipeline(DepotSourceConfig(api_token="token", repository="a/b"), inputs)+ assert str(error.value) in source.get_non_retryable_errors()+ make_session.assert_not_called()diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.pyindex 956ebd9cc836..f578a268ae59 100644--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/import_data_sync.py@@ -539,6 +539,7 @@ async def _import_data_with_reporting(inputs: ImportDataActivityInputs, logger:source_inputs = SourceInputs(schema_name=schema.name,+ sync_type=ExternalDataSchema.SyncType(schema.sync_type) if schema.sync_type is not None else None,schema_id=str(schema.id),source_id=str(inputs.source_id),team_id=inputs.team_id,diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_import_data_sync.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_import_data_sync.pyindex 69070f6c3e52..e70bec641782 100644--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_import_data_sync.py+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_import_data_sync.py@@ -94,6 +94,7 @@ def _patched_activity(source_mock, model=None, schema=None):if schema is None:schema = mock.MagicMock()+ schema.sync_type = ExternalDataSchema.SyncType.FULL_REFRESHschema.should_use_incremental_field = Falseschema.row_filters = Noneschema.delta_revive_required = None@@ -915,6 +916,9 @@ async def test_shared_non_retryable_error_routes_through_handler_without_source_def _incremental_schema(*, is_incremental: bool, lookback_seconds: int | None) -> mock.MagicMock:schema = mock.MagicMock()+ schema.sync_type = (+ ExternalDataSchema.SyncType.INCREMENTAL if is_incremental else ExternalDataSchema.SyncType.FULL_REFRESH+ )schema.should_use_incremental_field = Trueschema.is_incremental = is_incrementalschema.incremental_field_type = IncrementalFieldType.Timestamp@@ -1173,6 +1177,21 @@ async def test_synced_parent_uses_the_warehouse_path(sync_type):assert result is True+async def test_persisted_append_mode_reaches_source_before_extraction():+ source = mock.MagicMock(spec=SimpleSource)+ source.parse_config.return_value = {}+ source.source_for_pipeline.return_value = mock.MagicMock()+ schema = _incremental_schema(is_incremental=False, lookback_seconds=None)+ schema.sync_type = ExternalDataSchema.SyncType.APPEND++ with _patched_activity_reaching_run(source, schema):+ await import_data_activity_sync(_inputs_no_reset())++ _, source_inputs = source.source_for_pipeline.call_args.args+ assert source_inputs.sync_type == ExternalDataSchema.SyncType.APPEND++@pytest.mark.asyncioasync def test_fanout_gate_result_threaded_into_source_inputs():# The gate's decision must reach the source via SourceInputs — if this wiring drops,