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): harden realtime backfill observability and failure handling (#82769)

Gustavo H. Strassburger1186ed1e2142
diff --git a/posthog/tasks/calculate_cohort.py b/posthog/tasks/calculate_cohort.py
index e15381f51dff..3303ec97a015 100644
--- a/posthog/tasks/calculate_cohort.py
+++ b/posthog/tasks/calculate_cohort.py
@@ -25,11 +25,13 @@ from posthog.scoping_audit import skip_team_scope_audit
from posthog.tasks.utils import CeleryQueue
from products.cohorts.backend.backfill.finalize import finalize_backfill_runs
+from products.cohorts.backend.backfill.observe import publish_backfill_run_gauges
from products.cohorts.backend.backfill.runs import (
+ BackfillRefusalReason,
+ attempt_backfill_run_for_cohort,
+ attempt_person_backfill_run_for_cohort,
check_person_run_preconditions,
check_run_preconditions,
- create_backfill_run_for_cohort,
- create_person_backfill_run_for_cohort,
)
from products.cohorts.backend.models.backfill import CohortBackfillKind
from products.cohorts.backend.models.calculation_history import CohortCalculationHistory
@@ -919,6 +921,31 @@ COHORT_BACKFILL_TRIGGER_TASK_COUNTER = Counter(
labelnames=["backfill_kind", "outcome"],
)
+# Refusals grouped by the operator response they call for, not one label per reason: a budget
+# refusal means raise the budget or wait for in-flight runs, an occupied slot means an active run
+# already covers the cohort, and the rest are the cohort not being a candidate for this trigger.
+# Collapsing them into a single `refused`, as this used to, made the first two indistinguishable.
+# The full reason stays on the log line, so cardinality does not have to carry it.
+#
+# An occupied slot is the expected outcome of an ordinary backfill, not a wedge: a team-enablement
+# run covers every cohort on the team, and each cohort saved during one refuses this way. Read
+# `posthog_cohort_backfill_oldest_active_run_age_seconds` to tell a stuck run from normal progress.
+COHORT_BACKFILL_REFUSAL_OUTCOMES: dict[BackfillRefusalReason, str] = {
+ BackfillRefusalReason.OVER_BUDGET: "refused_over_budget",
+ BackfillRefusalReason.RUN_SLOT_OCCUPIED: "refused_slot_occupied",
+ BackfillRefusalReason.PARTICIPATION_ACTIVE: "refused_slot_occupied",
+ BackfillRefusalReason.SLOT_RACE: "refused_slot_occupied",
+ BackfillRefusalReason.TEAM_NOT_REALTIME: "refused_ineligible",
+ BackfillRefusalReason.COHORT_MISSING: "refused_ineligible",
+ BackfillRefusalReason.COHORT_INELIGIBLE: "refused_ineligible",
+ BackfillRefusalReason.INVALID_HORIZON: "refused_ineligible",
+ BackfillRefusalReason.PINNING_CAP_EXCEEDED: "refused_ineligible",
+ # Not transient: the sizing scan's read cap is deterministic, so a cohort that trips it trips it
+ # again on every later trigger until someone raises the limit. Nothing clears on its own.
+ BackfillRefusalReason.SIZING_SCAN_CAP_EXCEEDED: "refused_ineligible",
+ BackfillRefusalReason.DEFINITION_CHANGED: "refused_transient",
+}
+
# acks_late: a countdown message acked on receipt sits in one worker's memory for the whole window
# and dies with it, after the edit's supersession already ran. The creators refuse duplicates, so
@@ -972,19 +999,24 @@ def trigger_cohort_backfill_run_task(team_id: int, cohort_id: int, trigger_kind:
missing=missing,
)
return
- run = (
- create_person_backfill_run_for_cohort(team_id, cohort_id, trigger_kind)
+ attempt = (
+ attempt_person_backfill_run_for_cohort(team_id, cohort_id, trigger_kind)
if person
- else create_backfill_run_for_cohort(team_id, cohort_id, trigger_kind)
+ else attempt_backfill_run_for_cohort(team_id, cohort_id, trigger_kind)
)
+ run = attempt.run
if run is None:
- COHORT_BACKFILL_TRIGGER_TASK_COUNTER.labels(backfill_kind=backfill_kind, outcome="refused").inc()
+ # An unmapped reason falls back to the old flat `refused` rather than vanishing, so
+ # adding an enum member can never silently drop refusals out of the metric.
+ outcome = COHORT_BACKFILL_REFUSAL_OUTCOMES.get(attempt.reason, "refused") if attempt.reason else "refused"
+ COHORT_BACKFILL_TRIGGER_TASK_COUNTER.labels(backfill_kind=backfill_kind, outcome=outcome).inc()
logger.info(
"skipping_cohort_backfill_run_task",
cohort_id=cohort_id,
team_id=team_id,
trigger_kind=trigger_kind,
backfill_kind=backfill_kind,
+ refusal_reason=attempt.reason,
)
return
COHORT_BACKFILL_TRIGGER_TASK_COUNTER.labels(backfill_kind=backfill_kind, outcome="created").inc()
@@ -1010,6 +1042,17 @@ def trigger_cohort_backfill_run_task(team_id: int, cohort_id: int, trigger_kind:
raise
+@shared_task(ignore_result=True)
+def publish_cohort_backfill_run_gauges() -> None:
+ """Publish backfill run/chunk state for alerting.
+
+ Ungated on purpose, unlike ``finalize_cohort_backfill_runs``: a stalled run has to be alertable
+ while the finalizer is still dark, and the seeder's own metrics cannot see the transitions
+ Django owns.
+ """
+ publish_backfill_run_gauges()
+
+
@shared_task(ignore_result=True)
def finalize_cohort_backfill_runs() -> None:
"""Terminalize behavioral backfill runs the Rust seeder has fully observed. Gated off by
diff --git a/posthog/tasks/scheduled.py b/posthog/tasks/scheduled.py
index e28111a2c9a4..cb909db75679 100644
--- a/posthog/tasks/scheduled.py
+++ b/posthog/tasks/scheduled.py
@@ -11,7 +11,7 @@ from posthog.caching.warming import schedule_warming_for_teams_task
from posthog.clickhouse.client.execute_async import QueryStatusManager
from posthog.tasks.ai_observability_usage_report import send_ai_observability_usage_reports
from posthog.tasks.auth_token_cache_verification import verify_and_fix_auth_token_cache_task
-from posthog.tasks.calculate_cohort import finalize_cohort_backfill_runs
+from posthog.tasks.calculate_cohort import finalize_cohort_backfill_runs, publish_cohort_backfill_run_gauges
from posthog.tasks.email import (
EXTERNAL_DATA_DIGEST_DAY_BOUNDARY_HOUR_UTC,
send_hog_functions_daily_digest,
@@ -698,6 +698,13 @@ def setup_periodic_tasks(sender: Celery, **kwargs: Any) -> None:
name="finalize cohort backfill runs",
)
+ add_periodic_task_with_expiry(
+ sender,
+ crontab(minute="*/2"),
+ publish_cohort_backfill_run_gauges.s(),
+ name="publish cohort backfill run gauges",
+ )
+
add_periodic_task_with_expiry(
sender,
crontab(minute="*/2"),
diff --git a/posthog/tasks/test/__snapshots__/test_task_registration.ambr b/posthog/tasks/test/__snapshots__/test_task_registration.ambr
index 0142d2816b8e..cb6528701850 100644
--- a/posthog/tasks/test/__snapshots__/test_task_registration.ambr
+++ b/posthog/tasks/test/__snapshots__/test_task_registration.ambr
@@ -18,6 +18,7 @@
'posthog.tasks.calculate_cohort.insert_cohort_from_feature_flag',
'posthog.tasks.calculate_cohort.insert_cohort_from_filters',
'posthog.tasks.calculate_cohort.insert_cohort_from_query',
+ 'posthog.tasks.calculate_cohort.publish_cohort_backfill_run_gauges',
'posthog.tasks.calculate_cohort.trigger_cohort_backfill_run_task',
'posthog.tasks.comment_slack_sync.backfill_comment_slack_thread',
'posthog.tasks.comment_slack_sync.ingest_slack_discussion_reply',
diff --git a/posthog/tasks/test/test_calculate_cohort.py b/posthog/tasks/test/test_calculate_cohort.py
index c776bba7d3c9..0a1198a47295 100644
--- a/posthog/tasks/test/test_calculate_cohort.py
+++ b/posthog/tasks/test/test_calculate_cohort.py
@@ -15,6 +15,8 @@ from posthog.hogql.errors import QueryError
from posthog.exceptions import ClickHouseAtCapacity
from posthog.tasks.calculate_cohort import (
+ COHORT_BACKFILL_REFUSAL_OUTCOMES,
+ COHORT_BACKFILL_TRIGGER_TASK_COUNTER,
COHORT_STUCK_COUNT_GAUGE,
COHORTS_STALE_COUNT_GAUGE,
COHORTS_TOTAL_GAUGE,
@@ -31,6 +33,8 @@ from posthog.tasks.calculate_cohort import (
)
from posthog.test.persons import create_person
+from products.cohorts.backend.backfill.runs import BackfillRefusalReason
+from products.cohorts.backend.backfill.sizing import PersonSeedEstimate
from products.cohorts.backend.models.backfill import CohortBackfillKind, CohortBackfillRun
from products.cohorts.backend.models.cohort import Cohort, CohortType
from products.cohorts.backend.models.util import count_cohort_members, list_cohort_member_ids
@@ -1165,6 +1169,54 @@ class TestCohortCalculationTasks(APIBaseTest):
estimate.assert_not_called()
self.assertFalse(CohortBackfillRun.objects.for_team(self.team.pk).exists())
+ def test_trigger_backfill_run_task_labels_a_budget_refusal_apart_from_a_blocked_slot(self) -> None:
+ # These two refusals call for opposite operator responses — raise the budget vs. go unwedge
+ # a stuck run — so the single flat `refused` outcome could not drive either alert.
+ cohort = self._backfillable_cohort()
+
+ with (
+ patch.object(COHORT_BACKFILL_TRIGGER_TASK_COUNTER, "labels") as counter,
+ override_settings(**{**BACKFILL_TASK_SETTINGS, "BEHAVIORAL_BACKFILL_PERSON_TOPIC_BYTES_BUDGET": 1}),
+ patch("products.cohorts.backend.backfill.runs.estimate_person_seed_topic_bytes") as estimate,
+ ):
+ estimate.return_value = PersonSeedEstimate(
+ estimated_persons=10,
+ pinned_condition_count=1,
+ bytes_per_seed=294,
+ estimated_topic_bytes=2_940,
+ budget_bytes=1,
+ )
+ trigger_cohort_backfill_run_task(
+ self.team.pk, cohort.pk, "cohort_created", CohortBackfillKind.PERSON_PROPERTY.value
+ )
+
+ counter.assert_called_once_with(
+ backfill_kind=CohortBackfillKind.PERSON_PROPERTY.value, outcome="refused_over_budget"
+ )
+
+ with override_settings(**BACKFILL_TASK_SETTINGS):
+ trigger_cohort_backfill_run_task(
+ self.team.pk, cohort.pk, "cohort_created", CohortBackfillKind.BEHAVIORAL.value
+ )
+ with patch.object(COHORT_BACKFILL_TRIGGER_TASK_COUNTER, "labels") as counter:
+ trigger_cohort_backfill_run_task(
+ self.team.pk, cohort.pk, "cohort_edited", CohortBackfillKind.BEHAVIORAL.value
+ )
+
+ counter.assert_called_once_with(
+ backfill_kind=CohortBackfillKind.BEHAVIORAL.value, outcome="refused_slot_occupied"
+ )
+
+ def test_every_backfill_refusal_reason_has_a_trigger_outcome(self) -> None:
+ # A reason with no mapping entry falls back to the flat `refused`, which reads as an
+ # unclassified refusal rather than an omission. Catch the drift here instead.
+ self.assertEqual(set(COHORT_BACKFILL_REFUSAL_OUTCOMES), set(BackfillRefusalReason))
+ # The alert rules match these literals, so a rename has to break a test, not a dashboard.
+ self.assertEqual(
+ set(COHORT_BACKFILL_REFUSAL_OUTCOMES.values()),
+ {"refused_over_budget", "refused_slot_occupied", "refused_ineligible", "refused_transient"},
+ )
+
def test_trigger_backfill_run_task_rechecks_the_allowlist_at_execution_time(self) -> None:
# Tasks sit in the queue for the debounce countdown, so an operator shrinking the allowlist
# during an incident has to stop those too, not only new enqueues.
diff --git a/products/cohorts/backend/backfill/finalize.py b/products/cohorts/backend/backfill/finalize.py
index 481aa26603d0..5814bed59ef5 100644
--- a/products/cohorts/backend/backfill/finalize.py
+++ b/products/cohorts/backend/backfill/finalize.py
@@ -69,6 +69,9 @@ HELD_RUNS_GAUGE = Gauge(
# labels: "shortfall" (an outcome was missing), "error" (the pass raised), "gated" (a person
# run parked behind the readiness gate)
["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",
)
diff --git a/products/cohorts/backend/backfill/observe.py b/products/cohorts/backend/backfill/observe.py
new file mode 100644
index 000000000000..0b2b55ccc68e
--- /dev/null
+++ b/products/cohorts/backend/backfill/observe.py
@@ -0,0 +1,161 @@
+"""Publishes backfill run and chunk state as Prometheus gauges.
+
+The seeder owns the richest telemetry about a run — per chunk, per partition, reconcile liveness —
+but all of it is the seeder's own view: counters that restart with the pod, and blind to every
+transition Django owns. Supersession, cancellation, a `blocked` run parked on a missing attestation,
+and the finalizer's own moves never reach it. These gauges read the runs table instead, so a stalled
+run or a chunk that exhausted its retries is visible whichever side put it there, and survives a
+seeder deploy.
+
+Read the age gauge with the finalizer's state in mind: while `BEHAVIORAL_BACKFILL_FINALIZER_ENABLED`
+is off, a behavioral run that finishes seeding parks in `reconciling`, which counts as active, so
+that slice climbs forever for work that is already done. Until the finalizer is on, only the
+`seeding`, `awaiting_boundary` and `blocked` slices carry an alertable age.
+
+Deliberately not folded into ``finalize_backfill_runs``: that returns early while the finalizer is
+off, and the alerts have to work with it still dark.
+"""
+
+from dataclasses import field
+from datetime import timedelta
+
+from django.db.models import Count, Min
+from django.utils import timezone as django_timezone
+
+from prometheus_client import CollectorRegistry, Gauge
+
+from posthog.dataclasses import frozen
+from posthog.metrics import pushed_metrics_registry
+
+from products.cohorts.backend.models.backfill import (
+ ACTIVE_COHORT_BACKFILL_RUN_STATUSES,
+ TERMINAL_COHORT_BACKFILL_RUN_STATUSES,
+ CohortBackfillChunk,
+ CohortBackfillChunkStatus,
+ CohortBackfillKind,
+ CohortBackfillRun,
+)
+
+RECENT_WINDOW = timedelta(hours=1)
+
+PUSH_JOB_NAME = "cohort_backfill_observe"
+
+_KINDS = tuple(CohortBackfillKind)
+
+
+@frozen
+class ObservationPass:
+ """One pass's readings of the runs table, before they are published."""
+
+ active_runs: dict[tuple[str, str], int] = field(default_factory=dict)
+ oldest_active_age_seconds: dict[tuple[str, str], float] = field(default_factory=dict)
+ failed_chunks: dict[str, int] = field(default_factory=dict)
+ recent_runs: dict[tuple[str, str], int] = field(default_factory=dict)
+
+
+def publish_backfill_run_gauges() -> ObservationPass:
+ """One observation pass over every team's backfill runs and chunks."""
+ result = _observe()
+ # Pushed, rather than served from the worker's own registry: this is a whole-fleet snapshot, and
+ # whichever worker the task lands on is the only one holding it. Every other worker keeps serving
+ # whatever it last wrote, and no multiprocess mode reaches across pods, so a `max by (status,
+ # kind)` alert stays lit until the task comes back round to the pod with the stale reading. One
+ # push under one job name replaces the whole group atomically instead. The tradeoff is this
+ # helper's usual one: if beat stops, the pushgateway keeps serving the last push, which
+ # `push_time_seconds` covers.
+ with pushed_metrics_registry(PUSH_JOB_NAME) as registry:
+ _publish(result, registry)
+ return result
+
+
+def _observe() -> ObservationPass:
+ now = django_timezone.now()
+ result = ObservationPass()
+
+ # Seed every combination with a zero first, so each pass pushes a complete group. A slice left
+ # out while it is empty vanishes from the push the moment it drains, and an alert expression
+ # reading it goes from a value to no data rather than to zero.
+ for kind in _KINDS:
+ result.failed_chunks[kind] = 0
+ for status in ACTIVE_COHORT_BACKFILL_RUN_STATUSES:
+ result.active_runs[(status, kind)] = 0
+ result.oldest_active_age_seconds[(status, kind)] = 0.0
+ for status in TERMINAL_COHORT_BACKFILL_RUN_STATUSES:
+ result.recent_runs[(status, kind)] = 0
+
+ # Cross-team on purpose, like the finalizer: these gauges serve the whole fleet, and there is no
+ # per-team consumer. No index serves a team-less status predicate — `cohort_bfr_team_status_idx`
+ # is team-prefixed, which is the same reason the finalizer needed `cohort_bfr_reconciling_idx`.
+ # Fine while the trigger allowlist is narrow; revisit with a partial index if that widens.
+ for row in (
+ CohortBackfillRun.objects.unscoped()
+ .filter(status__in=ACTIVE_COHORT_BACKFILL_RUN_STATUSES)
+ .values("status", "backfill_kind")
+ .annotate(runs=Count("id"), oldest=Min("created_at"))
+ ):
+ key = (row["status"], row["backfill_kind"])
+ result.active_runs[key] = row["runs"]
+ result.oldest_active_age_seconds[key] = max(0.0, (now - row["oldest"]).total_seconds())
+
+ for row in (
+ CohortBackfillChunk.objects.unscoped()
+ .filter(
+ status=CohortBackfillChunkStatus.FAILED,
+ run__status__in=ACTIVE_COHORT_BACKFILL_RUN_STATUSES,
+ )
+ .values("run__backfill_kind")
+ .annotate(chunks=Count("id"))
+ ):
+ result.failed_chunks[row["run__backfill_kind"]] = row["chunks"]
+
+ for row in (
+ CohortBackfillRun.objects.unscoped()
+ .filter(status__in=TERMINAL_COHORT_BACKFILL_RUN_STATUSES, finished_at__gte=now - RECENT_WINDOW)
+ .values("status", "backfill_kind")
+ .annotate(runs=Count("id"))
+ ):
+ result.recent_runs[(row["status"], row["backfill_kind"])] = row["runs"]
+
+ return result
+
+
+def _publish(result: ObservationPass, registry: CollectorRegistry) -> None:
+ runs_active = Gauge(
+ "posthog_cohort_backfill_runs_active",
+ "Backfill runs in each active status, by backfill kind",
+ ["status", "kind"],
+ registry=registry,
+ )
+ oldest_active_run_age = Gauge(
+ "posthog_cohort_backfill_oldest_active_run_age_seconds",
+ "Age of the oldest backfill run in each active status, by backfill kind",
+ ["status", "kind"],
+ registry=registry,
+ )
+ chunks_failed = Gauge(
+ "posthog_cohort_backfill_chunks_failed",
+ # Retry churn, not wedged work: a chunk under the attempt cap is reclaimed and retried, and
+ # one past it takes its whole run out of the active set within a poll. A run wedged that way
+ # surfaces as `runs_recent{status="failed"}`.
+ "Chunks in `failed` status on a still-active run, by backfill kind — retry activity",
+ ["kind"],
+ registry=registry,
+ )
+ runs_recent = Gauge(
+ "posthog_cohort_backfill_runs_recent",
+ # The one to alert on, not `runs_finalized_total`: supersession, the readiness supersede and
+ # the seeder's own `fail_run` all terminalize a run without the finalizer counting it, so
+ # that counter measures finalizer throughput while this measures run outcomes.
+ "Backfill runs terminalized in the last hour, by terminal status and backfill kind",
+ ["status", "kind"],
+ registry=registry,
+ )
+
+ for (status, kind), runs in result.active_runs.items():
+ runs_active.labels(status=status, kind=kind).set(runs)
+ for (status, kind), age in result.oldest_active_age_seconds.items():
+ oldest_active_run_age.labels(status=status, kind=kind).set(age)
+ for kind, chunks in result.failed_chunks.items():
+ chunks_failed.labels(kind=kind).set(chunks)
+ for (status, kind), runs in result.recent_runs.items():
+ runs_recent.labels(status=status, kind=kind).set(runs)
diff --git a/products/cohorts/backend/backfill/runs.py b/products/cohorts/backend/backfill/runs.py
index 091306ad621e..c1f7860bec6e 100644
--- a/products/cohorts/backend/backfill/runs.py
+++ b/products/cohorts/backend/backfill/runs.py
@@ -1,5 +1,6 @@
from collections.abc import Iterable
from datetime import UTC, datetime, timedelta
+from enum import StrEnum
from typing import Any
from django.conf import settings
@@ -9,6 +10,7 @@ from django.utils import timezone as django_timezone
import structlog
+from posthog.dataclasses import frozen
from posthog.models.team.team import Team
from products.cohorts.backend.backfill.pinning import (
@@ -178,9 +180,57 @@ def _active_person_seed_topic_bytes(team_id: int) -> int:
)
+class BackfillRefusalReason(StrEnum):
+ """Why a creator declined to make a run.
+
+ The creators have always refused by returning ``None``, which collapsed a budget refusal and an
+ occupied run slot into the same signal — the two need entirely different operator responses
+ (raise the budget vs. go unwedge a stuck run), so the metric has to tell them apart.
+ """
+
+ TEAM_NOT_REALTIME = "team_not_realtime"
+ COHORT_MISSING = "cohort_missing"
+ COHORT_INELIGIBLE = "cohort_ineligible"
+ PARTICIPATION_ACTIVE = "participation_active"
+ RUN_SLOT_OCCUPIED = "run_slot_occupied"
+ SLOT_RACE = "slot_race"
+ INVALID_HORIZON = "invalid_horizon"
+ PINNING_CAP_EXCEEDED = "pinning_cap_exceeded"
+ OVER_BUDGET = "over_budget"
+ SIZING_SCAN_CAP_EXCEEDED = "sizing_scan_cap_exceeded"
+ DEFINITION_CHANGED = "definition_changed"
+
+
+@frozen
+class BackfillRunAttempt:
+ """A creator's outcome: the run, or the reason there isn't one. Exactly one is set."""
+
+ run: CohortBackfillRun | None
+ reason: BackfillRefusalReason | None
+
+ @classmethod
+ def created(cls, run: CohortBackfillRun) -> "BackfillRunAttempt":
+ return cls(run=run, reason=None)
+
+ @classmethod
+ def refused(cls, reason: BackfillRefusalReason) -> "BackfillRunAttempt":
+ return cls(run=None, reason=reason)
+
+
def create_backfill_run_for_cohort(team_id: int, cohort_id: int, trigger_kind: str) -> CohortBackfillRun | None:
+ """The run, or ``None``, for callers that assert on the run and never on why one was refused."""
+ return attempt_backfill_run_for_cohort(team_id, cohort_id, trigger_kind).run
+
+
+def attempt_backfill_run_for_cohort(team_id: int, cohort_id: int, trigger_kind: str) -> BackfillRunAttempt:
+ """Create one cohort's behavioral run, reporting the refusal reason rather than raising.
+
+ Every conflict check is re-run under a row lock, so a cohort edited again, deleted, or made
+ static in the meantime refuses instead of creating a second run for the same slot. The reason
+ comes back on the attempt so the signal path can label its metric with it.
+ """
if not is_realtime_cohort_team(team_id):
- return None
+ return BackfillRunAttempt.refused(BackfillRefusalReason.TEAM_NOT_REALTIME)
try:
with transaction.atomic():
@@ -190,18 +240,19 @@ def create_backfill_run_for_cohort(team_id: int, cohort_id: int, trigger_kind: s
.filter(id=cohort_id, team_id=team_id)
.first()
)
+ if cohort is None:
+ return BackfillRunAttempt.refused(BackfillRefusalReason.COHORT_MISSING)
if (
- cohort is None
- or cohort.cohort_type != CohortType.REALTIME
+ cohort.cohort_type != CohortType.REALTIME
or cohort.is_static
or cohort.deleted
or not has_behavioral_filters(cohort)
):
- return None
+ return BackfillRunAttempt.refused(BackfillRefusalReason.COHORT_INELIGIBLE)
if _active_participation_cohort_ids(team_id, [cohort_id], kind=CohortBackfillKind.BEHAVIORAL):
- return None
+ return BackfillRunAttempt.refused(BackfillRefusalReason.PARTICIPATION_ACTIVE)
if _has_active_cohort_run(team_id, cohort_id, kind=CohortBackfillKind.BEHAVIORAL):
- return None
+ return BackfillRunAttempt.refused(BackfillRefusalReason.RUN_SLOT_OCCUPIED)
filters_shape_hash = ensure_filters_shape_hash(cohort)
behavioral_filters_shape_hash = cohort.behavioral_filters_shape_hash or ""
@@ -227,17 +278,17 @@ def create_backfill_run_for_cohort(team_id: int, cohort_id: int, trigger_kind: s
behavioral_filters_shape_hash=behavioral_filters_shape_hash,
pinned_filters=cohort.filters,
)
- return run
+ return BackfillRunAttempt.created(run)
except IntegrityError:
# A writer this transaction could not see won the unique-constraint race after the conflict
- # checks passed. Refusing is this creator's contract, so return None rather than raise.
+ # checks passed. Refusing is this creator's contract, so report the race rather than raise.
logger.warning(
"cohort_backfill_run_conflict_race",
team_id=team_id,
cohort_id=cohort_id,
backfill_kind=CohortBackfillKind.BEHAVIORAL,
)
- return None
+ return BackfillRunAttempt.refused(BackfillRefusalReason.SLOT_RACE)
def _validate_boundary_at(trigger_kind: str, boundary_at: datetime | None) -> datetime | None:
@@ -333,6 +384,19 @@ def create_person_backfill_run_for_cohort(
*,
person_horizon_days: int | None = None,
) -> CohortBackfillRun | None:
+ """The run, or ``None``, for callers that assert on the run and never on why one was refused."""
+ return attempt_person_backfill_run_for_cohort(
+ team_id, cohort_id, trigger_kind, person_horizon_days=person_horizon_days
+ ).run
+
+
+def attempt_person_backfill_run_for_cohort(
+ team_id: int,
+ cohort_id: int,
+ trigger_kind: str,
+ *,
+ person_horizon_days: int | None = None,
+) -> BackfillRunAttempt:
"""Create one cohort's person-property run, on the signal path's contract.
Unlike ``create_person_team_backfill_run`` this refuses quietly where the team creator raises:
@@ -342,9 +406,12 @@ def create_person_backfill_run_for_cohort(
sizing failure (a ClickHouse timeout or transport error), which propagates so the task's retry
machinery re-runs it; the scan's own deterministic read cap still refuses quietly, since
retrying it would only repeat the capped scan.
+
+ The reason for a refusal comes back on the attempt, so the signal path can label its metric
+ with it.
"""
if not is_realtime_cohort_team(team_id):
- return None
+ return BackfillRunAttempt.refused(BackfillRefusalReason.TEAM_NOT_REALTIME)
horizon_days = (
person_horizon_days
@@ -358,18 +425,20 @@ def create_person_backfill_run_for_cohort(
cohort_id=cohort_id,
person_horizon_days=horizon_days,
)
- return None
+ return BackfillRunAttempt.refused(BackfillRefusalReason.INVALID_HORIZON)
# Unlocked pre-pass for the sizing gate: the estimate is a ClickHouse round trip, so it must not
# run while the create path below holds the cohort row FOR UPDATE. The locked pass re-derives
# eligibility and the pin, and refuses if the definition moved in between.
cohort = Cohort.objects.filter(id=cohort_id, team_id=team_id).first()
- if cohort is None or person_backfill_ineligibility_reason(cohort) is not None:
- return None
+ if cohort is None:
+ return BackfillRunAttempt.refused(BackfillRefusalReason.COHORT_MISSING)
+ if person_backfill_ineligibility_reason(cohort) is not None:
+ return BackfillRunAttempt.refused(BackfillRefusalReason.COHORT_INELIGIBLE)
if _active_participation_cohort_ids(team_id, [cohort_id], kind=CohortBackfillKind.PERSON_PROPERTY):
- return None
+ return BackfillRunAttempt.refused(BackfillRefusalReason.PARTICIPATION_ACTIVE)
if _has_active_cohort_run(team_id, cohort_id, kind=CohortBackfillKind.PERSON_PROPERTY):
- return None
+ return BackfillRunAttempt.refused(BackfillRefusalReason.RUN_SLOT_OCCUPIED)
try:
pinned = pin_person_conditions_for_cohorts(
[cohort],
@@ -382,7 +451,7 @@ def create_person_backfill_run_for_cohort(
cohort_id=cohort_id,
max_conditions=settings.BEHAVIORAL_BACKFILL_PERSON_MAX_PINNED_CONDITIONS,
)
- return None
+ return BackfillRunAttempt.refused(BackfillRefusalReason.PINNING_CAP_EXCEEDED)
person_scan_since = django_timezone.now() - timedelta(days=horizon_days)
# With a precondition missing the run below records as `blocked`, which the seeder never claims,
@@ -403,7 +472,7 @@ def create_person_backfill_run_for_cohort(
active_topic_bytes=active_topic_bytes,
budget_bytes=settings.BEHAVIORAL_BACKFILL_PERSON_TOPIC_BYTES_BUDGET,
)
- return None
+ return BackfillRunAttempt.refused(BackfillRefusalReason.OVER_BUDGET)
try:
estimate = estimate_person_seed_topic_bytes(team_id, person_scan_since, len(pinned["conditions"]))
except PersonSeedEstimateScanCapExceeded as error:
@@ -413,7 +482,7 @@ def create_person_backfill_run_for_cohort(
cohort_id=cohort_id,
error=str(error),
)
- return None
+ return BackfillRunAttempt.refused(BackfillRefusalReason.SIZING_SCAN_CAP_EXCEEDED)
if estimate.estimated_topic_bytes + active_topic_bytes > estimate.budget_bytes:
logger.warning(
"cohort_person_backfill_over_budget",
@@ -423,22 +492,27 @@ def create_person_backfill_run_for_cohort(
active_topic_bytes=active_topic_bytes,
budget_bytes=estimate.budget_bytes,
)
- return None
+ return BackfillRunAttempt.refused(BackfillRefusalReason.OVER_BUDGET)
try:
with transaction.atomic():
+ # The locked re-checks reuse the unlocked reasons on purpose: which pass caught the
+ # refusal is a debugging detail for the log line, not a dimension worth doubling the
+ # metric's cardinality for.
cohort = (
Cohort.objects.select_for_update(of=("self",))
.select_related("team")
.filter(id=cohort_id, team_id=team_id)
.first()
)
- if cohort is None or person_backfill_ineligibility_reason(cohort) is not None:
- return None
+ if cohort is None:
+ return BackfillRunAttempt.refused(BackfillRefusalReason.COHORT_MISSING)
+ if person_backfill_ineligibility_reason(cohort) is not None:
+ return BackfillRunAttempt.refused(BackfillRefusalReason.COHORT_INELIGIBLE)
if _active_participation_cohort_ids(team_id, [cohort_id], kind=CohortBackfillKind.PERSON_PROPERTY):
- return None
+ return BackfillRunAttempt.refused(BackfillRefusalReason.PARTICIPATION_ACTIVE)
if _has_active_cohort_run(team_id, cohort_id, kind=CohortBackfillKind.PERSON_PROPERTY):
- return None
+ return BackfillRunAttempt.refused(BackfillRefusalReason.RUN_SLOT_OCCUPIED)
try:
locked_pinned = pin_person_conditions_for_cohorts(
@@ -452,7 +526,7 @@ def create_person_backfill_run_for_cohort(
cohort_id=cohort_id,
max_conditions=settings.BEHAVIORAL_BACKFILL_PERSON_MAX_PINNED_CONDITIONS,
)
- return None
+ return BackfillRunAttempt.refused(BackfillRefusalReason.PINNING_CAP_EXCEEDED)
if locked_pinned != pinned:
# A racing edit changed the definition after sizing; its own save dispatched a fresh
# debounced task, so that task owns the re-sized run.
@@ -461,7 +535,7 @@ def create_person_backfill_run_for_cohort(
team_id=team_id,
cohort_id=cohort_id,
)
- return None
+ return BackfillRunAttempt.refused(BackfillRefusalReason.DEFINITION_CHANGED)
filters_shape_hash = ensure_filters_shape_hash(cohort)
person_filters_shape_hash = cohort.person_filters_shape_hash or ""
@@ -487,17 +561,17 @@ def create_person_backfill_run_for_cohort(
person_filters_shape_hash=person_filters_shape_hash,
pinned_filters=cohort.filters,
)
- return run
+ return BackfillRunAttempt.created(run)
except IntegrityError:
# A writer this transaction could not see won the unique-constraint race after the conflict
- # checks passed. Refusing is this creator's contract, so return None rather than raise.
+ # checks passed. Refusing is this creator's contract, so report the race rather than raise.
logger.warning(
"cohort_backfill_run_conflict_race",
team_id=team_id,
cohort_id=cohort_id,
backfill_kind=CohortBackfillKind.PERSON_PROPERTY,
)
- return None
+ return BackfillRunAttempt.refused(BackfillRefusalReason.SLOT_RACE)
def _person_cohorts_for_team(team_id: int, requested_ids: set[int] | None, *, lock: bool) -> list[Cohort]:
diff --git a/products/cohorts/backend/backfill/test/test_observe.py b/products/cohorts/backend/backfill/test/test_observe.py
new file mode 100644
index 000000000000..bd9c6018ddeb
--- /dev/null
+++ b/products/cohorts/backend/backfill/test/test_observe.py
@@ -0,0 +1,193 @@
+from collections.abc import Iterator
+from contextlib import contextmanager
+from datetime import datetime, timedelta
+
+from posthog.test.base import BaseTest
+from unittest.mock import patch
+
+from django.utils import timezone
+
+from prometheus_client import CollectorRegistry
+
+from posthog.models.team.team import Team
+
+from products.cohorts.backend.backfill.observe import PUSH_JOB_NAME, publish_backfill_run_gauges
+from products.cohorts.backend.models.backfill import (
+ CohortBackfillChunk,
+ CohortBackfillChunkStatus,
+ CohortBackfillKind,
+ CohortBackfillRun,
+ CohortBackfillRunStatus,
+ CohortBackfillScope,
+ CohortBackfillTrigger,
+)
+
+
+class TestBackfillObservation(BaseTest):
+ def setUp(self) -> None:
+ super().setUp()
+ # Assert on what the push carries, not on the pass that fed it: the gauges are the only
+ # output anything downstream sees, and deleting the publish step has to fail a test.
+ self.registry = CollectorRegistry()
+
+ @contextmanager
+ def _capture(job_name: str) -> Iterator[CollectorRegistry]:
+ self.assertEqual(job_name, PUSH_JOB_NAME)
+ # A fresh registry per push, as the real helper does, so a second pass in one test does
+ # not collide with the first pass's gauges.
+ self.registry = CollectorRegistry()
+ yield self.registry
+
+ patcher = patch("products.cohorts.backend.backfill.observe.pushed_metrics_registry", _capture)
+ patcher.start()
+ self.addCleanup(patcher.stop)
+
+ def _gauge(self, name: str, **labels: str) -> float | None:
+ return self.registry.get_sample_value(name, labels)
+
+ def _other_team(self) -> Team:
+ return Team.objects.create(organization=self.organization, name="other")
+
+ def _run(
+ self,
+ *,
+ status: str = CohortBackfillRunStatus.SEEDING,
+ kind: str = CohortBackfillKind.BEHAVIORAL,
+ created_at: datetime | None = None,
+ finished_at: datetime | None = None,
+ team: Team | None = None,
+ ) -> CohortBackfillRun:
+ team_id = (team or self.team).id
+ run = CohortBackfillRun.objects.for_team(team_id).create(
+ team_id=team_id,
+ backfill_kind=kind,
+ trigger_kind=CohortBackfillTrigger.TEAM_ENABLEMENT,
+ scope=CohortBackfillScope.TEAM,
+ status=status,
+ timezone="UTC",
+ finished_at=finished_at,
+ )
+ if created_at is not None:
+ CohortBackfillRun.objects.for_team(team_id).filter(id=run.id).update(created_at=created_at)
+ run.refresh_from_db()
+ return run
+
+ def test_publishes_zeroes_for_empty_slices(self) -> None:
+ publish_backfill_run_gauges()
+
+ seeding = CohortBackfillRunStatus.SEEDING
+ self.assertEqual(
+ self._gauge("posthog_cohort_backfill_runs_active", status=seeding, kind=CohortBackfillKind.BEHAVIORAL), 0.0
+ )
+ self.assertEqual(self._gauge("posthog_cohort_backfill_chunks_failed", kind=CohortBackfillKind.BEHAVIORAL), 0.0)
+ self.assertEqual(
+ self._gauge(
+ "posthog_cohort_backfill_runs_recent",
+ status=CohortBackfillRunStatus.FAILED,
+ kind=CohortBackfillKind.PERSON_PROPERTY,
+ ),
+ 0.0,
+ )
+ published = [
+ sample
+ for metric in self.registry.collect()
+ for sample in metric.samples
+ if sample.name == "posthog_cohort_backfill_runs_active"
+ ]
+ self.assertEqual(len(published), 8) # 4 active statuses x 2 kinds
+
+ def test_gauges_fall_back_to_zero_when_a_slice_drains(self) -> None:
+ # The freeze this guards against: a slice written only while it is non-empty keeps reporting
+ # the finished run's age, holding a stalled-run alert lit hours after the run ended.
+ now = timezone.now()
+ run = self._run(created_at=now - timedelta(hours=3))
+ labels = {"status": CohortBackfillRunStatus.SEEDING, "kind": CohortBackfillKind.BEHAVIORAL}
+
+ publish_backfill_run_gauges()
+
+ self.assertEqual(self._gauge("posthog_cohort_backfill_runs_active", **labels), 1.0)
+ self.assertAlmostEqual(
+ self._gauge("posthog_cohort_backfill_oldest_active_run_age_seconds", **labels) or 0.0,
+ 3 * 3600,
+ delta=60,
+ )
+
+ CohortBackfillRun.objects.for_team(self.team.id).filter(id=run.id).update(
+ status=CohortBackfillRunStatus.COMPLETED, finished_at=now
+ )
+ publish_backfill_run_gauges()
+
+ self.assertEqual(self._gauge("posthog_cohort_backfill_runs_active", **labels), 0.0)
+ self.assertEqual(self._gauge("posthog_cohort_backfill_oldest_active_run_age_seconds", **labels), 0.0)
+ self.assertEqual(
+ self._gauge(
+ "posthog_cohort_backfill_runs_recent",
+ status=CohortBackfillRunStatus.COMPLETED,
+ kind=CohortBackfillKind.BEHAVIORAL,
+ ),
+ 1.0,
+ )
+
+ def test_counts_active_runs_and_their_age_per_kind(self) -> None:
+ # The second behavioral run lives on another team: these gauges serve the whole fleet, and
+ # the active-team-kind constraint allows only one per team anyway.
+ now = timezone.now()
+ self._run(kind=CohortBackfillKind.BEHAVIORAL, created_at=now - timedelta(hours=3))
+ self._run(kind=CohortBackfillKind.BEHAVIORAL, created_at=now - timedelta(hours=1), team=self._other_team())
+ self._run(kind=CohortBackfillKind.PERSON_PROPERTY, created_at=now - timedelta(minutes=5))
+
+ publish_backfill_run_gauges()
+
+ seeding = CohortBackfillRunStatus.SEEDING
+ behavioral = {"status": seeding, "kind": CohortBackfillKind.BEHAVIORAL}
+ self.assertEqual(self._gauge("posthog_cohort_backfill_runs_active", **behavioral), 2.0)
+ self.assertEqual(
+ self._gauge("posthog_cohort_backfill_runs_active", status=seeding, kind=CohortBackfillKind.PERSON_PROPERTY),
+ 1.0,
+ )
+ # The oldest, not the newest: a stalled run has to stay visible behind fresher ones.
+ self.assertAlmostEqual(
+ self._gauge("posthog_cohort_backfill_oldest_active_run_age_seconds", **behavioral) or 0.0,
+ 3 * 3600,
+ delta=60,
+ )
+ self.assertEqual(
+ self._gauge(
+ "posthog_cohort_backfill_runs_active",
+ status=CohortBackfillRunStatus.RECONCILING,
+ kind=CohortBackfillKind.BEHAVIORAL,
+ ),
+ 0.0,
+ )
+
+ def test_counts_failed_chunks_only_on_still_active_runs(self) -> None:
+ active = self._run()
+ done = self._run(status=CohortBackfillRunStatus.COMPLETED, finished_at=timezone.now())
+ for run in (active, done):
+ CohortBackfillChunk.objects.for_team(self.team.id).create(
+ run=run,
+ team_id=self.team.id,
+ day="2026-01-01",
+ status=CohortBackfillChunkStatus.FAILED,
+ )
+
+ publish_backfill_run_gauges()
+
+ # A failed chunk on a terminal run is history; only one on a live run means retry churn.
+ self.assertEqual(self._gauge("posthog_cohort_backfill_chunks_failed", kind=CohortBackfillKind.BEHAVIORAL), 1.0)
+
+ def test_recent_runs_window_excludes_older_terminals(self) -> None:
+ now = timezone.now()
+ self._run(status=CohortBackfillRunStatus.FAILED, finished_at=now - timedelta(minutes=10))
+ self._run(status=CohortBackfillRunStatus.FAILED, finished_at=now - timedelta(hours=2))
+
+ publish_backfill_run_gauges()
+
+ self.assertEqual(
+ self._gauge(
+ "posthog_cohort_backfill_runs_recent",
+ status=CohortBackfillRunStatus.FAILED,
+ kind=CohortBackfillKind.BEHAVIORAL,
+ ),
+ 1.0,
+ )
diff --git a/products/cohorts/backend/backfill/test/test_runs.py b/products/cohorts/backend/backfill/test/test_runs.py
index c67a46836936..dd9f3834b715 100644
--- a/products/cohorts/backend/backfill/test/test_runs.py
+++ b/products/cohorts/backend/backfill/test/test_runs.py
@@ -1,3 +1,4 @@
+from collections.abc import Callable
from datetime import UTC, datetime, timedelta
from posthog.test.base import BaseTest
@@ -10,6 +11,10 @@ from parameterized import parameterized
from products.cohorts.backend.backfill.pinning import PersonPinningCapExceeded
from products.cohorts.backend.backfill.runs import (
+ BackfillRefusalReason,
+ BackfillRunAttempt,
+ attempt_backfill_run_for_cohort,
+ attempt_person_backfill_run_for_cohort,
create_backfill_run_for_cohort,
create_person_backfill_run_for_cohort,
create_person_team_backfill_run,
@@ -134,6 +139,53 @@ class TestBackfillRuns(BaseTest):
self.assertIsNone(create_backfill_run_for_cohort(self.team.id, cohort.id, "cohort_edited"))
self.assertEqual(CohortBackfillRun.objects.for_team(self.team.id).count(), 1)
+ def test_attempt_names_active_participation_and_a_missing_cohort(self) -> None:
+ cohort = self._cohort()
+ created = attempt_backfill_run_for_cohort(self.team.id, cohort.id, "cohort_created")
+ self.assertIsNotNone(created.run)
+ self.assertIsNone(created.reason)
+
+ blocked = attempt_backfill_run_for_cohort(self.team.id, cohort.id, "cohort_edited")
+ self.assertIsNone(blocked.run)
+ self.assertEqual(blocked.reason, BackfillRefusalReason.PARTICIPATION_ACTIVE)
+
+ missing = attempt_backfill_run_for_cohort(self.team.id, cohort.id + 10_000, "cohort_edited")
+ self.assertEqual(missing.reason, BackfillRefusalReason.COHORT_MISSING)
+
+ @parameterized.expand(
+ [
+ ("behavioral", attempt_backfill_run_for_cohort),
+ ("person_property", attempt_person_backfill_run_for_cohort),
+ ]
+ )
+ def test_attempt_names_a_team_outside_the_realtime_allowlist(
+ self, _name: str, attempt: Callable[[int, int, str], BackfillRunAttempt]
+ ) -> None:
+ # A team dropping out of the allowlist is the first gate either creator hits. Unlabelled it
+ # lands in the flat `refused` bucket, which reads as an unclassified refusal.
+ cohort = self._cohort()
+
+ with override_settings(REALTIME_COHORT_TEAM_ALLOWLIST="none"):
+ self.assertEqual(
+ attempt(self.team.id, cohort.id, "cohort_created").reason,
+ BackfillRefusalReason.TEAM_NOT_REALTIME,
+ )
+
+ def test_failed_run_frees_the_per_cohort_slot(self) -> None:
+ # The seeder fails a run whose chunk exhausted its retry budget. That only unwedges the
+ # cohort if `failed` stops counting as active here: otherwise the uniqueness slot stays
+ # taken and no replacement run can ever be created for that cohort.
+ cohort = self._cohort()
+ first = create_backfill_run_for_cohort(self.team.id, cohort.id, "cohort_created")
+ assert first is not None
+ self.assertIsNone(create_backfill_run_for_cohort(self.team.id, cohort.id, "cohort_edited"))
+
+ first.status = CohortBackfillRunStatus.FAILED
+ first.save(update_fields=["status"])
+
+ self.assertIsNotNone(create_backfill_run_for_cohort(self.team.id, cohort.id, "cohort_edited"))
+ self.assertEqual(CohortBackfillRun.objects.for_team(self.team.id).count(), 2)
+
def test_active_team_run_prevents_overlapping_cohort_run(self) -> None:
cohort = self._cohort()
create_team_backfill_run(self.team.id, "team_enablement")
@@ -375,6 +427,49 @@ class TestPersonBackfillRuns(BaseTest):
estimate.assert_not_called()
self.assertEqual(CohortBackfillRun.objects.for_team(self.team.id).count(), 1)
+ @mock.patch("products.cohorts.backend.backfill.runs.estimate_person_seed_topic_bytes")
+ def test_both_budget_gates_report_over_budget(self, estimate: mock.Mock) -> None:
+ # The budget refuses in two places — before the sizing scan when in-flight runs already ate
+ # it, and after when the estimate pushes the total over. Both have to name the budget, or
+ # the alert only sees whichever one the team happens to hit.
+ estimate.return_value = self._estimate(estimated_topic_bytes=1_000_001)
+ first = self._cohort()
+ second = Cohort.objects.create(
+ team=self.team,
+ name="second person cohort",
+ cohort_type=CohortType.REALTIME,
+ filters=self._filters(),
+ )
+
+ post_scan = attempt_person_backfill_run_for_cohort(self.team.id, first.id, "cohort_created")
+ self.assertIsNone(post_scan.run)
+ self.assertEqual(post_scan.reason, BackfillRefusalReason.OVER_BUDGET)
+
+ estimate.return_value = self._estimate(estimated_topic_bytes=1_000_000)
+ self.assertIsNotNone(create_person_backfill_run_for_cohort(self.team.id, first.id, "cohort_created"))
+ estimate.reset_mock()
+ pre_scan = attempt_person_backfill_run_for_cohort(self.team.id, second.id, "cohort_created")
+
+ estimate.assert_not_called()
+ self.assertIsNone(pre_scan.run)
+ self.assertEqual(pre_scan.reason, BackfillRefusalReason.OVER_BUDGET)
+
+ def test_attempt_reports_the_occupied_slot_and_success(self) -> None:
+ cohort = self._cohort()
+
+ with mock.patch(
+ "products.cohorts.backend.backfill.runs.estimate_person_seed_topic_bytes",
+ return_value=self._estimate(),
+ ):
+ created = attempt_person_backfill_run_for_cohort(self.team.id, cohort.id, "cohort_created")
+ self.assertIsNotNone(created.run)
+ self.assertIsNone(created.reason)
+
+ blocked = attempt_person_backfill_run_for_cohort(self.team.id, cohort.id, "cohort_edited")
+
+ self.assertIsNone(blocked.run)
+ self.assertEqual(blocked.reason, BackfillRefusalReason.PARTICIPATION_ACTIVE)
+
@override_settings(BEHAVIORAL_BACKFILL_PERSON_MAX_PINNED_CONDITIONS=0)
def test_cohort_run_warns_and_refuses_pinning_cap(self) -> None:
cohort = self._cohort()
diff --git a/products/cohorts/backend/models/backfill.py b/products/cohorts/backend/models/backfill.py
index 2a4389be00f1..b5685dd7844a 100644
--- a/products/cohorts/backend/models/backfill.py
+++ b/products/cohorts/backend/models/backfill.py
@@ -41,6 +41,12 @@ ACTIVE_COHORT_BACKFILL_RUN_STATUSES = (
CohortBackfillRunStatus.RECONCILING,
)
+# Derived, so the two tuples always partition the enum: a ninth status joins one or the other, and
+# cannot fall out of both and into no gauge.
+TERMINAL_COHORT_BACKFILL_RUN_STATUSES = tuple(
+ status for status in CohortBackfillRunStatus if status not in ACTIVE_COHORT_BACKFILL_RUN_STATUSES
+)
+
class CohortBackfillChunkStatus(models.TextChoices):
PENDING = "pending", "Pending"
diff --git a/rust/cohort-seeder/src/app/mod.rs b/rust/cohort-seeder/src/app/mod.rs
index 7e0554e6c43b..4e89cebb1920 100644
--- a/rust/cohort-seeder/src/app/mod.rs
+++ b/rust/cohort-seeder/src/app/mod.rs
@@ -18,6 +18,9 @@ pub use completion::{
ObservePolicyError,
};
pub use observe::{KafkaCommittedOffsets, KafkaTopicOffsets};
-pub use orchestrator::{PersonComponents, SeederOrchestrator, ORCHESTRATOR_LIVENESS_DEADLINE};
+pub use orchestrator::{
+ fail_exhausted_runs_of_kind, PersonComponents, SeederOrchestrator,
+ ORCHESTRATOR_LIVENESS_DEADLINE,
+};
pub use settings::{OrchestratorSettings, PersonSettings};
pub use watch::{MarkerWatchTask, PgMarkerFlush, WatchDirectives, MARKER_WATCH_LIVENESS_DEADLINE};
diff --git a/rust/cohort-seeder/src/app/orchestrator.rs b/rust/cohort-seeder/src/app/orchestrator.rs
index 12d86d4e1798..be6124152b04 100644
--- a/rust/cohort-seeder/src/app/orchestrator.rs
+++ b/rust/cohort-seeder/src/app/orchestrator.rs
@@ -19,10 +19,12 @@ use crate::clickhouse::scanner::ChunkScanner;
use crate::domain::{ClaimKind, RunId};
use crate::kafka::pacing::TilePacer;
use crate::kafka::producer::SeedTileProducer;
-use crate::observability::metrics::{CHUNKS_CLAIMED, CHUNKS_POISONED, CHUNKS_RECLAIMED};
+use crate::observability::metrics::{
+ CHUNKS_CLAIMED, CHUNKS_POISONED, CHUNKS_RECLAIMED, RUNS_FAILED_EXHAUSTED_CHUNKS,
+};
use crate::store::chunks::{Claim, PgChunkStore};
-use crate::store::runs::RunKind;
-use crate::store::Claimant;
+use crate::store::runs::{fail_run, RunError, RunKind};
+use crate::store::{Claimant, MaxAttempts, RenderedError};
use super::completion::CompletionDriver;
use super::execute::{execute_chunk, record_task_result, ChunkOutcome, ChunkTaskContext};
@@ -185,6 +187,10 @@ impl SeederOrchestrator {
&shutdown,
);
self.reap_poisoned_chunks(&eligible_runs).await;
+ // Immediately after reaping, which is where terminal chunk failures are minted,
+ // and before the completion driver's tick, so a run can never be failed and
+ // CAS'd to `reconciling` in the same pass.
+ self.fail_exhausted_runs(&eligible_runs).await;
self.fill_claim_slots(&eligible_runs, &mut tasks, &mut person_tasks, &shutdown)
.await;
if let Some(driver) = &self.completion_driver {
@@ -281,6 +287,33 @@ impl SeederOrchestrator {
}
}
+ /// Terminalize runs holding a chunk that exhausted its retry budget, one kind at a time.
+ ///
+ /// Such a chunk is never reclaimed again, and the completion CAS demands every chunk
+ /// `confirmed`, so without this the run sits in `seeding` forever and holds its cohort's
+ /// uniqueness slot — no future run for that cohort can ever be created. Failing it frees the
+ /// slot (Django does not count `failed` as active) and puts the reason in `runs.error`.
+ ///
+ /// Nothing has to be unwound for chunks still mid-scan: their heartbeat and the claim predicate
+ /// both join `runs.status = 'seeding'`, so they lose their lease on the next beat and halt
+ /// cleanly — the same mechanism a Django-side supersede already relies on.
+ async fn fail_exhausted_runs(&self, eligible_runs: &HashMap<RunId, PreparedRun>) {
+ for kind in [RunKind::Behavioral, RunKind::PersonProperty] {
+ let run_ids = run_ids_of_kind(eligible_runs, kind);
+ if run_ids.is_empty() {
+ continue;
+ }
+ fail_exhausted_runs_of_kind(
+ &self.pool,
+ &self.store,
+ &run_ids,
+ kind,
+ self.settings.max_chunk_attempts,
+ )
+ .await;
+ }
+ }
+
/// Claim work for whichever kind still has slot capacity. The claimable run-id set is
/// recomputed per claim from the remaining capacity, so a person chunk can never occupy a
/// behavioral slot (or vice versa) — the two budgets are independent by construction.
@@ -384,6 +417,60 @@ impl SeederOrchestrator {
}
}
+/// Fail every run in `run_ids` that holds a chunk past the attempt cap; returns how many it failed.
+///
+/// A free function rather than a method so the Postgres suite can drive the fix itself: building a
+/// [`SeederOrchestrator`] needs a scanner, a producer, a pacer and a lifecycle handle, none of which
+/// a store test has, and the method above is only a per-kind loop over this body.
+pub async fn fail_exhausted_runs_of_kind(
+ pool: &PgPool,
+ store: &PgChunkStore,
+ run_ids: &[RunId],
+ kind: RunKind,
+ max_attempts: MaxAttempts,
+) -> u64 {
+ let exhausted = match store
+ .runs_with_exhausted_chunks(run_ids, max_attempts)
+ .await
+ {
+ Ok(exhausted) => exhausted,
+ Err(error) => {
+ warn!(error = %error, "scanning for runs with exhausted chunks failed");
+ return 0;
+ }
+ };
+ let mut failed = 0;
+ for run in exhausted {
+ let error = RenderedError::from_message(format!(
+ "{} chunk(s) exhausted the {} attempt retry budget; chunk {}: {}",
+ run.exhausted,
+ max_attempts.get(),
+ run.chunk_id,
+ run.last_error,
+ ));
+ match fail_run(pool, run.run_id, &error).await {
+ Ok(()) => {
+ counter!(RUNS_FAILED_EXHAUSTED_CHUNKS, "kind" => kind.as_str()).increment(1);
+ failed += 1;
+ warn!(
+ run_id = ?run.run_id,
+ exhausted = run.exhausted,
+ chunk_id = %run.chunk_id,
+ kind = kind.as_str(),
+ "failing run: chunks exhausted their retry budget"
+ );
+ }
+ // Already terminal — a later pass re-reads the same exhausted chunks, so this is the
+ // steady state, not an error, and must not re-count the metric.
+ Err(RunError::NotActive(_)) => {}
+ Err(error) => {
+ warn!(run_id = ?run.run_id, error = %error, "failing exhausted run failed")
+ }
+ }
+ }
+ failed
+}
+
fn record_claim(claim_kind: ClaimKind, run_kind: RunKind) {
counter!(CHUNKS_CLAIMED, "kind" => run_kind.as_str()).increment(1);
if claim_kind == ClaimKind::Reclaim {
diff --git a/rust/cohort-seeder/src/observability/metrics.rs b/rust/cohort-seeder/src/observability/metrics.rs
index 98b4a79b2633..e73c1486f934 100644
--- a/rust/cohort-seeder/src/observability/metrics.rs
+++ b/rust/cohort-seeder/src/observability/metrics.rs
@@ -22,6 +22,11 @@ pub const CHUNKS_CONFIRMED: &str = "seeder_chunks_confirmed_total";
pub const CHUNKS_VACUOUS: &str = "seeder_chunks_vacuous_total";
pub const CHUNKS_FAILED: &str = "seeder_chunks_failed_total";
pub const CHUNKS_POISONED: &str = "seeder_chunks_poisoned_total";
+/// Runs terminally failed because ≥1 chunk exhausted its retry budget, labelled by `kind`.
+/// Such a run would otherwise park in `seeding` forever and hold its cohort's uniqueness slot,
+/// blocking every future run for that cohort. The paired `warn!` carries the chunk and its error,
+/// which is what an operator reads once this counter points them at a run.
+pub const RUNS_FAILED_EXHAUSTED_CHUNKS: &str = "seeder_runs_failed_exhausted_chunks_total";
pub const CHUNK_SCAN_DURATION_SECONDS: &str = "seeder_chunk_scan_duration_seconds";
pub const ROWS_SCANNED: &str = "seeder_rows_scanned_total";
pub const EVENTS_SKIPPED: &str = "seeder_events_skipped_total";
diff --git a/rust/cohort-seeder/src/store/chunks.rs b/rust/cohort-seeder/src/store/chunks.rs
index 6d637aaad833..b5d85bc2cb84 100644
--- a/rust/cohort-seeder/src/store/chunks.rs
+++ b/rust/cohort-seeder/src/store/chunks.rs
@@ -316,6 +316,43 @@ impl PgChunkStore {
Ok(result.rows_affected())
}
+ /// Runs holding ≥1 chunk that exhausted its retry budget, with a representative chunk and its
+ /// persisted error.
+ ///
+ /// The `attempts >= max_attempts` half is the whole point: a `failed` chunk still under the cap
+ /// is reclaimable by [`Self::claim_next`] and will retry, while a capped one never will. Only
+ /// the capped ones are terminal, and only they wedge the run — the completion CAS demands every
+ /// chunk `confirmed`, so a run carrying one sits in `seeding` forever and holds its cohort's
+ /// uniqueness slot against every future run.
+ pub async fn runs_with_exhausted_chunks(
+ &self,
+ run_ids: &[RunId],
+ max_attempts: MaxAttempts,
+ ) -> Result<Vec<ExhaustedRun>, ChunkStoreError> {
+ if run_ids.is_empty() {
+ return Ok(Vec::new());
+ }
+ let run_ids = run_ids.iter().map(|run_id| run_id.0).collect::<Vec<_>>();
+ let rows = sqlx::query_as::<_, ExhaustedRunRow>(
+ r#"
+ SELECT DISTINCT ON (run_id)
+ run_id,
+ count(*) OVER (PARTITION BY run_id) AS exhausted,
+ id::text AS chunk_id,
+ last_error
+ FROM cohort_backfill_chunks
+ WHERE run_id = ANY($1) AND status = $2 AND attempts >= $3
+ ORDER BY run_id, id
+ "#,
+ )
+ .bind(run_ids)
+ .bind(ChunkStatus::Failed.as_str())
+ .bind(max_attempts.get())
+ .fetch_all(&self.pool)
+ .await?;
+ Ok(rows.into_iter().map(ExhaustedRun::from).collect())
+ }
+
/// The person path's mark: seeds were already streamed to Kafka during the scan, so only the
/// count crosses the `scanning`→`produced` CAS.
pub async fn mark_produced_streamed(
@@ -657,6 +694,48 @@ impl ChunkProgress {
}
}
+/// A run wedged by chunks that exhausted their retry budget, as reported by
+/// [`PgChunkStore::runs_with_exhausted_chunks`].
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct ExhaustedRun {
+ pub run_id: RunId,
+ pub exhausted: u64,
+ /// One of the exhausted chunks, for the operator-facing error text. Which one is arbitrary but
+ /// stable (lowest id) — the point is a concrete row to go read, not a complete list.
+ pub chunk_id: String,
+ /// That same chunk's error, never another one's: an operator handed chunk A with chunk B's
+ /// failure text reads the wrong row. [`NO_ERROR_RECORDED`] when the chunk recorded none.
+ pub last_error: String,
+}
+
+/// Stands in for an empty `last_error` so the operator-facing message never ends in a bare colon.
+/// A capped chunk normally carries one, but `attempts` can reach the cap without a persisted error.
+pub const NO_ERROR_RECORDED: &str = "no error recorded";
+
+impl From<ExhaustedRunRow> for ExhaustedRun {
+ fn from(row: ExhaustedRunRow) -> Self {
+ Self {
+ run_id: row.run_id,
+ // `count(*) OVER (PARTITION BY run_id)` is ≥ 1 and bounded by the run's chunk count, so
+ // the cast cannot lose information.
+ exhausted: row.exhausted.max(0) as u64,
+ chunk_id: row.chunk_id.unwrap_or_default(),
+ last_error: row
+ .last_error
+ .filter(|error| !error.is_empty())
+ .unwrap_or_else(|| NO_ERROR_RECORDED.to_owned()),
+ }
+ }
+}
+
+#[derive(Debug, FromRow)]
+struct ExhaustedRunRow {
+ run_id: RunId,
+ exhausted: i64,
+ chunk_id: Option<String>,
+ last_error: Option<String>,
+}
+
#[derive(Debug, FromRow)]
struct ClaimedRow {
id: ChunkId,
diff --git a/rust/cohort-seeder/tests/pg_chunks.rs b/rust/cohort-seeder/tests/pg_chunks.rs
index f726603ec364..643639ab555b 100644
--- a/rust/cohort-seeder/tests/pg_chunks.rs
+++ b/rust/cohort-seeder/tests/pg_chunks.rs
@@ -12,6 +12,7 @@ use std::time::Duration;
use anyhow::{bail, ensure, Context, Result};
use cohort_core::filters::{CohortId, TeamId};
+use cohort_seeder::app::fail_exhausted_runs_of_kind;
use cohort_seeder::app::reconcile_dispatch::{
prepare_reconcile_dispatch, CompletionRequirement, PrepareReconcileDispatchError,
RegisterBackfillConfirmation,
@@ -19,7 +20,7 @@ use cohort_seeder::app::reconcile_dispatch::{
use cohort_seeder::domain::{
tile_ranges, ClaimEpoch, PersonRunValidation, PinnedWarning, ProduceHwms, ScopeKind,
};
-use cohort_seeder::store::chunks::{ChunkStoreError, PgChunkStore, PlanOutcome};
+use cohort_seeder::store::chunks::{ChunkStoreError, PgChunkStore, PlanOutcome, NO_ERROR_RECORDED};
use cohort_seeder::store::lease::LeaseFailure;
use cohort_seeder::store::runs::{
discover_runs, establish_boundary, fail_run, load_reconcile_run, record_run_warning,
@@ -803,6 +804,214 @@ async fn expired_scanning_chunk_at_the_cap_is_reaped_not_reclaimed() -> Result<(
.await
}
+/// Only chunks that saturated the attempt cap count as exhausted. A `failed` chunk still under the
+/// cap is reclaimable and will retry, so reporting it would fail runs that were about to recover.
+#[tokio::test]
+async fn runs_with_exhausted_chunks_selects_only_capped_failures() -> Result<()> {
+ with_db(|pool| async move {
+ let seeding_run =
+ insert_run(&pool, 2, "team_enablement", "seeding", true, empty_pinned()).await?;
+ let store = PgChunkStore::new(pool.clone());
+ ensure!(planned_count(store.plan_chunks(seeding_run, [100, 101], ONE_BAND).await?)? == 2);
+ let attempts5 = MaxAttempts::new(5)?;
+ let run_ids = [seeding_run];
+
+ let chunk_ids: Vec<Uuid> = sqlx::query_scalar(
+ "SELECT id FROM cohort_backfill_chunks WHERE run_id = $1 ORDER BY day",
+ )
+ .bind(seeding_run)
+ .fetch_all(&pool)
+ .await?;
+ sqlx::query(
+ "UPDATE cohort_backfill_chunks SET status = 'failed', attempts = 4, last_error = 'still retrying' WHERE id = $1",
+ )
+ .bind(chunk_ids[0])
+ .execute(&pool)
+ .await?;
+ ensure!(store
+ .runs_with_exhausted_chunks(&run_ids, attempts5)
+ .await?
+ .is_empty());
+
+ sqlx::query(
+ "UPDATE cohort_backfill_chunks SET status = 'failed', attempts = 5, last_error = 'scan blew up' WHERE id = $1",
+ )
+ .bind(chunk_ids[1])
+ .execute(&pool)
+ .await?;
+ let exhausted = store.runs_with_exhausted_chunks(&run_ids, attempts5).await?;
+ ensure!(exhausted.len() == 1);
+ ensure!(exhausted[0].run_id == seeding_run);
+ ensure!(exhausted[0].exhausted == 1, "only the capped chunk counts");
+ ensure!(exhausted[0].chunk_id == chunk_ids[1].to_string());
+ ensure!(exhausted[0].last_error == "scan blew up");
+
+ ensure!(store
+ .runs_with_exhausted_chunks(&[], attempts5)
+ .await?
+ .is_empty());
+ Ok(())
+ })
+ .await
+}
+
+/// The reported chunk and error come from one row. Aggregating them independently pairs the lowest
+/// chunk id with some other chunk's error, sending the operator to read a row that never failed
+/// that way.
+#[tokio::test]
+async fn exhausted_chunk_and_error_are_read_off_the_same_row() -> Result<()> {
+ with_db(|pool| async move {
+ let seeding_run =
+ insert_run(&pool, 2, "team_enablement", "seeding", true, empty_pinned()).await?;
+ let store = PgChunkStore::new(pool.clone());
+ ensure!(planned_count(store.plan_chunks(seeding_run, [100, 101], ONE_BAND).await?)? == 2);
+ let attempts5 = MaxAttempts::new(5)?;
+
+ // Ordered so the lowest-id chunk carries the *higher* error text: an independent
+ // `min(last_error)` would then hand back the other chunk's error.
+ let mut chunk_ids: Vec<Uuid> =
+ sqlx::query_scalar("SELECT id FROM cohort_backfill_chunks WHERE run_id = $1")
+ .bind(seeding_run)
+ .fetch_all(&pool)
+ .await?;
+ chunk_ids.sort();
+ for (chunk_id, error) in chunk_ids.iter().zip(["zzz lowest id", "aaa highest id"]) {
+ sqlx::query(
+ "UPDATE cohort_backfill_chunks SET status = 'failed', attempts = 5, last_error = $2 WHERE id = $1",
+ )
+ .bind(chunk_id)
+ .bind(error)
+ .execute(&pool)
+ .await?;
+ }
+
+ let exhausted = store
+ .runs_with_exhausted_chunks(&[seeding_run], attempts5)
+ .await?;
+ ensure!(exhausted.len() == 1);
+ ensure!(exhausted[0].exhausted == 2, "both capped chunks counted");
+ ensure!(exhausted[0].chunk_id == chunk_ids[0].to_string());
+ ensure!(exhausted[0].last_error == "zzz lowest id");
+
+ // A capped chunk with no persisted error still has to render as something: the run error
+ // interpolates this text, and an empty one leaves the operator a trailing colon.
+ sqlx::query("UPDATE cohort_backfill_chunks SET last_error = '' WHERE id = $1")
+ .bind(chunk_ids[0])
+ .execute(&pool)
+ .await?;
+ let exhausted = store
+ .runs_with_exhausted_chunks(&[seeding_run], attempts5)
+ .await?;
+ ensure!(exhausted[0].last_error == NO_ERROR_RECORDED);
+ Ok(())
+ })
+ .await
+}
+
+/// Failing a run whose chunk exhausted its retries stops the run dead: a still-pending sibling is no
+/// longer claimable, a live sibling's heartbeat is refused, and a second failure is a no-op rather
+/// than a double-count. Without it the run sits in `seeding` forever holding its cohort's slot.
+#[tokio::test]
+async fn exhausted_chunk_fails_the_run_and_stops_further_claims() -> Result<()> {
+ with_db(|pool| async move {
+ let seeding_run =
+ insert_run(&pool, 2, "team_enablement", "seeding", true, empty_pinned()).await?;
+ let store = PgChunkStore::new(pool.clone());
+ ensure!(
+ planned_count(store.plan_chunks(seeding_run, [100, 101, 102], ONE_BAND).await?)? == 3
+ );
+
+ let lease60 = LeaseDuration::new(Duration::from_secs(60))?;
+ let attempts5 = MaxAttempts::new(5)?;
+ let run_ids = [seeding_run];
+ let claimant = Claimant::new("worker-a")?;
+
+ // One chunk mid-scan with a live lease, one capped out, one left pending.
+ let claimed = store
+ .claim_next(&run_ids, &claimant, lease60, attempts5)
+ .await?
+ .context("claimant found no chunk")?;
+ let live_lease = claimed.chunk.spec().lease;
+ let capped_id: Uuid = sqlx::query_scalar(
+ "SELECT id FROM cohort_backfill_chunks WHERE run_id = $1 AND status = 'pending' ORDER BY day LIMIT 1",
+ )
+ .bind(seeding_run)
+ .fetch_one(&pool)
+ .await?;
+ sqlx::query(
+ "UPDATE cohort_backfill_chunks SET status = 'failed', attempts = 5, last_error = 'scan blew up' WHERE id = $1",
+ )
+ .bind(capped_id)
+ .execute(&pool)
+ .await?;
+
+ // Through the seeder's own pass, not a hand-rolled equivalent: the scan, the error text and
+ // the attempt-cap interpolation are what an operator ends up reading.
+ ensure!(
+ fail_exhausted_runs_of_kind(
+ &pool,
+ &store,
+ &run_ids,
+ RunKind::Behavioral,
+ attempts5
+ )
+ .await
+ == 1
+ );
+
+ let (status, error, finished): (String, String, bool) = sqlx::query_as(
+ "SELECT status, error, finished_at IS NOT NULL FROM cohort_backfill_runs WHERE id = $1",
+ )
+ .bind(seeding_run)
+ .fetch_one(&pool)
+ .await?;
+ ensure!(status == "failed");
+ ensure!(error.contains("1 chunk(s) exhausted the 5 attempt retry budget"));
+ ensure!(error.contains(&capped_id.to_string()));
+ ensure!(error.contains("scan blew up"));
+ ensure!(finished);
+
+ // The claim and heartbeat predicates both join `runs.status = 'seeding'`, so the pending
+ // sibling stops being claimable and the in-flight one halts on its next beat.
+ ensure!(store
+ .claim_next(&run_ids, &Claimant::new("worker-b")?, lease60, attempts5)
+ .await?
+ .is_none());
+ let still_pending: i64 = sqlx::query_scalar(
+ "SELECT count(*) FROM cohort_backfill_chunks WHERE run_id = $1 AND status = 'pending'",
+ )
+ .bind(seeding_run)
+ .fetch_one(&pool)
+ .await?;
+ ensure!(
+ still_pending == 1,
+ "a claimable chunk remained, so the run status is what blocked the claim"
+ );
+ ensure_lease_lost(test_support::heartbeat(&store, live_lease, &claimant, lease60).await)?;
+ drop(claimed);
+
+ // Idempotent: a later pass re-reads the same exhausted chunks, and the already-terminal run
+ // must not be counted again.
+ ensure!(
+ fail_exhausted_runs_of_kind(
+ &pool,
+ &store,
+ &run_ids,
+ RunKind::Behavioral,
+ attempts5
+ )
+ .await
+ == 0
+ );
+ ensure!(matches!(
+ fail_run(&pool, seeding_run, &RenderedError::from_message("again")).await,
+ Err(RunError::NotActive(_))
+ ));
+ Ok(())
+ })
+ .await
+}
+
/// Both persisted error columns are truncated to the limit: `chunk.fail` clamps `last_error` and
/// `fail_run` clamps `run.error`, each flipping the row to `failed`.
#[tokio::test]
diff --git a/rust/cohort-stream-processor/src/filters/manager.rs b/rust/cohort-stream-processor/src/filters/manager.rs
index 6a890e729108..141cfc4361af 100644
--- a/rust/cohort-stream-processor/src/filters/manager.rs
+++ b/rust/cohort-stream-processor/src/filters/manager.rs
@@ -4,12 +4,12 @@ use std::collections::hash_map::DefaultHasher;
use std::hash::{Hash, Hasher};
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::Arc;
-use std::time::Duration;
+use std::time::{Duration, SystemTime, UNIX_EPOCH};
use arc_swap::{ArcSwap, Guard};
use common_types::cohort::TeamAllowlist;
use lifecycle::Handle;
-use metrics::gauge;
+use metrics::{counter, gauge};
use rand::Rng;
use sqlx::PgPool;
use tokio::sync::Notify;
@@ -18,7 +18,10 @@ use tracing::{debug, info, warn};
use crate::filters::loader::{build_catalog_from_rows, load_realtime_cohorts, CohortRow};
use crate::filters::FilterError;
use crate::filters::{FilterCatalog, Generation};
-use crate::observability::metrics::{FILTER_CATALOG_TEAMS, FILTER_CATALOG_UNIQUE_CONDITIONS};
+use crate::observability::metrics::{
+ FILTER_CATALOG_LAST_SUCCESS_TIMESTAMP_SECONDS, FILTER_CATALOG_REFRESH_TOTAL,
+ FILTER_CATALOG_TEAMS, FILTER_CATALOG_UNIQUE_CONDITIONS,
+};
/// Snapshot counts returned by [`CatalogHandle::refresh`] for logging.
#[derive(Debug, Clone, Copy)]
@@ -122,7 +125,25 @@ impl CatalogHandle {
}
/// Query `posthog_cohort`, drop out-of-scope teams, rebuild the catalog, and swap it in.
+ ///
+ /// The staleness metrics are stamped here rather than in [`run_refresh_loop`] so the boot load
+ /// in `main` counts too — otherwise a pod that booted fine and then lost its refresh loop would
+ /// look identical to one that never loaded.
pub async fn refresh(&self, pool: &PgPool) -> Result<CatalogStats, FilterError> {
+ match self.refresh_inner(pool).await {
+ Ok(stats) => {
+ gauge!(FILTER_CATALOG_LAST_SUCCESS_TIMESTAMP_SECONDS).set(now_unix_seconds());
+ counter!(FILTER_CATALOG_REFRESH_TOTAL, "result" => "success").increment(1);
+ Ok(stats)
+ }
+ Err(err) => {
+ counter!(FILTER_CATALOG_REFRESH_TOTAL, "result" => "error").increment(1);
+ Err(err)
+ }
+ }
+ }
+
+ async fn refresh_inner(&self, pool: &PgPool) -> Result<CatalogStats, FilterError> {
let mut rows = load_realtime_cohorts(pool).await?;
let fetched_rows = rows.len();
retain_allowlisted(&mut rows, &self.allowlist);
@@ -143,6 +164,14 @@ impl CatalogHandle {
}
}
+/// Seconds since the Unix epoch, saturating at 0 on a clock set before it.
+fn now_unix_seconds() -> f64 {
+ SystemTime::now()
+ .duration_since(UNIX_EPOCH)
+ .map(|since| since.as_secs_f64())
+ .unwrap_or(0.0)
+}
+
/// Drop rows outside the configured team scope before catalog construction.
fn retain_allowlisted(rows: &mut Vec<CohortRow>, allowlist: &TeamAllowlist) {
rows.retain(|row| allowlist.includes(row.team_id));
@@ -321,6 +350,14 @@ mod tests {
assert_eq!(handle.load().generation(), Generation(1));
}
+ #[test]
+ fn now_unix_seconds_is_a_plausible_epoch_second() {
+ // The staleness alert computes `time() - gauge`, so a gauge stamped in the wrong unit (or
+ // from a monotonic clock starting near zero) would read as decades stale and page forever.
+ let now = now_unix_seconds();
+ assert!(now > 1_700_000_000.0, "expected epoch seconds, got {now}");
+ }
+
#[test]
fn no_op_refresh_keeps_the_generation_and_a_content_change_bumps_it() {
let handle = CatalogHandle::new();
diff --git a/rust/cohort-stream-processor/src/observability/metrics.rs b/rust/cohort-stream-processor/src/observability/metrics.rs
index 7b98382d1ce6..e7b75534107b 100644
--- a/rust/cohort-stream-processor/src/observability/metrics.rs
+++ b/rust/cohort-stream-processor/src/observability/metrics.rs
@@ -13,6 +13,19 @@ pub use cohort_core::metrics::{
pub const FILTER_CATALOG_TEAMS: &str = "filter_catalog_teams";
/// Distinct `conditionHash`es across all teams in the current snapshot (gauge).
pub const FILTER_CATALOG_UNIQUE_CONDITIONS: &str = "filter_catalog_unique_conditions";
+/// Unix timestamp of the last *successful* catalog refresh (gauge, seconds). Stamped inside
+/// `CatalogHandle::refresh`, so the boot load and the periodic loop both advance it. **Alert on
+/// staleness** via `time() - gauge`: a failed refresh keeps serving the previous snapshot silently,
+/// so cohort edits go invisible with nothing else moving. A gauge written only on success would go
+/// flat rather than climb, and the refresh loop is a detached task — a per-tick age gauge would
+/// freeze if it died. A timestamp keeps aging either way. Absent until the first successful refresh;
+/// the pipeline fails closed until then and the pod is not Ready, so the alert must be a plain
+/// threshold, never `absent()`.
+pub const FILTER_CATALOG_LAST_SUCCESS_TIMESTAMP_SECONDS: &str =
+ "filter_catalog_last_success_timestamp_seconds";
+/// Catalog refresh attempts, labelled by `result` (`success`|`error`) (counter). The `error` series
+/// gives the failure rate; the `success` series proves the loop is still ticking at all.
+pub const FILTER_CATALOG_REFRESH_TOTAL: &str = "filter_catalog_refresh_total";
/// Cascade depths reached, from the `depth` field on cascade messages (histogram). Cohort ids are
/// logged, not labelled, to keep cardinality bounded.
pub const CASCADE_DEPTH_OBSERVED: &str = "cascade_depth_observed";
@@ -577,6 +590,22 @@ pub fn install_recorder() -> PrometheusHandle {
mod tests {
use super::*;
+ #[test]
+ fn filter_catalog_metric_names_are_stable() {
+ // The staleness alert is written against these literals, so a rename here silently disarms
+ // the only signal that says the catalog stopped tracking cohort edits.
+ assert_eq!(FILTER_CATALOG_TEAMS, "filter_catalog_teams");
+ assert_eq!(
+ FILTER_CATALOG_UNIQUE_CONDITIONS,
+ "filter_catalog_unique_conditions",
+ );
+ assert_eq!(
+ FILTER_CATALOG_LAST_SUCCESS_TIMESTAMP_SECONDS,
+ "filter_catalog_last_success_timestamp_seconds",
+ );
+ assert_eq!(FILTER_CATALOG_REFRESH_TOTAL, "filter_catalog_refresh_total");
+ }
+
#[test]
fn cascade_metric_names_are_stable() {
assert_eq!(CASCADE_DEPTH_OBSERVED, "cascade_depth_observed");