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.

feat(warehouse-sources): add check-mismatches to manage_warehouse_queue (#76556)

estefania3f9236299d9b
diff --git a/products/warehouse_sources/backend/management/commands/manage_warehouse_queue.py b/products/warehouse_sources/backend/management/commands/manage_warehouse_queue.py
index de2760490c2f..0c8c41d03c53 100644
--- a/products/warehouse_sources/backend/management/commands/manage_warehouse_queue.py
+++ b/products/warehouse_sources/backend/management/commands/manage_warehouse_queue.py
@@ -1,10 +1,11 @@
"""Ops tooling for the v3 warehouse sources load queue (delta and duckgres sinks).
-Inspect queue state, manually fail wedged runs, and force-release stuck
-coordination state (group leases, the v3 Redis pipeline lock) from a toolbox
-pod. ``--sink duckgres`` drives the same verbs against the duckgres sink's
-status and lease tables; that sink does not own the ExternalDataJob, the Redis
-pipeline lock, or the Temporal workflow, so those steps are delta-only.
+Inspect queue state, count batches whose state disagrees with their job's,
+manually fail wedged runs, and force-release stuck coordination state (group
+leases, the v3 Redis pipeline lock) from a toolbox pod. ``--sink duckgres``
+drives the same verbs against the duckgres sink's status and lease tables; that
+sink does not own the ExternalDataJob, the Redis pipeline lock, or the Temporal
+workflow, so those steps (and check-mismatches entirely) are delta-only.
Mutating actions are dry-run by default and mirror the consumers' own
fail/reconcile semantics rather than inventing a second code path.
"""
@@ -49,6 +50,7 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
logger = structlog.get_logger(__name__)
DEFAULT_FAIL_REASON = "manually failed via manage_warehouse_queue"
+DEFAULT_MISMATCH_REASON = "reconciled via manage_warehouse_queue check-mismatches"
MAX_RUNS_DEFAULT = 20
PRINT_LIMIT = 50
DRY_RUN_MESSAGE = "Dry run - no changes written. Re-run with --live-run to apply."
@@ -91,8 +93,9 @@ class FailTarget:
class Command(BaseCommand):
help = (
- "Manage the v3 warehouse sources load queue: inspect state (status), manually fail "
- "wedged runs (fail-run/cancel), or force-release stuck group leases and v3 Redis "
+ "Manage the v3 warehouse sources load queue: inspect state (status), count batches "
+ "whose state disagrees with their job's (check-mismatches), manually fail wedged runs "
+ "(fail-run/cancel), or force-release stuck group leases and v3 Redis "
"pipeline locks (release-locks). --sink duckgres targets the duckgres sink's queue "
"state instead of the delta loader's. Mutating actions are dry-run unless --live-run "
"is given."
@@ -171,6 +174,35 @@ class Command(BaseCommand):
help="Also delete LIVE group leases (skipped by default - a healthy pod may hold them)",
)
+ mismatches = subparsers.add_parser(
+ "check-mismatches",
+ help="Count batches whose queue state disagrees with their ExternalDataJob's status (delta sink only)",
+ )
+ self._add_target_args(mismatches)
+ mismatches.add_argument(
+ "--grace-seconds",
+ type=int,
+ default=RECOVERY_GRACE_SECONDS,
+ help="Ignore mismatches younger than this - a job can go terminal moments before the "
+ f"consumer writes its last batch status (default {RECOVERY_GRACE_SECONDS}s)",
+ )
+ mismatches.add_argument(
+ "--reason", type=str, default=DEFAULT_MISMATCH_REASON, help="Recorded as the job's error when repairing"
+ )
+ mismatches.add_argument("--live-run", action="store_true", help="Repair what was found (default is dry-run)")
+ mismatches.add_argument("--yes", action="store_true", help="Skip interactive confirmation")
+ mismatches.add_argument(
+ "--max-runs",
+ type=int,
+ default=MAX_RUNS_DEFAULT,
+ help=f"Abort the repair if more than this many mismatches were found (default {MAX_RUNS_DEFAULT})",
+ )
+ mismatches.add_argument(
+ "--force",
+ action="store_true",
+ help="Also delete LIVE group leases while repairing (skipped by default)",
+ )
+
release = subparsers.add_parser(
"release-locks",
help="Force-release group leases and/or v3 Redis pipeline locks left behind by dead pods",
@@ -217,6 +249,8 @@ class Command(BaseCommand):
self._handle_status(conn, options, sink=sink, queue=queue)
elif action == "fail-run":
self._handle_fail_run(conn, options, sink=sink, queue=queue)
+ elif action == "check-mismatches":
+ self._handle_check_mismatches(conn, options, sink=sink, queue=queue)
elif action == "release-locks":
self._handle_release_locks(conn, options, sink=sink, queue=queue)
@@ -477,6 +511,16 @@ class Command(BaseCommand):
if cancel_workflow:
self._cancel_workflows(options, [jobs_by_id.get(t.job_id) for t in targets])
+ released, skipped_live = self._release_leases_for(conn, targets, queue=queue, force=force)
+ summary = f"Done. Released {released} group lease(s)."
+ if skipped_live:
+ summary += f" Skipped {skipped_live} LIVE lease(s)."
+ self.stdout.write(self.style.SUCCESS(summary))
+
+ def _release_leases_for(
+ self, conn: psycopg.Connection[Any], targets: list[FailTarget], *, queue: SinkQueue, force: bool
+ ) -> tuple[int, int]:
+ """Drop the group leases the just-failed targets held. Returns (released, skipped_live)."""
pair_set = {(t.team_id, t.schema_id) for t in targets if t.schema_id}
# Re-read lease state after the fail writes: gate liveness on what holds now,
# not on the preview snapshot, so a lease acquired mid-operation counts as live.
@@ -496,11 +540,7 @@ class Command(BaseCommand):
)
continue
leases_to_delete.append((lease.team_id, lease.schema_id))
- released = queue.force_release_leases(conn, pairs=leases_to_delete)
- summary = f"Done. Released {released} group lease(s)."
- if skipped_live:
- summary += f" Skipped {skipped_live} LIVE lease(s)."
- self.stdout.write(self.style.SUCCESS(summary))
+ return queue.force_release_leases(conn, pairs=leases_to_delete), skipped_live
@staticmethod
def _filter_stuck(targets: list[FailTarget], *, grace_seconds: int) -> tuple[list[FailTarget], int]:
@@ -610,6 +650,171 @@ class Command(BaseCommand):
)
)
+ # -- check-mismatches -------------------------------------------------------
+
+ def _handle_check_mismatches(
+ self, conn: psycopg.Connection[Any], options: dict[str, Any], *, sink: str, queue: SinkQueue
+ ) -> None:
+ """Report (and optionally repair) runs whose queue state disagrees with their job's status.
+
+ The queue and the ExternalDataJob live in different databases with no FK
+ between them, so nothing enforces agreement. Three ways they can diverge:
+
+ A. the job went terminal but the queue still holds non-terminal batches
+ B. the job is still Running with nothing left pending in the queue
+ C. batches reference a job_id that has no row in the main DB
+
+ A and B are the two halves of the consumers' own reconcile loop, so
+ repair reuses ``_fail_target`` rather than a second code path. C is
+ reported only: the job may have been hard-deleted or the id may be
+ corrupt, and guessing is worse than surfacing it.
+ """
+ if sink != SINK_DELTA:
+ raise CommandError(
+ "check-mismatches only applies to the delta sink: the duckgres sink does not own the "
+ "ExternalDataJob, and its batches legitimately outlive a Completed delta job."
+ )
+
+ scope = self._resolve_scope(options, allow_empty=True)
+ grace: int = options["grace_seconds"]
+ live_run: bool = options["live_run"]
+
+ # include_job_only pulls in the Running V3 jobs the queue knows nothing
+ # about, which is exactly class B; the queue-visible runs give A and C.
+ targets = self._collect_fail_targets(conn, scope, queue=queue, include_job_only=True)
+ jobs_by_id = {str(j.id): j for j in ExternalDataJob.objects.filter(id__in=[t.job_id for t in targets])}
+
+ class_a: list[FailTarget] = []
+ class_b: list[FailTarget] = []
+ class_c: list[FailTarget] = []
+ for t in targets:
+ if t.run_uuid is None:
+ class_b.append(t)
+ continue
+ if t.pending_batches == 0:
+ # Only reachable under --run-uuid, which reads terminal runs too.
+ continue
+ job = jobs_by_id.get(t.job_id)
+ if job is None:
+ class_c.append(t)
+ elif job.status != ExternalDataJob.Status.RUNNING:
+ class_a.append(t)
+
+ class_a, skipped_a = self._filter_stuck(class_a, grace_seconds=grace)
+ class_b, skipped_b = self._filter_stuck(class_b, grace_seconds=grace)
+ class_c, skipped_c = self._filter_stuck(class_c, grace_seconds=grace)
+ skipped = skipped_a + skipped_b + skipped_c
+
+ self.stdout.write(self.style.MIGRATE_HEADING(f"Mismatches [{sink} sink] (grace {grace}s)"))
+ a_batches = sum(t.pending_batches for t in class_a)
+ c_batches = sum(t.pending_batches for t in class_c)
+ self.stdout.write(f" A: terminal job, non-terminal batches {len(class_a)} run(s), {a_batches} batch(es)")
+ by_status: dict[str, list[FailTarget]] = {}
+ for t in class_a:
+ job = jobs_by_id.get(t.job_id)
+ by_status.setdefault(job.status if job else "?", []).append(t)
+ for status in sorted(by_status):
+ group = by_status[status]
+ self.stdout.write(f" {status}: {len(group)} runs / {sum(t.pending_batches for t in group)} batches")
+ self.stdout.write(f" B: Running job, nothing pending {len(class_b)} job(s)")
+ self.stdout.write(f" C: batches referencing a missing job {len(class_c)} run(s), {c_batches} batch(es)")
+ if skipped:
+ self.stdout.write(f" skipped (within grace): {skipped}")
+
+ for label, group in (("A", class_a), ("B", class_b), ("C", class_c)):
+ if not group:
+ continue
+ self.stdout.write(self.style.MIGRATE_HEADING(f"Class {label} detail ({len(group)})"))
+ for t in group[:PRINT_LIMIT]:
+ job = jobs_by_id.get(t.job_id)
+ job_status = job.status if job else "<job not found>"
+ queue_note = (
+ f"pending={t.pending_batches}/{t.total_batches}"
+ if t.run_uuid
+ else "no queue batches in retention window"
+ )
+ self.stdout.write(
+ f" run={t.run_uuid or '-'} job={t.job_id} (status={job_status}) team={t.team_id} "
+ f"schema={t.schema_id or '-'} {queue_note} last_activity={self._age(t.last_activity_at)} ago "
+ f"workflow_run_id={t.workflow_run_id or '-'}"
+ )
+ if len(group) > PRINT_LIMIT:
+ self.stdout.write(f" ... and {len(group) - PRINT_LIMIT} more")
+
+ repairable = class_a + class_b
+ if not repairable:
+ if not class_c:
+ self.stdout.write(self.style.SUCCESS("No mismatches in scope."))
+ else:
+ self.stdout.write("Class C is reported only - resolve the missing jobs by hand.")
+ return
+
+ if not live_run:
+ self.stdout.write(f"Would repair {len(repairable)} mismatch(es) (class A and B). {DRY_RUN_MESSAGE}")
+ return
+
+ max_runs: int = options["max_runs"]
+ if len(repairable) > max_runs:
+ raise CommandError(
+ f"{len(repairable)} repairable mismatches, above the --max-runs cap of {max_runs}. "
+ "Narrow the targeting or raise --max-runs explicitly."
+ )
+
+ reason: str = options["reason"]
+ self._confirm(f"Repair {len(repairable)} mismatch(es)? Type 'fail' to continue: ", "fail", yes=options["yes"])
+
+ repaired: list[FailTarget] = []
+ raced = 0
+ for t in repairable:
+ # Class B is a job-only snapshot taken during collection. Re-check that
+ # the queue still holds nothing pending for this job before failing it:
+ # a consumer that enqueued batches since then has turned it back into a
+ # healthy Running job, and failing it now would create the class A
+ # mismatch this command exists to fix.
+ if t.run_uuid is None and self._job_has_pending_batches(conn, t, queue=queue):
+ self.stdout.write(
+ self.style.WARNING(
+ f"job={t.job_id}: batches enqueued since detection - no longer a class B mismatch, skipped"
+ )
+ )
+ raced += 1
+ continue
+ self.stdout.write(f"run={t.run_uuid or '-'} job={t.job_id}:")
+ self._fail_target(conn, t, reason=reason, queue=queue, is_delta=True)
+ repaired.append(t)
+ logger.info(
+ "manage_warehouse_queue_check_mismatches",
+ sink=sink,
+ run_uuid=t.run_uuid,
+ job_id=t.job_id,
+ team_id=t.team_id,
+ external_data_schema_id=t.schema_id,
+ mismatch_class="B" if t.run_uuid is None else "A",
+ reason=reason,
+ )
+
+ # Only release leases for jobs we actually failed - a raced-back class B job
+ # is live work whose lease must stay put.
+ released, skipped_live = self._release_leases_for(conn, repaired, queue=queue, force=options["force"])
+ summary = f"Done. Repaired {len(repaired)} mismatch(es), released {released} group lease(s)."
+ if raced:
+ summary += f" Skipped {raced} that raced back to healthy."
+ if skipped_live:
+ summary += f" Skipped {skipped_live} LIVE lease(s)."
+ self.stdout.write(self.style.SUCCESS(summary))
+
+ def _job_has_pending_batches(self, conn: psycopg.Connection[Any], target: FailTarget, *, queue: SinkQueue) -> bool:
+ """True if the queue now holds non-terminal batches for this job's schema.
+
+ Used to re-check a class B (job-only) target at repair time so a job that
+ enqueued work between detection and now is not failed out from under a live
+ consumer.
+ """
+ if target.schema_id is None:
+ return False
+ runs = queue.get_active_runs(conn, team_id=target.team_id, schema_ids=[target.schema_id], only_pending=True)
+ return any(str(r.job_id) == target.job_id for r in runs)
+
# -- release-locks ----------------------------------------------------------
def _handle_release_locks(
diff --git a/products/warehouse_sources/backend/tests/management/test_manage_warehouse_queue.py b/products/warehouse_sources/backend/tests/management/test_manage_warehouse_queue.py
index d70fd85b967a..2be66bd7a715 100644
--- a/products/warehouse_sources/backend/tests/management/test_manage_warehouse_queue.py
+++ b/products/warehouse_sources/backend/tests/management/test_manage_warehouse_queue.py
@@ -19,6 +19,7 @@ import fakeredis
from posthog.api.test.test_organization import create_organization
from posthog.api.test.test_team import create_team
+from products.warehouse_sources.backend.management.commands.manage_warehouse_queue import Command
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
@@ -420,6 +421,171 @@ class TestStatus:
assert "unclaimed: 1" in out
+class TestCheckMismatches:
+ @pytest.mark.parametrize(
+ "status",
+ [ExternalDataJob.Status.FAILED, ExternalDataJob.Status.COMPLETED],
+ ids=["failed_job", "completed_job"],
+ )
+ def test_terminal_job_with_pending_batches_is_class_a(self, status, team, queue_conn, fake_redis):
+ _, schema, job = _create_pipeline(team)
+ run_uuid = str(uuid4())
+ _seed_active_run(queue_conn, team=team, schema=schema, job=job, run_uuid=run_uuid, age_hours=1)
+ ExternalDataJob.objects.filter(id=job.id).update(status=status)
+
+ out = _call("check-mismatches", "--team-id", str(team.pk))
+
+ assert "A: terminal job, non-terminal batches 1 run(s), 2 batch(es)" in out
+ assert f"{status}: 1 runs / 2 batches" in out
+ assert run_uuid in out
+
+ def test_running_job_with_nothing_pending_is_class_b(self, team, queue_conn, fake_redis):
+ _, _, job = _create_pipeline(team)
+ ExternalDataJob.objects.filter(id=job.id).update(created_at=timezone.now() - timedelta(hours=1))
+
+ out = _call("check-mismatches", "--team-id", str(team.pk))
+
+ assert "B: Running job, nothing pending 1 job(s)" in out
+ assert str(job.id) in out
+
+ def test_batches_referencing_a_missing_job_are_class_c(self, team, queue_conn, fake_redis):
+ _, schema, _ = _create_pipeline(team)
+ run_uuid, ghost_job_id = str(uuid4()), str(uuid4())
+ _insert_batch(
+ queue_conn,
+ team_id=team.pk,
+ schema_id=str(schema.id),
+ source_id=str(schema.source_id),
+ job_id=ghost_job_id,
+ run_uuid=run_uuid,
+ batch_index=0,
+ age_hours=1,
+ )
+
+ out = _call("check-mismatches", "--team-id", str(team.pk))
+
+ assert "C: batches referencing a missing job 1 run(s), 1 batch(es)" in out
+ assert "reported only" in out
+
+ def test_healthy_run_reports_no_mismatches(self, team, queue_conn, fake_redis):
+ _, schema, job = _create_pipeline(team)
+ _seed_active_run(queue_conn, team=team, schema=schema, job=job, run_uuid=str(uuid4()), age_hours=1)
+
+ out = _call("check-mismatches", "--team-id", str(team.pk))
+
+ assert "No mismatches in scope." in out
+
+ def test_mismatch_within_grace_is_skipped_not_reported(self, team, queue_conn, fake_redis):
+ _, schema, job = _create_pipeline(team)
+ run_uuid = str(uuid4())
+ _seed_active_run(queue_conn, team=team, schema=schema, job=job, run_uuid=run_uuid) # activity just now
+ ExternalDataJob.objects.filter(id=job.id).update(status=ExternalDataJob.Status.FAILED)
+
+ out = _call("check-mismatches", "--team-id", str(team.pk))
+
+ assert "A: terminal job, non-terminal batches 0 run(s), 0 batch(es)" in out
+ assert "skipped (within grace): 1" in out
+ assert "No mismatches in scope." in out
+
+ def test_dry_run_mutates_nothing(self, team, queue_conn, fake_redis):
+ _, schema, job = _create_pipeline(team)
+ _seed_active_run(queue_conn, team=team, schema=schema, job=job, run_uuid=str(uuid4()), age_hours=1)
+ _insert_lease(queue_conn, team_id=team.pk, schema_id=str(schema.id), live=False)
+ ExternalDataJob.objects.filter(id=job.id).update(status=ExternalDataJob.Status.COMPLETED)
+
+ out = _call("check-mismatches", "--team-id", str(team.pk))
+
+ assert "Would repair 1 mismatch(es)" in out
+ assert "Dry run" in out
+ assert _failed_status_counts_by_run(queue_conn) == {}
+ assert _lease_count(queue_conn, str(schema.id)) == 1
+
+ def test_live_run_terminalizes_class_a_batches_and_leaves_the_job_alone(self, team, queue_conn, fake_redis):
+ _, schema, job = _create_pipeline(team)
+ run_uuid = str(uuid4())
+ _seed_active_run(queue_conn, team=team, schema=schema, job=job, run_uuid=run_uuid, age_hours=1)
+ _insert_lease(queue_conn, team_id=team.pk, schema_id=str(schema.id), live=False)
+ ExternalDataJob.objects.filter(id=job.id).update(status=ExternalDataJob.Status.COMPLETED)
+
+ out = _call("check-mismatches", "--team-id", str(team.pk), "--live-run", "--yes")
+
+ assert _failed_status_counts_by_run(queue_conn) == {run_uuid: 2}
+ job.refresh_from_db()
+ assert job.status == ExternalDataJob.Status.COMPLETED # already terminal - not overwritten
+ assert "already terminal" in out
+ assert _lease_count(queue_conn, str(schema.id)) == 0
+
+ def test_live_run_fails_the_job_for_class_b(self, team, queue_conn, fake_redis):
+ _, _, job = _create_pipeline(team)
+ ExternalDataJob.objects.filter(id=job.id).update(created_at=timezone.now() - timedelta(hours=1))
+
+ _call("check-mismatches", "--team-id", str(team.pk), "--live-run", "--yes")
+
+ job.refresh_from_db()
+ assert job.status == ExternalDataJob.Status.FAILED
+
+ def test_class_b_that_races_back_to_healthy_is_not_failed(self, team, queue_conn, fake_redis):
+ _, schema, job = _create_pipeline(team)
+ ExternalDataJob.objects.filter(id=job.id).update(created_at=timezone.now() - timedelta(hours=1))
+ _insert_lease(queue_conn, team_id=team.pk, schema_id=str(schema.id), live=False)
+
+ # Simulate a consumer enqueuing batches between detection and repair: insert a
+ # pending batch for this job right after the class B target is collected, so the
+ # repair-time re-check sees live work and leaves the job alone.
+ real_collect = Command._collect_fail_targets
+
+ def collect_then_enqueue(self, conn, scope, *, queue, include_job_only):
+ targets = real_collect(self, conn, scope, queue=queue, include_job_only=include_job_only)
+ _insert_batch(
+ queue_conn,
+ team_id=team.pk,
+ schema_id=str(schema.id),
+ source_id=str(schema.source_id),
+ job_id=str(job.id),
+ run_uuid=str(uuid4()),
+ batch_index=0,
+ )
+ return targets
+
+ with patch.object(Command, "_collect_fail_targets", collect_then_enqueue):
+ out = _call("check-mismatches", "--team-id", str(team.pk), "--live-run", "--yes")
+
+ job.refresh_from_db()
+ assert job.status == ExternalDataJob.Status.RUNNING # not failed - raced back to healthy
+ assert "no longer a class B mismatch" in out
+ assert _lease_count(queue_conn, str(schema.id)) == 1 # lease preserved for live work
+
+ def test_max_runs_cap_aborts(self, team, queue_conn, fake_redis):
+ for _ in range(2):
+ _, schema, job = _create_pipeline(team)
+ _seed_active_run(queue_conn, team=team, schema=schema, job=job, run_uuid=str(uuid4()), age_hours=1)
+ ExternalDataJob.objects.filter(id=job.id).update(status=ExternalDataJob.Status.FAILED)
+
+ with pytest.raises(CommandError, match="--max-runs"):
+ _call("check-mismatches", "--team-id", str(team.pk), "--max-runs", "1", "--live-run", "--yes")
+
+ assert _failed_status_counts_by_run(queue_conn) == {}
+
+ def test_source_type_scoping_only_reports_matching_runs(self, team, team_2, queue_conn, fake_redis):
+ _, stripe_schema, stripe_job = _create_pipeline(team, source_type="Stripe")
+ _, pg_schema, pg_job = _create_pipeline(team_2, source_type="Postgres")
+ stripe_run, pg_run = str(uuid4()), str(uuid4())
+ _seed_active_run(queue_conn, team=team, schema=stripe_schema, job=stripe_job, run_uuid=stripe_run, age_hours=1)
+ _seed_active_run(queue_conn, team=team_2, schema=pg_schema, job=pg_job, run_uuid=pg_run, age_hours=1)
+ ExternalDataJob.objects.filter(id__in=[stripe_job.id, pg_job.id]).update(
+ status=ExternalDataJob.Status.FAILED,
+ )
+
+ out = _call("check-mismatches", "--source-type", "stripe")
+
+ assert stripe_run in out
+ assert pg_run not in out
+
+ def test_duckgres_sink_is_rejected(self, queue_conn, fake_redis):
+ with pytest.raises(CommandError, match="delta sink"):
+ _call("check-mismatches", "--sink", "duckgres", "--team-id", "1")
+
+
def _seed_duckgres_run(
conn: psycopg.Connection[Any],
*,