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(data-warehouse): add manage_warehouse_queue ops command for the v3 load queue (#68606)

estefaniac908382cb658
diff --git a/products/warehouse_sources/backend/management/commands/manage_warehouse_queue.py b/products/warehouse_sources/backend/management/commands/manage_warehouse_queue.py
new file mode 100644
index 000000000000..99751cd3a2de
--- /dev/null
+++ b/products/warehouse_sources/backend/management/commands/manage_warehouse_queue.py
@@ -0,0 +1,724 @@
+"""Ops tooling for the v3 warehouse sources load queue (delta sink).
+
+Inspect queue state, manually fail wedged runs, and force-release stuck
+coordination state (group leases, the v3 Redis pipeline lock) from a toolbox
+pod. Mutating actions are dry-run by default and mirror the consumer's own
+fail/reconcile semantics rather than inventing a second code path.
+"""
+
+import sys
+from dataclasses import dataclass
+from datetime import UTC, datetime
+from typing import Any
+
+from django.core.management.base import BaseCommand, CommandError, CommandParser
+
+import psycopg
+import structlog
+
+from posthog.settings import WAREHOUSE_SOURCES_DATABASE_URL
+
+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.temporal.data_imports.pipelines.pipeline_v3.batch_consumer import (
+ RECOVERY_GRACE_SECONDS,
+)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer import (
+ mark_job_failed_if_not_terminal,
+)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import (
+ PARTITION_PRUNING_INTERVAL,
+ ActiveRunRef,
+ BatchQueue,
+)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.sync_lock import (
+ get_v3_pipeline_lock_holder,
+ release_v3_pipeline_lock,
+)
+
+logger = structlog.get_logger(__name__)
+
+DEFAULT_FAIL_REASON = "manually failed via manage_warehouse_queue"
+MAX_RUNS_DEFAULT = 20
+PRINT_LIMIT = 50
+DRY_RUN_MESSAGE = "Dry run - no changes written. Re-run with --live-run to apply."
+
+
+@dataclass(frozen=True)
+class Scope:
+ """Resolved targeting: which slice of the queue an action applies to."""
+
+ team_id: int | None = None
+ schema_ids: list[str] | None = None
+ source_type: str | None = None # set only for source-type-only targeting (resolved queue-first)
+ run_uuid: str | None = None
+
+
+@dataclass(frozen=True)
+class FailTarget:
+ """A run (or queue-less Running job) selected for fail-run."""
+
+ run_uuid: str | None
+ job_id: str
+ team_id: int
+ schema_id: str | None
+ source_id: str | None
+ workflow_run_id: str | None
+ pending_batches: int
+ total_batches: int
+
+
+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 "
+ "pipeline locks (release-locks). Mutating actions are dry-run unless --live-run is given."
+ )
+
+ def add_arguments(self, parser: CommandParser) -> None:
+ subparsers = parser.add_subparsers(dest="action", required=True)
+
+ status = subparsers.add_parser("status", help="Show queue state (read-only)")
+ self._add_target_args(status)
+ status.add_argument(
+ "--stale-grace-seconds",
+ type=int,
+ default=RECOVERY_GRACE_SECONDS,
+ help="Age threshold for reporting stale 'executing' batches",
+ )
+
+ fail_run = subparsers.add_parser(
+ "fail-run",
+ aliases=["cancel"],
+ help="Fail wedged runs: mark pending batches failed, mark the job Failed, release locks",
+ )
+ self._add_target_args(fail_run)
+ fail_run.add_argument("--reason", type=str, default=DEFAULT_FAIL_REASON, help="Recorded as the job's error")
+ fail_run.add_argument("--live-run", action="store_true", help="Apply changes (default is dry-run)")
+ fail_run.add_argument("--yes", action="store_true", help="Skip interactive confirmation")
+ fail_run.add_argument(
+ "--max-runs",
+ type=int,
+ default=MAX_RUNS_DEFAULT,
+ help=f"Abort if more than this many runs match (default {MAX_RUNS_DEFAULT})",
+ )
+ fail_run.add_argument(
+ "--cancel-workflow",
+ action="store_true",
+ help="Also request cancellation of each run's Temporal workflow",
+ )
+ fail_run.add_argument(
+ "--force",
+ action="store_true",
+ help="Also delete LIVE group leases (skipped by default - a healthy pod may hold them)",
+ )
+
+ release = subparsers.add_parser(
+ "release-locks",
+ help="Force-release group leases and/or v3 Redis pipeline locks left behind by dead pods",
+ )
+ self._add_target_args(release)
+ release.add_argument("--leases-only", action="store_true", help="Only release Postgres group leases")
+ release.add_argument("--redis-only", action="store_true", help="Only release v3 Redis pipeline locks")
+ release.add_argument("--live-run", action="store_true", help="Apply changes (default is dry-run)")
+ release.add_argument("--yes", action="store_true", help="Skip interactive confirmation")
+ release.add_argument(
+ "--force",
+ action="store_true",
+ help="Also release live leases / locks that look owned by a Running job (may abort healthy work)",
+ )
+
+ @staticmethod
+ def _add_target_args(parser: CommandParser) -> None:
+ parser.add_argument("--team-id", type=int, help="Scope by team")
+ parser.add_argument("--schema-id", type=str, help="Scope by schema (requires --team-id)")
+ parser.add_argument("--source-id", type=str, help="Scope by source (requires --team-id)")
+ parser.add_argument(
+ "--source-type", type=str, help="Scope by source type, e.g. Stripe (alone or with --team-id)"
+ )
+ parser.add_argument("--run-uuid", type=str, help="Target one queue run directly (no other targeting flags)")
+
+ def handle(self, *args: Any, **options: Any) -> None:
+ action = options["action"]
+ if action == "cancel":
+ action = "fail-run"
+
+ with psycopg.connect(WAREHOUSE_SOURCES_DATABASE_URL, autocommit=True) as conn:
+ if action == "status":
+ self._handle_status(conn, options)
+ elif action == "fail-run":
+ self._handle_fail_run(conn, options)
+ elif action == "release-locks":
+ self._handle_release_locks(conn, options)
+
+ # -- targeting --------------------------------------------------------------
+
+ def _resolve_scope(self, options: dict[str, Any], *, allow_empty: bool) -> Scope:
+ team_id = options.get("team_id")
+ schema_id = options.get("schema_id")
+ source_id = options.get("source_id")
+ source_type = options.get("source_type")
+ run_uuid = options.get("run_uuid")
+
+ if run_uuid:
+ if any([team_id, schema_id, source_id, source_type]):
+ raise CommandError("--run-uuid targets one run directly; don't combine it with other targeting flags")
+ return Scope(run_uuid=run_uuid)
+
+ if (schema_id or source_id) and not team_id:
+ raise CommandError("--schema-id and --source-id require --team-id")
+
+ if team_id is None and source_type is None:
+ if not allow_empty:
+ raise CommandError(
+ "Provide targeting flags: --team-id (optionally with --schema-id/--source-id/--source-type), "
+ "--source-type alone, or --run-uuid"
+ )
+ return Scope()
+
+ if team_id is not None:
+ schema_ids = self._resolve_schema_ids(
+ team_id=team_id, schema_id=schema_id, source_id=source_id, source_type=source_type
+ )
+ return Scope(team_id=team_id, schema_ids=schema_ids)
+
+ return Scope(source_type=source_type)
+
+ def _resolve_schema_ids(
+ self, *, team_id: int, schema_id: str | None, source_id: str | None, source_type: str | None
+ ) -> list[str] | None:
+ """Resolve team-scoped targeting flags to queue schema_ids via the main DB. None = whole team."""
+ if schema_id:
+ if not ExternalDataSchema.objects.filter(team_id=team_id, id=schema_id).exists():
+ raise CommandError(f"No schema {schema_id!r} for team {team_id}")
+ return [schema_id]
+ if source_id:
+ ids = list(
+ ExternalDataSchema.objects.filter(team_id=team_id, source_id=source_id).values_list("id", flat=True)
+ )
+ if not ids:
+ raise CommandError(f"No schemas for source {source_id!r} in team {team_id}")
+ return [str(i) for i in ids]
+ if source_type:
+ ids = list(
+ ExternalDataSchema.objects.filter(team_id=team_id, source__source_type__iexact=source_type).values_list(
+ "id", flat=True
+ )
+ )
+ if not ids:
+ raise CommandError(f"No schemas with source type {source_type!r} in team {team_id}")
+ return [str(i) for i in ids]
+ return None
+
+ def _filter_runs_by_source_type(self, runs: list[ActiveRunRef], source_type: str) -> list[ActiveRunRef]:
+ """Post-filter queue runs for source-type-only targeting (queue-first, then one main-DB lookup)."""
+ source_ids = {r.source_id for r in runs if r.source_id}
+ if not source_ids:
+ return []
+ matching = {
+ str(pk)
+ for pk in ExternalDataSource.objects.filter(id__in=source_ids, source_type__iexact=source_type).values_list(
+ "id", flat=True
+ )
+ }
+ return [r for r in runs if r.source_id in matching]
+
+ def _running_v3_jobs(self, scope: Scope) -> list[ExternalDataJob]:
+ """Main-DB branch of "active": Running V3 jobs in scope (some may have nothing in the queue)."""
+ jobs = ExternalDataJob.objects.filter(
+ status=ExternalDataJob.Status.RUNNING,
+ pipeline_version=ExternalDataJob.PipelineVersion.V3,
+ )
+ if scope.team_id is not None:
+ jobs = jobs.filter(team_id=scope.team_id)
+ if scope.schema_ids is not None:
+ jobs = jobs.filter(schema_id__in=scope.schema_ids)
+ if scope.source_type is not None:
+ jobs = jobs.filter(pipeline__source_type__iexact=scope.source_type)
+ return list(jobs)
+
+ def _collect_fail_targets(self, conn: psycopg.Connection[Any], scope: Scope) -> list[FailTarget]:
+ runs = BatchQueue.get_active_runs(
+ conn,
+ team_id=scope.team_id,
+ schema_ids=scope.schema_ids,
+ run_uuid=scope.run_uuid,
+ only_pending=scope.run_uuid is None,
+ )
+ if scope.source_type:
+ runs = self._filter_runs_by_source_type(runs, scope.source_type)
+
+ targets = [
+ FailTarget(
+ run_uuid=r.run_uuid,
+ job_id=r.job_id,
+ team_id=r.team_id,
+ schema_id=r.schema_id,
+ source_id=r.source_id,
+ workflow_run_id=r.workflow_run_id,
+ pending_batches=r.pending_batches,
+ total_batches=r.total_batches,
+ )
+ for r in runs
+ ]
+
+ if scope.run_uuid:
+ if not targets:
+ raise CommandError(
+ f"Run {scope.run_uuid!r} has no batches inside the queue retention window "
+ f"({PARTITION_PRUNING_INTERVAL}) - nothing to fail. If its ExternalDataJob is stuck "
+ "in Running, target it via --team-id/--schema-id instead."
+ )
+ return targets
+
+ # Running jobs the queue knows nothing about (producer died before enqueueing,
+ # or the job-status write never landed after the batches went terminal).
+ known_job_ids = {t.job_id for t in targets}
+ for job in self._running_v3_jobs(scope):
+ if str(job.id) in known_job_ids:
+ continue
+ targets.append(
+ FailTarget(
+ run_uuid=None,
+ job_id=str(job.id),
+ team_id=job.team_id,
+ schema_id=str(job.schema_id) if job.schema_id else None,
+ source_id=str(job.pipeline_id) if job.pipeline_id else None,
+ workflow_run_id=job.workflow_run_id,
+ pending_batches=0,
+ total_batches=0,
+ )
+ )
+ return targets
+
+ # -- fail-run ---------------------------------------------------------------
+
+ def _handle_fail_run(self, conn: psycopg.Connection[Any], options: dict[str, Any]) -> None:
+ scope = self._resolve_scope(options, allow_empty=False)
+ reason: str = options["reason"]
+ live_run: bool = options["live_run"]
+ cancel_workflow: bool = options["cancel_workflow"]
+ force: bool = options["force"]
+
+ targets = self._collect_fail_targets(conn, scope)
+ if not targets:
+ self.stdout.write("No active runs match - nothing to fail.")
+ return
+
+ max_runs: int = options["max_runs"]
+ if len(targets) > max_runs:
+ raise CommandError(
+ f"{len(targets)} runs match, above the --max-runs cap of {max_runs}. "
+ "Narrow the targeting or raise --max-runs explicitly."
+ )
+
+ jobs_by_id = {str(j.id): j for j in ExternalDataJob.objects.filter(id__in=[t.job_id for t in targets])}
+
+ # Read-only lock/lease state so the dry-run preview is honest about what release will do.
+ leases_by_pair = {
+ (lease.team_id, lease.schema_id): lease
+ for lease in BatchQueue.get_leases(conn, schema_ids=sorted({t.schema_id for t in targets if t.schema_id}))
+ }
+
+ verb = "Would fail" if not live_run else "Failing"
+ self.stdout.write(f"{verb} {len(targets)} run(s):")
+ for t in targets:
+ job = jobs_by_id.get(t.job_id)
+ job_status = job.status if job else "<job not found>"
+ queue_note = (
+ f"pending_batches={t.pending_batches}/{t.total_batches}"
+ if t.run_uuid
+ else "no queue batches in retention window (job-only)"
+ )
+ 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} workflow_run_id={t.workflow_run_id or '-'}"
+ )
+ if t.schema_id:
+ notes = []
+ if t.workflow_run_id:
+ holder = get_v3_pipeline_lock_holder(t.team_id, t.schema_id)
+ if holder is None:
+ notes.append("redis lock unheld")
+ elif holder == t.workflow_run_id:
+ notes.append("redis lock held by this run (will release)")
+ else:
+ notes.append(f"redis lock held by a different token ({holder!r}) - will not release")
+ lease = leases_by_pair.get((t.team_id, t.schema_id))
+ if lease is not None:
+ if lease.is_live and not force:
+ notes.append("lease LIVE - will skip; a healthy pod may hold it (use --force to delete)")
+ else:
+ liveness = "LIVE (forced)" if lease.is_live else f"expired {self._age(lease.expires_at)} ago"
+ notes.append(f"lease {liveness} (will delete)")
+ if notes:
+ self.stdout.write(f" -> {'; '.join(notes)}")
+
+ if not live_run:
+ self.stdout.write(DRY_RUN_MESSAGE)
+ return
+
+ self._confirm(f"Fail {len(targets)} run(s)? Type 'fail' to continue: ", "fail", yes=options["yes"])
+
+ for t in targets:
+ self.stdout.write(f"run={t.run_uuid or '-'} job={t.job_id}:")
+ self._fail_target(conn, t, reason=reason, cancel_workflow=cancel_workflow, job=jobs_by_id.get(t.job_id))
+ logger.info(
+ "manage_warehouse_queue_fail_run",
+ run_uuid=t.run_uuid,
+ job_id=t.job_id,
+ team_id=t.team_id,
+ external_data_schema_id=t.schema_id,
+ reason=reason,
+ )
+
+ 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.
+ leases_to_delete: list[tuple[int, str]] = []
+ skipped_live = 0
+ for lease in BatchQueue.get_leases(conn, schema_ids=sorted({schema_id for _, schema_id in pair_set})):
+ if (lease.team_id, lease.schema_id) not in pair_set:
+ continue
+ if lease.is_live and not force:
+ skipped_live += 1
+ self.stdout.write(
+ self.style.WARNING(
+ f" lease team={lease.team_id} schema={lease.schema_id} is LIVE "
+ f"(expires {lease.expires_at.isoformat()}, owner {lease.owner_token}) - "
+ "skipped; a healthy pod may hold it. Use --force to release anyway."
+ )
+ )
+ continue
+ leases_to_delete.append((lease.team_id, lease.schema_id))
+ released = BatchQueue.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))
+
+ def _fail_target(
+ self,
+ conn: psycopg.Connection[Any],
+ target: FailTarget,
+ *,
+ reason: str,
+ cancel_workflow: bool,
+ job: ExternalDataJob | None,
+ ) -> None:
+ """Mirror the consumer's fail path; each step isolated so one failure doesn't abort the rest."""
+ if target.run_uuid:
+ try:
+ failed = BatchQueue.fail_run_sync(conn, run_uuid=target.run_uuid, reason=reason)
+ self.stdout.write(f" queue: marked {failed} pending batch(es) failed")
+ except Exception:
+ logger.exception("manage_warehouse_queue_fail_run_queue_write_failed", run_uuid=target.run_uuid)
+ self.stdout.write(self.style.ERROR(" queue: FAILED to write failed statuses (see logs)"))
+
+ try:
+ transitioned = mark_job_failed_if_not_terminal(job_id=target.job_id, team_id=target.team_id, error=reason)
+ self.stdout.write(" job: marked Failed" if transitioned else " job: already terminal - left unchanged")
+ except Exception:
+ logger.exception("manage_warehouse_queue_fail_run_job_update_failed", job_id=target.job_id)
+ self.stdout.write(self.style.ERROR(" job: FAILED to update status (see logs)"))
+
+ if target.workflow_run_id and target.schema_id:
+ released = release_v3_pipeline_lock(target.team_id, target.schema_id, token=target.workflow_run_id)
+ if released:
+ self.stdout.write(" redis lock: released")
+ else:
+ holder = get_v3_pipeline_lock_holder(target.team_id, target.schema_id)
+ if holder is None:
+ self.stdout.write(" redis lock: not held")
+ else:
+ self.stdout.write(
+ self.style.WARNING(
+ f" redis lock: held by a different token ({holder!r}) - a newer run may own it; "
+ "use release-locks if it is genuinely stale"
+ )
+ )
+
+ if cancel_workflow:
+ self._cancel_workflow(job)
+
+ def _cancel_workflow(self, job: ExternalDataJob | None) -> None:
+ # Deferred: pulls in the Temporal client stack, only needed with --cancel-workflow.
+ from temporalio.service import RPCError # noqa: PLC0415
+
+ from products.data_warehouse.backend.facade.api import cancel_external_data_workflow # noqa: PLC0415
+
+ if job is None or not job.workflow_id:
+ self.stdout.write(self.style.WARNING(" temporal: no workflow_id on the job - skipped"))
+ return
+ try:
+ cancel_external_data_workflow(job.workflow_id)
+ self.stdout.write(" temporal: cancellation requested")
+ except RPCError as e:
+ self.stdout.write(self.style.WARNING(f" temporal: cancellation failed ({e.message})"))
+ except Exception:
+ logger.exception("manage_warehouse_queue_temporal_cancel_failed", workflow_id=job.workflow_id)
+ self.stdout.write(self.style.ERROR(" temporal: cancellation failed (see logs)"))
+
+ # -- release-locks ----------------------------------------------------------
+
+ def _handle_release_locks(self, conn: psycopg.Connection[Any], options: dict[str, Any]) -> None:
+ if options["leases_only"] and options["redis_only"]:
+ raise CommandError("--leases-only and --redis-only are mutually exclusive")
+ scope = self._resolve_scope(options, allow_empty=False)
+ if scope.run_uuid:
+ raise CommandError("release-locks targets (team, schema) pairs; --run-uuid is not supported here")
+
+ pairs = self._resolve_lock_pairs(conn, scope)
+ if not pairs:
+ self.stdout.write("No (team, schema) pairs in scope - nothing to release.")
+ return
+
+ live_run: bool = options["live_run"]
+ force: bool = options["force"]
+ check_leases = not options["redis_only"]
+ check_redis = not options["leases_only"]
+
+ # workflow_run_ids of Running jobs, per schema: a redis lock held by one of
+ # these tokens belongs to live work and needs --force.
+ running_tokens: dict[str, set[str]] = {}
+ for job in self._running_v3_jobs(scope):
+ if job.schema_id and job.workflow_run_id:
+ running_tokens.setdefault(str(job.schema_id), set()).add(job.workflow_run_id)
+
+ leases_to_delete: list[tuple[int, str]] = []
+ if check_leases:
+ leases = BatchQueue.get_leases(conn, schema_ids=[schema_id for _, schema_id in pairs])
+ for lease in leases:
+ if lease.is_live and not force:
+ self.stdout.write(
+ self.style.WARNING(
+ f" lease team={lease.team_id} schema={lease.schema_id} is LIVE "
+ f"(expires {lease.expires_at.isoformat()}, owner {lease.owner_token}) - "
+ "skipped; a healthy pod may hold it. Use --force to release anyway."
+ )
+ )
+ continue
+ liveness = "LIVE (forced)" if lease.is_live else f"expired {self._age(lease.expires_at)} ago"
+ self.stdout.write(f" lease team={lease.team_id} schema={lease.schema_id}: {liveness} - release")
+ leases_to_delete.append((lease.team_id, lease.schema_id))
+
+ redis_to_release: list[tuple[int, str, str]] = []
+ if check_redis:
+ for team_id, schema_id in pairs:
+ holder = get_v3_pipeline_lock_holder(team_id, schema_id)
+ if holder is None:
+ continue
+ if holder in running_tokens.get(schema_id, set()) and not force:
+ self.stdout.write(
+ self.style.WARNING(
+ f" redis lock team={team_id} schema={schema_id} is held by a Running job "
+ f"({holder!r}) - skipped. Use --force to release anyway."
+ )
+ )
+ continue
+ self.stdout.write(f" redis lock team={team_id} schema={schema_id}: held by {holder!r} - release")
+ redis_to_release.append((team_id, schema_id, holder))
+
+ if not leases_to_delete and not redis_to_release:
+ self.stdout.write("Nothing releasable in scope.")
+ return
+
+ if not live_run:
+ self.stdout.write(DRY_RUN_MESSAGE)
+ return
+
+ self._confirm(
+ f"Release {len(leases_to_delete)} lease(s) and {len(redis_to_release)} redis lock(s)? "
+ "Type 'release' to continue: ",
+ "release",
+ yes=options["yes"],
+ )
+
+ released_leases = BatchQueue.force_release_leases(conn, pairs=leases_to_delete)
+ released_locks = 0
+ for team_id, schema_id, holder in redis_to_release:
+ # Token-compared delete: if a new run grabbed the lock since we read the
+ # holder, the release is a no-op rather than breaking the new run.
+ if release_v3_pipeline_lock(team_id, schema_id, token=holder):
+ released_locks += 1
+ else:
+ self.stdout.write(
+ self.style.WARNING(f" redis lock team={team_id} schema={schema_id}: holder changed - skipped")
+ )
+ logger.info(
+ "manage_warehouse_queue_release_locks",
+ released_leases=released_leases,
+ released_locks=released_locks,
+ team_id=scope.team_id,
+ source_type=scope.source_type,
+ )
+ self.stdout.write(
+ self.style.SUCCESS(f"Released {released_leases} group lease(s) and {released_locks} redis lock(s).")
+ )
+
+ def _resolve_lock_pairs(self, conn: psycopg.Connection[Any], scope: Scope) -> list[tuple[int, str]]:
+ """(team_id, schema_id) pairs to check for stuck coordination state."""
+ if scope.team_id is not None:
+ schema_ids = scope.schema_ids
+ if schema_ids is None:
+ schema_ids = [
+ str(i)
+ for i in ExternalDataSchema.objects.filter(team_id=scope.team_id, deleted=False).values_list(
+ "id", flat=True
+ )
+ ]
+ return [(scope.team_id, schema_id) for schema_id in schema_ids]
+
+ # source-type only: bound the sweep to pairs with actual queue presence
+ # (leases or active runs). Fully idle schemas' redis locks need --team-id scoping.
+ runs = self._filter_runs_by_source_type(BatchQueue.get_active_runs(conn), scope.source_type or "")
+ pairs = {(r.team_id, r.schema_id) for r in runs}
+ lease_schema_ids = {lease.schema_id for lease in BatchQueue.get_leases(conn)}
+ if lease_schema_ids:
+ matching = {
+ str(schema_pk): team_pk
+ for schema_pk, team_pk in ExternalDataSchema.objects.filter(
+ id__in=lease_schema_ids, source__source_type__iexact=scope.source_type or ""
+ ).values_list("id", "team_id")
+ }
+ pairs.update((team_pk, schema_id) for schema_id, team_pk in matching.items())
+ self.stdout.write(
+ "Note: with --source-type alone, only schemas with queue activity (batches or leases) are "
+ "checked - scope with --team-id to sweep idle schemas' redis locks."
+ )
+ return sorted(pairs)
+
+ # -- status -----------------------------------------------------------------
+
+ def _handle_status(self, conn: psycopg.Connection[Any], options: dict[str, Any]) -> None:
+ scope = self._resolve_scope(options, allow_empty=True)
+
+ runs = BatchQueue.get_active_runs(
+ conn,
+ team_id=scope.team_id,
+ schema_ids=scope.schema_ids,
+ run_uuid=scope.run_uuid,
+ only_pending=scope.run_uuid is None,
+ )
+ if scope.source_type:
+ runs = self._filter_runs_by_source_type(runs, scope.source_type)
+
+ # For source-type-only and run-uuid scoping, narrow the remaining sections
+ # to the schemas the filtered runs actually touch (the summary query can't
+ # join source_type, and a run-uuid lookup must not report fleet-wide state).
+ summary_schema_ids = scope.schema_ids
+ if summary_schema_ids is None and (scope.source_type or scope.run_uuid):
+ summary_schema_ids = sorted({r.schema_id for r in runs})
+
+ self.stdout.write(self.style.MIGRATE_HEADING("Queue summary (within retention window)"))
+ summary = BatchQueue.get_state_summary(conn, team_id=scope.team_id, schema_ids=summary_schema_ids)
+ if not summary:
+ self.stdout.write(" no batches in scope")
+ for row in summary:
+ line = f" {row['state']}: {row['batch_count']}"
+ if row["state"] == "unclaimed" and row["oldest_created_at"] is not None:
+ line += f" (oldest {self._age(row['oldest_created_at'])} old)"
+ self.stdout.write(line)
+
+ self.stdout.write(self.style.MIGRATE_HEADING(f"Active runs ({len(runs)})"))
+ jobs_by_id = {
+ str(j.id): j for j in ExternalDataJob.objects.filter(id__in=[r.job_id for r in runs[:PRINT_LIMIT]])
+ }
+ for r in runs[:PRINT_LIMIT]:
+ job = jobs_by_id.get(r.job_id)
+ job_status = job.status if job else "<job not found>"
+ activity = self._age(r.latest_activity_at) + " ago" if r.latest_activity_at else "-"
+ self.stdout.write(
+ f" run={r.run_uuid} job={r.job_id} (status={job_status}) team={r.team_id} schema={r.schema_id} "
+ f"pending={r.pending_batches}/{r.total_batches} last_activity={activity} "
+ f"workflow_run_id={r.workflow_run_id or '-'}"
+ )
+ if len(runs) > PRINT_LIMIT:
+ self.stdout.write(f" ... and {len(runs) - PRINT_LIMIT} more")
+
+ known_job_ids = {r.job_id for r in runs}
+ # A run-uuid scope carries no team/schema constraint, so _running_v3_jobs
+ # would return every Running V3 job in the fleet — skip the section.
+ orphan_jobs = (
+ [] if scope.run_uuid else [j for j in self._running_v3_jobs(scope) if str(j.id) not in known_job_ids]
+ )
+ if orphan_jobs:
+ self.stdout.write(
+ self.style.MIGRATE_HEADING(
+ f"Running V3 jobs with nothing pending in the queue ({len(orphan_jobs)}) - fail-run candidates"
+ )
+ )
+ for job in orphan_jobs[:PRINT_LIMIT]:
+ self.stdout.write(
+ f" job={job.id} team={job.team_id} schema={job.schema_id or '-'} "
+ f"workflow_run_id={job.workflow_run_id or '-'}"
+ )
+
+ self.stdout.write(self.style.MIGRATE_HEADING("Group leases"))
+ leases = BatchQueue.get_leases(conn, team_id=scope.team_id, schema_ids=summary_schema_ids)
+ if not leases:
+ self.stdout.write(" none in scope")
+ for lease in leases[:PRINT_LIMIT]:
+ liveness = "LIVE" if lease.is_live else f"EXPIRED {self._age(lease.expires_at)} ago"
+ self.stdout.write(
+ f" team={lease.team_id} schema={lease.schema_id} owner={lease.owner_token} {liveness} "
+ f"(expires {lease.expires_at.isoformat()})"
+ )
+
+ self.stdout.write(self.style.MIGRATE_HEADING("Redis pipeline locks"))
+ workflow_tokens: dict[tuple[int, str], set[str]] = {}
+ for r in runs:
+ if r.workflow_run_id:
+ workflow_tokens.setdefault((r.team_id, r.schema_id), set()).add(r.workflow_run_id)
+ for job in orphan_jobs:
+ if job.schema_id and job.workflow_run_id:
+ workflow_tokens.setdefault((job.team_id, str(job.schema_id)), set()).add(job.workflow_run_id)
+ lock_pairs = sorted(
+ {(r.team_id, r.schema_id) for r in runs}
+ | {(lease.team_id, lease.schema_id) for lease in leases}
+ | {(job.team_id, str(job.schema_id)) for job in orphan_jobs if job.schema_id}
+ )[:PRINT_LIMIT]
+ held_any = False
+ for team_id, schema_id in lock_pairs:
+ holder = get_v3_pipeline_lock_holder(team_id, schema_id)
+ if holder is None:
+ continue
+ held_any = True
+ known = holder in workflow_tokens.get((team_id, schema_id), set())
+ note = "" if known else " - token matches no known active workflow_run_id (stale-lock smell)"
+ self.stdout.write(f" team={team_id} schema={schema_id} holder={holder!r}{note}")
+ if not held_any:
+ self.stdout.write(" none held for in-scope pairs")
+
+ grace: int = options["stale_grace_seconds"]
+ stale = BatchQueue.get_stale_executing_sync(
+ conn, grace_seconds=grace, team_id=scope.team_id, schema_ids=summary_schema_ids
+ )
+ self.stdout.write(
+ self.style.MIGRATE_HEADING(f"Stale executing batches (>{grace}s, no live lease): {len(stale)}")
+ )
+ for batch in stale[:PRINT_LIMIT]:
+ self.stdout.write(
+ f" batch={batch.id} run={batch.run_uuid} team={batch.team_id} schema={batch.schema_id} "
+ f"batch_index={batch.batch_index}"
+ )
+
+ # -- shared -----------------------------------------------------------------
+
+ def _confirm(self, prompt: str, keyword: str, *, yes: bool) -> None:
+ if yes:
+ return
+ if not sys.stdin.isatty():
+ raise CommandError("Refusing to apply changes non-interactively without --yes")
+ if input(prompt).strip() != keyword:
+ raise CommandError("Aborted.")
+
+ @staticmethod
+ def _age(moment: datetime) -> str:
+ seconds = abs((datetime.now(UTC) - moment).total_seconds())
+ if seconds < 120:
+ return f"{int(seconds)}s"
+ if seconds < 2 * 3600:
+ return f"{int(seconds // 60)}m"
+ return f"{seconds / 3600:.1f}h"
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/consumer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/consumer.py
index 58cbc38c2b05..868f8de4e759 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/consumer.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/consumer.py
@@ -223,7 +223,7 @@ class DeltaBatchConsumerAdapter:
)
for ref in refs:
try:
- reconciled = await sync_to_async(_mark_job_failed_if_not_terminal)(
+ reconciled = await sync_to_async(mark_job_failed_if_not_terminal)(
job_id=ref.job_id,
team_id=ref.team_id,
error=ref.reason or "run failed (reconciled from queue)",
@@ -330,8 +330,12 @@ def _update_job_status_to_failed(*, job_id: str, team_id: int, error: str) -> No
)
-def _mark_job_failed_if_not_terminal(*, job_id: str, team_id: int, error: str) -> bool:
- """Mark a non-terminal ExternalDataJob Failed; returns True if it transitioned (terminal jobs are a no-op)."""
+def mark_job_failed_if_not_terminal(*, job_id: str, team_id: int, error: str) -> bool:
+ """Mark a non-terminal ExternalDataJob Failed; returns True if it transitioned (terminal jobs are a no-op).
+
+ Public seam shared by the reconcile sweep and the manage_warehouse_queue ops
+ command, so both fail paths agree on the terminal-status check.
+ """
from products.warehouse_sources.backend.models.external_data_job import ExternalDataJob
close_old_connections()
@@ -357,4 +361,5 @@ __all__ = [
"RECOVERY_INTERVAL_SECONDS",
"RETRY_BACKOFF_BASE_SECONDS",
"_group_by_key",
+ "mark_job_failed_if_not_terminal",
]
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/jobs_db.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/jobs_db.py
index f8234604072e..9d82c6046a75 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/jobs_db.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/jobs_db.py
@@ -90,6 +90,43 @@ def latest_status_lateral(batch_alias: str, status_alias: str, *, join: str = "L
"""
+def pending_batch_predicate(status_alias: str) -> str:
+ """A batch is pending (still actionable) when it has no status row yet or its latest state is non-terminal."""
+ return f"({status_alias}.batch_id IS NULL OR {status_alias}.job_state IN ('waiting', 'waiting_retry', 'executing'))"
+
+
+# Shared between the async consumer path and the sync ops command so both agree
+# on what counts as a pending (fail-able) batch.
+FAIL_RUN_SQL = f"""
+ INSERT INTO {STATUS_TABLE} (batch_id, job_state, attempt, exec_time, error_response, created_at)
+ SELECT b.id, 'failed', 0, now(), %(error_response)s, now()
+ FROM {BATCH_TABLE} b
+ {latest_status_lateral("b", "s")}
+ WHERE
+ b.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'
+ AND b.run_uuid = %(run_uuid)s
+ AND {pending_batch_predicate("s")}
+"""
+
+
+def _stale_executing_sql(scope_sql: str = "") -> str:
+ """Shared body of the stale-executing sweep (async consumer and its sync ops twin)."""
+ return f"""
+ SELECT
+ {pending_batch_select_columns("s")}
+ FROM {BATCH_TABLE} b
+ {latest_status_lateral("b", "s", join="INNER")}
+ LEFT JOIN {LEASE_TABLE} l ON l.team_id = b.team_id AND l.schema_id = b.schema_id
+ WHERE
+ b.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'
+ AND s.job_state = 'executing'
+ AND s.created_at <= now() - make_interval(secs => %(grace)s)
+ AND (l.team_id IS NULL OR l.expires_at <= now())
+ {scope_sql}
+ ORDER BY b.created_at ASC, b.batch_index ASC
+ """
+
+
# Retained for the duckgres sink, which still coordinates via session advisory
# locks (see duckgres/jobs_db.py). The delta queue now uses leases instead.
async def unlock_advisory_locks(
@@ -188,6 +225,34 @@ class RunActivitySummary:
is_stale: bool
+@dataclass(frozen=True, slots=True)
+class ActiveRunRef:
+ """Per-run aggregate of queue batches, used by the ops management command."""
+
+ run_uuid: str
+ job_id: str
+ team_id: int
+ schema_id: str
+ source_id: str
+ workflow_run_id: str | None
+ pending_batches: int
+ total_batches: int
+ latest_activity_at: datetime | None
+
+
+@dataclass(frozen=True, slots=True)
+class GroupLease:
+ """A ``sourcegrouplease`` row plus computed liveness, for ops inspection."""
+
+ team_id: int
+ schema_id: str
+ owner_token: str
+ acquired_at: datetime
+ updated_at: datetime
+ expires_at: datetime
+ is_live: bool
+
+
class BatchQueue:
"""
Async interface to the Postgres batch queue tables. Each method runs
@@ -512,22 +577,7 @@ class BatchQueue:
this threshold before the batch is considered orphaned.
"""
async with conn.cursor(row_factory=dict_row) as cur:
- await cur.execute(
- f"""
- SELECT
- {pending_batch_select_columns("s")}
- FROM {BATCH_TABLE} b
- {latest_status_lateral("b", "s", join="INNER")}
- LEFT JOIN {LEASE_TABLE} l ON l.team_id = b.team_id AND l.schema_id = b.schema_id
- WHERE
- b.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'
- AND s.job_state = 'executing'
- AND s.created_at <= now() - make_interval(secs => %(grace)s)
- AND (l.team_id IS NULL OR l.expires_at <= now())
- ORDER BY b.created_at ASC, b.batch_index ASC
- """,
- {"grace": grace_seconds},
- )
+ await cur.execute(_stale_executing_sql(), {"grace": grace_seconds})
rows = await cur.fetchall()
return [PendingBatch(**row) for row in rows]
@@ -541,16 +591,24 @@ class BatchQueue:
) -> int:
"""Mark every pending batch in a run as failed. Returns the count of batches failed."""
cursor = await conn.execute(
- f"""
- INSERT INTO {STATUS_TABLE} (batch_id, job_state, attempt, exec_time, error_response, created_at)
- SELECT b.id, 'failed', 0, now(), %(error_response)s, now()
- FROM {BATCH_TABLE} b
- {latest_status_lateral("b", "s")}
- WHERE
- b.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'
- AND b.run_uuid = %(run_uuid)s
- AND (s.batch_id IS NULL OR s.job_state IN ('waiting', 'waiting_retry', 'executing'))
- """,
+ FAIL_RUN_SQL,
+ {
+ "run_uuid": run_uuid,
+ "error_response": json.dumps({"error": reason}),
+ },
+ )
+ return cursor.rowcount or 0
+
+ @staticmethod
+ def fail_run_sync(
+ conn: psycopg.Connection[Any],
+ *,
+ run_uuid: str,
+ reason: str,
+ ) -> int:
+ """Sync twin of ``fail_run`` for the ops management command."""
+ cursor = conn.execute(
+ FAIL_RUN_SQL,
{
"run_uuid": run_uuid,
"error_response": json.dumps({"error": reason}),
@@ -784,3 +842,173 @@ class BatchQueue:
)
row = cur.fetchone()
return int(row["batch_count"]) if row else 0
+
+ # -- ops / management command helpers (sync) --------------------------------
+
+ @staticmethod
+ def get_active_runs(
+ conn: psycopg.Connection[Any],
+ *,
+ team_id: int | None = None,
+ schema_ids: list[str] | None = None,
+ run_uuid: str | None = None,
+ only_pending: bool = True,
+ ) -> list[ActiveRunRef]:
+ """Aggregate queue batches per run within the targeting scope.
+
+ ``only_pending=True`` keeps only runs with at least one non-terminal
+ batch (no status row yet, or waiting/waiting_retry/executing) — the runs
+ an operator can still act on. ``only_pending=False`` is for direct
+ ``run_uuid`` lookups where a fully-terminal run should still be visible.
+ """
+ scope_sql, params = _scope_filters(team_id=team_id, schema_ids=schema_ids, run_uuid=run_uuid)
+ having = f"HAVING COUNT(*) FILTER (WHERE {pending_batch_predicate('s')}) > 0"
+ with conn.cursor(row_factory=dict_row) as cur:
+ cur.execute(
+ f"""
+ SELECT
+ b.run_uuid,
+ b.team_id,
+ b.schema_id,
+ MAX(b.job_id) AS job_id,
+ MAX(b.source_id) AS source_id,
+ MAX(b.metadata->>'workflow_run_id') AS workflow_run_id,
+ COUNT(*) FILTER (
+ WHERE {pending_batch_predicate("s")}
+ ) AS pending_batches,
+ COUNT(*) AS total_batches,
+ GREATEST(MAX(s.created_at), MAX(b.created_at)) AS latest_activity_at
+ FROM {BATCH_TABLE} b
+ {latest_status_lateral("b", "s")}
+ WHERE b.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'
+ {scope_sql}
+ GROUP BY b.run_uuid, b.team_id, b.schema_id
+ {having if only_pending else ""}
+ ORDER BY latest_activity_at ASC
+ """,
+ params,
+ )
+ rows = cur.fetchall()
+ return [ActiveRunRef(**row) for row in rows]
+
+ @staticmethod
+ def get_state_summary(
+ conn: psycopg.Connection[Any],
+ *,
+ team_id: int | None = None,
+ schema_ids: list[str] | None = None,
+ ) -> list[dict[str, Any]]:
+ """Batch counts by latest state within the scope; ``state='unclaimed'`` means no status row yet.
+
+ Each row carries the oldest ``created_at`` in its state so the caller
+ can derive freshness signals (e.g. age of the oldest unclaimed batch).
+ """
+ scope_sql, params = _scope_filters(team_id=team_id, schema_ids=schema_ids)
+ with conn.cursor(row_factory=dict_row) as cur:
+ cur.execute(
+ f"""
+ SELECT
+ COALESCE(s.job_state, 'unclaimed') AS state,
+ COUNT(*) AS batch_count,
+ MIN(b.created_at) AS oldest_created_at
+ FROM {BATCH_TABLE} b
+ {latest_status_lateral("b", "s")}
+ WHERE b.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'
+ {scope_sql}
+ GROUP BY 1
+ ORDER BY 1
+ """,
+ params,
+ )
+ return cur.fetchall()
+
+ @staticmethod
+ def get_leases(
+ conn: psycopg.Connection[Any],
+ *,
+ team_id: int | None = None,
+ schema_ids: list[str] | None = None,
+ ) -> list[GroupLease]:
+ """Group leases within the scope, with computed liveness."""
+ scope_sql, params = _scope_filters(team_id=team_id, schema_ids=schema_ids, alias="l")
+ with conn.cursor(row_factory=dict_row) as cur:
+ cur.execute(
+ f"""
+ SELECT team_id, schema_id, owner_token, acquired_at, updated_at, expires_at,
+ expires_at > now() AS is_live
+ FROM {LEASE_TABLE} l
+ WHERE true
+ {scope_sql}
+ ORDER BY team_id, schema_id
+ """,
+ params,
+ )
+ rows = cur.fetchall()
+ return [GroupLease(**row) for row in rows]
+
+ @staticmethod
+ def force_release_leases(
+ conn: psycopg.Connection[Any],
+ *,
+ pairs: list[tuple[int, str]],
+ ) -> int:
+ """Delete group leases for ``pairs`` regardless of owner. Ops override only.
+
+ Unlike ``unlock_for_batches`` there is deliberately no ``owner_token``
+ predicate: the operator has decided the holder is dead. Deleting a live
+ lease makes its holder's next ``renew_lease`` return False and abort the
+ group, so callers must gate live leases behind explicit confirmation.
+ """
+ if not pairs:
+ return 0
+ cursor = conn.execute(
+ f"""
+ DELETE FROM {LEASE_TABLE}
+ WHERE (team_id, schema_id) IN (
+ SELECT * FROM unnest(%(team_ids)s::bigint[], %(schema_ids)s::varchar[])
+ )
+ """,
+ {
+ "team_ids": [team_id for team_id, _ in pairs],
+ "schema_ids": [schema_id for _, schema_id in pairs],
+ },
+ )
+ return cursor.rowcount or 0
+
+ @staticmethod
+ def get_stale_executing_sync(
+ conn: psycopg.Connection[Any],
+ *,
+ grace_seconds: int = 0,
+ team_id: int | None = None,
+ schema_ids: list[str] | None = None,
+ ) -> list[PendingBatch]:
+ """Sync, scope-filtered twin of ``get_stale_executing`` for ops inspection."""
+ scope_sql, params = _scope_filters(team_id=team_id, schema_ids=schema_ids)
+ params["grace"] = grace_seconds
+ with conn.cursor(row_factory=dict_row) as cur:
+ cur.execute(_stale_executing_sql(scope_sql), params)
+ rows = cur.fetchall()
+ return [PendingBatch(**row) for row in rows]
+
+
+def _scope_filters(
+ *,
+ team_id: int | None = None,
+ schema_ids: list[str] | None = None,
+ run_uuid: str | None = None,
+ alias: str = "b",
+) -> tuple[str, dict[str, Any]]:
+ """Build optional AND-clauses for the ops helpers' targeting scope."""
+ clauses: list[str] = []
+ params: dict[str, Any] = {}
+ if team_id is not None:
+ clauses.append(f"AND {alias}.team_id = %(scope_team_id)s")
+ params["scope_team_id"] = team_id
+ if schema_ids is not None:
+ clauses.append(f"AND {alias}.schema_id = ANY(%(scope_schema_ids)s)")
+ params["scope_schema_ids"] = schema_ids
+ if run_uuid is not None:
+ clauses.append(f"AND {alias}.run_uuid = %(scope_run_uuid)s")
+ params["scope_run_uuid"] = run_uuid
+ return "\n".join(clauses), params
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py
index f1cf1e8c0c26..ce7afea6f75d 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/postgres_queue/test_consumer.py
@@ -618,7 +618,7 @@ class TestReconcileFailedRuns:
return_value=[ref],
),
patch(
- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer._mark_job_failed_if_not_terminal",
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.mark_job_failed_if_not_terminal",
return_value=True,
) as mock_mark,
patch(
@@ -642,7 +642,7 @@ class TestReconcileFailedRuns:
return_value=[ref],
),
patch(
- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer._mark_job_failed_if_not_terminal",
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.mark_job_failed_if_not_terminal",
return_value=False,
) as mock_mark,
patch(
@@ -667,7 +667,7 @@ class TestReconcileFailedRuns:
return_value=[ref_a, ref_b],
),
patch(
- "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer._mark_job_failed_if_not_terminal",
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.mark_job_failed_if_not_terminal",
side_effect=[Exception("db down"), True],
) as mock_mark,
patch(
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
new file mode 100644
index 000000000000..19987a73d07b
--- /dev/null
+++ b/products/warehouse_sources/backend/tests/management/test_manage_warehouse_queue.py
@@ -0,0 +1,343 @@
+import json
+from collections.abc import Generator
+from contextlib import contextmanager
+from io import StringIO
+from typing import Any
+from uuid import uuid4
+
+import pytest
+from unittest.mock import patch
+
+from django.core.management import call_command
+from django.core.management.base import CommandError
+
+import psycopg
+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.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.temporal.data_imports.pipelines.pipeline_v3 import sync_lock
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import (
+ BATCH_TABLE,
+ LEASE_TABLE,
+ STATUS_TABLE,
+)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.test_jobs_db import (
+ _BATCH_DEFAULTS,
+ _ensure_tables,
+ _get_test_database_url,
+ _truncate_tables,
+)
+
+pytestmark = [pytest.mark.django_db]
+
+COMMAND_MODULE = "products.warehouse_sources.backend.management.commands.manage_warehouse_queue"
+
+
[email protected](autouse=True)
+def _keep_test_connection():
+ # The reused consumer fail path calls close_old_connections(), which closes the
+ # pytest-django test connection out from under the test transaction.
+ with patch(
+ "products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.consumer.close_old_connections"
+ ):
+ yield
+
+
+def organization():
+ return create_organization("test org")
+
+
+def team(organization):
+ return create_team(organization=organization)
+
+
+def team_2(organization):
+ return create_team(organization=organization)
+
+
+def queue_conn() -> Generator[psycopg.Connection[Any]]:
+ url = _get_test_database_url()
+ with psycopg.connect(url, autocommit=True) as conn:
+ _ensure_tables(conn)
+ _truncate_tables(conn)
+ with patch(f"{COMMAND_MODULE}.WAREHOUSE_SOURCES_DATABASE_URL", url):
+ yield conn
+
+
+def fake_redis() -> Generator[fakeredis.FakeRedis]:
+ client = fakeredis.FakeRedis()
+
+ @contextmanager
+ def _fake_client():
+ yield client
+
+ with patch.object(sync_lock, "_get_redis_client", _fake_client):
+ yield client
+
+
+def _create_pipeline(
+ team, source_type: str = "Stripe"
+) -> tuple[ExternalDataSource, ExternalDataSchema, ExternalDataJob]:
+ source = ExternalDataSource.objects.create(team=team, source_type=source_type, job_inputs={})
+ schema = ExternalDataSchema.objects.create(
+ name="test_table",
+ team=team,
+ source=source,
+ sync_type=ExternalDataSchema.SyncType.FULL_REFRESH,
+ status=ExternalDataSchema.Status.RUNNING,
+ )
+ job = ExternalDataJob.objects.create(
+ team=team,
+ pipeline=source,
+ schema=schema,
+ status=ExternalDataJob.Status.RUNNING,
+ pipeline_version=ExternalDataJob.PipelineVersion.V3,
+ workflow_id=f"workflow-{schema.id}",
+ workflow_run_id=str(uuid4()),
+ )
+ return source, schema, job
+
+
+def _insert_batch(conn: psycopg.Connection[Any], **overrides: Any) -> str:
+ params = {**_BATCH_DEFAULTS, **overrides}
+ params["metadata"] = json.dumps(params["metadata"])
+ row = conn.execute(
+ f"""
+ INSERT INTO {BATCH_TABLE} (
+ id, team_id, schema_id, source_id, job_id, run_uuid, batch_index, s3_path,
+ row_count, byte_size, is_final_batch, total_batches, total_rows, sync_type,
+ cumulative_row_count, resource_name, is_resume, is_first_ever_sync, metadata, created_at
+ ) VALUES (
+ gen_random_uuid(), %(team_id)s, %(schema_id)s, %(source_id)s, %(job_id)s, %(run_uuid)s,
+ %(batch_index)s, %(s3_path)s, %(row_count)s, %(byte_size)s, %(is_final_batch)s,
+ %(total_batches)s, %(total_rows)s, %(sync_type)s, %(cumulative_row_count)s,
+ %(resource_name)s, %(is_resume)s, %(is_first_ever_sync)s, %(metadata)s, now()
+ ) RETURNING id
+ """,
+ params,
+ ).fetchone()
+ assert row is not None
+ return str(row[0])
+
+
+def _set_status(conn: psycopg.Connection[Any], batch_id: str, state: str) -> None:
+ conn.execute(
+ f"INSERT INTO {STATUS_TABLE} (batch_id, job_state, attempt, exec_time, created_at) "
+ "VALUES (%s, %s, 0, now(), now())",
+ (batch_id, state),
+ )
+
+
+def _insert_lease(conn: psycopg.Connection[Any], *, team_id: int, schema_id: str, live: bool) -> None:
+ interval = "'5 minutes'" if live else "'-5 minutes'"
+ conn.execute(
+ f"INSERT INTO {LEASE_TABLE} (team_id, schema_id, owner_token, expires_at, acquired_at, updated_at) "
+ f"VALUES (%s, %s, %s, now() + interval {interval}, now(), now())",
+ (team_id, schema_id, str(uuid4())),
+ )
+
+
+def _lease_count(conn: psycopg.Connection[Any], schema_id: str) -> int:
+ row = conn.execute(f"SELECT COUNT(*) FROM {LEASE_TABLE} WHERE schema_id = %s", (schema_id,)).fetchone()
+ assert row is not None
+ return int(row[0])
+
+
+def _failed_status_counts_by_run(conn: psycopg.Connection[Any]) -> dict[str, int]:
+ rows = conn.execute(
+ f"""
+ SELECT b.run_uuid, COUNT(*)
+ FROM {STATUS_TABLE} s JOIN {BATCH_TABLE} b ON b.id = s.batch_id
+ WHERE s.job_state = 'failed'
+ GROUP BY b.run_uuid
+ """
+ ).fetchall()
+ return {run_uuid: int(n) for run_uuid, n in rows}
+
+
+def _seed_active_run(
+ conn: psycopg.Connection[Any],
+ *,
+ team,
+ schema: ExternalDataSchema,
+ job: ExternalDataJob,
+ run_uuid: str,
+) -> dict[str, str]:
+ """One succeeded batch and two pending ones (unclaimed + executing), like a mid-load run."""
+ common = {
+ "team_id": team.pk,
+ "schema_id": str(schema.id),
+ "source_id": str(schema.source_id),
+ "job_id": str(job.id),
+ "run_uuid": run_uuid,
+ "metadata": {"workflow_run_id": job.workflow_run_id},
+ }
+ succeeded = _insert_batch(conn, **common, batch_index=0)
+ _set_status(conn, succeeded, "succeeded")
+ executing = _insert_batch(conn, **common, batch_index=1)
+ _set_status(conn, executing, "executing")
+ unclaimed = _insert_batch(conn, **common, batch_index=2)
+ return {"succeeded": succeeded, "executing": executing, "unclaimed": unclaimed}
+
+
+def _call(*args: str) -> str:
+ out = StringIO()
+ call_command("manage_warehouse_queue", *args, stdout=out)
+ return out.getvalue()
+
+
+class TestFailRun:
+ def test_live_run_fails_pending_batches_job_lease_and_redis_lock(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)
+ _insert_lease(queue_conn, team_id=team.pk, schema_id=str(schema.id), live=False)
+ assert job.workflow_run_id is not None
+ assert sync_lock.acquire_v3_pipeline_lock(team.pk, str(schema.id), job.workflow_run_id)
+
+ out = _call("fail-run", "--team-id", str(team.pk), "--schema-id", str(schema.id), "--live-run", "--yes")
+
+ # only the executing + unclaimed batches get a failed status, not the succeeded one
+ assert _failed_status_counts_by_run(queue_conn) == {run_uuid: 2}
+ job.refresh_from_db()
+ assert job.status == ExternalDataJob.Status.FAILED
+ assert _lease_count(queue_conn, str(schema.id)) == 0
+ assert sync_lock.get_v3_pipeline_lock_holder(team.pk, str(schema.id)) is None
+ assert "marked 2 pending batch(es) failed" in out
+
+ def test_dry_run_mutates_nothing(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)
+ _insert_lease(queue_conn, team_id=team.pk, schema_id=str(schema.id), live=False)
+ assert job.workflow_run_id is not None
+ assert sync_lock.acquire_v3_pipeline_lock(team.pk, str(schema.id), job.workflow_run_id)
+
+ out = _call("fail-run", "--team-id", str(team.pk), "--schema-id", str(schema.id))
+
+ assert "Dry run" in out
+ assert _failed_status_counts_by_run(queue_conn) == {}
+ job.refresh_from_db()
+ assert job.status == ExternalDataJob.Status.RUNNING
+ assert _lease_count(queue_conn, str(schema.id)) == 1
+ assert sync_lock.get_v3_pipeline_lock_holder(team.pk, str(schema.id)) == job.workflow_run_id
+
+ def test_source_type_only_touches_only_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)
+ _seed_active_run(queue_conn, team=team_2, schema=pg_schema, job=pg_job, run_uuid=pg_run)
+
+ _call("fail-run", "--source-type", "stripe", "--live-run", "--yes")
+
+ assert _failed_status_counts_by_run(queue_conn) == {stripe_run: 2}
+ stripe_job.refresh_from_db()
+ pg_job.refresh_from_db()
+ assert stripe_job.status == ExternalDataJob.Status.FAILED
+ assert pg_job.status == ExternalDataJob.Status.RUNNING
+
+ 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()))
+
+ with pytest.raises(CommandError, match="--max-runs"):
+ _call("fail-run", "--team-id", str(team.pk), "--max-runs", "1", "--live-run", "--yes")
+
+ assert _failed_status_counts_by_run(queue_conn) == {}
+
+ @pytest.mark.parametrize("force", [False, True], ids=["without_force", "with_force"])
+ def test_live_lease_deleted_only_with_force(self, force, 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()))
+ _insert_lease(queue_conn, team_id=team.pk, schema_id=str(schema.id), live=True)
+
+ args = ["fail-run", "--team-id", str(team.pk), "--schema-id", str(schema.id), "--live-run", "--yes"]
+ if force:
+ args.append("--force")
+ out = _call(*args)
+
+ job.refresh_from_db()
+ assert job.status == ExternalDataJob.Status.FAILED
+ assert _lease_count(queue_conn, str(schema.id)) == (0 if force else 1)
+ if not force:
+ assert "Use --force" in out
+
+ def test_fails_running_job_with_no_queue_batches(self, team, queue_conn, fake_redis):
+ _, schema, job = _create_pipeline(team)
+
+ _call("fail-run", "--team-id", str(team.pk), "--schema-id", str(schema.id), "--live-run", "--yes")
+
+ job.refresh_from_db()
+ assert job.status == ExternalDataJob.Status.FAILED
+
+
+class TestTargetingValidation:
+ @pytest.mark.parametrize(
+ "args",
+ [
+ pytest.param(["fail-run", "--schema-id", "x"], id="schema_without_team"),
+ pytest.param(["fail-run", "--source-id", "x"], id="source_without_team"),
+ pytest.param(["fail-run", "--run-uuid", "x", "--team-id", "1"], id="run_uuid_combined"),
+ pytest.param(["fail-run"], id="fail_run_unscoped"),
+ pytest.param(["release-locks"], id="release_locks_unscoped"),
+ pytest.param(["release-locks", "--run-uuid", "x"], id="release_locks_run_uuid"),
+ pytest.param(
+ ["release-locks", "--team-id", "1", "--leases-only", "--redis-only"], id="release_both_only_flags"
+ ),
+ ],
+ )
+ def test_invalid_targeting_raises(self, args, queue_conn, fake_redis):
+ with pytest.raises(CommandError):
+ _call(*args)
+
+
+class TestReleaseLocks:
+ def test_live_lease_requires_force_and_stale_state_is_released(self, team, queue_conn, fake_redis):
+ source = ExternalDataSource.objects.create(team=team, source_type="Stripe", job_inputs={})
+ live_schema = ExternalDataSchema.objects.create(
+ name="live", team=team, source=source, sync_type=ExternalDataSchema.SyncType.FULL_REFRESH
+ )
+ stale_schema = ExternalDataSchema.objects.create(
+ name="stale", team=team, source=source, sync_type=ExternalDataSchema.SyncType.FULL_REFRESH
+ )
+ _insert_lease(queue_conn, team_id=team.pk, schema_id=str(live_schema.id), live=True)
+ _insert_lease(queue_conn, team_id=team.pk, schema_id=str(stale_schema.id), live=False)
+ # a stale redis lock: held by a token that matches no Running job
+ assert sync_lock.acquire_v3_pipeline_lock(team.pk, str(stale_schema.id), "dead-workflow-run")
+
+ out = _call("release-locks", "--team-id", str(team.pk), "--live-run", "--yes")
+
+ assert "LIVE" in out
+ assert _lease_count(queue_conn, str(stale_schema.id)) == 0
+ assert _lease_count(queue_conn, str(live_schema.id)) == 1 # live lease kept without --force
+ assert sync_lock.get_v3_pipeline_lock_holder(team.pk, str(stale_schema.id)) is None
+
+ _call("release-locks", "--team-id", str(team.pk), "--live-run", "--yes", "--force")
+ assert _lease_count(queue_conn, str(live_schema.id)) == 0
+
+
+class TestStatus:
+ def test_status_reports_all_sections_without_error(self, team, queue_conn, fake_redis):
+ _, schema, job = _create_pipeline(team)
+ run_uuid = str(uuid4())
+ batches = _seed_active_run(queue_conn, team=team, schema=schema, job=job, run_uuid=run_uuid)
+ _set_status(queue_conn, batches["executing"], "executing") # ensure stale-executing section has data
+ _insert_lease(queue_conn, team_id=team.pk, schema_id=str(schema.id), live=False)
+
+ out = _call("status", "--team-id", str(team.pk), "--stale-grace-seconds", "0")
+
+ assert run_uuid in out
+ assert str(schema.id) in out
+ assert "unclaimed: 1" in out