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(cohorts): audit and cancel wedged cohort backfill runs before enabling the finalizer (#83910)

Gustavo H. Strassburger958fad17da7f
diff --git a/posthog/settings/cohorts.py b/posthog/settings/cohorts.py
index 37d81106b0cf..5b6291a13379 100644
--- a/posthog/settings/cohorts.py
+++ b/posthog/settings/cohorts.py
@@ -42,6 +42,25 @@ BEHAVIORAL_BACKFILL_PERSON_TTL_ATTESTED: bool = get_from_env(
BEHAVIORAL_BACKFILL_FINALIZER_ENABLED: bool = get_from_env(
"BEHAVIORAL_BACKFILL_FINALIZER_ENABLED", False, type_cast=str_to_bool
)
+# Which runs the finalizer may stamp. Comma list of run UUIDs; empty / "all" / "*" lifts the
+# restriction, "none" matches nothing. Whitespace and case are tolerated and ids compare as parsed
+# UUIDs, so a line emitted by `manage_cohort_backfill_runs inventory` pastes in verbatim.
+#
+# It exists because a readiness stamp is one way. The moment
+# `BEHAVIORAL_BACKFILL_FINALIZER_ENABLED` flips, every reconciling run the seeder has observed
+# qualifies and gets stamped, and there is no un-stamp — so enabling the finalizer against an
+# unaudited backlog is irreversible. This narrows that to the short list of runs an operator
+# inspected by hand.
+#
+# A value meant as a restriction never degrades into "every run": if every token is malformed, the
+# parser matches nothing and logs, because widening is the direction that cannot be undone.
+#
+# The default lifts the restriction on purpose. A fail-closed default would silently park every
+# future run the first time someone forgot to widen it, which is the invisible backlog the
+# `not_allowlisted` gauge label exists to expose. Safety comes from ordering instead: set this to a
+# verified list (or "none") in every region before `BEHAVIORAL_BACKFILL_FINALIZER_ENABLED` is
+# turned on, so the default never applies where it matters.
+BEHAVIORAL_BACKFILL_FINALIZER_RUN_ALLOWLIST: str = os.getenv("BEHAVIORAL_BACKFILL_FINALIZER_RUN_ALLOWLIST", "all")
# Whether the finalizer may terminalize person-property runs and stamp
# `last_backfill_person_properties_at`.
#
diff --git a/products/cohorts/backend/backfill/allowlist.py b/products/cohorts/backend/backfill/allowlist.py
new file mode 100644
index 000000000000..0be61d101bd3
--- /dev/null
+++ b/products/cohorts/backend/backfill/allowlist.py
@@ -0,0 +1,42 @@
+"""Parses the finalizer's run allowlist.
+
+Its own module rather than living in ``finalize.py``: that module reaches ``posthog.tasks`` for the
+Celery queue, which imports it back, so anything importing it early sits inside that cycle. The
+parser has no dependencies at all, so both the finalizer and the operator tooling can read it.
+"""
+
+from uuid import UUID
+
+import structlog
+
+logger = structlog.get_logger(__name__)
+
+
+def parse_run_allowlist(raw: str) -> frozenset[UUID] | None:
+ """The runs the finalizer may stamp. ``None`` means every run, an empty set means none.
+
+ Grammar mirrors ``realtime_teams._team_in_allowlist``: empty / ``all`` / ``*`` match everything,
+ ``none`` matches nothing, otherwise a whitespace-tolerant comma list. Two deliberate departures,
+ both because a readiness stamp cannot be undone. Ids compare as parsed ``UUID``s, so an
+ unhyphenated or uppercase id from a pasted line still matches rather than silently matching
+ nothing. And a non-keyword value whose every token was malformed matches nothing rather than
+ everything: a typo in a restriction must not widen it to the whole fleet.
+ """
+ raw = raw.strip()
+ if raw == "" or raw.lower() == "all" or raw == "*":
+ return None
+ if raw.lower() == "none":
+ return frozenset()
+
+ allowed: set[UUID] = set()
+ malformed: list[str] = []
+ for part in (segment.strip() for segment in raw.split(",")):
+ if not part:
+ continue
+ try:
+ allowed.add(UUID(part))
+ except ValueError:
+ malformed.append(part)
+ if malformed:
+ logger.error("cohort_backfill_finalizer_allowlist_malformed_tokens", tokens=malformed)
+ return frozenset(allowed)
diff --git a/products/cohorts/backend/backfill/finalize.py b/products/cohorts/backend/backfill/finalize.py
index 5814bed59ef5..60429eae1603 100644
--- a/products/cohorts/backend/backfill/finalize.py
+++ b/products/cohorts/backend/backfill/finalize.py
@@ -28,6 +28,7 @@ from prometheus_client import Counter, Gauge
from posthog.tasks.utils import CeleryQueue
+from products.cohorts.backend.backfill.allowlist import parse_run_allowlist
from products.cohorts.backend.backfill.readiness import stamp_events_readiness, stamp_person_properties_readiness
from products.cohorts.backend.models.backfill import (
CohortBackfillKind,
@@ -67,16 +68,20 @@ HELD_RUNS_GAUGE = Gauge(
"posthog_cohort_backfill_finalizer_held_runs",
"Observed backfill runs the finalizer left in reconciling, by reason",
# labels: "shortfall" (an outcome was missing), "error" (the pass raised), "gated" (a person
- # run parked behind the readiness gate)
+ # run parked behind the readiness gate), "not_allowlisted" (excluded by
+ # BEHAVIORAL_BACKFILL_FINALIZER_RUN_ALLOWLIST)
["reason"],
- # This is a whole-fleet snapshot served from each worker pod's own registry, so `max` holds a
- # drained reason high until the task lands again on the pod that wrote the high reading.
- # `observe.py` pushes its equivalent gauges under one job name instead; this one wants the same.
- multiprocess_mode="max",
+ # Each pass is a whole-fleet snapshot, so only the newest reading is correct. `max` pinned the
+ # gauge at the highest value any celery process ever wrote, including dead ones, so a backlog
+ # that has since drained still reads as full. Widening the allowlist is meant to be watched on
+ # `not_allowlisted` going to zero, which `max` could never show. `observe.py` reaches the same
+ # end by pushing its gauges under one job name.
+ multiprocess_mode="livemostrecent",
)
-@dataclass
+# Mutable by design: one pass accumulates counters into it as it walks the runs.
+@dataclass(frozen=False)
class FinalizerPass:
runs_scanned: int = 0
completed: int = 0
@@ -84,6 +89,7 @@ class FinalizerPass:
held: int = 0
errored: int = 0
gated: int = 0
+ not_allowlisted: int = 0
stamped_participations: int = 0
invalidated_teams: int = 0
@@ -124,8 +130,8 @@ def finalize_backfill_runs() -> FinalizerPass:
"""One finalizer pass. Returns a summary so callers/tests can assert without scraping logs."""
result = FinalizerPass()
if not settings.BEHAVIORAL_BACKFILL_FINALIZER_ENABLED:
- # Reset rather than leave the gauge frozen at its last value: multiprocess_mode="max" keeps
- # a stale reading alive fleet-wide until the process recycles.
+ # Reset rather than leave the gauge frozen at its last value: a reason left unwritten while
+ # the finalizer is off keeps reporting whatever the last enabled pass observed.
_publish_held_runs(result)
return result
@@ -157,18 +163,25 @@ def finalize_backfill_runs() -> FinalizerPass:
# rather than bounding a sort, and neither kind pays for the other's parked backlog.
kinds = _finalizable_kinds()
per_kind = max(1, settings.BEHAVIORAL_BACKFILL_FINALIZER_MAX_RUNS_PER_PASS // len(kinds))
- observed = [
- row
- for kind in kinds
- for row in CohortBackfillRun.objects.unscoped()
- .filter(
+ allowlist = parse_run_allowlist(settings.BEHAVIORAL_BACKFILL_FINALIZER_RUN_ALLOWLIST)
+ observed: list[tuple[UUID, int]] = []
+ for kind in kinds:
+ discovered = CohortBackfillRun.objects.unscoped().filter(
backfill_kind=kind,
status=CohortBackfillRunStatus.RECONCILING,
reconcile_observed_at__isnull=False,
)
- .order_by("reconcile_observed_at")
- .values_list("id", "team_id")[:per_kind]
- ]
+ if allowlist is not None:
+ # Filtered in SQL, not in Python afterwards. The `[:per_kind]` slice below applies in the
+ # database, so a post-filter would let an excluded backlog consume the whole budget and
+ # starve the verified runs — the same starvation the per-kind split above guards against.
+ #
+ # Count the exclusions rather than leaving them invisible: the filter holds these runs in
+ # `reconciling` without touching `result.held`, so nothing else would report how much is
+ # waiting on the allowlist being widened.
+ result.not_allowlisted += discovered.exclude(id__in=allowlist).count()
+ discovered = discovered.filter(id__in=allowlist)
+ observed.extend(discovered.order_by("reconcile_observed_at").values_list("id", "team_id")[:per_kind])
teams_to_invalidate: set[int] = set()
for run_id, team_id in observed:
@@ -202,6 +215,7 @@ def _publish_held_runs(result: FinalizerPass) -> None:
HELD_RUNS_GAUGE.labels(reason="shortfall").set(result.held)
HELD_RUNS_GAUGE.labels(reason="error").set(result.errored)
HELD_RUNS_GAUGE.labels(reason="gated").set(result.gated)
+ HELD_RUNS_GAUGE.labels(reason="not_allowlisted").set(result.not_allowlisted)
def _finalize_one_run(run_id: UUID, team_id: int, result: FinalizerPass) -> bool:
diff --git a/products/cohorts/backend/backfill/inventory.py b/products/cohorts/backend/backfill/inventory.py
new file mode 100644
index 000000000000..55773b17d82c
--- /dev/null
+++ b/products/cohorts/backend/backfill/inventory.py
@@ -0,0 +1,350 @@
+"""Classifies active backfill runs so an operator can drain the wedged ones.
+
+An active run is not just work in progress: it holds one of the partial uniqueness slots
+(``cohort_bfr_active_cohort_kind_uq``, ``cohort_bfr_active_team_kind_uq``), so a run that can never
+reach a terminal status blocks its cohort or team from ever backfilling again. Nothing today can tell
+those apart from a run that is simply slow, and `observe.py`'s gauges count runs per status without
+saying which ones are stuck.
+
+Every run gets exactly one classification answering *what is it waiting on*. Age is a filter callers
+compose on top rather than a bucket of its own, so ``finalizable`` stays a byte-for-byte mirror of the
+finalizer's discovery predicate: the operator's verified list has to be exactly the set the finalizer
+will stamp, and a "stale" bucket would swallow old runs out of every other bucket.
+"""
+
+from collections.abc import Sequence
+from datetime import datetime, timedelta
+from typing import Any, Literal, get_args
+from uuid import UUID
+
+from django.conf import settings
+from django.db.models import Count, Max, Q
+from django.utils import timezone as django_timezone
+
+from posthog.dataclasses import frozen
+
+from products.cohorts.backend.backfill.allowlist import parse_run_allowlist
+from products.cohorts.backend.models.backfill import (
+ ACTIVE_COHORT_BACKFILL_RUN_STATUSES,
+ CohortBackfillChunk,
+ CohortBackfillChunkStatus,
+ CohortBackfillKind,
+ CohortBackfillRun,
+ CohortBackfillRunStatus,
+ CohortBackfillScope,
+)
+
+# The chunk tallies a run needs when it has no chunk rows yet: the grouped chunk query below only
+# emits a row per run that has chunks, so runs missing from it fall back to these zeros.
+_EMPTY_CHUNK_TALLY: dict[str, Any] = {
+ "chunks_total": 0,
+ "chunks_confirmed": 0,
+ "chunks_failed_exhausted": 0,
+ "chunk_last_progress_at": None,
+}
+
+RunClassification = Literal[
+ "orphaned",
+ "finalizable",
+ "awaiting-observation",
+ "seeding-stalled",
+ "seeding-healthy",
+ "blocked",
+ "awaiting-boundary",
+]
+
+RUN_CLASSIFICATIONS: tuple[RunClassification, ...] = get_args(RunClassification)
+
+# Classifications a `terminalize` sweep may cancel without extra opt-in. `seeding-stalled` and
+# `orphaned` are the two that can never reach a terminal status on their own; the rest are either
+# legitimately parked (`blocked`, `awaiting-boundary` — targetable, but only alongside an age cutoff)
+# or still owned by the seeder.
+DEFAULT_TERMINALIZE_CLASSIFICATIONS: tuple[RunClassification, ...] = ("seeding-stalled", "orphaned")
+
+# Only meaningful together with an age cutoff: these are parked by design, not broken.
+AGE_GATED_TERMINALIZE_CLASSIFICATIONS: tuple[RunClassification, ...] = ("blocked", "awaiting-boundary")
+
+# Runs the seeder is still working: one is scanning chunks, the other is waiting to be observed.
+# Canceling either races a live worker instead of freeing a stuck slot, and it discards seeding
+# progress the run would otherwise finish, so it takes an explicit opt-in. `finalizable` needs its
+# own opt-in for the mirror-image reason: that work is already *done*.
+SEEDER_OWNED_CLASSIFICATIONS: tuple[RunClassification, ...] = ("awaiting-observation", "seeding-healthy")
+
+# Mirrors `SEEDER_MAX_CHUNK_ATTEMPTS`'s envconfig default (rust/cohort-seeder/src/config.rs). Django
+# cannot read the seeder's config, so this is a knob on the command rather than a shared setting.
+DEFAULT_MAX_CHUNK_ATTEMPTS = 5
+
+
+@frozen
+class RunFacts:
+ """Everything ``classify_run`` reads.
+
+ Plain values only: no ORM object reaches the classifier, so the predicates are unit-testable
+ without a database and cannot accidentally issue a query per run.
+ """
+
+ status: str
+ scope: str
+ cohort_id: int | None
+ participations_total: int
+ participations_open: int
+ live_participation_cohorts: int
+ reconcile_observed_at: datetime | None
+ boundary_established_at: datetime | None
+ chunks_planned_at: datetime | None
+ chunks_total: int
+ chunks_unconfirmed: int
+ chunks_failed_exhausted: int
+ chunk_last_progress_at: datetime | None
+ now: datetime
+ stalled_after: timedelta
+
+
+@frozen
+class RunInventoryRow:
+ run_id: UUID
+ team_id: int
+ backfill_kind: str
+ scope: str
+ status: str
+ trigger_kind: str
+ cohort_id: int | None
+ classification: RunClassification
+ finalizer_gated: bool
+ allowlisted: bool
+ created_at: datetime
+ updated_at: datetime
+ reconcile_observed_at: datetime | None
+ participations_total: int
+ participations_open: int
+ participations_stamped: int
+ participations_superseded: int
+ chunks_total: int
+ chunks_confirmed: int
+ chunks_failed_exhausted: int
+ chunk_last_progress_at: datetime | None
+ evidence: str
+ blocked_reason: str
+ error: str
+
+
+def classify_run(facts: RunFacts) -> RunClassification:
+ """The single bucket a run belongs to. Raises on a terminal status: callers filter to active."""
+ if facts.status not in ACTIVE_COHORT_BACKFILL_RUN_STATUSES:
+ raise ValueError(f"{facts.status} is not an active backfill run status")
+
+ if _orphan_evidence(facts):
+ return "orphaned"
+
+ if facts.status == CohortBackfillRunStatus.RECONCILING:
+ return "finalizable" if facts.reconcile_observed_at is not None else "awaiting-observation"
+
+ if facts.status == CohortBackfillRunStatus.SEEDING:
+ return "seeding-stalled" if _stall_evidence(facts) else "seeding-healthy"
+
+ if facts.status == CohortBackfillRunStatus.BLOCKED:
+ return "blocked"
+
+ return "awaiting-boundary"
+
+
+def classification_evidence(facts: RunFacts) -> str:
+ """Why a run reads as orphaned or stalled, for the operator deciding whether to cancel it."""
+ return _orphan_evidence(facts) or _stall_evidence(facts) or ""
+
+
+def _orphan_evidence(facts: RunFacts) -> str:
+ """An orphan can never finalize regardless of status, so this precedes the status buckets."""
+ if facts.scope == CohortBackfillScope.COHORT and facts.cohort_id is None:
+ # The run's FK is SET_NULL, so a hard-deleted cohort leaves a cohort-scoped run pointing at
+ # nothing to stamp.
+ return "cohort-scoped run whose cohort was hard-deleted"
+ if facts.participations_total == 0:
+ # Participations CASCADE on Cohort, so a hard delete takes them with it.
+ return "no participation rows left"
+ if facts.live_participation_cohorts == 0:
+ return "every participating cohort is deleted"
+ if facts.participations_open == 0:
+ # `record_participation_partial` supersedes a participation while leaving the run active, so
+ # a run can hold its uniqueness slot with no work left to do.
+ return "every participation already resolved"
+ return ""
+
+
+def _stall_evidence(facts: RunFacts) -> str:
+ """Why a seeding run cannot make progress. Empty means it still can."""
+ if facts.chunks_failed_exhausted:
+ # Provably unclaimable, not a heuristic: `claim_next` only claims a pending/failed chunk with
+ # `attempts < max`, and the run's CAS out of `seeding` requires every chunk confirmed. Such a
+ # run stays in `seeding` forever.
+ return f"{facts.chunks_failed_exhausted} chunk(s) failed at the attempt cap with an expired lease"
+
+ cutoff = facts.now - facts.stalled_after
+ if facts.chunks_planned_at is None:
+ if facts.boundary_established_at is not None and facts.boundary_established_at < cutoff:
+ return "boundary established but no chunks planned"
+ return ""
+
+ if facts.chunks_total == 0:
+ # A run whose conditions plan no days legitimately stamps `chunks_planned_at` with zero
+ # chunks and waits for the completion sweep, so this only reads as stalled once that sweep
+ # has had time to run.
+ if facts.chunks_planned_at < cutoff:
+ return "chunks planned but none exist"
+ return ""
+ if facts.chunks_unconfirmed and (facts.chunk_last_progress_at is None or facts.chunk_last_progress_at < cutoff):
+ return f"{facts.chunks_unconfirmed} unconfirmed chunk(s) with no progress since the cutoff"
+ return ""
+
+
+def collect_run_inventory(
+ *,
+ team_id: int | None = None,
+ kinds: Sequence[str] | None = None,
+ statuses: Sequence[str] | None = None,
+ classifications: Sequence[RunClassification] | None = None,
+ run_ids: Sequence[UUID] | None = None,
+ stalled_after: timedelta,
+ older_than: timedelta | None = None,
+ max_chunk_attempts: int = DEFAULT_MAX_CHUNK_ATTEMPTS,
+ now: datetime | None = None,
+) -> list[RunInventoryRow]:
+ """Every active run matching the filters, classified, oldest first.
+
+ The scan is cross-team on purpose, like the finalizer's own discovery: the verified list has to
+ cover every team the finalizer will stamp, and a per-team read would silently produce a subset.
+ """
+ now = now or django_timezone.now()
+ allowlist = parse_run_allowlist(settings.BEHAVIORAL_BACKFILL_FINALIZER_RUN_ALLOWLIST)
+ person_readiness_off = not settings.BEHAVIORAL_BACKFILL_PERSON_READINESS_ENABLED
+
+ queryset = CohortBackfillRun.objects.unscoped().filter(status__in=statuses or ACTIVE_COHORT_BACKFILL_RUN_STATUSES)
+ if team_id is not None:
+ queryset = queryset.filter(team_id=team_id)
+ if kinds:
+ queryset = queryset.filter(backfill_kind__in=kinds)
+ if run_ids:
+ queryset = queryset.filter(id__in=run_ids)
+ if older_than is not None:
+ queryset = queryset.filter(created_at__lt=now - older_than)
+
+ # Annotate the per-run tallies rather than walking the relations: the prod active set is
+ # dominated by blocked runs, and an N+1 here makes the command unusable mid-cleanup. Only the
+ # participation aggregates are joined here; the chunk aggregates come from a separate grouped
+ # query below, because joining both `run_cohorts` and `chunks` in one SELECT multiplies into
+ # one intermediate row per participation-chunk pair, which a large team run turns into a heavy
+ # sort even though `distinct=True` keeps the counts right.
+ runs = list(
+ queryset.annotate(
+ participations_total=Count("run_cohorts", distinct=True),
+ participations_stamped=Count("run_cohorts", filter=Q(run_cohorts__stamped_at__isnull=False), distinct=True),
+ participations_superseded=Count(
+ "run_cohorts", filter=Q(run_cohorts__superseded_at__isnull=False), distinct=True
+ ),
+ live_participation_cohorts=Count(
+ "run_cohorts", filter=Q(run_cohorts__cohort__deleted=False), distinct=True
+ ),
+ ).order_by("created_at")
+ )
+
+ # One relation per query, so each aggregate stays linear in the chunk count. Keyed by run id and
+ # merged back below; runs with no chunks are simply absent and fall back to `_EMPTY_CHUNK_TALLY`.
+ chunk_tallies = (
+ CohortBackfillChunk.objects.unscoped()
+ .filter(run_id__in=[run.id for run in runs])
+ .values("run_id")
+ .annotate(
+ chunks_total=Count("id"),
+ chunks_confirmed=Count("id", filter=Q(status=CohortBackfillChunkStatus.CONFIRMED)),
+ chunks_failed_exhausted=Count(
+ "id",
+ filter=Q(status=CohortBackfillChunkStatus.FAILED, attempts__gte=max_chunk_attempts)
+ & (Q(lease_expires_at__isnull=True) | Q(lease_expires_at__lt=now)),
+ ),
+ chunk_last_progress_at=Max("updated_at"),
+ )
+ )
+ chunks_by_run = {tally["run_id"]: tally for tally in chunk_tallies}
+
+ inventory: list[RunInventoryRow] = []
+ for run in runs:
+ chunks = chunks_by_run.get(run.id, _EMPTY_CHUNK_TALLY)
+ facts = RunFacts(
+ status=run.status,
+ scope=run.scope,
+ cohort_id=run.cohort_id,
+ participations_total=run.participations_total,
+ participations_open=run.participations_total - run.participations_superseded,
+ live_participation_cohorts=run.live_participation_cohorts,
+ reconcile_observed_at=run.reconcile_observed_at,
+ boundary_established_at=run.boundary_established_at,
+ chunks_planned_at=run.chunks_planned_at,
+ chunks_total=chunks["chunks_total"],
+ chunks_unconfirmed=chunks["chunks_total"] - chunks["chunks_confirmed"],
+ chunks_failed_exhausted=chunks["chunks_failed_exhausted"],
+ chunk_last_progress_at=chunks["chunk_last_progress_at"],
+ now=now,
+ stalled_after=stalled_after,
+ )
+ classification = classify_run(facts)
+ if classifications and classification not in classifications:
+ continue
+ inventory.append(
+ RunInventoryRow(
+ run_id=run.id,
+ team_id=run.team_id,
+ backfill_kind=run.backfill_kind,
+ scope=run.scope,
+ status=run.status,
+ trigger_kind=run.trigger_kind,
+ cohort_id=run.cohort_id,
+ classification=classification,
+ finalizer_gated=person_readiness_off and run.backfill_kind == CohortBackfillKind.PERSON_PROPERTY,
+ allowlisted=allowlist is None or run.id in allowlist,
+ created_at=run.created_at,
+ updated_at=run.updated_at,
+ reconcile_observed_at=run.reconcile_observed_at,
+ participations_total=facts.participations_total,
+ participations_open=facts.participations_open,
+ participations_stamped=run.participations_stamped,
+ participations_superseded=run.participations_superseded,
+ chunks_total=facts.chunks_total,
+ chunks_confirmed=chunks["chunks_confirmed"],
+ chunks_failed_exhausted=facts.chunks_failed_exhausted,
+ chunk_last_progress_at=facts.chunk_last_progress_at,
+ evidence=classification_evidence(facts),
+ blocked_reason=run.blocked_reason,
+ error=run.error,
+ )
+ )
+ return inventory
+
+
+def summarize_inventory(rows: Sequence[RunInventoryRow]) -> dict[RunClassification, int]:
+ """Counts per classification, every bucket present so a drained one reads as 0, not absent."""
+ summary: dict[RunClassification, int] = dict.fromkeys(RUN_CLASSIFICATIONS, 0)
+ for row in rows:
+ summary[row.classification] += 1
+ return summary
+
+
+def stampable_now(rows: Sequence[RunInventoryRow]) -> list[RunInventoryRow]:
+ """The runs the finalizer would stamp the moment it is enabled, oldest observation first.
+
+ Excludes runs held by the person readiness gate: they are ``finalizable`` by column but invisible
+ to the finalizer's kind filter, so verifying one now and putting it on the allowlist would stamp
+ it much later, whenever that gate opens.
+ """
+ stampable = [row for row in rows if row.classification == "finalizable" and not row.finalizer_gated]
+ # `reconcile_observed_at` is non-null for every `finalizable` row; the fallback keeps mypy honest.
+ return sorted(stampable, key=lambda row: row.reconcile_observed_at or row.created_at)
+
+
+def allowlist_env_line(rows: Sequence[RunInventoryRow]) -> str:
+ """The paste-ready allowlist line for the runs above.
+
+ Emits ``none`` rather than an empty value when there is nothing to stamp: an empty value is read
+ as "every run", which is the opposite of what an operator who found no verified runs means.
+ """
+ run_ids = ",".join(str(row.run_id) for row in rows)
+ return f"BEHAVIORAL_BACKFILL_FINALIZER_RUN_ALLOWLIST={run_ids or 'none'}"
diff --git a/products/cohorts/backend/backfill/runs.py b/products/cohorts/backend/backfill/runs.py
index c1f7860bec6e..5dfd94221c30 100644
--- a/products/cohorts/backend/backfill/runs.py
+++ b/products/cohorts/backend/backfill/runs.py
@@ -2,6 +2,7 @@ from collections.abc import Iterable
from datetime import UTC, datetime, timedelta
from enum import StrEnum
from typing import Any
+from uuid import UUID
from django.conf import settings
from django.db import IntegrityError, transaction
@@ -739,3 +740,103 @@ def supersede_active_runs(team_id: int, cohort_ids: Iterable[int], *, kind: Coho
.filter(id__in=[participation_id for participation_id, _, _ in targets], superseded_at__isnull=True)
.update(superseded_at=Now(), error=error)
)
+
+
+@frozen
+class CancelOutcome:
+ cancelled_run_ids: tuple[UUID, ...] = ()
+ superseded_participations: int = 0
+ # (run_id, "stamped" | "finalizable" | "not_active")
+ refused: tuple[tuple[UUID, str], ...] = ()
+
+
+def cancel_runs(targets: Iterable[tuple[UUID, int]], *, reason: str, allow_finalizable: bool = False) -> CancelOutcome:
+ """Terminalize ``(run_id, team_id)`` pairs to ``cancelled`` on an operator's behalf.
+
+ This is the manual counterpart to ``supersede_active_runs``: an automatic writer reacting to a
+ cohort edit wants that one, which records *why* the backfill stopped mattering. ``cancelled``
+ means a person decided the run would never finish, so it stays out of signals, tasks, and request
+ paths. Its purpose is releasing the partial uniqueness slot an active run holds, which is what
+ lets the cohort or team be backfilled again.
+
+ Callers pass the team alongside each run rather than a bare id, so every query here is team
+ scoped and the sweep never reads run rows across teams by id.
+
+ Writes nothing beyond the run and its unresolved participations. No chunk write, because a chunk
+ under a live lease is fenced on ``claim_epoch`` and an unfenced update from here would race the
+ worker's own; the seeder's claim, plan, and CAS queries all require an active run status, so
+ canceling is already enough to stop it. No cache invalidation either, because no readiness stamp
+ is written and there is nothing stale to drop.
+ """
+ cancelled: list[UUID] = []
+ refused: list[tuple[UUID, str]] = []
+ participations = 0
+ for run_id, team_id in targets:
+ # One transaction per run. A sweep of fifty must not hold every run's lock at once: the
+ # cohort save path takes the same locks through `supersede_active_runs`, and a long
+ # multi-run transaction here would block saves for its whole duration.
+ with transaction.atomic():
+ # Same lock target as the finalizer's `_finalize_one_run`, so cancel and finalize
+ # serialize on the run row instead of racing. Deliberately not `skip_locked`: an
+ # operator needs a definite outcome per run, and the wait is bounded by one finalizer
+ # transaction.
+ run = (
+ CohortBackfillRun.objects.for_team(team_id)
+ .select_for_update(of=("self",))
+ .filter(id=run_id, status__in=ACTIVE_COHORT_BACKFILL_RUN_STATUSES)
+ .first()
+ )
+ if run is None:
+ refused.append((run_id, "not_active"))
+ continue
+
+ open_participations = CohortBackfillRunCohort.objects.for_team(team_id).filter(
+ run_id=run_id, superseded_at__isnull=True
+ )
+ # Re-read under the lock rather than trusting the inventory the operator looked at: the
+ # seeder may have observed the run since, and canceling one the finalizer would
+ # legitimately complete throws away a finished backfill. A run whose participations are
+ # all superseded is not that: the finalizer would only terminalize it, so refusing it
+ # would strand it holding its uniqueness slot with nothing able to release it.
+ if (
+ not allow_finalizable
+ and run.status == CohortBackfillRunStatus.RECONCILING
+ and run.reconcile_observed_at is not None
+ and open_participations.exists()
+ ):
+ refused.append((run_id, "finalizable"))
+ continue
+
+ if (
+ CohortBackfillRunCohort.objects.for_team(team_id)
+ .filter(run_id=run_id, stamped_at__isnull=False)
+ .exists()
+ ):
+ # A stamp is one way and the flags service already reads it as proof that
+ # `cohort_membership` is populated. Canceling behind one would leave the cohort
+ # marked ready with a run row claiming the backfill was abandoned.
+ refused.append((run_id, "stamped"))
+ continue
+
+ # Run row before participation rows, matching the ordering documented in
+ # `supersede_active_runs`; the reverse deadlocks against the finalizer.
+ CohortBackfillRun.objects.for_team(team_id).filter(id=run_id).update(
+ status=CohortBackfillRunStatus.CANCELLED, finished_at=Now(), error=reason
+ )
+ participations += open_participations.filter(stamped_at__isnull=True).update(
+ superseded_at=Now(), error=reason
+ )
+ cancelled.append(run_id)
+ logger.info(
+ "cohort_backfill_run_cancelled",
+ run_id=str(run_id),
+ team_id=team_id,
+ previous_status=run.status,
+ reason=reason,
+ )
+
+ return CancelOutcome(
+ cancelled_run_ids=tuple(cancelled),
+ superseded_participations=participations,
+ refused=tuple(refused),
+ )
diff --git a/products/cohorts/backend/backfill/test/test_finalize.py b/products/cohorts/backend/backfill/test/test_finalize.py
index 1864a04e3ad0..35f682719005 100644
--- a/products/cohorts/backend/backfill/test/test_finalize.py
+++ b/products/cohorts/backend/backfill/test/test_finalize.py
@@ -1,4 +1,5 @@
import importlib
+from datetime import timedelta
from posthog.test.base import BaseTest
from unittest import mock
@@ -376,3 +377,87 @@ class TestBackfillFinalizer(BaseTest):
self.assertEqual(
mock_logger.error.call_args[0][0], "cohort_backfill_finalizer_cohort_scoped_run_participation_count"
)
+
+ @parameterized.expand([("unset", ""), ("all", "all"), ("uppercase", "ALL"), ("star", "*")])
+ def test_run_allowlist_keywords_lift_the_restriction(self, _name: str, raw: str) -> None:
+ run, _ = self._make_run(["completed"])
+
+ with override_settings(BEHAVIORAL_BACKFILL_FINALIZER_RUN_ALLOWLIST=raw):
+ result = finalize_backfill_runs()
+
+ # A fail-closed reading of any of these would silently park the whole backlog on a
+ # deployment that never set the value.
+ run.refresh_from_db()
+ self.assertEqual(run.status, CohortBackfillRunStatus.COMPLETED)
+ self.assertEqual(result.not_allowlisted, 0)
+
+ def test_run_allowlist_excludes_a_run_that_is_not_listed(self) -> None:
+ listed, listed_cohorts = self._make_run(["completed"], scope=CohortBackfillScope.COHORT)
+ unlisted, unlisted_cohorts = self._make_run(["completed"], scope=CohortBackfillScope.COHORT)
+
+ with override_settings(BEHAVIORAL_BACKFILL_FINALIZER_RUN_ALLOWLIST=str(listed.id)):
+ result = finalize_backfill_runs()
+
+ listed.refresh_from_db()
+ unlisted.refresh_from_db()
+ listed_cohorts[0].refresh_from_db()
+ unlisted_cohorts[0].refresh_from_db()
+ self.assertEqual(listed.status, CohortBackfillRunStatus.COMPLETED)
+ self.assertIsNotNone(listed_cohorts[0].last_backfill_events_at)
+ # A stamp cannot be undone, so an unverified run must come out of the pass untouched.
+ self.assertEqual(unlisted.status, CohortBackfillRunStatus.RECONCILING)
+ self.assertIsNone(unlisted_cohorts[0].last_backfill_events_at)
+ self.assertEqual(result.not_allowlisted, 1)
+
+ @parameterized.expand(
+ [
+ ("none", "none", 0),
+ ("all_tokens_malformed", "not-a-uuid", 0),
+ ("one_good_token", None, 1),
+ ]
+ )
+ def test_run_allowlist_never_widens_on_a_bad_value(self, _name: str, raw: str | None, expected_stamps: int) -> None:
+ run, cohorts = self._make_run(["completed"])
+ # `None` stands for "the run's own id alongside a malformed token".
+ value = raw if raw is not None else f"{run.id},garbage"
+
+ with override_settings(BEHAVIORAL_BACKFILL_FINALIZER_RUN_ALLOWLIST=value):
+ finalize_backfill_runs()
+
+ cohorts[0].refresh_from_db()
+ # A typo in a restriction must not degrade into "every run": widening is the direction that
+ # cannot be walked back.
+ self.assertEqual(1 if cohorts[0].last_backfill_events_at else 0, expected_stamps)
+
+ @parameterized.expand([("unhyphenated", "hex"), ("uppercase", "upper")])
+ def test_run_allowlist_matches_a_pasted_id_in_any_form(self, _name: str, form: str) -> None:
+ run, cohorts = self._make_run(["completed"])
+ raw = run.id.hex if form == "hex" else str(run.id).upper()
+
+ with override_settings(BEHAVIORAL_BACKFILL_FINALIZER_RUN_ALLOWLIST=raw):
+ finalize_backfill_runs()
+
+ # Comparing raw strings would make an operator's pasted line silently match nothing.
+ cohorts[0].refresh_from_db()
+ self.assertIsNotNone(cohorts[0].last_backfill_events_at)
+
+ @override_settings(
+ BEHAVIORAL_BACKFILL_PERSON_READINESS_ENABLED=False,
+ BEHAVIORAL_BACKFILL_FINALIZER_MAX_RUNS_PER_PASS=2,
+ )
+ def test_excluded_runs_do_not_consume_the_per_kind_budget(self) -> None:
+ excluded = [self._make_run(["completed"], scope=CohortBackfillScope.COHORT)[0] for _ in range(5)]
+ CohortBackfillRun.objects.for_team(self.team.id).filter(id__in=[run.id for run in excluded]).update(
+ reconcile_observed_at=timezone.now() - timedelta(days=1)
+ )
+ allowlisted, cohorts = self._make_run(["completed"], scope=CohortBackfillScope.COHORT)
+
+ with override_settings(BEHAVIORAL_BACKFILL_FINALIZER_RUN_ALLOWLIST=str(allowlisted.id)):
+ finalize_backfill_runs()
+
+ # The budget slice is applied in SQL. A Python post-filter would let these five older
+ # exclusions eat the whole pass and the verified run would never be stamped.
+ allowlisted.refresh_from_db()
+ cohorts[0].refresh_from_db()
+ self.assertEqual(allowlisted.status, CohortBackfillRunStatus.COMPLETED)
+ self.assertIsNotNone(cohorts[0].last_backfill_events_at)
diff --git a/products/cohorts/backend/backfill/test/test_inventory.py b/products/cohorts/backend/backfill/test/test_inventory.py
new file mode 100644
index 000000000000..08b9a1ba6111
--- /dev/null
+++ b/products/cohorts/backend/backfill/test/test_inventory.py
@@ -0,0 +1,278 @@
+from datetime import date, timedelta
+
+from posthog.test.base import BaseTest
+
+from django.db import connection
+from django.test import SimpleTestCase, override_settings
+from django.test.utils import CaptureQueriesContext
+from django.utils import timezone
+
+from parameterized import parameterized
+
+from posthog.tasks.calculate_cohort import finalize_cohort_backfill_runs # noqa: F401 breaks an import cycle
+
+from products.cohorts.backend.backfill.finalize import finalize_backfill_runs
+from products.cohorts.backend.backfill.inventory import (
+ RUN_CLASSIFICATIONS,
+ RunFacts,
+ allowlist_env_line,
+ classify_run,
+ collect_run_inventory,
+ stampable_now,
+)
+from products.cohorts.backend.backfill.readiness import ensure_filters_shape_hash
+from products.cohorts.backend.models.backfill import (
+ ACTIVE_COHORT_BACKFILL_RUN_STATUSES,
+ CohortBackfillChunk,
+ CohortBackfillChunkStatus,
+ CohortBackfillKind,
+ CohortBackfillRun,
+ CohortBackfillRunCohort,
+ CohortBackfillRunStatus,
+ CohortBackfillScope,
+ CohortBackfillTrigger,
+)
+from products.cohorts.backend.models.cohort import Cohort, CohortType
+
+STALLED_AFTER = timedelta(hours=6)
+
+
+def _facts(**overrides: object) -> RunFacts:
+ defaults: dict[str, object] = {
+ "status": CohortBackfillRunStatus.SEEDING,
+ "scope": CohortBackfillScope.TEAM,
+ "cohort_id": None,
+ "participations_total": 1,
+ "participations_open": 1,
+ "live_participation_cohorts": 1,
+ "reconcile_observed_at": None,
+ "boundary_established_at": None,
+ "chunks_planned_at": None,
+ "chunks_total": 0,
+ "chunks_unconfirmed": 0,
+ "chunks_failed_exhausted": 0,
+ "chunk_last_progress_at": None,
+ "now": timezone.now(),
+ "stalled_after": STALLED_AFTER,
+ }
+ return RunFacts(**{**defaults, **overrides}) # type: ignore[arg-type]
+
+
+class TestClassifyRun(SimpleTestCase):
+ def test_seeding_run_with_chunks_at_the_attempt_cap_is_stalled(self) -> None:
+ now = timezone.now()
+
+ facts = _facts(
+ now=now,
+ chunks_planned_at=now - timedelta(hours=1),
+ chunks_total=3,
+ chunks_unconfirmed=1,
+ chunks_failed_exhausted=1,
+ chunk_last_progress_at=now - timedelta(minutes=1),
+ )
+
+ # Recent chunk progress must not rescue a run whose remaining chunk can never be reclaimed:
+ # this is the one provably-unclaimable population the cleanup exists to drain.
+ self.assertEqual(classify_run(facts), "seeding-stalled")
+
+ def test_seeding_run_with_recent_chunk_progress_is_healthy(self) -> None:
+ now = timezone.now()
+
+ facts = _facts(
+ now=now,
+ chunks_planned_at=now - timedelta(days=30),
+ chunks_total=100,
+ chunks_unconfirmed=40,
+ chunk_last_progress_at=now - timedelta(minutes=2),
+ )
+
+ # An old run seeding a long history is healthy, not a cancel target.
+ self.assertEqual(classify_run(facts), "seeding-healthy")
+
+ @parameterized.expand([("just_planned", 1, "seeding-healthy"), ("long_planned", 48, "seeding-stalled")])
+ def test_zero_chunk_run_is_healthy_until_the_completion_sweep_has_had_time(
+ self, _name: str, planned_hours_ago: int, expected: str
+ ) -> None:
+ now = timezone.now()
+
+ facts = _facts(now=now, chunks_planned_at=now - timedelta(hours=planned_hours_ago), chunks_total=0)
+
+ # A run whose conditions plan no days legitimately stamps `chunks_planned_at` with zero
+ # chunks. Without the grace period it reads as stalled the instant it is planned, and the
+ # default terminalize sweep cancels a backfill the seeder was about to complete.
+ self.assertEqual(classify_run(facts), expected)
+
+ @parameterized.expand(
+ [
+ ("cohort_hard_deleted", {"scope": CohortBackfillScope.COHORT, "cohort_id": None}),
+ ("no_participations", {"participations_total": 0}),
+ ("all_cohorts_deleted", {"live_participation_cohorts": 0}),
+ ("all_participations_resolved", {"participations_open": 0}),
+ ]
+ )
+ def test_orphan_precedes_the_status_buckets(self, _name: str, overrides: dict) -> None:
+ # Each of these can never finalize, so the status it happens to sit in is not the answer.
+ facts = _facts(status=CohortBackfillRunStatus.RECONCILING, reconcile_observed_at=timezone.now(), **overrides)
+
+ self.assertEqual(classify_run(facts), "orphaned")
+
+ @parameterized.expand([(status,) for status in ACTIVE_COHORT_BACKFILL_RUN_STATUSES])
+ def test_every_active_status_has_a_classification(self, status: str) -> None:
+ # A status added to the vocabulary without a bucket would otherwise fall through to
+ # `awaiting-boundary` and read as harmless.
+ self.assertIn(classify_run(_facts(status=status)), RUN_CLASSIFICATIONS)
+
+
+@override_settings(
+ REALTIME_COHORT_TEAM_ALLOWLIST="all",
+ BEHAVIORAL_BACKFILL_FINALIZER_ENABLED=True,
+ BEHAVIORAL_BACKFILL_PERSON_READINESS_ENABLED=True,
+ BEHAVIORAL_BACKFILL_FINALIZER_RUN_ALLOWLIST="all",
+)
+class TestCollectRunInventory(BaseTest):
+ def _cohort(self, name: str = "realtime", team_id: int | None = None) -> Cohort:
+ cohort = Cohort.objects.create(
+ team_id=team_id or self.team.id,
+ name=name,
+ cohort_type=CohortType.REALTIME,
+ filters={
+ "properties": {
+ "type": "AND",
+ "values": [
+ {
+ "type": "behavioral",
+ "key": "$pageview",
+ "event_type": "events",
+ "value": "performed_event_multiple",
+ "conditionHash": "hash",
+ "time_value": 7,
+ "time_interval": "day",
+ "operator": "gte",
+ "operator_value": 2,
+ }
+ ],
+ }
+ },
+ )
+ ensure_filters_shape_hash(cohort)
+ cohort.refresh_from_db()
+ return cohort
+
+ def _run(
+ self,
+ *,
+ team_id: int | None = None,
+ status: str = CohortBackfillRunStatus.SEEDING,
+ kind: str = CohortBackfillKind.BEHAVIORAL,
+ observed: bool = False,
+ cohort: Cohort | None = None,
+ ) -> CohortBackfillRun:
+ team_id = team_id or self.team.id
+ # Cohort scope so several runs can coexist: only one team-scoped run per kind may be active.
+ cohort = cohort or self._cohort(f"cohort-{CohortBackfillRun.objects.unscoped().count()}", team_id=team_id)
+ run = CohortBackfillRun.objects.for_team(team_id).create(
+ team_id=team_id,
+ backfill_kind=kind,
+ trigger_kind=CohortBackfillTrigger.COHORT_CREATED,
+ scope=CohortBackfillScope.COHORT,
+ cohort=cohort,
+ status=status,
+ reconcile_observed_at=timezone.now() if observed else None,
+ timezone="UTC",
+ )
+ CohortBackfillRunCohort.objects.for_team(team_id).create(
+ run=run,
+ team_id=team_id,
+ cohort=cohort,
+ filters_shape_hash=cohort.filters_shape_hash or "",
+ behavioral_filters_shape_hash=cohort.behavioral_filters_shape_hash or "",
+ person_filters_shape_hash=cohort.person_filters_shape_hash or "",
+ pinned_filters=cohort.filters,
+ reconcile_completed_at=timezone.now() if observed else None,
+ )
+ return run
+
+ def test_finalizable_rows_are_exactly_what_the_finalizer_stamps(self) -> None:
+ finalizable = self._run(status=CohortBackfillRunStatus.RECONCILING, observed=True)
+ unobserved = self._run(status=CohortBackfillRunStatus.RECONCILING, observed=False)
+
+ rows = {row.run_id: row.classification for row in collect_run_inventory(stalled_after=STALLED_AFTER)}
+ self.assertEqual(rows[finalizable.id], "finalizable")
+ self.assertEqual(rows[unobserved.id], "awaiting-observation")
+
+ # The bucket is only useful if it predicts the finalizer, so assert against the finalizer
+ # itself rather than restating its predicate.
+ finalize_backfill_runs()
+ finalizable.refresh_from_db()
+ unobserved.refresh_from_db()
+ self.assertEqual(finalizable.status, CohortBackfillRunStatus.COMPLETED)
+ self.assertEqual(unobserved.status, CohortBackfillRunStatus.RECONCILING)
+
+ def test_inventory_covers_every_team(self) -> None:
+ other_team = self.organization.teams.create(name="other")
+ mine = self._run()
+ theirs = self._run(team_id=other_team.id)
+
+ run_ids = {row.run_id for row in collect_run_inventory(stalled_after=STALLED_AFTER)}
+
+ # A per-team read would silently produce a verified list that is a subset of what the
+ # finalizer, which scans every team, will stamp.
+ self.assertEqual(run_ids, {mine.id, theirs.id})
+
+ def test_query_count_does_not_grow_with_the_run_count(self) -> None:
+ self._run()
+ with CaptureQueriesContext(connection) as one_run:
+ collect_run_inventory(stalled_after=STALLED_AFTER)
+
+ for _ in range(9):
+ self._run()
+ with CaptureQueriesContext(connection) as ten_runs:
+ collect_run_inventory(stalled_after=STALLED_AFTER)
+
+ # The prod active set is large, so an N+1 makes the command unusable mid-cleanup.
+ self.assertEqual(len(ten_runs.captured_queries), len(one_run.captured_queries))
+
+ def test_stalled_chunk_tally_respects_the_attempt_cap_and_lease(self) -> None:
+ run = self._run()
+ CohortBackfillRun.objects.for_team(self.team.id).filter(id=run.id).update(
+ chunks_planned_at=timezone.now() - timedelta(hours=1)
+ )
+ chunk = CohortBackfillChunk.objects.for_team(self.team.id).create(
+ run=run,
+ team_id=self.team.id,
+ day=date(2026, 1, 1),
+ status=CohortBackfillChunkStatus.FAILED,
+ attempts=5,
+ lease_expires_at=timezone.now() + timedelta(minutes=5),
+ )
+
+ # Still leased, so the seeder may yet reclaim it.
+ [row] = collect_run_inventory(stalled_after=STALLED_AFTER)
+ self.assertEqual(row.classification, "seeding-healthy")
+
+ CohortBackfillChunk.objects.for_team(self.team.id).filter(id=chunk.id).update(
+ lease_expires_at=timezone.now() - timedelta(minutes=5)
+ )
+ [row] = collect_run_inventory(stalled_after=STALLED_AFTER)
+ self.assertEqual(row.classification, "seeding-stalled")
+ self.assertEqual(row.chunks_failed_exhausted, 1)
+
+ @override_settings(BEHAVIORAL_BACKFILL_PERSON_READINESS_ENABLED=False)
+ def test_person_runs_held_by_the_readiness_gate_are_kept_off_the_allowlist_line(self) -> None:
+ behavioral = self._run(status=CohortBackfillRunStatus.RECONCILING, observed=True)
+ self._run(status=CohortBackfillRunStatus.RECONCILING, observed=True, kind=CohortBackfillKind.PERSON_PROPERTY)
+
+ rows = collect_run_inventory(stalled_after=STALLED_AFTER)
+
+ # Both are finalizable by column, but the finalizer's kind filter cannot see the person one,
+ # so putting it on the allowlist would stamp it whenever that gate opens instead of now.
+ self.assertEqual([row.run_id for row in stampable_now(rows)], [behavioral.id])
+ self.assertEqual(
+ allowlist_env_line(stampable_now(rows)),
+ f"BEHAVIORAL_BACKFILL_FINALIZER_RUN_ALLOWLIST={behavioral.id}",
+ )
+
+ def test_allowlist_line_says_none_when_there_is_nothing_to_stamp(self) -> None:
+ # An empty value reads as "every run", the opposite of what an operator who verified nothing
+ # means.
+ self.assertEqual(allowlist_env_line([]), "BEHAVIORAL_BACKFILL_FINALIZER_RUN_ALLOWLIST=none")
diff --git a/products/cohorts/backend/backfill/test/test_manage_cohort_backfill_runs_command.py b/products/cohorts/backend/backfill/test/test_manage_cohort_backfill_runs_command.py
new file mode 100644
index 000000000000..6dedbac9bc47
--- /dev/null
+++ b/products/cohorts/backend/backfill/test/test_manage_cohort_backfill_runs_command.py
@@ -0,0 +1,173 @@
+import io
+import re
+import json
+
+from posthog.test.base import BaseTest
+
+from django.core.management import CommandError, call_command
+from django.test import override_settings
+from django.utils import timezone
+
+from parameterized import parameterized
+
+from posthog.tasks.calculate_cohort import finalize_cohort_backfill_runs # noqa: F401 breaks an import cycle
+
+from products.cohorts.backend.backfill.finalize import finalize_backfill_runs
+from products.cohorts.backend.backfill.readiness import ensure_filters_shape_hash
+from products.cohorts.backend.models.backfill import (
+ CohortBackfillRun,
+ CohortBackfillRunCohort,
+ CohortBackfillRunStatus,
+ CohortBackfillScope,
+ CohortBackfillTrigger,
+)
+from products.cohorts.backend.models.cohort import Cohort, CohortType
+
+
+@override_settings(
+ REALTIME_COHORT_TEAM_ALLOWLIST="all",
+ BEHAVIORAL_BACKFILL_FINALIZER_ENABLED=True,
+ BEHAVIORAL_BACKFILL_PERSON_READINESS_ENABLED=True,
+ BEHAVIORAL_BACKFILL_FINALIZER_RUN_ALLOWLIST="all",
+)
+class TestManageCohortBackfillRuns(BaseTest):
+ def _cohort(self, name: str) -> Cohort:
+ cohort = Cohort.objects.create(
+ team=self.team,
+ name=name,
+ cohort_type=CohortType.REALTIME,
+ filters={
+ "properties": {
+ "type": "AND",
+ "values": [
+ {
+ "type": "behavioral",
+ "key": "$pageview",
+ "event_type": "events",
+ "value": "performed_event_multiple",
+ "conditionHash": f"hash-{name}",
+ "time_value": 7,
+ "time_interval": "day",
+ "operator": "gte",
+ "operator_value": 2,
+ }
+ ],
+ }
+ },
+ )
+ ensure_filters_shape_hash(cohort)
+ cohort.refresh_from_db()
+ return cohort
+
+ def _run(self, name: str, *, status: str, observed: bool = False) -> CohortBackfillRun:
+ cohort = self._cohort(name)
+ run = CohortBackfillRun.objects.for_team(self.team.id).create(
+ team_id=self.team.id,
+ trigger_kind=CohortBackfillTrigger.TEAM_ENABLEMENT,
+ scope=CohortBackfillScope.COHORT,
+ cohort=cohort,
+ status=status,
+ reconcile_observed_at=timezone.now() if observed else None,
+ timezone="UTC",
+ )
+ CohortBackfillRunCohort.objects.for_team(self.team.id).create(
+ run=run,
+ team_id=self.team.id,
+ cohort=cohort,
+ filters_shape_hash=cohort.filters_shape_hash or "",
+ behavioral_filters_shape_hash=cohort.behavioral_filters_shape_hash or "",
+ person_filters_shape_hash=cohort.person_filters_shape_hash or "",
+ pinned_filters=cohort.filters,
+ reconcile_completed_at=timezone.now() if observed else None,
+ )
+ return run
+
+ def _call(self, *args: str) -> str:
+ out = io.StringIO()
+ call_command("manage_cohort_backfill_runs", *args, stdout=out, stderr=out)
+ return out.getvalue()
+
+ def test_inventory_allowlist_line_round_trips_through_the_finalizer(self) -> None:
+ stampable = self._run("stampable", status=CohortBackfillRunStatus.RECONCILING, observed=True)
+ unobserved = self._run("unobserved", status=CohortBackfillRunStatus.RECONCILING, observed=False)
+
+ output = self._call("inventory")
+ [line] = re.findall(r"^BEHAVIORAL_BACKFILL_FINALIZER_RUN_ALLOWLIST=(.*)$", output, re.MULTILINE)
+
+ # Feed the emitted value back through the parser rather than eyeballing it: a line with a
+ # stray space, a trailing comma, or an empty value silently reads as "every run", which is
+ # the worst possible outcome of a change whose stamps cannot be undone.
+ with override_settings(BEHAVIORAL_BACKFILL_FINALIZER_RUN_ALLOWLIST=line):
+ finalize_backfill_runs()
+
+ stampable.refresh_from_db()
+ unobserved.refresh_from_db()
+ self.assertEqual(stampable.status, CohortBackfillRunStatus.COMPLETED)
+ self.assertEqual(unobserved.status, CohortBackfillRunStatus.RECONCILING)
+
+ def test_inventory_json_output_is_one_parseable_document(self) -> None:
+ self._run("seeding", status=CohortBackfillRunStatus.SEEDING)
+
+ payload = json.loads(self._call("inventory", "--format", "json"))
+
+ # Heading text leaking into the stream would break the machine-readable path the runbook
+ # depends on for recording the verified list.
+ self.assertEqual(len(payload["runs"]), 1)
+ self.assertEqual(payload["summary"]["seeding-healthy"], 1)
+
+ def test_terminalize_dry_run_writes_nothing(self) -> None:
+ run = self._run("orphan", status=CohortBackfillRunStatus.SEEDING)
+ CohortBackfillRunCohort.objects.for_team(self.team.id).filter(run_id=run.id).update(
+ superseded_at=timezone.now()
+ )
+
+ output = self._call("terminalize", "--classification", "orphaned")
+
+ run.refresh_from_db()
+ self.assertIn("Dry run", output)
+ self.assertEqual(run.status, CohortBackfillRunStatus.SEEDING)
+
+ self._call("terminalize", "--classification", "orphaned", "--live-run", "--yes")
+
+ run.refresh_from_db()
+ self.assertEqual(run.status, CohortBackfillRunStatus.CANCELLED)
+
+ def test_terminalize_needs_a_target(self) -> None:
+ # There is no cancel-everything-active mode, and a default that swept the whole active set
+ # would be irreversible for every team at once.
+ with self.assertRaisesMessage(CommandError, "--classification or --run-id"):
+ self._call("terminalize", "--live-run", "--yes")
+
+ def test_terminalize_aborts_over_the_max_runs_cap_without_writing(self) -> None:
+ runs = [self._run(f"orphan-{index}", status=CohortBackfillRunStatus.SEEDING) for index in range(3)]
+ CohortBackfillRunCohort.objects.for_team(self.team.id).filter(run_id__in=[run.id for run in runs]).update(
+ superseded_at=timezone.now()
+ )
+
+ with self.assertRaisesMessage(CommandError, "over the --max-runs cap"):
+ self._call("terminalize", "--classification", "orphaned", "--max-runs", "2", "--live-run", "--yes")
+
+ for run in runs:
+ run.refresh_from_db()
+ self.assertEqual(run.status, CohortBackfillRunStatus.SEEDING)
+
+ @parameterized.expand(
+ [
+ ("awaiting_observation", CohortBackfillRunStatus.RECONCILING),
+ ("seeding_healthy", CohortBackfillRunStatus.SEEDING),
+ ]
+ )
+ def test_terminalize_guards_seeder_owned_runs_named_by_run_id(self, _name: str, status: str) -> None:
+ run = self._run("live", status=status)
+
+ # Guarding only the --classification values would let a run id name a run the seeder is
+ # still working and skip every rule, canceling it out from under a live worker.
+ with self.assertRaisesMessage(CommandError, "still owned by the seeder"):
+ self._call("terminalize", "--run-id", str(run.id), "--live-run", "--yes")
+ run.refresh_from_db()
+ self.assertEqual(run.status, status)
+
+ self._call("terminalize", "--run-id", str(run.id), "--include-seeder-owned", "--live-run", "--yes")
+
+ run.refresh_from_db()
+ self.assertEqual(run.status, CohortBackfillRunStatus.CANCELLED)
diff --git a/products/cohorts/backend/backfill/test/test_runs.py b/products/cohorts/backend/backfill/test/test_runs.py
index dd9f3834b715..2af9118d5313 100644
--- a/products/cohorts/backend/backfill/test/test_runs.py
+++ b/products/cohorts/backend/backfill/test/test_runs.py
@@ -15,6 +15,7 @@ from products.cohorts.backend.backfill.runs import (
BackfillRunAttempt,
attempt_backfill_run_for_cohort,
attempt_person_backfill_run_for_cohort,
+ cancel_runs,
create_backfill_run_for_cohort,
create_person_backfill_run_for_cohort,
create_person_team_backfill_run,
@@ -708,3 +709,137 @@ class TestPersonBackfillRuns(BaseTest):
with self.settings(**{setting_name: False}), self.assertRaisesMessage(ValueError, expected_error):
create_person_team_backfill_run(self.team.id, "team_enablement", 30)
+
+
+@override_settings(
+ REALTIME_COHORT_TEAM_ALLOWLIST="all",
+ BEHAVIORAL_BACKFILL_MERGE_GATE_ATTESTED=True,
+ BEHAVIORAL_BACKFILL_DURABILITY_ATTESTED=True,
+)
+class TestCancelRuns(BaseTest):
+ def _cohort(self, event: str = "$pageview") -> Cohort:
+ return Cohort.objects.create(
+ team=self.team,
+ name=event,
+ cohort_type=CohortType.REALTIME,
+ filters={
+ "properties": {
+ "type": "AND",
+ "values": [
+ {
+ "type": "behavioral",
+ "key": event,
+ "event_type": "events",
+ "value": "performed_event_multiple",
+ "conditionHash": f"hash-{event}",
+ "time_value": 7,
+ "time_interval": "day",
+ "operator": "gte",
+ "operator_value": 2,
+ }
+ ],
+ }
+ },
+ )
+
+ @parameterized.expand(
+ [
+ ("cohort_scoped", CohortBackfillScope.COHORT),
+ ("team_scoped", CohortBackfillScope.TEAM),
+ ]
+ )
+ def test_cancel_frees_the_active_uniqueness_slot(self, _name: str, scope: str) -> None:
+ cohort = self._cohort()
+ if scope == CohortBackfillScope.COHORT:
+ run = create_backfill_run_for_cohort(self.team.id, cohort.id, "cohort_created")
+ else:
+ run = create_team_backfill_run(self.team.id, "team_enablement")
+ assert run is not None
+ CohortBackfillRun.objects.for_team(self.team.id).filter(id=run.id).update(
+ status=CohortBackfillRunStatus.SEEDING
+ )
+ self.assertIsNone(create_backfill_run_for_cohort(self.team.id, cohort.id, "cohort_edited"))
+
+ outcome = cancel_runs([(run.id, self.team.id)], reason="wedged in seeding")
+
+ run.refresh_from_db()
+ self.assertEqual(outcome.cancelled_run_ids, (run.id,))
+ self.assertEqual(run.status, CohortBackfillRunStatus.CANCELLED)
+ self.assertIsNotNone(run.finished_at)
+ self.assertEqual(run.error, "wedged in seeding")
+ # Releasing the partial unique constraint is the whole point: a run nobody can finish
+ # otherwise blocks its cohort or team from ever backfilling again.
+ self.assertIsNotNone(create_backfill_run_for_cohort(self.team.id, cohort.id, "cohort_edited"))
+
+ def test_cancel_refuses_a_run_whose_readiness_was_already_stamped(self) -> None:
+ cohort = self._cohort()
+ run = create_backfill_run_for_cohort(self.team.id, cohort.id, "cohort_created")
+ assert run is not None
+ CohortBackfillRunCohort.objects.for_team(self.team.id).filter(run_id=run.id).update(
+ stamped_at=datetime.now(UTC)
+ )
+
+ outcome = cancel_runs([(run.id, self.team.id)], reason="sweep")
+
+ run.refresh_from_db()
+ # A stamp is one way and the flags service already reads it, so a cancel behind one would
+ # leave the cohort marked ready by a run claiming it was abandoned.
+ self.assertEqual(outcome.refused, ((run.id, "stamped"),))
+ self.assertEqual(run.status, CohortBackfillRunStatus.AWAITING_BOUNDARY)
+
+ @parameterized.expand([("refused", False), ("allowed", True)])
+ def test_cancel_only_touches_a_finalizable_run_on_request(self, _name: str, allow: bool) -> None:
+ cohort = self._cohort()
+ run = create_backfill_run_for_cohort(self.team.id, cohort.id, "cohort_created")
+ assert run is not None
+ CohortBackfillRun.objects.for_team(self.team.id).filter(id=run.id).update(
+ status=CohortBackfillRunStatus.RECONCILING, reconcile_observed_at=datetime.now(UTC)
+ )
+
+ outcome = cancel_runs([(run.id, self.team.id)], reason="sweep", allow_finalizable=allow)
+
+ run.refresh_from_db()
+ # The seeder may have observed the run since the operator listed it, and this one is a
+ # finished backfill the finalizer would legitimately complete.
+ if allow:
+ self.assertEqual(outcome.cancelled_run_ids, (run.id,))
+ self.assertEqual(run.status, CohortBackfillRunStatus.CANCELLED)
+ else:
+ self.assertEqual(outcome.refused, ((run.id, "finalizable"),))
+ self.assertEqual(run.status, CohortBackfillRunStatus.RECONCILING)
+
+ def test_cancel_keeps_an_earlier_supersession_message(self) -> None:
+ cohort = self._cohort()
+ run = create_backfill_run_for_cohort(self.team.id, cohort.id, "cohort_created")
+ assert run is not None
+ supersede_active_runs(self.team.id, [cohort.id], kind=CohortBackfillKind.BEHAVIORAL)
+ CohortBackfillRun.objects.for_team(self.team.id).filter(id=run.id).update(
+ status=CohortBackfillRunStatus.SEEDING
+ )
+ participation = CohortBackfillRunCohort.objects.for_team(self.team.id).get(run_id=run.id)
+
+ cancel_runs([(run.id, self.team.id)], reason="operator sweep")
+
+ participation.refresh_from_db()
+ # The edit-time supersession is why this backfill stopped mattering; operator text must not
+ # overwrite that provenance.
+ self.assertEqual(participation.error, "Cohort definition changed during backfill")
+
+ def test_cancel_drains_an_observed_run_whose_participations_are_all_resolved(self) -> None:
+ cohort = self._cohort()
+ run = create_backfill_run_for_cohort(self.team.id, cohort.id, "cohort_created")
+ assert run is not None
+ CohortBackfillRunCohort.objects.for_team(self.team.id).filter(run_id=run.id).update(
+ superseded_at=datetime.now(UTC)
+ )
+ CohortBackfillRun.objects.for_team(self.team.id).filter(id=run.id).update(
+ status=CohortBackfillRunStatus.RECONCILING, reconcile_observed_at=datetime.now(UTC)
+ )
+
+ outcome = cancel_runs([(run.id, self.team.id)], reason="orphaned sweep")
+
+ run.refresh_from_db()
+ # The inventory classifies this `orphaned`, not `finalizable`, because the finalizer would
+ # only terminalize it. Refusing it here would leave nothing able to release its slot.
+ self.assertEqual(outcome.cancelled_run_ids, (run.id,))
+ self.assertEqual(run.status, CohortBackfillRunStatus.CANCELLED)
diff --git a/products/cohorts/backend/management/commands/manage_cohort_backfill_runs.py b/products/cohorts/backend/management/commands/manage_cohort_backfill_runs.py
new file mode 100644
index 000000000000..b05d23aff557
--- /dev/null
+++ b/products/cohorts/backend/management/commands/manage_cohort_backfill_runs.py
@@ -0,0 +1,334 @@
+"""Ops tooling for the realtime cohort backfill run set, meant for a toolbox pod.
+
+`inventory` lists every backfill run in an active status across all teams, says what each one is
+waiting on, and emits the paste-ready `BEHAVIORAL_BACKFILL_FINALIZER_RUN_ALLOWLIST` line for the runs
+the finalizer would stamp. `terminalize` cancels the ones that can never finish, releasing the
+uniqueness slot that otherwise blocks their cohort or team from backfilling again. Mutating actions
+are dry run by default.
+
+Order matters when turning the finalizer on, because a readiness stamp cannot be undone:
+
+ 1. Deploy with `BEHAVIORAL_BACKFILL_FINALIZER_RUN_ALLOWLIST` set to a verified list or `none`.
+ 2. Run `inventory` while the finalizer is still off, so the finalizable set holds still.
+ 3. Check each finalizable run by hand.
+ 4. `terminalize --classification seeding-stalled --classification orphaned --live-run`.
+ 5. Re-run `inventory` and set the allowlist line it prints.
+ 6. Turn on `BEHAVIORAL_BACKFILL_FINALIZER_ENABLED`, then watch
+ `posthog_cohort_backfill_finalizer_held_runs{reason="not_allowlisted"}` drain as the list widens.
+"""
+
+import sys
+import json
+from dataclasses import asdict
+from datetime import UTC, datetime, timedelta
+from typing import Any
+from uuid import UUID
+
+from django.conf import settings
+from django.core.management.base import BaseCommand, CommandError, CommandParser
+from django.core.serializers.json import DjangoJSONEncoder
+
+import structlog
+
+from products.cohorts.backend.backfill.allowlist import parse_run_allowlist
+from products.cohorts.backend.backfill.inventory import (
+ AGE_GATED_TERMINALIZE_CLASSIFICATIONS,
+ DEFAULT_MAX_CHUNK_ATTEMPTS,
+ DEFAULT_TERMINALIZE_CLASSIFICATIONS,
+ RUN_CLASSIFICATIONS,
+ SEEDER_OWNED_CLASSIFICATIONS,
+ RunInventoryRow,
+ allowlist_env_line,
+ collect_run_inventory,
+ stampable_now,
+ summarize_inventory,
+)
+from products.cohorts.backend.backfill.runs import cancel_runs
+from products.cohorts.backend.models.backfill import ACTIVE_COHORT_BACKFILL_RUN_STATUSES, CohortBackfillKind
+
+logger = structlog.get_logger(__name__)
+
+DEFAULT_REASON = "canceled via manage_cohort_backfill_runs"
+DEFAULT_STALLED_FOR_HOURS = 6
+MAX_RUNS_DEFAULT = 50
+PRINT_LIMIT = 50
+DRY_RUN_MESSAGE = "Dry run, nothing written. Re-run with --live-run to apply."
+
+
+class Command(BaseCommand):
+ help = "Inventory the active cohort backfill runs, and cancel the ones that can never finish."
+
+ def add_arguments(self, parser: CommandParser) -> None:
+ subparsers = parser.add_subparsers(dest="action", required=True)
+
+ inventory = subparsers.add_parser("inventory", help="List and classify the active runs.")
+ self._add_target_args(inventory)
+ inventory.add_argument("--format", choices=["table", "json"], default="table")
+ inventory.add_argument("--limit", type=int, default=None, help="Cap the runs listed per section.")
+
+ terminalize = subparsers.add_parser("terminalize", help="Cancel the targeted runs.")
+ self._add_target_args(terminalize)
+ terminalize.add_argument("--reason", default=DEFAULT_REASON, help="Recorded on each canceled run.")
+ terminalize.add_argument(
+ "--include-finalizable",
+ action="store_true",
+ help="Also cancel runs the finalizer would stamp. Throws away a finished backfill.",
+ )
+ terminalize.add_argument(
+ "--include-seeder-owned",
+ action="store_true",
+ help="Also cancel runs the seeder is still working. Throws away seeding progress.",
+ )
+ terminalize.add_argument("--live-run", action="store_true")
+ terminalize.add_argument("--yes", action="store_true", help="Skip the confirmation prompt.")
+ terminalize.add_argument("--max-runs", type=int, default=MAX_RUNS_DEFAULT)
+
+ def _add_target_args(self, parser: CommandParser) -> None:
+ parser.add_argument("--team-id", type=int, default=None)
+ parser.add_argument("--kind", action="append", choices=list(CohortBackfillKind.values), default=None)
+ parser.add_argument(
+ "--status",
+ action="append",
+ choices=[status.value for status in ACTIVE_COHORT_BACKFILL_RUN_STATUSES],
+ default=None,
+ help="Only active statuses: this command drains the active set.",
+ )
+ parser.add_argument("--classification", action="append", choices=list(RUN_CLASSIFICATIONS), default=None)
+ parser.add_argument("--run-id", action="append", default=None)
+ parser.add_argument("--older-than-hours", type=float, default=None, help="Only runs created before this.")
+ parser.add_argument(
+ "--stalled-for-hours",
+ type=float,
+ default=DEFAULT_STALLED_FOR_HOURS,
+ help="How long a seeding run may go without chunk progress before it reads as stalled.",
+ )
+ parser.add_argument(
+ "--max-chunk-attempts",
+ type=int,
+ default=DEFAULT_MAX_CHUNK_ATTEMPTS,
+ # Django cannot read the seeder's config, so the cap it retries chunks up to has to be
+ # repeated here. Pass the deployed value if it differs from the seeder's default.
+ help="The seeder's SEEDER_MAX_CHUNK_ATTEMPTS, used to spot chunks that can't be reclaimed.",
+ )
+
+ def handle(self, *args: Any, **options: Any) -> None:
+ if options["action"] == "inventory":
+ self._inventory(options)
+ return
+ self._terminalize(options)
+
+ # -- inventory --------------------------------------------------------------
+
+ def _inventory(self, options: dict[str, Any]) -> None:
+ rows = self._collect(options)
+ stampable = stampable_now(rows)
+ if options["format"] == "json":
+ # One document, no headings, so it pipes into jq.
+ self.stdout.write(
+ json.dumps(
+ {
+ "settings": self._settings_snapshot(),
+ "max_chunk_attempts": options["max_chunk_attempts"],
+ "summary": summarize_inventory(rows),
+ "runs": [asdict(row) for row in rows],
+ "allowlist_line": allowlist_env_line(stampable),
+ },
+ cls=DjangoJSONEncoder,
+ )
+ )
+ return
+
+ limit = PRINT_LIMIT if options["limit"] is None else options["limit"]
+ self.stdout.write(self.style.MIGRATE_HEADING("Finalizer settings"))
+ for name, value in self._settings_snapshot().items():
+ self.stdout.write(f" {name}={value}")
+ self.stdout.write(f" {self._classification_cap_line(options)}")
+
+ summary = summarize_inventory(rows)
+ teams = len({row.team_id for row in rows})
+ self.stdout.write(
+ self.style.MIGRATE_HEADING(f"\nActive runs by classification ({len(rows)} across {teams} team(s))")
+ )
+ for classification, count in summary.items():
+ self.stdout.write(f" {classification:<22}{count}")
+
+ self.stdout.write(
+ self.style.MIGRATE_HEADING(
+ f"\nFinalizable now ({len(stampable)}). These get stamped as soon as the finalizer is enabled."
+ )
+ )
+ # Never truncated, unlike every other section. These are the runs the allowlist line below
+ # carries, and a stamp cannot be undone, so the operator has to see each one to check it.
+ self._print_rows(stampable, len(stampable))
+
+ gated = [row for row in rows if row.classification == "finalizable" and row.finalizer_gated]
+ if gated:
+ self.stdout.write(
+ self.style.MIGRATE_HEADING(f"\nFinalizable but held by the person readiness gate ({len(gated)})")
+ )
+ self._print_rows(gated, limit)
+
+ candidates = [row for row in rows if row.classification in DEFAULT_TERMINALIZE_CLASSIFICATIONS]
+ self.stdout.write(self.style.MIGRATE_HEADING(f"\nCancel candidates ({len(candidates)})"))
+ self._print_rows(candidates, limit)
+
+ self.stdout.write(self.style.MIGRATE_HEADING("\nAllowlist line. Paste it after checking each run above."))
+ self.stdout.write(allowlist_env_line(stampable))
+
+ def _print_rows(self, rows: list[RunInventoryRow], limit: int) -> None:
+ for row in rows[:limit]:
+ line = (
+ f" run={row.run_id} team={row.team_id} kind={row.backfill_kind} scope={row.scope} "
+ f"cohort={row.cohort_id if row.cohort_id is not None else '-'} status={row.status} "
+ f"age={_age(row.created_at)} parts={row.participations_open}/{row.participations_total} "
+ f"chunks={row.chunks_confirmed}/{row.chunks_total}"
+ )
+ if row.evidence:
+ line += f" why={row.evidence}"
+ self.stdout.write(line)
+ if len(rows) > limit:
+ self.stdout.write(f" ... and {len(rows) - limit} more")
+
+ # -- terminalize ------------------------------------------------------------
+
+ def _terminalize(self, options: dict[str, Any]) -> None:
+ classifications = options["classification"]
+ run_ids = options["run_id"]
+ if not classifications and not run_ids:
+ raise CommandError(
+ "Pass --classification or --run-id. There is no cancel-everything mode. A good "
+ f"starting point is {' '.join(f'--classification {name}' for name in DEFAULT_TERMINALIZE_CLASSIFICATIONS)}"
+ )
+
+ rows = self._collect(options)
+ # Guard on what each targeted run actually is, not on what was asked for. Checking the
+ # `--classification` values alone would let `--run-id` name a run in a protected
+ # classification and skip every rule below.
+ for classification in sorted({row.classification for row in rows}):
+ if classification in SEEDER_OWNED_CLASSIFICATIONS and not options["include_seeder_owned"]:
+ raise CommandError(
+ f"{classification} runs are still owned by the seeder, so canceling one races a live "
+ "worker and discards seeding progress. Target seeding-stalled instead, or pass "
+ "--include-seeder-owned to stop live work deliberately."
+ )
+ if classification in AGE_GATED_TERMINALIZE_CLASSIFICATIONS and options["older_than_hours"] is None:
+ raise CommandError(f"{classification} runs are parked by design, so pass --older-than-hours too")
+ if classification == "finalizable" and not options["include_finalizable"]:
+ raise CommandError(
+ "finalizable runs are finished backfills the finalizer would stamp. "
+ "Pass --include-finalizable to throw that work away deliberately."
+ )
+
+ if not rows:
+ self.stdout.write("No runs matched. Run `inventory` to see what is active.")
+ return
+
+ # Abort before the prompt, not after: an operator who mistargeted should not be asked to
+ # confirm a sweep this command was never going to let through.
+ if len(rows) > options["max_runs"]:
+ raise CommandError(
+ f"{len(rows)} runs matched, over the --max-runs cap of {options['max_runs']}. "
+ "Narrow the targeting or raise the cap deliberately."
+ )
+
+ self.stdout.write(self.style.MIGRATE_HEADING(f"Runs to cancel ({len(rows)})"))
+ self._print_rows(rows, PRINT_LIMIT)
+
+ # The cap only shapes the `seeding-stalled` classification, so it is only worth flagging
+ # before the confirmation when one of those runs is in the cancel set.
+ if any(row.classification == "seeding-stalled" for row in rows):
+ self.stdout.write(f" {self._classification_cap_line(options)}")
+
+ if not options["live_run"]:
+ self.stdout.write(self.style.WARNING(DRY_RUN_MESSAGE))
+ return
+
+ self._confirm(f"Cancel {len(rows)} run(s)? Type 'cancel' to continue: ", "cancel", yes=options["yes"])
+
+ classification_by_run = {row.run_id: row.classification for row in rows}
+ outcome = cancel_runs(
+ [(row.run_id, row.team_id) for row in rows],
+ reason=options["reason"],
+ allow_finalizable=options["include_finalizable"],
+ )
+ for run_id in outcome.cancelled_run_ids:
+ logger.info(
+ "manage_cohort_backfill_runs_cancelled",
+ run_id=str(run_id),
+ classification=classification_by_run[run_id],
+ reason=options["reason"],
+ )
+ for run_id, refusal in outcome.refused:
+ self.stdout.write(self.style.WARNING(f" run={run_id} not canceled: {refusal}"))
+
+ self.stdout.write(
+ self.style.SUCCESS(
+ f"Canceled {len(outcome.cancelled_run_ids)} run(s), "
+ f"resolved {outcome.superseded_participations} participation(s), "
+ f"refused {len(outcome.refused)}."
+ )
+ )
+
+ # -- shared -----------------------------------------------------------------
+
+ def _collect(self, options: dict[str, Any]) -> list[RunInventoryRow]:
+ older_than_hours = options["older_than_hours"]
+ return collect_run_inventory(
+ team_id=options["team_id"],
+ kinds=options["kind"],
+ statuses=options["status"],
+ classifications=options["classification"],
+ run_ids=_parse_run_ids(options["run_id"]),
+ stalled_after=timedelta(hours=options["stalled_for_hours"]),
+ older_than=None if older_than_hours is None else timedelta(hours=older_than_hours),
+ max_chunk_attempts=options["max_chunk_attempts"],
+ )
+
+ def _classification_cap_line(self, options: dict[str, Any]) -> str:
+ # The cap Django classified against is invisible in the run listing otherwise, so a
+ # `seeding-stalled` reading looks identical whether it rests on the default or a value the
+ # operator passed. Surfacing it lets them catch a deployed SEEDER_MAX_CHUNK_ATTEMPTS the
+ # inventory undershot, which would misread a still-retryable chunk as provably wedged.
+ return (
+ f"max_chunk_attempts={options['max_chunk_attempts']} "
+ "(assumed seeder cap; pass --max-chunk-attempts if the deployed SEEDER_MAX_CHUNK_ATTEMPTS is higher)"
+ )
+
+ def _settings_snapshot(self) -> dict[str, Any]:
+ allowlist = parse_run_allowlist(settings.BEHAVIORAL_BACKFILL_FINALIZER_RUN_ALLOWLIST)
+ parsed = "every run" if allowlist is None else f"{len(allowlist)} run(s)"
+ return {
+ "BEHAVIORAL_BACKFILL_FINALIZER_ENABLED": settings.BEHAVIORAL_BACKFILL_FINALIZER_ENABLED,
+ "BEHAVIORAL_BACKFILL_PERSON_READINESS_ENABLED": settings.BEHAVIORAL_BACKFILL_PERSON_READINESS_ENABLED,
+ "BEHAVIORAL_BACKFILL_FINALIZER_MAX_RUNS_PER_PASS": settings.BEHAVIORAL_BACKFILL_FINALIZER_MAX_RUNS_PER_PASS,
+ "BEHAVIORAL_BACKFILL_FINALIZER_RUN_ALLOWLIST": (
+ f"{settings.BEHAVIORAL_BACKFILL_FINALIZER_RUN_ALLOWLIST} (matches {parsed})"
+ ),
+ }
+
+ # Mirrors `manage_warehouse_queue._confirm`.
+ 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.")
+
+
+def _parse_run_ids(raw_ids: list[str] | None) -> list[UUID] | None:
+ if not raw_ids:
+ return None
+ try:
+ return [UUID(raw) for raw in raw_ids]
+ except ValueError as error:
+ raise CommandError(f"--run-id must be a UUID: {error}")
+
+
+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"