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.

fix(cohorts): fail a backfill run closed when its cohort cannot be seeded (#103145)

Matheus Batistaf166a3bd8d21
diff --git a/posthog/tasks/test/test_calculate_cohort.py b/posthog/tasks/test/test_calculate_cohort.py
index 01f471103cb0..e090b5fe9422 100644
--- a/posthog/tasks/test/test_calculate_cohort.py
+++ b/posthog/tasks/test/test_calculate_cohort.py
@@ -55,6 +55,12 @@ from products.cohorts.backend.models.util import (
list_cohort_member_ids,
)
+# The catalog drops a leaf with no bytecode, and `_calculate_realtime_support` grants
+# `cohort_type=REALTIME` only when every leaf compiled to bytecode. A fixture without it is a
+# cohort shape no realtime cohort can have.
+_BYTECODE = ["_H", 1, 32, "matched", 32, "event", 1, 1, 11]
+
+
MISSING_COHORT_ID = 12345
BACKFILL_KINDS = [("behavioral", CohortBackfillKind.BEHAVIORAL), ("person", CohortBackfillKind.PERSON_PROPERTY)]
@@ -1124,6 +1130,7 @@ class TestCohortCalculationTasks(APIBaseTest):
"conditionHash": "behavior00000001",
"time_value": 7,
"time_interval": "day",
+ "bytecode": _BYTECODE,
},
{
"type": "person",
@@ -1131,6 +1138,7 @@ class TestCohortCalculationTasks(APIBaseTest):
"value": ["[email protected]"],
"operator": "exact",
"conditionHash": "person0000000001",
+ "bytecode": _BYTECODE,
},
],
}
diff --git a/products/cohorts/backend/backfill/pinning.py b/products/cohorts/backend/backfill/pinning.py
index 92af067a38f3..310daaee23e3 100644
--- a/products/cohorts/backend/backfill/pinning.py
+++ b/products/cohorts/backend/backfill/pinning.py
@@ -5,6 +5,7 @@ import structlog
from products.cohorts.backend.models.cohort import Cohort
from products.cohorts.backend.models.leaf_shape import walk_filter_leaves
+from products.cohorts.backend.parity.eligibility import is_action_key, leaf_drop_reason
_INTERVAL_DAYS = {"day": 1, "week": 7, "month": 30, "year": 365}
logger = structlog.get_logger(__name__)
@@ -26,6 +27,17 @@ def derive_window_days(time_value: object, time_interval: object) -> int:
return normalized_time_value * _INTERVAL_DAYS.get(time_interval, 0)
+def leaf_unpinnable_reason(leaf: dict[str, Any]) -> str | None:
+ """The catalog's drop label for a leaf the seeder could never resolve, or ``None``.
+
+ Every leaf type, not only behavioral: a cohort that loses any leaf classifies
+ ``Excluded(HasDroppedLeaf)``, so one refused `person_metadata` leaf takes the whole cohort out
+ of composition. Delegates to the processor mirror, which already carries the 16-byte hash and
+ HogVM header rules a second copy here would have to restate.
+ """
+ return leaf_drop_reason(leaf)
+
+
def pin_conditions_for_cohorts(cohorts: Iterable[Cohort]) -> tuple[dict[str, Any], list[str]]:
conditions: list[dict[str, Any]] = []
event_names: set[str] = set()
@@ -37,7 +49,9 @@ def pin_conditions_for_cohorts(cohorts: Iterable[Cohort]) -> tuple[dict[str, Any
continue
event_key = leaf.get("key")
- is_action = leaf.get("event_type") == "actions" or isinstance(event_key, int)
+ # The seeder drops an action-keyed condition, so reading `event_type` here as well would
+ # drop a leaf the gate admits.
+ is_action = is_action_key(event_key)
event_name = event_key if isinstance(event_key, str) and not is_action else None
if event_name is not None:
event_names.add(event_name)
diff --git a/products/cohorts/backend/backfill/runs.py b/products/cohorts/backend/backfill/runs.py
index 5dfd94221c30..44cf10a95aed 100644
--- a/products/cohorts/backend/backfill/runs.py
+++ b/products/cohorts/backend/backfill/runs.py
@@ -1,4 +1,4 @@
-from collections.abc import Iterable
+from collections.abc import Callable, Iterable
from datetime import UTC, datetime, timedelta
from enum import StrEnum
from typing import Any
@@ -16,6 +16,7 @@ from posthog.models.team.team import Team
from products.cohorts.backend.backfill.pinning import (
PersonPinningCapExceeded,
+ leaf_unpinnable_reason,
pin_conditions_for_cohorts,
pin_person_conditions_for_cohorts,
)
@@ -36,6 +37,7 @@ from products.cohorts.backend.models.backfill import (
)
from products.cohorts.backend.models.cohort import Cohort, CohortType
from products.cohorts.backend.models.leaf_shape import walk_filter_leaves
+from products.cohorts.backend.parity.eligibility import structural_exclusion
from products.cohorts.backend.realtime_teams import is_realtime_cohort_team
logger = structlog.get_logger(__name__)
@@ -82,11 +84,6 @@ def check_person_run_preconditions() -> tuple[dict[str, Any], list[str]]:
return preconditions, missing
-def has_behavioral_filters(cohort: Cohort) -> bool:
- properties = (cohort.filters or {}).get("properties")
- return any(leaf.get("type") == "behavioral" for leaf in walk_filter_leaves(properties))
-
-
def _has_pinnable_person_filters(cohort: Cohort) -> bool:
properties = (cohort.filters or {}).get("properties")
return any(
@@ -100,6 +97,30 @@ def _contains_person_metadata_leaf(cohort: Cohort) -> bool:
return any(leaf.get("type") == "person_metadata" for leaf in walk_filter_leaves(properties))
+def _catalog_refusal_reason(cohort: Cohort) -> str | None:
+ """The refusal for a cohort the frozen catalog will not compose, or ``None``.
+
+ The catalog excludes a cohort whole for one dropped leaf, so both run kinds screen every leaf.
+ The tree is screened too: the seeder fails a whole team run over one cohort with a negated root,
+ which has no dropped leaf.
+ """
+ for leaf in walk_filter_leaves((cohort.filters or {}).get("properties")):
+ reason = leaf_unpinnable_reason(leaf)
+ if reason is not None:
+ return f"has a filter the realtime catalog drops ({reason})"
+ exclusion = structural_exclusion(cohort.filters)
+ if exclusion is not None:
+ return f"has a shape the realtime catalog will not compose ({exclusion})"
+ return None
+
+
+NO_BEHAVIORAL_FILTER = "has no behavioral filter"
+NO_PERSON_FILTER = "has no person filter with a condition hash"
+# Reasons that say only that this run kind does not apply to the cohort. Every save of a cohort
+# carrying the other kind's leaves produces one, so they are not a refusal an operator can act on.
+INAPPLICABLE_BACKFILL_REASONS = frozenset({NO_BEHAVIORAL_FILTER, NO_PERSON_FILTER})
+
+
def person_backfill_ineligibility_reason(cohort: Cohort) -> str | None:
"""The single person-run eligibility predicate, shared by the creators, the management command,
and the dispatch receiver so none of them can judge a cohort backfillable that another refuses."""
@@ -112,8 +133,48 @@ def person_backfill_ineligibility_reason(cohort: Cohort) -> str | None:
if _contains_person_metadata_leaf(cohort):
return "contains person_metadata filters"
if not _has_pinnable_person_filters(cohort):
- return "has no person filter with a condition hash"
- return None
+ return NO_PERSON_FILTER
+ return _catalog_refusal_reason(cohort)
+
+
+def behavioral_backfill_ineligibility_reason(cohort: Cohort) -> str | None:
+ """The single behavioral-run eligibility predicate, shared by the creators, the management
+ command, and the dispatch receiver so none of them can judge a cohort backfillable that another
+ refuses.
+
+ A cohort with any leaf the frozen catalog would drop is refused whole rather than narrowed to
+ its seedable leaves, because the processor excludes such a cohort from composition entirely and
+ a readiness stamp on it would claim a membership the flags reader can never see. The exclusion
+ is per cohort, not per leaf, so a refused `person_metadata` leaf beside a seedable behavioral
+ one takes the whole cohort out — every leaf is screened, not only the behavioral ones.
+ """
+ if cohort.cohort_type != CohortType.REALTIME:
+ return "not realtime"
+ if cohort.is_static:
+ return "static"
+ if cohort.deleted:
+ return "deleted"
+ properties = (cohort.filters or {}).get("properties")
+ if not any(leaf.get("type") == "behavioral" for leaf in walk_filter_leaves(properties)):
+ return NO_BEHAVIORAL_FILTER
+ return _catalog_refusal_reason(cohort)
+
+
+def judge_team_cohorts(
+ team_id: int,
+ cohort_ids: list[int] | None,
+ ineligibility_reason: Callable[[Cohort], str | None],
+) -> list[tuple[Cohort, str | None]]:
+ """Every cohort of the team, or of ``cohort_ids``, paired with its refusal or ``None``.
+
+ Deliberately wider than the run creators, which narrow the SQL-expressible half of eligibility
+ away before they lock: a dry run exists to name *why* each cohort was refused, and it takes no
+ locks. Both sides decide with the same predicate.
+ """
+ queryset = Cohort.objects.filter(team_id=team_id)
+ if cohort_ids is not None:
+ queryset = queryset.filter(id__in=cohort_ids)
+ return [(cohort, ineligibility_reason(cohort)) for cohort in queryset.order_by("id")]
def _run_status(preconditions_missing: list[str]) -> tuple[str, str]:
@@ -243,12 +304,14 @@ def attempt_backfill_run_for_cohort(team_id: int, cohort_id: int, trigger_kind:
)
if cohort is None:
return BackfillRunAttempt.refused(BackfillRefusalReason.COHORT_MISSING)
- if (
- cohort.cohort_type != CohortType.REALTIME
- or cohort.is_static
- or cohort.deleted
- or not has_behavioral_filters(cohort)
- ):
+ ineligibility = behavioral_backfill_ineligibility_reason(cohort)
+ if ineligibility is not None:
+ logger.info(
+ "cohort_behavioral_backfill_ineligible",
+ team_id=team_id,
+ cohort_id=cohort_id,
+ reason=ineligibility,
+ )
return BackfillRunAttempt.refused(BackfillRefusalReason.COHORT_INELIGIBLE)
if _active_participation_cohort_ids(team_id, [cohort_id], kind=CohortBackfillKind.BEHAVIORAL):
return BackfillRunAttempt.refused(BackfillRefusalReason.PARTICIPATION_ACTIVE)
@@ -328,7 +391,9 @@ def create_team_backfill_run(
)
if requested_ids is not None:
queryset = queryset.filter(id__in=requested_ids)
- cohorts = [cohort for cohort in queryset.order_by("id") if has_behavioral_filters(cohort)]
+ cohorts = [
+ cohort for cohort in queryset.order_by("id") if behavioral_backfill_ineligibility_reason(cohort) is None
+ ]
if requested_ids is not None and {cohort.id for cohort in cohorts} != requested_ids:
invalid_ids = sorted(requested_ids - {cohort.id for cohort in cohorts})
raise ValueError(f"Cohorts are not eligible realtime behavioral cohorts: {invalid_ids}")
diff --git a/products/cohorts/backend/backfill/test/test_management_command.py b/products/cohorts/backend/backfill/test/test_management_command.py
index f1147268e307..4942f47763d5 100644
--- a/products/cohorts/backend/backfill/test/test_management_command.py
+++ b/products/cohorts/backend/backfill/test/test_management_command.py
@@ -19,6 +19,11 @@ from products.cohorts.backend.models.backfill import (
)
from products.cohorts.backend.models.cohort import Cohort, CohortType
+# The catalog drops a leaf with no bytecode or a `conditionHash` that is not 16 characters, and
+# `_calculate_realtime_support` grants `cohort_type=REALTIME` only when every leaf compiled to
+# bytecode. A fixture missing either is a cohort shape no realtime cohort can have.
+_BYTECODE = ["_H", 1, 32, "matched", 32, "event", 1, 1, 11]
+
@override_settings(
REALTIME_COHORT_TEAM_ALLOWLIST="all",
@@ -42,9 +47,10 @@ class TestCreateCohortBackfillRunCommand(BaseTest):
"key": event,
"event_type": "events",
"value": "performed_event",
- "conditionHash": f"hash-{event}",
+ "conditionHash": f"hash-{event}"[:16].ljust(16, "0"),
"time_value": 7,
"time_interval": "day",
+ "bytecode": _BYTECODE,
}
],
}
@@ -59,6 +65,7 @@ class TestCreateCohortBackfillRunCommand(BaseTest):
"value": ["[email protected]"],
"operator": "exact",
"conditionHash": "person0000000001",
+ "bytecode": _BYTECODE,
}
]
if person_metadata:
@@ -221,6 +228,63 @@ class TestCreateCohortBackfillRunCommand(BaseTest):
self.assertIn("Dry run", stdout.getvalue())
self.assertEqual(CohortBackfillRun.objects.for_team(self.team.id).count(), 0)
+ def test_behavioral_dry_run_names_every_refusal(self) -> None:
+ eligible = self._cohort("$pageview")
+ static = self._cohort("signup-static")
+ Cohort.objects.filter(id=static.id).update(is_static=True)
+ refused = Cohort.objects.create(
+ team=self.team,
+ cohort_type=CohortType.REALTIME,
+ filters={
+ "properties": {
+ "type": "AND",
+ "values": [
+ {
+ "type": "behavioral",
+ "key": "signup",
+ "event_type": "events",
+ "value": "performed_event",
+ "conditionHash": "hash-signup00000",
+ "bytecode": _BYTECODE,
+ }
+ ],
+ }
+ },
+ )
+ stdout = StringIO()
+
+ call_command(
+ "create_cohort_backfill_run",
+ team_id=self.team.id,
+ trigger="team_enablement",
+ dry_run=True,
+ stdout=stdout,
+ )
+
+ self.assertIn(
+ f"{refused.id} (has a filter the realtime catalog drops (unsupported_state_variant))",
+ stdout.getvalue(),
+ )
+ self.assertIn(f"{static.id} (static)", stdout.getvalue())
+ self.assertIn("Dry run: 1 cohorts", stdout.getvalue())
+ self.assertNotIn(f"{eligible.id} (", stdout.getvalue())
+
+ def test_behavioral_dry_run_refuses_a_team_with_nothing_runnable(self) -> None:
+ # The real command raises on the same team, so a dry run that exits 0 would tell
+ # exit-code-gated automation the run is possible.
+ static = self._cohort("signup")
+ static.is_static = True
+ static.save(update_fields=["is_static"])
+
+ with self.assertRaisesMessage(CommandError, "no eligible realtime behavioral cohorts"):
+ call_command(
+ "create_cohort_backfill_run",
+ team_id=self.team.id,
+ trigger="team_enablement",
+ dry_run=True,
+ stdout=StringIO(),
+ )
+
@override_settings(REALTIME_COHORT_TEAM_ALLOWLIST="none")
def test_non_allowlisted_team_errors(self) -> None:
with self.assertRaisesMessage(CommandError, "realtime cohort allowlist"):
diff --git a/products/cohorts/backend/backfill/test/test_pinning.py b/products/cohorts/backend/backfill/test/test_pinning.py
index 8bdf3471b1e5..73d32a3a3d78 100644
--- a/products/cohorts/backend/backfill/test/test_pinning.py
+++ b/products/cohorts/backend/backfill/test/test_pinning.py
@@ -7,6 +7,7 @@ from parameterized import parameterized
from products.cohorts.backend.backfill.pinning import (
PersonPinningCapExceeded,
derive_window_days,
+ leaf_unpinnable_reason,
pin_conditions_for_cohorts,
pin_person_conditions_for_cohorts,
)
@@ -28,6 +29,82 @@ class TestBackfillPinning(SimpleTestCase):
def test_derive_window_days(self, interval: str, value: object, expected: int) -> None:
self.assertEqual(derive_window_days(value, interval), expected)
+ @parameterized.expand(
+ [
+ ("windowed_performed_event", {}, None),
+ (
+ "explicit_absolute_range",
+ {"time_value": None, "time_interval": None, "explicit_datetime": "2026-01-03"},
+ None,
+ ),
+ # `classify_behavioral` reads a numeric key, never `event_type`, so the catalog keeps
+ # this leaf and the gate must too.
+ ("action_event_type_with_a_string_key", {"event_type": "actions"}, None),
+ ("sequence_value", {"value": "performed_event_sequence"}, "unsupported_behavioral_value"),
+ ("action_id_key", {"key": 42}, "behavioral_action_key"),
+ ("hashless", {"conditionHash": None}, "missing_condition_hash"),
+ ("short_hash", {"conditionHash": "aaaa"}, "missing_condition_hash"),
+ ("bytecodeless", {"bytecode": None}, "missing_bytecode"),
+ ("unloadable_bytecode", {"bytecode": [1, 2, 3]}, "malformed_bytecode"),
+ ("empty_key", {"key": ""}, "malformed_leaf"),
+ ("windowless", {"time_value": None, "time_interval": None}, "unsupported_state_variant"),
+ (
+ "sub_day_multiple",
+ {"value": "performed_event_multiple", "time_interval": "hour", "operator": "gte", "operator_value": 2},
+ "unsupported_state_variant",
+ ),
+ (
+ "relative_upper_bound",
+ {
+ "time_value": None,
+ "time_interval": None,
+ "explicit_datetime": "2026-01-03",
+ "explicit_datetime_to": "-1d",
+ },
+ "unsupported_state_variant",
+ ),
+ ]
+ )
+ def test_behavioral_leaf_screening(self, _name: str, overrides: dict, expected: str | None) -> None:
+ leaf = {
+ "type": "behavioral",
+ "key": "$pageview",
+ "event_type": "events",
+ "value": "performed_event",
+ "conditionHash": "aaaaaaaaaaaaaaaa",
+ "time_value": 7,
+ "time_interval": "day",
+ "bytecode": ["_H", 1, 32, "$pageview", 32, "event", 1, 1, 11],
+ **overrides,
+ }
+ self.assertEqual(leaf_unpinnable_reason(leaf), expected)
+
+ @parameterized.expand(
+ [
+ ("person_metadata", {"type": "person_metadata", "key": "distinct_id"}, "unknown_leaf_type"),
+ ("cohort_reference", {"type": "cohort", "value": 12}, None),
+ (
+ "person_leaf",
+ {
+ "type": "person",
+ "key": "email",
+ "conditionHash": "bbbbbbbbbbbbbbbb",
+ "bytecode": ["_H", 1, 32, "email", 32, "properties", 32, "person", 1, 3, 11],
+ },
+ None,
+ ),
+ (
+ "person_leaf_without_bytecode",
+ {"type": "person", "key": "email", "conditionHash": "bbbbbbbbbbbbbbbb"},
+ "missing_bytecode",
+ ),
+ ]
+ )
+ def test_non_behavioral_leaves_are_screened_too(self, _name: str, leaf: dict, expected: str | None) -> None:
+ # A cohort losing any leaf is `Excluded(HasDroppedLeaf)` whole, so the gate cannot look at
+ # behavioral leaves alone.
+ self.assertEqual(leaf_unpinnable_reason(leaf), expected)
+
def test_pins_leaf_state_fields_and_event_union(self) -> None:
cohort = Cohort(
id=7,
@@ -111,6 +188,35 @@ class TestBackfillPinning(SimpleTestCase):
self.assertTrue(action["is_action"])
self.assertIsNone(action["event_name"])
+ def test_an_actions_event_type_with_a_string_key_pins_as_an_event(self) -> None:
+ # The catalog keeps this leaf, so the gate admits the cohort. Pinning it as an action would
+ # drop the condition in the seeder and fail the run the gate just allowed.
+ cohort = Cohort(
+ id=7,
+ filters={
+ "properties": {
+ "type": "AND",
+ "values": [
+ {
+ "type": "behavioral",
+ "key": "$pageview",
+ "event_type": "actions",
+ "value": "performed_event",
+ "conditionHash": "aaaaaaaaaaaaaaaa",
+ "time_value": 7,
+ "time_interval": "day",
+ }
+ ],
+ }
+ },
+ )
+
+ pinned, event_names = pin_conditions_for_cohorts([cohort])
+
+ self.assertEqual(event_names, ["$pageview"])
+ self.assertFalse(pinned["conditions"][0]["is_action"])
+ self.assertEqual(pinned["conditions"][0]["event_name"], "$pageview")
+
def test_person_conditions_are_sorted_and_preserved_per_cohort(self) -> None:
second = Cohort(
id=2,
diff --git a/products/cohorts/backend/backfill/test/test_readiness.py b/products/cohorts/backend/backfill/test/test_readiness.py
index d5f0f8060715..516288aa4bc7 100644
--- a/products/cohorts/backend/backfill/test/test_readiness.py
+++ b/products/cohorts/backend/backfill/test/test_readiness.py
@@ -19,6 +19,12 @@ from products.cohorts.backend.models.backfill import CohortBackfillRun, CohortBa
from products.cohorts.backend.models.cohort import Cohort, CohortType
from products.cohorts.backend.models.leaf_shape import extract_leaf_shape_hash, extract_person_leaf_shape_hash
+# The catalog drops a leaf with no bytecode or a `conditionHash` that is not 16 characters, and
+# `_calculate_realtime_support` grants `cohort_type=REALTIME` only when every leaf compiled to
+# bytecode. A fixture missing either is a cohort shape no realtime cohort can have.
+_BYTECODE = ["_H", 1, 32, "matched", 32, "event", 1, 1, 11]
+
+
# (name, run factory, stamp fn, cohort hash column, cohort stamp column, same-kind edit,
# other-kind edit) — the stamp protocol is symmetric in these, so every step of it runs under both
# kinds. The two edits are the filters that move only this kind's hash, and only the other's.
@@ -60,11 +66,12 @@ class TestBackfillReadiness(BaseTest):
"key": "$pageview",
"event_type": "events",
"value": "performed_event_multiple",
- "conditionHash": "same-condition-hash",
+ "conditionHash": "same-condition00",
"time_value": window_days,
"time_interval": "day",
"operator": "gte",
"operator_value": 2,
+ "bytecode": _BYTECODE,
}
]
if person_hash is not None:
@@ -74,7 +81,10 @@ class TestBackfillReadiness(BaseTest):
"key": "email",
"value": ["[email protected]"],
"operator": "exact",
- "conditionHash": person_hash,
+ # The catalog wants exactly 16 characters; the cases only need the hashes to
+ # differ from each other.
+ "conditionHash": person_hash[:16].ljust(16, "0"),
+ "bytecode": _BYTECODE,
}
)
return {"properties": {"type": "AND", "values": values}}
diff --git a/products/cohorts/backend/backfill/test/test_runs.py b/products/cohorts/backend/backfill/test/test_runs.py
index 2af9118d5313..9eb23f8ef318 100644
--- a/products/cohorts/backend/backfill/test/test_runs.py
+++ b/products/cohorts/backend/backfill/test/test_runs.py
@@ -33,6 +33,11 @@ from products.cohorts.backend.models.backfill import (
)
from products.cohorts.backend.models.cohort import Cohort, CohortType
+# The catalog drops a leaf with no bytecode or a `conditionHash` that is not 16 characters, and
+# `_calculate_realtime_support` grants `cohort_type=REALTIME` only when every leaf compiled to
+# bytecode. A fixture missing either is a cohort shape no realtime cohort can have.
+_BYTECODE = ["_H", 1, 32, "matched", 32, "event", 1, 1, 11]
+
@override_settings(
REALTIME_COHORT_TEAM_ALLOWLIST="all",
@@ -50,11 +55,12 @@ class TestBackfillRuns(BaseTest):
"key": event,
"event_type": "events",
"value": "performed_event_multiple",
- "conditionHash": f"hash-{event}",
+ "conditionHash": f"hash-{event}"[:16].ljust(16, "0"),
"time_value": window_days,
"time_interval": "day",
"operator": "gte",
"operator_value": 2,
+ "bytecode": _BYTECODE,
}
],
}
@@ -201,6 +207,100 @@ class TestBackfillRuns(BaseTest):
with self.assertRaisesMessage(ValueError, "Cohorts already have active backfill runs"):
create_team_backfill_run(self.team.id, "team_enablement")
+ def _unseedable_cohort(self, *leaves: dict) -> Cohort:
+ return Cohort.objects.create(
+ team=self.team,
+ name="unseedable",
+ cohort_type=CohortType.REALTIME,
+ filters={"properties": {"type": "AND", "values": list(leaves)}},
+ )
+
+ # The UI never writes a behavioral leaf without a time window, but the API accepts one.
+ _WINDOWLESS_LEAF = {
+ "type": "behavioral",
+ "key": "navbar starred item added",
+ "event_type": "events",
+ "value": "performed_event",
+ "conditionHash": "c8236865303eb463",
+ "event_filters": [{"key": "item_type", "type": "event", "value": "insight", "operator": "exact"}],
+ "bytecode": _BYTECODE,
+ }
+ _WINDOWED_LEAF = {
+ "type": "behavioral",
+ "key": "$pageview",
+ "event_type": "events",
+ "value": "performed_event",
+ "conditionHash": "hash-$pageview00",
+ "time_value": 7,
+ "time_interval": "day",
+ "bytecode": _BYTECODE,
+ }
+
+ @parameterized.expand(
+ [
+ ("windowless_performed_event", [_WINDOWLESS_LEAF]),
+ ("action_keyed", [{**_WINDOWED_LEAF, "event_type": "actions", "key": 42}]),
+ (
+ "sub_day_multiple",
+ [
+ {
+ **_WINDOWED_LEAF,
+ "value": "performed_event_multiple",
+ "time_interval": "hour",
+ "operator": "gte",
+ "operator_value": 2,
+ }
+ ],
+ ),
+ ("hashless", [{k: v for k, v in _WINDOWED_LEAF.items() if k != "conditionHash"}]),
+ ("short_hash", [{**_WINDOWED_LEAF, "conditionHash": "tooshort"}]),
+ ("bytecodeless", [{k: v for k, v in _WINDOWED_LEAF.items() if k != "bytecode"}]),
+ ("one_seedable_sibling", [_WINDOWED_LEAF, _WINDOWLESS_LEAF]),
+ # The dropped leaf is not behavioral, so a gate reading behavioral leaves alone admits
+ # this cohort while the catalog classifies it `excluded_has_dropped_leaf` whole.
+ (
+ "person_metadata_sibling",
+ [_WINDOWED_LEAF, {"type": "person_metadata", "key": "created_at", "value": "2026-01-01"}],
+ ),
+ (
+ "bytecodeless_person_sibling",
+ [_WINDOWED_LEAF, {"type": "person", "key": "email", "conditionHash": "person0000000001"}],
+ ),
+ # Every leaf is kept, so only the tree tells these cohorts apart from a seedable one.
+ ("negated_root", [{**_WINDOWED_LEAF, "negation": True}]),
+ ("empty_group", [_WINDOWED_LEAF, {"type": "OR", "values": []}]),
+ ]
+ )
+ def test_unseedable_behavioral_cohort_is_refused(self, _name: str, leaves: list[dict]) -> None:
+ # The processor excludes a cohort with any dropped leaf, so a partly seedable one is
+ # refused whole.
+ cohort = self._unseedable_cohort(*leaves)
+
+ with self.assertLogs("products.cohorts.backend.backfill.runs", level="INFO") as logs:
+ attempt = attempt_backfill_run_for_cohort(self.team.id, cohort.id, "cohort_created")
+
+ self.assertEqual(attempt.reason, BackfillRefusalReason.COHORT_INELIGIBLE)
+ self.assertIn("the realtime catalog", "\n".join(logs.output))
+ self.assertEqual(CohortBackfillRun.objects.for_team(self.team.id).count(), 0)
+
+ def test_team_run_excludes_an_unseedable_cohort_and_refuses_it_by_id(self) -> None:
+ seedable = self._cohort()
+ unseedable = self._unseedable_cohort(self._WINDOWLESS_LEAF)
+
+ with self.assertRaisesMessage(ValueError, "not eligible realtime behavioral cohorts"):
+ create_team_backfill_run(self.team.id, "team_enablement", [unseedable.id])
+
+ run = create_team_backfill_run(self.team.id, "team_enablement")
+
+ self.assertEqual(
+ set(
+ CohortBackfillRunCohort.objects.for_team(self.team.id)
+ .filter(run=run)
+ .values_list("cohort_id", flat=True)
+ ),
+ {seedable.id},
+ )
+
def test_editing_the_cohort_supersedes_its_active_run(self) -> None:
# rust/cohort-seeder claims run rows and replays history from the filters the run pinned, so
# if the post_save receiver stops superseding, an edit leaves the seeder on a stale definition.
@@ -231,6 +331,7 @@ class TestPersonBackfillRuns(BaseTest):
*,
person_hashes: tuple[str | None, ...] = ("person0000000001",),
behavioral: bool = True,
+ windowless: bool = False,
person_metadata: bool = False,
) -> dict:
values: list[dict] = [
@@ -240,21 +341,25 @@ class TestPersonBackfillRuns(BaseTest):
"value": ["[email protected]"],
"operator": "exact",
"conditionHash": condition_hash,
+ "bytecode": _BYTECODE,
}
for condition_hash in person_hashes
]
if behavioral:
- values.append(
- {
- "type": "behavioral",
- "key": "$pageview",
- "event_type": "events",
- "value": "performed_event",
- "conditionHash": "behavior00000001",
- "time_value": 7,
- "time_interval": "day",
- }
- )
+ leaf = {
+ "type": "behavioral",
+ "key": "$pageview",
+ "event_type": "events",
+ "value": "performed_event",
+ "conditionHash": "behavior00000001",
+ "time_value": 7,
+ "time_interval": "day",
+ "bytecode": _BYTECODE,
+ }
+ if windowless:
+ # The API accepts a behavioral leaf with no time window; the catalog drops it.
+ del leaf["time_value"], leaf["time_interval"]
+ values.append(leaf)
if person_metadata:
values.append(
{
@@ -581,6 +686,10 @@ class TestPersonBackfillRuns(BaseTest):
("non_realtime", {"cohort_type": CohortType.BEHAVIORAL}),
("hashless", {"filters": "hashless"}),
("person_metadata", {"filters": "person_metadata"}),
+ # The seeder fails a person run for this cohort on its first tick, so a person gate
+ # admitting it would create one failed run per save.
+ ("windowless_behavioral_sibling", {"filters": "windowless"}),
+ ("negated_root", {"filters": "negated_root"}),
]
)
def test_ineligible_cohort_is_refused(self, _name: str, overrides: dict[str, object]) -> None:
@@ -591,6 +700,11 @@ class TestPersonBackfillRuns(BaseTest):
filters = self._filters(person_hashes=(None,), behavioral=False)
elif _name == "person_metadata":
filters = self._filters(person_metadata=True)
+ elif _name == "windowless_behavioral_sibling":
+ filters = self._filters(windowless=True)
+ elif _name == "negated_root":
+ filters = self._filters(behavioral=False)
+ filters["properties"]["values"][0]["negation"] = True
cohort_type = overrides.pop("cohort_type", CohortType.REALTIME)
cohort = Cohort.objects.create(
team=self.team,
@@ -731,11 +845,12 @@ class TestCancelRuns(BaseTest):
"key": event,
"event_type": "events",
"value": "performed_event_multiple",
- "conditionHash": f"hash-{event}",
+ "conditionHash": f"hash-{event}"[:16].ljust(16, "0"),
"time_value": 7,
"time_interval": "day",
"operator": "gte",
"operator_value": 2,
+ "bytecode": _BYTECODE,
}
],
}
diff --git a/products/cohorts/backend/management/commands/create_cohort_backfill_run.py b/products/cohorts/backend/management/commands/create_cohort_backfill_run.py
index 15d0e6ba4edc..d12e88f3f9cb 100644
--- a/products/cohorts/backend/management/commands/create_cohort_backfill_run.py
+++ b/products/cohorts/backend/management/commands/create_cohort_backfill_run.py
@@ -1,3 +1,4 @@
+from collections.abc import Callable
from datetime import datetime, timedelta
from typing import Any
@@ -16,16 +17,17 @@ from products.cohorts.backend.backfill.pinning import (
)
from products.cohorts.backend.backfill.runs import (
_validate_boundary_at,
+ behavioral_backfill_ineligibility_reason,
check_person_run_preconditions,
check_run_preconditions,
create_person_team_backfill_run,
create_team_backfill_run,
- has_behavioral_filters,
+ judge_team_cohorts,
person_backfill_ineligibility_reason,
)
from products.cohorts.backend.backfill.sizing import estimate_person_seed_topic_bytes
from products.cohorts.backend.models.backfill import CohortBackfillKind, CohortBackfillRunCohort, CohortBackfillTrigger
-from products.cohorts.backend.models.cohort import Cohort, CohortType
+from products.cohorts.backend.models.cohort import Cohort
from products.cohorts.backend.models.leaf_shape import walk_filter_leaves
from products.cohorts.backend.realtime_teams import is_realtime_cohort_team
@@ -98,17 +100,7 @@ class Command(BaseCommand):
cohort_ids = options.get("cohort_ids")
if options["dry_run"]:
- queryset = Cohort.objects.filter(
- team_id=team_id,
- cohort_type=CohortType.REALTIME,
- is_static=False,
- deleted=False,
- )
- if cohort_ids is not None:
- queryset = queryset.filter(id__in=cohort_ids)
- cohorts = [cohort for cohort in queryset.order_by("id") if has_behavioral_filters(cohort)]
- if cohort_ids is not None and {cohort.id for cohort in cohorts} != set(cohort_ids):
- raise CommandError("One or more --cohort-ids are not eligible realtime behavioral cohorts")
+ cohorts = self._dry_run_cohorts(team_id, cohort_ids, behavioral_backfill_ineligibility_reason, "behavioral")
pinned, event_names = pin_conditions_for_cohorts(cohorts)
self.stdout.write(
f"Dry run: {len(cohorts)} cohorts, {len(pinned['conditions'])} conditions, "
@@ -188,30 +180,7 @@ class Command(BaseCommand):
cohort_ids: list[int] | None,
boundary_at: datetime | None,
) -> None:
- requested_ids = set(cohort_ids) if cohort_ids is not None else None
- # Deliberately wider than `_person_cohorts_for_team`, which narrows the SQL-expressible half
- # of eligibility away before it locks: the dry run's whole job is naming *why* each cohort was
- # refused, and it takes no locks. Both sides decide with `person_backfill_ineligibility_reason`.
- queryset = Cohort.objects.filter(team_id=team_id)
- if requested_ids is not None:
- queryset = queryset.filter(id__in=requested_ids)
- candidates = [(cohort, person_backfill_ineligibility_reason(cohort)) for cohort in queryset.order_by("id")]
-
- refusals = [(cohort.id, reason) for cohort, reason in candidates if reason is not None]
- if requested_ids is not None:
- candidate_ids = {cohort.id for cohort, _ in candidates}
- refusals.extend((cohort_id, "not found") for cohort_id in sorted(requested_ids - candidate_ids))
-
- if refusals:
- self.stdout.write(
- "Refused cohorts: " + ", ".join(f"{cohort_id} ({reason})" for cohort_id, reason in refusals)
- )
- if requested_ids is not None and refusals:
- raise CommandError("One or more --cohort-ids are not eligible realtime person-property cohorts")
-
- cohorts = [cohort for cohort, reason in candidates if reason is None]
- if not cohorts:
- raise CommandError(f"Team {team_id} has no eligible realtime person-property cohorts")
+ cohorts = self._dry_run_cohorts(team_id, cohort_ids, person_backfill_ineligibility_reason, "person-property")
try:
pinned = pin_person_conditions_for_cohorts(
cohorts,
@@ -243,3 +212,28 @@ class Command(BaseCommand):
f"{estimate.estimated_topic_bytes} estimated topic bytes, budget {estimate.budget_bytes}, "
f"would refuse: {verdict}"
)
+
+ def _dry_run_cohorts(
+ self,
+ team_id: int,
+ cohort_ids: list[int] | None,
+ ineligibility_reason: Callable[[Cohort], str | None],
+ kind_label: str,
+ ) -> list[Cohort]:
+ candidates = judge_team_cohorts(team_id, cohort_ids, ineligibility_reason)
+ refusals = [(cohort.id, reason) for cohort, reason in candidates if reason is not None]
+ if cohort_ids is not None:
+ candidate_ids = {cohort.id for cohort, _ in candidates}
+ refusals.extend((cohort_id, "not found") for cohort_id in sorted(set(cohort_ids) - candidate_ids))
+
+ if refusals:
+ self.stdout.write(
+ "Refused cohorts: " + ", ".join(f"{cohort_id} ({reason})" for cohort_id, reason in refusals)
+ )
+ if cohort_ids is not None and refusals:
+ raise CommandError(f"One or more --cohort-ids are not eligible realtime {kind_label} cohorts")
+
+ cohorts = [cohort for cohort, reason in candidates if reason is None]
+ if not cohorts:
+ raise CommandError(f"Team {team_id} has no eligible realtime {kind_label} cohorts")
+ return cohorts
diff --git a/products/cohorts/backend/models/dependencies.py b/products/cohorts/backend/models/dependencies.py
index 02b5e47276f0..7332b9771a78 100644
--- a/products/cohorts/backend/models/dependencies.py
+++ b/products/cohorts/backend/models/dependencies.py
@@ -481,17 +481,40 @@ def _on_cohort_changed_full_warm(cohort: Cohort, always_invalidate: bool = False
warm_team_cohort_dependency_cache(cohort.team_id)
-def _has_backfillable_filters(cohort: Cohort, kind: CohortBackfillKind) -> bool:
+def _backfill_ineligibility_reason(cohort: Cohort, kind: CohortBackfillKind) -> str | None:
from products.cohorts.backend.backfill.runs import ( # noqa: PLC0415 — avoids a model-load cycle
- has_behavioral_filters,
+ behavioral_backfill_ineligibility_reason,
person_backfill_ineligibility_reason,
)
+ # Each creator's own predicate, so this cannot judge backfillable a cohort the creator will
+ # permanently refuse.
if kind == CohortBackfillKind.PERSON_PROPERTY:
- # The creator's own predicate, so this cannot judge backfillable a cohort the creator will
- # permanently refuse (for example one that also carries a person_metadata leaf).
- return person_backfill_ineligibility_reason(cohort) is None
- return has_behavioral_filters(cohort)
+ return person_backfill_ineligibility_reason(cohort)
+ return behavioral_backfill_ineligibility_reason(cohort)
+
+
+def _report_backfill_ineligible(cohort: Cohort, kind: CohortBackfillKind, reason: str) -> None:
+ """Name a refusal that creates no run, and so has nothing downstream to report it.
+
+ The seeder reports a cohort it cannot seed through the run's failure; a cohort refused here
+ never gets a run, so without this the cohort stays un-backfillable with no counter, log, or
+ gauge naming the cause.
+ """
+ from products.cohorts.backend.backfill.runs import ( # noqa: PLC0415 — avoids a model-load cycle
+ INAPPLICABLE_BACKFILL_REASONS,
+ )
+
+ if reason in INAPPLICABLE_BACKFILL_REASONS:
+ return
+ COHORT_BACKFILL_TRIGGER_COUNTER.labels(backfill_kind=kind, outcome="refused_ineligible").inc()
+ logger.info(
+ "cohort_backfill_refused_ineligible",
+ cohort_id=cohort.pk,
+ team_id=cohort.team_id,
+ backfill_kind=kind,
+ reason=reason,
+ )
def _trigger_cohort_backfill(cohort: Cohort, trigger_kind: str, kind: CohortBackfillKind) -> None:
@@ -660,7 +683,11 @@ def cohort_behavioral_shape_changed_backfill(sender, instance, **kwargs):
).inc()
return
trigger_kind = _backfill_trigger_kind(instance, kwargs, shape_changed=instance._leaf_shape_changed)
- if trigger_kind is None or not _has_backfillable_filters(instance, CohortBackfillKind.BEHAVIORAL):
+ if trigger_kind is None:
+ return
+ ineligibility = _backfill_ineligibility_reason(instance, CohortBackfillKind.BEHAVIORAL)
+ if ineligibility is not None:
+ _report_backfill_ineligible(instance, CohortBackfillKind.BEHAVIORAL, ineligibility)
return
transaction.on_commit(lambda: _trigger_cohort_backfill(instance, trigger_kind, CohortBackfillKind.BEHAVIORAL))
@@ -690,7 +717,11 @@ def cohort_person_shape_changed_backfill(sender, instance, **kwargs):
).inc()
return
trigger_kind = _backfill_trigger_kind(instance, kwargs, shape_changed=instance._person_shape_changed)
- if trigger_kind is None or not _has_backfillable_filters(instance, CohortBackfillKind.PERSON_PROPERTY):
+ if trigger_kind is None:
+ return
+ ineligibility = _backfill_ineligibility_reason(instance, CohortBackfillKind.PERSON_PROPERTY)
+ if ineligibility is not None:
+ _report_backfill_ineligible(instance, CohortBackfillKind.PERSON_PROPERTY, ineligibility)
return
transaction.on_commit(
diff --git a/products/cohorts/backend/models/leaf_shape.py b/products/cohorts/backend/models/leaf_shape.py
index 51351dc75f3f..42d1dea746c6 100644
--- a/products/cohorts/backend/models/leaf_shape.py
+++ b/products/cohorts/backend/models/leaf_shape.py
@@ -269,7 +269,8 @@ class FilterShapeHashes:
leaf_types = {leaf.get("type") for leaf in walk_filter_leaves((filters or {}).get("properties"))}
person_backfillable = bool(self.person) and "person_metadata" not in leaf_types
- # Match the run creators: an unhashed behavioral leaf can trigger a run, but person metadata cannot.
+ # Match the run creators: a moved behavioral hash hands the decision to the behavioral
+ # creator, but person metadata has no creator to hand to.
behavioral_run_fires = previous.behavioral != self.behavioral and "behavioral" in leaf_types
person_run_fires = previous.person != self.person and person_backfillable
diff --git a/products/cohorts/backend/models/test/test_behavioral_backfill_dependencies.py b/products/cohorts/backend/models/test/test_behavioral_backfill_dependencies.py
index 29108cd1a77c..acf377f93519 100644
--- a/products/cohorts/backend/models/test/test_behavioral_backfill_dependencies.py
+++ b/products/cohorts/backend/models/test/test_behavioral_backfill_dependencies.py
@@ -9,7 +9,16 @@ from parameterized import parameterized
from products.cohorts.backend.models.backfill import CohortBackfillKind
from products.cohorts.backend.models.cohort import Cohort, CohortType
-from products.cohorts.backend.models.dependencies import COHORT_REALTIME_STATE_ORPHANED_COUNTER
+from products.cohorts.backend.models.dependencies import (
+ COHORT_BACKFILL_TRIGGER_COUNTER,
+ COHORT_REALTIME_STATE_ORPHANED_COUNTER,
+)
+
+# The catalog drops a leaf with no bytecode or a `conditionHash` that is not 16 characters, and
+# `_calculate_realtime_support` grants `cohort_type=REALTIME` only when every leaf compiled to
+# bytecode. A fixture missing either is a cohort shape no realtime cohort can have.
+_BYTECODE = ["_H", 1, 32, "matched", 32, "event", 1, 1, 11]
+
# (name, run kind, two successive edits as `_filters` args) — the edits move only this kind's leaf
# shape, so only this kind's receiver reacts to them even though both share one allowlist.
@@ -33,9 +42,10 @@ class TestBehavioralBackfillDependencies(BaseTest):
*,
person_hash: str | None = None,
extra_person_hash: str | None = None,
- behavioral_hash: str | None = "stable-condition-hash",
+ behavioral_hash: str | None = "stable-conditio",
group_type: str = "AND",
cohort_ref: int | None = None,
+ windowless: bool = False,
) -> dict:
values = []
if window_days is not None:
@@ -48,11 +58,15 @@ class TestBehavioralBackfillDependencies(BaseTest):
"time_interval": "day",
"operator": "gte",
"operator_value": 2,
+ "bytecode": _BYTECODE,
}
+ if windowless:
+ behavioral = {k: v for k, v in behavioral.items() if k not in ("time_value", "time_interval")}
+ behavioral["value"] = "performed_event"
# Absent rather than null, which is how the API stores a leaf whose bytecode generation
# failed: the cohort keeps `cohort_type` realtime and the leaf keeps no condition hash.
if behavioral_hash is not None:
- behavioral["conditionHash"] = behavioral_hash
+ behavioral["conditionHash"] = behavioral_hash[:16].ljust(16, "0")
values.append(behavioral)
for leaf_hash in (person_hash, extra_person_hash):
if leaf_hash is not None:
@@ -62,7 +76,10 @@ class TestBehavioralBackfillDependencies(BaseTest):
"key": "email",
"value": ["[email protected]"],
"operator": "exact",
- "conditionHash": leaf_hash,
+ # The catalog wants exactly 16 characters; the cases only need the hashes
+ # to differ from each other.
+ "conditionHash": leaf_hash[:16].ljust(16, "0"),
+ "bytecode": _BYTECODE,
}
)
if cohort_ref is not None:
@@ -281,6 +298,44 @@ class TestBehavioralBackfillDependencies(BaseTest):
enqueue.assert_not_called()
redis.set.assert_not_called()
+ def test_a_cohort_the_catalog_refuses_is_named_rather_than_dropped_silently(self) -> None:
+ # No run is created, so the seeder has nothing to report the refusal with. Without this the
+ # cohort stays un-backfillable and nothing anywhere says why.
+ redis = self._redis()
+ before = self._refused_count(CohortBackfillKind.BEHAVIORAL)
+ with (
+ override_settings(COHORT_BACKFILL_TRIGGER_TEAM_ALLOWLIST="all"),
+ mock.patch("products.cohorts.backend.models.dependencies.get_redis_client", return_value=redis),
+ mock.patch("posthog.tasks.calculate_cohort.trigger_cohort_backfill_run_task.apply_async") as enqueue,
+ self.assertLogs("products.cohorts.backend.models.dependencies", level="INFO") as logs,
+ ):
+ Cohort.objects.create(
+ team=self.team,
+ cohort_type=CohortType.REALTIME,
+ filters=self._filters(7, windowless=True),
+ )
+
+ enqueue.assert_not_called()
+ self.assertEqual(self._refused_count(CohortBackfillKind.BEHAVIORAL) - before, 1)
+ self.assertIn("unsupported_state_variant", "\n".join(logs.output))
+
+ def test_a_cohort_of_the_other_kind_alone_reports_no_refusal(self) -> None:
+ # Every save of a person-only cohort reaches the behavioral receiver. Counting those would
+ # bury the refusals that need a signal.
+ redis = self._redis()
+ before = self._refused_count(CohortBackfillKind.BEHAVIORAL)
+ with (
+ override_settings(COHORT_BACKFILL_TRIGGER_TEAM_ALLOWLIST="all"),
+ mock.patch("products.cohorts.backend.models.dependencies.get_redis_client", return_value=redis),
+ mock.patch("posthog.tasks.calculate_cohort.trigger_cohort_backfill_run_task.apply_async"),
+ ):
+ self._cohort(None, person_hash="person-a")
+
+ self.assertEqual(self._refused_count(CohortBackfillKind.BEHAVIORAL), before)
+
+ def _refused_count(self, kind: CohortBackfillKind) -> float:
+ return COHORT_BACKFILL_TRIGGER_COUNTER.labels(backfill_kind=kind, outcome="refused_ineligible")._value._value
+
def _assert_one_debounced_task_per_kind(self, enqueue, redis, cohort: Cohort, trigger: str) -> None:
self.assertEqual(
{tuple(call.kwargs["args"][2:]) for call in enqueue.call_args_list},
@@ -474,11 +529,8 @@ class TestBehavioralBackfillDependencies(BaseTest):
cohort.refresh_from_db()
self.assertEqual(cohort.last_backfill_events_at, ready_at)
- def test_behavioral_leaf_losing_its_hash_enqueues_only_the_behavioral_run(self) -> None:
- # The behavioral receiver creates a run for any behavioral leaf, hashed or not, so this edit
- # already triggers one and the composition rule must not add a person run beside it. The API
- # reaches this state by storing the raw filters when filter validation raises, which leaves
- # the cohort realtime with a leaf that never got a condition hash.
+ def test_behavioral_leaf_losing_its_hash_enqueues_nothing(self) -> None:
+ # The API reaches this state by storing the raw filters when filter validation raises.
cohort = self._cohort(7, person_hash="person-a")
redis = self._redis()
with (
@@ -489,7 +541,8 @@ class TestBehavioralBackfillDependencies(BaseTest):
cohort.filters = self._filters(7, person_hash="person-a", behavioral_hash=None)
cohort.save()
- self._assert_one_debounced_task(enqueue, redis, cohort, CohortBackfillKind.BEHAVIORAL)
+ enqueue.assert_not_called()
+ redis.set.assert_not_called()
@parameterized.expand([("stored_hashes", False), ("null_hashes", True)])
def test_malformed_persisted_filters_still_invalidate_on_a_leaf_edit(self, _name: str, null_hashes: bool) -> None:
@@ -592,20 +645,21 @@ class TestBehavioralBackfillDependencies(BaseTest):
@parameterized.expand(
[
- ("static", {"is_static": True}),
- ("non_realtime_type", {"cohort_type": None}),
+ ("static", {"is_static": True}, {"person_hash": "person-a"}),
+ ("non_realtime_type", {"cohort_type": None}, {"person_hash": "person-a"}),
+ ("windowless_behavioral", {}, {"windowless": True}),
]
)
@override_settings(COHORT_BACKFILL_TRIGGER_TEAM_ALLOWLIST="all")
- def test_ineligible_create_enqueues_nothing(self, _name: str, overrides: dict) -> None:
+ def test_ineligible_create_enqueues_nothing(self, _name: str, overrides: dict, filter_kwargs: dict) -> None:
# Creates skip the shape-changed flags and dispatch straight off kwargs["created"], so the
- # type guard in _backfill_trigger_kind is all that keeps every ordinary (static or
- # non-realtime) cohort create in an opted-in team from firing tasks the creators refuse.
+ # type guard in _backfill_trigger_kind and the creators' own predicates are all that keep
+ # every ordinary cohort create in an opted-in team from firing tasks the creators refuse.
redis = self._redis()
params: dict = {
"team": self.team,
"cohort_type": CohortType.REALTIME,
- "filters": self._filters(7, person_hash="person-a"),
+ "filters": self._filters(7, **filter_kwargs),
**overrides,
}
with (
diff --git a/products/cohorts/backend/parity/eligibility.py b/products/cohorts/backend/parity/eligibility.py
index 59e83e217c51..ac2e45363175 100644
--- a/products/cohorts/backend/parity/eligibility.py
+++ b/products/cohorts/backend/parity/eligibility.py
@@ -39,6 +39,11 @@ _OP_RETURN = 38
PARSE_ERROR = "parse_error"
EMITTING_CLASSES = frozenset({SINGLE_LEAF, STAGE2_COMPOSABLE, STAGE2_COMPOSABLE_REF})
+# Decided from the cohort's own tree. The reference classes depend on other cohorts, so they are left
+# out, which is the line `composability` draws in `rust/cohort-seeder/src/domain/pinned.rs`.
+_STRUCTURAL_EXCLUSIONS = frozenset(
+ {EXCLUDED_HAS_DROPPED_LEAF, EXCLUDED_EMPTY_GROUP, EXCLUDED_TOP_LEVEL_NEGATION, EXCLUDED_NOT_MULTI_LEAF}
+)
_INTERVAL_DAYS = {"minute": 0, "hour": 0, "day": 1, "week": 7, "month": 30, "year": 365}
_INTERVAL_SECONDS = {"minute": 60, "hour": 3_600}
@@ -279,16 +284,37 @@ def _classify_leaf(node: Mapping[str, Any]) -> Union[_Leaf, str]:
return "unknown_leaf_type"
+def leaf_drop_reason(node: Mapping[str, Any]) -> Optional[str]:
+ """The catalog's drop label for a leaf the frozen catalog refuses, or ``None`` when it keeps it.
+
+ A cohort reference counts as kept: whether the cohort composes then depends on the reference
+ target, which one leaf cannot answer.
+
+ Public so the backfill seedability gate (``backfill/pinning.py``) reads this mirror rather than
+ keeping a looser copy of the classifier's rules.
+ """
+ classified = _classify_leaf(node)
+ return classified if isinstance(classified, str) else None
+
+
def _explicit_negation(node: Mapping[str, Any]) -> bool:
return node.get("negation") is True
+def is_action_key(key: Any) -> bool:
+ """Whether a behavioral leaf's ``key`` is an action id, which the catalog drops.
+
+ Public so the backfill pinner marks a leaf action-keyed exactly when this classifier drops it.
+ """
+ return isinstance(key, (int, float)) and not isinstance(key, bool)
+
+
def _classify_behavioral(node: Mapping[str, Any]) -> Union[_Leaf, str]:
value = node.get("value")
if value not in ("performed_event", "performed_event_multiple"):
return "unsupported_behavioral_value"
key = node.get("key")
- if isinstance(key, (int, float)) and not isinstance(key, bool):
+ if is_action_key(key):
return "behavioral_action_key"
if not _valid_condition_hash(node.get("conditionHash")):
return "missing_condition_hash"
@@ -409,6 +435,19 @@ def _classify_cohort(parsed: _Parsed) -> str:
return EXCLUDED_NOT_MULTI_LEAF
+def structural_exclusion(filters: Any) -> Optional[str]:
+ """The class of a cohort its own tree keeps out of composition, or ``None``.
+
+ Public so the backfill seedability gate refuses the cohorts the seeder fails a run over, such as
+ a negated root, which has no dropped leaf for a per-leaf screen to find.
+ """
+ parsed = _parse_cohort(filters)
+ if parsed is None:
+ return None
+ eligibility = _classify_cohort(parsed)
+ return eligibility if eligibility in _STRUCTURAL_EXCLUSIONS else None
+
+
def _find_cycles(edges: Mapping[int, set[int]]) -> set[int]:
"""Nodes in a ref cycle (SCC of size > 1, or self-loop), over all-ref edges.
diff --git a/rust/cohort-seeder/src/app/person_plan.rs b/rust/cohort-seeder/src/app/person_plan.rs
index d0dac6b06b77..41a8ef13ab55 100644
--- a/rust/cohort-seeder/src/app/person_plan.rs
+++ b/rust/cohort-seeder/src/app/person_plan.rs
@@ -28,10 +28,9 @@ use crate::store::RenderedError;
use std::sync::Arc;
/// A person run whose chunks do not exist yet, handed from `prepare` to the orchestrator's
-/// planning slot. Coverage travels along so the planner can withhold the stamp.
+/// planning slot.
pub(super) struct PersonPlanRequest {
pub(super) run: Arc<PinnedPersonRun>,
- pub(super) coverage_complete: bool,
}
/// How one planning attempt ended, for the orchestrator's backoff bookkeeping. Only `Failed`
@@ -141,17 +140,14 @@ async fn plan_claimed_run(
}
}
- // Without the proof an uncovered cohort could stamp readiness on zero seeded persons.
- if request.coverage_complete {
- match mark_chunks_planned(pool, run_id, RunKind::PersonProperty).await {
- Ok(PlanningStampOutcome::Stamped) => {
- counter!(RUNS_PLANNING_STAMPED, "kind" => RunKind::PersonProperty.as_str())
- .increment(1);
- }
- Ok(PlanningStampOutcome::Skipped) => {}
- Err(error) => {
- warn!(?run_id, error = %error, "stamping the person planning proof failed");
- }
+ match mark_chunks_planned(pool, run_id, RunKind::PersonProperty).await {
+ Ok(PlanningStampOutcome::Stamped) => {
+ counter!(RUNS_PLANNING_STAMPED, "kind" => RunKind::PersonProperty.as_str())
+ .increment(1);
+ }
+ Ok(PlanningStampOutcome::Skipped) => {}
+ Err(error) => {
+ warn!(?run_id, error = %error, "stamping the person planning proof failed");
}
}
PersonPlanAttempt::Done
diff --git a/rust/cohort-seeder/src/app/prepare.rs b/rust/cohort-seeder/src/app/prepare.rs
index 1ea4de4d1aa2..eb20c9bb013b 100644
--- a/rust/cohort-seeder/src/app/prepare.rs
+++ b/rust/cohort-seeder/src/app/prepare.rs
@@ -11,7 +11,6 @@ use std::collections::{HashMap, HashSet};
use std::sync::Arc;
use cohort_core::bucket_tz::window_start_for_now;
-use cohort_core::filters::CohortId;
use common_types::cohort::TeamAllowlist;
use metrics::{counter, gauge};
use sqlx::PgPool;
@@ -19,13 +18,14 @@ use tracing::{debug, info, warn};
use crate::domain::{
plan_days, ConditionAnalyses, ConditionClass, Lookback, PersonEmissionPolicy,
- PersonRunValidation, PinnedPersonRun, PinnedRun, PinnedWarning, PlanCaps, ProjectedKeys, RunId,
+ PersonRunValidation, PinnedError, PinnedPersonRun, PinnedRun, PinnedWarning, PlanCaps,
+ ProjectedKeys, RunId,
};
use crate::observability::metrics::{
team_label, BOUNDARY_CAS_LOST, BOUNDARY_ESTABLISHED, CHUNKS_PLANNED, CONDITIONS_CLASSIFIED,
CONDITIONS_DROPPED, CONDITIONS_UNANALYZABLE, LOOKBACK_TRUNCATED, RUNS_DISCOVERED,
- RUNS_PLANNING_STAMPED, RUNS_PLANNING_WITHHELD, RUNS_WAITING_BOUNDARY, RUNS_WITHOUT_CHUNKS,
- RUN_CHUNKS_REMAINING, RUN_VALIDATION_FAILURES, TZ_FALLBACK, WINDOW_DAYS_MISMATCH,
+ RUNS_PLANNING_STAMPED, RUNS_WAITING_BOUNDARY, RUNS_WITHOUT_CHUNKS, RUN_CHUNKS_REMAINING,
+ RUN_VALIDATION_FAILURES, TZ_FALLBACK, WINDOW_DAYS_MISMATCH,
};
use crate::store::chunks::{PgChunkStore, PlanOutcome};
use crate::store::completion::{mark_chunks_planned, read_planning_stamp, PlanningStampOutcome};
@@ -229,22 +229,15 @@ async fn prepare_behavioral(
persist_run_warning(pool, run_id, RunWarningNote::LookbackTruncated).await;
}
- // Without the proof the run never dispatches, so an uncovered cohort can never stamp readiness
- // on zero seeded history. Siblings still get planned and seeded.
- let coverage_complete =
- record_coverage(run_id, RunKind::Behavioral, &validated.uncovered_cohorts);
-
let days = plan_days(
&validated.run.conditions,
validated.run.boundary,
&plan_caps,
);
if days.is_empty() {
- if coverage_complete {
- // A legitimately zero-chunk run still needs the proof, or it stalls waiting for chunks
- // that will never exist.
- stamp_planning(pool, run_id, RunKind::Behavioral).await;
- }
+ // A legitimately zero-chunk run still needs the proof, or it stalls waiting for chunks
+ // that will never exist.
+ stamp_planning(pool, run_id, RunKind::Behavioral).await;
return PrepareOutcome::NoChunks;
}
match store
@@ -253,9 +246,7 @@ async fn prepare_behavioral(
{
Ok(PlanOutcome::Planned { inserted }) => {
counter!(CHUNKS_PLANNED, "kind" => RunKind::Behavioral.as_str()).increment(inserted);
- if coverage_complete {
- stamp_planning(pool, run_id, RunKind::Behavioral).await;
- }
+ stamp_planning(pool, run_id, RunKind::Behavioral).await;
}
Ok(PlanOutcome::RunNotSeeding) => return PrepareOutcome::Skipped,
Ok(PlanOutcome::AlreadyPlanned) => {
@@ -278,8 +269,8 @@ async fn prepare_behavioral(
})))
}
-/// The person pipeline: validate the pinned payload (zero surviving hashes with an active
-/// participation fails the run inside `handle_run_error`; all-superseded retires as zero-work),
+/// The person pipeline: validate the pinned payload (an active participation with no surviving
+/// hash fails the run inside `handle_run_error`; all-superseded retires as zero-work),
/// then classify by planning state — the stamp or existing chunks make the run claim-eligible;
/// otherwise it needs its planning scan.
async fn prepare_person(
@@ -316,12 +307,6 @@ async fn prepare_person(
{
persist_run_warning(pool, run_id, RunWarningNote::ConditionsDropped).await;
}
- let coverage_complete = record_coverage(
- run_id,
- RunKind::PersonProperty,
- &validated.uncovered_cohorts,
- );
-
let stamped = match read_planning_stamp(pool, run_id, RunKind::PersonProperty).await {
Ok(stamp) => stamp.is_some(),
Err(error) => {
@@ -335,17 +320,11 @@ async fn prepare_person(
}
match store.chunk_progress(run_id).await {
Ok(progress) if progress.total() > 0 => {
- // Planned but not yet stamped — the planner left the stamp to this pass (its coverage
- // snapshot could predate a supersession). Coverage here is fresh from the database.
- if coverage_complete {
- stamp_planning(pool, run_id, RunKind::PersonProperty).await;
- }
+ // A prior attempt landed the chunks and left the stamp to this pass.
+ stamp_planning(pool, run_id, RunKind::PersonProperty).await;
PrepareOutcome::Eligible(PreparedRun::Person(run))
}
- Ok(_) => PrepareOutcome::PlanningNeeded(PersonPlanRequest {
- run,
- coverage_complete,
- }),
+ Ok(_) => PrepareOutcome::PlanningNeeded(PersonPlanRequest { run }),
Err(error) => {
warn!(?run_id, error = %error, "reading person chunk progress failed");
PrepareOutcome::Skipped
@@ -408,19 +387,6 @@ pub(super) fn run_ids_of_kind(
.collect()
}
-fn record_coverage(run_id: RunId, kind: RunKind, uncovered_cohorts: &[CohortId]) -> bool {
- let coverage_complete = uncovered_cohorts.is_empty();
- if !coverage_complete {
- counter!(RUNS_PLANNING_WITHHELD, "kind" => kind.as_str()).increment(1);
- warn!(
- run_id = ?run_id,
- uncovered_cohorts = ?uncovered_cohorts,
- "active participations have no surviving pinned condition; withholding the planning proof"
- );
- }
- coverage_complete
-}
-
/// Stamp the planning proof once planning has run. A failure is logged but never changes the prepare
/// outcome — the run keeps seeding and the next pass re-stamps.
async fn stamp_planning(pool: &PgPool, run_id: RunId, kind: RunKind) {
@@ -560,6 +526,15 @@ enum RunErrorDisposition {
fn run_error_disposition(run_id: Option<RunId>, error: &RunError) -> RunErrorDisposition {
match error {
RunError::Pg(_) => RunErrorDisposition::Retry,
+ // Never a retry: the run re-derives the same refusal on every poll tick.
+ RunError::Pinned(PinnedError::UncoveredParticipations(_)) => {
+ run_id.map_or(RunErrorDisposition::Retry, |run_id| {
+ RunErrorDisposition::Fail {
+ run_id,
+ reason: "uncovered_participation",
+ }
+ })
+ }
RunError::Pinned(_) => run_id.map_or(RunErrorDisposition::Retry, |run_id| {
RunErrorDisposition::Fail {
run_id,
@@ -588,3 +563,48 @@ fn run_error_disposition(run_id: Option<RunId>, error: &RunError) -> RunErrorDis
| RunError::NotActive(_) => RunErrorDisposition::Retry,
}
}
+
+#[cfg(test)]
+mod tests {
+ use cohort_core::filters::CohortId;
+ use cohort_core::leaf_state::select::UnsupportedVariant;
+ use uuid::Uuid;
+
+ use crate::domain::{
+ ConditionHash, PinnedDropReason, UncoveredCohort, UncoveredParticipations, UncoveredReason,
+ };
+
+ use super::*;
+
+ #[test]
+ fn an_uncovered_participation_fails_its_run_under_its_own_reason() {
+ let run_id = RunId(Uuid::nil());
+ let uncovered = RunError::Pinned(PinnedError::UncoveredParticipations(
+ UncoveredParticipations(vec![UncoveredCohort {
+ cohort_id: CohortId(574801),
+ reason: UncoveredReason::NoSurvivingCondition,
+ catalog_class: Some("excluded_has_dropped_leaf"),
+ dropped: vec![(
+ ConditionHash::parse("c8236865303eb463").unwrap(),
+ PinnedDropReason::UnsupportedStateVariant(UnsupportedVariant::MissingWindow),
+ )],
+ }]),
+ ));
+ assert_eq!(
+ run_error_disposition(Some(run_id), &uncovered),
+ RunErrorDisposition::Fail {
+ run_id,
+ reason: "uncovered_participation",
+ }
+ );
+
+ let malformed = RunError::Pinned(PinnedError::SchemaVersion(2));
+ assert_eq!(
+ run_error_disposition(Some(run_id), &malformed),
+ RunErrorDisposition::Fail {
+ run_id,
+ reason: "pinned_validation",
+ }
+ );
+ }
+}
diff --git a/rust/cohort-seeder/src/domain/mod.rs b/rust/cohort-seeder/src/domain/mod.rs
index 879f7b858a34..eb82e757edbc 100644
--- a/rust/cohort-seeder/src/domain/mod.rs
+++ b/rust/cohort-seeder/src/domain/mod.rs
@@ -68,7 +68,8 @@ pub use person::{
pub use person_analysis::{AlwaysEvaluateReason, PersonAnalysisCensus};
pub use pinned::{
PinnedDropReason, PinnedError, PinnedParticipation, PinnedParticipationState, PinnedRun,
- PinnedRunSnapshot, PinnedWarning, TriggerKind, UnknownTriggerKind, ValidatedPinnedRun,
+ PinnedRunSnapshot, PinnedWarning, TriggerKind, UncoveredCohort, UncoveredParticipations,
+ UncoveredReason, UnknownTriggerKind, ValidatedPinnedRun,
};
pub use plan::{bands_for_day, conditions_active_on, plan_days, ActiveConditions};
pub use projection::{BlobSource, ChunkProjection, ColumnPlan, ProjectedKeys, ScalarColumn};
diff --git a/rust/cohort-seeder/src/domain/person.rs b/rust/cohort-seeder/src/domain/person.rs
index 47d11980f0bc..159827b94b0e 100644
--- a/rust/cohort-seeder/src/domain/person.rs
+++ b/rust/cohort-seeder/src/domain/person.rs
@@ -189,13 +189,11 @@ impl PersonEmissionPolicy {
}
}
+/// Proven coverable: [`PinnedPersonRun::validate`] refuses a run with an uncovered participation.
#[derive(Debug)]
pub struct ValidatedPinnedPersonRun {
pub run: PinnedPersonRun,
pub warnings: Vec<PinnedWarning>,
- /// Active participations left with no surviving condition, ascending — they withhold the
- /// planning proof exactly as behavioral uncovered cohorts do.
- pub uncovered_cohorts: Vec<CohortId>,
}
/// A person run's validation outcome. `Retired` mirrors the behavioral zero-condition retirement:
@@ -264,11 +262,9 @@ impl PinnedPersonRun {
}
}
}
- let uncovered_cohorts = participation.uncovered_from(&covered);
- if surviving.is_empty() && uncovered_cohorts.is_empty() {
- // No active participation expects coverage (all superseded or none exist): retire.
- // Zero survivors with an active participation stays terminal below — that cohort's
- // pinned conditions dropped from the catalog, which is a genuine data problem.
+ participation.prove_covered(&covered, &warnings)?;
+ if surviving.is_empty() {
+ // Coverage is proven, so no active participation is waiting on a survivor.
return Ok(PersonRunValidation::Retired { warnings });
}
let conditions = EvaluatedConditions::new(surviving)?;
@@ -286,7 +282,6 @@ impl PinnedPersonRun {
relevance,
},
warnings,
- uncovered_cohorts,
}))
}
@@ -388,10 +383,12 @@ pub struct EvaluatedConditions(Vec<(ConditionHash, ConditionProgram)>);
// Non-empty by construction, so an `is_empty` would be a method whose contract is "never call me".
#[allow(clippy::len_without_is_empty)]
impl EvaluatedConditions {
+ /// The caller proves coverage and retires an empty survivor set first, so only the cap refuses.
fn new(surviving: BTreeMap<ConditionHash, ConditionProgram>) -> Result<Self, PinnedError> {
- if surviving.is_empty() {
- return Err(PinnedError::NoSurvivingPersonConditions);
- }
+ debug_assert!(
+ !surviving.is_empty(),
+ "the caller retires an empty survivor set"
+ );
if surviving.len() > MAX_PERSON_SEED_HASHES {
return Err(PinnedError::PersonConditionsOverCap(surviving.len()));
}
@@ -609,6 +606,7 @@ mod tests {
use super::super::backoff::AttemptCount;
use super::super::chunk::BandSpec;
use super::super::ids::{ChunkId, SChunkMs};
+ use super::super::pinned::{UncoveredCohort, UncoveredParticipations, UncoveredReason};
use super::*;
fn hash(value: &str) -> ConditionHash {
@@ -843,8 +841,8 @@ mod tests {
Err(PinnedError::MissingPersonScanSince)
));
- // A hash absent from the frozen catalog warns, drops, and leaves the cohort uncovered.
- let validated = seedable(PinnedPersonRun::validate(snapshot(
+ // Uncovered, even though the sibling cohort's hash survives, so the whole run fails.
+ let partial = PinnedPersonRun::validate(snapshot(
pinned(&[(1, HASH_A), (2, HASH_B)]),
vec![
participation(1, active.clone(), false),
@@ -854,25 +852,21 @@ mod tests {
false,
),
],
- )));
+ ))
+ .unwrap_err();
+ let PinnedError::UncoveredParticipations(UncoveredParticipations(uncovered)) = partial
+ else {
+ panic!("expected an uncovered-participation failure, got {partial}");
+ };
assert_eq!(
- validated
- .run
- .conditions
- .iter()
- .map(|(hash, _)| *hash)
- .collect::<Vec<_>>(),
- vec![hash(HASH_A)]
- );
- assert_eq!(validated.uncovered_cohorts, vec![CohortId(2)]);
- assert!(validated
- .warnings
- .contains(&PinnedWarning::ConditionDropped {
+ uncovered,
+ vec![UncoveredCohort {
cohort_id: CohortId(2),
- hash: hash(HASH_B),
- reason: PinnedDropReason::AbsentFromFrozenCatalog,
- }));
- assert_eq!(validated.run.horizon_days, 30);
+ reason: UncoveredReason::NoSurvivingCondition,
+ catalog_class: Some("excluded_empty_group"),
+ dropped: vec![(hash(HASH_B), PinnedDropReason::AbsentFromFrozenCatalog)],
+ }]
+ );
// A superseded cohort's hash warns distinctly and expects no coverage.
let validated = seedable(PinnedPersonRun::validate(snapshot(
@@ -883,7 +877,7 @@ mod tests {
],
)));
assert_eq!(validated.run.conditions.len(), 1);
- assert!(validated.uncovered_cohorts.is_empty());
+ assert_eq!(validated.run.horizon_days, 30);
assert!(validated
.warnings
.contains(&PinnedWarning::ConditionSuperseded {
@@ -913,7 +907,6 @@ mod tests {
],
)));
assert_eq!(validated.run.conditions.len(), 1);
- assert!(validated.uncovered_cohorts.is_empty());
// Zero surviving hashes with an active participation is terminal — that cohort's pinned
// conditions dropped from the catalog, a genuine data problem.
@@ -922,7 +915,7 @@ mod tests {
pinned(&[(1, HASH_B)]),
vec![participation(1, active.clone(), false)],
)),
- Err(PinnedError::NoSurvivingPersonConditions)
+ Err(PinnedError::UncoveredParticipations(_))
));
// Every participation superseded: nothing expects coverage, so the run retires as
@@ -1423,30 +1416,47 @@ mod tests {
}
}
+ /// The person kind shares the behavioral coverage proof, so it shares the refusal. A
+ /// root-negated cohort is excluded the same way in both services, so seeding it would scan the
+ /// team for a reconcile the processor discards without a completion marker.
+ #[test]
+ fn a_root_negated_participation_fails_the_person_run_closed() {
+ let error = PinnedPersonRun::validate(snapshot(
+ pinned(&[(1, HASH_A)]),
+ vec![participation(1, negated_root_filter(HASH_A), false)],
+ ))
+ .unwrap_err();
+
+ let PinnedError::UncoveredParticipations(UncoveredParticipations(uncovered)) = error else {
+ panic!("expected an uncovered-participation failure, got {error}");
+ };
+ assert_eq!(
+ uncovered,
+ vec![UncoveredCohort {
+ cohort_id: CohortId(1),
+ reason: UncoveredReason::NotComposable,
+ catalog_class: Some("excluded_top_level_negation"),
+ dropped: Vec::new(),
+ }]
+ );
+ }
+
/// The cascade-off asymmetry, driven through `RelevanceOracle::build` rather than a hand-built
/// tree: the seeder calls a ref-bearing cohort `Excluded(HasCohortRef)` because it freezes with
/// cascade off, while the consumer composes it. Counting it as never-composed would prune its
- /// real members. A root-negated cohort is excluded the same way in both services and is skipped.
+ /// real members, and refusing the run over it would refuse a cohort the consumer serves.
#[test]
- fn build_counts_a_ref_bearing_cohort_and_skips_a_root_negated_one() {
+ fn build_counts_a_ref_bearing_cohort_rather_than_pruning_it() {
let person = Uuid::from_u128(7).to_string();
let ctx = context();
- const HASH_C: &str = "cccccccccccccccc";
let run = Arc::new(
seedable(PinnedPersonRun::validate(snapshot(
- pinned(&[(1, HASH_A), (1, HASH_B), (2, HASH_C)]),
- vec![
- participation(1, and_with_a_cohort_reference(), false),
- participation(2, negated_root_filter(HASH_C), false),
- ],
+ pinned(&[(1, HASH_A), (1, HASH_B)]),
+ vec![participation(1, and_with_a_cohort_reference(), false)],
)))
.run,
);
- assert_eq!(
- run.composable_cohorts(),
- Some(1),
- "the ref-bearing cohort composes; the root-negated one does not"
- );
+ assert_eq!(run.composable_cohorts(), Some(1));
let mut quiet = PersonEvaluator::new(&run, PersonEmissionPolicy::RelevantToSomeCohort);
// Both pinned leaves true turns the AND's unknown reference into the deciding leaf, so the
diff --git a/rust/cohort-seeder/src/domain/person_relevance.rs b/rust/cohort-seeder/src/domain/person_relevance.rs
index 2eb9a32cd6f6..2dedda1f4006 100644
--- a/rust/cohort-seeder/src/domain/person_relevance.rs
+++ b/rust/cohort-seeder/src/domain/person_relevance.rs
@@ -43,11 +43,13 @@
use std::collections::HashMap;
-use cohort_core::eligibility::{CohortEligibility, ExcludedReason};
+use cohort_core::eligibility::CohortEligibility;
use cohort_core::filters::tree::{BoolOp, CohortLeaf, FilterNode};
use cohort_core::filters::TeamFilters;
use cohort_core::seed::MAX_PERSON_SEED_HASHES;
+use super::pinned::{composability, Composability};
+
use super::person::EvaluatedConditions;
/// One condition's position in [`EvaluatedConditions`], which is sorted-distinct by hash — so
@@ -293,38 +295,6 @@ impl RelevanceOracle {
}
}
-/// Whether the *consumer* composes a cohort of this class at all.
-#[derive(Debug, Clone, Copy, PartialEq, Eq)]
-enum Composability {
- NeverComposed,
- Composable,
-}
-
-/// The seeder freezes its catalog with cascade off, so every ref-bearing cohort reads
-/// `Excluded(HasCohortRef)` here while the consumer runs with cascade on and composes it. The
-/// seeder also holds only the run's own participations, never the referenced cohorts, so
-/// `CycleDetected` and `UnresolvedRef` cannot be trusted either. Only the structural exclusions —
-/// decided from the tree and the parse flags alone — classify identically in both services.
-///
-/// Exhaustive rather than defaulted: a new eligibility variant has to decide here rather than
-/// silently join the class whose members are pruned away.
-const fn composability(eligibility: CohortEligibility) -> Composability {
- match eligibility {
- CohortEligibility::SingleLeaf(_)
- | CohortEligibility::Stage2Composable
- | CohortEligibility::Stage2ComposableRef => Composability::Composable,
- CohortEligibility::Excluded(reason) => match reason {
- ExcludedReason::NotMultiLeaf
- | ExcludedReason::TopLevelNegation
- | ExcludedReason::EmptyGroup
- | ExcludedReason::HasDroppedLeaf => Composability::NeverComposed,
- ExcludedReason::HasCohortRef
- | ExcludedReason::CycleDetected
- | ExcludedReason::UnresolvedRef => Composability::Composable,
- },
- }
-}
-
#[cfg(test)]
mod tests {
use proptest::prelude::*;
@@ -483,6 +453,7 @@ mod tests {
/// with cascade off, so a ref-bearing cohort it calls excluded is one the consumer composes.
#[test]
fn only_structurally_excluded_cohorts_count_as_never_composed() {
+ use cohort_core::eligibility::ExcludedReason;
use cohort_core::LeafStateKey;
for eligibility in [
diff --git a/rust/cohort-seeder/src/domain/pinned.rs b/rust/cohort-seeder/src/domain/pinned.rs
index 5d39aa3bef8f..fcb93d488940 100644
--- a/rust/cohort-seeder/src/domain/pinned.rs
+++ b/rust/cohort-seeder/src/domain/pinned.rs
@@ -2,11 +2,14 @@
//! typed, scannable run. Depends on `chunk`, `condition`, `window`, `ids`, and `cohort-core`.
use std::collections::{HashMap, HashSet};
+use std::fmt;
use std::str::FromStr;
use chrono_tz::Tz;
+use cohort_core::eligibility::{CohortEligibility, ExcludedReason};
use cohort_core::filters::tree::{BehavioralLeafConfig, BehavioralValue};
use cohort_core::filters::{CohortId, FilterError, TeamFilters, TeamFiltersBuilder, TeamId};
+use cohort_core::leaf_state::select::{pick_state_variant, UnsupportedVariant};
use cohort_core::resolve_tz_or_utc;
use cohort_core::EvictionWindow;
use cohort_core::LeafStateKey;
@@ -67,13 +70,11 @@ pub struct PinnedRun {
pub filters: TeamFilters,
}
+/// Proven coverable: [`PinnedRun::validate`] refuses a run with an uncovered participation.
#[derive(Debug)]
pub struct ValidatedPinnedRun {
pub run: PinnedRun,
pub warnings: Vec<PinnedWarning>,
- /// Active participations left with no surviving condition, ascending — cohorts that expect
- /// coverage nothing will seed. Per cohort, not per run: one sibling surviving hides the rest.
- pub uncovered_cohorts: Vec<CohortId>,
}
/// A run proven `seeding` with an established boundary, ready for pinned-payload validation. The
@@ -107,6 +108,7 @@ pub enum PinnedParticipationState {
pub enum PinnedDropReason {
ActionKeyed,
AbsentFromFrozenCatalog,
+ UnsupportedStateVariant(UnsupportedVariant),
/// Person runs only: the frozen catalog resolves the hash to a non-person-property leaf.
VariantMismatch,
}
@@ -116,11 +118,23 @@ impl PinnedDropReason {
match self {
Self::ActionKeyed => "action_keyed",
Self::AbsentFromFrozenCatalog => "absent_from_frozen_catalog",
+ Self::UnsupportedStateVariant(_) => "unsupported_state_variant",
Self::VariantMismatch => "variant_mismatch",
}
}
}
+impl fmt::Display for PinnedDropReason {
+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
+ match self {
+ Self::UnsupportedStateVariant(unsupported) => {
+ write!(formatter, "{} ({unsupported})", self.as_str())
+ }
+ _ => formatter.write_str(self.as_str()),
+ }
+ }
+}
+
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum PinnedWarning {
TimezoneFallback {
@@ -143,6 +157,110 @@ pub enum PinnedWarning {
},
}
+/// Whether the *consumer* composes a cohort of this class at all.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(super) enum Composability {
+ NeverComposed,
+ Composable,
+}
+
+/// The seeder freezes its catalog with cascade off, so every ref-bearing cohort reads
+/// `Excluded(HasCohortRef)` here while the consumer runs with cascade on and composes it. The
+/// seeder also holds only the run's own participations, never the referenced cohorts, so
+/// `CycleDetected` and `UnresolvedRef` cannot be trusted either. Only the structural exclusions —
+/// decided from the tree and the parse flags alone — classify identically in both services.
+///
+/// Exhaustive rather than defaulted: a new eligibility variant has to decide here rather than
+/// silently join the class whose members are pruned away.
+///
+/// `_STRUCTURAL_EXCLUSIONS` in `products/cohorts/backend/parity/eligibility.py` copies the
+/// `NeverComposed` arm for the Django backfill gate, so change both together. A gate that admits a
+/// class this arm refuses creates runs the seeder fails whole.
+pub(super) const fn composability(eligibility: CohortEligibility) -> Composability {
+ match eligibility {
+ CohortEligibility::SingleLeaf(_)
+ | CohortEligibility::Stage2Composable
+ | CohortEligibility::Stage2ComposableRef => Composability::Composable,
+ CohortEligibility::Excluded(reason) => match reason {
+ ExcludedReason::NotMultiLeaf
+ | ExcludedReason::TopLevelNegation
+ | ExcludedReason::EmptyGroup
+ | ExcludedReason::HasDroppedLeaf => Composability::NeverComposed,
+ ExcludedReason::HasCohortRef
+ | ExcludedReason::CycleDetected
+ | ExcludedReason::UnresolvedRef => Composability::Composable,
+ },
+ }
+}
+
+/// Why one active participation cannot be seeded.
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum UncoveredReason {
+ /// No surviving pinned condition names the cohort, so the scan would emit nothing for it.
+ NoSurvivingCondition,
+ /// The frozen catalog will not compose the cohort. Seeding it is wasted work the processor
+ /// discards without a completion marker, which leaves the run stuck in `reconciling`.
+ NotComposable,
+}
+
+impl UncoveredReason {
+ fn as_str(self) -> &'static str {
+ match self {
+ Self::NoSurvivingCondition => "no pinned condition survives the frozen catalog",
+ Self::NotComposable => "the frozen catalog will not compose it",
+ }
+ }
+}
+
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct UncoveredCohort {
+ pub cohort_id: CohortId,
+ pub reason: UncoveredReason,
+ pub catalog_class: Option<&'static str>,
+ pub dropped: Vec<(ConditionHash, PinnedDropReason)>,
+}
+
+impl fmt::Display for UncoveredCohort {
+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
+ write!(formatter, "cohort {}", self.cohort_id.0)?;
+ if let Some(class) = self.catalog_class {
+ write!(formatter, " ({class})")?;
+ }
+ write!(formatter, ": {}", self.reason.as_str())?;
+ if self.dropped.is_empty() {
+ return Ok(());
+ }
+ let dropped = self
+ .dropped
+ .iter()
+ .map(|(hash, reason)| format!("{hash} {reason}"))
+ .collect::<Vec<_>>()
+ .join(", ");
+ write!(formatter, ", dropped {dropped}")
+ }
+}
+
+/// `fail_run` renders this into the run's `error` column, the only surface naming the refused leaf.
+#[derive(Debug, Clone, PartialEq, Eq)]
+pub struct UncoveredParticipations(pub Vec<UncoveredCohort>);
+
+impl fmt::Display for UncoveredParticipations {
+ fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
+ write!(
+ formatter,
+ "{} active participation(s) cannot be seeded: ",
+ self.0.len()
+ )?;
+ let clauses = self
+ .0
+ .iter()
+ .map(ToString::to_string)
+ .collect::<Vec<_>>()
+ .join("; ");
+ formatter.write_str(&clauses)
+ }
+}
+
#[derive(Debug, thiserror::Error)]
pub enum PinnedError {
#[error("invalid pinned payload: {0}")]
@@ -165,8 +283,8 @@ pub enum PinnedError {
IncompleteMetadata(ConditionHash),
#[error("person run has no pinned person_scan_since")]
MissingPersonScanSince,
- #[error("no pinned person condition survived validation; nothing would be seeded")]
- NoSurvivingPersonConditions,
+ #[error("{0}")]
+ UncoveredParticipations(UncoveredParticipations),
#[error("surviving person conditions exceed the per-seed hash cap: {0}")]
PersonConditionsOverCap(usize),
}
@@ -233,10 +351,13 @@ impl PinnedRun {
let participation = ParticipationSet::build(snapshot.team_id, snapshot.participations, tz)?;
let conditions = resolve_conditions(payload.conditions, &participation, &mut warnings)?;
let event_names = EventNameSet::from_conditions(&conditions);
- let uncovered_cohorts = participation.uncovered_cohorts(&conditions);
+ let covered = conditions
+ .iter()
+ .map(|condition| condition.cohort_id)
+ .collect();
+ participation.prove_covered(&covered, &warnings)?;
Ok(ValidatedPinnedRun {
- uncovered_cohorts,
run: PinnedRun {
run_id: snapshot.run_id,
team_id: snapshot.team_id,
@@ -348,30 +469,79 @@ impl ParticipationSet {
&self.filters
}
- /// The active cohorts no surviving condition references, ascending. Conditions drop per cohort
- /// (`ActionKeyed`, `AbsentFromFrozenCatalog`), independently of participation state.
- fn uncovered_cohorts(&self, conditions: &[PinnedCondition]) -> Vec<CohortId> {
- let covered: HashSet<CohortId> = conditions
- .iter()
- .map(|condition| condition.cohort_id)
+ /// Every active participation must both keep a surviving pinned condition and be a cohort the
+ /// frozen catalog composes. Both are pure functions of the frozen row, so this refusal is
+ /// permanent and the run is failed rather than retried.
+ pub(super) fn prove_covered(
+ &self,
+ covered: &HashSet<CohortId>,
+ warnings: &[PinnedWarning],
+ ) -> Result<(), PinnedError> {
+ let uncovered = self.uncovered_from(covered);
+ if uncovered.is_empty() {
+ return Ok(());
+ }
+ let payload = uncovered
+ .into_iter()
+ .map(|(cohort_id, reason)| UncoveredCohort {
+ cohort_id,
+ reason,
+ catalog_class: self
+ .filters
+ .eligibility
+ .get(&cohort_id)
+ .copied()
+ .map(CohortEligibility::metric_class),
+ dropped: warnings
+ .iter()
+ .filter_map(|warning| match warning {
+ PinnedWarning::ConditionDropped {
+ cohort_id: dropped_for,
+ hash,
+ reason,
+ } if *dropped_for == cohort_id => Some((*hash, *reason)),
+ _ => None,
+ })
+ .collect(),
+ })
.collect();
- self.uncovered_from(&covered)
+ Err(PinnedError::UncoveredParticipations(
+ UncoveredParticipations(payload),
+ ))
}
- /// The active cohorts absent from `covered`, ascending.
- pub(super) fn uncovered_from(&self, covered: &HashSet<CohortId>) -> Vec<CohortId> {
+ /// The active cohorts this run cannot seed, ascending. A cohort absent from `covered` has no
+ /// surviving condition; one the catalog refuses to compose would be seeded into a reconcile the
+ /// processor discards.
+ fn uncovered_from(&self, covered: &HashSet<CohortId>) -> Vec<(CohortId, UncoveredReason)> {
let mut uncovered = self
.states
.iter()
- .filter(|(cohort_id, state)| {
- **state == PinnedParticipationState::Active && !covered.contains(cohort_id)
+ .filter(|(_, state)| **state == PinnedParticipationState::Active)
+ .filter_map(|(cohort_id, _)| {
+ if !covered.contains(cohort_id) {
+ Some((*cohort_id, UncoveredReason::NoSurvivingCondition))
+ } else if self.refuses_to_compose(*cohort_id) {
+ Some((*cohort_id, UncoveredReason::NotComposable))
+ } else {
+ None
+ }
})
- .map(|(cohort_id, _)| *cohort_id)
.collect::<Vec<_>>();
- uncovered.sort_unstable();
+ uncovered.sort_unstable_by_key(|(cohort_id, _)| *cohort_id);
uncovered
}
+ /// Whether the consumer would refuse to compose this cohort. The seeder's own catalog cannot
+ /// decide the reference classes, so [`composability`] leaves them out and this proof does too.
+ fn refuses_to_compose(&self, cohort_id: CohortId) -> bool {
+ self.filters
+ .eligibility
+ .get(&cohort_id)
+ .copied()
+ .is_some_and(|class| composability(class) == Composability::NeverComposed)
+ }
+
fn into_filters(self) -> TeamFilters {
self.filters
}
@@ -480,6 +650,13 @@ fn derive_lookback(
negated: false,
}
.with_state_key();
+ if let Err(unsupported) = pick_state_variant(&leaf) {
+ return Ok(LookbackResolution::Dropped(
+ PinnedDropReason::UnsupportedStateVariant(unsupported),
+ ));
+ }
+ // The shape is one the catalog keeps, so a miss here means the pinned scalars differ from the
+ // ones the frozen filters were parsed from, not that the leaf was refused.
let Some(meta) = filters.by_lsk.get(&leaf.leaf_state_key) else {
return Ok(LookbackResolution::Dropped(
PinnedDropReason::AbsentFromFrozenCatalog,
@@ -589,11 +766,7 @@ mod tests {
fn invalid_timezone_falls_back_once_and_keeps_the_run_loadable() {
let mut input = snapshot(
json!({ "schema_version": 1, "conditions": [], "event_names": [] }),
- vec![PinnedParticipation {
- cohort_id: CohortId(1),
- pinned_filters: json!({ "properties": { "type": "AND", "values": [] } }),
- state: PinnedParticipationState::Active,
- }],
+ vec![],
);
input.timezone = "not/a-zone".to_string();
let validated = PinnedRun::validate(input).unwrap();
@@ -623,7 +796,6 @@ mod tests {
{ "type": "behavioral", "value": "performed_event", "key": "relative", "conditionHash": hashes[1], "explicit_datetime": "-30d", "bytecode": bytecode("relative") },
{ "type": "behavioral", "value": "performed_event", "key": "absolute", "conditionHash": hashes[2], "explicit_datetime": "2026-01-03", "explicit_datetime_to": "2026-01-05", "bytecode": bytecode("absolute") },
{ "type": "behavioral", "value": "performed_event", "key": "hourly", "conditionHash": hashes[3], "time_value": 5, "time_interval": "hour", "bytecode": bytecode("hourly") },
- { "type": "behavioral", "value": "performed_event", "key": 42, "conditionHash": hashes[4], "time_value": 7, "time_interval": "day", "bytecode": BYTECODE },
]}
});
let second_filters = json!({
@@ -677,7 +849,9 @@ mod tests {
day_idx_of_naive_date(NaiveDate::from_ymd_opt(year, month, day).unwrap())
};
// The action-keyed condition (`hashes[4]`, no event name) resolves to a drop and is absent
- // from the stored conditions; its `ConditionDropped` warning is asserted below.
+ // from the stored conditions; its `ConditionDropped` warning is asserted below. Its leaf is
+ // deliberately not in the pinned filters: a dropped leaf makes the whole cohort
+ // `Excluded(HasDroppedLeaf)`, which fails the run before any of this is reached.
let expected = [
Lookback::SlidingDays(7),
Lookback::SlidingDays(30),
@@ -770,8 +944,6 @@ mod tests {
let validated = PinnedRun::validate(snapshot(payload.clone(), participations)).unwrap();
assert_eq!(validated.run.conditions.len(), 1);
assert_eq!(validated.run.conditions[0].cohort_id, CohortId(1));
- // A superseded participation expects no coverage, so it never withholds the proof.
- assert!(validated.uncovered_cohorts.is_empty());
assert_eq!(validated.run.event_names.as_slice(), &["active-event"]);
assert!(validated
.run
@@ -791,7 +963,7 @@ mod tests {
}));
let unknown = PinnedRun::validate(snapshot(
- payload,
+ payload.clone(),
vec![PinnedParticipation {
cohort_id: CohortId(1),
pinned_filters: filters("active-event", active_hash),
@@ -799,10 +971,28 @@ mod tests {
}],
));
assert!(matches!(unknown, Err(PinnedError::MissingParticipation(2))));
+
+ let retired = PinnedRun::validate(snapshot(
+ payload,
+ vec![
+ PinnedParticipation {
+ cohort_id: CohortId(1),
+ pinned_filters: filters("active-event", active_hash),
+ state: PinnedParticipationState::Superseded,
+ },
+ PinnedParticipation {
+ cohort_id: CohortId(2),
+ pinned_filters: filters("superseded-event", superseded_hash),
+ state: PinnedParticipationState::Superseded,
+ },
+ ],
+ ))
+ .expect("a run whose every participation is superseded retires rather than failing");
+ assert!(retired.run.conditions.is_empty());
}
#[test]
- fn an_active_cohort_whose_only_condition_is_dropped_is_reported_uncovered() {
+ fn a_partially_covered_run_fails_rather_than_seeding_the_covered_sibling() {
let covered_hash = "covered000000000";
let action_hash = "action0000000000";
let covered_filters = json!({
@@ -841,12 +1031,22 @@ mod tests {
},
];
- let validated = PinnedRun::validate(snapshot(payload, participations)).unwrap();
- // Cohort 1's surviving condition would satisfy a run-wide check while cohort 2 gets nothing.
- assert_eq!(validated.run.conditions.len(), 1);
- assert_eq!(validated.uncovered_cohorts, vec![CohortId(2)]);
- // A dropped condition does not make its cohort a second claimant on the scan's cost.
- assert_eq!(validated.run.sole_cohort_id(), Some(CohortId(1)));
+ let error = PinnedRun::validate(snapshot(payload, participations)).unwrap_err();
+ let PinnedError::UncoveredParticipations(UncoveredParticipations(uncovered)) = error else {
+ panic!("expected an uncovered-participation failure, got {error}");
+ };
+ assert_eq!(
+ uncovered,
+ vec![UncoveredCohort {
+ cohort_id: CohortId(2),
+ reason: UncoveredReason::NoSurvivingCondition,
+ catalog_class: Some("excluded_empty_group"),
+ dropped: vec![(
+ ConditionHash::parse(action_hash).unwrap(),
+ PinnedDropReason::ActionKeyed,
+ )],
+ }]
+ );
}
/// A validated run carrying one 7-day `performed_event` condition per `(cohort, event)` pair,
@@ -997,11 +1197,13 @@ mod tests {
}
#[test]
- fn lenient_serde_coerces_mistyped_scalars_to_none_without_failing_validation() {
+ fn lenient_serde_coerces_mistyped_scalars_to_none_without_failing_the_parse() {
let hash = "lenient000000000";
+ // The window comes from `explicit_datetime`, which the mistyped payload keeps, so only the
+ // key differs and `pick_state_variant` does not steal the drop label below.
let catalog = json!({
"properties": { "type": "AND", "values": [
- { "type": "behavioral", "value": "performed_event", "key": "evt", "conditionHash": hash, "time_value": 7, "time_interval": "day", "bytecode": bytecode("evt") },
+ { "type": "behavioral", "value": "performed_event", "key": "evt", "conditionHash": hash, "time_value": 7, "time_interval": "day", "explicit_datetime": "-30d", "bytecode": bytecode("evt") },
]}
});
let validate = |condition: Value| {
@@ -1014,12 +1216,16 @@ mod tests {
}],
))
};
+ let pinned = |time_value: Value, time_interval: Value| {
+ let mut raw = condition(1, hash, "performed_event", Some("evt"), 30);
+ raw["time_value"] = time_value;
+ raw["time_interval"] = time_interval;
+ raw["explicit_datetime"] = json!("-30d");
+ raw
+ };
// Well-typed scalars resolve against the frozen catalog.
- let mut well_typed = condition(1, hash, "performed_event", Some("evt"), 7);
- well_typed["time_value"] = json!(7);
- well_typed["time_interval"] = json!("day");
- let resolved = validate(well_typed).unwrap();
+ let resolved = validate(pinned(json!(7), json!("day"))).unwrap();
assert_eq!(
resolved
.run
@@ -1027,23 +1233,182 @@ mod tests {
.iter()
.map(|condition| condition.lookback)
.collect::<Vec<_>>(),
- [Lookback::SlidingDays(7)],
+ [Lookback::SlidingDays(30)],
+ );
+
+ // Mistyped scalars coerce to None exactly as json_i32/json_string did, so the parse still
+ // succeeds where a plain `Option<i32>` would reject the payload. They change the leaf-state
+ // key, so the condition misses the catalog. A key miss is not a refused shape, so it keeps
+ // `AbsentFromFrozenCatalog`.
+ let error = validate(pinned(json!("7"), json!(5))).unwrap_err();
+ let PinnedError::UncoveredParticipations(UncoveredParticipations(uncovered)) = error else {
+ panic!("expected an uncovered-participation failure, got {error}");
+ };
+ assert_eq!(
+ uncovered,
+ vec![UncoveredCohort {
+ cohort_id: CohortId(1),
+ reason: UncoveredReason::NoSurvivingCondition,
+ catalog_class: Some("single_leaf"),
+ dropped: vec![(
+ ConditionHash::parse(hash).unwrap(),
+ PinnedDropReason::AbsentFromFrozenCatalog,
+ )],
+ }]
+ );
+ }
+
+ /// A cohort keeping one leaf and losing another is `Excluded(HasDroppedLeaf)`, so the processor
+ /// discards its reconcile tile with no completion marker. Coverage read per surviving condition
+ /// would call the cohort covered off its kept leaf, seed it, and leave the run stuck in
+ /// `reconciling` — the wedge this failure exists to prevent, one stage later.
+ #[test]
+ fn a_cohort_the_catalog_will_not_compose_fails_the_run_even_with_a_surviving_condition() {
+ let kept_hash = "kept000000000000";
+ let dropped_hash = "dropped000000000";
+ let leaf = |event: &str, hash: &str, code: Value| {
+ json!({
+ "type": "behavioral",
+ "value": "performed_event",
+ "key": event,
+ "conditionHash": hash,
+ "time_value": 7,
+ "time_interval": "day",
+ "bytecode": code,
+ })
+ };
+ let pinned_condition = |hash: &str, event: &str| {
+ let mut raw = condition(1, hash, "performed_event", Some(event), 7);
+ raw["time_value"] = json!(7);
+ raw["time_interval"] = json!("day");
+ raw
+ };
+
+ let error = PinnedRun::validate(snapshot(
+ json!({
+ "schema_version": 1,
+ "conditions": [
+ pinned_condition(kept_hash, "kept-event"),
+ pinned_condition(dropped_hash, "dropped-event"),
+ ],
+ "event_names": ["dropped-event", "kept-event"],
+ }),
+ vec![PinnedParticipation {
+ cohort_id: CohortId(1),
+ pinned_filters: json!({
+ "properties": { "type": "AND", "values": [
+ leaf("kept-event", kept_hash, bytecode("kept-event")),
+ // The HogVM refuses an empty program, so the catalog drops this leaf.
+ leaf("dropped-event", dropped_hash, json!(BYTECODE)),
+ ]}
+ }),
+ state: PinnedParticipationState::Active,
+ }],
+ ))
+ .unwrap_err();
+
+ let PinnedError::UncoveredParticipations(UncoveredParticipations(uncovered)) = error else {
+ panic!("expected an uncovered-participation failure, got {error}");
+ };
+ assert_eq!(
+ uncovered,
+ vec![UncoveredCohort {
+ cohort_id: CohortId(1),
+ reason: UncoveredReason::NotComposable,
+ catalog_class: Some("excluded_has_dropped_leaf"),
+ dropped: vec![(
+ ConditionHash::parse(dropped_hash).unwrap(),
+ PinnedDropReason::AbsentFromFrozenCatalog,
+ )],
+ }]
);
+ }
- // A string where an int is expected and a number where a string is expected coerce to None
- // exactly as json_i32/json_string did: validation still succeeds (a plain `Option<i32>`
- // would reject this payload), but the mistyped scalars change the leaf-state key, so the
- // condition drops out of the frozen catalog instead of erroring.
- let mut mistyped = condition(1, hash, "performed_event", Some("evt"), 7);
- mistyped["time_value"] = json!("7");
- mistyped["time_interval"] = json!(5);
- mistyped["operator_value"] = json!("2");
- let dropped = validate(mistyped).unwrap();
- assert!(dropped.run.conditions.is_empty());
- assert!(dropped.warnings.contains(&PinnedWarning::ConditionDropped {
+ #[test]
+ fn a_windowless_performed_event_leaf_fails_the_run_closed() {
+ let hash = "c8236865303eb463";
+ let event = "navbar starred item added";
+ let participation = PinnedParticipation {
cohort_id: CohortId(1),
- hash: ConditionHash::parse(hash).unwrap(),
- reason: PinnedDropReason::AbsentFromFrozenCatalog,
- }));
+ pinned_filters: json!({
+ "properties": { "type": "AND", "values": [{
+ "type": "behavioral",
+ "value": "performed_event",
+ "key": event,
+ "event_type": "events",
+ "negation": false,
+ "conditionHash": hash,
+ "event_filters": [
+ { "key": "item_type", "type": "event", "value": "insight", "operator": "exact" },
+ ],
+ "bytecode": bytecode(event),
+ }]}
+ }),
+ state: PinnedParticipationState::Active,
+ };
+
+ let error = PinnedRun::validate(snapshot(
+ json!({
+ "schema_version": 1,
+ "conditions": [condition(1, hash, "performed_event", Some(event), 0)],
+ "event_names": [event],
+ }),
+ vec![participation],
+ ))
+ .unwrap_err();
+
+ let PinnedError::UncoveredParticipations(UncoveredParticipations(uncovered)) = error else {
+ panic!("expected an uncovered-participation failure, got {error}");
+ };
+ assert_eq!(
+ uncovered,
+ vec![UncoveredCohort {
+ cohort_id: CohortId(1),
+ reason: UncoveredReason::NoSurvivingCondition,
+ catalog_class: Some("excluded_has_dropped_leaf"),
+ dropped: vec![(
+ ConditionHash::parse(hash).unwrap(),
+ PinnedDropReason::UnsupportedStateVariant(UnsupportedVariant::MissingWindow),
+ )],
+ }]
+ );
+ }
+
+ #[test]
+ fn the_persisted_failure_names_each_cohort_its_class_its_reason_and_every_dropped_hash() {
+ let rendered = UncoveredParticipations(vec![
+ UncoveredCohort {
+ cohort_id: CohortId(574801),
+ reason: UncoveredReason::NoSurvivingCondition,
+ catalog_class: Some("excluded_has_dropped_leaf"),
+ dropped: vec![(
+ ConditionHash::parse("c8236865303eb463").unwrap(),
+ PinnedDropReason::UnsupportedStateVariant(UnsupportedVariant::MissingWindow),
+ )],
+ },
+ UncoveredCohort {
+ cohort_id: CohortId(9),
+ reason: UncoveredReason::NoSurvivingCondition,
+ catalog_class: Some("excluded_has_dropped_leaf"),
+ dropped: Vec::new(),
+ },
+ UncoveredCohort {
+ cohort_id: CohortId(11),
+ reason: UncoveredReason::NotComposable,
+ catalog_class: Some("excluded_top_level_negation"),
+ dropped: Vec::new(),
+ },
+ ])
+ .to_string();
+
+ assert_eq!(
+ rendered,
+ "3 active participation(s) cannot be seeded: \
+ cohort 574801 (excluded_has_dropped_leaf): no pinned condition survives the frozen \
+ catalog, dropped c8236865303eb463 unsupported_state_variant \
+ (performed_event leaf has no resolvable window); \
+ cohort 9 (excluded_has_dropped_leaf): no pinned condition survives the frozen catalog; \
+ cohort 11 (excluded_top_level_negation): the frozen catalog will not compose it"
+ );
}
}
diff --git a/rust/cohort-seeder/src/observability/metrics.rs b/rust/cohort-seeder/src/observability/metrics.rs
index 21582a36f5ca..14c54888c626 100644
--- a/rust/cohort-seeder/src/observability/metrics.rs
+++ b/rust/cohort-seeder/src/observability/metrics.rs
@@ -15,6 +15,9 @@ pub const RUNS_DISCOVERED: &str = "seeder_runs_discovered_total";
pub const BOUNDARY_ESTABLISHED: &str = "seeder_boundary_established_total";
pub const BOUNDARY_CAS_LOST: &str = "seeder_boundary_cas_lost_total";
pub const RUNS_WAITING_BOUNDARY: &str = "seeder_runs_waiting_boundary";
+/// Runs terminally failed during pinned-payload validation, labelled by `reason` (counter). For
+/// `uncovered_participation` the run's `error` column names the cohorts, why each cannot be seeded,
+/// and their dropped hashes.
pub const RUN_VALIDATION_FAILURES: &str = "seeder_run_validation_failures_total";
pub const TZ_FALLBACK: &str = "seeder_tz_fallback_total";
pub const CONDITIONS_DROPPED: &str = "seeder_conditions_dropped_total";
@@ -121,7 +124,6 @@ pub const RUN_CHUNKS_REMAINING: &str = "seeder_run_chunks_remaining";
pub const RUNS_WITHOUT_CHUNKS: &str = "seeder_runs_without_chunks";
pub const WINDOW_DAYS_MISMATCH: &str = "seeder_window_days_mismatch_total";
pub const RUNS_PLANNING_STAMPED: &str = "seeder_runs_planning_stamped_total";
-pub const RUNS_PLANNING_WITHHELD: &str = "seeder_runs_planning_withheld_total";
/// Reconcile dispatch attempts, labelled by bounded `outcome` and the run's `kind` (counter).
pub const RECONCILE_DISPATCHES: &str = "seeder_reconcile_dispatches_total";
/// Dispatch claims lost to a concurrent writer, labelled by the run's `kind` (counter).
diff --git a/rust/cohort-seeder/tests/pg_chunks.rs b/rust/cohort-seeder/tests/pg_chunks.rs
index cc40fccf7a5d..21c7eb300a45 100644
--- a/rust/cohort-seeder/tests/pg_chunks.rs
+++ b/rust/cohort-seeder/tests/pg_chunks.rs
@@ -1442,7 +1442,6 @@ async fn discovery_is_kind_gated_and_person_pinned_load_validates() -> Result<()
};
ensure!(validated.run.conditions.len() == 1);
ensure!(validated.run.horizon_days == 30);
- ensure!(validated.uncovered_cohorts.is_empty());
ensure!(validated.warnings.iter().any(|warning| matches!(
warning,
PinnedWarning::ConditionSuperseded { cohort_id, .. } if *cohort_id == CohortId(11)