Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

fix(data-warehouse): stop spending full retry caps on dead syncs (#113469)

Tom Owersc2693a2b507b
diff --git a/products/data_warehouse/backend/logic/external_data_source/jobs.py b/products/data_warehouse/backend/logic/external_data_source/jobs.py
index 1c7f7ae74f80..09851ec92df4 100644
--- a/products/data_warehouse/backend/logic/external_data_source/jobs.py
+++ b/products/data_warehouse/backend/logic/external_data_source/jobs.py
@@ -38,9 +38,39 @@ FINALIZE_QUEUE_SWEEP_ERRORS = Counter(
)
+def _move_failure_streak(
+ schema: ExternalDataSchema, status: ExternalDataJobStatus, *, counts_as_source_failure: bool
+) -> bool:
+ """Move the schema's failure streak for one run's outcome. Returns whether it changed.
+
+ Only the first terminal write of a run may call this. A run is finalized more than once: the
+ load consumer and the workflow both write, and an auto-disable teardown re-fails still-running
+ jobs, so each repeat would otherwise charge the same run again.
+ """
+ if status == ExternalDataJobStatus.FAILED and counts_as_source_failure:
+ schema.note_failed_run(dt.datetime.now(dt.UTC))
+ return True
+ if status == ExternalDataJobStatus.COMPLETED:
+ schema.clear_failure_streak()
+ return True
+ return False
+
+
def update_external_job_status(
- job_id: str, team_id: int, status: ExternalDataJobStatus, logger: FilteringBoundLogger, latest_error: str | None
+ job_id: str,
+ team_id: int,
+ status: ExternalDataJobStatus,
+ logger: FilteringBoundLogger,
+ latest_error: str | None,
+ counts_as_source_failure: bool = True,
) -> ExternalDataJob:
+ """Record a run's terminal status on the job and its schema.
+
+ Pass `counts_as_source_failure=False` for a failure that says nothing about the source: a
+ worker restart, an unreachable app DB, a lock takeover, a cancellation. Only a failure that
+ does say something moves the schema's failure streak, which decides the retry cap and the run
+ gap of its next runs (see `retry_limits`).
+ """
is_first_terminal_transition = False
with transaction.atomic():
model = ExternalDataJob.objects.select_for_update().get(id=job_id, team_id=team_id)
@@ -130,7 +160,13 @@ def update_external_job_status(
schema.status = schema_status
if not billing_limited_run:
schema.latest_error = error_to_persist
- schema.save(update_fields=["status", "latest_error", "updated_at"])
+ schema_update_fields = ["status", "latest_error", "updated_at"]
+ if is_first_terminal_transition and _move_failure_streak(
+ schema, status, counts_as_source_failure=counts_as_source_failure
+ ):
+ schema_update_fields.append("sync_type_config")
+
+ schema.save(update_fields=schema_update_fields)
# Every risky terminal write (any non-Completed terminal, plus the takeover-recovery
# Completed flip) can leave still-claimable batches in the v3 queue; a straggler loaded
diff --git a/products/data_warehouse/backend/logic/external_data_source/test/test_jobs.py b/products/data_warehouse/backend/logic/external_data_source/test/test_jobs.py
index 68f89f0c2ba9..ca2381e5ba9d 100644
--- a/products/data_warehouse/backend/logic/external_data_source/test/test_jobs.py
+++ b/products/data_warehouse/backend/logic/external_data_source/test/test_jobs.py
@@ -1,4 +1,5 @@
import uuid
+from datetime import UTC, datetime, timedelta
import pytest
from unittest.mock import MagicMock, patch
@@ -424,6 +425,77 @@ class TestUpdateExternalJobStatus:
assert schema.status == ExternalDataSchemaStatus.COMPLETED
assert schema.latest_error is None
+ @staticmethod
+ def _finalize(team, job, status, **kwargs):
+ with patch("products.data_warehouse.backend.logic.external_data_source.jobs.emit_data_import_app_metrics"):
+ return update_external_job_status(
+ job_id=str(job.id),
+ team_id=team.pk,
+ status=status,
+ logger=MagicMock(),
+ latest_error="boom" if status == ExternalDataJobStatus.FAILED else None,
+ **kwargs,
+ )
+
+ def test_first_failed_write_starts_the_failure_streak(self):
+ team, _source, schema, job = _create_org_team_source_schema_job()
+ assert schema.failed_runs_in_a_row == 0
+
+ before = datetime.now(UTC)
+ self._finalize(team, job, ExternalDataJobStatus.FAILED)
+
+ schema = ExternalDataSchema.objects.get(id=schema.id)
+ assert schema.failed_runs_in_a_row == 1
+ last_failed_at = schema.failure_streak_last_failed_at
+ assert last_failed_at is not None
+ assert last_failed_at.tzinfo is not None
+ assert before - timedelta(seconds=1) <= last_failed_at <= datetime.now(UTC) + timedelta(seconds=1)
+
+ def test_a_repeated_failed_write_for_the_same_job_does_not_count_again(self):
+ team, _source, schema, job = _create_org_team_source_schema_job()
+ schema.sync_type_config = {"failure_streak": {"runs": 2, "last_failed_at": datetime.now(UTC).isoformat()}}
+ schema.save()
+
+ self._finalize(team, job, ExternalDataJobStatus.FAILED)
+ self._finalize(team, job, ExternalDataJobStatus.FAILED)
+ self._finalize(team, job, ExternalDataJobStatus.FAILED)
+
+ assert ExternalDataSchema.objects.get(id=schema.id).failed_runs_in_a_row == 3
+
+ def test_a_completed_write_clears_the_failure_streak(self):
+ team, _source, schema, job = _create_org_team_source_schema_job()
+ schema.sync_type_config = {
+ "other": "kept",
+ "failure_streak": {"runs": 7, "last_failed_at": datetime.now(UTC).isoformat()},
+ }
+ schema.save()
+
+ self._finalize(team, job, ExternalDataJobStatus.COMPLETED)
+
+ schema = ExternalDataSchema.objects.get(id=schema.id)
+ assert schema.failed_runs_in_a_row == 0
+ assert schema.failure_streak_last_failed_at is None
+ assert schema.sync_type_config == {"other": "kept"}
+
+ @pytest.mark.parametrize(
+ "status,counts_as_source_failure",
+ [
+ (ExternalDataJobStatus.FAILED, False),
+ (ExternalDataJobStatus.BILLING_LIMIT_REACHED, True),
+ (ExternalDataJobStatus.BILLING_LIMIT_TOO_LOW, True),
+ ],
+ )
+ def test_runs_that_say_nothing_about_the_source_leave_the_streak_alone(self, status, counts_as_source_failure):
+ team, _source, schema, job = _create_org_team_source_schema_job()
+ last_failed_at = (datetime.now(UTC) - timedelta(hours=2)).isoformat()
+ schema.sync_type_config = {"failure_streak": {"runs": 7, "last_failed_at": last_failed_at}}
+ schema.save()
+
+ self._finalize(team, job, status, counts_as_source_failure=counts_as_source_failure)
+
+ schema = ExternalDataSchema.objects.get(id=schema.id)
+ assert schema.sync_type_config == {"failure_streak": {"runs": 7, "last_failed_at": last_failed_at}}
+
class TestFinalizeQueueSweep:
@pytest.mark.parametrize(
diff --git a/products/warehouse_sources/backend/models/external_data_schema.py b/products/warehouse_sources/backend/models/external_data_schema.py
index f6b297799405..ba31e0de9647 100644
--- a/products/warehouse_sources/backend/models/external_data_schema.py
+++ b/products/warehouse_sources/backend/models/external_data_schema.py
@@ -270,6 +270,15 @@ class ExternalDataSchemaQuerySet(models.QuerySet["ExternalDataSchema"]):
CDC_SNAPSHOT_LANE_KEY = "cdc_snapshot_lane"
+# In `sync_type_config`: how many of this schema's runs failed in a row, and when the last of them
+# failed. `retry_limits` turns the count into this schema's retry cap and its smallest gap between
+# runs. A key here rather than a column because clearing it is what a reset is for: a reset
+# re-reads the table from the start, which is the progress a streak counts the absence of.
+FAILURE_STREAK_KEY = "failure_streak"
+FAILURE_STREAK_RUNS_KEY = "runs"
+FAILURE_STREAK_LAST_FAILED_AT_KEY = "last_failed_at"
+
+
class ExternalDataSchema( # nosemgrep: semgrep.rules.security.prefer-uuid7-django-pk -- grandfathered UUIDT primary key
ModelActivityMixin, CreatedMetaFields, UpdatedMetaFields, UUIDTModel, DeletedMetaFields
):
@@ -500,6 +509,54 @@ class ExternalDataSchema( # nosemgrep: semgrep.rules.security.prefer-uuid7-djan
"""True when syncing will not resume without user action."""
return not self.should_sync or self.cdc_halted
+ @property
+ def _failure_streak(self) -> dict[str, Any]:
+ """The streak marker, or an empty one for any value this cannot read.
+
+ Both readers below run on the terminal status write of every run, so a raise here would
+ fail every sync of the schema rather than throttle it.
+ """
+ config = self.sync_type_config if isinstance(self.sync_type_config, dict) else {}
+ streak = config.get(FAILURE_STREAK_KEY)
+ return streak if isinstance(streak, dict) else {}
+
+ @property
+ def failed_runs_in_a_row(self) -> int:
+ """Runs of this schema that failed since its last completed run."""
+ runs = self._failure_streak.get(FAILURE_STREAK_RUNS_KEY)
+ return runs if isinstance(runs, int) and not isinstance(runs, bool) and runs > 0 else 0
+
+ @property
+ def failure_streak_last_failed_at(self) -> datetime | None:
+ """When the newest run in the streak failed, or None while there is no streak."""
+ stamped = self._failure_streak.get(FAILURE_STREAK_LAST_FAILED_AT_KEY)
+ if not isinstance(stamped, str):
+ return None
+ try:
+ parsed = datetime.fromisoformat(stamped)
+ except ValueError:
+ return None
+ return parsed if parsed.tzinfo else parsed.replace(tzinfo=UTC)
+
+ def note_failed_run(self, failed_at: datetime) -> None:
+ """Add one failed run to the streak, in memory.
+
+ The caller saves `sync_type_config` under the row lock it already holds for the run's
+ terminal status, so the streak lands in that statement rather than in a second
+ read-modify-write that could race it.
+ """
+ config = self.sync_type_config if isinstance(self.sync_type_config, dict) else {}
+ config[FAILURE_STREAK_KEY] = {
+ FAILURE_STREAK_RUNS_KEY: self.failed_runs_in_a_row + 1,
+ FAILURE_STREAK_LAST_FAILED_AT_KEY: failed_at.isoformat(),
+ }
+ self.sync_type_config = config
+
+ def clear_failure_streak(self) -> None:
+ """Drop the streak, in memory. The caller saves `sync_type_config`."""
+ if isinstance(self.sync_type_config, dict):
+ self.sync_type_config.pop(FAILURE_STREAK_KEY, None)
+
@property
def cdc_mode(self) -> Literal["snapshot", "streaming"] | None:
if self.sync_type_config:
@@ -1665,6 +1722,10 @@ def update_should_sync(
schema = ExternalDataSchema.objects.select_related("source").get(id=schema_id, team_id=team_id)
schema.should_sync = should_sync
+ # Turning syncing back on says the source is worth trying again, so the next run starts on
+ # the full retry cap and the normal cadence.
+ if should_sync:
+ schema.clear_failure_streak()
with sync_disable_context(error_message=disable_error_message, exclude_workflow_id=disable_exclude_workflow_id):
schema.save()
diff --git a/products/warehouse_sources/backend/presentation/views/external_data_schema.py b/products/warehouse_sources/backend/presentation/views/external_data_schema.py
index 3725f7676759..1f27f54a07ef 100644
--- a/products/warehouse_sources/backend/presentation/views/external_data_schema.py
+++ b/products/warehouse_sources/backend/presentation/views/external_data_schema.py
@@ -2205,6 +2205,7 @@ class ExternalDataSchemaViewset(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
status=ExternalDataJob.Status.FAILED,
logger=logger,
latest_error="Sync cancelled by user",
+ counts_as_source_failure=False,
)
return Response(status=status.HTTP_200_OK)
@@ -2216,6 +2217,7 @@ class ExternalDataSchemaViewset(TeamAndOrgViewSetMixin, viewsets.ModelViewSet):
status=ExternalDataJob.Status.FAILED,
logger=logger,
latest_error="Sync cancelled by user",
+ counts_as_source_failure=False,
)
if model.status != ExternalDataJob.Status.FAILED:
# The job reached a different terminal state concurrently (e.g. Completed).
diff --git a/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py b/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py
index 35f70fe54dcd..124eead0663c 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/external_data_job.py
@@ -62,6 +62,8 @@ from products.warehouse_sources.backend.temporal.data_imports.metrics import (
get_data_import_finished_metric,
get_fast_returned_run_metric,
get_import_handoffs_per_run_metric,
+ get_retry_budget_reduced_metric,
+ get_run_deferred_metric,
get_v3_lock_skipped_metric,
get_version_check_skipped_metric,
)
@@ -80,6 +82,7 @@ from products.warehouse_sources.backend.temporal.data_imports.post_import_job im
)
from products.warehouse_sources.backend.temporal.data_imports.retry_limits import (
MAX_RESUMABLE_SOURCE_RETRIES_PRODUCTION,
+ import_retry_budget,
)
from products.warehouse_sources.backend.temporal.data_imports.row_tracking import finish_row_tracking, get_rows
from products.warehouse_sources.backend.temporal.data_imports.sources import SourceRegistry
@@ -580,6 +583,7 @@ async def _update_job_status(inputs: UpdateExternalDataJobStatusInputs, logger:
source: ExternalDataSource | None = None
has_non_retryable_error = False
+ platform_failure = False
if inputs.internal_error:
logger.exception(
f"External data job failed for external data schema {inputs.schema_id} on job {inputs.job_id} with error: {inputs.internal_error}"
@@ -646,12 +650,21 @@ async def _update_job_status(inputs: UpdateExternalDataJobStatusInputs, logger:
if transient_message is not None:
inputs.latest_error = transient_message
+ # A failure PostHog caused says nothing about the source, and an auto-disabled schema runs
+ # again only once a person turns syncing back on, so neither may throttle the next run.
+ counts_as_source_failure = (
+ not platform_failure
+ and not has_non_retryable_error
+ and (inputs.latest_error not in (WORKER_RESTART_ERROR_MESSAGE, CANCELLED_RUN_MESSAGE))
+ )
+
await database_sync_to_async_pool(update_external_job_status)(
job_id=job_id,
status=ExternalDataJob.Status(inputs.status),
latest_error=inputs.latest_error,
logger=logger,
team_id=inputs.team_id,
+ counts_as_source_failure=counts_as_source_failure,
)
if inputs.internal_error and source is not None:
@@ -985,6 +998,14 @@ class ExternalDataJobWorkflow(PostHogWorkflow):
extra={"schema_id": str(inputs.external_data_schema_id)},
)
+ if lock_result is not None and lock_result.deferred:
+ workflow.logger.info(
+ "Run deferred because this sync keeps failing",
+ extra={"schema_id": str(inputs.external_data_schema_id)},
+ )
+ get_run_deferred_metric().add(1)
+ return
+
if lock_result is None or not lock_result.acquired:
workflow.logger.info(
"V3 pipeline lock not acquired, skipping",
@@ -1031,6 +1052,7 @@ class ExternalDataJobWorkflow(PostHogWorkflow):
hit_billing_limit = False
source_templates_needed = True
import_handoffs_are_free = False
+ failed_runs_in_a_row = 0
else:
job_id = create_job_result.job_id
incremental_or_append = create_job_result.incremental_or_append
@@ -1048,6 +1070,7 @@ class ExternalDataJobWorkflow(PostHogWorkflow):
hit_billing_limit = create_job_result.hit_billing_limit
source_templates_needed = create_job_result.source_templates_needed
import_handoffs_are_free = create_job_result.import_handoffs_are_free
+ failed_runs_in_a_row = create_job_result.failed_runs_in_a_row
update_inputs.job_id = str(job_id) if job_id is not None else None
# The job-creation activity answers the billing question in the same round trip. The
@@ -1105,16 +1128,6 @@ class ExternalDataJobWorkflow(PostHogWorkflow):
},
)
- job_inputs = ImportDataActivityInputs(
- team_id=inputs.team_id,
- run_id=job_id,
- schema_id=inputs.external_data_schema_id,
- source_id=inputs.external_data_source_id,
- reset_pipeline=inputs.reset_pipeline,
- fast_return_eligible=fast_return_eligible,
- scheduled_full_refresh=scheduled_full_refresh,
- )
-
is_resumable_source = False
if source_type is not None:
source = SourceRegistry.get_source(ExternalDataSourceType(source_type))
@@ -1140,6 +1153,31 @@ class ExternalDataJobWorkflow(PostHogWorkflow):
import_start_to_close_timeout = dt.timedelta(hours=24)
import_max_attempts = 3
+ # Derived from a recorded activity result, so a replay picks the same cap.
+ full_import_max_attempts = import_max_attempts
+ import_max_attempts = import_retry_budget(import_max_attempts, failed_runs_in_a_row)
+ if import_max_attempts != full_import_max_attempts:
+ workflow.logger.info(
+ "Retry cap reduced because this sync keeps failing",
+ extra={
+ "schema_id": str(inputs.external_data_schema_id),
+ "failed_runs_in_a_row": failed_runs_in_a_row,
+ "max_attempts": import_max_attempts,
+ },
+ )
+ get_retry_budget_reduced_metric(source_type=source_type).add(1)
+
+ job_inputs = ImportDataActivityInputs(
+ team_id=inputs.team_id,
+ run_id=job_id,
+ schema_id=inputs.external_data_schema_id,
+ source_id=inputs.external_data_source_id,
+ reset_pipeline=inputs.reset_pipeline,
+ fast_return_eligible=fast_return_eligible,
+ scheduled_full_refresh=scheduled_full_refresh,
+ on_resumable_retry_budget=is_resumable_source,
+ )
+
# A hand-off loop schedules the import activity more than once, which a history recorded
# without it cannot replay. Two things keep replay on the recorded branch. The flag is
# the output of the job-creation activity, so replay reads the value the first execution
diff --git a/products/warehouse_sources/backend/temporal/data_imports/metrics.py b/products/warehouse_sources/backend/temporal/data_imports/metrics.py
index bc6ed71a036b..12691fce974e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/metrics.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/metrics.py
@@ -76,6 +76,40 @@ def get_version_check_skipped_metric() -> MetricCounter:
)
+def get_retry_budget_reduced_metric(source_type: str | None) -> MetricCounter:
+ # Read against `data_import_finished{status="failed"}`: the two converging means the give-up
+ # covers the failures it was built for.
+ return (
+ workflow.metric_meter()
+ .with_additional_attributes({"source_type": source_type or "unknown"})
+ .create_counter(
+ "data_import_retry_budget_reduced",
+ "Runs whose import retry cap was cut because the schema keeps failing.",
+ )
+ )
+
+
+def get_run_deferred_metric() -> MetricCounter:
+ # Same visibility gap as the lock and version-check metrics: the skip leaves no job row, so
+ # without this counter a schema can silently miss every scheduled slot.
+ return workflow.metric_meter().create_counter(
+ "data_import_run_deferred", "Scheduled runs that stood down because the schema keeps failing."
+ )
+
+
+def get_progressless_stand_down_metric(source_type: str | None) -> MetricCounter:
+ # The resumable cap is justified only while attempts continue, and this counts where they did
+ # not, so a source that cannot checkpoint at all shows up as a class rather than as a ticket.
+ return (
+ activity.metric_meter()
+ .with_additional_attributes({"source_type": source_type or "unknown"})
+ .create_counter(
+ "data_import_progressless_stand_down",
+ "Imports that stopped retrying because no attempt committed anything to resume from.",
+ )
+ )
+
+
def get_worker_shutdown_handoff_metric(source_type: str | None) -> MetricCounter:
# Counts imports that gave up a shutting-down worker so another pod can continue them. An
# import that never hands off keeps its pod alive for the whole graceful shutdown timeout.
diff --git a/products/warehouse_sources/backend/temporal/data_imports/retry_limits.py b/products/warehouse_sources/backend/temporal/data_imports/retry_limits.py
index 97a0e25e214d..7cdcc6fcac5a 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/retry_limits.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/retry_limits.py
@@ -1,3 +1,50 @@
-# The largest retry cap an import activity gets. It lives apart from `external_data_job` so the
-# schema model can read it: that module loads temporalio, and the model loads during django.setup().
+"""How many retries one import run may spend, and how often a failing schema may run at all.
+
+It lives apart from `external_data_job` so the schema model can read it: that module loads
+temporalio, and the model loads during django.setup().
+"""
+
+import datetime as dt
+
+# The largest retry cap an import activity gets.
MAX_RESUMABLE_SOURCE_RETRIES_PRODUCTION = 20
+
+# Consecutive failed runs after which a schema stops getting the full retry cap. Of the schemas
+# that completed at least one run in a week of production, 96% of their failure streaks ended
+# within four runs, so a streak this long means a broken source rather than a flapping one.
+GIVE_UP_AFTER_FAILED_RUNS = 5
+
+# Two rather than one so a single worker restart cannot be the reason a run fails.
+FAILING_SCHEMA_MAX_IMPORT_ATTEMPTS = 2
+
+# Attempts an import on the resumable cap may spend before it has committed anything to resume
+# from. Above the per-run non-retryable allowance of four attempts, so an error a source
+# classifies as non-retryable still gives up first and keeps its own message.
+PROGRESSLESS_RESUMABLE_ATTEMPTS = 4
+
+# The smallest gap between two runs of a failing schema, and the cap that gap grows to. The cap
+# bounds how stale a table gets once its source recovers.
+FAILING_SCHEMA_RUN_GAP_BASE = dt.timedelta(minutes=10)
+FAILING_SCHEMA_RUN_GAP_CAP = dt.timedelta(hours=1)
+
+
+def import_retry_budget(budget: int, failed_runs_in_a_row: int) -> int:
+ """`budget` for a healthy schema, cut to a floor once the streak says the source is broken."""
+ if failed_runs_in_a_row < GIVE_UP_AFTER_FAILED_RUNS:
+ return budget
+ return min(budget, FAILING_SCHEMA_MAX_IMPORT_ATTEMPTS)
+
+
+def min_gap_between_runs(failed_runs_in_a_row: int) -> dt.timedelta | None:
+ """How long after its last failure a schema may run again, or None while it is not in a streak.
+
+ The gap doubles per failed run past the threshold, so a source that recovers on its own loses
+ at most one cap-length window, while one that never recovers settles at the cap.
+ """
+ if failed_runs_in_a_row < GIVE_UP_AFTER_FAILED_RUNS:
+ return None
+ doublings = failed_runs_in_a_row - GIVE_UP_AFTER_FAILED_RUNS
+ # Bounded before the shift so a long-dead schema cannot build an overflowing timedelta.
+ if doublings >= 32:
+ return FAILING_SCHEMA_RUN_GAP_CAP
+ return min(FAILING_SCHEMA_RUN_GAP_BASE * (2**doublings), FAILING_SCHEMA_RUN_GAP_CAP)
diff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/test_import_handoff_loop.py b/products/warehouse_sources/backend/temporal/data_imports/tests/test_import_handoff_loop.py
index 63a3f73f72c6..434a153b7a09 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/tests/test_import_handoff_loop.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/test_import_handoff_loop.py
@@ -25,6 +25,10 @@ from products.warehouse_sources.backend.temporal.data_imports.external_data_job
UpdateExternalDataJobStatusInputs,
)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.typings import PipelineResult
+from products.warehouse_sources.backend.temporal.data_imports.retry_limits import (
+ FAILING_SCHEMA_MAX_IMPORT_ATTEMPTS,
+ GIVE_UP_AFTER_FAILED_RUNS,
+)
from products.warehouse_sources.backend.temporal.data_imports.workflow_activities.acquire_v3_lock import (
AcquireV3LockActivityInputs,
AcquireV3LockActivityOutputs,
@@ -73,9 +77,13 @@ def _activities(
import_attempts: list[int],
updates: list[UpdateExternalDataJobStatusInputs],
buffer_one: list[str],
+ failed_runs_in_a_row: int = 0,
+ deferred: bool = False,
) -> list:
@activity.defn(name="acquire_v3_pipeline_lock_activity")
async def acquire_lock(inputs: AcquireV3LockActivityInputs) -> AcquireV3LockActivityOutputs:
+ if deferred:
+ return AcquireV3LockActivityOutputs(acquired=False, token="token", deferred=True)
return AcquireV3LockActivityOutputs(acquired=True, token="token")
@activity.defn(name="create_external_data_job_model_activity")
@@ -89,6 +97,7 @@ def _activities(
billing_limit_checked=True,
source_templates_needed=False,
import_handoffs_are_free=handoffs_are_free,
+ failed_runs_in_a_row=failed_runs_in_a_row,
)
@activity.defn(name="import_data_activity_sync")
@@ -126,7 +135,13 @@ def _patch_ids(history: WorkflowHistory) -> set[str]:
return patch_ids
-async def _run_workflow(script: list[str], *, handoffs_are_free: bool = True) -> _WorkflowRun:
+async def _run_workflow(
+ script: list[str],
+ *,
+ handoffs_are_free: bool = True,
+ failed_runs_in_a_row: int = 0,
+ deferred: bool = False,
+) -> _WorkflowRun:
import_inputs: list[ImportDataActivityInputs] = []
import_attempts: list[int] = []
updates: list[UpdateExternalDataJobStatusInputs] = []
@@ -137,6 +152,8 @@ async def _run_workflow(script: list[str], *, handoffs_are_free: bool = True) ->
mock.patch.object(workflow_module.workflow, "start_child_workflow", new_callable=mock.AsyncMock),
mock.patch.object(workflow_module, "get_data_import_finished_metric"),
mock.patch.object(workflow_module, "get_import_handoffs_per_run_metric") as handoffs_metric,
+ mock.patch.object(workflow_module, "get_retry_budget_reduced_metric"),
+ mock.patch.object(workflow_module, "get_run_deferred_metric"),
):
async with await WorkflowEnvironment.start_time_skipping() as env:
async with Worker(
@@ -150,6 +167,8 @@ async def _run_workflow(script: list[str], *, handoffs_are_free: bool = True) ->
import_attempts=import_attempts,
updates=updates,
buffer_one=buffer_one,
+ failed_runs_in_a_row=failed_runs_in_a_row,
+ deferred=deferred,
),
workflow_runner=UnsandboxedWorkflowRunner(),
activity_executor=ThreadPoolExecutor(max_workers=10),
@@ -281,3 +300,35 @@ async def test_histories_replay_on_the_branch_they_recorded(handoffs_are_free: b
workflows=[ExternalDataJobWorkflow],
workflow_runner=UnsandboxedWorkflowRunner(),
).replay_workflow(run.history)
+
+
+async def test_a_failing_schema_gets_fewer_attempts_than_a_healthy_one():
+ # The streak travels on the create-job activity's result and has to reach the import's retry
+ # policy. Nothing else fails if that line is dropped, so the throttle would never fire.
+ healthy = await _run_workflow([FAIL], failed_runs_in_a_row=0)
+ failing = await _run_workflow([FAIL], failed_runs_in_a_row=GIVE_UP_AFTER_FAILED_RUNS)
+
+ assert healthy.failed and failing.failed
+ assert len(failing.import_attempts) == FAILING_SCHEMA_MAX_IMPORT_ATTEMPTS
+ assert len(failing.import_attempts) < len(healthy.import_attempts)
+ assert [update.status for update in failing.updates] == [ExternalDataJob.Status.FAILED]
+
+
+async def test_a_deferred_run_imports_nothing_and_writes_no_status():
+ # A terminal status here would repaint the schema and overwrite the error the customer reads.
+ run = await _run_workflow([SUCCEED], deferred=True)
+
+ assert not run.failed
+ assert run.import_inputs == []
+ assert run.updates == []
+ assert run.buffer_one_triggers == 0
+
+
+async def test_the_import_learns_which_retry_cap_it_is_on():
+ # The activity's own stand-down depends on knowing which cap the workflow gave it.
+ run = await _run_workflow([SUCCEED])
+
+ assert [inputs.on_resumable_retry_budget for inputs in run.import_inputs] == [True]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/tests/test_retry_limits.py b/products/warehouse_sources/backend/temporal/data_imports/tests/test_retry_limits.py
new file mode 100644
index 000000000000..0a0bea34e702
--- /dev/null
+++ b/products/warehouse_sources/backend/temporal/data_imports/tests/test_retry_limits.py
@@ -0,0 +1,51 @@
+import datetime as dt
+
+from django.test import SimpleTestCase
+
+from parameterized import parameterized
+
+from products.warehouse_sources.backend.temporal.data_imports.retry_limits import (
+ FAILING_SCHEMA_MAX_IMPORT_ATTEMPTS,
+ FAILING_SCHEMA_RUN_GAP_BASE,
+ FAILING_SCHEMA_RUN_GAP_CAP,
+ GIVE_UP_AFTER_FAILED_RUNS,
+ import_retry_budget,
+ min_gap_between_runs,
+)
+
+
+class TestImportRetryBudget(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("healthy_keeps_resumable_cap", 20, 0, 20),
+ ("one_failure_keeps_cap", 20, 1, 20),
+ ("last_run_before_the_threshold_keeps_cap", 20, GIVE_UP_AFTER_FAILED_RUNS - 1, 20),
+ ("threshold_cuts_resumable_cap", 20, GIVE_UP_AFTER_FAILED_RUNS, FAILING_SCHEMA_MAX_IMPORT_ATTEMPTS),
+ ("past_threshold_cuts_incremental_cap", 9, 12, FAILING_SCHEMA_MAX_IMPORT_ATTEMPTS),
+ ("never_raises_a_smaller_cap", 1, 50, 1),
+ ]
+ )
+ def test_budget(self, _name: str, budget: int, failed_runs: int, expected: int) -> None:
+ assert import_retry_budget(budget, failed_runs) == expected
+
+
+class TestMinGapBetweenRuns(SimpleTestCase):
+ @parameterized.expand(
+ [
+ ("healthy_schema_has_no_gap", 0, None),
+ ("below_threshold_has_no_gap", GIVE_UP_AFTER_FAILED_RUNS - 1, None),
+ ("threshold_starts_at_the_base", GIVE_UP_AFTER_FAILED_RUNS, FAILING_SCHEMA_RUN_GAP_BASE),
+ ("gap_doubles_per_failed_run", GIVE_UP_AFTER_FAILED_RUNS + 1, FAILING_SCHEMA_RUN_GAP_BASE * 2),
+ ("gap_stops_at_the_cap", GIVE_UP_AFTER_FAILED_RUNS + 20, FAILING_SCHEMA_RUN_GAP_CAP),
+ # A schema that has failed for months must not build a timedelta that overflows.
+ ("an_absurd_streak_stays_at_the_cap", 10**9, FAILING_SCHEMA_RUN_GAP_CAP),
+ ]
+ )
+ def test_gap(self, _name: str, failed_runs: int, expected: dt.timedelta | None) -> None:
+ assert min_gap_between_runs(failed_runs) == expected
+
+ def test_the_gap_never_passes_the_cap(self) -> None:
+ for failed_runs in range(GIVE_UP_AFTER_FAILED_RUNS, GIVE_UP_AFTER_FAILED_RUNS + 40):
+ gap = min_gap_between_runs(failed_runs)
+ assert gap is not None
+ assert gap <= FAILING_SCHEMA_RUN_GAP_CAP
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/acquire_v3_lock.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/acquire_v3_lock.py
index 2543b9cdb33e..aa7b3d9030c4 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/acquire_v3_lock.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/acquire_v3_lock.py
@@ -19,6 +19,7 @@ from posthog.temporal.common.logger import get_logger
from products.data_warehouse.backend.facade.api import update_external_job_status
from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
+from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
from products.warehouse_sources.backend.temporal.data_imports.metrics import (
LOCK_TAKEOVER_LATEST_ERROR,
TERMINAL_JOB_STATUSES,
@@ -30,6 +31,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
release_v3_pipeline_lock,
write_v3_pipeline_lock_meta,
)
+from products.warehouse_sources.backend.temporal.data_imports.retry_limits import min_gap_between_runs
from products.warehouse_sources_queue.backend.sdk import BatchQueue
LOGGER = get_logger(__name__)
@@ -66,6 +68,11 @@ class AcquireV3LockActivityInputs:
class AcquireV3LockActivityOutputs:
acquired: bool
token: str
+ # True when the run stood down because the schema's runs keep failing, rather than because
+ # another run holds the lock. The workflow skips either way, so this only separates the two in
+ # the logs and the metrics. Defaults False so a payload that predates the field reads as the
+ # lock miss its history recorded.
+ deferred: bool = False
@dataclasses.dataclass
@@ -93,6 +100,10 @@ def acquire_v3_pipeline_lock_activity(inputs: AcquireV3LockActivityInputs) -> Ac
logger.error("v3_pipeline_lock_missing_workflow_run_id", schema_id=str(inputs.schema_id))
return AcquireV3LockActivityOutputs(acquired=False, token="")
+ # Before the lock, so a stood-down run never takes one and never needs to release one.
+ if _defer_failing_schema(inputs, logger):
+ return AcquireV3LockActivityOutputs(acquired=False, token=token, deferred=True)
+
acquired = acquire_v3_pipeline_lock(inputs.team_id, str(inputs.schema_id), token)
if not acquired:
acquired = _take_over_lock_if_holder_finished(inputs, token, logger)
@@ -117,6 +128,47 @@ def acquire_v3_pipeline_lock_activity(inputs: AcquireV3LockActivityInputs) -> Ac
return AcquireV3LockActivityOutputs(acquired=acquired, token=token)
+def _defer_failing_schema(inputs: AcquireV3LockActivityInputs, logger: Any) -> bool:
+ """Whether this run stands down because the schema's runs keep failing.
+
+ The schedule keeps its cadence and its runs are spaced out instead, so a source nothing can
+ reach costs one run per gap rather than one per slot. A reset run always goes ahead, because a
+ reset is the person asking for the table to be re-read from the start.
+
+ False on any error. This decides whether a sync runs at all, and the retry cap already bounds
+ what one failing run costs, so going ahead is the safe answer.
+ """
+ try:
+ schema = (
+ ExternalDataSchema.objects.filter(id=inputs.schema_id, team_id=inputs.team_id)
+ .only("sync_type_config")
+ .first()
+ )
+ if schema is None or schema.reset_pipeline:
+ return False
+
+ gap = min_gap_between_runs(schema.failed_runs_in_a_row)
+ last_failed_at = schema.failure_streak_last_failed_at
+ if gap is None or last_failed_at is None:
+ return False
+
+ since_last_failure = datetime.now(UTC) - last_failed_at
+ if since_last_failure >= gap:
+ return False
+
+ logger.info(
+ "data_import_run_deferred",
+ schema_id=str(inputs.schema_id),
+ failed_runs_in_a_row=schema.failed_runs_in_a_row,
+ gap_seconds=int(gap.total_seconds()),
+ since_last_failure_seconds=int(since_last_failure.total_seconds()),
+ )
+ return True
+ except Exception as e:
+ logger.warning("data_import_run_defer_check_failed", schema_id=str(inputs.schema_id), error=str(e))
+ return False
+
+
def _take_over_lock_if_holder_finished(inputs: AcquireV3LockActivityInputs, token: str, logger: Any) -> bool:
"""Decide whether to take over the Redis pipeline lock from its current holder.
@@ -372,6 +424,8 @@ def _take_over_stale_running_job(
status=ExternalDataJob.Status.FAILED,
logger=takeover_logger,
latest_error=LOCK_TAKEOVER_LATEST_ERROR,
+ # The stuck run never reported an outcome, so it says nothing about the source.
+ counts_as_source_failure=False,
)
except Exception as e:
logger.warning(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/create_job_model.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/create_job_model.py
index 458264f148a1..cf0a6b7e3698 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/create_job_model.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/create_job_model.py
@@ -325,6 +325,11 @@ class CreateExternalDataJobModelActivityOutputs:
# recorded with this activity's result, so a replay takes the same branch. Defaults False so a
# payload that predates the field keeps the single import execution its history recorded.
import_handoffs_are_free: bool = False
+ # Runs of this schema that failed since its last completed run, this one excluded. The workflow
+ # turns it into the import's retry cap (`retry_limits.import_retry_budget`). Read here because a
+ # workflow must not read the DB, and recorded with this activity's result so a replay picks the
+ # same cap. Defaults to 0 so a payload that predates the field keeps the full cap.
+ failed_runs_in_a_row: int = 0
@activity.defn
@@ -444,6 +449,9 @@ def create_external_data_job_model_activity(
lambda: billing_limit_reached(job, source, inputs.team_id, logger)
)
+ # Read before this run's own outcome can move it, so it is not counted against itself.
+ failed_runs_in_a_row = schema.failed_runs_in_a_row
+
source_templates_needed = source.source_type == ExternalDataSourceType.STRIPE and not (
ExternalDataJob.objects.filter(
team_id=inputs.team_id, pipeline_id=source.id, status=ExternalDataJob.Status.COMPLETED
@@ -469,6 +477,7 @@ def create_external_data_job_model_activity(
hit_billing_limit=hit_billing_limit,
source_templates_needed=source_templates_needed,
import_handoffs_are_free=settings.DATA_WAREHOUSE_IMPORT_FREE_HANDOFFS_ENABLED,
+ failed_runs_in_a_row=failed_runs_in_a_row,
)
except V3PipelineLockLostError:
# The takeover race the guard handles, not a defect — skip the generic handler's
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.py
index d8e5ca17eaf3..aaaa15e2a807 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
@@ -52,6 +52,7 @@ from products.warehouse_sources.backend.temporal.data_imports.import_attempt imp
)
from products.warehouse_sources.backend.temporal.data_imports.metrics import (
TERMINAL_JOB_STATUSES,
+ get_progressless_stand_down_metric,
get_worker_shutdown_handoff_metric,
)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.common.extract import (
@@ -72,6 +73,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.rep
)
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.typings import PipelineResult
from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_sync import PipelineInputs
+from products.warehouse_sources.backend.temporal.data_imports.retry_limits import PROGRESSLESS_RESUMABLE_ATTEMPTS
from products.warehouse_sources.backend.temporal.data_imports.row_tracking import setup_row_tracking
from products.warehouse_sources.backend.temporal.data_imports.sources import SourceRegistry
from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import (
@@ -135,6 +137,9 @@ class ImportDataActivityInputs:
handoff_count: int = 0
# Attempts that earlier executions of this activity used in the same workflow run.
prior_attempts: int = 0
+ # True when the workflow gave this run the resumable retry cap. Defaults False so a payload
+ # that predates the field keeps every attempt its history recorded.
+ on_resumable_retry_budget: bool = False
@property
def properties_to_log(self) -> dict[str, Any]:
@@ -715,7 +720,13 @@ async def _import_data_with_reporting(inputs: ImportDataActivityInputs, logger:
# here (deleted/misconfigured cluster hostname, revoked credentials) would
# otherwise bypass the guard in `_run` and be retried up to the activity's
# maximum on every scheduled sync. Route it through the same policy.
- await _handle_import_error(job_inputs, logger, e)
+ await _handle_import_error(
+ job_inputs,
+ logger,
+ e,
+ resumable_source_manager=resumable_source_manager,
+ on_resumable_retry_budget=inputs.on_resumable_retry_budget,
+ )
return await _run(
job_inputs=job_inputs,
@@ -726,6 +737,7 @@ async def _import_data_with_reporting(inputs: ImportDataActivityInputs, logger:
resumable_source_manager=resumable_source_manager,
source_cursor_manager=source_cursor_manager,
incremental_checkpoints_allowed=incremental_checkpoints_allowed,
+ on_resumable_retry_budget=inputs.on_resumable_retry_budget,
resumed_incremental_run_uuid=resumed_incremental_run_uuid,
resumed_incremental_value=resumed_incremental_value,
)
@@ -812,10 +824,34 @@ def _log_worker_shutdown_during_import(logger: FilteringBoundLogger) -> None:
)
+def _spent_resumable_cap_without_resuming(
+ resumable_source_manager: ResumableSourceManager | None,
+ on_resumable_retry_budget: bool,
+) -> bool:
+ """Whether this run has used its progressless share of the resumable cap.
+
+ The resumable cap is large because each attempt continues where the last stopped. An attempt
+ that never checkpointed restarts from row 0 instead, so a run that has committed nothing by
+ now would re-read the same rows for every attempt that is left.
+
+ False on any error reading the checkpoint, because keeping the attempts is the safe answer.
+ """
+ if not on_resumable_retry_budget or resumable_source_manager is None:
+ return False
+ if current_import_attempt() <= PROGRESSLESS_RESUMABLE_ATTEMPTS:
+ return False
+ try:
+ return not resumable_source_manager.can_resume()
+ except Exception:
+ return False
+
+
async def _handle_import_error(
job_inputs: PipelineInputs,
logger: FilteringBoundLogger,
error: Exception,
+ resumable_source_manager: ResumableSourceManager | None = None,
+ on_resumable_retry_budget: bool = False,
) -> NoReturn:
"""Route an import error through the source's non-retryable error policy.
@@ -1042,6 +1078,19 @@ async def _handle_import_error(
job_inputs.team_id, str(job_inputs.source_id), job_inputs.run_id, error_msg, logger, error
)
+ # Below the classified branches, which are PostHog-side or vendor-side blips that another
+ # attempt does clear. Raised `from error` so the finalizer still classifies the real failure
+ # and the customer still reads its message rather than this decision.
+ if _spent_resumable_cap_without_resuming(resumable_source_manager, on_resumable_retry_budget):
+ await logger.awarning(error_msg)
+ await logger.ainfo(
+ "No attempt of this run has anything to resume from, so it stops retrying",
+ attempt=current_import_attempt(),
+ )
+ if activity.in_activity():
+ get_progressless_stand_down_metric(str(job_inputs.job_type)).add(1)
+ raise NonRetryableException() from error
+
retryable_errors = source_cls.get_retryable_errors()
if error_message_matches(error_msg, retryable_errors):
await logger.awarning(error_msg)
@@ -1064,6 +1113,7 @@ async def _run(
incremental_checkpoints_allowed: bool = False,
resumed_incremental_run_uuid: str | None = None,
resumed_incremental_value: Any = None,
+ on_resumable_retry_budget: bool = False,
) -> PipelineResult:
try:
reset_pipeline = reset_pipeline or source_response.destination_reset_required
@@ -1088,4 +1138,10 @@ async def _run(
await logger.adebug("Finished running pipeline")
return result
except Exception as e:
- await _handle_import_error(job_inputs, logger, e)
+ await _handle_import_error(
+ job_inputs,
+ logger,
+ e,
+ resumable_source_manager=resumable_source_manager,
+ on_resumable_retry_budget=on_resumable_retry_budget,
+ )
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/test_acquire_v3_lock.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/test_acquire_v3_lock.py
index f2406199ddbc..90a28c76d84e 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/test_acquire_v3_lock.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/test_acquire_v3_lock.py
@@ -5,8 +5,14 @@ import pytest
import time_machine
from unittest.mock import AsyncMock, MagicMock, patch
+from django.db import OperationalError
+
from temporalio.client import WorkflowExecutionStatus
+from posthog.models import Organization, Team
+
+from products.warehouse_sources.backend.models.external_data_schema import ExternalDataSchema
+from products.warehouse_sources.backend.models.external_data_source import ExternalDataSource
from products.warehouse_sources.backend.temporal.data_imports.workflow_activities.acquire_v3_lock import (
AcquireV3LockActivityInputs,
CheckPipelineVersionActivityInputs,
@@ -117,6 +123,86 @@ class TestAcquireV3PipelineLockActivity:
assert result.token == ""
+def _schema_with_config(sync_type_config: dict) -> ExternalDataSchema:
+ org = Organization.objects.create(name="org")
+ team = Team.objects.create(organization=org, name="t")
+ source = ExternalDataSource.objects.create(source_id="src", connection_id="conn", team=team, source_type="Stripe")
+ return ExternalDataSchema.objects.create(name="Charge", team=team, source=source, sync_type_config=sync_type_config)
+
+
+def _streak(runs: int, failed_ago: timedelta) -> dict:
+ return {"runs": runs, "last_failed_at": (datetime.now(UTC) - failed_ago).isoformat()}
+
+
+class TestAcquireV3PipelineLockActivityDeferral:
+ @pytest.mark.parametrize(
+ "_name,config_extra,runs,failed_ago,expect_deferred",
+ [
+ ("streak_at_threshold_inside_gap", {}, 5, timedelta(minutes=2), True),
+ ("long_streak_inside_capped_gap", {}, 30, timedelta(minutes=40), True),
+ ("streak_at_threshold_past_gap", {}, 5, timedelta(minutes=11), False),
+ ("long_streak_past_capped_gap", {}, 30, timedelta(minutes=61), False),
+ ("streak_below_threshold", {}, 4, timedelta(seconds=1), False),
+ ("reset_pipeline_runs_anyway", {"reset_pipeline": True}, 8, timedelta(minutes=1), False),
+ ],
+ )
+ @patch(f"{MODULE}.write_v3_pipeline_lock_meta")
+ @patch(f"{MODULE}.acquire_v3_pipeline_lock", return_value=True)
+ @patch(f"{MODULE}.activity")
+ @patch(f"{MODULE}.bind_contextvars")
+ def test_deferral(
+ self,
+ _bind: MagicMock,
+ mock_activity: MagicMock,
+ mock_acquire: MagicMock,
+ _mock_write_meta: MagicMock,
+ _name: str,
+ config_extra: dict,
+ runs: int,
+ failed_ago: timedelta,
+ expect_deferred: bool,
+ ) -> None:
+ mock_activity.info.return_value.workflow_run_id = WORKFLOW_RUN_ID
+ mock_activity.info.return_value.workflow_id = "wf-abc-123"
+ schema = _schema_with_config({**config_extra, "failure_streak": _streak(runs, failed_ago)})
+
+ result = acquire_v3_pipeline_lock_activity(
+ AcquireV3LockActivityInputs(team_id=schema.team_id, schema_id=schema.id)
+ )
+
+ assert result.deferred is expect_deferred
+ assert result.acquired is not expect_deferred
+ assert result.token == WORKFLOW_RUN_ID
+ if expect_deferred:
+ mock_acquire.assert_not_called()
+ else:
+ mock_acquire.assert_called_once()
+
+ @patch(f"{MODULE}.write_v3_pipeline_lock_meta")
+ @patch(f"{MODULE}.acquire_v3_pipeline_lock", return_value=True)
+ @patch(f"{MODULE}.ExternalDataSchema.objects")
+ @patch(f"{MODULE}.activity")
+ @patch(f"{MODULE}.bind_contextvars")
+ def test_a_failing_schema_read_does_not_stop_the_sync(
+ self,
+ _bind: MagicMock,
+ mock_activity: MagicMock,
+ mock_objects: MagicMock,
+ mock_acquire: MagicMock,
+ _mock_write_meta: MagicMock,
+ ) -> None:
+ mock_activity.info.return_value.workflow_run_id = WORKFLOW_RUN_ID
+ mock_activity.info.return_value.workflow_id = "wf-abc-123"
+ mock_objects.filter.side_effect = OperationalError("db unavailable")
+
+ result = acquire_v3_pipeline_lock_activity(AcquireV3LockActivityInputs(team_id=TEAM_ID, schema_id=SCHEMA_ID))
+
+ assert result.deferred is False
+ assert result.acquired is True
+ mock_acquire.assert_called_once()
+
+
class TestTakeOverStaleLock:
HOLDER_TOKEN = "stale-run-999"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_create_job_model.py b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_create_job_model.py
index 5002b9b2b98d..c73bc0ea15ee 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_create_job_model.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/workflow_activities/tests/test_create_job_model.py
@@ -318,6 +318,28 @@ class TestCreateJobActivityStatusOrdering:
assert ExternalDataJob.objects.filter(schema_id=schema.id).exists()
assert schema.status == ExternalDataSchema.Status.FAILED
+ @patch(f"{MODULE}.close_old_connections")
+ @patch(f"{MODULE}.activity")
+ def test_outputs_carry_the_schemas_failure_streak(
+ self, mock_activity: MagicMock, _mock_close_connections: MagicMock
+ ) -> None:
+ mock_activity.info.return_value.workflow_id = "wf-1"
+ mock_activity.info.return_value.workflow_run_id = "run-1"
+ team = _team()
+ schema = _schema(team, None)
+ schema.sync_type_config = {
+ "failure_streak": {"runs": 4, "last_failed_at": (timezone.now() - dt.timedelta(minutes=5)).isoformat()}
+ }
+ schema.save()
+
+ outputs = create_external_data_job_model_activity(
+ CreateExternalDataJobModelActivityInputs(
+ team_id=team.id, schema_id=schema.id, source_id=schema.source_id, billable=True
+ )
+ )
+
+ assert outputs.failed_runs_in_a_row == 4
+
@pytest.mark.django_db
class TestCreateJobActivityScheduledFullRefresh:
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.py
index 64c99a6262be..2cbf6b75868e 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
@@ -40,6 +40,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.core imp
from products.warehouse_sources.backend.temporal.data_imports.pipelines.core.arrow_utils import (
SchemaColumnTypeChangedException,
)
+from products.warehouse_sources.backend.temporal.data_imports.retry_limits import PROGRESSLESS_RESUMABLE_ATTEMPTS
from products.warehouse_sources.backend.temporal.data_imports.sources.common.base import (
SimpleSource,
SourceExtractionNotImplementedError,
@@ -1667,3 +1668,105 @@ async def test_a_free_handoff_is_a_result_and_any_other_handoff_is_a_retry(hando
else:
with pytest.raises(WorkerShuttingDownError):
await import_data_activity_sync(inputs)
+
+
+ [
+ ("no_checkpoint_past_the_allowance", True, PROGRESSLESS_RESUMABLE_ATTEMPTS + 1, False, True),
+ ("checkpoint_past_the_allowance", True, PROGRESSLESS_RESUMABLE_ATTEMPTS + 1, True, False),
+ ("no_checkpoint_inside_the_allowance", True, PROGRESSLESS_RESUMABLE_ATTEMPTS, False, False),
+ ("first_attempt", True, 1, False, False),
+ # A smaller cap was chosen knowing each attempt restarts, so it stands.
+ ("not_on_the_resumable_cap", False, PROGRESSLESS_RESUMABLE_ATTEMPTS + 5, False, False),
+ ]
+)
+def test_the_progressless_stand_down_needs_a_spent_resumable_cap(
+ _name: str, on_resumable_cap: bool, attempt: int, can_resume: bool, expected: bool
+):
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = can_resume
+
+ with mock.patch.object(module, "current_import_attempt", return_value=attempt):
+ assert module._spent_resumable_cap_without_resuming(manager, on_resumable_cap) is expected
+
+
+def test_a_source_with_no_resumable_manager_never_stands_down():
+ with mock.patch.object(module, "current_import_attempt", return_value=PROGRESSLESS_RESUMABLE_ATTEMPTS + 5):
+ assert module._spent_resumable_cap_without_resuming(None, True) is False
+
+
+def test_an_unreadable_checkpoint_keeps_the_run_retrying():
+ # A Redis blip must not end a run's retries, or one unavailable dependency of ours fails syncs.
+ manager = mock.MagicMock()
+ manager.can_resume.side_effect = redis_exceptions.ConnectionError("redis is down")
+
+ with mock.patch.object(module, "current_import_attempt", return_value=PROGRESSLESS_RESUMABLE_ATTEMPTS + 5):
+ assert module._spent_resumable_cap_without_resuming(manager, True) is False
+
+
+async def test_a_spent_progressless_cap_stops_retrying_but_keeps_the_real_error():
+ # The finalizer classifies `internal_error` to pick the customer-facing message, so losing the
+ # cause here would replace a connection failure with this decision.
+ error = Exception('connection to server at "10.0.0.1", port 5432 failed: server closed the connection unexpectedly')
+ source = mock.MagicMock(spec=SimpleSource)
+ source.get_non_retryable_errors.return_value = {}
+ source.get_retryable_errors.return_value = {"server closed the connection unexpectedly"}
+
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = False
+
+ logger = mock.MagicMock()
+ logger.ainfo = mock.AsyncMock()
+ logger.awarning = mock.AsyncMock()
+ logger.aexception = mock.AsyncMock()
+ logger.adebug = mock.AsyncMock()
+
+ with (
+ mock.patch.object(module.SourceRegistry, "get_source", return_value=source),
+ mock.patch.object(module, "current_import_attempt", return_value=PROGRESSLESS_RESUMABLE_ATTEMPTS + 1),
+ ):
+ with pytest.raises(NonRetryableException) as exc_info:
+ await module._handle_import_error(
+ mock.MagicMock(),
+ logger,
+ error,
+ resumable_source_manager=manager,
+ on_resumable_retry_budget=True,
+ )
+
+ assert exc_info.value.__cause__ is error
+ logger.aexception.assert_not_awaited()
+
+
+async def test_a_non_retryable_error_keeps_its_own_give_up_path():
+ # The source's own policy disables the schema and shows its own message, so the stand-down
+ # must not pre-empt it and turn an actionable credential error into a bare failure.
+ error = Exception("password authentication failed for user")
+ source = mock.MagicMock(spec=SimpleSource)
+ source.get_non_retryable_errors.return_value = {"password authentication failed": "Check your password."}
+ source.get_retryable_errors.return_value = set()
+
+ manager = mock.MagicMock()
+ manager.can_resume.return_value = False
+
+ logger = mock.MagicMock()
+ logger.adebug = mock.AsyncMock()
+
+ with (
+ mock.patch.object(module.SourceRegistry, "get_source", return_value=source),
+ mock.patch.object(module, "current_import_attempt", return_value=PROGRESSLESS_RESUMABLE_ATTEMPTS + 1),
+ mock.patch.object(module, "handle_non_retryable_error", new=mock.AsyncMock()) as handle_mock,
+ ):
+ handle_mock.side_effect = NonRetryableException()
+ with pytest.raises(NonRetryableException):
+ await module._handle_import_error(
+ mock.MagicMock(),
+ logger,
+ error,
+ resumable_source_manager=manager,
+ on_resumable_retry_budget=True,
+ )
+
+ handle_mock.assert_awaited_once()
diff --git a/products/warehouse_sources/backend/tests/test_models.py b/products/warehouse_sources/backend/tests/test_models.py
index 7139bdad1260..3c057e4a1c45 100644
--- a/products/warehouse_sources/backend/tests/test_models.py
+++ b/products/warehouse_sources/backend/tests/test_models.py
@@ -1842,3 +1842,62 @@ class TestDeleteTable(BaseTest):
assert schema.status is None
assert schema.last_synced_at is None
assert DataWarehouseTable.objects.get(id=table_id).deleted is True
+
+
+class TestFailureStreakMarker(SimpleTestCase):
+ # These properties are read on the terminal-status write of every run, so an unparseable
+ # marker must read as "no streak" rather than fail every sync of the schema.
+ @parameterized.expand(
+ [
+ ("no_config", None, 0),
+ ("empty_config", {}, 0),
+ ("marker_absent", {"reset_pipeline": True}, 0),
+ ("marker_is_not_a_dict", {"failure_streak": "7"}, 0),
+ ("runs_missing", {"failure_streak": {}}, 0),
+ ("runs_is_not_an_int", {"failure_streak": {"runs": "7"}}, 0),
+ ("runs_is_negative", {"failure_streak": {"runs": -3}}, 0),
+ ("runs_is_a_count", {"failure_streak": {"runs": 7}}, 7),
+ ]
+ )
+ def test_failed_runs_in_a_row(self, _name: str, config: dict[str, Any] | None, expected: int) -> None:
+ assert ExternalDataSchema(sync_type_config=config).failed_runs_in_a_row == expected
+
+ @parameterized.expand(
+ [
+ ("no_marker", {}, None),
+ ("stamp_missing", {"failure_streak": {"runs": 7}}, None),
+ ("stamp_is_not_a_string", {"failure_streak": {"runs": 7, "last_failed_at": 12345}}, None),
+ ("stamp_is_unparseable", {"failure_streak": {"runs": 7, "last_failed_at": "not a date"}}, None),
+ (
+ "stamp_is_an_aware_timestamp",
+ {"failure_streak": {"runs": 7, "last_failed_at": "2026-01-02T03:04:05+00:00"}},
+ datetime(2026, 1, 2, 3, 4, 5, tzinfo=UTC),
+ ),
+ # Read as UTC rather than left naive, so arithmetic against an aware `now` cannot raise.
+ (
+ "stamp_is_a_naive_timestamp",
+ {"failure_streak": {"runs": 7, "last_failed_at": "2026-01-02T03:04:05"}},
+ datetime(2026, 1, 2, 3, 4, 5, tzinfo=UTC),
+ ),
+ ]
+ )
+ def test_failure_streak_last_failed_at(self, _name: str, config: dict[str, Any], expected: datetime | None) -> None:
+ assert ExternalDataSchema(sync_type_config=config).failure_streak_last_failed_at == expected
+
+ def test_a_failed_run_adds_to_the_streak_and_keeps_the_other_keys(self) -> None:
+ schema = ExternalDataSchema(sync_type_config={"incremental_field": "updated_at", "failure_streak": {"runs": 2}})
+
+ schema.note_failed_run(datetime(2026, 1, 2, 3, 4, 5, tzinfo=UTC))
+
+ assert schema.failed_runs_in_a_row == 3
+ assert schema.failure_streak_last_failed_at == datetime(2026, 1, 2, 3, 4, 5, tzinfo=UTC)
+ assert schema.sync_type_config["incremental_field"] == "updated_at"
+
+ def test_clearing_the_streak_keeps_the_other_keys(self) -> None:
+ schema = ExternalDataSchema(sync_type_config={"incremental_field": "updated_at", "failure_streak": {"runs": 9}})
+
+ schema.clear_failure_streak()
+
+ assert schema.failed_runs_in_a_row == 0
+ assert schema.failure_streak_last_failed_at is None
+ assert schema.sync_type_config == {"incremental_field": "updated_at"}