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 --only-stuck and duckgres sink to queue command (#69688)

estefaniaa330f2d8d0ff
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 99751cd3a2de..de2760490c2f 100644
--- a/products/warehouse_sources/backend/management/commands/manage_warehouse_queue.py
+++ b/products/warehouse_sources/backend/management/commands/manage_warehouse_queue.py
@@ -1,16 +1,21 @@
-"""Ops tooling for the v3 warehouse sources load queue (delta sink).
+"""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. Mutating actions are dry-run by default and mirror the consumer's own
+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.
+Mutating actions are dry-run by default and mirror the consumers' own
fail/reconcile semantics rather than inventing a second code path.
"""
import sys
+import asyncio
from dataclasses import dataclass
-from datetime import UTC, datetime
+from datetime import UTC, datetime, timedelta
from typing import Any
+from django.conf import settings
from django.core.management.base import BaseCommand, CommandError, CommandParser
import psycopg
@@ -24,11 +29,15 @@ from products.warehouse_sources.backend.models.external_data_source import Exter
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.duckgres.jobs_db import (
+ DuckgresBatchQueue,
+)
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,
+ TAKEOVER_STALE_THRESHOLD_SECONDS,
ActiveRunRef,
BatchQueue,
)
@@ -44,6 +53,14 @@ MAX_RUNS_DEFAULT = 20
PRINT_LIMIT = 50
DRY_RUN_MESSAGE = "Dry run - no changes written. Re-run with --live-run to apply."
+SINK_DELTA = "delta"
+SINK_DUCKGRES = "duckgres"
+
+# Both queue classes expose the same sync ops helpers (get_active_runs,
+# get_state_summary, get_leases, force_release_leases, get_stale_executing_sync,
+# fail_run_sync), so the handlers drive whichever sink was selected.
+SinkQueue = type[BatchQueue] | type[DuckgresBatchQueue]
+
@dataclass(frozen=True)
class Scope:
@@ -67,13 +84,18 @@ class FailTarget:
workflow_run_id: str | None
pending_batches: int
total_batches: int
+ # Newest queue activity for queue-visible runs; job creation time for
+ # job-only targets (there is no queue activity to measure).
+ last_activity_at: datetime
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."
+ "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."
)
def add_arguments(self, parser: CommandParser) -> None:
@@ -103,11 +125,46 @@ class Command(BaseCommand):
default=MAX_RUNS_DEFAULT,
help=f"Abort if more than this many runs match (default {MAX_RUNS_DEFAULT})",
)
+ fail_run.add_argument(
+ "--only-stuck",
+ action="store_true",
+ help="Only target runs that look wedged: no queue activity for --stuck-grace-seconds "
+ "(job-only targets qualify by how long the job has been Running). May be used without "
+ "other targeting flags to sweep everything in the queue.",
+ )
+ fail_run.add_argument(
+ "--stuck-grace-seconds",
+ type=int,
+ default=TAKEOVER_STALE_THRESHOLD_SECONDS,
+ help="Quiet time before --only-stuck treats a run as wedged "
+ f"(default {TAKEOVER_STALE_THRESHOLD_SECONDS}s, the lock-takeover staleness threshold)",
+ )
fail_run.add_argument(
"--cancel-workflow",
action="store_true",
- help="Also request cancellation of each run's Temporal workflow",
+ help="Also request cancellation of each run's Temporal workflow (delta sink only)",
+ )
+ # Temporal connection overrides (same flags as start_temporal_workflow): ops pods
+ # often lack the worker pods' TEMPORAL_* env, so settings-based sync_connect
+ # fails DNS there and the operator must point at the cluster explicitly.
+ fail_run.add_argument(
+ "--temporal-host",
+ default=settings.TEMPORAL_HOST,
+ help="Hostname for Temporal scheduler (with --cancel-workflow)",
+ )
+ fail_run.add_argument(
+ "--temporal-port",
+ default=settings.TEMPORAL_PORT,
+ help="Port for Temporal scheduler (with --cancel-workflow)",
+ )
+ fail_run.add_argument(
+ "--namespace",
+ default=settings.TEMPORAL_NAMESPACE,
+ help="Temporal namespace to connect to (with --cancel-workflow)",
)
+ fail_run.add_argument("--server-root-ca-cert", default=None, help="Optional root server CA cert")
+ fail_run.add_argument("--client-cert", default=settings.TEMPORAL_CLIENT_CERT, help="Optional client cert")
+ fail_run.add_argument("--client-key", default=settings.TEMPORAL_CLIENT_KEY, help="Optional client key")
fail_run.add_argument(
"--force",
action="store_true",
@@ -120,7 +177,9 @@ class Command(BaseCommand):
)
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(
+ "--redis-only", action="store_true", help="Only release v3 Redis pipeline locks (delta sink only)"
+ )
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(
@@ -131,6 +190,12 @@ class Command(BaseCommand):
@staticmethod
def _add_target_args(parser: CommandParser) -> None:
+ parser.add_argument(
+ "--sink",
+ choices=[SINK_DELTA, SINK_DUCKGRES],
+ default=SINK_DELTA,
+ help="Which sink's queue state to manage: the delta loader (default) or the duckgres sink",
+ )
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)")
@@ -144,13 +209,16 @@ class Command(BaseCommand):
if action == "cancel":
action = "fail-run"
+ sink: str = options.get("sink") or SINK_DELTA
+ queue: SinkQueue = BatchQueue if sink == SINK_DELTA else DuckgresBatchQueue
+
with psycopg.connect(WAREHOUSE_SOURCES_DATABASE_URL, autocommit=True) as conn:
if action == "status":
- self._handle_status(conn, options)
+ self._handle_status(conn, options, sink=sink, queue=queue)
elif action == "fail-run":
- self._handle_fail_run(conn, options)
+ self._handle_fail_run(conn, options, sink=sink, queue=queue)
elif action == "release-locks":
- self._handle_release_locks(conn, options)
+ self._handle_release_locks(conn, options, sink=sink, queue=queue)
# -- targeting --------------------------------------------------------------
@@ -173,7 +241,7 @@ class Command(BaseCommand):
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"
+ "--source-type alone, or --run-uuid (fail-run may instead sweep unscoped with --only-stuck)"
)
return Scope()
@@ -238,8 +306,10 @@ class Command(BaseCommand):
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(
+ def _collect_fail_targets(
+ self, conn: psycopg.Connection[Any], scope: Scope, *, queue: SinkQueue, include_job_only: bool
+ ) -> list[FailTarget]:
+ runs = queue.get_active_runs(
conn,
team_id=scope.team_id,
schema_ids=scope.schema_ids,
@@ -259,17 +329,25 @@ class Command(BaseCommand):
workflow_run_id=r.workflow_run_id,
pending_batches=r.pending_batches,
total_batches=r.total_batches,
+ last_activity_at=r.latest_activity_at,
)
for r in runs
]
if scope.run_uuid:
if not targets:
- raise CommandError(
+ message = (
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."
+ f"({PARTITION_PRUNING_INTERVAL}) - nothing to fail."
)
+ if include_job_only:
+ message += (
+ " If its ExternalDataJob is stuck in Running, target it via --team-id/--schema-id instead."
+ )
+ raise CommandError(message)
+ return targets
+
+ if not include_job_only:
return targets
# Running jobs the queue knows nothing about (producer died before enqueueing,
@@ -288,20 +366,34 @@ class Command(BaseCommand):
workflow_run_id=job.workflow_run_id,
pending_batches=0,
total_batches=0,
+ last_activity_at=job.created_at,
)
)
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)
+ def _handle_fail_run(
+ self, conn: psycopg.Connection[Any], options: dict[str, Any], *, sink: str, queue: SinkQueue
+ ) -> None:
+ is_delta = sink == SINK_DELTA
+ cancel_workflow: bool = options["cancel_workflow"]
+ if cancel_workflow and not is_delta:
+ raise CommandError("--cancel-workflow only applies to the delta sink; drop it or use --sink delta")
+
+ scope = self._resolve_scope(options, allow_empty=options["only_stuck"])
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)
+ targets = self._collect_fail_targets(conn, scope, queue=queue, include_job_only=is_delta)
+ if options["only_stuck"]:
+ targets, skipped_active = self._filter_stuck(targets, grace_seconds=options["stuck_grace_seconds"])
+ if skipped_active:
+ self.stdout.write(
+ f"--only-stuck: skipped {skipped_active} run(s) with queue activity within "
+ f"the last {options['stuck_grace_seconds']}s."
+ )
if not targets:
self.stdout.write("No active runs match - nothing to fail.")
return
@@ -318,11 +410,11 @@ class Command(BaseCommand):
# 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}))
+ for lease in queue.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):")
+ self.stdout.write(f"{verb} {len(targets)} run(s) [{sink} sink]:")
for t in targets:
job = jobs_by_id.get(t.job_id)
job_status = job.status if job else "<job not found>"
@@ -331,13 +423,15 @@ class Command(BaseCommand):
if t.run_uuid
else "no queue batches in retention window (job-only)"
)
+ activity = self._age(t.last_activity_at) + " ago"
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 '-'}"
+ f"schema={t.schema_id or '-'} {queue_note} last_activity={activity} "
+ f"workflow_run_id={t.workflow_run_id or '-'}"
)
if t.schema_id:
notes = []
- if t.workflow_run_id:
+ if is_delta and 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")
@@ -355,6 +449,12 @@ class Command(BaseCommand):
if notes:
self.stdout.write(f" -> {'; '.join(notes)}")
+ if not is_delta:
+ self.stdout.write(
+ "Note: failing duckgres runs leaves the ExternalDataJob untouched; "
+ "retry failed duckgres batches later with reset_duckgres_failed_runs."
+ )
+
if not live_run:
self.stdout.write(DRY_RUN_MESSAGE)
return
@@ -363,9 +463,10 @@ class Command(BaseCommand):
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))
+ self._fail_target(conn, t, reason=reason, queue=queue, is_delta=is_delta)
logger.info(
"manage_warehouse_queue_fail_run",
+ sink=sink,
run_uuid=t.run_uuid,
job_id=t.job_id,
team_id=t.team_id,
@@ -373,12 +474,15 @@ class Command(BaseCommand):
reason=reason,
)
+ if cancel_workflow:
+ self._cancel_workflows(options, [jobs_by_id.get(t.job_id) for t in targets])
+
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})):
+ for lease in queue.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:
@@ -392,30 +496,42 @@ class Command(BaseCommand):
)
continue
leases_to_delete.append((lease.team_id, lease.schema_id))
- released = BatchQueue.force_release_leases(conn, pairs=leases_to_delete)
+ 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))
+ @staticmethod
+ def _filter_stuck(targets: list[FailTarget], *, grace_seconds: int) -> tuple[list[FailTarget], int]:
+ """Keep targets whose last queue activity (or job creation, for job-only
+ targets) is older than ``grace_seconds``. Returns (stuck, skipped_count)."""
+ cutoff = datetime.now(UTC) - timedelta(seconds=grace_seconds)
+ stuck = [t for t in targets if t.last_activity_at <= cutoff]
+ return stuck, len(targets) - len(stuck)
+
def _fail_target(
self,
conn: psycopg.Connection[Any],
target: FailTarget,
*,
reason: str,
- cancel_workflow: bool,
- job: ExternalDataJob | None,
+ queue: SinkQueue,
+ is_delta: bool,
) -> 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)
+ failed = queue.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)"))
+ if not is_delta:
+ # The duckgres sink doesn't own the job, the redis lock, or the workflow.
+ return
+
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")
@@ -439,37 +555,76 @@ class Command(BaseCommand):
)
)
- if cancel_workflow:
- self._cancel_workflow(job)
+ def _cancel_workflows(self, options: dict[str, Any], jobs: list[ExternalDataJob | None]) -> None:
+ """Cancel each job's Temporal workflow over a single client connection.
- def _cancel_workflow(self, job: ExternalDataJob | None) -> None:
+ Connects with the command's --temporal-host/--temporal-port/--namespace/cert
+ options rather than sync_connect(), and once for the whole batch rather than
+ per workflow.
+ """
# 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
+ from posthog.temporal.common.client import connect # 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"))
+ workflow_ids: list[str] = []
+ for job in jobs:
+ if job is None or not job.workflow_id:
+ self.stdout.write(self.style.WARNING("temporal: a job has no workflow_id - skipped"))
+ elif job.workflow_id not in workflow_ids:
+ workflow_ids.append(job.workflow_id)
+ if not workflow_ids:
return
+
+ async def _cancel_all() -> None:
+ client = await connect(
+ options["temporal_host"],
+ options["temporal_port"],
+ options["namespace"],
+ server_root_ca_cert=options["server_root_ca_cert"],
+ client_cert=options["client_cert"],
+ client_key=options["client_key"],
+ )
+ for workflow_id in workflow_ids:
+ try:
+ await client.get_workflow_handle(workflow_id).cancel()
+ self.stdout.write(f"temporal: cancellation requested for {workflow_id}")
+ except RPCError as e:
+ self.stdout.write(
+ self.style.WARNING(f"temporal: cancellation failed for {workflow_id} ({e.message})")
+ )
+ except Exception:
+ logger.exception("manage_warehouse_queue_temporal_cancel_failed", workflow_id=workflow_id)
+ self.stdout.write(self.style.ERROR(f"temporal: cancellation failed for {workflow_id} (see logs)"))
+
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})"))
+ asyncio.run(_cancel_all())
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)"))
+ logger.exception("manage_warehouse_queue_temporal_connect_failed", host=options["temporal_host"])
+ self.stdout.write(
+ self.style.ERROR(
+ f"temporal: could not connect to {options['temporal_host']}:{options['temporal_port']} - "
+ f"no workflows cancelled. If this pod's TEMPORAL_* env doesn't point at the cluster, pass "
+ "--temporal-host/--temporal-port/--namespace (and certs) explicitly, as with "
+ "start_temporal_workflow."
+ )
+ )
# -- release-locks ----------------------------------------------------------
- def _handle_release_locks(self, conn: psycopg.Connection[Any], options: dict[str, Any]) -> None:
+ def _handle_release_locks(
+ self, conn: psycopg.Connection[Any], options: dict[str, Any], *, sink: str, queue: SinkQueue
+ ) -> None:
+ is_delta = sink == SINK_DELTA
if options["leases_only"] and options["redis_only"]:
raise CommandError("--leases-only and --redis-only are mutually exclusive")
+ if options["redis_only"] and not is_delta:
+ raise CommandError("--redis-only only applies to the delta sink; the duckgres sink has no redis lock")
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)
+ pairs = self._resolve_lock_pairs(conn, scope, queue=queue)
if not pairs:
self.stdout.write("No (team, schema) pairs in scope - nothing to release.")
return
@@ -477,18 +632,19 @@ class Command(BaseCommand):
live_run: bool = options["live_run"]
force: bool = options["force"]
check_leases = not options["redis_only"]
- check_redis = not options["leases_only"]
+ check_redis = is_delta and 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)
+ if check_redis:
+ 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])
+ leases = queue.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(
@@ -535,7 +691,7 @@ class Command(BaseCommand):
yes=options["yes"],
)
- released_leases = BatchQueue.force_release_leases(conn, pairs=leases_to_delete)
+ released_leases = queue.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
@@ -548,6 +704,7 @@ class Command(BaseCommand):
)
logger.info(
"manage_warehouse_queue_release_locks",
+ sink=sink,
released_leases=released_leases,
released_locks=released_locks,
team_id=scope.team_id,
@@ -557,7 +714,9 @@ class Command(BaseCommand):
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]]:
+ def _resolve_lock_pairs(
+ self, conn: psycopg.Connection[Any], scope: Scope, *, queue: SinkQueue
+ ) -> 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
@@ -572,9 +731,9 @@ class Command(BaseCommand):
# 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 "")
+ runs = self._filter_runs_by_source_type(queue.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)}
+ lease_schema_ids = {lease.schema_id for lease in queue.get_leases(conn)}
if lease_schema_ids:
matching = {
str(schema_pk): team_pk
@@ -591,10 +750,13 @@ class Command(BaseCommand):
# -- status -----------------------------------------------------------------
- def _handle_status(self, conn: psycopg.Connection[Any], options: dict[str, Any]) -> None:
+ def _handle_status(
+ self, conn: psycopg.Connection[Any], options: dict[str, Any], *, sink: str, queue: SinkQueue
+ ) -> None:
+ is_delta = sink == SINK_DELTA
scope = self._resolve_scope(options, allow_empty=True)
- runs = BatchQueue.get_active_runs(
+ runs = queue.get_active_runs(
conn,
team_id=scope.team_id,
schema_ids=scope.schema_ids,
@@ -611,8 +773,8 @@ class Command(BaseCommand):
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)
+ self.stdout.write(self.style.MIGRATE_HEADING(f"Queue summary [{sink} sink] (within retention window)"))
+ summary = queue.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:
@@ -638,10 +800,13 @@ class Command(BaseCommand):
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.
+ # Delta-only: Running V3 jobs belong to the delta path, and 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 scope.run_uuid or not is_delta
+ 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(
@@ -655,8 +820,8 @@ class Command(BaseCommand):
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)
+ self.stdout.write(self.style.MIGRATE_HEADING(f"Group leases [{sink} sink]"))
+ leases = queue.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]:
@@ -666,33 +831,34 @@ class Command(BaseCommand):
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")
+ if is_delta:
+ 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(
+ stale = queue.get_stale_executing_sync(
conn, grace_seconds=grace, team_id=scope.team_id, schema_ids=summary_schema_ids
)
self.stdout.write(
diff --git a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/jobs_db.py b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/jobs_db.py
index c6b8782a8ce9..6709094bf554 100644
--- a/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/jobs_db.py
+++ b/products/warehouse_sources/backend/temporal/data_imports/pipelines/pipeline_v3/duckgres/jobs_db.py
@@ -16,8 +16,11 @@ from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline
LEASE_TTL_SECONDS,
PARTITION_PRUNING_INTERVAL,
STATUS_TABLE,
+ ActiveRunRef,
+ GroupLease,
PendingBatch,
pending_batch_select_columns,
+ scope_filters,
)
DUCKGRES_STATUS_TABLE = "sourcebatchduckgresstatus"
@@ -71,6 +74,48 @@ async def _statement_timeout(conn: psycopg.AsyncConnection[Any], timeout_ms: int
yield
+def duckgres_pending_predicate(delta_alias: str, duckgres_alias: str) -> str:
+ """A batch is duckgres-pending (still fail-able) when its delta load succeeded
+ and its latest duckgres status is absent or non-terminal."""
+ return (
+ f"({delta_alias}.job_state = 'succeeded' AND "
+ f"({duckgres_alias}.batch_id IS NULL OR {duckgres_alias}.job_state IN ('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) duckgres batch.
+DUCKGRES_FAIL_RUN_SQL = f"""
+ INSERT INTO {DUCKGRES_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
+ LEFT JOIN {_latest_status_lateral(STATUS_TABLE, "b")} ds ON true
+ LEFT JOIN {_latest_status_lateral(DUCKGRES_STATUS_TABLE, "b")} dgs ON true
+ WHERE
+ b.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'
+ AND b.run_uuid = %(run_uuid)s
+ AND {duckgres_pending_predicate("ds", "dgs")}
+"""
+
+
+def _stale_executing_sql(scope_sql: str = "") -> str:
+ """Shared body of the duckgres stale-executing sweep (async consumer and its sync ops twin)."""
+ return f"""
+ SELECT
+ {pending_batch_select_columns("dgs")}
+ FROM {BATCH_TABLE} b
+ JOIN {_latest_status_lateral(DUCKGRES_STATUS_TABLE, "b")} dgs ON true
+ LEFT JOIN {DUCKGRES_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 dgs.job_state = 'executing'
+ AND dgs.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
+ """
+
+
# Structured classification key written into duckgres status error_response by
# every terminal-retire writer. Consumers (the backfill reconciler) dispatch on
# this, not on error-message prose.
@@ -937,18 +982,24 @@ class DuckgresBatchQueue:
reason: str,
) -> int:
cursor = await conn.execute(
- f"""
- INSERT INTO {DUCKGRES_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
- JOIN {_latest_status_lateral(STATUS_TABLE, "b")} ds ON true
- LEFT JOIN {_latest_status_lateral(DUCKGRES_STATUS_TABLE, "b")} dgs ON true
- WHERE
- b.created_at > now() - interval '{PARTITION_PRUNING_INTERVAL}'
- AND b.run_uuid = %(run_uuid)s
- AND ds.job_state = 'succeeded'
- AND (dgs.batch_id IS NULL OR dgs.job_state IN ('waiting_retry', 'executing'))
- """,
+ DUCKGRES_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(
+ DUCKGRES_FAIL_RUN_SQL,
{
"run_uuid": run_uuid,
"error_response": json.dumps({"error": reason}),
@@ -1020,22 +1071,7 @@ class DuckgresBatchQueue:
expired — unlike the old advisory-lock probe, an abandoned lease always
expires, so orphaned groups are always reclaimable."""
async with conn.cursor(row_factory=dict_row) as cur:
- await cur.execute(
- f"""
- SELECT
- {pending_batch_select_columns("dgs")}
- FROM {BATCH_TABLE} b
- JOIN {_latest_status_lateral(DUCKGRES_STATUS_TABLE, "b")} dgs ON true
- LEFT JOIN {DUCKGRES_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 dgs.job_state = 'executing'
- AND dgs.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]
@@ -1076,3 +1112,151 @@ class DuckgresBatchQueue:
f"DELETE FROM {DUCKGRES_LEASE_TABLE} WHERE owner_token = %(owner)s",
{"owner": owner_token},
)
+
+ # -- ops / management command helpers (sync) --------------------------------
+ # Duck-typed twins of BatchQueue's ops helpers so manage_warehouse_queue can
+ # drive either sink through the same interface.
+
+ @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 by their duckgres sink state.
+
+ ``pending_batches`` counts batches the duckgres sink still owes: delta-
+ succeeded but with no terminal duckgres status (the same predicate
+ ``fail_run`` writes against). ``latest_activity_at`` is the newest of
+ batch inserts, delta status writes, and duckgres status writes, so a run
+ the delta consumer is still actively loading does not look duckgres-stuck.
+ """
+ scope_sql, params = scope_filters(team_id=team_id, schema_ids=schema_ids, run_uuid=run_uuid)
+ having = f"HAVING COUNT(*) FILTER (WHERE {duckgres_pending_predicate('ds', 'dgs')}) > 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 {duckgres_pending_predicate("ds", "dgs")}
+ ) AS pending_batches,
+ COUNT(*) AS total_batches,
+ GREATEST(MAX(ds.created_at), MAX(dgs.created_at), MAX(b.created_at)) AS latest_activity_at
+ FROM {BATCH_TABLE} b
+ LEFT JOIN {_latest_status_lateral(STATUS_TABLE, "b")} ds ON true
+ LEFT JOIN {_latest_status_lateral(DUCKGRES_STATUS_TABLE, "b")} dgs ON true
+ 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]]:
+ """Delta-succeeded batch counts by latest duckgres state within the scope.
+
+ Scoped to delta-succeeded batches because that is the duckgres sink's
+ input set; ``state='unclaimed'`` means the sink has not touched the
+ batch yet. Each row carries the oldest ``created_at`` in its state.
+ """
+ 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(dgs.job_state, 'unclaimed') AS state,
+ COUNT(*) AS batch_count,
+ MIN(b.created_at) AS oldest_created_at
+ FROM {BATCH_TABLE} b
+ JOIN {_latest_status_lateral(STATUS_TABLE, "b")} ds ON ds.job_state = 'succeeded'
+ LEFT JOIN {_latest_status_lateral(DUCKGRES_STATUS_TABLE, "b")} dgs ON true
+ 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]:
+ """Duckgres 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 {DUCKGRES_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 duckgres group leases for ``pairs`` regardless of owner. Ops override only."""
+ if not pairs:
+ return 0
+ cursor = conn.execute(
+ f"""
+ DELETE FROM {DUCKGRES_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]
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 eb8c20f1ff44..485b3d4684ff 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
@@ -375,7 +375,7 @@ class ActiveRunRef:
workflow_run_id: str | None
pending_batches: int
total_batches: int
- latest_activity_at: datetime | None
+ latest_activity_at: datetime
@dataclass(frozen=True, slots=True)
@@ -1059,7 +1059,7 @@ class BatchQueue:
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)
+ 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(
@@ -1101,7 +1101,7 @@ class BatchQueue:
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)
+ 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"""
@@ -1128,7 +1128,7 @@ class BatchQueue:
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")
+ 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"""
@@ -1182,7 +1182,7 @@ class BatchQueue:
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)
+ 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)
@@ -1190,7 +1190,7 @@ class BatchQueue:
return [PendingBatch(**row) for row in rows]
-def _scope_filters(
+def scope_filters(
*,
team_id: int | None = None,
schema_ids: list[str] | None = None,
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 19987a73d07b..d70fd85b967a 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
@@ -1,15 +1,17 @@
import json
from collections.abc import Generator
from contextlib import contextmanager
+from datetime import timedelta
from io import StringIO
from typing import Any
from uuid import uuid4
import pytest
-from unittest.mock import patch
+from unittest.mock import AsyncMock, MagicMock, patch
from django.core.management import call_command
from django.core.management.base import CommandError
+from django.utils import timezone
import psycopg
import fakeredis
@@ -21,17 +23,24 @@ from products.warehouse_sources.backend.models.external_data_job import External
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.duckgres.jobs_db import (
+ DUCKGRES_LEASE_TABLE,
+ DUCKGRES_STATUS_TABLE,
)
-from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.test_jobs_db import (
+
+# The duckgres test module's DDL is a superset of the delta queue's (both status
+# and lease tables), which the --sink duckgres tests need.
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.duckgres.test_jobs_db import (
_BATCH_DEFAULTS,
_ensure_tables,
_get_test_database_url,
_truncate_tables,
)
+from products.warehouse_sources.backend.temporal.data_imports.pipelines.pipeline_v3.postgres_queue.jobs_db import (
+ BATCH_TABLE,
+ LEASE_TABLE,
+ STATUS_TABLE,
+)
pytestmark = [pytest.mark.django_db]
@@ -108,9 +117,10 @@ def _create_pipeline(
return source, schema, job
-def _insert_batch(conn: psycopg.Connection[Any], **overrides: Any) -> str:
+def _insert_batch(conn: psycopg.Connection[Any], *, age_hours: float = 0, **overrides: Any) -> str:
params = {**_BATCH_DEFAULTS, **overrides}
params["metadata"] = json.dumps(params["metadata"])
+ params["age_seconds"] = age_hours * 3600
row = conn.execute(
f"""
INSERT INTO {BATCH_TABLE} (
@@ -121,7 +131,8 @@ def _insert_batch(conn: psycopg.Connection[Any], **overrides: Any) -> str:
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()
+ %(resource_name)s, %(is_resume)s, %(is_first_ever_sync)s, %(metadata)s,
+ now() - make_interval(secs => %(age_seconds)s)
) RETURNING id
""",
params,
@@ -130,34 +141,38 @@ def _insert_batch(conn: psycopg.Connection[Any], **overrides: Any) -> str:
return str(row[0])
-def _set_status(conn: psycopg.Connection[Any], batch_id: str, state: str) -> None:
+def _set_status(
+ conn: psycopg.Connection[Any], batch_id: str, state: str, *, table: str = STATUS_TABLE, age_hours: float = 0
+) -> 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),
+ f"INSERT INTO {table} (batch_id, job_state, attempt, exec_time, created_at) "
+ "VALUES (%s, %s, 0, now(), now() - make_interval(secs => %s))",
+ (batch_id, state, age_hours * 3600),
)
-def _insert_lease(conn: psycopg.Connection[Any], *, team_id: int, schema_id: str, live: bool) -> None:
+def _insert_lease(
+ conn: psycopg.Connection[Any], *, team_id: int, schema_id: str, live: bool, table: str = LEASE_TABLE
+) -> 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"INSERT INTO {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()
+def _lease_count(conn: psycopg.Connection[Any], schema_id: str, *, table: str = LEASE_TABLE) -> int:
+ row = conn.execute(f"SELECT COUNT(*) FROM {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]:
+def _failed_status_counts_by_run(conn: psycopg.Connection[Any], *, table: str = STATUS_TABLE) -> 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
+ FROM {table} s JOIN {BATCH_TABLE} b ON b.id = s.batch_id
WHERE s.job_state = 'failed'
GROUP BY b.run_uuid
"""
@@ -172,6 +187,7 @@ def _seed_active_run(
schema: ExternalDataSchema,
job: ExternalDataJob,
run_uuid: str,
+ age_hours: float = 0,
) -> dict[str, str]:
"""One succeeded batch and two pending ones (unclaimed + executing), like a mid-load run."""
common = {
@@ -181,11 +197,12 @@ def _seed_active_run(
"job_id": str(job.id),
"run_uuid": run_uuid,
"metadata": {"workflow_run_id": job.workflow_run_id},
+ "age_hours": age_hours,
}
succeeded = _insert_batch(conn, **common, batch_index=0)
- _set_status(conn, succeeded, "succeeded")
+ _set_status(conn, succeeded, "succeeded", age_hours=age_hours)
executing = _insert_batch(conn, **common, batch_index=1)
- _set_status(conn, executing, "executing")
+ _set_status(conn, executing, "executing", age_hours=age_hours)
unclaimed = _insert_batch(conn, **common, batch_index=2)
return {"succeeded": succeeded, "executing": executing, "unclaimed": unclaimed}
@@ -282,6 +299,59 @@ class TestFailRun:
job.refresh_from_db()
assert job.status == ExternalDataJob.Status.FAILED
+ def test_cancel_workflow_connects_with_overrides_and_cancels(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()))
+ handle = MagicMock(cancel=AsyncMock())
+ client = MagicMock(**{"get_workflow_handle.return_value": handle})
+ connect_mock = AsyncMock(return_value=client)
+
+ with patch("posthog.temporal.common.client.connect", connect_mock):
+ out = _call(
+ "fail-run",
+ "--team-id",
+ str(team.pk),
+ "--schema-id",
+ str(schema.id),
+ "--cancel-workflow",
+ "--temporal-host",
+ "temporal-fe.internal",
+ "--live-run",
+ "--yes",
+ )
+
+ assert connect_mock.call_args.args[0] == "temporal-fe.internal"
+ client.get_workflow_handle.assert_called_once_with(job.workflow_id)
+ handle.cancel.assert_awaited_once()
+ assert f"cancellation requested for {job.workflow_id}" in out
+
+ def test_only_stuck_fails_only_inactive_runs_and_allows_unscoped_use(self, team, queue_conn, fake_redis):
+ # a wedged run: last queue activity 8h ago (past the 6h default grace)
+ _, stale_schema, stale_job = _create_pipeline(team)
+ stale_run = str(uuid4())
+ _seed_active_run(queue_conn, team=team, schema=stale_schema, job=stale_job, run_uuid=stale_run, age_hours=8)
+ # a healthy run: activity just now
+ _, fresh_schema, fresh_job = _create_pipeline(team)
+ fresh_run = str(uuid4())
+ _seed_active_run(queue_conn, team=team, schema=fresh_schema, job=fresh_job, run_uuid=fresh_run)
+ # job-only targets (nothing in the queue): one old, one just started
+ _, _, stale_orphan_job = _create_pipeline(team)
+ ExternalDataJob.objects.filter(id=stale_orphan_job.id).update(created_at=timezone.now() - timedelta(hours=8))
+ _, _, fresh_orphan_job = _create_pipeline(team)
+
+ out = _call("fail-run", "--only-stuck", "--live-run", "--yes")
+
+ assert _failed_status_counts_by_run(queue_conn) == {stale_run: 2}
+ for job, expected in [
+ (stale_job, ExternalDataJob.Status.FAILED),
+ (stale_orphan_job, ExternalDataJob.Status.FAILED),
+ (fresh_job, ExternalDataJob.Status.RUNNING),
+ (fresh_orphan_job, ExternalDataJob.Status.RUNNING),
+ ]:
+ job.refresh_from_db()
+ assert job.status == expected
+ assert "skipped 2 run(s)" in out
+
class TestTargetingValidation:
@pytest.mark.parametrize(
@@ -296,6 +366,13 @@ class TestTargetingValidation:
pytest.param(
["release-locks", "--team-id", "1", "--leases-only", "--redis-only"], id="release_both_only_flags"
),
+ pytest.param(
+ ["fail-run", "--sink", "duckgres", "--team-id", "1", "--cancel-workflow"],
+ id="cancel_workflow_duckgres",
+ ),
+ pytest.param(
+ ["release-locks", "--sink", "duckgres", "--team-id", "1", "--redis-only"], id="redis_only_duckgres"
+ ),
],
)
def test_invalid_targeting_raises(self, args, queue_conn, fake_redis):
@@ -341,3 +418,88 @@ class TestStatus:
assert run_uuid in out
assert str(schema.id) in out
assert "unclaimed: 1" in out
+
+
+def _seed_duckgres_run(
+ conn: psycopg.Connection[Any],
+ *,
+ team,
+ schema: ExternalDataSchema,
+ job: ExternalDataJob,
+ run_uuid: str,
+) -> dict[str, str]:
+ """A run mid-way through the duckgres sink: one batch fully applied, one the
+ sink hasn't claimed, one retrying, and one whose delta load isn't done yet."""
+ 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},
+ }
+ applied = _insert_batch(conn, **common, batch_index=0)
+ _set_status(conn, applied, "succeeded")
+ _set_status(conn, applied, "succeeded", table=DUCKGRES_STATUS_TABLE)
+ unclaimed = _insert_batch(conn, **common, batch_index=1)
+ _set_status(conn, unclaimed, "succeeded")
+ retrying = _insert_batch(conn, **common, batch_index=2)
+ _set_status(conn, retrying, "succeeded")
+ _set_status(conn, retrying, "waiting_retry", table=DUCKGRES_STATUS_TABLE)
+ delta_pending = _insert_batch(conn, **common, batch_index=3)
+ _set_status(conn, delta_pending, "executing")
+ return {"applied": applied, "unclaimed": unclaimed, "retrying": retrying, "delta_pending": delta_pending}
+
+
+class TestDuckgresSink:
+ def test_fail_run_fails_pending_duckgres_batches_without_touching_delta_or_job(self, team, queue_conn, fake_redis):
+ _, schema, job = _create_pipeline(team)
+ run_uuid = str(uuid4())
+ _seed_duckgres_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, table=DUCKGRES_LEASE_TABLE)
+ _insert_lease(queue_conn, team_id=team.pk, schema_id=str(schema.id), live=False)
+
+ out = _call(
+ "fail-run",
+ "--sink",
+ "duckgres",
+ "--team-id",
+ str(team.pk),
+ "--schema-id",
+ str(schema.id),
+ "--live-run",
+ "--yes",
+ )
+
+ # only the duckgres-pending batches (unclaimed + retrying) get duckgres failed rows;
+ # the applied batch and the delta-still-executing batch stay untouched
+ assert _failed_status_counts_by_run(queue_conn, table=DUCKGRES_STATUS_TABLE) == {run_uuid: 2}
+ assert _failed_status_counts_by_run(queue_conn) == {} # delta statuses untouched
+ job.refresh_from_db()
+ assert job.status == ExternalDataJob.Status.RUNNING # the duckgres sink doesn't own the job
+ assert _lease_count(queue_conn, str(schema.id), table=DUCKGRES_LEASE_TABLE) == 0
+ assert _lease_count(queue_conn, str(schema.id)) == 1 # delta lease untouched
+ assert "marked 2 pending batch(es) failed" in out
+
+ def test_release_locks_releases_only_duckgres_leases(self, team, queue_conn, fake_redis):
+ _, schema, _ = _create_pipeline(team)
+ _insert_lease(queue_conn, team_id=team.pk, schema_id=str(schema.id), live=False, table=DUCKGRES_LEASE_TABLE)
+ _insert_lease(queue_conn, team_id=team.pk, schema_id=str(schema.id), live=False)
+
+ _call("release-locks", "--sink", "duckgres", "--team-id", str(team.pk), "--live-run", "--yes")
+
+ assert _lease_count(queue_conn, str(schema.id), table=DUCKGRES_LEASE_TABLE) == 0
+ assert _lease_count(queue_conn, str(schema.id)) == 1
+
+ def test_status_reports_duckgres_sections(self, team, queue_conn, fake_redis):
+ _, schema, job = _create_pipeline(team)
+ run_uuid = str(uuid4())
+ batches = _seed_duckgres_run(queue_conn, team=team, schema=schema, job=job, run_uuid=run_uuid)
+ _set_status(queue_conn, batches["retrying"], "executing", table=DUCKGRES_STATUS_TABLE)
+ _insert_lease(queue_conn, team_id=team.pk, schema_id=str(schema.id), live=False, table=DUCKGRES_LEASE_TABLE)
+
+ out = _call("status", "--sink", "duckgres", "--team-id", str(team.pk), "--stale-grace-seconds", "0")
+
+ assert run_uuid in out
+ assert "unclaimed: 1" in out # delta-succeeded batch the duckgres sink hasn't claimed
+ assert "Redis pipeline locks" not in out # delta-only section