: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(data-warehouse): restart syncs whose schedule stopped firing (#102914)
Tom Owers16a0eab948db
diff --git a/posthog/tasks/scheduled.py b/posthog/tasks/scheduled.pyindex 2ee2ae517b7e..cf99f8d13b94 100644--- a/posthog/tasks/scheduled.py+++ b/posthog/tasks/scheduled.py@@ -139,7 +139,7 @@ from products.visual_review.backend.facade.tasks import (sweep_visual_review_artifacts,sweep_visual_review_runs,)-from products.warehouse_sources.backend.facade.tasks import sweep_stopped_schema_syncs+from products.warehouse_sources.backend.facade.tasks import sweep_stalled_schema_schedules, sweep_stopped_schema_syncsfrom products.web_analytics.backend.achievements.tasks import sweep_web_analytics_achievement_team_tracksfrom products.web_analytics.backend.tasks.heatmap_screenshot import (reap_stale_prewarm_heatmaps,@@ -710,6 +710,15 @@ def setup_periodic_tasks(sender: Celery, **kwargs: Any) -> None:name="sweep stopped schema syncs",)+ # The mirror of the sweep above: schemas that should be syncing but get no runs at all.+ # A schedule paused out of band produces no job row and no error, so this sweep is the+ # only thing that reports it.+ sender.add_periodic_task(+ crontab(hour="*", minute="40"),+ sweep_stalled_schema_schedules.s(),+ name="sweep stalled schema schedules",+ )+# Background net for tables created while nobody visits the warehouse status page. Each# reconcile opens a real warehouse session (one worker pod, billed compute), so the sweep is# deliberately infrequent — the 60s-coalesced status-read path is the interactive fast path.diff --git a/products/warehouse_sources/backend/facade/tasks.py b/products/warehouse_sources/backend/facade/tasks.pyindex 5f0bfd8fd0ee..826a869debb1 100644--- a/products/warehouse_sources/backend/facade/tasks.py+++ b/products/warehouse_sources/backend/facade/tasks.py@@ -1,5 +1,13 @@"""Celery tasks core schedules for warehouse_sources (see products/architecture.md, wiring couplings)."""-from products.warehouse_sources.backend.tasks import sweep_stopped_schema_syncs, validate_data_warehouse_table_columns+from products.warehouse_sources.backend.tasks import (+ sweep_stalled_schema_schedules,+ sweep_stopped_schema_syncs,+ validate_data_warehouse_table_columns,+)-__all__ = ["sweep_stopped_schema_syncs", "validate_data_warehouse_table_columns"]+__all__ = [+ "sweep_stalled_schema_schedules",+ "sweep_stopped_schema_syncs",+ "validate_data_warehouse_table_columns",+]diff --git a/products/warehouse_sources/backend/management/commands/migrate_cdc_source_to_buffered.py b/products/warehouse_sources/backend/management/commands/migrate_cdc_source_to_buffered.pyindex 84438e02f722..0319632a959d 100644--- a/products/warehouse_sources/backend/management/commands/migrate_cdc_source_to_buffered.py+++ b/products/warehouse_sources/backend/management/commands/migrate_cdc_source_to_buffered.py@@ -11,6 +11,7 @@ import datetime as dtfrom typing import Anyfrom django.core.management.base import BaseCommand, CommandError+from django.db import transactionimport psycopgimport structlog@@ -255,41 +256,68 @@ class Command(BaseCommand):# the source was still legacy. If it reads the source again after the change, it consumes# the buffer on that stale version, which records no load position, so nothing it read is# ever proven consumed. Quiesce the schedules so no run straddles the mode change.- self.stdout.write("3/7 pausing per-schema schedules")- self._pause_schema_schedules_strict(eligible)- self._wait_for_running_sync_jobs(source.team_id, [str(s.id) for s in eligible], drain_timeout)-- self.stdout.write("4/7 draining sourcebatch")- self._wait_for_sourcebatch_drain(source.team_id, [str(s.id) for s in eligible], drain_timeout)- self._retire_orphaned_companions(eligible)-- # Pre-flip files were already delivered by the legacy lane, whose rows carry no position,- # so nothing in the table could tell a replay of them from new changes. Every CDC schema is- # purged, not just the eligible ones: a schema still snapshotting today becomes eligible on- # its first completed sync, and would otherwise inherit whatever the shadow lane left here.- # On a source already buffered, the schemas it serves hold files the consumer still owes,- # so only the schemas moving now are purged.- already_buffered = (source.job_inputs or {}).get("cdc_ingest_mode") == "buffered"- to_purge = eligible if already_buffered else cdc_schemas- self.stdout.write("5/7 purging pre-flip buffer files")- for schema in to_purge:- purge_buffer_prefix(source.team_id, str(schema.id), logger)- self._verify_prefixes_empty(source.team_id, to_purge)-- # The step-3 wait sees job rows only; a workflow fired just before the pause may not have- # created its row yet. By now it has, so one more wait closes the straddle window.- self._wait_for_running_sync_jobs(source.team_id, [str(s.id) for s in eligible], drain_timeout)-- self.stdout.write("6/7 setting cdc_ingest_mode=buffered and marking the schemas served")- source.job_inputs = {- **(source.job_inputs or {}),- "cdc_ingest_mode": "buffered",- # Kept across a rollback: it is what tells a later flip that a `_ph_cdc_seq` column on- # the warehouse table may be one this lane wrote, not one the source owns.- "cdc_buffered_before": True,- }- source.save(update_fields=["job_inputs"])- self._mark_schemas(eligible, served=True)+ #+ # The pause call itself is inside this same try: a schedule that fails to pause partway+ # through the batch must not leave the ones that did pause stranded. `_restore_schema_schedules`+ # unpausing a schedule that was never paused is a no-op, so restoring the whole eligible set+ # on any failure here is safe.+ try:+ self.stdout.write("3/7 pausing per-schema schedules")+ self._pause_schema_schedules_strict(eligible)++ # Everything from here to the mode change leaves the schemas quiesced, and every step in+ # between can abort: a drain that times out, a buffer file that survives the purge. The+ # mode does not change until step 6, so on an abort the source is still the legacy source+ # it was before the command ran. Leaving its schedules paused there stops the customer's+ # syncs for as long as nobody notices, and nothing reports that: no run starts, so there+ # is no job row and no error. Restore the schedules and let the abort surface. Extraction+ # stays paused on purpose, because an operator has to look at whatever stopped the drain+ # before capture writes again.+ self._wait_for_running_sync_jobs(source.team_id, [str(s.id) for s in eligible], drain_timeout)++ self.stdout.write("4/7 draining sourcebatch")+ self._wait_for_sourcebatch_drain(source.team_id, [str(s.id) for s in eligible], drain_timeout)+ self._retire_orphaned_companions(eligible)++ # Pre-flip files were already delivered by the legacy lane, whose rows carry no+ # position, so nothing in the table could tell a replay of them from new changes. Every+ # CDC schema is purged, not just the eligible ones: a schema still snapshotting today+ # becomes eligible on its first completed sync, and would otherwise inherit whatever+ # the shadow lane left here. On a source already buffered, the schemas it serves hold+ # files the consumer still owes, so only the schemas moving now are purged.+ already_buffered = (source.job_inputs or {}).get("cdc_ingest_mode") == "buffered"+ to_purge = eligible if already_buffered else cdc_schemas+ self.stdout.write("5/7 purging pre-flip buffer files")+ for schema in to_purge:+ purge_buffer_prefix(source.team_id, str(schema.id), logger)+ self._verify_prefixes_empty(source.team_id, to_purge)++ # The step-3 wait sees job rows only; a workflow fired just before the pause may not+ # have created its row yet. By now it has, so one more wait closes the straddle window.+ self._wait_for_running_sync_jobs(source.team_id, [str(s.id) for s in eligible], drain_timeout)++ # Still inside the recovery boundary: `_mark_schemas` writes one schema at a time, so a+ # failure partway through it would otherwise leave the mode buffered with only some+ # schemas marked served and every schedule still paused — the same silent outage this+ # command exists to fix. The atomic block makes the two writes fail together, so a+ # failure here rolls `job_inputs` back to legacy too, and the `except` below restores+ # the schedules onto a state that is genuinely unchanged, not a half-flipped one.+ self.stdout.write("6/7 setting cdc_ingest_mode=buffered and marking the schemas served")+ with transaction.atomic():+ source.job_inputs = {+ **(source.job_inputs or {}),+ "cdc_ingest_mode": "buffered",+ # Kept across a rollback: it is what tells a later flip that a `_ph_cdc_seq`+ # column on the warehouse table may be one this lane wrote, not one the source+ # owns.+ "cdc_buffered_before": True,+ }+ source.save(update_fields=["job_inputs"])+ self._mark_schemas(eligible, served=True)+ except BaseException:+ self.stdout.write(self.style.WARNING("flip aborted, restoring per-schema schedules"))+ self._restore_schema_schedules(eligible)+ raiseself.stdout.write("7/7 unpausing schedules")unpause_cdc_extraction_schedule(source_id)@@ -334,26 +362,52 @@ class Command(BaseCommand):# Consumer next: a sync merging old buffered rows AFTER legacy capture resumed would# overwrite newer legacy writes — legacy writes carry no position, so the guard can't# protect them. Strict: a schedule that failed to pause could start such a sync.- self.stdout.write("4/6 pausing per-schema schedules")- self._pause_schema_schedules_strict(eligible)- self._wait_for_running_sync_jobs(source.team_id, [str(s.id) for s in eligible], drain_timeout)- self._wait_for_sourcebatch_drain(source.team_id, [str(s.id) for s in eligible], drain_timeout)- self._retire_orphaned_companions(eligible)-- self.stdout.write("5/6 setting cdc_ingest_mode=legacy and unmarking the schemas")- self._mark_schemas(eligible, served=False)- source.job_inputs = {- **(source.job_inputs or {}),- "cdc_ingest_mode": "legacy",- # Set here as well as on the flip, so a source flipped before this marker existed still- # carries it once it rolls back — which is the population that would otherwise be- # refused a second flip over a `_ph_cdc_seq` column the buffered lane wrote itself.- "cdc_buffered_before": True,- }- source.save(update_fields=["job_inputs"])+ #+ # The pause call is inside this same try: a schedule that fails to pause partway through+ # the batch must not leave the ones that did pause stranded. `_restore_schema_schedules`+ # unpausing a schedule that was never paused is a no-op, so restoring the whole eligible+ # set on any failure here is safe.+ try:+ self.stdout.write("4/6 pausing per-schema schedules")+ self._pause_schema_schedules_strict(eligible)+ self._wait_for_running_sync_jobs(source.team_id, [str(s.id) for s in eligible], drain_timeout)+ self._wait_for_sourcebatch_drain(source.team_id, [str(s.id) for s in eligible], drain_timeout)+ self._retire_orphaned_companions(eligible)++ # Still inside the recovery boundary, for the same reason as the flip: `_mark_schemas`+ # writes one schema at a time, and the atomic block makes it fail together with the+ # `job_inputs` write so a failure here leaves the source genuinely still buffered+ # rather than half-rolled-back, which is what the `except` below assumes.+ self.stdout.write("5/6 setting cdc_ingest_mode=legacy and unmarking the schemas")+ with transaction.atomic():+ self._mark_schemas(eligible, served=False)+ source.job_inputs = {+ **(source.job_inputs or {}),+ "cdc_ingest_mode": "legacy",+ # Set here as well as on the flip, so a source flipped before this marker+ # existed still carries it once it rolls back — which is the population that+ # would otherwise be refused a second flip over a `_ph_cdc_seq` column the+ # buffered lane wrote itself.+ "cdc_buffered_before": True,+ }+ source.save(update_fields=["job_inputs"])+ except BaseException:+ # The mode is still buffered, so the schemas go back to consuming the buffer, which is+ # what they were doing before this command ran. Leaving them paused instead would stop+ # the syncs silently and let the buffer age toward its TTL.+ self.stdout.write(self.style.WARNING("rollback aborted, restoring per-schema schedules"))+ self._restore_schema_schedules(eligible)+ raise# Leftover fully-applied files stay: the position guard no-ops a replay, the S3 TTL clears them.- self.stdout.write("6/6 unpausing extraction schedule")+ self.stdout.write("6/6 unpausing schedules")+ # Step 4 paused these, so the rollback has to hand them back. Without this the source ends+ # a successful rollback on legacy delivery with no schema scheduled to load it. Restored+ # before the extraction schedule: `_restore_schema_schedules` degrades gracefully per+ # schema, but `unpause_cdc_extraction_schedule` is a single Temporal call that can still+ # raise here, and doing this one first means a raise there does not also strand the+ # per-schema schedules a second time.+ self._restore_schema_schedules(eligible)unpause_cdc_extraction_schedule(source_id)self.stdout.write(self.style.SUCCESS(f"Source {source_id} is now legacy."))@@ -521,6 +575,19 @@ class Command(BaseCommand):self.stdout.write(f" waiting, {len(running)} sync job(s) running")time.sleep(DRAIN_POLL_SECONDS)+ def _restore_schema_schedules(self, schemas: list[ExternalDataSchema]) -> None:+ """Hand the schemas back their schedules, skipping any that stopped syncing meanwhile.++ `should_sync` is re-read rather than taken from the in-memory copies: a drain wait can run+ for minutes, and a schema disabled in that window must stay paused.+ """+ still_syncing = set(+ ExternalDataSchema.objects.filter(+ id__in=[s.id for s in schemas], should_sync=True, deleted=False+ ).values_list("id", flat=True)+ )+ self._set_schema_schedules([s for s in schemas if s.id in still_syncing], paused=False)+def _set_schema_schedules(self, schemas: list[ExternalDataSchema], *, paused: bool) -> None:from products.data_warehouse.backend.facade.api import (pause_external_data_schedule,diff --git a/products/warehouse_sources/backend/management/commands/repair_stalled_schema_schedules.py b/products/warehouse_sources/backend/management/commands/repair_stalled_schema_schedules.pynew file mode 100644index 000000000000..7bc88eb2c3c4--- /dev/null+++ b/products/warehouse_sources/backend/management/commands/repair_stalled_schema_schedules.py@@ -0,0 +1,194 @@+"""Put schemas back on their schedule after the schedule stopped firing.++`ExternalDataSchema.should_sync` and the Temporal schedule's paused flag are written together+and then drift apart: the flag is set once, when the schedule is created or rewritten, and+nothing reconciles it afterwards. A schedule paused out of band therefore takes a schema's+syncs down while every Postgres column still reports it as syncing. `sweep_stalled_schema_schedules`+reports that state; this command repairs it.++The repair rewrites the schedule from `should_sync`, which unpauses a paused one and recreates a+missing one, and repaints a stale Running status so the next tick is not skipped as an overlap.+It does not fire a run, because runs bill: the schema's own next tick does the work.++Scope: only schemas with no run at all since the stall window opened. A schema whose run started+and never finished has a wedged Temporal workflow instead, which needs terminating rather than+rescheduling; `unstick_external_data_jobs` handles those. This command lists them and skips them.++Dry-run by default.+"""++from typing import Any++from django.core.management.base import BaseCommand, CommandError, CommandParser++import structlog++from products.warehouse_sources.backend.stalled_schedules import (+ DEFAULT_MIN_STALL,+ DEFAULT_MISSED_INTERVALS,+ StalledSchema,+ find_stalled_schemas,+ repair_stalled_schema,+)++logger = structlog.get_logger(__name__)++MAX_SCHEMAS_DEFAULT = 100+++class Command(BaseCommand):+ help = (+ "Repair schemas whose Temporal schedule stopped firing: unpause or recreate the schedule "+ "and clear a stale Running status. Skips schemas whose run is wedged (use "+ "unstick_external_data_jobs) and buffered CDC sources. Dry-run unless --live-run is given."+ )++ def add_arguments(self, parser: CommandParser) -> None:+ parser.add_argument("--team-id", type=int, help="Scope by team")+ parser.add_argument("--source-type", type=str, help="Scope by source type, e.g. Supabase")+ parser.add_argument(+ "--missed-intervals",+ type=int,+ default=DEFAULT_MISSED_INTERVALS,+ help=(+ "Consecutive runs a schema must miss to count as stalled "+ f"(default {DEFAULT_MISSED_INTERVALS}). Raise it to target only the worst."+ ),+ )+ parser.add_argument(+ "--max-schemas",+ type=int,+ default=MAX_SCHEMAS_DEFAULT,+ help=f"Abort if more than this many schemas match (default {MAX_SCHEMAS_DEFAULT})",+ )+ parser.add_argument(+ "--include-buffered",+ action="store_true",+ help=(+ "Also repair schemas on a buffered CDC source. Their schedule paces buffer "+ "consumption, so restarting it out of sequence can merge files against a table "+ "the buffered lane already writes. Prefer re-running migrate_cdc_source_to_buffered."+ ),+ )+ parser.add_argument("--live-run", action="store_true", help="Apply changes (default is dry-run)")+ parser.add_argument("--yes", action="store_true", help="Skip interactive confirmation")++ def handle(self, *args: Any, **options: Any) -> None:+ live_run: bool = options["live_run"]+ include_buffered: bool = options["include_buffered"]++ max_schemas: int = options["max_schemas"]+ # One over the cap, so an unexpectedly wide match is refused rather than loaded whole.+ stalled = find_stalled_schemas(+ missed_intervals=options["missed_intervals"],+ min_stall=DEFAULT_MIN_STALL,+ team_id=options.get("team_id"),+ source_type=options.get("source_type"),+ limit=max_schemas + 1,+ )+ if not stalled:+ self.stdout.write("No stalled schemas match - nothing to do.")+ return++ if len(stalled) > max_schemas:+ raise CommandError(+ f"More than {max_schemas} schemas match, above the --max-schemas cap. "+ "Narrow the targeting or raise --max-schemas explicitly."+ )++ # --include-buffered only overrides the buffered-CDC exclusion; every other exclusion in+ # repairable_here stays in force — none of them are what that flag is for.+ actionable = [+ s+ for s in stalled+ if s.repairable_here+ or (+ include_buffered+ and s.kind == "no_runs"+ and not s.admin_paused+ and s.has_sync_interval+ and not s.cdc_streaming+ and not s.cdc_halted+ )+ ]+ actionable_ids = {s.schema_id for s in actionable}+ skipped = [s for s in stalled if s.schema_id not in actionable_ids]++ self.stdout.write(f"{len(stalled)} stalled schema(s):")+ for schema in stalled:+ marker = "repair" if schema.schema_id in actionable_ids else f"skip ({self._skip_reason(schema)})"+ self.stdout.write(+ f" schema={schema.schema_id} team={schema.team_id} source={schema.source_type} "+ f"name={schema.name} stalled={schema.stalled_for.total_seconds() / 3600:.1f}h -> {marker}"+ )++ verb = "Would repair" if not live_run else "Repairing"+ self.stdout.write(f"{verb} {len(actionable)} schema(s); skipping {len(skipped)}.")+ if any(s.kind == "stuck_job" for s in skipped):+ self.stdout.write(+ "Schemas marked stuck_job need unstick_external_data_jobs, which terminates the "+ "wedged workflow. Run it first, then re-run this command."+ )++ if not live_run:+ self.stdout.write("Dry run - no changes written. Re-run with --live-run to apply.")+ return+ if not actionable:+ return++ self._confirm(f"Repair {len(actionable)} schema(s)? Type 'repair' to continue: ", options["yes"])++ failures = 0+ skipped_on_reload = 0+ for schema in actionable:+ # One schema that cannot be repaired must not abort the rest of the sweep.+ try:+ schedule_rewritten = repair_stalled_schema(schema)+ except Exception:+ failures += 1+ logger.exception(+ "repair_stalled_schema_schedules_failed",+ schema_id=schema.schema_id,+ team_id=schema.team_id,+ )+ self.stdout.write(self.style.ERROR(f" schema={schema.schema_id} FAILED (see logs) - continuing"))+ continue+ if not schedule_rewritten:+ # A revalidation guard inside repair_stalled_schema found the row no longer+ # eligible on reload (e.g. disabled, or flipped to a state a fresh sweep would+ # skip) and returned without raising. That is not the same outcome as a rewrite,+ # so it must not count or log as one.+ skipped_on_reload += 1+ self.stdout.write(self.style.WARNING(f" schema={schema.schema_id} skipped (no longer eligible)"))+ continue+ logger.info(+ "repair_stalled_schema_schedules_repaired",+ schema_id=schema.schema_id,+ team_id=schema.team_id,+ source_type=schema.source_type,+ stalled_for_hours=round(schema.stalled_for.total_seconds() / 3600, 1),+ )+ self.stdout.write(self.style.SUCCESS(f" schema={schema.schema_id} rescheduled"))++ repaired = len(actionable) - failures - skipped_on_reload+ self.stdout.write(f"Repaired {repaired} schema(s), {failures} failed, {skipped_on_reload} skipped on reload.")+ self.stdout.write("Each schema runs on its own next tick; no run was triggered, so nothing was billed.")++ def _skip_reason(self, schema: StalledSchema) -> str:+ if schema.kind == "stuck_job":+ return "wedged run, use unstick_external_data_jobs"+ if schema.admin_paused:+ return "paused for an in-flight admin-triggered run"+ if not schema.has_sync_interval:+ return "no sync_frequency_interval set"+ if schema.cdc_streaming:+ return "streaming CDC schema, use repair_cdc"+ if schema.cdc_halted:+ return "CDC halted, use repair_cdc"+ return "buffered CDC source"++ def _confirm(self, prompt: str, yes: bool) -> None:+ if yes:+ return+ if input(prompt).strip() != "repair":+ raise CommandError("Aborted.")diff --git a/products/warehouse_sources/backend/stalled_schedules.py b/products/warehouse_sources/backend/stalled_schedules.pynew file mode 100644index 000000000000..1971d8182232--- /dev/null+++ b/products/warehouse_sources/backend/stalled_schedules.py@@ -0,0 +1,352 @@+"""Find schemas that should be syncing but have stopped getting runs.++A schema's cadence lives in a Temporal schedule whose paused flag is written once, when the+schedule is created or rewritten (`sync_external_data_job_workflow`). Nothing keeps that flag+in step with `should_sync` afterwards, so a schedule paused out of band stays paused while+Postgres still reports the schema as syncing. `migrate_cdc_source_to_buffered` pauses every+per-schema schedule at its step 3 and unpauses at its step 7, so any abort in between leaves+them down.++That failure is silent in a way an ordinary sync failure is not. No run starts, so there is no+job row, no `latest_error`, and nothing for the failure digest to report. Every column a+dashboard would read keeps saying the schema is healthy.++This module carries the predicate that finds those schemas from Postgres alone, shared by the+periodic sweep that reports them and the management command that repairs them.+"""++from datetime import timedelta++from django.db.models import DateTimeField, DurationField, ExpressionWrapper, F, QuerySet, Value+from django.db.models.functions import Coalesce, Greatest+from django.utils import timezone++import structlog++from posthog.dataclasses import frozen++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.models.external_data_source import ExternalDataSource++logger = structlog.get_logger(__name__)++# Consecutive runs a schema can miss before the silence is a fault rather than jitter. A run+# starts late when the source is slow, the worker fleet is saturated, or the previous run+# overran its own interval, and none of those need repair.+DEFAULT_MISSED_INTERVALS = 3++# Floor under the stall window. Without it a five-minute schema qualifies after 20 minutes,+# which one slow run produces on its own.+DEFAULT_MIN_STALL = timedelta(hours=2)++# Matches the `sync_frequency_interval` column default, used when the column is null.+FALLBACK_SYNC_INTERVAL = timedelta(hours=6)++# Statuses that already report themselves. A failing schema carries its error on the row and+# reaches the failure digest; a billing-limited one still starts runs. Neither is this fault,+# and including them would bury it.+SELF_REPORTING_STATUSES = (+ ExternalDataSchema.Status.FAILED,+ ExternalDataSchema.Status.BILLING_LIMIT_REACHED,+ ExternalDataSchema.Status.BILLING_LIMIT_TOO_LOW,+ ExternalDataSchema.Status.PAUSED,+)++# Replaces the stale Running status on a repaired schema. The row keeps a visible record of the+# gap, and the schema's own next tick clears it.+REPAIRED_SCHEMA_ERROR = (+ "This sync stopped running on its schedule. PostHog restarted it, and the next sync runs on schedule."+)+++@frozen+class StalledSchema:+ schema_id: str+ team_id: int+ name: str+ source_id: str+ source_type: str+ # "no_runs" when nothing has started since the stall window opened, which points at the+ # schedule. "stuck_job" when a run did start and never finished, which points at its+ # Temporal workflow and belongs to `unstick_external_data_jobs` instead.+ kind: str+ stalled_for: timedelta+ cdc_ingest_mode: str+ # `ad_hoc_sync.py` and the admin action set this on the schema it pauses for an in-flight+ # non-scheduled run, and clear it themselves once that run finishes successfully. It surviving+ # to a stall check means the run's own cleanup has not (yet, or ever) run, so the pause may+ # still be deliberate — unpausing here would race it against the admin-triggered workflow.+ admin_paused: bool+ # The stall window tolerates a null `sync_frequency_interval` (falls back to+ # FALLBACK_SYNC_INTERVAL for the window calculation only), but the schedule builder does not:+ # it passes the column straight into `ScheduleIntervalSpec`, where `timedelta(...) % None`+ # raises. Repairing would fail every time with the same error, so this is excluded rather+ # than left to fail — rewriting the schema's own cadence is not this tool's job.+ has_sync_interval: bool+ # True once a CDC schema has finished its initial snapshot and flipped to streaming+ # (`mark_initial_sync_complete`). `stalled_schema_queryset` already excludes this at the+ # source; this field backs `repairable_here` for the window between discovery and repair,+ # where a schema can flip to streaming after being read as `no_runs`.+ cdc_streaming: bool+ # Mirrors `ExternalDataSchema.cdc_halted`: true while the source is marked `cdc_broken`, or+ # its extraction schedule was paused after a non-retryable error. This is a configuration+ # marker independent of `should_sync` and `status`, so a halted schema can still read+ # should_sync=True and a non-self-reporting status. Cleared only by repair, resume, disable,+ # or a successful extraction run — not by anything this tool does.+ cdc_halted: bool++ @property+ def repairable_here(self) -> bool:+ """Whether unpausing the schedule is the right fix.++ A buffered CDC source is excluded because its schedule paces buffer consumption: once+ the mode is flipped, restarting the schedule out of sequence merges files against a+ table the buffered lane already writes. Those go back through+ `migrate_cdc_source_to_buffered`.++ A schema still carrying `admin_unpause_schedule_after_run` is excluded because its pause+ may belong to an in-flight admin-triggered run rather than to the outage this repairs.++ A schema with no `sync_frequency_interval` is excluded because the schedule builder+ cannot turn a null interval into a cadence.++ A streaming CDC schema is excluded because its own workflow paces the schedule; unpausing+ it does not restart a sync, it just races that workflow into re-pausing it. Those go back+ through `repair_cdc`.++ A halted CDC schema is excluded for the same reason, one step earlier: the marker exists+ precisely to stop anything else from touching the schema until `repair_cdc` clears it.+ """+ return (+ self.kind == "no_runs"+ and self.cdc_ingest_mode != "buffered"+ and not self.admin_paused+ and self.has_sync_interval+ and not self.cdc_streaming+ and not self.cdc_halted+ )+++def stalled_schema_queryset(+ *,+ missed_intervals: int = DEFAULT_MISSED_INTERVALS,+ min_stall: timedelta = DEFAULT_MIN_STALL,+) -> QuerySet[ExternalDataSchema]:+ """Schemas whose last successful sync is older than their own cadence allows.++ The window scales with `sync_frequency_interval` because a fixed one cannot serve both a+ five-minute schema and a daily one. A daily schema therefore needs days of silence to+ qualify, which is the cost of not flagging every schema that merely ran slowly.+ """+ stall_window = ExpressionWrapper(+ Greatest(+ Coalesce(F("sync_frequency_interval"), Value(FALLBACK_SYNC_INTERVAL)) * missed_intervals,+ Value(min_stall),+ ),+ output_field=DurationField(),+ )+ return (+ ExternalDataSchema.objects.filter(+ should_sync=True,+ deleted=False,+ source__deleted=False,+ # Has completed at least one sync, so a schema still working through its first+ # snapshot is not read as stalled.+ last_synced_at__isnull=False,+ # Narrows the scan before the per-row window below, which is computed and so cannot+ # use an index. No schema can qualify sooner than the floor, so this drops the bulk+ # of the fleet without changing the result.+ last_synced_at__lt=timezone.now() - min_stall,+ )+ .exclude(source__access_method=ExternalDataSource.AccessMethod.DIRECT)+ .exclude(status__in=SELF_REPORTING_STATUSES)+ # Streaming CDC and cdc_halted are excluded in `find_stalled_schemas` in Python, not+ # here: a JSON key lookup against a schema whose `sync_type_config` does not have that+ # key evaluates to SQL NULL, and `.exclude()` compiles to `NOT (...)` — NOT NULL is NULL,+ # not TRUE, so Postgres drops the row from the result entirely instead of keeping it.+ # That silently wipes out every schema without the key, not just the ones carrying it.+ .annotate(+ stalled_after=ExpressionWrapper(+ F("last_synced_at") + stall_window,+ output_field=DateTimeField(),+ )+ )+ .filter(stalled_after__lt=timezone.now())+ )+++def find_stalled_schemas(+ *,+ missed_intervals: int = DEFAULT_MISSED_INTERVALS,+ min_stall: timedelta = DEFAULT_MIN_STALL,+ team_id: int | None = None,+ source_type: str | None = None,+ limit: int | None = None,+) -> list[StalledSchema]:+ queryset = stalled_schema_queryset(missed_intervals=missed_intervals, min_stall=min_stall)+ if team_id is not None:+ queryset = queryset.filter(team_id=team_id)+ if source_type is not None:+ queryset = queryset.filter(source__source_type__iexact=source_type)++ queryset = queryset.select_related("source").order_by("last_synced_at")+ if limit is not None:+ queryset = queryset[:limit]++ schemas = list(queryset)+ if not schemas:+ return []++ # One query for the whole batch rather than one per schema. The batch is small by+ # construction: a healthy fleet returns nothing here.+ schemas_with_running_jobs = set(+ ExternalDataJob.objects.filter(+ schema_id__in=[schema.id for schema in schemas],+ status=ExternalDataJob.Status.RUNNING,+ ).values_list("schema_id", flat=True)+ )++ now = timezone.now()+ stalled = []+ for schema in schemas:+ # The queryset already excludes a null stamp. The check is here because the column is+ # nullable, so the subtraction below has no other way to know.+ if schema.last_synced_at is None:+ continue+ # Streaming CDC and cdc_halted are excluded here rather than in the queryset (see the+ # comment there): a paused per-schema schedule is streaming CDC's steady state, and+ # cdc_halted exists precisely to keep everything else off the schedule until repair_cdc+ # clears it. Skipped rather than reported-but-unrepairable, unlike buffered CDC: this+ # population can be the entire fleet during a broken-source incident, and reporting it+ # every sweep would bury the schedule-stall signal this predicate exists to surface.+ if schema.is_cdc and schema.cdc_mode == "streaming":+ continue+ if schema.cdc_halted:+ continue+ stalled.append(+ StalledSchema(+ schema_id=str(schema.id),+ team_id=schema.team_id,+ name=schema.name,+ source_id=str(schema.source_id),+ source_type=schema.source.source_type,+ kind="stuck_job" if schema.id in schemas_with_running_jobs else "no_runs",+ stalled_for=now - schema.last_synced_at,+ cdc_ingest_mode=(schema.source.job_inputs or {}).get("cdc_ingest_mode", "legacy"),+ admin_paused=bool((schema.sync_type_config or {}).get("admin_unpause_schedule_after_run")),+ has_sync_interval=schema.sync_frequency_interval is not None,+ cdc_streaming=schema.is_cdc and schema.cdc_mode == "streaming",+ cdc_halted=schema.cdc_halted,+ )+ )+ return stalled+++def repair_stalled_schema(stalled: StalledSchema) -> bool:+ """Put a stalled schema back on its schedule.++ Rewrites the Temporal schedule from the schema's current `should_sync`, which clears a+ paused flag left behind out of band and recreates a schedule that went missing. The rewrite+ does not fire a run: every scheduled run bills, so the repair waits for the schema's own+ next tick rather than charging for one now.++ Returns whether the schedule was actually rewritten. A revalidation guard below can skip+ without raising, and that is not the same outcome as a rewrite — the caller counts and logs+ them differently.+ """+ # data_load.service imports temporalio at module scope, so a top-level import here would+ # put the Temporal client on the import path of the sweep's Celery autodiscovery.+ from products.data_warehouse.backend.facade.api import sync_external_data_job_workflow # noqa: PLC0415++ # Shared with the workflow's own finalization so a repaired row reads the same as one an+ # ordinary failed run left behind.+ from products.warehouse_sources.backend.temporal.data_imports.external_data_job import ( # noqa: PLC0415+ _fail_stale_running_schema,+ )++ schema = ExternalDataSchema.objects.select_related("source").get(id=stalled.schema_id, team_id=stalled.team_id)++ # `stalled` is a discovery-time snapshot, and the management command's confirmation prompt+ # alone can put minutes between discovery and this call. Re-check should_sync and deleted+ # against the reloaded row rather than assuming the snapshot still holds — deleting a schema+ # does not itself flip should_sync, so a schema deleted in that window can still read+ # should_sync=True here. Either one must stay paused, not get rescheduled out from under it.+ if not schema.should_sync or schema.deleted:+ logger.info(+ "repair_stalled_schema_schedules_skipped_now_ineligible",+ schema_id=str(schema.id),+ team_id=schema.team_id,+ )+ return False++ # Same reasoning as should_sync above: an admin-triggered run can pause the schedule and set+ # this marker after discovery. Unpausing here would race the admin run's own workflow, which+ # relies on nothing else touching the schedule until it clears the marker itself.+ if (schema.sync_type_config or {}).get("admin_unpause_schedule_after_run"):+ logger.info(+ "repair_stalled_schema_schedules_skipped_admin_paused",+ schema_id=str(schema.id),+ team_id=schema.team_id,+ )+ return False++ # A null interval crashes the schedule builder below, so skip rather than fail. Re-checked+ # for the same staleness reason as the two guards above.+ if schema.sync_frequency_interval is None:+ logger.info(+ "repair_stalled_schema_schedules_skipped_no_sync_interval",+ schema_id=str(schema.id),+ team_id=schema.team_id,+ )+ return False++ # A paused schedule is steady state once a CDC schema is streaming — CDCExtractionWorkflow+ # owns it and re-pauses it on its own next tick. Unpausing here does not restart a sync, it+ # just races that workflow for nothing. Re-checked because initial_sync_complete (and so the+ # snapshot-to-streaming flip) can land in the window between discovery and this call.+ if schema.is_cdc and schema.cdc_mode == "streaming":+ logger.info(+ "repair_stalled_schema_schedules_skipped_cdc_streaming",+ schema_id=str(schema.id),+ team_id=schema.team_id,+ )+ return False++ # The halt marker exists precisely to stop anything else from touching the schedule until+ # `repair_cdc` clears it. Re-checked for the same staleness reason as the guards above.+ if schema.cdc_halted:+ logger.info(+ "repair_stalled_schema_schedules_skipped_cdc_halted",+ schema_id=str(schema.id),+ team_id=schema.team_id,+ )+ return False++ # A schema whose run never reached finalization still reads RUNNING, and the scheduler+ # treats that as a live run. Repainting it first stops the next tick being skipped.+ if schema.status == ExternalDataSchema.Status.RUNNING:+ _fail_stale_running_schema(+ str(schema.id),+ schema.team_id,+ REPAIRED_SCHEMA_ERROR,+ logger,+ )+ # get_team_ids_with_recent_sync_failures renotifies a FAILED schema once+ # last_error_notified_at is more than RENOTIFY_STILL_FAILING_AFTER old, with no newer+ # failed job required. A schema that failed long ago, was notified, and has since been+ # healthy for a while still carries that old stamp, so this repaint would otherwise read+ # as "still failing" and send the failure digest instead of the informational message+ # above. Stamping it here starts that window fresh; a genuinely new failure still notifies,+ # because its job's finished_at is newer than this stamp.+ ExternalDataSchema.objects.filter(id=schema.id, team_id=schema.team_id).update(+ last_error_notified_at=timezone.now()+ )++ sync_external_data_job_workflow(+ schema,+ create=True,+ should_sync=schema.should_sync,+ trigger_immediately=False,+ )+ return Truediff --git a/products/warehouse_sources/backend/tasks/__init__.py b/products/warehouse_sources/backend/tasks/__init__.pyindex 920839f7598b..4b6a8483e923 100644--- a/products/warehouse_sources/backend/tasks/__init__.py+++ b/products/warehouse_sources/backend/tasks/__init__.py@@ -1,5 +1,6 @@from products.warehouse_sources.backend.tasks.tasks import ( # noqa: F401cleanup_disabled_external_data_schema,+ sweep_stalled_schema_schedules,sweep_stopped_schema_syncs,validate_data_warehouse_table_columns,)diff --git a/products/warehouse_sources/backend/tasks/tasks.py b/products/warehouse_sources/backend/tasks/tasks.pyindex 561d305e6754..6f26af1f4b61 100644--- a/products/warehouse_sources/backend/tasks/tasks.py+++ b/products/warehouse_sources/backend/tasks/tasks.py@@ -1,3 +1,4 @@+from collections import defaultdictfrom datetime import timedeltafrom django.db.models import Q@@ -5,6 +6,7 @@ from django.utils import timezoneimport structlogfrom celery import shared_task+from prometheus_client import Gaugefrom posthog.ph_client import get_clientfrom posthog.scoping_audit import skip_team_scope_audit@@ -32,6 +34,27 @@ STOPPED_SYNC_SWEEP_GRACE = timedelta(minutes=30)# mass-failed (and their latest_error rewritten) on the first ticks after deploy.STOPPED_SYNC_SWEEP_MAX_JOB_AGE = timedelta(days=7)+# Bounds one tick's report. The gauge saturates here rather than scanning an unbounded+# set: past this many the answer is the same either way, which is that something broke+# fleet-wide.+STALLED_SCHEDULE_SWEEP_CAP = 2000++# Teams named in the sweep's log line, worst first.+STALLED_SCHEDULE_LOG_TEAMS = 10++# Alert on a sustained non-zero `no_runs`. Each tick is a whole-fleet snapshot from one query,+# so only the newest reading is correct. `livemax` would pin the gauge at the highest value any+# live process ever wrote for this label, so a count that has since dropped to zero — the sweep+# healed, or the schemas were repaired — would still read as the old, higher value as long as+# that process stays up.+STALLED_SCHEMA_SCHEDULES_GAUGE = Gauge(+ "warehouse_stalled_schema_schedules",+ "Schemas with should_sync set whose last sync is older than their own cadence allows. "+ "kind=no_runs means no run started, which points at the schedule; kind=stuck_job means a run started and never finished.",+ ["kind"],+ multiprocess_mode="livemostrecent",+)+@shared_task(ignore_result=True,@@ -146,3 +169,53 @@ def validate_data_warehouse_table_columns(team_id: int, table_id: str) -> None:finally:if ph_client:ph_client.shutdown()+++@shared_task(ignore_result=True)+@skip_team_scope_audit+def sweep_stalled_schema_schedules() -> None:+ """Report schemas that should be syncing but have stopped getting runs.++ A schedule paused out of band takes a schema's syncs down without producing a job row, an+ error, or a digest entry, so nothing else in the system reports it. This sweep is the only+ thing that does.++ It reports and does not repair. Restarting a sync reaches into a customer's database, and+ the predicate cannot tell a schedule paused by accident from one an operator paused on+ purpose during an incident. Repair stays behind `repair_stalled_schema_schedules`, where a+ person confirms the list first.+ """+ # Deferred so the sweep's Temporal-free query path stays off Celery autodiscovery imports.+ from products.warehouse_sources.backend.stalled_schedules import find_stalled_schemas # noqa: PLC0415++ stalled = find_stalled_schemas(limit=STALLED_SCHEDULE_SWEEP_CAP + 1)+ capped = len(stalled) > STALLED_SCHEDULE_SWEEP_CAP+ if capped:+ stalled = stalled[:STALLED_SCHEDULE_SWEEP_CAP]++ by_kind: dict[str, int] = defaultdict(int)+ for schema in stalled:+ by_kind[schema.kind] += 1++ STALLED_SCHEMA_SCHEDULES_GAUGE.labels(kind="no_runs").set(by_kind["no_runs"])+ STALLED_SCHEMA_SCHEDULES_GAUGE.labels(kind="stuck_job").set(by_kind["stuck_job"])++ if not stalled:+ return++ per_team: dict[int, int] = defaultdict(int)+ for schema in stalled:+ per_team[schema.team_id] += 1++ logger.warning(+ "sweep_stalled_schema_schedules_found",+ total=len(stalled),+ no_runs=by_kind["no_runs"],+ stuck_job=by_kind["stuck_job"],+ capped=capped,+ team_count=len(per_team),+ # The worst teams only. A fleet-wide stall would otherwise put thousands of ids in one+ # log line, and the count above already says how wide it is.+ worst_teams=sorted(per_team.items(), key=lambda item: -item[1])[:STALLED_SCHEDULE_LOG_TEAMS],+ longest_stall_hours=round(max(schema.stalled_for for schema in stalled).total_seconds() / 3600, 1),+ )diff --git a/products/warehouse_sources/backend/tests/management/test_migrate_cdc_source_to_buffered.py b/products/warehouse_sources/backend/tests/management/test_migrate_cdc_source_to_buffered.pyindex 26d4382f0a66..96b972a0a39d 100644--- a/products/warehouse_sources/backend/tests/management/test_migrate_cdc_source_to_buffered.py+++ b/products/warehouse_sources/backend/tests/management/test_migrate_cdc_source_to_buffered.py@@ -124,7 +124,7 @@ class TestMigrateCDCSourceToBuffered(BaseTest):# The purge itself is best-effort; a surviving file would replay legacy-delivered rows# against a lane with no watermark, silently. Abort with the mode unchanged.source = self._source()- self._schema(source, "users")+ schema = self._schema(source, "users")leftover = f"bucket/cdc_producer/x/{build_buffer_file_name(1, 2, 0)}"with _mocked_side_effects(buffer_keys=[leftover]) as mocks:@@ -133,8 +133,47 @@ class TestMigrateCDCSourceToBuffered(BaseTest):source.refresh_from_db()assert "cdc_ingest_mode" not in source.job_inputs+ # The mode never changed, so the source is the legacy source it was before the command+ # ran. Keeping its schedules paused would stop the customer's syncs with nothing to+ # report it: no run starts, so there is no job row and no error.+ mocks["unpause_schema"].assert_called_once_with(str(schema.id))mocks["unpause"].assert_not_called()+ def test_flip_restores_already_paused_schedules_when_a_later_pause_fails(self):+ # `_pause_schema_schedules_strict` pauses schemas one at a time; a later one failing must+ # not strand the ones that already paused. The mode never changed, so the source is still+ # legacy, and leaving any of its schedules paused would stop syncs with nothing anywhere+ # reporting it.+ source = self._source()+ first = self._schema(source, "users")+ second = self._schema(source, "events")++ with _mocked_side_effects() as mocks:+ mocks["pause_schema"].side_effect = [None, Exception("boom")]+ with pytest.raises(CommandError, match="Could not pause the schedule"):+ self._run(source)++ source.refresh_from_db()+ assert "cdc_ingest_mode" not in source.job_inputs+ assert mocks["pause_schema"].call_count == 2+ assert {c.args[0] for c in mocks["unpause_schema"].call_args_list} == {str(first.id), str(second.id)}++ def test_flip_restores_schedules_and_the_mode_when_marking_schemas_served_fails(self):+ # `source.save` and `_mark_schemas` run inside one transaction specifically so a failure+ # partway through marking rolls `job_inputs` back to legacy too, instead of leaving the+ # source buffered with only some schemas marked served and every schedule still paused.+ source = self._source()+ schema = self._schema(source, "users")++ with _mocked_side_effects() as mocks:+ with patch(f"{_CMD}.update_sync_type_config_keys", side_effect=Exception("boom")):+ with pytest.raises(Exception, match="boom"):+ self._run(source)++ source.refresh_from_db()+ assert "cdc_ingest_mode" not in source.job_inputs+ mocks["unpause_schema"].assert_called_once_with(str(schema.id))+def test_rollback_drains_the_buffer_then_pauses_the_consumer_before_the_mode_flips(self):source = self._source(ingest_mode="buffered")schema = self._schema(source, "users")@@ -147,6 +186,24 @@ class TestMigrateCDCSourceToBuffered(BaseTest):# Fully-applied leftovers stay: the position guard no-ops a replay, the TTL clears them.mocks["purge"].assert_not_called()mocks["pause_schema"].assert_called_once_with(str(schema.id))+ # Step 4 paused them, so the rollback has to hand them back, or the source lands on legacy+ # delivery with nothing scheduled to load it.+ mocks["unpause_schema"].assert_called_once_with(str(schema.id))++ def test_restoring_schedules_leaves_a_schema_that_stopped_syncing_paused(self):+ # A drain wait runs for minutes, and a user who turns a schema off in that window must not+ # have it turned back on by the abort path.+ source = self._source()+ staying = self._schema(source, "users")+ disabled = self._schema(source, "events")+ leftover = f"bucket/cdc_producer/x/{build_buffer_file_name(1, 2, 0)}"+ ExternalDataSchema.objects.filter(id=disabled.id).update(should_sync=False)++ with _mocked_side_effects(buffer_keys=[leftover]) as mocks:+ with pytest.raises(CommandError, match="survived the purge"):+ self._run(source)++ mocks["unpause_schema"].assert_called_once_with(str(staying.id))def test_rollback_refuses_while_the_buffer_holds_unapplied_changes(self):# The buffer tail is WAL the slot already advanced past — flipping to legacy before the@@ -163,6 +220,7 @@ class TestMigrateCDCSourceToBuffered(BaseTest):assert source.job_inputs["cdc_ingest_mode"] == "buffered"# Consumer schedules must still be live so they can catch up for the re-run.mocks["pause_schema"].assert_not_called()+ mocks["unpause_schema"].assert_not_called()def test_rollback_ignores_prefixes_the_buffered_lane_never_served(self):# A legacy schema's prefix holds shadow copies no consumer ever reads, so scanning it would@@ -210,6 +268,21 @@ class TestMigrateCDCSourceToBuffered(BaseTest):assert source.job_inputs["cdc_ingest_mode"] == "legacy"assert source.job_inputs["cdc_buffered_before"]+ def test_rollback_restores_schedules_even_when_the_extraction_unpause_fails(self):+ # The per-schema restore runs before the single Temporal call that unpauses extraction, so+ # a raise from that call does not also strand the per-schema schedules a second time.+ source = self._source(ingest_mode="buffered")+ schema = self._schema(source, "users")++ with _mocked_side_effects() as mocks:+ mocks["unpause"].side_effect = Exception("boom")+ with pytest.raises(Exception, match="boom"):+ self._run(source, rollback=True)++ source.refresh_from_db()+ assert source.job_inputs["cdc_ingest_mode"] == "legacy"+ mocks["unpause_schema"].assert_called_once_with(str(schema.id))+def test_a_flip_after_a_rollback_is_not_refused_for_our_own_column(self):# Rollback leaves `_ph_cdc_seq` in the warehouse table and puts the source back on legacy,# so the column looks exactly like a source-owned one. Refusing here would strand thediff --git a/products/warehouse_sources/backend/tests/management/test_repair_stalled_schema_schedules.py b/products/warehouse_sources/backend/tests/management/test_repair_stalled_schema_schedules.pynew file mode 100644index 000000000000..eb9bb7c7e222--- /dev/null+++ b/products/warehouse_sources/backend/tests/management/test_repair_stalled_schema_schedules.py@@ -0,0 +1,121 @@+import io+from datetime import timedelta++import pytest+from posthog.test.base import BaseTest+from unittest.mock import patch++from django.core.management import call_command+from django.core.management.base import CommandError+from django.utils import timezone++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.models.external_data_source import ExternalDataSource++_CMD = "products.warehouse_sources.backend.management.commands.repair_stalled_schema_schedules"+++class TestRepairStalledSchemaSchedules(BaseTest):+ def _stalled_schema(self, **overrides) -> ExternalDataSchema:+ source = ExternalDataSource.objects.create(+ team=self.team,+ source_type=overrides.pop("source_type", "Supabase"),+ job_inputs=overrides.pop("job_inputs", {}),+ )+ return ExternalDataSchema.objects.create(+ team=self.team,+ source=source,+ name=overrides.pop("name", "users"),+ sync_frequency_interval=timedelta(minutes=5),+ last_synced_at=timezone.now() - timedelta(days=5),+ status=overrides.pop("status", ExternalDataSchema.Status.COMPLETED),+ **overrides,+ )++ def _run(self, **kwargs) -> str:+ out = io.StringIO()+ call_command("repair_stalled_schema_schedules", stdout=out, yes=True, **kwargs)+ return out.getvalue()++ def test_dry_run_reports_without_touching_the_schedule(self) -> None:+ schema = self._stalled_schema()++ with patch(f"{_CMD}.repair_stalled_schema") as mock_repair:+ output = self._run()++ assert str(schema.id) in output+ assert "Dry run" in output+ mock_repair.assert_not_called()++ def test_live_run_repairs_each_stalled_schema(self) -> None:+ schema = self._stalled_schema()++ with patch(f"{_CMD}.repair_stalled_schema") as mock_repair:+ self._run(live_run=True)++ assert [call.args[0].schema_id for call in mock_repair.call_args_list] == [str(schema.id)]++ def test_a_schema_skipped_on_reload_is_not_counted_as_repaired(self) -> None:+ # repair_stalled_schema returns False, not an exception, when a revalidation guard finds+ # the row no longer eligible on reload. That must not be reported the same as a rewrite.+ schema = self._stalled_schema()++ with patch(f"{_CMD}.repair_stalled_schema", return_value=False) as mock_repair:+ output = self._run(live_run=True)++ mock_repair.assert_called_once()+ assert str(schema.id) in output+ assert "skipped (no longer eligible)" in output+ assert "Repaired 0 schema(s), 0 failed, 1 skipped on reload." in output++ def test_a_wedged_run_is_listed_but_left_for_the_unstick_command(self) -> None:+ schema = self._stalled_schema()+ ExternalDataJob.objects.create(+ team=self.team,+ pipeline=schema.source,+ schema=schema,+ status=ExternalDataJob.Status.RUNNING,+ rows_synced=0,+ )++ with patch(f"{_CMD}.repair_stalled_schema") as mock_repair:+ output = self._run(live_run=True)++ # Rescheduling a schema whose workflow is wedged changes nothing: Temporal skips the tick+ # while that workflow is still Running.+ mock_repair.assert_not_called()+ assert "unstick_external_data_jobs" in output++ def test_include_buffered_does_not_override_an_admin_paused_schema(self) -> None:+ # --include-buffered only overrides the buffered-CDC exclusion. A schema still carrying+ # admin_unpause_schedule_after_run is deferred to whatever cleared it, not to this flag.+ schema = self._stalled_schema(sync_type_config={"admin_unpause_schedule_after_run": True})++ with patch(f"{_CMD}.repair_stalled_schema") as mock_repair:+ output = self._run(live_run=True, include_buffered=True)++ mock_repair.assert_not_called()+ assert str(schema.id) in output+ assert "admin-triggered run" in output++ def test_a_streaming_cdc_schema_is_excluded_before_it_reaches_the_command(self) -> None:+ # A paused per-schema schedule is a streaming CDC schema's steady state, so it is+ # excluded at the predicate rather than surfaced here for --include-buffered to bypass.+ self._stalled_schema(sync_type=ExternalDataSchema.SyncType.CDC, sync_type_config={"cdc_mode": "streaming"})++ with patch(f"{_CMD}.repair_stalled_schema") as mock_repair:+ output = self._run(live_run=True, include_buffered=True)++ mock_repair.assert_not_called()+ assert "No stalled schemas match" in output++ def test_the_cap_stops_an_unexpectedly_wide_repair(self) -> None:+ for name in ("users", "events", "orgs"):+ self._stalled_schema(name=name)++ with patch(f"{_CMD}.repair_stalled_schema") as mock_repair:+ with pytest.raises(CommandError, match="above the --max-schemas cap"):+ self._run(live_run=True, max_schemas=2)++ mock_repair.assert_not_called()diff --git a/products/warehouse_sources/backend/tests/test_stalled_schedules.py b/products/warehouse_sources/backend/tests/test_stalled_schedules.pynew file mode 100644index 000000000000..f593268942e6--- /dev/null+++ b/products/warehouse_sources/backend/tests/test_stalled_schedules.py@@ -0,0 +1,306 @@+from datetime import timedelta++from posthog.test.base import BaseTest+from unittest.mock import patch++from django.utils import timezone++from parameterized import parameterized++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.models.external_data_source import ExternalDataSource+from products.warehouse_sources.backend.stalled_schedules import (+ REPAIRED_SCHEMA_ERROR,+ find_stalled_schemas,+ repair_stalled_schema,+)+from products.warehouse_sources.backend.tasks.tasks import (+ STALLED_SCHEMA_SCHEDULES_GAUGE,+ sweep_stalled_schema_schedules,+)+++class TestStalledSchedules(BaseTest):+ def _source(self, **overrides) -> ExternalDataSource:+ return ExternalDataSource.objects.create(+ team=self.team,+ source_type=overrides.pop("source_type", "Supabase"),+ job_inputs=overrides.pop("job_inputs", {}),+ **overrides,+ )++ def _schema(+ self,+ source: ExternalDataSource | None = None,+ *,+ synced_ago: timedelta = timedelta(days=1),+ sync_frequency_interval: timedelta | None = timedelta(hours=6),+ **overrides,+ ) -> ExternalDataSchema:+ return ExternalDataSchema.objects.create(+ team=self.team,+ source=source or self._source(),+ name=overrides.pop("name", "users"),+ sync_frequency_interval=sync_frequency_interval,+ last_synced_at=None if synced_ago is None else timezone.now() - synced_ago,+ status=overrides.pop("status", ExternalDataSchema.Status.COMPLETED),+ **overrides,+ )++ @parameterized.expand(+ [+ ("just synced", timedelta(hours=6), timedelta(hours=1), False),+ ("inside three intervals", timedelta(hours=6), timedelta(hours=10), False),+ ("past three intervals", timedelta(hours=6), timedelta(hours=20), True),+ # The two-hour floor keeps a single slow run on a five-minute schema from qualifying.+ ("five minute under the floor", timedelta(minutes=5), timedelta(hours=1), False),+ ("five minute past the floor", timedelta(minutes=5), timedelta(hours=3), True),+ # A null interval falls back to the column default of six hours.+ ("null interval uses the default", None, timedelta(hours=20), True),+ ]+ )+ def test_stall_window_scales_with_the_schema_cadence(+ self, _name: str, interval: timedelta | None, synced_ago: timedelta, expected: bool+ ) -> None:+ schema = self._schema(synced_ago=synced_ago, sync_frequency_interval=interval)++ found = {s.schema_id for s in find_stalled_schemas()}++ assert (str(schema.id) in found) is expected++ @parameterized.expand(+ [+ ("sync turned off", {"should_sync": False}, {}),+ ("deleted schema", {"deleted": True}, {}),+ # A failing schema carries its error on the row and reaches the failure digest.+ ("already failing", {"status": ExternalDataSchema.Status.FAILED}, {}),+ ("billing limited", {"status": ExternalDataSchema.Status.BILLING_LIMIT_REACHED}, {}),+ ("paused by the user", {"status": ExternalDataSchema.Status.PAUSED}, {}),+ # Nothing has ever completed, so the schema may still be on its first snapshot.+ ("never synced", {"synced_ago": None}, {}),+ ("deleted source", {}, {"deleted": True}),+ # A direct-query source has no schedule to stall.+ ("direct query source", {}, {"access_method": ExternalDataSource.AccessMethod.DIRECT}),+ # A paused per-schema schedule is a streaming CDC schema's steady state:+ # CDCExtractionWorkflow owns it and pauses it again on its own next tick+ # (CDCHandledExternally). A source marked cdc_broken can drift the schema's status+ # away from FAILED, so this is excluded here rather than relying on that status.+ (+ "streaming cdc schema",+ {"sync_type": ExternalDataSchema.SyncType.CDC, "sync_type_config": {"cdc_mode": "streaming"}},+ {},+ ),+ # cdc_halted is a configuration marker independent of should_sync and status: a+ # broken source's schema can still read should_sync=True and a self-reporting status.+ ("cdc broken source", {"sync_type_config": {"cdc_broken": True}}, {}),+ ("cdc extraction paused", {"sync_type_config": {"cdc_extraction_paused": True}}, {}),+ ]+ )+ def test_schemas_without_a_stalled_schedule_are_not_reported(+ self, _name: str, schema_overrides: dict, source_overrides: dict+ ) -> None:+ source = self._source(**source_overrides)+ schema = self._schema(source, **{"synced_ago": timedelta(days=5), **schema_overrides})++ found = {s.schema_id for s in find_stalled_schemas()}++ assert str(schema.id) not in found++ def test_a_schema_with_a_running_job_is_a_wedged_run_not_a_stalled_schedule(self) -> None:+ schema = self._schema(synced_ago=timedelta(days=5))+ ExternalDataJob.objects.create(+ team=self.team,+ pipeline=schema.source,+ schema=schema,+ status=ExternalDataJob.Status.RUNNING,+ rows_synced=0,+ )++ stalled = {s.schema_id: s for s in find_stalled_schemas()}++ # Rescheduling would not help: its workflow has to be terminated first, which is what+ # unstick_external_data_jobs does.+ assert stalled[str(schema.id)].kind == "stuck_job"+ assert stalled[str(schema.id)].repairable_here is False++ def test_a_buffered_cdc_schema_is_reported_but_not_repairable_here(self) -> None:+ source = self._source(job_inputs={"cdc_ingest_mode": "buffered"})+ schema = self._schema(source, synced_ago=timedelta(days=5))++ stalled = {s.schema_id: s for s in find_stalled_schemas()}++ # Its schedule paces buffer consumption, so restarting it out of sequence merges files+ # against a table the buffered lane already writes.+ assert stalled[str(schema.id)].kind == "no_runs"+ assert stalled[str(schema.id)].repairable_here is False++ def test_a_schema_with_no_sync_interval_is_reported_but_not_repairable_here(self) -> None:+ # get_sync_schedule passes sync_frequency_interval straight into ScheduleIntervalSpec,+ # where a null value raises. Reporting it is still useful; repairing it would just fail.+ schema = self._schema(synced_ago=timedelta(days=5), sync_frequency_interval=None)++ stalled = {s.schema_id: s for s in find_stalled_schemas()}++ assert stalled[str(schema.id)].kind == "no_runs"+ assert stalled[str(schema.id)].has_sync_interval is False+ assert stalled[str(schema.id)].repairable_here is False++ def test_a_schema_paused_for_an_admin_run_is_reported_but_not_repairable_here(self) -> None:+ # ad_hoc_sync.py and the admin action pause the schedule and set this marker for an+ # in-flight non-scheduled run, clearing it themselves once that run completes+ # successfully. It surviving to a stall check means unpausing here could race that run.+ schema = self._schema(+ synced_ago=timedelta(days=5),+ sync_type_config={"admin_unpause_schedule_after_run": True},+ )++ stalled = {s.schema_id: s for s in find_stalled_schemas()}++ assert stalled[str(schema.id)].kind == "no_runs"+ assert stalled[str(schema.id)].admin_paused is True+ assert stalled[str(schema.id)].repairable_here is False++ def test_repair_clears_a_stale_running_status_and_reschedules_without_billing_a_run(self) -> None:+ schema = self._schema(synced_ago=timedelta(days=5), status=ExternalDataSchema.Status.RUNNING)+ stalled = next(s for s in find_stalled_schemas() if s.schema_id == str(schema.id))++ with patch("products.data_warehouse.backend.facade.api.sync_external_data_job_workflow") as mock_sync:+ repair_stalled_schema(stalled)++ schema.refresh_from_db()+ # The scheduler skips a tick while the schema reads Running, so leaving the status behind+ # would reschedule a schema that still never runs.+ assert schema.status == ExternalDataSchema.Status.FAILED+ assert schema.latest_error == REPAIRED_SCHEMA_ERROR+ # Scheduled runs bill, so the repair waits for the schema's own next tick.+ assert mock_sync.call_args.kwargs["trigger_immediately"] is False+ assert mock_sync.call_args.kwargs["should_sync"] is True++ def test_repair_stamps_last_error_notified_at_to_avoid_a_stale_renotify(self) -> None:+ # get_team_ids_with_recent_sync_failures renotifies once last_error_notified_at is more+ # than seven days old, with no newer failed job required. Without a fresh stamp here, a+ # schema that failed and was notified long ago, then recovered, would have this repaint+ # read as "still failing" and send the failure digest instead of the informational message.+ old_notification = timezone.now() - timedelta(days=30)+ schema = self._schema(+ synced_ago=timedelta(days=5),+ status=ExternalDataSchema.Status.RUNNING,+ last_error_notified_at=old_notification,+ )+ stalled = next(s for s in find_stalled_schemas() if s.schema_id == str(schema.id))++ with patch("products.data_warehouse.backend.facade.api.sync_external_data_job_workflow"):+ repair_stalled_schema(stalled)++ schema.refresh_from_db()+ assert schema.last_error_notified_at is not None+ assert schema.last_error_notified_at > old_notification++ def test_repair_skips_a_schema_disabled_since_it_was_discovered(self) -> None:+ # The confirmation prompt in the management command alone can put minutes between+ # discovery and this call. A schema a user disabled in that window must stay paused,+ # not get rescheduled out from under them by a stale should_sync=True snapshot.+ schema = self._schema(synced_ago=timedelta(days=5))+ stalled = next(s for s in find_stalled_schemas() if s.schema_id == str(schema.id))++ schema.should_sync = False+ schema.save(update_fields=["should_sync"])++ with patch("products.data_warehouse.backend.facade.api.sync_external_data_job_workflow") as mock_sync:+ repair_stalled_schema(stalled)++ mock_sync.assert_not_called()++ def test_repair_skips_a_schema_deleted_since_it_was_discovered(self) -> None:+ # Deleting a schema does not itself flip should_sync, so a schema deleted in the window+ # between discovery and repair can still read should_sync=True here.+ schema = self._schema(synced_ago=timedelta(days=5))+ stalled = next(s for s in find_stalled_schemas() if s.schema_id == str(schema.id))++ schema.deleted = True+ schema.save(update_fields=["deleted"])++ with patch("products.data_warehouse.backend.facade.api.sync_external_data_job_workflow") as mock_sync:+ repair_stalled_schema(stalled)++ mock_sync.assert_not_called()++ def test_repair_skips_a_schema_paused_for_an_admin_run_since_it_was_discovered(self) -> None:+ # Same window as should_sync above: an admin-triggered run can pause the schedule and set+ # this marker after discovery. Unpausing here would race the admin run's own workflow.+ schema = self._schema(synced_ago=timedelta(days=5))+ stalled = next(s for s in find_stalled_schemas() if s.schema_id == str(schema.id))++ schema.sync_type_config = {"admin_unpause_schedule_after_run": True}+ schema.save(update_fields=["sync_type_config"])++ with patch("products.data_warehouse.backend.facade.api.sync_external_data_job_workflow") as mock_sync:+ repair_stalled_schema(stalled)++ mock_sync.assert_not_called()++ def test_repair_skips_a_schema_whose_sync_interval_is_null(self) -> None:+ # get_sync_schedule crashes on a null interval; skip rather than fail every time.+ schema = self._schema(synced_ago=timedelta(days=5))+ stalled = next(s for s in find_stalled_schemas() if s.schema_id == str(schema.id))++ schema.sync_frequency_interval = None+ schema.save(update_fields=["sync_frequency_interval"])++ with patch("products.data_warehouse.backend.facade.api.sync_external_data_job_workflow") as mock_sync:+ repair_stalled_schema(stalled)++ mock_sync.assert_not_called()++ def test_repair_skips_a_schema_that_flipped_to_cdc_streaming_since_it_was_discovered(self) -> None:+ # initial_sync_complete (and so the snapshot-to-streaming flip) can land in the window+ # between discovery and this call. A paused schedule is streaming's steady state, so+ # unpausing it here would just race CDCExtractionWorkflow for nothing.+ schema = self._schema(synced_ago=timedelta(days=5), sync_type=ExternalDataSchema.SyncType.CDC)+ stalled = next(s for s in find_stalled_schemas() if s.schema_id == str(schema.id))++ schema.sync_type_config = {"cdc_mode": "streaming"}+ schema.save(update_fields=["sync_type_config"])++ with patch("products.data_warehouse.backend.facade.api.sync_external_data_job_workflow") as mock_sync:+ repair_stalled_schema(stalled)++ mock_sync.assert_not_called()++ def test_repair_skips_a_schema_marked_cdc_broken_since_it_was_discovered(self) -> None:+ # The halt marker exists precisely to stop anything else from touching the schedule+ # until repair_cdc clears it, so it is re-checked for the same staleness reason as the+ # other guards even though the queryset already excludes it up front.+ schema = self._schema(synced_ago=timedelta(days=5), sync_type=ExternalDataSchema.SyncType.CDC)+ stalled = next(s for s in find_stalled_schemas() if s.schema_id == str(schema.id))++ schema.sync_type_config = {"cdc_broken": True}+ schema.save(update_fields=["sync_type_config"])++ with patch("products.data_warehouse.backend.facade.api.sync_external_data_job_workflow") as mock_sync:+ repair_stalled_schema(stalled)++ mock_sync.assert_not_called()+++class TestStalledScheduleSweep(BaseTest):+ def test_the_sweep_reports_stalled_schemas_without_repairing_them(self) -> None:+ # Restarting a sync reaches into a customer's database, and the predicate cannot tell a+ # schedule paused by accident from one an operator paused during an incident. Repair stays+ # behind the management command, where a person confirms the list first.+ source = ExternalDataSource.objects.create(team=self.team, source_type="Supabase", job_inputs={})+ ExternalDataSchema.objects.create(+ team=self.team,+ source=source,+ name="users",+ sync_frequency_interval=timedelta(minutes=5),+ last_synced_at=timezone.now() - timedelta(days=5),+ status=ExternalDataSchema.Status.COMPLETED,+ )++ with patch("products.data_warehouse.backend.facade.api.sync_external_data_job_workflow") as mock_sync:+ sweep_stalled_schema_schedules()++ mock_sync.assert_not_called()+ assert STALLED_SCHEMA_SCHEDULES_GAUGE.labels(kind="no_runs")._value.get() == 1